jaddle 0.2.3__tar.gz → 0.2.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {jaddle-0.2.3 → jaddle-0.2.4}/PKG-INFO +24 -2
- {jaddle-0.2.3 → jaddle-0.2.4}/README.md +23 -1
- jaddle-0.2.4/jaddle/__init__.py +1 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle/jaddle_convex.py +270 -101
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle.egg-info/PKG-INFO +24 -2
- {jaddle-0.2.3 → jaddle-0.2.4}/pyproject.toml +1 -1
- {jaddle-0.2.3 → jaddle-0.2.4}/tests/test_convex.py +80 -1
- jaddle-0.2.3/jaddle/__init__.py +0 -1
- {jaddle-0.2.3 → jaddle-0.2.4}/LICENSE.txt +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle/cones.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle/highs_helpers.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle/jaddle_basic_types.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle/jaddle_cvxpy.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle/jaddle_linear.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle/jaddle_optimisers.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle/presolve.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle.egg-info/SOURCES.txt +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle.egg-info/dependency_links.txt +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle.egg-info/requires.txt +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/jaddle.egg-info/top_level.txt +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/setup.cfg +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/tests/test_conic.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/tests/test_cvxpy.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/tests/test_examples.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/tests/test_linear.py +0 -0
- {jaddle-0.2.3 → jaddle-0.2.4}/tests/test_presolve.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: jaddle
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.4
|
|
4
4
|
Summary: First-order primal-dual solvers for large-scale linear and convex programs, written in JAX
|
|
5
5
|
Author: Brendan van Rooyen
|
|
6
6
|
License-Expression: MIT
|
|
@@ -685,7 +685,7 @@ x = result["solution"].primal
|
|
|
685
685
|
`Q` is symmetric positive semidefinite, the matrices are NumPy arrays or SciPy
|
|
686
686
|
sparse matrices, and any constraint block or bound can be left out. Each
|
|
687
687
|
matrix is held on the device as a dense array if at least a quarter of its
|
|
688
|
-
entries are nonzero and as a sparse one otherwise, so a full `Q` (a kernel
|
|
688
|
+
entries are nonzero (or it is small) and as a sparse one otherwise, so a full `Q` (a kernel
|
|
689
689
|
matrix, say) costs one dense product per gradient. The
|
|
690
690
|
function equilibrates the KKT matrix `[[Q, Aᵀ], [A, 0]]` symmetrically with
|
|
691
691
|
Ruiz and Pock–Chambolle sweeps (`ruiz_iterations`, `pc_iterations`, as in the
|
|
@@ -716,6 +716,28 @@ The stopping test is supplied through `JaddleCP`'s optional `residuals`
|
|
|
716
716
|
argument, a function of the solver state that returns the three quantities
|
|
717
717
|
`solve` tests. Any problem with a better certificate of its own can use it.
|
|
718
718
|
|
|
719
|
+
Many QPs that share their matrices and differ only in `c` and `b` arise in
|
|
720
|
+
model predictive control, parametric studies and scenario sweeps.
|
|
721
|
+
`jc.make_qp_solver` is `quadratic_program` split in two for that case. It
|
|
722
|
+
checks and scales the matrices once, on the host, and returns a pure-JAX
|
|
723
|
+
`solve_fn` to `jit` and `vmap` over the vectors:
|
|
724
|
+
|
|
725
|
+
```python
|
|
726
|
+
solve_fn = jax.jit(jax.vmap(jc.make_qp_solver(
|
|
727
|
+
Q, A_ineq=A_ineq, lower_bounds=l, upper_bounds=u, max_epochs=100,
|
|
728
|
+
)))
|
|
729
|
+
result = solve_fn(c_batch, b_ineq=b_batch, initial_solution=warm_batch)
|
|
730
|
+
x = result.solution.primal # one row per problem
|
|
731
|
+
```
|
|
732
|
+
|
|
733
|
+
It has the same stopping test as `quadratic_program`, and `make_solver`'s
|
|
734
|
+
result type (`solution`, `converged`, `epochs`). A matrix with at most 65,536
|
|
735
|
+
entries is always held dense, since a batched dense product is far cheaper
|
|
736
|
+
than a sparse one at that size.
|
|
737
|
+
[`examples/cp/mpc_fleet.py`](examples/cp/mpc_fleet.py) controls a fleet of
|
|
738
|
+
1000 systems this way. On a laptop GPU, each MPC solve took about 1/40 of the
|
|
739
|
+
time of a warm-started SCS loop on the CPU.
|
|
740
|
+
|
|
719
741
|
## Modelling with CVXPY
|
|
720
742
|
|
|
721
743
|
[CVXPY](https://www.cvxpy.org/) can serve as the modelling language
|
|
@@ -638,7 +638,7 @@ x = result["solution"].primal
|
|
|
638
638
|
`Q` is symmetric positive semidefinite, the matrices are NumPy arrays or SciPy
|
|
639
639
|
sparse matrices, and any constraint block or bound can be left out. Each
|
|
640
640
|
matrix is held on the device as a dense array if at least a quarter of its
|
|
641
|
-
entries are nonzero and as a sparse one otherwise, so a full `Q` (a kernel
|
|
641
|
+
entries are nonzero (or it is small) and as a sparse one otherwise, so a full `Q` (a kernel
|
|
642
642
|
matrix, say) costs one dense product per gradient. The
|
|
643
643
|
function equilibrates the KKT matrix `[[Q, Aᵀ], [A, 0]]` symmetrically with
|
|
644
644
|
Ruiz and Pock–Chambolle sweeps (`ruiz_iterations`, `pc_iterations`, as in the
|
|
@@ -669,6 +669,28 @@ The stopping test is supplied through `JaddleCP`'s optional `residuals`
|
|
|
669
669
|
argument, a function of the solver state that returns the three quantities
|
|
670
670
|
`solve` tests. Any problem with a better certificate of its own can use it.
|
|
671
671
|
|
|
672
|
+
Many QPs that share their matrices and differ only in `c` and `b` arise in
|
|
673
|
+
model predictive control, parametric studies and scenario sweeps.
|
|
674
|
+
`jc.make_qp_solver` is `quadratic_program` split in two for that case. It
|
|
675
|
+
checks and scales the matrices once, on the host, and returns a pure-JAX
|
|
676
|
+
`solve_fn` to `jit` and `vmap` over the vectors:
|
|
677
|
+
|
|
678
|
+
```python
|
|
679
|
+
solve_fn = jax.jit(jax.vmap(jc.make_qp_solver(
|
|
680
|
+
Q, A_ineq=A_ineq, lower_bounds=l, upper_bounds=u, max_epochs=100,
|
|
681
|
+
)))
|
|
682
|
+
result = solve_fn(c_batch, b_ineq=b_batch, initial_solution=warm_batch)
|
|
683
|
+
x = result.solution.primal # one row per problem
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
It has the same stopping test as `quadratic_program`, and `make_solver`'s
|
|
687
|
+
result type (`solution`, `converged`, `epochs`). A matrix with at most 65,536
|
|
688
|
+
entries is always held dense, since a batched dense product is far cheaper
|
|
689
|
+
than a sparse one at that size.
|
|
690
|
+
[`examples/cp/mpc_fleet.py`](examples/cp/mpc_fleet.py) controls a fleet of
|
|
691
|
+
1000 systems this way. On a laptop GPU, each MPC solve took about 1/40 of the
|
|
692
|
+
time of a warm-started SCS loop on the CPU.
|
|
693
|
+
|
|
672
694
|
## Modelling with CVXPY
|
|
673
695
|
|
|
674
696
|
[CVXPY](https://www.cvxpy.org/) can serve as the modelling language
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.4"
|
|
@@ -2139,17 +2139,21 @@ def _equilibrate_kkt(Q, A, ruiz_iterations, pc_iterations):
|
|
|
2139
2139
|
# A product with a BCOO matrix gathers and scatters every entry, where a dense
|
|
2140
2140
|
# one is a single BLAS call: on a GPU the dense product wins from about a
|
|
2141
2141
|
# quarter of the entries being nonzero, by 9x (n = 1000) to 40x (n = 4000) on a
|
|
2142
|
-
# full matrix.
|
|
2142
|
+
# full matrix. A small matrix is dense whatever its density: its dense product
|
|
2143
|
+
# is one cheap call, and under vmap a batched one, where a batched BCOO product
|
|
2144
|
+
# was 9x slower at 105 x 120 with 20% nonzeros (examples/cp/mpc_fleet.py).
|
|
2143
2145
|
_DENSE_DENSITY = 0.25
|
|
2146
|
+
_DENSE_SIZE = 1 << 16
|
|
2144
2147
|
|
|
2145
2148
|
|
|
2146
2149
|
def _device_matrix(A, dtype):
|
|
2147
2150
|
"""The scipy matrix ``A`` on the device with ``dtype`` data: a dense array
|
|
2148
|
-
if at
|
|
2151
|
+
if it has at most ``_DENSE_SIZE`` entries or at least ``_DENSE_DENSITY``
|
|
2152
|
+
of them are nonzero, else a BCOO."""
|
|
2149
2153
|
from jaddle.jaddle_basic_types import scipy_to_bcoo
|
|
2150
2154
|
|
|
2151
2155
|
size = A.shape[0] * A.shape[1]
|
|
2152
|
-
if size > 0 and A.nnz >= _DENSE_DENSITY * size:
|
|
2156
|
+
if size > 0 and (size <= _DENSE_SIZE or A.nnz >= _DENSE_DENSITY * size):
|
|
2153
2157
|
return jax.device_put(A.toarray().astype(jnp.dtype(dtype)))
|
|
2154
2158
|
return scipy_to_bcoo(A, dtype)
|
|
2155
2159
|
|
|
@@ -2201,6 +2205,136 @@ def _qp_certificate(Q, c, A_eq, b_eq, A_ineq, b_ineq, lower, upper, solution):
|
|
|
2201
2205
|
}
|
|
2202
2206
|
|
|
2203
2207
|
|
|
2208
|
+
def _matvec(M, v):
|
|
2209
|
+
"""``M @ v`` at full precision for a dense ``M``. Under ``vmap`` a product
|
|
2210
|
+
with a shared matrix becomes a matrix-matrix product, which the float32
|
|
2211
|
+
profile would run in TF32 (about 3 significant digits)."""
|
|
2212
|
+
if isinstance(M, jax.Array):
|
|
2213
|
+
return jnp.matmul(M, v, precision="highest")
|
|
2214
|
+
return M @ v
|
|
2215
|
+
|
|
2216
|
+
|
|
2217
|
+
def _scaled_qp_cp(matrices, c_s, b_eq_s, b_ineq_s, c_norm, b_norm):
|
|
2218
|
+
"""The ``JaddleCP`` of a KKT-scaled QP, with the QP certificate (in the
|
|
2219
|
+
problem's own units) as its ``residuals``. ``matrices`` is
|
|
2220
|
+
``(Q_s, A_eq_s, A_eq_T, A_ineq_s, A_ineq_T, lower_s, upper_s, d, e_eq,
|
|
2221
|
+
e_ineq)``: the scaled data and the variable and row scales. ``c_norm``
|
|
2222
|
+
and ``b_norm`` are the l2 norms of the unscaled ``c`` and ``b``."""
|
|
2223
|
+
Q_s, A_eq_s, A_eq_T, A_ineq_s, A_ineq_T, lower_s, upper_s, d, e_eq, e_ineq = (
|
|
2224
|
+
matrices
|
|
2225
|
+
)
|
|
2226
|
+
|
|
2227
|
+
def objective(x):
|
|
2228
|
+
# Q is symmetric, so the gradient is Qx + c: one product with Q,
|
|
2229
|
+
# where differentiating xᵀQx would take a second with Qᵀ.
|
|
2230
|
+
Qx = jax.lax.stop_gradient(_matvec(Q_s, x))
|
|
2231
|
+
return x @ Qx - 0.5 * jax.lax.stop_gradient(x) @ Qx + c_s @ x
|
|
2232
|
+
|
|
2233
|
+
def residuals(state):
|
|
2234
|
+
# _qp_certificate on the scaled problem: a residual of the original
|
|
2235
|
+
# is the scaled one over its row's or column's scale, and the
|
|
2236
|
+
# objectives and bound terms are the same numbers in either.
|
|
2237
|
+
x = state.primal
|
|
2238
|
+
Qx = _matvec(Q_s, x)
|
|
2239
|
+
reduced_cost = (
|
|
2240
|
+
Qx
|
|
2241
|
+
+ c_s
|
|
2242
|
+
+ _matvec(A_eq_T, state.dual_eq)
|
|
2243
|
+
+ _matvec(A_ineq_T, state.dual_ineq)
|
|
2244
|
+
)
|
|
2245
|
+
at_lower = (reduced_cost > 0) & jnp.isfinite(lower_s)
|
|
2246
|
+
at_upper = (reduced_cost < 0) & jnp.isfinite(upper_s)
|
|
2247
|
+
bound_term = jnp.sum(
|
|
2248
|
+
reduced_cost
|
|
2249
|
+
* jnp.where(at_lower, lower_s, jnp.where(at_upper, upper_s, 0.0))
|
|
2250
|
+
)
|
|
2251
|
+
dual_residual = jnp.linalg.norm(
|
|
2252
|
+
jnp.where(at_lower | at_upper, 0.0, reduced_cost) / d
|
|
2253
|
+
)
|
|
2254
|
+
primal_residual = jnp.linalg.norm(
|
|
2255
|
+
jnp.concatenate(
|
|
2256
|
+
[
|
|
2257
|
+
(_matvec(A_eq_s, x) - b_eq_s) / e_eq,
|
|
2258
|
+
jnp.maximum(_matvec(A_ineq_s, x) - b_ineq_s, 0.0) / e_ineq,
|
|
2259
|
+
]
|
|
2260
|
+
)
|
|
2261
|
+
)
|
|
2262
|
+
primal_objective = 0.5 * x @ Qx + c_s @ x
|
|
2263
|
+
dual_objective = (
|
|
2264
|
+
-0.5 * x @ Qx
|
|
2265
|
+
- b_eq_s @ state.dual_eq
|
|
2266
|
+
- b_ineq_s @ state.dual_ineq
|
|
2267
|
+
+ bound_term
|
|
2268
|
+
)
|
|
2269
|
+
return (
|
|
2270
|
+
dual_residual / (1 + jnp.maximum(c_norm, jnp.linalg.norm(Qx / d))),
|
|
2271
|
+
primal_residual / (1 + b_norm),
|
|
2272
|
+
jnp.abs(primal_objective - dual_objective)
|
|
2273
|
+
/ (1 + jnp.abs(primal_objective) + jnp.abs(dual_objective)),
|
|
2274
|
+
)
|
|
2275
|
+
|
|
2276
|
+
return JaddleCP(
|
|
2277
|
+
num_variables=c_s.shape[0],
|
|
2278
|
+
objective=objective,
|
|
2279
|
+
constraints_eq=lambda x: _matvec(A_eq_s, x) - b_eq_s,
|
|
2280
|
+
constraints_ineq=lambda x: _matvec(A_ineq_s, x) - b_ineq_s,
|
|
2281
|
+
lower_bounds=lower_s,
|
|
2282
|
+
upper_bounds=upper_s,
|
|
2283
|
+
residuals=residuals,
|
|
2284
|
+
)
|
|
2285
|
+
|
|
2286
|
+
|
|
2287
|
+
def _scale_qp(
|
|
2288
|
+
Q, n, A_eq, A_ineq, lower_bounds, upper_bounds, ruiz_iterations, pc_iterations
|
|
2289
|
+
):
|
|
2290
|
+
"""Check a QP's matrices and KKT-scale them. Returns the matrices as
|
|
2291
|
+
scipy CSR (``None`` blocks as empty ones), the bounds as float arrays,
|
|
2292
|
+
the variable scales ``d`` and row scales ``e`` (eq rows first), and the
|
|
2293
|
+
scaled device data ``_scaled_qp_cp`` takes as ``matrices``."""
|
|
2294
|
+
import scipy.sparse as sp
|
|
2295
|
+
|
|
2296
|
+
Q = sp.csr_matrix(Q, dtype=np.float64)
|
|
2297
|
+
if Q.shape != (n, n):
|
|
2298
|
+
raise ValueError(f"Q has shape {Q.shape}, expected {(n, n)}")
|
|
2299
|
+
if abs(Q - Q.T).max() > 1e-12 * max(abs(Q).max(), 1.0):
|
|
2300
|
+
raise ValueError("Q must be symmetric")
|
|
2301
|
+
|
|
2302
|
+
def block(A):
|
|
2303
|
+
if A is None:
|
|
2304
|
+
return sp.csr_matrix((0, n))
|
|
2305
|
+
return sp.csr_matrix(A, dtype=np.float64)
|
|
2306
|
+
|
|
2307
|
+
A_eq, A_ineq = block(A_eq), block(A_ineq)
|
|
2308
|
+
m_eq = A_eq.shape[0]
|
|
2309
|
+
lower = (
|
|
2310
|
+
np.full(n, -np.inf) if lower_bounds is None else np.asarray(lower_bounds, float)
|
|
2311
|
+
)
|
|
2312
|
+
upper = (
|
|
2313
|
+
np.full(n, np.inf) if upper_bounds is None else np.asarray(upper_bounds, float)
|
|
2314
|
+
)
|
|
2315
|
+
|
|
2316
|
+
d, e = _equilibrate_kkt(
|
|
2317
|
+
Q, sp.vstack([A_eq, A_ineq]), ruiz_iterations, pc_iterations
|
|
2318
|
+
)
|
|
2319
|
+
D = sp.diags(d)
|
|
2320
|
+
dtype = jo.jaddle_dtype()
|
|
2321
|
+
A_eq_scipy = sp.diags(e[:m_eq]) @ A_eq @ D
|
|
2322
|
+
A_ineq_scipy = sp.diags(e[m_eq:]) @ A_ineq @ D
|
|
2323
|
+
matrices = (
|
|
2324
|
+
_device_matrix(D @ Q @ D, dtype),
|
|
2325
|
+
_device_matrix(A_eq_scipy, dtype),
|
|
2326
|
+
_device_matrix(A_eq_scipy.T, dtype),
|
|
2327
|
+
_device_matrix(A_ineq_scipy, dtype),
|
|
2328
|
+
_device_matrix(A_ineq_scipy.T, dtype),
|
|
2329
|
+
jnp.asarray(lower / d, dtype=dtype),
|
|
2330
|
+
jnp.asarray(upper / d, dtype=dtype),
|
|
2331
|
+
jnp.asarray(d, dtype=dtype),
|
|
2332
|
+
jnp.asarray(e[:m_eq], dtype=dtype),
|
|
2333
|
+
jnp.asarray(e[m_eq:], dtype=dtype),
|
|
2334
|
+
)
|
|
2335
|
+
return Q, A_eq, A_ineq, lower, upper, d, e, matrices
|
|
2336
|
+
|
|
2337
|
+
|
|
2204
2338
|
def quadratic_program(
|
|
2205
2339
|
Q,
|
|
2206
2340
|
c,
|
|
@@ -2264,107 +2398,28 @@ def quadratic_program(
|
|
|
2264
2398
|
already equilibrates the rows, so ``gradient_scaling`` defaults to
|
|
2265
2399
|
``False`` here.
|
|
2266
2400
|
"""
|
|
2267
|
-
import scipy.sparse as sp
|
|
2268
|
-
|
|
2269
2401
|
c = np.asarray(c, dtype=np.float64)
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
return sp.csr_matrix((0, n)), np.zeros(0)
|
|
2280
|
-
return sp.csr_matrix(A, dtype=np.float64), np.asarray(b, dtype=np.float64)
|
|
2281
|
-
|
|
2282
|
-
A_eq, b_eq = block(A_eq, b_eq)
|
|
2283
|
-
A_ineq, b_ineq = block(A_ineq, b_ineq)
|
|
2284
|
-
m_eq = A_eq.shape[0]
|
|
2285
|
-
lower = (
|
|
2286
|
-
np.full(n, -np.inf) if lower_bounds is None else np.asarray(lower_bounds, float)
|
|
2287
|
-
)
|
|
2288
|
-
upper = (
|
|
2289
|
-
np.full(n, np.inf) if upper_bounds is None else np.asarray(upper_bounds, float)
|
|
2402
|
+
Q, A_eq, A_ineq, lower, upper, d, e, matrices = _scale_qp(
|
|
2403
|
+
Q,
|
|
2404
|
+
c.shape[0],
|
|
2405
|
+
A_eq,
|
|
2406
|
+
A_ineq,
|
|
2407
|
+
lower_bounds,
|
|
2408
|
+
upper_bounds,
|
|
2409
|
+
ruiz_iterations,
|
|
2410
|
+
pc_iterations,
|
|
2290
2411
|
)
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
)
|
|
2295
|
-
D = sp.diags(d)
|
|
2412
|
+
m_eq = A_eq.shape[0]
|
|
2413
|
+
b_eq = np.asarray(b_eq, dtype=np.float64) if m_eq else np.zeros(0)
|
|
2414
|
+
b_ineq = np.asarray(b_ineq, dtype=np.float64) if A_ineq.shape[0] else np.zeros(0)
|
|
2296
2415
|
dtype = jo.jaddle_dtype()
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
c_s = jnp.asarray(d * c, dtype=dtype)
|
|
2305
|
-
b_eq_s = jnp.asarray(e[:m_eq] * b_eq, dtype=dtype)
|
|
2306
|
-
b_ineq_s = jnp.asarray(e[m_eq:] * b_ineq, dtype=dtype)
|
|
2307
|
-
lower_s = jnp.asarray(lower / d, dtype=dtype)
|
|
2308
|
-
upper_s = jnp.asarray(upper / d, dtype=dtype)
|
|
2309
|
-
d_j = jnp.asarray(d, dtype=dtype)
|
|
2310
|
-
e_eq, e_ineq = jnp.asarray(e[:m_eq], dtype=dtype), jnp.asarray(
|
|
2311
|
-
e[m_eq:], dtype=dtype
|
|
2312
|
-
)
|
|
2313
|
-
b_norm = float(np.linalg.norm(np.concatenate([b_eq, b_ineq])))
|
|
2314
|
-
c_norm = float(np.linalg.norm(c))
|
|
2315
|
-
|
|
2316
|
-
def objective(x):
|
|
2317
|
-
# Q is symmetric, so the gradient is Qx + c: one product with Q,
|
|
2318
|
-
# where differentiating xᵀQx would take a second with Qᵀ.
|
|
2319
|
-
Qx = jax.lax.stop_gradient(Q_s @ x)
|
|
2320
|
-
return x @ Qx - 0.5 * jax.lax.stop_gradient(x) @ Qx + c_s @ x
|
|
2321
|
-
|
|
2322
|
-
def residuals(state):
|
|
2323
|
-
# _qp_certificate on the scaled problem: a residual of the original
|
|
2324
|
-
# is the scaled one over its row's or column's scale, and the
|
|
2325
|
-
# objectives and bound terms are the same numbers in either.
|
|
2326
|
-
x = state.primal
|
|
2327
|
-
Qx = Q_s @ x
|
|
2328
|
-
reduced_cost = Qx + c_s + A_eq_T @ state.dual_eq + A_ineq_T @ state.dual_ineq
|
|
2329
|
-
at_lower = (reduced_cost > 0) & jnp.isfinite(lower_s)
|
|
2330
|
-
at_upper = (reduced_cost < 0) & jnp.isfinite(upper_s)
|
|
2331
|
-
bound_term = jnp.sum(
|
|
2332
|
-
reduced_cost
|
|
2333
|
-
* jnp.where(at_lower, lower_s, jnp.where(at_upper, upper_s, 0.0))
|
|
2334
|
-
)
|
|
2335
|
-
dual_residual = jnp.linalg.norm(
|
|
2336
|
-
jnp.where(at_lower | at_upper, 0.0, reduced_cost) / d_j
|
|
2337
|
-
)
|
|
2338
|
-
primal_residual = jnp.linalg.norm(
|
|
2339
|
-
jnp.concatenate(
|
|
2340
|
-
[
|
|
2341
|
-
(A_eq_s @ x - b_eq_s) / e_eq,
|
|
2342
|
-
jnp.maximum(A_ineq_s @ x - b_ineq_s, 0.0) / e_ineq,
|
|
2343
|
-
]
|
|
2344
|
-
)
|
|
2345
|
-
)
|
|
2346
|
-
primal_objective = 0.5 * x @ Qx + c_s @ x
|
|
2347
|
-
dual_objective = (
|
|
2348
|
-
-0.5 * x @ Qx
|
|
2349
|
-
- b_eq_s @ state.dual_eq
|
|
2350
|
-
- b_ineq_s @ state.dual_ineq
|
|
2351
|
-
+ bound_term
|
|
2352
|
-
)
|
|
2353
|
-
return (
|
|
2354
|
-
dual_residual / (1 + jnp.maximum(c_norm, jnp.linalg.norm(Qx / d_j))),
|
|
2355
|
-
primal_residual / (1 + b_norm),
|
|
2356
|
-
jnp.abs(primal_objective - dual_objective)
|
|
2357
|
-
/ (1 + jnp.abs(primal_objective) + jnp.abs(dual_objective)),
|
|
2358
|
-
)
|
|
2359
|
-
|
|
2360
|
-
cp = JaddleCP(
|
|
2361
|
-
num_variables=n,
|
|
2362
|
-
objective=objective,
|
|
2363
|
-
constraints_eq=lambda x: A_eq_s @ x - b_eq_s,
|
|
2364
|
-
constraints_ineq=lambda x: A_ineq_s @ x - b_ineq_s,
|
|
2365
|
-
lower_bounds=lower_s,
|
|
2366
|
-
upper_bounds=upper_s,
|
|
2367
|
-
residuals=residuals,
|
|
2416
|
+
cp = _scaled_qp_cp(
|
|
2417
|
+
matrices,
|
|
2418
|
+
jnp.asarray(d * c, dtype=dtype),
|
|
2419
|
+
jnp.asarray(e[:m_eq] * b_eq, dtype=dtype),
|
|
2420
|
+
jnp.asarray(e[m_eq:] * b_ineq, dtype=dtype),
|
|
2421
|
+
float(np.linalg.norm(c)),
|
|
2422
|
+
float(np.linalg.norm(np.concatenate([b_eq, b_ineq]))),
|
|
2368
2423
|
)
|
|
2369
2424
|
if initial_solution is not None:
|
|
2370
2425
|
initial_solution = SaddleState(
|
|
@@ -2401,3 +2456,117 @@ def quadratic_program(
|
|
|
2401
2456
|
solution=solution, objective=certificate["objective"], certificate=certificate
|
|
2402
2457
|
)
|
|
2403
2458
|
return result
|
|
2459
|
+
|
|
2460
|
+
|
|
2461
|
+
def make_qp_solver(
|
|
2462
|
+
Q,
|
|
2463
|
+
A_eq=None,
|
|
2464
|
+
A_ineq=None,
|
|
2465
|
+
lower_bounds=None,
|
|
2466
|
+
upper_bounds=None,
|
|
2467
|
+
primal_feasibility_tolerance=1e-3,
|
|
2468
|
+
dual_feasibility_tolerance=1e-3,
|
|
2469
|
+
dual_gap_tolerance=1e-3,
|
|
2470
|
+
ruiz_iterations=10,
|
|
2471
|
+
pc_iterations=1,
|
|
2472
|
+
**settings,
|
|
2473
|
+
):
|
|
2474
|
+
"""
|
|
2475
|
+
Build a pure-JAX solve function for a family of quadratic programs that
|
|
2476
|
+
share their matrices and bounds and differ only in ``c`` and ``b``:
|
|
2477
|
+
|
|
2478
|
+
minimise ½ xᵀQx + cᵀx
|
|
2479
|
+
subject to A_eq x = b_eq
|
|
2480
|
+
A_ineq x <= b_ineq
|
|
2481
|
+
lower_bounds <= x <= upper_bounds
|
|
2482
|
+
|
|
2483
|
+
This is ``quadratic_program`` split in two. The matrices are checked and
|
|
2484
|
+
KKT-scaled once, here, on the host; the scaling depends only on them, so
|
|
2485
|
+
it serves every ``c`` and ``b``. The returned
|
|
2486
|
+
|
|
2487
|
+
solve_fn(c, b_eq=None, b_ineq=None, initial_solution=None)
|
|
2488
|
+
-> SolveCoreResult
|
|
2489
|
+
|
|
2490
|
+
is ``make_solver``'s, so it can be ``jax.jit``-ed and ``jax.vmap``-ed over
|
|
2491
|
+
a batch of vectors, as in model predictive control where the measured
|
|
2492
|
+
state enters only the right-hand side::
|
|
2493
|
+
|
|
2494
|
+
solve_fn = jax.jit(jax.vmap(make_qp_solver(Q, A_ineq=G, max_epochs=50)))
|
|
2495
|
+
batch = solve_fn(c_batch, b_ineq=h_batch)
|
|
2496
|
+
|
|
2497
|
+
``b_eq`` (``b_ineq``) is required when ``A_eq`` (``A_ineq``) is given.
|
|
2498
|
+
``initial_solution`` and the returned ``solution`` are ``SaddleState``-s
|
|
2499
|
+
in the problem's own units, with the multiplier signs of
|
|
2500
|
+
``quadratic_program``. The termination test is ``quadratic_program``'s
|
|
2501
|
+
(relative, in the problem's own units). Other keyword arguments go to
|
|
2502
|
+
``make_solver``; ``gradient_scaling`` defaults to ``False``, since the
|
|
2503
|
+
KKT scaling already equilibrates the rows.
|
|
2504
|
+
"""
|
|
2505
|
+
n = Q.shape[0]
|
|
2506
|
+
_, A_eq, A_ineq, _, _, d, e, matrices = _scale_qp(
|
|
2507
|
+
Q,
|
|
2508
|
+
n,
|
|
2509
|
+
A_eq,
|
|
2510
|
+
A_ineq,
|
|
2511
|
+
lower_bounds,
|
|
2512
|
+
upper_bounds,
|
|
2513
|
+
ruiz_iterations,
|
|
2514
|
+
pc_iterations,
|
|
2515
|
+
)
|
|
2516
|
+
m_eq, m_ineq = A_eq.shape[0], A_ineq.shape[0]
|
|
2517
|
+
dtype = jo.jaddle_dtype()
|
|
2518
|
+
d = jnp.asarray(d, dtype=dtype)
|
|
2519
|
+
e_eq, e_ineq = jnp.asarray(e[:m_eq], dtype=dtype), jnp.asarray(e[m_eq:], dtype=dtype)
|
|
2520
|
+
|
|
2521
|
+
def build_cp(params):
|
|
2522
|
+
return _scaled_qp_cp(matrices, *params)
|
|
2523
|
+
|
|
2524
|
+
settings.setdefault("gradient_scaling", False)
|
|
2525
|
+
scaled_solve = make_solver(
|
|
2526
|
+
build_cp,
|
|
2527
|
+
primal_grad_norm_tolerance=dual_feasibility_tolerance,
|
|
2528
|
+
primal_feasibility_tolerance=primal_feasibility_tolerance,
|
|
2529
|
+
complementarity_slack_tolerance=dual_gap_tolerance,
|
|
2530
|
+
**settings,
|
|
2531
|
+
)
|
|
2532
|
+
|
|
2533
|
+
def rhs(b, m, name):
|
|
2534
|
+
if m == 0:
|
|
2535
|
+
return jnp.zeros(0, dtype)
|
|
2536
|
+
if b is None:
|
|
2537
|
+
raise ValueError(f"{name} is required when its matrix is given")
|
|
2538
|
+
b = jnp.asarray(b, dtype=dtype)
|
|
2539
|
+
if b.shape != (m,):
|
|
2540
|
+
raise ValueError(f"{name} has shape {b.shape}, expected {(m,)}")
|
|
2541
|
+
return b
|
|
2542
|
+
|
|
2543
|
+
def solve_fn(c, b_eq=None, b_ineq=None, initial_solution=None):
|
|
2544
|
+
c = jnp.asarray(c, dtype=dtype)
|
|
2545
|
+
if c.shape != (n,):
|
|
2546
|
+
raise ValueError(f"c has shape {c.shape}, expected {(n,)}")
|
|
2547
|
+
b_eq = rhs(b_eq, m_eq, "b_eq")
|
|
2548
|
+
b_ineq = rhs(b_ineq, m_ineq, "b_ineq")
|
|
2549
|
+
params = (
|
|
2550
|
+
d * c,
|
|
2551
|
+
e_eq * b_eq,
|
|
2552
|
+
e_ineq * b_ineq,
|
|
2553
|
+
jnp.linalg.norm(c),
|
|
2554
|
+
jnp.linalg.norm(jnp.concatenate([b_eq, b_ineq])),
|
|
2555
|
+
)
|
|
2556
|
+
if initial_solution is not None:
|
|
2557
|
+
initial_solution = SaddleState(
|
|
2558
|
+
primal=jnp.asarray(initial_solution.primal, dtype) / d,
|
|
2559
|
+
dual_ineq=jnp.asarray(initial_solution.dual_ineq, dtype) / e_ineq,
|
|
2560
|
+
dual_eq=jnp.asarray(initial_solution.dual_eq, dtype) / e_eq,
|
|
2561
|
+
)
|
|
2562
|
+
result = scaled_solve(params, initial_solution)
|
|
2563
|
+
scaled = result.solution
|
|
2564
|
+
return result._replace(
|
|
2565
|
+
solution=SaddleState(
|
|
2566
|
+
primal=d * scaled.primal,
|
|
2567
|
+
dual_ineq=e_ineq * scaled.dual_ineq,
|
|
2568
|
+
dual_eq=e_eq * scaled.dual_eq,
|
|
2569
|
+
)
|
|
2570
|
+
)
|
|
2571
|
+
|
|
2572
|
+
return solve_fn
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: jaddle
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.4
|
|
4
4
|
Summary: First-order primal-dual solvers for large-scale linear and convex programs, written in JAX
|
|
5
5
|
Author: Brendan van Rooyen
|
|
6
6
|
License-Expression: MIT
|
|
@@ -685,7 +685,7 @@ x = result["solution"].primal
|
|
|
685
685
|
`Q` is symmetric positive semidefinite, the matrices are NumPy arrays or SciPy
|
|
686
686
|
sparse matrices, and any constraint block or bound can be left out. Each
|
|
687
687
|
matrix is held on the device as a dense array if at least a quarter of its
|
|
688
|
-
entries are nonzero and as a sparse one otherwise, so a full `Q` (a kernel
|
|
688
|
+
entries are nonzero (or it is small) and as a sparse one otherwise, so a full `Q` (a kernel
|
|
689
689
|
matrix, say) costs one dense product per gradient. The
|
|
690
690
|
function equilibrates the KKT matrix `[[Q, Aᵀ], [A, 0]]` symmetrically with
|
|
691
691
|
Ruiz and Pock–Chambolle sweeps (`ruiz_iterations`, `pc_iterations`, as in the
|
|
@@ -716,6 +716,28 @@ The stopping test is supplied through `JaddleCP`'s optional `residuals`
|
|
|
716
716
|
argument, a function of the solver state that returns the three quantities
|
|
717
717
|
`solve` tests. Any problem with a better certificate of its own can use it.
|
|
718
718
|
|
|
719
|
+
Many QPs that share their matrices and differ only in `c` and `b` arise in
|
|
720
|
+
model predictive control, parametric studies and scenario sweeps.
|
|
721
|
+
`jc.make_qp_solver` is `quadratic_program` split in two for that case. It
|
|
722
|
+
checks and scales the matrices once, on the host, and returns a pure-JAX
|
|
723
|
+
`solve_fn` to `jit` and `vmap` over the vectors:
|
|
724
|
+
|
|
725
|
+
```python
|
|
726
|
+
solve_fn = jax.jit(jax.vmap(jc.make_qp_solver(
|
|
727
|
+
Q, A_ineq=A_ineq, lower_bounds=l, upper_bounds=u, max_epochs=100,
|
|
728
|
+
)))
|
|
729
|
+
result = solve_fn(c_batch, b_ineq=b_batch, initial_solution=warm_batch)
|
|
730
|
+
x = result.solution.primal # one row per problem
|
|
731
|
+
```
|
|
732
|
+
|
|
733
|
+
It has the same stopping test as `quadratic_program`, and `make_solver`'s
|
|
734
|
+
result type (`solution`, `converged`, `epochs`). A matrix with at most 65,536
|
|
735
|
+
entries is always held dense, since a batched dense product is far cheaper
|
|
736
|
+
than a sparse one at that size.
|
|
737
|
+
[`examples/cp/mpc_fleet.py`](examples/cp/mpc_fleet.py) controls a fleet of
|
|
738
|
+
1000 systems this way. On a laptop GPU, each MPC solve took about 1/40 of the
|
|
739
|
+
time of a warm-started SCS loop on the CPU.
|
|
740
|
+
|
|
719
741
|
## Modelling with CVXPY
|
|
720
742
|
|
|
721
743
|
[CVXPY](https://www.cvxpy.org/) can serve as the modelling language
|
|
@@ -537,6 +537,82 @@ def test_quadratic_program_inequality_rows():
|
|
|
537
537
|
)
|
|
538
538
|
|
|
539
539
|
|
|
540
|
+
def random_qp(seed=0, n=12, m_eq=2, m_ineq=8):
|
|
541
|
+
"""A feasible dense QP with eq rows, ineq rows and bounds, minus its c and
|
|
542
|
+
b (returned separately so they can be varied)."""
|
|
543
|
+
rng = np.random.default_rng(seed)
|
|
544
|
+
M = rng.standard_normal((n, n))
|
|
545
|
+
matrices = dict(
|
|
546
|
+
Q=M @ M.T / n + 0.1 * np.eye(n),
|
|
547
|
+
A_eq=rng.standard_normal((m_eq, n)),
|
|
548
|
+
A_ineq=rng.standard_normal((m_ineq, n)),
|
|
549
|
+
lower_bounds=-np.ones(n),
|
|
550
|
+
upper_bounds=np.ones(n),
|
|
551
|
+
)
|
|
552
|
+
return matrices, rng
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def random_qp_vectors(matrices, rng):
|
|
556
|
+
# b is built around a point inside the box, so every draw is feasible.
|
|
557
|
+
x0 = rng.uniform(-0.5, 0.5, matrices["Q"].shape[0])
|
|
558
|
+
c = rng.standard_normal(x0.shape[0])
|
|
559
|
+
b_eq = matrices["A_eq"] @ x0
|
|
560
|
+
b_ineq = matrices["A_ineq"] @ x0 + rng.uniform(0.0, 0.5, matrices["A_ineq"].shape[0])
|
|
561
|
+
return c, b_eq, b_ineq
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
QP_SOLVER_SETTINGS = dict(QP_TOLS, iterations_per_epoch=200, max_epochs=300)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def test_make_qp_solver_matches_quadratic_program():
|
|
568
|
+
matrices, rng = random_qp()
|
|
569
|
+
c, b_eq, b_ineq = random_qp_vectors(matrices, rng)
|
|
570
|
+
reference = jc.quadratic_program(
|
|
571
|
+
**matrices, c=c, b_eq=b_eq, b_ineq=b_ineq, **QP_SOLVER_SETTINGS
|
|
572
|
+
)
|
|
573
|
+
assert_qp_certified(reference)
|
|
574
|
+
solve_fn = jc.make_qp_solver(**matrices, **QP_SOLVER_SETTINGS)
|
|
575
|
+
result = solve_fn(c, b_eq, b_ineq)
|
|
576
|
+
assert bool(result.converged)
|
|
577
|
+
for a, b in zip(result.solution, reference["solution"]):
|
|
578
|
+
np.testing.assert_allclose(np.asarray(a), np.asarray(b), atol=1e-5)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def test_make_qp_solver_vmap_batch():
|
|
582
|
+
matrices, rng = random_qp(seed=1)
|
|
583
|
+
batch = [random_qp_vectors(matrices, rng) for _ in range(5)]
|
|
584
|
+
c, b_eq, b_ineq = (jnp.asarray(np.stack(v)) for v in zip(*batch))
|
|
585
|
+
solve_fn = jc.make_qp_solver(**matrices, **QP_SOLVER_SETTINGS)
|
|
586
|
+
result = jax.jit(jax.vmap(solve_fn))(c, b_eq, b_ineq)
|
|
587
|
+
assert np.asarray(result.converged).all()
|
|
588
|
+
for i, (c_i, b_eq_i, b_ineq_i) in enumerate(batch):
|
|
589
|
+
reference = jc.quadratic_program(
|
|
590
|
+
**matrices, c=c_i, b_eq=b_eq_i, b_ineq=b_ineq_i, **QP_SOLVER_SETTINGS
|
|
591
|
+
)
|
|
592
|
+
np.testing.assert_allclose(
|
|
593
|
+
result.solution.primal[i], reference["solution"].primal, atol=1e-5
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def test_make_qp_solver_warm_start():
|
|
598
|
+
# Started at the solution of a nearby problem, the solve takes fewer epochs.
|
|
599
|
+
matrices, rng = random_qp(seed=2)
|
|
600
|
+
c, b_eq, b_ineq = random_qp_vectors(matrices, rng)
|
|
601
|
+
solve_fn = jax.jit(jc.make_qp_solver(**matrices, **QP_SOLVER_SETTINGS))
|
|
602
|
+
nearby = solve_fn(c + 1e-3, b_eq, b_ineq)
|
|
603
|
+
cold, warm = solve_fn(c, b_eq, b_ineq), solve_fn(c, b_eq, b_ineq, nearby.solution)
|
|
604
|
+
assert bool(cold.converged) and bool(warm.converged)
|
|
605
|
+
assert int(warm.epochs) < int(cold.epochs)
|
|
606
|
+
np.testing.assert_allclose(warm.solution.primal, cold.solution.primal, atol=1e-5)
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def test_make_qp_solver_requires_rhs():
|
|
610
|
+
matrices, _ = random_qp()
|
|
611
|
+
solve_fn = jc.make_qp_solver(**matrices)
|
|
612
|
+
with pytest.raises(ValueError, match="b_eq"):
|
|
613
|
+
solve_fn(np.zeros(12), b_ineq=np.zeros(8))
|
|
614
|
+
|
|
615
|
+
|
|
540
616
|
def test_quadratic_program_is_scale_invariant():
|
|
541
617
|
# The same problem in variables x = S z, with its row rescaled: unusable
|
|
542
618
|
# as given, and the scaling recovers it, duals included.
|
|
@@ -590,11 +666,14 @@ def test_quadratic_program_dense_and_sparse_storage_agree(monkeypatch):
|
|
|
590
666
|
)
|
|
591
667
|
dtype = jo.jaddle_dtype()
|
|
592
668
|
assert isinstance(jc._device_matrix(sp.csr_matrix(qp["Q"]), dtype), jax.Array)
|
|
593
|
-
|
|
669
|
+
# A small matrix is dense whatever its density; a large sparse one is not.
|
|
670
|
+
assert isinstance(jc._device_matrix(sp.identity(n, format="csr"), dtype), jax.Array)
|
|
671
|
+
assert isinstance(jc._device_matrix(sp.identity(300, format="csr"), dtype), BCOO)
|
|
594
672
|
assert isinstance(jc._device_matrix(sp.csr_matrix((0, n)), dtype), BCOO)
|
|
595
673
|
|
|
596
674
|
dense = solve_qp(qp)
|
|
597
675
|
monkeypatch.setattr(jc, "_DENSE_DENSITY", np.inf)
|
|
676
|
+
monkeypatch.setattr(jc, "_DENSE_SIZE", 0)
|
|
598
677
|
sparse = solve_qp(qp)
|
|
599
678
|
assert_qp_certified(dense)
|
|
600
679
|
assert_qp_certified(sparse)
|
jaddle-0.2.3/jaddle/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.2.3"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|