Convergence diagnostics¶
A DRO minimax problem nests one solve inside another, so a statement that the method converged can refer to either of them. This tutorial separates the two and checks each one on its own, because a converged outer loop on top of an unconverged inner solve still reports a value that looks correct.
The outer loop, unrolled by hand¶
The first half does not call
MinimaxSolver as a black box. It writes
out the same fixed-step iteration by hand,
and records \(x_k\) and the worst-case objective at every step. This keeps the trajectory that the solver would otherwise discard, which is the most useful information when a run looks suspicious. A plot shows at once whether the decision variable has settled or is still drifting, and a final scalar does not.
Each evaluation of the objective runs a complete inner worst-case solve.
The backward pass of torch.autograd.grad does not differentiate through
that solve, because the gradient is the maximizing distribution (Danskin's
theorem). The cost is small at this scale, but one outer step still
contains a full inner solve.
The inner solve, checked by a dual grid search¶
The second half checks the inner solve. KL-DRO has a one-dimensional convex dual,
whose value equals the worst-case expectation by strong duality (Ben-Tal et al., 2013)1. Optora does not evaluate this dual. It works in the primal and bisects the exponential tilt \(q_\beta \propto \mathrm{nominal} \cdot e^{\beta\,\mathrm{loss}}\) until the KL constraint is tight. The dual is therefore an independent check. The script evaluates it at 400 points of a \(\log \eta\) grid, which covers \(\eta \in [e^{-6}, e^{4}]\), and compares the grid minimum with the value the library returns.
Neither method has a step size or a tolerance to tune. If the two agree, the library has found the worst-case distribution, and if they disagree, the printed absolute difference shows by how much. The remaining difference, of order \(10^{-5}\), comes from the grid. Its spacing is about \(0.025\) in \(\log \eta\), and the minimum over the grid lies above the infimum by an amount that is quadratic in the distance from the minimizer to the nearest grid point.
The grid evaluation is fully vectorized. It is one broadcast logsumexp
over the whole \((\text{grid} \times \text{scenarios})\) tensor, without a
Python loop over the values of \(\eta\).
Watch the shapes when you write your own grid search
A common way to broadcast a grid against a loss vector can also build a \((G \times G)\) tensor by mistake and exhaust memory at a few million grid points. Check the shape of the intermediate tensor before you widen the grid.
Reading the figures¶
The script produces two figures. The first has two panels for the outer trajectory, with \(x\) against the iteration on the left and the worst-case objective against the iteration on the right. The second shows the inner dual landscape at the final decision. It is a smooth curve in \(\log \eta\) with a single minimum, and the grid minimizer is marked. As \(\eta \to 0\) the dual objective approaches \(\max_i \mathrm{loss}_i\), which is why the curve flattens at the left end of the grid.
Outer step, inner landscape¶
The two static figures show the outer trajectory and the inner landscape at the end of the run, and the animation shows the steps in between. The left panel shows the robust objective in \(x\) with the iterate moving down it, the middle panel shows the trajectory \(x_k\), and the right panel shows the inner dual landscape at the current \(x_k\). The landscape changes with every outer step, because the loss vector changes. The horizontal line at the library's value meets the grid minimum at every outer step, including the intermediate ones.
The figures¶
The figures are rendered from this script when the site is built, so they always show the output of the current code.
Source¶
"""Convergence diagnostics for a KL-DRO robust decision problem.
A DRO minimax problem has an outer and an inner solve, and the script
checks the convergence of each one separately.
1. For the outer solve, it unrolls by hand the fixed-step gradient
iteration that `optora.solvers.GradientDescent` runs, instead of
calling `MinimaxSolver.solve` as a black box, and records the robust
decision `x` and the worst-case objective at every iteration.
2. For the inner solve, it evaluates the KL-DRO dual objective on a fine
grid of the dual variable `eta` and compares the grid minimum with the
value of the ambiguity set. The set computes that value by bisecting
the exponential tilt in the primal, so agreement confirms that it has
found the worst-case distribution.
Run:
python tutorials/04_convergence_diagnostics.py
"""
import matplotlib.pyplot as plt
import torch
from _plotting import save_figure
from optora.dro import KLAmbiguitySet
OUTCOMES = torch.tensor([1.0, 2.0, 3.0, 10.0], dtype=torch.float64)
NOMINAL = torch.full_like(OUTCOMES, 1.0 / OUTCOMES.numel())
RADIUS = 0.15
def track_outer_convergence(
ambiguity_set: KLAmbiguitySet,
initial_point: torch.Tensor,
step_size: float,
num_iterations: int,
) -> tuple[list[float], list[float]]:
"""Manually unroll a fixed-step gradient trajectory, recording history."""
def objective(x: torch.Tensor) -> torch.Tensor:
return ambiguity_set.worst_case_expectation((OUTCOMES - x) ** 2)
point = initial_point.clone().requires_grad_(True)
x_history = [point.item()]
value_history = [objective(point).item()]
for _ in range(num_iterations):
value = objective(point)
(grad,) = torch.autograd.grad(value, point)
with torch.no_grad():
point = point - step_size * grad
point = point.detach().requires_grad_(True)
x_history.append(point.item())
value_history.append(objective(point).item())
return x_history, value_history
def kl_dual_grid_search(
nominal: torch.Tensor, loss: torch.Tensor, radius: float, log_eta_grid: torch.Tensor
) -> torch.Tensor:
"""Evaluate the KL-DRO dual objective on a fine grid of `log(eta)`."""
log_nominal = torch.log(nominal)
eta = torch.exp(log_eta_grid)
log_mgf = torch.logsumexp(
log_nominal.unsqueeze(0) + loss.unsqueeze(0) / eta.unsqueeze(1), dim=-1
)
return eta * radius + eta * log_mgf
def main() -> None:
ambiguity_set = KLAmbiguitySet(nominal=NOMINAL, radius=RADIUS)
x_history, value_history = track_outer_convergence(
ambiguity_set,
initial_point=torch.tensor(OUTCOMES.mean().item(), dtype=torch.float64),
step_size=0.01,
num_iterations=150,
)
print(f"x trajectory: {x_history[0]:.4f} -> {x_history[-1]:.4f}")
print(f"objective trajectory: {value_history[0]:.4f} -> {value_history[-1]:.4f}")
fig1, (ax_x, ax_value) = plt.subplots(1, 2, figsize=(10, 4))
ax_x.plot(x_history)
ax_x.set_xlabel("outer iteration")
ax_x.set_ylabel("decision variable x")
ax_x.set_title("robust decision trajectory")
ax_value.plot(value_history)
ax_value.set_xlabel("outer iteration")
ax_value.set_ylabel("worst-case objective")
ax_value.set_title("worst-case objective trajectory")
fig1.tight_layout()
save_figure(fig1, "04_outer_convergence")
loss_at_solution = (OUTCOMES - x_history[-1]) ** 2
log_eta_grid = torch.linspace(-6.0, 4.0, 400, dtype=torch.float64)
dual_values = kl_dual_grid_search(NOMINAL, loss_at_solution, RADIUS, log_eta_grid)
grid_min_value, grid_argmin_index = torch.min(dual_values, dim=0)
library_value = ambiguity_set.worst_case_expectation(loss_at_solution)
print(
f"grid-search dual minimum: {grid_min_value.item():.6f} "
f"at log(eta)={log_eta_grid[grid_argmin_index].item():.4f}"
)
print(f"library worst_case_expectation: {library_value.item():.6f}")
abs_diff = abs(grid_min_value.item() - library_value.item())
print(f"absolute difference: {abs_diff:.2e}")
fig2, ax = plt.subplots(figsize=(6, 4))
ax.plot(log_eta_grid, dual_values.detach(), label="dual objective")
ax.axvline(
log_eta_grid[grid_argmin_index].item(),
color="firebrick",
linestyle="--",
label="grid-search minimizer",
)
ax.set_xlabel("log(eta)")
ax.set_ylabel("KL-DRO dual objective")
ax.set_title("inner dual landscape at the robust solution")
ax.legend()
fig2.tight_layout()
save_figure(fig2, "04_inner_dual_landscape")
if __name__ == "__main__":
main()
-
Aharon Ben-Tal, Dick den Hertog, Anja De Waegenaere, Bertrand Melenberg and Gijs Rennen, "Robust Solutions of Optimization Problems Affected by Uncertain Probabilities", Management Science 59(2), 341-357 (2013). ↩