Skip to content

P8 · Model lifecycle and pruning

Follow one tiny model from a live object in RAM to saved weights, a resumable checkpoint, a reusable encoder and a pruned state. Every comparison runs offline on CPU.

P8 · Model lifecycle and pruning

You will practice: Restore weights, resume one update, reuse an encoder and inspect pruning state.

Read first: 6.1 · Memory, checkpoints and tracking · 6.2 · Compression, export and deployment

Data and setup: Six generated feature rows and a tiny model; offline CPU, no downloads.

What this experiment answers

Constructing TinyClassifier() allocates parameter tensors and defines how the encoder and head connect. Training changes those tensors in memory. Saving a state_dict writes tensor values and names to disk; restoring still needs compatible architecture code. The example performs one synthetic training step so the checkpoint contains actual optimizer momentum rather than an empty optimizer state.

The encoder maps four input features to eight hidden features. The head maps those eight features to two logits. Six synthetic rows keep the mechanism easy to inspect; no accuracy, compression speedup or real-world usefulness is claimed.

Architecture4 → 8 → 2encoder plus classifier head
Live tensors58 float32 valuestraining changes RAM state
Savestate_dict + contractdisk artifact persists
ReconstructTinyClassifier(**config)compatible code allocates tensors
Restoreload_state_dict(...)equal evaluation logits

Conceptual lifecycle with this example's exact tensor dimensions; not measured performance.

CPU means central processing unit; RAM is the process’s working memory. The encoder weight [8,4] maps four input features to eight outputs; its dense slots survive pruning. Common trap: weights_only=True restricts deserialization rather than selecting only the model entry. Inspect equality and file-byte fields separately from quality or speed claims.

Choose what to save

Choose the artifact for the next task

Inference artifact

Save: model parameters + persistent buffers, architecture/configuration and input contract.

Restore: construct compatible model → load state → eval + no_grad → predict.

Training checkpoint

Save: model + optimizer + run state, and the input contract. Include scheduler/scaler/random/data state when needed.

Restore: construct model and optimizer → restore their state → resume training deliberately.

Encoder only

Save: encoder state, configuration and feature/input contract.

Restore: construct encoder → restore it → attach a separate new head → train or adapt that head.

State dictionaries do not contain the forward implementation. Optimizer moments are not restored by model weights alone.

Artifact Contents What it enables
weights.pt Full model state dictionary Reconstruct compatible architecture and run inference.
checkpoint.pt Model and optimizer states, step count, configuration, labels and input contract Restore this demonstration's next training update.
encoder.pt Only the encoder state Reuse the representation with a separately chosen head.
pruned-folded.pt Full model state after folding a pruning mask Restore zeroed dense weights without pruning hooks.
report.json Equality checks, tensor shapes, zero counts and measured file sizes Inspect evidence independently of any model-quality claim.

An application checkpoint may also need scheduler/scaler states, random-number generator (RNG) state, dataset order or sampler position and library versions. This demonstration repeats the same CPU batch and optimizer configuration; it does not promise exact resumption of arbitrary training runs.

Code key: the short snippets are excerpts from the maintained script, not standalone programs. The complete source below supplies imports, classes, data and helper functions; run that script from the repository root.

checkpoint = torch.load(path, map_location="cpu", weights_only=True)
model = TinyClassifier(**checkpoint["config"])
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
with torch.inference_mode():
    logits = model(inputs)

map_location="cpu" maps loaded tensor storage to CPU. eval() selects evaluation behavior for layers such as Dropout and BatchNorm; inference_mode() disables autograd bookkeeping. These have different jobs.

weights_only=True does not discard metadata or optimizer entries. It restricts which objects the unpickler may reconstruct. Our tensor dictionaries and basic metadata still load; selecting checkpoint["model_state_dict"] is a separate operation. A weights file also does not contain Python architecture code. Load artifacts from trusted sources; restricted loading is not a guarantee that arbitrary files are harmless. PyTorch serialization notes.

