REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: train, validate and export a nonlinear classifier

This project trains a nonlinear classifier with real PyTorch autograd and Adam.

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: train, validate and export a nonlinear classifier →

Your task

Rows contain unique disjoint id, finite two-feature x and integer binary y. Fit population means/stds on train only (constant scale=1), then train Linear(2,8), Tanh, Linear(8,2) with Adam lr=.04 for steps full-batch updates. Select a deep-copied model state by lowest validation cross entropy, first exact tie. Restore it and evaluate test. Return artifact with state/means/scales, predictions, initial_loss, training_loss, validation_loss, best_step, test_loss and validation history. Preserve caller CPU RNG using fork_rng. Reject invalid partitions and steps. Trace uses four updates; checks train longer.

Starter

import torch


def fit_mlp(train, validation, test, steps, seed):
    return None
Inspect the worked answer
import copy
import math
import torch
from torch import nn
from torch.nn import functional as F


def fit_mlp(train, validation, test, steps, seed):
    if any(not part for part in (train, validation, test)) or type(steps) is not int or steps < 1:
        raise ValueError('three nonempty partitions and a positive step budget required')
    rows = train + validation + test
    if len({row['id'] for row in rows}) != len(rows):
        raise ValueError('unique disjoint sample identities required')
    if any(len(row['x']) != 2 or any(not math.isfinite(x) for x in row['x']) or type(row['y']) is not int or row['y'] not in (0, 1) for row in rows):
        raise ValueError('finite two-feature binary observations required')
    with torch.random.fork_rng(devices=[]):
        torch.manual_seed(seed)
        x = torch.tensor([r['x'] for r in train], dtype=torch.float32)
        y = torch.tensor([r['y'] for r in train], dtype=torch.long)
        means = x.mean(dim=0)
        scales = x.std(dim=0, correction=0)
        scales = torch.where(scales == 0, torch.ones_like(scales), scales)
        x = (x - means) / scales
        vx = (torch.tensor([r['x'] for r in validation]) - means) / scales
        vy = torch.tensor([r['y'] for r in validation], dtype=torch.long)
        model = nn.Sequential(nn.Linear(2, 8), nn.Tanh(), nn.Linear(8, 2))
        optimizer = torch.optim.Adam(model.parameters(), lr=.04)
        initial = float(F.cross_entropy(model(x), y).detach())
        best, history = None, []
        for step in range(1, steps + 1):
            model.train()
            optimizer.zero_grad(set_to_none=True)
            loss = F.cross_entropy(model(x), y)
            loss.backward()
            optimizer.step()
            model.eval()
            with torch.no_grad():
                value = float(F.cross_entropy(model(vx), vy))
            history.append(value)
            if best is None or value < best[0]:
                best = (value, step, copy.deepcopy(model.state_dict()))
        model.load_state_dict(best[2])
        model.eval()
        with torch.no_grad():
            tx = (torch.tensor([r['x'] for r in test]) - means) / scales
            ty = torch.tensor([r['y'] for r in test], dtype=torch.long)
            logits = model(tx)
            test_loss = float(F.cross_entropy(logits, ty))
            training_loss = float(F.cross_entropy(model(x), y))
        artifact = {'state': {k: v.tolist() for k, v in model.state_dict().items()},
                    'means': means.tolist(), 'scales': scales.tolist()}
        return {'artifact': artifact, 'predictions': logits.argmax(dim=-1).tolist(),
                'initial_loss': initial, 'training_loss': training_loss,
                'validation_loss': best[0], 'best_step': best[1],
                'test_loss': test_loss, 'history': history}

About this algorithm

How Project: train, validate and export a nonlinear classifier works

The idea

This project is a whole supervised training loop in miniature. The model is Linear(2, 8), Tanh, Linear(8, 2): the tanh between the two layers is what lets it bend its decision boundary, which a single linear layer cannot do for XOR-style points.

The real lesson is which data may influence what. Standardization means and scales come from the training rows only. Adam fits the weights on training rows. Validation rows choose which step's weights to keep: the deep-copied state with the lowest validation cross entropy. Test rows are scored once at the end and decide nothing. Break any of these rules and the test loss stops being an honest estimate.

How it works

  1. Check for three non-empty partitions with unique ids, then seed inside torch.random.fork_rng so the caller's random state is preserved.
  2. Compute means and scales from the training rows only and standardize all three partitions with them.
  3. Build Linear(2, 8), Tanh, Linear(8, 2) and an Adam optimizer with learning rate 0.04.
  4. For each step, zero the gradients, compute full-batch cross entropy, call backward() and optimizer.step().
  5. After each step, measure validation loss and deep-copy the state when it is strictly lower than the best so far.
  6. Load the best state, score the test rows once, and return the artifact, predictions and losses.

What it costs

Per step
O(N·P)
Memory
O(P) best-state copy
Scales with
steps, rows, weights

Every step pushes all N training rows through the P weights and then scores validation, and remembering the best checkpoint costs one extra copy of the weights.

Where it is used

  • scikit-learn's MLPClassifier(early_stopping=True) sets aside validation data and stops training when the validation score stops improving.
  • Keras' EarlyStopping(restore_best_weights=True) rolls a model back to the epoch with the best monitored validation value.
  • scikit-learn's Pipeline fits StandardScaler on the training folds only during cross-validation, the same no-leakage rule as means and scales.

Watch out for

  • Computing means and scales over all rows: validation and test statistics leak into training and flatter the scores.
  • Saving model.state_dict() without copy.deepcopy: the saved dict points at live tensors, so later steps overwrite the best state.
  • Choosing the best step by test loss: the test set has then been used for selection and no longer measures generalization.