Design of the LearningToOptimize ecosystem

This page explains how the code is organized and why. The goal is that implementing a new learning-to-optimize (L2O) method takes only the code that is specific to that method. Data generation, evaluation of objectives, violations and dual bounds, samplers and dataset conventions are shared.

Packages

Package map. Inside the LearningToOptimize.jl repository, LearningToOptimize and L2OSobolev depend on L2OCore (method families, problem wrapper, batched evaluators, datasets); L2OData and L2OKernels are planned. The method packages L2ODLL, L2ODC3 and L2OALM depend on L2OCore, and LDF is planned. L2OALM, and the planned L2OKernels, use BatchNLPKernels.jl through package extensions.

The same diagram in a narrow layout.

Every package depends on L2OCore, and on nothing else of the ecosystem. Solid arrows are dependencies; dashed boxes and arrows are planned packages, or package extensions (weak dependencies).
packageroledependencies
L2OCore (lib/L2OCore)method hierarchy, problem classes, ParametricProblem, evaluators, datasets, method-dispatched pipelineJuMP, MathOptInterface, LinearAlgebra, SparseArrays, Random
LearningToOptimizethe penalty method, Flux training loop, existing dataset generation (ProblemIterator, recorders, samplers), FullyConnected models; re-exports L2OCoreL2OCore + ML and file-format stack
L2OSobolev (lib/L2OSobolev)method-agnostic Sobolev (derivative) supervision: SobolevRegularized wrapper, masks, derivative labels from DiffOptL2OCore, ChainRulesCore; DiffOpt and Lux as package extensions
method packages (L2ODLL, L2ODC3, L2OALM, …)one method family member eachL2OCore only (plus what the method itself needs)
L2OKernels (planned)batched GPU evaluators as an AbstractEvaluator backendExaModels / BatchNLPKernels, loaded as a package extension

Why a lib/ subpackage instead of a separate repository? The core and the reference method evolve together while the interface settles; one repository gives one CI run, one documentation site and atomic changes. Method packages live in their own repositories because they have their own authors, papers and dependency stacks.

Why so few dependencies in L2OCore? Method packages must be able to depend on it without inheriting Flux, MLJ, CSV or Arrow. Everything heavy is either in the main package or behind package extensions.

Subpackage mechanism and Julia versions

Julia ≥ 1.11 resolves unregistered local packages from a [sources] section in Project.toml; Julia 1.10 (the LTS) ignores that section. We support both:

  • Project.toml declares [sources] L2OCore = {path = "lib/L2OCore"} (used on 1.11+);
  • CI runs Pkg.develop(path = "lib/L2OCore") before testing on every version, which is what makes 1.10 work and is harmless on 1.11+;
  • lib/L2OCore has its own Project.toml, test suite and CI job.

Once L2OCore is registered, [sources] and the develop step can be removed; [compat] L2OCore = "0.1" already pins the interface version.

Documentation for lib/ packages

There is one Documenter site. docs/make.jl loads both modules (modules = [LearningToOptimize, L2OCore]) and the API reference has one section per package, so cross-references between the core and the main package work and there is a single place to search.

Type hierarchy

Type hierarchy in three trees. Methods: AbstractL2OMethod with AbstractPrimalMethod (SupervisedMSE, PenaltyMethod, DC3, FSNet, LDF planned), AbstractDualMethod (DualLagrangianLearning), AbstractPrimalDualMethod (ALMMethod) and AbstractMethodWrapper (BoundedOutput, ProjectionRepair, SobolevRegularized). Problem classes: AbstractProblemClass with AbstractConvexClass (LinearConic, ConvexQuadratic), SmoothNonlinear and MixedInteger. Evaluators: AbstractEvaluator with MatrixEvaluator, JuMPEvaluator and a planned kernel evaluator.

The same diagram in a narrow layout.

Three small hierarchies. Concrete types are defined where they are implemented: SupervisedMSE, the repair wrappers, the problem classes and the evaluators in L2OCore; PenaltyMethod in LearningToOptimize; SobolevRegularized in L2OSobolev; DC3 and FSNet in L2ODC3; DualLagrangianLearning (built by L2ODLL.DLLMethod()) in L2ODLL; ALMMethod in L2OALM.
  • Families (AbstractPrimalMethod, AbstractDualMethod, AbstractPrimalDualMethod) select fallbacks: what is predicted, which labels are generated, how the raw output is split.
  • Problem classes are traits of the problem, detected from the JuMP model (detect_problem_class) or given explicitly. They exist so that a method can declare which problems its mathematics applies to (supports).
  • Evaluators are interchangeable backends for batched objective, constraint, violation and dual-bound evaluation.
  • Wrappers (AbstractMethodWrapper) add behavior to any method (e.g. derivative supervision) by forwarding everything to an inner method and adding a loss term.

