liveBook · Manning

Chapter 9: How transformers work

What you will learn in chapter 9 of Deep Learning with PyTorch, Second Edition

The introduction contrasts generative modeling with earlier prediction tasks and uses ELIZA to show why realistic text generation requires more than fixed response rules.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The introduction contrasts generative modeling with earlier prediction tasks and uses ELIZA to show why realistic text generation requires more than fixed response rules.

Key terms: generation, latent structure, implicit rules, probabilistic model, ELIZA, pattern matching, rule-based statements, conversational context

9.1 A motivating example: Generating names character by character

The section introduces character-by-character name generation, shows how to represent names as token sequences, and explains why random letter selection is a poor starting point.

Key terms: vocabulary, token, sequence, $, uniform distribution, probability, generative language models

9.2 Self-supervised learning

The section builds a character-pair model for generating names and uses it to introduce learning from unlabeled data.

Key terms: statistical generation, probability distributions, text sequences, bigram model, character pairs, bigram matrix, sample, realistic, supervised learning, self-supervised learning

9.2.1 Limits of the bigram model

The section shows why counting character-sequence probabilities becomes impractical as vocabulary or context grows, and presents neural networks as a way to generalize beyond those counts.

Key terms: bigram model, character pairs, data sparsity, vocabulary, longer-range dependencies, probability of the next character, dense, continuous representations, generalize to unseen patterns, fixed parameter count

9.3 Generating our training data

The section turns names into next-character training examples, then pads and batches those examples for model training.

Key terms: input-target pairs, encode, decode, input sequence, target sequence, pad, input sequences, target sequences, batch size, loss function

9.4 Embeddings and linear layers

This section builds a character-level name generator from trainable embeddings and a linear layer, then explains how its training examples, loss, and autoregressive sampling work.

Key terms: text embeddings, nn.Embedding, vocabulary size, trainable lookup table, backpropagation, subsequence, embeddings, flatten, linear layer, next character

9.4.1 Visualizing embeddings

This section uses a 3D visualization to show how training gives character embeddings a structure that reflects relationships among characters.

Key terms: embedding, tensor of size 3, 3D space, embeddings, vowels, consonants, special character $

9.5 Attention

This section explains why static character embeddings need context-sensitive attention and introduces query, key, and value as the way attention selects relevant information.

Key terms: embeddings, attention mechanism, context, query, key, value

9.5.1 Dot product self-attention

This section explains how self-attention combines information across sequence positions and how query–key dot products produce the weights for that combination.

Key terms: self-attention, value vectors, attention weights, weighted sum, query vectors, key vectors, dot product, softmax, matrix multiplication

9.5.2 Scaled dot product causal self-attention

The section extends dot-product attention with batching, causal masking, and scaling, then applies it to character generation and interprets the resulting attention weights.

Key terms: batching, causal masking, scaling, autoregressive models, embedding layer, attention mechanism, linear layers, flattening, attention weights, attention score

9.6 Transformers

Introduces attention as the core of transformers, outlines the original encoder–decoder architecture, and explains the prominence of decoder-only models.

Key terms: Transformer architecture, attention mechanism, encoder, decoder, input sequence, representations, output sequence, decoder-only transformers, large language models, text generation

9.6.1 The decoder

This section builds a GPT-style decoder from transformer blocks, explains the components added to the earlier attention-MLP block, and reports how the resulting name generator performs.

Key terms: decoder-only transformers, input embeddings, positional encoding, transformer blocks, linear layer, residual connections, skip connections, vanishing gradients, multiheaded attention, attention heads

9.7 Other Transformer architectures

9.7.1 The encoder

This section distinguishes the transformer encoder from the decoder and describes what its output is used for.

Key terms: transformer encoder, causal masking, fixed-size vector representation, text classification, sentiment analysis, spam detection, topic classification, BERT, pretrained

9.7.2 The encoder-decoder

This section explains how an encoder and decoder form a transformer that generates an output sequence from an input sequence.

Key terms: encoder, decoder, input sequence, output sequence, representations, encoder output, keys, values, decoder-encoder attention, machine translation

9.8 Tokenization

The section explains why text models use tokenizers and why practical tokenizers often use words or subwords rather than individual characters.

Key terms: tokenizer, raw text, tokens, words, subwords, characters

9.8.1 Generating sentences

The section reuses a token-based decoder to generate sentences and adjusts how its token output is displayed.

Key terms: tokens, decoder, model architecture, generate_samples, format_sequence, tokenizer

9.9 The Vision Transformer

This section explains how a Vision Transformer treats image patches as tokens, uses an encoder to process them, and uses the resulting representations for vision tasks.

Key terms: Vision Transformer, patches, tokens, positional embeddings, transformer encoder blocks, [CLS] token, self-attention, classification, Transformer architecture, attention

9.10 Conclusion

The conclusion summarizes the capabilities demonstrated in the chapter and urges a careful understanding of what transformers can and cannot be said to do.

Key terms: Transformer architecture, natural language generation, content understanding, appear to think autonomously, mechanics

9.11 Exercises

9.12 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 8: Using convolutions to generalize Chapter 10: Diffusion models for images →

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.