Skip to content

Chapter 3 — Coding Attention Mechanisms

Status: Chapter 3 reading is complete through Section 3.6.2, Exercises 3.1–3.3, and the chapter summary. The next reading step is Chapter 4: assembling the GPT architecture.

Chapter 2 prepared the inputs: text became token IDs, training windows, and vectors carrying token and position information. Now we move into the model architecture itself and study attention: how a token's representation gathers information from other accessible positions.

These notes follow Sebastian Raschka's Build a Large Language Model (From Scratch). The author's Chapter 3 code accompanies the implementation.

Section names and numbering follow Manning’s published contents. Numbered headings are book sections; unnumbered headings contain our companion notes. Unwritten sections are placeholders, not completed reading.

Where we are in the book's roadmap

We are at step 2, “Attention mechanism,” within Stage 1 of the author's roadmap. This is not Stage 2, which concerns pretraining and the foundation model. Data preparation gave us the inputs; attention is the next architectural component to unpack.

The author's roadmap from data preparation and attention to a foundation model and fine-tuning. Chapter 3 focuses on step 2, Attention mechanism, in Stage 1.

Sebastian Raschka's book roadmap, embedded from his website. We are focusing on step 2, “Attention mechanism.” Open the image for a full-size view.

Four implementations, one gradual progression

The chapter introduces four variations. We will follow the progression rather than unpacking the most advanced version immediately.

Simplified self-attention leads to trainable projections, then causal masking, then multiple attention heads.

Original companion figure explaining the same progression as Figure 3.2 in Sebastian Raschka's book, using our own layout and wording. These are cumulative teaching steps, not mutually exclusive categories: the final GPT-style multi-head attention also has trainable weights and a causal mask.

A head is one attention calculation; multiple heads perform several such calculations in parallel and combine their outputs. Heads are not successive transformer blocks. That is enough terminology for the introduction—we will work through the details in section 3.6.

Our preparation already touched queries, keys, values, and causal masking. The book now gives us an ordered path to implement them. Sections 3.1 and 3.2 first motivate attention before the simplified calculation in 3.3.

3.1 The problem with modeling long sequences

Starting with the problem makes the architecture easier to motivate. Translation cannot generally be handled by replacing each source word with its dictionary equivalent and keeping the same order. The target sentence needs the appropriate meaning and grammar, and the relevant source information may occur earlier or later than the word currently being generated.

Translation is not a row of independent substitutions

Consider our own German-to-English example:

German:                    Ich habe das Buch gelesen.
Literal, source-order:     I have the book read.
Natural English:           I have read the book.

The final German word, gelesen, contributes read, which appears before the book in the English translation. This short example isolates reordering; longer sentences also require resolving meaning and relationships across much greater distances. Not every translation needs reordering, but a general translation system must support it.

Word substitution preserves the German order and produces I have the book read; aligning the same words in English order produces I have read the book.

Original companion illustration inspired by the problem in the book's Figure 3.3, using a different sentence and our own layout. Arrows show illustrative word correspondences, not measured attention scores. Words are used for readability; actual models operate on tokens.

Having access to a later word in the source sentence is not the same as peeking at a future target answer. A translation encoder can read the complete source before decoding begins, while the decoder generates the target from its available prefix. This connects to the encoder–decoder distinction in Chapter 1.

The basic recurrent encoder–decoder

Before Transformers, recurrent neural networks (RNNs) were used for neural translation. In the basic design discussed here, an encoder processes the source sequence and a decoder generates the target sequence. These are roles in the model, not the tokenizer's encode and decode methods.

The encoder reads one token representation at a time and updates its hidden state: a vector of computed values carrying information from the sequence processed so far. The state is an activation, not a new set of learned weights. The same recurrent computation and learned weights are reused at each step.

Current token vector + previous encoder state → updated encoder state

After the final source token, the last encoder state supplies the source summary used to initialize the decoder in this schematic. The decoder then updates its own state and predicts target tokens one at a time, using the previous target token as input (a start marker is used first).

The encoder updates hidden states h1 through h5; only h5 initializes the decoder, which updates states s1 through s5 and generates the translated tokens.

Original companion illustration of the basic recurrent encoder–decoder bottleneck discussed in Figure 3.4. Encoder and decoder boxes represent steps through time, not separate layers with independent weights. This simplified design has no attention; outputs are illustrative, not measured results. Recurrent variants can carry additional state, such as an LSTM's cell state.

Why a fixed-size summary becomes a bottleneck

My initial interpretation was that we are trying to keep the whole context in a very small thing. More precisely, the state has a fixed width while the input can keep getting longer. It might contain hundreds or thousands of numbers; the issue is that more source information must be carried through the same-sized representation.

For illustration, a 256-coordinate encoder state still has 256 coordinates after reading either 5 or 100 tokens. Each update must preserve information that will be useful later. Earlier details can become difficult to retain and recover, particularly when the translation depends on distant parts of a long sentence. This is a learned compression bottleneck, not a literal rule that each coordinate stores one word or that a particular length always fails.

In this basic model without attention, the decoder has no direct route back to individual earlier encoder states. It does not repeatedly read an unchanging decoder state: its own state evolves as it generates. But the source information available through that state must have survived the encoder's final summary and subsequent decoder updates.

This limitation is not true of every RNN. Attention was introduced into recurrent encoder–decoder systems before the Transformer: the Bahdanau, Cho, and Bengio paper motivates attention as a way to consult relevant source representations instead of relying exclusively on one fixed-length source summary.

That gives us the question for attention: when producing a particular output token, could the decoder consult the source positions it needs? Section 3.2 develops that idea. We do not need to implement an RNN first to follow the motivation.

3.2 Capturing data dependencies with attention mechanisms

The fixed-summary encoder–decoder can work well on short sequences, but retaining and recovering relevant details becomes harder as sequences grow. This is not a sharp length cutoff or a statement that every RNN fails on long text. The limitation here is the basic decoder's lack of direct access to the earlier source representations.

Attention adds that access. The encoder still builds representations for the source positions, but the decoder can consult them again while producing each target token. It does not need every source detail to survive exclusively in the final encoder state.

Consult different source positions at each output step

Return to our example, Ich habe das Buch gelesen → I have read the book. Suppose the generated target prefix is I have, and we are about to generate read.

The decoder can compute mixing amounts over the source representations, combine those representations into a context vector, and use that vector to help produce the next output. In our illustration, the representation associated with gelesen receives the largest weight. These numbers are invented to explain the mechanism, not extracted from a model.

All five encoder states contribute to a weighted context vector used to generate read after I have; the illustrative weight for gelesen is largest.

Original companion illustration inspired by Figure 3.5, extending our previous recurrent encoder–decoder drawing. Thicker arrows indicate larger illustrative mixing weights. The decoder computes a new mixture at each output step. This is a conceptual sketch, not the exact Bahdanau implementation; start/end markers, token feedback wiring, and some internal operations are omitted.

The context vector still has a fixed width. The improvement is that its contents can be recomputed from all available encoder states for each output step, rather than requiring one source summary to serve every prediction. The model retains multiple source representations, so this extra access also requires storage and computation.

“Access to words” is shorthand: the attention calculation works with their encoder representations, not raw text or a dictionary. Each encoder representation can already contain contextual information. The mixture is usually soft: several positions can contribute, rather than the model selecting exactly one word.

The mixing weights depend on the current computation. They are not permanent importance scores attached to source words, and a large weight is not a complete explanation of why a model chose an output. We will calculate attention weights explicitly in the following sections.

From recurrent attention to the Transformer

The Bahdanau, Cho, and Bengio paper was first posted in 2014 and presented at ICLR 2015. It introduced an influential attention-based neural translation approach that lets a recurrent decoder use relevant source representations. This is the historical example here, not a claim that every idea called attention originated in that paper.

In 2017, Attention Is All You Need introduced the Transformer, showing that strong translation models could be built without recurrent layers. Attention handled interactions between positions alongside feedforward layers and other components. “Without recurrence” does not mean “without sequence order”: positional information and causal masking still matter.

The progression is:

Basic recurrent encoder–decoder
    → one final source summary

Recurrent encoder–decoder with attention
    → consult source representations for each output step

Transformer
    → use attention-based blocks without recurrent layers

The translation example has a decoder attending to an encoder's representations. That is attention between two sequences. The self-attention calculation we implement next mixes positions within one sequence. The shared idea is a context-dependent weighted combination; the architectures and exact calculations differ.

What self-attention adds

Self-attention builds context-aware representations by letting each position in a sequence weigh and combine information from positions in that same sequence. Without a mask, all positions can interact; with a causal mask, each position can use only itself and earlier positions.

Here, “better representations” means that a token's vector can reflect its surrounding context. It does not mean that attention necessarily takes less computation.

Before calculating attention, locate it in the complete model. Chapter 2 prepared input vectors from text. This chapter develops the attention mechanism that mixes information between positions. Chapter 4 assembles the full GPT-like architecture around it.

Text becomes input vectors, then enters a GPT-like transformer with self-attention and other components; vocabulary scores lead to token selection and decoded text.

Original companion illustration inspired by Figure 3.6 in Sebastian Raschka's book, using our own layout and example. This is a learning map, not an exact execution graph: normalization, residual connections, and feedforward operations surround attention within each block. The input phrase is illustrative; no tokenization or prediction result is claimed.

Attention receives vectors and produces vectors. It does not directly produce words or token IDs. The complete model eventually projects its representations into vocabulary scores; selecting token IDs and decoding them gives us generated text.

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

The self in self-attention

Self means that the positions being related belong to the same sequence. It does not mean a token attends only to itself. A token can incorporate information from other positions as well as its own.

In the translation example from section 3.2, a decoder attends to representations from a separate encoder sequence. That is cross-attention. Both are attention mechanisms; the distinction is where their inputs come from. Image models can likewise use self-attention between representations of image patches.

3.3.1 A simple self-attention mechanism without trainable weights

The goal is to turn each input vector into a context vector: a representation that incorporates information from the other available positions, including the position itself. Calling it an “enriched embedding” is a useful intuition. In this simplified calculation, it is a weighted combination of the input vectors, not an extra row permanently written into the token embedding table.

First, what are we trying to do?

We already have a sequence of input vectors. Choose one position and ask:

What information from this sequence should contribute to the new representation at this position?

The vector asking that question is called the query. For example, in our companion sentence “Small models learn patterns,” we will choose the position labeled “models.” Its input vector becomes the query because we want to calculate context for that position. “Question” is an analogy for its role in a numerical calculation; the model is not forming a literal question.

The calculation has three steps:

Step What we do What we get
Compare Take the query's dot product with every available input vector, including itself. One score for each contributing position.
Normalize Apply softmax across those scores. Mixing amounts, called attention weights, that sum to one.
Mix Multiply each input vector by its mixing amount, then add the weighted vectors coordinate by coordinate. One context vector for the chosen position.
Choose the position whose context we want
    ↓
Use its input vector as the query
    ↓
Compare with every input vector, including itself
    ↓
Scores → softmax → mixing amounts
    ↓
Use those amounts to combine the input vectors
    ↓
A context vector for the chosen position

A score is a comparison result. A mixing amount tells us how much a vector contributes to the sum. Keeping those two stages separate makes the calculation easier to follow. We will first demonstrate simple division by the score sum, then replace it with softmax.

The result is still a vector of the same width in this example. It now contains contributions from positions in the sequence. We have calculated one new representation, not predicted the next token or updated the stored embedding table. The calculation for another query position produces that position's own scores, weights, and context vector.

This already counts as self-attention: the query and the vectors it consults belong to the same sequence. “Self” does not restrict attention to the query's own position.

Why is this version simplified?

We use the input vectors themselves to decide how to mix the input vectors themselves. They do two jobs: provide the numbers being compared, and provide the information being mixed. No learned query/key/value projections separate those jobs yet.

If you followed the character-log experiment, we previously explored attention inside a complete transformer block, alongside normalization, residual additions, and a feedforward network. Here we are zooming into the attention component and temporarily removing some machinery so we can see its core calculation.

Job This simplified version Version with learned projections
Ask for information at a position That position's input vector A query vector produced using WQ
Supply vectors to compare against The input vectors Key vectors produced using WK
Supply information to mix The input vectors Value vectors produced using WV

The learned version retains compare → normalize → mix, but learns how to prepare the vectors for those jobs. We will introduce those projections in section 3.4; causal masking follows in 3.5. For now, all positions in the example are accessible. The attention output still needs the rest of the model before it becomes vocabulary scores for predicting a token.

With that purpose in mind, we can follow the symbols and arithmetic below. Section 3.3.1 works through one query position; section 3.3.2 extends the calculation to every position.

Follow one position through the calculation

Keep these symbols separate:

Symbol Meaning Small example
T Number of token positions in this sequence 4 positions
d Number of coordinates in each input vector 3 numbers per vector
x(2) Input vector at the second position; the number is a position, not an exponent [0, 2, 1]
z(2) Context vector computed for the second position Also 3 numbers here
α23 Mixing weight for input position 3 when computing the output for position 2 One scalar, not a vector

The book uses six word-labeled positions for “Your journey starts with one step.” Its input tensor therefore has six rows, each containing three numbers. In general, the input shape is [T, d]: positions × coordinates per vector. This is one sequence, with no batch axis in this example. Word labels help us read the example; a real tokenizer may split words into multiple tokens.

For our companion drawings, use four word-labeled positions and deliberately simple, invented vectors. These are teaching inputs, not representations from a trained model:

import torch

# One sequence: T=4 positions, d=3 coordinates per vector.
# These are floating-point vectors already, not integer token IDs.
inputs = torch.tensor([
    [1.0, 0.0, 1.0],  # Small   — position 1
    [0.0, 2.0, 1.0],  # models  — position 2
    [1.0, 1.0, 0.0],  # learn   — position 3
    [0.0, 1.0, 2.0],  # patterns — position 4
])

Four three-coordinate vectors are weighted separately and summed to form the context vector for the second position, models.

Original companion illustration inspired by Figure 3.7 in Raschka's book, using a different sentence and invented vectors. The weights are symbolic: this drawing shows the goal before we calculate the mixing amounts. All four positions are accessible because this example has no causal mask.

We focus on z(2) first, but the eventual goal is one context vector per input position. There is no concatenation here: multiplying each three-coordinate vector by a scalar and summing the results still produces three coordinates. Four input positions will ultimately produce four context vectors.

First calculate scores, not mixing amounts. Use the second input vector as the query—the position for which we want context—and take its dot product with each input vector. In this simplified version, “query” describes the role of an input vector; we have not introduced a learned query projection yet.

# Python index 1 selects position 2: [0, 2, 1], shape [3].
query = inputs[1]

# For each row, multiply matching coordinates and add them.
# inputs has shape [4, 3]; query has shape [3]; scores has shape [4].
scores = inputs @ query
print(scores)  # tensor([1., 5., 2., 4.])

The query vector zero two one is compared with each input by dot product, producing scores one five two four.

Original companion illustration inspired by Figure 3.8, using the same invented inputs as our preceding figure. The displayed scores are exact for these inputs. A score is an intermediate comparison value; it is not yet a normalized attention weight.

