Transformer Decoder Stack

Imagine a translation system that must produce French text one word at a time. Somehow it "knows" the full English sentence it is translating. Yet it never peeks at French words it has not generated yet. This is the exact problem the transformer decoder stack solves. It must condition on a complete source sequence. At the same time, it generates a target sequence strictly left to right. This respects causality during both training and inference. The decoder stack is the generative half of the original transformer. With cross-attention removed, it is also the entire architecture behind GPT-style autoregressive language models. Every large language model that writes text, one token after another, is fundamentally a stack of decoder layers. Understanding its internals means understanding how modern generative AI works. It shows how such models produce coherent, context-sensitive output token by token. The big picture is deceptively simple. Take the ingredients you already know: Masked Self-Attention, Residual Connections & Layer Normalization, and Position-Wise Feed-Forward Networks. Arrange them into a repeating block, stacked N times. Add one additional attention mechanism (cross-attention) when a source sequence must be consulted. The stack turns a sequence of previously generated tokens, plus an optional encoded source, into a probability distribution over the next token. This article gives a precise, step-by-step account of that block. It covers sublayer ordering, masking rules, and why residual paths and normalization make deep stacking trainable. It also covers the complexity of each operation. Finally, it explains how the same architecture specializes into two forms. One is the sequence-to-sequence decoder (with cross-attention) used in translation. The other is the decoder-only language model (without cross-attention) that underlies GPT and its descendants.

Key takeaways
  • A transformer decoder layer is masked self-attention, then (optionally) cross-attention, then a feed-forward network — each wrapped in a residual connection and layer normalization.
  • Masked self-attention enforces causality: position i can only attend to positions ≤ i, preserving valid left-to-right generation.
  • Cross-attention lets each decoder position query the encoder's output representations, fusing source-sequence information into target generation.
  • Stacking N identical layers builds up increasingly abstract, context-rich representations while residual paths keep gradients flowing across depth.
  • Per-layer time complexity is O(n²·d) for self-attention and O(n·m·d) for cross-attention, where n is target length, m is source length, d is model dimension.
  • Removing cross-attention yields the decoder-only architecture that powers GPT-family autoregressive language models.
The core insight

A transformer decoder stack repeatedly applies causally-masked self-attention, optional cross-attention to an encoded source, and a feed-forward network — each inside a residual-and-normalization wrapper — to convert previously generated tokens into a distribution over the next one.

The idea

A transformer decoder stack is a sequence of N identical decoder layers that transforms an embedded target sequence into contextual representations suitable for predicting the next token at every position simultaneously during training, and one token at a time during inference. Each decoder layer contains up to three sublayers: a masked (causal) self-attention sublayer, an optional cross-attention (also called encoder–decoder attention) sublayer, and a position-wise feed-forward network sublayer. Every sublayer is wrapped in a residual connection followed by layer normalization, so that the output of a sublayer is `LayerNorm(x + Sublayer(x))` (post-norm, as in the original transformer) or `x + Sublayer(LayerNorm(x))` (pre-norm, common in later models such as GPT-2 and beyond). The defining property of the decoder is the causal mask applied inside self-attention: when computing attention scores for target position i, all positions j > i are set to negative infinity before the softmax, so their attention weight becomes zero. This enforces the autoregressive property — the representation at position i depends only on tokens at positions 1 through i — which is exactly what is needed to train the model with teacher forcing on whole sequences in parallel while guaranteeing that at generation time the model never uses information it would not have during real left-to-right decoding. When the decoder is paired with an encoder (as in machine translation, summarization, or any conditional sequence-to-sequence task), a second attention sublayer, cross-attention, sits between the masked self-attention and the feed-forward sublayer. Here the queries come from the decoder's own (causally-masked) hidden states, but the keys and values come from the encoder's final output representations. This lets every decoder position "look at" the entire source sequence — with no masking, since the whole source is available — while still respecting causality among target tokens. Architectures that drop the encoder entirely and remove cross-attention, keeping only masked self-attention and the feed-forward sublayer, are called decoder-only models; this is the design used by GPT and virtually all modern large language models.

How it works

Step 1 — Input representation. The target sequence of tokens is mapped to embeddings and combined with positional encodings (sinusoidal or learned), since self-attention itself has no notion of order.

Step 2 — Masked self-attention sublayer. Each decoder layer first computes multi-head self-attention over the target sequence, with an upper-triangular mask that prevents attending to future positions. Formally, for queries Q, keys K, values V of dimension dkd_k per head,

Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V

