Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions sparsediffpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@
from sparsediffpy._compile import ( # noqa: F401
CompiledExpression, PerformanceWarning, Problem, compile,
)
from sparsediffpy._stats import ProblemStats, Timing # noqa: F401
17 changes: 15 additions & 2 deletions sparsediffpy/_atoms.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)


Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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):
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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]
Expand All @@ -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]
Expand All @@ -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).

Expand Down Expand Up @@ -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)
Expand All @@ -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.

Expand Down
3 changes: 3 additions & 0 deletions sparsediffpy/_bindings/bindings.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 = {
Expand Down
22 changes: 22 additions & 0 deletions sparsediffpy/_bindings/problem/stats.h
Original file line number Diff line number Diff line change
@@ -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 */
Loading
Loading