Overview

16 Text generation

This chapter surveys how generative modeling moved from niche curiosity to everyday tool and argues for AI as augmented intelligence in creative and practical workflows. It traces sequence generation from early LSTMs and Graves’ handwriting systems to the Transformer era, highlighting how OpenAI’s GPT series showed that large-scale next-token pretraining plus compute can unlock strong zero- and few-shot behaviors—alongside persistent issues like hallucinations, prompt sensitivity, and limited out‑of‑distribution robustness. With that context, the chapter positions large language models as foundation models trained to learn statistical structure and sample from latent spaces, reshaping how text (and beyond) can be produced and steered.

Readers then build a mini GPT from scratch: preparing web text (C4 subset) with subword tokenization, assembling a decoder-only Transformer with causal attention, positional embeddings with tied input/output projections, and stability measures such as warmup schedules and mixed precision. The chapter demonstrates generative decoding pitfalls and remedies (compiled inference, KV caching) and explores sampling strategies—greedy, temperature, Top‑K, and beam—to balance fluency and diversity. Because small models remain limited, it transitions to using a billion‑parameter pretrained Gemma model, showing prompting behaviors, instruction fine‑tuning to align outputs, and Low‑Rank Adaptation (LoRA) to drastically reduce trainable memory for practical fine‑tuning on commodity GPUs.

Finally, it broadens to methods that make LLMs more useful and reliable: Reinforcement Learning with Human Feedback (RLHF) to align models with preferences; instruction‑tuned checkpoints for chat; multimodal extensions that splice learned “soft” image tokens into text sequences; and Retrieval‑Augmented Generation (RAG) to ground answers in up‑to‑date or private sources. It explores emerging “reasoning” workflows (chain‑of‑thought prompting and self‑training on verifiable tasks like math and code), and discusses scaling trends, costs, energy and data constraints, and the shift toward foundation models adapted to downstream tasks. The chapter closes with a realistic outlook: today’s recipe—large‑scale self‑supervision, targeted fine‑tuning, and tool‑augmented prompting—yields powerful systems, yet open challenges in reliability, efficiency, and controllability remain central to the field’s next steps.

An image generated with the generative image software Midjourney. The prompt was A hand-drawn, sci-fi landscape of residents living in a building shaped like a red letter K.
keras midjourney image
Warmup makes our updates to model parameters smaller at the beginning of training, and can help with stability.
learning rate warmup
Greedy, Top-K and Random sampling strategies shown on the same probability distribution.
sampling strategies
The low-rank kernel decomposition contains far fewer parameters than the kernel itself.
lora layer
LoRA greatly reduces the memory we need for gradients and optimizer states.
lora memory
Handling image input by splicing text tokens and “soft” image tokens together.
multimodal transformer
A test image for the Gemma model. HTML: class=“small-image”
gemma test image
LLM parameter counts (left) and pretraining dataset sizes (right) over time. Note that many recent proprietary LLMs (e.g. GPT-4, Gemini), are not included because model details have not been disclosed.
llm sizes

Chapter summary

  • Large Language Models, or LLMs are the combination of a few key ingredients:
    • The Transformer architecture.
    • A language modeling task (predicting the next token based on past tokens).
    • A large amount of unlabeled text data.
  • An LLM learns a probability distribution for predicting individual tokens. This can be combined with a sampling strategy to generate a long string of text. There are many popular ways to sample text:
    • Greedy search takes the most likely predicted token at each generation step.
    • Random sampling directly samples the predicted categorical distribution over all tokens.
    • Top-K sampling restricts the categorical distribution to the top set of K candidates.
  • LLMs use billions of parameters and are trained on trillions of words of text.
  • LLM output is unreliable, and all LLMs will occasionally hallucinate factually incorrect information.
  • LLMs can be fine-tuned to follow instructions in a chat dialog. This type of fine-tuning is called instruction fine-tuning.
    • The simplest form of instruction fine-tuning involves directly training the model on instruction and response pairs.
    • More advanced forms of instruction fine-tuning involve reinforcement learning.
  • The most common resource bottleneck when working with LLMs is accelerator memory.
    • LoRA is a technique to reduce memory usage by freezing most Transformer parameters and only updating a low-rank decomposition of attention projection weights.
  • LLMs can input or output data from different modalities if you can figure out how to frame these inputs or outputs as sequences in a sequence prediction problem.
    • A foundation model is a general term for models, of any modality, trained using self-supervision for a wide range of downstream tasks.

