Highlights

Contents

Part VI
06

Checkpoints and Loading

Loading must preserve each tensor’s learned role. Correct names and shapes are necessary but insufficient. Inspect file structure, mapping, orientation, fused ordering, dtype, and sharing before trusting the loaded model.

YOU ARE HEREmessageschat templatetokenizertoken IDsconfig.jsonmodel.safetensorsint8 / int4 weightsOUR DECODER, REBUILT FROM THE CONFIGprefilldecodeattention kernelKV cacheparity checkvs referenceLM head → logitssamplingdetokenizereply textnext token

#Section 30Safetensors

What a model checkpoint stores

A checkpoint is the trained numbers and nothing else: one tensor per parameter, each with a name, a shape and a data type. It does not contain the architecture. Nothing in the file says “this tensor is a query projection, multiply by it after the norm”. That knowledge lives in the code, which is why Part V had to come first. Qwen3-0.6B’s checkpoint is one file, model.safetensors, 1,503,300,328 bytes. Larger models split theirs across several shards plus a small model.safetensors.index.json that says which tensor lives in which shard; Llama 3 8B ships as four.

The format

A safetensors file begins with the header length, followed by a JSON header and raw tensor bytes. Header entries describe where each tensor sits, so a loader can read selected tensors without decoding arbitrary objects.

MODEL.SAFETENSORS FOR QWEN3-0.6B: 1,503,300,328 BYTES, THREE ZOOMSthe whole filelm_headembed_tokens28 layers × 31,461,888 bytes (+ final norm)the first 35,560 bytesN = 35,552{ "lm_head.weight": {…}, …, "__metadata__": {"format": "pt"} }data →8 bytes, u64 little-endianJSON header: 311 entries"model.layers.0.self_attn.q_proj.weight": "dtype": "BF16", "shape": [2048, 1024], "data_offsets": [647500288, 651694592]4,194,304 bytes= 2,048 × 1,024 × 2
Figure 4.38Qwen3-0.6B’s checkpoint, drawn to its real proportions in three zooms. An 8-byte length, a 35,552-byte JSON header, then 1.5 GB of bf16 numbers packed end to end; each header entry points at its own slice.

The header maps each tensor name to its tensor dtype, its tensor shape and a pair of byte offsets into the data section. Here is the real entry for the first layer’s query projection:

text
"model.layers.0.self_attn.q_proj.weight": {
  "dtype": "BF16",
  "shape": [2048, 1024],
  "data_offsets": [647500288, 651694592]
}

Validate each byte range against its shape and dtype. Metadata is framework text, not executable code.

Offsets enable selective reads. The quantization example fetches one weight row without downloading the entire checkpoint.

Why safetensors exists

PyTorch’s traditional checkpoint, a .bin or .pt file written by torch.save, is a pickle: Python’s general object serialization format. Unpickling does not just read data; it rebuilds objects by calling functions named in the file. A malicious file can name any function, including one that runs a shell command, and torch.load will call it. Loading an untrusted pickle checkpoint is running untrusted code.

Safetensors, released by Hugging Face in 2022, is the answer: a format that can only describe tensors. Safe loading follows from the design. The loader parses JSON and copies bytes, so there is nothing to execute. It is also fast: the data section can be memory-mapped, so tensors are read from disk only when touched, and with no copy when the dtype and device already match.

Pickle (torch.save) Safetensors
Can run code when loaded yes, by design no
Read one tensor without reading the file no yes, by offset
Memory-mapped, zero-copy loading no yes
Stores arbitrary Python objects yes (optimizer state, configs) no, tensors and string metadata only
Header readable by any language no yes, JSON
WHAT THE LOADER IS HANDEDpytorch_model.bin (pickle)rebuild Tensor(storage 0, …)rebuild Tensor(storage 1, …)…call os.system("…")follows everyinstructionmodel.safetensors{"name": {dtype, shape, offsets}, …}copya table of contents and a block of bytes:nothing to executea program for rebuilding objects
Figure 4.39Opening the two kinds of file. A pickle hands the loader instructions to follow, and some instructions can be anything; a safetensors file hands it a table of contents and a block of bytes.

