liveBook · Manning

Chapter 16: Text generation

What you will learn in chapter 16 of Deep Learning with Python, Third Edition

The chapter introduces generative AI as a way to produce content from learned patterns while emphasizing human creative direction and practical uses beyond art.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The chapter introduces generative AI as a way to produce content from learned patterns while emphasizing human creative direction and practical uses beyond art.

Key terms: statistical structure, statistical latent spaces, sampling, algorithmic generation, augmented intelligence, latent space sampling, pattern recognition, rote tasks

16.1 A brief history of sequence generation

This section traces sequence generation from early recurrent-network work to GPT, explaining how general pretraining and increasing scale led to stronger text generation and prompting, while noting persistent limitations.

Key terms: LSTM, recurrent networks, sequence data generation, GPT, Generative Pretrained Transformer, unsupervised pretraining, fine-tuned, next token, GPT-1, GPT-2

16.2 Training a mini-GPT

This section prepares a manageable portion of the C4 corpus for mini-GPT pretraining by tokenizing documents and building an efficient pipeline of training and validation batches.

Key terms: Colossal Clean Crawled Corpus, C4, tokens, SentencePiece, subword tokenization, integer tokens, detokenize(), tf.data, sequences of length 256, document boundaries

16.2.1 Building the model

This section builds a small decoder-only GPT model and explains the architectural choices behind its text generation setup.

Key terms: decoder-only, encoder, left to right, attention, single sequence, latent space, pretraining, bidirectional, cross-attention, dropout

16.2.2 Pretraining the model

Explains how learning-rate warmup stabilizes mini-GPT pretraining, why its output is treated as logits, and what its training results indicate.

Key terms: exploding gradients, warmup steps, LearningRateSchedule, logit, softmax, SparseCategoricalCrossentropy(from_logits=True), validation loss, validation set, undertrained, training steps

16.2.3 Generative decoding

This section explains how mini-GPT generates text one token at a time and why compilation, fixed input shapes, and key-value caching make generation faster.

Key terms: prompt, probability distribution, next token, predict(), compilation, input shape, padding, recompilation, cached generation, key and value vectors

16.2.4 Sampling strategies

This section explains how sampling choices shape mini-GPT’s generated text, from repetitive greedy output to more varied but sometimes incoherent alternatives.

Key terms: greedy search, most likely next token, probability distribution, categorical distribution, temperature, logits, softmax, top-K sampling, K candidates, mini-GPT

16.3 Using a pretrained LLM

This section explains why pretrained LLMs are widely reused instead of trained from scratch, then places the book’s chosen Gemma model in scale relative to the earlier mini-GPT.

Key terms: pretraining, Transformer, pretrained models, Gemma, parameters, tokens, mini-GPT

16.3.1 Text generation with the Gemma model

This section uses KerasHub to generate text with pretrained Gemma and explains why its fluent output can still be unhelpful, unpredictable, or false.

Key terms: KerasHub, CausalLM, tokenizer, generate(), sampling strategies, pretraining objective, guess the next word, mini-GPT, autocomplete, prompt

16.3.2 Instruction fine-tuning

The section explains how instruction-response examples fine-tune a pretrained language model and how preprocessing limits training loss to the response.

Key terms: instruction fine-tuning, input/output pairs, [instruction], [response], guess the next word, pretraining, latent space, CausalLM, preprocessor layer, backbone model

16.3.3 Low-Rank Adaptation (LoRA)

The section explains why full LLM fine-tuning exhausts GPU memory, how LoRA reduces trainable parameters, and what instruction-tuning the adapted Gemma model does and does not achieve.

Key terms: Adam optimizer, gradients, optimizer state, frozen parameters, LoRA, kernel matrix, low rank, alpha, beta, inner rank

16.4 Going further with LLMs

Introduces upcoming extensions and improvements to basic language modeling without explaining them yet.

16.4.1 Reinforcement Learning with Human Feedback (RLHF)

The section explains how RLHF uses human response rankings to improve an instruction-tuned language model, then illustrates a chatbot trained with preference tuning and a memory-saving choice for loading it.

Key terms: supervised fine-tuning, human preference, RLHF, ranked preference dataset, reward model, prompt-response pair, action, reward, reward cutoff, iterative preference tuning

16.4.2 Multimodal LLMs

The section explains how Gemma incorporates images into a text-generating Transformer and places multimodal LLMs within the broader category of foundation models.

Key terms: Transformer, modalities, sequence representation, image encoder, patches, soft tokens, hard tokens, <start_of_image>, token embedding layer, pretraining

16.4.3 Retrieval Augmented Generation (RAG)

This section explains how retrieval-augmented generation adds retrieved information to an LLM’s prompt, why that helps, and how a vector database can find relevant text.

Key terms: cutoff date, private data, hallucinations, factually ground, retrieval-augmented generation, RAG, query, text context, prompt, vector database

16.4.4 “Reasoning” models

This section explains how writing intermediate steps can improve LLM answers and how verifiable answers can be used to train that behavior.

Key terms: chain-of-thought prompting, showing your work, intermediate steps, chain-of-thought fine-tuning, supervised examples, string parsing, supervised fine-tuning, reinforcement learning, environment, actions

16.5 Where are LLMs heading next?

The section explains why LLM progress is likely to involve more than larger models, as compute budgets, deployment costs, data scarcity, and learning efficiency shape what comes next.

Key terms: pretraining, parameters, compute, flops, tokens, deploying, model parameter counts, pretraining data, human-written content, reinforcement learning

16.6 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 15: Language models and the Transformer Chapter 17: Image generation →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.