Text generation with an RNN

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook

This tutorial demonstrates how to generate text using a character-based RNN. You will work with a dataset of Shakespeare's writing from Andrej Karpathy's The Unreasonable Effectiveness of Recurrent Neural Networks. Given a sequence of characters from this data ("Shakespear"), train a model to predict the next character in the sequence ("e"). Longer sequences of text can be generated by calling the model repeatedly.

This tutorial includes runnable code implemented using tf.keras and eager execution. The following is the sample output when the model in this tutorial trained for 30 epochs, and started with the prompt "Q":

QUEENE:
I had thought thou hadst a Roman; for the oracle,
Thus by All bids the man against the word,
Which are so weak of care, by old care done;
Your children were in your holy love,
And the precipitation through the bleeding throne.

BISHOP OF ELY:
Marry, and will, my lord, to weep in such a one were prettiest;
Yet now I was adopted heir
Of the world's lamentable day,
To watch the next way with his father with his face?

ESCALUS:
The cause why then we are all resolved more sons.

VOLUMNIA:
O, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, it is no sin it should be dead,
And love and pale as any will to that word.

QUEEN ELIZABETH:
But how long have I heard the soul for this world,
And show his hands of life be proved to stand.

PETRUCHIO:
I say he look'd on, if I must be content
To stay him from the fatal of our country's bliss.
His lordship pluck'd from this sentence then for prey,
And then let us twain, being the moon,
were she such a case as fills m

While some of the sentences are grammatical, most do not make sense. The model has not learned the meaning of words, but consider:

  • The model is character-based. When training started, the model did not know how to spell an English word, or that words were even a unit of text.

  • The structure of the output resembles a play—blocks of text generally begin with a speaker name, in all capital letters similar to the dataset.

  • As demonstrated below, the model is trained on small batches of text (100 characters each), and is still able to generate a longer sequence of text with coherent structure.

Setup

Import TensorFlow and other libraries

!pip install -q -U tf-keras

import os
import time

os.environ['TF_USE_LEGACY_KERAS'] = '1'

import numpy as np
import tensorflow as tf

Download the Shakespeare dataset

Change the following line to run this code on your own data.

path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')
Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt
1115394/1115394 [==============================] - 0s 0us/step

Read the data

First, look in the text:

# Read, then decode for py2 compat.
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')
# length of text is the number of characters in it
print(f'Length of text: {len(text)} characters')
Length of text: 1115394 characters
# Take a look at the first 250 characters in text
print(text[:250])
First Citizen:
Before we proceed any further, hear me speak.

All:
Speak, speak.

First Citizen:
You are all resolved rather to die than to famish?

All:
Resolved. resolved.

First Citizen:
First, you know Caius Marcius is chief enemy to the people.
# The unique characters in the file
vocab = sorted(set(text))
print(f'{len(vocab)} unique characters')
65 unique characters

Process the text

Vectorize the text

Before training, you need to convert the strings to a numerical representation.

The tf.keras.layers.StringLookup layer can convert each character into a numeric ID. It just needs the text to be split into tokens first.

example_texts = ['abcdefg', 'xyz']

chars = tf.strings.unicode_split(example_texts, input_encoding='UTF-8')
chars
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
W0000 00:00:1796300261.206915   62129 dlopen_checker.cc:38] Could not load dynamic library 'libcusolver.so.11'; dlerror: /tmpfs/src/tf_docs_env/lib/python3.11/site-packages/tensorflow/python/platform/../../../nvidia/cusolver/lib/../../cusparse/lib/libcusparse.so.12: undefined symbol: __nvJitLinkGetErrorLogSize_12_9, version libnvJitLink.so.12
W0000 00:00:1796300261.206956   62129 dlopen_checker.cc:38] Could not load dynamic library 'libcusparse.so.12'; dlerror: /tmpfs/src/tf_docs_env/lib/python3.11/site-packages/tensorflow/python/platform/../../../nvidia/cusparse/lib/libcusparse.so.12: undefined symbol: __nvJitLinkGetErrorLogSize_12_9, version libnvJitLink.so.12
W0000 00:00:1796300261.206960   62129 gpu_device.cc:2359] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
<tf.RaggedTensor [[b'a', b'b', b'c', b'd', b'e', b'f', b'g'], [b'x', b'y', b'z']]>

Now create the tf.keras.layers.StringLookup layer:

ids_from_chars = tf.keras.layers.StringLookup(
    vocabulary=list(vocab), mask_token=None)

It converts from tokens to character IDs:

ids = ids_from_chars(chars)
ids
<tf.RaggedTensor [[40, 41, 42, 43, 44, 45, 46], [63, 64, 65]]>

