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))Review the design
Review attention masks, pooling denominator, maximum context and checkpoint selection separately. Padding invariance here covers appended padding, not arbitrary changes to valid token positions.
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.
The explanation opens here once every check passes.