For example, the score comparing position 2 with position 3 is 0×1 + 2×1 + 1×0 = 2. These dot products depend on the vectors and their magnitudes; with invented inputs, we should not read semantic understanding into the resulting rankings.

Attention weights are not the same as trainable model weights

This section has no learned query/key/value matrices. It still computes attention scores and, subsequently, mixing weights from the inputs. Those mixing weights are computed activations, not stored parameters adjusted directly by the optimizer. In a full model, the input embeddings can themselves be learned even when a particular attention operation has no trainable projections.

The book's figures shorten the displayed decimal values to save space. Two rows can therefore look identical in a drawing while differing in the actual tensor. Use the full values from the code for calculations; do not expect dot products of truncated display values to reproduce the original scores exactly.

Reading the book's notation

The raised parenthesized number is a position label, not a power: x(2) means the input vector at position 2. More generally, x(T) is the last input vector when the sequence has T positions. The corresponding context vector is z(2).

  • ω (omega) denotes an attention score: ω23 = x(2) · x(3).
  • α (alpha) denotes a normalized attention weight: α23 is how much position 3 contributes to the context vector for position 2.
  • The first subscript identifies the query position; the second identifies the contributing position. These figures use omega and alpha, not theta.

Understanding dot products

A dot product multiplies matching coordinates and sums the products. It measures alignment and depends on vector magnitudes. If we double a vector without changing its direction, its dot product with the query doubles. So a higher score is not automatically evidence of a closer semantic relationship. In this example, larger positive scores will receive larger mixing weights after normalization.

For example, [1, 2] · [3, 4] = 1×3 + 2×4 = 11. Two vectors go in; one scalar score comes out.

From scores to weights that sum to one

For our query at position 2, the scores are [1, 5, 2, 4]. A first, simple normalization divides each score by their sum, 12:

# scores: shape [4], one scalar per input position for this query.
# All four scores in this toy example are positive.
attention_weights = scores / scores.sum()
print(attention_weights)  # tensor([0.0833, 0.4167, 0.1667, 0.3333])
print(attention_weights.sum())  # tensor(1.)

Scores omega 21 through omega 24 are divided by their sum 12 to obtain weights alpha 21 through alpha 24, summing to one.

Original companion illustration inspired by Figure 3.9 in Raschka's book. We retain our four-position example and show exact fractions to avoid rounding ambiguity. This figure demonstrates simple division by the score sum, not softmax.

The weights describe how to distribute the mixture across the input vectors: position 2 receives 5/12 of the weight, position 4 receives 4/12, and so on. This makes the combination interpretable as a weighted average and prevents its scale from growing merely because we add more equally weighted contributors. This normalization is across positions for one query; it is not LayerNorm across a token vector's coordinates.

This first normalization is only a teaching step

Arbitrary dot products can be negative, and their sum can be zero or very close to zero. Dividing by that sum is therefore not a general solution for attention. Softmax will give us nonnegative weights summing to one even when scores are negative. Normalization alone does not guarantee stable training.

Reproduce the book's six-token example

Our diagrams use four simple vectors to make the arithmetic easy to inspect. To compare directly with the book, here are the six input vectors and the score/normalization calculation from the official Chapter 3 notebook, section 3.3.1. The code below adapts that example with explicit names and comments; it is independent of the four-position example above.

import torch

# Floating-point input vectors, not token IDs.
# T=6 token positions; d=3 coordinates per vector; shape [6, 3].
book_inputs = torch.tensor([
    [0.43, 0.15, 0.89],  # Your
    [0.55, 0.87, 0.66],  # journey
    [0.57, 0.85, 0.64],  # starts
    [0.22, 0.58, 0.33],  # with
    [0.77, 0.25, 0.10],  # one
    [0.05, 0.80, 0.55],  # step
])

# Position 2 is Python row index 1. This query has shape [3].
book_query = book_inputs[1]

# Allocate six score slots. torch.empty does not initialize their values;
# the loop fills every slot before we read or print the tensor.
book_scores = torch.empty(book_inputs.shape[0])
for position_index, input_vector in enumerate(book_inputs):
    # Two vectors of shape [3] -> one scalar dot product.
    book_scores[position_index] = torch.dot(input_vector, book_query)

# Shape [6]: omega_21 through omega_26, in input-position order.
print(book_scores)

# Divide each score by the sum of all six scores for this query.
# Shape stays [6]: alpha_21 through alpha_26.
book_weights = book_scores / book_scores.sum()
print(book_weights)
print(book_weights.sum())
tensor([0.9544, 1.4950, 1.4754, 0.8434, 0.7070, 1.0865])
tensor([0.1455, 0.2278, 0.2249, 0.1285, 0.1077, 0.1656])
tensor(1.0000)

For the first score, ω21, the calculation is 0.43×0.55 + 0.15×0.87 + 0.89×0.66 = 0.9544. The score sum is 6.5617, so α21 is 0.9544 / 6.5617 ≈ 0.1455. These printed decimals are rounded; the calculation uses the tensor's stored precision. The last printed sum may display as 1. or 1.0000 depending on floating-point and display details.

The loop makes each comparison visible. book_inputs @ book_query computes the same six scores at once, which is the form used in our smaller example. This remains simple sum normalization, not softmax.

Use softmax for attention weights

Instead of dividing the raw scores by their sum, softmax first exponentiates each score and divides by the sum of those exponentials. For finite scores, the resulting weights are nonnegative and sum to one, even when some scores are negative. This is a smooth, differentiable transformation; changing one score also affects the other weights through the shared denominator. It does not guarantee that gradients will always be large or that training will always be stable.

Continuing with book_scores from the six-token example, the official notebook first demonstrates a naive implementation. Here it has a type hint and a shape explanation:

def softmax_naive(scores: torch.Tensor) -> torch.Tensor:
    """Normalize a floating-point score vector [T] into weights [T].

    T is the number of input positions for one query. This direct
    exponential formula illustrates softmax but is not numerically stable.
    """
    exponentials = torch.exp(scores)
    return exponentials / exponentials.sum(dim=0)

book_weights_naive = softmax_naive(book_scores)
print(book_weights_naive)
print(book_weights_naive.sum())
tensor([0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581])
tensor(1.)

Directly exponentiating large positive scores can overflow. A stable implementation subtracts the largest score before exponentiation; this leaves the mathematical result unchanged while avoiding that overflow for ordinary finite inputs. In practice, use PyTorch's implementation:

# book_scores has shape [6]. Axis 0 is its only axis: input positions.
# Normalize across those six positions for the single query "journey".
book_weights_softmax = torch.softmax(book_scores, dim=0)
print(book_weights_softmax)
print(book_weights_softmax.sum())

This prints the same weights as the naive implementation for our modest scores. It is not the same result as the earlier division by the raw score sum. The context-vector calculation below uses these softmax weights. Our experiment models also use PyTorch softmax; here we are unpacking the operation one step at a time.

Finish one context vector: multiply, then sum

For z(2), multiply each input vector x(i) by its scalar weight α2i, then add the resulting vectors coordinate by coordinate. The parenthesized superscript still labels the position, not a power.

# book_query has shape [3]: d=3 coordinates per vector.
# Begin with three zeros to accumulate the weighted contributions.
book_context_2 = torch.zeros_like(book_query)
for position_index, input_vector in enumerate(book_inputs):
    # One scalar weight times one [3] vector produces another [3] vector.
    weighted_input = book_weights_softmax[position_index] * input_vector
    book_context_2 += weighted_input

print(book_context_2)
# tensor([0.4419, 0.6515, 0.5683])

Those are three numbers: 0.4419, 0.6515, and 0.5683. Six input vectors of width three contribute to one output vector of width three. For example, its first coordinate is approximately 0.1385×0.43 + 0.2379×0.55 + 0.2333×0.57 + 0.1240×0.22 + 0.1082×0.77 + 0.1581×0.05 = 0.4419. The code uses full-precision weights, not the rounded ones displayed here.

Our four toy inputs are multiplied by their softmax weights and summed to form the second context vector, approximately zero point zero four seven four, one point six eight three six, one point two two one five.

Original companion illustration inspired by Figure 3.10 in Raschka's book. The diagram continues our four-position toy example; the code above reproduces the book's separate six-position example. Weights and output coordinates are rounded for display, but the calculation uses full precision. These weights come from softmax, replacing the simple sum normalization illustrated earlier.

The same weighted sum can be expressed compactly as book_weights_softmax @ book_inputs: shape [6] @ [6, 3] gives [3]. The loop exposes each contribution; the matrix operation combines them in one expression.

We have calculated the context vector for one position. Section 3.3.2 extends the calculation to all input positions simultaneously.

3.3.2 Computing attention weights for all input tokens

The calculation has not changed; the query position now changes. In 3.3.1, we used “journey” at position 2 as the query and calculated one set of mixing weights and one context vector. Now each of the six positions takes a turn as the query. Every query still consults all six original input vectors, including itself.

We do not feed the first context vector into the calculation of the second. All output rows are computed from the same input matrix. This is why we can calculate them together.

Read the rows and columns before the code

For our six-position example, both the score matrix and weight matrix have shape [6, 6]:

  • Row i: the query position whose context we want to compute.
  • Column j: the input position being compared or contributing information.
  • ωij: the dot-product score for that pair.
  • αij: the mixing amount for input j when constructing context vector z(i).

For example, α23 sits in the second row and third column: how much “starts” contributes to the context vector for “journey.” In Python, that cell is all_weights[1, 2], because indexing starts at zero.

A six-by-six attention-weight table with query positions as rows, contributing positions as columns, and the previously calculated journey row highlighted.

Original companion layout inspired by Figure 3.11 in Raschka's book. Values are computed from the book's six input vectors and rounded to four decimal places for display. Each full-precision row sums to approximately one; displayed rounding can change the last digit of its sum. The highlighted row is the single-query calculation from 3.3.1.

Each row of attention weights sums to one because softmax distributes that query's mixture across its available input positions. Raw score rows need not sum to one. Columns of the weight matrix need not sum to one either. The whole weight matrix sums to approximately six: six separate mixtures, each with a total weight of one. The book truncates its displayed values, so adding those shortened numbers may give a total below one.

Step 1: compute all pairwise scores

The following code adapts the official Chapter 3 notebook, section 3.3.2. Continue with book_inputs from the six-token example above: shape [6, 3], meaning six positions and three coordinates per vector. These are already floating-point vectors, not token IDs.

# T is the number of token positions in this one sequence, here 6.
num_positions = book_inputs.shape[0]
all_scores_loop = torch.empty(num_positions, num_positions)

# The outer loop selects the query: one complete output row at a time.
for query_index, query_vector in enumerate(book_inputs):
    # The inner loop compares that query with every input position.
    for input_index, input_vector in enumerate(book_inputs):
        all_scores_loop[query_index, input_index] = torch.dot(
            query_vector, input_vector
        )

print(all_scores_loop)
tensor([[0.9995, 0.9544, 0.9422, 0.4753, 0.4576, 0.6310],
         [0.9544, 1.4950, 1.4754, 0.8434, 0.7070, 1.0865],
         [0.9422, 1.4754, 1.4570, 0.8296, 0.7154, 1.0605],
         [0.4753, 0.8434, 0.8296, 0.4937, 0.3474, 0.6565],
         [0.4576, 0.7070, 0.7154, 0.3474, 0.6654, 0.2935],
         [0.6310, 1.0865, 1.0605, 0.6565, 0.2935, 0.9450]])

There are 36 scalar scores, not 36 context vectors. Row 2 contains the six scores we already computed for “journey.” Each row is another instance of the same calculation.

We can replace both loops with one matrix multiplication:

# [6, 3] @ [3, 6] -> [6, 6]: query positions × compared positions.
all_scores = book_inputs @ book_inputs.T
print(torch.allclose(all_scores, all_scores_loop))  # True

Why transpose? Each input vector starts as a row. Matrix multiplication computes the dot product of a row on the left with a column on the right. .T places each input vector in a column, so output cell [i, j] is exactly the dot product of input rows i and j. For these two-dimensional inputs, .T swaps the two axes; it does not change the coordinate values or introduce any learned weights. @ means matrix multiplication, whereas * would mean element-wise multiplication.

This is the bridge to NumPy and PyTorch: the mathematical operation is explicit, and the framework executes it using optimized numerical routines instead of making Python dispatch every individual dot product. The work still exists—here, 36 comparisons—but it can be organized efficiently and run in parallel where the hardware supports it. It is not a different attention algorithm, and a tiny example is not a meaningful performance benchmark.

Step 2: normalize each query's row independently

# all_scores: [6, 6], axes are [query position, compared position].
# dim=-1 selects the LAST axis: the six columns within each row.
all_weights = torch.softmax(all_scores, dim=-1)
print(all_weights[1])  # The previously calculated weights for query 2.
print(all_weights.sum(dim=-1))  # One sum per query row: shape [6].
tensor([0.1385, 0.2379, 0.2333, 0.1240, 0.1082, 0.1581])
tensor([1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000])

For this two-dimensional matrix, dim=-1 and dim=1 select the same column axis. Softmax takes six scores from one row, computes six weights for that row, and repeats independently for the other rows. dim=0 would normalize down the query rows within each column, which is not the mixture we want. all_weights.sum() without a dimension would collapse the whole matrix into one scalar instead of checking individual rows.

In 3.3.1 our scores were a one-dimensional vector [6], so dim=0 was its only axis. The dimension argument follows the tensor's shape, not a permanent rule that attention always uses axis 0 or axis 1.

Step 3: mix the original input vectors for every query

# [6, 6] @ [6, 3] -> [6, 3]: one three-coordinate vector per query.
all_context_vectors = all_weights @ book_inputs
print(all_context_vectors)

# Python row 1 is position 2. Compare with the prior single-query result.
print(torch.allclose(all_context_vectors[1], book_context_2))  # True
tensor([[0.4421, 0.5931, 0.5790],
         [0.4419, 0.6515, 0.5683],
         [0.4431, 0.6496, 0.5671],
         [0.4304, 0.6298, 0.5510],
         [0.4671, 0.5910, 0.5266],
         [0.4177, 0.6503, 0.5645]])
True

This multiplication does the weighted sum for every row. For example, the second output row is still:

z(2) = α21x(1) + α22x(2) + … + α26x(6).

For a particular output coordinate, matrix multiplication multiplies the six weights in that query's row by that coordinate from each of the six input vectors, then adds the products. It repeats this for all three coordinates and all six queries. Each output row is a vector with three coordinates—not a location in physical three-dimensional space and not a vocabulary prediction.

Shape trace: six-by-three input vectors produce six-by-six scores, row-wise softmax produces six-by-six weights, and multiplying by the original inputs produces six-by-three context vectors.

Original companion illustration inspired by Figure 3.12, with explicit shapes and the second query highlighted. The same original input matrix supplies both comparisons and information to mix. This is the simplified attention calculation: no learned Q/K/V projections or causal mask have been introduced.

All six contexts are now available, but the core operation is unchanged: compare → normalize → mix. Section 3.4 introduces learned transformations for the vectors performing these jobs.

3.4 Implementing self-attention with trainable weights

