Pretrained Models with Hugging Face

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 Name Says 2B, the File Holds 2.27B, the Model Loads 1.88B

The problem

A few library calls download Qwen3.5-2B and it answers a question.

  • The weight file holds 2,274,069,824 numbers in 4.55 GB. The loaded model has 1,881,825,088 parameters.
  • Will a prompt of 16,384 tokens fit next to it? How many prompts at once?
  • How fast can it write on a GPU that moves 1 TB/s?

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.

By the End of This Deck You Can

Goals

  • read every tensor’s shape from a repository without downloading weights;
  • pin a load so that it returns the same model next month;
  • count a model’s parameters from its configuration, to the last one;
  • derive the memory per sequence and the largest batch within a budget;
  • bound the time of a decode step and find where an eager step spends it.

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.

First Open a Checkpoint, Then Measure It

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
  • Uses: d2l.GPT with GPT-2’s weights, the KV cache, hybrids, the bandwidth bound on decoding.
  • Skips: fine-tuning, serving engines, licenses in depth (Tools appendix).

GPT-2 Continues the Question; a Current Model Answers It

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.

A Repository Is One Commit of Configuration, Tokenizer and Tensors

  • config.json: every shape.
  • Tokenizer files and chat_template.jinja: text to token ids.
  • One safetensors shard: 4,548 MB of 4,571 MB.
  • generation_config.json: optional, absent here.
  • The modeling code is in the library, selected by model_type.

Two Range Requests Read Every Tensor’s Shape

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: What Does the File Store?

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?

  • 4{,}548 \cdot 10^6 / 2{,}274{,}069{,}824 = 2 bytes per number: 16-bit floats (bf16).
  • 1{,}881{,}825{,}088 \cdot 2 bytes = 3.76 GB = 3.5 GiB of weights.
  • The other 392 million numbers, 0.8 GB, stay on disk.

A Pin Fixes the Files; an Error on Missing Tensors Checks the Load

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.

GPT-2 Spends Three Times as Many Tokens on Chinese

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
  • English: about 4 characters per token for all four.
  • GPT-2 (50,257 tokens from English web text) spends a token on every indentation space and breaks a Chinese character into pieces.

This ratio turns every cost per token (bytes of cache, ms per step) into a cost per character of text.

The Model Reads the Rendered Template, Not the Question

<|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>', 'ĊĊ']
  • The markers that open and close a turn are one token each (248045 and 248046).
  • The prompt ends inside the assistant’s turn, so the model answers.
  • Qwen can reason in a <think> block first. enable_thinking=False: the template closes the block. Defaults differ by checkpoint: pass it.

A Cached Step Takes About 30 ms; Reading the Weights Takes 4 ms

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
  • A four-line argmax loop without a cache writes the same 32 tokens, about 1.5 times slower after 1,024 tokens and about 8 times after 8,192.
  • With the cache: about 1 s for 32 tokens, roughly 30 ms each. Reading 3.8 GB of weights at 1 TB/s takes 4 ms. Where is the rest?

Sampling Defaults Hide in the Repository

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]
  • No generation_config.json: greedy, and the only stop token is not the one that ends a chat turn.
  • With one: Gemma samples, so two calls usually give two different replies.

Pass every sampling argument explicitly. Otherwise a comparison sets a greedy model against a sampling one.

Check: Top-k and Top-p Together

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?

  • Rule (a): top-k keeps 3; top-p needs 3, since two tokens hold only 0.7. Three tokens.
  • Rule (b), as in Transformers: drop the fourth, renormalize to (0.44, 0.33, 0.22); two tokens hold 0.78. Two tokens.

Few Layers Keep a Growing Cache: 6 of 24, and 3 of 35

  • Qwen3.5-2B, a hybrid: (3 recurrent layers, 1 full-attention layer) × 6. Recurrent (linear_attention): a head keeps a state of fixed size, which the delta rule decays and partly overwrites per token.
  • Gemma 4 E2B: (4 sliding layers, window 512, 1 full layer) × 7. The last 20 reuse the keys and values of layers 13 and 14, so 15 layers keep a cache: 3 full, 12 sliding.

