---
title: "OptNet: Differentiable Optimization as a Layer in Neural Networks"
description: "OptNet makes a constrained quadratic program a trainable neural network layer, with experiments in signal denoising and learning mini-Sudoku."
canonical: "https://research.elamur.ai/free/en/papers/amos-2017-optnet-differentiable-optimization-layer-neural/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/amos-2017-optnet-differentiable-optimization-layer-neural/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2017](https://md.research.elamur.ai/free/en/papers/2017/) / OptNet: Differentiable Optimization as a Layer in Neural Networks

# OptNet: Differentiable Optimization as a Layer in Neural Networks

Paper · 2017 · Brandon Amos and J. Zico Kolter

**Authors:** [Brandon Amos](https://md.research.elamur.ai/free/en/authors/brandon-amos/) and [J. Zico Kolter](https://md.research.elamur.ai/free/en/authors/j-zico-kolter/) · **Year:** 2017 · **Venue:** arXiv:1703.00443 · **Licence:** [arXiv — non-exclusive license to distribute](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

[licence](http://arxiv.org/licenses/nonexclusive-distrib/1.0/)

- [PDF](https://arxiv.org/pdf/1703.00443)
- [arXiv 1703.00443](https://arxiv.org/abs/1703.00443)

## Summary

A prediction can be plausible in each of its parts and still fail as a whole. In mini-Sudoku, for instance, a digit may look like a good choice for a cell until it conflicts with a choice elsewhere on the board. OptNet gives a neural network a way to make related choices together. One layer turns its input into the coefficients of a constrained optimization problem, solves that problem, and sends the solution onward. The coefficients can be learned from examples, so the architecture can express relationships that the designer has left unspecified.

The paper develops this idea for quadratic programs. A quadratic objective ranks the candidate outputs, and linear equalities and inequalities specify which outputs are allowed. In the forward pass, the layer returns a minimizer. In the backward pass, it uses the equations that characterize the optimum to determine how the answer responds to changes in the coefficients. The authors build a solver that handles many small programs together on a GPU and reuses a matrix factorization from the forward pass to compute the gradients. For a batch of 128 randomly generated programs with 100 variables and 100 inequalities apiece, the batched solver averaged 0.18 seconds, compared with 4.7 seconds for Gurobi on a CPU.

The clearest demonstration is 4x4 Sudoku. The authors train on incomplete boards paired with their solutions and leave the puzzle-specific equalities for the layer to learn. The convolutional baseline fits the training puzzles closely, while OptNet generalizes better to held-out boards. The denoising experiment shows how much the starting structure can matter. Learning a signal-difference operator from a random start produces a recognizable pattern but poor predictions. Starting from the standard total variation operator and training from there improves test mean squared error by 12% relative to total variation. On MNIST, a fully connected network and a variant with an OptNet layer perform similarly. Together, the experiments show what a learned optimization layer can contribute when outputs have important dependencies, and how much that contribution depends on the task and the way the problem is parameterized.

## Deep dive: OptNet: Differentiable Optimization as a Layer in Neural Networks

OptNet makes a constrained quadratic program a trainable neural network layer, with experiments in signal denoising and learning mini-Sudoku. · about 36 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### When a layer has to make joint choices

A fully connected layer can combine information from all its inputs, and a convolutional network can build up interactions across positions through successive layers. The question OptNet asks is what computation a single layer should perform when the output itself has to obey relationships. A Sudoku row illustrates the distinction. The clues can inform every cell prediction, but the choices for those cells also have to agree with each other. A constraint can express such an agreement directly. An objective then decides which of the allowed assignments is preferable for the particular input.

Putting that decision inside the network changes where learning can act. Suppose an early layer supplies information that makes some solutions more attractive than others. Its training signal should reflect how the eventual solution changes when that information changes. The same applies if training changes the constraints themselves. A solver can supply an answer for the current coefficients, but training needs a way to assign credit or blame to those coefficients after the answer has been used. The paper therefore treats computing the solution and computing its sensitivity as parts of the same layer.

That distinction matters even when the optimization problem is familiar. In denoising, there is a natural reason to prefer an output with few abrupt changes. One can express that preference using a fixed formula and solve the resulting problem for every noisy signal. OptNet asks whether examples of clean and noisy signals can also determine which changes the formula should penalize. In a task with less obvious structure, such as learning from solved puzzles without being given their rules, the coefficients can instead describe relationships that the training examples must reveal. The designer still chooses the family of optimization problems and how information enters it. Training searches within that family.

The paper places this idea in a broader [machine learning](https://md.research.elamur.ai/free/en/concepts/machine-learning/) tradition in which inference is formulated as optimization. Examples include structured prediction, where different parts of a prediction depend on each other, and image restoration, where a reconstruction is chosen to satisfy a preference for plausible images while remaining consistent with an observation. The authors also point to control and physical simulation as areas where optimization already describes how to choose an action or a state. Their interest is in learning the ingredients of such a decision from data and making the resulting computation available inside a network.

#### How earlier approaches handled the solution

The paper describes several ways to train systems that use optimization for inference. Energy-based learning shapes a scoring function so that observed configurations receive low energy. The authors discuss work that puts structured prediction at the end of a network, including conditional random fields, as well as work that embeds energy-based prediction more deeply. They identify a practical difference in the supervision available. A training objective can score a final answer even when there is no observed target for the intermediate result of an optimization layer. A gradient through that intermediate result lets the final task supply the learning signal.

A second option is to derive the optimizer explicitly. For an unconstrained quadratic objective, a solution formula can make the derivative accessible as well. The authors cite denoising work where this route is practical. General linear inequalities complicate that strategy because the constraints that determine the answer depend on the input. The same coefficients can describe a feasible region in which one input produces an interior solution and another puts the solution on a boundary. A single unconstrained solution formula does not capture both cases.

Another approach runs an iterative algorithm inside the network and differentiates through its updates. In the examples discussed by the paper, a first-order procedure such as gradient descent becomes a sequence of computations in the forward pass, and training follows that sequence in reverse. The authors cite the use of this idea to stabilize training in work on [Unrolled Generative Adversarial Networks](https://md.research.elamur.ai/free/en/papers/metz-2016-unrolled-generative-adversarial-networks/). The cost is that the update sequence itself enlarges the computation being differentiated. Constraints can add a projection step, which turns an intermediate point into one that satisfies the restrictions and may itself be difficult to differentiate. With OptNet, the derivative comes from the conditions at the final solution. The solver's path to that solution can therefore be chosen for numerical efficiency.

The closest prior approaches differentiate the minimizing argument itself. The paper connects these methods to sensitivity analysis, which asks how a solution changes after a perturbation, and bilevel optimization, in which an outer objective depends on the answer to an inner problem. The authors describe earlier work that treats equalities exactly and handles inequalities through a barrier, along with approaches specialized to particular algorithms or objectives. They also discuss implicit differentiation in a variational inference network with coordinate subspace constraints. OptNet gives a single treatment of linear equalities and inequalities for the quadratic program and allows the layer to sit at an intermediate position. The important addition for inequalities is to differentiate the equation linking a constraint's slack to its multiplier. That equation carries information about which bounds govern the answer.

### The method, step by step

#### Turning an input into a decision problem

The forward computation starts with an ordinary network activation. A differentiable mapping can turn that activation into any of the coefficients of a quadratic program. Which coefficients depend on the input is a design choice. An input can change the relative costs of possible answers while leaving the feasible region fixed. It can also shift the bounds, change the relationships among output coordinates, or affect several parts of the problem at once. Some coefficients can be learned directly and shared across examples. Others can be fixed by the architecture.

The quadratic program contains a candidate answer, an objective, and a feasible region. The curvature in the objective determines how expensive it is to move away from a preferred part of that region. The linear objective term can change where the preference lies. Equalities can require coordinates to balance exactly. Inequalities put limits on particular coordinates or combinations of coordinates. The solver searches over all allowed candidates together, so a bound involving several coordinates can make the preferred value of one coordinate depend on the others.

```
zᵢ₊₁ = argmin over z { ½ zᵀQz + qᵀz  subject to  Az = b, Gz ≤ h }
```

Here `i` is the index of the preceding layer, `zᵢ₊₁` is the output of the optimization layer, and `z` is its candidate output vector. The `argmin` returns the candidate that minimizes the objective. `Q` is the symmetric matrix of quadratic coefficients, `q` is the vector of linear coefficients, `ᵀ` denotes transpose, and `½` is the conventional factor in the quadratic term. `A` and `b` give the coefficient matrix and target vector for the equalities. `G` and `h` give the coefficient matrix and upper bounds for the inequalities. The equality sign applies to every row of the equality system, and `≤` applies component by component. The previous activation `zᵢ` can enter any of the six coefficient arrays through a differentiable mapping.

The vector `z` has `n` coordinates. With `m` equalities, `A` has `m` rows and `n` columns, and `b` has `m` entries. With `p` inequalities, `G` has `p` rows and `n` columns, and `h` has `p` entries. A positive semidefinite `Q` gives the objective convex curvature. A positive definite `Q` gives strict convexity, so a feasible problem has a unique minimizing vector. Feasibility comes from the constraints admitting a common solution. In some of the paper's constructions, the right-hand sides are built from a witness point that is feasible by design. The overall network can use the entire minimizing vector or take a subset if the program has internal variables that serve only to express the computation.

Forward and backward passes through OptNet The steps in order.

The forward pass ends with the minimizing vector. The outer training loss can use it directly, as in the denoising task, or receive the result of further layers. During back-propagation the layer receives a vector that says how the loss changes with its output coordinates. It has to translate that vector into gradients for costs, bounds, and the other coefficients that produced the optimizer. Those gradients then pass through the differentiable mappings that generated the coefficients, using the ordinary chain rule.

#### Reading the optimum from its equations

The method starts from the Lagrangian, which adds a weighted residual for each constraint to the objective. The weights, called dual variables or multipliers, will be found along with the minimizing vector. Equality multipliers can have either sign. Inequality multipliers must be non-negative under the convention that the left side of each inequality cannot exceed its bound.

```
L(z, ν, λ) = ½ zᵀQz + qᵀz + νᵀ(Az − b) + λᵀ(Gz − h)
```

`L` is the Lagrangian. Its arguments are the candidate vector `z`, the equality multipliers `ν`, and the inequality multipliers `λ`. `Q` and `q` are the quadratic and linear objective coefficients. `A` and `b` describe the equalities, and `G` and `h` describe the inequalities. The differences `Az − b` and `Gz − h` are the constraint residuals, and `ᵀ` denotes transpose.

At a solution, the objective's gradient is balanced by the constraint terms. The equalities are satisfied and every inequality residual is nonpositive. Complementary slackness adds a condition on each inequality and its multiplier. If the solution sits strictly below an upper bound, that bound has zero multiplier. A positive multiplier indicates that the corresponding constraint holds at equality. A constraint can also be tight with a zero multiplier. That last case matters for differentiation, because the equations can lose information about how to respond to a perturbation at such a point.

```
⎡ Qz★ + q + Aᵀν★ + Gᵀλ★ ⎤
⎢ Az★ − b                 ⎥ = 0
⎣ D(λ★)(Gz★ − h)           ⎦
```

The star `★` denotes the solution, so `z★` is the primal optimum and `ν★` and `λ★` are the corresponding multipliers. The first row block expresses stationarity, the second enforces the equality constraints, and the third expresses complementary slackness. `D` turns its vector argument into a diagonal matrix, making the last product a separate multiplication for each inequality. `Q`, `q`, `A`, `b`, `G`, and `h` are the program coefficients, and `ᵀ` denotes transpose. The `0` on the right represents a vector of zeros. These equations are used together with primal inequality feasibility and the nonnegativity of `λ★`. Collectively these are the Karush–Kuhn–Tucker conditions, called KKT conditions in the paper.

Complementarity records something that the forward answer alone need not make obvious. Imagine changing an upper bound that the optimizer currently leaves unused. As long as the bound stays away from the answer, the adjustment places no new demand on the output. Now consider moving a bound that is holding the optimizer at a boundary. The old answer can cease to be feasible, forcing a change in the output. At a transition between these situations, the change in the answer may depend on the direction of the perturbation. The derivative is thus a property of the program at its current solution, including the state of its constraints.

#### Differentiating the decision

To compute a local sensitivity, the authors perturb the coefficients and ask how the optimum and multipliers must move so that the optimality equations continue to hold to first order. The product rule supplies separate terms for changes in the coefficients and changes in the solution. In the equality residual, for example, a change in the matrix acts on the old solution, while the old matrix acts on the change in the solution. The same distinction applies to the inequality matrix. Complementarity produces two terms because both the inequality multiplier and the slack can change.

```
⎡ Q         Gᵀ           Aᵀ ⎤ ⎡ dz ⎤     ⎡ (dQ)z★ + dq + (dG)ᵀλ★ + (dA)ᵀν★ ⎤
⎢ D(λ★)G    D(Gz★ − h)    0  ⎥ ⎢ dλ ⎥ = − ⎢ D(λ★)((dG)z★ − dh)              ⎥
⎣ A         0             0  ⎦ ⎣ dν ⎦     ⎣ (dA)z★ − db                     ⎦
```

A `d` before a symbol denotes its first-order change. `dz`, `dλ`, and `dν` are the resulting changes in the primal solution, inequality multipliers, and equality multipliers. The known perturbations on the right are `dQ`, `dq`, `dG`, `dA`, `dh`, and `db`. A star marks a value at the original solution, `D` constructs a diagonal matrix, `ᵀ` denotes transpose, and `0` denotes a zero block. The coefficient matrices and vectors have the same roles as in the quadratic program. The minus sign moves the terms caused directly by changes in the coefficients to the right of the system.

Away from degeneracy, solving this linear system gives the changes caused by a specified perturbation. It also offers a way to compute a whole Jacobian, the array that records how every output coordinate responds to every input coordinate. To find the Jacobian with respect to the equality targets, for example, one can put the identity matrix in place of the perturbation of those targets and set the other perturbations to zero. Each column of the resulting primal block gives the response to changing the corresponding target. This is a way to understand what the differential system computes. In training, forming the entire array would do more work than the outer loss needs.

Back-propagation needs only the sensitivity after weighting the outputs by the gradient of a scalar loss. The authors therefore solve a transposed system whose right-hand side carries that gradient. Its unknowns are auxiliary vectors that summarize how the loss responds through stationarity, complementarity, and equality feasibility. One such solve provides the quantities needed for every coefficient. A layer with many learnable entries in a constraint matrix can use this method without a separate linear solve for each entry.

```
⎡ Q    GᵀD(λ★)      Aᵀ ⎤ ⎡ d_z ⎤     ⎡ (∂ℓ/∂z★)ᵀ ⎤
⎢ G    D(Gz★ − h)    0  ⎥ ⎢ d_λ ⎥ = − ⎢ 0           ⎥
⎣ A    0             0  ⎦ ⎣ d_ν ⎦     ⎣ 0           ⎦
```

`ℓ` is the scalar training loss, and `∂ℓ/∂z★` is the incoming row vector of partial derivatives with respect to the layer output. `d_z`, `d_λ`, and `d_ν` are the three auxiliary blocks, distinct from the perturbations `dz`, `dλ`, and `dν`. The symbols `Q`, `G`, `A`, and `h` denote program data. `λ★` and `z★` are the optimal multiplier and minimizing vector, `D` forms a diagonal matrix, `ᵀ` denotes transpose, and `0` marks zero blocks. The negative sign uses the sign convention of the forward differential system.

Once this solve is available, extracting the gradients requires combinations of vectors and outer products. The first example is the linear objective. A change in its coefficients enters stationarity directly, so the corresponding gradient is the primal auxiliary vector.

```
∇q ℓ = d_z
```

`∇q ℓ` denotes the gradient of `ℓ` with respect to the linear objective vector `q`, with the letter after `∇` identifying the coefficient being differentiated. `d_z` is the primal block of the auxiliary solution.

```
∇Q ℓ = ½(d_z z★ᵀ + z★ d_zᵀ)
```

`∇Q ℓ` is the loss gradient for the symmetric quadratic matrix `Q`. `d_z` is the primal auxiliary block, `z★` is the optimum, and `ᵀ` transposes a vector to form an outer product with the other vector. Adding the two orders and multiplying by `½` produces a symmetric gradient, consistent with the role of `Q`.

An equality contributes through its residual and through stationarity. The matrix occurs in both, which accounts for two terms in its gradient. Its right-hand side occurs only in the residual and enters there with a minus sign.

```
∇A ℓ = d_ν z★ᵀ + ν★ d_zᵀ
```

`∇A ℓ` is the loss gradient for the equality matrix `A`. `d_ν` is the equality block from the auxiliary solve, `z★` is the minimizing output, `ν★` is the optimal equality multiplier, and `d_z` is the primal auxiliary block. `ᵀ` denotes transpose and the two products have the shape of `A`.

```
∇b ℓ = −d_ν
```

`∇b ℓ` is the loss gradient for the equality targets `b`. The auxiliary vector `d_ν` carries their sensitivity, with the minus sign inherited from the equality residual.

The inequality matrix also contributes through both stationarity and a constraint equation. Here the latter contribution is weighted by the optimal inequality multipliers because the equation being differentiated is complementarity.

```
∇G ℓ = D(λ★)d_λ z★ᵀ + λ★ d_zᵀ
```

`∇G ℓ` is the loss gradient for the inequality matrix `G`. `λ★` is the optimal inequality multiplier, `D(λ★)` places it on the diagonal of a matrix, and `d_λ` is the inequality auxiliary vector. `z★` is the optimum, `d_z` is the primal auxiliary vector, and `ᵀ` denotes transpose.

```
∇h ℓ = −D(λ★)d_λ
```

`∇h ℓ` is the loss gradient for the inequality bounds `h`. The optimal multiplier `λ★` provides the diagonal weights in `D(λ★)`, `d_λ` provides the auxiliary response, and the sign reflects the subtraction of the bounds in the original residual.

The terms have the same shapes as the coefficients being updated. If a coefficient is itself trainable, its gradient can go directly to the training algorithm. If it was produced by earlier network activations, the derivative of that mapping carries the training signal further back. A coefficient can also lie on both paths, as when a learned transformation maps the input into an objective. This is the link between sensitivity analysis of the inner problem and end-to-end learning of the outer network.

#### Making repeated solves practical

A training batch contains examples that may have different objectives or different feasible regions. The implementation performs the corresponding small solves in parallel using [GPU and parallel computing](https://md.research.elamur.ai/free/en/topics/gpu-parallel-computing/). The authors build a primal-dual interior-point solver. It works on the candidate solution and its multipliers simultaneously, using residuals to measure progress toward stationarity, feasibility, and complementarity. To put inequalities in a form suited to these updates, it introduces a non-negative slack vector. The slack tells how far the left side of each inequality is below its upper bound.

```
Gz + s = h
```

`G` is the inequality matrix, `z` is the current primal vector, `s` is the slack vector, and `h` is the vector of inequality bounds. With `s` non-negative, this equality expresses the original upper bounds. At a solution, complementary slackness concerns the products of the entries of `s` and the corresponding inequality multipliers.

An iteration computes an affine scaling direction and a centering and correction direction. The affine direction uses the current residuals to propose a move towards the optimality equations. The second direction corrects for the interaction between changes in slack and multiplier and adds a centering term. Both directions come from systems with the same coefficient matrix. The solver combines them and chooses a step size for the update, working with positive slack and multiplier values along the interior-point iterations.

```
K = ⎡ Q    0       Gᵀ    Aᵀ ⎤
    ⎢ 0    D(λ)    D(s)  0  ⎥
    ⎢ G    I       0     0  ⎥
    ⎣ A    0       0     0  ⎦
```

`K` is the linear system matrix for an iteration. Its columns act on proposed changes in `z`, `s`, `λ`, and `ν`, in that order, where `λ` and `ν` are the current inequality and equality multipliers. The quadratic and constraint matrices are `Q`, `G`, and `A`, and `ᵀ` denotes transpose. `D(λ)` and `D(s)` are diagonal matrices of the current multiplier and slack entries. `I` is the identity on the slack coordinates, and `0` marks zero blocks. The rows correspond to stationarity, complementarity, the equality with slack, and the original equality constraints.

```
K [Δzᵃᶠᶠ, Δsᵃᶠᶠ, Δλᵃᶠᶠ, Δνᵃᶠᶠ]ᵀ =
    [−(Aᵀν + Gᵀλ + Qz + q), −D(s)λ, −(Gz + s − h), −(Az − b)]ᵀ
```

The brackets collect vector blocks into columns, and `ᵀ` also denotes matrix transpose within a block. `K` is the current system matrix, `Δ` marks a proposed change, and `aff` marks the affine scaling direction. `z` and `s` are the current primal and slack vectors, and `λ` and `ν` are the current multipliers. `Q` and `q` define the objective, `A` and `b` define the equalities, and `G` and `h` define the inequalities. `D(s)` makes a diagonal matrix of the slack entries. The four right-hand blocks are the negatives of the current residuals.

```
μ = sᵀλ / p
```

`μ` is the paper's duality gap quantity for the iteration. `s` is the current slack vector, `λ` is the current inequality multiplier, `ᵀ` denotes transpose, and `p` is the number of inequality constraints. The scalar is the average of the componentwise products.

```
K [Δzᶜᶜ, Δsᶜᶜ, Δλᶜᶜ, Δνᶜᶜ]ᵀ =
    [0, σμ𝟙 − D(Δsᵃᶠᶠ)Δλᵃᶠᶠ, 0, 0]ᵀ
```

`K` is the same matrix as in the affine solve. `Δ` denotes a direction, `cc` identifies the centering and correction direction, and `aff` identifies the direction already found. The variables `z`, `s`, `λ`, and `ν` identify the primal, slack, inequality multiplier, and equality multiplier blocks. `σ` is the centering parameter of the solver procedure followed by the authors. `μ` is the gap quantity, `𝟙` is a vector of ones with one entry per inequality, and `D` forms a diagonal matrix. `ᵀ` stacks the blocks into column form, and `0` denotes a zero block. Only the complementarity block gets a new right-hand side.

The implementation scales the complementarity row by the reciprocal slacks to obtain a symmetric system. Eliminating variables then gives smaller systems. The authors describe factoring an inequality-sized block at each iteration and factoring the blocks associated with the primal dimension and equality dimension once at the start. The distinction matters because the slack and multiplier ratios change from iteration to iteration. Operations involving the parts that stay fixed can be reused. The implementation uses batched LU factorization and triangular solves through a custom CUBLAS extension.

At the end of the forward pass, the symmetrized system already has the factors needed for the derivative calculation. The backward pass changes the right-hand side to the incoming loss gradient and solves with those factors. In this formulation the inequality block it obtains is already scaled by the optimal multipliers. That is the combination of quantities used in the gradients for the inequality matrix and bounds.

```
Kₛᵧₘ [d_z, d_s, d̃_λ, d_ν]ᵀ = [−(∂ℓ/∂zᵢ₊₁)ᵀ, 0, 0, 0]ᵀ
```

`Kₛᵧₘ` is the symmetrized system at the solution. `d_z` and `d_ν` are the primal and equality blocks needed for the gradients. `d_s` is an auxiliary slack block. `d̃_λ` is the vector formed by multiplying `d_λ` componentwise by the optimal inequality multipliers. `ℓ` is the training loss, `zᵢ₊₁` is the optimization layer's output, and `∂ℓ/∂zᵢ₊₁` is the incoming row gradient. `ᵀ` denotes transpose and `0` denotes a zero block.

The computational saving is the reuse of a factorization. The backward pass still performs substitution with the saved factors and assembles the parameter gradients. The paper contrasts the quadratic cost of substitution with the cubic cost of a fresh dense factorization. The forward pass has already paid for factorization as part of finding the solution. The authors released the PyTorch solver as `qpth` and made the experiment code and data available in the `icml2017` branch of their OptNet repository.

#### What the layer can express

The paper compares the optimization layer with familiar rectified linear units, or ReLUs. A ReLU after an affine transformation keeps positive coordinates and sets negative ones to zero. The same operation arises by finding the closest non-negative vector to the affine prediction. Each coordinate solves an independent choice in this example. More general constraints can tie the coordinates together and make the choice for one coordinate depend on several others.

```
z★ = argmin over z { ‖z − Wx − b‖₂²  subject to  z ≥ 0 }
```

`x` is the input, `W` is the affine transformation matrix, and `b` is its bias. `z` is the candidate vector and `z★` is the minimizing output. `‖·‖₂²` is the squared Euclidean norm. The constraint `z ≥ 0` requires each coordinate to be non-negative, and `argmin` returns the minimizing vector. Here `b` is used as an affine bias, separate from the equality targets in the general program.

The appendix extends this construction to elementwise piecewise linear functions. A scalar function of that kind can be assembled from rectified affine terms that change its slope at designated breakpoints. In the quadratic program, each auxiliary variable has a lower bound given by one affine term. Its square in the objective favors zero whenever zero is feasible. When the lower bound is positive, the closest feasible value is the bound itself. A second term ties the output coordinate to a weighted sum of the auxiliaries.

```
minimize over z, t { ‖t‖₂² + (z − wᵀt)²  subject to  aᵢx + bᵢ ≤ tᵢ for each i }
```

`z` is the scalar output and `t` is the vector of auxiliary variables. `x` is the scalar input, and `i` indexes the auxiliary terms. `aᵢ` and `bᵢ` give the slope and intercept of the affine lower bound on `tᵢ`. `w` contains the weights that combine the auxiliaries, `ᵀ` denotes transpose, and `‖t‖₂²` is the squared Euclidean norm of `t`. The squared difference involving `z` is minimized when the output equals the weighted sum. The same construction can be applied separately to each input coordinate. The paper states a parameter bound of `O(nk)` for `n` coordinates and `k` linear regions, where `O` describes order of growth. For an affine transformation with `m` inputs and `n` outputs followed by rectification, the bound given is `O(mn)`.

To illustrate the converse comparison, the authors consider a scalar output that is the maximum of three linear scores. A shallow network formed from a weighted sum of ReLUs changes slope along whole affine boundaries. A maximum can change slope along just part of such a boundary, because a third score can dominate on the remainder. The paper uses this geometry to explain why there are functions expressible by a small optimization layer that a ReLU followed by a linear readout has difficulty representing. It also gives projection onto the simplex as an example of a compact quadratic program whose ordinary closed-form evaluation involves a selection or sorting operation. These examples concern the shape of the function computed by a layer. The experiments address separately whether that function family is useful when its coefficients have to be learned from data.

### Experiments and results

#### The cost of solving inside a layer

The timing experiments ask two different questions. The first is how much more expensive an OptNet layer is than a simple layer of the same input and output width. The authors compare a batched matrix-vector multiplication with a random quadratic program whose number of inequality constraints equals its output dimension. The random input vectors have sizes 10, 50, 100, and 500, and the batch size is 128. The paper profiles both the forward and backward passes and averages the timings over 10 trials. The optimization layer is substantially slower. The comparison establishes the cost of exchanging a matrix multiplication for a constrained solve, even when both make use of the GPU.

The second question is how best to pay that cost when the application needs the constrained solution. The authors generate random programs with 100 variables and 100 inequality constraints and vary the batch size. They compare Gurobi with both serial and batched execution of `qpth`. The random generation is designed to give the solver genuine feasible programs. A matrix with uniform random entries determines the quadratic term through its transpose product with a small diagonal addition. The inequality coefficients are sampled from a normal distribution, and the authors construct the bounds using a sampled candidate solution and non-negative slack. Equality constraints are omitted from this test. It concentrates on the inequalities, which determine the size of a matrix block that the interior-point algorithm factors repeatedly.

```
Q = UᵀU + 10⁻³I
```

`U` is the matrix of uniform random entries, `ᵀ` denotes transpose, and `I` is the identity of the corresponding size. `Q` is the quadratic objective matrix. The coefficient `10⁻³` is the diagonal addition used in this benchmark.

```
h = Gz₀ + s₀
```

`h` is the constructed vector of upper bounds and `G` is the sampled inequality matrix. `z₀` is the normally sampled candidate solution and `s₀` is the uniformly sampled slack vector. This construction gives the inequalities a feasible point by putting the bounds at or above the corresponding entries of `Gz₀`.

The timing comparison reports means and standard deviations across 10 trials for each setting. OptNet uses a Titan X GPU with no other load, whereas Gurobi uses a quad-core Intel Core i7-5960X CPU running at 3 with no other load.00GHz. For a batch of 128, `qpth` in batched mode takes 0.18 seconds on average, and Gurobi takes 4.7 seconds on average. These are elapsed times for solving the full batch of synthetic programs. The hardware and execution strategy are both part of the comparison.

Mean solve time on a batch of 128 random quadratic programs Batched qpth on the GPU completes the workload faster than Gurobi on the CPU.

**The numbers**

| System or setting | seconds |
| --- | --- |
| Gurobi on CPU | 4.7 |
| Batched qpth on GPU (this paper) | 0.18 |

The two timing experiments provide complementary reference points for an engineer deciding where a layer fits. The matrix-multiplication comparison shows the cost of adding constrained inference to a network. The solver comparison shows how much the choice of execution strategy can affect the cost once that inference is part of the design. The benchmark's random coefficients and absence of equalities matter when applying the result to a different workload. The paper's explicit timings describe these feasible synthetic programs at the stated batch size.

#### Denoising piecewise constant signals

The denoising experiments use generated signals with stretches of constant value. Independent Gaussian noise is added to each clean signal to form the input. The goal is to recover the clean signal, and the reported measure is mean squared error, or MSE. Squaring the prediction error weights larger deviations more heavily, while averaging gives a single measure over the values being evaluated. In this experiment, a successful method has to preserve the jumps in the original while removing fluctuations induced by the noise.

Total variation denoising supplies the first baseline. It scores a candidate reconstruction using a term that measures departure from the observation and a penalty for the absolute differences between neighboring candidate values. The differencing matrix creates those neighbor comparisons. Putting an absolute-value penalty on the resulting vector favors explanations with relatively few changes. A single weight sets the tradeoff between fitting the observed data and suppressing small fluctuations. If the weight is too low, the reconstruction can follow the noise. A high weight can also suppress changes that are part of the original signal.

```
z★ = argmin over z { ½‖y − z‖ + λ‖Dz‖₁ }
```

`z★` is the reconstructed signal and `z` is a candidate reconstruction. `y` is the observed noisy signal, `D` is the differencing matrix, and `λ` is the penalty weight in this experiment. `‖·‖₁` sums the absolute entries of its argument. The first norm measures discrepancy from the observation and carries the factor `½`. The paper displays that term without specifying a norm subscript or a square. `argmin` selects the minimizer. The notation `D` here names a matrix of differences, distinct from the diagonal-matrix operator used in the derivation of the gradients.

```
Dᵢ = eᵢ − eᵢ₊₁
```

`Dᵢ` is the row associated with adjacent positions indexed by `i` and its successor `i + 1`. `eᵢ` and `eᵢ₊₁` are unit coordinate rows for those positions. Subtracting them produces the difference between the corresponding signal values when the row acts on `z`.

The authors vary the penalty weight between 0 and 100. The total variation baseline performs best at a weight of approximately 13, where test MSE is about 16.5. A fully connected baseline learns a direct mapping from the noisy input to the clean target by minimizing MSE. It performs worse than total variation. The data generator favors clean signals with few jumps, so the total variation baseline starts with a preference closely aligned with the task. The feedforward predictor has to acquire a useful smoothing rule through examples alone.

OptNet provides two ways to learn within a denoising problem. In one setting, the authors start with a randomly initialized differencing matrix and train it. The learned matrix looks more like a difference operator than the initial matrix does, but its denoising error is worse than that of the fully connected baseline. The authors attribute much of that poor error to over-regularization. They report that preserving the learned sparsity pattern and refining the remaining values reduces the error to a level close to, though slightly above, the total variation result. This setting distinguishes learning a recognizable operator from learning one that yields an accurate reconstruction.

In the other setting, the authors start the same OptNet architecture from the standard total variation differencing matrix. They then train using the example pairs. This [fine-tuning](https://md.research.elamur.ai/free/en/concepts/fine-tuning/) improves both training and test MSE relative to the total variation baseline. The reported improvement in test MSE is 12%. That percentage refers to the error change relative to the fixed total variation solution on this denoising task. The paper also shows convergence for the fully connected baseline and the OptNet version initialized with the total variation operator.

#### Inserting the layer into an MNIST network

The MNIST experiment tests whether the optimization layer can be integrated into a conventional prediction pipeline and trained through its solution. The baseline is `FC600-FC10-FC10-SoftMax`. The alternative is `FC600-FC10-Optnet10-SoftMax`. Each `FC` denotes a fully connected layer, and the digits in the names give the corresponding widths. The replacement occurs just before the softmax, which converts the final scores into a distribution. In the OptNet variant, the preceding activation supplies the linear objective term. The quadratic matrix is learned independently of that activation.

The appendix describes a parameterization that keeps the quadratic objective strictly convex by constructing its matrix from a learned factor and an identity term.

```
Q = LLᵀ + εI
```

`Q` is the quadratic matrix, `L` is the factor learned directly, `ᵀ` denotes transpose, `ε` is a positive diagonal offset, and `I` is the identity matrix. The product gives non-negative curvature, and the offset makes the curvature strictly positive.

The appendix also describes constructing feasible constraint targets from learned primal and slack vectors. The linear inequality matrix acts on the witness vector and the slack is added to form the bound, using the same relationship as in the timing experiment. The authors describe equality targets as the equality matrix applied to the witness vector. Their description of the MNIST configuration specifies inequality constraints, while this feasibility recipe covers equalities as well. What is clear in the comparison is where the input enters and which layer is replaced.

According to the paper, the two networks behave similarly in terms of error, though the OptNet version shows slightly smaller errors and lower variance. The accompanying figure shows training performance. The authors use this example to show how the layer can be integrated and trained, and they describe the gain as marginal. There is no numerical error rate in the written account of this comparison.

#### Learning to complete mini-Sudoku

The Sudoku task uses 4x4 puzzles with digits 1 through 4. A solution must reconcile the clues with the row, column, and subgrid restrictions. The input represents each known cell by a one-hot vector marking its digit and represents each blank cell by a vector of zeros. The resulting input is a 4x4x4 tensor. The target is a tensor of the same shape, with every cell encoded as the digit in the solved board. The grid and digit encoding are supplied by the experiment. The specific rules governing which cells can share a digit are left for training to recover.

The OptNet variant uses a generic constrained quadratic program. Its inequality constraints enforce nonnegativity, while a learned equality matrix and its right-hand side describe relationships among the candidate values. The quadratic matrix is fixed at `0.1I`, where `I` denotes the identity. This gives the objective strict positive curvature. The one-hot puzzle input supplies the linear term. The solver chooses values in a continuous space, so the resulting cell values can be read as scores until they are decoded. The quadratic program gives the network a place to express shared restrictions on those scores across different cells.

The comparison system is a feedforward convolutional network. The reported configuration has 10 convolutional layers with 512 filters of size 3x3 in each layer. The authors also tried other network configurations and use this one for the reported comparison. Both systems train with [Adam](https://md.research.elamur.ai/free/en/papers/kingma-2014-adam-method-stochastic-optimization/) to minimize MSE on the solution tensors. The dataset contains 9000 training puzzles and 1000 held-out puzzles. For the board-level evaluation, the largest output coordinate in each cell determines its predicted digit. A board then counts as correctly solved if the decoded prediction solves the whole puzzle. The paper's prose calls the percentage correctly solved an error rate. The board-level convention is clearer when expressed in terms of what counts as a success.

The distinction between the training loss and the board-level score is important here. A prediction can be close to the target in MSE and still choose the wrong digit in a cell. Conversely, continuous scores can differ from a one-hot target and give the right board after selecting the largest coordinate in each cell. Whole-puzzle success is especially sensitive to the dependencies the authors want the layer to learn, because a collection of individually plausible digits can fail to give a solution.

The convolutional network performs well on the training puzzles and overfits according to the authors' comparison with held-out performance. OptNet generalizes better to the unseen puzzles. The authors interpret the result as evidence that the optimization layer has captured most of the important hard restrictions from example solutions. The paper displays the training behavior and held-out comparison in plots, while its prose gives the ordering of the methods. The evidence establishes a qualitative generalization advantage in this setup, with the outcome measured on held-out boards after decoding.

### What the ablations show

#### Batching changes the practical cost of the solver

The paper offers controlled comparisons of solver execution, initialization, and layer replacement. The serial and batched runs of `qpth` address the effect of solving instances together while retaining the same solver approach. The synthetic problems and their sizes provide a common workload. This comparison is more direct evidence about the contribution of batched execution than the comparison with Gurobi, which also changes the software and the hardware. The timing against the linear layer answers another question, since it exchanges the entire solve for a much simpler computation.

The backward-pass speed argument comes primarily from the algebra and the implementation. The solver would factor the matrix in the course of finding the forward solution. Using those factors again leaves a substitution and the gradient assembly for training. The paper profiles forward and backward passes against a linear layer, but gives no independent timing comparison of a backward pass with and without factor reuse. The evidence supports the mechanism by which reuse saves work and the overall practicality of the batched solver for the smaller test problems.

#### The starting operator changes what denoising learns

The denoising experiment contains the clearest comparison within a shared architecture. The OptNet layer either starts with a generic randomly initialized matrix or begins from the total variation operator. Starting from the familiar operator gives better predictive results. Random initialization gives the learner the freedom to organize the penalty from scratch, and the learned matrix develops a pattern that can be compared with the hand-designed one. After arranging its rows for visualization, the authors see sparse rows with nearby large entries of alternating sign. Such entries make the operator respond strongly to local changes, which is the behavior the standard differencing matrix has by construction.

The poor error from the random start limits what can be inferred from that pattern. Rows can resemble good local comparisons while the combined penalty suppresses too much variation in the reconstruction. The follow-up that freezes the learned sparsity pattern and refines the coefficients illustrates the difference between finding a useful set of positions for non-zero entries and finding good weights for those positions. The authors' interpretation is that over-regularization accounts for much of the original error. The experiment shows that training outcomes depend on how the operator is initialized and constrained. It does not isolate the effect of each individual coefficient.

Starting with total variation gives a second point of comparison against a strong fixed baseline. Both methods begin with the same local difference idea, and the trained layer can adapt it to the distribution of paired clean and noisy signals. Its better test MSE is evidence that there was room to improve the fixed penalty on these data. The result from random initialization is equally relevant to that claim. It shows why access to the larger family of operators did not, on its own, yield a better estimator.

#### Task structure affects the value of the replacement

MNIST provides a layer replacement experiment. The outer arrangement remains a fully connected prediction network with a softmax at the end, and the authors substitute a quadratic program for a fully connected layer of the same width. The similar performance shows that the substitution can be trained through the solver without substantially changing the outcome on this task. The slightly better error and lower variance are reported as modest effects. The comparison gives little leverage for assigning those effects to a particular learned inequality or a specific component of the objective.

The Sudoku experiment changes the architecture more substantially. Its learned quadratic program and its convolutional baseline have different structures. Their comparison shows a difference in generalization under the reported setup. The paper does not give a component-by-component removal study of the learned equality constraints, the nonnegativity conditions, and the input-dependent objective. It also does not assess each learned equality against a named Sudoku rule. The whole-board results support the claim that a continuous optimization layer can learn relationships that help it complete unfamiliar puzzles. They give less information about precisely how those relationships are represented inside the layer.

### Limitations

#### Limits identified by the authors

The first limit is computational scale. Dense exact solving to numerical precision is expensive, and the authors describe cubic complexity in the number of variables or constraints, compared with quadratic complexity for a standard feedforward layer. They report that fewer than 1000 dimensions seems to be the practical range for their implementation, with substantially smaller problems appropriate for real-time use. That is a judgment about the solver and the setting studied. Batch parallelism improves throughput for many programs, and factor reuse makes training cheaper than independently solving another factorization problem. The forward pass still has to find the solution.

The implementation also treats matrices as dense. That is convenient for GPU arithmetic and for an experiment in which any coefficient can be learned. Some applications have substantial sparsity that a dense solver cannot exploit. The authors discuss the possibility of sparse factorization and mention experiments with batched sparse QR through cuSOLVER. A sparse system can acquire new non-zero entries during factorization, so the order in which variables are eliminated matters for the work and storage required. The paper treats these changes as possibilities for development, while the reported solver results are for its dense approach.

Training introduces a separate difficulty. Different coefficient arrays can describe the same decision rule. Scaling an equality row and its right-hand side together leaves the same equality, and positive scaling has the corresponding property for an inequality row. Moving through such equivalent parameterizations can change the coefficients without changing the output. The authors connect these freedoms to the extra tuning that a new layer can require. Denoising illustrates how the training can produce recognizable structure while still selecting a penalty that predicts poorly.

#### Qualifications from the mathematics and experiments

The derivative calculation is local to the current optimum and depends on the regularity of the associated system. The paper states an almost-everywhere differentiability result for its strictly convex setting and gives a Clarke generalized subdifferential, a set of limiting derivative information, for exceptional points. The appendix identifies tight inequalities with zero multipliers as an important source of degeneracy. When this happens, a row of the differential system can become zero, so the usual unique linear response is no longer available through that system. Strict convexity can give a unique primal output even when the multipliers or the ordinary derivative present difficulties.

The appendix's nonsingularity argument also uses independence of the active constraint rows together with the equality rows. Full row rank of the equality matrix alone cannot prevent dependence introduced by redundant active inequalities. That distinction matters when a learned parameterization can emit duplicate or dependent rows. Positive definiteness of the objective matrix also cannot establish constraint feasibility. A given collection of equalities and inequalities still needs a point that satisfies them. The witness constructions in the timing and MNIST descriptions show how feasibility can be arranged when the coefficient mapping is designed to provide it.

There are qualifications to the representational comparison as well. The shallow ReLU argument concerns the specified construction with a rectified layer and a linear combination of its outputs. The paper itself points to Maxout as an architecture that can express the illustrative maximum. In addition, the appendix writes the maximum example as a squared scalar objective with lower bounds given by the linear scores. As written, that program returns zero when all of the scores are negative. The example's geometric argument about changes in slope and the stated program for computing the maximum therefore warrant separate readings. The appendix's covering argument describes a route to approximation, with limited support there for a general lower bound on every possible shallow approximation. The experiment results do not depend on such a bound.

The setup also narrows the empirical claims. The solver benchmark uses generated instances of a particular dimension and omits equalities. Its headline numerical comparison changes both solver organization and hardware. The denoising data follow a distribution for which local differencing is already a good starting point. The reported improvement from training the operator applies to that distribution. MNIST demonstrates compatibility with an existing architecture and offers only marginal evidence of better prediction.

Sudoku tests 4x4 boards with a continuous optimization problem followed by a discrete choice at each cell. A learned equality can constrain the continuous solution, while the decoded board can still fail a puzzle rule. Generalization on held-out puzzles therefore measures how often the complete system produces good solutions under this setup. It does not certify the recovered equalities as a symbolic statement of the rules, establish exact recovery of the rule set, or show how the approach handles the usual 9x9 game. The encoding, the generic nonnegativity restriction, and the structure of the quadratic program all give the learner prior information about the kind of task, even though the experiment withholds the puzzle-specific rules.

### What came after

The later papers that cite OptNet take up several different roles for computation inside a learned system. Their subjects give a way to trace the reach of the question OptNet raised. A network can be studied in terms of how it allocates computation, what procedure its internal calculations resemble, or which tasks reveal capabilities that simpler tests miss. A citation establishes a connection to OptNet. The titles indicate the direction of each connection at a broader level than the details of the quadratic solver.

[Adaptively Sparse Transformers](https://md.research.elamur.ai/free/en/papers/correia-2019-adaptively-sparse-transformers/) takes up adaptive sparsity in the [Transformer and attention](https://md.research.elamur.ai/free/en/concepts/transformer/) setting. This is the closest thematic connection to OptNet's discussion of what an individual layer can express. In OptNet, restrictions on a joint output can decide which coordinates are free to vary at a solution. The later paper's focus is on adaptivity in a Transformer computation. The common issue is how the computation changes with its input, down to which parts of an internal representation participate.

[Transformers learn in-context by gradient descent](https://md.research.elamur.ai/free/en/papers/oswald-2022-transformers-learn-context-gradient-descent/) studies the connection between learning from context and gradient descent. OptNet begins with a specified optimization problem and equips the network to train through its answer. This later work asks an optimization question about behavior within a Transformer given its context. The comparison distinguishes two places to look for a learning procedure. One is the explicit computation assigned to a layer, and the other is the behavior that emerges as the network processes examples in its input.

[Learning Iterative Reasoning through Energy Diffusion](https://md.research.elamur.ai/free/en/papers/du-2024-learning-iterative-reasoning-through-energy/) connects [reasoning](https://md.research.elamur.ai/free/en/topics/reasoning/) to an iterative energy-based procedure. The point of comparison is the use of a numerical process to reach an answer whose parts depend on one another. For OptNet the iterations belong to a solver for a constrained quadratic objective, and the derivative is taken using the optimality equations. The later paper's stated focus shifts to learning iterative reasoning through energy diffusion.

[Scaling Up Test-Time Compute](https://md.research.elamur.ai/free/en/papers/geiping-2025-scaling-up-test-time-compute/) addresses the amount of computation performed when producing an answer. OptNet makes that resource question concrete because its forward pass solves a problem for each input, and its timing experiments show how the cost depends on the kind of operation and the way it is batched. The later title places the emphasis on increasing computation at test time. The connection concerns what happens during prediction, even though the citation alone leaves the relationship between the two computational procedures unspecified.

[Beyond the Imitation Game](https://md.research.elamur.ai/free/en/papers/srivastava-2022-imitation-game-quantifying-extrapolating-capabilities/) concerns quantifying and extrapolating capabilities. Its connection is to the evaluation side of OptNet. The Sudoku experiment makes a capability observable through complete boards and held-out puzzles, while the denoising and MNIST comparisons address other kinds of behavior. That difference in what each task can reveal is relevant to capability measurement more broadly. The five citations connect OptNet to work on the internal computation of a network and to work on how to evaluate what that computation can accomplish.

## Cite

Cite as Brandon Amos and J. Zico Kolter. 2017. OptNet: Differentiable Optimization as a Layer in Neural Networks. arXiv:1703.00443.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.48550/arxiv.1703.00443](https://doi.org/10.48550/arxiv.1703.00443) · [arXiv 1703.00443](https://arxiv.org/abs/1703.00443)

```bibtex
@misc{amos2017optnet,
  title = {{OptNet: Differentiable Optimization as a Layer in Neural Networks}},
  author = {Brandon Amos and J. Zico Kolter},
  year = {2017},
  doi = {10.48550/arxiv.1703.00443},
  eprint = {1703.00443},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.1703.00443}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
