shakespeare_main.py 10.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Runs a character LSTM model trained on Shakespeare."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

21
import functools
22
23
import os

24
# pylint: disable=wrong-import-order
25
from absl import app
26
from absl import flags
27
import numpy as np
28
import tensorflow as tf
29
from official.common import distribute_utils
30
# pylint: enable=wrong-import-order
31

32
33
from official.utils.flags import core as flags_core
from official.utils.misc import keras_utils
34
35
36
37

EMBEDDING_DIM = 256
RNN_UNITS = 1024
SEQ_LENGTH = 100
38
39
# Calculated by running batch_size=1
BATCHES_PER_EPOCH = 11043
40
41
42
43


def define_flags():
  """Define the flags for the Shakespeare character LSTM."""
44
45
46
47
48
  flags_core.define_base(data_dir=False,
                         clean=False,
                         train_epochs=True,
                         epochs_between_evals=False,
                         stop_threshold=False,
49
                         num_gpu=True,
50
                         export_dir=False,
51
52
                         run_eagerly=True,
                         distribution_strategy=True)
53
54
55
56
57
58

  flags_core.define_performance(num_parallel_calls=False,
                                inter_op=False,
                                intra_op=False,
                                synthetic_data=False,
                                max_train_steps=False,
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
59
                                dtype=True,
60
                                enable_xla=True)
61
62
63
64
65

  flags_core.set_defaults(train_epochs=43,
                          batch_size=64)

  flags.DEFINE_boolean(name='enable_eager', default=True, help='Enable eager?')
66
67
68
69
70
71
72
73
74
  flags.DEFINE_boolean(
      name='train', default=True,
      help='If true trains the model.')
  flags.DEFINE_string(
      name='predict_context', default=None,
      help='If set, makes a prediction with the given context.')
  flags.DEFINE_integer(
      name='predict_length', default=1000,
      help='Length of the predicted text including the context.')
75
76
  flags.DEFINE_integer(name='train_steps', default=None,
                       help='Overrides train_steps per epoch if not None.')
77
78
79
80
  flags.DEFINE_integer(
      name='log_steps', default=100,
      help='For every log_steps, we log the timing information such as '
      'examples per second.')
81
82
83
  flags.DEFINE_string(
      name='training_data', default=None,
      help='Path to file containing the training data.')
84
  flags.DEFINE_boolean(name='cudnn', default=True, help='Use CuDNN LSTM.')
85
86


87
def get_dataset(path_to_file, batch_size=None, seq_length=SEQ_LENGTH):
88
89
90
91
  """Creates a dataset from a given text file.

  Args:
    path_to_file: The path to the training data.
92
    batch_size: Batch size to use.
93
94
95
96
97
98
    seq_length: The length of the LSTM sequence.

  Returns:
    A tuple, consisting of the Dataset and the class to character mapping
    and character to class mapping.
  """
David Chen's avatar
David Chen committed
99
  with tf.io.gfile.GFile(path_to_file, 'rb') as train_data:
100
    text = train_data.read().decode(encoding='utf-8')
101
102
103
104
105
106
107
108
109

  # Create vocab
  vocab = sorted(set(text))
  char2idx = {u: i for i, u in enumerate(vocab)}
  idx2char = np.array(vocab)

  # Split text into sequence length + 1 chucks to create examples
  text_as_int = np.array([char2idx[c] for c in text])
  char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)
110
111
  sequences = char_dataset.batch(
      seq_length + 1, drop_remainder=True, num_parallel_calls=tf.data.AUTOTUNE)
112
113
114
115
116
117

  def split_input_target(chunk):
    input_text = chunk[:-1]
    target_text = chunk[1:]
    return input_text, tf.one_hot(target_text, len(vocab))
  dataset = sequences.map(split_input_target)
118
  dataset = dataset.shuffle(10000).repeat()
119
120
  dataset = dataset.batch(
      batch_size, drop_remainder=True, num_parallel_calls=tf.data.AUTOTUNE)
121
122
123
124
125
126
127

  return dataset, idx2char, char2idx


def build_model(vocab_size,
                embedding_dim=EMBEDDING_DIM,
                rnn_units=RNN_UNITS,
128
                batch_size=None,
129
130
                stateful=False,
                use_cudnn=True):
131
132
133
134
135
136
137
138
139
140
141
142
  """Builds the Shakespeare model.

  Args:
    vocab_size: The number of character classes in the input.
    embedding_dim: The dimension of the embedding space for each class.
    rnn_units: The number of RNN units in the layer.
    batch_size: When predicting, the batch size of the predictions.
    stateful: If true, the LSTM is stateful.

  Returns:
    A Keras Model.
  """
143
  LSTM = functools.partial(tf.keras.layers.LSTM, implementation=2)
144
145
146
147
148
149
150

  # By indirecting the activation through a lambda layer, the logic to dispatch
  # to CuDNN in V2 doesn't trigger and we force the LSTM to run in non-CuDNN
  # mode.
  lstm_activation = ('tanh' if use_cudnn else
                     lambda x: tf.math.tanh(x))

151
152
153
154
  batch_shape = [batch_size if stateful else None, None]
  return tf.keras.Sequential([
      tf.keras.layers.Embedding(vocab_size, embedding_dim,
                                batch_input_shape=batch_shape),
155
156
157
158
159
      LSTM(rnn_units,
           activation=lstm_activation,
           return_sequences=True,
           stateful=stateful,
           recurrent_initializer='glorot_uniform'),
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
160
161
      tf.keras.layers.Dense(vocab_size),
      tf.keras.layers.Softmax(dtype=tf.float32)])