A snapshot must stop changing

live_state = model.state_dict()
snapshot = deepcopy(live_state)

live_state is a new mapping whose tensors normally reference the model's storage. A later in-place training update can therefore change its values. deepcopy gives the chosen state its own tensor storage. The script deliberately changes the head, checks that the live mapping follows the update while the snapshot stays fixed, and then restores the snapshot. During real training, take this snapshot when validation improves; this example does not select a “best” model from validation data. Saving and loading tutorial.

Reuse only the encoder

torch.save(model.encoder.state_dict(), encoder_path)
fresh_encoder = TinyClassifier(**CONFIG).encoder
fresh_encoder.load_state_dict(
    torch.load(encoder_path, map_location="cpu", weights_only=True)
)

The submodule dictionary contains 0.weight and 0.bias; the full model uses encoder.0.weight and encoder.0.bias. Both describe the same layer in different namespaces. Loading the encoder into a compatible encoder produces identical features. The classifier head is separate and must be trained or loaded for its intended task. strict=False can tolerate missing/unexpected keys but does not make incompatible shapes match; inspect returned keys when intentionally loading partial full-model state.

Pruning zeros is different from shrinking a tensor

The encoder weight has shape [8, 4], containing 32 float32 values. l1_unstructured(..., amount=0.5) masks the 16 smallest absolute values. Before removal, the state contains weight_orig plus weight_mask. prune.remove folds their product into a regular weight, removes the mask/hook machinery and preserves the effective forward computation.

Stage Encoder shape Zero values State representation
Before pruning [8, 4] Seed-dependent Dense weight
Mask active [8, 4] 16 in this seeded toy weight_orig + weight_mask
Mask folded [8, 4] 16 Dense weight

The folded model still has 58 float32 values: 232 bytes of dense tensor payload. Ordinary dense storage keeps slots for zeros. Folding does not make the weight tensor smaller, and this script measures no inference acceleration. Smaller architectures, quantized representation or sparse kernels address different deployment constraints. Official pruning tutorial.

Run and read the evidence

python examples/model_lifecycle.py
python examples/model_lifecycle.py --output artifacts/my-lifecycle-run
python tests/validate_model_lifecycle.py

No datasets, pretrained weights, GPU or network connection are needed. The output directory defaults to ignored artifacts/model-lifecycle/. The tests use temporary directories and leave maintained teaching assets untouched.

Inspect these report fields:

  • restored_max_logit_difference and weights_only_file_max_logit_difference: zero means the checkpoint and weights paths reproduced the saved evaluation outputs.
  • encoder_max_feature_difference: zero means the independently restored submodule reproduced its hidden features.
  • resumed_next_step_max_parameter_difference: zero means restored momentum and model state reproduced this example's next update.
  • deepcopy_snapshot_unchanged and alias_followed_update: both should be true, exposing the difference between a reference and an independent snapshot.
  • pruning: compare unchanged shapes, zero count, state keys and equal outputs before/after mask folding.
  • sizes: compare summed dense tensor payload with actual serialized file bytes. Their difference includes archive/container metadata and overhead. File bytes depend on serialization and are not a RAM estimate or latency benchmark.

The resumed update changes the live model later in the script; weights.pt remains the saved state after the first step. The pruning branch starts from that saved state, so these comparisons do not accidentally mix different training moments.

Try changing: replace the hidden width 8 with 4 and rerun. Check the parameter count and dense payload. Then compare that actual architecture reduction with pruning half the original weights. For a real deployment, measure quality and latency on representative inputs and the intended hardware before choosing either approach.

Continue with model memory, state and restoration, then optimization and serving.

Complete source

Open the maintained runnable script
"""Original offline CPU experiment: trained state, checkpoints, parts and pruning.

This demonstrates mechanisms on synthetic data, not useful classifier quality.
Only checkpoints created by this example are loaded.
"""
from __future__ import annotations

