Module contents
Lesson 20 of 20Research 110 min

Out-of-distribution generalization: distributional robustness and invariance

When deployment conditions are unknown, learn predictors that work across a family of distributions. Formulate out-of-distribution generalization with worst-case risk, develop f-divergence DRO, CVaR and group DRO, and study spurious correlations, invariant risk minimization and empirical regularities such as accuracy on the line.

After this lesson you can

  • Formulate out-of-distribution generalization as worst-case risk minimization over an uncertainty set.
  • Derive the DRO dual form of CVaR and relate χ²-ball DRO to variance penalization.
  • Implement group DRO and compare its worst-group error with ERM on a spurious-correlation problem.
  • Explain IRM and its IRMv1 relaxation, analyze Rosenfeld et al.’s failure cases, and connect IRM with invariant causal prediction.
  • Use DomainBed, WILDS and accuracy on the line to judge when well-tuned ERM is sufficient.

Before you start

Motivation: the model that learns the background

Arjovsky, Bottou, Gulrajani, and Lopez-Paz open their IRM paper with a thought experiment: you label pictures of cows and camels, but selection bias puts almost every cow in a green meadow and almost every camel in a desert. Your trained network passes the test and fails as soon as it sees a cow on a beach: it learned to classify green and beige landscapes. Geirhos et al. (2020) collect many real cases of this pattern under the name shortcut learning. The most cited: a pneumonia classifier trained on radiographs from several hospitals performed much worse at new hospitals because it learned to recognize the hospital (for example, from a distinctive metal mark on the image) and used each hospital’s pneumonia prevalence to predict well while learning almost nothing about pneumonia.

The problem is not exclusive to vision. A vulnerability detector trained on code from a few projects may rely on naming conventions or team style instead of the data flow that makes a function exploitable; a credit-risk model may rely on a variable predictive only in one interest-rate regime. In all three cases the feature predicts training data and stops doing so at deployment, and validation error does not reveal it because validation comes from the same distribution.

The WILDS benchmark (Koh et al. 2021) quantifies the cost in real problems. In its table 1, an ERM-trained model on Camelyon17 (lymph-node tissue patches from five hospitals) achieves 93.2 %93.2\,\% in seen hospitals and 70.3 %70.3\,\% in a new hospital; in iWildCam (camera-trap photographs) macro F1 falls from 47.047.0 to 31.031.0 on unseen cameras; in CivilComments, worst-demographic-group accuracy is 56.0 %56.0\,\% when the mean is 92.2 %92.2\,\%.

The previous lesson covered distribution shift when you know something about the target distribution: target samples let you estimate importance weights or label shift, and the domain-adaptation bound says how much mismatch costs. Here you have nothing from the target. You can only learn predictors that work well across a family of possible distributions, and the question is which family makes sense and what protection against it costs.

InteractiveThe spurious-correlation trap
  • y=+1y = +1
  • y=−1y = -1
  • ERM
  • Group DRO
  • IRMv1
  • invariant (ws=0w_s = 0, wc=1.96w_c = 1.96)
Training environments: P(a=y)=0.98P(a = y) = 0.98 and 0.820.82 (130 points each, for display only).
ERM
worst group
46.4 %
test environment
51.5 %
training
92.2 %
Group DRO
worst group
84.1 %
test environment
84.1 %
training
84.1 %
IRMv1
worst group
82.5 %
test environment
82.8 %
training
85.3 %
Dashed line: 84.1 %, the best classifier using only xcx_c (equal across groups and environments). Dotted: chance.
0.90
Δ = 0.08
10^4.0
ERM: ws/wcw_s / w_c1.099
Group DRO: ws/wcw_s / w_c0.000
IRMv1: ws/wcw_s / w_c0.064
IRMv1 penalty at its solution2.5e−5
Group DRO: minority-group weight qq0.50
ERM assigns xsx_s 1.10 times the causal weight and achieves 46.4 % worst-group accuracy. Group DRO and IRMv1 nearly eliminate that weight and approach the invariant classifier's 84.1 %.
Explicit model: y=±1y = \pm 1, spurious attribute aa matching yy with probability pep_e in environment ee, causal feature xc=y+ε1x_c = y + \varepsilon_1, and spurious feature xs=a+0.4 ε2x_s = a + 0.4\,\varepsilon_2. Two training environments have p1=ρ+Δp_1 = \rho + \Delta and p2=ρ−Δp_2 = \rho - \Delta; test has p=1−ρp = 1 - \rho. All three models are intercept-free logistic regressions trained by gradient descent on the exact distribution (Gaussian integrals by quadrature), so there is no sampling noise; group accuracies are exact. Arrows indicate weight-vector directions and lines decision boundaries. At right: worst (y,a)(y, a) group accuracy, test-environment accuracy, and training mean.

Three things the figure shows and the rest of the lesson formalizes:

  1. ERM makes no mistake: it does exactly what you ask. With ρ=0.9\rho = 0.9, the spurious feature predicts the label better than the causal one (the sign of xsx_s is correct 89.5 %89.5\,\% of the time, 0.9 Φ(2.5)+0.1 (1−Φ(2.5))0.9\,\Phi(2.5) + 0.1\,(1 - \Phi(2.5)), versus 84.1 %84.1\,\% for the sign of xcx_c, which is Φ(1)\Phi(1)), so the average-risk minimizer uses it heavily: its weight on xsx_s is comparable to that on xcx_c. In the minority group, where a=−ya = -y, the spurious feature pushes the wrong way, and in the test environment, where correlation reverses, the model falls below 60 %60\,\%.
  2. Extra information is needed to avoid it. Group DRO receives group labels (y,a)(y, a) and minimizes the worst group; IRMv1 receives environments and seeks what remains unchanged between them. With data from one environment and no groups there is no way to distinguish xcx_c from xsx_s: both are predictive.
  3. That information must be informative. Move Δ\Delta to zero: the two environments are identical, IRMv1’s penalty vanishes at the ERM solution, and IRMv1 returns ERM. Even with Δ>0\Delta > 0, if small, IRMv1 leaves appreciable spurious weight: you will see why when we study its penalty landscape.

Formalization: environments, uncertainty sets, and worst-case risk

Fix a loss ℓ\ell and predictor class fθf_\theta. Each environment ee is a distribution PeP^e over (X,Y)(X, Y) and its risk is Re(θ)=E(X,Y)∼Pe[ℓ(fθ(X),Y)]R^e(\theta) = \E_{(X, Y) \sim P^e}[\ell(f_\theta(X), Y)]. Training environments Etr\mathcal{E}_{\text{tr}} are observed; deployment environments form an unseen set Eall⊇Etr\mathcal{E}_{\text{all}} \supseteq \mathcal{E}_{\text{tr}}.

Without assumptions on Eall\mathcal{E}_{\text{all}} the problem has no solution, and the argument is as short as for the No Free Lunch theorem.

Proof

At each x∉Sx \notin S, h1(x)≠h2(x)h_1(x) \neq h_2(x), so f(x)f(x) is wrong under exactly one of the two distributions: 1[f(x)≠h1(x)]+1[f(x)≠h2(x)]=1\ind[f(x) \neq h_1(x)] + \ind[f(x) \neq h_2(x)] = 1. Integrating with QXQ_X over ScS^c gives RQ1(f)+RQ2(f)≥QX(Sc)R_{Q_1}(f) + R_{Q_2}(f) \ge Q_X(S^c), and the maximum of two numbers is at least their mean. Training data cannot distinguish Q1Q_1 from Q2Q_2: any algorithm produces the same ff under both.

∎

If deployment puts half its mass outside training support, no method gets below 25 %25\,\% worst-case error. It is not necessary to leave support: if Eall\mathcal{E}_{\text{all}} permits freely changing P(Y∣X)P(Y \given X) inside SS, the same argument works with all of SS. The theory in this lesson consists of choosing a restriction on Eall\mathcal{E}_{\text{all}} that is both credible and sufficient:

Deployment assumptionMethodRequirements
It is near the training distribution (in ff-divergence or Wasserstein)DROa radius
It is a mixture of known groups in arbitrary proportionsGroup DROtraining group labels
It shares a mechanism P(Y∣Φ(X))P(Y \given \Phi(X)) with all environmentsICP, IRMmultiple training environments
It behaves like observed shiftsAccuracy on the linea population of models and an OOD dataset

The previous lesson’s reweighting is the degenerate case where the uncertainty set has one element, the target, which can also be sampled; none of the four rows needs to see the target.

Distributionally robust optimization with ff-divergences

For the sample, QQ assigns probability qiq_i to each point and is conveniently written with likelihood ratio wi=nqiw_i = n q_i, so P^n\hat P_n is w≡1w \equiv 1, EQ[ℓ]=1n∑iwiℓi\E_Q[\ell] = \frac1n\sum_i w_i \ell_i, and Df(Q ∥ P^n)=1n∑if(wi)D_f(Q \,\|\, \hat P_n) = \frac1n \sum_i f(w_i). The adversary chooses weights and you choose θ\theta: this is a min–max problem.

The ball only reweights what you have seen. For KL, χ2\chi^2 or CVaR, Df(Q ∥ P)=∞D_f(Q \,\|\, P) = \infty if QQ puts mass where PP does not (in all three, f(t)/t→∞f(t)/t \to \infty when t→∞t \to \infty, penalizing singular mass), and the usual formulation (Duchi and Namkoong, equation 3) directly optimizes over L= ⁣dQ/ ⁣dPL = \dd Q/\dd P. With the empirical distribution, QQ lives on the sample’s nn points. ff-divergence DRO protects against subpopulations already present, even if underrepresented; it cannot help with nighttime images absent from your data.

Duality: from the adversary to a minimization problem

The supremum over QQ is linear in LL with convex constraints, and its dual is a problem in two scalars.

Proof

The inequality ≤\le is weak duality and is proved in one line. For admissible LL, λ≥0\lambda \ge 0, and η∈R\eta \in \R,

E[Lℓ]≤E[Lℓ]−λ(E[f(L)]−ρ)−η(E[L]−1)=λρ+η+E[L(ℓ−η)−λf(L)],\E[L\ell] \le \E[L\ell] - \lambda\big(\E[f(L)] - \rho\big) - \eta\big(\E[L] - 1\big) = \lambda\rho + \eta + \E\big[L(\ell - \eta) - \lambda f(L)\big],

