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.
#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.
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:
"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 |
#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.
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.
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.
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.
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.
#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.
- Instantiate architecture first, from the config, on the
metadevice, so no memory is allocated for random weights that will be thrown away. - Load tensors from the safetensors file, one at a time with
safe_open, or all at once withload_file. - Match dtype: keep bf16 for inference unless you have a reason not to (Section 34).
- Match device: load straight onto the GPU if that is where the model will run.
- Copy parameters: map each name and assign the tensor to its parameter.
- Validate every shape, and check that every parameter was filled exactly once.
- Freeze weights for inference: no gradients, evaluation mode.
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.
#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.