# Walk Through One Decoder Block

> How one decoder block passes text along: masked attention, a feed-forward network and two add-and-normalise steps, explained for your AI interview.

**In short:** A decoder block takes one vector per token and returns vectors of the same shape. In the 2017 design, it runs masked self-attention, so each token sees only itself and earlier tokens, then a feed-forward network, with an add-and-normalise step after each part.

AI and LLM interview question Q073, Transformer architecture. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/walk-through-one-decoder-block-forward-pass

## Say it in 30 seconds

A decoder block takes one vector for each token and gives back vectors of the same shape. First, masked self-attention lets each token look only at itself and the tokens before it. I add the input back and normalise the numbers. Next, a feed-forward network works on each token separately, and I add and normalise again. The output goes up to the next block. A model is a stack of these blocks, and the last one helps predict the next token.

## Say it in 2 minutes

Start with what goes in. A language model cuts text into tokens, which are word pieces, and gives each token a vector of numbers. A decoder block takes that set of vectors and returns a set of the same shape. Many blocks are stacked, and each one refines the vectors a little more. The last vectors decide the next token.

Inside one block there are two parts, and each part gets a residual connection. That means the layer adds its input back to its result, so the input is kept and the layer only adds to it. Layer normalisation then evens out the numbers. The first part is masked self-attention. Each token looks at itself and the tokens before it, never the ones after. The mask is what lets the model write left to right.

The second part is a feed-forward network. It is a small network that runs on each token separately, so no token looks at another in this step. The block then passes its output up to the next block. Newer designs, such as Pre-LN, put the normalisation before each part, and a 2020 study found that this keeps gradients well-behaved at the start of training.

If I were asked to walk through it, I would use a claims example. A note reads "Burst pipe, kitchen, Tuesday night", and the model predicts the next word. At each step, a word can see the words before it, but never the words it is about to predict. That rule is the core of the decoder block.

## What is one decoder block, in plain words?

A decoder block is one layer in the stack that a text generator runs. It takes a vector for each token, which is a list of numbers that stands for that word piece, and it hands back vectors of the same shape for the next layer.

Think of a claims adjuster on a long file. She reads the notes in order. For each note she checks it against the notes she has already read, and she never peeks at notes further down the pile. Then she writes a short view and passes the file on. A decoder block makes the same kind of pass, once per layer, with numbers instead of paper.

In a real tool, a claims triage agent might read "Burst pipe, kitchen, Tuesday night" and must guess the next word of its summary. It can use only the words it has read so far, and the block is what enforces that rule.

The design comes from the 2017 paper Attention Is All You Need. That paper had an encoder and a decoder. GPT-2 is a causal transformer language model built from decoder layers.

- **Token:** A word piece, the unit a model reads. A word can be one token or several.
- **Self-attention:** A step where each token looks at the other tokens in the same text to decide what matters.
- **Residual connection:** A shortcut that adds a step's input back to its output, so the input is kept and the step only adds a change to it.
- **Layer normalisation:** A step that rescales each token's numbers so they stay in a steady range.

## What happens inside one decoder block, step by step?

In the 2017 layout, every token goes through the same five steps. The first two make up the attention part. The next two make up the feed-forward part. The last one hands the result on.

1. **Masked self-attention:** Each token scores how much it should look at the tokens up to and including itself. The mask blocks every later token, so scores for future words never count.
2. **Add and normalise:** The attention output is added to the block's input, then layer normalisation evens out the numbers.
3. **Feed-forward network:** A small two-step network runs on each token separately. It gives each token a fresh mix of its own features, with no token looking at another.
4. **Add and normalise again:** The feed-forward output is added back to its input and normalised once more.
5. **Pass it up:** The block's output has the same shape as its input, so the next block can take it straight away.