because the two subtracted terms are ≤0\le 0 and =0= 0. Inside the expectation, pointwise L(ℓ−η)−λf(L)≤sup⁡t≥0(t(ℓ−η)−λf(t))=λf∗((ℓ−η)/λ)L(\ell - \eta) - \lambda f(L) \le \sup_{t \ge 0}\big(t(\ell - \eta) - \lambda f(t)\big) = \lambda f^*\big((\ell - \eta)/\lambda\big) if λ>0\lambda > 0. Taking supremum over LL and infimum over (λ,η)(\lambda, \eta) gives ≤\le. Equality is strong duality: L≡1L \equiv 1 satisfies E[f(L)]=0<ρ\E[f(L)] = 0 < \rho strictly (this problem’s Slater condition), and Shapiro’s result extends it to this infinite-dimensional problem.

∎

The dual turns the min–max problem into joint minimization in (θ,λ,η)(\theta, \lambda, \eta), convex if ℓ\ell is convex in θ\theta: this is the practical path to training with DRO. Two special cases have closed forms explaining what the adversary does.

CVaR: the worst subpopulation of size α\alpha

Take f(t)=0f(t) = 0 if 0≤t≤1/α0 \le t \le 1/\alpha and f(t)=+∞f(t) = +\infty otherwise. Constraint E[f(L)]≤ρ\E[f(L)] \le \rho says only L≤1/αL \le 1/\alpha: the adversary can multiply any point’s probability by at most 1/α1/\alpha. The conjugate is f∗(s)=sup⁡0≤t≤1/αts=s+/αf^*(s) = \sup_{0 \le t \le 1/\alpha} ts = s_+/\alpha, positively homogeneous, so λf∗((ℓ−η)/λ)=(ℓ−η)+/α\lambda f^*((\ell - \eta)/\lambda) = (\ell - \eta)_+/\alpha for every λ>0\lambda > 0 and term λρ\lambda\rho goes to zero. This gives the Rockafellar–Uryasev formula:

CVaRα(ℓ)=inf⁡η∈R{η+1α E[(ℓ−η)+]}=sup⁡{EQ[ℓ]: ⁣dQ ⁣dP≤1α}.\text{CVaR}_\alpha(\ell) = \inf_{\eta \in \R}\Big\{\eta + \tfrac{1}{\alpha}\,\E\big[(\ell - \eta)_+\big]\Big\} = \sup\Big\{\E_Q[\ell] : \tfrac{\dd Q}{\dd P} \le \tfrac{1}{\alpha}\Big\}.

The infimum is attained at quantile 1−α1 - \alpha of ℓ\ell (VaR) and the supremum at QQ placing density 1/α1/\alpha on the tail. Duchi and Namkoong read it this way: if P=αQ+(1−α)Q′P = \alpha Q + (1 - \alpha)Q', then  ⁣dQ/ ⁣dP≤1/α\dd Q/\dd P \le 1/\alpha, and conversely; the uncertainty set contains all subpopulations of mass at least α\alpha, and CVaR is the average loss of the worst. This is the same risk measure as expected shortfall in quantitative finance, and minimizing it over portfolios is CVaR optimization. Exercises ask you to prove equality of the two expressions and calculate a case by hand.

The χ2\chi^2 ball: mean plus standard deviation

With f(t)=12(t−1)2f(t) = \frac12(t - 1)^2 the ball is {w≥0:wˉ=1, 1n∑i12(wi−1)2≤r}\{w \ge 0 : \bar w = 1,\ \frac1n\sum_i \frac12(w_i - 1)^2 \le r\}, and the adversary has an explicit solution.

Proof

Write 1n∑iwiℓi=ℓˉ+1n∑i(wi−1)(ℓi−ℓˉ)\frac1n\sum_i w_i\ell_i = \bar\ell + \frac1n\sum_i (w_i - 1)(\ell_i - \bar\ell), valid because wˉ=1\bar w = 1. By the Cauchy–Schwarz inequality with product 1n∑iaibi\frac1n\sum_i a_ib_i,

1n∑i(wi−1)(ℓi−ℓˉ)≤(1n∑i(wi−1)2)1/2s≤2r s.\tfrac1n\textstyle\sum_i (w_i - 1)(\ell_i - \bar\ell) \le \Big(\tfrac1n\sum_i(w_i - 1)^2\Big)^{1/2} s \le \sqrt{2r}\,s.

Equality in Cauchy–Schwarz requires w−1w - 1 proportional to ℓ−ℓˉ\ell - \bar\ell with positive constant, and equality in the constraint requires it to be active: wi=1+2r (ℓi−ℓˉ)/sw_i = 1 + \sqrt{2r}\,(\ell_i - \bar\ell)/s. Those weights have mean 1 and divergence exactly rr, and are admissible if and only if all are ≥0\ge 0, the condition on min⁡iℓi\min_i \ell_i. Otherwise the maximum is strictly smaller: optimal weights (by KKT conditions) are wi∝(ℓi−η)+w_i \propto (\ell_i - \eta)_+ and zero out the smallest losses.

∎

With radius scaling as r=ρ/nr = \rho/n, equality says Rf(θ)=ℓˉ+2ρ s2/n\mathcal{R}_f(\theta) = \bar\ell + \sqrt{2\rho\,s^2/n}: χ2\chi^2 DRO is empirical loss plus a penalty proportional to loss standard deviation. Namkoong and Duchi (2017) prove this expansion holds with high probability when loss variance is sufficient, and unlike directly penalizing variance (nonconvex in θ\theta), the robust objective is convex if ℓ\ell is: a convex way to regularize by variance. Penalizing variance targets exactly what a model that succeeds for most and fails for a minority produces: widely dispersed losses.

InteractiveThe adversary inside the ball
Sorted losses ℓi\ell_i (opacity shows their adversarial weight)
Adversarial likelihood ratio wi=n Qiw_i = n\,Q_i (empirical value is 1)
  • mean ℓˉ\bar\ell
  • worst case in the ball
  • ℓˉ+2r s\bar\ell + \sqrt{2r}\,s
  • exact worst case
  • ℓ̄ + √(2r)·s
  • sample maximum
Uncertainty set
0.100
Mean ℓˉ\bar\ell and standard deviation ss0.342 · 0.338
Worst case in the ball0.4937
ℓˉ+2r s\bar\ell + \sqrt{2r}\,s0.4937
Zero weights0 of 20
Exact equality: the worst case is ℓˉ+2r s=0.4937\bar\ell + \sqrt{2r}\,s = 0.4937 because no weight reaches zero (up to r∗=0.510r^* = 0.510). DRO is the mean plus a standard-deviation penalty.
Twenty sorted logistic losses log⁡(1+e−mi)\log(1 + e^{-m_i}) with margins mi∼N(1.5,1.52)m_i \sim \Normal(1.5, 1.5^2). Above: losses (bar opacity is adversarial weight); below: likelihood ratio wi=nQiw_i = nQ_i for the exact worst case computed by KKT conditions. At right: worst-case value versus radius (or α\alpha), compared with ℓˉ+2r s\bar\ell + \sqrt{2r}\,s. Move radius above r∗r^* and see small-loss weights reach zero and the variance formula become a bound. In CVaR mode weights can only be 00 or 1/α1/\alpha (except one at the boundary).

Notice three things. Below r∗r^* the exact and variance curves coincide. Above it, the adversary zeros small losses and keeps moving mass to the tail, but never exceeds the sample maximum: it can reweight, not invent. CVaR is the extreme case of the same idea, with bounded weights instead of a quadratic penalty.

Robustness has a statistical cost. Duchi and Namkoong prove minimax upper and lower bounds for the Cressie–Read family and conclude distributional robustness sometimes costs convergence speed: protection against large shifts requires more data for the same robust-objective estimation error.

Implementation from scratch: three paths to the same number

The cell computes CVaR three ways (sorting, the Rockafellar–Uryasev formula, and a linear program with scipy.optimize.linprog) and worst-case χ2\chi^2 three more ways (closed form, primal solved by SLSQP, and the theorem’s dual with Nelder–Mead), with radii on both sides of r∗r^*.

[ ]CVaR and χ² ball: closed form, primal, and dualBrowser
import numpy as np
from scipy.optimize import linprog, minimize

rng = np.random.default_rng(7)
l = np.logaddexp(0, -rng.normal(1.5, 1.5, 30))           # 30 pérdidas logísticas
n = len(l)

# ---- CVaR: tres caminos que deben coincidir
def cvar_top(l, alpha):
    """Media de la peor masa α: los pesos 1/α van a las pérdidas mayores (con un peso fraccionario en el borde)."""
    s = np.sort(l)[::-1]
    k = alpha * len(l)
    full = int(np.floor(k))
    return (s[:full].sum() + (k - full) * (s[full] if full < len(s) else 0)) / k

def cvar_ru(l, alpha):
    """Rockafellar-Uryasev: inf_η η + E(ℓ - η)₊/α. La función es convexa y lineal a trozos: basta probar η = ℓ_i."""
    return min(eta + np.mean(np.maximum(l - eta, 0)) / alpha for eta in l)

def cvar_lp(l, alpha):
    """Primal como programa lineal: max Σ q_i ℓ_i con Σ q_i = 1 y 0 ≤ q_i ≤ 1/(α n)."""
    res = linprog(-l, A_eq=np.ones((1, n)), b_eq=[1.0], bounds=[(0, 1 / (alpha * n))] * n)
    return -res.fun

for alpha in (0.1, 0.25, 0.5):
    print(f'CVaR_{alpha}: ordenando {cvar_top(l, alpha):.6f}   Rockafellar-Uryasev {cvar_ru(l, alpha):.6f}   LP {cvar_lp(l, alpha):.6f}')

# ---- bola χ²: forma cerrada, primal numérico y dual
def chi2_closed(l, r):
    return l.mean() + np.sqrt(2 * r) * l.std()

def chi2_primal(l, r):
    """max (1/n) Σ w_i ℓ_i con w ≥ 0, media(w) = 1 y media(½ (w - 1)²) ≤ r, resuelto con SLSQP."""
    cons = [{'type': 'eq', 'fun': lambda w: w.mean() - 1},
            {'type': 'ineq', 'fun': lambda w: r - np.mean(0.5 * (w - 1) ** 2)}]
    res = minimize(lambda w: -np.mean(w * l), np.ones(n), bounds=[(0, None)] * n, constraints=cons, method='SLSQP')
    return -res.fun

def f_star(s):
    """Conjugada de f(t) = ½(t - 1)² restringida a t ≥ 0."""
    return np.where(s >= -1, s + 0.5 * s ** 2, -0.5)