Since the goal of this tutorial is to generate text, it will also be important to invert this representation and recover human-readable strings from it. For this you can use tf.keras.layers.StringLookup(..., invert=True).

chars_from_ids = tf.keras.layers.StringLookup(
    vocabulary=ids_from_chars.get_vocabulary(), invert=True, mask_token=None)

This layer recovers the characters from the vectors of IDs, and returns them as a tf.RaggedTensor of characters:

chars = chars_from_ids(ids)
chars
<tf.RaggedTensor [[b'a', b'b', b'c', b'd', b'e', b'f', b'g'], [b'x', b'y', b'z']]>

You can tf.strings.reduce_join to join the characters back into strings.

tf.strings.reduce_join(chars, axis=-1).numpy()
array([b'abcdefg', b'xyz'], dtype=object)
def text_from_ids(ids):
  return tf.strings.reduce_join(chars_from_ids(ids), axis=-1)

The prediction task

Given a character, or a sequence of characters, what is the most probable next character? This is the task you're training the model to perform. The input to the model will be a sequence of characters, and you train the model to predict the output—the following character at each time step.

Since RNNs maintain an internal state that depends on the previously seen elements, given all the characters computed until this moment, what is the next character?

Create training examples and targets

Next divide the text into example sequences. Each input sequence will contain seq_length characters from the text.

For each input sequence, the corresponding targets contain the same length of text, except shifted one character to the right.

So break the text into chunks of seq_length+1. For example, say seq_length is 4 and our text is "Hello". The input sequence would be "Hell", and the target sequence "ello".

To do this first use the tf.data.Dataset.from_tensor_slices function to convert the text vector into a stream of character indices.

all_ids = ids_from_chars(tf.strings.unicode_split(text, 'UTF-8'))
all_ids
<tf.Tensor: shape=(1115394,), dtype=int64, numpy=array([19, 48, 57, ..., 46,  9,  1], shape=(1115394,))>
ids_dataset = tf.data.Dataset.from_tensor_slices(all_ids)
for ids in ids_dataset.take(10):
    print(chars_from_ids(ids).numpy().decode('utf-8'))
F
i
r
s
t
 
C
i
t
i
seq_length = 100

The batch method lets you easily convert these individual characters to sequences of the desired size.

sequences = ids_dataset.batch(seq_length+1, drop_remainder=True)

for seq in sequences.take(1):
  print(chars_from_ids(seq))
tf.Tensor(
[b'F' b'i' b'r' b's' b't' b' ' b'C' b'i' b't' b'i' b'z' b'e' b'n' b':'
 b'\n' b'B' b'e' b'f' b'o' b'r' b'e' b' ' b'w' b'e' b' ' b'p' b'r' b'o'
 b'c' b'e' b'e' b'd' b' ' b'a' b'n' b'y' b' ' b'f' b'u' b'r' b't' b'h'
 b'e' b'r' b',' b' ' b'h' b'e' b'a' b'r' b' ' b'm' b'e' b' ' b's' b'p'
 b'e' b'a' b'k' b'.' b'\n' b'\n' b'A' b'l' b'l' b':' b'\n' b'S' b'p' b'e'
 b'a' b'k' b',' b' ' b's' b'p' b'e' b'a' b'k' b'.' b'\n' b'\n' b'F' b'i'
 b'r' b's' b't' b' ' b'C' b'i' b't' b'i' b'z' b'e' b'n' b':' b'\n' b'Y'
 b'o' b'u' b' '], shape=(101,), dtype=string)

It's easier to see what this is doing if you join the tokens back into strings:

for seq in sequences.take(5):
  print(text_from_ids(seq).numpy())
b'First Citizen:\nBefore we proceed any further, hear me speak.\n\nAll:\nSpeak, speak.\n\nFirst Citizen:\nYou '
b'are all resolved rather to die than to famish?\n\nAll:\nResolved. resolved.\n\nFirst Citizen:\nFirst, you k'
b"now Caius Marcius is chief enemy to the people.\n\nAll:\nWe know't, we know't.\n\nFirst Citizen:\nLet us ki"
b"ll him, and we'll have corn at our own price.\nIs't a verdict?\n\nAll:\nNo more talking on't; let it be d"
b'one: away, away!\n\nSecond Citizen:\nOne word, good citizens.\n\nFirst Citizen:\nWe are accounted poor citi'

For training you'll need a dataset of (input, label) pairs. Where input and label are sequences. At each time step the input is the current character and the label is the next character.

Here's a function that takes a sequence as input, duplicates, and shifts it to align the input and label for each timestep:

