L2OSobolev API

L2OSobolev lives in lib/L2OSobolev of this repository. The DiffOpt, Lux and Zygote features are package extensions: load DiffOpt (and JuMP) for DiffOptSensitivities, Lux for LuxNestedAD, Zygote for ZygoteNestedAD.

L2OSobolev.L2OSobolev — Module
L2OSobolev

Method-agnostic Sobolev (derivative) supervision for learning-to-optimize proxies, following Masked Sobolev Training for Feasibility-Reliable Optimization Proxies (Rosemberg, Dias Garcia, Bent and Van Hentenryck, NeurIPS 2026).

SobolevRegularized wraps any L2OCore method whose proxy predicts primal variables and adds the masked derivative-matching term of eq. (2)–(3) of the paper to its loss:

\[\mathcal{L}(θ) = \mathcal{L}_{\text{inner}}(θ) + \frac{λ}{N} \sum_{i=1}^{N} \frac{\big\| \mathcal{M} \odot \big(D\hat g_θ(p_i) - D g(p_i)\big) \big\|_F^2}{\|\mathcal{M}\|_0},\]

where $Dg(p_i) = ∂x^\star/∂p$ are solver sensitivities stored as optional derivative labels of the dataset (sensitivity_labels) and $D\hat g_θ$ is computed by an AbstractSobolevBackend.

Package extensions:

  • DiffOpt (+ JuMP): DiffOptSensitivities, derivative labels from implicit differentiation of the KKT conditions;
  • Lux: LuxNestedAD, exact proxy Jacobians with Lux's nested-AD helpers;
  • Zygote: ZygoteNestedAD, exact proxy Jacobians of Flux models and other Zygote-differentiable callables (Zygote over Zygote).
source

Wrapper

L2OSobolev.SobolevRegularized — Type
SobolevRegularized(method; weight = 1.0, mask = DenseMask(),
                   directions = FullJacobian(), backend = CentralDifferences(),
                   through_completion = false, rng = Random.Xoshiro(0))

Add masked Sobolev (derivative) supervision to any L2OCore method whose proxy predicts primal variables (primal and primal-dual families). The training loss becomes

\[\mathcal{L}(θ) = \mathcal{L}_{\texttt{method}}(θ) + \frac{λ}{N} \sum_{i=1}^{N} \ell_d\big(\mathcal{M} \odot D\hat g_θ(p_i),\, \mathcal{M} \odot Dg(p_i)\big),\]

eq. (2) of the masked Sobolev training paper with the value term replaced by the wrapped method's own loss: SupervisedMSE gives exactly eq. (2); a self-supervised method (penalty, augmented Lagrangian) gives the paper's semi-self-supervised variant; a method with a completion layer can be supervised before or through that layer (through_completion). $\ell_d$ is the normalized masked loss of eq. (3) (sobolev_loss).

Arguments:

Pipeline behavior:

  • supports, decompose, complete are the wrapped method's (the regularizer changes training only, not how predictions are completed);
  • generate_data(pipe; sampler, n, optimizer, oracle, ...) builds the wrapped method's dataset and attaches derivative labels from oracle (default DiffOptSensitivities(optimizer)); see L2OCore.generate_data;
  • loss(pipe, P, proxy(P); targets, proxy) needs targets with derivative labels and the proxy itself (training loops pass proxy = model).

The labels are meaningful where the solution map is differentiable at the training samples (LICQ, SOSC, strict complementarity; Remark 1 of the paper), and the proxy map must act column by column. The approximation benefit (Theorem 3 of the paper: uniform error $≤ \tfrac12 (M_g + M_{\hat g}) δ^2$ under exact value and Jacobian interpolation, versus $(L_g + L_{\hat g}) δ$ for values only) holds in regions where the solution map is $C^1$ with Lipschitz Jacobian; it is not a statement about the convergence of training.

source
L2OCore.generate_data — Method
generate_data(::SobolevRegularized, pipe; sampler, n, rng = Random.default_rng(),
              optimizer = nothing, oracle = DiffOptSensitivities(optimizer),
              drop_failed = true, consistency_atol = 1e-4,
              consistency_rtol = 1e-4, max_label_error = Inf,
              fd_step = 1e-5, kwargs...)

