REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: resume AdamW, sampling and dropout exactly

Resuming weights alone is not resuming an experiment.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

No GPU, external model weights or API key is required. After downloading the topic and packages, this Lab runs offline.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Read lesson: Project: resume AdamW, sampling and dropout exactly →

Your task

Train CPU Sequential(Linear(2,4),Tanh,Dropout(.25),Linear(4,1)) with AdamW lr=.02 and weight_decay=.01. Each step draws randperm(N)[:min(3,N)] and minimizes mean squared error. Return checkpoint (model/optimizer deep copies, CPU rng clone, cumulative step, SHA256 of json.dumps([xs,ys],sort_keys=True,allow_nan=False).encode()), losses and sampled batches. On resume initialize objects, load model and copied optimizer state, then restore captured RNG before the next draw. Preserve caller RNG with fork_rng. Reject changed data, invalid steps or nonfinite/misaligned two-feature data. Zero steps capture state without updating.

Starter

import torch


def train_segment(xs, ys, steps, seed, checkpoint=None):
    return None
Inspect the worked answer
import copy
import hashlib
import json
import math
import torch
from torch import nn
from torch.nn import functional as F


def train_segment(xs, ys, steps, seed, checkpoint=None):
    if not xs or len(xs) != len(ys) or type(steps) is not int or steps < 0:
        raise ValueError('aligned data and nonnegative integer steps required')
    if any(len(row) != 2 or any(not math.isfinite(v) for v in row) for row in xs) or any(not math.isfinite(v) for v in ys):
        raise ValueError('finite two-feature regression data required')
    identity = hashlib.sha256(json.dumps([xs, ys], sort_keys=True, allow_nan=False).encode()).hexdigest()
    if checkpoint is not None and (checkpoint['data'] != identity or type(checkpoint['step']) is not int or checkpoint['step'] < 0):
        raise ValueError('checkpoint belongs to a different data stream')
    with torch.random.fork_rng(devices=[]):
        torch.manual_seed(seed)
        model = nn.Sequential(nn.Linear(2, 4), nn.Tanh(), nn.Dropout(.25), nn.Linear(4, 1))
        optimizer = torch.optim.AdamW(model.parameters(), lr=.02, weight_decay=.01)
        position = 0
        if checkpoint is not None:
            model.load_state_dict(checkpoint['model'])
            optimizer.load_state_dict(copy.deepcopy(checkpoint['optimizer']))
            torch.set_rng_state(checkpoint['rng'].clone())
            position = checkpoint['step']
        x = torch.tensor(xs, dtype=torch.float32)
        y = torch.tensor(ys, dtype=torch.float32)
        model.train()
        losses, batches = [], []
        for step in range(steps):
            indices = torch.randperm(len(xs))[:min(3, len(xs))]
            optimizer.zero_grad(set_to_none=True)
            loss = F.mse_loss(model(x[indices]).squeeze(-1), y[indices])
            loss.backward()
            optimizer.step()
            losses.append(float(loss.detach()))
            batches.append(indices.tolist())
        captured = copy.deepcopy({'model': model.state_dict(), 'optimizer': optimizer.state_dict(),
                                 'rng': torch.get_rng_state(), 'step': position + steps,
                                 'data': identity})
        return {'checkpoint': captured, 'losses': losses, 'batches': batches}

About this algorithm

How Project: resume AdamW, sampling and dropout exactly works

The idea

Weights are only part of a training run. AdamW keeps two running averages for every weight plus a step count, and the random generator decides which rows each batch samples and which units dropout switches off.

Resuming is exact only when everything that shapes the next step comes back: model state, optimizer state, generator state and the step counter, on the same data. Then a run that stops, saves and continues produces the same losses as one that never stopped. Restore the weights alone and Adam's averages restart from zero while the batches and dropout masks change, so the run quietly becomes a different experiment. train_segment also stores a SHA-256 of the data to refuse a checkpoint made from other data.

How it works

  1. Validate the data and hash it with SHA-256, so a checkpoint can be matched to the data it came from.
  2. Inside torch.random.fork_rng, seed and build the model and AdamW exactly as a fresh run would.
  3. If a checkpoint is given, load the model state, a copy of the optimizer state, and then the saved RNG state.
  4. Each step draws up to three row indices with torch.randperm, runs the model with dropout active and takes one AdamW step on mean squared error.
  5. Deep-copy the model and optimizer state and store them with the current RNG state, the cumulative step and the data hash.
  6. Return that checkpoint together with the losses and the sampled batches.

What it costs

Per step
O(B·P)
Checkpoint
about 3× the weights
Restore
O(P) copies

A checkpoint holds the weights plus AdamW's two moment tensors per weight and a small generator state, so saving or loading costs a few copies of the model.

Where it is used

  • PyTorch's own checkpoint tutorial saves model_state_dict and optimizer_state_dict together with the epoch and loss so training can continue.
  • Hugging Face Trainer checkpoints store optimizer, scheduler and RNG state files next to the weights for resume_from_checkpoint.
  • Amazon SageMaker managed spot training resumes interrupted jobs from checkpoints saved to S3.

Watch out for

  • Saving only the weights: on resume AdamW's moment estimates and step count restart from zero, so the next updates differ.
  • Restoring the RNG state before building the model: weight initialization then consumes random numbers and shifts every later batch and dropout mask.
  • Storing optimizer.state_dict() without a deep copy: it refers to live tensors that keep changing as training goes on.