Lesson 2: What one token costs · Workbook
What one token costs: the workbook
The full working behind lesson 2. Every step of one token's forward pass with its shapes, parameters, FLOPs and bytes; where the parameters live; the 2N rule and where it breaks; why the bytes tell a different story; and seven exercises to check yourself.
Lesson 1 treated Llama 3.1 8B as a single block: about 7.5 billion weights that are multiplied once per token, at 2 FLOPs and, in BF16, 2 bytes each. That was enough to explain why decode is memory-bound. It is not enough to decide what to optimize, because the cost is not spread evenly. Some steps hold most of the weights, one step grows with the length of the conversation, and several steps that matter for correctness cost almost nothing.
This lesson opens the block. We follow one token through one forward pass of Llama 3.1 8B, in order, and for each step write down the tensor shapes, the parameters, the FLOPs and the bytes read. By the end you will be able to rebuild the “2 FLOPs per parameter” rule from its parts, see exactly where it stops being true, and know which part of the model each later lesson in this course is attacking.
The model we are walking through
Every number here comes from the model’s config.json and the Llama 3 paper. Llama 3.1 8B has:
- a hidden size of 4,096: each token is represented as a vector of 4,096 numbers between steps;
- 32 decoder layers, each with an attention block and an MLP block;
- 32 query heads of 128 dimensions each, but only 8 key/value heads, a design called grouped-query attention (GQA);
- an MLP width of 14,336;
- a vocabulary of 128,256 tokens.
The vector that flows from layer to layer is called the residual stream. Each block reads it, computes an update, and adds the update back. We count costs for one new token during decode, the case from lesson 1, with 1,024 earlier tokens already processed. Bytes read means weights plus the stored keys and values of earlier tokens (the KV cache). Weights are in BF16, 2 bytes each.
Step by step through one token
Embedding lookup
The token arrives as an integer ID. The embedding table has one row of 4,096 numbers per vocabulary entry, 525M parameters in all. Turning the ID into a vector is a lookup, not a multiplication: copy one row. That is 0 FLOPs and 8.19 KB read. The table is large, but almost none of it is touched per token, which is why lesson 1 left it out of the bytes.
RMSNorm
Before attention, the vector is normalized. Llama uses RMSNorm (Zhang and Sennrich, 2019), which divides by the root mean square of the vector and multiplies by a learned gain :
It drops the mean subtraction of the older LayerNorm, which the paper hypothesizes is not needed. Cost: 4,096 parameters, roughly 16.4 KFLOP, and 8.19 KB read. Necessary, and negligible.
Q, K and V projections
Attention needs three vectors per token: a query (what this token is looking for), a key (what it offers to later tokens) and a value (what it passes along if attended to). Each is a matrix multiply of the 4,096-wide vector by a weight matrix.
The query has 32 heads × 128 = 4,096 dimensions, so is 4,096 × 4,096: 16.8M parameters. With GQA, keys and values have only 8 heads × 128 = 1,024 dimensions, so and are 4,096 × 1,024, a quarter of the size: 4.19M each. Every group of 4 query heads shares one key/value head. The Llama 3 paper says it uses GQA with 8 key/value heads to speed up inference and shrink the KV cache.
A matrix-vector multiply does one multiply-add per weight, so each projection costs 2 FLOPs and 2 bytes per parameter: 33.6 MFLOP and 33.6 MB for .
RoPE
Attention by itself has no notion of word order. Rotary position embedding (RoPE, Su et al., 2021) adds it by rotating pairs of dimensions in each query and key by an angle proportional to the token’s position, with a different frequency for each pair. When a query and key are compared, only the difference of their positions survives. Llama 3 raised RoPE’s base frequency to 500,000 to support longer contexts.
RoPE has no learned parameters. It is a few multiplies per element of Q and K: roughly 15.4 KFLOP. After rotation, the new key and value are appended to the KV cache.
Attention scores and weighted sum
Now the new token’s query is compared with every key in the cache. For each head, the score with key is the dot product , scaled by . A softmax over the scores turns them into weights that sum to 1, and the output is the weighted sum of the value vectors.
With keys (the 1,024 cached tokens plus the new one), each query head does dot products of length 128 for the scores and the same amount of work for the weighted sum. Across all 32 heads that is
where is the total query width, 4,096 here. At 1,024 cached tokens that is 16.8 MFLOP per layer, small next to the projections. The difference is the bytes: this step has no weights, but it reads every cached key and value, 4.20 MB per layer at this context. Both numbers grow with . Nothing else in the layer does.
Output projection and the residual add
The 32 head outputs are concatenated into a 4,096-wide vector and multiplied by , 4,096 × 4,096: another 16.8M parameters, 33.6 MFLOP. The result is added to the residual stream, 4,096 additions.
The SwiGLU MLP
A second RMSNorm, then the MLP. Llama uses SwiGLU (Shazeer, 2020). Instead of the original transformer’s two matrices with a ReLU between them, it has three:
and are each 4,096 × 14,336, and is 14,336 × 4,096. SiLU is ; its output gates the “up” branch element by element. Each matrix holds 58.7M parameters and costs 117 MFLOP and 117 MB per token. A second residual add closes the layer.
Final norm, lm_head and sampling
After the last layer, one more RMSNorm, then the lm_head: a 4,096 × 128,256 matrix that turns the hidden vector into one score (a logit) per vocabulary entry. In Llama 3.1 8B it is a separate matrix from the embedding table, 525M parameters, so it costs 1.05 GFLOP and 1.05 GB per token, more than 2 whole decoder layers. Some smaller models reuse the embedding table here (“tied embeddings”). That saves memory, but the multiply still reads the whole matrix.
Finally a softmax over the 128,256 logits and a choice of token (the most likely one, or a random draw weighted by the probabilities). That is a few FLOPs per vocabulary entry, roughly 385 KFLOP. The chosen token ID becomes the input to the next step.
The whole pass in one table
| Step | Weight shape | Parameters | FLOPs per token | Bytes read per token |
|---|---|---|---|---|
| Embedding lookup | 525M | 0 | 8.19 KB | |
| Each of the 32 decoder layers | ||||
| RMSNorm before attention | 4,096 | ≈ 16.4 KFLOP | 8.19 KB | |
| Q projection | 4,096 × 4,096 | 16.8M | 33.6 MFLOP | 33.6 MB |
| K projection | 4,096 × 1,024 | 4.19M | 8.39 MFLOP | 8.39 MB |
| V projection | 4,096 × 1,024 | 4.19M | 8.39 MFLOP | 8.39 MB |
| RoPE on Q and K | 0 | ≈ 15.4 KFLOP | 0 | |
| Attention scores and weighted sum | 0 | 16.8 MFLOP | 4.20 MB | |
| Output projection | 4,096 × 4,096 | 16.8M | 33.6 MFLOP | 33.6 MB |
| Residual add | 0 | ≈ 4.10 KFLOP | 0 | |
| RMSNorm before MLP | 4,096 | ≈ 16.4 KFLOP | 8.19 KB | |
| MLP gate | 4,096 × 14,336 | 58.7M | 117 MFLOP | 117 MB |
| MLP up | 4,096 × 14,336 | 58.7M | 117 MFLOP | 117 MB |
| SiLU and multiply | 0 | ≈ 86.0 KFLOP | 0 | |
| MLP down | 14,336 × 4,096 | 58.7M | 117 MFLOP | 117 MB |
| Residual add | 0 | ≈ 4.10 KFLOP | 0 | |
| Once, after the last layer | ||||
| Final RMSNorm | 4,096 | ≈ 16.4 KFLOP | 8.19 KB | |
| lm_head (vocabulary projection) | 4,096 × 128,256 | 525M | 1.05 GFLOP | 1.05 GB |
| Softmax and sampling | 0 | ≈ 385 KFLOP | 0 | |
| Whole forward pass | 8.03B | 15.6 GFLOP | 15.1 GB | |
Three things stand out. First, the matrix multiplies do nearly all the work: norms, RoPE, SiLU, residual adds and sampling together are 0.03% of FLOPs at short context. Second, the total of 15.6 GFLOP is 2 FLOPs per matmul weight plus 4% more for attention over 1,024 cached tokens. Third, the bytes, 15.1 GB, are almost exactly the weights read once each.
Where the parameters live
The MLP is the bulk of the model. One Llama 3.1 8B layer holds 218M parameters: 41.9M in the four attention projections, 176M in the three MLP matrices, and 8,192 in the two norm gains.
So the MLP holds 81% of each layer, and 70% of the whole model once you count the embedding table and lm_head.
The rule of thumb you will often read is “two-thirds”. That comes from the classic transformer shape in Kaplan et al. (2020): MLP width , two MLP matrices, and keys and values as wide as queries. Then the attention projections hold and the MLP holds :
Llama moves further toward the MLP for two reasons. GQA shrinks and to a quarter of their classic size, and Llama makes its SwiGLU MLP wider than the parameter-neutral choice. Shazeer’s paper keeps parameters constant by shrinking the MLP width by a factor of 2/3 when it adds the third matrix, which would give . Llama 3.1 8B uses 3.5, so its MLP has 10.5 parameters against the classic .
The 3D figure below lays out every weight matrix in one layer as a flat slab, with true proportions: width is the output dimension, depth is the input dimension, one unit per 4,096. K and V are narrow because of grouped-query attention, bytes assume BF16 weights, and the menu holds the other models from lesson 1. Select a slab to see what it costs, or press Read it for one token to watch the read sweep cross every slab at the same speed. Then switch on lm_head to see the single largest matrix in the model.
Drag to rotate, click a slab
- Parameters
- Share of the layer's parameters
- FLOPs per token
- Bytes read per token (BF16)
Counting FLOPs: 2N plus attention
Add up the table and a simple rule appears. Every weight in a matrix multiply contributes one multiply-add, 2 FLOPs, per token. Call the number of those weights . For Llama 3.1 8B, is 7.50 billion: 6.98 billion layer weights plus 0.53 billion in lm_head; it excludes the embedding table, because a lookup is not a multiply. The only other term that is not tiny is attention, which grows with the number of keys :
Kaplan et al. (2020) write the same estimate as
Their attention term is half of ours. Kaplan et al. list it as a single “Attention: Mask” row and do not say how they count it. It equals our per-token cost averaged over a causal training sequence of length (token attends to keys, about on average), which is the natural reading for a training-compute estimate. A new token at the end of a long conversation attends to all of it and pays the full . (Kaplan’s also leaves out the output projection to the vocabulary; we include lm_head because it is a matrix multiply that runs every decode step.)
This tells you when “2 FLOPs per parameter” breaks. The attention term equals the matmul term when
At 8,192 tokens of context, attention is already 22% of a new token’s FLOPs. At Llama 3.1’s maximum of 131,072 it is 82%, and a single token costs 83.7 GFLOP instead of 15.0 GFLOP. Kaplan et al. note that the context term is small when , and the models they studied were mostly in that regime. Long-context serving is not.
Drag the context slider below and watch the attention area take over. Try Mistral 7B, whose sliding window caps every token at 4,096 keys, so its attention share stops growing.
| Part | Share | FLOPs |
|---|
Bytes tell a different story
FLOPs are only half the bill. In lesson 1, decode was memory-bound, so what sets its speed is bytes, and the bytes split differently.
The weights are read once per decode step and shared by every sequence in the batch. The KV cache is per sequence: each sequence reads its own 131 KB per cached token (keys and values, 32 layers, 1,024 dimensions each, 2 bytes). For one sequence, the cache traffic reaches the 15.0 GB of weights only at about 114,500 tokens. But in a batch of 64 the weights are still read once while the caches are read 64 times, so cache traffic reaches the weight traffic 64 times sooner. That is why the KV cache gets four lessons of its own, starting with the KV cache lesson.
The attention step also has a fixed arithmetic intensity. Per layer it does FLOPs while reading bytes of K and V in BF16, where is the total key/value width, 1,024 here (8 heads × 128), so
At 32,768 tokens the computed value is 4.00 FLOPs per byte, nowhere near the H100’s ridge of 295. Batching independent sequences cannot raise it, because each sequence brings its own keys and values. The levers are the ratio itself, which is what GQA and its successors change (lesson 5), fewer bytes per cached number (quantization), and more query tokens per cache read (speculative decoding, shared-prefix attention).
What this means for the rest of the course
Each later lesson targets a specific row of the table.
- The matmul rows (projections, MLP, lm_head) are 99.96% of FLOPs and nearly all weight bytes at short context. Batching (continuous batching), weight quantization and speculative decoding all aim here, by reusing each weight read for more tokens or making it cheaper.
- The attention row is the one that grows. Its memory is the subject of the KV cache, paged KV memory and prefix caching lessons; its kernel is FlashAttention.
- The elementwise rows (norms, RoPE, SiLU, residuals, sampling) cost almost nothing in FLOPs or weight bytes. In practice they cost kernel launches and activation traffic, which is why inference engines fuse them into neighboring kernels.
During prefill the same steps run for every prompt token at once, which changes which resource each one hits. That is the next lesson, Prefill and decode.
Check yourself
Every answer comes from the same code as the table and figures above. The last two revisit lesson 1. Your progress is saved with the lesson.
Exercise 1. Llama 3.1 70B has hidden size 8,192, 64 query heads and 8 key/value heads of 128 dimensions, and MLP width 28,672. What share of one layer's parameters is in the MLP?
Show the worked answer
About 82%. The attention projections hold 151M ( for Q and O, plus K and V at 1,024 wide) and the MLP holds = 705M. With 64 query heads sharing 8 key/value heads, GQA shrinks K and V even more than in the 8B model.
Exercise 2. For Llama 3.1 70B (80 layers, query width 8,192, and the same 128,256-token vocabulary as the 8B model), at what context does a new token's attention FLOPs equal its matmul FLOPs?
Show the worked answer
About 53,000 tokens. Divide , 69.5 billion matmul weights, by . Bigger models have more weights per unit of attention width, so the crossover comes later than the 8B model’s 28,600.
Exercise 3. Qwen2.5 0.5B has hidden size 896, 24 layers, 14 query heads and 2 key/value heads of 64 dimensions, MLP width 4,864 and a 151,936-token vocabulary, and ties its lm_head to the embedding table. What share of its matmul FLOPs at short context goes to lm_head?
Show the worked answer
About 28%. lm_head is = 136M weights, against 494M matmul weights in total. Tying saves storage, not work: the matrix is still read and multiplied every token. Compare 7% for Llama 3.1 8B. In small models with large vocabularies, the vocabulary projection is a big share of decode cost.
Exercise 4. Suppose Llama 3.1 8B used full multi-head attention, 32 key/value heads instead of 8. How many parameters would that add, and how big would the KV cache be per token in BF16?
Show the answer
Each layer’s and grow from 1,024 to 4,096 columns, adding 25.2M parameters per layer and 805M in total, 10% more. The KV cache grows 4×, from 131 KB to 524 KB per token. The parameter cost is modest; the cache cost is what GQA was designed to avoid.
Exercise 5. Batch 256 sequences of Llama 3.1 8B at 32,768 tokens of context each on an H100. In lesson 1, batching pushed the matmuls toward compute-bound. Does it do the same for attention?
Show the answer
No. The matmul weights are read once for all 256 sequences, so their intensity rises to 256 FLOPs per byte, close to the ridge, and keeps rising with batch. Attention reads each sequence’s own cache, so its intensity stays at = 4.0 FLOPs per byte however large the batch, far below the ridge of 295. Attention at decode is memory-bound by construction.
Exercise 6. From lesson 1: one decode token of Llama 3.1 8B at 1,024 tokens of context reads 15.1 GB (weights plus the KV cache), and an H100 reads memory at 3.35 TB/s. At batch 1 the step is memory-bound. What is the floor on its time, in milliseconds?
Show the worked answer
About 4.52 ms: 15.1 GB ÷ 3.35 TB/s. The arithmetic, 15.5 GFLOP at 989 TFLOP/s, would take about 15.7 µs, so memory sets the pace. That is a ceiling of about 221 tokens per second for one user, and this lesson shows where those bytes come from: 74% of them are the MLP weights.
Exercise 7. From lesson 1: in BF16 each matmul weight is 2 bytes and does 2 FLOPs per sequence in the batch, so at batch B the decode matmuls do about B FLOPs per byte. The H100's ridge point is its peak compute (989 TFLOP/s) divided by its bandwidth (3.35 TB/s). Roughly what batch size makes the matmuls compute-bound?
Show the worked answer
About 296 sequences: the first batch size past the ridge of 989 TFLOP/s ÷ 3.35 TB/s ≈ 295 FLOPs per byte, since the matmul intensity is about B. That holds for the projection, MLP and lm_head rows of this lesson’s table, which share one weight read across the whole batch. It does not hold for the attention row: as exercise 5 shows, each sequence reads its own cache, so attention stays at about 4 FLOPs per byte whatever the batch.
Sources
- Kaplan, McCandlish, Henighan, Brown, Chess, Child, Gray, Radford, Wu, Amodei (2020). Scaling Laws for Neural Language Models. arXiv:2001.08361. Table 1: per-operation parameter and FLOP counts, and C_forward = 2N + 2 n_layer n_ctx d_attn
- Dubey et al., Llama Team, AI @ Meta (2024). The Llama 3 Herd of Models. arXiv:2407.21783. Table 3: 8B has 32 layers, model dimension 4,096, FFN dimension 14,336, 32 heads, 8 key/value heads, SwiGLU, RoPE base 500,000
- Llama 3.1 8B config.json (Meta, via the ungated unsloth mirror). vocab_size 128,256, untied embeddings, rms_norm_eps 1e-5, no attention or MLP biases
- Shazeer (2020). GLU Variants Improve Transformer. arXiv:2002.05202. SwiGLU, and the 2/3 reduction of d_ff that keeps parameters constant
- Su, Lu, Pan, Murtadha, Wen, Liu (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864
- Zhang, Sennrich (2019). Root Mean Square Layer Normalization. NeurIPS 2019. arXiv:1910.07467
- kipply (2022). Transformer inference arithmetic. The same step-by-step count for a 52B model, arriving at about 2 FLOPs per parameter