def chi2_dual(l, r):
    obj = lambda v: np.exp(v[0]) * r + v[1] + np.exp(v[0]) * np.mean(f_star((l - v[1]) / np.exp(v[0])))
    return minimize(obj, [0.0, l.mean()], method='Nelder-Mead', options={'xatol': 1e-10, 'fatol': 1e-12, 'maxiter': 4000}).fun

r_star = l.var() / (2 * (l.mean() - l.min()) ** 2)
print(f'media {l.mean():.4f}, desviación típica {l.std():.4f}, radio a partir del que se anulan pesos r* = {r_star:.4f}')
for r in (0.5 * r_star, r_star, 3 * r_star):
    print(f'r = {r:.4f}: media + √(2r)·s = {chi2_closed(l, r):.5f}   primal = {chi2_primal(l, r):.5f}   dual = {chi2_dual(l, r):.5f}')

The three CVaR methods agree to six decimal places at all three levels. In the χ2\chi^2 ball, primal and dual always agree (strong duality), and formula ℓˉ+2r s\bar\ell + \sqrt{2r}\,s agrees with them for r=r∗/2r = r^*/2 and r=r∗r = r^*, while with r=3r∗r = 3r^* it overestimates them (1.510941.51094 versus 1.495071.49507): exactly as the theorem predicts.

Wasserstein DRO as a concept

