Sub topic 1
What is inside a model file
Prerequisites
This chapter assumes you know basic Python, including classes, dictionaries, and methods. You should know that a trained model stores numbers called weights. The core examples need only the Python standard library.
What is inside a model file
A model file is a saved copy of a trained model. It usually holds the weights, which are the numbers the model learned during training. It may also hold layer names, training settings, and sometimes whole Python objects. A file is only a sequence of bytes on disk, so a program must convert in-memory objects into bytes when saving and back again when loading.
Serialization
Serialization converts an object into a byte stream. Deserialization is the reverse. Python's standard pickle module performs both steps.
import pickle
import pickletools
weights = {"layer1.bias": [0.1, -0.2], "epoch": 3}
data = pickle.dumps(weights, protocol=2)
print(len(data), "bytes")
print(pickle.loads(data) == weights) # True
pickletools.dis(data)How pickle works
A pickle is a list of instructions called opcodes. A small stack-based virtual machine runs these opcodes in order during loading. Each opcode pushes a value onto a stack, pops values off, or builds a new object from the stack. Because the file is a program for this machine, it can contain more than plain data.
Reading a pickle with pickletools
pickletools.dis prints each opcode as readable text. It does not run them. The output lists opcodes such as EMPTY_DICT, which creates a dictionary, and SETITEMS, which fills it. The exact opcodes depend on the protocol version you choose.
Why loading a pickle can run code
A class can define __reduce__, a method that tells pickle how to rebuild the object. The method returns a callable and its arguments. During loading, the unpickler calls that callable. A malicious file can name any importable function, such as os.system, so loading it runs that function.
Exercise
Why is it safe to run pickletools.dis on an untrusted pickle?
Show answer
It decodes each opcode into readable text and never performs the stack operations, so it never calls the function a payload names.