Overview

12 Training A Transformer to Generate Text

This chapter walks through building and training a GPT-style Transformer from scratch in PyTorch, focusing on a practical, lightweight model inspired by GPT-2 that can be trained on a regular GPU. Beyond showing how to generate text, it explains why training (or fine-tuning) your own model matters: tailoring behavior to a domain, improving relevance, and retaining control over data and privacy. The workflow spans designing a scaled-down architecture, preparing data, training with appropriate safeguards against overfitting, and deploying the model for autoregressive text generation.

The model mirrors GPT-2’s decoder-only design but is deliberately small: about 5.12 million parameters with 3 decoder blocks, 256-dimensional embeddings, 4 attention heads, learned positional embeddings, GELU activations, layer normalization, residual connections, and dropout. Training data is curated from three Ernest Hemingway novels to balance stylistic coverage and computational cost. The text is cleaned (including quote normalization), lowercased, and tokenized at the word level with punctuation separated, yielding a vocabulary of roughly 10,600 tokens plus an UNK token for robustness. Text is converted to integer sequences, batched into 128-token contexts, and trained via next-token prediction by shifting targets one step to the right.

Training uses Adam with cross-entropy loss, gradient norm clipping, checkpointing every 10 epochs up to 40, and GPU acceleration where available. After training, text is generated autoregressively from a prompt using temperature and optional top-k sampling. Results illustrate the trade-off between coherence and memorization: the 20-epoch model produces mostly coherent output with fewer verbatim passages, while the 40-epoch model is more fluent but more likely to copy training text, especially under unconditional prompts. The chapter emphasizes selecting suitable training length or using validation to curb overfitting, and it equips readers with an end-to-end recipe—from data choice and tokenization to architecture, training, and controlled text generation.

The architecture of a decoder-only Transformer, designed to generate text. The text from three Hemingway novels is tokenized and then converted into indexes. We arrange 128 indexes into a sequence, and each batch contains 32 such sequences. The input first undergoes word embedding and positional encoding, with the input embedding being the sum of these two components. This input embedding is then processed through three decoder layers. Following this, the output undergoes layer normalization and passes through a linear layer, resulting in an output size of 10,600, which corresponds to the number of unique tokens in the vocabulary.
The training process for a decoder-only Transformer to generate text, Hemingway-style.

Summary

  • The style of the generated text from a GPT model will be heavily influenced by the training data. For effective text generation, it's important to have a balance of text length and variation in the training material. The training dataset should be sufficiently large for the model to learn and emulate a specific writing style accurately. However, if the dataset lacks diversity, the model might end up reproducing passages directly from the training text. Conversely, overly long training datasets can require excessive computational resources for training.
  • Choosing the right hyperparameters in the GPT model is crucial for successful model training and text generation. Setting the hyperparameters too large may lead to too many parameters. This results in longer training time and an overfitted model. Setting the hyperparameters too small may hinder the model’s ability to learn effectively and capture the writing style in the training data. This may lead to incoherent generated text.
  • The appropriate number of training epochs is important for text generation. While training too few epochs may lead to incoherent text, training for too many epochs may lead to an overfitted model that generates text identical to passages in the training text.

FAQ

Why do we build a scaled-down GPT instead of training GPT-2XL?A full GPT-2XL has about 1.558 billion parameters and requires supercomputing resources and massive data. This chapter builds a smaller GPT (~5.12 million parameters) with 3 decoder blocks, 256-d embeddings, 4 heads, and sequence length 128, which can be trained on a regular GPU in a few hours.
How is the training text prepared and tokenized?The text from three Hemingway novels is cleaned (remove non-book content, normalize quotes), lowercased, line breaks replaced with spaces, and spaces are inserted around punctuation. Word-level tokenization is used, a vocabulary is built from tokens, and an “UNK” token is added for out-of-vocabulary words, yielding a vocab size of 10,600.
Why use word-level tokenization and add an UNK token?Word-level tokenization is simple to implement and (in this setup) keeps the number of unique tokens manageable, reducing model size. Adding “UNK” prevents crashes when prompts contain unseen words by mapping unknown tokens to a valid index.
What input and target sequences are used for training?Inputs are sequences of 128 token indices. Targets are the same sequences shifted one token to the right. This trains the model to predict the next token given the current and all previous tokens.
What does the model architecture look like?It’s a decoder-only Transformer: learned word and positional embeddings (both 256-d), 3 decoder blocks with causal self-attention (4 heads) and a GELU feed-forward network (4× hidden expansion), layer norms and residuals, followed by a linear head to 10,600 logits (one per token).
How is causal self-attention implemented?The model projects inputs to Q, K, V, splits them into 4 heads, applies a causal mask (lower-triangular) to prevent attending to future positions, uses softmax attention with dropout, concatenates heads, and applies a projection with residual/dropout.
How is the model trained (optimizer, loss, and stability)?The model is trained with Adam (lr=1e-4) using cross-entropy loss over vocabulary logits versus shifted targets. Gradient norm clipping (to 1) is applied to prevent exploding gradients. Training runs for 40 epochs, saving weights every 10 epochs.
How does text generation work in this chapter?Given a prompt, the model autoregressively predicts the next token, appends it, and repeats for a fixed number of new tokens. Temperature and top-k sampling control diversity. A sample() function loads selected weights and returns only newly generated indices; generate() handles prompt preprocessing/postprocessing.
How do we balance coherence and the risk of copying training text?More training (e.g., 40 epochs) tends to produce more coherent text but increases the chance of copying passages. Fewer epochs (e.g., 20) reduce copying risk but may yield occasional grammatical errors. Using multiple novels, unique prompts, validation-based early stopping, and sampling controls (temperature/top-k) also help.
What compute is required and how long does training take?The model is small enough to train on a CUDA-enabled GPU; training typically takes a couple of hours. The code moves tensors and positional indices to the GPU when available, and saved checkpoints (every 10 epochs) allow testing different training durations.

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