Introduction
A .pt or .pth file is whatever
PyTorch wrote with its torch.save
function. Most often it is a model’s state_dict, a dictionary from layer
names to weight tensors, but it can be any Python object that contains tensors: a whole
model, an optimiser’s state or a training checkpoint. The
two extensions mean the same thing. Hugging Face models from before safetensors are
the same format named pytorch_model.bin.
Loading one uses Python’s pickle module, which can run code hidden in the file, so a
model from an untrusted source is a risk. Since version 2.6, torch.load
loads only tensors and plain data unless told otherwise. Shared models have largely
moved to safetensors, which cannot run code.
Python itself also uses .pth for unrelated path configuration files in
its site-packages folder.
Structure
Since PyTorch 1.6 the file is a ZIP archive whose entries are stored without compression, so tensors can be read in place. Everything sits in one top folder:
data.pkl: the saved object, pickled, with each tensor replaced by a reference to a storage recorddata/0,data/1and so on: the raw bytes of each storage, one entry per storageversion: the version of the serialisation formatbyteorderin newer files:littleorbig
Older files, from before 1.6, are a series of pickles one after another followed by
the storage bytes, with no ZIP wrapper. TorchScript models saved with
torch.jit.save are ZIP archives too, with the model’s code in a
code/ folder beside the data. The archive
and tensors page gives the entries and how tensors are stored.
Not described
PyTorch publishes no specification of its checkpoint format; the archive page follows
torch/serialization.py and the C++ inline container.
Known, not yet covered
- Reference: the mobile bytecode archive's contents
(
bytecode.pkl's tuple layout and the flatbuffer bytecode of version 9), and the pickledtorch.packagelayout; neither was read. The rebuild functions, the storage types, the TorchScript entries, the version numbers and the legacy tar format are now described. - Viewer: not re-audited in this pass.
Unknown
- Reference: which PyTorch release first wrote each version number:
versions.hgives the reasons for the numbers but no release names.
Also used for
- GGML model file – The model format of ggml and whisper.cpp from before GGUF.
Links
Software
- PyTorch – the machine learning framework that writes these files (Windows, macOS, Linux)
- Hugging Face Transformers – loads older models saved as
pytorch_model.bin(Python) - Netron – viewer that lists the tensors (Windows, macOS, Linux, web)
Developers
- PyTorch –
torch.saveandtorch.load, with LibTorch for C++ (Python, C++) - safetensors – for converting weights to the safetensors format (Python, Rust)
Reference
- Serialization semantics – PyTorch’s description of how tensors and models are saved