Differentiable Knapsack and Top-k Operators via Dynamic Programming

Germain Vivier-Ardisson, Michael Eli Sander, Axel Parmentier, Mathieu BlondelNeurIPS 2026

TL;DR

Deep learning thrives on smooth gradients, while classic combinatorial decisions—like picking the $k$ best items (Top-$k$) or packing items under a budget (Knapsack)—are stubbornly discrete step functions. By reframing both problems as a single Dynamic Programming (DP) recursion and gently smoothing the internal "max" decisions, the authors build the first specialized differentiable layer for Knapsack problems and a unified, Swiss-Army-knife framework for Top-$k$. You get fast parallel forward passes, exact backward passes, and the power to choose between genuinely sparse selections or order-agnostic ones.

What Problem Does This Paper Address?

Suppose you want a neural network to pick a subset of items—say, selecting which layers to execute in a conditional-computation pipeline, or deciding what products to display in an online store. Top-$k$ picks a fixed count of items; the 0/1 Knapsack problem generalizes this by giving each item a weight and enforcing a total capacity limit.

The catch? Both operations are piecewise constant. Slightly nudge an item's predicted value, and the chosen subset usually doesn't change at all—until it suddenly jumps. That means gradients are zero almost everywhere (and undefined at the jumps), breaking backpropagation.

Unregularized Knapsack operators produce jagged, piecewise-constant step functions with zero gradients almost everywhere.

Existing workarounds force uncomfortable trade-offs:

  1. Black-box solver perturbations inject random noise and run combinatorial solvers repeatedly to estimate gradients—flexible, yet computationally sluggish.
  2. Specialized Top-$k$ layers (via optimal transport or sorting) are faster, but they can't handle the non-uniform item weights of a Knapsack constraint. Moreover, most only output deterministic "soft" averages rather than sampling actual discrete $0/1$ subsets, and lock you into dense (never-quite-zero) outputs.

Methods

The authors notice that Top-$k$ is really just a special case of Knapsack where every item has weight $1$, capacity is $k$, and the DP table's boundary is initialized with $-\infty$ to force exact equality.

In standard DP, you fill out a table step-by-step, deciding at each item whether to skip it or pack it using a hard $\max$ operator. Building on algorithmic smoothing, the authors replace that hard $\max$ in the Bellman recursion with a smoothed maximum ($\max_\Omega$) controlled by a convex regularizer $\Omega$ (specifically testing Shannon, Gini, and $1.5$-Tsallis entropies).

What is novel here is how far they push this single smoothed DP table:

  • Wavefront Parallelism: Because row $i$ of the DP table only depends on row $i-1$, they vectorize across capacities, shrinking $\mathcal{O}(nC)$ sequential work into $\mathcal{O}(n)$ parallel steps.
  • Three Integration Modes:
  • Deterministic hidden layer: Outputs a continuous selection vector, using a custom reverse-over-forward algorithm for exact vector-Jacobian products (VJPs) during backprop.
  • Stochastic hidden layer: Uses the DP transition probabilities to run $\mathcal{O}(n)$ ancestral sampling, yielding hard $0/1$ subsets in the forward pass paired with unbiased first-order surrogate gradients in the backward pass.
  • Output layer: Pairs the operator with Fenchel-Young losses for convex, effortless supervised gradients.

Datasets

Rather than introducing new datasets, the authors evaluate across three established settings:

  • PyEPO Benchmark: Synthetic feature-to-value data for learning to predict Knapsack solutions.
  • Stacked MNIST: A variant of MNIST where each input image is the pixel-wise average of $k=3$ distinct digits, testing whether a Discrete VAE can disentangle digit identities.
  • Constrained Dynamic Assortment RL: A simulated retail environment ($n=20$ items over $80$ steps) with capacity limits, depleting inventory, and a hidden customer choice model.

