Topic: llm-architecture

The map of what is inside a large language model: one decoder block, its parts (tokens, the sequence mixer and its cache, position, the feed-forward network and mixture of experts, normalisation and the residual stream, shape, family and objective), how the choices for each part compare, and which child page teaches each in depth. Tiny models trained on an Apple M1 Pro, a small open model inspected, frontier models compared from their configs, published results kept apart. Reading: 26 min, plus 13 in closed details. Data as of October 2026.

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.

New terms on this page (each defined again where it is used):
Residual stream: the vector each position carries through the stack; blocks only add to it.
Sequence mixer: the sublayer where a position reads other positions (attention, or a recurrent layer).
KV cache: the keys and values of past tokens that attention keeps so it never recomputes them.
Prefill / decode: processing the prompt at once (compute-bound) / one new token per step (memory-bound).
Total / active parameters: what must sit in memory / what one token multiplies through (they differ in MoE).
Hybrid: a stack that mixes a few attention layers with many fixed-state recurrent layers.

1. The decoder in one screen

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.

  1. Tokens in. A tokenizer cuts text into ids from a vocabulary of 128,256; each id picks one row of the 128,256 × 4,096 embedding table, 525.3M weights (the four words are illustrative). Owner: Tokenizers.
  2. The residual stream and its norms. The stream holds one vector of d numbers per position (4,096 here); each sublayer reads an RMSNorm copy (4,096 learned gains) and adds its result back, so blocks only ever add. Owner: Normalisation, residuals and stability, whose Fig. 2 moves the norm.
  3. Attention, with position. Wq and Wo are 4,096 × 4,096, but Wk and Wv only 4,096 × 1,024, because the 32 query heads share 8 KV heads (GQA): 41.9M weights in all. RoPE turns each query and key by its position before they meet. Owners: Attention variants (Fig. 3, heads sharing KV heads) and Positional Encodings (Fig. 4, the RoPE dials).
  4. The KV cache grows. Every past token leaves its keys and values in every layer: 2 × 32 layers × 8 KV heads × 128 × 2 bytes = 128 KiB per token, 16 GiB for one 128K request (derived), and every decode step reads all of it (section 4). Owners: Long context sizes it; Attention variants shrinks each entry.
  5. Or a fixed state. A recurrent or state-space layer folds each token into a state of fixed size instead (drawn illustrative), so memory per sequence stops growing, at the price of exact recall; hybrids keep a few attention layers that still grow a cache (section 4). Owner: Beyond attention.
  6. The FFN: four fifths of the block. SwiGLU's three plates hold 3 × 4,096 × 14,336 = 176.2M weights, 81% of the block's 218.1M. Mixture of experts cuts this part into many experts and a router runs a few for each token (8 and 2 drawn, illustrative): MoE targets the FFN because the weights are there. Owner: Mixture of experts.
  7. 32 blocks on one stream. The block repeats 32 times, 218.1M weights each; with the two vocabulary tables that makes 8.03B, the model's size. Owners: The transformer from zero builds and trains this block; the LLM architecture gallery stacks released models layer by layer from their configs.
  8. A distribution out. A final RMSNorm and the 4,096 × 128,256 unembedding give one logit per vocabulary entry, and a softmax turns them into next-token probabilities (bar heights illustrative). Training predicts every position's next token at once under a causal mask; what the mask and the objective can be instead: Families and objectives.

The same map as a table: the usual choice, the alternatives and what each trades