import argparse
from copy import deepcopy
import json
from pathlib import Path

import torch
from torch import nn
from torch.nn.utils import prune


SEED = 71
CONFIG = {"input_features": 4, "hidden_features": 8, "classes": 2}


class TinyClassifier(nn.Module):
    """Architecture is code; a state_dict supplies parameter/buffer values."""

    def __init__(self, input_features=4, hidden_features=8, classes=2):
        super().__init__()
        self.encoder = nn.Sequential(nn.Linear(input_features, hidden_features), nn.ReLU())
        self.head = nn.Linear(hidden_features, classes)

    def forward(self, inputs):
        return self.head(self.encoder(inputs))


def synthetic_batch():
    generator = torch.Generator().manual_seed(SEED + 1)
    inputs = torch.randn(6, CONFIG["input_features"], generator=generator)
    labels = torch.tensor([0, 1, 0, 1, 1, 0], dtype=torch.long)
    return inputs, labels


def train_step(model, optimizer, inputs, labels):
    model.train()
    optimizer.zero_grad(set_to_none=True)
    loss = nn.functional.cross_entropy(model(inputs), labels)
    loss.backward()
    optimizer.step()
    return float(loss.detach())


def tensor_payload_bytes(value):
    """Sum dense tensor leaf payloads; exclude archive/container overhead.

    This is not process RAM usage or a general storage-deduplicating estimator.
    Our tiny state contains separate, dense tensors with no tied storage.
    """
    if isinstance(value, torch.Tensor):
        return value.numel() * value.element_size()
    if isinstance(value, dict):
        return sum(tensor_payload_bytes(item) for item in value.values())
    if isinstance(value, (list, tuple)):
        return sum(tensor_payload_bytes(item) for item in value)
    return 0


def output_logits(model, inputs):
    model.eval()
    with torch.inference_mode():
        return model(inputs).clone()