Dataset of the wrapped method (same sampler, n, rng, optimizer, kwargs) with derivative labels of w.directions from oracle attached as ds.derivatives. Samples whose label solve failed are dropped when drop_failed; so are samples whose primal labels (if the wrapped method records them) differ from the oracle's solution by more than consistency_atol + consistency_rtol * ‖x‖_∞ in the max norm (a different local optimum would make value and derivative labels describe different solution branches). The number of dropped samples is stored in ds.metadata["sobolev_dropped"].

With a finite max_label_error, the labels are also verified against central finite differences of the solver map (label_errors with step = fd_step, 2d extra solves per sample) and samples whose relative error exceeds it are dropped: these are the degenerate samples (weakly active constraints, active-set changes within ± fd_step) where the solution map is not differentiable and the KKT sensitivities of eq. (1) of the paper are not its derivative. Their number is stored in ds.metadata["sobolev_degenerate"].

source

Loss and masks

L2OSobolev.sobolev_loss — Function
sobolev_loss(backend, f, P, labels; mask = DenseMask(), rng = Random.default_rng()) -> Real

Masked derivative-matching loss of a batch, eq. (2)–(3) of the masked Sobolev training paper without the weight $λ$:

\[\frac{1}{B} \sum_{k=1}^{B} \frac{\big\| \mathcal{M} \odot (\hat D_k - D_k) \big\|_2^2}{\|\mathcal{M}\|_0},\]

where $\hat D_k$ are input derivatives of the column-wise map f at P[:, k] (computed by backend) and $D_k$ the matching derivative labels:

labels$\hat D_k$$D_k$mask shape
JacobianLabels$D\hat g_θ(p_k)$J[:, :, k]n × d
PullbackLabels$D\hat g_θ(p_k)^⊤ w_k$values[:, k]d
PushforwardLabels$D\hat g_θ(p_k)\, v_k$values[:, k]n

A single mask is drawn per call (shared by the batch) with sample_mask; DenseMask gives the mean squared error over all entries.

The loss is 0 when the proxy derivatives equal the labels, and with RandomMask its expectation over masks is the dense loss (eq. (4) of the paper).

source
L2OSobolev.AbstractDerivativeMask — Type
AbstractDerivativeMask

Which derivative entries enter the Sobolev term at one loss evaluation: the binary mask $\mathcal{M}$ of eq. (2)–(3) of the masked Sobolev training paper. Implement sample_mask for a new mask type.

source
L2OSobolev.DenseMask — Type
DenseMask()

Every entry is supervised ($\mathcal{M} = \mathbf{1}$): dense derivative matching, $\ell_d = \|D\hat g_θ - Dg\|_F^2 / (n d)$.

source
L2OSobolev.RandomMask — Type
RandomMask(density)

Uniformly random subset of a fixed number of entries, k = clamp(round(Int, density * m), 1, m) out of the m supervised entries, redrawn at every loss evaluation and shared by the samples of the batch (the same $\mathcal{M}$ in every term of eq. (2) of the paper).

With the normalization by $\|\mathcal{M}\|_0 = k$, the masked loss is an unbiased estimator of the dense loss, $\mathbb{E}_{\mathcal{M}}[\ell_d] = \|D\hat g_θ - Dg\|_F^2 / (n d)$, because every entry is retained with probability $k/m$.

The paper reports that keeping 5–10% of the Jacobian entries (density = 0.05–0.1) gave lower infeasibility than dense matching on AC-OPF.

source
L2OSobolev.RandomColumnMask — Type
RandomColumnMask(count)