Data flow

How an optimization proxy is trained and used. Parametric problem: OPT of p is the minimum over x of f of x and p subject to g_i of x and p in S_i, with p drawn by a sampler. Proxy: a network phi_theta maps p to a raw output z. Method: an optional BoundedOutput layer, then either the training loss ell of phi_theta of p and p, or at inference complete, giving x-hat and y-hat, and an optional ProjectionRepair; evaluate reports objective, violations, dual bound and gap. A dashed arrow returns the gradient of the expected loss to theta.

The same diagram in a narrow layout.

The pipeline as the reader uses it. The same objects as the table below: the problem wrapper, the proxy, the method's loss and completion, and the evaluation.
stepcallresult
wrap the modelParametricProblem(model)layouts and problem class
build the pipelineL2OPipeline(problem, method)checks supports, runs decompose
generate datagenerate_data(pipe; sampler, optimizer)L2ODataset: inputs, and optionally primal, dual, objective, derivatives
trainminimize loss(pipe, P, proxy(P))a trained proxy
completecomplete(pipe, P, raw)Prediction(primal, dual)
evaluateevaluate(pipe, P, prediction)EvaluationReport: objective, violations, dual bound, gap

Layouts are fixed once by ParametricProblem:

quantityshapeorder
inputs Pnum_parameters × Bparameters(problem) (creation order)
primal Xnum_decision_variables × Bdecision_variables(problem)
dual Ynum_duals × Bconstraint_refs(problem), rows dual_layout(problem)[i], signs of JuMP.dual

Batch-first (batch = last dimension) matches Flux, Lux and BatchNLPKernels and keeps every per-instance quantity a contiguous column.

Method lifecycle

orderthe user callsthe pipeline dispatches toif the method defines nothing
1L2OPipeline(problem, method)supports(method, class)false: UnsupportedProblemError
2(same call)decompose(problem, method)fallback by family
3generate_data(pipe; sampler, n)generate_data(method, pipe; …)sample and solve, labels by family
4loss(pipe, P, proxy(P); targets, proxy), in the training looploss(method, pipe, …)supervised MSE
5complete(pipe, P, proxy(P))complete(method, pipe, P, raw)split the raw output
6evaluate(pipe, P, prediction)the evaluator functions—

What a method package writes:

functionrequired?fallback
struct M <: Abstract*Methodyes—
supports(::M, ::Class) = trueyes, per classfalse (no silent fallback)
decompose(problem, ::M)if the method predicts a subsetFullSpaceDecomposition by family
generate_data(::M, pipe; …)if labels differsample + solve, labels by family
complete(::M, pipe, P, raw)if there is a completion/repairsplit raw output
loss(::M, pipe, P, raw; …)if not supervised MSEsupervised MSE

Why supports is opt-in. Each method rests on mathematics with hypotheses: DLL's dual completion needs a conic problem, DC3's equality completion needs an invertible Jacobian block. Running DLL on a nonconvex problem or DC3's correction on nonlinear constraints silently changes what the output means. The pipeline therefore refuses unsupported classes up front with an error. Users can still override a mis-detected class explicitly (ParametricProblem(model; class = …)).

Why the pipeline object. L2OPipeline checks support once, computes the decomposition once (which can be expensive: dualization, Jacobian factorizations) and holds the evaluator. It replaces hidden caches stored in model.ext. Extension functions take (method, pipe, …) so packages dispatch on their own method type; fallbacks leave the other arguments untyped so these definitions are never ambiguous.

Methods at a glance