ff-divergence balls do not move mass to new places; Wasserstein balls do. With transport cost c(z,z′)c(z, z'), ball {Q:Wc(Q,P^n)≤ε}\{Q : W_c(Q, \hat P_n) \le \varepsilon\} contains distributions moving each point slightly, and its worst case answers: how much does loss worsen if each example can move an average distance ε\varepsilon?

For W1W_1 with c(z,z′)=∥z−z′∥c(z, z') = \norm{z - z'} and loss LL-Lipschitz in zz, Kantorovich–Rubinstein duality immediately gives EQ[ℓ]−EP^n[ℓ]≤L W1(Q,P^n)\E_Q[\ell] - \E_{\hat P_n}[\ell] \le L\,W_1(Q, \hat P_n), so

sup⁡W1(Q,P^n)≤εEQ[ℓ]≤EP^n[ℓ]+ε L.\sup_{W_1(Q, \hat P_n) \le \varepsilon} \E_Q[\ell] \le \E_{\hat P_n}[\ell] + \varepsilon\,L.

In logistic regression with ℓ=log⁡(1+e−yw⊤x)\ell = \log(1 + e^{-y\vb{w}\T\vb{x}}) and transport only on x\vb{x} (labels do not move), the Lipschitz constant in x\vb{x} is ∥w∥∗\norm{\vb{w}}_*, the dual norm to the cost’s norm. Shafieezadeh-Abadeh, Mohajerin Esfahani, and Kuhn (2015, remark 1) prove Wasserstein DRO then reduces exactly to regularized logistic regression EP^n[ℓ]+ε∥w∥∗\E_{\hat P_n}[\ell] + \varepsilon\norm{\vb{w}}_*: norm regularization is robustness against input shifts.

If instead of the constraint its Lagrangian relaxation with multiplier γ\gamma is used, the inner problem is a per-example attack:

sup⁡Q{EQ[ℓ(θ;Z)]−γWc(Q,P)}=EP[sup⁡z{ℓ(θ;z)−γ c(z,Z)}],\sup_Q\big\{\E_Q[\ell(\theta; Z)] - \gamma W_c(Q, P)\big\} = \E_P\Big[\sup_{z}\big\{\ell(\theta; z) - \gamma\, c(z, Z)\big\}\Big],

This is Sinha, Namkoong, and Duchi’s (2018) formulation: training against Wasserstein worst case is training with distance-penalized adversarial examples, with guarantees when γ\gamma is large enough for the inner problem to be strongly concave. Adversarial robustness, encountered with PGD, is thus DRO with a very local uncertainty set; the OOD generalization in this lesson seeks robustness against large but structured shifts.

Group DRO: the worst group

Often you know which subpopulations concern you: image background combined with class, hospital, demographic group. If each example has a group label g∈{1,…,m}g \in \{1, \dots, m\} with distributions PgP_g, the natural uncertainty set is mixtures {∑gqgPg:q∈Δm}\{\sum_g q_g P_g : q \in \Delta_m\}.

Optimizing max⁡gR^g\max_g \hat R_g with stochastic gradients is awkward (the maximum changes groups between steps and its minibatch estimate is biased), so Sagawa et al. propose an online algorithm alternating one exponentiated-gradient step on qq and one descent step on θ\theta, an instance of gradient descent–ascent:

qg←qg eηqR^g(θ)∑g′qg′ eηqR^g′(θ),θ←θ−η∑gqg∇R^g(θ).q_g \leftarrow \frac{q_g\, e^{\eta_q \hat R_g(\theta)}}{\sum_{g'} q_{g'}\, e^{\eta_q \hat R_{g'}(\theta)}}, \qquad \theta \leftarrow \theta - \eta\sum_g q_g \grad\hat R_g(\theta).

The highest-loss group gains weight multiplicatively. Their proposition 2 gives, for nonnegative convex losses bounded by BℓB_\ell and B∇B_\nabla-Lipschitz on a parameter set of radius BΘB_\Theta, with a randomly selected group per step, expected error of the average iterate in the min–max problem at most 2m10 (BΘ2B∇2+Bℓ2log⁡m)/T2m\sqrt{10\,(B_\Theta^2B_\nabla^2 + B_\ell^2\log m)/T}: the usual O(1/T)\bigO(1/\sqrt{T}) order.

This is not the same as reweighting. Giving each group a fixed weight inversely proportional to its size (importance reweighting toward a uniform group mixture) minimizes mean group risk, not the maximum. Sagawa et al. construct a two-loss toy example (figure 4) where no fixed weight vector reaches the group DRO optimum. In practice the difference appears when some groups are easier to fit than others.

The central finding: strong regularization is needed

The paper’s title result is negative. With ResNet50 on Waterbirds (CUB birds pasted on Places backgrounds; n=4795n = 4795 training images, only 56 waterbirds on land), standard-regularization models interpolate: both ERM and group DRO reach 100 %100\,\% accuracy on the worst training group. If the model already fits every group perfectly, worst-group and average objectives have the same minimizers and group DRO has nothing to correct. At test time ERM’s worst group remains at 60.0 %60.0\,\% and group DRO’s at 76.9 %76.9\,\%; in CelebA both are 41.1 %41.1\,\% (table 1).

The cause is generalization, not training: the train–test gap is much larger in small groups. The solution is therefore to control that gap:

Regime (Sagawa et al. table 1)Worst test group, ERMWorst test group, group DRO
Waterbirds, standard regularization60.0 %76.9 %
Waterbirds, ℓ2\ell_2 strong (λ=1\lambda = 1)21.3 %84.6 %
Waterbirds, early stopping6.7 %86.0 %
CelebA, ℓ2\ell_2 strong (λ=0.1\lambda = 0.1)37.8 %86.7 %
CelebA, early stopping25.0 %88.3 %

With ℓ2\ell_2 penalty four orders of magnitude above usual (λ=1\lambda = 1 versus 10−410^{-4}), no model interpolates, ERM sacrifices the minority (35.7 %35.7\,\% worst-training-group accuracy on Waterbirds), and group DRO protects it (97.5 %97.5\,\%); because the generalization gap is small, this transfers to test. Regularization does not help mean risk but is essential for worst-group risk. With wider hyperparameter search (table 3), Waterbirds worst group is 63.7 %63.7\,\% for ERM, 88.0 %88.0\,\% for reweighting, and 91.4 %91.4\,\% for group DRO. Another adjustment, adding C/ngC/\sqrt{n_g} to each group’s loss to compensate for poorer small-group generalization, raises Waterbirds worst group from 84.684.6 to 90.5 %90.5\,\% (table 2).

Sagawa, Raghunathan, Koh, and Liang (2020) explain the mechanism with a synthetic model like the lab’s. In the overparameterized regime many zero-training-error solutions exist, and the one implicitly selected (recall maximum-margin bias) “memorizes” the fewest examples. Using the spurious feature requires memorizing only the minority; using the noisy causal feature requires memorizing many more points. In their model (n=3000n = 3000, majority 90 %90\,\%, core features a hundred times noisier than spurious), best worst-group test error, 28.5 %28.5\,\%, is achieved by an underparameterized model, while highly overparameterized ones plateau around 55 %55\,\%.

Retraining the last layer. Kirichenko, Izmailov, and Wilson (2023) observe that an ERM-trained Waterbirds network often also learns core features; what fails is the final layer’s weighting. Retraining only the final linear layer on a small group-balanced set (from validation) raises Waterbirds worst group from the starting ERM’s 74.9 %74.9\,\% to 92.9 %92.9\,\%, and CelebA’s from 46.946.9 to 88.3 %88.3\,\% (table 2), comparable to group DRO at a fraction of the cost. The practical lesson: group information is better used where the model cannot interpolate.

Lab: group DRO from scratch

The lab model reduces Sagawa et al.’s to essentials: y,a∈{−1,+1}y, a \in \{-1, +1\}, the spurious attribute matches the label in 90 %90\,\% of examples, the core feature is xcore∼N(y,1)x_{\text{core}} \sim \Normal(y, 1) and the spurious feature xspu∼N(a,0.12)x_{\text{spu}} \sim \Normal(a, 0.1^2), much cleaner. There are four groups (y,a)(y, a), two majority and two minority. You implement logistic regression by gradient descent with three objectives: ERM, group reweighting (each group weighs 1/41/4), and online group DRO with the exponentiated step above. A test set balanced across all four groups evaluates the worst group.

[ ]Group DRO, reweighting, and ERM with spurious correlationBrowser
import numpy as np

def make_groups(n, p_maj, d_noise, rng, balanced=False):
    """y y a en {-1, +1}; a = y con probabilidad p_maj (o grupos equilibrados para evaluar).
    x = [x_core ~ N(y, 1), x_spu ~ N(a, 0.1²), d_noise rasgos de ruido N(0, 9/d_noise)]."""
    if balanced:
        g = np.repeat(np.arange(4), n // 4)                 # 0: (y=-1, a=-1)  1: (-1, +1)  2: (+1, -1)  3: (+1, +1)
    else:
        y = rng.choice([-1, 1], n)
        a = np.where(rng.random(n) < p_maj, y, -y)
        g = 2 * (y > 0) + (a > 0)
    y = np.where(g >= 2, 1.0, -1.0)
    a = np.where(g % 2 == 1, 1.0, -1.0)
    X = np.column_stack([y + rng.standard_normal(len(g)), a + 0.1 * rng.standard_normal(len(g)), np.ones(len(g))])
    if d_noise:
        X = np.hstack([X, rng.standard_normal((len(g), d_noise)) * np.sqrt(9.0 / d_noise)])
    return X, y, g

def sigmoid(z):
    return 0.5 * (1 + np.tanh(0.5 * z))

def train(X, y, g, method, lam=0.0, steps=1000, lr=1.0, eta_q=0.05):
    """Regresión logística por descenso por gradiente con tres objetivos:
    'erm' (media), 'rw' (cada grupo pesa 1/4: reponderación por importancia) y 'dro' (group DRO en línea)."""
    n, d = X.shape
    w = np.zeros(d)
    cnt = np.bincount(g, minlength=4).astype(float)
    q = np.full(4, 0.25)
    for _ in range(steps):
        m = y * (X @ w)
        loss = np.logaddexp(0.0, -m)
        dz = -y * sigmoid(-m)                           # derivada de la pérdida respecto a f(x)
        if method == 'erm':
            c = np.full(n, 1.0 / n)
        elif method == 'rw':
            c = (0.25 / cnt)[g]
        else:
            L_g = np.bincount(g, weights=loss, minlength=4) / cnt
            q = q * np.exp(eta_q * L_g)                 # ascenso por gradiente exponenciado sobre q
            q = q / q.sum()
            c = (q / cnt)[g]                            # descenso sobre w con la mezcla de grupos q
        w -= lr * (X.T @ (c * dz) + lam * w)
    return w, q

def group_acc(w, X, y, g):
    pred = np.where(X @ w >= 0, 1.0, -1.0)
    return np.array([np.mean(pred[g == k] == y[g == k]) for k in range(4)])

rng = np.random.default_rng(0)
X, y, g = make_groups(1000, 0.9, 0, rng)
Xte, yte, gte = make_groups(4000, 0.9, 0, rng, balanced=True)
print('ejemplos por grupo (y, a) = (-1,-1) (-1,+1) (+1,-1) (+1,+1):', np.bincount(g))
p_train = np.bincount(g) / len(g)
print(f"{'método':>6} {'w_core':>7} {'w_spu':>6} {'peor grupo (ent.)':>18} {'peor grupo (test)':>18} {'media (dist. de ent.)':>22}")
for method in ('erm', 'rw', 'dro'):
    w, q = train(X, y, g, method)
    acc_tr, acc_te = group_acc(w, X, y, g), group_acc(w, Xte, yte, gte)
    print(f'{method:>6} {w[0]:7.2f} {w[1]:6.2f} {acc_tr.min():18.3f} {acc_te.min():18.3f} {acc_te @ p_train:22.3f}')
print('pesos finales de group DRO por grupo:', np.round(q, 3))

In low dimension the model cannot interpolate (the core feature is noisy), and the result is clear. ERM splits weight between both features (wcore=1.99w_{\text{core}} = 1.99, wspu=2.29w_{\text{spu}} = 2.29) and its worst group stays at 39.6 %39.6\,\% on test; reweighting and group DRO almost zero the spurious weight (−0.02-0.02 and 0.010.01) and raise the worst group to 81.681.6 and 83.2 %83.2\,\%, near 84.1 %84.1\,\% for the core-only classifier. The cost appears in the training-distribution mean: 93.3 %93.3\,\% for ERM versus 83.5 %83.5\,\% for group DRO, because ERM exploits a correlation real in training.

Now add 600 pure-noise features with only 200 examples: the model has 603 parameters and can interpolate any labeling. This is the Waterbirds regime.

[ ]The interpolating regime: without regularization, group DRO does not helpBrowser
rng = np.random.default_rng(1)
Xh, yh, gh = make_groups(200, 0.9, 600, rng)            # 603 parámetros y 200 ejemplos: el modelo puede interpolar
Xhte, yhte, ghte = make_groups(4000, 0.9, 600, rng, balanced=True)
print('ejemplos por grupo:', np.bincount(gh))
print(f"{'λ':>5} {'método':>6} {'w_core':>7} {'w_spu':>6} {'peor grupo (ent.)':>18} {'peor grupo (test)':>18}")
for lam in (0.0, 0.1):
    for method in ('erm', 'rw', 'dro'):
        w, q = train(Xh, yh, gh, method, lam=lam)
        print(f'{lam:5.1f} {method:>6} {w[0]:7.2f} {w[1]:6.2f} {group_acc(w, Xh, yh, gh).min():18.3f} '
              f'{group_acc(w, Xhte, yhte, ghte).min():18.3f}')

Without regularization (λ=0\lambda = 0) all three methods fit 100 %100\,\% of every training group, and on test the worst group is 52.8 %52.8\,\% (ERM), 61.5 %61.5\,\% (reweighting), and 61.1 %61.1\,\% (group DRO): a small improvement, because once every group is fitted the worst-group objective no longer distinguishes solutions, and spurious weight stays large (2.442.44 for group DRO). The minority has been memorized using noise features that do not generalize. With λ=0.1\lambda = 0.1 no method interpolates; ERM sacrifices the minority (27.3 %27.3\,\% for worst training group and 48.1 %48.1\,\% on test), while reweighting and group DRO reduce spurious weight to 0.070.07 and 0.140.14 and reach 79.279.2 and 78.0 %78.0\,\% on test. This is Sagawa et al.’s table 1 in miniature. It is unsurprising reweighting matches group DRO here: both minority groups are equally difficult, so fixed weight 1/41/4 is already close to the adversary’s optimum.

Spurious correlations and shortcut learning

Why does the model learn them if the correct feature is also available? Three mutually reinforcing reasons.

  1. They are predictive. If the spurious feature is cleaner than the causal one, the average-risk minimizer uses it, as in the first figure and lab. Nothing in ERM penalizes using correlated information.
  2. They are easy. Geirhos et al. distinguish shortcut opportunity offered by the dataset from model preference for simple solutions. Image text or background color are much simpler pixel functions than animal shape, and gradient descent finds simple directions first (spectral bias from lesson 18 is a version of this preference).
  3. They are cheap to interpolate. In the overparameterized regime, implicit regularization selects among many zero-error solutions, and the shortcut-using one must memorize fewer exceptions (Sagawa, Raghunathan, Koh and Liang 2020, above).

The practical consequence is that diagnosis must come from outside the training distribution: evaluate by groups, build test sets breaking the correlation (as in the first figure’s test environment or waterbirds on land), and measure the worst group rather than the mean.

Invariance: invariant causal prediction, IRM, and their limits

Group DRO needs someone to name the spurious attribute. The alternative is to exploit data coming from several environments and seek what remains unchanged across them.

Invariant causal prediction

If data come from a structural causal model and environments are interventions on variables other than YY, the structural equation of YY given its causal parents does not change. Peters, Bühlmann, and Meinshausen (2016) turn that observation into an inference method. Their assumption 1 (invariant prediction) is that there exists a set S∗S^* and coefficients γ∗\gamma^* with support S∗S^* such that, in every environment ee,

Ye=μ+Xeγ∗+εe,εe∼F,εe⊥ ⁣ ⁣ ⁣⊥XS∗e,Y^e = \mu + X^e\gamma^* + \varepsilon^e, \qquad \varepsilon^e \sim F,\quad \varepsilon^e \indep X^e_{S^*},

with the same noise distribution FF in every environment and XeX^e arbitrarily distributed. If S∗S^* are the parents of YY in the structural model, the assumption holds.

Invariant causal prediction (ICP) tests, for each variable subset SS, the null hypothesis that SS satisfies invariance, and returns the intersection of nonrejected sets, S^=⋂S: H0,S no rechazadaS\hat S = \bigcap_{S:\, H_{0,S}\ \text{no rechazada}} S. Their theorem 1 gives coverage: if each test has level α\alpha, then P(S^⊆S∗)≥1−α\Pr(\hat S \subseteq S^*) \ge 1 - \alpha. The proof is one line: S∗S^* satisfies the null, so is rejected only with probability ≤α\le \alpha, and if not rejected the intersection is contained in it. ICP is conservative by construction (few environments or weak interventions return a small or empty set) and traverses 2p2^p subsets, so it works only with few observed variables. For images, where causal factors are latent, a representation must be learned.

IRM: one classifier optimal in every environment

With squared loss or cross-entropy, the optimal classifier is the conditional expectation, and the condition is equivalent to E[Ye∣Φ(Xe)=h]\E[Y^e \given \Phi(X^e) = h] not depending on ee. Arjovsky et al. illustrate this with example 1, the model of the interactive below:

X1∼N(0,σ2),Y=X1+N(0,σ2),X2=Y+N(0,1),X_1 \sim \Normal(0, \sigma^2), \qquad Y = X_1 + \Normal(0, \sigma^2), \qquad X_2 = Y + \Normal(0, 1),

with two training environments σ2=10\sigma^2 = 10 and σ2=20\sigma^2 = 20. X1X_1 causes YY and X2X_2 is an effect. Regressing YY on X1X_1 gives coefficient 1 in both environments: it is invariant. Regressing on (X1,X2)(X_1, X_2) gives (1/(σ2+1), σ2/(σ2+1))\big(1/(\sigma^2 + 1),\ \sigma^2/(\sigma^2 + 1)\big), which depends on environment: X2X_2 predicts better, but its relation to YY is unstable. The invariant predictor Y=X1Y = X_1 is the only one with bounded risk in all environments intervening on X2X_2.

The IRM constraint is a bilevel problem. The practical relaxation has two steps. First, since w∘Φ=(w∘Ψ−1)∘(Ψ∘Φ)w \circ \Phi = (w \circ \Psi^{-1}) \circ (\Psi \circ \Phi) for any bijection Ψ\Psi, the classifier can be fixed: Arjovsky et al. prove (theorem 4) that for linear predictors a fixed scalar classifier w=1.0w = 1.0 suffices, and a vector vv can be written as an invariant predictor if and only if v⊤∇Re(v)=0v\T\grad R^e(v) = 0 in every environment. Second, optimality of w=1.0w = 1.0 in each environment is measured with the squared derivative:

IRMv1:min⁡Φ  ∑e∈EtrRe(Φ)+λ ∥∇w ∣ w=1.0Re(w⋅Φ)∥2.\textbf{IRMv1:}\qquad \min_\Phi\; \sum_{e \in \mathcal{E}_{\text{tr}}} R^e(\Phi) + \lambda\,\big\|\grad_{w \,|\, w = 1.0} R^e(w \cdot \Phi)\big\|^2.

In example 1 everything is calculable by hand. With Φ(x)=α1x1+α2x2\Phi(\vb{x}) = \alpha_1x_1 + \alpha_2x_2, Σe=Ee[XX⊤]\mat{\Sigma}_e = \E_e[\vb{X}\vb{X}\T], and ce=Ee[XY]\vb{c}_e = \E_e[\vb{X}Y], risk is Re(α)=2σe2−2α⊤ce+α⊤ΣeαR^e(\alpha) = 2\sigma_e^2 - 2\alpha\T\vb{c}_e + \alpha\T\mat{\Sigma}_e\alpha and the derivative with respect to scale is

Ge(α)= ⁣d ⁣dwRe(w α)∣w=1=2(α⊤Σeα−α⊤ce),Σe=[σe2σe2σe22σe2+1],ce=[σe22σe2].G_e(\alpha) = \frac{\dd}{\dd w} R^e(w\,\alpha)\Big|_{w = 1} = 2\big(\alpha\T\mat{\Sigma}_e\alpha - \alpha\T\vb{c}_e\big), \qquad \mat{\Sigma}_e = \begin{bmatrix}\sigma_e^2 & \sigma_e^2 \\ \sigma_e^2 & 2\sigma_e^2 + 1\end{bmatrix},\quad \vb{c}_e = \begin{bmatrix}\sigma_e^2 \\ 2\sigma_e^2\end{bmatrix}.

Each condition Ge(α)=0G_e(\alpha) = 0 is an ellipse passing through the origin and that environment’s least-squares regression. The zero set of penalty ∑eGe2\sum_e G_e^2 is the intersection of the ellipses.

InteractiveThe IRMv1 penalty landscape
  • zeros of G1G_1 (environment 1)
  • zeros of G2G_2 (environment 2)
  • invariant (1,0)(1, 0); hollow: degenerate (0,0)(0, 0)
  • ERM
  • IRMv1 minimum and its path as λ\lambda varies
  • gradient descent
On α2=0\alpha_2 = 0 the penalty vanishes at α1=0\alpha_1 = 0 and α1=1\alpha_1 = 1, with a hump between: it is not convex.
Heatmap (log scale)
λ = 10^2.00
1
4
Penalty slice
ERM (pooled least squares)(0.286, 0.714) · risk 1.43
Invariant (1,0)(1, 0)risk 5.00 · penalty 0
Global IRMv1 minimum at this λ\lambda(0.931, 0.199)
Gradient descent (2000 steps)(−0.272, 0.159), near the degenerate solution
The ellipses intersect only at the origin (degenerate) and the invariant (1,0)(1, 0), where they are tangent: the penalty therefore grows as α24\alpha_2^4 in the spurious direction and the IRMv1 minimum retains α2=0.199\alpha_2 = 0.199 with λ=102.0\lambda = 10^{2.0}.
Arjovsky et al. example 1 with two environments (σ12=1\sigma_1^2 = 1 and σ22=4\sigma_2^2 = 4 initially; the paper uses 10 and 20). The heatmap shows log⁡10\log_{10} of penalty ∑eGe(α)2\sum_e G_e(\alpha)^2 or the full IRMv1 objective; orange and aqua curves are ellipses G1=0G_1 = 0 and G2=0G_2 = 0. Points: invariant (1,0)(1, 0), degenerate (0,0)(0, 0) (hollow), ERM optimum, and global IRMv1 minimum for the selected λ\lambda, with its path as λ\lambda varies from 10−210^{-2} to 10510^5 (dashed). The draggable blue point is the result of 2000 gradient-descent steps on IRMv1. Right: penalty along a slice.

With the paper’s values σ2=10\sigma^2 = 10 and 2020, the ellipses nearly coincide (for large σ2\sigma^2, equation Ge=0G_e = 0 barely depends on σ2\sigma^2); the interactive starts with σ12=1\sigma_1^2 = 1 and σ22=4\sigma_2^2 = 4, which separates them, and following numbers use those values. Subtracting the two equations shows that if σ12≠σ22\sigma_1^2 \neq \sigma_2^2, they intersect only where α2=0\alpha_2 = 0 and α1∈{0,1}\alpha_1 \in \{0, 1\}. The landscape shows three defects of the relaxation.

  • Degenerate solutions and nonconvexity. α=0\alpha = 0 zeros the penalty in any problem: the constant predictor is trivially invariant. On slice α2=0\alpha_2 = 0 the penalty is ∑e4σe4 α12(α1−1)2\sum_e 4\sigma_e^4\,\alpha_1^2(\alpha_1 - 1)^2, with zeros at 00 and 11 and a hump between them (height 4.254.25 with σ2=1\sigma^2 = 1 and 44): it is not convex, as the authors warn. The full objective has another local minimum besides the global one that is not invariant: with λ=102\lambda = 10^2 it is at (−0.24,0.14)(-0.24, 0.14) and with λ=103\lambda = 10^3 at (0.12,−0.06)(0.12, -0.06), progressively closer to the origin. Drag the gradient-descent output to the upper-left quadrant and it ends there instead of at the invariant.
  • A flat penalty exactly where it matters. In this example ∇Ge(1,0)=2(2Σeα−ce)=(2σe2,0)\grad G_e(1, 0) = 2(2\mat{\Sigma}_e\alpha - \vb{c}_e) = (2\sigma_e^2, 0) for all environments: ellipses are tangent to each other and line α1=1\alpha_1 = 1 at the invariant. Thus along α1=1\alpha_1 = 1, Ge(1,α2)=2(2σe2+1)α22G_e(1, \alpha_2) = 2(2\sigma_e^2 + 1)\alpha_2^2 and penalty grows as α24\alpha_2^4, while risk grows linearly away from the ERM optimum. The IRMv1 minimum approaches the invariant very slowly: its spurious weight is α2≈0.099\alpha_2 \approx 0.099, 0.0470.047, and 0.0220.022 with λ=103\lambda = 10^3, 10410^4, and 10510^5, a factor near 101/3≈2.1510^{1/3} \approx 2.15 per decade, the λ−1/3\lambda^{-1/3} scale from balancing an order-1 term with an λα23\lambda\alpha_2^3 term in the first-order condition. This is what you saw in the first figure with small Δ\Delta.
  • Without variation across environments there is no signal. Set σ12=σ22\sigma_1^2 = \sigma_2^2: the ellipses coincide, the penalty vanishes on an entire curve containing the ERM optimum, and IRMv1 returns ERM.

In Colored MNIST, Arjovsky et al.’s experiment, the binary label (digit below 5 or not) is flipped with probability 0.25 and color matches the label except with probability 0.20.2 and 0.10.1 in the two training environments and 0.90.9 in test. ERM achieves 87.4 %87.4\,\% in training and 17.1 %17.1\,\% in test because it classifies by color; IRM achieves 70.8 %70.8\,\% and 66.9 %66.9\,\%; the hypothetical optimal invariant model achieves 75 %75\,\% on both (table 1). This result made IRM popular, and the next section explains why it has not transferred to real benchmarks.

The risks of IRM

Rosenfeld, Ravikumar, and Risteski (2021) analyze IRM in a latent-variable model: y=±1y = \pm 1, invariant features zc∼N(yμc,σc2I)z_c \sim \Normal(y\mu_c, \sigma_c^2\mat{I}) in Rdc\R^{d_c} with fixed parameters, environment features ze∼N(yμe,σe2I)z_e \sim \Normal(y\mu_e, \sigma_e^2\mat{I}) in Rde\R^{d_e} with mean and variance changing by environment, and observation x=f(zc,ze)x = f(z_c, z_e) with injective ff. Their results concern classification with logistic loss:

  • Linear case: a threshold on environment count (theorem 5.1). If E>deE > d_e, any linear IRM-feasible representation discards environment features (under nondegeneracy conditions) and the predictor is optimal invariant. If E≤deE \le d_e and environment means are linearly independent, a feasible representation exists using environment features (with rank de+1−Ed_e + 1 - E in that part) and has lower logistic and 0–1 risk than the invariant in training environments: IRM prefers it. You need more environments than spurious dimensions, and in images ded_e is enormous.
  • Nonlinear case: failure even with many environments (theorem 6.1). They construct a representation which, with the ERM classifier on top, has IRMv1 penalty exponentially small in ded_e, agrees with the optimal invariant predictor on nearly all training data and with ERM elsewhere. In a test environment whose spurious-feature mean is sufficiently far from training means, it behaves like ERM on nearly all points, and if spurious correlation reverses, accuracy is nearly 0. The issue is not environment or data count: the penalty controls only behavior near training data. They conclude IRM and alternatives fundamentally do not improve on ERM unless training environments “cover” test environments, in which case ERM or DRO would work too.

ICP has guarantees because it tests hypotheses about observed variables; IRM loses them when learning a representation with a soft penalty. This is the distance between the causal idea, which is correct, and its practical relaxation.

Empirical evidence: DomainBed, WILDS, and accuracy on the line

DomainBed: model selection decides

Gulrajani and Lopez-Paz (2021) reimplement nine domain-generalization algorithms (ERM, IRM, group DRO, Mixup, MLDG, CORAL, MMD, DANN, and C-DANN) on seven datasets with the same architectures (ResNet-50, except a small CNN for two MNIST variants), same augmentation, and same random hyperparameter-search budget (20 configurations per algorithm and test domain), requiring hyperparameter selection to be declared. They compare three criteria:

  1. Training-domain validation: hold out part of each training domain and choose the model with best accuracy on combined validation.
  2. Leave-one-domain-out cross-validation: train leaving each training domain out in turn and choose what works best on the held-out domain.
  3. Test-domain validation (oracle): choose using test-domain data, limited to 20 queries per algorithm and no early stopping. The authors call this invalid for comparing methods because it uses the target.

With the first criterion (their table 4, arXiv version), mean out-of-domain accuracy is 67.0 %67.0\,\% for ERM, 66.0 %66.0\,\% for IRM, 65.5 %65.5\,\% for group DRO, and 67.2 %67.2\,\% for CORAL, the best: no method improves ERM’s mean by more than one point. The decisive detail is in Colored MNIST. With training-domain validation, ERM achieves 10.0 %10.0\,\% and IRM 10.1 %10.1\,\% in the test domain; with oracle selection ERM gets 30.0 %30.0\,\% and IRM 65.2 %65.2\,\%. IRM’s advantage in Arjovsky et al.’s table appears only when choosing hyperparameters by looking at the test domain, because training data contain no signal preferring the invariant solution over the one using color. The authors attribute their ERM’s strength to four factors: a larger network, strong augmentation, careful hyperparameter tuning, and in Rotated MNIST using all training data instead of a 1000-image subset.

WILDS: real shifts, little help from methods

WILDS (Koh et al. 2021) assembles ten datasets with real distribution shifts and compares ERM with CORAL, IRM, and group DRO (table 2). On Camelyon17, ERM obtains 70.3 %70.3\,\% out of distribution, CORAL 59.559.5, IRM 64.264.2, and group DRO 68.468.4; on iWildCam (macro F1), ERM 31.031.0, CORAL 32.832.8, IRM 15.115.1, and group DRO 23.923.9. The exception is CivilComments, a subpopulation shift with known groups, where worst group rises from 56.0 %56.0\,\% with ERM to 70.0 %70.0\,\% with group DRO, still far from mean 92.2 %92.2\,\%. This matches the preceding discussion: methods using group information help when deployment remixes known groups; none has shown general help against new domains.

Accuracy on the line

If specialized methods barely improve ERM, what predicts out-of-distribution accuracy? Miller et al. (2021) train more than 3000 models (from nearest neighbors and kernel machines to high-performing convolutional networks), evaluate them on distribution pairs (D,D′)(D, D'), and find a surprising regularity.

The probit scale matters: accuracy lies in [0,1][0, 1] and can follow a straight line only on a bounded range, whereas Φ−1\Phi^{-1} maps [0,1][0, 1] onto all R\R; Miller et al. observe much more precise trends with probit (or logit) than linear axes. For CIFAR-10 versus CIFAR-10.1 (Recht et al.’s 2018 test-set reproduction, 2000 new images collected by the same procedure, where models lose 4–10 points), the fit with 1060 models has R2=0.995R^2 = 0.995; with CIFAR-10.2, 0.9970.997 (their table 1). The line persists across architecture, hyperparameters, training-set size, and training duration.

Exceptions are equally instructive. In several synthetic CIFAR-10-C corruptions correlation is weak, especially with isotropic Gaussian noise. On Camelyon17, models with 95 %95\,\% in distribution range from 50 %50\,\% (chance) to 95 %95\,\% outside: there is no line. And pretraining changes the relationship in some cases but not others: fine-tuned ImageNet-pretrained models stay on the same line on CIFAR-10.2 and FMoW but change the trend on iWildCam, and zero-shot models (CLIP) depart from the CIFAR-10.2 line. Miller et al. also propose a Gaussian model where shift changes data covariance: for linear classifiers independent of the shift’s random direction, probit accuracies have an approximately linear relationship with deviation of order d−1/2d^{-1/2} in dimension.

Lab: accuracy on the line on the GPU

The lab reproduces the experiment on a small scale. It trains a population of CIFAR-10 classifiers (linear, one-hidden-layer perceptrons, and three-stage CNNs of widths 8 to 64), varying training size and epochs, plus four interventions: crop-and-flip augmentation, Gaussian-noise augmentation, group DRO using ten classes as groups, and an ImageNet-pretrained ResNet18 fine-tuned on images enlarged to 64×6464\times 64. Each model is evaluated on CIFAR-10 test, CIFAR-10.1 v6 (downloaded from Recht et al.’s repository at a pinned version), and three corruptions generated by the cell on test: Gaussian noise with standard deviation 0.080.08, Gaussian blur of σ=1\sigma = 1 pixel, and contrast reduced to 30 %30\,\%. It then fits the probit line on baseline models and measures each model’s effective robustness. It uses the PyTorch training loop, nn.Module, and optimizer API, with all data on GPU and mixed precision.

The full configuration (28 baseline configurations with two seeds each, 20 interventions, up to 50,000 images and 30 epochs) is the one for you to run; ORYON_VERIFY_SHORT=1 runs a short version checking the flow end to end. The cell is not run in automated checks due to duration.

[ ]Accuracy on the line with a population of CIFAR-10 modelsLocal GPU
"""Accuracy on the line con una población de modelos entrenados en CIFAR-10.

Se entrena una población de clasificadores (lineal, MLP y CNN de anchura k) con distintos tamaños de entrenamiento,
épocas y semillas, y cuatro intervenciones: aumento de datos (recorte y volteo), aumento con ruido gaussiano,
preentrenamiento en ImageNet (ResNet18 ajustada) y group DRO con las clases como grupos. Cada modelo se evalúa en el
test de CIFAR-10 (en distribución), en CIFAR-10.1 v6 (cambio natural, Recht et al. 2018) y en tres corrupciones
sintéticas generadas aquí sobre el test de CIFAR-10. Después se ajusta, para cada conjunto fuera de distribución,
la recta probit(OOD) = a + b * probit(ID) con los modelos de base (sin intervención) y se mide la robustez efectiva
de cada modelo: su exactitud OOD menos la que predice la recta.

ORYON_VERIFY_SHORT=1 ejecuta una versión corta (menos modelos, datos y épocas) que comprueba el flujo.
"""
import io as _io
import json
import math
import os
import time
import urllib.request
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from PIL import Image
from scipy.stats import norm
from torch import nn
from torchvision.models import resnet18, ResNet18_Weights

SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
OUT = Path(os.environ.get('ORYON_AOTL_OUTPUT', 'accuracy-on-the-line.json'))
CACHE = Path.home() / '.cache' / 'oryon-learn' / 'cifar10.1'
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.backends.cudnn.benchmark = True

# ---------------------------------------------------------------- datos
def load_cifar(split):
    """CIFAR-10 desde la caché de Hugging Face (uoft-cs/cifar10, versión fijada), como uint8 N x 3 x 32 x 32."""
    path = hf_hub_download('uoft-cs/cifar10', f'plain_text/{split}-00000-of-00001.parquet', repo_type='dataset',
                           revision='0b2714987fa478483af9968de7c934580d0bb9a2')
    t = pq.read_table(path)
    X = np.stack([np.array(Image.open(_io.BytesIO(d['bytes'])).convert('RGB')) for d in t.column('img').to_pylist()])
    return torch.tensor(X).permute(0, 3, 1, 2).contiguous(), torch.tensor(t.column('label').to_numpy())


def load_cifar101():
    """CIFAR-10.1 v6 (2000 imágenes), del repositorio de Recht et al. en una versión fijada; se guarda en caché."""
    base = 'https://raw.githubusercontent.com/modestyachts/CIFAR-10.1/d9982abb0bfc4846b8d13a11e66b887d946205d0/datasets/'
    CACHE.mkdir(parents=True, exist_ok=True)
    arrs = []
    for name in ('cifar10.1_v6_data.npy', 'cifar10.1_v6_labels.npy'):
        f = CACHE / name
        if not f.exists():
            urllib.request.urlretrieve(base + name, f)
        arrs.append(np.load(f))
    X, y = arrs
    return torch.tensor(X).permute(0, 3, 1, 2).contiguous(), torch.tensor(y.astype(np.int64))


Xtr_all, ytr_all = load_cifar('train')
Xte, yte = load_cifar('test')
X101, y101 = load_cifar101()
print(f'CIFAR-10: {len(Xtr_all)} de entrenamiento, {len(Xte)} de test; CIFAR-10.1 v6: {len(X101)} imágenes')

MEAN = torch.tensor([0.4914, 0.4822, 0.4465]).view(1, 3, 1, 1)
STD = torch.tensor([0.2470, 0.2435, 0.2616]).view(1, 3, 1, 1)


def corrupt(X, kind, gen):
    """Corrupciones sintéticas sobre imágenes en [0, 1] (versiones propias, en el espíritu de CIFAR-10-C)."""
    if kind == 'ruido':
        return (X + 0.08 * torch.randn(X.shape, generator=gen)).clamp(0, 1)
    if kind == 'desenfoque':
        r = torch.arange(-2, 3, dtype=torch.float32)
        k = torch.exp(-r ** 2 / (2 * 1.0 ** 2))
        k = (k / k.sum()).view(1, 1, 1, 5)
        Y = F.conv2d(F.pad(X, (2, 2, 0, 0), mode='reflect'), k.repeat(3, 1, 1, 1), groups=3)
        return F.conv2d(F.pad(Y, (0, 0, 2, 2), mode='reflect'), k.transpose(2, 3).repeat(3, 1, 1, 1), groups=3)
    if kind == 'contraste':
        m = X.mean(dim=(1, 2, 3), keepdim=True)
        return (m + 0.3 * (X - m)).clamp(0, 1)
    raise ValueError(kind)


gen = torch.Generator().manual_seed(0)
Xte_f = Xte.float() / 255
EVAL = {'id': (Xte_f, yte), 'cifar10.1': (X101.float() / 255, y101)}
for kind in ('ruido', 'desenfoque', 'contraste'):
    EVAL[kind] = (corrupt(Xte_f, kind, gen), yte)
EVAL = {k: (((v[0] - MEAN) / STD).half().to(device), v[1].to(device)) for k, v in EVAL.items()}
del Xte_f

# ---------------------------------------------------------------- modelos
class CNN(nn.Module):
    """Tres etapas conv-BN-ReLU (anchuras k, 2k, 4k) con max-pooling y una lineal tras el promedio global."""
    def __init__(self, k):
        super().__init__()
        def block(ci, co):
            return [nn.Conv2d(ci, co, 3, padding=1, bias=False), nn.BatchNorm2d(co), nn.ReLU(inplace=True)]
        self.f = nn.Sequential(*block(3, k), *block(k, k), nn.MaxPool2d(2), *block(k, 2 * k), nn.MaxPool2d(2),
                               *block(2 * k, 4 * k), nn.MaxPool2d(2), nn.AdaptiveAvgPool2d(1), nn.Flatten())
        self.head = nn.Linear(4 * k, 10)

    def forward(self, x):
        return self.head(self.f(x))


class Pretrained(nn.Module):
    """ResNet18 preentrenada en ImageNet; las imágenes se amplían a 64 x 64 y se cambia la capa final."""
    def __init__(self):
        super().__init__()
        self.net = resnet18(weights=ResNet18_Weights.IMAGENET1K_V1)
        self.net.fc = nn.Linear(512, 10)

    def forward(self, x):
        return self.net(F.interpolate(x, size=64, mode='bilinear', align_corners=False))


def make(arch):
    if arch == 'lineal':
        return nn.Sequential(nn.Flatten(), nn.Linear(3 * 32 * 32, 10))
    if arch == 'mlp':
        return nn.Sequential(nn.Flatten(), nn.Linear(3 * 32 * 32, 512), nn.ReLU(), nn.Linear(512, 10))
    if arch == 'resnet18-in':
        return Pretrained()
    return CNN(int(arch[3:]))


def augment(x, kind, g):
    """Aumento en la GPU: recorte aleatorio con relleno de 4 píxeles y volteo horizontal; o ruido gaussiano."""
    n = x.shape[0]
    if kind == 'ruido':   # ruido gaussiano de la misma intensidad que la corrupción, en la mitad de cada lote
        sd = (0.08 / STD).to(x.device)
        half = (torch.rand(n, device=x.device, generator=g) < 0.5).view(n, 1, 1, 1)
        return x + half * sd * torch.randn(x.shape, device=x.device, generator=g)
    flip = torch.rand(n, device=x.device, generator=g) < 0.5
    x = torch.where(flip.view(n, 1, 1, 1), x.flip(3), x)
    xp = F.pad(x, (4, 4, 4, 4))
    dx = torch.randint(0, 9, (n,), device=x.device, generator=g)
    dy = torch.randint(0, 9, (n,), device=x.device, generator=g)
    ar = torch.arange(32, device=x.device)
    rows = (dy.view(n, 1) + ar).view(n, 1, 32, 1)
    cols = (dx.view(n, 1) + ar).view(n, 1, 1, 32)
    return xp[torch.arange(n, device=x.device).view(n, 1, 1, 1), torch.arange(3, device=x.device).view(1, 3, 1, 1), rows, cols]


@torch.no_grad()
def accuracy(model, X, y):
    model.eval()
    hits = 0
    for i in range(0, len(X), 1000):
        with torch.autocast('cuda', dtype=torch.bfloat16, enabled=device.type == 'cuda'):
            hits += (model(X[i:i + 1000].float()).argmax(1) == y[i:i + 1000]).sum().item()
    model.train()
    return hits / len(X)


def train(cfg):
    """Entrena un modelo con SGD con momento y tasa en coseno; cfg fija arquitectura, n, épocas, semilla e intervención."""
    torch.manual_seed(cfg['seed'])
    g = torch.Generator(device=device).manual_seed(cfg['seed'])
    idx = torch.randperm(len(Xtr_all), generator=torch.Generator().manual_seed(cfg['seed']))[:cfg['n']]
    X = ((Xtr_all[idx].float() / 255 - MEAN) / STD).half().to(device)
    y = ytr_all[idx].to(device)
    model = make(cfg['arch']).to(device).to(memory_format=torch.channels_last)
    lr = 0.01 if cfg['arch'] == 'resnet18-in' else (0.02 if cfg['arch'] in ('lineal', 'mlp') else 0.05)
    opt = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9, nesterov=True, weight_decay=5e-4)
    B = 256
    steps = cfg['epochs'] * math.ceil(cfg['n'] / B)
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=steps, pct_start=0.15)
    q = torch.full((10,), 0.1, device=device)       # pesos de grupo de group DRO (grupos = clases)
    for ep in range(cfg['epochs']):
        perm = torch.randperm(cfg['n'], device=device, generator=g)
        for i in range(0, cfg['n'], B):
            b = perm[i:i + B]
            xb = X[b].float()
            if cfg['interv'] in ('aumento', 'ruido'):
                xb = augment(xb, 'ruido' if cfg['interv'] == 'ruido' else 'crop', g)
            with torch.autocast('cuda', dtype=torch.bfloat16, enabled=device.type == 'cuda'):
                losses = F.cross_entropy(model(xb), y[b], reduction='none').float()
            if cfg['interv'] == 'groupdro':
                # pérdida media de cada clase en el lote; gradiente exponenciado sobre q (Sagawa et al., algoritmo 1)
                cnt = torch.bincount(y[b], minlength=10).float()
                lg = torch.zeros(10, device=device).index_add_(0, y[b], losses.detach()) / cnt.clamp(min=1)
                q = q * torch.exp(0.01 * lg * (cnt > 0))
                q = q / q.sum()
                loss = (q[y[b]] * losses / cnt[y[b]]).sum()
            else:
                loss = losses.mean()
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step()
            sched.step()
    res = {k: accuracy(model, *v) for k, v in EVAL.items()}
    del model, opt, X
    if device.type == 'cuda':
        torch.cuda.empty_cache()
    return res


# ---------------------------------------------------------------- población
def grid():
    rng = np.random.default_rng(1)
    if SHORT:
        base = [('lineal', 10000, 10), ('mlp', 10000, 10), ('mlp', 25000, 15)]
        base += [(f'cnn{k}', n, e) for k in (8, 16, 32, 64) for n, e in ((5000, 6), (20000, 10))]
        base += [('cnn64', 50000, 10), ('cnn32', 5000, 2), ('cnn16', 2000, 4), ('cnn8', 20000, 3)]
        interv = [(f'cnn{k}', 20000, e, 'aumento') for k, e in ((16, 10), (32, 10), (32, 20))]
        interv += [(f'cnn{k}', 20000, 10, t) for k in (16, 32) for t in ('ruido', 'groupdro')]
        interv += [('resnet18-in', n, 3, 'preentrenada') for n in (5000, 20000)]
        seeds = [0]
    else:
        base = [('lineal', n, 20) for n in (10000, 50000)] + [('mlp', n, e) for n, e in ((10000, 20), (50000, 30))]
        base += [(f'cnn{k}', n, e) for k in (8, 16, 32, 64) for n, e in ((2500, 10), (5000, 15), (10000, 20), (25000, 25), (50000, 30))]
        base += [(f'cnn{k}', 50000, e) for k in (16, 64) for e in (2, 5)]
        interv = [(f'cnn{k}', n, 30, t) for k in (16, 32, 64) for n in (10000, 50000) for t in ('aumento', 'ruido', 'groupdro')]
        interv += [('resnet18-in', n, e, 'preentrenada') for n, e in ((10000, 5), (50000, 5))]
        seeds = [0, 1]
    cfgs = [dict(arch=a, n=n, epochs=e, interv='ninguna', seed=s) for a, n, e in base for s in seeds]
    cfgs += [dict(arch=a, n=n, epochs=e, interv=t, seed=0) for a, n, e, t in interv]
    return cfgs


runs = []
t0 = time.time()
for cfg in grid():
    acc = train(cfg)
    runs.append({**cfg, 'acc': acc})
    print(f"{cfg['arch']:>11} n={cfg['n']:5d} ép={cfg['epochs']:2d} {cfg['interv']:>12}  "
          + '  '.join(f'{k} {v:.3f}' for k, v in acc.items()) + f'  [{time.time() - t0:.0f} s]', flush=True)

# ---------------------------------------------------------------- rectas en escala probit
def probit(p, n):
    """Φ⁻¹ de una exactitud, recortada a [0.5/n, 1 - 0.5/n] para que sea finita."""
    return norm.ppf(np.clip(p, 0.5 / n, 1 - 0.5 / n))

n_id = len(EVAL['id'][1])
POPS = {'todos': lambda r: True, 'cnn': lambda r: r['arch'].startswith('cnn')}   # población de referencia
fits = {}
for pop, keep in POPS.items():
    base_runs = [r for r in runs if r['interv'] == 'ninguna' and keep(r)]
    x = np.array([probit(r['acc']['id'], n_id) for r in base_runs])
    for k in EVAL:
        if k == 'id':
            continue
        nk = len(EVAL[k][1])
        yk = np.array([probit(r['acc'][k], nk) for r in base_runs])
        b, a = np.polyfit(x, yk, 1)
        r2 = 1 - ((yk - (a + b * x)) ** 2).sum() / ((yk - yk.mean()) ** 2).sum()
        fits.setdefault(pop, {})[k] = {'a': float(a), 'b': float(b), 'r2': float(r2)}
        print(f'[{pop:>5}, {len(base_runs):2d} modelos] recta probit para {k:>10}: OOD = {a:+.3f} {b:+.3f}·ID   R² = {r2:.3f}')
        for r in runs:   # robustez efectiva: exactitud OOD menos la que predice la recta
            pred = norm.cdf(a + b * probit(r['acc']['id'], n_id))
            r.setdefault('eff', {}).setdefault(pop, {})[k] = float(r['acc'][k] - pred)

print('robustez efectiva media por intervención frente a la recta de las CNN (puntos de exactitud OOD):')
for t in ('ninguna', 'aumento', 'ruido', 'groupdro', 'preentrenada'):
    rs = [r for r in runs if r['interv'] == t and (t != 'ninguna' or r['arch'].startswith('cnn'))]
    if rs:
        print(f'  {t:>12} ({len(rs):2d} modelos): ' + '  '.join(
            f"{k} {100 * np.mean([r['eff']['cnn'][k] for r in rs]):+.1f}" for k in fits['cnn']))
OUT.write_text(json.dumps({'short': SHORT, 'fits': fits, 'runs': runs}), encoding='utf-8')
print('guardado en', OUT)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The figure shows real output of the short run: 15 baseline models with one seed (up to 50,000 images and 10 epochs) and 9 interventions. It is a small run, one model per configuration, and should be read as such.

InteractiveIs your model on the line?
Horizontal: CIFAR-10 test accuracy (%)Vertical: accuracy on CIFAR-10.1 (natural shift) (%)
  • baseline CNNs
  • linear and MLP (squares)
  • fitted line
  • diagonal (no loss)
  • Gaussian noise augmentation
Line fitted with
Probit line: Φ−1(OOD)=a+b Φ−1(ID)\Phi^{-1}(\text{OOD}) = a + b\,\Phi^{-1}(\text{ID})a = −0.280, b = 0.832
R2R^2 of fit (probit scale)0.994
Effective robustness of each highlighted model (points)−0.5 · 0.1
Gaussian noise augmentation lies on the line (mean effective robustness −0.2 points): out-of-distribution gains are explained by in-distribution gains.
Actual output of the short lab run (ORYON_VERIFY_SHORT=1). Each point is a model: CIFAR-10 test accuracy (horizontal) versus accuracy on the selected OOD dataset (vertical), on probit scales with percentage ticks. Gray: baseline models (squares: linear and MLP); colors: interventions, with rings on the highlighted one. The line is fitted by the cell using baseline models (the 12 CNNs or all 15 models). Turn off probit scaling to see why it is needed.

Results. On CIFAR-10.1 the line is almost perfect: for the 12 baseline CNNs, Φ−1(acc10.1)=−0.280+0.832 Φ−1(acc10)\Phi^{-1}(\text{acc}_{10.1}) = -0.280 + 0.832\,\Phi^{-1}(\text{acc}_{10}) with R2=0.994R^2 = 0.994, and for all 15 models (including linear and MLP), R2=0.993R^2 = 0.993, on the order of Miller et al.’s 0.9950.995 with a thousand models. Models lose 6–14 points (for example, the widest CNN with 50,000 images drops from 82.882.8 to 71.3 %71.3\,\%). No intervention departs from the line beyond statistical noise (with 2000 images, standard error for accuracy 70 %70\,\% is one point): augmentation gets −0.2-0.2, 0.20.2, and 0.00.0 points of effective robustness, noise augmentation −0.5-0.5 and 0.10.1, group DRO over classes −1.9-1.9 and −0.7-0.7, and pretrained ResNet18, by far the best model (86.0 %86.0\,\% in distribution), 1.71.7 and 1.31.3: its OOD advantage is almost entirely predicted by its in-distribution advantage, as Miller et al. found when fine-tuning pretrained models on CIFAR-10.2.

For synthetic corruptions there is no single line. With 15 baseline models, R2=0.17R^2 = 0.17 (noise), 0.210.21 (blur), and 0.360.36 (contrast). The cause is linear and MLP models: they are worse in distribution but almost insensitive to noise and blur (the MLP with 25,000 images goes from 52.2 %52.2\,\% to 51.2 %51.2\,\% with noise and 53.3 %53.3\,\% with blur), while CNNs lose enormously (the widest CNN with 50,000 images falls to 44.2 %44.2\,\% with noise). Restricting the line to CNNs, blur does follow a line (R2=0.965R^2 = 0.965), contrast approximately (0.8750.875), but noise does not (0.480.48), like Miller et al.’s Gaussian-noise exception. Effective robustness does appear here: training with Gaussian noise in half of each batch gives 23.323.3 and 27.927.9 points above the line on noise, at the cost of 2.42.4 in-distribution points for the width-16 CNN (65.365.3 versus 67.7 %67.7\,\%), and does not improve CIFAR-10.1. Pretrained ResNet18 also lies above the CNN line for all three corruptions (between 3.43.4 and 14.214.2 points depending on model and corruption), although this run cannot separate pretraining from a different architecture seeing images enlarged to 64×6464\times 64; recall Miller et al. also find pretraining changes the relation for some shifts (iWildCam) but not others (CIFAR-10.2). An intervention targeted at a corruption buys robustness to that corruption; none of the nine buys effective robustness to the unknown natural shift CIFAR-10.1.

When well-tuned ERM suffices

Putting the pieces together yields a decision guide:

  • If you do not know deployment conditions, the best documented bet is improving in-distribution accuracy with standard techniques (more data, larger models, pretraining, augmentation, hyperparameter tuning with training-domain validation). For shifts following the line, each in-distribution point translates to a predictable fraction outside, and DomainBed and WILDS find no method consistently exceeding this.
  • If you know the groups that matter and deployment remixes them, measure the worst group and use group DRO (or retrain the last layer on a balanced set), always with strong regularization or early stopping chosen by group validation.
  • If you know the transformation (sensor noise, compression, blur), augment with it: that intervention does leave the line, but only for that transformation.
  • If you have environments with genuinely distinct mechanisms and few observed variables, ICP gives guarantees; IRM and its variants do not in the nonlinear regime, and their empirical advantage depends on model selection.
  • Always check whether your shift follows the line with a model population and labeled out-of-distribution set: if it does, effective robustness is the number to inspect, not raw OOD accuracy; if it does not (Camelyon17 is an example), no in-distribution accuracy protects you.

The same ideas recur elsewhere: domain randomization to close the robotics simulation-to-reality gap augments training environments until deployment is covered; CVaR portfolio optimization applies this lesson’s DRO to returns; and out-of-distribution detection and corruption robustness complete the picture from the reliability side.

Common mistakes

Exercises

ProofCVaR is DRO with bounded likelihood ratio
Prove: Let ℓ\ell be an integrable random variable with distribution PP and α∈(0,1]\alpha \in (0, 1]. Then inf⁡η∈R{η+EP[(ℓ−η)+]/α}=sup⁡{EQ[ℓ]:Q≪P,  ⁣dQ/ ⁣dP≤1/α}\inf_{\eta \in \R}\{\eta + \E_P[(\ell - \eta)_+]/\alpha\} = \sup\{\E_Q[\ell] : Q \ll P,\ \dd Q/\dd P \le 1/\alpha\}, and both are attained.
0
Write L= ⁣dQ/ ⁣dPL = \dd Q/\dd P, so the right side is the supremum of EP[Lℓ]\E_P[L\ell] over measurable functions with 0≤L≤1/α0 \le L \le 1/\alpha and EP[L]=1\E_P[L] = 1. Call the infimum II and supremum SS.

Step 1 of 4. How do you prove S≤IS \le I?

NumericCVaR by hand
Ten equally likely points have losses 0,0,0,0,0,0,0,0,1,30, 0, 0, 0, 0, 0, 0, 0, 1, 3. Calculate CVaR0.2\text{CVaR}_{0.2}.
NumericThe χ² ball with four losses
Four equally likely points have losses 1,2,3,61, 2, 3, 6. Calculate the worst case sup⁡14∑iwiℓi\sup \frac14\sum_i w_i\ell_i over the ball {w≥0:wˉ=1, 14∑i12(wi−1)2≤1/8}\{w \ge 0 : \bar w = 1,\ \frac14\sum_i \frac12(w_i - 1)^2 \le 1/8\}.
QuizWhat the ball cannot see
You train a skin-lesion classifier with DRO over a large-radius KL ball around the empirical distribution. All images are from dermatoscopes made by two manufacturers. Phone photos absent from the data appear at deployment. What does training guarantee about them?
QuizGroup DRO that does nothing
You train a ResNet50 on Waterbirds with group DRO and standard regularization for 300 epochs. The worst test group is nearly the same as with ERM. What explains this and what do you change?
NumericThe IRMv1 penalty at a point
In Arjovsky et al.’s example 1 with σ2=10\sigma^2 = 10, calculate the environment’s IRMv1 penalty, G(α)2G(\alpha)^2 with G(α)= ⁣d ⁣dwR(wα)∣w=1G(\alpha) = \frac{\dd}{\dd w}R(w\alpha)\big|_{w = 1}, at α=(0.5,0.5)\alpha = (0.5, 0.5).
QuizWhen IRM fails in the nonlinear regime
According to Rosenfeld, Ravikumar, and Risteski (2021), when can IRM fail in the nonlinear regime?
QuizThe detail that decides DomainBed
Gulrajani and Lopez-Paz find well-tuned ERM matches almost all domain-generalization methods. Which protocol detail is decisive for this conclusion?
QuizRobust or merely better?
A new method increases a model’s CIFAR-10 test accuracy from 70 %70\,\% to 80 %80\,\% and CIFAR-10.1 accuracy from 56 %56\,\% to 66 %66\,\% (2000 images). Baseline CNNs follow the probit line Φ−1(acc10.1)=−0.28+0.83 Φ−1(acc10)\Phi^{-1}(\text{acc}_{10.1}) = -0.28 + 0.83\,\Phi^{-1}(\text{acc}_{10}). Another method raises the same model to 72 %72\,\% on CIFAR-10 and 63 %63\,\% on CIFAR-10.1. What do you conclude?
CodeA stable group DRO step
Implement group_dro_step(losses_by_group, q, eta_q), taking mean losses for each group in the current batch (an array of length mm, with np.nan for absent groups), current weights q (positive, summing to 1), and rate eta_q, and returning (q_nuevo, perdida) (new weights, loss): weights after an exponentiated-gradient step, qg←qgeηqLg/∑g′qg′eηqLg′q_g \leftarrow q_g e^{\eta_q L_g}/\sum_{g'}q_{g'}e^{\eta_q L_{g'}}, and weighted loss ∑gqgnuevoLg\sum_g q^{\text{nuevo}}_g L_g over present groups, which is backpropagated. Absent groups are not updated (their LgL_g counts as 0 in the exponent). Compute stably: losses in the thousands with ηq=1\eta_q = 1 must not produce nan or inf.
import numpy as np

def group_dro_step(losses_by_group, q, eta_q):
  """Un paso de gradiente exponenciado sobre q. Devuelve (q_nuevo, pérdida ponderada)."""
  L = np.asarray(losses_by_group, dtype=float)
  q = np.asarray(q, dtype=float)
  # tu código: actualiza q en espacio logarítmico, normaliza y pondera las pérdidas presentes
  return q, float(np.nanmean(L))
Shift+Enter to run

Summary

Key idea
Out-of-distribution generalization minimizes worst-case risk over a set of environments and is impossible without an assumption about that set. Each method makes a different assumption: DRO assumes deployment is a nearby reweighting of data, group DRO a remix of known groups, IRM a mechanism invariant across environments, and accuracy on the line a shift resembling those already observed.
  • ff-divergence DRO has a two-scalar dual. CVaR is DRO with likelihood ratio bounded by 1/α1/\alpha, the mean loss of the worst subpopulation of mass α\alpha; the χ2\chi^2 ball equals the mean plus 2r\sqrt{2r} standard deviations while no weight vanishes. These balls only reweight data: they do not protect outside support. Wasserstein balls move mass and connect with norm regularization and adversarial training.
  • Group DRO minimizes the worst group with exponentiated-gradient updates to group weights. In interpolating models it does nothing without strong regularization or early stopping; with it, Waterbirds’ worst group rises from 21.3 %21.3\,\% to 84.6 %84.6\,\%. Retraining only the last layer with balanced data achieves comparable results.
  • Spurious correlations are learned because they are predictive, simple, and cheap to interpolate. Diagnose them outside the training distribution with groups or environments where the correlation breaks.
  • ICP has coverage guarantees with observed variables. IRMv1 relaxes IRM with a derivative penalty on a fixed classifier, which vanishes at degenerate solutions, is nonconvex, may be flat near the invariant, and is uninformative if environments resemble each other. Rosenfeld et al. prove the linear case needs more environments than spurious dimensions and the nonlinear case can fail against any distant test.
  • In DomainBed and WILDS, well-tuned ERM matches specialized methods when hyperparameters are chosen without looking at the target. For many natural shifts OOD accuracy follows a probit-scale line against in-distribution accuracy; effective robustness, distance from that line, measures whether an intervention adds something. In your lab, CIFAR-10.1 follows the line with R2=0.994R^2 = 0.994 and no intervention departs from it; noise augmentation lies far above, but only for noise.