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 NoneInspect 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}