def run(output):
    output = Path(output)
    output.mkdir(parents=True, exist_ok=True)
    torch.manual_seed(SEED)
    model = TinyClassifier(**CONFIG).cpu()
    optimizer = torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9)
    inputs, labels = synthetic_batch()
    train_step(model, optimizer, inputs, labels)
    expected_logits = output_logits(model, inputs)

    # A state_dict is a mapping, but its tensors normally share model storage.
    live_state = model.state_dict()
    snapshot = deepcopy(live_state)
    original_head = snapshot["head.weight"].clone()
    with torch.no_grad():
        model.head.weight.add_(1.0)  # stand-in for later training updates
    alias_followed_update = torch.equal(live_state["head.weight"], model.head.weight)
    snapshot_isolated = torch.equal(snapshot["head.weight"], original_head)
    model.load_state_dict(snapshot)  # restore the chosen state before saving

    weights_path = output / "weights.pt"
    checkpoint_path = output / "checkpoint.pt"
    encoder_path = output / "encoder.pt"
    torch.save(model.state_dict(), weights_path)
    checkpoint = {
        "model_state_dict": snapshot,
        "optimizer_state_dict": deepcopy(optimizer.state_dict()),
        "completed_steps": 1,
        "config": CONFIG,
        "labels": ["class-zero", "class-one"],
        "input_contract": "six float32 rows, four synthetic features per row",
        "seed": SEED,
    }
    torch.save(checkpoint, checkpoint_path)
    torch.save(model.encoder.state_dict(), encoder_path)

    # weights_only restricts unpickling; it does not select dictionary fields.
    loaded_checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
    restored = TinyClassifier(**loaded_checkpoint["config"]).cpu()
    restored.load_state_dict(loaded_checkpoint["model_state_dict"])
    restored_logits = output_logits(restored, inputs)
    weights_restored = TinyClassifier(**CONFIG).cpu()
    weights_restored.load_state_dict(torch.load(weights_path, map_location="cpu", weights_only=True))

    # The submodule's keys are local: "0.weight", not "encoder.0.weight".
    fresh_encoder = TinyClassifier(**CONFIG).encoder.cpu()
    encoder_state = torch.load(encoder_path, map_location="cpu", weights_only=True)
    fresh_encoder.load_state_dict(encoder_state)
    with torch.inference_mode():
        encoder_delta = float((model.encoder(inputs) - fresh_encoder(inputs)).abs().max())

    # Same optimizer class/config + its state make the next update reproducible.
    resumed_optimizer = torch.optim.SGD(restored.parameters(), lr=0.05, momentum=0.9)
    resumed_optimizer.load_state_dict(loaded_checkpoint["optimizer_state_dict"])
    train_step(model, optimizer, inputs, labels)
    train_step(restored, resumed_optimizer, inputs, labels)
    next_step_delta = max(float((value - restored.state_dict()[key]).abs().max())
                          for key, value in model.state_dict().items())

    # Separate branch: demonstrate zeros without claiming smaller dense shapes.
    pruned = deepcopy(weights_restored)
    layer = pruned.encoder[0]
    shape_before = list(layer.weight.shape)
    prune.l1_unstructured(layer, name="weight", amount=0.5)
    mask_state_keys = list(pruned.state_dict())
    effective_weight = layer.weight.detach().clone()
    masked_logits = output_logits(pruned, inputs)
    prune.remove(layer, "weight")
    folded_logits = output_logits(pruned, inputs)
    folded_path = output / "pruned-folded.pt"
    torch.save(pruned.state_dict(), folded_path)

    sizes = {}
    for name, path, state in [("weights", weights_path, snapshot),
                              ("checkpoint", checkpoint_path, checkpoint),
                              ("encoder", encoder_path, encoder_state),
                              ("pruned_folded", folded_path, pruned.state_dict())]:
        payload = tensor_payload_bytes(state)
        file_bytes = path.stat().st_size
        sizes[name] = {"tensor_payload_bytes": payload, "actual_file_bytes": file_bytes,
                       "file_minus_tensor_payload_bytes": file_bytes - payload}

    report = {
        "evidence": "seeded synthetic CPU mechanism check; no quality or speed benchmark",
        "torch_version": str(torch.__version__), "seed": SEED, "device": "cpu",
        "config": CONFIG,
        "alias_followed_update": alias_followed_update,
        "deepcopy_snapshot_unchanged": snapshot_isolated,
        "restored_max_logit_difference": float((expected_logits - restored_logits).abs().max()),
        "weights_only_file_max_logit_difference": float((expected_logits - output_logits(weights_restored, inputs)).abs().max()),
        "encoder_max_feature_difference": encoder_delta,
        "resumed_next_step_max_parameter_difference": next_step_delta,
        "weights_only_load_kept_checkpoint_metadata": loaded_checkpoint["completed_steps"] == 1,
        "pruning": {"shape_before": shape_before, "shape_after": list(layer.weight.shape),
                    "zero_count": int((layer.weight == 0).sum()), "elements": layer.weight.numel(),
                    "keys_with_mask": mask_state_keys, "keys_after_remove": list(pruned.state_dict()),
                    "effective_weights_preserved": torch.equal(effective_weight, layer.weight),
                    "remove_max_logit_difference": float((masked_logits - folded_logits).abs().max())},
        "sizes": sizes,
        "size_note": "Dense tensor payload excludes serialization metadata and archive overhead; file bytes are measured, not RAM or inference latency.",
    }
    (output / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path("artifacts/model-lifecycle"))
    args = parser.parse_args()
    report = run(args.output)
    print(json.dumps(report, indent=2))
    print(f"Artifacts written to {args.output}")


if __name__ == "__main__":
    main()

Inspect after running: Inspect equality checks, shapes, zero counts and actual file bytes in report.json; the script does not benchmark speed.

Connect the result: 6.1 · Memory, checkpoints and tracking · 6.2 · Compression, export and deployment. Choose another project.