The next mechanism is scaled dot-product attention, the attention calculation introduced in the original Transformer. We now add trainable projections to the calculation we have been studying; this section develops the single-head building block before causal masking and multiple heads.

Figure 3.13 in the book revisits the roadmap: we are still at step 2, Attention mechanism, within Stage 1. Within this chapter, we move from simplified self-attention to self-attention with trainable weights. The complete model architecture and training loop are separate steps.

The author's overall roadmap: data preparation, attention, and architecture lead to pretraining and fine-tuning. We remain at Attention mechanism in Stage 1.

Sebastian Raschka's book roadmap, embedded from his website and repeated here to keep our location visible. We are at step 2, “Attention mechanism,” within Stage 1. This is the overall map; the chapter progression below shows the attention variant we are implementing now.

You are here: self-attention with trainable weights

We have worked through simplified self-attention. Now we extend it with learned query, key, and value projections. Causal masking and multiple heads come next; assembling the full LLM architecture remains a later step on the overall map.

Four attention variations: simplified attention, trainable projections, causal masking, and multiple heads. Section 3.4 focuses on the second step.

Our chapter progression figure, reused to mark the transition highlighted in Figure 3.13 of Raschka's book. The focus is now the second card: introducing learned query, key, and value projections. See the overall book roadmap for the larger architecture and training stages.

The goal stays familiar: produce a context vector for each query position by combining information from available input positions. The important change is that the model can learn how to prepare that information. Stored matrices WQ, WK, and WV transform inputs into query, key, and value vectors. The weighted sum will combine the value vectors, which are transformed inputs, rather than the original input vectors directly.

These matrices are model parameters updated during training. They are different from the attention weights calculated from the current queries and keys on each forward pass. Training learns the transformations; each forward pass uses them to calculate input-dependent scores and mixtures.

The word scaled refers to dividing query–key dot-product scores by the square root of the key-vector width before softmax. We will work through that calculation and its reason in 3.4.1. Scaling and softmax are separate operations; scaling alone does not make the scores sum to one.

From individual calculations to a reusable component

The section has two parts: first implement the calculations step by step, then collect them into a compact Python class that the LLM architecture can use. This matches the approach in our character-log experiment.

In experiments/character-logs/model.py, the composition is:

TinyTransformer
    └── TransformerBlock
            ├── Normalization and residual connections
            ├── CausalAttention
            └── Feedforward network

TinyTransformer creates a TransformerBlock; that block creates a CausalAttention instance and calls it on normalized input vectors. experiments/character-logs/train.py creates the complete TinyTransformer and runs training through it. The attention class owns its learned projections and implements its forward calculation; the training script handles the loss, backpropagation, and optimizer steps.

Our existing CausalAttention already includes future-position masking and an output projection. The book's section 3.4 class is an earlier component in that progression, so we should not expect it to match our implementation line for line. Packaging a calculation in a class makes it reusable; it does not change the mathematics.

3.4.1 Computing the attention weights step by step

First project the inputs into queries, keys, and values

We begin with three separate stored weight matrices: WQ, WK, and WV. Multiplying an input vector by each matrix produces three different vectors with different roles. The same matrices are shared across token positions; we do not create a separate set of parameters for every token.

For continuity with the preceding runnable example, use the book's six-position sentence and book_inputs tensor from 3.3.1. Its second row, “journey,” is [0.55, 0.87, 0.66]. The following adapts the official Chapter 3 notebook, with comments explaining the shapes:

# book_inputs: [6, 3], six positions with three coordinates each.
x_2 = book_inputs[1]  # Position 2, Python index 1; shape [3].
d_in = book_inputs.shape[1]  # Input-vector width: 3.
d_out = 2  # Projection output width: 2, chosen for this demonstration.

torch.manual_seed(123)
# Each parameter matrix is [3, 2]. Three independent random draws.
# Gradient tracking is off for this arithmetic-only demonstration.
W_query = torch.nn.Parameter(torch.rand(d_in, d_out), requires_grad=False)
W_key = torch.nn.Parameter(torch.rand(d_in, d_out), requires_grad=False)
W_value = torch.nn.Parameter(torch.rand(d_in, d_out), requires_grad=False)

# Each multiplication: [3] @ [3, 2] -> [2].
query_2 = x_2 @ W_query
key_2 = x_2 @ W_key
value_2 = x_2 @ W_value
print(query_2)
# tensor([0.4306, 1.4551])

The two output coordinates come from dot products with the matrix's two columns. The first combines all three input coordinates using the first column's coefficients; the second uses the second column. We do not simply discard the third input coordinate.

The same three-coordinate input vector at position two is multiplied separately by query, key, and value parameter matrices of shape three by two, producing three two-coordinate vectors.

Original companion illustration inspired by Figure 3.14 in Raschka's book, focusing on the second input so the three projections are explicit. Values come from the seeded book calculation and are rounded for display. The same key/value matrices will also be applied to the other input positions when calculating context for this query.

Input width and projection output width do not have to be equal. Here the change from three coordinates to two makes it visible that a transformation happened. These are vector widths, not sequence lengths or vocabulary sizes. In many GPT implementations the full projected width matches the model width, while individual attention heads use smaller widths. The vectors used in a query–key dot product must have matching widths. We will stay with the book's 3 → 2 example here.

What does requires_grad=False mean?

requires_grad asks PyTorch whether it should track the calculations needed to obtain gradients for a tensor during backpropagation. It does not turn matrix multiplication on or off. We get the same numerical query vector either way.

For this example, the inputs and all three matrices have gradient tracking disabled. PyTorch can calculate the outputs without constructing a backward graph, so the printed result has no extra grad_fn information. That is what the book means by reducing output clutter; it changes gradient bookkeeping, not just print formatting.

For training these matrices, the sequence would be:

  1. Create the parameters with requires_grad=True (the default for nn.Parameter).
  2. Run the model forward and calculate a loss.
  3. Call loss.backward() to calculate gradients for parameters that contribute to the loss.
  4. Call the optimizer's step() to update the parameters included in that optimizer.

True allows gradients to be calculated; the optimizer performs the update. Merely declaring a parameter or doing a forward pass does not train it. Conversely, False disables gradient accumulation for that parameter; it does not make its values immutable. Freezing some parameters is also useful when only part of a model should be trained. If other operands require gradients, an operation involving a frozen parameter can still be tracked for those operands.

nn.Parameter is a tensor subclass used for model parameters. When assigned as an attribute of an nn.Module, it is registered so model.parameters() can find it. Here the matrices are standalone variables for the walkthrough; the later class will own them. Our tiny model's nn.Linear layers already create and register their weight parameters for us.

Random initialization provides starting values when training from scratch; it is not a rule that every parameter in every architecture must be random. Normalization scales and biases can start from constants, and loading a trained checkpoint supplies existing learned values. The seed makes this example reproducible; it does not train the matrices.

Weight parameters versus attention weights

Weight parameters are the entries in WQ, WK, and WV. Training adjusts these stored coefficients; during an ordinary inference forward pass, they stay fixed.

Attention weights, αij, are computed from the current queries and keys. They tell us how much each value vector contributes to a particular query's context vector. Different inputs or query positions can produce different attention weights while using exactly the same stored parameter matrices.

The word weight is used for both, but their roles differ. The matrices define the learned transformations; the attention weights define the current mixture. We have not calculated attention weights for the projected vectors yet: the next outputs are still raw scores, ωij.

One query still needs keys and values from all positions

We want the context vector for position 2, “journey.” That means we need its query q(2), but information can come from any of the six available positions. We therefore prepare a key and a value for every input position:

# Reuse book_inputs and W_key/W_value from the preceding code.
# [6, 3] @ [3, 2] -> [6, 2] for each projection.
keys = book_inputs @ W_key
values = book_inputs @ W_value
print("keys.shape:", keys.shape)
print("values.shape:", values.shape)
keys.shape: torch.Size([6, 2])
values.shape: torch.Size([6, 2])

There are still six token positions, now with two coordinates in each key or value vector. The same WK is applied to every input row, and likewise for WV.

Keep the roles separate: keys participate in the score calculation; values will supply the information to mix later. Values do not enter the query–key dot products. Computing them now prepares the later weighted sum.

Calculate one score, then all scores for query 2

ω22 compares the query for position 2 with the key for position 2. Those vectors come from the same input position but different parameter matrices, so this is not generally a vector dotted with itself.

keys_2 = keys[1]  # Python index 1 is position 2; shape [2].
attn_score_22 = query_2.dot(keys_2)  # [2] dot [2] -> scalar.
print(attn_score_22)
# tensor(1.8524)

The query is approximately [0.4306, 1.4551] and this key is approximately [0.4433, 1.1419]. Multiply corresponding coordinates and add them. The code uses the stored values, not these rounded display values.

The second input is projected to query two; every input is projected to a key and a value. Query two dotted with each key produces six unscaled attention scores, with score two two highlighted. Values are reserved for the later mixture.

Original companion illustration inspired by Figure 3.15 in Raschka's book. Uses the seeded six-token example from the preceding code, with scores rounded to four decimal places. The diagram separates key-based comparisons from values reserved for the later context-vector calculation. No scaling, softmax, or causal mask has been applied at this point.

Now perform all six comparisons in one matrix multiplication:

# query_2: [2]; keys: [6, 2]; keys.T: [2, 6].
# Each column of keys.T holds one key vector.
# [2] @ [2, 6] -> [6]: one score per key, all for the same query.
attn_scores_2 = query_2 @ keys.T
print(attn_scores_2)
print(torch.allclose(attn_scores_2[1], attn_score_22))
tensor([1.2705, 1.8524, 1.8111, 1.0795, 0.5577, 1.5440])
True

The entries are ω21, ω22, …, ω26, in input-position order. The first index stays 2 because the query has not changed. “All scores” here means all six scores for query 2, not a six-by-six score matrix for all queries. The second entry matches the individually computed ω22, confirming that the matrix operation carries out the same dot products.

This is the bridge from the simplified calculation: we still compare vectors with dot products, but those vectors are now queries and keys produced by learned transformations. The scores are unscaled and unnormalized; they need not sum to one. Scaling and softmax turn these scores into the weights used below.

Scale the scores, then apply softmax

We now have six scores for query q(2). To turn them into attention weights, first divide by the square root of the key-vector width, then apply softmax:

# keys: [6, 2]. Last axis is the number of coordinates in each key.
d_k = keys.shape[-1]  # 2, NOT the six positions or original input width 3.
scaled_scores_2 = attn_scores_2 / d_k**0.5
attn_weights_2 = torch.softmax(scaled_scores_2, dim=-1)
print(attn_weights_2)
print(attn_weights_2.shape)
print(torch.allclose(attn_weights_2.sum(), torch.tensor(1.0)))
tensor([0.1500, 0.2264, 0.2199, 0.1311, 0.0906, 0.1820])
torch.Size([6])
True

This is one set of six weights for query 2: α21 through α26. Although the output prints on one line, its actual shape is [6], a one-dimensional tensor, not [1, 6]. Scaling preserves the score ordering but changes their separation; softmax turns the scaled scores into mixing amounts that sum to approximately one.

Six raw scores omega for query two are divided by square root of two, then softmax produces six alpha weights summing to one.

Original companion illustration inspired by Figure 3.16 in Raschka's book. Values are computed from our seeded book example and rounded to four decimals for display. Scaling and softmax are shown as separate operations; division by √2 alone does not make the scores sum to one.

The rationale behind scaled dot-product attention

A dot product adds one product per query/key coordinate. Under the usual simplifying assumption of independent, zero-mean, unit-variance coordinates, its variance grows with dk, so its standard deviation grows with √dk. Dividing by √dk counteracts that growth in scale.

When score differences become large, softmax can put almost all its weight on one position. In that saturated region, many derivatives through softmax become very small, making learning through the attention scores harder. Scaling helps keep scores in a more useful range; it does not guarantee that gradients will always be large or training stable.

Absolute score size alone is not the issue: adding the same constant to every score leaves softmax unchanged. This scaling also has a different purpose from subtracting the maximum inside numerically stable softmax, which prevents exponential overflow while preserving the mathematical probabilities.

The relevant width is the query/key width used in the dot product. In multi-head attention, that is the width per head, which may be much smaller than the model's overall embedding width. Here it is simply 2, so the divisor is √2 ≈ 1.4142. This score scaling gives scaled dot-product attention its name. It is not LayerNorm and not the earlier demonstration of division by the sum of scores.

Finish the context vector by combining values

The final step now uses value vectors, not the original input vectors. Each scalar α2j multiplies the corresponding v(j), and we add the weighted vectors:

z(2) = α21v(1) + α22v(2) + … + α26v(6).

# Six scalar weights @ six value vectors with two coordinates each.
# [6] @ [6, 2] -> [2]: one context vector for query position 2.
context_vec_2 = attn_weights_2 @ values
print(context_vec_2)
# tensor([0.3061, 0.8210])

To make the meaning of @ explicit, this loop calculates the same weighted sum:

context_vec_2_loop = torch.zeros_like(values[0])  # Two zeros.
for position_index, value_vector in enumerate(values):
    context_vec_2_loop += attn_weights_2[position_index] * value_vector
print(torch.allclose(context_vec_2, context_vec_2_loop))  # True

Each of six two-coordinate value vectors is multiplied by its attention weight for query two. Summing the contributions produces context vector zero point three zero six one, zero point eight two one zero.

Original companion illustration inspired by Figure 3.17, using all six positions from the seeded example. Weighted contributions and final coordinates are computed at full precision and rounded independently for display. Queries and keys determined the weights; the value vectors supply the information in the final mixture.

The resulting two coordinates match the value-vector width. We still have just one context vector, because only q(2) supplied the scores. This is the attention output before any later output projection or residual addition, not a next-token prediction. None of these forward calculations trained the parameter matrices.

The complete calculation for this position is now: project inputs → compare query with keys → scale → softmax → combine values. Section 3.4.2 packages the calculation in a reusable class and computes context vectors for all positions.

Why query, key, and value?

The book borrows these names from information retrieval and databases. Think of looking something up: you have a request, something to match the request against, and information you want to receive.

Name Plain-language role In our attention calculation
Query What am I looking for? q(2) represents the request from position 2.
Key What can this item be matched on? Each k(j) is compared with the query to calculate a score.
Value What information does this item contribute? Each v(j) supplies the vector that will be weighted and added.

These are descriptions of the vectors' roles, not literal questions, labels, or database records stored inside them. The model learns the transformations that create these numerical representations.

A database analogy helps separate matching from receiving information. Imagine searching a collection of documents: the features used to decide which documents match your request need not be the same representation you return from those documents. In attention, keys perform the matching role, while values supply the information for the result.

Query from position 2
    │
    ├── compare with key 1 → score → attention weight 1 → weight value 1
    ├── compare with key 2 → score → attention weight 2 → weight value 2
    └── compare with key j → score → attention weight j → weight value j
                                                              │
                                                add the weighted values
                                                              ↓
                                                context for position 2

Scaling and softmax turn the scores into weights together, across the available positions. Each branch above is not normalized independently.

The key decides how strongly its paired value contributes. The value supplies the information that contributes. Their pairing comes from their input position: k(3) and v(3) both come from x(3), through different learned matrices. A key is not required to be unique, and the lookup is not an exact equality check like accessing a Python dictionary.