PartUsual choice in 2026AlternativesWhat the choice tradesOwner
Tokens and embeddingByte-level BPE, vocabulary of about 100K to 260KSentencePiece unigram, bytes, smaller vocabulariesShorter sequences against a bigger embedding tableTokenizers
Sequence mixer: attention variantGrouped-query attention (GQA)MHA, MQA, MLA, sliding window, trained sparse attentionBytes each token keeps and each step reads, against qualityAttention variants
Sequence mixer: attention or a fixed stateAttention; hybrids in a growing share of flagshipsState-space or linear layers (Mamba, Gated DeltaNet), mixed with a few attention layersConstant memory per sequence against exact recallBeyond attention
Context and its cache128K or more, with windowed layers in some modelsGlobal layers only, local : global mixes, cache evictionMemory and compute per token of context, against what the model can still useLong context
PositionRoPE, with a scaling rule for long contextLearned or sinusoidal absolute, ALiBi, no position (NoPE) on some layersBehaviour past the trained lengthPositional Encodings
Feed-forwardSwiGLU; mixture of experts (MoE) in most large open modelsGELU MLP of width 4d; dense against sparseCompute per token against memory for all expertsMixture of experts
NormalisationPre-norm RMSNorm, often QK-normPost-norm LayerNorm (2017), norms after the sublayer, both sidesTrainability at depth and loss spikesNormalisation, residuals and stability
ShapeWidth about 100 to 130 times the depth in large modelsDeeper and thinner small modelsSame parameters, different latency and qualityThis page (section 8)
Family and objectiveDecoder-only, next-token predictionEncoder-only (masked tokens), encoder-decoder, multi-token prediction, diffusion LMsWhat the model can be asked to do, and how fast it generatesFamilies 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.

2. Tokens in, a distribution out

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

3. The block and its residual stream

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):

h = x + Attention(Norm(x))
x′ = h + FFN(Norm(h))
x, h, x′
the residual stream before, between and after the two sublayers: one vector of d numbers per position
Attention
the sequence mixer: the only step where a position reads other positions (section 4)
FFN
the feed-forward network: the same small MLP applied to each position on its own (section 6)

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.

Predict: in one Llama 3.1 8B block, what share of the weights sits in the feed-forward network rather than in attention?

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

One token through one Llama 3.1 8B block: every step's shape and weights
StepWhat happensShape out (one token)Weights
NormRMSNorm: divide by the root mean square, multiply by a learned gain4,0964,096
Q, K, VThree linear maps. 32 query heads of 128, but only 8 key and 8 value heads (GQA)Q 32 × 128; K, V 8 × 1284,096 × 4,096 + 2 × 4,096 × 1,024 = 25.2M
RoPERotate Q and K by the position (section 5)samenone
AttentionEach query head scores the T cached keys of its group, softmax, weighted sum of values32 × 128 = 4,096none (cost grows with T)
Output proj.Merge heads back to d4,0964,096 × 4,096 = 16.8M
Addh = x + attention output4,096none
NormRMSNorm again4,0964,096
FFNSwiGLU: gate and up to 14,336, SiLU(gate) × up, down to 4,09614,336 inside, 4,096 out3 × 4,096 × 14,336 = 176.2M
Addx′ = h + FFN output4,096none

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

Four fifths of a Llama 3.1 8B block's weights are in the FFN, so attention design changes the cache far more than the parameter count

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()).

4. The sequence mixer: attention, its cache, and the fixed-state alternative

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:

Attention(Q, K, V) = softmax( Q K⊤ / √dh + M ) V
Q, K, V
T × dh matrices, one row per position; dh is the head dimension (64 to 256 in current models)
√dh
a dot product of dh unit-variance terms has spread about √dh; dividing keeps the softmax from saturating into a one-hot (Vaswani et al. 2017, section 3.2.1); H heads run in parallel, each with its own projections, and are concatenated back to d (Inside a real model finds what SmolLM2's heads track)
M
the causal mask: 0 where a query may look (itself and earlier), minus infinity for later positions

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:

KV bytes per token = 2 × L × Hkv × dh × b
2
keys and values
L
layers that keep a cache
Hkv
key-value heads per layer, set by the attention variant (not the query heads)
b
bytes per number: 2 in BF16, 1 in FP8

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

Four levers on the cache, owned by three pages

Every design since GQA pulls one of four levers, and which one decides what is saved, storage or reads, and what is given up.

LeverShrinks what a token stores?Shrinks what a step reads?What it gives upSeen inOwner
A smaller entry per token: fewer KV heads (GQA, MQA), a compressed latent (MLA), an FP8 cacheYesYesSome quality, most for MQA; MLA needs extra projections and its own kernelsGQA: Llama 3, Qwen3, Gemma 3, gpt-oss. MQA: PaLM, Gemma 3 270M. MLA: DeepSeek-V2/V3, Kimi K2, GLM-5Attention 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 fromYesThe indexer can miss a key that matteredNSA; DeepSeek-V3.2 (DSA), GLM-5; DeepSeek-V4 also compressesAttention variants
Keep fewer tokens in some layers: sliding windows, local : global mixes, evictionCapped, not smaller per entryYesA windowed layer cannot see past its window; far recall rests on the global layersMistral 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 stateYes, in those layers; the few attention layers still grow a cacheYesA fixed state is a lossy summary: weaker exact recall and copyingQwen3-Next, Jamba, Nemotron 3 Super, Kimi K3Beyond 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).

The fourth lever: how a recurrent layer keeps a fixed state

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

2026 configs on these levers (derived from each config.json)

Caches derived as the Architecture map computes them (BF16, every cache-growing layer counted); sizes are the makers' cards, vendor.

  • Windows. Gemma 3 27B keeps 496 KiB per token by the formula (62 layers, 16 KV heads of 128), but at 128K its 52 windowed layers (window 1,024) hold only 416 MiB together and its 10 global layers 10 GiB, about 10.4 GiB against the 62 GiB the per-token figure suggests. Gemma 4 31B keeps Gemma 3's 5 sliding layers (window 1,024) per global layer, and its 10 global layers store one tensor for both K and V (4 KV heads of 512): a 128K request holds about 5.8 GiB, against 105 GiB if every layer kept every token.
  • Latent and sparse. GLM-5 moves from GQA to MLA with DeepSeek's sparse indexer, 87.75 KiB per token. DeepSeek-V3.2's main cache is DeepSeek-V3's 68.6 KiB per token, and its indexer keeps a second, smaller cache of keys, 15.25 KiB per token: 83.88 KiB with both. DeepSeek-V4-Pro (1.6T parameters) caches each layer's history compressed 4 or 128 times plus a 128-token window (Attention variants draws it).
  • Hybrids. Qwen3-Next keeps full attention in every fourth layer (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).
