Chapter 6 β Decoder-Only Models
βThe decoder-only transformer, trained with a simple next-token prediction objective on internet-scale data, turned out to be the most powerful architecture humanity has ever built for language understanding and generation.β
The Causal Language Modelling Objective
Decoder-only models are trained to predict the next token given all previous tokens. The training objective is straightforward β minimize the cross-entropy loss:
\[\mathcal{L} = -\sum_{t=1}^{T} \log P(x_t \mid x_1, \ldots, x_{t-1})\]This simple objective, scaled to trillions of tokens, produces models capable of reasoning, code generation, and multilingual understanding.
- All positions processed in parallel
- Causal mask ensures each position only sees past
- Loss computed at every position simultaneously
- One forward pass for the entire sequence
- Tokens generated one at a time
- Each new token appended to context
- KV-cache avoids recomputation
- Prefill (parallel) β Decode (sequential)
Full Decoder Pass β Tensor Shapes
The GPT Family
GPT (Generative Pre-trained Transformer) established the decoder-only paradigm:
The LLaMA Architecture
LLaMA (Meta, 2023β2024) is the most influential open-source decoder model family. Its architectural choices have become the de facto standard:
Model Size Comparison
| Model | Params | Layers | d_model | Heads (Q/KV) | d_k | FFN dim | Context | Vocab |
|---|---|---|---|---|---|---|---|---|
| LLaMA-1 7B | 6.7B | 32 | 4096 | 32/32 | 128 | 11008 | 2048 | 32000 |
| LLaMA-2 7B | 6.7B | 32 | 4096 | 32/32 | 128 | 11008 | 4096 | 32000 |
| LLaMA-2 70B | 70B | 80 | 8192 | 64/8 | 128 | 28672 | 4096 | 32000 |
| LLaMA-3 8B | 8B | 32 | 4096 | 32/8 | 128 | 14336 | 8192 | 128256 |
| LLaMA-3 70B | 70B | 80 | 8192 | 64/8 | 128 | 28672 | 8192 | 128256 |
| LLaMA-3.1 405B | 405B | 126 | 16384 | 128/8 | 128 | 53248 | 128K | 128256 |
Key evolution: MHA β GQA (LLaMA-2 70B onwards), 32K β 128K vocab (LLaMA-3), 2K β 128K context (LLaMA-3.1).
The Open-Source Landscape
Using Decoder Models with Transformers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
model_name = "meta-llama/Llama-3.1-8B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.bfloat16,
device_map="auto",
)
messages = [{"role": "user", "content": "Explain attention in one paragraph."}]
input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt").to(model.device)
# Inspect intermediate shapes
with torch.no_grad():
outputs = model(input_ids, output_hidden_states=True)
print(f"Input: {input_ids.shape}") # [1, T]
print(f"Hidden: {outputs.hidden_states[-1].shape}") # [1, T, 4096]
print(f"Logits: {outputs.logits.shape}") # [1, T, 128256]
# Generate
output_ids = model.generate(input_ids, max_new_tokens=256, temperature=0.7, do_sample=True)
print(tokenizer.decode(output_ids[0], skip_special_tokens=True))
Autoregressive Generation Loop
Under the hood, model.generate() runs an autoregressive loop. Hereβs what happens step by step:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def generate_simple(model, input_ids, max_new_tokens, temperature=1.0):
"""Simplified autoregressive generation loop."""
past_key_values = None # KV-cache
for _ in range(max_new_tokens):
outputs = model(
input_ids=input_ids if past_key_values is None else input_ids[:, -1:],
past_key_values=past_key_values,
use_cache=True,
)
past_key_values = outputs.past_key_values # cache K, V
# Sample from the logits of the last position
logits = outputs.logits[:, -1, :] / temperature # [B, vocab_size]
probs = torch.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1) # [B, 1]
input_ids = torch.cat([input_ids, next_token], dim=-1)
if next_token.item() == model.config.eos_token_id:
break
return input_ids
Notice: on the first pass (prefill), the entire prompt is processed at once. On subsequent passes (decode), only the last token is fed in β the KV-cache stores everything else. See Chapter 17 for full details.
Whatβs Next
Decoder-only models dominate generation, but theyβre not the only game in town. The next chapter covers encoder and encoder-decoder architectures that excel at understanding tasks like classification, NER, and translation.
β Previous: Chapter 5 β GQA, MQA & MLA Β· Next: Chapter 7 β Encoder & Seq2Seq Models β
Last updated: April 2026