# LLM Cheat Sheet: Estimating Parameters, Compute, Memory and Decoding Speed

> One page for the estimates you reuse most: counting parameters, training compute (about 6ND), memory for weights, training state and the KV cache, the bandwidth bound on decoding speed, and the LoRA and pass@k formulas, each with a standard-library script checked against published numbers.

- URL: https://dmxsf.com/en/wiki/start/cheat-sheet/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-15
- Tags: Transformer, Scaling laws, KV cache, Inference, LoRA

## After this page you will be able to

- Count the parameters of a dense Transformer from its configuration, and say what the rough formula 12·L·d² leaves out.
- Estimate training compute with 6ND and turn it into GPU hours using hardware peak and MFU.
- Estimate the memory of weights, training state and the KV cache, and convert between GiB and GB without slipping.
- Bound single-GPU decoding speed with memory bandwidth, and explain how context length and batch size move that bound.
- Write the LoRA parameter count and the unbiased pass@k estimator, and work one example of each.

Most back-of-the-envelope questions about LLMs reuse a handful of formulas: how many parameters a model has, how much compute training takes, how much memory the weights and the KV cache occupy, and how many tokens per second one GPU can produce. This page puts them side by side, gives each a worked example, and points to the page that explains it in full. Every example comes from one standard-library script, so you can reproduce the numbers; follow the links in the last column when you need the details.

## The Table First