def split_input_target(sequence):
    input_text = sequence[:-1]
    target_text = sequence[1:]
    return input_text, target_text
split_input_target(list("Tensorflow"))
(['T', 'e', 'n', 's', 'o', 'r', 'f', 'l', 'o'],
 ['e', 'n', 's', 'o', 'r', 'f', 'l', 'o', 'w'])
dataset = sequences.map(split_input_target)
for input_example, target_example in dataset.take(1):
    print("Input :", text_from_ids(input_example).numpy())
    print("Target:", text_from_ids(target_example).numpy())
Input : b'First Citizen:\nBefore we proceed any further, hear me speak.\n\nAll:\nSpeak, speak.\n\nFirst Citizen:\nYou'
Target: b'irst Citizen:\nBefore we proceed any further, hear me speak.\n\nAll:\nSpeak, speak.\n\nFirst Citizen:\nYou '

Create training batches

You used tf.data to split the text into manageable sequences. But before feeding this data into the model, you need to shuffle the data and pack it into batches.

# Batch size
BATCH_SIZE = 64

# Buffer size to shuffle the dataset
# (TF data is designed to work with possibly infinite sequences,
# so it doesn't attempt to shuffle the entire sequence in memory. Instead,
# it maintains a buffer in which it shuffles elements).
BUFFER_SIZE = 10000

dataset = (
    dataset
    .shuffle(BUFFER_SIZE)
    .batch(BATCH_SIZE, drop_remainder=True)
    .prefetch(tf.data.experimental.AUTOTUNE))

dataset
<_PrefetchDataset element_spec=(TensorSpec(shape=(64, 100), dtype=tf.int64, name=None), TensorSpec(shape=(64, 100), dtype=tf.int64, name=None))>

Build The Model

This section defines the model as a keras.Model subclass (For details see Making new Layers and Models via subclassing).

This model has three layers:

  • tf.keras.layers.Embedding: The input layer. A trainable lookup table that will map each character-ID to a vector with embedding_dim dimensions;
  • tf.keras.layers.GRU: A type of RNN with size units=rnn_units (You can also use an LSTM layer here.)
  • tf.keras.layers.Dense: The output layer, with vocab_size outputs. It outputs one logit for each character in the vocabulary. These are the log-likelihood of each character according to the model.
# Length of the vocabulary in StringLookup Layer
vocab_size = len(ids_from_chars.get_vocabulary())

# The embedding dimension
embedding_dim = 256

# Number of RNN units
rnn_units = 1024
class MyModel(tf.keras.Model):
  def __init__(self, vocab_size, embedding_dim, rnn_units):
    super().__init__()
    self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
    self.gru = tf.keras.layers.GRU(rnn_units,
                                   return_sequences=True,
                                   return_state=True)
    self.dense = tf.keras.layers.Dense(vocab_size)

  def call(self, inputs, states=None, return_state=False, training=False):
    x = inputs
    x = self.embedding(x, training=training)
    if states is None:
      states = self.gru.get_initial_state(x)
    x, states = self.gru(x, initial_state=states, training=training)
    x = self.dense(x, training=training)

    if return_state:
      return x, states
    else:
      return x
model = MyModel(
    vocab_size=vocab_size,
    embedding_dim=embedding_dim,
    rnn_units=rnn_units)

For each character the model looks up the embedding, runs the GRU one timestep with the embedding as input, and applies the dense layer to generate logits predicting the log-likelihood of the next character:

A drawing of the data passing through the model

Try the model

Now run the model to see that it behaves as expected.

First check the shape of the output:

for input_example_batch, target_example_batch in dataset.take(1):
    example_batch_predictions = model(input_example_batch)
    print(example_batch_predictions.shape, "# (batch_size, sequence_length, vocab_size)")
(64, 100, 66) # (batch_size, sequence_length, vocab_size)

In the above example the sequence length of the input is 100 but the model can be run on inputs of any length:

model.summary()
Model: "my_model"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 embedding (Embedding)       multiple                  16896

 gru (GRU)                   multiple                  3938304

 dense (Dense)               multiple                  67650

=================================================================
Total params: 4022850 (15.35 MB)
Trainable params: 4022850 (15.35 MB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________

To get actual predictions from the model you need to sample from the output distribution, to get actual character indices. This distribution is defined by the logits over the character vocabulary.

Try it for the first example in the batch:

sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)
sampled_indices = tf.squeeze(sampled_indices, axis=-1).numpy()

This gives us, at each timestep, a prediction of the next character index:

sampled_indices
array([ 6, 49, 21, 38, 40, 52, 15,  5, 22, 29, 41, 22, 15, 10, 36, 21, 53,
       13, 15, 31, 57, 58, 63, 55, 60, 39, 37, 59, 24, 36, 62, 27, 34, 47,
       50, 23, 34, 29, 10, 41, 45, 54, 20, 61, 65, 59, 45,  5, 64, 33, 11,
       53, 31, 29, 64, 49, 47,  3, 23, 41, 36, 35, 24, 54,  6,  5, 18,  2,
        2, 39, 16, 34, 60, 25, 28,  8, 41, 19, 41, 29, 25,  9, 47, 40,  4,
        3, 24,  5, 47, 23, 31, 43, 65, 19, 19,  1, 29, 45, 26, 61])

Decode these to see the text predicted by this untrained model:

print("Input:\n", text_from_ids(input_example_batch[0]).numpy())
print()
print("Next Char Predictions:\n", text_from_ids(sampled_indices).numpy())
Input:
 b"give my poor host freedom.\n\nCOMINIUS:\nO, well begg'd!\nWere he the butcher of my son, he should\nBe fr"

Next Char Predictions:
 b"'jHYamB&IPbIB3WHn?BRrsxpuZXtKWwNUhkJUP3bfoGvztf&yT:nRPyjh!JbWVKo'&E  ZCUuLO-bFbPL.ha$!K&hJRdzFF\nPfMv"

Train the model

At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character.

Attach an optimizer, and a loss function

The standard tf.keras.losses.sparse_categorical_crossentropy loss function works in this case because it is applied across the last dimension of the predictions.

Because your model returns logits, you need to set the from_logits flag.

loss = tf.losses.SparseCategoricalCrossentropy(from_logits=True)
example_batch_mean_loss = loss(target_example_batch, example_batch_predictions)
print("Prediction shape: ", example_batch_predictions.shape, " # (batch_size, sequence_length, vocab_size)")
print("Mean loss:        ", example_batch_mean_loss)
Prediction shape:  (64, 100, 66)  # (batch_size, sequence_length, vocab_size)
Mean loss:         tf.Tensor(4.189432, shape=(), dtype=float32)

A newly initialized model shouldn't be too sure of itself, the output logits should all have similar magnitudes. To confirm this you can check that the exponential of the mean loss is approximately equal to the vocabulary size. A much higher loss means the model is sure of its wrong answers, and is badly initialized:

tf.exp(example_batch_mean_loss).numpy()
np.float32(65.98531)

Configure the training procedure using the tf.keras.Model.compile method. Use tf.keras.optimizers.Adam with default arguments and the loss function.

model.compile(optimizer='adam', loss=loss)

Configure checkpoints

Use a tf.keras.callbacks.ModelCheckpoint to ensure that checkpoints are saved during training:

# Directory where the checkpoints will be saved
checkpoint_dir = './training_checkpoints'
# Name of the checkpoint files
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")

checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_prefix,
    save_weights_only=True)

Execute the training

To keep training time reasonable, use 10 epochs to train the model. In Colab, set the runtime to GPU for faster training.

EPOCHS = 20
history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback])
Epoch 1/20
172/172 [==============================] - 95s 534ms/step - loss: 2.7339
Epoch 2/20
172/172 [==============================] - 92s 532ms/step - loss: 1.9905
Epoch 3/20
172/172 [==============================] - 93s 533ms/step - loss: 1.7093
Epoch 4/20
172/172 [==============================] - 92s 530ms/step - loss: 1.5471
Epoch 5/20
172/172 [==============================] - 92s 531ms/step - loss: 1.4481
Epoch 6/20
172/172 [==============================] - 92s 530ms/step - loss: 1.3817
Epoch 7/20
172/172 [==============================] - 92s 529ms/step - loss: 1.3287
Epoch 8/20
172/172 [==============================] - 92s 527ms/step - loss: 1.2836
Epoch 9/20
172/172 [==============================] - 92s 529ms/step - loss: 1.2417
Epoch 10/20
172/172 [==============================] - 92s 528ms/step - loss: 1.2014
Epoch 11/20
172/172 [==============================] - 92s 529ms/step - loss: 1.1616
Epoch 12/20
172/172 [==============================] - 92s 526ms/step - loss: 1.1203
Epoch 13/20
172/172 [==============================] - 91s 525ms/step - loss: 1.0757
Epoch 14/20
172/172 [==============================] - 91s 524ms/step - loss: 1.0287
Epoch 15/20
172/172 [==============================] - 92s 528ms/step - loss: 0.9805
Epoch 16/20
172/172 [==============================] - 91s 525ms/step - loss: 0.9293
Epoch 17/20
172/172 [==============================] - 91s 524ms/step - loss: 0.8751
Epoch 18/20
172/172 [==============================] - 92s 526ms/step - loss: 0.8240
Epoch 19/20
172/172 [==============================] - 91s 525ms/step - loss: 0.7713
Epoch 20/20
172/172 [==============================] - 91s 524ms/step - loss: 0.7233

