20.3.4 Portability and load triage
This part of Model Loading: Hub to GPU develops the mechanisms below. Work the numerical examples or trace the code before checking the answer.
Concepts from other sections (12)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Transformation (JAX): a function such as
jit,grad,vmap, orpmapthat takes a pure function and returns a compiled, differentiated, batched, or parallel version of it. Read more: 16.3 Embeddings, small models, and platforms - KV cache: the stored keys and values of all processed tokens, per layer, that let each new token attend without recomputation. Read more: Chapter 20: Inference Engines and GPU Deployment
- BF16: a 16-bit float with float32’s sign and exponent and 7 mantissa bits; the top half of a rounded float32. Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream
- fp16: a 16-bit format with 5 exponent bits and 10 mantissa bits; finer precision but a maximum of 65504 and a smallest subnormal of . Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing
- Tied embeddings: one Tensor shared by generator and discriminator, trained by both losses. Read more: 12.3 ELECTRA: replaced-token detection
- MXFP4: blocks of 32 FP4 E2M1 codes sharing one power-of-two E8M0 scale. Read more: 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
- Grouped-query attention (GQA): query heads share key/value heads, each serving a contiguous group of query heads. Read more: 13.5 Grouped-Query Attention with a Cache Hook, Windows, and Sinks
- Mixture of experts (MoE): a layer of many expert MLPs of which a router picks per token. Read more: 13.8 Mixture of Experts
- RoPE: rotary position embedding, which rotates queries and keys by position to encode relative position. Read more: 5.3 Model landscape and lifecycle
- time to first token (TTFT): the time until the first body byte of an answer is ready to send to the client. Read more: 25.3 The SSE streaming proxy
- LoRA: a frozen Linear plus a trainable low-rank update . Read more: 12.6 LoRA: low-rank adaptation with PiSSA initialization and merging
- Service Level Agreement (SLA): an agreement specifying service commitments, how they are measured, and consequences when they are missed. Read more: Chapter 13: Engineering Acronyms in Software Engineering
Learning objectives
- Separate artifact, loader, execution, and tokenizer failures.
Beyond PyTorch: JAX, Flax NNX, and Keras 3
Section titled “Beyond PyTorch: JAX, Flax NNX, and Keras 3”Everything so far assumed PyTorch, but transformers v5 dropped its TensorFlow and Flax backends, so the JAX world loads through its own stack. The pattern is the same as the meta-device skeleton, expressed in Flax NNX and Orbax: build an abstract model with shapes only, then restore into it.
# Flax NNX + Orbax: build an abstract model (shapes only), then restore into itabstract = nnx.eval_shape(lambda: Transformer(cfg, rngs=nnx.Rngs(0)))graphdef, abstract_state = nnx.split(abstract)state = ocp.StandardCheckpointer().restore(ckpt_dir / "state", abstract_state)model = nnx.merge(graphdef, state)nnx.eval_shape plays the role of PyTorch’s meta device, and Orbax restores each array directly onto its target sharding across a device mesh, with no host-side gather; this is how MaxText and TPU serving load. Converting Hugging Face safetensors into JAX means the same key renaming plus transposes, because nn.Linear stores out × in while Flax Dense kernels store in × out.
Keras 3 and KerasHub presets are backend-agnostic. keras_hub.models.CausalLM.from_preset("hf://<org>/<repo>", dtype="bfloat16") converts supported Hugging Face architectures (Llama 3, Gemma, Mistral, Mixtral, Qwen, gpt-oss, and others in utils/transformers/) on load and runs them on JAX, PyTorch, or TensorFlow.
A triage playbook
Section titled “A triage playbook”The four layers give you a diagnostic order. When a customer reports a problem, start from their words, run the first command, and check the most likely causes in order:
| Customer says | First command | Most likely cause |
|---|---|---|
| “Won’t load” | safetensors_inspect.py <index.json> and diff keys vs base model | Prefix drift, missing shard, fused or renamed projections, unknown model_type |
| “Loads but OOMs” | config_explain.py config.json | Weights + KV cache at max context exceed GPU; dtype upcast to FP32 |
| “Slow to start” | Time each term of the cold-start equation separately | Pulling from the Hub per replica; network filesystem with mmap; no warm cache |
| “Gives garbage” | Same prompt in transformers BF16 vs engine | Missing lm_head, FP16 overflow, TP slicing of fused tensors, quant config mismatch |
| “Worse than the base model” | Diff templated token ids vs training | Chat template, double BOS, EOS list, sampling defaults |
| “Never stops” | Print generation_config.eos_token_id | Turn terminator not in EOS list |
The best way to internalize this table is to break a load on purpose. Run code/safetensors_inspect.py with --url against three Hub models (one with tied embeddings, one FP8, one MXFP4) and explain every tensor name you see. Then rename keys with a module. prefix, drop lm_head.weight, delete rope_scaling, and swap the chat template, recording the symptom of each. The table you produce is your on-call runbook. Finally, read one real loader end to end: vLLM’s llama.py, following hf_to_vllm_mapper and AutoWeightsLoader.
Where this leads
Section titled “Where this leads”Every tensor name in a checkpoint corresponds to a piece of the transformer block from Deep Learning: attention projections, GQA heads, MoE experts, RoPE parameters. The FP8, MXFP4, NVFP4, AWQ, and GPTQ tensors you learned to recognize here are derived in Quantization: Math to Code. LoRA adapters and chat templates come from fine-tuning and SFT data formatting, covered in Training and Post-Training. Getting weights onto nodes through image baking, daemonsets, and warm pools is the subject of Cloud Native in Systems Engineering, and measuring each cold-start term alongside time to first token belongs to Observability. Once a model loads, Serving & Load takes up what happens when traffic arrives.
This is daily work at inference providers. At Fireworks, Together, and Baseten, field engineers debug customer checkpoints, LoRA multi-tenancy, and cold-start SLAs; Hugging Face owns the Hub storage, safetensors, and the transformers loader; NVIDIA ships ModelOpt FP8 and NVFP4 checkpoints, TensorRT-LLM engine builds, and GPUDirect Storage; Modal, Replicate, and RunPod compete on scale-to-zero, GPU memory snapshots, and weight caching; Anyscale and Databricks run vLLM-based serving from model registries and object-store streaming; and Google builds on Orbax, MaxText, KerasHub, and TPU serving.
Further reading
Section titled “Further reading”- safetensors format spec
- Transformers: Loading models and Dynamic weight loading
- huggingface_hub: Download files and Understand caching
- vLLM engine arguments
- Transformers: Chat templates
- GGUF spec, Hub Xet storage,
hfCLI guide - vLLM Run:ai Model Streamer, fastsafetensors, CoreWeave tensorizer, NVIDIA cuda-checkpoint
- PEFT LoRA docs and the LoRA paper
- FP8 formats paper and the OCP Microscaling (MX) spec
- Flax NNX checkpointing and KerasHub
Key terms
Section titled “Key terms”- safetensors: a weight format consisting of an 8-byte little-endian header length, a JSON header of tensor names, dtypes, shapes, and offsets, and a flat byte buffer.
- revision: a commit sha in a Hub repo; pinning one makes a load reproducible, while
maincan change. - meta device: a PyTorch device that records tensor shapes without allocating memory, used to build a model skeleton before filling it from a checkpoint.
- fused projection: an engine-side parameter such as
qkv_projorgate_up_projthat concatenates several checkpoint tensors into one GEMM. - column- and row-parallel: the two tensor-parallel slicing patterns, splitting a weight’s output rows (no communication) or its input columns (partial sums followed by an all-reduce).
- LoRA adapter: a low-rank update stored separately from the base model.
- cold start: the time from scheduling a replica to serving its first request, dominated by fetching and reading weight bytes and then by engine initialization.
- chat template: a Jinja program that renders a list of chat messages into the exact token sequence the model was trained on.
Summary
Section titled “Summary”- A model is config plus weights plus tokenizer plus generation defaults, each in a different file; garbage output is more often a tokenizer or config bug than a weights bug.
- safetensors is a JSON header plus a flat byte buffer, so you can inspect any checkpoint, even remotely, by reading its first
8 + Nbytes. from_pretrainedand engine loaders are key-matching problems; prefix drift, tied weights, fused projections, and tensor-parallel slicing of fused tensors cause most failures.- Cold start is roughly plus engine init; cache placement beats loader tuning, and production never loads from the Hub at request time.
- Chat templates fail silently; only diffing templated token ids against training proves correctness.
Review questions
Section titled “Review questions”- A customer’s checkpoint loads with “Some weights were not initialized” for every layer, and the unexpected keys all start with
module.. What happened, and how do you fix it?Answer
The checkpoint was saved from a DDP wrapper (similar prefixes come from `torch.compile`, `_orig_mod.`, and PEFT, `base_model.model.`), so every name carries a prefix the model's parameters lack and no key matches. Diff the header keys against `model.state_dict().keys()` to confirm, then strip the prefix or re-save from the unwrapped model (for PEFT, `merge_and_unload()` first). - How can you learn the dtypes and shapes of every tensor in a 100 GB remote checkpoint without downloading it?
Answer
Read the safetensors header with HTTP `Range` requests: the first 8 bytes give the header length `N` as a little-endian u64, and the next `N` bytes are a JSON object listing each tensor's dtype, shape, and data offsets. Two range requests suffice; `safetensors_inspect.py --url` does exactly this. - Hand-derive the parameter count of Llama 3.1 8B from its config (vocabulary 128,256; hidden size 4096; 32 layers; 32 query heads and 8 KV heads of dimension 128; MLP intermediate size 14,336; untied embeddings). Check it against the index file.
Answer
The embedding and the untied `lm_head` are each $128{,}256 \times 4096 = 525{,}336{,}576$. Per layer, attention has $q$ and $o$ at $4096 \times 4096 = 16{,}777{,}216$ each and $k$ and $v$ at $4096 \times 1024 = 4{,}194{,}304$ each, for 41,943,040; the MLP has three $4096 \times 14{,}336$ matrices, 176,160,768; and two RMSNorm vectors add 8,192. That is 218,112,000 per layer, or 6,979,584,000 for 32 layers. Adding both embedding matrices and the final 4,096-element norm gives 8,030,261,248, and at 2 bytes each in BF16 that is 16,060,522,496 bytes, exactly the index's `metadata.total_size`. - Why must a fused
gate_up_projbe sliced per sub-matrix under tensor parallelism, and why is getting it wrong so dangerous?Answer
The fused tensor is $[G; U]$, and each rank needs its slice of both, $[G_r; U_r]$. Taking the contiguous $r$-th chunk of the fused tensor would give rank 0 all of $G$ and the last rank all of $U$. Because the shapes still match, this loads without error and silently produces garbage. - Using the cold-start table, explain why “cache placement beats loader tuning”, and what becomes the floor once weights are local.
Answer
A 70B BF16 model takes about 12 minutes over a single HTTP stream but about 22 s from one local NVMe drive and 2.8 s across PCIe Gen5; the network and disk terms dominate the others by 10 to 100 times, so where the bytes sit matters far more than how the loader reads them. Once weights are local, engine initialization (CUDA graph capture and compilation, often 20 to 60 s) is the floor, which GPU state snapshotting attacks. - An instruct fine-tune never stops generating and keeps printing
assistantturns. What do you check?Answer
Compare `generation_config.eos_token_id` with the template's turn terminator. In Llama 3 an instruct turn ends with `<|eot_id|>` (128009); if only `<|end_of_text|>` (128001) is listed as EOS, generation runs past each turn. Make `eos_token_id` a list containing every terminator. - Why are chat-template mismatches silent, and what is the one reliable test?
Answer
The model still receives valid tokens, so it produces fluent text; it is merely conditioned on an out-of-distribution prefix, which shows up as ignored system prompts, malformed tool calls, more refusals, and a few points lost on evals. The reliable test is to compare the token ids from `apply_chat_template(..., add_generation_prompt=True)` with the ids of the training formatter's output tokenized with `add_special_tokens=False`, and assert they are identical.