*Diagram, Inside one decoder block: In the 2017 layout, one decoder block, left to right. Each token enters the attention step, is added back and normalised, goes through the feed-forward network, and is added back and normalised again. The numbers on the arrows give the order.*
1. Each token's vector enters the attention step.
2. The attention output is added to the input, then normalised.
3. The result goes to the feed-forward network.
4. Each token's result is added back in, then normalised.
5. The block's output goes up to the next block.

The first line from the paper is about the mask. The second lists the parts of PyTorch's decoder layer.

> "We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions." (Vaswani et al., Attention Is All You Need (2017))
>
> "TransformerDecoderLayer is made up of self-attn, multi-head-attn and feedforward network." (PyTorch documentation, TransformerDecoderLayer)

The original paper's decoder also had a third step that reads the encoder's output. That step serves translation-style models that read one text and write another. Text generators like GPT-2 have no encoder, so they skip this step.

## Why is the attention step masked?

Without a mask, a token could read the very word it is supposed to predict, and the model would learn to copy instead of predict. The paper says the decoder must prevent leftward information flow to keep the auto-regressive property, which means each word is predicted from the words before it only.

The mask works on the grid of scores before softmax, the step that turns scores into weights. A masked score is set to minus infinity, so after softmax its weight is zero. The remaining weights add up to one. The paper describes this step as applying a softmax function to get the weights.

*Diagram, What the word 'pipe' can see: The word 'pipe' in a three-word claim note. Its own word and the word before it get scores. The word after it is masked out before softmax, so it gets no weight. The two weights add up to one.*
1. The score for Burst goes into the softmax.
2. The score for pipe goes in too. The later word is never scored.
3. The two weights add up to one, so the result is a weighted mix of the visible words.

Here is the attention step alone, in plain Python, with made-up vectors so the numbers are easy to check. It leaves out the feed-forward part and the add steps.

```python
# A made-up 3-word claim note: "Burst pipe kitchen". Each word scores only itself and the words before it.
import math

words = ["Burst", "pipe", "kitchen"]
q = [[1.0, 0.0], [0.5, 1.0], [0.0, 1.0]]
k = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
v = [[10.0, 0.0], [0.0, 10.0], [5.0, 5.0]]

def softmax(xs):
    e = [math.exp(x) for x in xs]
    return [x / sum(e) for x in e]

for i, word in enumerate(words):
    # Causal mask: word i looks only at positions 0 to i, the same as setting later scores to minus infinity.
    scores = [sum(a * b for a, b in zip(q[i], k[j])) / math.sqrt(2) for j in range(i + 1)]
    w = softmax(scores)
    out = [round(sum(w[j] * v[j][d] for j in range(i + 1)), 2) for d in range(2)]
    print(word, [round(x, 2) for x in w], out)
```

Output:

```text
Burst [1.0] [10.0, 0.0]
pipe [0.41, 0.59] [4.13, 5.87]
kitchen [0.2, 0.4, 0.4] [3.98, 6.02]
```

Read the middle row. 'pipe' gives 0.41 weight to 'Burst' and 0.59 to itself, and nothing to 'kitchen', which it can't see yet. The last row is 'kitchen', which can weigh all three words because it comes last.

## Where does the normalisation go, before or after?

The 2017 design put layer normalisation after each residual add. Many newer models put it before each part instead. A 2020 study explains why the choice matters for training. It looks at gradients, the signals that tell the model how to adjust its numbers during training.

> "for the original-designed Post-LN Transformer, which places the layer normalization between the residual blocks" (Xiong et al., On Layer Normalization in the Transformer Architecture (2020))
>
> "if the layer normalization is put inside the residual blocks (recently proposed as Pre-LN Transformer), the gradients are well-behaved at initialization" (Xiong et al., On Layer Normalization in the Transformer Architecture (2020))

- **After (original): Normalise after each add.** Gradients near the output are large at the start, so training needs a slow warm-up of the learning rate (the size of each adjustment step).
- **Before (newer): Normalise before each part.** Gradients behave well at the start. The study trained without the warm-up stage and still reached comparable results.

PyTorch has the same switch in its norm_first option. Set it to True and the layer norm runs before the attention and the feed-forward parts. Otherwise it runs after.

> **Tip:** Asked which to use? Say the before-layout (Pre-LN) starts training more steadily, then say the choice depends on the model you build and on your tests.

### How would you check that the mask is working?

A discharge-summary model scores far too well in tests. You suspect it can see the words it should predict. This is how I would check it.

1. **Pick a test note:** Take a clinical note from the test set and run it through the model. Save the output at every position.
2. **Change only a later word:** Edit a word near the end, such as a drug name in the last sentence, and run the model again.
3. **Compare the earlier positions:** Output at every earlier position must stay the same, within floating-point rounding, with dropout switched off. If an earlier position changes, a later word is leaking backwards, and the mask is broken.
4. **Fix in code, then rerun:** Check that the mask is applied before the softmax, then repeat the test. Keep this check in the test suite.

> **Tip:** A leak can make a score look great, so don't trust the score alone. Test the mask directly.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] The order: masked attention, add and normalise, feed-forward, add and normalise.
- [ ] Why the mask matters: a token must not see the words it predicts.
- [ ] Residual connections help the signal pass through a deep stack.
- [ ] Before-norm versus after-norm, with the trade-off.
- [ ] Input and output share a shape, so blocks stack.
- [ ] Why the feed-forward step runs per token: attention is the only place tokens meet.

**Common traps**

- Trap: "The mask is optional, the decoder reads the whole sentence." Better: The mask stops a token from seeing the words it predicts. Remove it and training cheats.
- Trap: "Layer norm and attention do the same job." Better: Attention mixes information between tokens. Normalisation only rescales each token's numbers.
- Trap: "The feed-forward network looks at the other tokens." Better: It works on each token on its own. Only the attention step lets tokens exchange information.

## Can you spot the mistake?

**Spot the mistake:** A colleague wrote this note about our decoder block. Which line is wrong?

A. Each token attends only to itself and earlier tokens.
B. The feed-forward network works on each token separately.
C. The mask lets a token look at the words that come after it.
D. A residual connection adds a sub-layer's input back to that sub-layer's output.

**Answer:** C. The mask does the opposite. It blocks later words, so the model can't copy the word it is meant to predict. The other three lines are correct.

**Quick check:** The attention scores let a word weigh a later word, which breaks training. What is the simplest fix?

A. Add more feed-forward layers
B. Set future scores to minus infinity before softmax
C. Raise the learning rate
D. Write a longer system prompt

**Answer:** B. A score of minus infinity becomes zero weight after softmax, so future words drop out. More layers, a faster learning rate or a longer prompt don't change which words a row can see.

## Can you answer these from memory?

**Flash cards**

- **What is the order inside a decoder block?** Masked attention, add and normalise, feed-forward, add and normalise.
- **What does the causal mask do?** Stops each token from weighing the tokens that come after it.
- **What is a residual connection?** A shortcut that adds a step's input back to its output.
- **What does the feed-forward network see?** Each token on its own. Tokens only mix in the attention step.
- **What changes in the before-norm layout?** Layer norm runs before each part, not after the add.
- **Does a decoder block change the shape?** No. Output has the same shape as input, so blocks stack.

## Likely follow-up questions

- Q063 Masked vs causal language modelling? https://designervenkat.online/interview/ai/masked-vs-causal-language-modelling
- Q066 Attention masks and padding? (full answer coming)
- Q068 How does the final hidden state become the next token? https://designervenkat.online/interview/ai/how-does-the-final-hidden-state-become-the-next-token
- Q074 What uses memory at inference time? https://designervenkat.online/interview/ai/what-uses-memory-at-inference-time
- Q049 Encoder-only vs decoder-only vs encoder-decoder? https://designervenkat.online/interview/ai/encoder-only-vs-decoder-only-vs-encoder-decoder

## Learn it in depth

- [Transformers](https://designervenkat.online/learn/machine-learning/transformers)
