What Data Does PyTorch state_dict Serialize?

In PyTorch, saving model checkpoints typically relies on the state_dict object. This article explores the precise data serialized when saving a PyTorch model's state_dict, explaining the exact components included—specifically learnable parameters and persistent buffers—as well as the critical elements omitted during serialization that developers must handle separately.

The Structure of a state_dict

A PyTorch state_dict is a standard Python dictionary (collections.OrderedDict) that maps each layer or submodule to its corresponding parameter and buffer tensors. Only layers with internal, persistent states are represented in this dictionary.

When you serialize a model's state_dict using torch.save(model.state_dict(), PATH), the file stores:

1. Learnable Parameters

The primary data stored in a state_dict consists of all objects instantiated as torch.nn.Parameter within the model and its child submodules. These parameters update during backpropagation:

Each tensor is saved along with its current values, data type (dtype), and shape, maintaining the state of the model at the exact moment of saving.

2. Registered Persistent Buffers

Not all stateful values are updated via gradient descent. Models frequently require non-trainable tensors that persist across training and inference iterations. Any tensor registered using model.register_buffer() is serialized into the state_dict by default (unless registered with persistent=False).

Common examples of registered buffers include:

What is NOT Serialized

A common misconception is that a state_dict contains everything required to re-instantiate a model from scratch. The state_dict excludes:

Standard Complete Checkpoint Practice

Because model.state_dict() captures only weights and persistent buffers, standard PyTorch practice packages the model state alongside operational metadata when saving checkpoints for later resumption:

checkpoint = {
    'epoch': epoch,
    'model_state_dict': model.state_dict(),
    'optimizer_state_dict': optimizer.state_dict(),
    'scheduler_state_dict': scheduler.state_dict(),
    'loss': loss,
}
torch.save(checkpoint, 'checkpoint.pth')

This comprehensive dictionary ensures that the model parameters, buffer states, optimizer parameters, and training progress markers are fully preserved in a single serialized file.