Skip to content
Edit this page View source of this page

optora.dro.phi_dro

Phi-divergence ambiguity sets (phi-DRO) and the penalized chi-square objective.

PhiAmbiguitySet

Bases: DualAmbiguitySet

Phi-divergence-constrained ambiguity set solved via its convex dual.

Bounds every candidate distribution q by \(D_\phi(q \,\|\, \mathrm{nominal}) \le \mathrm{radius}\) for a general convex generator \(\phi\) (see optora.divergences.f_divergence.PhiDivergence). The worst-case expected loss over this set admits the convex dual (Ben-Tal et al. 2013; Duchi, Glynn, and Namkoong 2021; Duchi and Namkoong 2021)

\[ \sup_{q:\, D_\phi(q \,\|\, \mathrm{nominal}) \,\le\, \mathrm{radius}} \mathbb{E}_q[\mathrm{loss}] = \inf_{\substack{\eta > 0 \\ \lambda \in \mathbb{R}}} \eta \cdot \mathrm{radius} + \lambda + \eta \, \mathbb{E}_{\mathrm{nominal}}\!\left[ \phi^*\!\left(\frac{\mathrm{loss} - \lambda}{\eta}\right) \right] \]

where \(\phi^*\) is the convex (Legendre-Fenchel) conjugate of \(\phi\) restricted to its effective domain \(t \ge 0\). This generalizes the KLAmbiguitySet dual to an arbitrary phi-divergence at the cost of a second dual variable \(\lambda\). Setting \(\phi(t) = t \log t - t + 1\), whose conjugate is \(\phi^*(s) = \exp(s) - 1\), and minimizing over \(\lambda\) in closed form recovers the KL-DRO dual exactly.

