Before you start
Build a small text classifier that gives the same answer however much padding a sentence carries.
Sentences have different lengths, so a batch is a padded (B, T) tensor of
token ids. Id 0 is the padding token. Write MeanPoolClassifier, an
nn.Module that:
nn.Embedding(vocab_size, dim, padding_idx=0), stored as self.embedding,nn.Linear(dim, n_classes), stored
as self.head.mask = tokens != 0 # (B, T)
pooled = sum of embeddings where mask / number of real tokens
logits = head(pooled) # (B, n_classes)
Then write train_text_classifier, which trains a new model on the data it
gets and returns it in eval mode.
class MeanPoolClassifier(torch.nn.Module):
def __init__(self, vocab_size, dim, n_classes): ...
def forward(self, tokens): ...
def train_text_classifier(tokens, labels, vocab_size, n_classes):
Input
model = MeanPoolClassifier(vocab_size=30, dim=8, n_classes=3)
short = torch.tensor([[5, 7, 0]])
padded = torch.tensor([[5, 7, 0, 0, 0, 0, 0]])
Output
torch.allclose(model(short), model(padded)) -> True
Reasoning
Both rows hold the same two real tokens, 5 and 7. The mask removes every
padding position, and the mean divides by 2 in both cases. A plain
.mean(dim=1) would divide by 3 for one row and by 7 for the other, so
the logits would change with the padding.
tokens is int64 with shape (B, T). Padding is always 0 and comes
after the real tokens.1.Run it in Colab
Google Colab has PyTorch and a free GPU, and needs nothing installed. Take a code, open the notebook, and paste the code into its first cell. Grading happens there and the result comes back here.
In Colab, the grading cell is your Submit. It runs the hidden cases there, and the result shows here on its own. This one is scored on a threshold, not on exact values.
⇧↵run cell