In our example, q(2) comes from “journey.” It is compared with all six keys. The score for the key at “starts” becomes α23 ≈ 0.2199 after scaling and softmax. That weight then multiplies the value at “starts,” v(3), before we add its contribution to the other weighted values. We do not add the key itself to the result.

The result is usually a blend of information from several positions, not one retrieved record. With a causal mask later, only permitted positions can contribute. And a token can both ask and supply information: in self-attention, its input vector produces its query, key, and value. The matrices give those three roles different learned representations.

For now we have used just one query, q(2). Using the other queries will give each position its own mixture and context vector. That is the next step in 3.4.2.

3.4.2 Implementing a compact self-attention Python class

The class packages the calculation we already know and applies it to every query position at once. It does not introduce another attention mechanism. In 3.4.1 we asked for the context of “journey”; now each of the six positions gets its own context vector.

Put the parameters and calculation together

__init__ creates the three parameter matrices once when we instantiate the layer. forward uses those same matrices each time we supply input vectors. It computes new queries, keys, values, attention weights, and context vectors; it does not reinitialize or update the parameters.

The following adapts Listing 3.1 from the official Chapter 3 notebook. The book names the class SelfAttention_v1; we use SelfAttentionV1 here, with type hints and explicit shape comments.

SelfAttentionV1 — one sequence, all query positions
import torch
from torch import nn


class SelfAttentionV1(nn.Module):
    """Single-head self-attention with trainable projections and no causal mask."""

    def __init__(self, d_in: int, d_out: int) -> None:
        """Set input-vector width d_in and query/key/value width d_out."""
        super().__init__()
        # Registered parameters: the optimizer can find them via .parameters().
        # Each matrix is [d_in, d_out], shared across all token positions.
        # requires_grad=True by default; training can calculate their gradients.
        self.W_query = nn.Parameter(torch.rand(d_in, d_out))
        self.W_key = nn.Parameter(torch.rand(d_in, d_out))
        self.W_value = nn.Parameter(torch.rand(d_in, d_out))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Map floating-point input vectors [T, d_in] to contexts [T, d_out].

        T is the number of token positions in one sequence (6 in our example).
        d_in is the input width (3); d_out is each projected vector's width (2).
        There is no batch axis here. x contains vectors, not integer token IDs.
        Each output row mixes value vectors from all T positions, including
        later positions. Calling this method does not update model parameters.
        """
        # [6, 3] @ [3, 2] -> [6, 2]: one vector per position for each role.
        queries = x @ self.W_query
        keys = x @ self.W_key
        values = x @ self.W_value

        # keys.T puts each key in a column: [6, 2] @ [2, 6] -> [6, 6].
        # Entry [i, j] is query i dotted with key j: raw score omega_ij.
        scores = queries @ keys.T
        key_width = keys.shape[-1]  # 2 coordinates, not 6 token positions.
        scaled_scores = scores / key_width**0.5

        # Normalize across keys (columns) separately for each query (row).
        # [6, 6] -> [6, 6]; each row of alpha weights sums to approximately 1.
        attention_weights = torch.softmax(scaled_scores, dim=-1)

        # [6, 6] @ [6, 2] -> [6, 2]. Row i is sum_j(alpha_ij * value_j).
        context_vectors = attention_weights @ values
        return context_vectors

nn.Module lets PyTorch manage registered parameters, nested layers, device moves, and state saving/loading. Calling attention(book_inputs) goes through the module's call machinery to forward; we normally use this rather than calling forward directly. The class structure is useful organization, not a mathematical requirement of attention.

Check that the single-query calculation is still inside it

Reuse the book_inputs tensor from 3.3.1 and the context_vec_2 result from 3.4.1:

# Same seed, shapes, and parameter creation order as the manual example.
torch.manual_seed(123)
attention = SelfAttentionV1(d_in=3, d_out=2)
context_vectors = attention(book_inputs)
print(context_vectors)
print(torch.allclose(context_vectors[1], context_vec_2))
tensor([[0.2996, 0.8053],
        [0.3061, 0.8210],
        [0.3058, 0.8203],
        [0.2948, 0.7939],
        [0.2927, 0.7891],
        [0.2990, 0.8040]], grad_fn=<MmBackward0>)
True

There are six rows because there are six input positions, and two coordinates per row because the value width is two. The second row, z(2), matches the earlier result. This agreement relies on using the same inputs and parameter values: the same seed alone would not guarantee a match if we changed the random draws or initialization scheme.

grad_fn shows that PyTorch tracked this calculation for backpropagation, because the parameters now require gradients. It does not mean a backward pass or optimizer update has happened. The exact printed backward-function label can vary with PyTorch versions.

Read Figure 3.18 as a map of the calculation

The book's figure puts inputs, three projections, attention weights, and output contexts on one page. Read it in two stages: queries and keys determine the mixing amounts; values supply the information to mix. In our original companion diagram, scaling and softmax have their own box so raw scores and normalized weights stay distinct.

All-position trainable self-attention: six three-coordinate inputs produce queries, keys, and values of shape six by two. Query-key dot products produce six by six scores. Scaling and row-wise softmax produce attention weights, which mix values into six two-coordinate context vectors.

Original companion diagram for Figure 3.18 in Raschka's book. One sequence, six positions; no batch axis or causal mask. The highlighted second output row matches the seeded calculation above. Arrows show dependencies, not a sequence of optimizer updates.
Object Shape in this example What one row means
Inputs X [6, 3] The input vector at one position.
Queries Q, keys K, values V Each [6, 2] A projected vector for that position's particular role.
Scores Ω = QKᵀ [6, 6] One query's dot products with all six keys.
Attention weights A, entries αij [6, 6] One query's six mixing amounts, summing to approximately one.
Contexts Z = AV [6, 2] One weighted combination of all six value vectors.

Follow row 2 through the diagram: x(2) produces q(2); that query produces score row 2 and then attention-weight row 2; that weight row mixes all value rows to produce z(2). The other five queries do the same calculation independently. We do not feed the completed z(1) into the calculation of z(2).

The numbers in the book's overview figure are illustrative

Figure 3.18's caption explicitly says its attention-matrix entries are not the actual attention weights from this calculation. Use the runnable code for numerical checks. Our diagram shows the shapes and the verified second context row instead of copying that illustrative matrix. Also distinguish raw scores ω from normalized weights α: the matrix used to mix values contains weights.

Bridge to our tiny transformer, and to nn.Linear

Our Character Logs model already packages attention in a class, CausalAttention in model.py. Its query, key, and value projections play the same roles. It additionally handles batches, masks future positions, and applies an output projection. Normalization, residual connections, and the feedforward network belong to the surrounding transformer block; they are not missing lines from this small self-attention class.

The book next replaces explicitly created parameter matrices with nn.Linear layers, not nonlinear layers. With bias=False, nn.Linear performs x @ layer.weight.T. It stores the matrix in [d_out, d_in] order, whereas our explicit matrices above are [d_in, d_out]. This is a storage convention, not a different attention calculation.

nn.Linear creates and registers its parameters and supplies its own initialization scheme. Its default is bias=True, so a bias-free projection must request False explicitly. Changing the initialization can change the numerical outputs even with the same seed. No GELU or ReLU is being added here; those are nonlinear activation functions from the feedforward part we studied earlier.

Implementing SelfAttention_v2 with nn.Linear

Listing 3.2 packages the projections using nn.Linear:

SelfAttention_v2 — projections managed by nn.Linear
import torch
import torch.nn as nn


class SelfAttention_v2(nn.Module):
    def __init__(self, d_in: int, d_out: int, qkv_bias: bool = False) -> None:
        super().__init__()
        self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
        self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
        self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Map floating-point vectors [T, d_in] to contexts [T, d_out].

        T is the number of positions in one sequence (6 here); d_in is the
        input width (3), and d_out is the query/key/value width (2).
        There is no batch axis or causal mask. These are vectors, not IDs.
        A forward pass computes outputs without updating stored parameters.
        """
        # With bias=False: self.W_key(x) equals x @ self.W_key.weight.T.
        # With bias=True: the layer also adds its learned bias vector.
        keys = self.W_key(x)        # [6, 3] @ [3, 2] -> [6, 2]
        queries = self.W_query(x)    # [6, 2]
        values = self.W_value(x)     # [6, 2]

        attn_scores = queries @ keys.T  # [6, 2] @ [2, 6] -> [6, 6]
        attn_weights = torch.softmax(
            attn_scores / keys.shape[-1] ** 0.5, dim=-1
        )  # [6, 6]

        context_vec = attn_weights @ values  # [6, 6] @ [6, 2] -> [6, 2]
        return context_vec

We instantiate SelfAttention_v2 using the book's seed 789 and test it with our 6-position book_inputs:

torch.manual_seed(789)
sa_v2 = SelfAttention_v2(d_in=3, d_out=2)
print(sa_v2(book_inputs))
tensor([[-0.0739,  0.0713],
        [-0.0748,  0.0703],
        [-0.0749,  0.0702],
        [-0.0760,  0.0685],
        [-0.0763,  0.0679],
        [-0.0754,  0.0693]], grad_fn=<MmBackward0>)

Why do the outputs differ from SelfAttentionV1?

SelfAttentionV1 and SelfAttention_v2 perform identical mathematical steps during the forward pass. Their outputs differ here solely because of their starting weights. SelfAttentionV1 drew values uniformly from [0, 1) with torch.rand, while nn.Linear initializes weights uniformly between −1/√din and +1/√din. PyTorch implements that default through kaiming_uniform_ with a particular parameter choice; it is not a guarantee of stable training. These examples also use different seeds. In Exercise 3.1, we will verify this by transferring weights between the two implementations.

Exercise 3.1: Comparing SelfAttentionV1 and SelfAttention_v2

To confirm that the output difference comes purely from weight initialization rather than a flaw in the attention logic, the book asks us to transfer the weights from an instance of SelfAttention_v2 into SelfAttentionV1 so that both produce identical context vectors.

The key observation is how each class stores its projection weights:

  1. In SelfAttentionV1, projections are explicit matrices multiplied on the right: x @ self.W_query. With input width din = 3 and output width dout = 2, self.W_query has shape [3, 2] ([d_in, d_out]).
  2. In SelfAttention_v2, nn.Linear(d_in, d_out, bias=False) stores its underlying weight matrix as layer.weight with shape [d_out, d_in] ([2, 3]), because nn.Linear evaluates xWT.

To transfer the weights, transpose each V2 matrix and copy its values into the existing V1 parameter. Use torch.no_grad() because this setup operation is not part of the forward computation. The two modules keep independent parameter storage. This comparison uses qkv_bias=False, matching the bias-free V1 class:

# Create an instance of v1 and transfer transposed weights from v2
sa_v1 = SelfAttentionV1(d_in=3, d_out=2)

with torch.no_grad():
    sa_v1.W_query.copy_(sa_v2.W_query.weight.T)
    sa_v1.W_key.copy_(sa_v2.W_key.weight.T)
    sa_v1.W_value.copy_(sa_v2.W_value.weight.T)

# Compare the context vectors from both modules
out_v1 = sa_v1(book_inputs)
out_v2 = sa_v2(book_inputs)

print("v1 output:\n", out_v1)
print("v2 output:\n", out_v2)
print("torch.allclose:", torch.allclose(out_v1, out_v2))
v1 output:
 tensor([[-0.0739,  0.0713],
        [-0.0748,  0.0703],
        [-0.0749,  0.0702],
        [-0.0760,  0.0685],
        [-0.0763,  0.0679],
        [-0.0754,  0.0693]], grad_fn=<MmBackward0>)
v2 output:
 tensor([[-0.0739,  0.0713],
        [-0.0748,  0.0703],
        [-0.0749,  0.0702],
        [-0.0760,  0.0685],
        [-0.0763,  0.0679],
        [-0.0754,  0.0693]], grad_fn=<MmBackward0>)
torch.allclose: True

Understanding torch.allclose

Why use torch.allclose instead of ==? Floating-point rounding can differ with the operation order and hardware. out_v1 == out_v2 returns an element-wise Boolean tensor using exact numerical equality; small differences such as 0.07130001 versus 0.07130000 can produce False. It is not a bitwise comparison, and the size of rounding differences depends on the values and computation.

torch.allclose(a, b) checks whether all values fall within a narrow numerical tolerance:

|a − b| ≤ (atol + rtol × |b|)

with PyTorch defaults rtol = 10−5 and atol = 10−8. Returning True means all corresponding values in these tested outputs agree within that tolerance. It does not prove that two implementations are mathematically equivalent for every possible input. Here, the matching formulas and copied parameters explain why we expect agreement.

Looking ahead: causal masking and multiple heads

With trainable projections packaged into a clean PyTorch module, the author outlines two remaining enhancements needed before plugging attention into a full GPT architecture:

  1. Causal masking (Section 3.5): Causal (cause and effect—not casual!) attention modifies the mechanism so each position can only attend to previous and current tokens, never future tokens. For autoregressive language models, next-word prediction requires that position t cannot peek at token t + 1. Our character-log experiment enforces this restriction. Without it, training predictions could access their target tokens, allowing information leakage and misleadingly low loss.
  2. Multi-head attention (Section 3.6): Rather than relying on a single set of query, key, and value projections, multi-head attention splits the projection dimension across multiple independent "heads." Each head projects the representations into a different subspace, allowing different learned mixtures in parallel. We do not assign heads fixed jobs such as syntax or semantics, and distinct useful specializations are not guaranteed.

With these two goals in view, Section 3.5 tackles causal masking first.

3.5 Hiding future words with causal attention

Causal attention restricts each query position to previous positions and itself. “Masked attention” is a broader term: a causal mask is the particular mask that hides future positions. We keep the same learned query/key/value projections; we change which positions may contribute to each context vector.

The current input is allowed; the next token is the target

For our example sequence Your journey starts with one step, query position 2 corresponds to “journey.” Its context may use “Your” and “journey,” but not “starts” or anything later. In next-token training, the output at position 2 is used to predict “starts,” the token at position 3. Attending to the current input is therefore allowed; attending to the next input would reveal the answer.

Training provides whole input windows so many next-token predictions can be calculated together. The mask gives every position its own permitted prefix, without removing future positions from the tensor altogether. Those later positions still need to make their own predictions.

Read the mask by rows and columns

  • Row i identifies the query position whose context we are calculating.
  • Column j identifies the key/value position that could contribute.
  • Keep entries where j ≤ i, including the diagonal; set weights where j > i to zero.

This leaves a lower triangle of permitted contributions. For the first position, only its own value can contribute. For the last position in this window, all six inputs are permitted.

Six-by-six attention weights before and after causal masking. Entries above the diagonal become zero; the remaining entries are renormalized within each row. Row two can use only positions one and two.

Original companion illustration inspired by Figure 3.19 in Raschka's book. Values are computed from the seed-789 SelfAttention_v2 example above, rather than copied from the book's illustrative matrix. Coordinates are rounded to three decimals, so displayed row sums can differ slightly from one. Grey cells have exactly zero weight after masking.

Why normalize again?

