Example

Find what changed in a model checkpoint

Hash a pinned checkpoint, digest its parameters, and separate eval mode from autograd mode before serving a single request.

A model file is an artefact; an executing model is a process. Between them sit three switches that are easy to conflate: the module’s training/eval mode, the requires_grad flag on its parameters, and PyTorch’s global autograd mode. A checkpoint can match its recorded hash and still be served by a process that is not ready, because model.eval() does not disable autograd.

This example inspects the artefact first, then asks what the process must be true of before inference. It uses the cached GPT-2 checkpoint, so the identity fields refer to one exact snapshot. The point is not GPT-2 itself; it is the habit of recording which bytes and which tensor values the claim belongs to.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch02/execution_modes.py manifest
python examples/ch02/execution_modes.py readiness

Python 3.11 or later with PyTorch, Transformers and a cached GPT-2 snapshot. The commands set no network requirement of their own, but a reader without the snapshot must download it first. Both are CPU-only and finish in a few seconds.

Implementation

The file hash covers the bytes on disk. The parameter digest covers names, shapes and raw tensor bytes in a fixed order, so it detects a one-value change even when the file-level metadata is unchanged. inference_readiness deliberately reports the switches separately instead of returning one optimistic boolean.

def file_manifest(directory: Path, names: Iterable[str]) -> List[dict]:
    """Size and SHA-256 for each named file in ``directory`` (symlinks followed)."""
    rows = []
    for name in names:
        path = directory / name
        rows.append({"file": name, "bytes": path.stat().st_size, "sha256": sha256_file(path)})
    return rows


def parameter_manifest(module) -> dict:
    """Names, shapes, dtypes and byte counts of every parameter tensor."""
    rows = []
    total_elements = 0
    total_bytes = 0
    for name, parameter in module.named_parameters():
        total_elements += parameter.numel()
        total_bytes += parameter.numel() * parameter.element_size()
        rows.append({"name": name, "shape": list(parameter.shape), "dtype": str(parameter.dtype)})
    return {
        "tensors": len(rows),
        "elements": total_elements,
        "bytes": total_bytes,
        "dtypes": sorted({row["dtype"] for row in rows}),
        "parameters": rows,
    }


def parameter_digest(module) -> str:
    """SHA-256 over parameter names, shapes and raw bytes in a fixed order."""
    digest = hashlib.sha256()
    for name, parameter in sorted(module.named_parameters(), key=lambda item: item[0]):
        digest.update(name.encode("utf-8"))
        digest.update(str(tuple(parameter.shape)).encode("utf-8"))
        digest.update(parameter.detach().cpu().contiguous().numpy().tobytes())
    return digest.hexdigest()


def inference_readiness(module) -> dict:
    """The three independent switches an inference entry point has to look at.

    ``training_mode``       - ``module.training`` (dropout and similar behaviour).
    ``trainable_tensors``   - parameters with ``requires_grad`` set (can accumulate gradients).
    ``autograd_enabled``    - the global grad mode at the point of the call.
    """
    import torch

    parameters = list(module.parameters())
    trainable = sum(1 for p in parameters if p.requires_grad)
    return {
        "training_mode": bool(module.training),
        "trainable_tensors": trainable,
        "total_tensors": len(parameters),
        "autograd_enabled": bool(torch.is_grad_enabled()),
        "ready": (not module.training) and (not torch.is_grad_enabled()),
    }

Expected outcome

Observed with the two commands above (both exit 0). Selected stable fields:

  "snapshot": "607a30d783dfa663caf39e06633721c8d4cfcd7e",
      "file": "model.safetensors",
      "bytes": 548105171,
      "sha256": "248dfc3911869ec493c76e65bf2fcf7f615828b0254c12b473182f0f81d3a707"
  "parameter_tensors": 148,
  "parameter_elements": 124439808,
  "parameter_bytes": 497759232,
  "parameter_dtypes": [
    "torch.float32"
  ],
  "parameter_digest_sha256": "95cb2531cd09fbf7de76055f9448d98fa44c04ad7787ea1e608709efc437a029"

Readiness reported the same 148 trainable tensors in every state. After model.eval() alone, training_mode was false, autograd_enabled was still true, and ready was false. Inside torch.inference_mode() it became autograd_enabled: false and ready: true. Eval mode changed dropout behaviour; it did not change autograd.

Mechanism and limitations

Documented: the chapter records that the safetensors file holds 160 tensors: 148 parameters plus twelve 1024x1024 causal-mask buffers, and that the file header is 14,291 bytes. parameter_manifest counts only named_parameters, so buffers are intentionally excluded from the parameter digest. The test file checks that the digest is stable, that a 1e-6 change to one bias changes it, that file hashing covers the bytes, that dropout diverges in train mode and not in eval mode, and that grad-enabled output can be trained through.

Observed: the manifest command exited 0 and printed the snapshot, file hash, parameter counts and digest above. The readiness command exited 0 and printed ready: false after eval, ready: true inside inference mode. The targeted tests tests.test_ch02_execution_modes and tests.test_ch02_reproducible ran as part of a 36-test batch with the Chapter 03-05 tests and reported OK.

Not shown: that the checkpoint is safe, licensed for a particular use, or numerically identical on another device; that a GPU exists; that the tokeniser matches the weights beyond the recorded snapshot; or that inference_mode makes a whole service correct. The counts are for GPT-2 small, not a general model. A file hash also does not prove that the process loaded the file it hashed.

Challenge this result

Copy the snapshot directory, change one byte in a copy of model.safetensors, and run the manifest against the copy. Predict which field changes: the file hash, the parameter digest, both, or neither. Then explain why a service that records only the file hash can still load different parameter values, and what the readiness check would need to include to catch that case.

Source and verification

Canonical source: examples/ch02/execution_modes.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch02_execution_modes.py and tests/test_ch02_reproducible.py . Chapter: From Training to Execution . The run above is a fresh local execution on Windows 11 with Python 3.13.15 and PyTorch 2.6.0+cu124, using the cached gpt2 snapshot named above.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.