162
163


164
def train_model(flags_obj, dataset, vocab_size, strategy, checkpoint_dir=None):
165
166
167
  """Trains a Shakespeare model.

  Args:
168
    flags_obj: An object containing parsed flag values.s
169
170
    dataset: the training data set.
    vocab_size: the number of unique character classes.
171
    strategy: distribution strategy to use.
172
173
174
    checkpoint_dir: if not None, the directory in which to make checkpoints.

  Returns:
175
    The training history and callbacks.
176
  """
177
178
179
180
  if flags_obj.train_steps:
    train_steps = flags_obj.train_steps
  else:
    train_steps = BATCHES_PER_EPOCH // flags_obj.batch_size
181
  strategy_scope = distribute_utils.get_strategy_scope(strategy)
182

183
  with strategy_scope:
184
185
    model = build_model(vocab_size=vocab_size, batch_size=flags_obj.batch_size,
                        use_cudnn=flags_obj.cudnn)
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
186

187
188
    # Model.fit() automatically applies loss scaling so we don't need to create
    # a LossScaleOptimizer.
189
190
191
192
193
    model.compile(
        optimizer=tf.keras.optimizers.Adam(),
        loss=tf.keras.losses.CategoricalCrossentropy(),
        metrics=[tf.keras.metrics.Recall(top_k=1, name='RecallAt1'),
                 tf.keras.metrics.Recall(top_k=5, name='RecallAt5')],
194
        run_eagerly=flags_obj.run_eagerly)
195
196
197
198
199
200
201
202

  callbacks = []
  if checkpoint_dir:
    checkpoint_prefix = os.path.join(checkpoint_dir, 'ckpt_{epoch}')
    checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
        filepath=checkpoint_prefix,
        save_weights_only=True)
    callbacks.append(checkpoint_callback)
203
204
  time_callback = keras_utils.TimeHistory(flags_obj.batch_size,
                                          flags_obj.log_steps)
205
206
207
208
209
210
211
  callbacks.append(time_callback)
  history = model.fit(dataset,
                      epochs=flags_obj.train_epochs,
                      steps_per_epoch=train_steps,
                      callbacks=callbacks,
                      verbose=2)
  return history, callbacks
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254


def make_prediction(checkpoint_dir, length, context, idx2char, char2idx):
  """Make predictions from a Shakespeare model.

  Args:
    checkpoint_dir: the directory from which to load checkpoints
    length: the total length of the generated text (including the context).
    context: the initial text with which the LSTM is primed.
    idx2char: the character class to character mapping.
    char2idx: the character to character class mapping.

  Returns:
    A generated string of text of the given length.
  """
  prediction_model = build_model(
      vocab_size=len(idx2char), batch_size=1, stateful=True)
  prediction_model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))
  prediction_model.build(tf.TensorShape([1, None]))

  input_eval = [char2idx[s] for s in context]
  input_eval = tf.expand_dims(input_eval, 0)

  text_generated = []

  prediction_model.reset_states()
  for _ in range(length - len(context)):
    predictions = prediction_model(input_eval)
    predictions = tf.squeeze(predictions, 0)

    # We applied a softmax to the output of the model so that
    # tf.keras.metrics.Recall would work. We need logits for
    # tf.random.categorical, so we convert the probabilities back to log odds
    predictions = tf.math.log(predictions / (1 - predictions))

    random_output = tf.random.categorical(predictions, num_samples=1)
    selected_id = random_output[-1, 0].numpy()
    input_eval = tf.expand_dims([selected_id], 0)
    text_generated.append(idx2char[selected_id])

  return context + ''.join(text_generated)


255
256
257
258
259
def run(flags_obj):
  """Run Shakespeare training and predict.

  Args:
    flags_obj: An object containing parsed flag values.
260

261
262
263
  Returns:
    Dictionary with status from the run.
  """
264
265
266
267
268
269
  if not flags_obj.training_data:
    raise ValueError(
        'Must set the path to a training data file. e.g download the following '
        'https://storage.googleapis.com/download.tensorflow.org/data/'
        'shakespeare.txt')

A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
270
  if flags_obj.dtype == 'fp16':
271
    tf.keras.mixed_precision.set_global_policy('mixed_float16')
A. Unique TensorFlower's avatar
A. Unique TensorFlower committed
272

273
274
275
  keras_utils.set_session_config(
      enable_xla=flags_obj.enable_xla)

276
  strategy = distribute_utils.get_distribution_strategy(
277
278
279
280
281
282
      distribution_strategy=flags_obj.distribution_strategy,
      num_gpus=flags_obj.num_gpus)

  dataset, idx2char, char2idx = get_dataset(flags_obj.training_data,
                                            batch_size=flags_obj.batch_size)
  stats = {}
283
  if flags_obj.train:
284
285
286
287
288
289
    history, callbacks = train_model(flags_obj, dataset,
                                     len(idx2char), strategy,
                                     checkpoint_dir=flags_obj.model_dir)

    stats['history'] = history.history
    stats['callbacks'] = callbacks
290
291
292
293
294
295
296
297
298
299

  if flags_obj.predict_context:
    if not flags_obj.model_dir:
      raise ValueError('Must set model_dir to get predictions.')
    print(make_prediction(flags_obj.model_dir,
                          flags_obj.predict_length,
                          flags_obj.predict_context,
                          idx2char,
                          char2idx))

300
301
302
303
304
305
306
  return stats


def main(_):
  flags_obj = flags.FLAGS
  run(flags_obj)

307
308
309

if __name__ == '__main__':
  define_flags()
310
  app.run(main)