PythiloLesson 2 of 8 · progress kept in this browser

Normalize sequence loss by valid tokens

Padded sequence positions should not train the model, and their count should not dilute the reported loss. Mask them before normalization and divide by the number of valid targets. An all-padding batch needs an explicit finite result with a valid zero-gradient connection.

The exercise uses real log-softmax and gather operations over logits. It checks both forward values and backward gradients. Token masking is separate from attention masking: one controls which targets contribute to the objective, while the other controls which context positions can influence predictions. A correct loss mask cannot repair future-token leakage in attention.

import torch
logits=torch.tensor([[0.,0.],[0.,0.]])
logp=torch.nn.functional.log_softmax(logits,dim=-1)
print(-logp[0,1].item())
This example uses torch. Run it in the Pythilo app, where these features are available.
Your task

Implement masked_ce(logits,targets,pad=-1), logits shape [N,C], targets [N]. Mean negative log probability over non-pad targets only. Return logits.sum()*0 for all padding so backward works. Valid non-pad targets are class indices.

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.