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 NoneInspect 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