Sub topic 1
What is inside a model file
A trained model is stored in a file, and that file holds more than one kind of thing. This chapter separates the kinds and shows which are plain data and which can carry behavior. The rest of the tutorial depends on that distinction.
Prerequisites
This chapter assumes you have:
- Basic Python, including classes and special methods.
- Some familiarity with what a trained model and its weights are.
- Basic use of PyTorch, such as defining an
nn.Moduleand callingstate_dict(). - A general idea of what a file format and a byte stream are.
You do not need to know anything about pickle yet. The next chapters cover it.
A model is numbers plus a recipe
A trained network has two parts:
- The recipe is the architecture: which layers exist, how they connect, and what operations run between them.
- The numbers are the learned parameters, usually called weights. They are stored as tensors, which are multi-dimensional arrays of numbers.
Training changes the numbers and leaves the recipe fixed. Most of a model file's size comes from the numbers. A 7-billion-parameter model stored in 16-bit floats takes about 7 × 10⁹ × 2 bytes = 14 GB. The recipe is usually a few kilobytes.
Everything that is not a weight tensor is small, but it can have a large effect on safety. A model file can store plain data, such as numbers and strings. It can also store instructions about how to rebuild Python objects. The second kind is where the risk comes from.
The usual contents
Different files hold different subsets of the following items.
| Item | What it is | Typical size | Data or behavior |
|---|---|---|---|
| Weight tensors | Named arrays of learned parameters | Megabytes to hundreds of GB | Data |
| Tensor metadata | Name, dtype, shape and location of each tensor | Kilobytes | Data |
| Architecture description | Layer types and connections, as a graph, a config, or a pickled Python object | Kilobytes to megabytes | Depends on the format |
| Hyperparameters and config | Layer counts, hidden sizes, vocabulary size | Kilobytes | Data |
| Tokenizer | Vocabulary and merge rules that map text to integers | Megabytes | Data, if stored as JSON or a plain binary |
| Optimizer state | Per-parameter running statistics, such as Adam's moments | Often 2 times the weights | Data, but often saved with Python containers |
| Training bookkeeping | Epoch, step, learning-rate scheduler state, random seeds | Kilobytes | Mixed |
| Arbitrary Python objects | Whole `nn.Module` instances, custom classes, lambdas | Varies | Behavior |
The last row is the one to watch. A format that can store "any Python object" can store an object whose loading triggers code.
Weights, step by step
In PyTorch, the dictionary that maps parameter names to tensors is the state_dict. This example builds a small model and prints what its weights look like.
import torch
from torch import nn
model = nn.Sequential(nn.Linear(4, 3), nn.ReLU(), nn.Linear(3, 2))
state = model.state_dict()
total_bytes = 0
for name, tensor in state.items():
size = tensor.numel() * tensor.element_size()
total_bytes += size
print(f"{name:10} shape={tuple(tensor.shape)} dtype={tensor.dtype} bytes={size}")
print("total bytes:", total_bytes)The output lists four entries: 0.weight, 0.bias, 2.weight and 2.bias. The ReLU layer has no parameters, so it does not appear. The total is 92 bytes for 23 parameters at 4 bytes each.
Two details matter later:
- Names carry structure. The prefix
0.or2.is the layer's position in theSequential. Loading works by matching these names against the model you build in code. - The state dict has no layer logic. It does not say that a
ReLUsits between the two linear layers. To use these weights you must already have code that builds the same architecture. Formats that store only weights depend on that outside code.
Where the recipe lives
There are three common ways to keep the architecture, and they differ in safety.
- Code outside the file. The file holds only weights, and your own source defines the model class. This is the PyTorch
state_dictpattern and the safest of the three, because the file never describes behavior. - A declarative description inside the file. The file stores a graph of operations or a JSON config, which a runtime interprets. ONNX and the Hugging Face
config.jsonare examples. The runtime decides what each operation means, so the file can only name operations the runtime already supports. - Serialized code objects inside the file. The file stores the Python objects themselves, for example
torch.save(model, path)on a whole module. Loading must re-create those objects, and that is the pickle behavior covered in later chapters.
A full training checkpoint
A training checkpoint is a snapshot you can resume from. It holds more than weights.
import torch
from torch import nn
model = nn.Linear(4, 2)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# Take one step so the optimizer has state to save.
loss = model(torch.randn(8, 4)).pow(2).mean()
loss.backward()
optimizer.step()
checkpoint = {
"epoch": 1,
"model_state": model.state_dict(),
"optimizer_state": optimizer.state_dict(),
}
torch.save(checkpoint, "checkpoint.pt")
loaded = torch.load("checkpoint.pt", map_location="cpu", weights_only=True)
print(list(loaded.keys()))
print(list(loaded["optimizer_state"].keys()))The first line printed is ['epoch', 'model_state', 'optimizer_state']. The second is ['state', 'param_groups']. The state entry holds Adam's two running averages for each parameter, so the optimizer state is about twice the size of the weights. A resumable checkpoint is therefore roughly three times larger than the weights alone.
Checkpoints are often shared by mistake. People upload a training checkpoint when they meant to publish weights. This makes the download larger. It also exposes training details, and it gives the file more places to hold non-tensor objects.
Weights are not the whole model
For text models, the weights are unusable without matching auxiliary files. A model repository usually contains:
model.safetensorsorpytorch_model.binfor the weights.config.jsonfor architecture settings.tokenizer.jsonor similar for the text-to-integer mapping.generation_config.jsonfor default sampling settings.
Common errors come from these files not matching each other:
- Wrong tokenizer for the weights. The model loads without complaint and produces garbage, because token IDs mean different words.
- Config and weights disagree. A different
hidden_sizegives shape-mismatch errors when you load the weights. - Missing keys or unexpected keys. A checkpoint saved from a wrapped model, for example one wrapped in
DataParallel, has amodule.prefix on every name. Loading it into an unwrapped model fails until you strip the prefix. - Dtype surprises. A file saved in
float16that you load into afloat32model is converted silently, which doubles memory use. Treat dtype as part of the file's contents, not a detail.
Why files need a serialization step
Tensors live in memory as Python and framework objects. Memory disappears when the process ends, and it cannot be copied directly to another machine, because it holds pointers and runtime-specific layouts. To save a model you must convert it to a sequence of bytes. This is called serialization. Reading the bytes back into objects is deserialization.
Formats differ in what they promise about that second step:
- A format that stores only tensor bytes plus a description of their layout can be read by simple parsing.
- A format that stores instructions for rebuilding objects must run those instructions.
The following chapters build on this contrast. Pickle is the second kind, and PyTorch's classic .pt and .pth files use it.
Questions to ask about any model file
When you receive a model file, check four things before you load it:
- Which format is it? Check the real structure, not only the extension.
- Does it hold only tensors? Look for optimizer state, whole module objects, or custom classes.
- Where is the architecture defined? In your code, in a declarative graph, or in serialized objects.
- Who produced it? The source determines how much you can trust its contents.
Each of the formats in later chapters answers these four questions differently.
Exercise
A colleague sends you best.pt, produced by torch.save(model, "best.pt") where model is a whole nn.Module. Compare it with a file produced by torch.save(model.state_dict(), "best.pt"). Which one stores architecture information, and why does that matter for safety?
Show answer
The first file stores the whole module object, so the file itself describes the model's class and structure as serialized Python objects. Loading it must rebuild those objects, which means loading can invoke code. The second file stores only a dictionary of parameter names to tensors. It has no architecture, so you must define the model class in your own code and then call load_state_dict. The second pattern is safer because the file holds data rather than instructions for building objects.
Exercise
A float32 model has 1 billion parameters. Estimate the size of its weights in GB, and the size of a training checkpoint saved with the Adam optimizer, assuming Adam's state is stored in float32.
Show answer
The weights take 1 × 10⁹ × 4 bytes = 4 GB. Adam stores two extra float32 values per parameter, which adds 8 GB. The checkpoint is therefore about 12 GB, roughly three times the weights alone, plus a small amount for metadata.