Without a dual_solver, the default, the worst case is solved exactly for any generator, as a bracketed tilt. By the KKT conditions the maximizer is \(q_i = \mathrm{nominal}_i\,(\phi^*)'(\mu - a\, \mathrm{gap}_i)\) for a rate \(a = 1/\eta\) and a normalizing level \(\mu\), and its divergence grows monotonically with the rate, so optora.core.dro_base.TiltedAmbiguitySet bisects the rate in a guaranteed bracket, as it does for KLAmbiguitySet and ChiSquareAmbiguitySet, while an inner bisection pins the level. The solve has a fixed trip count, never synchronizes with the host, reaches the maximum loss exactly at saturation, and carries exact first and second derivatives in loss, nominal, and radius. It needs only divergence.phi and phi_conjugate, differentiated with torch.func, so both must be differentiable functions of tensors. The nested bisection makes it slower than the dedicated sets, so prefer KLAmbiguitySet, ChiSquareAmbiguitySet, or CVaRAmbiguitySet for their generators.

With a dual_solver, the convex dual above is minimized over \((\log(\eta), \lambda)\) by that solver instead, from a warm start (see optora.core.dro_base.DualAmbiguitySet). Its accuracy is then the solver's, and a fixed-step GradientDescent is sensitive to its step size, to the support size, and to a radius near zero or saturation.

phi_conjugate must be finite everywhere on the real line, as chi_square_conjugate and kl_conjugate are. A generator whose conjugate has a hard finite feasibility boundary, such as total variation, is solved by its dedicated closed form, TotalVariationAmbiguitySet.

The two paths treat a float radius of zero differently. The exact tilt returns sum(nominal * loss) without solving, which is right for any generator it accepts. A differentiable conjugate means a strictly convex generator, whose divergence vanishes at the nominal alone. The dual path solves at every radius, a float zero included, because its weaker requirement admits a generator that vanishes on an interval, such as the CVaR indicator behind cvar_conjugate, whose ball of radius zero is the whole CVaR set rather than {nominal}.

Attributes:

Name Type Description
nominal Tensor

Reference distribution the ambiguity set is centered on.

divergence PhiDivergence

PhiDivergence instance measuring distance from nominal.

radius float | Tensor

Nonnegative bound on the phi-divergence of any distribution inside the ambiguity set from nominal, either a float or a tensor of radii evaluated as one batch.

phi_conjugate

Convex (Legendre-Fenchel) conjugate of divergence.phi, finite everywhere on the real line.

dual_solver

Solver minimizing the dual objective over (log(eta), lam), or None for the exact bracketed tilt.

initial_dual_point Tensor

Values of (log(eta), lam) the first dual solve starts from, in the units of the raw loss (eta and lam have the units of loss). Later solves warm-start from the previous optimum (see optora.core.dro_base.DualAmbiguitySet).

__init__(nominal, divergence, radius, phi_conjugate, dual_solver=None, initial_log_eta=None, initial_lam=None, validate=False)

Initialize the phi-divergence ambiguity set.

Parameters:

Name Type Description Default
nominal Tensor

Reference distribution the ambiguity set is centered on, a nonnegative tensor that sums to one along its last dimension.

required
divergence PhiDivergence

PhiDivergence instance measuring distance from nominal.

required
radius float | Tensor

Nonnegative bound on the phi-divergence of any distribution inside the ambiguity set from nominal. A tensor radius is broadcast against the batch shape of worst_case_expectation's loss.

required
phi_conjugate Callable[[Tensor], Tensor]

Convex conjugate of divergence.phi, finite everywhere on the real line.

required
dual_solver Solver[MinimizationProblem, MinimizationResult] | None

Solver minimizing the dual objective over (log(eta), lam). None, the default, solves the worst case exactly as a bracketed tilt instead, and ignores the initial dual point.

None
initial_log_eta float | None

Value of log(eta) the first dual solve starts from, in the units of the raw loss (eta has the units of loss). Later calls warm-start from the previous solve's optimum unless reset_warm_start() is called.

None
initial_lam float | None

Value of lam the first dual solve starts from, in the units of the raw loss, warm-started on later calls alongside initial_log_eta. Give both or neither. When both are None, the default, the solve starts at eta equal to the loss spread and lam equal to the minimum loss, which is the same point whatever the scale or offset of the loss.

None
validate bool

Whether to check that nominal is nonnegative and sums to one. The check synchronizes with the device, so it is opt-in and off by default.

False

Raises:

Type Description
ValueError

If radius is a negative float, if only one of initial_log_eta and initial_lam is given, or if validate is set and nominal is not a valid probability distribution.

worst_case_expectation(loss)

Compute the worst-case expected loss over the phi-divergence ball.

Parameters:

Name Type Description Default
loss Tensor

Per-scenario loss values of shape (..., n), one trailing entry per element of nominal's support. Leading dimensions are a batch of independent loss vectors, solved together.

required

Returns:

Type Description
Tensor

A tensor of shape (...) holding the worst-case expected loss.

Tensor

Without a dual_solver it is the expectation under the

Tensor

maximizer found by the bracketed tilt, which is the exact

Tensor

sum(nominal * loss) when radius is a zero float. With one

Tensor

it is the dual objective at the optimum that solver found, at

Tensor

every radius (see the class docstring).

Raises:

Type Description
ValueError

If loss's trailing dimension does not match nominal's support size, its batch shape does not broadcast against nominal and radius, or validate is set and loss is not finite.

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 nominal.

required

Returns:

Type Description
Tensor

A boolean tensor that is True where the divergence of

Tensor

candidate from nominal does not exceed radius.

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.

ChiSquareAmbiguitySet

Bases: TiltedAmbiguitySet

Chi-square-divergence-constrained ambiguity set for chi-square-DRO.

Bounds every candidate distribution q by

\[ D_{\chi^2}(q \,\|\, \mathrm{nominal}) = \sum_i \frac{(q_i - \mathrm{nominal}_i)^2}{\mathrm{nominal}_i} \le \mathrm{radius}, \]

the phi-divergence generated by \(\phi(t) = (t-1)^2\). Unlike PhiAmbiguitySet, worst_case_expectation is not computed by minimizing the general convex dual over \((\eta, \lambda)\), because the chi-square maximizer is known in closed form up to a single scalar. The KKT conditions give

\[ q^\star_i \propto \mathrm{nominal}_i \, (\mathrm{loss}_i - c)_+, \]

a linear tilt of the nominal truncated at a cut level \(c\) (Duchi and Namkoong 2021). Its divergence rises monotonically as \(c\) rises, from \(0\) as \(c \to -\infty\) to \(1/P^\star - 1\) as \(c \to \max \mathrm{loss}\), where \(P^\star\) is the nominal mass on the highest-loss scenarios, so the radius constraint pins \(c\) by one monotone scalar root solve.

In the interior regime where no scenario is truncated to \(q_i = 0\), the cut level drops below \(\min \mathrm{loss}\) and the value reduces to the variance-penalty form (Duchi and Namkoong 2021)

\[ \sup_{q:\, D_{\chi^2}(q \,\|\, \mathrm{nominal}) \,\le\, \mathrm{radius}} \mathbb{E}_q[\mathrm{loss}] = \mathbb{E}_{\mathrm{nominal}}[\mathrm{loss}] + \sqrt{\mathrm{radius} \cdot \mathrm{Var}_{\mathrm{nominal}}(\mathrm{loss})}. \]

The truncated regime has the same form on the scenarios that keep positive weight, so the root is found exactly rather than by the bisection of optora.core.dro_base.TiltedAmbiguitySet. Sorting the scenarios by loss identifies which of them are truncated, and the cut level then solves a quadratic (see _solve_tilt). The solve costs one sort and a fixed number of vectorized operations whatever the dtype, which matters on a GPU, where the 52 float64 bisection steps are bound by kernel launches rather than by arithmetic. The root is exact up to rounding. Where the bisection returns a tilt that tested feasible, the divergence of this maximizer matches the radius to the precision of evaluating it.

Attributes:

Name Type Description
nominal Tensor

Reference distribution the ambiguity set is centered on.

divergence

ChiSquareDivergence instance measuring distance from nominal.

radius float | Tensor

Nonnegative bound on the chi-square divergence of any distribution inside the ambiguity set from nominal, either a float or a tensor of radii evaluated as one batch.

__init__(nominal, radius, eps=1e-12, validate=False)

Initialize the chi-square ambiguity set.

Parameters:

Name Type Description Default
nominal Tensor

Reference distribution the ambiguity set is centered on, a nonnegative tensor that sums to one along its last dimension.

required
radius float | Tensor

Nonnegative bound on the chi-square divergence of any distribution inside the ambiguity set from nominal. A tensor radius is broadcast against the batch shape of worst_case_expectation's loss.

required
eps float

Small positive constant used to clamp nominal away from zero before dividing, passed through to the underlying ChiSquareDivergence.

1e-12
validate bool

Whether to check that nominal is nonnegative and sums to one. The check synchronizes with the device, so it is opt-in and off by default.

False

Raises:

Type Description
ValueError

If radius is a negative float, if eps is not positive, or if validate is set and nominal is not a valid probability distribution.

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 nominal.

required

Returns:

Type Description
Tensor

A boolean tensor that is True where the divergence of

Tensor

candidate from nominal does not exceed radius.

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 (..., n), one trailing entry per element of nominal's support. Leading dimensions are a batch of independent loss vectors, bisected together in one vectorized solve.

required

Returns:

Type Description
Tensor

A tensor of shape (...) holding the worst-case expected loss.

Tensor

When radius is a zero float it is the exact expectation at

Tensor

the start of the tilt path (_center_expectation), which is

Tensor

sum(nominal * loss) by default. Otherwise it is the

Tensor

expectation of loss under the feasible tilted distribution

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 max(loss)

Tensor

rather than directly. Every term of

Tensor

sum(q * (loss - max(loss))) is nonpositive, so the result can

Tensor

never round to above max(loss), and a loss with a small

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 loss's trailing dimension does not match nominal's support size, its batch shape does not broadcast against nominal and radius, or validate is set and loss is not finite.

PenalizedChiSquareDRO

Bases: Module

Penalized chi-square DRO objective (Levy, Carmon, Duchi, and Sidford 2020).

Replaces the radius constraint of ChiSquareAmbiguitySet by a penalty on the chi-square divergence from the nominal distribution \(p\),

\[ V(\ell) = \sup_{q \in \Delta_n} \; \mathbb{E}_q[\ell] - \lambda \, D_{\chi^2}(q \,\|\, p), \qquad D_{\chi^2}(q \,\|\, p) = \sum_i \frac{(q_i - p_i)^2}{p_i}, \]

where \(\lambda > 0\) is penalty and \(\Delta_n\) is the probability simplex. This is Eq. (4) of Levy et al. (2020). They define the divergence with the generator \(\frac{1}{2}(t - 1)^2\), half of ChiSquareDivergence, so their penalty \(\lambda_{\mathrm{Levy}}\) corresponds to penalty \(= \lambda_{\mathrm{Levy}} / 2\). The same conversion applies to the reg argument of RobustLoss(size=inf, reg=...) in their code.

\(V\) is not the worst-case expectation over a fixed set of distributions, so this class is not an AmbiguitySet. Calling the module returns \(V\), as calling OnlineGroupDRO or StochasticPhiDual returns their objectives. optora.dro.MultilevelMonteCarloEstimator accepts it in place of an ambiguity set.

By convex duality (Ben-Tal and Teboulle 2007), with the multiplier \(\eta\) of the constraint \(\sum_i q_i = 1\) and the conjugate \(\phi^*(s) = \frac{1}{4}(s + 2)_+^2 - 1\) of \(\phi(t) = (t - 1)^2\) restricted to \(t \ge 0\),

\[ V(\ell) = \inf_{\eta \in \mathbb{R}} \; \eta + \lambda \, \mathbb{E}_p\!\left[\phi^*\!\left( \frac{\ell - \eta}{\lambda}\right)\right] = \inf_{c \in \mathbb{R}} \; c + \lambda + \frac{1}{4\lambda} \, \mathbb{E}_p\big[(\ell - c)_+^2\big], \]

with \(c = \eta - 2\lambda\). The maximizer is the truncated linear tilt

\[ q^\star_i = p_i \, \frac{(\ell_i - c^\star)_+}{2\lambda}, \qquad \mathbb{E}_p\big[(\ell - c^\star)_+\big] = 2\lambda, \]

the same shape as the maximizer of ChiSquareAmbiguitySet. While no scenario is truncated, that is while \(\ell_i \ge \mathbb{E}_p[\ell] - 2\lambda\) on the support of \(p\), the cut level is \(c^\star = \mathbb{E}_p[\ell] - 2\lambda\) and

\[ V(\ell) = \mathbb{E}_p[\ell] + \frac{\mathrm{Var}_p(\ell)}{4\lambda}. \]

For a general smooth generator a divergence penalty is a variance penalty to leading order (Gotoh, Kim, and Lim 2018), and for chi-square the expansion is exact in this regime. \(V\) tends to \(\mathbb{E}_p[\ell]\) as \(\lambda \to \infty\) and to the largest loss on the support of \(p\) as \(\lambda \to 0\).

The normalization condition is piecewise linear and increasing in the cut depth below the largest loss, so sorting the scenarios by loss locates the truncated ones exactly, as in ChiSquareAmbiguitySet. The solve is one sort and a fixed number of vectorized operations, and nothing is read back to the host, so the forward and backward passes can be captured in a CUDA graph.

Let \(A\) be the set of scenarios with positive weight, \(P_A\) and \(T_A\) the nominal masses inside and outside \(A\), and \(S_A = \sum_{i \in A} p_i (\max \ell - \ell_i)\). Once \(A\) is known, the multiplier \(\eta^\star = \max \ell - (2\lambda T_A + S_A) / P_A\) is an explicit smooth function of \((\ell, p, \lambda)\). The value is computed as the dual objective at that multiplier in plain differentiable operations, with only \(A\) held fixed. \(A\) is locally constant away from the points where a scenario enters or leaves it, so autograd returns exact derivatives of every order, torch.func transforms included. The first derivatives are \(\partial V / \partial \ell = q^\star\) by Danskin's theorem, and \(\partial V / \partial \lambda = -D_{\chi^2}(q^\star \,\|\, p)\) and \(\partial V / \partial p_i = \lambda \, \phi^*((\ell_i - \eta^\star) / \lambda)\) by the envelope theorem. Only the derivative with respect to nominal along directions that keep it summing to one is defined. The objective in \(q\) is strongly concave, so the maximizer is unique and \(V\) is continuously differentiable in \(\ell\) everywhere, tied losses included.

The largest loss on the support of \(p\) is subtracted before solving. This leaves the maximizer unchanged, since \(V(\ell + a) = V(\ell) + a\), and keeps the precision of a small loss spread around a large offset. A scenario with zero nominal mass gets zero weight whatever its loss.

Attributes:

Name Type Description
nominal Tensor

Reference distribution, a nonnegative tensor that sums to one along its last dimension.

divergence

ChiSquareDivergence instance, for evaluating \(D_{\chi^2}(q \,\|\, p)\) of a candidate distribution.

penalty float | Tensor

Positive penalty \(\lambda\) on the divergence, in the units of the loss, either a float or a tensor of penalties evaluated as one batch.

validate

Whether the value checks that synchronize with the device run.

__init__(nominal, penalty, eps=1e-12, validate=False)

Initialize the penalized chi-square objective.

Parameters:

Name Type Description Default
nominal Tensor

Reference distribution of shape (..., n), a nonnegative tensor that sums to one along its last dimension. Leading dimensions are a batch of nominals.

required
penalty float | Tensor

Positive penalty on the chi-square divergence, in the units of the loss. A tensor penalty is registered as a buffer and broadcast against the batch shape of the loss, which evaluates a sweep of penalties in one call. Its entries are checked only when validate is set. A float penalty must be positive and finite. Zero and infinity are the limits in which the value is the largest loss and the nominal expectation, which CVaRAmbiguitySet(nominal, 0.0) and torch.sum(nominal * loss, -1) compute directly.

required
eps float

Small positive constant used to clamp nominal away from zero before dividing, passed through to divergence.

1e-12
validate bool

Whether to run the value checks that synchronize with the device. They check that nominal is a probability distribution, that a tensor penalty is positive and finite, and, on every call, that the loss is finite. The shape and float checks are metadata-only and always run.

False

Raises:

Type Description
ValueError

If nominal is a scalar tensor, a float penalty is not positive and finite, eps is not positive, or validate is set and nominal or a tensor penalty fails its check.

forward(loss)

Evaluate the penalized chi-square objective.

Parameters:

Name Type Description Default
loss Tensor

Per-scenario losses of shape (..., n), one trailing entry per element of nominal's support. Leading dimensions are a batch, broadcast against those of nominal and against penalty's shape.

required

Returns:

Type Description
Tensor

The penalized value of shape (...), the broadcast batch shape,

Tensor

computed in optora.core.working_dtype(loss, nominal) and

Tensor

returned in torch.promote_types(loss.dtype, nominal.dtype). A

Tensor

batch element whose loss holds a nan or infinite entry is

Tensor

nan.

Raises:

Type Description
ValueError

If loss's trailing dimension does not match nominal's support size, its batch shape does not broadcast against nominal and penalty, or validate is set and loss is not finite.

TotalVariationAmbiguitySet

Bases: AmbiguitySet

Total-variation-constrained ambiguity set for total-variation-DRO.

Bounds every candidate distribution q by

\[ D_{\mathrm{TV}}(q \,\|\, \mathrm{nominal}) = \frac{1}{2} \sum_i |q_i - \mathrm{nominal}_i| \le \mathrm{radius}. \]

Unlike PhiAmbiguitySet, worst_case_expectation is computed from a direct closed form rather than from a convex dual. The conjugate of the total-variation generator is \(+\infty\) for \(s > 1/2\), and PhiAmbiguitySet needs a conjugate that is finite on the whole real line.

The worst-case expectation is the value of a linear program over the simplex intersected with the total-variation ball, and its optimal solution has a simple combinatorial structure (Ben-Tal et al. 2013). Starting from nominal, mass moves from the lowest-loss scenarios, in ascending order of loss, to the single highest-loss scenario until the moved mass reaches radius or every scenario but the highest-loss one is fully drained, whichever happens first. This is implemented as a sort followed by a cumulative-sum sweep rather than an iterative solve, so it is exact and needs no solver tuning.

At tied losses the linear program has many maximizers. The sort is stable, so ties are broken by support index as if a later index had a marginally larger loss. Tied low-loss scenarios are drained in index order, and the moved mass goes to the last of the tied maxima. The maximizer, and with it the gradient with respect to loss, is then the same on every device.

Attributes:

Name Type Description
nominal Tensor

Reference distribution the ambiguity set is centered on.

divergence

TotalVariationDivergence instance measuring distance from nominal.

radius float | Tensor

Nonnegative bound on the total variation distance of any distribution inside the ambiguity set from nominal, either a float or a tensor of radii evaluated as one batch.

__init__(nominal, radius, eps=1e-12, validate=False)

Initialize the total variation ambiguity set.

Parameters:

Name Type Description Default
nominal Tensor

Reference distribution the ambiguity set is centered on, a nonnegative tensor that sums to one along its last dimension.

required
radius float | Tensor

Nonnegative bound on the total variation distance of any distribution inside the ambiguity set from nominal. A tensor radius is broadcast against the batch shape of worst_case_expectation's loss, which turns a radius sweep into one vectorized evaluation of the closed form.

required
eps float

Small positive constant used to clamp the reference distribution away from zero before dividing, passed through to the underlying TotalVariationDivergence.

1e-12
validate bool

Whether to check that nominal is nonnegative and sums to one. The check synchronizes with the device, so it is opt-in and off by default.

False

Raises:

Type Description
ValueError

If radius is a negative float, if eps is not positive, or if validate is set and nominal is not a valid probability distribution.

worst_case_expectation(loss)

Compute the worst-case expected loss over the total variation ambiguity set.

Parameters:

Name Type Description Default
loss Tensor

Per-scenario loss values of shape (..., n), one trailing entry per element of nominal's support. Leading dimensions are a batch of independent loss vectors. The closed form is evaluated over the whole batch at once, with no solver and no Python-level loop over batch elements.

required

Returns:

Type Description
Tensor

A tensor of shape (...) holding the worst-case expected loss.

Tensor

It is the exact sum(nominal * loss) when radius is zero,

Tensor

since the ambiguity set then contains only nominal, and

Tensor

otherwise the closed-form value of the mass-reallocation linear

Tensor

program described in the class docstring.

Raises:

Type Description
ValueError

If loss's trailing dimension does not match nominal's support size, its batch shape does not broadcast against nominal and radius, or validate is set and loss is not finite.

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 nominal.

required

Returns:

Type Description
Tensor

A boolean tensor that is True where the divergence of

Tensor

candidate from nominal does not exceed radius.

CVaRAmbiguitySet

Bases: AmbiguitySet

Conditional value-at-risk (CVaR) ambiguity set.

The conditional value-at-risk of a loss at tail probability \(\alpha \in (0, 1]\), the mean of its upper \(\alpha\)-tail, is the worst case over every distribution whose likelihood ratio to the nominal is at most \(1/\alpha\) (Artzner et al. 1999; Rockafellar and Uryasev 2002),

\[ \mathrm{CVaR}_\alpha(\mathrm{loss}) = \sup_{q:\, q_i \,\le\, \mathrm{nominal}_i / \alpha} \mathbb{E}_q[\mathrm{loss}]. \]

The constraint set is the phi-divergence ball of the indicator generator \(\phi_\alpha(t) = 0\) on \([0, 1/\alpha]\) and \(+\infty\) elsewhere (see cvar_conjugate), so CVaR-DRO is a phi-DRO special case. It is also exactly the ball of radius \(\log(1/\alpha)\) in the max-divergence \(D_\infty(q \,\|\, \mathrm{nominal}) = \log \max_i q_i / \mathrm{nominal}_i\) (optora.divergences.MaxDivergence), and that is the representation used here. With it divergence and contains stay finite and meaningful, and radius \(= \log(1/\alpha)\) indexes the set like every other ambiguity set. \(\alpha = 1\) gives the nominal expectation and \(\alpha \to 0\) the maximum loss on the nominal's support.

The maximizer fills the tail greedily. In descending order of loss, each scenario receives its full nominal mass until the cumulative mass reaches \(\alpha\), the scenario at the boundary receives the remainder, and the result is normalized by the filled mass, which equals \(\alpha\) up to rounding. It is computed as a sort followed by a cumulative-sum sweep, as for TotalVariationAmbiguitySet, so it is exact, solver-free, and synchronization-free. The sort is stable, so tied losses are filled in support-index order and the maximizer, and with it the gradient with respect to loss, is the same on every device.

Attributes:

Name Type Description
nominal Tensor

Reference distribution the ambiguity set is centered on.

divergence

MaxDivergence instance measuring distance from nominal.

alpha float | Tensor

Tail probability in \([0, 1]\), a float or a tensor of levels evaluated as one batch.

radius float | Tensor

Max-divergence radius \(\log(1/\alpha)\), of alpha's type and shape.

__init__(nominal, alpha, eps=1e-12, validate=False)

Initialize the CVaR ambiguity set.

Parameters:

Name Type Description Default
nominal Tensor

Reference distribution the ambiguity set is centered on, a nonnegative tensor that sums to one along its last dimension.

required
alpha float | Tensor

Tail probability in [0, 1]. A tensor level is registered as a buffer and broadcast against the batch shape of worst_case_expectation's loss, which turns a sweep of levels into one vectorized evaluation. Its entries are checked only when validate is set. Zero is the limit in which the worst case is the maximum loss on the nominal's support.

required
eps float

Small positive constant used to clamp nominal away from zero before dividing, passed through to the underlying MaxDivergence.

1e-12
validate bool

Whether to check that nominal is a valid probability distribution and that a tensor alpha lies in [0, 1]. The checks synchronize with the device, so they are opt-in and off by default.

False

Raises:

Type Description
ValueError

If alpha is a float outside [0, 1] or nan, if eps is not positive, or if validate is set and nominal is not a valid probability distribution or a tensor alpha holds an entry outside [0, 1].

worst_case_expectation(loss)

Compute the conditional value-at-risk of loss under nominal.

Parameters:

Name Type Description Default
loss Tensor

Per-scenario loss values of shape (..., n), one trailing entry per element of nominal's support. Leading dimensions are a batch of independent loss vectors. The closed form is evaluated over the whole batch at once, with no solver and no Python-level loop over batch elements.

required

Returns:

Type Description
Tensor

A tensor of shape (...) holding the upper alpha-tail mean of

Tensor

loss. It is the exact sum(nominal * loss) when alpha is

Tensor

the float one, and otherwise the greedy tail fill described in

Tensor

the class docstring. Its gradient with respect to loss is the

Tensor

maximizer, by Danskin's theorem.

Raises:

Type Description
ValueError

If loss's trailing dimension does not match nominal's support size, its batch shape does not broadcast against nominal and alpha, or validate is set and loss is not finite.

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 nominal.

required

Returns:

Type Description
Tensor

A boolean tensor that is True where the divergence of

Tensor

candidate from nominal does not exceed radius.

kl_conjugate(scaled_shift)

Overflow-free convex conjugate of the KL generator \(\phi(t) = t \log t - t + 1\).

The exact conjugate \(\phi^*(s) = e^s - 1\) overflows once \(s\) passes \(\log\) of the dtype's largest value (about 88.7 in float32), as it does in optora.dro.minibatch.StochasticPhiDual when \(\lambda\) lags a loss spike, and the resulting inf turns every gradient into nan. This returns instead the conjugate of the generator restricted to likelihood ratios \(t \le T = e^c\), with \(c\) a quarter of the dtype's logarithmic range (about 22.2 in float32, 177.4 in float64),

\[ \sup_{0 \le t \le T} \big(s\,t - \phi(t)\big) = \begin{cases} e^s - 1, & s \le c, \\ e^c (1 + s - c) - 1, & s > c, \end{cases} \]

the exact conjugate continued along its tangent at \(c\). It is convex and continuously differentiable, and its slope never exceeds \(T\), so the dual objective, its gradients, and their squares (as accumulated by Adam and RMSprop) stay finite for any loss spike up to about \(T\) times \(\eta\). At half the range the squared gradient of \(\log \eta\) would already overflow float32. The dual it defines is the exact dual of the KL ball intersected with the likelihood-ratio bound \(q / \mathrm{nominal} \le T\), so it equals the KL dual whenever the worst-case likelihood ratio \(e^s\) stays below \(T\) (about \(4 \times 10^9\) in float32). Since a ratio \(r\) on an event of nominal probability \(p\) puts mass \(r p \le 1\) on it, the bound can only bind where the worst case loads events of nominal probability below \(1 / T\). Pass it as phi_conjugate to PhiAmbiguitySet or optora.dro.minibatch.StochasticPhiDual for the KL ball.

Parameters:

Name Type Description Default
scaled_shift Tensor

Elementwise dual argument \(s = (\mathrm{loss} - \lambda) / \eta\).

required

Returns:

Type Description
Tensor

The conjugate evaluated elementwise on scaled_shift.

chi_square_conjugate(scaled_shift)

Convex conjugate of the chi-square generator \(\phi(t) = (t-1)^2\), \(t \ge 0\).

\(\phi^*(s) = \sup_{t \ge 0} \big(s\,t - \phi(t)\big)\). The unconstrained maximizer \(t = s/2 + 1\) is nonnegative whenever \(s \ge -2\), giving the interior branch \(s + s^2/4\). Otherwise the constrained maximizer sits at the boundary \(t = 0\), giving the constant \(-1\). The two branches agree at \(s = -2\), and both have zero derivative there, so \(\phi^*\) is continuously differentiable everywhere on the real line. Pass it as phi_conjugate to PhiAmbiguitySet or optora.dro.minibatch.StochasticPhiDual for the chi-square ball.

Parameters:

Name Type Description Default
scaled_shift Tensor

Elementwise dual argument \(s = (\mathrm{loss} - \lambda) / \eta\).

required

Returns:

Type Description
Tensor

\(\phi^*\) evaluated elementwise on scaled_shift.

cvar_conjugate(scaled_shift, alpha)

Convex conjugate of the CVaR generator at level \(\alpha \in (0, 1]\).

The conditional value-at-risk ball (see CVaRAmbiguitySet) is the phi-divergence ball of the indicator generator \(\phi_\alpha(t) = 0\) for \(t \in [0, 1/\alpha]\) and \(+\infty\) otherwise, whose conjugate is \(\phi_\alpha^*(s) = \sup_{0 \le t \le 1/\alpha} s\,t = (s)_+ / \alpha\). Because \((s)_+\) is positively homogeneous, the phi-DRO dual at radius zero no longer depends on \(\eta\) and reduces to the Rockafellar-Uryasev representation

\[ \mathrm{CVaR}_\alpha(\ell) = \inf_{\lambda \in \mathbb{R}} \lambda + \frac{1}{\alpha}\, \mathbb{E}[(\ell - \lambda)_+], \]

minimized at the upper \(\alpha\)-quantile of \(\ell\) (Rockafellar and Uryasev 2000). Bind the level, functools.partial(cvar_conjugate, alpha=0.1), and pass it with radius=0.0 to optora.dro.minibatch.StochasticPhiDual for minibatch CVaR training, or to PhiAmbiguitySet with a dual_solver, which solves the dual at a zero radius rather than returning the nominal expectation. The indicator vanishes on the whole interval \([0, 1/\alpha]\), so its ball of radius zero is the full CVaR set.

Parameters:

Name Type Description Default
scaled_shift Tensor

Elementwise dual argument \(s = (\mathrm{loss} - \lambda) / \eta\).

required
alpha float | Tensor

Tail probability in \((0, 1]\), a float or a tensor broadcasting against scaled_shift.

required

Returns:

Type Description
Tensor

\(\phi_\alpha^*\) evaluated elementwise on scaled_shift.