Before masking, each row sums to approximately one. If we simply remove its future-position contributions, the retained weights usually sum to less than one. Divide the retained weights by their row sum to redistribute the full mixture over the allowed values.

For a small arithmetic example, suppose a row contains [0.2, 0.3, 0.5]. At position 2, only the first two entries are allowed:

Original weights:       [0.2, 0.3, 0.5]  sum = 1.0
Zero future entries:    [0.2, 0.3, 0.0]  sum = 0.5
Divide by retained sum: [0.4, 0.6, 0.0]  sum = 1.0

The final context is 0.4 * value_1 + 0.6 * value_2. The value at position 3 contributes nothing. This normalization acts on attention weights, not embedding coordinates; it is not LayerNorm.

Bridge to the masking in our experiment

The book first explains masking by zeroing future weights after softmax and renormalizing. Our Character Logs implementation instead replaces future scores before softmax with negative infinity. Softmax then gives those positions zero weight and normalizes over the permitted positions in one operation. Setting a score to zero would not exclude it: exp(0) is 1.

These approaches express the same causal restriction in exact arithmetic. Masking before softmax avoids problems such as all retained weights underflowing to zero after an unmasked softmax. We will follow the book's implementation step by step next.

3.5.1 Applying a causal attention mask

We now implement the three-step path introduced in Figure 3.20: softmax → multiply by a lower-triangular mask → normalize each remaining row. This is the book's first teaching implementation; the score-masking approach comes next.

Scaled scores become attention weights through softmax, future weights become zero through element-wise masking, and dividing by each retained row sum produces normalized causal weights.

Original companion diagram inspired by Figure 3.20 in Raschka's book. Shapes stay [6, 6] throughout. The middle result contains masked weights awaiting renormalization; it is not a return to raw query–key scores.

1. Compute attention weights as before

Reuse sa_v2 and book_inputs from 3.4.2. We are using the same stored parameters, not creating or training a new layer. This adapts the official Chapter 3 notebook.

# One sequence: T = 6 token positions; input width = 3; key/query width = 2.
queries = sa_v2.W_query(book_inputs)  # [6, 3] -> [6, 2]
keys = sa_v2.W_key(book_inputs)       # [6, 3] -> [6, 2]
attn_scores = queries @ keys.T       # [6, 2] @ [2, 6] -> [6, 6]
attn_weights = torch.softmax(attn_scores / keys.shape[-1] ** 0.5, dim=-1)
print(attn_weights)
tensor([[0.1921, 0.1646, 0.1652, 0.1550, 0.1721, 0.1510],
        [0.2041, 0.1659, 0.1662, 0.1496, 0.1665, 0.1477],
        [0.2036, 0.1659, 0.1662, 0.1498, 0.1664, 0.1480],
        [0.1869, 0.1667, 0.1668, 0.1571, 0.1661, 0.1564],
        [0.1830, 0.1669, 0.1670, 0.1588, 0.1658, 0.1585],
        [0.1935, 0.1663, 0.1666, 0.1542, 0.1666, 0.1529]],
       grad_fn=<SoftmaxBackward0>)

Every row already sums to approximately one, but future positions still have nonzero weights.

2. What does torch.tril do?

Think triangular, lower. torch.tril keeps entries on and below the main diagonal and replaces entries above it with zeros. It does not create ones by itself: torch.ones_like supplies the ones in this example.

# Same [6, 6] shape, dtype, and device as the weights.
# Equivalent here to tril(ones(6, 6)), with device/dtype inherited safely.
mask_simple = torch.tril(torch.ones_like(attn_weights))
print(mask_simple)
tensor([[1., 0., 0., 0., 0., 0.],
        [1., 1., 0., 0., 0., 0.],
        [1., 1., 1., 0., 0., 0.],
        [1., 1., 1., 1., 0., 0.],
        [1., 1., 1., 1., 1., 0.],
        [1., 1., 1., 1., 1., 1.]])

The diagonal stays one: the current input is allowed. The zeros above it exclude future key/value positions. This mask is a fixed positional rule, not a learned parameter.

# Element-wise multiplication: each weight meets the mask at the same [i, j].
masked_weights = attn_weights * mask_simple  # [6, 6] * [6, 6] -> [6, 6]
print(masked_weights[1])  # Position 2, Python index 1.
tensor([0.2041, 0.1659, 0.0000, 0.0000, 0.0000, 0.0000],
       grad_fn=<SelectBackward0>)

Use * for this mask, not @

weight * 1 keeps that entry; weight * 0 removes that entry. The mask acts cell by cell. @ performs matrix multiplication, combining multiple entries, so attn_weights @ mask_simple would not implement this mask even though its output would also be [6, 6].

3. Divide each row by its own remaining sum

Row 2 now sums to about 0.3700, rather than one. Dividing each retained entry by that total makes its weights approximately [0.5517, 0.4483, 0, 0, 0, 0].

# Sum across columns separately for each query row.
row_sums = masked_weights.sum(dim=-1, keepdim=True)  # [6, 6] -> [6, 1]
causal_weights = masked_weights / row_sums         # [6, 6] / [6, 1] -> [6, 6]
print(causal_weights[1])
print(causal_weights.sum(dim=-1))
tensor([0.5517, 0.4483, 0.0000, 0.0000, 0.0000, 0.0000],
       grad_fn=<SelectBackward0>)
tensor([1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000],
       grad_fn=<SumBackward1>)

keepdim=True keeps one sum per row in a column-shaped tensor. PyTorch broadcasts each [6, 1] denominator across its matching row. Without it, the sums would have shape [6]; division would align those six numbers with the six columns instead, silently dividing along the wrong axis in this square example.

The first row becomes [1, 0, 0, 0, 0, 0]. The last row stays mathematically unchanged because it had no future positions to remove. Only the permitted values will contribute when we later multiply causal_weights @ values.

Does the first softmax leak future information?

Future scores initially affect the softmax denominator, but renormalizing cancels that shared denominator. For query position 2, suppose the exponentiated scores are 2, 3, and 5:

                          Position 1   Position 2   Position 3
                          (allowed)    (allowed)    (future)
                          ----------   ----------   ----------
Exponentiated scores          2            3            5
Softmax: divide by 10          0.2          0.3          0.5
Apply mask                    0.2          0.3          0
Renormalize: divide by 0.5     0.4          0.6          0

For position 1, (2 / 10) / (5 / 10) = 2 / 5 = 0.4. Excluding the future position from the start also gives [2 / 5, 3 / 5] = [0.4, 0.6]. The future score's contribution to the denominator cancels; its value receives zero weight. This equivalence holds in exact arithmetic, assuming the allowed query/key/value vectors have not already absorbed future information elsewhere.

The displayed numbers are rounded; calculations use full precision. Printed grad_fn labels can vary by PyTorch version. This post-softmax demonstration also inherits the numerical limitation described above: extreme scores can leave a retained row sum of zero through underflow. The next approach will mask scores before softmax.

Mask scores before softmax: the shorter route

Figure 3.21 combines exclusion and normalization in a simpler order: replace future scores with negative infinity → scale and apply softmax. Softmax exponentiates each score; exp(−∞) is zero, so those positions contribute nothing to either the numerator or denominator. The permitted positions receive a normalized distribution immediately.

Future score entries are replaced with negative infinity, then scaling and row-wise softmax produce causal weights with zeros at future positions. No second normalization is needed.

Original companion diagram inspired by Figure 3.21 in Raschka's book. Shows row 2 of the same seeded V2 example, rounded for display. The mask marks positions; masked_fill changes the scores at those positions.
Mark the future with torch.triu

triu means upper triangle. This time, one means “exclude this position,” whereas one in our earlier lower-triangular mask meant “keep this position.” The meaning follows from how we use the mask.

# Reuse attn_scores [6, 6] from the preceding calculation.
# diagonal=1 starts one diagonal ABOVE the main diagonal: self stays allowed.
future_mask = torch.triu(torch.ones_like(attn_scores), diagonal=1).bool()
print(future_mask)
tensor([[False,  True,  True,  True,  True,  True],
        [False, False,  True,  True,  True,  True],
        [False, False, False,  True,  True,  True],
        [False, False, False, False,  True,  True],
        [False, False, False, False, False,  True],
        [False, False, False, False, False, False]])

.bool() converts the zeros and ones into False and True. masked_fill replaces each score where the mask is True and leaves the other scores alone:

# -torch.inf is negative infinity; float("-inf") expresses the same value.
# This returns a new tensor; attn_scores and future_mask remain unchanged.
masked_scores = attn_scores.masked_fill(future_mask, -torch.inf)
print(masked_scores[1])
tensor([0.4656, 0.1723,   -inf,   -inf,   -inf,   -inf],
       grad_fn=<SelectBackward0>)

We are replacing scores, not turning the mask itself into the attention weights. Nor are we multiplying scores by negative infinity.

One softmax now does the normalization
# Query/key width = 2. Dividing -inf by this positive scale leaves -inf.
masked_attn_weights = torch.softmax(
    masked_scores / keys.shape[-1] ** 0.5, dim=-1
)
print(masked_attn_weights[1])
print(torch.allclose(masked_attn_weights.sum(dim=-1), torch.ones_like(row_sums[:, 0])))
print(torch.allclose(masked_attn_weights, causal_weights))
tensor([0.5517, 0.4483, 0.0000, 0.0000, 0.0000, 0.0000],
       grad_fn=<SelectBackward0>)
True
True

The first check verifies that every row sums to approximately one. The second compares against our earlier mask-and-renormalize result. The permitted mixture is the same; the separate row-sum division is gone. These are attention probabilities over input positions, not next-token probabilities over the vocabulary.

Why negative infinity, not zero?

A zero score still contributes exp(0) = 1 to softmax. Negative infinity contributes zero, so the masked position receives exactly zero weight. Each row must still have at least one finite allowed score: a row consisting entirely of -inf is not a valid softmax distribution and can produce NaNs. Keeping the diagonal permits at least the current position in this causal mask, assuming its score is finite.

We can now form contexts using the same value projection as before:

values = sa_v2.W_value(book_inputs)             # [6, 2]
causal_contexts = masked_attn_weights @ values  # [6, 6] @ [6, 2] -> [6, 2]

Every output row mixes only past and current values. No extra normalization follows softmax, and no parameter update has occurred. This is the score-masking approach used in our Character Logs attention implementation. Section 3.5.1 is now covered; the next subsection introduces dropout as a training regularizer to help reduce overfitting.

3.5.2 Masking additional attention weights with dropout

Causal masking answers which positions may this query use? Dropout adds a different restriction during training: randomly leave out some of those permitted contributions on this forward pass. This is a regularization technique: it can help reduce overfitting by discouraging the model from relying too heavily on particular combinations of activations. It does not guarantee better generalization on every dataset.

The familiar description is “drop hidden units.” More precisely, nn.Dropout temporarily zeros elements of the tensor it receives. Here that tensor contains attention weights after softmax, not hidden layers or learned projection parameters. WQ, WK, and WV remain trainable parameters; the attention weights are computed from the current inputs and those parameters. Dropout adds no learned parameters and does not permanently delete anything.

The book describes two places to apply dropout around attention:

Placement What gets zeroed in our single-sequence example?
After softmax, before mixing values Entries in the attention-weight matrix [T, T]: row = query position, column = contributing value position.
After mixing the value vectors Coordinates of the context vectors [T, d_out]: row = position, column = output feature.

We follow the first placement here. These are different operations, not interchangeable ways of selecting the same contributions. For our six-token example, the flow is:

causally masked scores [6, 6]
    → row-wise softmax
    → attention weights [6, 6]
    → dropout during training
    → weights [6, 6] @ values [6, 2]
    → context vectors [6, 2]

Four-position example: causal attention weights, one illustrative keep-or-drop mask, and the dropout result. Future positions stay zero; dropped allowed entries become zero; survivors double at dropout probability one half.

Original companion illustration inspired by Figure 3.22 in Raschka's book. Uses four positions and deliberately chosen weights and mask for readable arithmetic, not the book's seeded output. Unlike a picture showing only which connections disappear, this includes PyTorch's scaling of surviving weights.

What does a 50% dropout rate mean?

With p=0.5, each entry independently has a 50% probability of being zeroed. A particular matrix need not lose exactly half its entries; a short row can lose every allowed contribution. Future entries were already zero because of causal masking, so the visible fraction of additional zeros is not necessarily 50% either.

For 0 <= p < 1, PyTorch scales each surviving entry by 1 / (1 - p) during training. At p=0.5, the scale factor is 2. (The special case p=1 drops every entry instead.) For one possible mask:

Attention weights:       [0.20, 0.30, 0.50, 0.00]  sum = 1.00
Keep (1) / drop (0):     [   1,    0,    1,    0]
After dropout and ×2:    [0.40, 0.00, 1.00, 0.00]  sum = 1.40

Scaling is not row renormalization

In Section 3.5.1 we divided by the retained row sum to produce a distribution over permitted positions. Dropout instead uses the fixed factor 1 / (1 - p). We do not renormalize afterward. Rows can sum to more or less than one, and a surviving weight can exceed one. Each entry's expected value is preserved: 0.5 × 0 + 0.5 × (2 × a) = a. For example, a weight of 0.3 becomes either 0 or 0.6, with equal probability, so its expected value remains 0.3. For fixed value vectors, this also preserves the expected weighted sum before subsequent nonlinear operations. This is an average over random masks, not a promise about each individual output row or the full model output.

Try nn.Dropout on ones first

The book starts with ones so the zeros and scaling are easy to see:

import torch

# A newly created nn.Dropout module starts in training mode.
torch.manual_seed(123)
dropout = torch.nn.Dropout(p=0.5)
example = torch.ones(6, 6)
dropped_example = dropout(example)
print(dropped_example)

Every output entry is either 0 (dropped) or 2 (kept and scaled). The shape stays [6, 6]. The seed makes a demonstration repeatable in the same environment; the exact random pattern can differ across PyTorch versions or devices, so compare the behavior rather than requiring the book's precise mask.

Is the book's dropout reproducibility issue resolved?

As checked on November 1, 2026, PyTorch issue #121595, opened by Raschka, remains open. The discussion traced the reported CPU discrepancy to different Bernoulli sampling implementations in builds with and without Intel's Math Kernel Library (MKL). Those implementations can produce different masks from the same seed. Operating system alone is therefore not the whole explanation. Maintainers consider this permitted behavior under PyTorch's reproducibility policy: identical seeds do not guarantee identical results across builds, platforms, devices, or releases. A different zero pattern does not by itself mean dropout is incorrect; the drop probability and survivor scaling are the behavior to check.

Applied to the causal weights from Section 3.5.1:

# Reuse masked_attn_weights [6, 6] and values [6, 2].
torch.manual_seed(123)
dropped_weights = dropout(masked_attn_weights)
training_contexts = dropped_weights @ values  # [6, 2]

The dropout mask is applied to attention weights after softmax, even though Figure 3.22 uses “attention scores” in one annotation. These are the computed mixing coefficients, not the raw query–key scores or learned projection matrices. Causal zeros remain zero: neither dropping nor scaling can create a future contribution. Randomly dropped entries remove individual query-to-value contributions on this pass; they do not remove entire tokens from every query.

