Lensa ML
Lensa ML

Decoder-Only Transformers

Step 1 of 6

The Architecture

Inside a decoder-only transformer block

Decoder blocks (N)5
Structure of a Decoder-Only TransformerFull model (left) and one decoder block (right)Output Token Vectors#sarecool.!×5Decoder BlockDecoder BlockDecoder BlockDecoder BlockDecoder BlockPositionEmbedding+++++Input Token VectorsLLM#sarecool.Decoder BlockLayer NormMasked Self-Attention+Layer NormFFNN+Structure of a decoder-only transformer model
BLOCKS
5
COMPONENTS/BLOCK
5
ATTENTION
Causal

With 5 decoder blocks stacked, the model builds increasingly abstract representations. Early blocks capture syntax and local patterns; later blocks capture semantics and long-range dependencies. Each block has the same structure: Layer Norm → Masked Self-Attention → Add → Layer Norm → FFNN → Add. GPT-2 Small uses 12 blocks; LLaMA-7B uses 32.

Step 1 of 6: The Architecture

Inside a decoder-only transformer block

Decoder blocks (N)5
Structure of a Decoder-Only TransformerFull model (left) and one decoder block (right)Output Token Vectors#sarecool.!×5Decoder BlockDecoder BlockDecoder BlockDecoder BlockDecoder BlockPositionEmbedding+++++Input Token VectorsLLM#sarecool.Decoder BlockLayer NormMasked Self-Attention+Layer NormFFNN+Structure of a decoder-only transformer model
BLOCKS
5
COMPONENTS/BLOCK
5
ATTENTION
Causal

With 5 decoder blocks stacked, the model builds increasingly abstract representations. Early blocks capture syntax and local patterns; later blocks capture semantics and long-range dependencies. Each block has the same structure: Layer Norm → Masked Self-Attention → Add → Layer Norm → FFNN → Add. GPT-2 Small uses 12 blocks; LLaMA-7B uses 32.

Step 2 of 6: Causal Masking

Tokens can only see the past

Query position3
Causal Mask: tokens see only the pastUpper triangle = masked to −∞ before softmaxQueryKeyThecatsatonthematThecatsatonthemat1.000.650.350.260.410.330.310.190.270.230.150.280.180.240.150.140.230.160.190.140.15"on" (pos 3) can attend to:The31%cat19%sat27%onquerythemaskedmatmasked
QUERY POS
3
VISIBLE
4
MASKED
2
ENTROPY
1.98

Position 3 sees 4 tokens. More context = higher entropy (1.98 bits) since attention is spread across more tokens. At the last position, the model sees the full sequence — same as inference time. This is why decoder-only training is so efficient: one forward pass generates 5 training signals (one per position).

Step 3 of 6: Layer Normalization

Stabilizing activations in deep transformers

Activation scale5
Layer NormalizationStabilize activations between matrix multiplicationsRaw Activations (scale = 5×)4.0-6.01.510.5-2.58.0-4.52.0γ · (x − μ) / √(σ² + ε) + βAfter LayerNorm0.44-1.40-0.021.63-0.761.17-1.120.07Pre-Norm (modern LLMs)LayerNormSublayerAdd
MEAN
1.63
STD
5.45
RMS
5.69
VARIANT
LayerNorm

Standard Layer Normalization computes the mean and variance over the embedding dimension for each token independently. It then normalizes to zero mean and unit variance, and applies learnable scale (γ) and shift (β) parameters. With scale=5×, raw activations range from -6.0 to 10.5, but after LayerNorm they are stable between -1.40 and 1.63. Modern LLMs use pre-norm: normalizing before each sublayer (attention, FFN) rather than after, which dramatically improves training stability for deep models.

Step 4 of 6: Next-Token Prediction

The universal training objective

Temperature1.0
Next-Token Prediction"The cat sat down" \u2192 predict next wordThecatsatdownDecoder-Only TransformerLinear (d \u2192 vocab_size)Softmax (T=1.0)Probability distribution over vocabulary<pad>NaN%theNaN%aNaN%catNaN%dogNaN%satNaN%Loss = −log(P("mat")) = NaNEvery position predicts its next token \u2192 3 training signals per sequence
TEMP
1.0
TOP PRED
<pad>
LOSS
NaN
PERPLEXITY
NaN

At temperature 1.0, the distribution is balanced. The model outputs logits (raw scores), divides by temperature, then applies softmax. Loss = −log(P(correct)) = NaN. Perplexity NaN means the model is as confused as choosing between ~NaN equally likely tokens.

Step 5 of 6: Autoregressive Generation

How LLMs generate text token by token

Max tokens4
Autoregressive GenerationGenerate one token at a time, append, repeatCurrent sequence (2 tokens)thepromptcatpromptForward Pass (causal masked)Step 1: predict next token<pad>NaN%theNaN%aNaN%catNaN%dogNaN%KV Cache: store K,V from previous tokensEach step recomputes only the new token → O(n) instead of O(n²)
GENERATED
0/4
SEQ LENGTH
2
NEXT
<pad>
CONFIDENCE
NaN%

Starting with prompt "the cat". Press Play or Step to generate. At each step, the entire sequence feeds through the model, and the last token's output distribution determines the next token. This is autoregressive generation: each new token depends on all previous ones.

Step 6 of 6: Modern Variants & Scale

RoPE, GQA, SwiGLU, and scaling laws

Method50
Modern LLM Architecture ImprovementsSame decoder-only foundation, refined componentsPositional Encoding EvolutionAbsolutesin/cos or learnedGPT-2, BERT012345RoPERotation in pairsLLaMA, Mistral012345ALiBiLinear attention biasBLOOM, MPT0.0-0.1-0.2-0.3-0.4-0.5
CATEGORY
Position
LATEST
RoPE
USED BY
LLaMA

Positional encoding has evolved significantly. The original Transformer used fixed sinusoidal encodings. RoPE (Rotary Position Embeddings) applies rotation matrices to Q and K at each layer — relative positions are encoded via the angle between vectors, enabling better length generalization. ALiBi simply adds a linear bias to attention scores, requiring no learned parameters.