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 None
Inspect 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()

About this algorithm

How Differentiate masked focal loss under class imbalance works

The idea

Focal loss is cross-entropy with one extra factor. For each row it computes -(1 - p) ** gamma * log(p), where p is the probability the model gives to the correct class. When the model is confident and right, (1 - p) ** gamma is close to zero and the row adds almost nothing. When the model is wrong, the factor is close to one and the row counts nearly in full.

That matters under class imbalance, where thousands of easy examples can drown out a few hard ones. With gamma = 0 the loss is ordinary cross-entropy. Optional alpha weights scale each class. This Lab divides by the number of valid targets, skips rows whose target equals ignore, and keeps the focal factor inside the gradient.

How it works

  1. Validate finite [batch, classes] logits, int64 targets, gamma >= 0, and positive finite alpha weights if they are given.
  2. Build the mask valid = targets != ignore and check that every valid label is a real class index.
  3. If no row is valid, return logits.sum() * 0, a zero that is still connected to the graph.
  4. Take log_softmax of the valid rows and gather the log-probability of each target into selected.
  5. Compute -weight * (1 - selected.exp()) ** gamma * selected, with weight read from alpha by target class.
  6. Return the mean over the valid rows.

What it costs

Per batch
O(N·C)
Memory
O(N·C)
Scales with
batch N, classes C

The log-softmax reads every logit once, and the focal factor adds only a few elementwise operations per row on top of cross-entropy.

Where it is used

  • Lin and co-authors introduced focal loss in 2017 to train the RetinaNet object detector, where background boxes vastly outnumber objects.
  • torchvision provides sigmoid_focal_loss in torchvision.ops and uses it in its RetinaNet implementation.
  • MMDetection includes FocalLoss as a configurable classification loss for detectors such as RetinaNet and FCOS.

Watch out for

  • Detaching (1 - p) ** gamma: the gradient then ignores how the factor changes with the logits, and the Lab's finite-difference check fails.
  • Computing softmax and then log: very large logits give a probability of exactly 0 and an infinite loss. Use log_softmax.
  • Dividing by the sum of the alpha weights, as weighted F.cross_entropy does: this Lab divides by the count of valid targets.