optora.dro.minibatch¶
Minibatch estimators of the worst-case expected loss under a population nominal.
Every optora.core.AmbiguitySet evaluates the worst case over a ball around a
fixed, finite nominal. In stochastic training the nominal is instead an
unknown population distribution \(P_0\) seen only through minibatches of
i.i.d. samples, and the plug-in estimate, the worst case over the ball around
the empirical distribution \(\hat P_m\) of one minibatch,
is a biased estimate of the population worst case \(V\). The supremum is a nonlinear functional of the sample, so \(\mathbb{E}[\hat V_m] \neq V\) and the gradient of \(\hat V_m\) is not an unbiased stochastic gradient of \(V\) (Levy, Carmon, Duchi, and Sidford 2020). For KL-DRO the plug-in is a log-sum-exp of the minibatch losses at the optimal temperature.
This module provides the two standard remedies.
MultilevelMonteCarloEstimatorkeeps the exact plug-in solve of any ambiguity set, or of the penalized objectiveoptora.dro.PenalizedChiSquareDRO, and removes its bias up to the largest batch size by randomized multilevel Monte Carlo (Blanchet and Glynn 2015; Levy et al. 2020). The expected batch size grows only logarithmically in that largest batch size.StochasticPhiDualkeeps the dual variables of a phi-divergence ball as learnable parameters, which turns the worst case into a plain expectation over \(P_0\) whose minibatch mean is exactly unbiased (Ben-Tal et al. 2013; Levy et al. 2020; Jin, Zhang, Wang, and Wang 2021).
MultilevelMonteCarloEstimator
¶
Bases: Module
Randomized multilevel Monte Carlo estimator of a minibatch worst case.
Let \(\hat V_m\) be the plug-in worst case of an ambiguity set centered on the uniform distribution over \(m\) i.i.d. samples. Its bias shrinks as \(m\) grows, but evaluating a large \(m\) on every step is what minibatching avoids. With a base batch size \(n_0\) and a maximum level \(L\), draw a level \(J \in \{1, \dots, L\}\) with probability \(p_J \propto 2^{-J}\), draw \(n_0 2^J\) samples \(S\), split them into halves \(S^{(1)}, S^{(2)}\), and report
Each term has the distribution of a plug-in estimate on that many i.i.d. samples, so the expectation telescopes,
and the same holds for the gradient, since every term is differentiated
at its own maximizer (Danskin). The estimator therefore has the bias of
a batch of \(n_0 2^L\) samples at an expected batch size of
\(n_0 L / (1 - 2^{-L})\) (Blanchet and Glynn 2015; Levy et al. 2020). The
antithetic halves keep its variance bounded as \(L\) grows. The
correction is the gap between one solve and the mean of two solves on
the same samples, which vanishes as the plug-in converges. With
max_level=0 there is no correction and the estimator is the plain
plug-in on \(n_0\) samples. The same construction applies to the
penalized chi-square objective optora.dro.PenalizedChiSquareDRO,
which is also a nonlinear functional of the sample and which Levy et
al. (2020) estimate this way.
In a training loop the batch size is drawn anew at every step.
estimator = MultilevelMonteCarloEstimator(
functools.partial(KLAmbiguitySet, radius=0.1),
base_batch_size=32,
max_level=4,
)
batch_size = estimator.sample_batch_size()
loss = per_sample_loss(model, next_batch(batch_size))
estimator(loss).backward()
Attributes:
| Name | Type | Description |
|---|---|---|
ambiguity_sets |
One ambiguity set, or penalized objective, per
level |
|
base_batch_size |
Number of samples \(n_0\) of the base level. |
|
max_level |
Largest level \(L\). The bias is that of a batch of
|
expected_batch_size
property
¶
Mean number of samples a step draws, \(n_0 L / (1 - 2^{-L})\) for \(L > 0\).
__init__(ambiguity_set_factory, base_batch_size, max_level, device=None, dtype=None)
¶
Initialize the estimator and build one ambiguity set per level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ambiguity_set_factory
|
Callable[[Tensor], AmbiguitySet | PenalizedChiSquareDRO]
|
Map from a nominal distribution to the
ambiguity set centered on it, for example
|
required |
base_batch_size
|
int
|
Number of samples \(n_0\) of the base level, at least one. |
required |
max_level
|
int
|
Largest level \(L\), at least zero. |
required |
device
|
device | str | None
|
Device of the uniform nominals, the current default
device when |
None
|
dtype
|
dtype | None
|
Dtype of the uniform nominals, the default dtype when
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
sample_batch_size(generator=None)
¶
Draw the batch size \(n_0 2^J\) of the next step.
The level is drawn on the CPU, so drawing it never waits on an accelerator. The data pipeline needs the returned size on the host in any case.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
generator
|
Generator | None
|
CPU random number generator to draw the level with, for reproducible runs. Defaults to PyTorch's global one. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
|
int
|
|
int
|
|
forward(loss)
¶
Estimate the worst-case expected loss from one multilevel batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss
|
Tensor
|
Per-sample losses of shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
The multilevel estimate, of the batch shape the levels return |
Tensor
|
for a |
Tensor
|
its gradient are those of the plug-in value on |
Tensor
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
StochasticPhiDual
¶
Bases: Module
Phi-DRO dual objective with learnable dual variables, unbiased on minibatches.
The worst case over a phi-divergence ball around a population \(P_0\) has the convex dual (Ben-Tal et al. 2013; Duchi and Namkoong 2021)
an expectation over \(P_0\) for fixed \((\eta, \lambda)\). Minimizing it
jointly with the model parameters \(\theta\) therefore needs only
unbiased estimates of that expectation, and the minibatch mean is one.
forward is linear in the empirical distribution, so its expectation
over a minibatch, and that of its gradient with respect to \(\theta\),
\(\log \eta\), and \(\lambda\), is the population dual exactly. This is the
dual stochastic-gradient approach to large-scale phi-DRO (Levy et al.
2020; Jin et al. 2021, who analyze it for non-convex losses).
At any \((\eta, \lambda)\) the population dual bounds the worst case from
above (weak duality), with equality at the joint minimizer. The dual
variables are nn.Parameters, so they train with the model.
dual = StochasticPhiDual(radius=0.1, phi_conjugate=kl_conjugate)
optimizer = torch.optim.Adam([*model.parameters(), *dual.parameters()])
dual(per_sample_loss(model, batch)).backward()
optimizer.step()
Use optora.dro.kl_conjugate for KL. It is \(\phi^*(s) = e^s - 1\)
continued along its tangent past a quarter of the dtype's exponent
range, so a loss spike that \(\lambda\) has not caught up with gives a
large, finite objective and gradient. torch.expm1 would instead give
inf and then nan dual variables. The chi-square conjugate is
optora.dro.chi_square_conjugate. The price of unbiasedness is that
\((\eta, \lambda)\) are reached by stochastic optimization rather than
solved per batch. A conjugate that grows exponentially, as KL's does,
makes the objective's variance sensitive to \(\lambda\) trailing the loss
scale, and nothing here standardizes the loss, since a per-batch shift
or scale would reintroduce the bias. Start the dual variables on the
scale of the loss. A reliable start is the exact dual optimum of a
pilot minibatch at the initial model, found by minimizing this module
on that batch alone. The defaults
initial_log_eta=0 and initial_lam=0 can stall training under KL.
Attributes:
| Name | Type | Description |
|---|---|---|
radius |
float | Tensor
|
Nonnegative phi-divergence radius \(\rho\), a float or a tensor of radii, each with its own dual variables. |
phi_conjugate |
Convex conjugate \(\phi^*\) of the generator restricted to \(t \ge 0\), finite on the real line. |
|
log_eta |
Learnable \(\log \eta\), of |
|
lam |
Learnable \(\lambda\), in the units of the loss, of |
__init__(radius, phi_conjugate, initial_log_eta=0.0, initial_lam=0.0)
¶
Initialize the stochastic dual and its dual variables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
float | Tensor
|
Nonnegative phi-divergence radius. A tensor radius is
registered as a buffer and gives every entry its own
|
required |
phi_conjugate
|
Callable[[Tensor], Tensor]
|
Convex conjugate of the generator restricted to
\(t \ge 0\), finite on the real line, for example
|
required |
initial_log_eta
|
float
|
Starting value of |
0.0
|
initial_lam
|
float
|
Starting value of |
0.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
forward(loss)
¶
Evaluate the dual objective on a minibatch of per-sample losses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss
|
Tensor
|
Per-sample losses of shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
$\eta \rho + \lambda + \eta \cdot \frac{1}{m} \sum_i |
Tensor
|
\phi^*((\ell_i - \lambda) / \eta)$ per batch element, computed in |
Tensor
|
|
Tensor
|
promoted dtype of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |