Inference Engineering

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:

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

RMSNorm(x)=x1d∑ixi2+ϵ⊙g\mathrm{RMSNorm}(x) = \frac{x}{\sqrt{\tfrac{1}{d}\sum_i x_i^2 + \epsilon}} \odot g

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 WQW_Q is 4,096 × 4,096: 16.8M parameters. With GQA, keys and values have only 8 heads × 128 = 1,024 dimensions, so WKW_K and WVW_V 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 WQW_Q.

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 jj is the dot product q⋅kjq \cdot k_j, scaled by 1/1281/\sqrt{128}. 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 nn keys (the 1,024 cached tokens plus the new one), each query head does nn dot products of length 128 for the scores and the same amount of work for the weighted sum. Across all 32 heads that is

attention FLOPs per layer=2 n dattn+2 n dattn=4 n dattn\text{attention FLOPs per layer} = \htmlClass{c-compute}{2 \, n \, d_{\text{attn}} + 2 \, n \, d_{\text{attn}} = 4 \, n \, d_{\text{attn}}}

where dattnd_{\text{attn}} 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 nn. 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 WOW_O, 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:

MLP(x)=(SiLU(xWgate)⊙xWup) Wdown\mathrm{MLP}(x) = \big(\mathrm{SiLU}(x W_{\text{gate}}) \odot x W_{\text{up}}\big)\, W_{\text{down}}

WgateW_{\text{gate}} and WupW_{\text{up}} are each 4,096 × 14,336, and WdownW_{\text{down}} is 14,336 × 4,096. SiLU is x⋅sigmoid(x)x \cdot \mathrm{sigmoid}(x); 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

StepWeight shapeParametersFLOPs per tokenBytes read per token
Embedding lookup525M08.19 KB
Each of the 32 decoder layers
RMSNorm before attention4,096≈ 16.4 KFLOP8.19 KB
Q projection4,096 × 4,09616.8M33.6 MFLOP33.6 MB
K projection4,096 × 1,0244.19M8.39 MFLOP8.39 MB
V projection4,096 × 1,0244.19M8.39 MFLOP8.39 MB
RoPE on Q and K0≈ 15.4 KFLOP0
Attention scores and weighted sum016.8 MFLOP4.20 MB
Output projection4,096 × 4,09616.8M33.6 MFLOP33.6 MB
Residual add0≈ 4.10 KFLOP0
RMSNorm before MLP4,096≈ 16.4 KFLOP8.19 KB
MLP gate4,096 × 14,33658.7M117 MFLOP117 MB
MLP up4,096 × 14,33658.7M117 MFLOP117 MB
SiLU and multiply0≈ 86.0 KFLOP0
MLP down14,336 × 4,09658.7M117 MFLOP117 MB
Residual add0≈ 4.10 KFLOP0
Once, after the last layer
Final RMSNorm4,096≈ 16.4 KFLOP8.19 KB
lm_head (vocabulary projection)4,096 × 128,256525M1.05 GFLOP1.05 GB
Softmax and sampling0≈ 385 KFLOP0
Whole forward pass8.03B15.6 GFLOP15.1 GB
One decode token through Llama 3.1 8B in BF16 with 1,024 tokens already cached. Per-layer rows are for one layer; the total multiplies them by 32. Rows marked ≈ are rough operation counts for elementwise work. Bytes include weights and KV-cache traffic, not activations.

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.

MLPlayer=3⋅4096⋅14336218,112,000≈0.81\frac{\text{MLP}}{\text{layer}} = \frac{3 \cdot 4096 \cdot 14336}{218{,}112{,}000} \approx 0.81

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 4d4d, two MLP matrices, and keys and values as wide as queries. Then the attention projections hold 4d24d^2 and the MLP holds 8d28d^2:

8d24d2+8d2=23\frac{8d^2}{4d^2 + 8d^2} = \frac{2}{3}

