diff --git a/README.md b/README.md index e4601b6..71d2cfe 100644 --- a/README.md +++ b/README.md @@ -52,11 +52,16 @@ A = scope.Parameter(2, 3, value=np.ones((2, 3))) fn = sp.compile(sp.sin(A @ x)) x.value = [0.1, 0.2, 0.3] -J1 = fn.jacobian() +J1 = fn.jacobian().copy() # keep this Jacobian (see below) A.value = np.arange(6.0).reshape(2, 3) # no recompile needed J2 = fn.jacobian() ``` +`jacobian()` and `hessian(w)` each return the same `csr_matrix` on every call. Its +sparsity pattern is fixed and its values are refreshed in place, so an evaluation +builds and copies nothing. The next evaluation overwrites the values: call `.copy()` +on a result you want to keep, as for `J1` above. + ## Using it in a solver `sp.Problem(objective, constraints)` exposes the callbacks NLP solvers ask for: @@ -65,7 +70,9 @@ Hessian `hessian(obj_factor, lagrange)` = `obj_factor * H_f + sum_i lagrange_i * Like `compile`, everything is evaluated at the scope's current values, so a solver callback sets the flat point with `scope.set_values(u)` and then asks for what it needs, in any order. Each stage runs once per point and its result is a read-only -array. Here it drives SciPy: +array. As with `compile`, `jacobian()` and `hessian(...)` each reuse one +`csr_matrix`, so copy a result that has to survive the next evaluation. Here it +drives SciPy: ```python import numpy as np @@ -83,12 +90,13 @@ def at(u, method, *args): # evaluate prob.method(*args) at the flat point u scope.set_values(u) return getattr(prob, method)(*args) +# SciPy keeps the matrices of earlier points, so the callbacks return copies con = NonlinearConstraint(lambda u: at(u, "constraints"), -np.inf, 1.0, - jac=lambda u: at(u, "jacobian"), - hess=lambda u, v: at(u, "hessian", 0.0, v)) + jac=lambda u: at(u, "jacobian").copy(), + hess=lambda u, v: at(u, "hessian", 0.0, v).copy()) res = minimize(lambda u: at(u, "objective"), np.zeros(4), jac=lambda u: at(u, "gradient"), - hess=lambda u: at(u, "hessian", 1.0, [0.0]), + hess=lambda u: at(u, "hessian", 1.0, [0.0]).copy(), method="trust-constr", constraints=con) print(res.x) # approx. [0. 0.289 0.549 0.784], on the boundary ||x|| = 1 ``` diff --git a/sparsediffpy/_bindings/bindings.c b/sparsediffpy/_bindings/bindings.c index a3ee501..02a283d 100644 --- a/sparsediffpy/_bindings/bindings.c +++ b/sparsediffpy/_bindings/bindings.c @@ -54,6 +54,7 @@ /* Include problem bindings */ #include "problem/constraint_forward.h" #include "problem/gradient.h" +#include "problem/csr_views.h" #include "problem/hessian.h" #include "problem/init_derivatives.h" #include "problem/init_hessian.h" @@ -165,6 +166,14 @@ static PyMethodDef DNLPMethods[] = { "Get constraint jacobian without recomputing"}, {"problem_hessian", py_problem_hessian, METH_VARARGS, "Compute Lagrangian Hessian"}, + {"problem_jacobian_csr", py_problem_jacobian_csr, METH_O, + "Read-only views (data, indices, indptr, shape) of the Jacobian's storage"}, + {"problem_hessian_csr", py_problem_hessian_csr, METH_O, + "Read-only views (data, indices, indptr, shape) of the Hessian's storage"}, + {"problem_jacobian_eval", py_problem_jacobian_eval, METH_O, + "Refresh the Jacobian values in place"}, + {"problem_hessian_eval", py_problem_hessian_eval, METH_VARARGS, + "Refresh the Lagrangian Hessian values in place"}, {"get_hessian", py_get_hessian, METH_VARARGS, "Get Lagrangian Hessian without recomputing"}, {"problem_init_jacobian_coo", py_problem_init_jacobian_coo, METH_VARARGS, diff --git a/sparsediffpy/_bindings/problem/csr_views.h b/sparsediffpy/_bindings/problem/csr_views.h new file mode 100644 index 0000000..2b97a87 --- /dev/null +++ b/sparsediffpy/_bindings/problem/csr_views.h @@ -0,0 +1,107 @@ +#ifndef PROBLEM_CSR_VIEWS_H +#define PROBLEM_CSR_VIEWS_H + +#include "common.h" + +/* The Jacobian and the Lagrangian Hessian as read-only numpy views of the + * engine's own CSR storage, plus evaluations that return nothing. The Python + * layer wraps the views in one csr_matrix per problem, once; an evaluation then + * only refreshes the values in place, with no copy and no new array. + * + * Each view holds a reference to the problem capsule, so the storage stays + * alive for as long as any view does. The storage is allocated by + * problem_init_derivatives, which must have run, and never moves afterwards. */ + +/* Read-only 1-D view of `len` items at `ptr`, kept alive by `owner`. */ +static PyObject *csr_view(void *ptr, npy_intp len, int typenum, PyObject *owner) +{ + PyObject *arr; + if (len == 0) + { + /* nothing to view, and ptr may be NULL, which numpy must not wrap */ + arr = PyArray_SimpleNew(1, &len, typenum); + if (!arr) return NULL; + } + else + { + arr = PyArray_SimpleNewFromData(1, &len, typenum, ptr); + if (!arr) return NULL; + Py_INCREF(owner); + if (PyArray_SetBaseObject((PyArrayObject *) arr, owner) < 0) + { + Py_DECREF(arr); + return NULL; + } + } + PyArray_CLEARFLAGS((PyArrayObject *) arr, NPY_ARRAY_WRITEABLE); + return arr; +} + +/* (data, indices, indptr, (m, n)) viewing A */ +static PyObject *csr_views(CSR_matrix *A, PyObject *owner) +{ + PyObject *data = csr_view(A->x, A->nnz, NPY_DOUBLE, owner); + PyObject *indices = csr_view(A->i, A->nnz, NPY_INT32, owner); + PyObject *indptr = csr_view(A->p, (npy_intp) A->m + 1, NPY_INT32, owner); + if (!data || !indices || !indptr) + { + Py_XDECREF(data); + Py_XDECREF(indices); + Py_XDECREF(indptr); + return NULL; + } + return Py_BuildValue("(NNN(ii))", data, indices, indptr, A->m, A->n); +} + +/* problem_jacobian_csr(prob): views of the constraint Jacobian */ +static PyObject *py_problem_jacobian_csr(PyObject *self, PyObject *capsule) +{ + (void) self; + problem *prob = (problem *) PyCapsule_GetPointer(capsule, PROBLEM_CAPSULE_NAME); + if (!prob) return NULL; + return csr_views(prob->jacobian, capsule); +} + +/* problem_hessian_csr(prob): views of the Lagrangian Hessian */ +static PyObject *py_problem_hessian_csr(PyObject *self, PyObject *capsule) +{ + (void) self; + problem *prob = (problem *) PyCapsule_GetPointer(capsule, PROBLEM_CAPSULE_NAME); + if (!prob) return NULL; + return csr_views(prob->lagrange_hessian, capsule); +} + +/* problem_jacobian_eval(prob): refresh the Jacobian values in place */ +static PyObject *py_problem_jacobian_eval(PyObject *self, PyObject *capsule) +{ + (void) self; + problem *prob = (problem *) PyCapsule_GetPointer(capsule, PROBLEM_CAPSULE_NAME); + if (!prob) return NULL; + problem_jacobian(prob); + Py_RETURN_NONE; +} + +/* problem_hessian_eval(prob, obj_factor, lagrange): refresh the Hessian values + * in place. lagrange holds one multiplier per constraint row. */ +static PyObject *py_problem_hessian_eval(PyObject *self, PyObject *args) +{ + (void) self; + PyObject *capsule; + double obj_factor; + PyObject *lagrange_obj; + if (!PyArg_ParseTuple(args, "OdO", &capsule, &obj_factor, &lagrange_obj)) + { + return NULL; + } + problem *prob = (problem *) PyCapsule_GetPointer(capsule, PROBLEM_CAPSULE_NAME); + if (!prob) return NULL; + + PyArrayObject *lagrange = (PyArrayObject *) PyArray_FROM_OTF( + lagrange_obj, NPY_DOUBLE, NPY_ARRAY_IN_ARRAY); + if (!lagrange) return NULL; + problem_hessian(prob, obj_factor, (double *) PyArray_DATA(lagrange)); + Py_DECREF(lagrange); + Py_RETURN_NONE; +} + +#endif /* PROBLEM_CSR_VIEWS_H */ diff --git a/sparsediffpy/_compile.py b/sparsediffpy/_compile.py index 3c42341..7b4721b 100644 --- a/sparsediffpy/_compile.py +++ b/sparsediffpy/_compile.py @@ -90,10 +90,10 @@ def _build_one(self, e): return cap -def _csr(triple): - """scipy CSR matrix from an engine (data, indices, indptr, shape) tuple.""" - data, indices, indptr, shape = triple - return sps.csr_matrix((data, indices, indptr), shape=shape) +def _csr_view(views): + """csr_matrix sharing the engine's (data, indices, indptr, shape) views.""" + data, indices, indptr, shape = views + return sps.csr_matrix((data, indices, indptr), shape=shape, copy=False) def _read_only(arr): @@ -116,6 +116,11 @@ class Problem: Each engine call runs at most once per point (scope values and parameters), and the results are read-only arrays. + + ``jacobian()`` and ``hessian()`` each return the same csr_matrix on every + call: its sparsity pattern is fixed and its values are refreshed in place, + so no matrix is built or copied per evaluation. A later evaluation + overwrites the values, so ``.copy()`` a result you want to keep. """ def __init__(self, objective, constraints=(), verbose=False): @@ -141,7 +146,12 @@ def __init__(self, objective, constraints=(), verbose=False): # The engine holds one point; _key identifies it (scope values and # parameters). Results computed there are cached until it moves. self._key = None - self._obj = self._con = self._grad = self._jac = None + self._obj = self._con = self._grad = None + # The Jacobian and the Hessian are built once, on the engine's own + # storage; evaluating refreshes their values in place. + self._jac = _csr_view(_C.problem_jacobian_csr(self._capsule)) + self._hess = _csr_view(_C.problem_hessian_csr(self._capsule)) + self._jac_current = False def _sync_params(self): """Push Parameter values to the engine if any changed since last time.""" @@ -162,7 +172,8 @@ def _refresh(self): if key != self._key: self._sync_params() self._key = key - self._obj = self._con = self._grad = self._jac = None + self._obj = self._con = self._grad = None + self._jac_current = False def _u(self): """The flat variable vector this problem is evaluated at.""" @@ -191,23 +202,30 @@ def gradient(self): return self._grad def jacobian(self): - """Constraint Jacobian, csr_matrix of shape (total_constraint_size, n_vars).""" + """Constraint Jacobian, csr_matrix of shape (total_constraint_size, n_vars). + + The same matrix is returned on every call, with its values refreshed + in place; copy it to keep the values of this point. + """ self.constraints() - if self._jac is None: - self._jac = _csr(_C.problem_jacobian(self._capsule)) - _read_only(self._jac.data) - _read_only(self._jac.indices) - _read_only(self._jac.indptr) + if not self._jac_current: + _C.problem_jacobian_eval(self._capsule) + self._jac_current = True return self._jac def hessian(self, obj_factor, lagrange): - """Lagrangian Hessian obj_factor H_f + sum_i lagrange_i H_gi (csr_matrix).""" + """Lagrangian Hessian obj_factor H_f + sum_i lagrange_i H_gi (csr_matrix). + + The same matrix is returned on every call, with its values refreshed + in place; copy it to keep the values of this call. + """ lagrange = _flatten_vector(lagrange, self.total_constraint_size, "lagrange") # The engine's Hessian reads values left by the forwards, the gradient # and the Jacobian, so all four must be current (no-ops if they are). self.gradient() self.jacobian() - return _csr(_C.problem_hessian(self._capsule, float(obj_factor), lagrange)) + _C.problem_hessian_eval(self._capsule, float(obj_factor), lagrange) + return self._hess class CompiledExpression: @@ -222,13 +240,17 @@ def forward(self): return self._problem.constraints().reshape(self.shape, order="F") def jacobian(self): - """Sparse Jacobian df/dx, shape (f.size, n_vars).""" + """Sparse Jacobian df/dx, shape (f.size, n_vars). + + Returned as one reused csr_matrix; see ``Problem.jacobian``. + """ return self._problem.jacobian() def hessian(self, weights): """Sparse Hessian of sum(weights * f(x)), shape (n_vars, n_vars). weights has f's shape (a 1-D array is also accepted when f is a vector). + Returned as one reused csr_matrix; see ``Problem.hessian``. """ return self._problem.hessian(0.0, _flatten_shaped(weights, self.shape)) diff --git a/tests/test_api.py b/tests/test_api.py index fad9dfe..a5783c6 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -369,8 +369,8 @@ def test_forward_runs_once_per_point(scope, monkeypatch): def test_derivatives_reuse_forward_and_jacobian(scope, monkeypatch): n_fwd = count_calls(monkeypatch, "problem_constraint_forward") - n_jac = count_calls(monkeypatch, "problem_jacobian") - n_hess = count_calls(monkeypatch, "problem_hessian") + n_jac = count_calls(monkeypatch, "problem_jacobian_eval") + n_hess = count_calls(monkeypatch, "problem_hessian_eval") x = scope.Variable(2, 1) fn = sp.compile(sp.exp(x)) x.value = [0.5, -0.5] @@ -387,7 +387,7 @@ def test_derivatives_reuse_forward_and_jacobian(scope, monkeypatch): def test_problem_runs_each_stage_once_per_point(scope, monkeypatch): names = ["problem_objective_forward", "problem_constraint_forward", - "problem_gradient", "problem_jacobian", "problem_hessian"] + "problem_gradient", "problem_jacobian_eval", "problem_hessian_eval"] calls = {n: count_calls(monkeypatch, n) for n in names} counts = lambda: tuple(len(calls[n]) for n in names) # noqa: E731 x, a = scope.Variable(2, 1), scope.Parameter(1, 1, value=1.0) @@ -483,14 +483,86 @@ def test_results_are_read_only(scope): fn = sp.compile(p * sp.exp(x)) prob = sp.Problem(sp.sum(sp.exp(x)), [sp.exp(x)]) x.value = [0.0, 1.0] + J, H = prob.jacobian(), prob.hessian(1.0, [1.0, 1.0]) for arr in (x.value, p.value, fn.forward(), fn.jacobian().data, - prob.constraints(), prob.gradient(), prob.jacobian().data): + prob.constraints(), prob.gradient(), + J.data, J.indices, J.indptr, H.data, H.indices, H.indptr): with pytest.raises(ValueError, match="read-only"): arr[0] = 5.0 np.testing.assert_array_equal(x.value, [[0.0], [1.0]]) assert scope.get_values().flags.writeable +def test_jacobian_and_hessian_are_reused_in_place(scope): + """One matrix per problem; its values follow the point and the weights.""" + x = scope.Variable(2, 1) + prob = sp.Problem(sp.sum(sp.exp(x)), [x ** 2]) + fn = sp.compile(sp.exp(x)) + x.value = [1.0, 2.0] + J, H, Jf = prob.jacobian(), prob.hessian(1.0, [0.0, 0.0]), fn.jacobian() + J1, H1 = J.copy(), H.copy() # a copy keeps the values of this evaluation + np.testing.assert_allclose(J.toarray(), np.diag([2.0, 4.0])) + np.testing.assert_allclose(H.toarray(), np.diag(np.exp([1.0, 2.0]))) + + assert prob.hessian(0.0, [1.0, 3.0]) is H # new weights, same matrix + np.testing.assert_allclose(H.toarray(), np.diag([2.0, 6.0])) + + x.value = [3.0, -1.0] + assert prob.jacobian() is J and fn.jacobian() is Jf + np.testing.assert_allclose(J.toarray(), np.diag([6.0, -2.0])) + np.testing.assert_allclose(Jf.toarray(), np.diag(np.exp([3.0, -1.0]))) + assert prob.hessian(1.0, [0.0, 0.0]) is H + np.testing.assert_allclose(H.toarray(), np.diag(np.exp([3.0, -1.0]))) + np.testing.assert_allclose(J1.toarray(), np.diag([2.0, 4.0])) + np.testing.assert_allclose(H1.toarray(), np.diag(np.exp([1.0, 2.0]))) + + +def test_reused_matrices_match_the_copying_bindings(scope, rng): + x, y = scope.Variable(3, 1), scope.Variable(3, 1) + A = rng.standard_normal((4, 3)) + prob = sp.Problem(sp.sum(sp.exp(A @ x) * sp.sum(y ** 2)), + [x * y, sp.sin(A @ x), x + y]) + for _ in range(4): + scope.set_values(rng.standard_normal(6)) + lam = rng.standard_normal(prob.total_constraint_size) + J, H = prob.jacobian(), prob.hessian(0.7, lam) + for M, ref in ((J, _compile._C.problem_jacobian(prob._capsule)), + (H, _compile._C.problem_hessian(prob._capsule, 0.7, lam))): + data, indices, indptr, shape = ref + np.testing.assert_array_equal(M.data, data) + np.testing.assert_array_equal(M.indices, indices) + np.testing.assert_array_equal(M.indptr, indptr) + assert M.shape == shape + + +def test_reused_matrices_outlive_the_problem(): + """The matrices view engine memory, which they must keep alive.""" + import gc + + def build(): + scope = sp.Scope() + x = scope.Variable(3, 1) + prob = sp.Problem(sp.sum(sp.exp(x)), [x ** 2]) + x.value = [1.0, 2.0, 3.0] + return prob.jacobian(), prob.hessian(1.0, [0.0, 0.0, 0.0]) + + J, H = build() + gc.collect() + np.zeros(1000) # give freed memory a chance to be reused + np.testing.assert_allclose(J.toarray(), np.diag([2.0, 4.0, 6.0])) + np.testing.assert_allclose(H.toarray(), np.diag(np.exp([1.0, 2.0, 3.0]))) + + +def test_jacobian_and_hessian_without_constraints(scope): + x = scope.Variable(3, 1) + prob = sp.Problem(sp.sum(x ** 2)) + x.value = [1.0, 2.0, 3.0] + J = prob.jacobian() + assert J.shape == (0, 3) and J.nnz == 0 + np.testing.assert_allclose(prob.hessian(1.0, []).toarray(), 2.0 * np.eye(3)) + assert prob.hessian(1.0, []) is prob.hessian(2.0, []) + + def test_hessian_without_prior_jacobian(scope): """hessian() must refresh the Jacobian values the engine's Hessian reuses.""" x, y = scope.Variable(2, 1), scope.Variable(2, 1)