Section 6 built one attention computation. This section assembles the full machine every model in this course actually is. Attention gets stacked into a repeating block. That block gets arranged in one specific shape: decoder-only, causally masked. Every deployed LLM uses that shape. By the end, "GPT-style" and "decoder-only Transformer" name the exact same design. You'll also know why that specific shape, and not the others, is what generation requires.
A Transformer block is one repeating station on a line of stations.
Each station does two things, in order. First, self-attention (Section
6) lets every token gather information from every other token. Second,
a feed-forward network -- an ordinary small network, the same kind
deep-learning's early chapters build -- handles each token's own
result a little further, on its own. Both steps are wrapped in a
residual connection. In other words: "add the station's own input
back onto its output." That's a backup. It guarantees information can
always flow straight through a station, even if that station's own work
turns out to add little. That turns out to matter a lot, once dozens of
stations are stacked back to back. A full model is just many of these
identical-shaped stations, chained together, each with its own
separately learned settings.
Before the very first station, positional encoding stamps a pattern based on position onto each token. Attention by itself genuinely cannot tell "the cat sat" from "sat the cat." Without this step, both would produce the identical set of attention outputs, just swapped. Multi-head attention means several attention computations run side by side, inside one station, instead of just one. Each one is free to form its own sense of "what matters." It's like having several readers pay attention to the same sentence in different, useful ways at once -- instead of forcing one single reading approach on everybody.
Masking, in other words: simply zero out certain attention weights, before they're ever used. Do this by making their score negative infinity, so softmax gives them exactly zero. A causal mask blocks every token from seeing anything that comes after it. Word 5 can only look at words 1 through 5, never word 6 onward. Here's why that specific rule defines almost every LLM you've ever used. Training a model to predict the next word IS its entire job. At the actual moment it has to generate word 6 for real, word 6 doesn't exist yet to peek at. So training it to peek during practice would teach a skill it could never actually use. A decoder-only model is simply a stack of Transformer blocks that all use this causal rule, with nothing else attached. That's specifically the shape of GPT, Claude, Llama, and almost every large language model you can talk to right now. (A model built to only read, not generate -- BERT is the classic example -- drops the causal mask and looks both directions at once instead. A model built to transform one complete text into another, like a program that translates, keeps both a reading half and a writing half. This course only ever wires up the kind built to write new text.)
Two last, practical terms this chapter has now set up. Context window is the maximum number of tokens a model can hold in view at once -- think of it as a fixed-size working memory. KV caching is a bookkeeping trick. It avoids working out every earlier word's key and value again from scratch, each time a new word appears. Both terms come back in Chapter 3, once the wiring -- not just the design -- is the point.
A Transformer block wraps self-attention (Section 6) around two more pieces. Each piece is guarded by a residual connection -- add the sublayer's input back to its output, so information always has a clear path through -- and a normalization step. Self-attention runs first. Then comes a position-wise feed-forward network: an ordinary two-layer network, applied the same way, independently, to every token's own vector. A full model stacks N of these identical-shaped blocks. Each block's output matches its input in shape. That's exactly what lets block k feed block k+1, with no reshaping anywhere in the stack. Before the first block, positional encoding adds a position-dependent pattern to each token's embedding. Attention alone has no notion of token order. Without positional encoding, "the cat sat" and "sat the cat" would produce identical attention outputs. Multi-head attention runs several independent attention computations in parallel, inside each block, each with its own learned projections. That lets different heads specialize in different kinds of connections (nearby words, long-range reference), rather than forcing one single notion of what matters onto the whole layer.
Masking, from Section 6's pipeline, steps in between the score and softmax steps. A disallowed position's score gets overwritten with -\infty before softmax runs, so it receives exactly zero attention weight. A causal mask disallows every query position i from attending to any key position j>i -- future tokens. A decoder-only model stacks Transformer blocks using causal self-attention at every layer, with no separate encoder and nothing to cross-attend to. This is the design behind almost every LLM in this course. The pretraining objective is next-token prediction (Section 2): predict token t from tokens 1,\ldots,t-1 only. Training the model to peek at token t while predicting it would teach a habit it can never use at real generation time, when later tokens don't exist yet. This is one of three model families built from the same block. Encoder-only models (bidirectional, no masking) are good at understanding a complete input. Encoder-decoder models (both halves) are good at transformation tasks like translation. But every model this course wires into a system is decoder-only.
Finally, a decoder-only model's context window is the fixed maximum number of tokens it can attend over at once. KV caching is the standard technique that makes generating one token at a time fast enough, within that window. Each position's key and value vectors get computed once, and reused for every later step -- rather than recomputed from scratch at each new token.
Step through one full decoder block, causally masked
Click Next repeatedly and watch the diagram highlight causal self-attention, the residual add, normalization, and the feed-forward network in order -- notice attention here only ever looks backward or at itself.
Loading interactive…
This section's own sentence, now causally masked
Click row 'I' first -- it can only attend to itself. Then click row 'love' and compare its weights to Section 6's unmasked version: the same relative preference for 'love' over 'I,' just renormalized over fewer allowed positions.
Loading interactive…
Worked example
Basic: what stays the same shape through the stack
-
1
A decoder block receives 3 token vectors, each 2-dimensional (this section's own running example). What is the shape of that block's output? Why does that matter for stacking N blocks?
-
2
Self-attention outputs one vector per input position, at the same size. The feed-forward network maps each token's vector to itself, at the same size, independently. Both residual adds are elementwise.
-
3
\boxed{\text{Still 3 vectors, each 2-dimensional}} -- identical shape in and out is exactly what lets block k's output feed directly into block k+1 with no reshaping, however many blocks are stacked.
Worked example
Typical: masking renormalizes, it doesn't just zero out
-
1
Section 6 computed query "love"'s unmasked attention weights as a_{\text{I}}\approx0.1978, a_{\text{love}}\approx0.4011, a_{\text{NLP}}\approx0.4011. Under a causal mask, "love" (position 2) cannot attend to "NLP" (position 3). Compute "love"'s masked weights.
-
2
Masking sets a_{\text{NLP}}'s score to -\infty before softmax, so it gets exactly 0 weight. But softmax's denominator only sums over the allowed positions. So a_{\text{I}} and a_{\text{love}} get rescaled to still sum to 1, between just the two of them: 0.1978/(0.1978+0.4011)\approx0.3303 and 0.4011/(0.1978+0.4011) \approx0.6697.
-
3
\boxed{a_{\text{I}}\approx0.3303,\ a_{\text{love}}\approx0.6697,\ a_{\text{NLP}}=0} -- the relative preference for "love" over "I" is preserved, just spread over fewer allowed positions. This is exactly the widget's own row above.
Worked example
Recognition: why decoder-only, not encoder-only, for generation
-
1
A team wants to build a system that generates open-ended text, one token at a time, in response to a prompt. Could an encoder-only model (BERT-style, bidirectional, no causal mask) do this job?
-
2
An encoder-only model's entire design assumes the full input is already available. It lets every position see every other position, forward and backward. There's no mechanism in it for producing a sequence of new tokens one at a time -- nothing constrains earlier positions to be predictable from only what came before them.
-
3
\boxed{\text{No -- generation specifically requires the causal restriction a decoder-only model is built around}}. Encoder-only models are excellent at classifying or embedding a complete, already-available piece of text. Open-ended generation is exactly the job decoder-only design exists for.
Where this goes next
Chapter 3, how an LLM generates text
Chapter 3 picks up exactly where this section stops. This section ends with a decoder-only model's next-token probability distribution, at each step. Chapter 3 asks: how does a real system turn that into actual generated text? It covers greedy decoding, temperature, and top-k and top-p sampling. It also shows how the context window and KV cache, named above, become real engineering limits -- once a system is serving that model at scale.
Check your understanding (counts toward your progress)
A model has masked self-attention plus a feed-forward network in every block, and no cross-attention sublayer anywhere. What does the absence of cross-attention tell you?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Encoder-only models also lack cross-attention -- but the causal MASKING described here is the decoder-only signature, not encoder-only.
Self-attention and cross-attention are independent features -- a model can use one, both, or neither.
Cross-attention's presence or absence directly signals a specific architectural choice (whether a separate encoder exists), not a random detail.
Why
Cross-attention only exists to let a decoder attend to a separate encoder's output -- its complete absence, combined with masked self-attention, is exactly the decoder-only architectural signature.
Cross-attention specifically requires a separate encoder to attend TO -- what does its total absence, combined with masked self-attention, imply?
What is a model's context window?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Training corpus size is a separate quantity from the context window, which is about a single forward pass's token limit.
Head count is a design choice unrelated to how many tokens fit in one attention computation.
Block count (stack depth) is a separate architectural choice from the token-length limit.
Why
The context window is the fixed maximum number of token positions a model can attend over in a single forward pass -- both the prompt and everything generated so far count against it.
Why is positional encoding needed at all, given that attention already exists?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Dot products don't depend on positional encoding -- they're computed from queries and keys regardless.
Softmax's operation has nothing to do with whether positional encoding was added.
Positional encoding is added ON TOP of token embeddings, not as a replacement for them.
Why
Self-attention by itself treats a sequence as an unordered set of tokens -- positional encoding injects order-dependent information before attention ever runs, so order actually matters to the computation.
What does multi-head attention change, compared to running one single attention computation?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
The heads use separately learned projections and run in parallel, not the same computation repeated sequentially.
Multi-head attention still uses softmax inside each head -- normalization itself is unchanged.
Every head still uses all three of queries, keys, and values -- keys aren't removed.
Why
Multi-head attention runs several attention computations side by side, each with independently learned projections, so different heads can specialize instead of forcing one single notion of relevance onto the whole layer.
Why does every block's output need to match its input in shape?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Shape-matching does make the residual add well-defined, but its broader purpose is enabling straightforward stacking of many blocks -- that's the point this section makes.
Unbounded shape growth would make stacking many blocks impossible without constant reshaping -- that's exactly what's avoided.
Every block in the stack preserves shape identically, not just the first one.
Why
Identical input/output shape at every block is exactly what lets an arbitrary number of blocks be stacked straight through, block after block, with no reshaping step required anywhere.
Think about what would have to happen between every pair of adjacent blocks if their shapes DIDN'T match.
What two sublayers does a Transformer block wrap self-attention around, in order?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Transformer blocks use no convolution or recurrence at all -- they're built entirely from attention and feed-forward layers.
A block uses one self-attention sublayer plus one feed-forward sublayer, not two attention layers.
The order is self-attention first, feed-forward second, not the reverse.
Why
A Transformer block is self-attention followed by a position-wise feed-forward network, each wrapped in its own residual connection and normalization step.
Why does a causal mask block query position i from attending to key position j > i?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Softmax is perfectly well-defined over any set of scores -- masking is a design choice about which positions SHOULD be allowed, not a mathematical necessity.
During training, every position's keys and values are computed -- masking specifically blocks access to already-computed future positions, it doesn't skip computing them.
Causal masking has a real effect on what the model learns to do -- it isn't just a speed optimization.
Why
At real generation time, tokens after the current position genuinely don't exist yet -- causal masking trains the model under the identical constraint it will face at inference, rather than letting it "cheat" during training in a way it structurally can't replicate later.
Think about what's true at TRAINING time (full sequence available) versus at ACTUAL GENERATION time (later tokens don't exist yet).
Check your understanding (counts toward your progress)
This section computed query "love"'s unmasked weights as approximately (0.20, 0.40, 0.40) over (I, love, NLP). Under a causal mask, what happens to those weights?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Masking changes the weights themselves, before the final output is even computed -- it isn't applied only afterward.
Masking doesn't force uniformity -- the RELATIVE preference between the still-allowed positions is preserved, just renormalized.
"Love" is the QUERY position here, attending over I and love -- it isn't the position being masked out; NLP (a future position relative to love) is what gets masked.
Why
Causal masking sets the disallowed position's score to -\infty, giving it exactly 0 weight after softmax, while renormalizing the remaining allowed weights so they still sum to 1 -- exactly this section's own worked computation.
Position 2 ("love") can only attend to positions 1 and 2 under a causal mask -- position 3 ("NLP") is in its future.
For a 6-token sequence under a causal mask, how many key positions can query position i = 4 attend to (count positions 1 through 4)?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Why
A causal mask allows attending to positions j \le i -- for i=4, that's positions 1, 2, 3, and 4: four allowed positions.
Correct answer
Also accepted:
Why
A causal mask allows query i to attend to keys j <= i.
Could an encoder-only model (bidirectional, no causal mask) generate open-ended text one token at a time the way a decoder-only model does?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
The two architectures differ specifically in masking and structure, and that difference is exactly what makes decoder-only generation possible and encoder-only generation not.
Head count doesn't address the structural issue -- encoder-only attention has no causal restriction at all, regardless of head count.
Parameter count isn't the limiting factor -- the architecture's masking (or lack of it) is.
Why
Open-ended generation specifically requires the causal restriction decoder-only models are built around; encoder-only models are built for a different job entirely (understanding a complete, already-available input).
Ask what mechanism decoder-only models have that lets them predict one new token at a time -- does encoder-only have an equivalent?
What problem does KV caching solve during autoregressive generation?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
KV caching is about computational efficiency within the existing context window -- it doesn't extend the window's actual limit.
Causal masking and KV caching are separate mechanisms -- caching doesn't remove the need for masking.
Block count is unaffected by caching -- every block still runs; caching avoids redundant re-computation within each block's attention.
Why
Without caching, generating each new token would recompute every earlier position's key and value vectors from scratch -- KV caching computes each position's key/value exactly once and reuses it, turning a wastefully repeated computation into an incremental one.
Think about what's identical between generating token 50 and generating token 49 a moment earlier -- what got computed both times, needlessly?
This section's decoder-only stack diagram ends by producing what, after the final block?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Classification labels are a different task (closer to what an encoder-only model produces), not what a decoder-only stack outputs at each step.
A decoder-only model doesn't perform translation as a distinct built-in output -- it produces a next-token distribution, one step at a time, regardless of the eventual task.
The stack transforms the input through every block -- its final output is a probability distribution over the next token, not an unchanged copy of the input.
Why
Every decoder-only model's stack ends the same way, regardless of what it's eventually used for: a next-token probability distribution, ready for Chapter 3's sampling strategies to turn into an actual chosen token.
An encoder-decoder model (like T5) and a decoder-only model can both technically be trained to translate a sentence, by giving the decoder-only model the source sentence as part of its prompt. What is the encoder-decoder version's structural advantage?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Decoder-only models routinely process multi-sentence prompts -- that's not the limitation here.
Encoder-decoder models DO use masking -- specifically causal masking in the decoder half, just not in the encoder half.
There is a genuine structural difference in how the (already fully available) source gets processed -- bidirectionally versus causally.
Why
An encoder-decoder's encoder reads the fully-known source bidirectionally, using its complete context from the start; a decoder-only model applies the SAME causal restriction to the source that it needs for generating the target, even though the source is already entirely available and doesn't need that restriction.
Compare how the SOURCE sentence specifically gets processed in each architecture -- is it read all at once, or one token at a time under a restriction?
Practice: The Transformer block, causal masking, and why LLMs are decoder-only (5 problems · doesn’t affect your progress)
A Transformer block's output always matches its input in what property?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Why
Every sublayer (self-attention, FFN) and every residual add preserves shape, which is exactly what lets many blocks stack without reshaping.
Shape
Without positional encoding, what would attention be unable to distinguish?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Why
Self-attention alone is permutation-equivariant -- it cannot tell one ordering of the same tokens from a different ordering without positional information added in.
Two different orderings of the identical set of tokens
Why is causal masking necessary for training a next-token-prediction model, specifically?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Why
Causal masking trains the model under the identical information constraint it faces at real generation time, when future tokens genuinely don't exist yet.
Because at real generation time, later tokens genuinely don't exist yet -- training must match that same constraint
For an 8-token sequence under a causal mask, how many key positions can query position i = 5 attend to?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Why
Positions j\le5 are allowed: 1, 2, 3, 4, 5 -- five positions.
Correct answer
Also accepted:
Why
A causal mask allows query i to attend to keys j <= i.
A model has bidirectional self-attention in every block and no causal mask anywhere. What is it most likely built for?
Right on try — credit. Right — the answer had already been shown, so no credit this time. Next try is worth Answer shown after three tries — this one no longer earns credit. You chose to see the answer — this one earns no credit.
Why
Bidirectional attention with no causal restriction is the encoder-only signature -- excellent for understanding a complete, already-available input, not built for open-ended generation.
No causal mask at all rules out one specific family this section names -- which one, and what is IT good at?
Understanding tasks over a complete input -- classification, tagging, embedding