REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: train a padding-safe transformer classifier

A sequence classifier must distinguish real tokens from batching artifacts.

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 a padding-safe transformer classifier →

Your task

Use rows with disjoint id, tokens (0=PAD, at least one non-PAD, max length 32) and integer binary y. SequenceClassifier has width-8 token/position embeddings, one-head qkv Linear(8,24), scaled bidirectional attention excluding PAD keys, Linear(8,8) projection and residual LayerNorm, valid-token mean pooling, Linear(8,2) head. Train AdamW lr=.03 weight_decay=.01 with gradient cap 1. Choose and restore a deep-copied minimum validation-loss state (first tie), then evaluate test. Return artifact(vocab/state), initial_loss, training_loss, validation_loss, best_step, test_loss, predictions, history. Provide detached sequence_logits(artifact,sequences). Preserve caller RNG.

Starter

import torch


def train_sequence_classifier(train, validation, test, vocab, 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


class SequenceClassifier(nn.Module):
    def __init__(self, vocab):
        super().__init__()
        self.token = nn.Embedding(vocab, 8, padding_idx=0)
        self.position = nn.Embedding(32, 8)
        self.qkv = nn.Linear(8, 24)
        self.projection = nn.Linear(8, 8)
        self.norm = nn.LayerNorm(8)
        self.head = nn.Linear(8, 2)

    def forward(self, tokens):
        valid = tokens != 0
        x = self.token(tokens) + self.position(torch.arange(tokens.shape[1], device=tokens.device))
        q, k, v = self.qkv(x).chunk(3, dim=-1)
        scores = q @ k.transpose(-2, -1) / math.sqrt(8)
        weights = torch.softmax(scores.masked_fill(~valid[:, None, :], float('-inf')), dim=-1)
        hidden = self.norm(x + self.projection(weights @ v))
        pooled = (hidden * valid[:, :, None]).sum(dim=1) / valid.sum(dim=1, keepdim=True)
        return self.head(pooled)


def _encode(sequences, vocab):
    if type(vocab) is not int or vocab < 3 or not sequences:
        raise ValueError('a vocabulary and nonempty sequences required')
    if any(not row or len(row) > 32 or any(type(t) is not int or not 0 <= t < vocab for t in row) or not any(row) for row in sequences):
        raise ValueError('in-vocabulary rows need a non-padding token and length at most 32')
    length = max(len(row) for row in sequences)
    return torch.tensor([row + [0] * (length - len(row)) for row in sequences], dtype=torch.long)


def sequence_logits(artifact, sequences):
    encoded = _encode(sequences, artifact['vocab'])
    with torch.random.fork_rng(devices=[]):
        model = SequenceClassifier(artifact['vocab'])
        model.load_state_dict({k: torch.tensor(v, dtype=torch.float32) for k, v in artifact['state'].items()})
        model.eval()
        with torch.no_grad():
            return model(encoded)


def train_sequence_classifier(train, validation, test, vocab, steps, seed):
    if any(not part for part in (train, validation, test)) or type(steps) is not int or steps < 1:
        raise ValueError('nonempty partitions and positive training steps required')
    rows = train + validation + test
    if len({r['id'] for r in rows}) != len(rows) or any(type(r['y']) is not int or r['y'] not in (0, 1) for r in rows):
        raise ValueError('disjoint sample identities and binary labels required')
    encoded = [_encode([r['tokens'] for r in part], vocab) for part in (train, validation, test)]
    labels = [torch.tensor([r['y'] for r in part], dtype=torch.long) for part in (train, validation, test)]
    with torch.random.fork_rng(devices=[]):
        torch.manual_seed(seed)
        model = SequenceClassifier(vocab)
        optimizer = torch.optim.AdamW(model.parameters(), lr=.03, weight_decay=.01)
        initial = float(F.cross_entropy(model(encoded[0]), labels[0]).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(encoded[0]), labels[0])
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0, error_if_nonfinite=True)
            optimizer.step()
            model.eval()
            with torch.no_grad():
                value = float(F.cross_entropy(model(encoded[1]), labels[1]))
            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():
            logits = model(encoded[2])
            train_loss = float(F.cross_entropy(model(encoded[0]), labels[0]))
            test_loss = float(F.cross_entropy(logits, labels[2]))
        artifact = {'vocab': vocab, 'state': {k: v.tolist() for k, v in model.state_dict().items()}}
        return {'artifact': artifact, 'initial_loss': initial, 'training_loss': train_loss,
                'test_loss': test_loss, 'validation_loss': best[0], 'best_step': best[1],
                'predictions': logits.argmax(dim=-1).tolist(), 'history': history}

About this algorithm

How Project: train a padding-safe transformer classifier works

The idea

Sequences in a batch have different lengths, so shorter ones are filled with a PAD token to make a rectangle. Padding is an artefact of batching, and a correct model gives the same answer for a sequence however much padding follows it.

SequenceClassifier protects two places. In attention, scores toward PAD keys are set to negative infinity before the softmax, so no real token reads from padding. In pooling, hidden states are multiplied by the valid mask and divided by the count of real tokens, so padding does not dilute the mean. Attention is bidirectional here, since a classifier may read the whole sequence. Training keeps a deep copy of the weights with the lowest validation loss and touches the test set once, at the end.

How it works

  1. Check that ids are unique across the three splits and labels are 0 or 1, then right-pad each split with 0 to its longest row.
  2. Embed tokens and positions, compute one-head attention, and mask every PAD key with negative infinity before the softmax.
  3. Add the projected attention output to the input, apply LayerNorm, average only the valid positions, and map the result to two logits with head.
  4. Train with AdamW and a gradient norm cap of 1, appending the validation loss after every step to history.
  5. Keep a deep copy of the state whenever validation loss is strictly lower than the best so far.
  6. Restore that state, then compute training loss, test loss and test predictions, and export the weights as lists.

What it costs

Per step
train + validation pass
Attention
O(T²) per sequence
Best state
one deep copy kept

Every update is followed by a validation forward pass, and each improvement stores a full copy of the small model's weights.

Where it is used

  • Hugging Face tokenizers return an attention_mask with 1 for real tokens and 0 for padding, which BERT uses to hide padded keys.
  • PyTorch's nn.MultiheadAttention takes a key_padding_mask for the same purpose.
  • Sentence-Transformers mean pooling multiplies token embeddings by the attention mask and divides by the number of real tokens.

Watch out for

  • Averaging over the padded length with hidden.mean(dim=1), so the same sentence gets a different vector in a longer batch.
  • Masking the query axis instead of the key axis; the mask must be valid[:, None, :] so that it hides PAD columns.
  • Selecting the best step by test loss. The test set is evaluated once, after the validation-chosen state is restored.