methodfamilyproblem classeswhat the completion or loss doesreference
PenaltyMethod (this package)primalLinearConic, ConvexQuadraticsoft loss, eq. (2) of the paper; outputs may be infeasibleDonti et al. 2021
DLL (L2ODLL.jl)dualconic (LinearConic, ConvexQuadratic) where, for every predicted $y$ in the dual cone, the completion problem (8) is strictly feasible and bounded (e.g. finite variable bounds, strictly convex quadratic objective)completes $y$ to a dual-feasible point, so its Lagrangian value is a valid dual bound (Theorems 1 and 2 of the paper)Tanneau & Van Hentenryck 2024; Klamkin et al. 2024
DC3 (L2ODC3.jl)primalequality constraints with an invertible Jacobian blockcompletion solves the equalities exactly; gradient correction reduces inequality violation (converging for linear constraints)Donti et al. 2021
ALM / PDL (L2OALM.jl)primal-dualsmooth problems, kernels for batched evaluationaugmented-Lagrangian loss with learned multipliersPark & Van Hentenryck 2023
LDF (planned)primalsmooth problemsLagrangian-dual loss with multipliers updated by subgradient stepsFioretto et al. 2020

Method packages test these properties numerically on random instances through evaluate (violations, dual bounds compared with solver optima).

Repair layers

BoundedOutput and ProjectionRepair are AbstractMethodWrappers that work with any primal method: the first is an output layer used during training and inference that keeps predictions inside the variable bounds, the second a projection onto the feasible set at inference (convex classes only). Because they are wrappers, they forward the loss and completion to the inner method, leave dual predictions untouched, and tighten the support check (ProjectionRepair refuses non-convex classes even if the inner method accepts them).

Evaluation layer, front ends and GPUs

Every loss, completion and evaluation is expressed through the AbstractEvaluator functions (batch_objective, constraint_values, row_violation, cone_violation, dual_bound). Two backends ship today:

  • MatrixEvaluator: extracts A, B, b, Q, c, H once; every batch operation is a sparse-dense product or broadcast. It is differentiable with array AD and element-type generic. Moving its arrays to a GPU (Adapt) is the planned L2OCore extension for linear/quadratic problems.
  • JuMPEvaluator: per-instance reference through JuMP.value; it is the ground truth in tests, never used in training loops.

The plan for nonlinear problems and for an ExaModels front end is a single kernel backend:

stageobjectprovided by
front enda JuMP model with MOI.Parameters, converted function by function, or an ExaModels model written by the userJuMP → ExaModels conversion (planned)
modela parametric ExaModelExaModels
batchBatchNLPKernels.BatchModelBatchNLPKernels.jl
evaluatora kernel evaluator implementing the AbstractEvaluator functionspackage extension L2OCore + BatchNLPKernels (planned)
uselosses, completions and evaluation on CPU or GPUevery method, unchanged
  • Problems stated in JuMP or directly in ExaModels end up as a parametric ExaModel; a BatchModel from BatchNLPKernels provides batched objective, constraints, Jacobian products and violations with ChainRulesCore rules.
  • A kernel evaluator implementing the AbstractEvaluator functions on top of a BatchModel plugs into every method unchanged. It lives in a package extension (L2OCore + BatchNLPKernels), keeping the core light.
  • An ExaModels front end subtypes AbstractParametricProblem (which ParametricProblem already does), implementing the layout functions, objective_sign and default_evaluator.
  • Batched solvers can label data much faster than a loop over optimize!; a batched-modeling layer (batched parameters/constraints over JuMP, with a bridge to ExaModels and NLPModels) would let solve_instances hand a whole batch to such solvers. This is tracked as a follow-up issue.

CI runs on CPU. GPU paths are written without scalar indexing and are testable by running the same tests with arrays adapted to the device.

Machine-learning frameworks

L2OCore is framework-agnostic: a proxy is any callable on a batch. The main package ships a Flux training loop (train_flux!) because Flux is already a dependency. Derivative (Sobolev) supervision needs nested AD: an input-Jacobian product of the proxy inside the loss, then a gradient with respect to the weights. We measured which combinations give correct gradients (compared with central finite differences) on a two-layer network:

proxyouter ADinner AD (input VJP)result
Lux (StatefulLuxLayer)ZygoteLux.vector_jacobian_product(…, AutoZygote(), …)correct
Lux (StatefulLuxLayer)ForwardDiffZygotecorrect
Lux (StatefulLuxLayer)ZygoteZygote (Zygote.gradient inside the loss)error (array mutation)
LuxEnzymeEnzymeerror (runtime activity / mutability)
FluxZygoteZygotecorrect
FluxForwardDiffZygotecorrect
Lux or FluxZygoteForwardDiffsilently wrong (nothing gradient)
Lux, helpers applied to a closure around the layerZygoteLux.vector_jacobian_product / jacobian_vector_producterror (mutation / dual-tag ordering)
Lux (StatefulLuxLayer)ZygoteLux.batched_jacobian(…, AutoForwardDiff())correct
any callableZygotecentral differences of forward passescorrect to $O(h^2)$ (≈1e-8 relative in Float64)
Flux Chain (Jacobian, pushforward, pullback of the raw proxy)ZygoteZygote pullbacks (ZygoteNestedAD)correct
completion layer (keyword constructors, branches)ZygoteZygoteerror (Zygote's second-order compilation)

Measured with Lux 1.32, Flux 0.16, Zygote 0.7, ForwardDiff 1.5 and a recent Enzyme on a Dense(3→8, tanh) → Dense(8→2) network with Float64 weights (Float32 weights make the finite-difference reference unreliable); reproduce with julia dev/nested_ad_matrix.jl. The table is evidence for the configurations listed, not a general statement; method packages test each framework on the models they ship examples for.

Decision:

  • method packages must work with any callable proxy; L2OCore never differentiates through the proxy itself;
  • Lux and Flux are both supported for losses that need nested AD, each in the configurations the tests show to be correct:
    • Lux through its vector_jacobian_product / jacobian_vector_product helpers under an outer Zygote gradient (Lux maintains these for exactly this use, and they also work on GPUs); nesting Zygote.gradient by hand inside a Lux loss fails, so derivative-supervision code calls the helpers;
    • Flux (a Chain, or any Zygote-differentiable callable) with Zygote both inside the loss and for the outer gradient with respect to the weights;
  • the Flux loop in the main package (train_flux!) covers first-order losses (penalty, supervised, augmented-Lagrangian losses); a method package that needs derivative supervision provides its own loss for either framework;
  • never put ForwardDiff inside a Zygote-differentiated loss for parameter gradients: Zygote treats the inner call as constant and returns nothing without an error.

lib/L2OSobolev follows this decision: LuxNestedAD() (exact, Lux helpers on the StatefulLuxLayer itself), ZygoteNestedAD() (exact, Zygote pullbacks of a Flux model or any Zygote-differentiable callable) and CentralDifferences() (any callable proxy, also through completion layers), all checked against finite differences of the weight gradient in its test suite, with a Flux and a Lux training run.

Datasets and trained models on the Hugging Face Hub

Datasets and trained proxies are shared under huggingface.co/LearningToOptimize. Proposed conventions (design only):

Dataset card fields

fieldexamplewhy
problem_id, problem_versionpglib_opf_case5_pjm/DCPPowerModel, 1.0reproducible problem identity
problem_file.mof.json with parametersthe JuMP model, readable by MOI.FileFormats
parameter_sampler{"type": "ScaledSampler", "low": 0.8, "high": 1.2} (#32)inputs distribution, needed to generate more data
layoutsnames of parameters, variables, constraints in orderties columns to model entities
solver, solver_version, tolerancesHiGHS 1.x, primal_feas = 1e-7label quality
labelsprimal, dual, objective, status, optional `derivatives: pullbackjacobian`
label_qualitymax violation ≤ 1e-6, dual gap ≤ 1e-6measured with evaluate before upload
splits, seedtrain/val/test, 42comparability

Model card fields: method (type and hyper-parameters), proxy (architecture, framework, parameter count), training_data (dataset id and revision), metrics (EvaluationReport means on the test split, gap, max violation, dual bound where the method predicts duals).

Compatibility with the existing API

All existing exports (ProblemIterator, Recorder, ArrowFile, CSVFile, samplers, FullyConnected, evaluators) are unchanged. L2OCore names are re-exported. Names that collide with other packages commonly loaded together (MLJ.evaluate) are resolved inside LearningToOptimize in favor of the L2OCore meaning; users that load MLJ too can write LearningToOptimize.evaluate.

Planned work

  • Move ProblemIterator, recorders and file formats to lib/L2OData.jl once L2ODataset I/O is designed (#12), so the main package can drop Arrow/CSV/DataFrames for users who only train.
  • Kernel evaluator extension and the ExaModels front end (#33).
  • Graph encoders from the problem structure (#29).