Key Insights and Ideas

  • The Equivariance–Sparsity Trade-off: Because DP processes items sequentially ($1$ to $n$), you might worry that shuffling the input order changes the answer. The authors prove a striking theorem: Shannon entropy is the only separable regularizer that makes the DP operator permutation-equivariant (because log-sum-exp is uniquely associative!). However, Shannon's gradients explode at $0$ and $1$, meaning its outputs are always dense—every item gets a tiny non-zero weight.
  • Exact Sparsity Without Losing Smoothness: If you swap Shannon for regularizers with bounded slope at the boundaries—like Gini or $1.5$-Tsallis—individual DP transitions can saturate to hard $0$s and $1$s. Even better, below a finite regularization threshold, they recover the exact discrete optimal solution while remaining differentiable!
Tsallis regularization smooths out the step jumps while still allowing flat, genuinely sparse 0/1 regions, whereas Shannon regularization is smooth everywhere.
  • Free Probability Distributions: Smoothing the Bellman recursion doesn't just give you a soft vector; it implicitly defines a tractable autoregressive probability distribution over valid subsets. You can sample valid Knapsack packings in $\mathcal{O}(n)$ time or compute the exact probability of any candidate subset.

Key Results

  • Predicting Knapsack Solutions: On PyEPO ($n$ from $10$ to $100$), DP-based Fenchel-Young losses achieve the lowest test relative regret (~$1.3\%$–$1.5\%$), beating perturbation and black-box baselines while running in ~$1$–$10\text{ ms}$ for moderate $n$.
  • Discrete VAEs (Stacked MNIST): Gini and Tsallis Top-$k$ layers achieve lower reconstruction error ($0.231 \times 10^{-2}$ MSE) than the Shannon-based SIMPLE baseline ($0.258 \times 10^{-2}$), rapidly converge to sparse $k=3$ active latents (unlike dense baselines hovering near $10$), and avoid the KL-divergence explosions seen in straight-through Gumbel estimators.
  • Dynamic Assortment RL: DP-based structured RL achieves the highest expected revenue (~$373$, approaching the cheating full-information Expert ceiling of ~$375$). Sparse regularizers cut gradient variance by over an order of magnitude compared to Shannon and perturbation baselines, while running nearly $2\times$ faster (~$2.8\text{ ms}$ vs. ~$5.5\text{ ms}$) by avoiding repeated solver calls.

Limitations and Future Work

While wavefront parallelism reduces runtime to $\mathcal{O}(n)$ parallel steps, storing the DP table for backpropagation requires $\mathcal{O}(nC)$ memory. For applications with a massive capacity $C$, memory could become a bottleneck. The authors note two practical mitigations: gradient checkpointing (saving only a fraction of DP rows and recomputing the rest during the backward pass) or rescaling item weights and capacity $C$ by a common divisor to shrink the state space.

Summary updated

Abstract

Knapsack and Top-$k$ operators are useful for selecting discrete subsets of variables. However, their integration into neural networks is challenging as they are piecewise constant, yielding gradients that are zero almost everywhere. In this paper, we propose a unified framework casting these operators as dynamic programs, and derive differentiable relaxations by smoothing the underlying recursions. On the algorithmic side, we develop efficient parallel algorithms supporting both deterministic and stochastic forward passes, and vector-Jacobian products for the backward pass. On the theoretical side, we prove that Shannon entropy is the unique separable binary regularization choice for the local DP smoothing that yields permutation-equivariant operators, and characterize regularizers inducing sparse selections. On the experimental side, we demonstrate our framework on a benchmark on learning to predict Knapsack solutions, an extension of discrete VAEs, and a constrained dynamic assortment RL problem.
BibTeX
@inproceedings{vivierardisson2026differentiable,
  author = {Germain Vivier-Ardisson and Michael Eli Sander and Axel Parmentier and Mathieu Blondel},
  title = {{Differentiable Knapsack and Top-k Operators via Dynamic Programming}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=Joe3lARuyi},
}
Figure