where Mij=−∞M_{ij} = -\infty for j>ij > i and 00 otherwise. The additive mask is applied before the softmax so that masked entries become exactly zero after exponentiation.

Step 3 — Residual + normalization. The self-attention output is added back to its input and normalized: `x = LayerNorm(x + SelfAttn(x))`.

Step 4 — Cross-attention sublayer (if an encoder is present). Multi-head attention is computed again, but queries come from the current decoder state while keys and values come from the encoder's output `H_enc`. No causal mask is needed here, because the entire source sequence is legitimately visible at every decoding step.

Step 5 — Residual + normalization wraps the cross-attention sublayer exactly as in step 3.

Step 6 — Feed-forward sublayer. A position-wise two-layer MLP with a nonlinearity (ReLU or GELU) is applied identically and independently to each position, followed by another residual-and-normalization wrap.

Step 7 — Stack repetition. Steps 2–6 constitute one decoder layer; this block is repeated N times (N = 6 in the original transformer, tens to over a hundred in modern large models), with each layer's output feeding the next layer's input.

Step 8 — Output projection. The final layer's output is projected through a linear layer (often tied to the input embedding matrix) and a softmax to produce a probability distribution over the vocabulary for the next token, at every position. At inference time, generation is inherently sequential: the model produces one token, appends it to the input, and repeats — this is why efficient decoders cache previously computed keys and values (KV-caching) so each new token is generated in O(n) additional work rather than recomputing attention over the whole prefix from scratch. ``` function DECODER_LAYER(x, H_enc, use_cross_attention):

# x: [seq_len, d_model] target hidden states so far

# H_enc: [src_len, d_model] encoder output, or None for decoder-only

# 1. Masked self-attention sublayer a = MULTI_HEAD_ATTENTION(query=x, key=x, value=x, mask=CAUSAL_MASK(len(x))) x = LAYER_NORM(x + a)

# 2. Optional cross-attention sublayer if use_cross_attention and H_enc is not None: c = MULTI_HEAD_ATTENTION(query=x, key=H_enc, value=H_enc, mask=None) x = LAYER_NORM(x + c)

# 3. Position-wise feed-forward sublayer f = FEED_FORWARD(x) # Linear -> GELU/ReLU -> Linear, applied per position x = LAYER_NORM(x + f) return x

function DECODER_STACK(target_tokens, H_enc, num_layers, use_cross_attention): x = EMBED(target_tokens) + POSITIONAL_ENCODING(len(target_tokens)) for layer_index in 1..num_layers: x = DECODER_LAYER(x, H_enc, use_cross_attention) logits = LINEAR_PROJECTION(x) # [seq_len, vocab_size] return SOFTMAX(logits) # next-token distribution at each position

function CAUSAL_MASK(n): M = zero matrix of shape [n, n] for i in 1..n: for j in (i+1)..n: M[i][j] = -infinity return M

function GENERATE(H_enc, max_len, use_cross_attention): tokens = [START_TOKEN] kv_cache = {} # per-layer cached keys/values for generated prefix for step in 1..max_len: x = DECODER_STACK_STEP(tokens, H_enc, kv_cache, use_cross_attention) next_token = ARGMAX_OR_SAMPLE(x[-1]) # distribution at final position tokens.append(next_token) if next_token == END_TOKEN: break return tokens ``` The pseudocode's key correctness-critical detail is `CAUSAL_MASK`: it is strictly upper-triangular (excluding the diagonal), so position i attends to itself and all earlier positions, never later ones. Cross-attention deliberately passes `mask=None`, because masking the source would incorrectly hide legitimate context.

Figure
One decoder layer: masked self-attention, cross-attention, and feed-forward, each inside a residual + norm wrapper
Decoder Layer x (target states) Masked Self-Attention residual Add & Norm Cross-Attention (Q from x) Encoder output K, V (source) Add & Norm Feed-Forward (per position) Linear → GELU → Linear Add & Norm output → next layer (dashed = residual skip connection)

Complexity & correctness

Time complexity per layer. Let n be the target sequence length, m the source sequence length (when cross-attention is present), and d the model dimension.

  • Masked self-attention: computing QK⊤QK^\top costs O(n2d)O(n^2 d), since it is an n×dn \times d matrix times a d×nd \times n matrix; the softmax and weighted sum with V cost the same order. The causal mask itself is applied in O(n2)O(n^2) but does not change the asymptotic cost, which is dominated by the matrix multiplications.
  • Cross-attention: queries are n×dn \times d, keys/values are m×dm \times d, so the cost is O(nmd)O(n m d).
  • Feed-forward sublayer: applied independently per position with hidden width dffd_{ff} (typically 4d4d), costing O(n⋅d⋅dff)=O(nd2)O(n \cdot d \cdot d_{ff}) = O(n d^2) up to a constant factor.

