REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Update a detached Group DRO adversary from group means

Return (robust_loss, next_log_weights). All G declared groups must occur in this batch. Average losses within each group, update adversary log weights by eta times DETACHED group means, normalize in log space, then weight differentiable group means by detached updated probabilities. Do not backpropagate into old adversary state. Reject empty/missing/out-of-range groups, nonfinite losses/state and nonpositive eta. This deliberately balanced-batch contract avoids silently inventing loss for unobserved groups.

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: Update a detached Group DRO adversary from group means →

Your task

Return (robust_loss, next_log_weights). All G declared groups must occur in this batch. Average losses within each group, update adversary log weights by eta times DETACHED group means, normalize in log space, then weight differentiable group means by detached updated probabilities. Do not backpropagate into old adversary state. Reject empty/missing/out-of-range groups, nonfinite losses/state and nonpositive eta. This deliberately balanced-batch contract avoids silently inventing loss for unobserved groups.

Starter

import math
import torch

def group_dro(losses, groups, log_weights, eta=.1):
    # TODO: implement group_dro under the declared contract.
    return None
Inspect the worked answer
import math
import torch

def group_dro(losses, groups, log_weights, eta=.1):
    if losses.ndim!=1 or losses.numel()==0 or not losses.is_floating_point() or not torch.isfinite(losses).all():raise ValueError('Expected finite floating per-row losses.')
    if groups.shape!=losses.shape or groups.dtype!=torch.long or log_weights.ndim!=1 or not log_weights.is_floating_point() or len(log_weights)==0 or not torch.isfinite(log_weights).all():raise ValueError('Expected aligned groups and finite adversary state.')
    if not math.isfinite(eta) or eta<=0 or groups.min()<0 or groups.max()>=len(log_weights):raise ValueError('Invalid group ID or learning rate.')
    means=[]
    for group in range(len(log_weights)):
        selected=groups==group
        if not selected.any():raise ValueError('Every declared group must occur in this batch.')
        means.append(losses[selected].mean())
    means=torch.stack(means)
    next_log=(log_weights.detach()+eta*means.detach()).log_softmax(0)
    robust=(next_log.exp().detach()*means).sum()
    return robust,next_log

About this algorithm

How Update a detached Group DRO adversary from group means works

The idea

A model with a low average loss can still fail badly on a small group of examples, because large groups dominate the average. Group DRO, distributionally robust optimization over groups, trains on a weighted sum of per-group mean losses, and the weights are set by an adversary that favours whichever group is doing worst.

group_dro averages the losses inside each group, raises each group's log weight by eta times its mean loss, and renormalises with log_softmax. Groups with high loss gain weight, so the model's next gradient pays more attention to them. The weights are detached: the model receives gradients only through the group means, never through the adversary. Every declared group must appear in the batch, since a missing group has no loss to average.

How it works

  1. Validate the per-row losses, aligned int64 group ids, finite log_weights and eta > 0.
  2. Average the losses of each group into means, raising ValueError if any declared group has no rows in the batch.
  3. Compute next_log as the log_softmax of log_weights.detach() + eta * means.detach().
  4. Turn next_log into probabilities with exp() and detach them.
  5. Return robust, the sum of those probabilities times means, together with next_log for the next call.

What it costs

Per batch
O(N·G) in this answer
Adversary
G log weights
Scales with
rows N, groups G

The answer builds one mask over all N rows for each of the G groups, which is fine for a handful of groups, and the adversary's whole state is G numbers.

Where it is used

  • Sagawa and co-authors introduced this online Group DRO algorithm in 2019 and showed it needs strong regularisation to improve worst-group accuracy.
  • The Waterbirds dataset, built by pasting bird photos onto land or water backgrounds, is a standard test of worst-group accuracy.
  • The WILDS benchmark of distribution shifts includes Group DRO among its baseline training algorithms.

Watch out for

  • Letting gradients flow through the adversary weights, so the optimizer also tries to change the weights instead of only lowering group losses.
  • Weighting rows instead of group means: duplicating the rows of one group would then change that group's share of the loss.
  • Treating a group absent from the batch as having zero loss, which quietly lowers its weight. The Lab raises an error instead.