Published and measured evidence on what each lever costs
  • GQA. The GQA paper converts multi-head checkpoints by continued training on "5% of original pre-training compute" and reports that "uptrained GQA achieves quality close to multi-head attention with comparable speed to MQA" (Ainslie et al. 2023, authors' own runs).
  • Tensor parallelism. MQA's single KV head must be replicated on every GPU, while GQA with 8 groups keeps most of MHA's quality at an eighth (for 64 heads) of its cache and its 8 KV heads split cleanly over 8 GPUs.
  • MLA. DeepSeek reports that MLA in DeepSeek-V2 "reduces the KV cache by 93.3% and boosts the maximum generation throughput to 5.76 times", against its earlier dense DeepSeek 67B (DeepSeek-V2 abstract, vendor; that comparison also changes the model, so it is not MLA alone). At DeepSeek-V3's shape (61 layers, 128 heads of 128) full MHA would keep 3,904 KiB per token; MLA keeps 68.6 KiB, 57 times less (derived).
  • The variants on the tiny GPT (same seed and token budget, held-out loss after 1,500 steps of 8,192 tokens, RoPE in every preset): MHA 2.160 (6,144 bytes of cache per token in BF16), GQA-4 2.185 (3,072), GQA-2 2.182 (1,536), MQA 2.177 (768), MLA 2.255 (960), sliding window 64 2.173, and 2 local : 1 global layers at window 64 2.154 measured. A second seed moved MHA by 0.016, so the grouped variants cost nothing measurable at this size; MLA is about 0.1 worse (seed 1: 2.248), which does not reproduce DeepSeek's result (Attention variants discusses why).
  • Decode is a memory-traffic story. One attention layer of Llama 3.1 8B's shape with 32K cached tokens (batch 4, on the laptop's GPU) takes 0.34 of MHA's time with GQA-8, 0.09 with MQA and 0.20 with absorbed MLA, against cache bytes of 0.25, 0.031 and 0.070 measured: the ratios follow the bytes; the milliseconds do not transfer to a datacenter GPU.
  • Fixed state against attention. Jelassi et al. 2024 prove that "a two layer transformer can copy strings of exponential length while" fixed-state models "are fundamentally limited by their fixed-size latent state", and find pretrained transformers "dramatically outperform state space models at copying and retrieving information from context". The same limit measured here, a pretrained SSM against a transformer on copying and the tiny GPT as SSM, hybrid and attention, is sections 8 and 9 of Beyond attention.
  • Sinks in SmolLM2-135M. Under 0.09 of the attention lands on the first token in layers 0 to 11, and 0.31 to 0.74 from layer 12 on. Masking the first token as a key in every layer raises the loss on the running text from 1.563 to 1.648 and derails generation ("Once upon a time, and the people were so much in love with him, that they would not let him go out of the house."). On 1,024-token stories a 64-token sliding window without the first token doubles the loss after the window (3.36 against 1.62); keeping just the first token brings it back to 1.81 measured. The tiny GPT, trained on 12.3M tokens, has no sink: at most 0.05 on the first token in any head.

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

5. Position: telling attention where each token sits

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.

Measured: past the trained length on the tiny GPT

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

6. The feed-forward network and mixture of experts

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.

Expert size, balancing and what the tiny GPT measured

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

7. Normalisation, residuals and stability

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.

  • RMSNorm (Zhang and Sennrich 2019) divides by the root mean square and drops LayerNorm's mean subtraction and bias: one reduction instead of two, no measured quality loss; universal in current models.
  • QK-norm: RMSNorm on queries and keys before the dot product, so attention scores cannot grow without bound, a known source of loss spikes (Dehghani et al. 2023; used in OLMo 2, Gemma 3 and Qwen3).
  • Norms after the sublayer: OLMo 2 normalises each sublayer's output before adding it, x + Norm(F(x)); Gemma 3 normalises both before and after (Gemma 3 report).

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.

Measured runs and newer variants
  • Placements and fixes on the tiny GPT. Post-norm with a 500-step warmup is the best of eight placement runs (2.138), and QK-norm is the fix that saves a run at ten times the default rate (2.432 against 4.295); the runs, the gradient reaching each block and the stream under each placement are sections 2 and 4 of Normalisation, residuals and stability measured.
  • Massive activations. In SmolLM2-135M dimension 507 of the first token's residual stream reaches 20,156 at layer 12 and stays above 4,047 to the last block, while the median entry at that depth is about 1.6, a ratio near 13,000 to 1; Qwen3-0.6B shows the same thing, dimension 35 of the first token at 6,160 in layer 26, about 1,100 times its median. The tiny GPT, without a sink, has none: its largest entry after training is 36 measured.
  • Newer variants, read from configs and code (transformers v5.20.1): Gemma 4 multiplies by a plain RMSNorm gain where Gemma 1 to 3 used 1 + gain (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).

8. Shape and the arithmetic that ties the parts together

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

N ≈ L × (attention + FFN) + 2Vd
FLOPs per token ≈ 2N + 4 L T H dh
attention
2d² for Q and output, plus 2 d Hkv dh for K and V (4d² with full MHA)
FFN
3 d dff for SwiGLU (2 d dff for a plain MLP; 8d² at dff = 4d, hence the classic 12 L d²)
2Vd
embedding and unembedding (Vd once if tied)
4 L T H dh
the attention term for one token attending to T earlier tokens: scores Q K⊤ and the weighted sum with V, 2 FLOPs per multiply-add each; it does not depend on Hkv, so GQA shrinks the cache, not these FLOPs

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, with five real models

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.

