Sobolev supervision: package guide

L2OSobolev (in lib/L2OSobolev of this repository) adds derivative supervision to any L2OCore method whose proxy predicts primal variables. The method, its derivative labels and the approximation results are on the theory page; a runnable example is Sobolev-regularized proxy for a parametric QP.

Masked Sobolev supervision. Dataset lane: each sampled p_i is solved for the value label g of p_i; DiffOpt or finite differences give the derivative label Dg of p_i. Training lane: the proxy g-hat_theta enters the inner method loss; its input Jacobian and the derivative label, both masked by M, are compared by ell_d; the total loss is the inner loss plus lambda times the mean masked term.

The same diagram in a narrow layout.

Values and sensitivities from the solver, a masked derivative term in the loss. Labels are computed offline by generate_data with a sensitivity oracle; during training the backend computes the proxy derivatives, the mask selects the entries that are matched, and SobolevRegularized adds $\lambda$ times the masked term to the inner method's loss. Equation numbers refer to the theory page.

Getting started

using L2OCore, L2OSobolev, JuMP, HiGHS, DiffOpt, Lux

problem = ParametricProblem(model)            # JuMP model with MOI.Parameter
method  = SobolevRegularized(SupervisedMSE();  # any primal / primal-dual method
                             weight = 1.0,
                             mask = RandomMask(0.1),
                             directions = FullJacobian(),
                             backend = LuxNestedAD())
pipe = L2OPipeline(problem, method)
data = generate_data(pipe; sampler, n = 1000, optimizer = HiGHS.Optimizer)
# in the training loop (sm = StatefulLuxLayer of the proxy):
ℓ = loss(pipe, X, sm(X); targets = batch, proxy = sm)

The same pipeline trains a Flux model with exact derivatives through ZygoteNestedAD (Zygote inside the loss and for the gradient with respect to the weights):

using L2OCore, L2OSobolev, JuMP, HiGHS, DiffOpt, Flux, Zygote

method = SobolevRegularized(SupervisedMSE(); weight = 1.0, backend = ZygoteNestedAD())
pipe = L2OPipeline(problem, method)
data = generate_data(pipe; sampler, n = 1000, optimizer = HiGHS.Optimizer)
X = data.inputs
nin, nout = num_parameters(problem), num_decision_variables(problem)
model = Flux.f64(Chain(Dense(nin => 32, tanh), Dense(32 => nout)))
opt = Flux.setup(Adam(5e-3), model)
for epoch = 1:500
    g = Flux.gradient(m -> loss(pipe, X, m(X); targets = data, proxy = m), model)[1]
    Flux.update!(opt, model, g)
end

train_flux! from LearningToOptimize runs the same loop with mini-batches (it passes proxy = model to loss).

Concepts

concepttyperole
wrapperSobolevRegularizedloss = inner loss + weight · sobolev_loss; everything else is the inner method's
directionsFullJacobian, RandomPullbacks, RandomPushforwardswhich derivative labels generate_data records
oracleDiffOptSensitivities, FiniteDifferenceSensitivitieswhere labels come from (generate_data(...; oracle))
labelsJacobianLabels, PullbackLabels, PushforwardLabels (in L2OCore)optional ds.derivatives field of the dataset
maskDenseMask, RandomMask, FixedMask, RandomColumnMask, RandomRowMaskwhich entries are matched per loss evaluation
evaluationproxy_metrics, max_infeasibility_reduction, covering_radiusthe paper's MSE / GAP / INF / RMI metrics; the $δ$ of its approximation bounds
backendLuxNestedAD, ZygoteNestedAD, CentralDifferenceshow proxy input derivatives are computed inside the loss
mapProxyMapraw primal output, or completed primal (through_completion = true)

Labels are optional in the data layer: L2ODataset.derivatives is nothing unless an oracle filled it, and datasets with labels work unchanged with any other method. label_errors compares labels with finite differences of the solver map and flags degenerate samples.

Choosing a mask and filtering labels

maskwhat one update matchesproxy derivatives computed (full Jacobian labels)
DenseMask()all $n d$ entriesfull Jacobian
RandomMask(ρ)round(ρ n d) random entriesfull Jacobian (the mask is an algorithmic control)
RandomColumnMask(k)$k$ random columns (parameters)$k$ Jacobian–vector products (LuxNestedAD, CentralDifferences); one Jacobian with ZygoteNestedAD
RandomRowMask(k)$k$ random rows (decision variables)$k$ vector–Jacobian products (LuxNestedAD, ZygoteNestedAD); one Jacobian with CentralDifferences
FixedMask(M)the entries of a fixed Mfull Jacobian

All random masks are normalized so the expected loss is the dense loss. Column masks are the cheap option when the number of parameters $d$ is large.