#Section 31State Dictionaries

A PyTorch model keeps its parameters inside a tree of modules. A state dictionary flattens that tree into a dictionary from parameter names to tensors. The names are built from nested module names: the attribute path from the root module to the parameter, joined with dots. In Hugging Face’s Qwen3, the root Qwen3ForCausalLM has a model attribute, which has a layers list, whose entry 0 has a self_attn attribute, which has a q_proj linear layer, which has a weight. So that tensor is model.layers.0.self_attn.q_proj.weight. The checkpoint’s tensor names are exactly these state-dict keys.

A STATE-DICT KEY IS THE PATH THROUGH THE MODULE TREEQwen3ForCausalLMmodellm_headlayersembed_tokens, norm01, 2, … 27self_attnmlp, input_layernorm, post_attention_layernormq_projk_proj, v_proj, o_proj, q_norm, k_normweightkey:model.layers.0.self_attn.q_proj.weight
Figure 4.40How a tensor gets its name. The path from the root module down to the parameter, joined with dots, is the key in the state dict and the name in the checkpoint.

Mapping names to tensors is all a state dict does, and loading state dictionaries is the reverse: model.load_state_dict(sd) walks the dictionary and copies each tensor into the parameter with the same name. With the default strict=True it also compares the two sets of names and reports three kinds of problem.

Missing keys are parameters your model has that the dictionary does not. If you built your model with q_norm and k_norm but load a Qwen2.5 checkpoint, those 56 tensors are missing, and with strict=False they keep their random initial values. Unexpected keys are tensors in the dictionary your model has no place for. Load Qwen3 into a model built Qwen2.5-style and the 56 norm weights are unexpected; load it into a model whose LM head is tied and has no separate parameter, and lm_head.weight is unexpected. Shape mismatches are names that match with shapes that do not, and PyTorch raises an error for them even with strict=False. The head-size bug of Section 26 shows up here: q_proj.weight expected (1,024, 1,024), found (2,048, 1,024).

The dangerous habit is strict=False to “make the errors go away”. Missing keys then silently keep random values, and the model runs. Use strict=False only when you have listed every expected missing or unexpected key and checked the list matches.

#Section 32Weight Mapping

Reference model naming vs our model naming

Our model does not have to use Hugging Face’s names, and usually does not. The job of weight mapping is a function from each name in the checkpoint to the name and layout of a parameter in our model. For Qwen3 and the model we built in Section 26:

Checkpoint (reference) name Our name Transform
model.embed_tokens.weight tok_emb.weight none
model.layers.{i}.input_layernorm.weight layers.{i}.norm1.weight none
model.layers.{i}.self_attn.q_proj.weight layers.{i}.wq.weight none (both (out, in))
model.layers.{i}.self_attn.k_proj.weight, v_proj layers.{i}.wk.weight, wv none
model.layers.{i}.self_attn.q_norm.weight, k_norm layers.{i}.q_norm.weight, k_norm none
model.layers.{i}.self_attn.o_proj.weight layers.{i}.wo.weight none
model.layers.{i}.post_attention_layernorm.weight layers.{i}.norm2.weight none
model.layers.{i}.mlp.gate_proj.weight, up_proj, down_proj layers.{i}.gate.weight, up, down none
model.norm.weight norm_f.weight none
lm_head.weight (tied to tok_emb.weight) skip, after checking equality

Mapping layer by layer repeats the mapping pattern for every block and adds the global tensors. Store the mapping as data so missing or duplicate assignments can be inspected.