Generate text

The simplest way to generate text with this model is to run it in a loop, and keep track of the model's internal state as you execute it.

To generate text the model's output is fed back to the input

Each time you call the model you pass in some text and an internal state. The model returns a prediction for the next character and its new state. Pass the prediction and state back in to continue generating text.

The following makes a single step prediction:

class OneStep(tf.keras.Model):
  def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0):
    super().__init__()
    self.temperature = temperature
    self.model = model
    self.chars_from_ids = chars_from_ids
    self.ids_from_chars = ids_from_chars

    # Create a mask to prevent "[UNK]" from being generated.
    skip_ids = self.ids_from_chars(['[UNK]'])[:, None]
    sparse_mask = tf.SparseTensor(
        # Put a -inf at each bad index.
        values=[-float('inf')]*len(skip_ids),
        indices=skip_ids,
        # Match the shape to the vocabulary
        dense_shape=[len(ids_from_chars.get_vocabulary())])
    self.prediction_mask = tf.sparse.to_dense(sparse_mask)

  @tf.function
  def generate_one_step(self, inputs, states=None):
    # Convert strings to token IDs.
    input_chars = tf.strings.unicode_split(inputs, 'UTF-8')
    input_ids = self.ids_from_chars(input_chars).to_tensor()

    # Run the model.
    # predicted_logits.shape is [batch, char, next_char_logits]
    predicted_logits, states = self.model(inputs=input_ids, states=states,
                                          return_state=True)
    # Only use the last prediction.
    predicted_logits = predicted_logits[:, -1, :]
    predicted_logits = predicted_logits/self.temperature
    # Apply the prediction mask: prevent "[UNK]" from being generated.
    predicted_logits = predicted_logits + self.prediction_mask

    # Sample the output logits to generate token IDs.
    predicted_ids = tf.random.categorical(predicted_logits, num_samples=1)
    predicted_ids = tf.squeeze(predicted_ids, axis=-1)

    # Convert from token ids to characters
    predicted_chars = self.chars_from_ids(predicted_ids)

    # Return the characters and model state.
    return predicted_chars, states
one_step_model = OneStep(model, chars_from_ids, ids_from_chars)

Run it in a loop to generate some text. Looking at the generated text, you'll see the model knows when to capitalize, make paragraphs and imitates a Shakespeare-like writing vocabulary. With the small number of training epochs, it has not yet learned to form coherent sentences.

start = time.time()
states = None
next_char = tf.constant(['ROMEO:'])
result = [next_char]

for n in range(1000):
  next_char, states = one_step_model.generate_one_step(next_char, states=states)
  result.append(next_char)

result = tf.strings.join(result)
end = time.time()
print(result[0].numpy().decode('utf-8'), '\n\n' + '_'*80)
print('\nRun time:', end - start)
ROMEO:
Nay, then Metter at Savio!--
And he been repetition!

First Senator:
Not of her help to arm that shrew myself,
And see how he yielded me, or this most ignorance
That ever liefed this most publicle:
But I, with that shall spoil thy browdry souls;
Then like a hopich to his fairest head,
And hundred him for 'good his brother Guty:
What say is this thy cold, shall never see thee,
Reaposts her no more advancence, wetchwack
Build'd from the place, still my name for cheers,
Deed hap which craves shall be so strongly: seal thy torch: I,
but not to bed of joy will obsyran with
his eye: were boy: old goating fire she speaks us.

GONZELO:
Then is it were aside your honour's ear,
She make the sea from vile summers stabless
The city. But, am I but justice
with mine own mouth, though thou art a hill,
And Now thy heavy charges of my brother
And repath may give thee a diseal throne,
I must believe thy helmet-times hath Duke's
Assistours in the leaves-for off
Unlook'd upon us. Whither?

SICINIUS:
You  

________________________________________________________________________________

Run time: 2.3631138801574707

The easiest thing you can do to improve the results is to train it for longer (try EPOCHS = 30).

You can also experiment with a different start string, try adding another RNN layer to improve the model's accuracy, or adjust the temperature parameter to generate more or less random predictions.

If you want the model to generate text faster the easiest thing you can do is batch the text generation. In the example below the model generates 5 outputs in about the same time it took to generate 1 above.

start = time.time()
states = None
next_char = tf.constant(['ROMEO:', 'ROMEO:', 'ROMEO:', 'ROMEO:', 'ROMEO:'])
result = [next_char]

