REAL PYTORCH · CPU TRAINING AND AUTOGRAD
Differentiate masked focal loss under class imbalance
Implement multiclass focal loss: mean of -alpha[y]*(1-p[y])**gamma*log(p[y]) over valid rows, normalized by the number of valid targets, not the sum of class weights. Use log-softmax, preserve autograd and return graph-connected zero when every target is ignored. Reject nonfinite logits, invalid shapes/dtypes/labels, negative or nonfinite gamma, and nonpositive/nonfinite class weights. Do not detach the focal factor.
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: Differentiate masked focal loss under class imbalance →
Your task
Implement multiclass focal loss: mean of -alpha[y]*(1-p[y])**gamma*log(p[y]) over valid rows, normalized by the number of valid targets, not the sum of class weights. Use log-softmax, preserve autograd and return graph-connected zero when every target is ignored. Reject nonfinite logits, invalid shapes/dtypes/labels, negative or nonfinite gamma, and nonpositive/nonfinite class weights. Do not detach the focal factor.
Starter
import math
import torch
from torch.nn import functional as F
def focal_loss(logits, targets, gamma=2., alpha=None, ignore=-100):
# TODO: implement focal_loss under the declared contract.
return NoneInspect the worked answer
import math
import torch
from torch.nn import functional as F
def focal_loss(logits, targets, gamma=2., alpha=None, ignore=-100):
if logits.ndim!=2 or logits.shape[0]==0 or logits.shape[1]<2 or not logits.is_floating_point() or not torch.isfinite(logits).all():
raise ValueError('Expected finite nonempty [batch, classes] floating logits.')
if targets.shape!=logits.shape[:1] or targets.dtype!=torch.long or not math.isfinite(gamma) or gamma<0:
raise ValueError('Expected aligned int64 targets and finite gamma >= 0.')
valid=targets!=ignore
if ((targets[valid]<0)|(targets[valid]>=logits.shape[1])).any():
raise ValueError('Target outside the vocabulary.')
if alpha is not None and (alpha.shape!=(logits.shape[1],) or not torch.isfinite(alpha).all() or (alpha<=0).any()):
raise ValueError('Class weights must be finite positive [classes].')
if not valid.any():return logits.sum()*0
selected=logits[valid].log_softmax(-1).gather(1,targets[valid,None]).squeeze(1)
weight=1 if alpha is None else alpha[targets[valid]]
loss=-weight*(1-selected.exp()).pow(gamma)*selected
return loss.mean()