Summing across N layers, total training-time (full-sequence, teacher-forced) complexity is

O(N⋅(n2d+nmd+nd2)).O\big(N \cdot (n^2 d + n m d + n d^2)\big).

Space complexity is dominated by the attention score matrices, O(n2)O(n^2) per head-batch for self-attention (or O(nm)O(nm) for cross-attention) plus O(nd)O(n d) for activations, per layer; with N layers and H heads this is O(NHn2)O(N H n^2) in the worst case if all intermediate score matrices are retained (as needed for backpropagation), though techniques like memory-efficient/FlashAttention-style kernels reduce the materialized memory to roughly O(n)O(n) per query block while preserving the same FLOP count.

Why parallel training is correct despite sequential generation. During training with teacher forcing, the entire target sequence is fed in at once and processed in parallel — this is only valid because the causal mask guarantees the representation and loss at position i are mathematically identical to what would be computed if the model had generated tokens 1,…,i−11, \dots, i-1 one at a time and only just now produced token i. Formally, define hi(ℓ)h_i^{(\ell)} as the hidden state at position i after layer ℓ\ell. The causal mask enforces

hi(ℓ)=f(h1(ℓ−1),…,hi(ℓ−1))h_i^{(\ell)} = f\big(h_1^{(\ell-1)}, \dots, h_i^{(\ell-1)}\big)

with no dependence on hj(ℓ−1)h_j^{(\ell-1)} for j>ij > i, by induction on layer depth ℓ\ell: the base case (ℓ=0\ell=0, the embeddings) trivially satisfies this, and each subsequent layer's masked self-attention plus position-wise feed-forward preserves the property, since attention weights to future positions are exactly zero and the feed-forward sublayer never mixes information across positions at all. This invariant is precisely what licenses computing an entire sequence's loss in one forward pass and matches token-by-token autoregressive generation.

Why residual connections and layer normalization make deep stacking trainable. Each sublayer computes x′=LayerNorm(x+Sublayer(x))x' = \text{LayerNorm}(x + \text{Sublayer}(x)). The additive residual term means the gradient of the loss with respect to xx contains an identity term:

∂L∂x=∂L∂x′⋅(I+∂Sublayer(x)∂x)\frac{\partial \mathcal{L}}{\partial x} = \frac{\partial \mathcal{L}}{\partial x'} \cdot \left( I + \frac{\partial \text{Sublayer}(x)}{\partial x} \right)

(up to the LayerNorm Jacobian, which is well-conditioned because normalization keeps activation statistics stable). This identity term guarantees gradients can flow unattenuated through arbitrarily many layers even if a particular sublayer's Jacobian is small, directly counteracting the vanishing-gradient problem that plagues naively stacked deep networks. Layer normalization additionally re-centers and re-scales each position's representation, keeping activation magnitudes stable regardless of depth, which stabilizes optimization and permits the large learning rates used in practice.

Tradeoffs. The quadratic O(n2)O(n^2) self-attention cost is the main scalability bottleneck for long sequences; cross-attention adds a further O(nm)O(nm) term that grows with source length. KV-caching removes redundant recomputation during generation but trades memory for speed, since keys and values for every previously generated token must be stored. Decoder-only models forgo the encoder and cross-attention entirely, saving computation and parameters, at the cost of needing to encode source and target in a single shared causal sequence (as GPT-style models do by concatenating prompt and continuation).

Worked example

Consider a tiny English-to-French translation setup with target-side vocabulary indices and a source sentence "the cat sat" already encoded by an encoder into Henc∈R3×dH_{enc} \in \mathbb{R}^{3 \times d}. We trace generation of the French translation "le chat s'est assis" one token at a time, focusing on what masked self-attention and cross-attention can see at each step.

StepTokens generated so far (decoder input)Self-attention can seeCross-attention keys/valuesNext token predicted
1``position 1 onlyfull encoder output (3 source positions)"le"
2` le`positions 1–2full encoder output (3 source positions)"chat"
3` le chat`positions 1–3full encoder output (3 source positions)"s'est"
4` le chat s'est`positions 1–4full encoder output (3 source positions)"assis"
5` le chat s'est assis`positions 1–5full encoder output (3 source positions)``

Two details are worth checking numerically. First, at step 3 the causal mask for a 3-token target prefix is

M=(0−∞−∞00−∞000),M = \begin{pmatrix} 0 & -\infty & -\infty \\ 0 & 0 & -\infty \\ 0 & 0 & 0 \end{pmatrix},

so after adding MM to the raw attention scores QK⊤/dkQK^\top / \sqrt{d_k} and applying softmax row-wise, row 3 (the query for "chat", the most recent position) has nonzero weight only on columns 1–3, and rows 1–2 never attend to column 3 at all — confirming "le" and ``'s representations are computed exactly as they would be if "chat" had not been generated yet, satisfying the invariant from the correctness argument above. Second, cross-attention at every step uses the same HencH_{enc} (3 rows, one per source token) as keys and values, regardless of how long the target prefix has grown; there is no masking here because "the cat sat" is fully available at every decoding step. If the decoder's query at step 3 (representing "chat", the direct object) places high attention weight on the encoder row for "cat," this is exactly the alignment behavior — content words attending to their translational counterparts — that makes cross-attention interpretable as soft alignment, analogous to classical statistical machine translation alignments but learned end-to-end. During training, all five target positions are processed in a single forward pass (teacher forcing with the ground-truth prefix at each position), and the causal mask guarantees this parallel computation produces identical per-position hidden states to the step-by-step trace above — this equivalence is what makes transformer training so much faster than the strictly sequential training required by recurrent architectures.

Common pitfalls & traps

PitfallWhy it happensConsequence
Forgetting the causal maskCopy-pasting encoder self-attention code, which has no maskModel "cheats" by seeing future tokens during training; train loss looks great, generation is garbage
Masking cross-attention with a causal maskConfusing cross-attention with self-attentionDecoder cannot see later parts of the source sentence, hurting translation quality
Off-by-one in the mask (masking the diagonal too)Using strict `<` instead of `<=` when deciding visibilityPosition i cannot attend to itself, destroying its own current-token information
Not caching keys/values at inferenceTreating training-time parallel code as inference code unchangedGeneration becomes O(n²) per token, i.e. O(n³) total, instead of the intended O(n) amortized per token via caching
Applying LayerNorm before adding the residual incorrectly (post-norm vs. pre-norm confusion)Mixing conventions from different papersTraining instability or exploding/vanishing gradients in very deep stacks
Reusing encoder output shape assumptions when source length changes per batch itemFixed-size cross-attention key/value tensorsPadding tokens leak into cross-attention unless a source-side padding mask is applied

Pioneers & history

Origins · 1 minAshish Vaswani and how this was discovered
AV
Ashish Vaswani
active 2010s–present · Google Brain researcher, lead author of "Attention Is All You Need" (2017), which introduced the encoder–decoder transformer architecture underlying the decoder stack described here.

History
2014
— sequence-to-sequence models with RNN encoders and decoders introduced for neural machine translation.
2015
— additive attention mechanisms let RNN decoders attend over encoder states, foreshadowing cross-attention.
2017
— the transformer paper replaces recurrence entirely with self-attention, defining the encoder–decoder stack with masked decoder self-attention and cross-attention.
2018
— GPT introduces a decoder-only stack (no cross-attention) trained purely as an autoregressive language model.
2019
–present — decoder-only stacks scale to hundreds of billions of parameters, becoming the dominant architecture for large language models.

The transformer decoder stack emerged from a lineage of work trying to remove the sequential bottleneck of recurrent sequence-to-sequence models while retaining their ability to condition generation on an entire source sequence. Early neural machine translation systems used recurrent encoders and decoders connected by an attention mechanism that let the decoder "look back" at encoder hidden states — this attention idea is the direct ancestor of cross-attention. The 2017 transformer paper's key insight was that self-attention alone, properly masked, could replace the recurrent decoder entirely, enabling full parallelization across sequence positions during training. Soon after, researchers observed that the decoder half of the transformer, used alone without any encoder or cross-attention, was already a powerful general-purpose sequence model — this observation launched the decoder-only lineage that includes GPT and its successors, which now dominate the landscape of generative language models.

Where this matters

The encoder–decoder variant of the decoder stack, with cross-attention intact, underlies neural machine translation systems, abstractive summarization models, speech-to-text systems that decode transcripts conditioned on audio encodings, and image-captioning systems that decode text conditioned on visual encodings. The decoder-only variant, with cross-attention removed, is the architecture of GPT-family models, and by extension the technology behind conversational assistants, code-generation tools, and most modern chat-based large language models, where the "encoder" role is absorbed by simply placing the prompt earlier in the same causally-masked sequence. KV-caching, a direct consequence of the causal-mask invariant proven above, is the standard optimization that makes real-time interactive generation from these models computationally feasible, and it is implemented in essentially every production inference engine for large language models today. Understanding the decoder stack is also the natural bridge to the Full Transformer Architecture, which combines this stack with a bidirectional encoder, and to GPT & Autoregressive Language Modeling, which studies the decoder-only specialization in depth.

Ask the tutor: How does removing cross-attention and concatenating prompt and continuation into one sequence let a decoder-only model like GPT still condition generation on context?

Why can't the decoder just use bidirectional self-attention like the encoder?

Bidirectional self-attention lets every position see every other position, including ones that come later in the sequence. During training this would let the model "cheat" by copying the very token it is supposed to predict from later in the sequence, since teacher forcing feeds in the whole ground-truth sequence at once. The model would achieve near-zero training loss without learning anything useful, and then fail completely at inference time, when future tokens genuinely do not exist yet because they haven't been generated. The causal mask closes this loophole by making the training-time computation mathematically identical to genuine step-by-step generation, which is exactly the invariant that makes parallel training valid.

What exactly is cross-attention attending over, and how is it different from self-attention?

In cross-attention, the queries come from the decoder's own current hidden states, but the keys and values come from the encoder's final output representations of the source sequence. Self-attention, by contrast, uses queries, keys, and values all derived from the same sequence — the decoder's own tokens. Cross-attention has no causal mask, because the whole source sequence is available regardless of how much of the target has been generated. Intuitively, self-attention builds context among already-generated target tokens, while cross-attention lets the decoder consult the source sentence to decide what to generate next, similar to alignment in classical translation systems.

Is a decoder-only model (like GPT) missing something an encoder-decoder model has?

A decoder-only model has no separate encoder and no cross-attention sublayer; instead, any "source" context, such as a prompt or instruction, is simply placed earlier in the same sequence and processed by the same causally-masked self-attention as everything else. This is architecturally simpler and scales well, since there's a single stack to train and serve, but it means the model cannot use bidirectional context on the prompt the way an encoder could. In practice, decoder-only models have proven extremely capable and now dominate large language model design, largely because their simplicity makes them easier to scale to enormous sizes and train on massive unlabeled text corpora.

What is KV-caching and why is it needed for efficient generation?

Without caching, generating each new token would require recomputing keys and values for the entire prefix generated so far, costing O(n) work per new token and O(n²) total work per sequence for the self-attention part alone, repeated per layer. KV-caching stores the previously computed keys and values for all prior positions, so each new token only requires computing its own new key, value, and query, then attending over the cached history. This reduces the incremental cost per generated token to roughly O(n) instead of O(n²), which is a major practical speedup and is standard in virtually every deployed autoregressive language model.

Does the feed-forward sublayer mix information across positions?

No. The position-wise feed-forward network is applied independently and identically to each position's hidden vector, using the same weight matrices at every position but no interaction between positions. All cross-position information mixing happens exclusively in the attention sublayers, both masked self-attention and cross-attention. This separation matters for the correctness argument about causality: since the feed-forward sublayer cannot leak information from later positions into earlier ones, the only sublayer that needs a causal mask to preserve the autoregressive invariant is self-attention.

How does the decoder stack relate to residual connections and layer normalization I already know?

The decoder stack is essentially those two prerequisite ideas applied three times per layer — once around masked self-attention, once around cross-attention (if present), and once around the feed-forward network. Each sublayer's raw output is added to its input before normalization, exactly as described in Residual Connections & Layer Normalization. What's new here is specifically the causal masking rule inside self-attention and the introduction of a second attention mechanism, cross-attention, that draws its keys and values from an external encoder rather than from the sequence being processed.

Why does stacking N decoder layers help rather than just using one very wide layer?

Each layer's attention sublayer can capture different types of relationships between positions — one layer might learn short-range syntactic dependencies, another longer-range semantic ones — and stacking allows these representations to be progressively refined and composed, similar to how deeper convolutional networks build hierarchical visual features. Empirically and theoretically, depth increases the expressive power of the function computed by the network, since composing N nonlinear transformations can represent a strictly richer class of functions than a single transformation of comparable total parameter count, provided training remains stable, which is exactly what residual connections and layer normalization are designed to ensure.

Before this

Where this leads