for n in range(1000):
  next_char, states = one_step_model.generate_one_step(next_char, states=states)
  result.append(next_char)

result = tf.strings.join(result)
end = time.time()
print(result, '\n\n' + '_'*80)
print('\nRun time:', end - start)
tf.Tensor(
[b"ROMEO:\nThere let the man and the iching of thy people,\nBefore you with a flowery neighbours by your neighbours,\nWhich you cannot business possessed with going\nA nept of a summect bears, a man, or else\nI use the sovereign and acroady that\nWhich is not thy heart's regive than their hell,\nAnd little forfend that she, I have to hear\nAs think'st that we die done. These grace\nHe does at his use to win our voices,\nShe moveably aching occasions;\nAnd therefore can smile at their pound, my brother's state\nTo misisties an oath between mangle to thee,\nThou hast assuing me the forfeian's moie.\n\nPROSPERO:\nBe thou and these?\n\nKING RICHARD III:\nAy, not a mind; we talk not.\n\nFirst Senator:\nNob, you have pardon:\n'Thank you;' an if this hand, I hear they muster us:\nBut neither he commens it thus far safe,\nBears his for near; nay, my conceit myself:\nStay not from them to loss of house.\n\nBIONDELLO:\nO ho! we will not know thy gentlemen,\nAnd nevolkicle his voice: make your consul.\n\nCURTIS:\nWhy, a hailthon why?\n\nBA"
 b"ROMEO:\nAnd we are made the seal of wrence,--wept for mercy,\nAnd is the best insirent confirm'd clown'd hastest,\nAnd cheer'd off by my false hours in't,\nYou are power to thy eyes, which thou hast marr'd.\nBut when he ride, cold citizens and have accuse\nOf in submosts: with a fill thing entering\nFrom them awhile: well alone make up riching\nByhels But that his hate while or I\nDo him arrived for ever.\n\nPRINCE EDWARD:\nBest he that halloom it each horns,\nI'll win the time, when such a tangtee of\nthy conscience, the fiery true of father wrong,\nLocks the earth, and that's not foul misfortune down\nThey prosper you! one noble heart\nFrome harm from me that revoved his justicesh'd cames,\nTill to the fireTy 'gainst our councry: I\nAm I must fall in too frame my brother die.\n\nProvost:\nI am a husband, lent your grace may stables,\nEither had left me to the triumph die.\n\nLaDY CAPULET:\nWhen he shall did.\n\nPOLIXENES:\nA senseless voices,\nWe have part'd with her tombin thieves;\nSuster this direful time how foul fi"
 b"ROMEO:\nThese eyes that rises but thy pieces. What could have\nno judgement and brave York, and will not speak\nFor what this valour. this did I know thou?--\nAnd he is crown'd by the oaker pardon him.\n\nProvost:\nAy, sir; what hath a toiz? from whence is fixed\nFrom thy hand! which was the cause\nBy fair young Rutland, not of honour friends,\nNot of that vow of fault; and then I'll saycr\nyet that conguius impress'd off it?\n\nHENRY BOLINGBROKE:\nWhat fast leg Richard left upon it?\nI am abled to say that I am undone.\n\nGREMIO:\nA part, I gail it is to famm;\n'trick for the Capitol mer; away!\n\nSecond Murderer:\nWhere is my fancy of Wern married?\n\nLARTIUS:\nThere was it not a black of with content.\n\nMENENIUS:\nDown with her\nSelfommed with any children of your tongue.\n\nFLORIZEL:\nI have: but hadst thou so:\n'Tis trang-fis thine; straight shall not call me thrown in his master;\nSuch wits are marvellous, and let it read\nA name as in my tent that rustless child\nLife on his party: authority\nMethinks she hung about of "
 b"ROMEO:\nThis matter, Lancaster, and him\nAre you a loyal present peace,\nTo furrer is thy husband's royalty, thus\nI could I need no more loin'd withal.\n\nTRANIO:\nFaith, noble prince!\n\nApothecary:\nCursed him for this gentleman: there is no tonguel,\nTherefore can be so resolved to the senate;\nAhoin upand, proud queen and life, perform at nine\nearse alive. I'll hear us all;\nIn sometitu and reigns: we may put not\nCorn both my Edward Delivery.\n\nQUEEN MARGARET:\nAnd look you not ato.\n\nROMEO:\nI have seen the duke did march on one.\n\nWARWICK:\nSay, Standake is come to you; there is she\naccuse his bail. Come, what of that?\n\nKATHARINA:\nAre you in earnest? speaking load, Buckingham--\nIs is the city may be still.\n\nRICHARD:\nAnd turns were fraitt's Suns and recree before\nEven with the sides; no hopels of a morring; now\nNot-honour'd lances to me; come, all alone.\n\nPAULINA:\nTrue.\n\nSOMERSET:\nIt shall be ruled by the comforted when Bohemia\n\nPETRUCHIO:\nNay, that I was my master, go, Edward lo,\nMy absolute fore and am"
 b"ROMEO:\nWhat! look upon me? Master life, for the prince's name\nIs nothing. God make an envious both of war\nAgainst my windows looks addaid:\n'What, nor none with nature, heartily; take it one:\nI am the king's fight wherein which serves\nWe not too while the king of fiary Rome,\nSome nightingate for like: thou the way but now\nCamillo betwixt them then most wivowch.\nWisble with a traitor to I fish at Dian's table.\n\nBAPTISTA:\nAnd you, my noble brother may be writ.\n\nGREEN:\nAll seest thou to mine; or I will find his cap of it\ngloces: marry, I have gone roteet,\nI long to send the Duke of Norfolk,\nTo make an end; I am struck not\nIn horses, unfiside, they sky their wetchmends.\n\nhereford, Exize,\nThe cause was nature's forward of crossing fable,\nTheir head no right relove when I battle,\nThis sing it should her married win my valour.\nCome, entreat our babe: I'll not be long light o'\nthe king is here with silver and recrepita's fault;\nAnd tells such Jackic and the two knows how much\n'dife's nothing; no surp"], shape=(5,), dtype=string) 

