Model State Dictionaries and PyTorch Tensor Serialization
Agent-Assisted Exploration
Prerequisites
Completion of Day 54 Transformer assessment and PyTorch Module fundamentals.
Learning Objective
Understand the exact data structures inside model.state_dict(), how parameters and buffers are distinguished, and how CPU/CUDA mapping works during torch.save/torch.load.
Instructions
Study source: within this activity's existing reading/practice time, use CS336 Assignment 1: Basics (Spring 2025 tagged release), tests/test_serialization.py: test_checkpointing; model, optimizer and iteration state, then explain one connection to the local task in your own words. Keep the local exercise and acceptance checks; use its original explanation if the external source is unavailable. 1. Inspect model.state_dict(). Notice keys are strings corresponding to submodule hierarchies (e.g., 'blocks.0.attn.c_attn.weight').
2. Note that torch.save uses Python pickle under the hood, storing tensor metadata and storage pointers.
3. Compare saving the entire model object vs saving state_dict(). Recognize why official PyTorch guidelines mandate state_dict for code decoupling and architecture stability.
4. Observe map_location='cpu' to prevent OOM errors when loading a GPU-trained checkpoint onto a CPU or a different GPU index.
Practice & Prediction Log
Instantiate a tiny 2-layer GPT model. Save its state_dict to 'ckpt_model.pt'. Load it back into a freshly initialized model using load_state_dict() with map_location='cpu'. Verify with torch.allclose() that all weights match to machine precision.
Check model.state_dict().keys() before saving. Use model.load_state_dict(torch.load('ckpt_model.pt', map_location='cpu')).
import torch
from model import GPT, GPTConfig
cfg = GPTConfig(vocab_size=256, block_size=64, n_layer=2, n_head=2, n_embd=64)
m1 = GPT(cfg)
torch.save(m1.state_dict(), 'ckpt_model.pt')
m2 = GPT(cfg)
m2.load_state_dict(torch.load('ckpt_model.pt', map_location='cpu'))
for k in m1.state_dict():
assert torch.equal(m1.state_dict()[k], m2.state_dict()[k])
Successfully serialize and reload model weights with 100% parameter equality across instances.
Authoritative Source Resources & Provenance
CS336 Assignment 1: Basics (Spring 2025 tagged release)
Relevant Section / Range: tests/test_serialization.py: test_checkpointing; model, optimizer and iteration state
Verified Version & Date: spring2025 tag; README, tests and MIT LICENSE checked 2026-11-01
Lead assignment-driven source for pretraining component practice and tests. nanoGPT remains a compact historical code-reading companion, not the current recommended training curriculum.
Fluent Python, PyTorch, and linear algebra
Local self-contained pretraining scripts run on standard local CPUs or budget GPUs without Stanford cluster dependency.
Compared Candidate Sources & Selection Analysis (2)
Simpler code layout, useful complementary reference for minimal PyTorch Transformer.
High-level API focus rather than building from raw tensor fundamentals.
PyTorch Tutorial: Saving and Loading Models
Relevant Section / Range: What is a state_dict?
Verified Version & Date: PyTorch 2.x Documentation (Verified: 2026-10-30)
Official documentation detailing state_dict serialization, optimizer state saving, and safe loading patterns.
Python, PyTorch tensors and nn.Module basics.
All checkpoint serialization semantics, dictionary schema keys, and safe recovery steps are self-contained in lesson code.
Compared Candidate Sources & Selection Analysis (2)
TensorFlow trackable checkpoint architecture; PyTorch's explicit dictionary is our target implementation standard.
Safetensors provides safe zero-copy tensor storage without pickle, compared directly when discussing pickle execution risks.
nanoGPT: train.py pretraining loop
Relevant Section / Range: train.py: checkpoint dict {'model', 'optimizer', 'model_args', 'iter_num', 'best_val_loss', 'config'} written with torch.save to out_dir/ckpt.pt; the init_from == 'resume' branch reloads it
Verified Version & Date: Git master commit 71c3905 (Verified: 2026-10-30)
Compact historical code reference for the named implementation functions; CS336 spring2025 provides the lead component exercises. Do not infer top-p, atomic persistence or cloud budget enforcement from nanoGPT.
Transformer architecture from Days 46-48 and training loop from Days 49-51.
Complete checkpoint saving patterns and resuming loops are directly implemented in lesson exercises.
Compared Candidate Sources & Selection Analysis (2)
High-complexity multi-GPU distributed model-parallel checkpointing; nanoGPT provides accessible single-GPU clarity.
High-level framework callback abstraction; nanoGPT keeps explicit control over state dict dictionaries.