Skip to content
Edit this page View source of this page

optora.dro.group_dro

Group distributionally robust optimization (Sagawa et al. 2020).

The training population is a mixture of \(G\) known groups, for example the combinations of a label and a spurious attribute, and group DRO minimizes the risk of the worst group rather than the average one,

\[ \min_\theta \max_{g = 1, \dots, G} R_g(\theta) = \min_\theta \sup_{q \in \Delta_G} \sum_{g=1}^{G} q_g R_g(\theta), \qquad R_g(\theta) = \mathbb{E}_{Z \sim P_g}[\ell(\theta; Z)]. \]

Over the empirical group risks, the inner supremum is a worst case over distributions on the groups, so it is an existing ambiguity set applied to the vector of group losses that group_losses computes, centred on the group proportions \(p\). Four of the library's sets recover the worst group risk.

  • CVaRAmbiguitySet(p, alpha=0.0) is the maximum over the groups with \(p_g > 0\). Its level \(\alpha\) interpolates between ERM at \(\alpha = 1\) and group DRO as \(\alpha \to 0\).
  • TotalVariationAmbiguitySet(p, radius=1.0) is the maximum over all groups.
  • KLAmbiguitySet(p, radius) and ChiSquareAmbiguitySet(p, radius) are balls around the group mix, and equal the worst group exactly once the radius reaches \(\log(1/p_{g^\star})\), respectively \(1/p_{g^\star} - 1\), for the worst group \(g^\star\).

On a minibatch, the maximum of the minibatch group means overestimates the worst group risk (\(\mathbb{E}[\max] \ge \max \mathbb{E}\)), and the worst group can change from one minibatch to the next. OnlineGroupDRO implements the online algorithm of Sagawa et al. for this setting. It keeps the group weights as state and moves them by exponentiated-gradient ascent, one step per minibatch.

OnlineGroupDRO

Bases: Module

Online group DRO by exponentiated-gradient ascent on the group weights.

Group DRO is the minimax problem \(\min_\theta \max_{q \in \Delta_G} \sum_g q_g R_g(\theta)\). The online algorithm of Sagawa et al. (2020, Algorithm 1) plays stochastic mirror ascent on \(q\) with the entropic mirror map, that is exponentiated gradient (Nemirovski et al. 2009), against stochastic gradient descent on \(\theta\). On a minibatch with group losses \(\hat\ell_g\) it first moves the weights,

\[ q_g \leftarrow \frac{q_g\, e^{\eta \hat\ell_g}} {\sum_h q_h\, e^{\eta \hat\ell_h}}, \]

and then descends the weighted loss \(\sum_g q_g \hat\ell_g\) in \(\theta\). step takes the ascent step and forward evaluates the weighted loss, so one training step reads

group_loss = group_losses(per_sample_loss, groups, num_groups)
adversary.step(group_loss)
adversary(group_loss).backward()
optimizer.step()

in that order. As in Algorithm 1, the model step uses the weights already updated on the same minibatch. forward alone never changes the weights, so without step it is a fixed reweighting.

A group absent from the minibatch has group loss zero (see group_losses), so step leaves its unnormalized weight unchanged, which is how Algorithm 1 treats every group it did not sample. Draw minibatches with every group present, for example by sampling a fixed number of examples per group, and each group loss is an unbiased estimate of that group's risk given the minibatch's group counts.

After \(T\) steps on the same group losses \(\ell\) the weights are the exponential tilt \(q_0\, e^{T \eta \ell} / Z\) of the initial weights, which is the worst case of the KL ball around \(q_0\) whose radius is the tilt's KL divergence from \(q_0\) (see optora.dro.KLAmbiguitySet). The iterates follow the KL-DRO worst-case path and approach the worst group as \(T \eta\) grows.

The weights are state, kept as normalized log-weights in a buffer, so .to(...) moves them, state_dict checkpoints them, and a group with zero initial weight keeps weight zero. step runs without autograd and is not part of the objective. forward is a pure function of the weights and the group losses, so it composes with torch.func transforms, while step must run outside them. Neither synchronizes with the host.