________________________________________________________________________________

Run time: 2.121931552886963

Export the generator

This single-step model can easily be saved and restored, allowing you to use it anywhere a tf.saved_model is accepted.

tf.saved_model.save(one_step_model, 'one_step')
one_step_reloaded = tf.saved_model.load('one_step')
WARNING:tensorflow:Skipping full serialization of TF-Keras layer <__main__.OneStep object at 0x7f6fdc464390>, because it is not built.
WARNING:tensorflow:Skipping full serialization of TF-Keras layer <__main__.OneStep object at 0x7f6fdc464390>, because it is not built.
WARNING:tensorflow:Model's `__init__()` arguments contain non-serializable objects. Please implement a `get_config()` method in the subclassed Model for proper saving and loading. Defaulting to empty config.
WARNING:tensorflow:Model's `__init__()` arguments contain non-serializable objects. Please implement a `get_config()` method in the subclassed Model for proper saving and loading. Defaulting to empty config.
WARNING:tensorflow:Model's `__init__()` arguments contain non-serializable objects. Please implement a `get_config()` method in the subclassed Model for proper saving and loading. Defaulting to empty config.
WARNING:tensorflow:Model's `__init__()` arguments contain non-serializable objects. Please implement a `get_config()` method in the subclassed Model for proper saving and loading. Defaulting to empty config.
INFO:tensorflow:Assets written to: one_step/assets
INFO:tensorflow:Assets written to: one_step/assets
states = None
next_char = tf.constant(['ROMEO:'])
result = [next_char]

for n in range(100):
  next_char, states = one_step_reloaded.generate_one_step(next_char, states=states)
  result.append(next_char)

print(tf.strings.join(result)[0].numpy().decode("utf-8"))
ROMEO:
And you this people?

MENENIUS:
We are all thing of new misapplied
And lace of cicily's angry, to h

Advanced: Customized Training

The above training procedure is simple, but does not give you much control. It uses teacher-forcing which prevents bad predictions from being fed back to the model, so the model never learns to recover from mistakes.

So now that you've seen how to run the model manually next you'll implement the training loop. This gives a starting point if, for example, you want to implement curriculum learning to help stabilize the model's open-loop output.

The most important part of a custom training loop is the train step function.

Use tf.GradientTape to track the gradients. You can learn more about this approach by reading the eager execution guide.

The basic procedure is:

  1. Execute the model and calculate the loss under a tf.GradientTape.
  2. Calculate the updates and apply them to the model using the optimizer.
class CustomTraining(MyModel):
  @tf.function
  def train_step(self, inputs):
      inputs, labels = inputs
      with tf.GradientTape() as tape:
          predictions = self(inputs, training=True)
          loss = self.loss(labels, predictions)
      grads = tape.gradient(loss, model.trainable_variables)
      self.optimizer.apply_gradients(zip(grads, model.trainable_variables))

      return {'loss': loss}

The above implementation of the train_step method follows Keras' train_step conventions. This is optional, but it allows you to change the behavior of the train step and still use keras' Model.compile and Model.fit methods.

model = CustomTraining(
    vocab_size=len(ids_from_chars.get_vocabulary()),
    embedding_dim=embedding_dim,
    rnn_units=rnn_units)
