PythiloLesson 9 of 9 · progress kept in this browser

Practice in Lab: Project: train a padding-safe transformer classifier →

Project: train a padding-safe transformer classifier

A sequence classifier must distinguish real tokens from batching artifacts. This project trains an actual attention encoder over variable-length sequences, masks padding keys and pools only valid query positions. Validation selects an owned checkpoint; test labels cannot alter it. The saved artifact is reloaded on differently padded inputs to verify prediction stability. This is a small CPU model with learned absolute positions and a synthetic binary vocabulary task. It is not a pretrained encoder, and its local checks do not establish generalization on real text.

import torch
ids = torch.tensor([[1, 2, 0]])
valid = ids != 0
print(valid.sum(-1))
This example uses torch. Run it in the Pythilo app, where these features are available.
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.

This lesson uses torch, which Python in this browser does not include. Read it here, and run and check it in the Pythilo app on iPhone or iPad.

All lessons