The core idea. Almost every LLM in 2026 is one decoder block repeated L times around a residual stream: each block lets every position read earlier positions (the sequence mixer), then transforms each position on its own (the feed-forward network), and nearly every design choice since 2017 trades quality against what one token costs to keep, read and compute in one of those two places.
You need a neural network, a matrix multiply and a softmax. If the transformer itself is rusty, The transformer from zero first.
Fig. 1 is one block of Llama 3.1 8B, the model sections 2 and 3 count, with tokens in and a distribution out. Every plate is a weight matrix d = 4,096 tall and as deep as its other side, to scale, so the sizes are the real ones; only the two vocabulary tables are drawn shortened. Each step lights one part and names the page that owns it.
| Part | Usual choice in 2026 | Alternatives | What the choice trades | Owner |
|---|---|---|---|---|
| Tokens and embedding | Byte-level BPE, vocabulary of about 100K to 260K | SentencePiece unigram, bytes, smaller vocabularies | Shorter sequences against a bigger embedding table | Tokenizers |
| Sequence mixer: attention variant | Grouped-query attention (GQA) | MHA, MQA, MLA, sliding window, trained sparse attention | Bytes each token keeps and each step reads, against quality | Attention variants |
| Sequence mixer: attention or a fixed state | Attention; hybrids in a growing share of flagships | State-space or linear layers (Mamba, Gated DeltaNet), mixed with a few attention layers | Constant memory per sequence against exact recall | Beyond attention |
| Context and its cache | 128K or more, with windowed layers in some models | Global layers only, local : global mixes, cache eviction | Memory and compute per token of context, against what the model can still use | Long context |
| Position | RoPE, with a scaling rule for long context | Learned or sinusoidal absolute, ALiBi, no position (NoPE) on some layers | Behaviour past the trained length | Positional Encodings |
| Feed-forward | SwiGLU; mixture of experts (MoE) in most large open models | GELU MLP of width 4d; dense against sparse | Compute per token against memory for all experts | Mixture of experts |
| Normalisation | Pre-norm RMSNorm, often QK-norm | Post-norm LayerNorm (2017), norms after the sublayer, both sides | Trainability at depth and loss spikes | Normalisation, residuals and stability |
| Shape | Width about 100 to 130 times the depth in large models | Deeper and thinner small models | Same parameters, different latency and quality | This page (section 8) |
| Family and objective | Decoder-only, next-token prediction | Encoder-only (masked tokens), encoder-decoder, multi-token prediction, diffusion LMs | What the model can be asked to do, and how fast it generates | Families and objectives |
Each row is a section below with its sources. The Architecture map places real models from GPT-2 to 2026 on these axes; the Block lab runs one real token through one block.
A tokenizer cuts text into integer ids from a vocabulary of size V (Llama 3.1: V = 128,256, config). Each id picks a row of a V × d embedding table; the blocks transform that vector; a final norm and a d × V unembedding give one score (logit) per vocabulary entry, and a softmax turns the logits into next-token probabilities. In training every position predicts its own next token at once, and a causal mask stops it seeing later ones, so one pass over a 4,096-token sequence gives 4,096 training examples; in generation the model predicts one token, appends it and runs again (picking the token is Sampling and decoding).
The distinction that crosses pages: vocabulary size. A bigger vocabulary needs fewer tokens per sentence, so attention and the KV cache (sections 4 and 9) are cheaper per sentence, but the two V × d tables grow and each token is rarer in training. Tied embeddings use one matrix for both ends (Press and Wolf 2016), which small models do because the table is a large share of them: in a 135M-parameter model with a 49,152-token vocabulary at d = 576 it is 28M parameters, a fifth of the model, so count it once when tie_word_embeddings is true. Llama 3.1 8B does not tie ("tie_word_embeddings": false); its two tables are 1.05 billion of its 8.03 billion parameters (derived as 2 × 128,256 × 4,096).
Go deeper: Tokenizers (BPE, byte-level, unigram, the language tax, glitch tokens); Families and objectives for what the mask and the objective can be instead; the logit lens shows what the residual stream would predict if the model stopped after each layer. Drawn in 3D: one sentence through a tokenizer (Tokenizers, Fig. 1), one token becoming a vector (The transformer from zero, Fig. 2) and the last vector becoming a loss (Fig. 6).
A block does two things to the residual stream x of every position, each wrapped the same way: normalise a copy, transform it, add the result back. In the pre-norm layout every current model uses (section 7):
Because each sublayer only adds to x, what layer 3 writes is still there for layer 30 to read, and gradients flow back along the same identity path; that is why a stack of 80 or 126 such blocks trains at all.
That split is why mixture of experts (section 6) targets the FFN, where the parameters are, while the attention variants (section 4) target the cache. Each weight is used once per token in one multiply and one add, so a forward pass costs about 2 FLOPs per weight per token; the backward pass costs about twice the forward, giving 6N FLOPs per training token (Kaplan et al. 2020, section 2.1). Attention adds a term that grows with the context (section 8).
| Step | What happens | Shape out (one token) | Weights |
|---|---|---|---|
| Norm | RMSNorm: divide by the root mean square, multiply by a learned gain | 4,096 | 4,096 |
| Q, K, V | Three linear maps. 32 query heads of 128, but only 8 key and 8 value heads (GQA) | Q 32 × 128; K, V 8 × 128 | 4,096 × 4,096 + 2 × 4,096 × 1,024 = 25.2M |
| RoPE | Rotate Q and K by the position (section 5) | same | none |
| Attention | Each query head scores the T cached keys of its group, softmax, weighted sum of values | 32 × 128 = 4,096 | none (cost grows with T) |
| Output proj. | Merge heads back to d | 4,096 | 4,096 × 4,096 = 16.8M |
| Add | h = x + attention output | 4,096 | none |
| Norm | RMSNorm again | 4,096 | 4,096 |
| FFN | SwiGLU: gate and up to 14,336, SiLU(gate) × up, down to 4,096 | 14,336 inside, 4,096 out | 3 × 4,096 × 14,336 = 176.2M |
| Add | x′ = h + FFN output | 4,096 | none |
In your head: attention Q and output 2 × 4,096² = 33.6M, K and V 2 × 4,096 × 1,024 = 8.4M; FFN 3 × 4,096 × 14,336 = 176.2M; about 218M. Times 32, plus two 525M embedding tables: 8.03B. The Block lab runs one real token of the running sequence through every step with the recorded vectors, and quotes the line of transformers' Llama code that does each.
Go deeper: The transformer from zero derives every step and trains the GPT; the Block lab walks one token through it with shapes, parameters and FLOPs for six real models. Drawn in 3D: the block on its residual stream (The transformer from zero, Fig. 5) and where the norm sits in it (Normalisation, Fig. 2).
derived from the Llama 3.1 8B config (hidden_size 4,096, 32 heads, 8 KV heads, head_dim 128, intermediate_size 14,336, no biases): 218.1M weights per block, 41.9M in attention and 176.2M in the FFN. The tiny GPT of the running example (d_model 256, 8 query heads of 32 with 8 KV heads, a GELU FFN of 1,024, two matrices): 786,944 weights per block, 262,144 in attention and 524,288 in the FFN, the classic 4d² and 8d² split measured (model.param_groups()).
Attention. Each position makes a query (what it looks for), a key (what it offers) and a value (what it passes on) from its normalised residual stream, and its output is a weighted average of earlier positions' values, weighted by query-key match. For one head:
Why a cache. A past token's keys and values never change, so generation computes them once and keeps them: the KV cache. Prefill runs the whole prompt as one large matrix multiply, limited by arithmetic; decode makes one token per step and must read every weight and the whole cache to do little arithmetic, so it is limited by memory bandwidth; batching more sequences raises the FLOPs per weight byte but not per cache byte, since each sequence reads its own cache. What each token leaves behind is:
At long context this, not the parameter count, decides what a GPU can serve: Llama 3.1 70B (80 layers, 8 KV heads of 128, BF16) keeps 320 KiB per token, 40 GiB for one 128K request against about 141 GB of weights (derived; sized for 45 models on Long context's KV-cache calculator). FlashAttention changes how attention is computed (tiled, never storing the T × T matrix), not how much is cached (FlashAttention).
Every design since GQA pulls one of four levers, and which one decides what is saved, storage or reads, and what is given up.
| Lever | Shrinks what a token stores? | Shrinks what a step reads? | What it gives up | Seen in | Owner |
|---|---|---|---|---|---|
| A smaller entry per token: fewer KV heads (GQA, MQA), a compressed latent (MLA), an FP8 cache | Yes | Yes | Some quality, most for MQA; MLA needs extra projections and its own kernels | GQA: Llama 3, Qwen3, Gemma 3, gpt-oss. MQA: PaLM, Gemma 3 270M. MLA: DeepSeek-V2/V3, Kimi K2, GLM-5 | Attention variants |
| Read a learned subset: trained sparse attention (an indexer picks the keys each query reads) | No: every key stays for the indexer to choose from | Yes | The indexer can miss a key that mattered | NSA; DeepSeek-V3.2 (DSA), GLM-5; DeepSeek-V4 also compresses | Attention variants |
| Keep fewer tokens in some layers: sliding windows, local : global mixes, eviction | Capped, not smaller per entry | Yes | A windowed layer cannot see past its window; far recall rests on the global layers | Mistral 7B, Gemma 3 and Gemma 4 (5 of 6 layers), gpt-oss (half) | Long context |
| Fewer layers with a cache: recurrent or linear layers keep a fixed-size state | Yes, in those layers; the few attention layers still grow a cache | Yes | A fixed state is a lossy summary: weaker exact recall and copying | Qwen3-Next, Jamba, Nemotron 3 Super, Kimi K3 | Beyond attention |
Two misreadings this table prevents: a window or a sparse indexer does not shrink the per-token entry (only fewer KV heads, compression, lower precision or layers without a cache do), and a hybrid is not cache-free (Qwen3-Next's attention layers keep 24 KiB per token, and each request also carries a fixed state for the recurrent layers). Trained models also park attention on the first tokens (attention sinks), so any cache that evicts tokens must keep them (Attention variants, measured in Inside a real model).
A recurrent layer replaces the growing cache with a fixed-size state updated once per token, so memory and work per token stay constant however long the context. Linear attention writes each value into a matrix state indexed by its key (St = St−1 + vtkt⊤, read out as Stqt); a state-space model (SSM) runs ht = Atht−1 + Btxt, yt = Ctht. They became competitive once the update depended on the input, so the layer chooses what to keep: Mamba's selective SSM (Mamba) and gated delta rules that erase what a key stored before writing (Gated DeltaNet, Yang et al. 2024). Training still runs in parallel with a scan or chunked algorithm. One layer of each in Qwen3-Next holds the same number of numbers at 512 tokens: 1,024 per token for attention, 524,288 in all for the Gated DeltaNet state (derived from its config; drawn on Beyond attention).
Caches derived as the Architecture map computes them (BF16, every cache-growing layer counted); sizes are the makers' cards, vendor.
full_attention_interval: 4) and Gated DeltaNet in the rest, 24 KiB of cache per token against 96 KiB had all 48 layers been attention; Qwen3.5-397B-A17B keeps that 3 : 1 pattern. NVIDIA's Nemotron 3 Super (120B, 12B active) interleaves 40 Mamba-2 layers with 8 attention layers of 2 KV heads, 8 KiB per token. Moonshot's Kimi K3 (2.8T total, 104B active) puts 3 Kimi Delta Attention layers before each MLA layer, MLA in 24 of its 93 layers, 27 KiB per token. Jamba uses one attention layer per seven Mamba layers and reports a KV cache of about 4 GB at 256K tokens in 16-bit (Lieber et al. 2024, vendor); NVIDIA's Nemotron-H "replace[s] the majority of self-attention layers" with Mamba layers and reports "up to 3× faster" inference than comparable transformers (Nemotron-H, vendor).Go deeper: Attention variants (MHA to MLA, windows, NSA, DSA, DeepSeek-V4, sinks: each with its picture); Long context (whole-model cache sizing, eviction, local and global layouts); Beyond attention (SSMs, Mamba, linear attention, RWKV, hybrids); Batching, KV cache and scheduling and PagedAttention for how servers manage the cache; Memory technology for why bandwidth is the limit. Drawn in 3D: the cache of one sequence (Attention variants, Fig. 2), query heads sharing KV heads (Fig. 3), MLA's latent (Fig. 4), windows (Fig. 5); a recurrent layer against attention (Beyond attention, Fig. 1).
Attention by itself is blind to order: shuffle the earlier tokens and each query gets the same weighted average. The near-universal answer is RoPE (rotary position embedding, RoFormer): split each query and key into pairs and rotate pair i by position × θi, with θi = base−2i/dh; rotations compose, so the query-key product depends only on the distance between the tokens, with no parameters. The base sets the slowest rotation: 10,000 in the original, 500,000 in Llama 3.1 (rope_theta). The alternatives: absolute positions added to the embedding (fixed sinusoids, Vaswani et al. 2017, or a learned table, GPT-2's 1,024 positions, with nothing for position 1,025); ALiBi, a score penalty proportional to distance (Press et al. 2021); and NoPE, no position signal at all, since a causal decoder can infer order from the mask (one layer in four in SmolLM3, config).
The distinction that crosses pages: position sets the third long-context wall (section 9). A model trained on 8K tokens has never seen the rotation angles of position 100,000 in its slow pairs, and quality collapses there. The fixes stretch the angles back into the trained range, position interpolation (Chen et al. 2023), base scaling, or YaRN, which stretches only the slow pairs (Peng et al. 2023), each followed by a short training phase at the longer length. The rule ships in the config: Llama 3.1 has "rope_scaling": {"rope_type": "llama3", "factor": 8.0, "original_max_position_embeddings": 8192}; gpt-oss uses YaRN with factor 32 from 4,096 to 131,072 (config). Drop that field when converting or copying a config and the model still loads, still answers short prompts well, and degrades past the original length; diff the config against the original after any conversion.
The tiny GPT (RoPE, trained on 256-token windows) with the running story moved to start at position 1,024: loss 3.87 against 1.74 at position 0, and the greedy continuation turns into "friends like to play with the park was a little boy was very happy. As the sunrise, the sun came to the park." The config mistake does the same with no error: YaRN ×8 with original_max_position_embeddings set to 2,048 instead of 256 gives 3.78 at that position measured (section 8 of Positional Encodings, which measures every fix).
Go deeper: Positional Encodings owns the schemes, the extension methods and their configs, and runs five schemes past their trained length; Long context what else breaks there. Drawn in 3D: RoPE as one rotation per pair (Positional Encodings, Fig. 4) and each extension method reshaping the dials (Fig. 6).
After attention has gathered information from other positions, the FFN transforms each position on its own: expand, apply a nonlinearity, project back. It holds most of the parameters (section 3) and behaves like a key-value memory where many stored facts are found (Geva et al. 2021): each hidden unit's input weights are a key, its output weights the value it adds when the key matches. The Transformer paper said so first, in an appendix of its v2 and v3 (June 2017), "Two Feed-Forward Layers = Attention over Parameters", cut from later versions (the transformers-from-memory article). Current models use SwiGLU, out = Wdown( SiLU(Wgatex) × Wupx ), better at equal compute than the original ReLU MLP of width 4d (Shazeer 2020); its three matrices shrink the width to 8d/3 so they cost what two did (Llama 3.1 8B: 14,336 = 3.5d; the original 2,048 for d = 512).
Mixture of experts (MoE) replaces the one FFN by E smaller FFNs (experts) and a router, a linear layer that scores every expert for each token; the token goes to its top k experts and their outputs are summed, weighted by the router's scores. DeepSeek-V3 has 256 routed experts plus 1 shared expert that every token uses, 8 routed per token: in one of its MoE layers the experts hold 11.3 billion weights and a token uses 0.40 billion of them, 3.5% (derived from its config: experts of 3 × 7,168 × 2,048); the whole model is 671B total and 37B active (DeepSeek-V3 report, vendor).
The distinction that crosses pages: total and active parameters bill different things. Total parameters set the memory floor (every expert must be resident); active parameters set FLOPs per token. At large decode batches nearly every expert is touched in each step, so the weight bytes read per step approach the total, not the active count; and MoE does not help a small device where every expert must fit in memory. Mixture of experts (section 1) builds a model's dense twin at equal active parameters and steps through what the experts change; the Config calculator gives both counts for any config.
The trend is from few large experts (Mixtral 8x7B: 8 experts, top 2, Mixtral) to many small ones (Qwen3-235B-A22B: 128 experts, top 8, no shared expert, Qwen3 report). Experts must stay busy in equal measure: the classic fix is an auxiliary loss that rewards balanced routing (Switch Transformers); DeepSeek-V3 instead nudges a per-expert bias after each step and reports this "auxiliary-loss-free" scheme beats the loss (vendor). Spread over GPUs, an MoE needs expert parallelism and its all-to-all traffic.
On the tiny GPT at equal active FFN, only the fine-grained, shared-expert layout clearly beats dense (2.210 against 2.278); without balancing the router collapses; tokens over an expert's capacity are dropped. The runs, the seed spread and the capacity arithmetic are sections 2 to 6 of Mixture of experts measured.
Go deeper: Mixture of experts owns routers, balancing, capacity, fine-grained and shared experts and expert parallelism; Activation functions derives GELU, SiLU and the GLU family. Drawn in 3D: stored against computed weights, to scale (Mixture of experts, Fig. 2), and eight recorded tokens through one router (Fig. 3).
A normalisation layer rescales a vector to a standard size so activations and gradients neither grow nor shrink layer by layer. The 2017 Transformer used post-norm, x′ = Norm(x + F(x)), which normalises the residual stream itself; deep post-norm models need a careful learning-rate warmup to train at all. Pre-norm, x′ = x + F(Norm(x)), normalises only the copy each sublayer reads and leaves an untouched identity path; pre-norm can drop the warmup (Xiong et al. 2020, their claim; every run here uses a 100-step warmup). Its cost is a residual stream whose size grows with depth, since every layer only adds. On the tiny GPT at the default learning rate, post-norm never leaves the unigram plateau (it ends at 5.943, the loss of predicting each token by its frequency) while pre-norm reaches 2.281 measured; section 2 of Normalisation, residuals and stability draws both residual streams.
How to check a run. A loss spike is a sudden jump in training loss; log the global gradient norm, the largest attention logit and the per-layer residual norms. A spike preceded by growing attention logits points at QK-norm or a lower learning rate; a single bad batch points at data. Trained models also grow a few massive activations, single residual dimensions thousands of times larger than the rest (Sun et al. 2024), tied to the attention sinks of section 4, which matter for low-precision training and quantisation.
modeling_gemma4.py line 222); MiniMax-M1 keeps post-norm with DeepNorm's residual scale, α = (2 × 80)1/4 ≈ 3.5566 for its 80 layers (layernorm_*_alpha in its config); DeepSeek-V4 widens the residual stream into 4 streams mixed by a doubly stochastic matrix, manifold-constrained hyper-connections (mHC, arXiv 2512.24880), with pre-norm RMSNorm inside.Go deeper: Normalisation, residuals and stability owns placements, initialisation and loss-spike forensics; Normalisation and initialisation (ML fundamentals) derives LayerNorm and RMSNorm. Drawn in 3D: where the norm sits in one sub-layer (Normalisation, Fig. 2), the stream's size through 12 sub-layers (Fig. 3) and SmolLM2-135M's massive activations (Fig. 5).
Three numbers answer most questions about a model, and all three come from its config in a minute: parameters, FLOPs per token, and KV bytes per token (section 4).
Worked: Llama 3.1 8B. 32 blocks of 218.1M = 6.98B, plus two 525.3M embedding tables and a final norm = 8.03B parameters, the published size (derived). Forward FLOPs per token: 2N = 15.0 GFLOP. The attention term at T = 131,072: 4 × 32 × 131,072 × 4,096 = 68.7 GFLOP, more than four times the weights' share. The two are equal at T ≈ 28,600 tokens: below that a token's cost is set by the parameter count, above it by the context (derived). Training costs about three times the forward (plus three times the attention term).
Shape (width against depth) changes latency more than quality at a fixed parameter count: each layer is a sequential step, and small models are the exception that go deep and thin (closed block below).
Read the fields, do not derive them. Never derive head_dim as hidden_size / num_attention_heads when the field exists: Gemma 3 27B has hidden size 5,376 and 32 heads but head_dim 128, not 168 (config), so every derived cache and FLOP figure would be 31% too high; Qwen3-0.6B has 1,024 and 16 heads with head_dim 128 (config).
Depth against width (large models run about 100 to 130 times wider than deep). At a fixed parameter count shape matters less than one might think: Kaplan et al. 2020 found that "other architectural details such as network width or depth have minimal effects within a wide range" (abstract). It matters for speed: each layer is a sequential step, so a deeper model of the same size has more latency per token. Small models are the exception that go deep and thin: Meta's MobileLLM reports that under a billion parameters depth beats width (Liu et al. 2024, vendor), and SmolLM2-135M is 30 layers of 576.
| Model | Width d | Depth L | d / L |
|---|---|---|---|
| SmolLM2-135M | 576 | 30 | 19 |
| Llama 3.1 8B | 4,096 | 32 | 128 |
| Llama 3.1 70B | 8,192 | 80 | 102 |
| Llama 3.1 405B | 16,384 | 126 | 130 |
| DeepSeek-V3 | 7,168 | 61 | 118 |
From each model's config.json (hidden_size, num_hidden_layers), rechecked on 2026-10-19 against the saved files (src/data/configs) and the Config calculator: 43 values agree, including every row of this table, Llama 3.1 70B and 405B, DeepSeek-V3, gpt-oss-120b, Gemma 3 27B, Qwen3-Next and SmolLM2-135M (src/read/derive.py).
The Config calculator reproduces the Hugging Face stored-tensor count of all 44 saved configs that have one exactly, once extra tensors are added back: multi-token-prediction modules (the largest: DeepSeek-V3's Hub count of 684.5B is the 671.0B main model plus a 13.5B MTP module plus 41.5M FP8 scale tensors), vision towers (Llama 4, 0.87B; Gemma 3 27B, 0.42B), buffers such as GPT-2's attention masks, and Qwen3-0.6B's stored copy of its tied head (155.6M) measured. Published headline sizes are rounded or truncated by their makers; 42 of 45 match one of three accountings, and GLM-4.5 (355B), MiniMax-M2 (230B) and Gemma 7B ("7B" for 8.54B) do not, for reasons the calculator explains.
Go deeper: the Config calculator does all of this for any config; the Block lab counts FLOPs per operation against context; Performance math turns FLOPs and bytes into seconds on real hardware; Scaling Laws and Chinchilla for how parameters and data trade. Drawn in 3D: five released stacks, one slab per layer (LLM architecture gallery, Fig. 1), and why layers in a config are not caches per token (Fig. 14).
A model "supports 128K tokens" only if it clears four separate limits. Each is owned by a different page, which is why long context is a map question:
| Wall | What limits | Remedies | How to check | Owner |
|---|---|---|---|---|
| 1. Memory | The KV cache grows linearly with context and batch (40 GiB per 128K request for Llama 3.1 70B, section 4) | Fewer KV heads, MLA, windowed layers, FP8 caches, layers without a cache | Compute the cache at the target context and concurrency; read the server's KV capacity (vLLM prints it at start-up) | Attention variants, Long context |
| 2. Compute | Prefill attention grows with the square of the prompt; past about 29K tokens it is most of Llama 3.1 8B's work (section 8) | Sliding windows, trained sparse attention, linear layers | Time a prefill at that length | Long context, Beyond attention |
| 3. Position | Rotation angles past the trained length were never seen (section 5) | RoPE scaling plus a long-context training phase | Read rope_scaling and max_position_embeddings | Positional Encodings |
| 4. Use | A model can fit and run 128K tokens and still not use them | Long-context training data; retrieval-style evaluation | Run a long-context benchmark at the length you need, not the length on the card | Long context, Long-context and multimodal benchmarks |
Wall 4 is the one a spec sheet hides. RULER found that of models claiming 32K or more, "only half of them can maintain satisfactory performance at the length of 32K" (Hsieh et al. 2024, third-party), and information in the middle of a long prompt is used worse than at its ends (Liu et al. 2023). The claimed context is a ceiling; the effective context is measured.
SmolLM2-135M, whose config allows 8,192 positions, finds a pass key 80% of the time at 8,192 tokens and never at 12,288 or 16,384 (wall 3). Wall 4 hides behind perplexity: at 4,096 tokens, evicting three quarters of its KV cache with scores computed before the question is seen drops retrieval from 97% to 0%, while H2O eviction down to 12.5% of the cache moves the loss on a new story only from 2.07 to 2.10. A model trained with a window has no position wall: the tiny GPT with window 64 (RoPE, trained on 256 tokens) scores 2.09 on positions 1,024 to 2,047, where the same model with full attention scores 3.82 measured.
Go deeper: Long context owns cache growth and compression, local and global layouts and effective context; Long-context and multimodal benchmarks owns how it is measured. Drawn in 3D: one Llama 3.1 8B request on one GPU (Long context, Fig. 1), prefill against decode (Fig. 2) and the tiny GPT past its trained length (Fig. 4).
The same blocks build three families, differing in which positions may see which (the mask) and in what they are trained to predict (the objective):
| Family | Attention mask | Objective | Good at | Example |
|---|---|---|---|---|
| Decoder-only | Causal: each token sees itself and earlier tokens | Predict the next token at every position | Generation; everything, at scale | GPT-3, Llama, Qwen, DeepSeek |
| Encoder-only | Bidirectional: every token sees every token | Recover masked tokens (15% in BERT) | Embeddings, classification, retrieval; cannot generate fluently | BERT |
| Encoder-decoder | Bidirectional encoder over the input; causal decoder that also attends to it | Rebuild corrupted spans, or input-to-output | Translation, summarisation; the input is encoded once | T5, T5Gemma 2 |
Decoder-only won because one objective, next-token prediction, turns any text into training data and any task into a prompt, and it scales simply. Two newer objectives change what a decoder predicts. Multi-token prediction (MTP) trains extra heads to predict tokens further ahead (Gloeckle et al. 2024): DeepSeek-V3 trains one extra token and can reuse that module as a draft for speculative decoding. Diffusion language models start from a fully masked sequence and unmask many tokens per step in any order, trading the left-to-right loop for parallel refinement (LLaDA, Nie et al. 2025; DiffusionGemma).
In section 7 of Families and objectives, one MTP module trained jointly lowers the main model's held-out loss from 2.278 to 2.241 at an equal number of tokens, a gain of 0.036; but the module adds 32% training FLOPs per step, and the plain model given those FLOPs reaches 2.160. At equal compute MTP loses at this scale. DeepSeek-V3 reports gains from MTP at a far larger scale (vendor), not tested here measured.
Go deeper: Families and objectives owns the masks, the objectives, MTP and diffusion LMs; Pretraining how the objective is run at scale. Drawn in 3D: one block under four masks (Families and objectives, Fig. 2), multi-token prediction (Fig. 6) and causal against diffusion decoding (Fig. 7).
A Hugging Face config.json is the architecture in about thirty fields, and every part of the map above has its fields. Llama 3.1 8B (excerpt, field order kept; full file):
num_hidden_layers × hidden_size: 32 × 4,096.num_attention_heads against num_key_value_heads: 32 against 8 is GQA with groups of 4; with head_dim 128 that is 2 × 32 × 8 × 128 × 2 = 128 KiB per token in BF16. Other variants announce themselves: kv_lora_rank and qk_rope_head_dim mean MLA, sliding_window or layer_types mean windowed layers, linear-layer fields mean a hybrid.intermediate_size 14,336 with silu means SwiGLU at 3.5d. MoE adds num_experts or n_routed_experts, num_experts_per_tok and a separate expert width (moe_intermediate_size).rope_theta, rope_scaling and max_position_embeddings: trained at 8,192 and stretched 8 times to 131,072.vocab_size and tie_word_embeddings for the embedding share, then section 8's formula: 8.03B.Go deeper: paste any config into the Config calculator; the Architecture map lays these fields side by side from GPT-2 to 2026; the LLM architecture gallery decodes many more 2026 configs.
| Constraint | Choose | Why, and what you give up |
|---|---|---|
| Short contexts, high throughput, standard serving stacks | Dense or MoE with GQA, SwiGLU, RoPE, pre-norm RMSNorm | Mature kernels everywhere; the cache is small at short context anyway |
| Long contexts at high concurrency | MLA, or GQA with few KV heads; FP8 cache; windowed layers mixed with global ones | Shrinks what each token keeps or how long; costs kernel complexity (MLA) or far recall through fewer layers (windows) |
| Very long streams, fixed memory | Hybrid: mostly SSM or linear layers, one attention layer in 4 to 8 | Near-constant memory; exact recall rests on the few attention layers |
| More quality at the same latency, memory available | MoE with many small experts and a shared expert | Active parameters set latency; total parameters set memory, and balancing must be engineered |
| Small device, little memory | Small dense model, deep and thin, tied embeddings, GQA | MoE does not help when every expert must fit in memory |
| Stable training at scale | Pre-norm RMSNorm plus QK-norm | Two extra norms per layer, almost free |
Go deeper: the Architecture map lays these choices out model by model from GPT-2 to 2026 and has a picker by constraint; the Config calculator checks a candidate's parameters and FLOPs, and the KV-cache calculator its cache.
Budget first: an 8B-class model's BF16 weights take about 16 GB, leaving about 64 GB for 32 × 131,072 = 4.2M cached tokens: about 15 KB per token across all layers. Llama 3.1 8B's GQA needs 128 KiB per token (512 GiB in total), 9 times over. So change the mixer, not the size: for example 32 layers of which 8 are full attention with 2 KV heads of 128 and an FP8 cache (4 KiB per token, 16 GiB in total) and 24 linear or SSM layers (a fixed state of about 24 MiB per request, 768 MiB in total), leaving room for activations. Name the price: exact recall over 128K rests on 8 layers, so measure it with a long-context retrieval benchmark (wall 4), and train the long-context phase with the target RoPE scaling (wall 3). Alternatives: MLA (36 KiB per token at this shape in BF16, still too big alone at batch 32 without FP8 and fewer layers), or GQA with sliding windows on 5 of 6 layers (derived in src/read/derive.py).
enable_gqa): RuntimeError: The size of tensor a (8) must match the size of tensor b (2) at non-singleton dimension 1.repeat instead of repeat_interleave: no error, the shapes match, but each query head reads the wrong KV head; the trained GQA-2 model's held-out loss goes from 2.103 to 2.991.q @ k): RuntimeError: Expected size for first two dimensions of batch2 tensor to be: [8, 32] but got: [8, 256].IndexError: learned positions stop at 256; got position 256 (the tiny GPT raises it on purpose)..view but no transpose 3.64; heads merged without transposing back 5.03 ("Lily saw a little girl saw a little girl was the girl"); causal mask left out 3.64, and a model trained without it learns to copy the next token, held-out 0.21 with the leak and 7.02 once the mask is back (sections 1 and 3 of Families and objectives).All measured on the laptop; errors pasted verbatim.
Labels: measured means run for this topic in October 2026 on an Apple M1 Pro; vendor, a lab's figure about its own model; third-party, someone without a stake; derived, computed here from a config with the formula shown; unconfirmed, no primary source. Shapes, parameter counts, FLOPs and bytes transfer exactly to a datacenter GPU; laptop seconds do not.
A tiny decoder-only GPT trained here from scratch: d_model 256, 6 layers, 8 heads of 32, context 256, learned positions, a GELU FFN of width 1,024, pre-norm LayerNorm and tied embeddings, 5,836,032 parameters (4,721,920 outside the embeddings). It trains on TinyStories (CDLA-Sharing-1.0; one shard of 122M tokens) with its own byte-level BPE of 4,096 tokens, 1,500 steps of 8,192 tokens (12.3M tokens, about 5 minutes on the laptop's GPU), and reaches a held-out loss of 2.30 (2.16 with RoPE instead of learned positions, the setting the attention runs use). The running sequence is 256 tokens of a held-out story, Roxy the rhinoceros and the icy hill, never seen in training; names repeat ("Roxy" 11 times), which attention, copying and cache demos need measured.
A small open model inspected layer by layer: SmolLM2-135M (Apache-2.0, Hugging Face revision 93efa2f0; 30 layers of width 576, 9 query heads and 3 KV heads), run on the same story re-tokenised with its own tokenizer (226 tokens), with Qwen3-0.6B (Apache-2.0, revision c1899de2) as a second opinion. And the config.json files of real models (Llama 3.1, Qwen3 dense and MoE, DeepSeek-V3, gpt-oss, Gemma 3, hybrids), from which every frontier number on this page is derived with the formula shown.
Neighbouring topics own their subjects and are linked, not repeated: Topic: llm-landscape (labs, models, prices), Topic: llm-training-and-post-training (how these models are trained), Batching, KV cache and scheduling (how they are served) and Performance math (the hardware side of FLOPs and bytes).
Each part of the map has a page that teaches it in depth, on the same running example. In reading order; times are each page's Reading tab as its header states (230 words a minute, closed details apart).
Every number a decoder block produces, for one real token of the running example, with the shape, the parameters and the FLOPs of each step, then where the compute goes as the context grows.
A decoder block is the unit a GPT repeats: it reads the residual stream (one vector of d_model numbers per token, the model’s working memory), lets the token gather information from earlier tokens (attention), transforms each token on its own (the feed-forward network, FFN), and adds both results back to the stream. The table lists every step with its output shape, its parameters and its forward FLOPs per token (a FLOP here is one multiply or one add, so a multiply-add of a weight costs 2). t is the number of positions the token attends to.
derived Real models from their config.json through the Config calculator’s code (window.CC); the tiny GPT from src/data/tiny_gpt.py (GPT-2 style: d_model 256, 6 layers, 8 heads of 32, LayerNorm pre-norm, GELU 4x FFN, learned positions, tied embeddings, no biases).
The token is “o” at position 157 of the running sequence, in ““Why are you sad, Ro”. The trained tiny GPT (the reference run, held-out loss 2.28) gives the next token, “x”, a probability of 75.8%: it has to find “Roxy” earlier in the story and copy it, which is attention’s job. Every picture below is the real vector at that step, one cell per number (orange positive, blue negative, darker is larger in magnitude), recorded by src/block/trace.py, which re-runs the block step by step and checks that its logits equal the model’s own forward pass (largest difference 1.5e-5). The model selector changes the shapes, parameter counts and FLOPs to a real model’s; the pictures and measured values stay the tiny GPT’s.
What the recorded weights show (softmax step): in block 1, heads 1, 6 and 7 look mostly at the previous token, “R” (weights 0.65, 0.70 and 0.31), and head 5 already puts 0.39 on the “x” of the last “Roxy” (position 143). In blocks 5 and 6, several heads park 0.89 to 0.98 of their weight on the opening quote mark (position 150), a sink-like habit, and block 5’s head 4 has its largest weight (0.13) on the “x” of the very first “Roxy” (position 22). The Inside a real model tab measures such heads properly (induction scores, sinks) on SmolLM2-135M.
Why each design choice exists. The scale 1/√d_head: a dot product of two vectors of d_head independent entries with variance 1 has variance d_head, so without the scale the softmax saturates (one weight near 1, gradients near 0) more as heads get wider. Softmax makes the weights positive and sum to one, so the head reads an average whose size does not depend on how many tokens it sees. Several heads let one layer look for several things at once (here one head copies the name, others track nearby words) at the same cost as one wide head. The residual add keeps an identity path from the embedding to the output, so a block only has to learn a correction and gradients reach the first layer. The FFN’s 4x width is the 2017 Transformer’s choice (d_model 512, d_ff 2048); SwiGLU uses three matrices, so Llama-style models cut the width to about 8/3 x d_model to keep the same parameters (Llama 3.1 8B: 14,336 / 4,096 = 3.5, a little wider).
Go deeper (optional): The transformer from zero derives each step and trains the GPT; Attention variants change what each token stores; Positional encodings owns RoPE; Activation functions owns GELU and SwiGLU.
k_proj.weight? (hidden_size 4,096; 32 heads; 8 KV heads; head_dim 128)nn.Linear(in, out) stores its weight as (out, in). q_proj is (4096, 4096). The tempting (4096, 4096) is right for multi-head attention, where K has as many heads as Q; grouped-query attention is why Llama’s K and V are 4x smaller than Q (modeling_llama.py:219-227)..view(B, T, H, hd).transpose(1, 2) moves them there (option 4 is the shape before the transpose).The problem. “How much compute does a model need per token?” decides training budgets and serving cost, and it has a two-line answer once the block is clear. How it works. A weight matrix of shape (out, in) applied to one token is out x in multiply-adds, 2 x out x in FLOPs. Every matrix weight a token passes through is used exactly once, so the weights cost 2N FLOPs, N being the matrix weights a token touches (the input embedding is a row copy and costs nothing; a tied LM head is a matrix product and counts; in a mixture of experts only the active experts count). Attention adds work no weight accounts for: per layer, the query meets t keys (2 x d_attn x t) and the weights meet t values (the same again), so 4 x n_layer x d_attn x t for a token that sees t positions. The backward pass needs two products of the same size per weight (the gradient for the input and the gradient for the weight), so a training step is about 3x the forward: 6N per token when attention is small.
measured PyTorch’s FLOP counter (torch.utils.flop_counter.FlopCounterMode, torch 2.14.1, CPU) on one forward pass of the tiny GPT over the 256-token running sequence: 3,355,443,200 FLOPs, equal to the formula (2N x 256 = 2,952,790,016 for the weights plus 402,653,184 for attention), and the same exact match for the SwiGLU and GQA presets. Forward plus backward on 255 tokens: 10,022,307,840 against 3,340,769,280 forward, a ratio of 3.0. The counter sees the full 256 x 256 score matrix (the mask is added, nothing is skipped), so its attention term is t = 256 for every token; a causal kernel such as FlashAttention skips the masked half, which is the per-token average of t(t+1)/2 / t that the calculator uses for prefill. Script: src/block/flops.py.
published Kaplan et al. 2020, Table 1 (arXiv 2001.08361, read 2026-10-18), writes C_forward = 2N + 2 n_layer n_ctx d_attn with N the non-embedding parameters, and drops the context term because it is “a relatively small fraction” when d_model > n_ctx / 12; with the backward pass “approximately twice the compute”, C ≈ 6N. Their single context term equals the two products here averaged over a causal context (each sees n_ctx/2 positions on average). Their N also leaves out the de-embedding (LM head), which they count apart (2 d_model n_vocab); the calculator below keeps it in 2N, which matters for small models with large vocabularies.
derived from each model’s config.json with the Config calculator’s formulas (window.CC: sliding-window layers stop at their window, MLA decodes in the absorbed form, recurrent layers counted per step); this card only splits CC’s weight FLOPs by operation, and the check line confirms the split adds back to CC’s 2N. Decode: the token at position t reads t cached positions. Prefill: the average over a t-token prompt. The solid line is the slider; the dashed line is where attention over the context equals 2N.
When it matters. For the tiny GPT (d_model 256) attention reaches 2N at 1,878 positions when decoding (3,754 averaged over a prefill); for Llama 3.1 8B (d_attn 4,096) at 28,628 (57,255); for a model whose attention layers all use a window (or for an SSM) the line never comes. A decoder-only layer of width d with a 4x FFN has 12 d² matrix weights (4 d² attention, 8 d² FFN), 24 d² FLOPs, against 4 d t for attention, so for the blocks alone the crossover is t = 6 d for one decoded token and t = 12 d averaged over a causal prefill, Kaplan’s n_ctx / 12 rule; the LM head and a wider FFN push it later. GQA does not move it: it shrinks K and V, not the queries that do the dot products. How to check. Wrap one forward in FlopCounterMode (it counts matrix products only) on the eager path, or compare a profiler’s matmul time to its attention-kernel time at two context lengths. What transfers. FLOP counts are properties of the architecture and transfer exactly; time does not, because decoding is limited by memory traffic (weights and KV cache read per token), not by FLOPs (Performance math).
Where the norm sits decides what happens to the residual stream this walk traces: under pre-norm (the tiny GPT and every current LLM) the stream only grows, block after block; under post-norm it is reset to a fixed size after every sub-layer. The matched runs on this token and this model (the same seed and budget at five learning rates, the gradient reaching each block, and why post-norm at the default rate learns only token frequencies) are section 2 of Normalisation, residuals and stability, which steps through four placements on the same trace.
Four one-line bugs that a from-scratch attention commonly has, each run on the trained tiny GPT with the running sequence (src/block/mistakes.py, CPU). None of them raises an error: the model still produces fluent-looking text, and only the loss shows the damage. That is the case for always checking a rewritten block against a reference forward (here: the rewritten correct forward reproduces the model’s loss exactly, 1.96).
The missing mask does not change the last position (it has no future to see) but corrupts every earlier position’s keys and values from block 2 on, so even generation changes. The missing scale is the mildest here because d_head is only 32 (scores 5.7x too large in spread); at d_head 128 the softmax saturates harder. Splitting heads with .view(B, H, T, hd) cuts the sequence into head-sized slices: shapes are legal and nothing complains.
And the errors that do raise, verbatim (scrubbed of paths), with what each means:
In order: the learned position table has 256 rows, so position 256 does not exist (an RoPE model would run and degrade instead, see Positional encodings); GPTConfig asserts that d_model splits evenly into heads; q @ k without .transpose(-2, -1) multiplies (256 x 32) by (256 x 32); and K, V with fewer heads than Q need repeat_kv (or an attention kernel that supports grouped heads) before the product.
d = 4,096, 32 query heads and 8 KV heads of 128, FFN 14,336. Attention: Q and O are d x d each (2 x 16.8M), K and V are d x 1,024 each (2 x 4.2M): 41.9M. SwiGLU FFN: 3 x 4,096 x 14,336 = 176.2M. Two RMSNorm gains: 8,192. Block: 218.1M; x 32 = 6.98B; plus untied embedding and LM head, 2 x 128,256 x 4,096 = 1.05B: 8,030,261,248, the Hub’s exact count (the Config calculator reproduces it).
Forward 2N + 4 x n_layer x d_attn x t; training about 3x that, 6N when context is short. Training compute about 6 x N x D. For Llama 3.1 8B (N = 7.50B matrix weights including the LM head) over an illustrative 15 trillion tokens: 6 x 7.50e9 x 1.5e13 = 6.8e23 FLOPs (calculated). Measured here: a training step counts exactly 3.0x the forward.
2N = 15.0 GFLOPs for the weights; attention over the context 4 x 32 x 4,096 x 131,072 = 68.7 GFLOPs, 4.6x the weights (calculated with the Config calculator’s formulas). GQA does not reduce this (32 query heads still do the dot products); it reduces the KV bytes read, which is what limits decode speed. Only windows, sparse or latent attention, or fewer attention layers (hybrids) cut the FLOPs.
q · k sums d_head products; with unit-variance entries its variance is d_head. The softmax of large scores is nearly one-hot, its gradient nearly zero, so learning stalls, more so for wider heads. Measured here on the trained tiny GPT: removing the scale raises the loss on the running sequence from 1.96 to 2.88.
4x is the 2017 Transformer’s d_ff = 2,048 for d_model = 512, kept since. A two-matrix FFN of width 4d has 8 d² weights; SwiGLU has three matrices, so width 8/3 d gives the same 8 d² (Shazeer 2020, arXiv 2002.05202). Models then round for hardware: the tiny GPT’s SwiGLU preset uses 704 (8/3 x 256 rounded up to 32), Llama 3.1 8B uses 14,336 = 3.5 x 4,096.
Measure first: at 32k context a Llama-8B-shaped model spends about as much on attention as on all its weights in prefill (crossover 57,255 averaged over a prompt, 28,628 for decode), and decode time is set by bytes read (weights plus KV cache), not FLOPs. Levers: GQA or MLA cut KV bytes (decode speed, batch size) but not FLOPs; sliding-window layers interleaved with a few global ones (Gemma 3, 5:1) cut both, at a cost in long-range recall; replacing most attention layers with SSM layers (hybrids) makes most of the model’s cost independent of context, at a cost in exact copying; a smaller vocabulary or a tied head trims the fixed 2 x d x V. Check each with Attention variants, the KV-cache calculator and the Config calculator, then on a long-context benchmark.
modeling_llama.py (v5.20.1), with line numbersRuns (all measured on Apple M1 Pro, 16 GB, MPS, fp32, at low priority on a shared machine, 2026-10-18): the tiny GPT (5,836,032 parameters) trained with src/data/train.py, seed 0, batch 32 x 256, 1,500 steps (12.3M tokens), AdamW (0.9, 0.95), weight decay 0.1, gradient clipping 1.0, linear warmup then cosine to 10%. Traces, FLOP counts, gradient norms (drawn on the Normalisation page) and mistakes ran on the CPU. Scripts and recorded outputs: src/block/ (trace.py, flops.py, gradnorm.py, mistakes.py, collect_runs.py, code_refs.py, out/).
What transfers to a datacenter model. Shapes, parameter counts and FLOP counts transfer exactly (they are arithmetic on the config). Timings are not quoted here.
Sources. Vaswani et al. 2017, Attention Is All You Need (d_ff = 2,048 for d_model = 512, post-norm, the √d_k scale); Kaplan et al. 2020, Table 1 and section 2.1 (arXiv 2001.08361); Xiong et al. 2020, On Layer Normalization in the Transformer Architecture (arXiv 2002.04745); Shazeer 2020, GLU Variants Improve Transformer (arXiv 2002.05202); transformers v5.20.1 (commit 0ea8779) models/llama/modeling_llama.py; configs as recorded in src/data/configs/. All read 2026-10-18.
A model's config.json is enough to know how many parameters it has, how many it uses per token, how many floating-point operations (FLOPs) each token costs, and how much memory its weights take. This tab does that arithmetic with one set of formulas, shows the formulas with the chosen model's numbers in them, and checks them against the exact stored tensor counts of real checkpoints.
hidden_size), V = vocabulary, nh query heads, nkv key/value heads, dh head dimension, f feed-forward width (intermediate_size), L layers.
Any Hugging Face config of a supported family: Llama, Mistral, Mixtral, Qwen2/3 and Qwen3-MoE, Qwen3-Next, Gemma 1/2/3, Phi-3/4, OLMo 2/3, GPT-2, gpt-oss, Llama 4, DeepSeek-V2/V3/V3.2, Kimi K2, GLM-4.5, MiniMax-M2, Nemotron-H and Nemotron 3 (from hybrid_override_pattern or layers_block_type; Nemotron 3's latent MoE layers included, its MTP layers not; Nano 30B-A3B equals the Hub's stored-tensor count of 31,577,937,344, Super 120B-A12B equals the Hub's count less its MTP layers, checked 2026-10-23), Granite 4.0-H, Falcon-H1, Jamba, Mamba and Mamba-2. Refused with a reason rather than miscounted: GLM-5 (glm_moe_dsa), DeepSeek-V4, Kimi Linear and Kimi K3 (kimi_linear), and Gemma 4; the Architecture map shows their layouts and caches. Llama 4 Scout's config has an empty no_rope_layers, so it is treated as all-global here (transformers fills in one NoPE global layer in 4; see the note under the model). Edit a number (try num_key_value_heads) and press Compute.
Both bars are drawn to the same scale: the top one is everything that must be in memory, the bottom one is what a single token multiplies through. For a dense model they are the same length. For an MoE model the routed experts shrink to k/E of their size in the bottom bar, which is the whole point of MoE: memory scales with the total, compute with the active part.
Try: Llama 3.1 8B (the embedding and the separate output head are 13% of it), then SmolLM2 135M (tied embeddings: the one vocabulary matrix is 21% of a small model), then DeepSeek-V3 (the routed experts are almost everything in memory and a small sliver per token).
Every count below is a product of config fields, written once in src/calc/calc.py and ported line for line to this page. Each block lists the formula, then the same formula with the chosen model's values, then the count for all layers of that kind. Weight matrices dominate; biases and norm gains are listed so the total is exact, not because they matter for cost.
The tiles above give decode and prefill FLOPs at the context you pick; attention FLOPs per token grow linearly with it and pass the weight FLOPs at about 28,600 tokens for Llama 3.1 8B. How many bytes the cache holds, for one sequence or a batch, with windows and fixed states credited, and where it passes the weights, is sized on Long context, whose KV-cache calculator runs the same formulas as this tab (the root's src/calc/calc.py) on 45 model presets. What each attention design keeps per token in one layer is drawn on Attention variants.
attn_impl = "absorb" by default at line 17 and computes the scores against kv_cache and pe_cache at lines 486 to 487, read 2026-10-18), which is why DeepSeek-V3's attention FLOPs per position are large while its cache is small. Sliding-window and chunked layers read at most their window. Recurrent layers (Mamba, Gated DeltaNet) are counted in their step-by-step form, with their fixed state taken as FP32. Weight bytes per step at batch 1 count only the experts one token uses; how many experts a larger batch touches, and a dense model against its MoE twin at equal active parameters, are on Mixture of experts (sections 1 and 8; the twin stepper moved there from this tab on 2026-10-23).Interview arithmetic. Each answer is computed live from the real config with the same code as the calculator, and shows the working. Rough mental numbers to carry: a 4096-wide layer's attention projections with 8 KV heads are about 42M parameters; a SwiGLU feed-forward block is 3df; BF16 is 2 bytes.
The target is not the number in a model's name but the exact count of stored tensors that Hugging Face reports for each repository's safetensors files (read 2026-10-18 at the commit listed in src/calc/inputs/hf_param_counts.json). Those counts include things that are not the main model's parameters, so the check is: calculated main model + MTP layers + vision tower + anything else stored = Hub count, with every addition explained. The second check is the published headline: which way of counting rounds (or truncates) to the figure the vendor printed.
head_dim explicitly. Gemma 7B has 16 heads of 256 on a 3072-wide stream (16 × 256 = 4096 ≠ 3072); Qwen3 32B has 64 heads of 128 on a 5120-wide stream. hidden_size // num_attention_heads gives the wrong attention parameters and the wrong cache for both. Read head_dim when it is there.tie_word_embeddings: true means the output head reuses the input embedding matrix: count Vd once. It still costs 2Vd FLOPs per token as the head. And a tied checkpoint can still store both: Qwen3 0.6B's file saves lm_head.weight as its own tensor, which is why the Hub says 0.75B for a 0.6B model.The formulas live once, in src/calc/calc.py (standard library only); parts/33_js_cc_1core.js is a line-by-line port. Below: the parameter functions as they ran, the validation output, and the check that the page's JavaScript gives the same numbers as the Python on every config at five context lengths.
Columns: calculated main model, MTP layers shipped in the checkpoint, vision tower, other stored tensors (buffers, FP8 scales, a duplicated head), the Hub's count, and the residual.
The other tabs build a transformer from its parts. This one opens trained models and measures what they do with those parts: which earlier tokens each attention head reads, where attention goes when nothing is worth reading, how large the residual stream grows, and what the model would predict if it stopped after layer k. Each measurement explains a design decision met elsewhere on this page.
The models. SmolLM2-135M (Hugging Face, Apache-2.0, revision 93efa2f): a Llama-architecture model with 30 layers, 9 query heads sharing 3 key-value heads, width 576, RoPE, RMSNorm before each sub-layer, tied input and output embeddings. Qwen3-0.6B (Alibaba, Apache-2.0, revision c1899de, run in float16): 28 layers, 16 query heads on 8 key-value heads, width 1,024, plus RMSNorm on every query and key (QK-norm). Pythia-70M-deduped (EleutherAI, Apache-2.0): 6 layers of 8 heads, with checkpoints published from the start of training, which we read but did not train. And the tiny GPT of this topic (6 layers, 8 heads, width 256, trained here on TinyStories; see the running example). The text is the running sequence, the story of Roxy the rhinoceros, re-tokenised by each model's own tokenizer.
Terms. An attention weight aij is how much query position i reads from key position j: one row of the softmax over the scores qi·kj/√d, so each row sums to 1. A head is one such pattern; a layer has several. The residual stream is the vector each token carries from layer to layer; every attention and feed-forward sub-layer reads it and adds its output back.
All values measured on an Apple M1 Pro (MPS for SmolLM2 and Qwen3, CPU for Pythia and the tiny GPT), 2026-10-18, torch 2.14.1, transformers 5.20.1. These are deterministic forward passes on fixed inputs: what transfers to a datacenter GPU is everything here except the timings (none are quoted).
The problem. Fast attention kernels never build the T × T matrix of weights: FlashAttention and PyTorch's scaled_dot_product_attention (SDPA) stream over keys and keep only running sums (FlashAttention). So the weights you want to look at do not exist in a normal forward pass.
How to get them. Load the model with attn_implementation="eager". Eager attention is the textbook arithmetic, and it returns the weights. In transformers v5.20.1 (commit 0ea8779), src/transformers/models/llama/modeling_llama.py, which SmolLM2 runs:
Lines 180 to 202, abridged (signature joined, comments ours). Lines 253 to 255 pick the function: ALL_ATTENTION_FUNCTIONS.get_interface(self.config._attn_implementation, eager_attention_forward); line 331 records each LlamaAttention's second output as outputs.attentions. The softmax runs in float32 even for a float16 model (line 197). Qwen3 differs only by RMSNorm on queries and keys first (modeling_qwen3.py lines 229 and 244). Lines located by pattern: src/inside/locate_source.py.
The mistake. With the default SDPA path, asking for weights gives nothing usable. Our run printed:
From src/inside/extract_pretrained.py (SDPA's function returns attn_output, None: integrations/sdpa_attention.py line 182). The cost of eager: it materialises B·H·T² weights per layer, which is fine for 226 tokens and out of the question at 128k.
How we measure the rest without editing the library: transformers lets you register your own attention function (AttentionInterface.register). Ours is the eager arithmetic plus a rule about which keys a query may see; with no rule it reproduces the model's loss exactly ( on the running text, both ways). The sink and window experiments below only change that rule.
The problem. "Attention lets every token look at every earlier token" says what a head may do. A trained model uses that freedom very unevenly, and the patterns it settles on are what the architecture choices on this page are really about: a head that only ever reads the previous token needs no long cache; a head that parks most of its weight on token 0 is why streaming caches keep that token.
How to read the explorer. The grid has one cell per head of SmolLM2-135M (rows are layers 0 to 29, columns heads 0 to 8), coloured by the score you pick. Click a cell to draw that head's map: row i is query token i, column j key token j, darker means more weight, and everything above the diagonal is empty because of the causal mask. Click a token in the text to see what it reads in that head.
What the explorer shows (scores defined under the grid, all on the running text unless noted):
When it matters. Head patterns decide what can be pruned, cached or windowed. Gemma 3 and gpt-oss make most layers local (a sliding window) because most heads read nearby tokens; they keep some global layers for the few heads that do not (Architecture map). How to check it on any model: eager attention, a few hundred tokens, and the three scores above: about 20 lines (head_scores in src/inside/make_page_data.py).
The problem. Much of what a language model does with its context is copying: a name introduced in sentence one, a variable defined at the top of a file, a phrase the user typed. The model cannot store those in its weights; it must find them in the context at run time. Olsson et al. (Anthropic, 2022, In-context learning and induction heads) traced much of this to one circuit, the induction head, and reported "a phase change that occurs early in training for language models of every size" when it appears.
How it works. Two heads in two layers. A previous-token head (section 2) writes into each position j the identity of token j−1. Later, at the current position whose token is A, an induction head builds a query that means "find positions whose previous token was A". It matches the position right after the earlier A, reads its token B, and raises B's logit. The rule it implements: [A][B] ... [A] → predict [B]. It needs two layers because the "previous token" information must already sit in the key before the second head can match on it.
Found from the weights alone. Because the circuit is two heads composing, it can be found without running the model: take a head that attends one token back and multiply what it writes (its output-value matrix) into each later head's query-key matrix; heads whose keys read strongly from it are induction candidates (K-composition, Elhage et al. 2021). GPT-6 Astra did this without being shown the method, on the four middle blocks of three character-level transformers, with no input or output layers and no forward passes: its list matched the heads the repeated-random-string test measured in all three models, with no false ones (Sparks of Weight-Space Programming, Experiment 3). The activation test below stays the check that needs no assumption about which matrices compose.
The clean test. Feed a block of random tokens twice: <|endoftext|> R R, with R = 100 token ids drawn uniformly (8 random draws, seed 0). On the first copy nothing can be predicted, so the loss is near or above log(vocabulary). On the second copy every token is predictable by copying. The induction score of a head is its mean attention weight, over queries in the second copy, on the token just after the earlier occurrence of the current token: the exact place an induction head should look.
One input, published checkpoints of one training run. Top: loss on each position of the sequence (first copy left of the line, second copy right). Bottom: what the strongest induction head of that checkpoint reads from one query in the second copy (position 150), with the "right place to look" marked. published checkpoints measured here (CPU)
The tiny GPT does not get there. Trained here for 1,500 steps (12.3M tokens, about 5 minutes), it never forms an induction head: its best induction score is and its loss on the second copy of random tokens () is no better than on the first (; both above log 4,096 = 8.32, because random ids are far outside TinyStories). Even a repeated 127-token passage of real validation text only drops from to . That is a budget fact, not an architecture fact: Pythia-70M, the same shape (6 layers of 8 heads), formed its induction head between and billion tokens (chart above), about times our whole run. What the tiny GPT does learn is to reuse the name it has just read. The four tokens of "Roxy" are R, o, x, y; predicting x after R o needs the context. Its loss on each of the 11 xs in the running sequence:
So the tiny GPT reuses a name from its context although no classic induction head shows (its best induction score on repeated random tokens is ): how it does so is unconfirmed (not investigated here). The transformer from zero tracks the same reuse through training: on the same retrain, the three tokens after R cost 9.0 nats together at the name’s first appearance, 4.5 at the second and 1.6 on average from the third on, and the drop for repeats starts at step 500.
The cost and when it matters. An induction head needs the earlier tokens kept in full: that is the case for attention with a KV cache and against a fixed-size state. Jelassi et al. (2024, Repeat After Me) show that transformers "dramatically outperform state space models at copying and retrieving information from context"; hybrids keep a few attention layers largely for this (Reading: beyond attention). Sliding-window layers can only copy within their window. How to check a model or a change: the repeated-random-tokens loss (first copy against second copy) is a 10-line test that needs no labels; run it after any change to attention, position encoding or caching.
The problem. Softmax weights must sum to 1. A head that has nothing useful to read at some position still has to put its weight somewhere. Trained models settle on one place: the first token. Xiao et al. (2023, StreamingLLM) named this the attention sink. The first token is a natural dump: every later query can see it, and its residual vector can be made distinctive (section 5) so that a head can match it without moving the output much.
The first token, whatever it is. Neither SmolLM2's nor Qwen3's tokenizer adds a beginning-of-sequence token by default, so above the sink sits on the word "Once". Put <|endoftext|> in front and the sink moves to it: in SmolLM2, the weight left on "Once" falls to at most per layer, and the loss on the same text tokens moves from to .
What happens when the sink is removed. Our attention function can forbid every query from reading token 0 (each row renormalises over the other keys). Same model, same text:
The greedy continuation of "Once upon a time," shows what that loss means (SmolLM2, 40 new tokens, real outputs):
1,024 tokens of TinyStories validation stories through SmolLM2. Each query may read only the last 64 tokens (a sliding-window cache), or those 64 plus the first 4 tokens (StreamingLLM's fix). Positions stay as they are; with RoPE, masking keys is the same as evicting them from a cache. Step through the query positions; the strip shows which keys the query can read under each rule, and the chart the loss per block of 32 tokens. measured here (MPS)
StreamingLLM's abstract states that window attention "fails when the text length surpasses the cache size" and that "keeping the KV of initial tokens will largely recover the performance". Our small run reproduces both, independently; here a single kept token recovers as much as four ( against , Qwen3: against ).
Designs that build the sink in. Instead of letting a model hijack a real token, give every head somewhere to put weight on purpose. In gpt-oss, "each attention head has a learned bias in the denominator of the softmax", which lets a head "pay no attention to any tokens" (OpenAI, gpt-oss model card, section 2.2, 2025-08-08; the tiny GPT's sink preset implements it, Attention variants). StreamingLLM also trained models with a dedicated learnable sink token. When it matters: any cache that evicts tokens (sliding windows, streaming chat, KV compression) must keep the sink, and any quantisation or pruning scheme must leave the first token's enormous vector alone (next section). How to check: the mean weight on token 0 by layer, as in the chart, takes one eager forward pass.
The problem. In a pre-norm block (the norm sits before each sub-layer, Block lab), every sub-layer adds its output to the residual stream and nothing ever rescales it. So the stream's size is free to grow with depth, and a model can use that freedom to make a few numbers enormous. Sun et al. (2024, Massive Activations in Large Language Models) found such "massive activations" across many LLMs, sometimes about 100,000 times the typical value (paraphrase of their abstract); they sit in a few fixed dimensions on a few tokens (often the first), stay nearly constant whatever the input, act like bias terms, and are what lets attention concentrate on those tokens. That is the mechanism behind the sinks of the previous section.
What we measured. In SmolLM2, one dimension of the residual stream (dimension of 576) on the first token reaches at layer 12 and stays above until the last block, while the median absolute value of an entry at that depth is about : a ratio of about to 1. Layer 12 is exactly where the sink switched on (section 4). In layers 3 to 9 the same dimension already reaches about , on token 4, the first comma ("Once upon a time,"), while the weight on token 0 in those layers is still small (0.07 to 0.09): the big value moves to the first token at the layer where the sink appears. The tiny GPT, which never formed a sink, also has no massive activation: its largest entry after training is . Qwen3-0.6B:
Why an architect cares.
self.norm at modeling_llama.py line 402). Post-norm models renormalise after every block instead and pay for it in stability (Normalisation, residuals and stability, section 2).How to check: hook the output of every decoder layer (a forward hook, as in extract_pretrained.py; the hidden_states output of a Hugging Face model applies the final norm to its last entry) and print the largest |x| per layer with its token and dimension.
The idea (nostalgebraist, 2020, interpreting GPT: the logit lens). The residual stream is one shared space that every layer writes into and the unembedding finally reads. So apply the model's own final norm and unembedding to the stream after layer k and read off a next-token distribution. If the stream is a gradually refined prediction, the early guesses should drift towards the final one.
Rows are layers (0 = the embedding, 30 = the model's output); columns are positions in the running text. Each cell shows the top-1 predicted next token at that layer; green means the true next token got high probability. Drag to move through the text. measured here (MPS)
What we measured.
When it matters and the caveat. The lens is a cheap first look at where in depth a prediction forms, useful when deciding where to cut layers (early exit, layer pruning) or where to read features from. It is not exact: middle layers may encode the answer in directions the final unembedding does not read, which is why the tuned lens (Belrose et al., 2023, arXiv 2303.08112) learns a small map per layer (not run here). How to check: model.lm_head(model.model.norm(h)) for each hooked h; the last layer must reproduce the model's logits exactly (ours: max difference ).
outputs.attentions is not a usable list of tensors (section 1). Load with attn_implementation="eager", or switch with model.set_attn_implementation("eager"), and keep the sequence short: eager attention materialises every weight.hidden_states entry as the raw residual streamScripts and recorded outputs: src/inside/ (extract_pretrained.py, pythia_phase.py, train_snapshots.py, tiny_analysis.py, make_page_data.py; outputs in src/inside/out/). Models: SmolLM2-135M revision 93efa2f097d58c2a74874c7e644dbc9b0cee75a2; Qwen3-0.6B revision c1899de289a04d12100db370d81485cdf75e47ca; Pythia-70M-deduped revisions listed in src/inside/out/pythia_manifest.json.
Every major open decoder from GPT-2 (2019) to Kimi K3 (July 2026) on the same axes: attention, position, normalisation, feed-forward, sequence mixer, depth and width. 46 models, each row read from its own config.json where one is public, with dates, licences and published parameter counts linked to the model card or paper. KV-cache figures are calculations from the configs (bf16, 2 bytes per number), not measurements.
Each dot is one model, placed by release date in its lab's lane. Colour it by attention design or by feed-forward kind. A ring around a dot means sliding-window layers; a hollow dot means closed weights. The numbered flags mark where each shift first appears in this map (not necessarily its first use anywhere: the flag says which model). Press play to sweep the years and watch the counters.
Take a real model's width, depth and head count, build it the 2018 way (post-norm LayerNorm, a learned position table, one K and V head per query head, a 4d GELU feed-forward), then apply the shifts that model adopted, one at a time, in the order the field adopted them. The drawing is one block; the counters are that model's whole cache and one layer's parameters, recalculated at every step from its config.json. It steps through the shifts by itself once in view; choose a model, or take the controls to step at your own pace.
How the counters are made: src/map/shifts.py. KV per token counts every cache-growing layer at full cost (bf16); the 131,072-token sequence credits sliding windows (a windowed layer keeps its last W entries) and lists a hybrid's fixed recurrent state apart. Attention parameters are for one attention layer; FFN parameters for one FFN layer (for MoE: total, and active per token including the router). For MoE targets the dense FFN shown before the MoE step has the same active width as the final MoE layer, so that step shows parameters multiplying at constant compute. DeepSeek-V3's MHA baseline uses 128-dimension heads, as the DeepSeek page draws it. These are calculations from configs, not measurements; full model sums are in the Config calculator.
Filter, sort by any column (click its header), and click a row for the full card with its layer strip and sources. "KV / token" is bf16 over all layers at full cost; "at 128K" credits sliding windows. Published parameter counts are as the source states them; where a cell says config, the value is the config's own field because no published figure was found.
Pick the constraint that binds. The card gives the design choice on each axis with the reason and the cost, then ranks the models in this map that already made that choice, by the number that matters for the constraint (computed from the same rows as the table).
Answers are computed from the table's rows when you click.
config.json says num_key_value_heads: 128. Plugging that into 2 x layers x kv_heads x head_dim x 2 bytes gives 3,904 KiB per token (with 128-dimension values), about 3.8 MiB. MLA caches one latent of kv_lora_rank (512) plus one RoPE key of qk_rope_head_dim (64) per layer: 576 x 61 x 2 bytes = 68.6 KiB. The field is there for the code path that rebuilds heads; check for kv_lora_rank before using it.max_position_embeddings as the trained contextnum_key_value_heads: 16 with head_dim: 256, but those apply to the 50 sliding layers. Its 10 global layers use num_global_key_value_heads: 4 of global_head_dim: 512 and store one tensor for both K and V (attention_k_eq_v). Counting all 60 layers the sliding way gives 960 KiB per token; the config's own layer types give 840 KiB.config.json on Hugging Face (copies in src/map/inputs/configs/, fetched 2026-10-18; gated Meta and Google repos read from public mirrors with the same shapes). GPT-3 and PaLM have no public config: their rows use the papers' tables. Dates, licences and parameter counts link to the model card, paper or announcement in each row's card; where a 2025 or 2026 date comes only from Sebastian Raschka's LLM Architecture Gallery (a third-party list, Apache 2.0) the row says "gallery".The tabs of this page, its ten child pages, the knowledge base pages it leans on, the papers behind it and the best outside resources, each with an approximate time. Outside sources are marked maker (written by the lab or company that builds the model or library: authoritative on how it works, not neutral on whether to use it) or third-party (independent researchers and writers). Links checked on 2026-10-18.
The map: one Llama 3.1 8B decoder block in 3D, each part with the page that owns it, and the comparison table, then one short section per part with the distinction that only shows across the child pages: vocabulary size, the four levers on the cache, total against active parameters, the four long-context walls, the arithmetic, reading a config, choosing. 26 min, plus 13 in closed details.
One real token of the running sequence through one decoder block, with the recorded vector, shape, parameters and FLOPs at every step for six real models; where the FLOPs go as context grows. 15 min, plus 4 in closed details.
Any config.json to parameters, active parameters, weight memory and FLOPs per token; checked against stored tensor counts of real checkpoints. The dense twin of an MoE is on Mixture of experts; the KV cache is sized on Long context. 13 min, plus 11 in closed details.
SmolLM2 taken apart: where the attention weights come from, attention maps, induction heads, attention sinks, massive activations and the logit lens. 24 min, plus 2 in closed details.
Decoder lineage from GPT-2 to 2026 on the axes of this page: attention, position, norm, FFN, mixer, shape, size, licence; a timeline and a design picker. 14 min, plus 1 in closed details.
In reading order; the Reading tab's Child pages section says which section each extends. Times are each page's Reading tab as its header states (230 words a minute).
One block, every shape, a GPT you train; why a KV cache exists. 40 min, plus 22 in closed details.
BPE, byte-level, unigram, vocabulary size, the language tax, failure modes, special tokens. 46 min, plus 15 in closed details.
MHA, MQA, GQA, MLA, windows, NSA, DSA, DeepSeek-V4's compression, sinks and gates. 37 min, plus 28 in closed details.
Absolute and relative schemes, RoPE and its base, context extension, five schemes run past their trained length. 40 min, plus 21 in closed details.
The dense twin, routers, load balancing, capacity, fine-grained and shared experts, expert parallelism. 35 min, plus 21 in closed details.
Pre-norm against post-norm, RMSNorm, QK-norm, initialisation, loss spikes. 31 min, plus 15 in closed details.
KV cache sizing for any model, the levers that shrink it, local and global attention, effective context. 28 min, plus 13 in closed details.
SSMs, Mamba, linear attention, RWKV, the delta rule and hybrids. 37 min, plus 20 in closed details.
Decoder-only, encoders, encoder-decoder, multi-token prediction, diffusion LMs. 34 min, plus 14 in closed details.
A survey of released architectures: which open model made which choice, read from config.json. 28 min, plus 9 in closed details.
The labs, their models, benchmarks and prices; DeepSeek (its MLA explainer now lives on Attention variants), Alibaba: Qwen the Qwen hybrids.
Sampling and Decoding, Batching, KV cache and scheduling, Speculative decoding (incl. MTP), vLLM.
Performance math, Memory technology and the KV cache, Writing kernels, incl. FlashAttention.
Normalisation and initialisation, Activation functions, Sequence models: the pre-transformer lineage, Linear algebra, Matrix calculus and backprop, Numerical computing.
Long-context and multimodal benchmarks: effective context, measured.
Attention Is All You Need, RoFormer, FlashAttention, PagedAttention.
Switch Transformers, Mixtral, DeepSeek-V3, The Llama 3 Herd, Qwen3, OLMo 2.
Andrej Karpathy, January 2023. A decoder written live in PyTorch, from bigrams to self-attention, residuals and LayerNorm. Pairs with nanoGPT and the newer nanochat. about 2 h
Harvard NLP (2018, updated 2022): the original paper interleaved with runnable code, encoder-decoder and all. about 1 h 30 min
Jay Alammar, 2018. Pictures of Q, K, V and multi-head attention; the gentlest first read. about 30 min
Google DeepMind authors, 2025. Parameters, FLOPs and KV cache per component, worked; the best companion to section 8. about 1 h
kipply, 2022. KV cache, memory-bound decode and FLOP counting for serving. about 40 min
EleutherAI, April 2023. The 6N rule, memory for training, worked numbers. about 25 min
Sebastian Raschka, from July 2025, kept updated, with the LLM Architecture Gallery: what changed inside the block from DeepSeek-V3 onward, with diagrams. about 1 h
Lilian Weng, January 2023. A survey of attention, position and efficiency variants up to 2022; a map of names. about 1 h 30 min
Anthropic, December 2021. The residual stream as a communication channel, heads as independent read-write operations; with In-context learning and induction heads (2022). about 2 h for both
nostalgebraist, 2020. Decode the residual stream after every layer. about 20 min
EleutherAI, 2021. RoPE derived and compared, from the team that first trained it at scale. about 25 min
Maarten Grootendorst, 2024. Routers, top-k, capacity and balancing in pictures; his visual guide to Mamba does the same for SSMs. about 40 min each
Tri Dao, May 2024, four parts. How SSMs and linear attention are the same computation, by Mamba's co-author. about 1 h
Course with lectures on architectures, hyperparameters and MoE, and assignments that build and train a transformer. a course: tens of hours; the architecture lecture about 1 h 20 min