model.compile(optimizer = tf.keras.optimizers.Adam(),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))
model.fit(dataset, epochs=1)
172/172 [==============================] - 93s 521ms/step - loss: 2.7287
<tf_keras.src.callbacks.History at 0x7f6fdc491e90>

Or if you need more control, you can write your own complete custom training loop:

EPOCHS = 10

mean = tf.metrics.Mean()

for epoch in range(EPOCHS):
    start = time.time()

    mean.reset_states()
    for (batch_n, (inp, target)) in enumerate(dataset):
        logs = model.train_step([inp, target])
        mean.update_state(logs['loss'])

        if batch_n % 50 == 0:
            template = f"Epoch {epoch+1} Batch {batch_n} Loss {logs['loss']:.4f}"
            print(template)

    # saving (checkpoint) the model every 5 epochs
    if (epoch + 1) % 5 == 0:
        model.save_weights(checkpoint_prefix.format(epoch=epoch))

    print()
    print(f'Epoch {epoch+1} Loss: {mean.result().numpy():.4f}')
    print(f'Time taken for 1 epoch {time.time() - start:.2f} sec')
    print("_"*80)

model.save_weights(checkpoint_prefix.format(epoch=epoch))
Epoch 1 Batch 0 Loss 2.1728
Epoch 1 Batch 50 Loss 2.0724
Epoch 1 Batch 100 Loss 2.0046
Epoch 1 Batch 150 Loss 1.8792
Epoch 1 Loss: 2.0005
Time taken for 1 epoch 91.75 sec
________________________________________________________________________________
Epoch 2 Batch 0 Loss 1.8301
Epoch 2 Batch 50 Loss 1.7385
Epoch 2 Batch 100 Loss 1.6800
Epoch 2 Batch 150 Loss 1.6676
Epoch 2 Loss: 1.7232
Time taken for 1 epoch 90.36 sec
________________________________________________________________________________
Epoch 3 Batch 0 Loss 1.6174
Epoch 3 Batch 50 Loss 1.6062
Epoch 3 Batch 100 Loss 1.5647
Epoch 3 Batch 150 Loss 1.4876
Epoch 3 Loss: 1.5603
Time taken for 1 epoch 90.74 sec
________________________________________________________________________________
Epoch 4 Batch 0 Loss 1.5123
Epoch 4 Batch 50 Loss 1.4403
Epoch 4 Batch 100 Loss 1.4659
Epoch 4 Batch 150 Loss 1.4138
Epoch 4 Loss: 1.4587
Time taken for 1 epoch 90.60 sec
________________________________________________________________________________
Epoch 5 Batch 0 Loss 1.3663
Epoch 5 Batch 50 Loss 1.3637
Epoch 5 Batch 100 Loss 1.4183
Epoch 5 Batch 150 Loss 1.3388
Epoch 5 Loss: 1.3882
Time taken for 1 epoch 90.69 sec
________________________________________________________________________________
Epoch 6 Batch 0 Loss 1.2868
Epoch 6 Batch 50 Loss 1.3561
Epoch 6 Batch 100 Loss 1.3306
Epoch 6 Batch 150 Loss 1.3328
Epoch 6 Loss: 1.3350
Time taken for 1 epoch 90.50 sec
________________________________________________________________________________
Epoch 7 Batch 0 Loss 1.3063
Epoch 7 Batch 50 Loss 1.2996
Epoch 7 Batch 100 Loss 1.3199
Epoch 7 Batch 150 Loss 1.2952
Epoch 7 Loss: 1.2913
Time taken for 1 epoch 90.78 sec
________________________________________________________________________________
Epoch 8 Batch 0 Loss 1.2714
Epoch 8 Batch 50 Loss 1.2759
Epoch 8 Batch 100 Loss 1.2736
Epoch 8 Batch 150 Loss 1.2375
Epoch 8 Loss: 1.2499
Time taken for 1 epoch 92.22 sec
________________________________________________________________________________
Epoch 9 Batch 0 Loss 1.2013
Epoch 9 Batch 50 Loss 1.1910
Epoch 9 Batch 100 Loss 1.2380
Epoch 9 Batch 150 Loss 1.2153
Epoch 9 Loss: 1.2098
Time taken for 1 epoch 91.28 sec
________________________________________________________________________________
Epoch 10 Batch 0 Loss 1.1513
Epoch 10 Batch 50 Loss 1.1766
Epoch 10 Batch 100 Loss 1.1938
Epoch 10 Batch 150 Loss 1.1407
Epoch 10 Loss: 1.1709
Time taken for 1 epoch 92.85 sec
________________________________________________________________________________