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
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,25 @@ res = minimize(lambda u: at(u, "objective"), np.zeros(4),
print(res.x) # approx. [0. 0.289 0.549 0.784], on the boundary ||x|| = 1
```

## Write array operations, not loops

Every operation is a node in the expression graph, so a model written one
entry at a time gets a few nodes per entry and is slower to compile and to
differentiate than the same model written with array operations:

```python
e = x[0] ** 2
for i in range(1, n):
e = e + x[i] ** 2 # slow: a few nodes per entry

e = sp.sum(x ** 2) # fast: three nodes for any n
```

`sp.compile` and `sp.Problem` raise a `sp.PerformanceWarning` when more than
500 single entries (`x[i]` or `X[i, j]`) are indexed out of arrays. If the
model really has to be written that way, silence it with
`warnings.filterwarnings("ignore", category=sp.PerformanceWarning)`.

## Supported operations

- **Operators:** `+ - * @ **`, `/` by a constant, `.T`, and indexing with ints, slices and integer lists: `x[1:3]` on a
Expand Down
4 changes: 3 additions & 1 deletion sparsediffpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@
normal_cdf, power, prod, quad_form, quad_over_lin, rel_entr, reshape, sin,
sinh, sum, tan, tanh, trace, vstack, xexp,
)
from sparsediffpy._compile import CompiledExpression, Problem, compile # noqa: F401
from sparsediffpy._compile import ( # noqa: F401
CompiledExpression, PerformanceWarning, Problem, compile,
)
53 changes: 49 additions & 4 deletions sparsediffpy/_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,75 @@
of w' f.
"""

import os
import sys
import warnings

import numpy as np
import scipy.sparse as sps

from sparsediffpy import _sparsediffengine as _C
from sparsediffpy._expression import (
Constant, Parameter, Variable, _check_size, _flatten_shaped, _flatten_vector,
cast_to_const,
_Index, cast_to_const,
)


class PerformanceWarning(UserWarning):
"""The problem is written in a way that is likely slow to compile/evaluate."""


# Warn when more than this many single entries are indexed out of arrays.
_ENTRYWISE_WARN_THRESHOLD = 500
_PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__)) + os.sep


def _collect_leaves(exprs):
"""The Variables and the Parameters in exprs, each in creation order."""
"""Return (variables, parameters, n_entry_picks) for the expressions in 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.
"""
leaves, seen, stack = [], set(), list(exprs)
n_entry_picks = 0
while stack:
e = stack.pop()
if id(e) in seen:
continue
seen.add(id(e))
if isinstance(e, (Variable, Parameter)):
leaves.append(e)
elif (isinstance(e, _Index) and e.shape == (1, 1)
and e.args[0].shape != (1, 1)):
n_entry_picks += 1
stack.extend(e.args)
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")
return variables, [e for e in leaves if isinstance(e, Parameter)]
return variables, [e for e in leaves if isinstance(e, Parameter)], n_entry_picks


def _warn_if_entrywise(n_entry_picks):
"""Warn, at the user's call site, if the problem looks written entry by entry."""
if n_entry_picks <= _ENTRYWISE_WARN_THRESHOLD:
return
# Attribute the warning to the first frame outside this package, whether
# the user called Problem, compile or CompiledExpression.
stacklevel, frame = 1, sys._getframe()
while frame is not None and os.path.abspath(
frame.f_code.co_filename).startswith(_PACKAGE_DIR):
stacklevel, frame = stacklevel + 1, frame.f_back
warnings.warn(
f"This problem indexes {n_entry_picks} individual entries out of arrays "
"(x[i] or X[i, j]), which suggests it was written entry by entry in a "
"Python loop. Each entry becomes separate nodes in the expression "
"graph, which slows down compilation and derivative evaluation. Prefer "
"array operations, e.g. sp.sum(x ** 2) instead of adding x[i] ** 2 in "
"a loop. To silence this warning: warnings.filterwarnings(\"ignore\", "
"category=sp.PerformanceWarning).",
PerformanceWarning, stacklevel=stacklevel)


def _stack(leaves):
Expand Down Expand Up @@ -150,7 +193,9 @@ 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._variables, self._params = _collect_leaves([objective, *constraints])
self._variables, self._params, n_entry_picks = _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)
self._offsets = [var_offsets[id(v)] for v in self._variables]
Expand Down
6 changes: 5 additions & 1 deletion sparsediffpy/_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ def __init__(self, make, args, shape):
_check_size(self.shape)


class _Index(Node):
"""An indexing node, tagged so compile can count entry-by-entry indexing."""


class Constant(Expression):
"""Fixed dense or scipy.sparse data.

Expand Down Expand Up @@ -366,7 +370,7 @@ def index_flat(x, flat_indices, shape):
if idx.size and (idx.min() < 0 or idx.max() >= x.size):
raise IndexError(f"flat index out of range for size {x.size}")
idx = idx.astype(np.int32) # safe now that all are in range; also copies
return Node(lambda c: _C.make_index(c, shape[0], shape[1], idx), [x], shape)
return _Index(lambda c: _C.make_index(c, shape[0], shape[1], idx), [x], shape)


def _axis_indices(key, n):
Expand Down
52 changes: 52 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Variables and values, shape rules, validation errors, parameters, and Problem."""

import sys
import warnings

import numpy as np
import pytest
Expand Down Expand Up @@ -579,6 +580,57 @@ def test_hessian_without_prior_jacobian():
atol=1e-12)


def _entrywise_sum(x, n):
"""sum_i x[i]^2 written the slow way, one entry at a time."""
e = x[0] ** 2
for i in range(1, n):
e = e + x[i] ** 2
return e


def test_entrywise_warning():
x = sp.Variable(2000, 1)
e = _entrywise_sum(x, 2000)
with pytest.warns(sp.PerformanceWarning, match="2000 individual entries") as rec:
sp.Problem(e, [e, 2 * e]) # shared nodes are counted once
assert len(rec) == 1


def test_entrywise_warning_not_raised():
x, y = sp.Variable(2000, 1), sp.Variable(1, 1)
g = y
for _ in range(1500): # scalar recurrence: many scalar nodes, no indexing
g = sp.sin(g) + 0.5 * y
with warnings.catch_warnings():
warnings.simplefilter("error")
sp.compile(sp.sum(x ** 2))
sp.compile(_entrywise_sum(x, 300))
sp.compile(g)
sp.Problem(sp.sum(x ** 2), [x[0:1500] ** 2, g])


def test_entrywise_warning_points_at_caller():
x = sp.Variable(1500, 1)
e = _entrywise_sum(x, 1500)
for build in (lambda: sp.Problem(e), lambda: sp.compile(e),
lambda: sp.CompiledExpression(e)):
with pytest.warns(sp.PerformanceWarning) as rec:
build()
assert len(rec) == 1
assert rec[0].filename == __file__
assert rec[0].lineno == build.__code__.co_firstlineno


def test_entrywise_warning_can_be_silenced():
x = sp.Variable(1500, 1)
e = _entrywise_sum(x, 1500)
with warnings.catch_warnings():
warnings.simplefilter("error")
warnings.filterwarnings("ignore", category=sp.PerformanceWarning)
sp.compile(e)


@pytest.mark.filterwarnings("ignore::sparsediffpy.PerformanceWarning")
def test_compile_deep_sum():
"""A loop-built sum is a chain of adds deeper than the recursion limit."""
x, p = sp.Variable(3, 1), sp.Parameter(1, 1, value=2.0)
Expand Down
Loading