The Configuration Counts the Parameters to the Last One

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.

Half of Gemma 4 E2B Is a Table Read One Row per Token

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
  • The table is looked up: it takes memory, not time.
  • The file stores 18,880,512 more numbers: key and value projections of the 20 sharing layers, which the library never builds.

A Hybrid’s Memory per Sequence Is a Slope Plus a Constant

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
  • One full-attention layer: 2 (keys, values) × 2 heads × 256 × 2 bytes = 2,048 bytes per token.

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.

The Live Cache Matches the Slope and the Constant to the Byte

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
  • Prefill: one pass over the prompt that keeps its cache. walker: bytes of the tensors in the cache. Later columns: measured over derived.
  • A prefill of 4,096 tokens: weights 3.505 GiB, cache 0.047, state 0.018, activations 0.289, the tensors of the pass itself. Six times the cache.
  • All logits of 16,384 positions would add 8.1 GB, twice the weights: keep one position.

Check: How Many Prompts Fit in 15 GiB?

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?

  • (15 - 3.505) / 0.355 = 32.4: 32 sequences. Measured: 32.
  • Gemma: (15 - 8.621) / 0.467 = 13.7: 13. Measured: 13. A prefill holds every position of the sliding layers, not the window.
  • Only with an allocator that does not fragment (expandable_segments:True); its overhead is then 167 MiB.

A Fused Kernel Takes Two Thirds of the Memory and Half the Time

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
  • Kernel: a compiled GPU program. A launch costs the CPU (the host) 5 to 15 µs, and results between kernels pass through memory.
  • Reference code: a kernel per operation, fp32 copies, a Python loop. Fused (fla, for the recurrent layers): a few kernels per layer.
  • Same top token at 97% to 100% of positions; batch 2 against 1: 98%.

A Window Mask Takes n² Bytes; Flex Attention Compiles It Away

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
  • Reference: a mask tensor, one byte per pair of positions. Up to 16,384 tokens the difference is the mask alone.
  • In each call the attention kernel adds a copy at 2 bytes per pair: 3n^2 bytes, 12 GiB at 65,536 tokens. Out of memory on 24 GB.
  • Flex attention: the mask is a function inside the kernel; empty tiles are skipped.

A Decode Step Reads the Weights Once: at Least 4 ms

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

An Eager Decode Step Spends Three Quarters of Its Time on the Host

  • Left: the measured points lie on the derived lines.
  • Right, on a log scale: wall time (solid), GPU (the device) busy (dashed), bytes read / \beta (dotted). Qwen3.5-2B: about 26, 6 and 4 ms.
  • Eager: Python on the host issues every operation, about 1,500 and 3,200 launches per step, some 15 µs each.

Matrix Products Follow Bytes Read: 1.3 Times, Not 2.5

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
  • Matrix products run within about 10% of the bandwidth bound.
  • Gemma 4 E2B holds 2.5 times the bytes and reads 1.2 times: half of its parameters take memory and no time.
  • Outside the bound: Gemma’s attention kernel for one query takes 10 ms at 16,384 tokens.

Check: The Bound and the Clock

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?

  • Bound: 3.8 / 0.92 \approx 4.1 ms, about 240 tokens per second.
  • Clock: 1{,}500 \times 17 µs \approx 26 ms, about 40 tokens per second.
  • A compiled decode loop removes the launches, not the 4 ms.

Wrap-up

Wrap-up

  • A checkpoint is a pinned commit: configuration, tokenizer, template, tensors. The code is in the library.
  • The configuration of Qwen3.5-2B gives its 1,881,825,088 parameters exactly, and its memory per sequence: 12,288 bytes per token plus 18.8 MiB.
  • Within 15 GiB: 32 prompts of 4,096 tokens, as derived.
  • Fused kernels: two thirds of the memory, half the prefill time.
  • Decode: bound 4 ms, matrix products within 10% of it, wall time 26 ms.

Next: the same kind of tensors in the book’s own code, checked layer by layer.