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
- 13Dataset shift taxonomyDomain adaptation boundImportance weightingLimits of invariant representationsRegularized loss minimizationImplicit regularization (implicit bias)
- 06Dual problem and weak dualityStrong duality and Slater's conditionGradient descent-ascent
- 07f-divergences
- 27Structural causal modelCausal Markov condition and truncated factorization
- 00Canonical training and evaluation loopnn.ModulePyTorch optimizer API
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 in seen hospitals and in a new hospital; in iWildCam (camera-trap photographs) macro F1 falls from to on unseen cameras; in CivilComments, worst-demographic-group accuracy is when the mean is .
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.
Three things the figure shows and the rest of the lesson formalizes:
- ERM makes no mistake: it does exactly what you ask. With , the spurious feature predicts the label better than the causal one (the sign of is correct of the time, , versus for the sign of , which is ), so the average-risk minimizer uses it heavily: its weight on is comparable to that on . In the minority group, where , the spurious feature pushes the wrong way, and in the test environment, where correlation reverses, the model falls below .
- Extra information is needed to avoid it. Group DRO receives group labels 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 from : both are predictive.
- That information must be informative. Move to zero: the two environments are identical, IRMv1’s penalty vanishes at the ERM solution, and IRMv1 returns ERM. Even with , 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 and predictor class . Each environment is a distribution over and its risk is . Training environments are observed; deployment environments form an unseen set .
Without assumptions on the problem has no solution, and the argument is as short as for the No Free Lunch theorem.
Proof
At each , , so is wrong under exactly one of the two distributions: . Integrating with over gives , and the maximum of two numbers is at least their mean. Training data cannot distinguish from : any algorithm produces the same under both.
∎If deployment puts half its mass outside training support, no method gets below worst-case error. It is not necessary to leave support: if permits freely changing inside , the same argument works with all of . The theory in this lesson consists of choosing a restriction on that is both credible and sufficient:
| Deployment assumption | Method | Requirements |
|---|---|---|
| It is near the training distribution (in -divergence or Wasserstein) | DRO | a radius |
| It is a mixture of known groups in arbitrary proportions | Group DRO | training group labels |
| It shares a mechanism with all environments | ICP, IRM | multiple training environments |
| It behaves like observed shifts | Accuracy on the line | a 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 -divergences
For the sample, assigns probability to each point and is conveniently written with likelihood ratio , so is , , and . The adversary chooses weights and you choose : this is a min–max problem.
The ball only reweights what you have seen. For KL, or CVaR, if puts mass where does not (in all three, when , penalizing singular mass), and the usual formulation (Duchi and Namkoong, equation 3) directly optimizes over . With the empirical distribution, lives on the sample’s points. -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 is linear in with convex constraints, and its dual is a problem in two scalars.
Proof
The inequality is weak duality and is proved in one line. For admissible , , and ,
because the two subtracted terms are and . Inside the expectation, pointwise if . Taking supremum over and infimum over gives . Equality is strong duality: satisfies 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 , convex if is convex in : 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
Take if and otherwise. Constraint says only : the adversary can multiply any point’s probability by at most . The conjugate is , positively homogeneous, so for every and term goes to zero. This gives the Rockafellar–Uryasev formula:
The infimum is attained at quantile of (VaR) and the supremum at placing density on the tail. Duchi and Namkoong read it this way: if , then , and conversely; the uncertainty set contains all subpopulations of mass at least , 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 ball: mean plus standard deviation
With the ball is , and the adversary has an explicit solution.
Proof
Write , valid because . By the Cauchy–Schwarz inequality with product ,
Equality in Cauchy–Schwarz requires proportional to with positive constant, and equality in the constraint requires it to be active: . Those weights have mean 1 and divergence exactly , and are admissible if and only if all are , the condition on . Otherwise the maximum is strictly smaller: optimal weights (by KKT conditions) are and zero out the smallest losses.
∎With radius scaling as , equality says : 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 ), the robust objective is convex if 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.
Notice three things. Below 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 three more ways (closed form, primal solved by SLSQP, and the theorem’s dual with Nelder–Mead), with radii on both sides of .
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 ball, primal and dual always agree (strong duality), and formula agrees with them for and , while with it overestimates them ( versus ): exactly as the theorem predicts.
Wasserstein DRO as a concept
-divergence balls do not move mass to new places; Wasserstein balls do. With transport cost , ball contains distributions moving each point slightly, and its worst case answers: how much does loss worsen if each example can move an average distance ?
For with and loss -Lipschitz in , Kantorovich–Rubinstein duality immediately gives , so
In logistic regression with and transport only on (labels do not move), the Lipschitz constant in is , 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 : norm regularization is robustness against input shifts.
If instead of the constraint its Lagrangian relaxation with multiplier is used, the inner problem is a per-example attack:
This is Sinha, Namkoong, and Duchi’s (2018) formulation: training against Wasserstein worst case is training with distance-penalized adversarial examples, with guarantees when 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 with distributions , the natural uncertainty set is mixtures .
Optimizing 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 and one descent step on , an instance of gradient descent–ascent:
The highest-loss group gains weight multiplicatively. Their proposition 2 gives, for nonnegative convex losses bounded by and -Lipschitz on a parameter set of radius , with a randomly selected group per step, expected error of the average iterate in the min–max problem at most : the usual 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; training images, only 56 waterbirds on land), standard-regularization models interpolate: both ERM and group DRO reach 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 and group DRO’s at ; in CelebA both are (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, ERM | Worst test group, group DRO |
|---|---|---|
| Waterbirds, standard regularization | 60.0 % | 76.9 % |
| Waterbirds, strong () | 21.3 % | 84.6 % |
| Waterbirds, early stopping | 6.7 % | 86.0 % |
| CelebA, strong () | 37.8 % | 86.7 % |
| CelebA, early stopping | 25.0 % | 88.3 % |
With penalty four orders of magnitude above usual ( versus ), no model interpolates, ERM sacrifices the minority ( worst-training-group accuracy on Waterbirds), and group DRO protects it (); 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 for ERM, for reweighting, and for group DRO. Another adjustment, adding to each group’s loss to compensate for poorer small-group generalization, raises Waterbirds worst group from to (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 (, majority , core features a hundred times noisier than spurious), best worst-group test error, , is achieved by an underparameterized model, while highly overparameterized ones plateau around .
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 to , and CelebA’s from to (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: , the spurious attribute matches the label in of examples, the core feature is and the spurious feature , much cleaner. There are four groups , two majority and two minority. You implement logistic regression by gradient descent with three objectives: ERM, group reweighting (each group weighs ), and online group DRO with the exponentiated step above. A test set balanced across all four groups evaluates the worst group.
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 (, ) and its worst group stays at on test; reweighting and group DRO almost zero the spurious weight ( and ) and raise the worst group to and , near for the core-only classifier. The cost appears in the training-distribution mean: for ERM versus 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.
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 () all three methods fit of every training group, and on test the worst group is (ERM), (reweighting), and (group DRO): a small improvement, because once every group is fitted the worst-group objective no longer distinguishes solutions, and spurious weight stays large ( for group DRO). The minority has been memorized using noise features that do not generalize. With no method interpolates; ERM sacrifices the minority ( for worst training group and on test), while reweighting and group DRO reduce spurious weight to and and reach and 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 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.
- 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.
- 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).
- 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 , the structural equation of 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 and coefficients with support such that, in every environment ,
with the same noise distribution in every environment and arbitrarily distributed. If are the parents of in the structural model, the assumption holds.
Invariant causal prediction (ICP) tests, for each variable subset , the null hypothesis that satisfies invariance, and returns the intersection of nonrejected sets, . Their theorem 1 gives coverage: if each test has level , then . The proof is one line: satisfies the null, so is rejected only with probability , 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 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 not depending on . Arjovsky et al. illustrate this with example 1, the model of the interactive below:
with two training environments and . causes and is an effect. Regressing on gives coefficient 1 in both environments: it is invariant. Regressing on gives , which depends on environment: predicts better, but its relation to is unstable. The invariant predictor is the only one with bounded risk in all environments intervening on .
The IRM constraint is a bilevel problem. The practical relaxation has two steps. First, since for any bijection , the classifier can be fixed: Arjovsky et al. prove (theorem 4) that for linear predictors a fixed scalar classifier suffices, and a vector can be written as an invariant predictor if and only if in every environment. Second, optimality of in each environment is measured with the squared derivative:
In example 1 everything is calculable by hand. With , , and , risk is and the derivative with respect to scale is
Each condition is an ellipse passing through the origin and that environment’s least-squares regression. The zero set of penalty is the intersection of the ellipses.
With the paper’s values and , the ellipses nearly coincide (for large , equation barely depends on ); the interactive starts with and , which separates them, and following numbers use those values. Subtracting the two equations shows that if , they intersect only where and . The landscape shows three defects of the relaxation.
- Degenerate solutions and nonconvexity. zeros the penalty in any problem: the constant predictor is trivially invariant. On slice the penalty is , with zeros at and and a hump between them (height with and ): it is not convex, as the authors warn. The full objective has another local minimum besides the global one that is not invariant: with it is at and with at , 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 for all environments: ellipses are tangent to each other and line at the invariant. Thus along , and penalty grows as , while risk grows linearly away from the ERM optimum. The IRMv1 minimum approaches the invariant very slowly: its spurious weight is , , and with , , and , a factor near per decade, the scale from balancing an order-1 term with an term in the first-order condition. This is what you saw in the first figure with small .
- Without variation across environments there is no signal. Set : 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 and in the two training environments and in test. ERM achieves in training and in test because it classifies by color; IRM achieves and ; the hypothetical optimal invariant model achieves 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: , invariant features in with fixed parameters, environment features in with mean and variance changing by environment, and observation with injective . Their results concern classification with logistic loss:
- Linear case: a threshold on environment count (theorem 5.1). If , any linear IRM-feasible representation discards environment features (under nondegeneracy conditions) and the predictor is optimal invariant. If and environment means are linearly independent, a feasible representation exists using environment features (with rank 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 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 , 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:
- Training-domain validation: hold out part of each training domain and choose the model with best accuracy on combined validation.
- Leave-one-domain-out cross-validation: train leaving each training domain out in turn and choose what works best on the held-out domain.
- 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 for ERM, for IRM, for group DRO, and 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 and IRM in the test domain; with oracle selection ERM gets and IRM . 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 out of distribution, CORAL , IRM , and group DRO ; on iWildCam (macro F1), ERM , CORAL , IRM , and group DRO . The exception is CivilComments, a subpopulation shift with known groups, where worst group rises from with ERM to with group DRO, still far from mean . 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 , and find a surprising regularity.
The probit scale matters: accuracy lies in and can follow a straight line only on a bounded range, whereas maps onto all ; 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 ; with CIFAR-10.2, (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 in distribution range from (chance) to 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 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 . 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 , Gaussian blur of pixel, and contrast reduced to . 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 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)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.
Results. On CIFAR-10.1 the line is almost perfect: for the 12 baseline CNNs, with , and for all 15 models (including linear and MLP), , on the order of Miller et al.’s with a thousand models. Models lose 6–14 points (for example, the widest CNN with 50,000 images drops from to ). No intervention departs from the line beyond statistical noise (with 2000 images, standard error for accuracy is one point): augmentation gets , , and points of effective robustness, noise augmentation and , group DRO over classes and , and pretrained ResNet18, by far the best model ( in distribution), and : 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, (noise), (blur), and (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 to with noise and with blur), while CNNs lose enormously (the widest CNN with 50,000 images falls to with noise). Restricting the line to CNNs, blur does follow a line (), contrast approximately (), but noise does not (), like Miller et al.’s Gaussian-noise exception. Effective robustness does appear here: training with Gaussian noise in half of each batch gives and points above the line on noise, at the cost of in-distribution points for the width-16 CNN ( versus ), and does not improve CIFAR-10.1. Pretrained ResNet18 also lies above the CNN line for all three corruptions (between and points depending on model and corruption), although this run cannot separate pretraining from a different architecture seeing images enlarged to ; 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
Step 1 of 4. How do you prove ?
group_dro_step(losses_by_group, q, eta_q), taking mean losses for each group in the current batch (an array of length , 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, , and weighted loss over present groups, which is backpropagated. Absent groups are not updated (their counts as 0 in the exponent). Compute stably: losses in the thousands with 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))Summary
- -divergence DRO has a two-scalar dual. CVaR is DRO with likelihood ratio bounded by , the mean loss of the worst subpopulation of mass ; the ball equals the mean plus 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 to . 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 and no intervention departs from it; noise augmentation lies far above, but only for noise.