ONE LAYER: CHECKPOINT NAMES → OUR PARAMETERS (i = 0 … 27)model.layers.{i}.layers.{i}.input_layernorm.weightnorm1.weightself_attn.q_proj.weightwq.weightself_attn.k_proj.weightwk.weightself_attn.v_proj.weightwv.weightself_attn.q_norm.weightq_norm.weightself_attn.k_norm.weightk_norm.weightself_attn.o_proj.weightwo.weightpost_attention_layernorm.weightnorm2.weightmlp.gate_proj.weightgate.weightmlp.up_proj.weightup.weightmlp.down_proj.weightdown.weightq_norm, k_norm:missing in anyQwen2-style model+ embed_tokens → tok_emb, norm → norm_f, lm_head → tied (skipped): 28 × 11 + 3 = 311 names
Figure 4.41The mapping for one layer. Eleven checkpoint names on the left, eleven parameters of our model on the right; every one maps one to one with no transform, because our model also stores weights output size first.

Transposition issues

Our model used nn.Linear, which stores weights as (out, in), the same as the checkpoint, so nothing is transposed. If your model stores a weight as (in, out) and computes x @ W, every projection must be transposed when loaded. A real example: Hugging Face’s GPT-2 uses a Conv1D layer that stores (in, out), so porting GPT-2 into nn.Linear code needs transposes and porting Llama does not.

Rectangular transpose mistakes usually fail a shape check. Square matrices can load with the wrong orientation, so numerical parity is still necessary.

LOADING A TRANSPOSED WEIGHT: RECTANGLES FAIL LOUDLY, SQUARES FAIL SILENTLYq_proj (2048, 1024)expectedgiven (transposed)RuntimeError: size mismatchcaught at load timek_proj (1024, 1024)expectedgiven (transposed)loads without a wordevery key is wrong; only parity tests catch it
Figure 4.42A wrong transpose. For a rectangular matrix like q_proj the shapes disagree and loading fails; for a square one like k_proj the shapes agree, loading succeeds and every output is wrong.

Concatenated vs separate QKV matrices

Fused projections concatenate several weights and split the output afterward. Loading order must match that split order, including gate/up projections; a swapped ordering can pass shape checks.

GQA-specific shapes

GQA’s query block can be wider than its key and value blocks. Derive each fused size from the configured head count and head dimension, never by splitting into equal thirds.

FUSED QKV FOR QWEN3-0.6B: 4,096 ROWS × 1,024, SPLIT 2,048 / 1,024 / 1,024WQ (16 heads)WK (8 heads)WV (8 heads)02,0483,0724,096correct: sizes from H·d_h and H_kv·d_hq?k?v?MHA habit: three equal thirds
Figure 4.43Fusing q_proj, k_proj and v_proj into one matrix for Qwen3-0.6B. Under GQA the blocks are 2,048, 1,024 and 1,024 rows, not three equal thirds.

Embedding and LM-head handling

Qwen3-0.6B’s config says tie_word_embeddings: true: one matrix serves as both the embedding table and the LM head (Chapter 1, Section 14). Yet its checkpoint contains both model.embed_tokens.weight and lm_head.weight, two full copies, 311,164,928 bytes of duplication, a fifth of the file. Comparing the stored bytes of row 0 and of row 9,707, the embedding of the token “Hello”, the two copies are identical.

The right handling is to load the embedding, make the LM head point at the same tensor (model.lm_head.weight = model.tok_emb.weight), and skip lm_head.weight after checking, once, that it equals the embedding. If you load both into separate parameters instead, the model works but uses 311 MB more memory, and if you ever fine-tune it the two copies drift apart and the tie is broken. If a checkpoint for a tied model contains only the embedding, the LM head must be tied explicitly or it stays random.

TIED EMBEDDINGS: STORED TWICE IN THE FILE, KEPT ONCE IN MEMORYin the checkpointmodel.embed_tokens.weight311,164,928 byteslm_head.weight311,164,928 bytesrows 0 and 9,707 ("Hello"):byte for byte identicalin our modelone (151,936 × 1,024)matrixloadedchecked, skippedtok_emb.weightlm_head.weighttwo names, one tensor
Figure 4.44One matrix, two jobs. The checkpoint stores it twice under two names; the loader keeps one copy and points the LM head at it.

#Section 33Loading Pretrained Weights