Training mode and evaluation mode

Dropout is used during training and disabled for ordinary evaluation and generation. With nn.Dropout, call model.eval() on the containing model (or dropout.eval() for this standalone demonstration). The module then returns its input unchanged, with no extra scaling. model.train() enables it again. torch.no_grad() controls gradient tracking; it does not switch dropout off.

dropout.eval()
print(torch.equal(dropout(masked_attn_weights), masked_attn_weights))  # True
dropout.train()  # Restore training mode for subsequent demonstrations.

See the PyTorch nn.Dropout documentation for its elementwise probability, scaling, and evaluation behavior.

Did our earlier experiments use dropout?

Our earlier experiments did not use dropout. Character Logs deliberately omitted it for simplicity; we have not compared training with and without dropout to determine whether it would help either experiment. Its absence from the pre-book introduction was a simplification, not evidence that small datasets do not need dropout.

The Character Logs notes record that choice. Its learned parameters and computed attention weights are still separate concepts; causal masking alone is not dropout.

Our Cosmopedia attention implementation calls F.scaled_dot_product_attention(query, key, value, is_causal=True) without a dropout argument. That function's default is dropout_p=0.0, so it also trains without attention dropout. Neither model adds dropout to the context vectors or feedforward layers.

One API distinction for later: the functional attention call uses its explicit dropout_p argument even in evaluation mode. If we add dropout there, we must pass zero during evaluation ourselves; nn.Dropout handles its mode switch automatically. See PyTorch's functional attention documentation.

3.5.3 Implementing a compact causal attention class

This is another building block: the earlier self-attention class, now with causal masking and dropout, plus support for batches. The projections, scaled query–key scores, softmax, and weighted sum of values retain their familiar roles. Packaging these pieces together gives us the single head we will later extend to multi-head attention.

Add a batch axis

Chapter 2's data loader produces batches, not just one sequence at a time. To make the new dimension visible, the book duplicates the same six-token example. Reuse our book_inputs tensor for “Your journey starts with one step”:

batch = torch.stack((book_inputs, book_inputs), dim=0)
print(batch.shape)
torch.Size([2, 6, 3])
One sequence: [   6, 3]   → six tokens, three coordinates each
Batch:        [2, 6, 3]   → two sequences, six tokens each, three coordinates each
               B  T  d_in

stack introduces the new axis at position zero. The duplicate sequences make this demonstration easy to compare; real batches can contain different sequences. Both examples use the same learned projection parameters, but attention mixes positions only within each example. Nothing in this calculation allows one batch example to attend to the other.

Put causal masking and dropout into the class

The following adapts Listing 3.3 from Raschka's book and Chapter 3 code, with type hints and shape comments. We store the mask as a Boolean tensor from the start, rather than converting the book's numeric mask to Boolean in each forward pass. The exclusion rule is unchanged: True means a future position.

CausalAttention — one head, with a batch dimension
import torch
from torch import nn


