optora.core.dro_base¶
Shared contract for ambiguity sets used by DRO formulations.
AmbiguitySet
¶
Bases: Module, ABC
Set of distributions within a bounded divergence of a nominal distribution.
An ambiguity set pairs a Divergence with a radius. Every distribution
q inside the set satisfies divergence(q, nominal) <= radius. Modules
in optora.dro subclass AmbiguitySet to implement the inner
maximization of the DRO minimax problem for a specific divergence
geometry (for example KL, a general phi-divergence, or Wasserstein).
Inherits from torch.nn.Module (rather than a plain ABC) so nominal
is registered as a buffer and divergence as a submodule. A single
.to(device)/.cuda() call then moves the nominal distribution and any
tensor state the divergence holds (for example SinkhornDivergence's
ground-cost matrix) together, and both surface through state_dict().
Every subclass follows the numerical policy below. Precision and
validation are handled by _prepare_loss and _as_result.
- Precision. The worst case is computed in
optora.core.working_dtype(loss, nominal), so half-precision losses or a half-precision set are solved in float32, and the result is returned intorch.promote_types(loss.dtype, nominal.dtype). - Non-finite losses. A
nanor infinite loss entry makes the corresponding batch element of the result non-finite (nan, or the infinite value itself), never a finite number. Other batch elements are unaffected. - Validation. Metadata checks (shapes, a negative or
nanfloat radius) always run. Checks that read tensor values back to the host run only withvalidate=True, in the spirit oftorch.distributions'validate_args. - Gradients. The worst case is differentiable in
lossby Danskin's theorem, and to first order innominaland a tensorradiusby the envelope theorem (_attach_parameter_gradients). Only the derivative along directions that keepnominalsumming to one is defined.
Attributes:
| Name | Type | Description |
|---|---|---|
nominal |
Tensor
|
Reference distribution the ambiguity set is centered on, a nonnegative tensor that sums to one along its last dimension. |
divergence |
Divergence used to measure distance from |
|
radius |
float | Tensor
|
Nonnegative bound on the divergence of any distribution
inside the ambiguity set from |
validate |
Whether the value checks that synchronize with the device
run. They cover |
__init__(nominal, divergence, radius, validate=False)
¶
Initialize the ambiguity set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nominal
|
Tensor
|
Reference distribution the ambiguity set is centered on. |
required |
divergence
|
Divergence
|
Divergence used to measure distance from |
required |
radius
|
float | Tensor
|
Nonnegative bound on the divergence of any distribution
inside the ambiguity set from |
required |
validate
|
bool
|
Whether to run the value checks that synchronize with
the device. These check that |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
contains(candidate)
¶
Check whether a candidate distribution lies inside the ambiguity set.
The answer is returned as a boolean tensor on candidate's device
rather than as a Python bool, so membership can be used as a mask
or composed with further tensor work without forcing a
device-to-host synchronization. Call bool(...) on the result only
where a host-side branch is genuinely needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
candidate
|
Tensor
|
Candidate distribution with the same shape as
|
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A boolean tensor that is |
Tensor
|
|
worst_case_expectation(loss)
abstractmethod
¶
Compute the worst-case expected loss over the ambiguity set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss
|
Tensor
|
Per-scenario loss values of shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A tensor of shape |
Tensor
|
worst-case expected loss attainable by any distribution inside |
Tensor
|
the ambiguity set. An unbatched |
TiltedAmbiguitySet
¶
Bases: AmbiguitySet
Ambiguity set whose worst case is a tilt of the nominal, located by bisection.
For the divergence balls whose inner supremum has a known maximizer shape, the worst-case distribution is a one-parameter tilt of the nominal, that is, a family \(q_t\) with \(q_0 = \mathrm{nominal}\) along which the divergence \(D(q_t \,\|\, \mathrm{nominal})\) increases monotonically from \(0\) to the divergence of the distribution concentrated on the highest-loss scenarios. KL-DRO tilts exponentially, \(q \propto \mathrm{nominal} \cdot e^{\beta\,\mathrm{loss}}\), and chi-square-DRO tilts linearly, \(q \propto \mathrm{nominal} \cdot (\mathrm{loss} - c)_+\). Both forms follow from the KKT conditions of the primal problem (Hu and Hong 2013; Ben-Tal et al. 2013; Duchi and Namkoong 2021).
Because the divergence along the path is monotone, the constraint \(D(q_t \,\|\, \mathrm{nominal}) \le \mathrm{radius}\) pins the tilt by a bracketed scalar root solve rather than by minimizing a convex dual. This class implements that solve once for every such formulation, with the properties below.
- A guaranteed bracket. The tilt is parameterized by \(t \in [0, 1)\), a bounded reparameterization of the unbounded natural parameter (the inverse multiplier \(1/\eta\)). The bracket \([0, 1]\) is valid for every loss and every radius by construction, so bisection cannot fail to make progress the way an unconstrained first-order dual solve can when the minimizer runs off to infinity.
- A fixed, synchronization-free trip count. The resolution is read
off the dtype by
_bisection_steps, so the solve is a fixed number of device-side kernels with no host read of a convergence flag. A small problem, whose cost is kernel launches rather than arithmetic, evaluates up to 15 tilts per step in one batched call and so needs a quarter of the steps (_search_bits). A large one bisects. What counts as small depends on the device, since a GPU absorbs far more work per kernel launch than a CPU. - Feasibility by construction. Each step keeps the endpoint that
tested feasible, so the returned tilt always satisfies the radius
constraint. The reported value is therefore a primal objective value
at a feasible distribution. It can never exceed \(\max \mathrm{loss}\),
and it is
nan-free whatever the support size or loss scale. - Saturation without a special case. Once
radiusreaches the divergence of the distribution concentrated on the highest-loss scenarios, every tilt is feasible, bisection drives \(t\) to the top of the bracket, and \(q_t\) is that distribution, so the value is exactly \(\max \mathrm{loss}\).
A subclass whose root has a closed form overrides _solve_tilt and
keeps the rest, as optora.dro.ChiSquareAmbiguitySet does.
The tilt is computed on the loss standardized to unit spread,
\((\max \ell - \ell) / (\max \ell - \min \ell)\). An ambiguity set does
not depend on loss, so a positive affine rescaling of the loss leaves
the maximizer unchanged. Standardizing only keeps the tilt parameter
and the divergence well conditioned on a loss of any scale or offset.
The maximum and minimum are taken over the reachable scenarios only
(_reachable). By default these are the support of the nominal. A
subclass that tilts another base distribution uses that distribution's
support instead, as optora.dro.SinkhornAmbiguitySet does with its
reference measure, which also moves the path's start off the nominal
(_center_expectation). With the default, every tilt
is a reweighting \(q \propto \mathrm{nominal} \cdot w\), so a
scenario with zero nominal mass is unreachable whatever its loss, and
letting its loss set the scale would both misreport the saturated value
as that unreachable loss and leave no zero gap on the support for the
tilt to concentrate on. Such scenarios are given the largest gap, 1,
which keeps every intermediate of the tilt finite while their weight
stays exactly zero.
The worst-case expectation is reported as
\(\sum_i q^\star_i \,\mathrm{loss}_i\) with \(q^\star\) detached. By
Danskin's theorem the gradient of \(\sup_{q \in \mathcal{U}}
\mathbb{E}_q[\mathrm{loss}]\) with respect to loss is exactly the
maximizer \(q^\star\), so detaching the tilt costs no accuracy in the
backward pass while keeping the bisection itself out of the autograd
graph.
The tilt path is solved on a detached nominal, and the first
derivatives with respect to nominal and a tensor radius are
attached afterwards by the envelope theorem, from the multiplier
\(\lambda^\star\) that each subclass reads off its solved tilt in closed
form (_standardized_sensitivities).
Second derivatives are exact as well, in every pair of loss,
nominal, and radius. A recorded backward pass (create_graph=True,
torch.func.hessian) rebuilds the solved tilt as a function of all
three by one implicit-function step (_implicit_solution), and from it
\(q^\star\) and the two envelope derivatives, so differentiating the
gradient yields their exact Jacobians rather than the zero detached
constants would give. A plain .backward() never pays for that step.
Where the worst case is not differentiable (tied highest losses once
the radius saturates the set) the gradient is the maximizer that splits
the tied mass in proportion to nominal, a subgradient of the convex
worst case.
Attributes:
| Name | Type | Description |
|---|---|---|
nominal |
Tensor
|
Reference distribution the ambiguity set is centered on. |
divergence |
Divergence used to measure distance from |
|
radius |
float | Tensor
|
Nonnegative bound on the divergence of any distribution
inside the ambiguity set from |
worst_case_expectation(loss)
¶
Compute the worst-case expected loss at the tilt pinned by radius.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss
|
Tensor
|
Per-scenario loss values of shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A tensor of shape |
Tensor
|
When |
Tensor
|
the start of the tilt path ( |
Tensor
|
|
Tensor
|
expectation of |
Tensor
|
the search returned, which equals the largest reachable loss |
Tensor
|
once the radius saturates the set. |
Tensor
|
The expectation is accumulated as a correction to |
Tensor
|
rather than directly. Every term of |
Tensor
|
|
Tensor
|
never round to above |
Tensor
|
spread around a large offset keeps the precision of its spread |
Tensor
|
instead of losing it to the offset. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
__init__(nominal, divergence, radius, validate=False)
¶
Initialize the ambiguity set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nominal
|
Tensor
|
Reference distribution the ambiguity set is centered on. |
required |
divergence
|
Divergence
|
Divergence used to measure distance from |
required |
radius
|
float | Tensor
|
Nonnegative bound on the divergence of any distribution
inside the ambiguity set from |
required |
validate
|
bool
|
Whether to run the value checks that synchronize with
the device. These check that |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
contains(candidate)
¶
Check whether a candidate distribution lies inside the ambiguity set.
The answer is returned as a boolean tensor on candidate's device
rather than as a Python bool, so membership can be used as a mask
or composed with further tensor work without forcing a
device-to-host synchronization. Call bool(...) on the result only
where a host-side branch is genuinely needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
candidate
|
Tensor
|
Candidate distribution with the same shape as
|
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A boolean tensor that is |
Tensor
|
|
DualAmbiguitySet
¶
Bases: AmbiguitySet
Ambiguity set whose worst-case expectation is a low-dimensional dual solve.
Every divergence-based ambiguity set that reformulates its inner
supremum as a convex dual minimization over a handful of dual variables
(optora.dro.PhiAmbiguitySet over \((\log(\eta), \lambda)\)) runs the
same machinery around a formulation-specific dual objective, and this
class holds that machinery. It keeps an injected dual_solver, starts
it from a dual point, and re-evaluates the dual objective at the
returned optimum so the result stays differentiable with respect to
loss, nominal, and radius by the envelope theorem. A zero-valued
implicit-function term (_implicit_curvature) built from the dual
Hessian at the optimum makes second derivatives exact as well, once
the solve has converged.
Repeated calls are warm-started. The dual optimum moves only slightly
between consecutive worst_case_expectation calls on a slowly changing
loss, which is the sequence the outer iterations of an
optora.dro.MinimaxSolver produce. _solve_dual therefore caches the
detached optimum of each solve and starts the next solve from it
instead of from initial_dual_point.
That makes the second and later solves of such a sequence converge in
far fewer inner iterations at the same optimum, since each dual is
convex and its solution does not depend on where the iteration started.
Call reset_warm_start() to discard the cache and go back to
initial_dual_point, for example before evaluating an unrelated loss or
after a diverged solve.
A batched loss of shape (..., n) is solved with one set of dual
variables per batch element, since the duals decouple across batch
elements. _solve_dual therefore hands dual_solver the sum of the
per-element dual objectives. The gradient of the sum with respect to
one element's dual variables is that element's own gradient, so a
single joint solve takes the same steps as independent per-element
solves. Convergence is judged on the joint gradient norm over the whole
batch, so every element keeps iterating until the batch as a whole is
stationary. Stopping elements one by one would need a host read of a
per-element mask at every step, the synchronization
optora.core.convergence.ConvergenceTracker avoids.
The loss scale is handled here once rather than in each formulation.
The set of candidate distributions does not depend on loss, so
\(\sup_q \mathbb{E}_q[a\,\ell + b] = a \sup_q \mathbb{E}_q[\ell] + b\)
for \(a > 0\). The dual's curvature grows with the squared loss spread,
so a step size tuned for an order-one loss diverges on a wide one. The
dual is therefore solved on the loss standardized to unit spread,
\((\ell - \min \ell) / (\max \ell - \min \ell)\), with a detached shift
and scale. For any fixed constants this is the same function of loss,
so values and every derivative are unchanged. initial_dual_point and
the warm start stay in the units of the raw loss and are converted at
the boundary by _to_standard_units and _from_standard_units.
What standardization cannot fix is the shape of the dual itself. The
minimizer runs off to infinity as radius vanishes, and it ceases to
exist at all once radius reaches the divergence of the distribution
concentrated on the highest-loss scenarios, where the infimum is
approached only in the limit. A first-order solver returns a stale
iterate in the first case and can diverge outright in the second, so
this class is the fallback for a formulation whose maximizer optora
does not know in closed form. A formulation that does know it should
use TiltedAmbiguitySet, whose bracketed bisection has neither
failure mode.
Attributes:
| Name | Type | Description |
|---|---|---|
nominal |
Tensor
|
Reference distribution the ambiguity set is centered on. |
divergence |
Divergence used to measure distance from |
|
radius |
float | Tensor
|
Nonnegative bound on the divergence of any distribution
inside the ambiguity set from |
dual_solver |
Solver minimizing the dual objective. Required to evaluate the set at any radius. |
|
initial_dual_point |
Tensor
|
Dual point of a single batch element that the
first solve starts from, registered as a buffer so it is built
once and follows |
__init__(nominal, divergence, radius, dual_solver, initial_dual_point, initial_in_raw_units=True, validate=False)
¶
Initialize the dual-solved ambiguity set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nominal
|
Tensor
|
Reference distribution the ambiguity set is centered on. |
required |
divergence
|
Divergence
|
Divergence used to measure distance from |
required |
radius
|
float | Tensor
|
Nonnegative bound on the divergence of any distribution
inside the ambiguity set from |
required |
dual_solver
|
Solver[MinimizationProblem, MinimizationResult] | None
|
Solver minimizing the dual objective. Required to evaluate the set at any radius. |
required |
initial_dual_point
|
Tensor
|
Dual point of a single batch element that the first solve starts from. |
required |
initial_in_raw_units
|
bool
|
Whether |
True
|
validate
|
bool
|
Whether to run the value checks of |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
reset_warm_start()
¶
Discard the cached dual optimum so the next solve starts cold.
After this call the next worst_case_expectation starts from
initial_dual_point again, as the first one did.
worst_case_expectation(loss)
¶
Compute the worst-case expected loss from the convex dual.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss
|
Tensor
|
Per-scenario loss values of shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A tensor of shape |
Tensor
|
the dual objective evaluated at the optimum found by |
Tensor
|
|
Tensor
|
case from above at any dual point, so an unconverged solve can |
Tensor
|
overestimate the worst case but never underestimates it. |
Tensor
|
A float radius of zero is solved like any other rather than |
Tensor
|
short-circuited to |
Tensor
|
only the conjugate of the generator, so it admits a generator |
Tensor
|
that vanishes on an interval rather than at one alone (the |
Tensor
|
CVaR indicator, see |
Tensor
|
ball of radius zero of such a generator is larger than |
Tensor
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
RuntimeError
|
If |
contains(candidate)
¶
Check whether a candidate distribution lies inside the ambiguity set.
The answer is returned as a boolean tensor on candidate's device
rather than as a Python bool, so membership can be used as a mask
or composed with further tensor work without forcing a
device-to-host synchronization. Call bool(...) on the result only
where a host-side branch is genuinely needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
candidate
|
Tensor
|
Candidate distribution with the same shape as
|
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
A boolean tensor that is |
Tensor
|
|