esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

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.

12 min readIntermediateCommon · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

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.

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.

Key words

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. 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. 2

    Add and normalise

    The attention output is added to the block's input, then layer normalisation evens out the numbers.

  3. 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. 4

    Add and normalise again

    The feed-forward output is added back to its input and normalised once more.

  5. 5

    Pass it up

    The block's output has the same shape as its input, so the next block can take it straight away.

Inside one decoder block

Token vectors in

one vector per word piece

1. Look back

Masked attention

each token sees itself and earlier ones

Add and normalise

adds the input back, evens out numbers

2. Think per token

Feed-forward network

same small network for every token

Add and normalise

adds back again, then normalises

Block output

same shape, goes to the next block

  1. 1Each token's vector enters the attention step.
  2. 2The attention output is added to the input, then normalised.
  3. 3The result goes to the feed-forward network.
  4. 4Each token's result is added back in, then normalised.
  5. 5The block's output goes up to the next 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.

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.

What the word 'pipe' can see

Row for 'pipe'

Burst

earlier word: visible

pipe

its own word: visible

kitchen

later word: masked out

Softmax weights

0.41 for Burst, 0.59 for pipe

Weights add to 1

kitchen gets no weight

  1. 1The score for Burst goes into the softmax.
  2. 2The score for pipe goes in too. The later word is never scored.
  3. 3The two weights add up to one, so the result is a weighted mix of the visible words.
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.

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

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. 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. 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. 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. 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."

    BetterThe mask stops a token from seeing the words it predicts. Remove it and training cheats.

  • Trap"Layer norm and attention do the same job."

    BetterAttention mixes information between tokens. Normalisation only rescales each token's numbers.

  • Trap"The feed-forward network looks at the other tokens."

    BetterIt 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?

Quick check

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

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q063Masked vs causal language modelling?11 min
  2. Q066Attention masks and padding?Coming soon
  3. Q068How does the final hidden state become the next token?9 min
  4. Q074What uses memory at inference time?11 min
  5. Q049Encoder-only vs decoder-only vs encoder-decoder?11 min

Learn it in depth

Last updated on 26 November 2026

Building an agent that reads notes, claims or contracts?

I design and build AI products and agents, including the model side and the system around it. Book a short call and tell me what your model needs to read and write.