class CausalAttention(nn.Module):
    """Batched single-head attention with a causal mask and weight dropout."""

    mask: torch.Tensor

    def __init__(
        self,
        d_in: int,
        d_out: int,
        context_length: int,
        dropout: float,
        qkv_bias: bool = False,
    ) -> None:
        """Create projections and a fixed mask for up to context_length tokens.

        d_in is input-vector width; d_out is query/key/value-vector width.
        dropout is the probability of zeroing each attention-weight entry.
        """
        super().__init__()
        self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
        self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
        self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
        self.dropout = nn.Dropout(dropout)
        self.register_buffer(
            "mask",
            torch.triu(
                torch.ones(context_length, context_length, dtype=torch.bool),
                diagonal=1,
            ),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Map floating-point vectors [B, T, d_in] to contexts [B, T, d_out].

        B = batch examples; T = tokens per example, with 1 <= T <= the
        configured context_length. x and the module must share a device.
        Inputs are embedded vectors, not integer token IDs. Attention never
        mixes examples. Forward computes outputs without updating parameters.
        """
        num_tokens = x.shape[1]
        keys = self.W_key(x)      # [B, T, d_out]
        queries = self.W_query(x)  # [B, T, d_out]
        values = self.W_value(x)  # [B, T, d_out]

        # Keep B in front: transpose token and feature axes only.
        # [B, T, d_out] @ [B, d_out, T] -> [B, T, T]
        attn_scores = queries @ keys.transpose(1, 2)
        attn_scores.masked_fill_(
            self.mask[:num_tokens, :num_tokens], -torch.inf
        )
        attn_weights = torch.softmax(
            attn_scores / keys.shape[-1] ** 0.5, dim=-1
        )
        attn_weights = self.dropout(attn_weights)
        return attn_weights @ values  # [B, T, T] @ [B, T, d_out]

Compared with our single-sequence SelfAttention_v2, three details deserve attention:

  • keys.transpose(1, 2) changes [B, T, d_out] into [B, d_out, T]. It preserves the batch axis; .T is not the right way to transpose just the last two axes of this three-dimensional tensor.
  • The stored mask has shape [context_length, context_length]. Slicing selects [T, T] for the current sequence length, and broadcasting applies that same causal rule to each of the B examples. The class expects sequences no longer than its configured context length.
  • masked_fill_ changes the newly computed score tensor in place; the trailing underscore marks that behavior. It does not change the learned matrices or the stored mask. Dropout then acts on the weights after softmax, before the value mixture.

Why register the mask as a buffer?

The mask is model state, but not a trainable parameter. register_buffer makes PyTorch manage it alongside the model: ca.to(device) moves the registered mask with the parameters, and the mask is included in ca.state_dict() by default. It is not included in ca.parameters(), and this Boolean mask is not learned by gradient updates. See PyTorch's buffer documentation.

This connects to moving a camera frame onto the GPU before processing it. The model and tensors participating in these operations must be on compatible devices, but they do not all move through the same call:

Tensor How it moves to the selected device
Input frame or embedded batch Move it explicitly: batch = batch.to(device).
Learned projection parameters ca.to(device) moves them.
Registered causal-mask buffer The same ca.to(device) call moves it too.
Tensor stored as an ordinary attribute ca.to(device) does not automatically move it.

A buffer does not move the input for us

Registering the mask avoids manually moving that internal tensor whenever the model moves. The incoming batch remains our responsibility. Calling ca(batch) does not automatically copy a CPU batch to the GPU. The mask's registration also does not add it to the set of trainable projection parameters.

Instantiate the head and inspect its output

As before, constructing the object initializes its parameters; calling the object runs the calculation:

torch.manual_seed(123)
d_in, d_out = 3, 2
context_length = batch.shape[1]  # 6 token positions, not batch size 2
ca = CausalAttention(d_in, d_out, context_length, dropout=0.0)
context_vecs = ca(batch)
print("context_vecs.shape:", context_vecs.shape)
context_vecs.shape: torch.Size([2, 6, 2])

ca(batch) calls the module with batch as its input; it is not an attribute lookup such as ca.batch. PyTorch routes the call through the module machinery to forward.

The input is [B, T, d_in] = [2, 6, 3]; the output is [B, T, d_out] = [2, 6, 2]. We still have two sequences and six token positions in each. Each token's new context vector has two coordinates because we selected d_out=2. “Three-dimensional tensor” describes the three axes; it does not mean that each token still has three coordinates. These are computed context vectors, not new entries written into the token embedding table.

The book uses dropout=0.0 here, so no entries are randomly dropped even though the dropout layer is present. For the identical inputs, the two output slices match. With nonzero dropout during training, independently sampled masks can make those slices differ even for identical inputs.

Where we are: from simplified attention to multiple heads

Four-stage attention roadmap. Simplified attention uses input vectors directly; trainable self-attention introduces learned query, key, and value projections; the current causal head adds batches, a causal mask, and dropout; multi-head attention is the next reading step.

Original companion roadmap inspired by Figure 3.23 in Raschka's book. The highlighted stage is our current single causal head. The final stage previews Section 3.6 below, where we implement both the wrapper and grouped multi-head versions.

Did our earlier experiments already use multiple heads?

Our memory of the experiments fits the code and recorded configurations:

Experiment Transformer blocks Attention heads per block Representation width
Character Logs 1 1 32 coordinates
Cosmopedia 4 4 256 coordinates total; 64 per head

Cosmopedia's recorded 1,000-step run configuration confirms four heads and four layers; these are not just unused defaults. Its code reshapes projected vectors into four heads, performs causal attention, combines their outputs, and applies an output projection. Both experiments omit dropout, as discussed above.

Heads and blocks count different things. Within one block, heads compute different attention mixtures alongside one another. Blocks are applied in sequence: the output of one becomes the input to the next. Four blocks with four heads each does not mean one attention operation with sixteen heads. Our next reading step will unpack how the multiple heads are implemented.

3.6 Extending single-head attention to multi-head attention

We have one causal attention head. The next step is to apply several heads to the same input and combine their outputs. Each head has its own learned query, key, and value projections, giving it a different way to compare positions and prepare the information it mixes.

The book develops this in two stages: first an intuitive wrapper containing several instances of CausalAttention, then an implementation that groups the head computations more efficiently. We will follow that order as we read.

Single head does not mean a sequential loop through tokens

Our single-head class already calculates the scores for all query positions together. Causal masking restricts which positions each query can use; it does not require computing one context vector after another during this full-sequence forward pass. “Multiple heads” means multiple sets of projections and attention mixtures, not a change from sequential token processing to parallel token processing.

3.6.1 Stacking multiple single-head attention layers

Read Figure 3.24 as two branches from the same input

The figure shows two attention calculations, not two different input sequences. Both heads receive the same input matrix X. We do not divide the sentence so that head 1 gets some tokens and head 2 gets the rest, and the attention operation does not overwrite the input embeddings.

The same six-by-three input branches into two causal attention heads. Each owns three learned projection matrices, computes its own queries, keys, values, scores and weights, and produces six-by-two context vectors. Joining the outputs along the feature axis gives six-by-four contexts.

Original companion diagram inspired by Figure 3.24 in Raschka's book. Shows one sequence; a batch adds the same leading B axis to the computed tensors. The example output coordinates are deliberately illustrative, not results computed from specified projection matrices. Shapes and the concatenation are exact for two heads of width two.

Follow the two branches:

Object Head 1 Head 2
Input The same X [6, 3] The same X [6, 3]
Learned projections WQ1, WK1, WV1 Separate WQ2, WK2, WV2
Computed queries, keys, values Q₁, K₁, V₁: each [6, 2] Q₂, K₂, V₂: each [6, 2]
Computed scores and attention weights Each [6, 6] Each [6, 6]
Output context vectors Z₁ [6, 2] Z₂ [6, 2]

There are six learned projection matrices in total: three per head. In the mathematical X @ W convention, each is [3, 2]; an nn.Linear(3, 2) stores its weight as [2, 3] and handles the transpose. These stored parameters are distinct from Q₁/Q₂ and the other projected activations, and from the attention-weight matrices computed for this input.

Each head uses its own Q and K to compute scores, then applies the same causal rule, scaling, and softmax. If dropout is enabled during training, its random mask is sampled for each head's calculation and can differ between heads. The resulting weights mix that head's own V into its context matrix Z. The heads can therefore produce different contexts for the same token; independence does not guarantee that they learn different roles or assign them predefined jobs.

Combine the contexts for the same position

The fifth row in the book is one highlighted example, not the only row being processed. Each head produces a context for every token position. To combine them, join the corresponding rows along the feature axis:

Illustrative position 5:
Head 1 context:  [ 0.20, 0.80]
Head 2 context:  [-0.40, 0.60]
Combined:       [ 0.20, 0.80, -0.40, 0.60]

All positions:  Z₁ [6, 2] and Z₂ [6, 2] → concatenate → Z [6, 4]
With a batch:   [B, 6, 2] and [B, 6, 2] → [B, 6, 4]

Here “combine” means concatenate, not elementwise addition or averaging. The number of token positions stays six; each output vector becomes wider. In this example each head contributes two coordinates, so two heads contribute four coordinates altogether. Our original diagram uses its own illustrative numbers to make that joining step explicit.

Stacked heads are not successive transformer blocks

The book draws heads stacked on top of one another; our companion figure places them side by side. In both layouts, they are parallel branches of the same attention operation. Head 2 receives X, not Z₁. Transformer blocks instead run in sequence, as in our four-block Cosmopedia model. The simple wrapper may call heads one after another in Python; that execution order does not make one head depend on another head's output.

Implement the wrapper with nn.ModuleList

Listing 3.4 puts the branches into a small class. Reuse our CausalAttention class from Section 3.5.3. This adapts the official Chapter 3 implementation, with type hints and explicit axis descriptions:

MultiHeadAttentionWrapper — separate heads, joined outputs
class MultiHeadAttentionWrapper(nn.Module):
    """Run separate causal heads on the same input and concatenate features."""

    def __init__(
        self,
        d_in: int,
        d_out: int,
        context_length: int,
        dropout: float,
        num_heads: int,
        qkv_bias: bool = False,
    ) -> None:
        """Create num_heads heads; d_out is the output width of EACH head."""
        super().__init__()
        self.heads = nn.ModuleList(
            [
                CausalAttention(
                    d_in, d_out, context_length, dropout, qkv_bias
                )
                for _ in range(num_heads)
            ]
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Map floating vectors [B, T, d_in] to [B, T, num_heads * d_out].

        B = batch examples; T = token positions. Input length must fit the
        heads' context_length, and x must share the module's device/dtype.
        Each head produces [B, T, d_out]. Concatenation joins the last axis;
        it preserves the batch and token axes and adds no separate head axis.
        """
        return torch.cat([head(x) for head in self.heads], dim=-1)

The constructor's list comprehension creates a new CausalAttention instance on each iteration. Each instance owns its own projection parameters. We are not calling the same head repeatedly or resetting the seed before each head.

nn.ModuleList registers the heads as child modules. This lets the wrapper's .parameters(), .to(device), .eval(), and .state_dict() reach them. A plain Python list would not register its contents with those model-management operations. ModuleList does not choose a computation order or combine outputs itself; our forward method does that.

In forward, [head(x) for head in self.heads] produces a Python list of output tensors. torch.cat(..., dim=-1) joins the existing last dimension. This differs from torch.stack, which introduced the new batch axis earlier. The wrapper calls heads one after another in Python; their input dependencies are parallel branches, but this implementation does not explicitly compute all heads together in one grouped operation.

Figure 3.25: two coordinates per head become four per token

Two heads each produce a six-row, two-column context matrix for one sentence. The two matrices concatenate along columns into a six-row, four-column result. Both sentences in the duplicated batch get this calculation, giving output shape two by six by four.

Original companion illustration inspired by Figure 3.25 in Raschka's book. Shows one batch item's six token rows, using the verified wrapper output below, rounded to four decimals. The colors track which two columns come from each head. The batch axis is preserved; it does not count heads.

Which width does d_out mean here?

In this wrapper's constructor, d_out=2 is per-head width. Each Z₁ or Z₂ therefore has two columns per token. The concatenated Z has four columns: num_heads * d_out = 2 * 2. Keep the per-head width and the combined width separate when reading the figure's dimension labels.

Instantiate the wrapper and inspect the result

We reuse batch with shape [2, 6, 3]: two copies of “Your journey starts with one step.” Like the book, we set dropout to zero for this demonstration.

torch.manual_seed(123)
context_length = batch.shape[1]  # 6 tokens, not 2 batch examples
d_in, d_out = 3, 2
mha = MultiHeadAttentionWrapper(
    d_in, d_out, context_length, dropout=0.0, num_heads=2
)
context_vecs = mha(batch)
print(context_vecs)
print("context_vecs.shape:", context_vecs.shape)
tensor([[[-0.4519,  0.2216,  0.4772,  0.1063],
         [-0.5874,  0.0058,  0.5891,  0.3257],
         [-0.6300, -0.0632,  0.6202,  0.3860],
         [-0.5675, -0.0843,  0.5478,  0.3589],
         [-0.5526, -0.0981,  0.5321,  0.3428],
         [-0.5299, -0.1081,  0.5077,  0.3493]],

        [[-0.4519,  0.2216,  0.4772,  0.1063],
         [-0.5874,  0.0058,  0.5891,  0.3257],
         [-0.6300, -0.0632,  0.6202,  0.3860],
         [-0.5675, -0.0843,  0.5478,  0.3589],
         [-0.5526, -0.0981,  0.5321,  0.3428],
         [-0.5299, -0.1081,  0.5077,  0.3493]]], grad_fn=<CatBackward0>)
context_vecs.shape: torch.Size([2, 6, 4])

The model parameters are shared across batch examples. Because both inputs are identical and dropout is zero, the two output slices are identical too. This does not mean the two heads have identical outputs: within each token's four numbers, the first pair comes from head 1 and the second pair from head 2. Nonzero dropout during training can make duplicate batch examples produce different results.

Read [2, 6, 4] one axis at a time

context_vecs.shape = [2, 6, 4]
                     │  │  └─ coordinates per token: 2 heads × 2 coordinates
                     │  └──── token positions in each sentence
                     └─────── sentence examples in the batch
Axis Size What it counts
0: batch 2 Two copies of the input sentence. This is not the number of heads.
1: token position 6 Your, journey, starts, with, one, step.
2: combined features 4 Two coordinates from head 1 followed by two from head 2.

Think of the output as two tables, each with six rows and four columns. Each table belongs to one sentence, each row belongs to a token, and the four columns hold the concatenated context vector for that token. The tensor has three axes; each token's vector has four coordinates. It contains 2 * 6 * 4 = 48 scalar values altogether.

For the first sentence's first token, the actual row is:

Token: “Your”
Head 1 supplies: [-0.4519, 0.2216]
Head 2 supplies: [ 0.4772, 0.1063]
Joined vector:  [-0.4519, 0.2216, 0.4772, 0.1063]

We can select those pieces without changing the tensor:

print(context_vecs[0].shape)         # [6, 4]: first sentence's table
print(context_vecs[0, 0].shape)      # [4]: its first token's vector
print(context_vecs[0, 0, :2])        # first token, head 1's two coordinates
print(context_vecs[0, 0, 2:])        # first token, head 2's two coordinates
print(context_vecs[1, 0])            # same token in the duplicate sentence

Two different counts happen to equal two here: batch size is two, and head count is also two. Their equality is coincidental. Concatenation incorporates the head outputs into the feature axis, so there is no separate head axis in the final [2, 6, 4] tensor. These are context-vector coordinates, not vocabulary probabilities or a newly stored token embedding table.

Exercise 3.2: Returning two-dimensional embedding vectors

The book asks us to adjust the MultiHeadAttentionWrapper call so that each token's final context vector has two coordinates instead of four, while keeping num_heads=2 and leaving the class implementation unchanged.

The key is that this wrapper's d_out argument controls each head's output width, not the combined width:

Combined width = number of heads × dout

  1. The preceding example uses two heads with d_out=2, giving 2 × 2 = 4 coordinates per token.
  2. To obtain two coordinates while keeping two heads, set d_out=1, giving 2 × 1 = 2.

Reuse the existing batch, whose input shape remains [2, 6, 3]:

# Only the per-head output-width argument changes from the earlier call.
torch.manual_seed(123)
mha_two_dim = MultiHeadAttentionWrapper(
    d_in=3,
    d_out=1,
    context_length=batch.shape[1],
    dropout=0.0,
    num_heads=2,
)
context_vecs_two_dim = mha_two_dim(batch)
print("context_vecs.shape:", context_vecs_two_dim.shape)
context_vecs.shape: torch.Size([2, 6, 2])

Each head now produces [2, 6, 1]. Concatenating along the last axis gives [2, 6, 2]: two sentences, six token positions each, and two coordinates per token.

For one token:
Head 1:  [a]
Head 2:  [b]
Joined:  [a, b]

Input width and output width are different choices

d_in=3 still describes the three coordinates in each input vector. We keep that argument because the input batch has not changed. d_out=1 changes the learned projection sizes inside each newly created head. The resulting two coordinates are newly computed using those narrower projections; they need not equal the first two coordinates from the earlier four-coordinate result.

The exercise changes only a constructor argument. The existing wrapper already concatenates any compatible per-head output widths; its implementation needs no edit. The more efficient grouped implementation is the next reading step.

3.6.2 Implementing multi-head attention with weight splits

The wrapper made the structure visible: create several CausalAttention objects, call each on the same input, then concatenate their outputs. The integrated class expresses the head calculations together in larger tensors. We retain separate learned projections for each head, but store them inside larger query, key, and value layers instead of separate head objects.

There are two different kinds of work here:

  • Linear projections and attention calculate new values. Learned matrices produce Q, K, and V; attention computes scores, weights, and weighted mixtures.
  • Reshaping and transposing organize those values. They expose a head axis and put it in the right place for batched matrix multiplication. They do not introduce new learned parameters or change a coordinate's numerical value by themselves.

First, notice the change in what d_out means

The wrapper and integrated class use d_out differently

In MultiHeadAttentionWrapper, d_out meant width per head. In the integrated MultiHeadAttention, it means total output width across all heads. The new class computes head_dim = d_out // num_heads, so d_out must be divisible by num_heads.

For the same two-head, two-coordinates-per-head layout:

Class Constructor arguments Width per head Combined width
MultiHeadAttentionWrapper d_out=2, num_heads=2 2 4
MultiHeadAttention d_out=4, num_heads=2 2 4

Setting d_out=2 in the new class instead gives one coordinate per head and a combined width of two, like the target shape in Exercise 3.2. The argument's meaning changed; keep that distinction in mind while following the shapes.

The integrated class, with each shape change spelled out

The following adapts Listing 3.5 from Raschka's Chapter 3 implementation. We add type hints, separate the value mixture from its transpose for readability, and retain our Boolean mask from Section 3.5.3. The mathematical steps match the book's class.

For the concrete shape comments, choose B=2, T=6, d_in=3, total d_out=4, num_heads=2, and head_dim=2. Here B counts batch examples, T counts token positions, H counts heads, and D counts coordinates per head.

MultiHeadAttention — project together, split into heads
class MultiHeadAttention(nn.Module):
    """Causal multi-head attention with grouped projections and weight dropout."""

    mask: torch.Tensor

    def __init__(
        self,
        d_in: int,
        d_out: int,
        context_length: int,
        dropout: float,
        num_heads: int,
        qkv_bias: bool = False,
    ) -> None:
        """Configure positive widths/head count and a maximum context length.

        d_in is the input width; d_out is TOTAL output width across heads.
        Each head uses head_dim = d_out // num_heads coordinates for Q/K/V.
        """
        super().__init__()
        assert d_out % num_heads == 0, "d_out must be divisible by num_heads"
        self.d_out = d_out
        self.num_heads = num_heads
        self.head_dim = d_out // num_heads

        # One larger layer PER ROLE projects to every head's coordinates.
        # Each head still has its own rows in these stored weight tables.
        # Here each Linear stores [4, 3]; output activations are [B, T, 4].
        self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
        self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
        self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)

        # After concatenation, mix information across the joined head features.
        # Shape stays [B, T, d_out]. This Linear includes a bias by default;
        # qkv_bias controls only the three projection layers above.
        self.out_proj = nn.Linear(d_out, d_out)
        self.dropout = nn.Dropout(dropout)

        # True marks a future position; the diagonal remains permitted.
        # This fixed [context_length, context_length] rule moves with the model.
        self.register_buffer(
            "mask",
            torch.triu(
                torch.ones(context_length, context_length, dtype=torch.bool),
                diagonal=1,
            ),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Map floating vectors [B, T, d_in] to [B, T, d_out].

        B = batch examples; T = tokens; H = heads; D = head_dim.
        Require 1 <= T <= context_length and matching input/model device and
        floating dtype. Learned parameters are shared across B and T. Neither
        batch examples nor heads mix during the attention calculation itself.
        The final output projection mixes head features within each position.
        """
        b, num_tokens, _ = x.shape

        # 1. PROJECT: each role gets all H * D coordinates in one operation.
        # [B, T, d_in] -> [B, T, d_out], e.g. [2, 6, 3] -> [2, 6, 4].
        keys = self.W_key(x)
        queries = self.W_query(x)
        values = self.W_value(x)

        # 2. EXPOSE HEADS: split the last axis into H groups of D coordinates.
        # [B, T, H * D] -> [B, T, H, D], e.g. [2, 6, 4] -> [2, 6, 2, 2].
        # view adds no parameters and performs no new projection arithmetic.
        keys = keys.view(b, num_tokens, self.num_heads, self.head_dim)
        queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
        values = values.view(b, num_tokens, self.num_heads, self.head_dim)

        # 3. GROUP BY HEAD: swap token axis 1 with head axis 2.
        # [B, T, H, D] -> [B, H, T, D]. B and each coordinate's identity stay.
        # Each [T, D] slice now holds one head's vectors for one example.
        keys = keys.transpose(1, 2)
        queries = queries.transpose(1, 2)
        values = values.transpose(1, 2)

        # 4. COMPARE: transpose only K's last two axes, leaving B/H untouched.
        # [B, H, T, D] @ [B, H, D, T] -> scores [B, H, T, T].
        # Matrix multiplication operates on the last two axes independently
        # for each (example, head) pair. Here scores have shape [2, 2, 6, 6].
        attn_scores = queries @ keys.transpose(2, 3)

        # Slice the common [T, T] causal rule for the current sequence length.
        # It broadcasts across BOTH B and H, hiding the future in every head.
        mask_bool = self.mask[:num_tokens, :num_tokens]
        attn_scores.masked_fill_(mask_bool, -torch.inf)

        # Scale by sqrt(D), not sqrt(total d_out): dot products use D features.
        # Softmax runs over the last axis: contributing key/token positions.
        # Dropout acts on the computed weights, not the learned weight tables.
        attn_weights = torch.softmax(attn_scores / keys.shape[-1] ** 0.5, dim=-1)
        attn_weights = self.dropout(attn_weights)

        # 5. MIX VALUES within each head, then put token positions first again.
        # [B, H, T, T] @ [B, H, T, D] -> [B, H, T, D].
        head_contexts = attn_weights @ values
        context_vec = head_contexts.transpose(1, 2)  # [B, T, H, D]

        # 6. JOIN HEAD FEATURES: [B, T, H, D] -> [B, T, H * D].
        # Transpose can leave non-contiguous storage. contiguous() makes the
        # layout suitable for this view; it preserves the logical values.
        context_vec = context_vec.contiguous().view(b, num_tokens, self.d_out)

        # 7. OUTPUT PROJECTION: learned mixing of the concatenated features.
        # [B, T, d_out] -> [B, T, d_out]; no mixing of token/batch positions.
        context_vec = self.out_proj(context_vec)
        return context_vec

The stored projection weights are trainable parameters. Q/K/V, scores, attention weights, and contexts are computed activations. The causal mask is a fixed buffer. The view and transpose calls create no new trainable objects.

Follow one projected vector through the split

Suppose one token's already-projected query is [10, 11, 20, 21]. These invented numbers isolate the arrangement; they are not measured outputs from our model.

Before the split:  [10, 11, 20, 21]   four projected query coordinates
After the split:  [[10, 11],         head 1's two coordinates
                   [20, 21]]         head 2's two coordinates

Every head's projection was calculated from the full input vector. We group the resulting coordinates; we do not give different heads different subsets of the original sentence or require them to ignore original input features. The same arrangement applies separately to queries, keys, and values.

After view, the axes read [example, token, head, coordinate]. After transpose(1, 2), they read [example, head, token, coordinate]. That makes the final two dimensions a [T, D] matrix for each example/head pair, exactly what the attention matrix multiplication needs. Both shapes happen to be [2, 6, 2, 2] and [2, 2, 6, 2] in our chosen example, but the axis meanings are more important than their sizes.

Stage General shape Our two-head layout
Input vectors [B, T, d_in] [2, 6, 3]
Projected Q, K, V Each [B, T, H * D] [2, 6, 4]
Expose the head axis with view Each [B, T, H, D] [2, 6, 2, 2]
Group by head with transpose(1, 2) Each [B, H, T, D] [2, 2, 6, 2]
Scores and attention weights [B, H, T, T] [2, 2, 6, 6]
Each head's contexts [B, H, T, D] [2, 2, 6, 2]
Put token axis back first [B, T, H, D] [2, 6, 2, 2]
Join head features [B, T, H * D] [2, 6, 4]
Apply the output projection [B, T, d_out] [2, 6, 4]

view changes the shape while sharing storage and requires a compatible memory layout. transpose swaps two axes; for these dense tensors it also shares storage. After the return transpose, contiguous provides a contiguous layout when needed so we can merge the adjacent head/coordinate axes with view. None of these operations learns how to split the heads; the learned projections determine their features.

The new output projection is an additional operation

The wrapper returned the concatenation directly. This class also applies out_proj, a learned linear layer across the combined feature coordinates. It can mix information from different heads while preserving [B, T, d_out]. “The same concept” refers to the per-head attention structure; it does not promise the same final numbers from the two classes. Matching numerical results would require compatible widths and projection parameters, and accounting for this additional output layer. A shared random seed alone does not do that.

This is the same grouping idea already used by our Cosmopedia attention implementation. Cosmopedia goes one step further by computing all three Q/K/V projections in a combined linear layer and using PyTorch's functional attention operation. Here we keep the three roles and explicit attention steps visible while learning their arrangement. We have not measured a speedup for this book implementation.

Figure 3.26: one larger projection, then expose the heads

The general idea is exactly this: pack the separate heads' projection weights into one larger matrix, multiply once, then organize the projected coordinates into heads. The figure shows queries only; we do the same thing separately for keys and values.

Separate query projections use the same input X with two three-by-two matrices to produce Q1 and Q2, each six by two. The grouped version packs the weights side by side into a three-by-four matrix and multiplies X once to obtain six-by-four Q. Its first two columns are Q1 and last two are Q2. The split rearranges the projected coordinates without further projection arithmetic.

Original companion diagram inspired by Figure 3.26 in Raschka's book. Shows one sequence with six positions, input width three, and two query coordinates per head. Uses the mathematical XW convention, so weights are [input width, output width]; nn.Linear stores their transposes. Matching colors identify the same parameter blocks and output coordinates in the two arrangements.

In mathematical notation, placing the two weight blocks side by side gives:

WQ = [WQ1 | WQ2]
⇒ XWQ = [XWQ1 | XWQ2] = [Q1 | Q2]

The vertical bars mark column boundaries, not an operation that mixes the heads. If the parameter blocks have the same values as the separate matrices, the projected queries match, up to floating-point rounding. Reshaping then exposes those column groups as a head axis. A newly initialized larger layer is not guaranteed to match two independently initialized smaller layers merely because the seed is the same.

For the six-token example:

Arrangement Query projections Query result
Separate heads Two products: [6, 3] @ [3, 2], one for each head Two [6, 2] matrices
Grouped heads One product: [6, 3] @ [3, 4] One [6, 4] matrix, containing the two heads' columns

Each head still has its own learned query parameters. We have 12 query-weight entries either way: 2 * (3 * 2) separately, or 3 * 4 together, excluding biases. Grouping does not force the heads to share the same projection or reduce the total feature width.

A small hand-worked example makes the equality tangible. For one invented input vector and two illustrative projection matrices:

x = [1, 2, 3]

       W_Q1              W_Q2
       [1, 0]            [ 2, 0]
       [0, 1]            [ 0, 2]
       [1, 1]            [-1, 1]

x W_Q1 = [1 + 3, 2 + 3]        = [ 4, 5]
x W_Q2 = [2 - 3, 4 + 3]        = [-1, 7]

Pack their columns into W_Q:
       [1, 0 |  2, 0]
       [0, 1 |  0, 2]
       [1, 1 | -1, 1]

x W_Q = [4, 5 | -1, 7]
Split = head 1 [4, 5], head 2 [-1, 7]

Here the code-style names are readable text equivalents of the subscripted mathematical symbols. The numbers illustrate the projection identity; they are not outputs from a trained experiment.

A larger multiplication still has a cost

The benefit is not that matrix size stops mattering. For these matching shapes, the basic scalar arithmetic is comparable; we express it in fewer, larger operations. That can reduce per-operation overhead and give optimized CPU/GPU matrix routines a larger amount of work to process efficiently. The actual speed depends on dimensions, device, and implementation. We have verified the projection identity, not measured a speedup for this example.

In PyTorch storage order, packing two nn.Linear(3, 2) query weights means stacking their [2, 3] weight tables along dimension zero to form [4, 3]. That is the transpose of placing [3, 2] mathematical matrices side by side. This storage convention explains how the single larger W_query layer represents both heads; view and transpose then arrange its output as [B, H, T, D] for attention.

Batched matrix multiplication: one score matrix per head

The book next isolates the matrix multiplication with a small tensor. This example changes the sizes from our earlier walkthrough: one batch example, two heads, three token positions, and four coordinates per token per head. The supplied numbers illustrate the operation; they are not trained-model results.

# Example from Section 3.6.2 of the book: [B, H, T, D] = [1, 2, 3, 4].
a = torch.tensor([
    [
        [
            [0.2745, 0.6584, 0.2775, 0.8573],
            [0.8993, 0.0390, 0.9268, 0.7388],
            [0.7179, 0.7058, 0.9156, 0.4340],
        ],
        [
            [0.0772, 0.3565, 0.1479, 0.5331],
            [0.4066, 0.2318, 0.4545, 0.9737],
            [0.4606, 0.5159, 0.4220, 0.5786],
        ],
    ]
])

# Swap token and coordinate axes; preserve batch and head axes.
result = a @ a.transpose(2, 3)
print(result)
print("result.shape:", result.shape)
tensor([[[[1.3208, 1.1631, 1.2879],
          [1.1631, 2.2150, 1.8424],
          [1.2879, 1.8424, 2.0402]],

         [[0.4391, 0.7003, 0.5903],
          [0.7003, 1.3737, 1.0620],
          [0.5903, 1.0620, 0.9912]]]])
result.shape: torch.Size([1, 2, 3, 3])

The multiplication acts on the last two axes; the leading batch/head axes identify which matrices belong together:

a:                    [1, 2, 3, 4]
a.transpose(2, 3):    [1, 2, 4, 3]
result:               [1, 2, 3, 3]
                       B  H  T  T

For each (batch example, head): [3, 4] @ [4, 3] → [3, 3]

We see two matrices in the printout because there are two heads. They are two [3, 3] slices inside one [1, 2, 3, 3] tensor, not two separate returned tensors. Each score compares a pair of token vectors within that head. There are no comparisons between head 1 and head 2.

For instance, the first entry of the first head's result is its first token vector dotted with itself:

0.2745² + 0.6584² + 0.2775² + 0.8573² ≈ 1.3208

Check the same calculation one head at a time

The book then unpacks the grouped operation. Once we select a single example and head, we have an ordinary two-dimensional matrix, so .T is appropriate:

first_head = a[0, 0, :, :]   # [3, 4]
first_res = first_head @ first_head.T

second_head = a[0, 1, :, :]  # [3, 4]
second_res = second_head @ second_head.T

print("First head:\n", first_res)
print("Second head:\n", second_res)
print("Head 1 matches:", torch.allclose(result[0, 0], first_res))
print("Head 2 matches:", torch.allclose(result[0, 1], second_res))
First head:
 tensor([[1.3208, 1.1631, 1.2879],
        [1.1631, 2.2150, 1.8424],
        [1.2879, 1.8424, 2.0402]])
Second head:
 tensor([[0.4391, 0.7003, 0.5903],
        [0.7003, 1.3737, 1.0620],
        [0.5903, 1.0620, 0.9912]])
Head 1 matches: True
Head 2 matches: True

This demonstrates the multiplication, not the full attention output

The example multiplies a by its own transpose to make the mechanics visible. In the attention class, the corresponding line is queries @ keys.transpose(2, 3): Q and K have compatible shapes but generally different values. The example's matrices are dot-product results, not normalized attention weights or context vectors. Scaling, causal masking, softmax, dropout, and the value mixture are separate steps. These self-dot-product matrices are symmetric; real query–key score matrices need not be.

Join the head contexts, then learn how to mix their features

After the attention-weight/value multiplication, the contexts from all heads are stored together with shape [B, H, T, D]. Selecting one head gives [B, T, D]. The return transpose changes that to [B, T, H, D], putting all of one token's head vectors together. The final reshape joins its head/coordinate axes:

Head contexts:      [B, H, T, D]
Transpose back:    [B, T, H, D]
Join head features: [B, T, H * D] = [B, T, d_out]
Output projection:  [B, T, d_out]

The last dimension is combined feature width, d_out = H * D, not the token count T. Joining preserves the batch size and token positions. The distinction between joining and projecting is the new point here:

  • Concatenation places the head outputs side by side. In our two-head, width-two example, [a, b] and [c, d] become [a, b, c, d]. It introduces no learned parameters.
  • The output projection, self.out_proj = nn.Linear(d_out, d_out), applies a learned transformation to that combined vector. Each output coordinate can use coordinates from all heads. Its parameter matrix and bias are shared across batch examples and token positions.

For one token, PyTorch evaluates:

zout = zjoined WoutT + bout

Here W_out denotes the layer's stored [d_out, d_out] weight table, following nn.Linear storage order. This projection changes values while keeping the same vector width. It mixes features within a position; the attention calculation before it is what mixed information across permitted token positions.

A small numerical illustration uses two head outputs [1, 2] and [10, 20]. Choose an output matrix that takes sums and differences across their corresponding coordinates, and a zero bias:

# Deliberately chosen demonstration weights, not trained model parameters.
joined = torch.tensor([1.0, 2.0, 10.0, 20.0])
projection = nn.Linear(4, 4)
with torch.no_grad():
    projection.weight.copy_(torch.tensor([
        [1.0, 0.0,  1.0,  0.0],
        [0.0, 1.0,  0.0,  1.0],
        [1.0, 0.0, -1.0,  0.0],
        [0.0, 1.0,  0.0, -1.0],
    ]))
    projection.bias.zero_()

projected = projection(joined)
print(projected.detach())
tensor([ 11.,  22.,  -9., -18.])

The four calculations are 1 + 10, 2 + 20, 1 - 10, and 2 - 20. We still have four coordinates, but their values combine information from both heads. In the model, training determines the projection's weights and bias; these hand-picked sums and differences only illustrate what a linear projection can do.

What does ‘not strictly necessary’ mean?

The attention mechanism already produces usable context vectors after concatenating heads, as our wrapper demonstrated. An output projection is therefore not required just to obtain a valid attention result or join the heads. The author includes it so this class also has the learned output-mixing step commonly used in Transformer attention. ‘For completeness’ means completing that architectural pattern. We have not measured the contribution of this layer in isolation. Appendix B is the author's reference for further discussion.

Neither concatenation nor this per-position linear projection introduces future-token access: they combine features already produced for that same position. Both our Character Logs and Cosmopedia attention implementations also include an output projection, as their source code shows.

Run the integrated class on our two-sentence batch

We can instantiate MultiHeadAttention and call it just like the earlier attention modules. The class defined here applies causal masking; the familiar call pattern does not turn it into unmasked attention.

The book returns to a tiny total output width of two, so the printed values remain readable. With two heads, each head has one query/key/value coordinate:

torch.manual_seed(123)
batch_size, context_length, d_in = batch.shape
d_out = 2
mha = MultiHeadAttention(
    d_in, d_out, context_length, dropout=0.0, num_heads=2
)
context_vecs = mha(batch)
print(context_vecs)
print("context_vecs.shape:", context_vecs.shape)
tensor([[[0.3190, 0.4858],
         [0.2943, 0.3897],
         [0.2856, 0.3593],
         [0.2693, 0.3873],
         [0.2639, 0.3928],
         [0.2575, 0.4028]],

        [[0.3190, 0.4858],
         [0.2943, 0.3897],
         [0.2856, 0.3593],
         [0.2693, 0.3873],
         [0.2639, 0.3928],
         [0.2575, 0.4028]]], grad_fn=<ViewBackward0>)
context_vecs.shape: torch.Size([2, 6, 2])

The input shape is [2, 6, 3] and the output is [2, 6, 2]. Both sentence examples receive identical outputs here because the inputs are duplicated, the parameters are shared, and dropout is zero. Unlike the wrapper, this class's d_out directly specifies the final width. Its output projection is included in the values above. Printed backward-function labels can differ between PyTorch versions.

The author calls the integrated implementation more efficient because it expresses the head projections as one larger multiplication per role, rather than one per role per head in a Python loop. Grouping also lets the attention products operate over the batch/head axes together. This is an implementation advantage, not a speed measurement from our companion examples.

From readable toy widths to GPT-2-sized attention

The small widths let us inspect complete tensors; the same class can use larger dimensions. The book contrasts two GPT-2 configurations:

Configuration Heads Total representation width Coordinates per head
Smallest GPT-2 12 768 768 / 12 = 64
Largest GPT-2 25 1,600 1600 / 25 = 64

In these GPT-2 configurations, the input and output representation widths match: d_in = d_out. This lets attention fit into the surrounding transformer architecture without changing the width at every block. Our tiny teaching examples used unequal input/output widths to make the roles visible. The smallest configuration's 768-coordinate width, 12 heads, and 1,024-token context are also recorded in OpenAI's original GPT-2 defaults.

Exercise 3.3: Initializing GPT-2 size attention modules

The book asks us to initialize one MultiHeadAttention module with the smallest GPT-2 model's 12 heads, 768-coordinate inputs and outputs, and maximum context length of 1,024 tokens.

The total width divides evenly across the heads:

Coordinates per head = 768 ÷ 12 = 64

Use those values in the existing constructor; the class implementation needs no change:

torch.manual_seed(123)
gpt2_attention = MultiHeadAttention(
    d_in=768,
    d_out=768,
    context_length=1024,
    dropout=0.0,
    num_heads=12,
)

print("num_heads:", gpt2_attention.num_heads)
print("head_dim:", gpt2_attention.head_dim)
print("query weight shape:", gpt2_attention.W_query.weight.shape)
print("mask shape:", gpt2_attention.mask.shape)
num_heads: 12
head_dim: 64
query weight shape: torch.Size([768, 768])
mask shape: torch.Size([1024, 1024])

Each Q/K/V layer maps 768 input coordinates to 768 projected coordinates. Reshaping groups those projected coordinates into 12 heads of width 64. After attention, the heads join back into 768 coordinates and pass through the 768-to-768 output projection.

A maximum context length is not a required batch length

context_length=1024 allocates the causal-mask capacity. A call can use a shorter sequence, with the mask sliced to its actual token count T. The expected input/output shapes are [B, T, 768] for 1 <= T <= 1024. The constructor does not create a 1,024-token input batch by itself.

This initializes one attention module with random parameters, using the requested head count, widths, and context capacity. Dropout is set to zero for the exercise, and Q/K/V bias follows our class's default. Matching these dimensions does not load pretrained weights or construct the complete GPT-2 model. The full architecture also needs the surrounding embeddings, transformer blocks, and output layers.

End of chapter

Chapter 3 reading is complete. The book's summary brings the attention mechanisms together; our companion now traces the progression from a single dot product to the causal multi-head module that the next chapter will place inside GPT.

The main distinctions to carry forward:

  • Attention produces context vectors by mixing information from accessible positions. In the simplified example, the input vectors supply both the comparisons and the information being mixed. In trainable attention, learned projections separate those roles into queries, keys, and values.
  • Scores, attention weights, and model parameters are different objects. A query–key dot product produces a raw score. Scaling by the square root of the key width and applying softmax produces attention weights. Those weights mix the values; the stored projection matrices are the parameters training can update.
  • Matrix multiplication packages many dot products and weighted sums. It replaces explicit loops with grouped operations. In [B, H, T, D] tensors, the last two axes participate in each matrix product, while the leading axes identify independent example/head calculations.
  • Causal masking restricts information flow. Each position may use itself and earlier positions. Replacing future scores with negative infinity before softmax gives those positions zero weight; ordinary full-sequence training can still compute all query positions together.
  • Dropout is a training-time regularizer with a different purpose from causal masking. It randomly zeros attention-weight entries and scales survivors, preserving their expected values rather than renormalizing each realized row. Evaluation disables it in our nn.Dropout layers.
  • Multiple heads give separate learned projections and mixtures for the same input. Concatenating head outputs joins their coordinates; the output projection learns how to mix those features. Heads within a block are different from transformer blocks applied one after another.
  • The wrapper and weight-split class express the same per-head attention idea in different arrangements. Larger projection layers pack the head parameters together; view and transpose arrange the projected activations. The integrated class also includes the output projection, and its d_out means total width across heads.

The exercises check three concrete details: transfer transposed projection weights between implementations, choose per-head width for a desired combined output, and initialize a GPT-2-sized attention module. The companion examples verify these calculations; they do not claim a new training run or benchmark.

Chapter 2 gave us embedded inputs. Chapter 3 supplied the attention building block. Chapter 4 will assemble the surrounding GPT architecture, including normalization, shortcut connections, and feedforward layers. Our pre-book experiments already contain those pieces; the reading will unpack their design in the same step-by-step way.