ModelWidth dDepth Ld / L
SmolLM2-135M5763019
Llama 3.1 8B4,09632128
Llama 3.1 70B8,19280102
Llama 3.1 405B16,384126130
DeepSeek-V37,16861118

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

Checked against the checkpoints

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

9. Long context: four walls, four pages

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:

WallWhat limitsRemediesHow to checkOwner
1. MemoryThe 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 cacheCompute 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. ComputePrefill 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 layersTime a prefill at that lengthLong context, Beyond attention
3. PositionRotation angles past the trained length were never seen (section 5)RoPE scaling plus a long-context training phaseRead rope_scaling and max_position_embeddingsPositional Encodings
4. UseA model can fit and run 128K tokens and still not use themLong-context training data; retrieval-style evaluationRun a long-context benchmark at the length you need, not the length on the cardLong 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.

Measured on the Long context child (CPU)

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

10. Families and training objectives

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):

FamilyAttention maskObjectiveGood atExample
Decoder-onlyCausal: each token sees itself and earlier tokensPredict the next token at every positionGeneration; everything, at scaleGPT-3, Llama, Qwen, DeepSeek
Encoder-onlyBidirectional: every token sees every tokenRecover masked tokens (15% in BERT)Embeddings, classification, retrieval; cannot generate fluentlyBERT
Encoder-decoderBidirectional encoder over the input; causal decoder that also attends to itRebuild corrupted spans, or input-to-outputTranslation, summarisation; the input is encoded onceT5, 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).

Measured: MTP on the tiny GPT

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

11. Reading a model's config in 30 seconds

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):

"head_dim": 128, "hidden_act": "silu", "hidden_size": 4096, "intermediate_size": 14336, "max_position_embeddings": 131072, "num_attention_heads": 32, "num_hidden_layers": 32, "num_key_value_heads": 8, "rms_norm_eps": 1e-05, "rope_scaling": {"factor": 8.0, "high_freq_factor": 4.0, "low_freq_factor": 1.0, "original_max_position_embeddings": 8192, "rope_type": "llama3"}, "rope_theta": 500000.0, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "vocab_size": 128256
  1. Shape: num_hidden_layers × hidden_size: 32 × 4,096.
  2. Mixer and cache: 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.
  3. FFN: 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).
  4. Position and context: rope_theta, rope_scaling and max_position_embeddings: trained at 8,192 and stretched 8 times to 131,072.
  5. Size: 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.

12. Choosing: which design for which constraint

ConstraintChooseWhy, and what you give up
Short contexts, high throughput, standard serving stacksDense or MoE with GQA, SwiGLU, RoPE, pre-norm RMSNormMature kernels everywhere; the cache is small at short context anyway
Long contexts at high concurrencyMLA, or GQA with few KV heads; FP8 cache; windowed layers mixed with global onesShrinks what each token keeps or how long; costs kernel complexity (MLA) or far recall through fewer layers (windows)
Very long streams, fixed memoryHybrid: mostly SSM or linear layers, one attention layer in 4 to 8Near-constant memory; exact recall rests on the few attention layers
More quality at the same latency, memory availableMoE with many small experts and a shared expertActive parameters set latency; total parameters set memory, and balancing must be engineered
Small device, little memorySmall dense model, deep and thin, tied embeddings, GQAMoE does not help when every expert must fit in memory
Stable training at scalePre-norm RMSNorm plus QK-normTwo 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.

Optional: across the whole block

A design question that needs every part of the map: 128K context, 32 sequences, one 80 GB GPU

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

