Overview

8 Text Generation with Recurrent Neural Networks (RNNs)

This chapter shifts the book’s focus to text generation and explains why modeling language is challenging: meaning depends on strict word order, long-range context, and ambiguous, culturally nuanced usage. It introduces recurrent neural networks (RNNs) as architectures built for sequences, emphasizing how hidden states carry information over time. Long Short-Term Memory (LSTM) networks are highlighted as a stronger RNN variant that better preserves long- and short-term dependencies, enabling more coherent language modeling while still having limitations on very long contexts. The chapter’s goal is to teach the core principles of text generation with an LSTM and use those lessons to motivate more advanced Transformer models later.

The workflow centers on preparing and modeling text at the word level. After selecting a suitably sized training corpus (the novel Anna Karenina), the text is cleaned and tokenized; vocabularies and integer mappings are built; and the corpus is converted to sequences of fixed length, with targets formed by shifting inputs one token to the right for next-token prediction. The chapter contrasts character, word, and subword tokenization, then focuses on word tokenization for clarity. To overcome inefficiencies of one-hot vectors, an embedding layer learns dense representations that capture semantic relationships. A PyTorch model stacks an embedding, multi-layer LSTM, and a linear output over the vocabulary, and is trained with cross-entropy loss and Adam on mini-batches, then saved alongside the tokenizer mappings for inference.

Generation proceeds by feeding a prompt and repeatedly sampling the next token from the model’s predicted distribution, appending each choice back into the context. The chapter shows how temperature scaling and top-K sampling shape output: lower temperature and small K favor safer, more coherent text, while higher temperature and large K increase diversity but can reduce coherence. The resulting LSTM generations are grammatically reasonable and stylistically influenced by the training data, though not on par with state-of-the-art systems. The key takeaway is a solid foundation in tokenization, embeddings, sequence modeling, and sampling strategies, preparing readers for upcoming chapters on attention and Transformer architectures.

How a layer of recurrent neurons unfolds through time. When a recurrent neural network makes a prediction on sequential data, it takes the hidden state from the previous time step, h(t-1), along with the input at the current time step, x(t), and generates the output, y(t), and the updated hidden state, h(t). The hidden state at time step t captures the information in all previous time steps, x(0), x(1), …, x(t).
An example of how an LSTM model is trained. We first break down the training text into tokens and assign a unique integer to each token, creating a numerical representation of the text as a sequence of indexes. We then divide this long sequence into shorter sequences of equal length. These sequences form the features (the x variable) of our model. We then generate the output y by shifting the input sequence one token to the right. This setup enables the LSTM model to predict the next token based on previous tokens in the sequence.

Summary

  • Recurrent neural networks (RNNs) are a specialized form of artificial neural network designed to recognize patterns in sequences of data, such as text, music, or stock prices. Unlike traditional neural networks, which process inputs independently, RNNs have loops in them, allowing information to persist. Long short-term memory (LSTM) networks are improved versions of RNNs.
  • There are three approaches to tokenization. The first is character tokenization, where the text is divided into its constituent characters. The second approach is word tokenization, where the text is split into individual words. The third approach is subword tokenization, which breaks words into smaller, meaningful components called subwords.
  • Word embedding is a method that transforms words into compact vector representations, capturing their semantic information and interrelationships. This technique is vital in NLP, especially since deep neural networks, including models like LSTM and Transformers, require numerical input.
  • Temperature is a parameter to influence the behavior of text generation models. It controls the randomness of the predictions by scaling the logits (the inputs to the softmax function for probability calculation) before applying softmax. Low temperature makes the model more conservative in its predictions but also more repetitive. At higher temperatures, the model becomes less repetitive and more innovative increasing the diversity of the generated text.
  • Top-K sampling is another way to influence the behavior of text generation models. It involves selecting the next word from the K most likely candidates, as determined by the model. The probability distribution is truncated to keep only the top K words. Small values of K make the output more predictable and coherent but potentially less diverse and interesting.

FAQ

Why are RNNs suitable for text generation, and how do they differ from feedforward networks?RNNs process inputs sequentially and maintain a hidden state that summarizes information from previous time steps, which lets them model word order and context. Feedforward networks treat each input independently and cannot capture temporal dependencies, making them less suitable for text generation.
Why use LSTMs instead of vanilla RNNs?Standard RNNs struggle with long-range dependencies due to vanishing gradients. LSTMs introduce a cell state and gating mechanisms that let the model retain or forget information over many time steps, enabling better handling of long-term context in text.
What tokenization methods are covered, and when should I use each?- Character tokenization: tiny vocabulary, fast to train, but weak semantics per token. Useful for languages with rich morphology. - Word tokenization: easy to understand and implement; tokens carry meaning, but vocabulary can be large. - Subword tokenization: splits rare words into pieces, keeps frequent words whole; balances vocabulary size and semantic fidelity. It’s the approach used by modern LLMs and later chapters.
What is word embedding and why is it preferable to one-hot encoding?Word embeddings map tokens to dense, low-dimensional vectors that capture semantic similarity (similar words are close in embedding space). This is more efficient than large sparse one-hot vectors and improves learning. In PyTorch, nn.Embedding provides a trainable lookup table learned during training.
How is the Anna Karenina text prepared for training?- Download the text and clean it: lowercase, replace line breaks/hyphens with spaces, and insert spaces around punctuation so punctuation becomes separate tokens. - Build a vocabulary from token frequencies (about 12,778 unique tokens in this chapter’s setup). - Create mappings word_to_int and int_to_word, then convert the full text to a sequence of indexes.
How are training sequences and targets created?Use sliding windows of length 100 over the index sequence as inputs x. Create targets y by shifting each input window by one token to the right. This trains the model to predict the next token given the previous tokens. Data are batched (batch size 32) with a DataLoader.
What does the PyTorch LSTM model look like and which hyperparameters are used?The model has an embedding layer (dim 128), a stacked LSTM with 3 layers, hidden size 128, dropout 0.2, and a final linear layer projecting to vocabulary size. Training uses Adam with learning rate 0.0001 and CrossEntropyLoss, with gradient clipping. It’s trained for 50 epochs.
How long does training take and what gets saved?On a CUDA-enabled GPU, training takes roughly hours (about six in the chapter’s setup); on CPU it can take a day or more. After training, save the model weights (state_dict) and the word_to_int dictionary so you can generate without reprocessing the text.
How is text generated from the trained LSTM?Provide a prompt, convert it to indexes, and iteratively predict one token at a time. Append each chosen token to the sequence and feed either the whole sequence (if short) or the last 100 tokens back into the model. Sampling is done from the softmax probabilities; punctuation spacing is post-processed. Fixing random seeds makes results reproducible.
How do temperature and top-K sampling affect creativity and coherence?- Temperature rescales logits before softmax: below 1 makes outputs more confident and conservative; above 1 increases randomness and creativity but may reduce coherence. - Top-K sampling restricts choices to the K most probable tokens. Small K yields more predictable, coherent text; large K or None allows more diverse outputs. The chapter’s sample() uses temperature=1 and no top-K; generate() adds temperature and top_k controls.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn Generative AI with PyTorch ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn Generative AI with PyTorch ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn Generative AI with PyTorch ebook for free