Attributes:

Name Type Description
log_weights Tensor

Normalized log group weights of shape (..., G), -inf for a group with zero weight. Leading dimensions index independent adversaries, one per batch element of the losses.

step_size float | Tensor

Nonnegative ascent step size \(\eta\) in inverse units of the loss, a float or a tensor broadcasting against the leading dimensions of log_weights, giving each adversary its own.

num_groups property

Number of groups \(G\).

weights property

Current group weights \(q\) of shape (..., G), on the simplex.

__init__(initial_weights, step_size, validate=False)

Initialize the group weights.

Parameters:

Name Type Description Default
initial_weights Tensor

Starting group weights \(q_0\), a nonnegative floating-point tensor of shape (..., G) that sums to one along its last dimension. Sagawa et al. start from the uniform distribution. Starting from the group proportions makes a zero step size exactly ERM. Leading dimensions give independent adversaries, for example one per jointly trained model.

required
step_size float | Tensor

Nonnegative ascent step size \(\eta\). A tensor is registered as a buffer and must broadcast against the leading dimensions of initial_weights.

required
validate bool

Whether to check that initial_weights is a distribution and a tensor step_size is finite and nonnegative. The check reads reductions on the host, so it is opt-in.

False

Raises:

Type Description
ValueError

If initial_weights is not a floating-point tensor with at least one dimension and one group, a float step_size is negative or not finite, a tensor step_size does not broadcast against the leading dimensions, or validate is set and a check fails.

step(group_loss)

Take one exponentiated-gradient ascent step on the group weights.

Sets \(q \leftarrow q\, e^{\eta \hat\ell} / \sum_h q_h e^{\eta \hat\ell_h}\) in place, computed in log space without autograd.

Parameters:

Name Type Description Default
group_loss Tensor

Group losses of shape (..., G), broadcasting to the shape of log_weights. Only its value is used.

required

Raises:

Type Description
ValueError

If group_loss does not have shape (..., G) or does not broadcast to the shape of log_weights.

RuntimeError

If called inside a torch.func transform, which cannot mutate the weights.

forward(group_loss)

Evaluate the weighted loss \(\sum_g q_g \hat\ell_g\) at the current weights.

Parameters:

Name Type Description Default
group_loss Tensor

Group losses of shape (..., G), broadcasting against the leading dimensions of log_weights.

required

Returns:

Type Description
Tensor

The weighted loss over the broadcast batch, computed in

Tensor

optora.core.working_dtype(group_loss, log_weights) and

Tensor

returned in the promoted dtype of group_loss and

Tensor

log_weights. Its gradient with respect to group_loss is the

Tensor

weights.

Raises:

Type Description
ValueError

If group_loss does not have shape (..., G).

group_losses(loss, groups, num_groups)

Average per-sample losses within each group.

The group loss of group \(g\) is the empirical group risk

\[ \hat R_g = \frac{1}{n_g} \sum_{i:\, g_i = g} \ell_i, \qquad n_g = |\{i : g_i = g\}|, \]

and is zero for a group without samples, whose sum is empty. Weighting the group losses by the group proportions \(n_g / n\) recovers the mean of loss. The reduction is a scatter-add, so it never synchronizes with the host and its gradient with respect to \(\ell_i\) is \(1 / n_{g_i}\).

Parameters:

Name Type Description Default
loss Tensor

Per-sample losses of shape (..., n).

required
groups Tensor

Integer group index of each sample, in [0, num_groups), of a shape broadcasting against loss, for example (n,) for one group assignment shared by every batch element. Indices out of range are not checked, since the check would read the data on the host. A CPU tensor then raises an indexing error and a CUDA tensor triggers a device-side assertion.

required
num_groups int

Number of groups \(G\), at least one.

required

Returns:

Type Description
Tensor

The group losses of shape (..., num_groups) over the broadcast

Tensor

batch, computed in optora.core.working_dtype(loss) and returned in

Tensor

loss's dtype.

Raises:

Type Description
ValueError

If num_groups is less than one, loss is zero-dimensional, or groups is not an integer tensor or does not broadcast against loss.