Llama moves further toward the MLP for two reasons. GQA shrinks WKW_K and WVW_V 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 23⋅4d≈2.7d\tfrac{2}{3} \cdot 4d \approx 2.7d. Llama 3.1 8B uses 3.5dd, so its MLP has 10.5d2d^2 parameters against the classic 8d28d^2.

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.

Parameters
Share of the layer's parameters
FLOPs per token
Bytes read per token (BF16)

One layer of Llama 3.1 8B, each weight matrix drawn as a slab sized by how many numbers it holds. Front row: the attention projections Q, K, V and O. Back row: the MLP matrices gate, up and down. K and V are thin on purpose (lesson 5 says why).

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 NN. For Llama 3.1 8B, NN 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 nn:

FLOPs for one new token≈2N+4 nlayer n dattn\text{FLOPs for one new token} \approx \htmlClass{c-compute}{2N + 4\, n_{\text{layer}}\, n\, d_{\text{attn}}}

Kaplan et al. (2020) write the same estimate as

Cforward≈2N+2 nlayer nctx dattnC_{\text{forward}} \approx 2N + 2\, n_{\text{layer}}\, n_{\text{ctx}}\, d_{\text{attn}}

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 nctxn_{\text{ctx}} (token pp attends to pp keys, about nctx/2n_{\text{ctx}}/2 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 4 nlayer n dattn4\, n_{\text{layer}}\, n\, d_{\text{attn}}. (Kaplan’s NN 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

n∗=N2 nlayer dattn=7.50×1092⋅32⋅4096≈28,600 tokensn^{*} = \frac{N}{2\, n_{\text{layer}}\, d_{\text{attn}}} = \frac{7.50 \times 10^{9}}{2 \cdot 32 \cdot 4096} \approx 28{,}600 \text{ tokens}

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 dmodel>nctx/12d_{\text{model}} > n_{\text{ctx}}/12, 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.

PartShareFLOPs

Share of one decode token's FLOPs by part of the model, as the number of cached tokens grows. Attention scores and weighted sum (the red area) is the only part that depends on context. The dashed line marks where a new token's attention FLOPs equal all of its matmul 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 4 n dattn4\, n\, d_{\text{attn}} FLOPs while reading 2×2 n dkv2 \times 2\, n\, d_{\text{kv}} bytes of K and V in BF16, where dkvd_{\text{kv}} is the total key/value width, 1,024 here (8 heads × 128), so

Iattention=4 n dattn4 n dkv=dattndkv=4I_{\text{attention}} = \frac{4\, n\, d_{\text{attn}}}{4\, n\, d_{\text{kv}}} = \frac{d_{\text{attn}}}{d_{\text{kv}}} = 4

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.

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 (2⋅819222 \cdot 8192^2 for Q and O, plus K and V at 1,024 wide) and the MLP holds 3⋅8192⋅286723 \cdot 8192 \cdot 28672 = 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?

tokens
Show the worked answer

About 53,000 tokens. Divide NN, 69.5 billion matmul weights, by 2⋅80⋅81922 \cdot 80 \cdot 8192. 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 896×151,936896 \times 151{,}936 = 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 WKW_K and WVW_V 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 dattn/dkvd_{\text{attn}} / d_{\text{kv}} = 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?

ms
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?

sequences
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

  1. 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
  2. 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
  3. 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
  4. Shazeer (2020). GLU Variants Improve Transformer. arXiv:2002.05202. SwiGLU, and the 2/3 reduction of d_ff that keeps parameters constant
  5. Su, Lu, Pan, Murtadha, Wen, Liu (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864
  6. Zhang, Sennrich (2019). Root Mean Square Layer Normalization. NeurIPS 2019. arXiv:1910.07467
  7. kipply (2022). Transformer inference arithmetic. The same step-by-step count for a 52B model, arriving at about 2 FLOPs per parameter

Back to lesson 2: What one token costs