REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: Resume real transformer training exactly

Interrupt LoRA mid-epoch, save AdamW and both RNGs, restore a fresh process state and match the uninterrupted trajectory.

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.

That explicit download includes the shared UCI sentiment dataset/tokenizer and 17.7 MB pretrained BERT weights. Its source stays local. After setup it trains and evaluates offline; no API key is needed.

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 →

Download complete project source →

Read lesson: Project: Resume real transformer training exactly →

Your task

Interrupt LoRA mid-epoch, save AdamW and both RNGs, restore a fresh process state and match the uninterrupted trajectory. Implement run_project(output, quick=False). Follow the reference report/artifact schema; the checks run quick=True with actual pretrained weights and real data. The full dataset is the default.

Starter

from pathlib import Path
import torch
import pythilo_finetune as ft


def run_project(output, quick=False):
    raise NotImplementedError("Implement the training, evidence and artifact contract in the task")
Inspect the worked answer
"""Exact CPU resume with AdamW moments, dropout RNG, sampler RNG, order and cursor."""
from pathlib import Path
import random
import torch
from torch.nn import functional as F
import pythilo_finetune as ft


def run_project(output, quick=False):
    torch.set_num_threads(2)
    output = Path(output); output.mkdir(parents=True, exist_ok=True)
    data = ft.dataset(quick=quick)
    length, batch_size, epochs = (24, 8, 2) if quick else (48, 16, 2)
    train, valid, test = [ft.encode(data[key], length) for key in ('train', 'valid', 'test')]
    total_steps = epochs * ((len(data['train']) + batch_size - 1) // batch_size)

    def initialize():
        model = ft.pretrained('lora')
        optimizer = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=.001)
        rng = random.Random(17)
        torch.manual_seed(317)
        return model, optimizer, rng

    def advance(model, optimizer, rng, state, steps):
        epoch, cursor, order = state
        losses = []
        model.train()
        for _ in range(steps):
            if cursor >= len(order):
                epoch += 1; cursor = 0
                order = list(range(len(data['train']))); rng.shuffle(order)
            ids, mask, labels = ft.minibatch(train, order[cursor:cursor + batch_size])
            optimizer.zero_grad(set_to_none=True)
            loss = F.cross_entropy(model(ids, mask), labels)
            if not torch.isfinite(loss): raise ValueError('Nonfinite loss')
            loss.backward()
            torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad], 1., error_if_nonfinite=True)
            optimizer.step(); cursor += len(labels); losses.append(loss.item())
        return (epoch, cursor, order), losses

    continuous, optimizer, rng = initialize()
    _, expected_losses = advance(continuous, optimizer, rng, (0, 0, []), total_steps)
    interrupted, interrupted_optimizer, interrupted_rng = initialize()
    split = max(1, total_steps // 2 - 1)  # Deliberately not restricted to an epoch boundary.
    state, first_losses = advance(interrupted, interrupted_optimizer, interrupted_rng, (0, 0, []), split)
    ft.save_checkpoint(output / 'resume.pt', interrupted, interrupted_optimizer, *state, interrupted_rng)
    # Construct a fresh model and optimizer to simulate process loss.
    resumed, resumed_optimizer, resumed_rng = initialize()
    checkpoint = ft.load_checkpoint(output / 'resume.pt', resumed, resumed_optimizer, resumed_rng)
    position = (checkpoint['epoch'], checkpoint['cursor'], checkpoint['order'])
    _, remaining_losses = advance(resumed, resumed_optimizer, resumed_rng, position, total_steps - split)
    difference = max((a - b).abs().max().item() for a, b in zip(continuous.state_dict().values(), resumed.state_dict().values()))
    if difference != 0 or expected_losses != first_losses + remaining_losses:
        raise AssertionError('Resume did not reproduce the uninterrupted CPU trajectory')
    report = ft.provenance(data, resumed, resumed_optimizer)
    report.update(max_parameter_difference=difference, identical_losses=True, steps=total_steps,
                  checkpoint_step=split, sequence_length=length, validation=ft.evaluate(resumed, valid), test=ft.evaluate(resumed, test))
    ft.export_adapter(resumed, output / 'adapter.pt')
    ft.save_json(output / 'report.json', report)
    return report

About this algorithm

How Project: Resume real transformer training exactly works

The idea

Resuming training exactly means the restored run produces the same numbers as a run that was never interrupted. Model weights alone are not enough. AdamW keeps running averages of gradients and squared gradients, dropout draws from PyTorch's random generator, and the sampler's generator and position decide which rows come next. Lose any of them and the resumed run drifts away from the original.

This project trains LoRA adapters on BERT-Tiny twice: once straight through, and once stopped in the middle of an epoch. The checkpoint holds the model, the optimizer, both generator states, the shuffled order, the cursor into it and the epoch. A freshly built model resumes from it and must match the uninterrupted run exactly: identical losses and a maximum parameter difference of zero.

How it works

  1. Write initialize() so every run starts from the same pretrained model, optimizer, sampler seed and PyTorch seed.
  2. Write advance() to run a number of steps from a position (epoch, cursor, order), reshuffling order whenever the cursor reaches its end.
  3. Train one model for all total_steps and keep its losses as the reference.
  4. Train a second model for split steps, stopping inside an epoch, and call ft.save_checkpoint with the model, optimizer, position and sampler generator.
  5. Build a third, fresh model and optimizer, restore everything with ft.load_checkpoint, and run the remaining steps.
  6. Compare every tensor and the joined loss lists with the reference, and raise if anything differs.

What it costs

Training
2 × total steps
Checkpoint
weights + AdamW + RNGs
Must match
difference exactly 0

The proof costs twice the training, because the same schedule runs once uninterrupted and once in two parts; the checkpoint adds optimizer moments and two generator states to the weights.

Where it is used

  • Hugging Face Accelerate's save_state writes models, optimizers and random generator states so that load_state can continue a run.
  • PyTorch Lightning checkpoints include optimizer states, the epoch and the global step, and trainer.fit(..., ckpt_path=...) restores them.
  • TensorFlow's tf.train.Checkpoint can track the optimizer and a dataset iterator alongside the model, so both are restored with the weights.

Watch out for

  • Saving only the model weights: AdamW restarts with empty moment estimates and the next updates differ from the original run.
  • Restoring the sampler seed but not the saved order and cursor, so the resumed epoch replays or skips batches.
  • Forgetting the PyTorch generator state, which changes the dropout masks after the restart.