Real failures from the labs: errors and silent bugs in a hand-written block
  • KV heads not expanded (8 query heads, 2 KV heads, PyTorch 2.14.1 SDPA without enable_gqa): RuntimeError: The size of tensor a (8) must match the size of tensor b (2) at non-singleton dimension 1.
  • Expanded with 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.
  • Keys not transposed (q @ k): RuntimeError: Expected size for first two dimensions of batch2 tensor to be: [8, 32] but got: [8, 256].
  • Learned positions past the table: IndexError: learned positions stop at 256; got position 256 (the tiny GPT raises it on purpose).
  • Silent one-line attention bugs on the trained tiny GPT, loss on the running sequence 1.96 when correct: scores not divided by √dh 2.88; heads split with .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).
  • Post-norm at the default learning rate: stuck at 5.943, the unigram loss (section 7).
  • MoE without balancing: one expert takes 48% of a layer's assignments and 14 of 48 experts get under 1% (Mixture of experts).

All measured on the laptop; errors pasted verbatim.

The running example every lab and child page uses, and the labels on numbers

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

The child pages

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

The transformer from zero: one block, every shape, a GPT you trainThe whole block written from an empty file in nine steps, every shape tested, then the GPT trained and sampled; why a KV cache exists (section 9); ablations of each part.Sections 2, 3, 8. 40 min, plus 22 in closed details.
TokenizersBPE, WordPiece and unigram trained on one corpus; byte-level; vocabulary size and its costs; the language tax; failure modes; special tokens and chat templates.Section 2. 46 min, plus 15 in closed details.
Attention variants: MHA, MQA, GQA, MLA, sliding window, sparse attention and sinksWhat each past token leaves in each layer and what the next token reads: MHA, MQA, GQA, MLA, windows, NSA, DSA, DeepSeek-V4's compression, sinks and gates.Section 4 (levers 1 and 2). 38 min, plus 28 in closed details.
Positional EncodingsAbsolute and relative schemes, RoPE derived as a rotation, its base, partial and M-RoPE and NoPE layers read from real configs, the scalings (PI, NTK, YaRN, Llama 3, LongRoPE), five schemes run past their trained length.Sections 5 and 9 (wall 3). 38 min, plus 20 in closed details.
Mixture of experts: routers, load balancing, fine-grained and shared experts, expert parallelismTotal against active and the dense twin, routers, load balancing by loss or bias, capacity and drops, fine-grained and shared experts, expert parallelism, serving cost.Section 6. 35 min, plus 20 in closed details.
Normalisation, residuals and stability: pre-norm, RMSNorm, QK-norm, initialisation, loss spikesWhere the norm sits (pre, post, sandwich, output norm, mHC), LayerNorm against RMSNorm, QK-norm and soft-capping, z-loss, initialisation, massive activations, loss-spike forensics.Section 7. 34 min, plus 15 in closed details.
Long context: KV cache growth and compression, local and global attention, effective contextWhat each token of context costs, sizing any model's KV cache (a calculator with 45 presets), the levers that shrink it, and effective context.Sections 4 (lever 3) and 9. 27 min, plus 13 in closed details.
Beyond attention: SSMs, Mamba, linear attention, RWKV and hybridsLinear attention as a recurrence, S4 to Mamba-2, RWKV, the delta rule (Gated DeltaNet, Kimi Delta Attention), the hybrids that ship in 2026, and where a fixed state beats a growing cache.Section 4 (lever 4). 36 min, plus 20 in closed details.
Families and objectives: decoder-only, encoders, encoder-decoder, multi-token prediction, diffusion LMsDecoder, encoder and encoder-decoder from one change of mask; next-token, masked, span, multi-token and diffusion objectives, each run here.Section 10. 34 min, plus 14 in closed details.
LLM Architecture Gallery (rasbt) and the architectural deltas that matterA survey of released architectures: which of 105 open models made which design choice, read layer by layer from its config, the ratio counts, and corrections of the gallery's figures.Sections 4 and 11. 28 min, plus 9 in closed details.