Degenerate samples (non-differentiable points of the solution map) can be removed while labeling with generate_data(pipe; ..., max_label_error = 1e-3), which compares every label with central differences of the solver map (2d extra solves per sample) and records the number removed in ds.metadata["sobolev_degenerate"].

To compare proxies as in the paper's experiments:

ref   = generate_data(L2OPipeline(problem, SupervisedMSE()); sampler, n = 500, optimizer)
bench = proxy_metrics(pipe, ref.inputs, plain_proxy(ref.inputs); reference = ref)
sob   = proxy_metrics(pipe, ref.inputs, sobolev_proxy(ref.inputs); reference = ref)
max_infeasibility_reduction(bench, sob)    # RMI per instance, in %

Composing with methods

inner methodvalue termwhat Sobolev addsnotes
SupervisedMSEsolver labelseq. (2) of the paper exactly
penalty (PenaltyMethod in LearningToOptimize)self-supervisedlocal solver information beyond the objective"semi-self-supervised" setting of the paper; labels still need a solver
augmented Lagrangian / primal-dual learningself-supervisedas above, on the primal rowsprimal-dual raw outputs: only primal rows are supervised
completion / repair (e.g. DC3)method's lossderivatives through the completionthrough_completion = true with CentralDifferences()
dual methods (e.g. DLL)—not supported (labels are primal sensitivities)constructor throws

Machine-learning frameworks and nested AD

The Sobolev term differentiates the proxy with respect to its inputs inside a loss that is then differentiated with respect to the weights. Measured behavior (see the design page for the full matrix and dev/nested_ad_matrix.jl):

proxybackendouter ADstatus
Lux StatefulLuxLayerLuxNestedAD()Zygoteexact; tested
Flux Chain, closure over Flux parameters, any Zygote-differentiable functionZygoteNestedAD()Zygoteexact; tested (including Flux training)
any callable (Lux, Flux, function)CentralDifferences()Zygote (or any AD)$O(h^2)$ approximation of the inner derivative; tested
completion layer around any proxyCentralDifferences(), through_completion = trueZygotetested
Lux layer wrapped in a closureLuxNestedAD()Zygotefails (Lux's rules need the layer itself): use CentralDifferences()
completion layer around any proxyZygoteNestedAD(), through_completion = trueZygoterejected (Zygote cannot differentiate completion layers twice in general): use CentralDifferences()
anyForwardDiff inside a Zygote lossZygotesilently wrong (nothing gradients): never do this

Recommendation: for exact derivatives, Lux with LuxNestedAD() or Flux (or any Zygote-differentiable callable) with ZygoteNestedAD(); both are supported and tested against finite differences. CentralDifferences() works with any proxy and any outer AD, and is the backend for derivatives through completion layers.

GPUs

  • sobolev_loss, the masks and CentralDifferences use only broadcasts, reshapes and reductions; masks and directions are copied to the array type of the inputs (similar + copyto!), so they run on GPU arrays without scalar indexing.
  • LuxNestedAD uses Lux's helpers, which support GPU devices.
  • ZygoteNestedAD uses Zygote pullbacks of the proxy, repeat, reshapes and broadcasts; its seeds are copied to the array type of the inputs, so it runs wherever the proxy's Zygote rules do (e.g. Flux layers on GPU arrays). CI tests it on the CPU.
  • Label generation with DiffOpt runs on the CPU, one instance at a time. A GPU oracle (batched KKT solves for ExaModels/MadNLP problems) plugs in through the oracle extension point below.

Extension points

Everything is extended by dispatch on abstract types.

A new mask (e.g. structure-aware masking):

struct TopRowsMask <: L2OSobolev.AbstractDerivativeMask
    rows::Vector{Int}
end
function L2OSobolev.sample_mask(m::TopRowsMask, rng, dims::Dims)
    M = falses(dims)
    M[m.rows, :] .= true
    return Array{Bool}(M)
end

A new backend (e.g. another nested-AD system): subtype AbstractSobolevBackend and implement proxy_jacobian, proxy_pushforward and proxy_pullback for the map types you support; results must be differentiable by the outer AD.

A new oracle (e.g. GPU or batched solvers): subtype AbstractSensitivityOracle and implement

L2OSobolev.sensitivity_labels(o::MyOracle, problem, inputs, directions; rng)
    -> (; labels, primal, ok)

for the directions you support. generate_data(pipe; oracle = MyOracle(...)) uses it, and the test pattern of test_labels.jl (label_errors against finite differences) applies unchanged.

A new label type: subtype L2OCore.AbstractDerivativeLabels (add subsetting in L2OCore) and add a sobolev_loss method.