From 16bf04b86b64a5d4d224e87264323641e9158726 Mon Sep 17 00:00:00 2001 From: dance858 Date: Mon, 30 Nov 2026 06:42:56 -0800 Subject: [PATCH 1/2] Remove Scope: standalone variables, stacked per problem Variables and parameters are created with sp.Variable(d1, d2) and sp.Parameter(d1, d2) and hold their own values. Each Problem and CompiledExpression stacks the variables it uses in the order they were created, whatever the order they appear in the expression, and skips variables it does not use. The order is exposed as `variables`, and the flat vector is set and read with set_values() and get_values(). Offsets and the staleness check move from the scope to the problem: each problem assigns its own variable and parameter offsets and compares a version counter per leaf, so a variable can be shared by several problems. Assigning a value a variable or parameter already has keeps the caches. Evaluating while a variable has no value raises. This is a breaking change; there is no Scope alias. The bindings and the engine are unchanged. Co-Authored-By: Claude Fable 5.2 --- README.md | 74 ++++++--- sparsediffpy/__init__.py | 2 +- sparsediffpy/_compile.py | 182 ++++++++++++++++------- sparsediffpy/_expression.py | 120 +++++++-------- tests/conftest.py | 24 +-- tests/test_api.py | 289 ++++++++++++++++++------------------ tests/test_atoms.py | 11 +- tests/test_variables.py | 278 ++++++++++++++++++++++++++++++++++ 8 files changed, 672 insertions(+), 308 deletions(-) create mode 100644 tests/test_variables.py diff --git a/README.md b/README.md index 71d2cfe..41409a4 100644 --- a/README.md +++ b/README.md @@ -19,8 +19,7 @@ From source: `git clone --recursive https://github.com/SparseDifferentiation/Spa import numpy as np import sparsediffpy as sp -scope = sp.Scope() # owns the flat variable vector -x = scope.Variable(3, 1) # shapes are always 2-D: (rows, cols) +x = sp.Variable(3, 1) # shapes are always 2-D: (rows, cols) f = sp.exp(x) + 2.0 * x # build an expression with operators and sp.* atoms fn = sp.compile(f) # analyze sparsity once @@ -31,14 +30,43 @@ print(fn.jacobian().toarray()) # diag(exp(x) + 2), a 3x3 csr_matrix print(fn.hessian(np.ones(3))) # Hessian of w' f(x) for weights w ``` -`forward()` has the shape of `f`, `jacobian()` has shape `(f.size, n_vars)` -and `hessian(w)` has shape `(n_vars, n_vars)`, where `n_vars` is the total -size of all variables in the scope, in declaration order. Values must have -the exact shape of what they set: `x.value` takes an array shaped like `x`, -`hessian(w)` takes `w` shaped like `f` (for vectors a 1-D array also works), -and flat vectors such as `scope.set_values(u)` must be 1-D. Flat vectors (the -rows of the Jacobian, the scope values) are column-major. Reading `x.value` -gives a read-only copy, so assign to `x.value` to change it. +A variable holds its own value: assign `x.value` to choose the point, and every +expression compiled from `x` is evaluated there. Evaluating while a variable has no +value raises an error. Reading `x.value` gives a read-only copy (`None` before it is +set), so assign to `x.value` to change it. + +Shapes are always 2-D, `(rows, cols)`, and both are always given: a column is +`sp.Variable(3, 1)` and a row is `sp.Variable(1, 3)`. `forward()` has the shape of `f`, `jacobian()` has shape +`(f.size, n_vars)` and `hessian(w)` has shape `(n_vars, n_vars)`, where `n_vars` is +the total size of the variables in `f`. Values must have the exact shape of what +they set: `x.value` takes an array shaped like `x`, and `hessian(w)` takes `w` +shaped like `f` (for vectors a 1-D array also works). + +**Several variables** are stacked in the order they were created, whatever the +order they appear in the expression, so rewriting an expression never moves a +column. Variables the expression does not use are left out. `fn.variables` lists +the variables in stacking order: + +```python +import numpy as np +import sparsediffpy as sp + +x = sp.Variable(2, 1) +Y = sp.Variable(2, 2) +fn = sp.compile(Y @ x) # fn.variables == [x, Y], fn.n_vars == 6 + +x.value = [1.0, 2.0] +Y.value = [[3.0, 4.0], [5.0, 6.0]] +J = fn.jacobian() # columns 0-1 belong to x, columns 2-5 to Y +u = fn.get_values() # [1. 2. 3. 5. 4. 6.]: x, then Y column by column +fn.set_values(2 * u) # set all variables from one flat vector +print(Y.value) # [[6. 8.] [10. 12.]] +``` + +Flat vectors (`set_values`, `get_values`, the rows of the Jacobian) are 1-D and +column-major within each variable. A variable can be used in several compiled +expressions or problems; each stacks its own variables, and setting the variable's +value moves the point of all of them. **Parameters** are data you can change without recompiling: @@ -46,9 +74,8 @@ gives a read-only copy, so assign to `x.value` to change it. import numpy as np import sparsediffpy as sp -scope = sp.Scope() -x = scope.Variable(3, 1) -A = scope.Parameter(2, 3, value=np.ones((2, 3))) +x = sp.Variable(3, 1) +A = sp.Parameter(2, 3, value=np.ones((2, 3))) fn = sp.compile(sp.sin(A @ x)) x.value = [0.1, 0.2, 0.3] @@ -67,10 +94,12 @@ on a result you want to keep, as for `J1` above. `sp.Problem(objective, constraints)` exposes the callbacks NLP solvers ask for: `objective()`, `gradient()`, `constraints()`, `jacobian()` and the Lagrangian Hessian `hessian(obj_factor, lagrange)` = `obj_factor * H_f + sum_i lagrange_i * H_gi`. -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. As with `compile`, `jacobian()` and `hessian(...)` each reuse one +Like `compile`, everything is evaluated at the variables' current values, and +`prob.variables` lists them in stacking order. A solver callback sets the flat point +with `prob.set_values(u)` and then asks for what it needs, in any order. Each stage +runs once per point and set of parameter values, also when the same values are set +again, and its result is a +read-only 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: @@ -81,13 +110,12 @@ from scipy.optimize import NonlinearConstraint, minimize import sparsediffpy as sp # minimize sum(exp(x) - c * x) subject to ||x||^2 <= 1 -scope = sp.Scope() -x = scope.Variable(4, 1) +x = sp.Variable(4, 1) c = np.array([[1.0], [2.0], [3.0], [4.0]]) # constants are 2-D, like variables prob = sp.Problem(sp.sum(sp.exp(x) - c * x), [sp.sum(x ** 2)]) def at(u, method, *args): # evaluate prob.method(*args) at the flat point u - scope.set_values(u) + prob.set_values(u) return getattr(prob, method)(*args) # SciPy keeps the matrices of earlier points, so the callbacks return copies @@ -128,10 +156,12 @@ concurrently from different threads: the engine keeps no mutable global state, every problem and expression owns its own buffers, and all inputs and outputs are copied at the boundary. This assumes a default build, since `SP_TRACK_MEMORY` adds global allocation counters that are not thread-safe. +Variables and parameters can be created from several threads at once. A single problem or expression capsule is **not** thread-safe. Do not call into -the same problem from two threads at once, and do not share expression capsules -between problems that are evaluated concurrently. Note that `expr::refcount` is +the same problem from two threads at once, do not set a variable or parameter +while another thread evaluates a problem that uses it, and do not share expression +capsules between problems that are evaluated concurrently. Note that `expr::refcount` is a plain `int`, so breaking this rule corrupts the heap rather than merely interleaving calls, as it would under the GIL. diff --git a/sparsediffpy/__init__.py b/sparsediffpy/__init__.py index 08995f9..951c832 100644 --- a/sparsediffpy/__init__.py +++ b/sparsediffpy/__init__.py @@ -16,7 +16,7 @@ from sparsediffpy import _sparsediffengine # noqa: F401 from sparsediffpy._expression import ( # noqa: F401 - DimensionError, Expression, Parameter, Scope, Variable, broadcast, index_flat, + DimensionError, Expression, Parameter, Variable, broadcast, index_flat, ) from sparsediffpy._atoms import ( # noqa: F401 asinh, atan, atan2, atanh, cos, diag_vec, entr, exp, hstack, log, logistic, diff --git a/sparsediffpy/_compile.py b/sparsediffpy/_compile.py index 7b4721b..fd229d9 100644 --- a/sparsediffpy/_compile.py +++ b/sparsediffpy/_compile.py @@ -16,23 +16,31 @@ ) -def _find_scope(exprs): - """Return the single Scope shared by all Variables/Parameters in exprs.""" - scopes, has_var, seen, stack = set(), False, set(), list(exprs) +def _collect_leaves(exprs): + """The Variables and the Parameters in exprs, each in creation order.""" + leaves, seen, stack = [], set(), list(exprs) while stack: e = stack.pop() if id(e) in seen: continue seen.add(id(e)) if isinstance(e, (Variable, Parameter)): - scopes.add(e._scope) - has_var |= isinstance(e, Variable) + leaves.append(e) stack.extend(e.args) - if not has_var: + leaves.sort(key=lambda leaf: leaf._id) + variables = [e for e in leaves if isinstance(e, Variable)] + if not variables: raise ValueError("Expression must contain at least one Variable") - if len(scopes) > 1: - raise ValueError("All variables must belong to the same Scope") - return scopes.pop() + return variables, [e for e in leaves if isinstance(e, Parameter)] + + +def _stack(leaves): + """Offsets of leaves stacked in order, as {id(leaf): offset}, and the total.""" + offsets, total = {}, 0 + for leaf in leaves: + offsets[id(leaf)] = total + total += leaf.size + return offsets, total class _Builder: @@ -44,8 +52,9 @@ class _Builder: post-order traversal. """ - def __init__(self, scope): - self.n_vars = scope.total_var_size + def __init__(self, n_vars, offsets): + self.n_vars = n_vars + self.offsets = offsets # {id(leaf): offset}, set by the problem self.cache = {} self.params = [] # (Parameter, capsule), each once @@ -69,10 +78,10 @@ def _build_one(self, e): """Build e's capsule; all of e's children must already be cached.""" d1, d2 = e.shape if isinstance(e, Variable): - cap = _C.make_variable(d1, d2, e._offset, self.n_vars) + cap = _C.make_variable(d1, d2, self.offsets[id(e)], self.n_vars) elif isinstance(e, Parameter): values = e._flat if e._flat is not None else np.zeros(e.size) - cap = _C.make_parameter(d1, d2, e._offset, self.n_vars, values) + cap = _C.make_parameter(d1, d2, self.offsets[id(e)], self.n_vars, values) self.params.append((e, cap)) elif isinstance(e, Constant): # Only a constant used as an ordinary operand (e.g. sum(A) or A * x) @@ -102,20 +111,33 @@ def _read_only(arr): return arr +def _flat_value(leaf, kind): + """The column-major value of a Variable or Parameter, or raise if unset.""" + if leaf._flat is None: + raise ValueError(f"{kind} with shape {leaf.shape} has no value; " + f"set its value before evaluating") + return leaf._flat + + class Problem: """A scalar objective plus a list of constraint expressions. - Everything is evaluated at the scope's current values: set ``x.value`` (or - ``scope.set_values(u)`` with the flat vector) to move the point, then call - any method in any order:: + Everything is evaluated at the variables' current values: set ``x.value`` + (or ``prob.set_values(u)`` with the flat vector) to move the point, then + call any method in any order:: - scope.set_values(u) + prob.set_values(u) prob.objective(); prob.gradient() prob.constraints(); prob.jacobian() prob.hessian(obj_factor, lagrange) - Each engine call runs at most once per point (scope values and - parameters), and the results are read-only arrays. + The flat vector stacks the variables the problem uses in the order they + were created, whatever the order they appear in the expressions. + ``prob.variables`` lists them in that order, which is also the order of + the columns of the Jacobian and of the Hessian. + + Each engine call runs at most once per point (variable and parameter + values), 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, @@ -128,24 +150,30 @@ def __init__(self, objective, constraints=(), verbose=False): constraints = [cast_to_const(c) for c in constraints] if objective.shape != (1, 1): raise ValueError(f"Objective must be scalar, got {objective.shape}") - self._scope = _find_scope([objective, *constraints]) + self._variables, self._params = _collect_leaves([objective, *constraints]) + var_offsets, self.n_vars = _stack(self._variables) + param_offsets, self._n_params = _stack(self._params) + self._offsets = [var_offsets[id(v)] for v in self._variables] + self._param_offsets = [param_offsets[id(p)] for p in self._params] + offsets = {**var_offsets, **param_offsets} # Separate engine nodes for the objective and the constraints, so that # neither evaluation can overwrite values the other one reads. - obj_build, con_build = _Builder(self._scope), _Builder(self._scope) + obj_build = _Builder(self.n_vars, offsets) + con_build = _Builder(self.n_vars, offsets) obj_cap = obj_build(objective) con_caps = [con_build(c) for c in constraints] self._capsule = _C.make_problem(obj_cap, con_caps, verbose) - params = obj_build.params + con_build.params - self._params = [p for p, _ in params] - if params: - _C.problem_register_params(self._capsule, [c for _, c in params]) + param_caps = [c for _, c in obj_build.params + con_build.params] + if param_caps: + _C.problem_register_params(self._capsule, param_caps) _C.problem_init_derivatives(self._capsule) - self._param_version = None - self.n_vars = self._scope.total_var_size self.total_constraint_size = sum(c.size for c in constraints) - # The engine holds one point; _key identifies it (scope values and - # parameters). Results computed there are cached until it moves. - self._key = None + # The engine holds one point: the stacked values in _u, and the + # parameters. The versions say which values of the variables and + # parameters it was taken from; results are cached until one changes. + self._u = np.zeros(self.n_vars) + self._var_versions = [None] * len(self._variables) + self._param_versions = [None] * len(self._params) 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. @@ -153,37 +181,60 @@ def __init__(self, objective, constraints=(), verbose=False): 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.""" - if not self._params or self._param_version == self._scope._param_version: - return - theta = np.zeros(self._scope._n_params) - for p in self._params: - if p._flat is None: - raise ValueError(f"Parameter with shape {p.shape} has no value; " - "set parameter.value before evaluating") - theta[p._offset:p._offset + p.size] = p._flat - _C.problem_update_params(self._capsule, theta) - self._param_version = self._scope._param_version + @property + def variables(self): + """The problem's variables as a list, in stacking (creation) order.""" + return list(self._variables) + + def set_values(self, array): + """Set all variables at once from a flat array, stacked as ``variables``. + + Each variable gets its slice, so ``x.value`` reads it back. A variable + whose slice equals its current value is left alone, so setting the + same point again keeps the cached results. + """ + values = _flatten_vector(array, self.n_vars, "values") + for v, offset in zip(self._variables, self._offsets): + v._set_flat(values[offset:offset + v.size]) + + def get_values(self): + """The variables' values as a new flat array, stacked as ``variables``.""" + u = np.empty(self.n_vars) + for v, offset in zip(self._variables, self._offsets): + u[offset:offset + v.size] = _flat_value(v, "Variable") + return u def _refresh(self): - """Forget cached results if the scope's values or parameters changed.""" - key = (self._scope._values_version, self._scope._param_version) - if key != self._key: - self._sync_params() - self._key = key - self._obj = self._con = self._grad = None - self._jac_current = False - - def _u(self): - """The flat variable vector this problem is evaluated at.""" - return self._scope._values[:self.n_vars] + """Take the variables' and parameters' values if any changed. + + Costs a comparison per variable and parameter when nothing changed. + Otherwise the cached results are dropped and the changed values are + copied to the engine's point. + """ + var_versions = [v._version for v in self._variables] + param_versions = [p._version for p in self._params] + if (var_versions == self._var_versions + and param_versions == self._param_versions): + return + self._obj = self._con = self._grad = None + self._jac_current = False + if param_versions != self._param_versions: + theta = np.empty(self._n_params) + for p, offset in zip(self._params, self._param_offsets): + theta[offset:offset + p.size] = _flat_value(p, "Parameter") + _C.problem_update_params(self._capsule, theta) + self._param_versions = param_versions + for i, v in enumerate(self._variables): + if var_versions[i] != self._var_versions[i]: + offset = self._offsets[i] + self._u[offset:offset + v.size] = _flat_value(v, "Variable") + self._var_versions[i] = var_versions[i] def objective(self): """Objective value (float).""" self._refresh() if self._obj is None: - self._obj = _C.problem_objective_forward(self._capsule, self._u()) + self._obj = _C.problem_objective_forward(self._capsule, self._u) return self._obj def constraints(self): @@ -191,7 +242,7 @@ def constraints(self): self._refresh() if self._con is None: self._con = _read_only( - _C.problem_constraint_forward(self._capsule, self._u())) + _C.problem_constraint_forward(self._capsule, self._u)) return self._con def gradient(self): @@ -229,11 +280,30 @@ def hessian(self, obj_factor, lagrange): class CompiledExpression: - """A compiled expression f, evaluated at the scope's current values.""" + """A compiled expression f, evaluated at its variables' current values. + + ``variables`` lists the variables f uses in the order they were created. + They are stacked in that order: it is the order of the columns of the + Jacobian and the Hessian and of the flat vector of ``set_values``. + """ def __init__(self, expr): self.shape = expr.shape self._problem = Problem(Constant(0.0), [expr]) + self.n_vars = self._problem.n_vars + + @property + def variables(self): + """The variables f uses as a list, in stacking (creation) order.""" + return self._problem.variables + + def set_values(self, array): + """Set all variables at once from a flat array, stacked as ``variables``.""" + self._problem.set_values(array) + + def get_values(self): + """The variables' values as a new flat array, stacked as ``variables``.""" + return self._problem.get_values() def forward(self): """f(x) as a read-only array of shape f.shape.""" diff --git a/sparsediffpy/_expression.py b/sparsediffpy/_expression.py index 17937a6..8fb76bd 100644 --- a/sparsediffpy/_expression.py +++ b/sparsediffpy/_expression.py @@ -1,11 +1,13 @@ -"""Expression graph: Scope, leaves (Variable/Parameter/Constant), and operators. +"""Expression graph: leaves (Variable/Parameter/Constant) and operators. Every non-leaf is a generic ``Node(make, args, shape)``: ``make`` receives the C capsules of ``args`` and returns the node's own capsule. Shapes are always 2-D ``(d1, d2)`` and values are flattened column-major, like the C engine. """ +import itertools import numbers +import threading import numpy as np import scipy.sparse as sps @@ -157,49 +159,73 @@ def dense(self): return self.value.toarray() if sps.issparse(self.value) else self.value -class Variable(Expression): - """A block of the scope's flat variable vector. Create via Scope.Variable.""" +_leaf_ids = itertools.count() +_leaf_id_lock = threading.Lock() - def __init__(self, scope, offset, shape): - self._scope, self._offset, self.shape = scope, offset, shape - @property - def value(self): - """The variable's current entries, shaped like the variable.""" - flat = self._scope._values[self._offset:self._offset + self.size] - return _read_only_copy(flat.reshape(self.shape, order="F")) - - @value.setter - def value(self, val): - self._scope._values[self._offset:self._offset + self.size] = \ - _flatten_shaped(val, self.shape) - self._scope._values_version += 1 +def _next_leaf_id(): + """A new id, larger than every earlier one, also across threads.""" + with _leaf_id_lock: + return next(_leaf_ids) -class Parameter(Expression): - """Data that can change without recompiling. Create via Scope.Parameter.""" +class _Leaf(Expression): + """What Variable and Parameter share: a shape, a creation id and a value.""" - def __init__(self, scope, offset, shape, value=None): - self._scope, self._offset, self.shape = scope, offset, shape + def __init__(self, d1, d2): + self.shape = _check_shape(d1, d2) + self._id = _next_leaf_id() # creation order: decides the stacking self._flat = None - self._symmetric = False # set by quad_form; the engine assumes Q = Q' - if value is not None: - self.value = value + self._version = 0 # bumped when the value changes; problems compare it @property def value(self): - """The parameter's current value, or None if it was never set.""" + """The current value, shaped like the leaf, or None if it was never set.""" if self._flat is None: return None return _read_only_copy(self._flat.reshape(self.shape, order="F")) @value.setter def value(self, val): - flat = _flatten_shaped(val, self.shape).copy() # don't alias the caller's array + self._set_flat(_flatten_shaped(val, self.shape)) + + def _set_flat(self, flat): + """Set the value from a column-major flat array, copying it. + + Setting the value it already has changes nothing, so problems keep + what they computed with it. + """ + if self._flat is None: + self._flat = flat.copy() + elif np.array_equal(flat, self._flat): + return + else: + self._flat[:] = flat + self._version += 1 + + +class Variable(_Leaf): + """A (d1, d2) block of unknowns. + + A variable holds its own value. A compiled expression or problem stacks + the variables it uses in the order they were created, whatever the order + they appear in the expression; see its ``variables`` attribute. + """ + + +class Parameter(_Leaf): + """(d1, d2) data that can change without recompiling.""" + + def __init__(self, d1, d2, value=None): + super().__init__(d1, d2) + self._symmetric = False # set by quad_form; the engine assumes Q = Q' + if value is not None: + self.value = value + + def _set_flat(self, flat): if self._symmetric: _check_symmetric(flat, self.shape) - self._flat = flat - self._scope._param_version += 1 + super()._set_flat(flat) def _check_symmetric(flat, shape): @@ -242,46 +268,6 @@ def _flatten_vector(val, n, name): return arr -class Scope: - """Owns the flat variable vector and the parameter vector.""" - - def __init__(self): - self._values = np.zeros(0) - self._values_version = 0 # bumped on every write; problems skip stale work - self._n_params = 0 - self._param_version = 0 - - def Variable(self, d1, d2): - """Create a (d1, d2) variable, appending its entries to the flat vector.""" - shape = _check_shape(d1, d2) - var = Variable(self, self._values.size, shape) - self._values = np.concatenate([self._values, np.zeros(var.size)]) - return var - - def Parameter(self, d1, d2, value=None): - """Create a (d1, d2) parameter, optionally with an initial value.""" - shape = _check_shape(d1, d2) - param = Parameter(self, self._n_params, shape, value) - self._n_params += param.size - return param - - @property - def total_var_size(self): - """Length of the flat variable vector.""" - return self._values.size - - def set_values(self, array): - """Set all variables at once from a flat array (declaration order).""" - values = _flatten_vector(array, self._values.size, "values") - if not np.array_equal(values, self._values): # same point: keep caches - self._values[:] = values - self._values_version += 1 - - def get_values(self): - """A copy of the flat variable vector (declaration order).""" - return self._values.copy() - - def cast_to_const(value): """Return ``value`` as an Expression, wrapping non-Expressions in a Constant.""" return value if isinstance(value, Expression) else Constant(value) diff --git a/tests/conftest.py b/tests/conftest.py index bd8e38b..87f8648 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,12 +1,7 @@ import numpy as np import pytest -import sparsediffpy as sp - - -@pytest.fixture -def scope(): - return sp.Scope() +from sparsediffpy import _compile @pytest.fixture @@ -14,12 +9,23 @@ def rng(): return np.random.default_rng(0) -def check_derivatives(fn, scope, x0, w, h=1e-6, rtol=1e-5, atol=1e-6): +def count_calls(monkeypatch, name): + """Count calls to the engine function `name` as seen from _compile.""" + calls, real = [], getattr(_compile._C, name) + + def counted(*args): + calls.append(1) + return real(*args) + monkeypatch.setattr(_compile._C, name, counted) + return calls + + +def check_derivatives(fn, x0, w, h=1e-6, rtol=1e-5, atol=1e-6): """Check fn.jacobian() and fn.hessian(w) against central differences.""" x0 = np.asarray(x0, dtype=np.float64) def at(x, f): - scope.set_values(x) + fn.set_values(x) return f() def jac(x): @@ -37,6 +43,6 @@ def jac(x): df = at(x0 + e, fn.forward) - at(x0 - e, fn.forward) J_fd[:, j] = df.ravel(order="F") / (2 * h) H_fd[:, j] = (jac(x0 + e) - jac(x0 - e)).T @ w / (2 * h) - scope.set_values(x0) + fn.set_values(x0) np.testing.assert_allclose(J, J_fd, rtol=rtol, atol=atol, err_msg="Jacobian") np.testing.assert_allclose(H, H_fd, rtol=rtol, atol=atol, err_msg="Hessian") diff --git a/tests/test_api.py b/tests/test_api.py index a5783c6..5d0c2cf 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -1,41 +1,45 @@ -"""Scope/values, shape rules, validation errors, parameters, and Problem.""" +"""Variables and values, shape rules, validation errors, parameters, and Problem.""" import sys import numpy as np import pytest import scipy.sparse as sps +from conftest import count_calls import sparsediffpy as sp from sparsediffpy import _compile -def test_values_are_column_major(scope): - X, y = scope.Variable(2, 2), scope.Variable(1, 1) +def test_values_are_column_major(): + X, y = sp.Variable(2, 2), sp.Variable(1, 1) X.value = np.array([[1.0, 2.0], [3.0, 4.0]]) y.value = 5.0 - np.testing.assert_array_equal(scope.get_values(), [1, 3, 2, 4, 5]) - scope.set_values(np.arange(5.0)) + fn = sp.compile(sp.sum(X) + y) + np.testing.assert_array_equal(fn.get_values(), [1, 3, 2, 4, 5]) + fn.set_values(np.arange(5.0)) np.testing.assert_array_equal(X.value, [[0, 2], [1, 3]]) + np.testing.assert_array_equal(y.value, [[4]]) -def test_wrong_sizes(scope): - x = scope.Variable(3, 1) - p = scope.Parameter(2, 1) +def test_wrong_sizes(): + x = sp.Variable(3, 1) + p = sp.Parameter(2, 1) with pytest.raises(sp.DimensionError): x.value = [1.0, 2.0] with pytest.raises(sp.DimensionError): p.value = [1.0, 2.0, 3.0] + fn = sp.compile(p[0] * x) with pytest.raises(sp.DimensionError): - scope.set_values(np.zeros(4)) - assert p.value is None + fn.set_values(np.zeros(4)) + assert p.value is None and x.value is None -def test_value_shapes(scope): +def test_value_shapes(): """Values need the exact shape, not just the right number of elements.""" - X, r, c, y = (scope.Variable(2, 3), scope.Variable(1, 3), - scope.Variable(3, 1), scope.Variable(1, 1)) - P = scope.Parameter(2, 3) + X, r, c, y = (sp.Variable(2, 3), sp.Variable(1, 3), + sp.Variable(3, 1), sp.Variable(1, 1)) + P = sp.Parameter(2, 3) for leaf in (X, P): for bad in (np.zeros(6), np.zeros((3, 2)), np.zeros((6, 1)), 1.0): with pytest.raises(sp.DimensionError, match="expected shape"): @@ -52,12 +56,13 @@ def test_value_shapes(scope): y.value = [8.0] assert y.value.shape == (1, 1) - n = scope.total_var_size + fn = sp.compile(sp.exp(X)) + n = fn.n_vars + assert n == 6 with pytest.raises(sp.DimensionError, match="values"): - scope.set_values(np.zeros((n, 1))) - scope.set_values(np.zeros(n)) + fn.set_values(np.zeros((n, 1))) + fn.set_values(np.zeros(n)) - fn = sp.compile(sp.exp(X)) with pytest.raises(sp.DimensionError): fn.hessian(np.ones(6)) assert fn.hessian(np.ones((2, 3))).shape == (n, n) @@ -68,44 +73,45 @@ def test_value_shapes(scope): @pytest.mark.parametrize("shape", [(0, 1), (-1, 2), (2.0, 1)]) -def test_invalid_shapes(scope, shape): +def test_invalid_shapes(shape): with pytest.raises((ValueError, TypeError)): - scope.Variable(*shape) + sp.Variable(*shape) -def test_too_many_entries(scope): +def test_too_many_entries(): """Sizes are C ints in the engine; larger shapes must fail before reaching C.""" big = (65536, 65537) # 2**32 + 65536 entries - x = scope.Variable(1, 1) - a, b = scope.Variable(65536, 1), scope.Variable(1, 65537) - for make in (lambda: scope.Variable(*big), lambda: scope.Parameter(*big), + x = sp.Variable(1, 1) + a, b = sp.Variable(65536, 1), sp.Variable(1, 65537) + for make in (lambda: sp.Variable(*big), lambda: sp.Parameter(*big), lambda: sp.broadcast(x, big), lambda: a @ b): with pytest.raises(ValueError, match="at most"): make() assert sp.broadcast(x, (2**31 - 1, 1)).size == 2**31 - 1 -def test_large_sparse_constant(scope): +def test_large_sparse_constant(): """A sparse constant is limited by its nonzeros, not by rows times columns.""" m, n = 65536, 65537 # 2**32 + 65536 entries rows, cols = np.array([0, 1, m - 1]), np.array([n - 1, 0, 2]) A = sps.csr_matrix((np.array([1.0, 2.0, 3.0]), (rows, cols)), (m, n)) - x = scope.Variable(n, 1) + x = sp.Variable(n, 1) x.value = np.arange(n, dtype=float) fn = sp.compile(A @ x) np.testing.assert_array_equal(fn.forward().ravel(), A @ np.arange(n)) assert abs(fn.jacobian() - A).max() == 0 - row = scope.Variable(1, m) - assert abs(sp.compile(row @ A).jacobian()[:, n:] - A.T).max() == 0 + row = sp.Variable(1, m) + row.value = np.zeros(m) + assert abs(sp.compile(row @ A).jacobian() - A.T).max() == 0 # any other use would need the matrix dense with pytest.raises(ValueError, match="at most"): sp.compile(sp.sum(A) * x) with pytest.raises(ValueError, match="at most"): - A * scope.Variable(1, 1) + A * sp.Variable(1, 1) -def test_reevaluates_at_new_values(scope): - x = scope.Variable(2, 1) +def test_reevaluates_at_new_values(): + x = sp.Variable(2, 1) fn = sp.compile(sp.exp(x)) for v in ([0.0, 1.0], [2.0, -1.0]): x.value = v @@ -114,26 +120,28 @@ def test_reevaluates_at_new_values(scope): np.testing.assert_allclose(fn.hessian([1, 1]).diagonal(), np.exp(v)) -def test_two_compiles_share_scope(scope): - x, y = scope.Variable(2, 1), scope.Variable(2, 1) +def test_two_compiles_share_variables(): + """Each compiled expression stacks only the variables it uses.""" + x, y = sp.Variable(2, 1), sp.Variable(2, 1) f, g = sp.compile(sp.sin(x)), sp.compile(x * y) - scope.set_values([1.0, 2.0, 3.0, 4.0]) + g.set_values([1.0, 2.0, 3.0, 4.0]) np.testing.assert_allclose(f.forward(), np.sin([[1], [2]])) np.testing.assert_allclose(g.forward(), [[3], [8]]) - assert f.jacobian().shape == g.jacobian().shape == (2, 4) + assert f.jacobian().shape == (2, 2) and g.jacobian().shape == (2, 4) + assert f.n_vars == 2 and g.n_vars == 4 -def test_forward_has_expression_shape(scope): - x, M = scope.Variable(1, 3), scope.Variable(2, 2) - scope.set_values([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]) +def test_forward_has_expression_shape(): + x, M = sp.Variable(1, 3), sp.Variable(2, 2) + x.value, M.value = [1.0, 2.0, 3.0], [[4.0, 6.0], [5.0, 7.0]] assert sp.compile(2.0 * x).forward().shape == (1, 3) out = sp.compile(sp.exp(M)).forward() assert out.shape == (2, 2) np.testing.assert_allclose(out, np.exp([[4.0, 6.0], [5.0, 7.0]])) # column-major -def test_constants_must_be_2d(scope): - x = scope.Variable(3, 1) +def test_constants_must_be_2d(): + x = sp.Variable(3, 1) for bad in (np.ones(3), [1.0, 2.0, 3.0], np.zeros((2, 2, 2))): with pytest.raises(ValueError, match="2-D"): x + bad @@ -143,24 +151,24 @@ def test_constants_must_be_2d(scope): assert (x + np.ones((3, 1))).shape == (3, 1) -def test_variable_declared_after_compile(scope): - x = scope.Variable(2, 1) +def test_variable_created_after_compile(): + x = sp.Variable(2, 1) fn = sp.compile(sp.exp(x)) - scope.Variable(3, 1) + sp.Variable(3, 1) x.value = [0.0, 1.0] np.testing.assert_allclose(fn.forward(), np.exp([[0.0], [1.0]])) assert fn.jacobian().shape == (2, 2) -def test_affine_hessian_is_zero(scope): - x = scope.Variable(3, 1) +def test_affine_hessian_is_zero(): + x = sp.Variable(3, 1) fn = sp.compile(sp.sum(-x[0:2]) + 2.0) x.value = [1.0, 2.0, 3.0] assert not fn.hessian([1.0]).toarray().any() -def test_shapes(scope): - x, r, X = scope.Variable(3, 1), scope.Variable(1, 2), scope.Variable(3, 2) +def test_shapes(): + x, r, X = sp.Variable(3, 1), sp.Variable(1, 2), sp.Variable(3, 2) assert (x + r).shape == (3, 2) assert (X @ r.T).shape == (3, 1) assert x.T.shape == (1, 3) @@ -170,20 +178,20 @@ def test_shapes(scope): @pytest.mark.parametrize("make", [ - lambda s: s.Variable(3, 1) + s.Variable(2, 1), - lambda s: s.Variable(3, 2) @ s.Variable(3, 2), - lambda s: sp.trace(s.Variable(2, 3)), - lambda s: sp.diag_vec(s.Variable(1, 3)), - lambda s: sp.reshape(s.Variable(3, 2), 4, 2), - lambda s: sp.hstack([]), - lambda s: sp.vstack([s.Variable(2, 1), s.Variable(2, 2)]), - lambda s: sp.quad_form(s.Variable(3, 1), np.eye(2)), - lambda s: sp.sum(s.Variable(2, 2), axis=2), - lambda s: sp.rel_entr(s.Variable(3, 1), s.Variable(2, 1)), + lambda: sp.Variable(3, 1) + sp.Variable(2, 1), + lambda: sp.Variable(3, 2) @ sp.Variable(3, 2), + lambda: sp.trace(sp.Variable(2, 3)), + lambda: sp.diag_vec(sp.Variable(1, 3)), + lambda: sp.reshape(sp.Variable(3, 2), 4, 2), + lambda: sp.hstack([]), + lambda: sp.vstack([sp.Variable(2, 1), sp.Variable(2, 2)]), + lambda: sp.quad_form(sp.Variable(3, 1), np.eye(2)), + lambda: sp.sum(sp.Variable(2, 2), axis=2), + lambda: sp.rel_entr(sp.Variable(3, 1), sp.Variable(2, 1)), ]) -def test_shape_errors(scope, make): +def test_shape_errors(make): with pytest.raises(ValueError): - make(scope) + make() @pytest.mark.parametrize("make", [ @@ -193,20 +201,20 @@ def test_shape_errors(scope, make): lambda x: sp.quad_over_lin(x, x[0]), lambda x: sp.rel_entr(x, x), ]) -def test_variable_only_atoms(scope, make): +def test_variable_only_atoms(make): with pytest.raises(ValueError): - make(scope.Variable(4, 1)) + make(sp.Variable(4, 1)) @pytest.mark.parametrize("key", [4, -5, [0, 4], (0, 3), (3, 0)]) -def test_index_out_of_range(scope, key): - X = scope.Variable(2, 2) if isinstance(key, tuple) else scope.Variable(4, 1) +def test_index_out_of_range(key): + X = sp.Variable(2, 2) if isinstance(key, tuple) else sp.Variable(4, 1) with pytest.raises(IndexError): X[key] -def test_index_must_be_explicit(scope): - x, X = scope.Variable(4, 1), scope.Variable(2, 3) +def test_index_must_be_explicit(): + x, X = sp.Variable(4, 1), sp.Variable(2, 3) for key in (1, slice(0, 2), [0, 1]): with pytest.raises(IndexError, match="ambiguous"): X[key] @@ -222,17 +230,15 @@ def test_index_must_be_explicit(scope): X[0, 0, 0] -def test_compile_errors(scope): +def test_compile_errors(): with pytest.raises(ValueError, match="at least one Variable"): - sp.compile(sp.Scope().Parameter(1, 1, value=1.0) * 2.0) - with pytest.raises(ValueError, match="same Scope"): - sp.compile(scope.Variable(1, 1) + sp.Scope().Variable(1, 1)) + sp.compile(sp.Parameter(1, 1, value=1.0) * 2.0) with pytest.raises(TypeError): - scope.Variable(1, 1) ** scope.Variable(1, 1) + sp.Variable(1, 1) ** sp.Variable(1, 1) -def test_expressions_are_not_iterable(scope): - x, X = scope.Variable(3, 1), scope.Variable(2, 2) +def test_expressions_are_not_iterable(): + x, X = sp.Variable(3, 1), sp.Variable(2, 2) with pytest.raises(TypeError, match="not iterable"): list(x) with pytest.raises(TypeError, match="not iterable"): @@ -240,8 +246,8 @@ def test_expressions_are_not_iterable(scope): assert sp.Problem(sp.sum(X), [X]).total_constraint_size == 4 -def test_none_is_rejected(scope): - x, p = scope.Variable(2, 1), scope.Parameter(2, 1) +def test_none_is_rejected(): + x, p = sp.Variable(2, 1), sp.Parameter(2, 1) with pytest.raises(TypeError, match="None"): x + None with pytest.raises(TypeError, match="None"): @@ -250,16 +256,16 @@ def test_none_is_rejected(scope): p.value = None -def test_index_flat_wraps_constants(scope): - x = scope.Variable(2, 1) +def test_index_flat_wraps_constants(): + x = sp.Variable(2, 1) fn = sp.compile(sp.index_flat(np.array([[5.0], [6.0]]), [1], (1, 1)) + x[0]) x.value = [1.0, 2.0] np.testing.assert_array_equal(fn.forward(), [[7.0]]) -def test_index_flat_checks_before_casting(scope): +def test_index_flat_checks_before_casting(): """Indices are validated as given, not after conversion to int32.""" - x = scope.Variable(3, 1) + x = sp.Variable(3, 1) with pytest.raises(IndexError): sp.index_flat(x, np.array([2**32 + 1]), (1, 1)) # would wrap to 1 for bad in ([1.7], [True]): @@ -272,16 +278,16 @@ def test_index_flat_checks_before_casting(scope): np.testing.assert_array_equal(sp.compile(e).forward(), [[10.0], [20.0]]) -def test_numpy_scalar_exponent(scope): - x = scope.Variable(2, 1) +def test_numpy_scalar_exponent(): + x = sp.Variable(2, 1) f1, f2 = sp.compile(x ** np.int64(2)), sp.compile(x ** np.float32(2)) x.value = [1.5, -2.0] np.testing.assert_array_equal(f1.forward(), x.value ** 2) np.testing.assert_array_equal(f2.forward(), x.value ** 2) -def test_division_only_by_nonzero_constants(scope): - x = scope.Variable(2, 1) +def test_division_only_by_nonzero_constants(): + x = sp.Variable(2, 1) with pytest.raises(TypeError, match="d \\*\\* -1"): x / x with pytest.raises(TypeError): @@ -290,12 +296,12 @@ def test_division_only_by_nonzero_constants(scope): x / np.array([[1.0], [0.0]]) -def test_quad_form_parameter_must_be_symmetric(scope): - x = scope.Variable(2, 1) +def test_quad_form_parameter_must_be_symmetric(): + x = sp.Variable(2, 1) N, S = np.array([[1.0, 5.0], [0.0, 1.0]]), np.array([[1.0, 2.0], [2.0, 3.0]]) with pytest.raises(ValueError, match="symmetric"): - sp.quad_form(x, scope.Parameter(2, 2, value=N)) - P = scope.Parameter(2, 2, value=S) + sp.quad_form(x, sp.Parameter(2, 2, value=N)) + P = sp.Parameter(2, 2, value=S) fn = sp.compile(sp.quad_form(x, P)) with pytest.raises(ValueError, match="symmetric"): P.value = N @@ -304,10 +310,10 @@ def test_quad_form_parameter_must_be_symmetric(scope): np.testing.assert_allclose(fn.jacobian().toarray(), [2 * (2 * S) @ [1.0, 1.0]]) -def test_parameter_update_without_recompile(scope): - x = scope.Variable(3, 1) - A = scope.Parameter(2, 3, value=np.ones((2, 3))) - c = scope.Parameter(1, 1, value=1.0) +def test_parameter_update_without_recompile(): + x = sp.Variable(3, 1) + A = sp.Parameter(2, 3, value=np.ones((2, 3))) + c = sp.Parameter(1, 1, value=1.0) fn = sp.compile(c * sp.exp(A @ x)) x.value = [0.1, 0.2, 0.3] for Av, cv in [(np.ones((2, 3)), 1.0), (np.arange(6.0).reshape(2, 3), -2.0)]: @@ -317,41 +323,31 @@ def test_parameter_update_without_recompile(scope): np.testing.assert_allclose(fn.jacobian().toarray(), J) -def test_parameter_value_is_copied(scope): +def test_parameter_value_is_copied(): """Editing the assigned array in place must not change the parameter.""" - x = scope.Variable(2, 1) + x = sp.Variable(2, 1) x.value = [1.0, 2.0] arr = np.ones(2) - p = scope.Parameter(2, 1, value=arr) + p = sp.Parameter(2, 1, value=arr) fn = sp.compile(sp.sum(p * x)) arr[:] = 10.0 np.testing.assert_array_equal(p.value, [[1.0], [1.0]]) assert fn.forward().item() == 3.0 -def test_unset_parameter_raises(scope): - x, p = scope.Variable(2, 1), scope.Parameter(2, 1) +def test_unset_parameter_raises(): + x, p = sp.Variable(2, 1), sp.Parameter(2, 1) fn = sp.compile(p * x) - with pytest.raises(ValueError, match="no value"): + x.value = [0.0, 0.0] + with pytest.raises(ValueError, match="Parameter .* no value"): fn.forward() p.value = [1.0, 2.0] np.testing.assert_allclose(fn.forward(), [[0], [0]]) -def count_calls(monkeypatch, name): - """Count calls to the engine function `name` as seen from _compile.""" - calls, real = [], getattr(_compile._C, name) - - def counted(*args): - calls.append(1) - return real(*args) - monkeypatch.setattr(_compile._C, name, counted) - return calls - - -def test_forward_runs_once_per_point(scope, monkeypatch): +def test_forward_runs_once_per_point(monkeypatch): n_fwd = count_calls(monkeypatch, "problem_constraint_forward") - x, p = scope.Variable(2, 1), scope.Parameter(1, 1, value=1.0) + x, p = sp.Variable(2, 1), sp.Parameter(1, 1, value=1.0) fn = sp.compile(p * sp.exp(x)) x.value = [0.0, 1.0] for _ in range(3): @@ -359,7 +355,7 @@ def test_forward_runs_once_per_point(scope, monkeypatch): assert len(n_fwd) == 1 x.value = [1.0, 1.0] fn.forward() - scope.set_values([2.0, 2.0]) + fn.set_values([2.0, 2.0]) fn.forward() assert len(n_fwd) == 3 p.value = 3.0 @@ -367,11 +363,11 @@ def test_forward_runs_once_per_point(scope, monkeypatch): assert len(n_fwd) == 4 -def test_derivatives_reuse_forward_and_jacobian(scope, monkeypatch): +def test_derivatives_reuse_forward_and_jacobian(monkeypatch): n_fwd = count_calls(monkeypatch, "problem_constraint_forward") n_jac = count_calls(monkeypatch, "problem_jacobian_eval") n_hess = count_calls(monkeypatch, "problem_hessian_eval") - x = scope.Variable(2, 1) + x = sp.Variable(2, 1) fn = sp.compile(sp.exp(x)) x.value = [0.5, -0.5] fn.forward() @@ -385,19 +381,19 @@ def test_derivatives_reuse_forward_and_jacobian(scope, monkeypatch): assert (len(n_fwd), len(n_jac), len(n_hess)) == (2, 2, 3) -def test_problem_runs_each_stage_once_per_point(scope, monkeypatch): +def test_problem_runs_each_stage_once_per_point(monkeypatch): names = ["problem_objective_forward", "problem_constraint_forward", "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) + x, a = sp.Variable(2, 1), sp.Parameter(1, 1, value=1.0) prob = sp.Problem(sp.sum(a * x ** 2), [sp.exp(x)]) - scope.set_values([1.0, 2.0]) + prob.set_values([1.0, 2.0]) for _ in range(2): prob.hessian(1.0, [1.0, 1.0]) prob.objective(), prob.gradient(), prob.constraints(), prob.jacobian() assert counts() == (1, 1, 1, 1, 2) - scope.set_values(np.array([1.0, 2.0])) # equal values: same point + prob.set_values(np.array([1.0, 2.0])) # equal values: same point prob.gradient() assert counts() == (1, 1, 1, 1, 2) x.value = [1.0, 3.0] @@ -408,13 +404,13 @@ def test_problem_runs_each_stage_once_per_point(scope, monkeypatch): assert counts() == (2, 2, 2, 2, 2) -def test_problem(scope): - x = scope.Variable(3, 1) +def test_problem(): + x = sp.Variable(3, 1) shared = sp.sin(x) prob = sp.Problem(sp.sum(sp.exp(shared)), [x[0:2] * x[1:3], shared]) u = np.array([0.3, -0.5, 0.8]) s, c = np.sin(u), np.cos(u) - scope.set_values(u) + prob.set_values(u) assert prob.objective() == pytest.approx(np.exp(s).sum()) np.testing.assert_allclose(prob.gradient(), np.exp(s) * c) @@ -438,8 +434,8 @@ def test_problem(scope): sp.Problem(x) -def test_problem_without_constraints(scope): - x = scope.Variable(2, 1) +def test_problem_without_constraints(): + x = sp.Variable(2, 1) prob = sp.Problem(sp.sum(sp.exp(x))) x.value = [0.0, 1.0] np.testing.assert_allclose(prob.gradient(), np.exp([0.0, 1.0])) @@ -448,8 +444,8 @@ def test_problem_without_constraints(scope): np.testing.assert_allclose(prob.hessian(1.0, []).diagonal(), np.exp([0.0, 1.0])) -def test_problem_parameters(scope): - x, a = scope.Variable(2, 1), scope.Parameter(1, 1, value=2.0) +def test_problem_parameters(): + x, a = sp.Variable(2, 1), sp.Parameter(1, 1, value=2.0) prob = sp.Problem(sp.sum(a * x ** 2)) x.value = [1.0, 3.0] assert prob.objective() == pytest.approx(20.0) @@ -459,27 +455,27 @@ def test_problem_parameters(scope): @pytest.mark.parametrize("shared", [True, False]) -def test_problem_interleaved_points(scope, shared): +def test_problem_interleaved_points(shared): """Moving the point between a forward and its derivative never goes stale.""" - x = scope.Variable(3, 1) + x = sp.Variable(3, 1) e = sp.exp(x) obj, con = (sp.sum(e), e * x) if shared else (sp.sum(x * x), sp.exp(x) * x) grad = (lambda u: np.exp(u)) if shared else (lambda u: 2 * u) # noqa: E731 jac = lambda u: np.exp(u) * (1 + u) # noqa: E731 u1, u2 = np.zeros(3), np.array([1.0, 2.0, 3.0]) prob = sp.Problem(obj, [con]) - scope.set_values(u1) + prob.set_values(u1) prob.objective() - scope.set_values(u2) + prob.set_values(u2) prob.constraints() np.testing.assert_allclose(prob.gradient(), grad(u2)) - scope.set_values(u1) + prob.set_values(u1) np.testing.assert_allclose(prob.jacobian().diagonal(), jac(u1)) np.testing.assert_allclose(prob.gradient(), grad(u1)) -def test_results_are_read_only(scope): - x, p = scope.Variable(2, 1), scope.Parameter(2, 1, value=[1.0, 2.0]) +def test_results_are_read_only(): + x, p = sp.Variable(2, 1), sp.Parameter(2, 1, value=[1.0, 2.0]) fn = sp.compile(p * sp.exp(x)) prob = sp.Problem(sp.sum(sp.exp(x)), [sp.exp(x)]) x.value = [0.0, 1.0] @@ -490,12 +486,12 @@ def test_results_are_read_only(scope): 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 + assert prob.get_values().flags.writeable -def test_jacobian_and_hessian_are_reused_in_place(scope): +def test_jacobian_and_hessian_are_reused_in_place(): """One matrix per problem; its values follow the point and the weights.""" - x = scope.Variable(2, 1) + x = sp.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] @@ -517,13 +513,13 @@ def test_jacobian_and_hessian_are_reused_in_place(scope): 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) +def test_reused_matrices_match_the_copying_bindings(rng): + x, y = sp.Variable(3, 1), sp.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)) + prob.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)), @@ -540,8 +536,7 @@ def test_reused_matrices_outlive_the_problem(): import gc def build(): - scope = sp.Scope() - x = scope.Variable(3, 1) + x = sp.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]) @@ -553,8 +548,8 @@ def build(): 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) +def test_jacobian_and_hessian_without_constraints(): + x = sp.Variable(3, 1) prob = sp.Problem(sp.sum(x ** 2)) x.value = [1.0, 2.0, 3.0] J = prob.jacobian() @@ -563,13 +558,13 @@ def test_jacobian_and_hessian_without_constraints(scope): assert prob.hessian(1.0, []) is prob.hessian(2.0, []) -def test_hessian_without_prior_jacobian(scope): +def test_hessian_without_prior_jacobian(): """hessian() must refresh the Jacobian values the engine's Hessian reuses.""" - x, y = scope.Variable(2, 1), scope.Variable(2, 1) + x, y = sp.Variable(2, 1), sp.Variable(2, 1) fn = sp.compile(x * y + sp.sin(x * y)) prob = sp.Problem(sp.sum(x * y), [x * y]) for u in ([0.1, 0.2, 0.3, 0.4], [1.0, -2.0, 0.5, 3.0]): - scope.set_values(u) + prob.set_values(u) xy, xv, yv = np.multiply(u[:2], u[2:]), np.array(u[:2]), np.array(u[2:]) w = np.array([1.0, 2.0]) # d2/dx_i dy_i of w_i * (x_i y_i + sin(x_i y_i)) @@ -584,9 +579,9 @@ def test_hessian_without_prior_jacobian(scope): atol=1e-12) -def test_compile_deep_sum(scope): +def test_compile_deep_sum(): """A loop-built sum is a chain of adds deeper than the recursion limit.""" - x, p = scope.Variable(3, 1), scope.Parameter(1, 1, value=2.0) + x, p = sp.Variable(3, 1), sp.Parameter(1, 1, value=2.0) n_adds = 5000 assert n_adds > sys.getrecursionlimit() # each add is one level deeper f = x[0] @@ -605,13 +600,13 @@ def test_compile_deep_sum(scope): np.diag(-pv * counts * np.sin(u)), atol=1e-9) -def test_compile_deep_nonlinear_chain(scope): +def test_compile_deep_nonlinear_chain(): """A deep chain of nonlinear atoms that all reuse one shared subexpression. The shared node is shallow on purpose: the engine re-evaluates a shared subexpression once per use, so reusing a deep one would take exponential time. """ - x = scope.Variable(1, 1) + x = sp.Variable(1, 1) n_levels, c = 3000, 1e-3 shared = sp.sin(x) g = x diff --git a/tests/test_atoms.py b/tests/test_atoms.py index 48d4e8b..beab43e 100644 --- a/tests/test_atoms.py +++ b/tests/test_atoms.py @@ -107,15 +107,14 @@ def _dense(M): @pytest.mark.parametrize("name, shapes, f, positive", CASES, ids=[c[0] for c in CASES]) def test_atom(name, shapes, f, positive, rng): - scope = sp.Scope() - leaves = [scope.Parameter(*s.shape, value=s) if isinstance(s, np.ndarray) - else scope.Variable(*s) for s in shapes] + leaves = [sp.Parameter(*s.shape, value=s) if isinstance(s, np.ndarray) + else sp.Variable(*s) for s in shapes] expr = f(sp, *leaves) fn = sp.compile(expr) low, high = (0.2, 0.9) if positive else (-1.0, 1.0) - x0 = rng.uniform(low, high, scope.total_var_size) - scope.set_values(x0) + x0 = rng.uniform(low, high, fn.n_vars) + fn.set_values(x0) expected = f(NP, *[leaf.value for leaf in leaves]) np.testing.assert_allclose(fn.forward(), np.broadcast_to(expected, expr.shape), rtol=1e-10, atol=1e-12) - check_derivatives(fn, scope, x0, rng.standard_normal(expr.size)) + check_derivatives(fn, x0, rng.standard_normal(expr.size)) diff --git a/tests/test_variables.py b/tests/test_variables.py new file mode 100644 index 0000000..a4638d3 --- /dev/null +++ b/tests/test_variables.py @@ -0,0 +1,278 @@ +"""Standalone variables: stacking order, shared variables, values and caching.""" + +import threading + +import numpy as np +import pytest +from conftest import check_derivatives, count_calls + +import sparsediffpy as sp + + +def test_both_dimensions_are_required(): + for leaf in (sp.Variable, sp.Parameter): + with pytest.raises(TypeError): + leaf(3) + assert leaf(3, 1).shape == (3, 1) and leaf(1, 3).shape == (1, 3) + p = sp.Parameter(3, 1, [1.0, 2.0, 3.0]) + np.testing.assert_array_equal(p.value, [[1.0], [2.0], [3.0]]) + assert not hasattr(sp, "Scope") + + +def test_stacking_is_creation_order_not_expression_order(): + x, y = sp.Variable(2, 1), sp.Variable(3, 1) + fn = sp.compile(sp.vstack([y, x])) # y comes first in the expression + assert fn.variables == [x, y] + x.value, y.value = [1.0, 2.0], [3.0, 4.0, 5.0] + np.testing.assert_array_equal(fn.get_values(), [1, 2, 3, 4, 5]) + J = np.zeros((5, 5)) + J[:3, 2:], J[3:, :2] = np.eye(3), np.eye(2) # columns: x, then y + np.testing.assert_array_equal(fn.jacobian().toarray(), J) + + # the objective only uses y and the constraint only uses x + prob = sp.Problem(sp.sum(y ** 2), [sp.exp(x)]) + assert prob.variables == [x, y] and prob.n_vars == 5 + np.testing.assert_allclose(prob.gradient(), [0, 0, 6, 8, 10]) + np.testing.assert_allclose(prob.jacobian().toarray(), + np.c_[np.diag(np.exp([1.0, 2.0])), np.zeros((2, 3))]) + + +def test_rewriting_an_expression_keeps_the_columns(): + x, y = sp.Variable(2, 1), sp.Variable(2, 1) + x.value, y.value = [1.0, 2.0], [3.0, 4.0] + f, g = sp.compile(x * y + sp.sin(y)), sp.compile(sp.sin(y) + y * x) + assert f.variables == g.variables == [x, y] + np.testing.assert_array_equal(f.jacobian().toarray(), g.jacobian().toarray()) + np.testing.assert_array_equal(f.hessian([1.0, 2.0]).toarray(), + g.hessian([1.0, 2.0]).toarray()) + + +def test_unused_variables_are_skipped(): + x, unused, z = sp.Variable(2, 1), sp.Variable(4, 1), sp.Variable(1, 1) + fn = sp.compile(z * sp.exp(x)) + assert fn.variables == [x, z] and fn.n_vars == 3 + fn.set_values([0.0, 1.0, 2.0]) + assert unused.value is None + np.testing.assert_allclose(fn.jacobian().toarray(), + np.c_[np.diag(2 * np.exp([0.0, 1.0])), np.exp([0.0, 1.0])]) + assert fn.hessian([1.0, 1.0]).shape == (3, 3) + + +def test_variables_is_a_copy(): + x, y = sp.Variable(2, 1), sp.Variable(2, 1) + prob = sp.Problem(sp.sum(x * y)) + prob.variables.clear() + assert prob.variables == [x, y] + fn = sp.compile(x * y) + fn.variables.reverse() + assert fn.variables == [x, y] + + +def test_variable_shared_by_two_problems(): + x, y, z = sp.Variable(2, 1), sp.Variable(2, 1), sp.Variable(2, 1) + p1 = sp.Problem(sp.sum(x * y)) # y is at offset 2 + p2 = sp.Problem(sp.sum(sp.exp(y) * z)) # y is at offset 0 + assert p1.variables == [x, y] and p2.variables == [y, z] + x.value, y.value, z.value = [1.0, 2.0], [3.0, 4.0], [5.0, 6.0] + np.testing.assert_allclose(p1.gradient(), [3, 4, 1, 2]) + np.testing.assert_allclose(p2.gradient(), np.r_[np.exp([3, 4]) * [5, 6], + np.exp([3, 4])]) + + y.value = [0.0, 1.0] # moves the point of both problems + np.testing.assert_allclose(p1.gradient(), [0, 1, 1, 2]) + np.testing.assert_allclose(p2.gradient(), np.r_[np.exp([0, 1]) * [5, 6], + np.exp([0, 1])]) + + p1.set_values([7.0, 8.0, -1.0, 0.5]) # x and y; z keeps its value + np.testing.assert_array_equal(p2.get_values(), [-1.0, 0.5, 5.0, 6.0]) + np.testing.assert_allclose(p2.objective(), np.exp([-1.0, 0.5]) @ [5.0, 6.0]) + + +def test_unset_variable_raises(): + x, y = sp.Variable(2, 1), sp.Variable(2, 1) + assert x.value is None + fn = sp.compile(x * y) + prob = sp.Problem(sp.sum(x * y)) + x.value = [1.0, 2.0] + for call in (fn.forward, fn.jacobian, lambda: fn.hessian([1.0, 1.0]), + fn.get_values, prob.objective, prob.gradient, prob.constraints, + prob.jacobian, lambda: prob.hessian(1.0, []), prob.get_values): + with pytest.raises(ValueError, match=r"Variable with shape \(2, 1\) has no value"): + call() + y.value = [3.0, 4.0] + np.testing.assert_array_equal(fn.forward(), [[3.0], [8.0]]) + assert prob.objective() == 11.0 + + +def test_set_values_round_trips_through_value(): + X, y, z = sp.Variable(2, 2), sp.Variable(3, 1), sp.Variable(1, 2) + prob = sp.Problem(sp.sum(X) + sp.sum(y) + sp.sum(z)) + assert X.value is None + u = np.arange(1.0, 10.0) + prob.set_values(u) # also works while the variables have no value + np.testing.assert_array_equal(X.value, [[1, 3], [2, 4]]) # column-major + np.testing.assert_array_equal(y.value, [[5], [6], [7]]) + np.testing.assert_array_equal(z.value, [[8, 9]]) + np.testing.assert_array_equal(prob.get_values(), u) + + u[:] = 0.0 # the values were copied + assert prob.get_values()[0] == 1.0 + out = prob.get_values() + out[:] = -1.0 # and so is what get_values returns + assert prob.get_values()[0] == 1.0 + + y.value = [0.5, 0.25, 0.125] + np.testing.assert_array_equal(prob.get_values(), [1, 2, 3, 4, .5, .25, .125, 8, 9]) + fn = sp.compile(sp.exp(y)) + fn.set_values([1.0, 2.0, 3.0]) + np.testing.assert_array_equal(prob.get_values()[4:7], [1, 2, 3]) + + +def test_caches_are_kept_at_an_unchanged_point(monkeypatch): + names = ["problem_objective_forward", "problem_constraint_forward", + "problem_gradient", "problem_jacobian_eval"] + calls = {n: count_calls(monkeypatch, n) for n in names} + counts = lambda: tuple(len(calls[n]) for n in names) # noqa: E731 + + def evaluate(prob): + prob.objective(), prob.gradient(), prob.constraints(), prob.jacobian() + + x, y = sp.Variable(2, 1), sp.Variable(2, 1) + prob = sp.Problem(sp.sum(x * y), [sp.exp(x) + y]) + prob.set_values([1.0, 2.0, 3.0, 4.0]) + evaluate(prob) + assert counts() == (1, 1, 1, 1) + J = prob.jacobian() + + prob.set_values(np.array([1.0, 2.0, 3.0, 4.0])) # the same point again + x.value = [1.0, 2.0] + y.value = np.array([[3.0], [4.0]]) + evaluate(prob) + assert counts() == (1, 1, 1, 1) and prob.jacobian() is J + + prob.set_values([1.0, 2.0, 3.0, 5.0]) # one entry moved + evaluate(prob) + assert counts() == (2, 2, 2, 2) and prob.jacobian() is J + + +def test_other_problems_keep_their_caches(monkeypatch): + n_obj = count_calls(monkeypatch, "problem_objective_forward") + x, y, z = sp.Variable(2, 1), sp.Variable(2, 1), sp.Variable(2, 1) + p1, p2 = sp.Problem(sp.sum(x * y)), sp.Problem(sp.sum(y * z)) + x.value, y.value, z.value = [1.0, 2.0], [3.0, 4.0], [5.0, 6.0] + p1.objective(), p2.objective() + assert len(n_obj) == 2 + p1.set_values([0.0, 0.0, 3.0, 4.0]) # moves x, which p2 does not use + assert p2.objective() == 39.0 and len(n_obj) == 2 + assert p1.objective() == 0.0 and len(n_obj) == 3 + p1.set_values([0.0, 0.0, 1.0, 1.0]) # moves y, which both use + assert p2.objective() == 11.0 and len(n_obj) == 4 + + +def test_equal_parameter_assignment_keeps_caches(monkeypatch): + n_obj = count_calls(monkeypatch, "problem_objective_forward") + n_upd = count_calls(monkeypatch, "problem_update_params") + x, a = sp.Variable(2, 1), sp.Parameter(2, 1, value=[1.0, 2.0]) + prob = sp.Problem(sp.sum(a * x)) + x.value = [3.0, 4.0] + assert prob.objective() == 11.0 + a.value = np.array([[1.0], [2.0]]) # the value it already has + assert prob.objective() == 11.0 + assert (len(n_obj), len(n_upd)) == (1, 1) + a.value = [2.0, 2.0] + assert prob.objective() == 14.0 + assert (len(n_obj), len(n_upd)) == (2, 2) + + +def test_symmetry_is_checked_on_equal_assignment(): + """A value set before quad_form is checked even when assigned again.""" + x, P = sp.Variable(2, 1), sp.Parameter(2, 2) + S = np.array([[2.0, 1.0], [1.0, 3.0]]) + P.value = S + sp.quad_form(x, P) + P.value = S + with pytest.raises(ValueError, match="symmetric"): + P.value = S + np.triu(np.ones((2, 2)), 1) + np.testing.assert_array_equal(P.value, S) + + +def test_variable_ids_are_unique_across_threads(): + n_threads, per_thread = 8, 500 + created = [[] for _ in range(n_threads)] + start = threading.Barrier(n_threads) + + def create(out): + start.wait() + for i in range(per_thread): + out.append(sp.Variable(1, 1) if i % 2 else sp.Parameter(1, 1)) + + threads = [threading.Thread(target=create, args=(out,)) for out in created] + for t in threads: + t.start() + for t in threads: + t.join() + ids = [leaf._id for out in created for leaf in out] + assert len(set(ids)) == n_threads * per_thread + for out in created: # within a thread, later means larger + assert [leaf._id for leaf in out] == sorted(leaf._id for leaf in out) + + +def test_compile_example(rng): + """The compile example of the README, against finite differences.""" + n = 5 + A, x0, w = rng.standard_normal((n, n)), rng.standard_normal(n), rng.standard_normal(n) + x = sp.Variable(n, 1) + f = sp.compile(sp.exp(A @ x) + x ** 2) + x.value = x0 + e = np.exp(A @ x0) + np.testing.assert_allclose(f.forward(), (e + x0 ** 2)[:, None]) + np.testing.assert_allclose(f.jacobian().toarray(), e[:, None] * A + 2 * np.diag(x0)) + np.testing.assert_allclose(f.hessian(w).toarray(), + A.T @ np.diag(w * e) @ A + 2 * np.diag(w)) + check_derivatives(f, x0, w) + + +def test_problem_example(rng): + """Two variables in a Problem, against analytic and finite differences.""" + d, N, h = 3, 6, 1e-6 + A = rng.standard_normal((N, d)) + theta0, w0 = rng.standard_normal(d), rng.uniform(0.5, 1.5, N) + sigma, lam = 0.7, np.array([-1.3]) + + theta = sp.Variable(d, 1) + w = sp.Variable(N, 1) + prob = sp.Problem(sp.sum(w * sp.logistic(A @ theta)), [sp.sum(w)]) + assert prob.variables == [theta, w] + theta.value, w.value = theta0, w0 + + z = A @ theta0 + s = 1 / (1 + np.exp(-z)) # logistic(z) = log(1 + exp(z)), so this is its slope + grad = np.r_[A.T @ (w0 * s), np.logaddexp(0, z)] + H = np.zeros((d + N, d + N)) + H[:d, :d] = A.T @ np.diag(w0 * s * (1 - s)) @ A + H[:d, d:] = A.T * s + H[d:, :d] = H[:d, d:].T + assert prob.objective() == pytest.approx(w0 @ np.logaddexp(0, z)) + np.testing.assert_allclose(prob.gradient(), grad) + np.testing.assert_allclose(prob.jacobian().toarray(), [np.r_[np.zeros(d), np.ones(N)]]) + np.testing.assert_allclose(prob.hessian(sigma, lam).toarray(), sigma * H, atol=1e-12) + + def lagrangian_gradient(u): + prob.set_values(u) + return sigma * prob.gradient() + prob.jacobian().T @ lam + + u0 = np.r_[theta0, w0] + grad_fd, H_fd = np.zeros(d + N), np.zeros((d + N, d + N)) + for j in range(d + N): + e = np.zeros(d + N) + e[j] = h + prob.set_values(u0 + e) + f_plus = prob.objective() + prob.set_values(u0 - e) + grad_fd[j] = (f_plus - prob.objective()) / (2 * h) + H_fd[:, j] = (lagrangian_gradient(u0 + e) - lagrangian_gradient(u0 - e)) / (2 * h) + prob.set_values(u0) + np.testing.assert_allclose(prob.gradient(), grad_fd, rtol=1e-6, atol=1e-7) + np.testing.assert_allclose(prob.hessian(sigma, lam).toarray(), H_fd, + rtol=1e-5, atol=1e-6) + np.testing.assert_array_equal(theta.value.ravel(), theta0) From 9d079945e37d3ced354881ce585feb6500de1afb Mon Sep 17 00:00:00 2001 From: dance858 Date: Mon, 30 Nov 2026 09:39:14 -0800 Subject: [PATCH 2/2] Check example Hessians by finite differences only The analytic references used NumPy's A.T @ D @ A, which returns wrong numbers in the emulated aarch64 wheel tests (NumPy 2.5.5). The Hessians are still checked against finite differences. Also rewrite the symmetry test and tighten the free-threading sentence in the README. Co-Authored-By: Claude Fable 5.2 --- README.md | 4 ++-- tests/test_variables.py | 25 ++++++++----------------- 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 41409a4..9465f97 100644 --- a/README.md +++ b/README.md @@ -151,8 +151,8 @@ default builds. There is no `cp313t` wheel because NumPy ships none from 2.5 onwards, so that build would have to compile NumPy from source. The extension declares that it does not need the GIL, so importing it leaves -free threading enabled. Distinct problems can be built and evaluated -concurrently from different threads: the engine keeps no mutable global state, +free threading enabled. Problems that share no variable or parameter can be +built and evaluated concurrently from different threads: the engine keeps no mutable global state, every problem and expression owns its own buffers, and all inputs and outputs are copied at the boundary. This assumes a default build, since `SP_TRACK_MEMORY` adds global allocation counters that are not thread-safe. diff --git a/tests/test_variables.py b/tests/test_variables.py index a4638d3..7a2dd47 100644 --- a/tests/test_variables.py +++ b/tests/test_variables.py @@ -185,15 +185,13 @@ def test_equal_parameter_assignment_keeps_caches(monkeypatch): def test_symmetry_is_checked_on_equal_assignment(): - """A value set before quad_form is checked even when assigned again.""" - x, P = sp.Variable(2, 1), sp.Parameter(2, 2) - S = np.array([[2.0, 1.0], [1.0, 3.0]]) - P.value = S - sp.quad_form(x, P) - P.value = S + """Assigning the value a parameter already has does not skip the check.""" + N = np.array([[2.0, 5.0], [1.0, 3.0]]) # not symmetric + P = sp.Parameter(2, 2, value=N) + P._symmetric = True # what quad_form sets on its matrix with pytest.raises(ValueError, match="symmetric"): - P.value = S + np.triu(np.ones((2, 2)), 1) - np.testing.assert_array_equal(P.value, S) + P.value = N + np.testing.assert_array_equal(P.value, N) def test_variable_ids_are_unique_across_threads(): @@ -227,13 +225,11 @@ def test_compile_example(rng): e = np.exp(A @ x0) np.testing.assert_allclose(f.forward(), (e + x0 ** 2)[:, None]) np.testing.assert_allclose(f.jacobian().toarray(), e[:, None] * A + 2 * np.diag(x0)) - np.testing.assert_allclose(f.hessian(w).toarray(), - A.T @ np.diag(w * e) @ A + 2 * np.diag(w)) - check_derivatives(f, x0, w) + check_derivatives(f, x0, w) # the Hessian is checked here def test_problem_example(rng): - """Two variables in a Problem, against analytic and finite differences.""" + """Two variables in a Problem; the Hessian against finite differences.""" d, N, h = 3, 6, 1e-6 A = rng.standard_normal((N, d)) theta0, w0 = rng.standard_normal(d), rng.uniform(0.5, 1.5, N) @@ -248,14 +244,9 @@ def test_problem_example(rng): z = A @ theta0 s = 1 / (1 + np.exp(-z)) # logistic(z) = log(1 + exp(z)), so this is its slope grad = np.r_[A.T @ (w0 * s), np.logaddexp(0, z)] - H = np.zeros((d + N, d + N)) - H[:d, :d] = A.T @ np.diag(w0 * s * (1 - s)) @ A - H[:d, d:] = A.T * s - H[d:, :d] = H[:d, d:].T assert prob.objective() == pytest.approx(w0 @ np.logaddexp(0, z)) np.testing.assert_allclose(prob.gradient(), grad) np.testing.assert_allclose(prob.jacobian().toarray(), [np.r_[np.zeros(d), np.ones(N)]]) - np.testing.assert_allclose(prob.hessian(sigma, lam).toarray(), sigma * H, atol=1e-12) def lagrangian_gradient(u): prob.set_values(u)