Skip to content

Writing a client

A client is a program that asks the rules questions and acts on the answers. Two kinds of client want different things from the same answer:

  • A strict client must agree with NumPy exactly. It acts on Known and Refused, which are proofs, and asks NumPy for everything else.
  • A static client, such as a type checker, cannot ask NumPy, because nothing is running. It wants a best reading and uses likely.

This page works through a sketch of each. Both are small on purpose. Neither is taken from a real project.

>>> import shaperules as sr

A strict client at run time

The setting is a lazy array layer: a library that records NumPy calls as a graph and computes them later. To record a + b without computing it, the layer needs the shape and the element type of the result. The lazy layer of hotkernels is the intended client of this kind. The sketch below is not its code.

A lazy array knows its shape and element type and holds a function that computes its values on request:

>>> import numpy as np

>>> class Lazy:
...     """An array not computed yet: its shape and element type are known, its values are not."""
...
...     def __init__(self, shape, dtype, compute):
...         self.shape, self.dtype, self.compute = tuple(shape), str(dtype), compute
...
...     def __repr__(self):
...         return f"Lazy(shape={self.shape}, dtype={self.dtype})"

To watch what gets computed, the sources in this example write their name to a log when their values are asked for:

>>> log = []

>>> def source(name, shape, dtype):
...     def compute():
...         log.append(name)
...         return np.ones(shape, dtype)
...     return Lazy(shape, dtype, compute)

The rule for a ufunc of two operands asks shaperules for the shape and for the element type, and then acts on the three answers:

>>> RAISES = {
...     "ValueError": ValueError,
...     "IndexError": IndexError,
...     "TypeError": TypeError,
...     "AxisError": np.exceptions.AxisError,
... }

>>> def lazy_ufunc(name, a, b):
...     """Record the ufunc `name` applied to two lazy arrays."""
...     dtype = sr.ufunc_dtype(name, a.dtype, b.dtype)
...     shape = sr.broadcast(a.shape, b.shape)
...
...     # Refused is a proof that NumPy raises. Raise now, with nothing computed.
...     for answer in (dtype, shape):
...         if isinstance(answer, sr.Refused):
...             raise RAISES[answer.refusal.raises](answer.refusal.message)
...
...     def compute():
...         return getattr(np, name)(a.compute(), b.compute())
...
...     # Known is a proof of the result. Record the call and compute nothing.
...     if isinstance(shape, sr.Known) and isinstance(dtype, sr.Known):
...         return Lazy(shape.value, dtype.value, compute)
...
...     # Unknown proves nothing. Ask NumPy: make the call and read the result.
...     value = compute()
...     return Lazy(value.shape, value.dtype, lambda: value)

The three branches are the whole policy of a strict client. likely is not read anywhere.

Known: nothing runs

Adding a float32 column to an int16 row, then comparing with a scalar:

>>> x = source("x", (1000, 1), "float32")
>>> y = source("y", (500,), "int16")

>>> total = lazy_ufunc("add", x, y)
>>> total
Lazy(shape=(1000, 500), dtype=float32)

>>> mask = lazy_ufunc("less", total, source("threshold", (), "float64"))
>>> mask
Lazy(shape=(1000, 500), dtype=bool)

>>> log
[]

Two calls are recorded, both shapes and both element types are known, and the log is empty. No array of half a million elements was built to find that out.

Refused: the error comes early

A call NumPy would refuse is refused when it is recorded, not when the graph is computed later:

>>> lazy_ufunc("add", x, source("bad", (3, 7), "float32"))
Traceback (most recent call last):
    ...
ValueError: shapes (1000, 1) (3, 7) do not broadcast: they disagree at axis -2

>>> flags = source("flags", (4,), "bool")
>>> lazy_ufunc("subtract", flags, flags)
Traceback (most recent call last):
    ...
TypeError: subtract has no loop for bool, bool

>>> log
[]

The exception class is the one NumPy raises. The message is shaperules' own. A client that wants NumPy's message can make the call in place of the raise and let NumPy raise it: the proof says that it will.

Unknown: ask NumPy

At run time every size is an integer, and with integer sizes the shape rules do not answer Unknown. The doubt comes from the element types. Dates are not among the fourteen types covered:

>>> days = source("days", (3,), "datetime64[D]")
>>> step = source("step", (3,), "timedelta64[D]")

>>> sr.ufunc_dtype("add", days.dtype, step.dtype)
Unknown(reason="element type 'datetime64[D]' is not covered", likely=None)

The strict client does not guess. It computes the call and reads the answer off the result, so the two sources appear in the log:

>>> lazy_ufunc("add", days, step)
Lazy(shape=(3,), dtype=datetime64[D])
>>> log
['days', 'step']

The client is slower here than it could be, and it is never wrong. Each rule added to shaperules moves calls from this branch to the first one without the client changing.

A run-time client can meet Unknown for a shape too, once it holds sizes that are not integers yet. The number of elements a boolean mask selects is fixed but not known until the mask is computed. fresh gives such a length a name of its own, so that the rules can still prove that two arrays selected by one mask have the same length.

A static client

The setting is a checker that reads source code and reports shape errors without running it. Sizes are names from the signature of a function. numty is the real client of this kind. The sketch below is not its code and does not describe its policy.

A static client cannot ask NumPy. If it kept only proofs, it would lose track of a shape at the first slice, since a[1:] is n-1 long only when n is not 0. So it reads likely:

>>> def read(answer):
...     """A shape to carry on with, and a diagnostic to report. Either can be None."""
...     match answer:
...         case sr.Known(shape):
...             return shape, None
...         case sr.Refused(refusal):
...             return None, refusal.message
...         case sr.Unknown(likely=sr.Known(shape)):
...             return shape, None
...         case sr.Unknown(likely=sr.Refused(refusal)):
...             return None, refusal.message
...         case sr.Unknown():
...             return None, None

There are five cases:

Answer The static client
Known Carries on with the shape.
Refused Reports the refusal. The code is wrong for every size.
Unknown, likely Known Carries on with the likely shape and reports nothing.
Unknown, likely Refused Reports the refusal. The code works only for a few special sizes.
Unknown, no likely reading Reports nothing and loses the shape.

The fourth row is a choice. A stricter checker could stay silent there, and a checker that reports it will be wrong about code that is only ever called with those special sizes.

Checking a function

Take this function, where x has shape (batch, time) and w has shape (time, 10):

def features(x, w):
    scores = x @ w
    steps = x[:, 1:] - x[:, :-1]
    drift = x[:, 1:] - x

The checker starts with the two shapes from the signature:

>>> x = sr.shape("batch", "time")
>>> w = sr.shape("time", 10)

The first line is a matrix product. The answer is a proof:

>>> scores, problem = read(sr.matmul(x, w))
>>> sr.fmt_shape(scores), problem
('(batch, 10)', None)

The second line slices twice. Neither slice is a proof, because time may be 0. Both have a likely shape, and the checker carries on with it:

>>> sr.index(x, (slice(None), slice(1, None))).reason
'the slice selects time-1 elements only when the axis, of size time, is long enough'

>>> tail, _ = read(sr.index(x, (slice(None), slice(1, None))))
>>> head, _ = read(sr.index(x, (slice(None), slice(None, -1))))
>>> sr.fmt_shape(tail), sr.fmt_shape(head)
('(batch, time-1)', '(batch, time-1)')

>>> steps, problem = read(sr.broadcast(tail, head))
>>> sr.fmt_shape(steps), problem
('(batch, time-1)', None)

The subtraction of two (batch, time-1) arrays is a proof again: time-1 equals time-1.

The third line is an off-by-one. time-1 is never equal to time:

>>> drift, problem = read(sr.broadcast(tail, x))
>>> drift is None
True
>>> print(problem)
shapes (batch, time-1) (batch, time) do not broadcast: they disagree at axis -1

The answer behind that diagnostic is an Unknown with a likely refusal. The subtraction does broadcast when time is 1 or 2, so it is not refused for every size. For a checker that is close enough to report.

When there is no reading

If the signature had given w the shape (features, 10), the matrix product would depend on whether time equals features, and no reading is better than another:

>>> read(sr.matmul(x, sr.shape("features", 10)))
(None, None)

The sketch drops the shape. A real checker has more options. It can go axis by axis with match_pair and broadcast_pair and keep the axes that are proven, or record that the two names must be equal and check later uses against that.

When the sizes arrive

A client that learns the sizes later can turn a symbolic shape into a concrete one with substitute_shape, without asking the rule again:

>>> sr.substitute_shape(scores, {"batch": 64})
(64, 10)
>>> sr.substitute_shape(steps, {"batch": 64, "time": 100})
(64, 99)

Choosing

Strict client Static client
Acts on Known Yes Yes
Acts on Refused Yes Yes, as an error
On Unknown Asks NumPy Reads likely
Can be wrong No, as far as the rules agree with NumPy Yes, where likely does not hold
Convenient method unwrap() best()

unwrap raises on anything that is not a proof, and best returns the value or the likely value. Both are described in The three answers. How the proofs are checked against NumPy is in Checked against NumPy.