diff --git a/README.md b/README.md index 84a6c98..939d9f7 100644 --- a/README.md +++ b/README.md @@ -148,6 +148,44 @@ e = sp.sum(x ** 2) # fast: three nodes for any n model really has to be written that way, silence it with `warnings.filterwarnings("ignore", category=sp.PerformanceWarning)`. +## Timing + +`prob.stats` (and `fn.stats` for a compiled expression) reports where the time +went so far, split into the Python interface and the C engine: + +```python +print(prob.stats) +``` + +``` + calls python (s) engine (s) + build expressions 0.104 + setup 0.055 2.401 + objective 20 0.000 0.015 + gradient 20 0.000 2.655 + constraints 20 0.000 0.000 + jacobian 20 0.000 0.000 + hessian 20 0.000 1.810 + total 0.160 6.881 + 2% 98% +``` + +`engine` is the time inside the engine's own routines and `python` is everything +around them, the bindings included. `build expressions` is the time spent in +SparseDiffPy's operators and functions creating the expressions the problem uses, +and `setup` is the `sp.Problem(...)` or `sp.compile(...)` call. The other rows are +the methods, summed over the calls that did real work: a result served from the +cache is not a call. A method is not charged for what it needs from another one, +so the `hessian` row does not include the Jacobian it relies on. + +The table is in seconds, or in ms or us when the smaller of the two totals is +small. The same numbers +are available as fields, always in seconds: `prob.stats.hessian.python`, +`.engine` and `.calls` for each row (`build`, `setup`, `objective`, `gradient`, +`constraints`, `jacobian`, `hessian`), and `prob.stats.python` and +`prob.stats.engine` for the totals. `prob.stats` is a snapshot; read it again for +newer numbers. + ## Supported operations - **Operators:** `+ - * @ **`, `/` by a constant, `.T`, and indexing with ints, slices and integer lists: `x[1:3]` on a diff --git a/sparsediffpy/__init__.py b/sparsediffpy/__init__.py index 2286247..efad770 100644 --- a/sparsediffpy/__init__.py +++ b/sparsediffpy/__init__.py @@ -26,3 +26,4 @@ from sparsediffpy._compile import ( # noqa: F401 CompiledExpression, PerformanceWarning, Problem, compile, ) +from sparsediffpy._stats import ProblemStats, Timing # noqa: F401 diff --git a/sparsediffpy/_atoms.py b/sparsediffpy/_atoms.py index 58ce53e..88a8a30 100644 --- a/sparsediffpy/_atoms.py +++ b/sparsediffpy/_atoms.py @@ -6,7 +6,7 @@ from sparsediffpy import _sparsediffengine as _C from sparsediffpy._expression import ( Constant, Node, Parameter, Variable, _check_shape, _check_symmetric, - cast_to_const, + _pow, _timed, cast_to_const, ) @@ -24,6 +24,7 @@ def _elementwise(make, name, restricted=False): A restricted atom (domain not all of R) only accepts a plain Variable. """ + @_timed def atom(x): x = cast_to_const(x) if restricted: @@ -50,11 +51,13 @@ def atom(x): xexp = _elementwise(_C.make_xexp, "xexp") +@_timed def power(x, p): """Elementwise x ** p for a constant exponent p.""" - return cast_to_const(x) ** p + return _pow(cast_to_const(x), p) +@_timed def atan2(y, x): """Elementwise atan2(y, x) for distinct Variables of the same shape.""" _require_variables("atan2", y, x) @@ -72,6 +75,7 @@ def _reduction_shape(x, axis): return shapes[axis] +@_timed def sum(x, axis=None): """Sum of entries: axis=None -> (1, 1), axis=0 -> (1, d2), axis=1 -> (1, d1).""" x = cast_to_const(x) @@ -80,6 +84,7 @@ def sum(x, axis=None): return Node(lambda c: _C.make_sum(c, c_axis), [x], shape) +@_timed def prod(x, axis=None): """Product of entries; shapes as for :func:`sum`. ``x`` must be a Variable.""" if not isinstance(x, Variable): @@ -91,6 +96,7 @@ def prod(x, axis=None): return Node(make, [x], shape) +@_timed def reshape(x, d1, d2): """Column-major reshape.""" x, shape = cast_to_const(x), _check_shape(d1, d2) @@ -99,6 +105,7 @@ def reshape(x, d1, d2): return Node(lambda c: _C.make_reshape(c, *shape), [x], shape) +@_timed def trace(x): """Sum of the diagonal of a square matrix, as a (1, 1) expression.""" x = cast_to_const(x) @@ -107,6 +114,7 @@ def trace(x): return Node(_C.make_trace, [x], (1, 1)) +@_timed def diag_vec(x): """(n, 1) column vector -> (n, n) diagonal matrix.""" x = cast_to_const(x) @@ -115,6 +123,7 @@ def diag_vec(x): return Node(_C.make_diag_vec, [x], (x.shape[0], x.shape[0])) +@_timed def hstack(exprs): """Concatenate horizontally; all arguments need the same number of rows.""" exprs = [cast_to_const(e) for e in exprs] @@ -125,6 +134,7 @@ def hstack(exprs): return Node(lambda *caps: _C.make_hstack(list(caps)), exprs, shape) +@_timed def vstack(exprs): """Concatenate vertically; all arguments need the same number of columns.""" exprs = [cast_to_const(e) for e in exprs] @@ -135,6 +145,7 @@ def vstack(exprs): return Node(lambda *caps: _C.make_vstack(list(caps)), exprs, shape) +@_timed def quad_form(x, Q): """x' Q x for a column vector x (n, 1) and a constant or Parameter Q (n, n). @@ -166,6 +177,7 @@ def quad_form(x, Q): V.indptr.astype(np.int32), n, n), [x], (1, 1)) +@_timed def quad_over_lin(x, z): """sum(x**2) / z for distinct Variables x and scalar z.""" _require_variables("quad_over_lin", x, z) @@ -174,6 +186,7 @@ def quad_over_lin(x, z): return Node(_C.make_quad_over_lin, [x, z], (1, 1)) +@_timed def rel_entr(x, y): """Elementwise x * log(x / y) for distinct Variables x, y. diff --git a/sparsediffpy/_bindings/bindings.c b/sparsediffpy/_bindings/bindings.c index 02a283d..278005c 100644 --- a/sparsediffpy/_bindings/bindings.c +++ b/sparsediffpy/_bindings/bindings.c @@ -63,6 +63,7 @@ #include "problem/make_problem.h" #include "problem/objective_forward.h" #include "problem/register_params.h" +#include "problem/stats.h" #include "problem/update_params.h" static int numpy_initialized = 0; @@ -193,6 +194,8 @@ static PyMethodDef DNLPMethods[] = { "Register parameter nodes with a problem"}, {"problem_update_params", py_problem_update_params, METH_VARARGS, "Update parameter values from theta array"}, + {"problem_stats", py_problem_stats, METH_O, + "The engine's accumulated timers in seconds, as a dict keyed by phase"}, {NULL, NULL, 0, NULL}}; static struct PyModuleDef sparsediffpy_module = { diff --git a/sparsediffpy/_bindings/problem/stats.h b/sparsediffpy/_bindings/problem/stats.h new file mode 100644 index 0000000..079a299 --- /dev/null +++ b/sparsediffpy/_bindings/problem/stats.h @@ -0,0 +1,22 @@ +#ifndef PROBLEM_STATS_H +#define PROBLEM_STATS_H + +#include "common.h" + +/* problem_stats(prob): the engine's accumulated timers in seconds, as a dict + * keyed by phase. The Python layer subtracts them from its own wall times to + * get the time spent outside the engine. */ +static PyObject *py_problem_stats(PyObject *self, PyObject *capsule) +{ + (void) self; + problem *prob = (problem *) PyCapsule_GetPointer(capsule, PROBLEM_CAPSULE_NAME); + if (!prob) return NULL; + const Diff_engine_stats *s = &prob->stats; + return Py_BuildValue("{s:d,s:d,s:d,s:d,s:d,s:d}", "setup", + s->time_init_derivatives, "objective", s->time_forward_obj, + "gradient", s->time_eval_gradient, "constraints", + s->time_forward_constraints, "jacobian", + s->time_eval_jacobian, "hessian", s->time_eval_hessian); +} + +#endif /* PROBLEM_STATS_H */ diff --git a/sparsediffpy/_compile.py b/sparsediffpy/_compile.py index 5935b89..9d6d134 100644 --- a/sparsediffpy/_compile.py +++ b/sparsediffpy/_compile.py @@ -9,6 +9,7 @@ import os import sys import warnings +from time import perf_counter import numpy as np import scipy.sparse as sps @@ -18,6 +19,7 @@ Constant, Parameter, Variable, _check_size, _flatten_shaped, _flatten_vector, _Index, cast_to_const, ) +from sparsediffpy._stats import ProblemStats, Timing class PerformanceWarning(UserWarning): @@ -30,19 +32,21 @@ class PerformanceWarning(UserWarning): def _collect_leaves(exprs): - """Return (variables, parameters, n_entry_picks) for the expressions in exprs. + """Return (variables, parameters, n_entry_picks, build_time) for exprs. The Variables and the Parameters are each in creation order. n_entry_picks counts the nodes that index one entry out of an array (``x[i]`` or ``X[i, j]``), the signature of a model written entry by entry. + build_time is the seconds it took to build the expressions in exprs. """ leaves, seen, stack = [], set(), list(exprs) - n_entry_picks = 0 + n_entry_picks, build_time = 0, 0.0 while stack: e = stack.pop() if id(e) in seen: continue seen.add(id(e)) + build_time += e._build_time if isinstance(e, (Variable, Parameter)): leaves.append(e) elif (isinstance(e, _Index) and e.shape == (1, 1) @@ -53,7 +57,8 @@ def _collect_leaves(exprs): variables = [e for e in leaves if isinstance(e, Variable)] if not variables: raise ValueError("Expression must contain at least one Variable") - return variables, [e for e in leaves if isinstance(e, Parameter)], n_entry_picks + parameters = [e for e in leaves if isinstance(e, Parameter)] + return variables, parameters, n_entry_picks, build_time def _warn_if_entrywise(n_entry_picks): @@ -154,6 +159,10 @@ def _read_only(arr): return arr +# The phases the engine times, named as in _C.problem_stats and ProblemStats. +_PHASES = ("setup", "objective", "gradient", "constraints", "jacobian", "hessian") + + def _flat_value(leaf, kind): """The column-major value of a Variable or Parameter, or raise if unset.""" if leaf._flat is None: @@ -186,15 +195,19 @@ class Problem: 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. + + ``prob.stats`` says where the time went, split into the Python interface + and the C engine. """ - def __init__(self, objective, constraints=(), verbose=False): + def __init__(self, objective, constraints=()): + start = perf_counter() objective = cast_to_const(objective) 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._variables, self._params, n_entry_picks = _collect_leaves( - [objective, *constraints]) + self._variables, self._params, n_entry_picks, self._build_time = \ + _collect_leaves([objective, *constraints]) _warn_if_entrywise(n_entry_picks) # before the (possibly slow) build var_offsets, self.n_vars = _stack(self._variables) param_offsets, self._n_params = _stack(self._params) @@ -207,7 +220,9 @@ def __init__(self, objective, constraints=(), verbose=False): 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) + # The engine can print its own timings when it frees the problem; the + # Python layer reports them through stats instead. + self._capsule = _C.make_problem(obj_cap, con_caps, False) param_caps = [c for _, c in obj_build.params + con_build.params] if param_caps: _C.problem_register_params(self._capsule, param_caps) @@ -225,6 +240,37 @@ def __init__(self, objective, constraints=(), verbose=False): self._jac = _csr_view(_C.problem_jacobian_csr(self._capsule)) self._hess = _csr_view(_C.problem_hessian_csr(self._capsule)) self._jac_current = False + # Wall seconds and number of calls per phase, for stats. + self._wall = dict.fromkeys(_PHASES, 0.0) + self._calls = dict.fromkeys(_PHASES, 0) + self._wall["setup"] = perf_counter() - start + + def _charge(self, phase, start): + """Charge the time since start to phase, as one call.""" + self._wall[phase] += perf_counter() - start + self._calls[phase] += 1 + + @property + def stats(self): + """Timings so far as a ``ProblemStats``; ``print(prob.stats)`` for a table.""" + return self._stats(compiled=False) + + def _stats(self, compiled): + engine = _C.problem_stats(self._capsule) + # The engine's time is part of the wall time; the rest is Python. + rows = {phase: Timing(self._calls[phase], + max(self._wall[phase] - engine[phase], 0.0), + engine[phase]) for phase in _PHASES} + if compiled: + # compile() gives the problem a zero objective, which the engine + # still evaluates for the Hessian: report it there. + extra = [rows["objective"], rows["gradient"]] + h = rows["hessian"] + rows["hessian"] = Timing(h.calls, h.python + sum(t.python for t in extra), + h.engine + sum(t.engine for t in extra)) + rows["objective"] = rows["gradient"] = Timing() + return ProblemStats(build=Timing(python=self._build_time), **rows, + _compiled=compiled) @property def variables(self): @@ -279,22 +325,28 @@ def objective(self): """Objective value (float).""" self._refresh() if self._obj is None: + start = perf_counter() self._obj = _C.problem_objective_forward(self._capsule, self._u) + self._charge("objective", start) return self._obj def constraints(self): """Stacked constraint values, shape (total_constraint_size,).""" self._refresh() if self._con is None: + start = perf_counter() self._con = _read_only( _C.problem_constraint_forward(self._capsule, self._u)) + self._charge("constraints", start) return self._con def gradient(self): """Objective gradient, shape (n_vars,).""" self.objective() if self._grad is None: + start = perf_counter() self._grad = _read_only(_C.problem_gradient(self._capsule)) + self._charge("gradient", start) return self._grad def jacobian(self): @@ -305,8 +357,10 @@ def jacobian(self): """ self.constraints() if not self._jac_current: + start = perf_counter() _C.problem_jacobian_eval(self._capsule) self._jac_current = True + self._charge("jacobian", start) return self._jac def hessian(self, obj_factor, lagrange): @@ -315,12 +369,17 @@ def hessian(self, obj_factor, lagrange): The same matrix is returned on every call, with its values refreshed in place; copy it to keep the values of this call. """ + start = perf_counter() 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). + # They are timed as their own phases, not as part of the Hessian. + checked = perf_counter() self.gradient() self.jacobian() + ready = perf_counter() _C.problem_hessian_eval(self._capsule, float(obj_factor), lagrange) + self._charge("hessian", start + (ready - checked)) return self._hess @@ -350,6 +409,14 @@ def get_values(self): """The variables' values as a new flat array, stacked as ``variables``.""" return self._problem.get_values() + @property + def stats(self): + """Timings so far as a ``ProblemStats``; ``print(fn.stats)`` for a table. + + ``forward()`` is reported in its ``constraints`` field. + """ + return self._problem._stats(compiled=True) + def forward(self): """f(x) as a read-only array of shape f.shape.""" return self._problem.constraints().reshape(self.shape, order="F") diff --git a/sparsediffpy/_expression.py b/sparsediffpy/_expression.py index 229d7b5..43cd1c7 100644 --- a/sparsediffpy/_expression.py +++ b/sparsediffpy/_expression.py @@ -5,9 +5,11 @@ 2-D ``(d1, d2)`` and values are flattened column-major, like the C engine. """ +import functools import itertools import numbers import threading +from time import perf_counter import numpy as np import scipy.sparse as sps @@ -48,12 +50,31 @@ def _check_sparse_size(shape, nnz): f"columns and nonzeros") +def _timed(fn): + """Charge the wall time of fn to the expression it returns. + + For the functions users call to build expressions. A problem adds up + ``_build_time`` over its nodes to report how long they took to build. + A timed function must not call another timed one, or that time would be + counted twice: inside the package use the untimed ``_neg``, ``_pow``, + ``_broadcast`` and ``_index_flat``. + """ + @functools.wraps(fn) + def wrapper(*args, **kwargs): + start = perf_counter() + out = fn(*args, **kwargs) + out._build_time += perf_counter() - start + return out + return wrapper + + class Expression: """Base class for all expressions. Supports + - * @ ** [] and .T.""" __array_ufunc__ = None # make NumPy defer to our reflected operators shape = None args = () + _build_time = 0.0 # seconds spent creating this expression, see _timed @property def size(self): @@ -61,31 +82,40 @@ def size(self): return self.shape[0] * self.shape[1] @property + @_timed def T(self): """Transpose.""" return Node(_C.make_transpose, [self], self.shape[::-1]) + @_timed def __add__(self, other): return _add(self, cast_to_const(other)) + @_timed def __radd__(self, other): return _add(cast_to_const(other), self) + @_timed def __sub__(self, other): - return _add(self, -cast_to_const(other)) + return _add(self, _neg(cast_to_const(other))) + @_timed def __rsub__(self, other): - return _add(cast_to_const(other), -self) + return _add(cast_to_const(other), _neg(self)) + @_timed def __neg__(self): - return Node(_C.make_neg, [self], self.shape) + return _neg(self) + @_timed def __mul__(self, other): return _mul(self, cast_to_const(other)) + @_timed def __rmul__(self, other): return _mul(cast_to_const(other), self) + @_timed def __truediv__(self, other): """self / c for a constant c (a number or array), as self * (1 / c).""" if isinstance(other, Expression) or sps.issparse(other): @@ -94,19 +124,21 @@ def __truediv__(self, other): c = np.asarray(other, dtype=np.float64) if np.any(c == 0): raise ZeroDivisionError("division of an expression by zero") - return self * (1.0 / c) + return _mul(self, cast_to_const(1.0 / c)) + @_timed def __matmul__(self, other): return _matmul(self, cast_to_const(other)) + @_timed def __rmatmul__(self, other): return _matmul(cast_to_const(other), self) + @_timed def __pow__(self, p): - if not isinstance(p, numbers.Real): - raise TypeError("Exponent must be a constant number") - return Node(lambda c: _C.make_power(c, float(p)), [self], self.shape) + return _pow(self, p) + @_timed def __getitem__(self, key): return _index(self, key) @@ -292,6 +324,7 @@ def _broadcast_shape(a, b): return tuple(out) +@_timed def broadcast(x, shape): """Broadcast a scalar, row or column expression to ``shape``.""" x, shape = cast_to_const(x), _check_shape(*shape) @@ -304,10 +337,25 @@ def broadcast(x, shape): return Node(lambda c: _C.make_broadcast(c, *shape), [x], shape) +_broadcast = broadcast.__wrapped__ # untimed, for use inside timed functions + + +def _neg(x): + """-x.""" + return Node(_C.make_neg, [x], x.shape) + + +def _pow(x, p): + """Elementwise x ** p for a constant number p.""" + if not isinstance(p, numbers.Real): + raise TypeError("Exponent must be a constant number") + return Node(lambda c: _C.make_power(c, float(p)), [x], x.shape) + + def _add(a, b): """a + b, broadcasting both operands to the common shape first.""" shape = _broadcast_shape(a.shape, b.shape) - return Node(_C.make_add, [broadcast(a, shape), broadcast(b, shape)], shape) + return Node(_C.make_add, [_broadcast(a, shape), _broadcast(b, shape)], shape) def _mul(a, b): @@ -321,7 +369,7 @@ def _mul(a, b): if _is_data(a) and a.shape == (1, 1): return Node(_C.make_param_scalar_mult, [a, b], b.shape) shape = _broadcast_shape(a.shape, b.shape) - a, b = broadcast(a, shape), broadcast(b, shape) + a, b = _broadcast(a, shape), _broadcast(b, shape) make = _C.make_param_vector_mult if _is_data(a) else _C.make_multiply return Node(make, [a, b], shape) @@ -358,6 +406,7 @@ def _matmul_with_data(make, A): return lambda c: make(None, c, "dense", data, m, n) +@_timed def index_flat(x, flat_indices, shape): """Gather entries of ``x`` by column-major flat indices into ``shape``.""" x = cast_to_const(x) @@ -373,6 +422,9 @@ def index_flat(x, flat_indices, shape): return _Index(lambda c: _C.make_index(c, shape[0], shape[1], idx), [x], shape) +_index_flat = index_flat.__wrapped__ # untimed, for use inside timed functions + + def _axis_indices(key, n): """Positions along an axis of length n chosen by an int, slice or int list.""" if isinstance(key, (bool, np.bool_)): # bool subclasses int; x[True] is not x[1] @@ -403,9 +455,9 @@ def _index(x, key): f"Expected 2 indices for shape {x.shape}, got {len(key)}") rows, cols = _axis_indices(key[0], d1), _axis_indices(key[1], d2) flat = (rows[:, None] + cols[None, :] * d1).ravel(order="F") - return index_flat(x, flat, (rows.size, cols.size)) + return _index_flat(x, flat, (rows.size, cols.size)) if d1 > 1 and d2 > 1: raise IndexError(f"A single index on shape {x.shape} is ambiguous; " "use X[i, j], X[i, :] or X[:, j]") flat = _axis_indices(key, x.size) - return index_flat(x, flat, (1, flat.size) if d1 == 1 else (flat.size, 1)) + return _index_flat(x, flat, (1, flat.size) if d1 == 1 else (flat.size, 1)) diff --git a/sparsediffpy/_stats.py b/sparsediffpy/_stats.py new file mode 100644 index 0000000..393b455 --- /dev/null +++ b/sparsediffpy/_stats.py @@ -0,0 +1,86 @@ +"""Where the time went: Python interface versus C engine, per phase.""" + +from dataclasses import dataclass, fields + + +@dataclass(frozen=True) +class Timing: + """Time of one phase, in seconds. + + ``engine`` is the time inside the C engine's own routines and ``python`` + is everything else: the Python code and the bindings around them. + ``calls`` counts real evaluations; a result served from the cache is not + a call and takes no time here. + """ + + calls: int = 0 + python: float = 0.0 + engine: float = 0.0 + + @property + def total(self): + """python + engine.""" + return self.python + self.engine + + +@dataclass(frozen=True) +class ProblemStats: + """A snapshot of a problem's timings; ``print`` it for a table. + + ``build`` is the time spent in SparseDiffPy's operators and atoms creating + the expressions the problem uses, before the problem existed. ``setup`` is + the ``Problem(...)`` call. The other fields are the problem's methods, + accumulated over all calls so far. A method is not charged for what it + needs from another one (``hessian`` does not include ``jacobian``). + """ + + build: Timing + setup: Timing + objective: Timing + gradient: Timing + constraints: Timing + jacobian: Timing + hessian: Timing + _compiled: bool = False # made by compile(): constraints is forward() + + def _rows(self): + """(name, Timing) for every phase, in table order.""" + return [(f.name, getattr(self, f.name)) for f in fields(self) + if f.name != "_compiled"] + + @property + def python(self): + """Total seconds outside the engine.""" + return sum(t.python for _, t in self._rows()) + + @property + def engine(self): + """Total seconds inside the engine.""" + return sum(t.engine for _, t in self._rows()) + + def __str__(self): + """A table of the phases that ran, in s, ms or us: the largest unit + that keeps digits in the smaller of the two totals.""" + total = self.python + self.engine + small = min([t for t in (self.python, self.engine) if t > 0], default=0.0) + unit, scale = ("s", 1) if small >= 0.1 else ( + ("ms", 1e3) if small >= 1e-4 else ("us", 1e6)) + labels = {"build": "build expressions"} + if self._compiled: + labels["constraints"] = "forward" + lines = [f" {'':<18}{'calls':>7}{f'python ({unit})':>13}" + f"{f'engine ({unit})':>13}"] + for name, t in self._rows(): + once = name in ("build", "setup") # not a method: no call count + if not once and t.calls == 0: + continue # never evaluated + calls = "" if once else str(t.calls) + engine = "" if name == "build" else f"{scale * t.engine:.3f}" + lines.append(f" {labels.get(name, name):<18}{calls:>7}" + f"{scale * t.python:>13.3f}{engine:>13}".rstrip()) + lines.append(f" {'total':<18}{'':>7}{scale * self.python:>13.3f}" + f"{scale * self.engine:>13.3f}") + if total > 0: + share = round(100 * self.python / total) + lines.append(f" {'':<18}{'':>7}{f'{share}%':>13}{f'{100 - share}%':>13}") + return "\n".join(lines) diff --git a/tests/test_stats.py b/tests/test_stats.py new file mode 100644 index 0000000..7b95cc3 --- /dev/null +++ b/tests/test_stats.py @@ -0,0 +1,148 @@ +"""Tests for the timings reported by ``Problem.stats`` and ``compile(...).stats``.""" + +import dataclasses +import gc +from time import perf_counter + +import numpy as np + +import sparsediffpy as sp + +EVALUATIONS = ("objective", "gradient", "constraints", "jacobian", "hessian") + + +def _problem(): + x = sp.Variable(3, 1) + prob = sp.Problem(sp.sum(sp.exp(x)), [sp.sum(x ** 2), x[0] * x[1]]) + x.value = [1.0, 2.0, 3.0] + return x, prob + + +def test_calls_follow_the_cache(): + x, prob = _problem() + assert all(getattr(prob.stats, name).calls == 0 for name in EVALUATIONS) + prob.hessian(1.0, [1.0, 1.0]) # needs every other stage once + assert all(getattr(prob.stats, name).calls == 1 for name in EVALUATIONS) + prob.hessian(2.0, [1.0, 1.0]) # same point: only the Hessian runs again + prob.jacobian() + stats = prob.stats + assert stats.hessian.calls == 2 + assert all(getattr(stats, name).calls == 1 for name in EVALUATIONS[:-1]) + x.value = [2.0, 2.0, 3.0] + prob.objective() + assert prob.stats.objective.calls == 2 + assert prob.stats.gradient.calls == 1 + + +def test_times_are_split_into_python_and_engine(): + _, prob = _problem() + prob.hessian(1.0, [1.0, 1.0]) + stats = prob.stats + rows = [getattr(stats, f.name) for f in dataclasses.fields(stats) + if f.name != "_compiled"] + assert len(rows) == 7 + for row in rows: + assert row.python >= 0 and row.engine >= 0 + assert row.total == row.python + row.engine + assert stats.python == sum(row.python for row in rows) + assert stats.engine == sum(row.engine for row in rows) + assert stats.engine > 0 and stats.python > 0 + + +def test_build_time_counts_each_operator_once(): + x = sp.Variable(50, 1) + start = perf_counter() + f = sp.sum(x[0] ** 2) + for i in range(1, 50): + f = f + (x[i] - 1.0) ** 2 / 2.0 # operators that call other operators + wall = perf_counter() - start + stats = sp.Problem(f).stats + assert 0 < stats.build.python <= wall + assert stats.build.engine == 0 and stats.build.calls == 0 + + +def test_no_timed_function_calls_another(monkeypatch): + # With a clock that ticks once per reading, a timed call that calls no other + # timed one is charged exactly 1; one that nests is charged more. + from sparsediffpy import _expression + ticks = iter(range(10 ** 6)) + monkeypatch.setattr(_expression, "perf_counter", lambda: next(ticks)) + x, y, X = sp.Variable(3, 1), sp.Variable(3, 1), sp.Variable(3, 3) + z = sp.Variable(1, 1) + A, Q = np.ones((3, 3)), np.eye(3) + made = [ + x + 1.0, 1.0 + x, x - y, 1.0 - x, -x, x * y, 2.0 * x, x / 2.0, A @ x, + x.T @ A, x ** 2, x[0], x[1:3], X[0, :], X.T, sp.power(x, 3), + sp.broadcast(z, (3, 1)), sp.index_flat(x, [0, 2], (2, 1)), sp.exp(x), + sp.log(x), sp.atan2(x, y), sp.sum(X, axis=0), sp.prod(x), + sp.reshape(X, 9, 1), sp.trace(X), sp.diag_vec(x), sp.hstack([x, y]), + sp.vstack([x, y]), sp.quad_form(x, Q), sp.quad_over_lin(x, z), + sp.rel_entr(x, y), + ] + assert [e._build_time for e in made] == [1] * len(made) + + +def test_build_time_only_counts_the_problems_own_expressions(): + x = sp.Variable(400, 1) # few enough entries not to raise a PerformanceWarning + small = sp.sum(x[0] ** 2) + big = small + for i in range(1, 400): + big = big + x[i] ** 2 + assert sp.Problem(small).stats.build.python < sp.Problem(big).stats.build.python + + +def test_setup_time(): + x = sp.Variable(200, 1) + f = sp.sum(sp.exp(x) * x) + start = perf_counter() + prob = sp.Problem(f) + wall = perf_counter() - start + setup = prob.stats.setup + assert setup.engine > 0 + assert setup.total <= wall + + +def test_stats_is_a_snapshot(): + _, prob = _problem() + prob.objective() + before = prob.stats + calls, python = before.hessian.calls, before.python + prob.hessian(1.0, [1.0, 1.0]) + assert (before.hessian.calls, before.python) == (calls, python) + assert prob.stats.hessian.calls == calls + 1 + + +def test_table(): + _, prob = _problem() + prob.gradient() + lines = str(prob.stats).splitlines() + header = lines[0].split() + assert header[::3] == ["calls", "engine"] and header[1] == "python" + assert header[2] == header[4] in ("(s)", "(ms)", "(us)") # scaled to the total + names = [line.split()[0] for line in lines[1:-1]] + # phases that never ran are left out + assert names == ["build", "setup", "objective", "gradient", "total"] + assert lines[3].split()[1] == "1" # objective was called once + shares = [int(s.rstrip("%")) for s in lines[-1].split()] + assert sum(shares) == 100 + + +def test_compiled_expression_stats(): + x = sp.Variable(3, 1) + fn = sp.compile(sp.exp(x)) + x.value = [1.0, 2.0, 3.0] + fn.forward() + fn.hessian(np.ones(3)) + stats = fn.stats + assert (stats.constraints.calls, stats.jacobian.calls, stats.hessian.calls) \ + == (1, 1, 1) + names = [line.split()[0] for line in str(stats).splitlines()[1:-1]] + assert names == ["build", "setup", "forward", "jacobian", "hessian", "total"] + + +def test_nothing_is_printed_unasked(capfd): + x = sp.Variable(3, 1) + prob = sp.Problem(sp.sum(sp.exp(x))) + del prob + gc.collect() # the engine's own banner at free stays off + assert capfd.readouterr().out == ""