With the mapping in hand, loading is a fixed sequence. Doing the steps in this order avoids every failure from Sections 31 and 32.

  1. Instantiate architecture first, from the config, on the meta device, so no memory is allocated for random weights that will be thrown away.
  2. Load tensors from the safetensors file, one at a time with safe_open, or all at once with load_file.
  3. Match dtype: keep bf16 for inference unless you have a reason not to (Section 34).
  4. Match device: load straight onto the GPU if that is where the model will run.
  5. Copy parameters: map each name and assign the tensor to its parameter.
  6. Validate every shape, and check that every parameter was filled exactly once.
  7. Freeze weights for inference: no gradients, evaluation mode.
python
from safetensors import safe_open

with torch.device("meta"):
    model = Qwen3(cfg)                                    # shapes only, no memory
params = dict(model.named_parameters())
seen = set()
with safe_open("model.safetensors", framework="pt", device="cuda") as f:
    for ckpt_name in f.keys():
        ours = mapping(ckpt_name)                         # None for lm_head.weight
        if ours is None:
            continue
        t = f.get_tensor(ckpt_name)                       # bf16, on the GPU
        assert t.shape == params[ours].shape, (ckpt_name, t.shape)
        set_param(model, ours, nn.Parameter(t, requires_grad=False))
        seen.add(ours)
model.lm_head.weight = model.tok_emb.weight               # tie
assert seen == set(params) - {"lm_head.weight"}, set(params) - seen
model.eval()

The last assertion is the one people skip. It proves that every parameter of our model came from the file and none was left at its initial value, which strict=False, or a missed name in a hand-written loop, would otherwise hide. Run generation under torch.inference_mode(), which turns off gradient tracking entirely.

LOADING IN SEVEN STEPS1 build on metashapes, no memory2 open the filesafe_open, lazy3 dtypekeep bf164 devicestraight to GPU5 map + assign311 names, 1 skipped6 validateevery shape, every param7 freezeeval, inference_modestep 6 is the one people skip
Figure 4.45Loading, in order. Build the shapes on the meta device, stream tensors from the file straight to the GPU, check each shape, tie the head, prove every parameter was filled, freeze.

#Section 34Dtype and Device Handling

CPU loading and GPU transfer

By default, load_file and torch.load put tensors on the CPU. CPU loading then GPU transfer with .to("cuda") works, but it holds the weights in CPU memory first and copies them across the bus. Loading straight to the GPU, with device="cuda" in safetensors, skips the round trip. Either way, every tensor that takes part in one operation must be on the same device, or PyTorch raises a device mismatch error such as “Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!”. The usual culprits are buffers created in __init__ rather than registered with register_buffer (they do not move with .to()), RoPE tables built on the CPU, and input IDs that were never moved.

FP32 vs FP16/BF16 checkpoints

Match the intended compute dtype. Copying low-precision tensors into an FP32 model increases storage; substituting FP16 for BF16 changes range and can overflow values the original format represents.

Casting

Casting inside the forward pass is deliberate in a few places. RMSNorm upcasts its input to fp32 to compute the mean of squares and casts back, because summing 1,024 squares in bf16 loses precision. RoPE’s cos and sin tables are computed in fp32 (Chapter 2, Section 3). Softmax inside attention kernels accumulates in fp32. Copy those choices from the reference exactly; a missing upcast is a classic small parity failure.

Memory-conscious loading

Constructing random weights and retaining a full loaded dictionary duplicates storage. Building on meta and assigning streamed tensors avoids those unnecessary copies. Check the resulting device, dtype, and tied aliases.

PEAK MEMORY WHILE LOADING QWEN3-0.6B0 GB1 GB2 GB3 GB4 GBnaivefp32 init + state dictrandom fp32 model 2.38file 1.503.89carefulmeta + stream bf16the model1.19Llama 3 8B: 48 GB against 16 GB
Figure 4.46Peak memory while loading Qwen3-0.6B. Random fp32 weights plus a full state dict peak at 3.89 GB; meta-device construction plus streaming bf16 tensors peaks at the model’s own 1.19 GB.