Design¶
This page explains the choices behind the library: why a rule has three answers, what a proof means here, how sizes are stored, and why some answers come from tables.
Why three answers¶
A shape rule over integers has two outcomes. The call works and has a shape, or NumPy raises. With names in the shapes there is a third case, and it is common: the outcome depends on the values of the names.
(n,) and (m,) broadcast when n equals m, or when either is 1, and not
otherwise. A rule that has to pick one of two outcomes for this has only bad
options. If it says "works", a caller that trusts it is wrong whenever n
and m differ. If it says "raises", it rejects every correct program that
adds two arrays of related lengths. If it raises an exception of its own, the
caller cannot tell "NumPy would refuse this" from "I do not know".
The clients of the rules also want different things from that third case:
- A client at run time, such as a lazy array layer, must agree with NumPy exactly. A wrong shape there is a wrong result or a crash far from its cause. It can always ask NumPy, so for it "I do not know" is a fine answer.
- A type checker cannot ask NumPy. If it stops at every doubt it stops almost at once, since a slice of an axis of unknown length is already a doubt. It needs a best reading, and it can live with being wrong sometimes.
So the answer has three parts that do not mix:
| Answer | Standing |
|---|---|
Known |
A proof of the result. |
Refused |
A proof that NumPy raises. |
Unknown |
No proof. A reason, and a likely reading kept apart from the proofs. |
The strict client reads the first two and ignores likely. The static client
reads all of it. Neither has to trust anything it does not want to, and the
rules are written once for both. Writing a client shows
the two side by side.
What a proof means¶
Known and Refused are statements about every assignment of the names. An
assignment gives each name a non-negative integer. Nothing else is assumed
about a name:
- A name can be 0. NumPy allows an empty axis.
- A name can be 1, and a 1 stretches in a broadcast.
- Two different names can have the same value.
These three are where a rule that looks right is wrong. Each one turns a
plausible Known into an Unknown:
>>> sr.index(("n",), 0).reason
'index 0 needs n to be at least 1'
>>> sr.broadcast(("n",), (3,)).reason
'sizes at axis -1 must be equal or 1: n and 3'
>>> sr.stack([("n",), ("m",)]).reason
'sizes at axis 0 must be equal: n and m'
The policy is that a rule may always answer Unknown and may never answer
Known or Refused for something that fails for one assignment. A rule that
is unsure is allowed. A rule that is wrong is a bug.
The same policy holds for sizes. Two sizes are provably unequal only when no
assignment makes them equal. 2*n and n look different and are equal at
n = 0, so they are not provably unequal:
>>> from shaperules import dims
>>> dims.unequal(sr.dim("2*n"), sr.dim("n"))
False
>>> dims.unequal(sr.dim("2*n"), sr.dim("2*n + 1"))
True
A proof can still be strong. The rules use the lower bound of a formula and its divisibility where those settle the question:
>>> sr.index(("n + 1",), 0)
Known(value=())
>>> sr.broadcast(("2*n",), (3,)).refusal.kind
'broadcast'
>>> sr.reshape(("2*n + 1",), (2, -1)).refusal.kind
'reshape-size'
The exception is part of the proof¶
A Refused answer names the exception NumPy raises, and the tests compare
the class. This matters to a strict client that raises on NumPy's behalf:
code that catches IndexError must still catch it.
Where NumPy raises different exceptions for different assignments, the rule
names a class that is right for all of them. stack has such a case, which
the refusals reference describes.
The message is not part of the proof. It is written by shaperules, in terms of the shapes the rule was given, names included. NumPy's message is about integers and could not be reproduced for a symbolic shape.
The likely reading¶
Unknown.likely is what holds once the doubt is set aside: the call is
assumed to be valid, and no name is assumed to be 0 or 1 or equal to another
name. It is a Known, a Refused, or None where there is no single best
reading.
It is kept inside Unknown so that it cannot be mistaken for a proof. A
caller has to go through Unknown to reach it, or call best().
Sizes and their forms¶
A size that is not an integer is stored as one of three canonical forms.
| Form | Is | Example |
|---|---|---|
LinForm |
A sum of names with integer coefficients plus a constant. | 2*n + m - 1 |
DivForm |
A linear form divided by a positive integer and rounded down, plus a constant. | (n + 1) // 2 + 3 |
MonoForm |
One product of two or more names with an integer coefficient. | 2*h*w |
These cover what the shape rules produce. Concatenation adds sizes, so sums are needed. A slice with a step divides and rounds. Reshape multiplies whole axes together.
One spelling¶
The arithmetic keeps each form in one spelling. Names are sorted, zero
coefficients are dropped, a formula with no names left becomes an int, and
a division that comes out even is carried out.
>>> sr.dim("m + n + 1") == sr.dim("1 + n + m")
True
>>> sr.fmt(sr.dim("(4*n + 2) // 2"))
'2*n+1'
>>> sr.dim("n*2 - n - n")
0
The point of one spelling is that equality becomes cheap and safe. Two sizes
that compare equal with == are the same size for every assignment. A rule
can then prove n + 1 == 1 + n with a tuple comparison, with no solver.
A division is brought to one spelling as far as the arithmetic can take it: a factor shared by the dividend and the divisor cancels, and a whole multiple of the divisor in the constant leaves the division.
>>> sr.dim("(n + 2) // 2") == sr.dim("n // 2 + 1")
True
>>> sr.dim("(2*n) // 4") == sr.dim("n // 2")
True
The reverse of the rule does not hold in general. Two sizes that are equal for every assignment do not always compare equal, because one of them may have no form at all:
>>> sr.dim("(2*n + m) // 2")
DivForm(inner=LinForm(coeffs=(('m', 1), ('n', 2)), const=0), div=2, plus=0)
>>> sr.dim("n + m // 2")
ANY
This costs precision and not correctness. The rules treat sizes that do not
compare equal as "not proven equal", and the answer is Unknown where it
could have been Known.
No approximation¶
The three forms do not cover every formula. A sum of products has no form.
When arithmetic leaves the forms, the result is ANY, the size nothing is
known about.
The alternative would be to keep an approximate or partial formula. Then a
size could look known and be wrong, and every proof built on it would be
wrong with it. ANY claims nothing. Nothing is proven from it, not even that
it equals itself.
The cost is real. Flattening a shape that has n + 1 in it loses the count:
Sums of products are on the roadmap.
Two layers¶
shaperules.forms is the low layer. It defines the three forms and the
arithmetic that keeps them canonical. It has no unknown size, does no
coercion, and answers None where there is no form.
shaperules.dims is built on it. It adds ANY, reads sizes from integers and
strings, and turns None into ANY. The rules use dims only.
How a shape answer is put together¶
Most rules decide axis by axis. Two helpers do the per-axis work:
- the size several sizes must all equal, used for the inner sizes of a matrix product and the fixed axes of a concatenation;
- the size several sizes broadcast to, where a 1 stretches.
match_pair and broadcast_pair are those two helpers for two sizes. Each
gives one of the three answers for one axis. A rule then joins the per-axis
answers into the answer for the shape:
- One refusal refuses the whole call.
- Otherwise one doubt makes the whole answer
Unknown. Its reason lists the doubts, and its likely reading joins the likely readings of the axes when every doubtful axis has one. - Otherwise every axis is proven and the answer is
Known.
>>> answer = sr.broadcast(("n", "k", 3), (4, "m", 3))
>>> print(answer.reason)
sizes at axis -3 must be equal or 1: n and 4; sizes at axis -2 must be equal or 1: k and m
>>> answer.likely is None
True
Axis -3 has a likely size, 4. Axis -2 has none, since k and m are two
names. So the shape as a whole has no likely reading.
Promotion by rule¶
result_type is computed. NumPy's promotion of the fourteen element types
follows from each type's kind and width, and the rule fits in a page of code.
Python numbers add one more step: under NEP 50 a Python int, float or
complex takes the type of the array it meets, within its kind.
The rule is small enough to check completely, and the tests do. The one surprise it held, that promoting several types is not a fold over pairs, is told in Checked against NumPy.
Tables for what a ufunc returns¶
What a ufunc returns is another matter. A ufunc is implemented in NumPy as a list of loops, one per combination of element types it supports. Which loop is picked for given operands, and so what comes out, is decided per ufunc:
>>> sr.ufunc_dtype("sqrt", "int8").value
'float16'
>>> sr.ufunc_dtype("sqrt", "int32").value
'float64'
>>> sr.ufunc_dtype("true_divide", "int8", "int8").value
'float64'
>>> sr.ufunc_dtype("absolute", "complex64").value
'float32'
>>> sr.ufunc_dtype("negative", "bool").refusal.kind
'no-loop'
There is no short rule behind these. A hand-written model would be a second implementation of NumPy's loop selection, written from reading the first, and it would be wrong in the corners.
So shaperules does not model it. tools/generate_tables.py asks NumPy for
the result of every ufunc on every combination of operand types and writes
the answers to src/shaperules/_tables.py. The library reads the table. The
question "what does NumPy return here" is answered by NumPy, once, ahead of
time.
The table is compact. An element type is one character, NumPy's own type
character for it. A ufunc of one input is a string of 17 cells, for the fourteen types
and the three kinds of Python number. A ufunc of two inputs is 17 rows of 17.
A cell holds ! where NumPy raises TypeError.
A table has two weaknesses, and each has an answer:
- It can go stale. A test generates it again on the NumPy under test and compares, on every NumPy version in CI.
- It holds only what was asked. A ufunc or an element type outside the table
answers
Unknown, never a guess.
The element types of reductions are tables for the same reason. np.sum of
int8 is int64, and np.mean of int8 is float64. These come from the
reduction's own code and not from a promotion rule.
No dependencies¶
The package depends on nothing, NumPy included. It can be installed next to any NumPy 2, or with no NumPy at all. A checker that reads source code does not need the library it reasons about.
NumPy objects are still accepted where they are convenient. A dtype or a scalar type is read by its name, and a NumPy integer is read as a size, both without importing NumPy.
The price is that shaperules describes NumPy from outside and can fall behind it. The tests against NumPy are the check on that.