Dive into Deep Learning · §18.1
Pretrained Models with Hugging Face
repositories and pins · templates and sampling defaults · configurations · memory · fused kernels · decode speed
The problem
A few library calls download Qwen3.5-2B and it answers a question.
A released model is a configuration file plus tensors. Its memory and a lower bound on its decode time follow from the configuration, before any download.
Goals
Running example: Qwen3.5-2B in 16-bit floats on one RTX 4090 (24 GB of memory, read at 1.0 TB/s): 24 layers of width 2,048. Second model: Gemma 4 E2B.
Where this fits
| movement | section |
|---|---|
| open a checkpoint | Pretrained Models with Hugging Face |
| A Released Checkpoint in the Book’s Own Code | |
| measure it | Prompting and In-Context Learning |
| Scoring Language Models | |
| Evaluation Suites, Judges and Error Bars | |
| inside and outside | Interpretability |
| Models behind an API |
d2l.GPT with GPT-2’s weights, the KV cache, hybrids, the bandwidth bound on decoding.GPT-2 (2019), 32 greedy tokens:
Q: Why does a language model keep a key-value cache when it generates text?
A: The key-value cache is a way to store data in a database. It is a way to
store data in a database that is not stored in a key
Qwen3.5-2B, 64 greedy tokens after apply_chat_template:
Language models (like those in LLMs) use a **key-value cache** (often called
a **context window** or **attention mechanism**) primarily to balance
**computational efficiency** with **memory constraints**. Here's why
it's essential:
### 1. **Efficient Context Processing**
-
Qwen3_5ForCausalLM: 1,881,825,088 parameters
The same question, wrapped in the chat format this model was trained to answer.
config.json: every shape.chat_template.jinja: text to token ids.generation_config.json: optional, absent here.model_type.| bytes of a safetensors file | content |
|---|---|
| 0 to 7 | length m of the header, an integer |
| 8 to 7 + m | JSON: name, dtype, shape and byte range of each tensor |
| the rest | tensor data, 4.5 GB |
632 tensors {'F32': 36, 'BF16': 596}, 2,274,069,824 elements
1,881,825,088 model.language_model
331,416,576 model.visual
60,828,160 mtp
The file holds a language model, a vision tower and a head for multi-token prediction (mtp). A text model loads only the first.
Check
The weight file of Qwen3.5-2B takes 4,548 MB and holds 2,274,069,824 numbers. Which dtype is that? A text model loads 1,881,825,088 of them: how many GiB (2^{30} bytes) of GPU memory?
| risk | guard in d2l.load_hf |
|---|---|
| the repository changes | revision= one commit hash, for model and tokenizer |
| code in the repository | trust_remote_code=False, use_safetensors=True |
| a module finds no tensor and stays random | error on any missing tensor |
| the file also holds image and audio models | build the text model only; list the tensors left on disk |
A loader that finds no tensor for a module only warns: the model has the right parameter count and random weights.
Tokens per character of three texts, for four tokenizers:
vocabulary embedding rows The Time Machine d2l/torch.py Chinese
GPT-2 50257 50257 0.25 0.45 2.17
Qwen3-0.6B 151669 151936 0.24 0.24 0.70
Qwen3.5-2B 248077 248320 0.24 0.25 0.64
Gemma 4 E2B 262144 262144 0.24 0.29 0.67
This ratio turns every cost per token (bytes of cache, ms per step) into a cost per character of text.
<|im_start|>user
Why does a language model keep a key-value cache when it generates text?<|im_end|>
<|im_start|>assistant
<think>
</think>
[248046, 198, 248045, 74455, 198, 248068, 271, 248069, 271]
['<|im_end|>', 'Ċ', '<|im_start|>', 'assistant', 'Ċ', '<think>', 'ĊĊ', '</think>', 'ĊĊ']
<think> block first. enable_thinking=False: the template closes the block. Defaults differ by checkpoint: pass it.generate loops: logits of the next token, choose, append, stop at a stop token.
identical: True
argmax loop without a cache: 1.25 s for 32 tokens after 1,024 prompt tokens
generate with a cache: 0.88 s for 32 tokens after 1,024 prompt tokens
argmax loop without a cache: 8.98 s for 32 tokens after 8,192 prompt tokens
generate with a cache: 1.11 s for 32 tokens after 8,192 prompt tokens
Qwen3.5-2B (config.json, library defaults): greedy
do_sample=None, temperature=None, top_k=None, top_p=None, stop tokens 248044
Gemma 4 E2B (generation_config.json): sampling
do_sample=True, temperature=1.0, top_k=64, top_p=0.95, stop tokens [1, 106, 50]
generation_config.json: greedy, and the only stop token is not the one that ends a chat turn.Pass every sampling argument explicitly. Otherwise a comparison sets a greedy model against a sampling one.
Check
Next-token probabilities (0.4, 0.3, 0.2, 0.1). Top-k = 3 keeps the 3 most probable tokens; top-p = 0.75 keeps the smallest set that reaches probability 0.75. How many tokens can be sampled if (a) each cutoff is computed on the full distribution and the smaller count wins, (b) top-p is applied to the renormalized top-k distribution?
linear_attention): a head keeps a state of fixed size, which the delta rule decays and partly overwrites per token.P = Vd + L_f\,(A_f + 3df + 2d) + L_l\,(A_l + 3df + 2d) + d
V vocabulary rows, d width, f MLP width; L_f full-attention layers with A_f attention parameters each, L_l recurrent layers with A_l each.
from config from header
model.language_model 1,881,825,088 1,881,825,088
model.visual 331,416,576 331,416,576
mtp 60,828,160 60,828,160
total 2,274,069,824 2,274,069,824
Qwen/Qwen3.5-2B as loaded: 1,881,825,088 parameters, from its configuration 1,881,825,088
embedding 508,559,360; one layer: full attention 52,433,408, linear attention 58,814,624
508{,}559{,}360 + 6 \cdot 52{,}433{,}408 + 18 \cdot 58{,}814{,}624 + 2{,}048 = 1{,}881{,}825{,}088. The MLP, 3df, is 72% of a full-attention layer.
| group | parameters |
|---|---|
| per-layer embedding, 262{,}144 \times 35 \times 256 | 2,348,810,240 |
| embedding, shared with the output layer | 402,653,184 |
| attention, MLPs, projections and norms of 35 layers | 1,877,105,920 |
| loaded text model | 4,628,569,344 |
| multiplied in a forward pass | 2,279,759,104 |
Bytes per sequence at context n, in bf16, with an fp32 state:
| per token | constant | |
|---|---|---|
| Qwen3.5-2B: 6 full-attention layers, 18 states | 6 \cdot 2{,}048 = 12{,}288 | 19,759,104 |
| the same shape, 24 full-attention layers | 49,152 | 0 |
| Gemma 4 E2B: 3 full, 12 sliding layers | 6,144 | at most 6,279,168 |
| the same shape, 35 caches, no window | 43,008 | 0 |
12{,}288\,n + 19{,}759{,}104 = 49{,}152\,n at n = 536. Beyond it the hybrid holds less: 0.27 of the all-attention cache at 16,384 tokens.
live cache at 1,024 tokens: 13,467,648 B bfloat16, 18,874,368 B float32
recurrent state float32 | convolution inputs bfloat16
n walker MiB formula MiB growth after step peak held
256 21.84 21.84 1.0 1.0 0.98 1.0
1024 30.84 30.84 1.0 1.0 0.98 1.0
4096 66.84 66.84 1.0 1.0 0.98 1.0
16384 210.84 210.84 1.0 1.0 0.98 1.0
walker: bytes of the tensors in the cache. Later columns: measured over derived.Check
Qwen3.5-2B: weights 3.505 GiB. A prefill of 4,096 tokens needs 0.355 GiB per sequence (cache, state, activations). How many sequences fit a budget of 15 GiB? And for Gemma 4 E2B, with 8.621 GiB and 0.467 GiB?
expandable_segments:True); its overhead is then 167 MiB.kernels: attention sdpa, delta rule fla, short convolution PyTorch
n kernels formula peak prefill_s decode_ms top-1 agree max |diff|
4096 fused 0.355 0.349 0.120 26.33
4096 reference 0.355 0.530 0.214 29.15 0.97 0.281
4096 ref., batch 2 0.98 0.250
16384 fused 1.363 1.340 0.588
16384 reference 1.363 2.060 1.094 0.98 0.625
65536 fused 5.394 5.306 2.863
65536 reference 5.394 8.185 5.830 1.00 0.438
fla, for the recurrent layers): a few kernels per layer.Gemma 4 E2B, peak memory of a prefill above the weights, in GiB:
| prompt tokens n | fused | reference | difference / n^2 bytes | fused is faster by |
|---|---|---|---|---|
| 4,096 | 0.48 | 0.49 | 0.96 | 1.3× |
| 16,384 | 1.9 | 2.2 | 1.00 | 1.9× |
| 32,768 | 3.8 | 5.0 | 1.15 | 2.5× |
| 65,536 | 7.7 | out of memory |
R(n) = b\,(P - P_g) + \textrm{KV}_\textrm{read}(n) + 2S, \qquad t_\textrm{step} \ge R(n) / \beta
b bytes per number, P parameters, P_g of them looked up, not multiplied; cache read; state S read and written; \beta bandwidth.
| bytes held | bytes read per step | R / \beta at 0.92 TB/s | |
|---|---|---|---|
| Qwen3.5-2B | 3.8 GB | 3.8 GB | 4.1 ms |
| Gemma 4 E2B | 9.3 GB | 4.6 GB | 5.0 ms |
| ratio | 2.46 | 1.20 |
Qwen3.5-2B: device busy 24%-26% of the step, 17.1-17.3 us of wall time per launch
16,384 / 256 tokens: wall 1.00, busy 1.10, bytes read 1.05
Gemma 4 E2B: device busy 22%-43% of the step, 14.2-14.7 us of wall time per launch
16,384 / 256 tokens: wall 1.03, busy 2.03, bytes read 1.05
matrix products Gemma/Qwen: 1.27 (bytes read 1.20, bytes held 2.46)
Qwen3.5-2B: matrix products 4.34 ms, weights read at measured bandwidth 4.09 ms
Gemma 4 E2B: matrix products 5.50 ms, weights read at measured bandwidth 4.96 ms
Check
Qwen3.5-2B at batch 1 reads 3.8 GB per decode step at 0.92 TB/s, and a step launches about 1,500 kernels at about 17 µs of wall time each. What does the bound allow, and what does the clock show?
Wrap-up
Next: the same kind of tensors in the book’s own code, checked layer by layer.