FAQ

What is the core idea behind GPT-style text generation and how does a decoder-only Transformer work?GPT-style models are trained with a next-token prediction objective on a single, left-to-right sequence. They use a decoder-only Transformer with causal self-attention, so each position can only attend to previous tokens. Inputs and outputs (for tasks like Q&A) are concatenated into one sequence; there’s no separate encoder. This simplifies pretraining at web scale but removes bidirectional context during encoding.
How was the mini-GPT in the chapter built and trained?It uses a small GPT architecture (about 41M params): 8 decoder blocks, hidden_dim=512, 8 heads, intermediate_dim=2056, dropout, and tied input/output embeddings. Data comes from a small subset of C4, tokenized with SentencePiece (32k vocab) and an <|endoftext|> boundary token. Sequences are length 256 with batch size 128 (nearly 1B tokens total). Training uses Adam, a warmup learning-rate schedule, and mixed precision.
Why is training large Transformers finicky, and how is it stabilized here?- Deep stacks can suffer exploding gradients and optimization instability.
- Stabilizers used: linear LR warmup (to 2e-4 over ~1k steps), Adam optimizer, dropout inside each decoder block, layer normalization, and mixed precision for speed/efficiency. These help the loss converge and keep training numerically stable.
Why can generation be slow, and how can you speed it up?- Directly calling the model each token runs uncompiled graphs and is slow.
- Speedups:
1) Use model.predict (compiled) with fixed-length padding to avoid re-compilation at each step.
2) Cache attention key/value tensors so you only compute the new token instead of the whole sequence each step (dramatic speedups for long outputs).
What sampling strategies improve the diversity and coherence of generated text?- Greedy: pick the argmax token; high coherence, prone to repetition.
- Random sampling: sample from the softmax; diverse but can be incoherent.
- Temperature: scale logits before softmax (low=conservative, high=diverse).
- Top-K: sample only among the K most likely tokens (often combined with temperature).
- Beam search: explore multiple candidate continuations heuristically.
Why do pretrained LLMs hallucinate, and what helps?Pretrained LLMs are “autocomplete for the internet”: they optimize likelihood, not truth. They may confidently produce false continuations, are sensitive to prompt phrasing, and have a knowledge cutoff. Mitigations include better prompting, instruction fine-tuning to shape behavior, retrieval-augmented generation (RAG) to ground answers in retrieved text, and preference-based tuning (e.g., RLHF) to bias toward helpful/faithful responses.
What is instruction fine-tuning and how did the chapter make it fit on a single GPU?Instruction fine-tuning feeds prompt/response pairs (with simple markers like [instruction]/[response]) as a single sequence using the standard next-token loss, nudging the model to follow directions. To fit memory budgets, the chapter uses LoRA: freeze the backbone and add small low-rank adapters (rank=8) to key/query projections. This cuts trainable params to ~1.3M (megabytes of optimizer state), making fine-tuning feasible on modest GPUs.
What is RLHF and how does it improve chatbots beyond supervised fine-tuning?RLHF (Reinforcement Learning with Human Feedback) trains a reward model from human preference rankings of responses, then optimizes the LLM to generate outputs that score higher under that reward. It iterates: generate responses, score them with the reward model, and update the LLM. This pushes models toward helpful, safe, and preference-aligned behavior beyond what handwritten targets alone can achieve.
How do multimodal LLMs accept images and answer questions about them?A vision encoder turns an image into a sequence of “soft tokens” (e.g., 256 vectors). These are spliced into the text token sequence after embedding, often indicated by a special token like <start_of_image>. The Transformer then attends across text and image tokens jointly. During training, losses are computed on text tokens (image tokens are inputs only). This enables image captioning and VQA with the same causal LM backbone.
What is Retrieval-Augmented Generation (RAG) and when should you use it?RAG augments the prompt with retrieved context (from a search engine or vector database of embedded documents). Steps: embed the user query, retrieve nearest documents by vector similarity, and “stuff” the relevant text into the prompt. Use it to: 1) avoid knowledge cutoff, 2) access private/enterprise data, and 3) reduce hallucinations by grounding answers in provided context.

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
  • Deep Learning with Python, Third Edition 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
  • Deep Learning with Python, Third Edition 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
  • Deep Learning with Python, Third Edition ebook for free