L2OCore API
L2OCore lives in lib/L2OCore of this repository. All of its exported names are re-exported by LearningToOptimize.
L2OCore.L2OCore — Module
L2OCoreLightweight interfaces shared by every Learning-to-Optimize (L2O) method in the LearningToOptimize ecosystem.
L2OCore defines what an L2O method is (a type in a small hierarchy), which problems it accepts (supports), how its predictions are evaluated (evaluate) and the method-dispatched pipeline
ParametricProblem ─ decompose ─ generate_data ─ (train proxy) ─ complete ─ evaluatewith sane fallbacks for each method family. It depends only on JuMP, MathOptInterface and standard libraries, so method packages can depend on it without pulling in a machine-learning framework.
Conventions:
- Batch-first: the batch is always the last dimension. Parameters are
num_parameters × B, primal predictionsnum_decision_variables × B, dual predictionsnum_duals × B. - Element-type generic: evaluators are parametrized by the element type.
- Minimal scalar indexing in vectorized evaluation code so arrays can be moved to accelerators by a future kernels extension.
Methods and proxies
L2OCore.AbstractL2OMethod — Type
AbstractL2OMethodSupertype of every Learning-to-Optimize method.
A method is a (usually small, immutable) struct holding its hyper-parameters. Concrete methods subtype one of the three families AbstractPrimalMethod, AbstractDualMethod or AbstractPrimalDualMethod; the family selects the fallback behavior of decompose, generate_data, loss and complete.
To add a method, a package defines
struct MyMethod <: L2OCore.AbstractPrimalMethod
ρ::Float64
end
L2OCore.supports(::MyMethod, ::L2OCore.LinearConic) = trueand overrides only the pipeline steps that differ from the family fallback.
L2OCore.AbstractPrimalMethod — Type
AbstractPrimalMethod <: AbstractL2OMethodMethods whose proxy predicts (a subset of) the primal decision variables, e.g. penalty methods, DC3, LDF.
L2OCore.AbstractDualMethod — Type
AbstractDualMethod <: AbstractL2OMethodMethods whose proxy predicts (a subset of) the dual variables, e.g. Dual Lagrangian Learning (DLL). A dual feasible prediction gives a valid bound on the optimal value through dual_bound.
L2OCore.AbstractPrimalDualMethod — Type
AbstractPrimalDualMethod <: AbstractL2OMethodMethods that predict both primal and dual variables, e.g. primal-dual learning with an augmented Lagrangian (ALM/PDL).
L2OCore.AbstractMethodWrapper — Type
AbstractMethodWrapper <: AbstractL2OMethodA method that wraps another method and changes only part of its behavior — the hook for method-agnostic add-ons such as derivative (Sobolev) supervision or extra regularizers. A wrapper must implement
L2OCore.inner_method(w)→ the wrapped method;L2OCore.extra_loss(w, pipe, inputs, output; targets, proxy, kwargs...)→ the additional loss term (a scalar).
Leave the pipe, inputs and output arguments untyped (or typed no more narrowly than the fallbacks) to avoid method ambiguities. Everything else (family, supports, decompose, generate_data, complete) is forwarded to the inner method, and loss is loss(inner) + extra_loss(wrapper). A wrapper may override any of them, e.g. generate_data to attach derivative labels with with_derivatives.
L2OCore.inner_method — Function
inner_method(w::AbstractMethodWrapper) -> AbstractL2OMethodThe method wrapped by w. Fallback: the field w.inner.
L2OCore.extra_loss — Function
extra_loss(w::AbstractMethodWrapper, pipe, inputs, output; kwargs...) -> RealAdditional loss term contributed by a wrapper; see AbstractMethodWrapper.
L2OCore.method_family — Function
method_family(method::AbstractL2OMethod)Return PrimalFamily(), DualFamily() or PrimalDualFamily().
L2OCore.PrimalFamily — Type
PrimalFamily()Value of method_family for AbstractPrimalMethods. Family values are convenient for code that branches on what is predicted without dispatching on the method type itself (for example, data recorders).
L2OCore.DualFamily — Type
DualFamily()Value of method_family for AbstractDualMethods.
L2OCore.PrimalDualFamily — Type
PrimalDualFamily()Value of method_family for AbstractPrimalDualMethods.
L2OCore.SupervisedMSE — Type
SupervisedMSE()Plain value supervision: the proxy predicts all decision variables and is trained on solver labels with the mean squared error
\[\mathcal{L}(θ) = \frac{1}{N n} \sum_{i=1}^{N} \big\| \hat g_θ(p_i) - x^\star(p_i) \big\|_2^2 ,\]
the empirical-risk-minimization baseline of the optimization-proxy literature (the value term of supervised Sobolev training). It is the primal family fallback made concrete: generate_data solves every sampled instance for primal labels, complete is the identity and loss is the supervised MSE against targets.
It needs a solver that returns (locally) optimal primal solutions for the sampled parameters and accepts any problem class, since labels are only data. A regression proxy is in general infeasible; measure its violations with evaluate.
L2OCore.AbstractProxyModel — Type
AbstractProxyModelOptional supertype for proxy models (the learned map from parameters to raw outputs).
L2OCore is framework-agnostic: any callable f(inputs::AbstractMatrix) returning an output_dimension × B array can be used as a proxy (a Flux.Chain, a closure over a Lux model and its state, a plain function). Subtyping AbstractProxyModel is only needed to attach extra behavior, for example a custom predict_batch or trainable-parameter handling.
L2OCore.predict_batch — Function
predict_batch(proxy, inputs::AbstractMatrix)Apply a proxy to a batch of inputs (input_dimension × B) and return the raw output (output_dimension × B). The fallback calls proxy(inputs); extend it for proxies that are not directly callable.
Problems and classes
L2OCore.AbstractProblemClass — Type
AbstractProblemClassTrait describing the mathematical class of a parametric problem for fixed parameters. Methods declare which classes they accept with supports.
The built-in classes are ordered from most to least structured: LinearConic ⊂ ConvexQuadratic (as objective classes), SmoothNonlinear and MixedInteger. Packages may add classes by subtyping AbstractProblemClass (or AbstractConvexClass) and passing the class explicitly to ParametricProblem.
L2OCore.AbstractConvexClass — Type
AbstractConvexClass <: AbstractProblemClassProblem classes for which every instance (for fixed parameters) is a convex optimization problem, so that weak and strong duality arguments (under a constraint qualification) apply.
L2OCore.LinearConic — Type
LinearConic()Affine objective, affine constraint functions in (products of) closed convex cones: LPs, SOCPs, SDPs, exponential-cone programs, …
Parameters may appear affinely in the objective and in the constraint constants.
L2OCore.ConvexQuadratic — Type
ConvexQuadratic()Convex quadratic objective (½xᵀQx + cᵀx with Q ⪰ 0 for minimization, Q ⪯ 0 for maximization) and affine conic constraints.
L2OCore.SmoothNonlinear — Type
SmoothNonlinear()Continuous problems with nonlinear (or nonconvex quadratic) objective or constraints, e.g. AC optimal power flow. Only first-order stationarity is meaningful; weak duality still holds but certificates require extra work.
L2OCore.MixedInteger — Type
MixedInteger()Problems with integrality restrictions (Integer, ZeroOne, semi-continuous or SOS constraints).
L2OCore.detect_problem_class — Function
detect_problem_class(model::JuMP.Model; atol = 1e-9) -> AbstractProblemClassInspect a JuMP model and return the most structured built-in class that describes it:
- any integrality/SOS/semi-continuous constraint →
MixedInteger; - any nonlinear expression, legacy
@NLblock or quadratic constraint with a product of two decision variables →SmoothNonlinear; - quadratic objective with a product of decision variables → convexity is checked numerically (
eigmin(sQ) ≥ -atol,s = ±1for the sense):ConvexQuadraticif convex,SmoothNonlinearotherwise; - otherwise
LinearConic.
Products parameter × variable do not change the class (for fixed parameters they are affine in the decision variables).
L2OCore.AbstractParametricProblem — Type
AbstractParametricProblemSupertype of parametric problems, independent of the modeling front end. ParametricProblem is the JuMP front end; other front ends (for example an ExaModels-based one) subtype this and implement problem_class, num_parameters, num_decision_variables, num_duals, objective_sign and default_evaluator (and solve_instances to support solver-labeled data).
L2OCore.ParametricProblem — Type
ParametricProblem(model::JuMP.Model; class = detect_problem_class(model))A parametric optimization problem: a JuMP model in which the problem data that changes between instances are declared as parameters (@variable(model, p in MOI.Parameter(value))).
The wrapper fixes three layouts used throughout the ecosystem:
- inputs:
parameters, in creation order (num_parameters × B); - primal:
decision_variables= all non-parameter variables in creation order (num_decision_variables × B); - dual:
constraint_refs, including variable bounds but not parameter or integrality constraints; constraintiowns the rowsdual_layout(problem)[i](num_duals × B). Signs follow the MathOptInterface convention returned byJuMP.dual.
class is a trait (AbstractProblemClass) used by supports; pass it explicitly to override detection (e.g. to declare a convex QCQP or a custom class).
Fields are considered internal; use the accessor functions.
L2OCore.problem_class — Function
problem_class(problem::ParametricProblem) -> AbstractProblemClassL2OCore.parameters — Function
parameters(problem::ParametricProblem) -> Vector{JuMP.VariableRef}Parameters of the problem, in input order.
L2OCore.decision_variables — Function
decision_variables(problem::ParametricProblem) -> Vector{JuMP.VariableRef}Non-parameter variables, in primal-prediction order.
L2OCore.constraint_refs — Function
constraint_refs(problem::ParametricProblem) -> Vector{JuMP.ConstraintRef}Constraints (including variable bounds) in dual-prediction order.
L2OCore.num_parameters — Function
num_parameters(problem::ParametricProblem) -> IntL2OCore.num_decision_variables — Function
num_decision_variables(problem::ParametricProblem) -> IntL2OCore.num_duals — Function
num_duals(problem::ParametricProblem) -> IntTotal scalar dimension of all constraints in constraint_refs.
L2OCore.dual_layout — Function
dual_layout(problem::ParametricProblem) -> Vector{UnitRange{Int}}Rows of a dual prediction owned by each constraint in constraint_refs.
L2OCore.parameter_values — Function
parameter_values(problem::ParametricProblem) -> Vector{Float64}Current values of the parameters stored in the JuMP model (a single instance).
L2OCore.objective_sign — Function
objective_sign(problem) -> Int1 for minimization (and feasibility) problems, -1 for maximization; objective_sign(problem) * objective is always to be minimized.
L2OCore.supports — Function
supports(method::AbstractL2OMethod, class::AbstractProblemClass) -> BoolWhether method is defined for problems of class, i.e. whether the mathematical assumptions of the method hold for that class. The fallback is false: a method must opt in explicitly, class by class, e.g.
L2OCore.supports(::MyMethod, ::L2OCore.AbstractConvexClass) = trueThere is deliberately no silent fallback that would run a method on a class its derivation does not cover; see check_supports.
L2OCore.check_supports — Function
check_supports(problem::ParametricProblem, method::AbstractL2OMethod)Throw an UnsupportedProblemError unless supports(method, problem_class(problem)). Called by L2OPipeline before anything else.
L2OCore.UnsupportedProblemError — Type
UnsupportedProblemError(method, class)Thrown by check_supports when a method is used on a problem class it does not support.
Evaluation
L2OCore.AbstractEvaluator — Type
AbstractEvaluatorBatch evaluation backend for a ParametricProblem. Evaluators turn batches of parameters P (num_parameters × B), primal points X (num_decision_variables × B) and dual points Y (num_duals × B) into objective values, constraint violations and dual bounds.
Built-in backends:
MatrixEvaluator: extractsA,Q,c, … once and evaluates with array operations (vectorized, differentiable by array AD, element-type generic). Used forLinearConicandConvexQuadraticproblems whose parameters enter affinely.JuMPEvaluator: per-instance fallback throughJuMP.value; works for any expression JuMP can evaluate (including nonlinear) but is not meant to be differentiated.
Extension point. Kernel packages (e.g. an ExaModels/BatchNLPKernels extension) add a backend by subtyping AbstractEvaluator and implementing
| function | required | returns |
|---|---|---|
batch_objective(ev, X, P) | yes | length-B vector |
constraint_values(ev, X, P) | yes | num_duals × B |
row_violation(ev, X, P) | yes | num_duals × B, ≥ 0 |
equality_rows(ev) | yes | BitVector of length num_duals |
cone_violation(ev, X, P) | if non-decomposable cones | n_cones × B, ≥ 0 |
dual_bound(ev, Y, P) | for dual methods | (bound, infeasibility) vectors |
and, optionally, a method of default_evaluator for the problems it should handle.
L2OCore.MatrixEvaluator — Type
MatrixEvaluator(problem::ParametricProblem; T = Float64)Matrix-form evaluator for problems of the form (for each instance p)
\[\min_x \; \tfrac12 x^\top Q x + c^\top x + x^\top H p + c_p^\top p + \tfrac12 p^\top Q_{pp} p + c_0 \quad \text{s.t.} \quad A x + B p + b \in \mathcal{K}\]
where 𝒦 is the product of the constraint sets in dual_layout order (max is handled through the sense). Box-like sets become row bounds l ≤ Ax + Bp + b ≤ u; other cones are kept as blocks.
All batch operations are matrix products and broadcasts, so they are vectorized, allocation-light and differentiable with array AD (Zygote, Enzyme, …). cone_violation and the cone part of dual_bound evaluate MOI.Utilities.distance_to_set per column (differentiable with Zygote for the second-order cone; not GPU-friendly).
L2OCore.JuMPEvaluator — Type
JuMPEvaluator(problem::ParametricProblem)Reference evaluator that loops over the batch and evaluates every expression with JuMP.value(var_value, expr). It supports anything JuMP can evaluate (affine, quadratic and GenericNonlinearExpr functions, any MOI set with MOI.Utilities.distance_to_set) and serves as the ground truth against which faster backends are tested. It is not meant for training loops.
dual_bound is not available for this backend.
L2OCore.default_evaluator — Function
default_evaluator(problem::ParametricProblem; T = Float64) -> AbstractEvaluatorMatrixEvaluator when the problem can be put in matrix form (affine constraints, at most quadratic objective, parameters entering affinely), otherwise JuMPEvaluator. The result is cached in the problem.
L2OCore.has_matrix_form — Function
has_matrix_form(problem::ParametricProblem) -> BoolWhether MatrixEvaluator can represent problem: affine constraint functions (parameters may appear in the constants), at most quadratic objective, no legacy @NL block.
L2OCore.batch_objective — Function
batch_objective(ev::AbstractEvaluator, X, P) -> AbstractVectorObjective value of each column of X (with parameters the matching column of P), in the sense of the model (maximization objectives are not negated).
L2OCore.constraint_values — Function
constraint_values(ev::AbstractEvaluator, X, P) -> AbstractMatrixValue of every constraint function, stacked in dual_layout order (num_duals × B).
L2OCore.row_violation — Function
row_violation(ev::AbstractEvaluator, X, P) -> AbstractMatrixElement-wise violation max(l - f, 0) + max(f - u, 0) of every row whose set is a box (EqualTo, GreaterThan, LessThan, Interval, Zeros, Nonnegatives, Nonpositives), and 0 for rows of non-decomposable cones (see cone_violation). Shape num_duals × B.
L2OCore.cone_violation — Function
cone_violation(ev::AbstractEvaluator, X, P) -> AbstractMatrixEuclidean distance of each non-decomposable conic constraint (second-order, PSD, exponential, …) to its set, n_cones × B. The fallback returns a 0 × B matrix.
L2OCore.equality_rows — Function
equality_rows(ev::AbstractEvaluator) -> BitVectorMask of rows (in dual_layout order) that are equality constraints.
L2OCore.bound_rows — Function
bound_rows(ev::AbstractEvaluator) -> BitVectorMask of rows that are variable bounds (VariableRef-in-set constraints).
L2OCore.dual_bound — Function
dual_bound(ev::AbstractEvaluator, Y, P; atol = 1e-6) -> (bound, infeasibility)Value of the Lagrangian dual function at each column of Y (signs as returned by JuMP.dual) and the dual infeasibility of that column.
By weak duality, whenever infeasibility[k] ≤ atol, bound[k] is a lower bound (upper bound for maximization) on the optimal value of instance k, up to infeasibility[k] * ‖x⋆‖₁ when the stationarity residual is nonzero (see the Theory page). Columns that are not dual feasible get bound = -Inf (+Inf for maximization).
Dual signs follow JuMP.dual (the MathOptInterface convention). For quadratic objectives sQ ⪰ 0 is required and verified; otherwise no bound is returned.
L2OCore.EvaluationReport — Type
EvaluationReportPer-instance quality metrics returned by evaluate. Every field is a length-B vector or nothing when it does not apply.
objective: primal objective of the prediction;max_violation: largest violation over all constraints;max_equality_violation,max_inequality_violation;dual_bound,dual_infeasibility: seedual_bound;gap:|objective - dual_bound| / max(1, |objective|)when both a primal and a feasible dual prediction are available.
L2OCore.evaluate — Function
evaluate(pipe::L2OPipeline, inputs, prediction; atol = 1e-6)
evaluate(problem::ParametricProblem, inputs, prediction;
evaluator = default_evaluator(problem), atol = 1e-6)Quality metrics of a batch of completed predictions as an EvaluationReport: objective and violations of the primal part, dual bound and dual infeasibility of the dual part, and the gap when both exist.
Data
L2OCore.AbstractParameterSampler — Type
AbstractParameterSamplerDistribution of problem parameters. Implement sample_parameters(sampler, rng, n) returning a num_parameters × n matrix. Any function f(rng, n) can be used directly as a sampler.
L2OCore.sample_parameters — Function
sample_parameters(sampler, rng::Random.AbstractRNG, n::Integer) -> AbstractMatrixDraw n parameter vectors, one per column.
L2OCore.BoxSampler — Type
BoxSampler(lower, upper)Independent uniform parameters, p[i] ~ U(lower[i], upper[i]).
L2OCore.ScaledSampler — Type
ScaledSampler(nominal; low = 0.8, high = 1.2)
ScaledSampler(problem::ParametricProblem; low = 0.8, high = 1.2)Multiplicative perturbation of a nominal parameter vector, p[i] = nominal[i] * U(low, high). With a problem, the nominal values are the current parameter values of the JuMP model.
L2OCore.L2ODataset — Type
L2ODatasetColumns-as-samples dataset (N samples):
inputs:num_parameters × N(always present);primal:num_decision_variables × Nornothing;dual:num_duals × Nornothing;objective: lengthNornothing;status: termination status per sample ornothing(unsolved data, e.g. for self-supervised methods);derivatives: anAbstractDerivativeLabelsornothing;metadata: free-formDict{String,Any}(problem id, sampler, solver, tolerances…), mirrored by the dataset-card conventions in the design docs.
Samples whose solve failed hold NaN labels; filter them with ds[findall(ok)] where ok comes from status.
L2OCore.num_samples — Function
num_samples(ds::L2ODataset) -> IntL2OCore.with_derivatives — Function
with_derivatives(ds::L2ODataset, labels::Union{Nothing,AbstractDerivativeLabels}) -> L2ODatasetCopy of ds with its derivative labels replaced (datasets are immutable).
L2OCore.AbstractDerivativeLabels — Type
AbstractDerivativeLabelsOptional derivative (sensitivity) labels attached to a dataset, e.g. computed by differentiating through the solver. Datasets never require them; methods that use them (Sobolev-type training) check for their presence.
L2OCore.JacobianLabels — Type
JacobianLabels(J)Full Jacobians of the primal solution with respect to the parameters: J is num_decision_variables × num_parameters × N.
L2OCore.PullbackLabels — Type
PullbackLabels(seeds, values)Vector–Jacobian products: for each sample k, values[:, k] = J_kᵀ seeds[:, k] where J_k = ∂x*/∂p; seeds is num_decision_variables × N, values is num_parameters × N. Cheaper than full Jacobians and sufficient for pullback-based Sobolev losses.
L2OCore.PushforwardLabels — Type
PushforwardLabels(directions, values)Jacobian–vector products: for each sample k, values[:, k] = J_k directions[:, k] where J_k = ∂x*/∂p; directions is num_parameters × N, values is num_decision_variables × N. The forward-mode counterpart of PullbackLabels: cheaper than full Jacobians when the number of parameters is large, and sufficient for directional Sobolev losses.
L2OCore.solve_instances — Function
solve_instances(problem, inputs; optimizer = nothing, primal = true,
dual = false, silent = true) -> L2ODatasetSolve one instance per column of inputs by setting the parameter values of the JuMP model and calling optimize!. Records the objective value, termination status and, as requested, the primal solution (decision_variables order) and the dual solution (dual_layout order, JuMP.dual signs).
The JuMP model is modified in place (parameter values, optimizer).
Pipeline
L2OCore.Prediction — Type
Prediction(; primal = nothing, dual = nothing)A batch of (completed) predictions: primal is num_decision_variables × B in decision_variables order, dual is num_duals × B in dual_layout order. Either may be nothing.
L2OCore.AbstractDecomposition — Type
AbstractDecompositionMethod-specific structure computed once per problem by decompose: which quantities the proxy predicts and how the rest is recovered by complete. Examples: DLL's split of the duals into predicted y and completed z; DC3's independent/dependent variables. A decomposition must implement output_dimension.
L2OCore.FullSpaceDecomposition — Type
FullSpaceDecomposition(primal::Bool, dual::Bool)The family fallback: the proxy predicts all primal variables (if primal) followed by all duals (if dual), stacked vertically, and completion is the identity.
L2OCore.L2OPipeline — Type
L2OPipeline(problem::ParametricProblem, method::AbstractL2OMethod;
evaluator = default_evaluator(problem))Bind a method to a problem: checks supports (throwing UnsupportedProblemError), computes decompose once and keeps an AbstractEvaluator. All pipeline steps take the pipeline:
pipe = L2OPipeline(problem, method)
data = generate_data(pipe; sampler, n = 100, optimizer)
ℓ = loss(pipe, data.inputs, proxy(data.inputs))
pred = complete(pipe, inputs, proxy(inputs))
evaluate(pipe, inputs, pred)L2OCore.decompose — Function
decompose(problem::ParametricProblem, method::AbstractL2OMethod) -> AbstractDecompositionCompute the method-specific structure of problem. Called once by L2OPipeline after check_supports.
Fallback by family (FullSpaceDecomposition): primal methods predict all primal variables, dual methods all duals, primal-dual methods both.
L2OCore.input_dimension — Function
input_dimension(pipe::L2OPipeline) -> IntNumber of rows of the proxy input; the fallback is num_parameters.
L2OCore.output_dimension — Function
output_dimension(decomposition::AbstractDecomposition) -> Int
output_dimension(pipe::L2OPipeline) -> IntNumber of rows the proxy must output.
L2OCore.generate_data — Function
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"].
generate_data(pipe::L2OPipeline; sampler, n, rng = Random.default_rng(), kwargs...)
generate_data(method, pipe; sampler, n, rng, kwargs...) # extension pointBuild an L2ODataset for training pipe.method.
Family fallback: sample n parameter vectors from sampler and solve every instance with solve_instances (kwargs such as optimizer are forwarded), recording primal labels for primal methods, dual labels for dual methods and both for primal-dual methods. Methods override the second form, e.g. self-supervised methods that need only inputs, or DC3 storing only independent variables.
generate_data(::PenaltyMethod, pipe; sampler, n, rng, optimizer = nothing)Penalty training is self-supervised: only parameters are sampled. When an optimizer is given, instances are also solved so that the dataset carries reference optima for evaluation (objective gaps, dual bounds).
L2OCore.complete — Function
complete(pipe::L2OPipeline, inputs, output) -> Prediction
complete(method, pipe, inputs, output) # extension pointTurn the raw proxy output (output_dimension × B) into a Prediction in the method's own sense (projection, equality completion, dual completion, repair…). The FullSpaceDecomposition fallback only splits the output into primal and dual blocks.
Implementations should be written with array operations so they can be differentiated and run on accelerators when the loss needs them.
L2OCore.loss — Function
loss(pipe::L2OPipeline, inputs, output; targets = nothing) -> Real
loss(method, pipe, inputs, output; targets) # extension pointTraining loss of a batch of raw proxy outputs. Training loops should also pass proxy = <the proxy> so that loss terms which differentiate the proxy with respect to its inputs (Sobolev / derivative supervision) can use it; methods that do not need it ignore it. Fallback: supervised mean squared error between the completed prediction and the labels in targets (an L2ODataset restricted to the batch, or a Prediction). Self-supervised methods override it (see the penalty method in LearningToOptimize.jl).
L2OCore.train_proxy! — Function
train_proxy!(method, pipe::L2OPipeline, proxy, data; kwargs...)Train proxy in place for method. L2OCore defines no method for it, since training depends on the ML framework; framework-specific packages (e.g. LearningToOptimize.jl for Flux) and method packages add methods.
Repair layers
L2OCore.BoundedOutput — Type
BoundedOutput(inner::AbstractL2OMethod; mode = :smooth)Wrapper that maps the primal part of the raw proxy output into the variable bounds $l ≤ x ≤ u$ before the inner method sees it, both in loss and in complete — a bound-preserving output layer.
With mode = :smooth each coordinate uses
\[x_j = \begin{cases} l_j + (u_j - l_j)\,σ(z_j) & l_j, u_j \text{ finite},\\ l_j + \operatorname{softplus}(z_j) & \text{only } l_j \text{ finite},\\ u_j - \operatorname{softplus}(-z_j) & \text{only } u_j \text{ finite},\\ z_j & \text{free}, \end{cases}\]
(fixed variables are set to their value), which is smooth and never has a zero gradient; mode = :clamp uses the Euclidean projection onto the box, $x = \min(\max(z, l), u)$, whose gradient vanishes outside the box.
The inner method must use a FullSpaceDecomposition with primal predictions (its raw output starts with all primal variables); the bounds are those declared on the JuMP variables.
Every completed primal prediction satisfies the variable bounds. Dual outputs are not modified, so a dual bound of the inner method is unchanged; other primal properties of the inner method (e.g. satisfied equalities) can be lost, since changing $x$ can break them.
L2OCore.bound_transform — Function
bound_transform(d::BoundedOutputDecomposition, Z::AbstractMatrix, mode::Symbol)Apply the bound-preserving map of BoundedOutput to the primal block Z (num_decision_variables × B). Non-mutating and differentiable with array AD.
L2OCore.BoundedOutputDecomposition — Type
BoundedOutputDecompositionDecomposition of a BoundedOutput pipeline: the inner decomposition and the variable bounds.
L2OCore.ProjectionRepair — Type
ProjectionRepair(inner::AbstractL2OMethod, optimizer)Wrapper that repairs the primal prediction of inner at inference time by the Euclidean projection onto the feasible set $\mathcal F(p)$ of each instance,
\[Π_{\mathcal F(p)}(\hat x) = \arg\min_{x \in \mathcal F(p)} \; \|x - \hat x\|_2^2,\]
solved with optimizer (any JuMP solver for the resulting convex QP or conic program). Training is unchanged: loss is the inner loss.
The problem class must be convex (so $\mathcal F(p)$ is closed and convex and the projection is unique) and the feasible set of each instance non-empty. The repaired prediction is then feasible to the solver's tolerance, and dual outputs pass through unchanged. The projection is nonexpansive: for every feasible $x$, in particular an optimal $x^\star$, $\|Π(\hat x) - x\| \le \|\hat x - x\|$. The objective value need not improve.
L2OCore.project_onto_feasible_set — Function
project_onto_feasible_set(d::ProjectionDecomposition, inputs, X) -> MatrixEuclidean projection of each column of X onto the feasible set of the matching instance. Columns whose projection problem is not solved to optimality are returned as NaN.
L2OCore.ProjectionDecomposition — Type
ProjectionDecompositionDecomposition of a ProjectionRepair pipeline: the inner decomposition and a copy of the JuMP model used for projections.