LAWS.bend source
LAWS.bend on the hub · documented module
# The laws of bend-ndarray. Broadcasting is characterised for every pair of shapes (sound, complete, least: together# they pin the result to the least shape both fit, so it is also symmetric);# the other shape rules and the arrays' values are pinned at literal inputs (float32 results are tested against# NumPy by test/compare.py, float64 ones by test/f64_check.py; the float64 laws below use bend-float64's arithmetic,# which the checker runs).# Gate: ./bend-check PROOF.bend --verdictimport Baseimport ./shape.bend as Simport ./ndarray.bend as NPimport ./rng.bend as Rimport ./npy.bend as NPYimport ./tree.bend as Timport ./cells64.bend as C64import bend-float64@0.1.8.0/float64.bend as F# ---- reference definitions ----def shape_of(r: Result<&2, &2, S.NdErr, List<&2, Nat>>) -> Maybe<&2, List<&2, Nat>>: match r: case Done{s}: Some{s} case Fail{e}: None{}def is_fail(r: Result<&1, &1, S.NdErr, NP.ND>) -> Bool: match r: case Done{a}: False{} case Fail{e}: True{}def is_done(r: Result<&2, &2, S.NdErr, List<&2, Nat>>) -> Bool: match r: case Done{s}: True{} case Fail{e}: False{}# ---- broadcasting ----# Guarantees: when a and b broadcast to s, each of them fits s: aligned at the last dimension, every one of its# dimensions is 1 or equal to s's, and it has no more dimensions than s.# Why it matters: the data of each operand is then stretched only where it has a 1, so no element is invented or# misplaced; a rule that stretched a 3 to a 6 would silently repeat data.law broadcast_sound: for +a: List<&2, Nat> for +b: List<&2, Nat> for +s: List<&2, Nat> for h: {S.broadcast(a, b) == Done{s} : Result<&2, &2, S.NdErr, List<&2, Nat>>} {Bool.and(S.fits(a, s), S.fits(b, s)) == True{} : Bool}# Guarantees: whenever a and b both fit some shape s, broadcasting them succeeds.# Why it matters: NumPy accepts every such pair (a (5, 1) and a (3,) both fit (5, 3)); refusing one would break code# ported from NumPy with a broadcasting error it never gets there.law broadcast_complete: for +a: List<&2, Nat> for +b: List<&2, Nat> for +s: List<&2, Nat> for +ha: {S.fits(a, s) == True{} : Bool} for +hb: {S.fits(b, s) == True{} : Bool} {is_done(S.broadcast(a, b)) == True{} : Bool}# Guarantees: the shape a and b broadcast to fits every shape they both fit: it is the smallest common shape.# Why it matters: with sound and complete, this pins the result exactly to NumPy's: a rule that answered a larger# shape both fit (stretching a 1 that NumPy keeps) would pass the other two laws and give wrongly sized arrays.law broadcast_least: for +a: List<&2, Nat> for +b: List<&2, Nat> for +s: List<&2, Nat> for +t: List<&2, Nat> for h: {S.broadcast(a, b) == Done{t} : Result<&2, &2, S.NdErr, List<&2, Nat>>} for +ha: {S.fits(a, s) == True{} : Bool} for +hb: {S.fits(b, s) == True{} : Bool} {S.fits(t, s) == True{} : Bool}# Guarantees: (2, 3) with (3,) gives (2, 3); (5, 1, 4) with (3, 1) gives (5, 3, 4); a 0 dimension against a 1 gives 0;# (2, 3) with (2,) is refused, naming both shapes.# Why it matters: these are NumPy's own documented examples and edge cases, at the public entry point.law broadcast_examples: {[S.broadcast([2n, 3n], [3n]), S.broadcast([5n, 1n, 4n], [3n, 1n]), S.broadcast([0n, 4n], [1n, 4n]), S.broadcast([2n, 3n], [2n])] == [Done{[2n, 3n]}, Done{[5n, 3n, 4n]}, Done{[0n, 4n]}, Fail{S.NoBroadcast{[2n, 3n], [2n]}}] : List<&2, Result<&2, &2, S.NdErr, List<&2, Nat>>>}# ---- the other shape rules ----# Guarantees: reshape keeps the number of elements: (2, 3, 4) to (6, 4) and to (24,) succeed; to (5, 5) (more) and# to (2, 3) (fewer) are refused naming both shapes; a 0-element shape reshapes to another 0-element shape.# Why it matters: a reshape that changed the element count would drop or invent data.law reshape_rules: {[S.reshape([2n, 3n, 4n], [6n, 4n]), S.reshape([2n, 3n, 4n], [24n]), S.reshape([2n, 3n, 4n], [5n, 5n]), S.reshape([2n, 3n, 4n], [2n, 3n]), S.reshape([0n, 3n], [3n, 0n])] == [Done{[6n, 4n]}, Done{[24n]}, Fail{S.BadReshape{[2n, 3n, 4n], [5n, 5n]}}, Fail{S.BadReshape{[2n, 3n, 4n], [2n, 3n]}}, Done{[3n, 0n]}] : List<&2, Result<&2, &2, S.NdErr, List<&2, Nat>>>}# Guarantees: transposing (2, 3, 4) by (2, 0, 1) gives (4, 2, 3), and by its inverse (1, 2, 0) back to (2, 3, 4); a# perm that repeats an axis, misses one or has the wrong length is refused.# Why it matters: result axis k is input axis perm[k] (NumPy's meaning); the reverse reading silently scrambles axes.law transpose_rules: {[S.transpose([2n, 3n, 4n], [2n, 0n, 1n]), S.transpose([4n, 2n, 3n], [1n, 2n, 0n]), S.transpose([2n, 3n], [0n, 0n]), S.transpose([2n, 3n], [0n, 2n]), S.transpose([2n, 3n], [0n])] == [Done{[4n, 2n, 3n]}, Done{[2n, 3n, 4n]}, Fail{S.BadPerm{[0n, 0n], 2n}}, Fail{S.BadPerm{[0n, 2n], 2n}}, Fail{S.BadPerm{[0n], 2n}}] : List<&2, Result<&2, &2, S.NdErr, List<&2, Nat>>>}# Guarantees: reducing (2, 3, 4) along axis 1 gives (2, 4), or (2, 1, 4) keeping the axis; axis 3 is refused.# Why it matters: the reduced axis is the one named, counted from 0 (NumPy's axis=1).law reduce_rules: {[shape_of(Done{S.reduce_keep(False{}, [2n, 3n, 4n], 1n)}), shape_of(Done{S.reduce_keep(True{}, [2n, 3n, 4n], 1n)})] == [Some{[2n, 4n]}, Some{[2n, 1n, 4n]}] : List<&2, Maybe<&2, List<&2, Nat>>>}law axis_rules: {[S.axis_of(2n, 3n), S.axis_of(3n, 3n)] == [Done{2n}, Fail{S.BadAxis{3n, 3n}}] : List<&2, Result<&2, &2, S.NdErr, Nat>>}# Guarantees: slice lengths follow Python's a[start:stop:step] for positive steps: 10 elements [2:8:3] is 2 (2, 5),# [0:10:1] is 10, [8:2:1] is 0, [3:100:4] is 2 (3, 7), [12:15:1] is 0.# Why it matters: an off-by-one here drops or adds a row with no error.law slice_rules: {[S.slice_len(10n, 2n, 8n, 3n), S.slice_len(10n, 0n, 10n, 1n), S.slice_len(10n, 8n, 2n, 1n), S.slice_len(10n, 3n, 100n, 4n), S.slice_len(10n, 12n, 15n, 1n)] == [2n, 10n, 0n, 2n, 0n] : List<&2, Nat>}# Guarantees: (2, 3) and (2, 5) join along axis 1 into (2, 8); (2, 3) and (4, 3) along axis 0 into (6, 3); (2, 3) and# (3, 3) along axis 1 are refused, and so is an axis past the last.# Why it matters: every axis but the joined one must agree, or rows would be glued to rows of another length.law concat_rules: {[S.concat(1n, [2n, 3n], [2n, 5n]), S.concat(0n, [2n, 3n], [4n, 3n]), S.concat(1n, [2n, 3n], [3n, 3n]), S.concat(2n, [2n, 3n], [2n, 3n])] == [Done{[2n, 8n]}, Done{[6n, 3n]}, Fail{S.BadConcat{1n, [2n, 3n], [3n, 3n]}}, Fail{S.BadConcat{2n, [2n, 3n], [2n, 3n]}}] : List<&2, Result<&2, &2, S.NdErr, List<&2, Nat>>>}# ---- math ----# Guarantees: exp of int32 and sqrt of uint8 are refused, arctan2 of mixed dtypes and of int32, and hypot of int32, are refused;# exp of float32 and square of int32 are not; exp, divide and hypot of float64 are not, and arctan2 of float64 with# float32 is.# Why it matters: decision 2 (one dtype, explicit astype): a float function applied to integer cells would read the# integers' bits as floats and give garbage with no error.law math_dtypes: {[is_fail(NP.exp(NP.arange(NP.i32(), 3n))), is_fail(NP.sqrt(NP.arange(NP.u8(), 3n))), is_fail(NP.exp(NP.arange(NP.f32(), 3n))), is_fail(NP.square(NP.arange(NP.i32(), 3n))), is_fail(NP.arctan2(NP.arange(NP.f32(), 3n), NP.arange(NP.i32(), 3n))), is_fail(NP.arctan2(NP.arange(NP.i32(), 3n), NP.arange(NP.i32(), 3n))), is_fail(NP.hypot(NP.arange(NP.i32(), 3n), NP.arange(NP.i32(), 3n))), is_fail(NP.exp(NP.arange(NP.f64(), 3n))), is_fail(NP.divide(NP.arange(NP.f64(), 3n), NP.arange(NP.f64(), 3n))), is_fail(NP.hypot(NP.arange(NP.f64(), 3n), NP.arange(NP.f64(), 3n))), is_fail(NP.arctan2(NP.arange(NP.f64(), 3n), NP.arange(NP.f32(), 3n)))] == [True{}, True{}, False{}, False{}, True{}, True{}, True{}, False{}, False{}, False{}, True{}] : List<&2, Bool>}# ---- random numbers ----def b2n(b: Bool) -> Nat: match b: case True{}: 1n case False{}: 0n# how many entries of xs carry index vdef count_i(+v: Nat, xs: List<&2, R.KI>) -> Nat: match xs: case []: 0n case R.KI{k, i} <> t: Nat.add(b2n(Nat.is_eq(v, i)), count_i(v, t))def iota(c: Nat, +s: Nat) -> List<&2, Nat>: match c: case 0n: [] case 1n+d: s <> iota(d, Nat.add(s, 1n))# Guarantees: Philox4x32-10 gives Random123's published answer for counter 0 and key 0.# Why it matters: the generator is the published one, so its tested statistical quality carries over; a wrong round# constant or a wrong 64-bit product would still look random while being a different, untested generator.law philox_known: {R.philox(R.Q4{0, 0, 0, 0}, 0, 0) == R.Q4{1713891541, 3781805453, 3159862348, 2600524760} : R.Q4}# Guarantees: for every list of (key, index) pairs and every fuel, sorting keeps each index exactly as many times as# the list had it.# Why it matters: permutation is this sort applied to random keys; a sort that dropped or repeated an entry would hand# out a shuffled dataset with rows lost or duplicated, whatever the keys were.law sort_keeps: for +fuel: Nat for +xs: List<&2, R.KI> for +v: Nat {count_i(v, R.msort(fuel, xs)) == count_i(v, xs) : Nat}# Guarantees: the pairs permutation sorts carry the indices start, start + 1, ..., start + c - 1, in order.# Why it matters: with sort_keeps, permutation(n) holds 0 .. n - 1 once each: a permutation, for every seed.law keyed_indices: for c: Nat for +k0: U32 for +k1: U32 for +n: U32 for +s: Nat {R.idxs(R.keyed(c, k0, k1, n, s)) == iota(c, s) : List<&2, Nat>}# ---- .npy files ----type Sig is Data: Sig{dt: String, shape: List<&2, Nat>, cells: List<&2, U32>}def sig(a: NP.ND) -> Sig: match a: case NP.ND{+dt, +s, d}: Sig{NP.dt_name(dt), s, NP.to_list(NP.ND{dt, s, d})}# what a load gives: the array's dtype, shape and cells, or the error in wordsdef loaded(r: Result<&1, &1, S.NdErr, NP.ND>) -> Result<&2, &2, String, Sig>: match r: case Done{a}: Done{sig(a)} case Fail{e}: Fail{NP.why(e)}def lit(+dt: S.DType, +s: List<&2, Nat>, +xs: List<&2, U32>) -> NP.ND: NP.ND{dt, s, T.from_rows(NP.ps(dt, s), xs)}# Guarantees: astype from float64 to float32 rounds as NumPy's: 1.0 and 0.1 (rounded to nearest), 1 + 2^-24 (a tie,# to even: 1.0), 1 + 3 * 2^-24 (a tie, to even: up), 2^-149 (the smallest subnormal), 2^-150 (a tie with 0: 0), 1e39# and the first double that rounds past the largest float (infinity), -0.0, and NaN (a quiet NaN).# Why it matters: float64 data narrowed to float32 (for speed, or for a float32-only consumer) must change only by the# one rounding NumPy makes; a wrong rounding changes data silently.law f64_rounding: {[C64.to_cell(S.DF32{}, F.F64{1072693248, 0}), C64.to_cell(S.DF32{}, F.F64{1069128089, 2576980378}), C64.to_cell(S.DF32{}, F.F64{1072693248, 268435456}), C64.to_cell(S.DF32{}, F.F64{1072693248, 805306368}), C64.to_cell(S.DF32{}, F.F64{916455424, 0}), C64.to_cell(S.DF32{}, F.F64{915406848, 0}), C64.to_cell(S.DF32{}, F.F64{1208451719, 4103883293}), C64.to_cell(S.DF32{}, F.F64{1206910975, 4026531840}), C64.to_cell(S.DF32{}, F.F64{2147483648, 0}), C64.to_cell(S.DF32{}, F.F64{2146959360, 0})] == [1065353216, 1036831949, 1065353216, 1065353218, 1, 0, 2139095040, 2139095040, 2147483648, 2143289344] : List<&2, U32>}# Guarantees: float16 to float32 exactly: 1.0, the smallest subnormal 2^-24, the largest half 65504, infinity, -infinity.# Why it matters: float16 files (common for model weights) load with every value unchanged.law f16_exact: {[NPY.f16_to_f32(15360), NPY.f16_to_f32(1), NPY.f16_to_f32(31743), NPY.f16_to_f32(31744), NPY.f16_to_f32(64512)] == [1065353216, 864026624, 1199562752, 2139095040, 4286578688] : List<&2, U32>}# Guarantees: saving then loading gives the same dtype, shape and elements: an int32 (2, 3), a bool (3,), a uint8 0-d# array, an empty float32 (2, 0), an int32 (4,) with negatives, and a float64 (2,) (1.0 and -0.1, each two cells).# Why it matters: the format must round-trip what bend-ndarray writes, or a save and load would change an array.law npy_round_trip: {[loaded(NPY.from_npy(NPY.to_npy(lit(NP.i32(), [2n, 3n], [0, 1, 2, 3, 4, 5])))), loaded(NPY.from_npy(NPY.to_npy(lit(NP.bool(), [3n], [1, 0, 1])))), loaded(NPY.from_npy(NPY.to_npy(lit(NP.u8(), [], [200])))), loaded(NPY.from_npy(NPY.to_npy(lit(NP.f32(), [2n, 0n], [])))), loaded(NPY.from_npy(NPY.to_npy(lit(NP.i32(), [4n], [4294967295, 7, 2147483648, 0])))), loaded(NPY.from_npy(NPY.to_npy(lit(NP.f64(), [2n], [1072693248, 0, 3216611737, 2576980378]))))] == [Done{Sig{"int32", [2n, 3n], [0, 1, 2, 3, 4, 5]}}, Done{Sig{"bool", [3n], [1, 0, 1]}}, Done{Sig{"uint8", [], [200]}}, Done{Sig{"float32", [2n, 0n], []}}, Done{Sig{"int32", [4n], [4294967295, 7, 2147483648, 0]}}, Done{Sig{"float64", [2n], [1072693248, 0, 3216611737, 2576980378]}}] : List<&2, Result<&2, &2, String, Sig>>}def hdr16(+h: String, +data: List<&2, U32>) -> List<&2, U32>: List.append(&2, U32, [147, 78, 85, 77, 80, 89, 1, 0, U32.from_nat(List.length(&2, U32, NPY.ascii(h))), 0], List.append(&2, U32, NPY.ascii(h), data))# Guarantees: files as other writers make them load as np.load reads them: a Fortran-order (2, 3) int32 (transposed# into row-major), a big-endian int32, an int16 with a negative value, a Python 2 header ('L' suffixes, double# quotes, other key order), an int64 that fits, and a big-endian float64 (loaded as float64, bit for bit); an int64# past int32, complex64, a short file and a non-.npy file are refused.# Why it matters: decisions 1 and 2: Fortran order and byte order are layouts np.save writes, and reading them as C# order or little-endian would scramble or corrupt every value with no error.law npy_layouts: {[loaded(NPY.from_npy(hdr16("{'descr': '<i4', 'fortran_order': True, 'shape': (2, 3), }\n", [0,0,0,0, 3,0,0,0, 1,0,0,0, 4,0,0,0, 2,0,0,0, 5,0,0,0]))), loaded(NPY.from_npy(hdr16("{'descr': '>i4', 'fortran_order': False, 'shape': (2,), }\n", [0,0,1,2, 255,255,255,254]))), loaded(NPY.from_npy(hdr16("{'descr': '<i2', 'fortran_order': False, 'shape': (2,), }\n", [255,255, 3,0]))), loaded(NPY.from_npy(hdr16("{\"shape\": (2L,), \"fortran_order\": False, \"descr\": \"<i4\"}\n", [1,0,0,0, 2,0,0,0]))), loaded(NPY.from_npy(hdr16("{'descr': '<i8', 'fortran_order': False, 'shape': (1,), }\n", [255,255,255,255, 255,255,255,255]))), loaded(NPY.from_npy(hdr16("{'descr': '>f8', 'fortran_order': False, 'shape': (2,), }\n", [63,240,0,0,0,0,0,0, 191,185,153,153,153,153,153,154]))), loaded(NPY.from_npy(hdr16("{'descr': '<i8', 'fortran_order': False, 'shape': (1,), }\n", [0,0,0,128, 0,0,0,0]))), loaded(NPY.from_npy(hdr16("{'descr': '<c8', 'fortran_order': False, 'shape': (1,), }\n", [0,0,0,0, 0,0,0,0]))), loaded(NPY.from_npy(hdr16("{'descr': '<i4', 'fortran_order': False, 'shape': (3,), }\n", [1,0,0,0]))), loaded(NPY.from_npy([80, 75, 3, 4]))] == [Done{Sig{"int32", [2n, 3n], [0, 1, 2, 3, 4, 5]}}, Done{Sig{"int32", [2n], [258, 4294967294]}}, Done{Sig{"int32", [2n], [4294967295, 3]}}, Done{Sig{"int32", [2n], [1, 2]}}, Done{Sig{"int32", [1n], [4294967295]}}, Done{Sig{"float64", [2n], [1072693248, 0, 3216611737, 2576980378]}}, Fail{"element 0 (<i8) does not fit a 32-bit integer"}, Fail{"a .npy dtype bend-ndarray cannot hold: <c8"}, Fail{".npy: the file ends before its data does"}, Fail{".npy: not a .npy file (no \\x93NUMPY at the start)"}] : List<&2, Result<&2, &2, String, Sig>>}