| Quantity | Formula | Example (script output) | Details |
| --- | --- | --- | --- |
| Parameters | Embeddings plus per-layer attention, feed-forward and norms | Llama 3 8B: 8,030,261,248 | [Transformer Block](https://dmxsf.com/en/wiki/architecture/transformer-block/) |
| Training compute | $C\approx 6ND$ | Llama 3 405B: 3.79e+25 FLOPs | [Compute and Memory Accounting](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/) |
| Weight memory | Parameters times bytes per parameter | 8B in BF16: 14.96 GiB | [Quantization](https://dmxsf.com/en/wiki/inference/quantization/) |
| Training memory | About 16 bytes per parameter, activations excluded | 8B: 119.7 GiB | [Compute and Memory Accounting](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/) |
| KV cache | $2\,L\,n_{kv}\,d_h\,b$ bytes per token | Llama 3 8B: 128 KiB per token | [KV Cache](https://dmxsf.com/en/wiki/inference/kv-cache/) |
| Decoding speed | Memory bandwidth over bytes read per step | 8B in BF16 on an H100: 209 tokens/s | [GPUs and the Roofline Model](https://dmxsf.com/en/wiki/systems/gpu-and-roofline/) |
| LoRA | $r\,(d_{in}+d_{out})$ per matrix | r=16: 41,943,040 parameters | [LoRA Fine-Tuning](https://dmxsf.com/en/wiki/post-training/lora-finetuning/) |
| pass@k | $1-\binom{n-c}{k}/\binom{n}{k}$ | n=20, c=2, k=5: 0.4474 | [Evaluation Statistics](https://dmxsf.com/en/wiki/evaluation/eval-statistics/) |

> [!NOTE] Environment and conventions
> The script uses only the Python standard library, needs no GPU and downloads no model; a run takes under a second. The structural parameters of the five models come from the `config.json` on each model's Hugging Face page; the "reported" totals come from the Hub's safetensors metadata (read on 2026-11-15); memory bandwidth and dense compute come from NVIDIA's H100 and A100 material. The code blocks below, run in order, are the whole script. **GiB** means $2^{30}$ bytes and **GB** means $10^{9}$ bytes, and the tables keep them apart.

```python
import math
import sys

print(f"Python {sys.version.split()[0]}, standard library only")
```

```text
Python 3.14.3, standard library only
```

## Parameters: Count From the Configuration

A dense decoder has three groups of parameters: the input embedding and the output matrix (vocabulary $V$ times hidden size $d$; these five models do not tie them, so there is one of each), the attention and feed-forward blocks of every layer, and the normalization scales. With $L$ layers, $h$ query heads, $n_{kv}$ KV heads, head dimension $d_h$ and feed-forward width $f$, a model with grouped-query attention (GQA) and SwiGLU has

$$
\begin{aligned}
N &= 2Vd + d + L\,(A + 3df + 2d),\\
A &= 2\,d\,h\,d_h + 2\,d\,n_{kv}\,d_h.
\end{aligned}
$$

In $A$, the two terms are the Q and output projections and the K and V projections; $3df$ is the three SwiGLU matrices; the $2d$ per layer and the final $d$ are RMSNorm scale vectors. With multi-head attention ($n_{kv}=h$ and $h\,d_h=d$), $A=4d^2$, and with $f\approx\tfrac{8}{3}d$ a layer has about $12d^2$ parameters, so $N\approx 12Ld^2+2Vd$.

```python
# (layers, hidden, heads, KV heads, FFN width, vocab, QKV bias)
CONFIGS = {
    "Llama 2 7B": (32, 4096, 32, 32, 11008, 32000, False),
    "Llama 3 8B": (32, 4096, 32, 8, 14336, 128256, False),
    "Mistral 7B": (32, 4096, 32, 8, 14336, 32000, False),
    "Qwen2.5 7B": (28, 3584, 28, 4, 18944, 152064, True),
    "Llama 3 70B": (80, 8192, 64, 8, 28672, 128256, False),
}
# Totals in the Hub's safetensors metadata, read on 2026-11-15
REPORTED = {
    "Llama 2 7B": 6_738_415_616, "Llama 3 8B": 8_030_261_248,
    "Mistral 7B": 7_241_732_096, "Qwen2.5 7B": 7_615_616_512,
    "Llama 3 70B": 70_553_706_496,
}

def total(L, d, h, kv, f, V, bias):
    """Dense decoder: GQA attention, SwiGLU, RMSNorm, untied embeddings"""
    hd = d // h
    attn = d * h * hd + 2 * d * kv * hd + h * hd * d
    attn += (h + 2 * kv) * hd if bias else 0
    block = attn + 3 * d * f + 2 * d
    return 2 * V * d + L * block + d

print("model               formula       reported diff    rough share")
for name, c in CONFIGS.items():
    n, L, d, V = total(*c), c[0], c[1], c[5]
    rough = 12 * L * d * d + 2 * V * d
    print(f"{name:<12}{n:>15,}{REPORTED[name]:>15,}{n - REPORTED[name]:>5}"
          f"{rough / 1e9:>8.2f}B{rough / n:>6.0%}")
V, d = CONFIGS["Llama 3 8B"][5], CONFIGS["Llama 3 8B"][1]
share = 2 * V * d / REPORTED["Llama 3 8B"]
print(f"Llama 3 8B: 2·V·d = {2 * V * d:,} ({share:.0%} of all parameters)")
```

```text
model               formula       reported diff    rough share
Llama 2 7B    6,738,415,616  6,738,415,616    0    6.70B   99%
Llama 3 8B    8,030,261,248  8,030,261,248    0    7.49B   93%
Mistral 7B    7,241,732,096  7,241,732,096    0    6.70B   93%
Qwen2.5 7B    7,615,616,512  7,615,616,512    0    5.41B   71%
Llama 3 70B  70,553,706,496 70,553,706,496    0   66.53B   94%
Llama 3 8B: 2·V·d = 1,050,673,152 (13% of all parameters)
```

- **The exact formula matches the Hub totals parameter for parameter.** The `diff` column is all zeros. Qwen2.5 7B has QKV biases, which the script's `bias` switch adds to $A$; leave out any term and that column stops being zero.
- **The rough formula is only an order-of-magnitude check.** The `share` column is rough over exact. Llama 2 7B has feed-forward width 11,008, close to $\tfrac{8}{3}d$, so the rough formula is within 1% (99%). Llama 3 8B and Mistral 7B have a feed-forward width of $\tfrac{7}{2}d$ and reach only 93%; Llama 3 70B reaches 94%; Qwen2.5 7B has a feed-forward width of 18,944, more than five times $d=3584$, and reaches only 71%.
- **A big vocabulary makes embeddings a big share.** Llama 3's 128,256 tokens make $2Vd$ equal to 1,050,673,152, which is 13% of the 8B model's parameters.
- **Sparse models have two numbers.** Total parameters decide how much memory you need; active parameters decide the compute per token. They differ by a factor of several, and compute estimates use the active count; see [Mixture of Experts](https://dmxsf.com/en/wiki/architecture/mixture-of-experts/).

To change the inputs yourself, use the widget below: pick a model, or enter your own layer count, hidden size and vocabulary, and see what each part contributes.

## Training Compute: 6ND and GPU Hours

A linear layer processing one token uses each weight in one multiplication and one addition, about 2 FLOPs forward; the backward pass does one matrix multiplication of the same size for the input and one for the weights, about 4 FLOPs. That is about 6 FLOPs per parameter per token:

$$
C \approx 6\,N\,D
$$

$N$ counts the parameters that take part in matrix multiplications (not the input embedding table, which is a lookup; active parameters for mixture-of-experts models) and $D$ is the number of training tokens. Dividing $C$ by "hardware peak FLOP/s times MFU" gives GPU seconds. MFU (Model FLOPs Utilization) is the share of the hardware peak that goes to FLOPs the model needs. Use the dense peak: the H100 SXM's dense BF16 peak is 989 TFLOP/s, and the 1,979 on vendor tables is the figure with sparsity.

```python
PEAK = 989e12  # H100 SXM BF16 dense peak, FLOP/s
MFU = 0.40

def train_flops(n, d):
    return 6 * n * d  # about 2 forward and 4 backward FLOPs

c = train_flops(405e9, 15.6e12)
print(f"6·N·D = {c:.2e} FLOPs (the paper says 3.8e25)")
hours = c / (PEAK * MFU) / 3600
print(f"{hours / 1e6:.1f}M H100-hours (at MFU {MFU:.0%})")
for n in (8e9, 70e9, 405e9):
    print(f"N={n / 1e9:.0f}B: 20·N = {20 * n / 1e12:.2f}T tokens,",
          f"6·N·20N = {train_flops(n, 20 * n):.2e} FLOPs")
n8 = REPORTED["Llama 3 8B"]
print(f"15T tokens / {n8 / 1e9:.2f}B = {15e12 / n8:,.0f} tokens per parameter")
n_in = V * d  # the input table is a lookup, not a matmul
print(f"N = {n8 - n_in:,} (input embedding table removed, "
      f"{n_in / n8:.1%})")
```

```text
6·N·D = 3.79e+25 FLOPs (the paper says 3.8e25)
26.6M H100-hours (at MFU 40%)
N=8B: 20·N = 0.16T tokens, 6·N·20N = 7.68e+21 FLOPs
N=70B: 20·N = 1.40T tokens, 6·N·20N = 5.88e+23 FLOPs
N=405B: 20·N = 8.10T tokens, 6·N·20N = 1.97e+25 FLOPs
15T tokens / 8.03B = 1,868 tokens per parameter
N = 7,504,924,672 (input embedding table removed, 6.5%)
```

- **It matches the paper.** For Llama 3 405B, $6ND$ is 3.79e+25 FLOPs, and the paper's introduction states $3.8\times10^{25}$.
- **MFU is an assumption, not a finding.** The 40% used here gives 26.6M H100 hours, which is an order of magnitude and nothing more; the paper's Table 4 reports a BF16 MFU of 38% to 43%. To check a GPU-hour figure someone else reports, see [Compute and Memory Accounting](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/).
- **"20 tokens per parameter" is Chinchilla's rule of thumb** ([Hoffmann et al., 2022](https://dmxsf.com/en/blog/chinchilla-training-compute-optimal-large-language-models/)). By it an 8B model needs only 0.16T tokens, while Llama 3's corpus is about 15T tokens, which is 1,868 tokens per parameter even for an 8B model that reads it once. The paper says it trained the smaller models for much longer than is compute-optimal, which gives better models at the same inference budget.
- **Which N.** Without its input embedding table, Llama 3 8B has $N$ = 7,504,924,672, with the table at 6.5% of the total; the bigger the model, the smaller the table's share.
- **What 6ND leaves out.** The attention-matrix term at long context, and the extra forward pass that activation recomputation adds (the hardware then executes about $8ND$), have to be counted separately; see [Compute and Memory Accounting](https://dmxsf.com/en/wiki/pretraining/compute-and-memory/).

## Memory: Weights, Training State and the KV Cache

At inference, GPU memory holds two main things: the weights, and a KV cache that grows with the number of requests and the context length. Training also stores gradients, optimizer state and activations.

```python
BYTES = {"fp32": 4, "bf16": 2, "int8": 1, "int4": 0.5}
GIB = 2**30
n = REPORTED["Llama 3 8B"]
for dtype, b in BYTES.items():
    print(f"weights {dtype}: {n * b / GIB:6.2f} GiB")
print(f"bf16 weights: {n * 2 / 1e9:.2f} GB = {n * 2 / GIB:.2f} GiB")
print(f"training, mixed-precision Adam, 16 bytes per parameter: "
      f"{16 * n / GIB:.1f} GiB")

def kv_per_token(L, d, h, kv, *rest):
    return 2 * L * kv * (d // h) * 2  # K and V, 2 bytes per number in BF16

print("model        KiB/token    8K context 128K context")
# v0.1 has a 4,096-token sliding window that caps its cache
SKIP = {"Mistral 7B"}
for name, c in CONFIGS.items():
    if name in SKIP:
        continue
    b = kv_per_token(*c)
    print(f"{name:<12}{b / 1024:>10.0f}{b * 8192 / GIB:>10.2f} GiB"
          f"{b * 131072 / GIB:>9.1f} GiB")
```

```text
weights fp32:  29.92 GiB
weights bf16:  14.96 GiB
weights int8:   7.48 GiB
weights int4:   3.74 GiB
bf16 weights: 16.06 GB = 14.96 GiB
training, mixed-precision Adam, 16 bytes per parameter: 119.7 GiB
model        KiB/token    8K context 128K context
Llama 2 7B         512      4.00 GiB     64.0 GiB
Llama 3 8B         128      1.00 GiB     16.0 GiB
Qwen2.5 7B          56      0.44 GiB      7.0 GiB
Llama 3 70B        320      2.50 GiB     40.0 GiB
```

- **Weights** are the parameter count times bytes per parameter: 4 for FP32, 2 for BF16, 1 for INT8, 0.5 for INT4. The same BF16 weights are 16.06 GB or 14.96 GiB, a 7% difference: cards are specified in GB, most tools report GiB, and a comparison needs one unit. Real 4-bit formats also store scale factors, so they use slightly more than half a byte per parameter; see [Quantization](https://dmxsf.com/en/wiki/inference/quantization/).
- **Training state** with mixed-precision AdamW is about 16 bytes per parameter: 2 for BF16 weights, 2 for BF16 gradients, 4 for FP32 master weights and 4 for each of Adam's two moments. For the 8B model that is 119.7 GiB, which does not fit on one 80 GB card and has to be sharded with ZeRO or FSDP; see [Distributed Training](https://dmxsf.com/en/wiki/pretraining/distributed-training/). Activations are not counted here.
- **The KV cache** costs 2 (K and V) times layers, KV heads, head dimension and bytes per number, per token, and each concurrent request needs its own. Llama 3 8B needs 128 KiB per token, 1.00 GiB at 8K context and 16.0 GiB at 128K. GQA cuts the KV heads from 32 to 8, so Llama 3 8B's cache per token is a quarter of Llama 2 7B's 512 KiB; Llama 2's context length is 4K, and the 128K column just applies the formula.
- **A sliding window caps the cache.** The `config.json` of Mistral 7B v0.1 sets `sliding_window` to 4096, so its cache does not grow without bound and it is left out of the table; the formula gives the full-attention value.

The two widgets below let you change the inputs: the first computes the KV cache for a model, context length and batch size; the second computes training memory for an optimizer and parallelism setup.

## Decoding Speed: Bandwidth Sets the Ceiling

At batch size 1, every generated token reads all the weights from GPU memory once, and each weight is used for a single multiply-add, so the arithmetic is tiny and memory bandwidth sets the speed:

$$
v \le \frac{\mathrm{BW}}{B}
$$

$v$ is tokens per second, $\mathrm{BW}$ is memory bandwidth, and $B$ is the number of bytes read per step (at least the weight bytes, $2N$ in BF16).

```python
GPUS = {  # memory bandwidth, GB/s, vendor specs
    "H100 SXM": 3350, "A100 80GB SXM": 2039,
}
weights = REPORTED["Llama 3 8B"] * 2  # bytes of BF16 weights
for gpu, bw in GPUS.items():
    rate = bw * 1e9 / weights
    print(f"{gpu:<14}{rate:>6.0f} tokens/s (upper bound at batch 1)")
kv = kv_per_token(*CONFIGS["Llama 3 8B"]) * 131072
bw = GPUS["H100 SXM"] * 1e9
print(f"H100, 128K context, also reading {kv / 1e9:.2f} GB of KV cache: "
      f"{bw / (weights + kv):.0f} tokens/s")
print(f"H100 ridge point: {PEAK / 3.35e12:.0f} FLOPs/byte")
prefill = PEAK * MFU / (2 * REPORTED["Llama 3 8B"])
print(f"prefill bound: {prefill:,.0f} tokens/s (at MFU {MFU:.0%})")
```

```text
H100 SXM         209 tokens/s (upper bound at batch 1)
A100 80GB SXM    127 tokens/s (upper bound at batch 1)
H100, 128K context, also reading 17.18 GB of KV cache: 101 tokens/s
H100 ridge point: 295 FLOPs/byte
prefill bound: 24,632 tokens/s (at MFU 40%)
```

- **On an H100 SXM** (3.35 TB/s), Llama 3 8B in BF16 is bounded at 209 tokens/s; **on an A100 80GB** (2,039 GB/s) it is 127.
- **A longer context lowers the bound.** At 128K tokens each step also reads 17.18 GB of KV cache, and the H100 bound falls from 209 to 101.
- **A larger batch lets one pass over the weights serve more requests.** With BF16 weights a step's arithmetic intensity is about the batch size, and the H100's ridge point is 295 FLOPs/byte, so well below a batch of 295 adding requests barely lengthens a step (ignoring KV reads and attention). That is why continuous batching raises throughput; see [Continuous Batching](https://dmxsf.com/en/wiki/inference/continuous-batching/).
- **Prefill is a different bottleneck.** Processing a prompt reuses each weight for many tokens and is limited by compute: the bound is 24,632 tokens/s at an MFU of 40%, far faster than token-by-token decoding.
- **A bound is not a measurement.** Kernels do not saturate bandwidth, and each step also reads the KV cache, normalizes and samples; vendor figures are peaks.

## LoRA and pass@k

LoRA adds a pair of low-rank matrices to each adapted matrix $W\in\mathbb{R}^{d_{in}\times d_{out}}$, so the trainable parameters are $r\,(d_{in}+d_{out})$. pass@k counts $c$ passing samples out of $n$, and the unbiased estimator is

$$
\mathrm{pass@}k = 1-\frac{\binom{n-c}{k}}{\binom{n}{k}}
$$

(Chen et al., 2021, [Evaluating Large Language Models Trained on Code](https://arxiv.org/abs/2107.03374)).

```python
def lora(L, d, h, kv, f, V, bias, r):
    hd = d // h
    shapes = [(d, h * hd), (d, kv * hd), (d, kv * hd), (h * hd, d),
              (d, f), (d, f), (f, d)]  # q k v o gate up down
    return L * sum(r * (i + o) for i, o in shapes)

for r in (8, 16, 64):
    p = lora(*CONFIGS["Llama 3 8B"], r)
    print(f"r={r:<3}{p:>13,} trainable parameters",
          f"({p / REPORTED['Llama 3 8B']:.2%})")
```

```text
r=8     20,971,520 trainable parameters (0.26%)
r=16    41,943,040 trainable parameters (0.52%)
r=64   167,772,160 trainable parameters (2.09%)
```

```python
def pass_at_k(n, c, k):
    if n - c < k:
        return 1.0
    return 1 - math.comb(n - c, k) / math.comb(n, k)

n, c = 20, 2
for k in (1, 5, 10):
    naive = 1 - (1 - c / n) ** k
    print(f"pass@{k:<2} = {pass_at_k(n, c, k):.4f}  naive {naive:.4f}")
```

```text
pass@1  = 0.1000  naive 0.1000
pass@5  = 0.4474  naive 0.4095
pass@10 = 0.7632  naive 0.6513
```

- **LoRA.** Adapting all seven linear layers of every Llama 3 8B block (q, k, v, o, gate, up, down) at $r=16$ gives 41,943,040 trainable parameters, 0.52% of the total; doubling $r$ doubles the count. For details and how to choose $r$, see [LoRA Fine-Tuning](https://dmxsf.com/en/wiki/post-training/lora-finetuning/).
- **pass@k.** At $k=1$ both estimates are $c/n$. As $k$ grows, the naive estimate $1-(1-c/n)^k$ is biased low (Jensen's inequality): with $n=20$, $c=2$ and $k=5$ it gives 0.4095, while the unbiased estimate is 0.4474. The two converge as $n$ grows; state $n$ whenever you report pass@k, as in [Evaluation Statistics](https://dmxsf.com/en/wiki/evaluation/eval-statistics/).

## Six Common Mistakes in Estimates

| Mistake | Consequence | What to do |
| --- | --- | --- |
| Mixing GB and GiB | Off by 7%, enough to flip fits and does not fit | Use one unit; tools report GiB, specs use GB |
| Using total parameters for MoE FLOPs | Overestimates several-fold | Active parameters for compute, total for memory |
| Using the sparsity peak for MFU | MFU is half of what it should be | Use the dense peak and state the precision |
| Counting KV cache for one request | Underestimates memory under load | Multiply by concurrency, add weights and activations |
| Treating the bandwidth bound as measured speed | Overestimates decoding speed | Treat it as a ceiling; measure separately |
| Applying the full-attention formula to a sliding-window model | Overestimates the cache at long context | Check the window in `config.json` first |

## Summary and Exercises

**Key points:**

1. Count parameters term by term from the configuration; the rough $12Ld^2+2Vd$ is an order-of-magnitude check, off by 1% to 7% for the first four models and by 29% for the wide-feed-forward Qwen2.5 7B.
2. Training compute is $C\approx6ND$ and GPU time is $C$ over dense peak times MFU; $N$ excludes the input embedding table, and mixture-of-experts models use active parameters.
3. Weights take 2 bytes per parameter in BF16 and training state about 16; the KV cache costs $2\,L\,n_{kv}\,d_h\,b$ bytes per token and grows linearly with concurrency and context.
4. The decoding speed bound at batch size 1 is bandwidth over bytes read per step; a longer context lowers it and a larger batch raises total throughput.

### Quick Check

**1. How much memory do the BF16 weights of an 8.03B-parameter model take?**

- [ ] About 8 GiB
- [x] About 15 GiB
- [ ] About 30 GiB
- [ ] About 120 GiB

> At 2 bytes per parameter, 8,030,261,248 parameters are 16.06 GB, or 14.96 GiB. 30 GiB is the FP32 weights (29.92 GiB), and 120 GiB is the mixed-precision training state (119.7 GiB).

**2. What should N be when you estimate the training compute of a mixture-of-experts model with $6ND$?**

- [ ] The total parameter count
- [x] The active parameter count per token
- [ ] The parameter count of a single expert
- [ ] Only the attention parameters

> Each token passes through only the experts it is routed to, so compute follows active parameters; total parameters decide how much memory you need. Using the total overestimates compute several-fold.

**3. Which of these change the KV cache bytes per token? (Select all that apply.)**

- [x] Number of layers
- [x] Number of KV heads
- [x] Head dimension
- [ ] Feed-forward width
- [ ] Vocabulary size

> The cache per token is $2\,L\,n_{kv}\,d_h\,b$ bytes, set by the number of layers, KV heads, head dimension and data type. Feed-forward width, vocabulary size and whether the model is a mixture of experts do not affect it.

**4. What mainly sets the decoding speed bound of one GPU at batch size 1?**

- [ ] The hardware's peak FLOP/s
- [x] Memory bandwidth divided by the bytes read per step
- [ ] The vocabulary size
- [ ] Network bandwidth

> Every token reads all the weights once with very little arithmetic, so memory bandwidth is the bottleneck: about 209 tokens/s for Llama 3 8B on an H100. A longer context adds KV cache reads to every step and lowers the bound.

**5. With $n=20$ and $c=2$, the naive estimate $1-(1-c/n)^5$ gives 0.4095 and the unbiased estimate gives 0.4474. Which statement is right?**

- [ ] The naive estimate is more accurate because it uses all the samples
- [x] The naive estimate is biased low, and the two converge as $n$ grows
- [ ] They are always equal for $k>1$
- [ ] The unbiased estimate only applies at $k=1$

> $(1-\hat p)^k$ is convex in $\hat p$, so plugging in the estimate underestimates pass@k on average (Jensen's inequality). The unbiased estimator counts, with binomial coefficients, the fraction of $k$-sample subsets with at least one pass; at $k=1$ the two agree.

### Exercises

1. For Qwen2.5 7B at a 32K context, batch size 8 and BF16, how much memory does the KV cache take, and how many such requests fit on an 80 GB card once the weights are loaded?
2. Use $6ND$ to estimate the A100 hours needed to train a 7B model on 2T tokens (dense BF16 peak 312 TFLOP/s, MFU 40%), and compare with the 184,320 that Llama 2 7B reports.
3. How many trainable parameters does LoRA with $r=16$ add if only the attention q and v projections of Llama 3 8B are adapted?

<details>
<summary>Reference answers</summary>

```python
qwen = CONFIGS["Qwen2.5 7B"]
one = kv_per_token(*qwen) * 32768
print(f"1. KV cache of one 32K request: "
      f"{one / GIB:.2f} GiB, batch of 8: {8 * one / GIB:.1f} GiB")
free = 80e9 - REPORTED["Qwen2.5 7B"] * 2
print(f"   80 GB card minus weights leaves "
      f"{free / GIB:.1f} GiB; at most {int(free // one)} requests")
hours = 6 * 7e9 * 2e12 / (312e12 * MFU) / 3600
print(f"2. {hours:,.0f} A100-hours "
      f"(Llama 2 7B reports 184,320, "
      f"{hours / 184320 - 1:+.1%})")
d, h, kv = 4096, 32, 8
per_layer = 16 * (d + d) + 16 * (d + kv * (d // h))  # q and v
lora_qv = 32 * per_layer
print(f"3. LoRA r=16, q and v only: {lora_qv:,} "
      f"({lora_qv / REPORTED['Llama 3 8B']:.2%})")
```

```text
1. KV cache of one 32K request: 1.75 GiB, batch of 8: 14.0 GiB
   80 GB card minus weights leaves 60.3 GiB; at most 34 requests
2. 186,966 A100-hours (Llama 2 7B reports 184,320, +1.4%)
3. LoRA r=16, q and v only: 6,815,744 (0.08%)
```

1. Qwen2.5 7B has only 4 KV heads, so 56 KiB per token; one 32K request takes 1.75 GiB and a batch of 8 takes 14.0 GiB. After the weights, an 80 GB card has 60.3 GiB left, enough for at most 34 such requests; that is a ceiling, because activations, the runtime and fragmentation also use memory.
2. About 186,966 A100 hours, 1.4% above the reported 184,320: the estimate uses 7B rather than 6.74B parameters, and the MFU is an assumption; the order of magnitude agrees with the paper.
3. One pair of low-rank matrices for q, $16\,(4096+4096)$, and one for v, $16\,(4096+1024)$, is 212,992 per layer and 6,815,744 over 32 layers, 0.08% of the total and about a sixth of adapting all seven linear layers (41,943,040).

</details>

## Further Reading

- Llama Team, [The Llama 3 Herd of Models](https://arxiv.org/abs/2407.21783) (2024): the $3.8\times10^{25}$ FLOPs in the introduction, parallelism configurations and MFU in Table 4; [paper walkthrough](https://dmxsf.com/en/blog/the-llama-3-herd-of-models/)
- Touvron et al., [Llama 2: Open Foundation and Fine-Tuned Chat Models](https://arxiv.org/abs/2307.09288) (2023): GPU hours in Table 2; [paper walkthrough](https://dmxsf.com/en/blog/llama-2-open-foundation-and-fine-tuned-chat-models/)
- Hoffmann et al., [Training Compute-Optimal Large Language Models](https://arxiv.org/abs/2203.15556) (2022): the source of "20 tokens per parameter"; [paper walkthrough](https://dmxsf.com/en/blog/chinchilla-training-compute-optimal-large-language-models/)
- Kaplan et al., [Scaling Laws for Neural Language Models](https://arxiv.org/abs/2001.08361) (2020): the derivation of $C\approx6NBS$; [paper walkthrough](https://dmxsf.com/en/blog/scaling-laws-for-neural-language-models/)
- Rajbhandari et al., [ZeRO](https://arxiv.org/abs/1910.02054) (2019): the 16 bytes per parameter of model state; [paper walkthrough](https://dmxsf.com/en/blog/zero-memory-optimizations-toward-training-trillion-parameter-models/)
- Ainslie et al., [GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints](https://arxiv.org/abs/2305.13245) (2023); [paper walkthrough](https://dmxsf.com/en/blog/gqa-grouped-query-attention/)
- Hu et al., [LoRA: Low-Rank Adaptation of Large Language Models](https://arxiv.org/abs/2106.09685) (2021); [paper walkthrough](https://dmxsf.com/en/blog/lora-low-rank-adaptation/)
- Chen et al., [Evaluating Large Language Models Trained on Code](https://arxiv.org/abs/2107.03374) (2021): the unbiased pass@k estimator
- NVIDIA, the [H100](https://www.nvidia.com/en-us/data-center/h100/) and [A100](https://www.nvidia.com/en-us/data-center/a100/) product pages (memory bandwidth and dense compute; consulted in November 2026)

## Companion code

[LLM formula sheet: parameters, memory and compute](https://github.com/dmxsf/dmxsf/tree/main/labs/start/cheat-sheet): Cross-check released-model parameter counts, KV bytes, training FLOPs and pass@k.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run start/cheat-sheet`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/start/cheat-sheet/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/start/cheat-sheet/README.en.md)
- [`configs.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/architecture/configs.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#cheat-sheet)

## FAQ

### How do you estimate the number of parameters in an LLM?

A dense decoder has three groups of parameters. The input embedding and the output matrix are vocabulary size times hidden size, one each when they are not tied. Each layer has an attention block (Q, K, V and output projections) and a SwiGLU feed-forward block (three matrices). The normalization scales are the third group. Adding these up from the layer count, hidden size, head counts, feed-forward width and vocabulary reproduces the totals reported on Hugging Face exactly for Llama 2 7B, Llama 3 8B and 70B, Mistral 7B and Qwen2.5 7B. The rough formula 12·L·d² + 2·V·d is only an order-of-magnitude check, and lands between 71% and 99% of the exact value for these five models.

### How much compute and how many GPU hours does it take to train an LLM?

Training compute is about 6ND, where N is the number of parameters that take part in matrix multiplications (active parameters for mixture-of-experts models) and D is the number of training tokens. Llama 3 405B, with N = 405B and D = 15.6T, gives 3.79e25 FLOPs, and the paper states 3.8e25. GPU hours are that compute divided by the hardware's dense peak times MFU. At the H100 SXM's dense BF16 peak of about 989 TFLOP/s and an MFU of 40%, that is about 26.6M H100 hours; the paper reports an MFU of 38% to 43%.

### How much memory does an 8B-parameter model need?

Inference needs weights plus the KV cache. Llama 3 8B has 8,030,261,248 parameters, so BF16 weights take 14.96 GiB (16.06 GB) and INT8 about 7.48 GiB. The KV cache costs 128 KiB per token, so one 8K-token request adds 1.00 GiB, and every concurrent request needs its own. Training needs about 16 bytes per parameter (weights, gradients, FP32 master weights and Adam's two moments), 119.7 GiB before activations, which does not fit on one 80 GB card.

### How many bytes does the KV cache take per token?

Per token it is 2 (for K and V) times the number of layers, the number of KV heads, the head dimension, and the bytes per number. Llama 3 8B has 32 layers, 8 KV heads and head dimension 128, which is 128 KiB in BF16. Llama 2 7B has 32 KV heads and needs 512 KiB, so grouped-query attention (GQA) cuts it to a quarter. Feed-forward width, vocabulary size and whether the model is a mixture of experts do not matter. Sliding-window attention caps the cache, so the formula gives the full-attention value.

### How many tokens per second can one GPU generate?

At batch size 1, every generated token reads all the weights once, so speed is bounded by memory bandwidth divided by the bytes read per step. For Llama 3 8B in BF16 (16.06 GB of weights), the bound is about 209 tokens/s on an H100 SXM (3.35 TB/s) and about 127 on an A100 80GB (2,039 GB/s). At a 128K-token context each step also reads 17.18 GB of KV cache, and the H100 bound drops to 101. These are upper bounds; measured speeds are lower, and a larger batch lets one pass over the weights serve more requests, so total throughput rises.
