Skip to content
Edit this page View source of this page

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,

\[ \hat V_m = \sup_{q:\, D(q \,\|\, \hat P_m) \,\le\, \rho} \mathbb{E}_q[\ell], \]

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.

  • MultilevelMonteCarloEstimator keeps the exact plug-in solve of any ambiguity set, or of the penalized objective optora.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.
  • StochasticPhiDual keeps 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

\[ \hat V = \hat V_{n_0}(S_{1:n_0}) + \frac{1}{p_J}\Big(\hat V_{n_0 2^J}(S) - \tfrac{1}{2}\big(\hat V_{n_0 2^{J-1}}(S^{(1)}) + \hat V_{n_0 2^{J-1}}(S^{(2)})\big)\Big). \]

Each term has the distribution of a plug-in estimate on that many i.i.d. samples, so the expectation telescopes,

\[ \mathbb{E}[\hat V] = \mathbb{E}[\hat V_{n_0}] + \sum_{j=1}^{L} \big(\mathbb{E}[\hat V_{n_0 2^j}] - \mathbb{E}[\hat V_{n_0 2^{j-1}}]\big) = \mathbb{E}[\hat V_{n_0 2^L}], \]

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 j = 0, ..., max_level, centered on the uniform distribution over base_batch_size * 2 ** j samples. Registered as submodules, so .to(...) moves and casts every level together.

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 base_batch_size * 2 ** max_level samples.

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 functools.partial(KLAmbiguitySet, radius=0.1). It is called once per level with a uniform nominal on device in dtype. Any set whose construction depends only on the nominal qualifies, such as the KL, chi-square, total-variation, CVaR, and general phi sets. The Wasserstein, Sinkhorn, and MMD sets also need a ground cost or a Gram matrix over the samples and do not qualify. The factory may instead return a PenalizedChiSquareDRO, for example functools.partial(PenalizedChiSquareDRO, penalty=0.5), whose value is then estimated in place of a worst case.

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.

None
dtype dtype | None

Dtype of the uniform nominals, the default dtype when None. Build in the dtype the set will run in rather than casting afterwards, since 1 / m rounded to float32 and cast to float64 is not the float64 uniform distribution.

None

Raises:

Type Description
ValueError

If base_batch_size is less than one or max_level is negative.

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

base_batch_size * 2 ** J for a level J drawn from

int

{1, ..., max_level} with probability proportional to

int

2 ** -J, or base_batch_size when max_level is zero.

forward(loss)

Estimate the worst-case expected loss from one multilevel batch.

Parameters:

Name Type Description Default
loss Tensor

Per-sample losses of shape (..., m) for m i.i.d. samples, where m is a size sample_batch_size can return. The level is read off m. Leading dimensions are independent batches, broadcast against a tensor radius or penalty as in AmbiguitySet.worst_case_expectation.

required

Returns:

Type Description
Tensor

The multilevel estimate, of the batch shape the levels return

Tensor

for a (..., m) loss. Its expectation and the expectation of

Tensor

its gradient are those of the plug-in value on

Tensor

base_batch_size * 2 ** max_level samples.

Raises:

Type Description
ValueError

If loss is zero-dimensional or its trailing size is not one sample_batch_size can return.

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)

\[ \sup_{q:\, D_\phi(q \,\|\, P_0) \,\le\, \rho} \mathbb{E}_q[\ell] = \inf_{\eta > 0,\, \lambda \in \mathbb{R}} \mathbb{E}_{X \sim P_0}\!\left[\eta \rho + \lambda + \eta\, \phi^*\!\left(\frac{\ell(X) - \lambda}{\eta}\right)\right], \]

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 radius's shape.

lam

Learnable \(\lambda\), in the units of the loss, of radius's shape.

__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 log_eta and lam, in its dtype and on its device, so a radius sweep trains in one module.

required
phi_conjugate Callable[[Tensor], Tensor]

Convex conjugate of the generator restricted to \(t \ge 0\), finite on the real line, for example optora.dro.kl_conjugate for KL.

required
initial_log_eta float

Starting value of log_eta.

0.0
initial_lam float

Starting value of lam, in the units of the loss.

0.0

Raises:

Type Description
ValueError

If radius is a negative or nan float, or either initial value is not finite.

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 (..., m) for m i.i.d. samples. Leading dimensions are independent batches, broadcast against radius's 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

optora.core.working_dtype(loss, log_eta) and returned in the

Tensor

promoted dtype of loss and log_eta.

Raises:

Type Description
ValueError

If loss is zero-dimensional.