Sub topic 2
Serialization: turning objects into bytes and back
This chapter assumes you know basic Python, including classes and special methods. It also assumes you know what a trained model and its weights are. You don't need to know how pickle works yet. Later chapters cover that.
Why models must be serialized
A trained model lives in memory as Python objects, arrays, and framework data structures. When the process exits, all of it is gone. To reuse the model, share it, or deploy it, you have to write it to disk or send it over a network. Disks and networks carry bytes, not live objects.
Serialization is the process of turning an in-memory object into a sequence of bytes. Deserialization is the reverse: reading those bytes and rebuilding an equivalent object. The word "loading" in "load a model" almost always means deserialization.
import json
config = {"layers": 3, "dropout": 0.1}
data = json.dumps(config).encode("utf-8") # serialize: object -> bytes
print(data)
restored = json.loads(data.decode("utf-8")) # deserialize: bytes -> object
print(restored == config)The output is the bytes b'{"layers": 3, "dropout": 0.1}' followed by True. The round trip gives back an equal object.
What a serialized format has to describe
A serialization format is a contract between a writer and a reader. To rebuild a model, the bytes must answer several questions:
- What values exist? For a model, these are mostly tensors: large arrays of numbers.
- What type is each value? A tensor needs a dtype such as
float16orint8and a shape such as(4096, 4096). - How are the values arranged? Byte order (endianness), memory layout, and offsets all matter.
- How are the values named and related? Weights are usually keyed by name, such as
layer1.weight. - Is there structure beyond the data? Some formats also store the computation graph, the configuration, or the code needed to rebuild the model.
The last question is where formats differ most, and it is where the security risk comes from. Chapter 1 of this plan described what a model file contains. Here the focus is on how a format represents it.
Two broad design philosophies
Formats fall into two groups, based on what the reader is asked to do with the bytes.
Data-only formats
A data-only format stores values and a description of them. The reader parses the description, then copies bytes into arrays. The format cannot say "run this function". The worst a malicious file can do is be malformed, which a careful parser rejects.
JSON, CSV, and protobuf are general examples. In model formats, safetensors is a data-only format for tensors. GGUF and ONNX are also designed as data and graph descriptions. Later chapters cover each one.
Object-graph formats
An object-graph format tries to save arbitrary live objects, including instances of your own classes. To rebuild an instance of MyModel, the reader needs to know how to construct it. So the bytes contain instructions about which class or function to call and with what arguments.
Python's pickle is the main example. It is flexible. You can save almost any Python object without writing any save code. That flexibility is also the risk: the file contains instructions, and the loader follows them.
| Property | Data-only format | Object-graph format |
|---|---|---|
| What the bytes describe | Values, types, shapes | Values plus how to construct objects |
| What the reader does | Parses and copies data | Executes construction steps |
| Typical example | safetensors, JSON | pickle |
| Effort to save custom objects | You write the mapping | Mostly automatic |
| Risk from an untrusted file | Parser bugs only | Can run attacker-chosen code |
Trust at the deserialization boundary
Every deserializer reads bytes that someone else wrote, possibly at another time and place. That makes the load call a trust boundary. The question to ask is: how much power does the file's author get over my process?
- With a data-only format, the author controls the values in the arrays, and little else.
- With an object-graph format, the author may control which functions run, with the permissions of your process.
A model download is an easy way to cross this boundary without noticing. A line like model = load("downloaded_file") looks like reading data, but it can be running a program someone else wrote.
import json
# A text format can carry hostile *values*, but not instructions.
untrusted = '{"layers": 3, "note": "__import__(\'os\').system(\'echo hi\')"}'
parsed = json.loads(untrusted)
print(parsed["note"]) # just a string; nothing runsThe string looks dangerous but is only a string. JSON has no way to ask the parser to call a function. This is the property you want from a format for untrusted input.
The flow from training to inference
Models usually go through a pipeline: a trainer writes a file, the file moves through storage or a model hub, and a different machine loads it for inference. The writer and the reader are often different people.
The trust boundary is the step from file to memory on the consumer's machine. Safe practice at that step is the subject of the rest of this tutorial.
Common design choices and their consequences
Several design choices appear across model formats. They have different effects on safety, speed, and portability.
- Self-describing versus schema-based. A self-describing format, like JSON, carries field names in the data. A schema-based format, like protobuf, relies on a separate definition both sides share. Schemas make parsing stricter.
- Text versus binary. Binary formats are compact and fast for large tensors. Text formats are readable but slow and large for billions of floats.
- Copying versus memory mapping. Some formats lay out tensors so a reader can map the file into memory and use it without copying. That needs a fixed, simple layout with known offsets.
- Language-specific versus portable. Pickle is tied to Python. ONNX and GGUF can be read from many languages and runtimes.
- Code in the file versus code outside it. Formats that store only data require the loader to already have the model's code. Formats that embed construction steps can load without it, at a cost to safety.
Notice how these interact. A fixed layout with known offsets, which supports memory mapping, also makes the format simple to validate. A format that can reference arbitrary callables cannot be validated by looking at its structure alone.
Common errors at this stage
These mistakes come up often when people first think about model files:
- Assuming that a file extension tells you the format. A file named
model.binmight be pickle, safetensors, or something else. Extensions are labels, not guarantees. - Assuming that "loading" is a read-only operation. For some formats it is closer to running a script.
- Assuming that a popular source means a safe file. A model hub hosts files from many authors. The platform may scan files, but scanning is not a guarantee.
- Treating serialization as only a storage concern. It is also a security and compatibility concern: a format choice decides who can read your file and what a malicious file could do.
- Confusing a format with a library. PyTorch is a library. A
.ptfile is a file in a format that PyTorch happens to read and write. Different libraries can read the same format.
Where this leads
The next chapters look at pickle as a small virtual machine, then at how it can execute code on load, and then at the formats designed to avoid that problem. The idea to keep from this chapter is the split between formats that store data and formats that store instructions. That split decides how much you must trust a file's author before you open it.
Exercise
A teammate says: "Loading a model file is just reading numbers from disk, so it can't be dangerous." Using the data-only versus object-graph distinction, explain when this is true and when it is false.
Show answer
It is true for data-only formats such as safetensors, where the file holds tensor values and a description of them, and the reader only parses and copies bytes. It is false for object-graph formats such as pickle, where the file holds instructions for constructing objects, including which callables to invoke. Loading such a file executes those steps with your process's permissions, so the file's author can run code on your machine. The safe habit is to identify the format first and trust the file only as much as the format limits what it can do.
Exercise
Name two reasons a format with a fixed layout and known byte offsets is easier to validate than an object-graph format.
Show answer
First, a reader can check the structure without running anything: it can verify that offsets and sizes fit inside the file and that dtypes and shapes agree with the byte counts. Second, the format contains no references to arbitrary callables, so there is nothing to execute and no need to judge which functions are safe. An object-graph format can name any importable function, so its safety depends on what those functions do, not on the structure of the bytes.