Keeps count uniformly random columns of the Jacobian (parameters), redrawn at every loss evaluation and shared by the batch. For JacobianLabels the loss only needs the proxy Jacobian–vector products along the selected unit directions, so its cost is count proxy_pushforwards instead of a full proxy_jacobian (the paper's remark that selected columns can be computed with Jacobian–vector products). For directional labels it keeps count entries of the label vector.

Every entry is kept with probability count / d and the loss is normalized by $\|\mathcal M\|_0 = n \cdot \mathrm{count}$, so the expectation is the dense loss (eq. (4) of the paper for this structured mask).

source
L2OSobolev.RandomRowMask — Type
RandomRowMask(count)

Keeps count uniformly random rows of the Jacobian (decision variables), redrawn at every loss evaluation and shared by the batch. For JacobianLabels the loss only needs count proxy_pullbacks (vector–Jacobian products with unit seeds). For directional labels it keeps count entries of the label vector. Unbiased for the dense loss, like RandomColumnMask.

source
L2OSobolev.sample_mask — Function
sample_mask(mask::AbstractDerivativeMask, rng, dims::Dims) -> Union{Nothing,Array{Bool}}

Draw the mask for one loss evaluation over entries of shape dims. nothing means "all entries" (no masking). Not differentiated.

source

Proxy derivatives

L2OSobolev.ProxyMap — Type
ProxyMap(proxy, pipe; through_completion = false)

The map $P \mapsto \hat x_θ(P)$ whose input derivatives are supervised: the primal prediction of proxy on a batch of parameters P (num_parameters × B → num_decision_variables × B).

  • through_completion = false: the primal rows of the raw proxy output (requires the FullSpaceDecomposition of the pipeline's method, where these rows are the primal prediction before any repair); this is $D\hat g_θ$ of the paper.
  • through_completion = true: the primal part of complete(pipe, P, proxy(P)), i.e. derivatives taken through a completion / repair / projection layer (the paper's "through the feasibility module" variant).

Assumption: the map acts column by column (sample k of the output depends only on column k of the input), as for feed-forward networks without batch statistics. Batched input-derivative computations rely on it.

source
L2OSobolev.AbstractSobolevBackend — Type
AbstractSobolevBackend

How input derivatives of the proxy map are computed inside the training loss (which is itself differentiated with respect to the proxy weights: nested differentiation). A backend implements

for a column-wise map f (usually a ProxyMap). Each result must be differentiable by the outer AD used for training.

source
L2OSobolev.CentralDifferences — Type
CentralDifferences(; step = nothing)

Framework-agnostic backend: input derivatives by central differences of the map, $J v ≈ (f(P + h v) - f(P - h v)) / 2h$, evaluated as batched forward passes. The outer AD only differentiates forward passes, so it works with any callable proxy (Flux, Lux, plain functions), any outer AD and on GPUs, and also through completion layers. All d directions of a Jacobian are evaluated in a single forward pass of width 2 d B.

The truncation error is $O(h^2 \|D^3 f\|)$ and the rounding error $O(ε (\|f\| + \|D f\|\,\|P\|_∞) / h)$ (rounding of both the outputs and the perturbed inputs). The default step balances the two, $h = ε^{1/3} \max(1, \|P\|_∞)$ of the input element type (≈ 6e-6 for Float64, ≈ 5e-3 for Float32, times the input scale); step = h fixes an absolute step instead. Directions should be of unit scale. The approximation assumes the map is $C^3$ near the inputs; for piecewise-linear activations (ReLU) the differences straddle kinks with small probability and then return a one-sided average. For exact derivatives use LuxNestedAD with Lux models, or ZygoteNestedAD with Flux models and other Zygote-differentiable callables.

source
L2OSobolev.LuxNestedAD — Type
LuxNestedAD()

Exact input derivatives of a Lux model with Lux's nested-AD helpers (Lux.batched_jacobian and Lux.jacobian_vector_product with AutoForwardDiff, Lux.vector_jacobian_product with AutoZygote), which have dedicated rules for being differentiated again by Zygote with respect to the weights. Requires using Lux (package extension) and Zygote for pullbacks and training.

The proxy must be a Lux.StatefulLuxLayer and the map a ProxyMap with through_completion = false (Lux's rules apply to the layer itself, not to closures around it; measured, see the design page). For derivatives through a completion layer use CentralDifferences.

source
L2OSobolev.ZygoteNestedAD — Type
ZygoteNestedAD()

Exact input derivatives of any callable that Zygote can differentiate twice: a Flux Chain, a closure over Flux parameters, or a plain Julia function. The input derivatives are Zygote pullbacks, and an outer Zygote gradient with respect to the weights (Zygote.gradient, Flux.gradient) differentiates through them (Zygote over Zygote; measured correct for Flux, see the design page). Requires using Zygote (package extension).

  • proxy_pullback: one reverse pass of width B;
  • proxy_jacobian: one reverse pass of width n B (the n output rows are seeded at once on a repeated batch);
  • proxy_pushforward: the Jacobian contracted with the directions (reverse mode only, so it costs as much as proxy_jacobian).

For a ProxyMap the backend differentiates the proxy itself and keeps the primal rows through the seeds, so the map must use through_completion = false with a FullSpaceDecomposition. Zygote cannot differentiate completion layers twice in general (keyword constructors, mutation, branches); use CentralDifferences for derivatives through a completion layer. Any other callable f is differentiated as given, so its body must be differentiable twice by Zygote (no mutation; a closure such as P -> re(θ)(P) around a Flux model is fine). For Lux models use LuxNestedAD: nesting Zygote pullbacks around a StatefulLuxLayer fails (design page).

source
L2OSobolev.proxy_jacobian — Function
proxy_jacobian(backend, f, P) -> AbstractArray{T,3}

Input Jacobians of the column-wise map f at every column of P: J[:, :, k] = ∂f(P)[:, k] / ∂P[:, k] (n × d × B, the layout of JacobianLabels).

source
L2OSobolev.proxy_pullback — Function
proxy_pullback(backend, f, P, W) -> AbstractMatrix

Vector–Jacobian products J_kᵀ * W[:, k] for every column (d × B).

source

Derivative labels

L2OSobolev.RandomPullbacks — Type
RandomPullbacks(; distribution = :onehot)

Record one vector–Jacobian product $Dg(p_k)^⊤ w_k$ per sample (one reverse sensitivity solve). Seeds $w_k ∈ ℝ^n$ are drawn per sample: :onehot picks a uniformly random decision variable (the label is a random row of the Jacobian, i.e. a sparse, stochastic subset of its entries), :gaussian a uniformly random unit direction.

source
L2OSobolev.RandomPushforwards — Type
RandomPushforwards(; distribution = :onehot)

Record one Jacobian–vector product $Dg(p_k)\, v_k$ per sample (one forward sensitivity solve). Directions $v_k ∈ ℝ^d$: :onehot picks a random parameter (a random column of the Jacobian), :gaussian a random unit direction.

source
L2OSobolev.DiffOptSensitivities — Type
DiffOptSensitivities(optimizer; mode = :reverse, model_constructor = nothing,
                     silent = true)

Derivative labels by implicit differentiation of the KKT conditions with DiffOpt.jl: at a solution $s^\star = (x^\star, λ^\star)$ of $F(s, p) = 0$ (stationarity, primal feasibility, complementarity),

\[∇_p s^\star = -\big(∇_s F(s^\star, p)\big)^{-1} ∇_p F(s^\star, p)\]

(eq. (1) of the masked Sobolev training paper). Reverse mode (mode = :reverse) gives vector–Jacobian products, forward mode (mode = :forward) Jacobian–vector products; both reuse one solve per sample. Labels of the other kind are assembled from full Jacobians (n reverse or d forward sensitivity solves). The default is reverse mode: with DiffOpt 0.6 we measured wrong forward-mode sensitivities for parameters that enter inequality constraints, while reverse mode agreed with finite differences on every test problem (DiffOpt 0.5 was correct in both modes).

optimizer is the solver constructor (wrapped with DiffOpt.diff_optimizer). model_constructor selects DiffOpt's differentiation model (DiffOpt.QuadraticProgram.Model, DiffOpt.ConicProgram.Model, DiffOpt.NonLinearProgram.Model); nothing picks NonLinearProgram for SmoothNonlinear problems and DiffOpt's automatic choice otherwise.

The labels are the derivatives of the solution map under LICQ, second-order sufficient conditions and strict complementarity at $x^\star(p)$ (Fiacco 1976), so that the solution map is locally differentiable and $∇_s F$ is invertible. At degenerate points (weakly active constraints, active-set changes) the result is one element of a generalized derivative and can disagree with finite differences; see label_errors.

Requires using DiffOpt (package extension). Labels are computed on a copy of the problem's JuMP model (JuMP.copy_model), so the user's model is left unchanged.

source
L2OSobolev.FiniteDifferenceSensitivities — Type
FiniteDifferenceSensitivities(optimizer; step = 1e-5)

Reference oracle by central differences of the solver's solution map, $Dg(p) v ≈ (x^\star(p + h v) - x^\star(p - h v)) / 2h$, using only solve_instances (any JuMP solver, no differentiation layer). Costs 2d solves per sample for Jacobians and pullbacks and 2 per sample for pushforwards; used to verify other oracles (label_errors) and as a fallback when no differentiable solver is available.

The differences are accurate when the solution is unique, the active set does not change within $[p - h v, p + h v]$ and the solver tolerance is well below step.

source
L2OSobolev.sensitivity_labels — Function
sensitivity_labels(oracle, problem, inputs, directions;
                   rng = Random.default_rng()) -> (; labels, primal, ok)

Solve the instances in the columns of inputs (num_parameters × N) and record derivative labels of the requested directions (AbstractDerivativeDirections). Returns a named tuple with the labels (an AbstractDerivativeLabels with NaN columns for failed samples), the primal solutions (num_decision_variables × N) and a BitVector ok of samples whose solves (and differentiation) succeeded.

source
L2OSobolev.label_errors — Function
label_errors(labels, problem, inputs; optimizer, step = 1e-5) -> Vector{Float64}

Check derivative labels against central finite differences of the solver's solution map (under LICQ, SOSC and strict complementarity the KKT sensitivities of eq. (1) of the paper are the derivatives of $p \mapsto x^\star(p)$). Returns, per sample, the relative error $\|D - D_{\mathrm{fd}}\| / \max(1, \|D_{\mathrm{fd}}\|)$ (NaN if a perturbed solve failed). Large errors flag degenerate samples where the solution map is not differentiable (active-set changes within ± step).

source

Approximation diagnostics and evaluation

L2OSobolev.covering_radius — Function
covering_radius(train::AbstractMatrix, query::AbstractMatrix) -> Real

Empirical covering radius of the training parameters (columns of train) over the parameters in query:

\[δ = \max_{q ∈ \text{query}} \min_{p_i ∈ \text{train}} \|q - p_i\|_2 ,\]

the quantity $δ$ of Theorems 1–3 of the masked Sobolev training paper (evaluated on a finite set of query points instead of the supremum over the whole parameter space; a dense query set gives a lower estimate of $δ$). Under exact interpolation, value supervision bounds the proxy error by $(L_g + L_{\hat g}) δ$ and joint value-and-Jacobian supervision by $\tfrac12 (M_g + M_{\hat g}) δ^2$; covering_radius tells how far a test set is from the training data in these terms.

source
L2OSobolev.proxy_metrics — Function
proxy_metrics(pipe, inputs, primal; reference = nothing, include_bounds = true)
    -> (; mse, gap, inf, max_violation, violations)

Per-sample evaluation metrics of the masked Sobolev training paper (AC-OPF evaluation appendix) for a batch of primal predictions primal (num_decision_variables × B) at parameters inputs:

\[\mathrm{MSE}_i = \tfrac1n \|\tilde x_i - x^\star_i\|_2^2, \qquad \mathrm{GAP}_i = \frac{|f(\tilde x_i) - f(x^\star_i)|}{|f(x^\star_i)|}, \qquad \mathrm{INF}_i = \frac{\sum_{c ∈ \mathcal E} |c(\tilde x_i)| + \sum_{g ∈ \mathcal I} \max\{g(\tilde x_i), 0\}}{|\mathcal E| + |\mathcal I|},\]

and the largest violation $\max_j \mathrm{Infeas}_{ij}$. Violations come from the pipeline's evaluator (row_violation plus cone_violation); violations is the m × B matrix $\mathrm{Infeas}_{ij}$. Variable bounds count as inequalities unless include_bounds = false. mse and gap need a reference dataset with primal and objective labels for the same inputs (nothing otherwise). Use max_infeasibility_reduction to compare two proxies.

source
L2OSobolev.max_infeasibility_reduction — Function
max_infeasibility_reduction(benchmark, candidate) -> Vector{Float64}

Relative reduction in maximum infeasibility (RMI, in percent) of a candidate proxy over a benchmark proxy on the same instances, as defined in the evaluation appendix of the masked Sobolev training paper:

\[\mathrm{RMI}_i = 100\% × \frac{\max_j \mathrm{Infeas}^{\text{bench}}_{ij} - \max_j \mathrm{Infeas}^{\text{cand}}_{ij}}{\max_{i,j} \mathrm{Infeas}^{\text{cand}}_{ij}} .\]

Positive values mean the candidate reduced the worst violation of instance i. Both arguments are results of proxy_metrics. The normalization by the single largest candidate violation avoids division by zero on instances without violation; if the candidate has no violation at all, the denominator is eps().

source