liveBook · Manning

Chapter 3: Coding attention mechanisms

What you will learn in chapter 3 of Build a Large Language Model (From Scratch)

The introduction connects prepared text embeddings to attention as an integral part of the LLM architecture.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The introduction connects prepared text embeddings to attention as an integral part of the LLM architecture.

Key terms: tokens, embeddings, attention mechanisms, LLM architecture

3.1 The problem with modeling long sequences

This section uses machine translation to explain how encoder–decoder RNNs process text and why their limited access to earlier input context motivated attention mechanisms.

Key terms: source language, target language, grammatical structures, encoder, decoder, RNN, hidden state, final hidden state, earlier hidden states, decoding phase

3.2 Capturing data dependencies with attention mechanisms

The section explains how attention addresses an RNN encoder–decoder limitation and introduces self-attention as a key mechanism in transformer-based LLMs.

Key terms: RNN, encoder–decoder RNN, single hidden state, Bahdanau attention mechanism, decoder, self-attention, input sequence, transformer architecture, GPT series

3.3 Attending to different parts of the input with self-attention

This section defines the “self” in self-attention by contrasting relationships within one input sequence with attention between two sequences.

Key terms: self-attention, attention weights, input sequence, traditional attention mechanisms

3.3.1 A simple self-attention mechanism without trainable weights

This section builds a context vector for one token using a simplified self-attention procedure without trainable weights.

Key terms: context vector, enriched embedding vector, input sequence, query, attention scores, dot product, normalization, attention weights, softmax, softmax_naive

3.3.2 Computing attention weights for all input tokens

This subsection extends simple self-attention from one input to all inputs by computing pairwise scores, normalizing them into attention weights, and producing a context vector for each input.

Key terms: attention scores, tensor, matrix multiplication, attention weights, torch.softmax, dim=-1, attn_scores, context vectors, context_vec_2

3.4 Implementing self-attention with trainable weights

The section introduces trainable self-attention as an extension of basic self-attention that learns to produce better context vectors.

Key terms: self-attention, context vectors, weighted sums, trainable weight matrices, scaled dot-product attention

3.4.1 Computing the attention weights step by step

This section computes one context vector using learned query, key, and value projections, scaled attention scores, and a weighted sum of values.

Key terms: Wq, Wk, Wv, query, key, value, weight parameters, attention weights, attention scores, softmax

3.4.2 Implementing a compact self-attention Python class

This section packages self-attention in a PyTorch class and compares two implementations of its trainable projections.

Key terms: SelfAttention_v1, nn.Module, W_query, W_key, W_value, attn_scores, SelfAttention_v2, nn.Linear, nn.Parameter, weight initialization

3.5 Hiding future words with causal attention

Introduces causal attention as self-attention that prevents a token from attending to future tokens, and describes the masking and normalization that enforce this restriction.

Key terms: causal attention, masked attention, standard self-attention, attention weights, mask out, above the diagonal, normalize

3.5.1 Applying a causal attention mask

This section shows two ways to mask future-token attention weights: zeroing and renormalizing weights, or masking scores before softmax.

Key terms: causal attention mask, softmax, tril, renormalize, information leakage, masked positions, renormalization, negative infinity, attention scores

3.5.2 Masking additional attention weights with dropout

The section explains why dropout is used in attention and how it randomly zeros and rescales attention weights during training.

Key terms: dropout, overfitting, training, attention weights, dropout mask, dropout rate, value vectors

3.5.3 Implementing a compact causal attention class

This section presents a batched causal-attention class that adds masking and dropout to the earlier self-attention class and registers a buffer for device compatibility.

Key terms: CausalAttention, SelfAttention, dropout, causal mask, batch inputs, three-dimensional tensor, context vector, embedding, register_buffer, buffer

3.6 Extending single-head attention to multi-head attention

This section defines multi-head attention as an extension of causal attention with multiple independently operating heads.

Key terms: multi-head attention, heads, single-head attention, causal attention module, attention weights

3.6.1 Stacking multiple single-head attention layers

This section builds multi-head attention by stacking independently weighted CausalAttention heads and explains the wrapper’s output shape and sequential execution.

Key terms: multi-head attention, single-head attention, learned linear projections, weights, num_heads, d_out, context_vecs, context vector, MultiHeadAttentionWrapper, forward method

3.6.2 Implementing multi-head attention with weight splits

This section implements multi-head attention in one class by splitting projected tensors into heads, computing attention across those heads, and recombining their outputs.

Key terms: MultiHeadAttention, num_heads, head_dim, .view, .transpose, batched matrix multiplication, context vectors, d_out, MultiHeadAttentionWrapper, queries

3.7 Summary

This section summarizes how self-attention builds context vectors and how causal masking and multi-head attention adapt it for transformer-based LLMs.

Where this is used later

Concepts explained in this chapter

← Chapter 2: Working with text data Chapter 4: Implementing a GPT model from scratch to generate text →

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.