main.bend

bend-ml-tensor-array@0.1.7.0 · 1,275 lines · 0 definitions

1# bend-ml-tensor-array: tensors over a flat Array<F32>, with the shape in the type.
2#
3#   import bend-ml-tensor-array@0.1.7.0/main.bend as TA
4#
5# Mat<r, c> stores r*c numbers in an Array<F32>, row by row (index i*c + j). The
6# dimensions are erased type parameters: the same guarantee as bend-ml-tensor
7# (a product with wrong dimensions does not compile), but ~50x faster than lists:
8# Array.get/set by index, and products in parallel blocks of rows.
9#
10# An Array is affine (a single owner): every operation that reads an operand returns it
11# together with the result (as Array.get does), in records MM, AR, ... Use Mat.clone
12# when you need two copies.
13#
14# What is NOT proved: the invariant "the Array has capacity >= r*c" holds because
15# the constructors (Mat.zeros, Mat.of_list) allocate the right size; and F32 is
16# validated by tests against PyTorch (reference/test_tensor_array.py), not by proof.
17
18import Base
19
20# ---------------------------------------------------------------------
21# helper types
22# ---------------------------------------------------------------------
23
24type R is Type:
25  R{a: Array<F32>, b: Array<F32>, x: F32}
26
27type G is Type:
28  G{a: Array<F32>, b: Array<F32>, c: Array<F32>}
29
30# A dot product with four partial sums. Each step adds its product to a0 and rotates the sums
31# (a1, a2, a3, a0), so each sum gets every fourth product and the processor can work on the next
32# addition before the last one has finished; at the end the sums are added in pairs. The order of
33# the additions is fixed, so the result is the same on every run and every thread count, but it is
34# not the order of a single running sum (NOTES.md, exp. 17).
35def dotr(k: Nat, +ia: U32, +ib: U32, +sa: U32, +sb: U32, a0: F32, a1: F32, a2: F32, a3: F32, ra: Array<F32> & F32, rb: Array<F32> & F32) -> R:
36  match k ra rb:
37    case 0n Tuple{a, x} Tuple{b, y}:
38      R{a, b, ((a0 + a1 : F32) + (a2 + a3 : F32) : F32)}
39    case 1n+p Tuple{a, +x} Tuple{b, +y}:
40      dotr(p, (ia + sa : U32), (ib + sb : U32), sa, sb, a1, a2, a3, (a0 + (x * y : F32) : F32), Array.get(F32, a, (ia + sa : U32)), Array.get(F32, b, (ib + sb : U32)))
41
42def dotg(k: Nat, +ia: U32, +ib: U32, +sa: U32, +sb: U32, acc: F32, ra: Array<F32> & F32, rb: Array<F32> & F32) -> R:
43  dotr(k, ia, ib, sa, sb, acc, 0.0, 0.0, 0.0, ra, rb)
44
45# row i of C, columns j.. ; r is the product of the current column (already computed)
46
47def gcols(mleft: Nat, +kn: Nat, +ia0: U32, +ib0: U32, +sa: U32, +sb: U32, +bcol: U32, +cidx: U32, c: Array<F32>, r: R) -> G:
48  match mleft r:
49    case 0n R{a, b, +x}:
50      G{a, b, Array.set(F32, c, cidx, x)}
51    case 1n+p R{a, b, +x}:
52      gcols(p, kn, ia0, (ib0 + bcol : U32), sa, sb, bcol, (cidx + 1 : U32), Array.set(F32, c, cidx, x), dotg(kn, ia0, (ib0 + bcol : U32), sa, sb, 0.0, Array.get(F32, a, ia0), Array.get(F32, b, (ib0 + bcol : U32))))
53
54def grows(nleft: Nat, +mm1: Nat, +kn: Nat, +i: U32, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, +mu: U32, g: G) -> G:
55  match nleft g:
56    case 0n G{a, b, c}:
57      G{a, b, c}
58    case 1n+p G{a, b, c}:
59      grows(p, mm1, kn, (i + 1 : U32), arow, sa, sb, bcol, mu, gcols(mm1, kn, (i * arow : U32), 0, sa, sb, bcol, (i * mu : U32), c, dotg(kn, (i * arow : U32), 0, sa, sb, 0.0, Array.get(F32, a, (i * arow : U32)), Array.get(F32, b, 0))))
60
61# C (n x m) = A · B with k steps; c is the output array (with capacity n*m)
62
63def gemm(+n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array<F32>, b: Array<F32>, c: Array<F32>) -> G:
64  grows(n, Nat.sub(m, 1n), k, 0, arow, sa, sb, bcol, U32.from_nat(m), G{a, b, c})
65
66
67# ---------------------------------------------------------------------
68# parallel gemm: 2^d blocks of rows of C, each with its own copy of A and B,
69# returning lists that are written into C at the end
70# ---------------------------------------------------------------------
71
72type S3 is Type:
73  S3{a: Array<F32>, b: Array<F32>, out: List<&2, F32>}
74
75def lcols(mleft: Nat, +kn: Nat, +ia0: U32, +ib0: U32, +sa: U32, +sb: U32, +bcol: U32, out: List<&2, F32>, r: R) -> S3:
76  match mleft r:
77    case 0n R{a, b, +x}:
78      S3{a, b, x <> out}
79    case 1n+p R{a, b, +x}:
80      lcols(p, kn, ia0, (ib0 + bcol : U32), sa, sb, bcol, x <> out, dotg(kn, ia0, (ib0 + bcol : U32), sa, sb, 0.0, Array.get(F32, a, ia0), Array.get(F32, b, (ib0 + bcol : U32))))
81
82def lrows(nleft: Nat, +mm1: Nat, +kn: Nat, +i: U32, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, st: S3) -> S3:
83  match nleft st:
84    case 0n S3{a, b, out}:
85      S3{a, b, out}
86    case 1n+p S3{a, b, out}:
87      lrows(p, mm1, kn, (i + 1 : U32), arow, sa, sb, bcol, lcols(mm1, kn, (i * arow : U32), 0, sa, sb, bcol, out, dotg(kn, (i * arow : U32), 0, sa, sb, 0.0, Array.get(F32, a, (i * arow : U32)), Array.get(F32, b, 0))))
88
89def lblock_fin(st: S3) -> List<&2, F32>:
90  match st:
91    case S3{a, b, out}:
92      List.reverse(&2, F32, out)
93
94def lblock(cnt: Nat, +mm1: Nat, +kn: Nat, +i: U32, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array<F32>, b: Array<F32>) -> List<&2, F32>:
95  lblock_fin(lrows(cnt, mm1, kn, i, arow, sa, sb, bcol, S3{a, b, Nil{}}))
96
97def lpar(d: Nat, +cnt: Nat, +mm1: Nat, +kn: Nat, +i: U32, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, ra: Array<F32> & Array<F32>, rb: Array<F32> & Array<F32>) -> List<&2, F32>:
98  match d ra rb:
99    case 0n Tuple{a, a2} Tuple{b, b2}:
100      lblock(cnt, mm1, kn, i, arow, sa, sb, bcol, a, b)
101    case 1n++q Tuple{a, a2} Tuple{b, b2}:
102      x y = lpar(q, Nat.div(cnt, 2n), mm1, kn, i, arow, sa, sb, bcol, Array.clone(F32, a), Array.clone(F32, b)) lpar(q, Nat.sub(cnt, Nat.div(cnt, 2n)), mm1, kn, (i + U32.from_nat(Nat.div(cnt, 2n)) : U32), arow, sa, sb, bcol, Array.clone(F32, a2), Array.clone(F32, b2))
103      List.append(&2, F32, x, y)
104
105def write_l(xs: List<&2, F32>, +idx: U32, c: Array<F32>) -> Array<F32>:
106  match xs:
107    case Nil{}:
108      c
109    case Con{h, t}:
110      write_l(t, (idx + 1 : U32), Array.set(F32, c, idx, h))
111
112# c[idx..] += list
113
114def gp3(a: Array<F32>, b: Array<F32>, c: Array<F32>, xs: List<&2, F32>) -> G:
115  G{a, b, write_l(xs, 0, c)}
116
117def gp2(d: Nat, +n: Nat, +mm1: Nat, +kn: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, c: Array<F32>, pa: Array<F32> & Array<F32>, pb: Array<F32> & Array<F32>) -> G:
118  match pa pb:
119    case Tuple{a1, a2} Tuple{b1, b2}:
120      gp3(a1, b1, c, lpar(d, n, mm1, kn, 0, arow, sa, sb, bcol, Array.clone(F32, a2), Array.clone(F32, b2)))
121
122# C (n x m) = A · B, with 2^d blocks of rows in parallel; returns A, B (intact) and C
123
124def gemm_par(d: Nat, +n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array<F32>, b: Array<F32>, c: Array<F32>) -> G:
125  gp2(d, n, Nat.sub(m, 1n), k, arow, sa, sb, bcol, c, Array.clone(F32, a), Array.clone(F32, b))
126
127
128# ---------------------------------------------------------------------
129# parallel gemm by COLUMNS, for n = 1 (matrix · vector): each block computes a
130# range of columns of C, with its own copy of the operands
131# ---------------------------------------------------------------------
132
133def cblock_fin(st: S3) -> List<&2, F32>:
134  match st:
135    case S3{a, b, out}:
136      List.reverse(&2, F32, out)
137
138# cnt columns starting at j0 (cnt >= 1); row 0 of A is at ia0
139
140def cblock_go(cnt1: Nat, +kn: Nat, +ia0: U32, +j0: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array<F32>, b: Array<F32>) -> List<&2, F32>:
141  cblock_fin(lcols(cnt1, kn, ia0, (j0 * bcol : U32), sa, sb, bcol, Nil{}, dotg(kn, ia0, (j0 * bcol : U32), sa, sb, 0.0, Array.get(F32, a, ia0), Array.get(F32, b, (j0 * bcol : U32)))))
142
143def cblock(cnt: Nat, +kn: Nat, +ia0: U32, +j0: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array<F32>, b: Array<F32>) -> List<&2, F32>:
144  match cnt:
145    case 0n:
146      Nil{}
147    case 1n+p:
148      cblock_go(p, kn, ia0, j0, sa, sb, bcol, a, b)
149
150def cpar(d: Nat, +cnt: Nat, +kn: Nat, +ia0: U32, +j0: U32, +sa: U32, +sb: U32, +bcol: U32, ra: Array<F32> & Array<F32>, rb: Array<F32> & Array<F32>) -> List<&2, F32>:
151  match d ra rb:
152    case 0n Tuple{a, a2} Tuple{b, b2}:
153      cblock(cnt, kn, ia0, j0, sa, sb, bcol, a, b)
154    case 1n++q Tuple{a, a2} Tuple{b, b2}:
155      x y = cpar(q, Nat.div(cnt, 2n), kn, ia0, j0, sa, sb, bcol, Array.clone(F32, a), Array.clone(F32, b)) cpar(q, Nat.sub(cnt, Nat.div(cnt, 2n)), kn, ia0, (j0 + U32.from_nat(Nat.div(cnt, 2n)) : U32), sa, sb, bcol, Array.clone(F32, a2), Array.clone(F32, b2))
156      List.append(&2, F32, x, y)
157
158def cp2(d: Nat, +m: Nat, +kn: Nat, +sa: U32, +sb: U32, +bcol: U32, c: Array<F32>, pa: Array<F32> & Array<F32>, pb: Array<F32> & Array<F32>) -> G:
159  match pa pb:
160    case Tuple{a1, a2} Tuple{b1, b2}:
161      gp3(a1, b1, c, cpar(d, m, kn, 0, 0, sa, sb, bcol, Array.clone(F32, a2), Array.clone(F32, b2)))
162
163# C (1 x m) = A (1 x k) · B, with 2^d blocks of columns in parallel
164
165def gemm_par_cols(d: Nat, +m: Nat, +k: Nat, +sa: U32, +sb: U32, +bcol: U32, a: Array<F32>, b: Array<F32>, c: Array<F32>) -> G:
166  cp2(d, m, k, sa, sb, bcol, c, Array.clone(F32, a), Array.clone(F32, b))
167
168# ---------------------------------------------------------------------
169# element-wise operations (in place, by index)
170# ---------------------------------------------------------------------
171
172# ---------------------------------------------------------------------
173# gemm: C[i][j] = sum_p A[i*arow + p*sa] * B[p*sb + j*bcol]
174# (nn: arow=K, sa=1, sb=M, bcol=1 | nt: B stored m x k: sb=1, bcol=K | tn: A stored k x n: arow=1, sa=N)
175# ---------------------------------------------------------------------
176
177# acc += A[ia + t*sa] * B[ib + t*sb] for k steps; ra, rb already carry the first pair
178
179type P2 is Type:
180  P2{a: Array<F32>, b: Array<F32>}
181
182type AL is Type:
183  AL{c: Array<F32>, l: List<&2, F32>}
184
185# list of m elements starting at idx (reads with Array.get, returning the array)
186
187def read_l(mleft: Nat, +idx: U32, acc: List<&2, F32>, rc: Array<F32> & F32) -> AL:
188  match mleft rc:
189    case 0n Tuple{c, +v}:
190      AL{c, List.reverse(&2, F32, v <> acc)}
191    case 1n+p Tuple{c, +v}:
192      read_l(p, (idx + 1 : U32), v <> acc, Array.get(F32, c, (idx + 1 : U32)))
193
194# writes the list starting at idx
195
196def addl(xs: List<&2, F32>, +idx: U32, rc: Array<F32> & F32) -> Array<F32>:
197  match xs rc:
198    case Nil{} Tuple{c, v}:
199      c
200    case Con{+h, t} Tuple{c, +v}:
201      addl(t, (idx + 1 : U32), Array.get(F32, Array.set(F32, c, idx, (v + h : F32)), (idx + 1 : U32)))
202
203# adds a bias (a list of m) to each of the n rows of c (n x m)
204
205def bias_rows(nleft: Nat, +i: U32, +mu: U32, +bl: List<&2, F32>, c: Array<F32>) -> Array<F32>:
206  match nleft:
207    case 0n:
208      c
209    case 1n+p:
210      bias_rows(p, (i + 1 : U32), mu, bl, addl(bl, (i * mu : U32), Array.get(F32, c, (i * mu : U32))))
211
212# in-place relu on the first n elements
213
214def relu_l(nleft: Nat, +t: U32, rc: Array<F32> & F32) -> Array<F32>:
215  match nleft rc:
216    case 0n Tuple{c, v}:
217      c
218    case 1n+p Tuple{c, +v}:
219      relu_l(p, (t + 1 : U32), Array.get(F32, Array.set(F32, c, t, F32.max(v, 0.0)), (t + 1 : U32)))
220
221def pos2(b: Bool) -> F32:
222  match b:
223    case True{}:
224      1.0
225    case False{}:
226      0.0
227
228def pos(+y: F32) -> F32:
229  pos2(F32.is_gt(y, 0.0))
230
231# d[t] *= (h[t] > 0): the relu gradient; returns both arrays
232
233def mask_l(nleft: Nat, +t: U32, rd: Array<F32> & F32, rh: Array<F32> & F32) -> P2:
234  match nleft rd rh:
235    case 0n Tuple{d, x} Tuple{h, y}:
236      P2{d, h}
237    case 1n+p Tuple{d, +x} Tuple{h, +y}:
238      mask_l(p, (t + 1 : U32), Array.get(F32, Array.set(F32, d, t, (x * pos(y) : F32)), (t + 1 : U32)), Array.get(F32, h, (t + 1 : U32)))
239
240# w[t] -= lr * dw[t]
241
242def maxl2(xs: List<&2, F32>, cur: F32) -> F32:
243  match xs:
244    case Nil{}:
245      cur
246    case Con{+h, t}:
247      maxl2(t, F32.max(cur, h))
248
249def maxl(xs: List<&2, F32>) -> F32:
250  match xs:
251    case Nil{}:
252      0.0
253    case Con{+h, t}:
254      maxl2(t, h)
255
256def expl(xs: List<&2, F32>, +m: F32) -> List<&2, F32>:
257  match xs:
258    case Nil{}:
259      Nil{}
260    case Con{+h, t}:
261      F32.exp((h - m : F32)) <> expl(t, m)
262
263def suml(xs: List<&2, F32>, acc: F32) -> F32:
264  match xs:
265    case Nil{}:
266      acc
267    case Con{+h, t}:
268      suml(t, (acc + h : F32))
269
270def divl(xs: List<&2, F32>, +s: F32) -> List<&2, F32>:
271  match xs:
272    case Nil{}:
273      Nil{}
274    case Con{+h, t}:
275      (h / s : F32) <> divl(t, s)
276
277def softmax2(+es: List<&2, F32>) -> List<&2, F32>:
278  divl(es, suml(es, 0.0))
279
280def softmax(+xs: List<&2, F32>) -> List<&2, F32>:
281  softmax2(expl(xs, maxl(xs)))
282
283# p[label]
284
285def sgd_l(nleft: Nat, +t: U32, +lr: F32, rw: Array<F32> & F32, rd: Array<F32> & F32) -> P2:
286  match nleft rw rd:
287    case 0n Tuple{w, x} Tuple{d, y}:
288      P2{w, d}
289    case 1n+p Tuple{w, +x} Tuple{d, +y}:
290      sgd_l(p, (t + 1 : U32), lr, Array.get(F32, Array.set(F32, w, t, (x - (lr * y : F32) : F32)), (t + 1 : U32)), Array.get(F32, d, (t + 1 : U32)))
291
292# ---------------------------------------------------------------------
293# softmax + cross-entropy per row (lists of 10 elements: negligible cost)
294# ---------------------------------------------------------------------
295
296def pick(ps: List<&2, F32>, n: Nat) -> F32:
297  match ps n:
298    case Con{+h, t} 0n:
299      h
300    case Con{h, t} 1n+q:
301      pick(t, q)
302    case Nil{} _:
303      0.0
304
305# (p - onehot(label)) / n
306
307def hit(b: Bool) -> F32:
308  match b:
309    case True{}:
310      1.0
311    case False{}:
312      0.0
313
314def grad_l(ps: List<&2, F32>, +label: Nat, +j: Nat, +nf: F32) -> List<&2, F32>:
315  match ps:
316    case Nil{}:
317      Nil{}
318    case Con{+h, t}:
319      (((h - hit(Nat.is_eq(label, j)) : F32) / nf) : F32) <> grad_l(t, label, 1n+j, nf)
320
321type L2 is Type:
322  L2{loss: F32, c: Array<F32>}
323
324def ce_row2(+ps: List<&2, F32>, +label: Nat, +nf: F32, +idx: U32, loss: F32, c: Array<F32>) -> L2:
325  L2{(loss - F32.log(F32.max(pick(ps, label), 0.000000000001)) : F32), write_l(grad_l(ps, label, 0n, nf), idx, c)}
326
327def ce_row(al: AL, +label: Nat, +nf: F32, +idx: U32, loss: F32) -> L2:
328  match al:
329    case AL{c, l}:
330      ce_row2(softmax(l), label, nf, idx, loss, c)
331
332# walks the rows of z2 (n x m): r carries the accumulated loss and the array; at the end the array has become the gradient
333
334type Mat<-r: Nat, -c: Nat> is Type:
335  Mat{d: Array<F32>}
336
337def ce_rows(labels: List<&2, Nat>, +mm1: Nat, +mu: U32, +nf: F32, +i: U32, r: L2) -> L2:
338  match labels r:
339    case Nil{} L2{loss, c}:
340      L2{loss, c}
341    case Con{+y, t} L2{loss, c}:
342      ce_rows(t, mm1, mu, nf, (i + 1 : U32), ce_row(read_l(mm1, (i * mu : U32), Nil{}, Array.get(F32, c, (i * mu : U32))), y, nf, (i * mu : U32), loss))
343
344# ---- helper: hits per row ----
345
346type CR is Type:
347  CR{c: Array<F32>, n: Nat}
348
349def gt_head(xs: List<&2, F32>, +v: F32) -> Bool:
350  match xs:
351    case Nil{}:
352      False{}
353    case Con{+h, t}:
354      F32.is_gt(h, v)
355
356def argmax2(xs: List<&2, F32>, g: Bool, +i: Nat, +bi: Nat, +bv: F32) -> Nat:
357  match xs g:
358    case Nil{} _:
359      bi
360    case Con{+h, +t} True{}:
361      argmax2(t, gt_head(t, h), 1n+i, i, h)
362    case Con{h, +t} False{}:
363      argmax2(t, gt_head(t, bv), 1n+i, bi, bv)
364
365def argmax(xs: List<&2, F32>) -> Nat:
366  match xs:
367    case Nil{}:
368      0n
369    case Con{+h, +t}:
370      argmax2(t, gt_head(t, h), 1n, 0n, h)
371
372def one(b: Bool) -> Nat:
373  match b:
374    case True{}:
375      1n
376    case False{}:
377      0n
378
379def count_rows3(+y: Nat, n: Nat, al: AL) -> CR:
380  match al:
381    case AL{c, l}:
382      CR{c, Nat.add(n, one(Nat.is_eq(argmax(l), y)))}
383
384def count_rows(labels: List<&2, Nat>, +mm1: Nat, +mu: U32, +i: U32, r: CR) -> CR:
385  match labels r:
386    case Nil{} CR{c, n}:
387      CR{c, n}
388    case Con{+y, t} CR{c, n}:
389      count_rows(t, mm1, mu, (i + 1 : U32), count_rows3(y, n, read_l(mm1, (i * mu : U32), Nil{}, Array.get(F32, c, (i * mu : U32)))))
390
391
392# =====================================================================
393# Typed API: Mat<r, c> (the dimensions enter the type)
394# =====================================================================
395
396# =====================================================================
397# Array capacity: a PROVED depth for the number of slots
398# =====================================================================
399#
400# cap_depth(n) is the d such that an Array with 2^d slots holds n elements. It is computed by
401# structural recursion on n (not with U32.log2) so that the law cap_ok below can prove
402# `n <= 2^cap_depth(n)`. What stays trusted is only that Array.new(T, d, v) allocates 2^d slots.
403
404# a type chosen by a Bool: rewriting through it refutes True == False
405def BD(b: Bool, t: Type, f: Type) -> Type:
406  match b:
407    case True{}:
408      t
409    case False{}:
410      f
411
412# a <= b, by direct recursion
413def leb(a: Nat, b: Nat) -> Bool:
414  match a b:
415    case 0n _:
416      True{}
417    case 1n+p 0n:
418      False{}
419    case 1n+p 1n+q:
420      leb(p, q)
421
422def pow2(d: Nat) -> Nat:
423  match d:
424    case 0n:
425      1n
426    case 1n++q:
427      Nat.add(pow2(q), pow2(q))
428
429# smallest power of two >= n, by structural recursion on n: returns (depth, 2^depth)
430def cap_pick(ok: Bool, d: Nat, +p: Nat) -> Nat & Nat:
431  match ok:
432    case True{}:
433      (d, p)
434    case False{}:
435      (1n+d, Nat.add(p, p))
436
437def cap_step(r: Nat & Nat, +n: Nat) -> Nat & Nat:
438  match r:
439    case Tuple{+d, +p}:
440      cap_pick(leb(n, p), d, p)
441
442def cap_pair(n: Nat) -> Nat & Nat:
443  match n:
444    case 0n:
445      (0n, 1n)
446    case 1n++m:
447      cap_step(cap_pair(m), 1n+m)
448
449def fst_nat(r: Nat & Nat) -> Nat:
450  match r:
451    case Tuple{d, p}:
452      d
453
454def snd_nat(r: Nat & Nat) -> Nat:
455  match r:
456    case Tuple{d, p}:
457      p
458
459# the depth d such that an Array with 2^d slots holds n elements
460def cap_depth(n: Nat) -> Nat:
461  fst_nat(cap_pair(n))
462
463# ---- lemmas ----
464
465# a <= b  ->  a <= 1 + b
466def leb_succ(a: Nat, b: Nat, e: {True{} == leb(a, b) : Bool}) -> {True{} == leb(a, 1n+b) : Bool}:
467  match a b:
468    case 0n _:
469      {==}
470    case 1n+p 0n:
471      %e : BD(_, Unit, {True{} == leb(1n+p, 1n) : Bool})
472      Unit{}
473    case 1n+p 1n+q:
474      leb_succ(p, q, e)
475
476# a <= b  ->  a <= c + b
477def leb_up_l(+a: Nat, +b: Nat, c: Nat, +e: {True{} == leb(a, b) : Bool}) -> {True{} == leb(a, Nat.add(c, b)) : Bool}:
478  match c:
479    case 0n:
480      e
481    case 1n++c2:
482      leb_succ(a, Nat.add(c2, b), leb_up_l(a, b, c2, e))
483
484# a <= b  ->  a <= b + c
485def leb_up(a: Nat, b: Nat, c: Nat, e: {True{} == leb(a, b) : Bool}) -> {True{} == leb(a, Nat.add(b, c)) : Bool}:
486  match a b:
487    case 0n _:
488      {==}
489    case 1n+p 0n:
490      %e : BD(_, Unit, {True{} == leb(1n+p, Nat.add(0n, c)) : Bool})
491      Unit{}
492    case 1n+p 1n+q:
493      leb_up(p, q, c, e)
494
495# a <= b  and  c <= d  ->  a + c <= b + d
496def leb_add(a: Nat, b: Nat, c: Nat, d: Nat, e1: {True{} == leb(a, b) : Bool}, e2: {True{} == leb(c, d) : Bool}) -> {True{} == leb(Nat.add(a, c), Nat.add(b, d)) : Bool}:
497  match a b:
498    case 0n _:
499      leb_up_l(c, d, b, e2)
500    case 1n+p 0n:
501      %e1 : BD(_, Unit, {True{} == leb(Nat.add(1n+p, c), Nat.add(0n, d)) : Bool})
502      Unit{}
503    case 1n+p 1n+q:
504      leb_add(p, q, c, d, e1, e2)
505
506# 1 <= 2^d
507def pow2_pos(d: Nat) -> {True{} == leb(1n, pow2(d)) : Bool}:
508  match d:
509    case 0n:
510      {==}
511    case 1n++q:
512      leb_up(1n, pow2(q), pow2(q), pow2_pos(q))
513
514# 1 <= p when p = 2^d
515def pos_p(d: Nat, p: Nat, i1: {p == pow2(d) : Nat}) -> {True{} == leb(1n, p) : Bool}:
516  %Equal.sym(Nat, p, pow2(d), i1) : {True{} == leb(1n, _) : Bool}
517  pow2_pos(d)
518
519# p + p == 2^(1+d) when p == 2^d
520def step_eq(d: Nat, p: Nat, i1: {p == pow2(d) : Nat}) -> {Nat.add(p, p) == pow2(1n+d) : Nat}:
521  %i1 : {Nat.add(p, p) == Nat.add(_, _) : Nat}
522  {==}
523
524# one step: given the invariant for m, the invariant for 1+m holds whichever way the comparison goes
525def step_ok(ok: Bool, +d: Nat, +p: Nat, +m: Nat, +e: {ok == leb(1n+m, p) : Bool}, +i1: {p == pow2(d) : Nat}, +i2: {True{} == leb(m, p) : Bool}) -> {snd_nat(cap_pick(ok, d, p)) == pow2(fst_nat(cap_pick(ok, d, p))) : Nat} & {True{} == leb(1n+m, snd_nat(cap_pick(ok, d, p))) : Bool}:
526  match ok:
527    case True{}:
528      (i1, e)
529    case False{}:
530      (step_eq(d, p, i1), leb_add(1n, p, m, p, pos_p(d, p, i1), i2))
531
532
533# the invariant for cap_step on a pair, opened
534def step_pair_ok(+m: Nat, r: Nat & Nat, i1: {snd_nat(r) == pow2(fst_nat(r)) : Nat}, i2: {True{} == leb(m, snd_nat(r)) : Bool}) -> {snd_nat(cap_step(r, 1n+m)) == pow2(fst_nat(cap_step(r, 1n+m))) : Nat} & {True{} == leb(1n+m, snd_nat(cap_step(r, 1n+m))) : Bool}:
535  match r:
536    case Tuple{+d, +p}:
537      step_ok(leb(1n+m, p), d, p, m, {==}, i1, i2)
538
539def cap_succ(+m: Nat, ih: {snd_nat(cap_pair(m)) == pow2(fst_nat(cap_pair(m))) : Nat} & {True{} == leb(m, snd_nat(cap_pair(m))) : Bool}) -> {snd_nat(cap_pair(1n+m)) == pow2(fst_nat(cap_pair(1n+m))) : Nat} & {True{} == leb(1n+m, snd_nat(cap_pair(1n+m))) : Bool}:
540  match ih:
541    case Tuple{i1, i2}:
542      step_pair_ok(m, cap_pair(m), i1, i2)
543
544# the invariant of cap_pair: the second component is 2^(first) and is >= n
545def cap_inv(n: Nat) -> {snd_nat(cap_pair(n)) == pow2(fst_nat(cap_pair(n))) : Nat} & {True{} == leb(n, snd_nat(cap_pair(n))) : Bool}:
546  match n:
547    case 0n:
548      ({==}, {==})
549    case 1n++m:
550      cap_succ(m, cap_inv(m))
551
552def cap_final(n: Nat, pr: {snd_nat(cap_pair(n)) == pow2(fst_nat(cap_pair(n))) : Nat} & {True{} == leb(n, snd_nat(cap_pair(n))) : Bool}) -> {True{} == leb(n, pow2(cap_depth(n))) : Bool}:
553  match pr:
554    case Tuple{i1, i2}:
555      %i1 : {True{} == leb(n, _) : Bool}
556      i2
557
558# LAW (cap_ok): an Array with 2^cap_depth(n) slots always has room for n elements.
559law cap_ok:
560  for +n: Nat
561  {True{} == leb(n, pow2(cap_depth(n))) : Bool}
562
563def cap_ok(n):
564  cap_final(n, cap_inv(n))
565
566# r x c of zeros, with the exact capacity (smallest power of 2)
567
568def Mat.zeros(+r: Nat, +c: Nat) -> Mat<r, c>:
569  Mat{Array.new(F32, cap_depth(Nat.mul(r, c)), 0.0)}
570
571def Mat.fill(+r: Nat, +c: Nat, +v: F32) -> Mat<r, c>:
572  Mat{Array.new(F32, cap_depth(Nat.mul(r, c)), v)}
573
574def fill_list(xs: List<&2, F32>, +i: U32, a: Array<F32>) -> Array<F32>:
575  match xs:
576    case Nil{}:
577      a
578    case Con{h, t}:
579      fill_list(t, (i + 1 : U32), Array.set(F32, a, i, h))
580
581def len_is(xs: List<&2, F32>, n: Nat) -> Bool:
582  match xs n:
583    case Nil{} 0n:
584      True{}
585    case Con{h, t} 1n+p:
586      len_is(t, p)
587    case _ _:
588      False{}
589
590def Mat.of_list2(-r: Nat, -c: Nat, +rr: Nat, +cc: Nat, ok: Bool, xs: List<&2, F32>) -> Maybe<&1, Mat<r, c>>:
591  match ok:
592    case True{}:
593      Some{Mat{fill_list(xs, 0, Array.new(F32, cap_depth(Nat.mul(rr, cc)), 0.0))}}
594    case False{}:
595      None{}
596
597# Mat<r, c> from r*c numbers in row order; None if the size does not match
598
599def Mat.of_list(+r: Nat, +c: Nat, +xs: List<&2, F32>) -> Maybe<&1, Mat<r, c>>:
600  Mat.of_list2(r, c, r, c, len_is(xs, Nat.mul(r, c)), xs)
601
602# reads the first n numbers, returning the matrix
603
604# Mat<r, c> without checking the list size (a short list leaves the rest at zero, a long one is cut
605# by the capacity): only for when the size is known by construction. Prefer Mat.of_list.
606
607def Mat.from_list(+r: Nat, +c: Nat, xs: List<&2, F32>) -> Mat<r, c>:
608  Mat{fill_list(xs, 0, Array.new(F32, cap_depth(Nat.mul(r, c)), 0.0))}
609
610# writes the numbers of xs into m starting at flat index i (row-major); numbers past the
611# capacity are dropped. For loading a large matrix block by block without building one big list.
612def Mat.fill_at(-r: Nat, -c: Nat, +i: U32, xs: List<&2, F32>, m: Mat<r, c>) -> Mat<r, c>:
613  match m:
614    case Mat{d}:
615      Mat{fill_list(xs, i, d)}
616
617type ML<-r: Nat, -c: Nat> is Type:
618  ML{m: Mat<r, c>, l: List<&2, F32>}
619
620def Mat.to_list2(-r: Nat, -c: Nat, al: AL) -> ML<r, c>:
621  match al:
622    case AL{d, l}:
623      ML{Mat{d}, l}
624
625# two independent copies
626
627def Mat.to_list(+r: Nat, +c: Nat, m: Mat<r, c>) -> ML<r, c>:
628  match m:
629    case Mat{d}:
630      Mat.to_list2(r, c, read_l(Nat.sub(Nat.mul(r, c), 1n), 0, Nil{}, Array.get(F32, d, 0)))
631
632type MM2<-r: Nat, -c: Nat> is Type:
633  MM2{a: Mat<r, c>, b: Mat<r, c>}
634
635def Mat.clone2(-r: Nat, -c: Nat, p: Array<F32> & Array<F32>) -> MM2<r, c>:
636  match p:
637    case Tuple{x, y}:
638      MM2{Mat{x}, Mat{y}}
639
640# ---- products: C (n x m) = A · B, with 2^par blocks of rows in parallel ----
641
642# C = A(n x k) · B(k x m)
643
644def Mat.clone(-r: Nat, -c: Nat, m: Mat<r, c>) -> MM2<r, c>:
645  match m:
646    case Mat{d}:
647      Mat.clone2(r, c, Array.clone(F32, d))
648
649type MMul<-n: Nat, -k: Nat, -m: Nat> is Type:
650  MMul{a: Mat<n, k>, b: Mat<k, m>, c: Mat<n, m>}
651
652# C = A(n x k) · Bᵀ, with B stored m x k
653
654type MMulNT<-n: Nat, -k: Nat, -m: Nat> is Type:
655  MMulNT{a: Mat<n, k>, b: Mat<m, k>, c: Mat<n, m>}
656
657# C = Aᵀ · B, with A stored k x n
658
659type MMulTN<-n: Nat, -k: Nat, -m: Nat> is Type:
660  MMulTN{a: Mat<k, n>, b: Mat<k, m>, c: Mat<n, m>}
661
662def gemm_any3(cols: Bool, d: Nat, +n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array<F32>, b: Array<F32>, c: Array<F32>) -> G:
663  match cols:
664    case True{}:
665      gemm_par_cols(d, m, k, sa, sb, bcol, a, b, c)
666    case False{}:
667      gemm_par(d, n, m, k, arow, sa, sb, bcol, a, b, c)
668
669def gemm_any2(d: Nat, +n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array<F32>, b: Array<F32>, c: Array<F32>) -> G:
670  match d:
671    case 0n:
672      gemm(n, m, k, arow, sa, sb, bcol, a, b, c)
673    case 1n+q:
674      gemm_any3(Nat.is_eq(n, 1n), 1n+q, n, m, k, arow, sa, sb, bcol, a, b, c)
675
676def gemm_any(d: Nat, +n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array<F32>, b: Array<F32>, c: Array<F32>) -> G:
677  gemm_any2(d, n, m, k, arow, sa, sb, bcol, a, b, c)
678
679def mmul_fin(-n: Nat, -k: Nat, -m: Nat, g: G) -> MMul<n, k, m>:
680  match g:
681    case G{a, b, c}:
682      MMul{Mat{a}, Mat{b}, Mat{c}}
683
684def mmul_nt_fin(-n: Nat, -k: Nat, -m: Nat, g: G) -> MMulNT<n, k, m>:
685  match g:
686    case G{a, b, c}:
687      MMulNT{Mat{a}, Mat{b}, Mat{c}}
688
689def mmul_tn_fin(-n: Nat, -k: Nat, -m: Nat, g: G) -> MMulTN<n, k, m>:
690  match g:
691    case G{a, b, c}:
692      MMulTN{Mat{a}, Mat{b}, Mat{c}}
693
694def mm_a(+n: Nat, +k: Nat, +m: Nat, d: Nat, a: Array<F32>, b: Array<F32>) -> MMul<n, k, m>:
695  mmul_fin(n, k, m, gemm_any(d, n, m, k, U32.from_nat(k), 1, U32.from_nat(m), 1, a, b, Array.new(F32, cap_depth(Nat.mul(n, m)), 0.0)))
696
697# C = A · B   (n x k) · (k x m); par = log2 of the number of parallel blocks (0 = sequential)
698
699def Mat.matmul(+n: Nat, +k: Nat, +m: Nat, par: Nat, a: Mat<n, k>, b: Mat<k, m>) -> MMul<n, k, m>:
700  match a b:
701    case Mat{x} Mat{y}:
702      mm_a(n, k, m, par, x, y)
703
704def mm_nt(+n: Nat, +k: Nat, +m: Nat, d: Nat, a: Array<F32>, b: Array<F32>) -> MMulNT<n, k, m>:
705  mmul_nt_fin(n, k, m, gemm_any(d, n, m, k, U32.from_nat(k), 1, 1, U32.from_nat(k), a, b, Array.new(F32, cap_depth(Nat.mul(n, m)), 0.0)))
706
707# C = A · Bᵀ   (n x k) · (m x k)ᵀ: for weights stored with one row per output
708
709def Mat.matmul_nt(+n: Nat, +k: Nat, +m: Nat, par: Nat, a: Mat<n, k>, b: Mat<m, k>) -> MMulNT<n, k, m>:
710  match a b:
711    case Mat{x} Mat{y}:
712      mm_nt(n, k, m, par, x, y)
713
714def mm_tn(+n: Nat, +k: Nat, +m: Nat, d: Nat, a: Array<F32>, b: Array<F32>) -> MMulTN<n, k, m>:
715  mmul_tn_fin(n, k, m, gemm_any(d, n, m, k, 1, U32.from_nat(n), U32.from_nat(m), 1, a, b, Array.new(F32, cap_depth(Nat.mul(n, m)), 0.0)))
716
717# C = Aᵀ · B   (k x n)ᵀ · (k x m): weight gradient, X^T · dY
718
719def Mat.matmul_tn(+n: Nat, +k: Nat, +m: Nat, par: Nat, a: Mat<k, n>, b: Mat<k, m>) -> MMulTN<n, k, m>:
720  match a b:
721    case Mat{x} Mat{y}:
722      mm_tn(n, k, m, par, x, y)
723
724# ---- element-wise and training operations ----
725
726# adds the bias (one row, m numbers) to each row of C (n x m)
727
728type MBias<-n: Nat, -m: Nat> is Type:
729  MBias{c: Mat<n, m>, b: Mat<1n, m>}
730
731def add_row2(-n: Nat, -m: Nat, +nn: Nat, +mm: Nat, cd: Array<F32>, al: AL) -> MBias<n, m>:
732  match al:
733    case AL{bd, bl}:
734      MBias{Mat{bias_rows(nn, 0, U32.from_nat(mm), bl, cd)}, Mat{bd}}
735
736def Mat.add_row(+n: Nat, +m: Nat, c: Mat<n, m>, b: Mat<1n, m>) -> MBias<n, m>:
737  match c b:
738    case Mat{cd} Mat{bd}:
739      add_row2(n, m, n, m, cd, read_l(Nat.sub(m, 1n), 0, Nil{}, Array.get(F32, bd, 0)))
740
741# pair of matrices of the same shape (the result of an operation that reads two operands)
742
743type MPair<-r: Nat, -c: Nat> is Type:
744  MPair{a: Mat<r, c>, b: Mat<r, c>}
745
746def mpair_fin(-r: Nat, -c: Nat, p: P2) -> MPair<r, c>:
747  match p:
748    case P2{a, b}:
749      MPair{Mat{a}, Mat{b}}
750
751def relu_fin(-r: Nat, -c: Nat, d: Array<F32>) -> Mat<r, c>:
752  Mat{d}
753
754def Mat.relu(+r: Nat, +c: Nat, a: Mat<r, c>) -> Mat<r, c>:
755  match a:
756    case Mat{d}:
757      relu_fin(r, c, relu_l(Nat.mul(r, c), 0, Array.get(F32, d, 0)))
758
759# (dy * (h > 0), h): the gradient that passes through the relu
760
761def Mat.relu_bwd(+r: Nat, +c: Nat, dy: Mat<r, c>, h: Mat<r, c>) -> MPair<r, c>:
762  match dy h:
763    case Mat{d} Mat{x}:
764      mpair_fin(r, c, mask_l(Nat.mul(r, c), 0, Array.get(F32, d, 0), Array.get(F32, x, 0)))
765
766# (w - lr * dw, dw): one SGD step
767
768def Mat.sgd(+r: Nat, +c: Nat, +lr: F32, w: Mat<r, c>, dw: Mat<r, c>) -> MPair<r, c>:
769  match w dw:
770    case Mat{x} Mat{y}:
771      mpair_fin(r, c, sgd_l(Nat.mul(r, c), 0, lr, Array.get(F32, x, 0), Array.get(F32, y, 0)))
772
773# (a + b, b): element-wise sum (a - (-1)*b is exactly a + b)
774
775def Mat.add(+r: Nat, +c: Nat, a: Mat<r, c>, b: Mat<r, c>) -> MPair<r, c>:
776  match a b:
777    case Mat{x} Mat{y}:
778      mpair_fin(r, c, sgd_l(Nat.mul(r, c), 0, (0.0 - 1.0 : F32), Array.get(F32, x, 0), Array.get(F32, y, 0)))
779
780# sum of each column (n x m -> 1 x m), returning the matrix
781
782type MColSum<-n: Nat, -m: Nat> is Type:
783  MColSum{a: Mat<n, m>, s: Mat<1n, m>}
784
785def colsum_fin(-n: Nat, -m: Nat, g: G) -> MColSum<n, m>:
786  match g:
787    case G{ones, a, s}:
788      MColSum{Mat{a}, Mat{s}}
789
790def Mat.col_sums(+n: Nat, +m: Nat, a: Mat<n, m>) -> MColSum<n, m>:
791  match a:
792    case Mat{d}:
793      colsum_fin(n, m, gemm(1n, m, n, 0, 1, U32.from_nat(m), 1, Array.new(F32, cap_depth(n), 1.0), d, Array.new(F32, cap_depth(m), 0.0)))
794
795# mean cross-entropy and its gradient on the logits: (softmax - one-hot) / n.
796# labels has one entry per row (n); the gradient replaces the logits.
797
798type MCE<-n: Nat, -c: Nat> is Type:
799  MCE{loss: F32, grad: Mat<n, c>}
800
801def ce_fin(-n: Nat, -c: Nat, +nf: F32, r: L2) -> MCE<n, c>:
802  match r:
803    case L2{loss, d}:
804      MCE{(loss / nf : F32), Mat{d}}
805
806def Mat.softmax_ce(+n: Nat, +c: Nat, z: Mat<n, c>, labels: List<&2, Nat>) -> MCE<n, c>:
807  match z:
808    case Mat{d}:
809      ce_fin(n, c, F32.from_nat(n), ce_rows(labels, Nat.sub(c, 1n), U32.from_nat(c), F32.from_nat(n), 0, L2{0.0, d}))
810
811# argmax hits per row against labels
812
813type MHits<-n: Nat, -c: Nat> is Type:
814  MHits{z: Mat<n, c>, hits: Nat}
815
816def hits_fin(-n: Nat, -c: Nat, r: CR) -> MHits<n, c>:
817  match r:
818    case CR{d, k}:
819      MHits{Mat{d}, k}
820
821def Mat.count_correct(+n: Nat, +c: Nat, z: Mat<n, c>, labels: List<&2, Nat>) -> MHits<n, c>:
822  match z:
823    case Mat{d}:
824      hits_fin(n, c, count_rows(labels, Nat.sub(c, 1n), U32.from_nat(c), 0, CR{d, 0n}))
825
826# a row as a list (returning the matrix) and the other way around
827
828type MRow<-r: Nat, -c: Nat> is Type:
829  MRow{m: Mat<r, c>, row: List<&2, F32>}
830
831def row_fin(-r: Nat, -c: Nat, al: AL) -> MRow<r, c>:
832  match al:
833    case AL{d, l}:
834      MRow{Mat{d}, l}
835
836def Mat.read_row(+r: Nat, +c: Nat, m: Mat<r, c>, +i: U32) -> MRow<r, c>:
837  match m:
838    case Mat{d}:
839      row_fin(r, c, read_l(Nat.sub(c, 1n), (i * U32.from_nat(c) : U32), Nil{}, Array.get(F32, d, (i * U32.from_nat(c) : U32))))
840
841def Mat.write_row(-r: Nat, +c: Nat, m: Mat<r, c>, +i: U32, xs: List<&2, F32>) -> Mat<r, c>:
842  match m:
843    case Mat{d}:
844      Mat{write_l(xs, (i * U32.from_nat(c) : U32), d)}
845
846# ---- variants that check the number of labels ----
847
848# does the list of labels have exactly n entries (one per row)?
849def labels_len_is(xs: List<&2, Nat>, n: Nat) -> Bool:
850  match xs n:
851    case Nil{} 0n:
852      True{}
853    case Con{h, t} 1n+p:
854      labels_len_is(t, p)
855    case _ _:
856      False{}
857
858def ce_checked(ok: Bool, +n: Nat, +c: Nat, z: Mat<n, c>, labels: List<&2, Nat>) -> Maybe<&1, MCE<n, c>>:
859  match ok:
860    case True{}:
861      Some{Mat.softmax_ce(n, c, z, labels)}
862    case False{}:
863      None{}
864
865# like Mat.softmax_ce, but returns None unless labels has exactly n entries
866def Mat.softmax_ce_checked(+n: Nat, +c: Nat, z: Mat<n, c>, +labels: List<&2, Nat>) -> Maybe<&1, MCE<n, c>>:
867  ce_checked(labels_len_is(labels, n), n, c, z, labels)
868
869def hits_checked(ok: Bool, +n: Nat, +c: Nat, z: Mat<n, c>, labels: List<&2, Nat>) -> Maybe<&1, MHits<n, c>>:
870  match ok:
871    case True{}:
872      Some{Mat.count_correct(n, c, z, labels)}
873    case False{}:
874      None{}
875
876# like Mat.count_correct, but returns None unless labels has exactly n entries
877def Mat.count_correct_checked(+n: Nat, +c: Nat, z: Mat<n, c>, +labels: List<&2, Nat>) -> Maybe<&1, MHits<n, c>>:
878  hits_checked(labels_len_is(labels, n), n, c, z, labels)
879
880# ---------------------------------------------------------------------
881# Bands<r, c>: a matrix cut into bands of rows, for matrix · vector in parallel
882# without copying the weights.
883#
884# Mat.matmul_nt with n = 1 can only run in parallel by cloning the whole weight
885# matrix for every task, and in matrix · vector each weight is read once, so the
886# copies cost more than the products (NOTES.md, exp. 9). Bands keeps each band in
887# its own Array: a task takes its band and nothing is copied except the input vector.
888#
889# A node with r rows has children with half(r) and r - half(r) rows. The split is
890# part of the type, so the row count of every band follows from r, and the law
891# half_cover says that the two halves always cover the r rows exactly.
892# ---------------------------------------------------------------------
893
894# n / 2 rounded down. A tail loop with an accumulator: a non-tail recursion here would put a
895# continuation on every node of the band tree and keep the bands from running in parallel.
896def half.go(n: Nat, acc: Nat) -> Nat:
897  match n:
898    case 0n:
899      acc
900    case 1n+p:
901      match p:
902        case 0n:
903          acc
904        case 1n+q:
905          half.go(q, 1n+acc)
906
907def half(n: Nat) -> Nat:
908  half.go(n, 0n)
909
910# a <= a
911def leb_refl(+a: Nat) -> {True{} == leb(a, a) : Bool}:
912  match a:
913    case 0n:
914      {==}
915    case 1n+p:
916      leb_refl(p)
917
918# 1 + (a + b) == a + (1 + b)
919def add_succ_r(+a: Nat, -b: Nat) -> {1n+Nat.add(a, b) == Nat.add(a, 1n+b) : Nat}:
920  match a:
921    case 0n:
922      {==}
923    case 1n+p:
924      %add_succ_r(p, b) : {2n+Nat.add(p, b) == 1n+_ : Nat}
925      {==}
926
927# a + 0 == a
928def add_zero_r(+a: Nat) -> {Nat.add(a, 0n) == a : Nat}:
929  match a:
930    case 0n:
931      {==}
932    case 1n+p:
933      %add_zero_r(p) : {1n+Nat.add(p, 0n) == 1n+_ : Nat}
934      {==}
935
936# half.go(n, acc) <= n + acc
937def half_go_le(+n: Nat, +acc: Nat) -> {True{} == leb(half.go(n, acc), Nat.add(n, acc)) : Bool}:
938  match n:
939    case 0n:
940      leb_refl(acc)
941    case 1n+p:
942      match p:
943        case 0n:
944          leb_succ(acc, acc, leb_refl(acc))
945        case 1n+q:
946          %Equal.sym(Nat, 1n+Nat.add(q, acc), Nat.add(q, 1n+acc), add_succ_r(q, acc)) : {True{} == leb(half.go(q, 1n+acc), 1n+_) : Bool}
947          leb_succ(half.go(q, 1n+acc), Nat.add(q, 1n+acc), half_go_le(q, 1n+acc))
948
949# half(n) <= n
950def half_le(+n: Nat) -> {True{} == leb(half(n), n) : Bool}:
951  %add_zero_r(n) : {True{} == leb(half(n), _) : Bool}
952  half_go_le(n, 0n)
953
954# a <= r  ->  r == a + (r - a)
955def add_sub(+a: Nat, +r: Nat, e: {True{} == leb(a, r) : Bool}) -> {r == Nat.add(a, Nat.sub(r, a)) : Nat}:
956  match a r:
957    case 0n 0n:
958      {==}
959    case 0n 1n+q:
960      {==}
961    case 1n+p 0n:
962      %e : BD(_, Unit, {0n == Nat.add(1n+p, Nat.sub(0n, 1n+p)) : Nat})
963      Unit{}
964    case 1n+p 1n+q:
965      %add_sub(p, q, e) : {1n+q == 1n+_ : Nat}
966      {==}
967
968# LAW (half_cover): the two bands of a node, half(r) rows and r - half(r) rows,
969# add up to exactly r rows: no row is lost and none is counted twice.
970law half_cover:
971  for +n: Nat
972  {n == Nat.add(half(n), Nat.sub(n, half(n))) : Nat}
973
974def half_cover(n):
975  add_sub(half(n), n, half_le(n))
976
977type Bands<-r: Nat, -c: Nat> is Type:
978  BLeaf{m: Mat<r, c>}
979  BNode{x: Bands<half(r), c>, y: Bands<Nat.sub(r, half(r)), c>}
980
981# r x c of zeros in 2^d bands (d = 0: a single band, the same as a Mat)
982def Bands.zeros(+d: Nat, +r: Nat, +c: Nat) -> Bands<r, c>:
983  match d:
984    case 0n:
985      BLeaf{Mat.zeros(r, c)}
986    case 1n+q:
987      BNode{Bands.zeros(q, half(r), c), Bands.zeros(q, Nat.sub(r, half(r)), c)}
988
989# the row counts of the two bands follow the row count of the node: if rr == r at run
990# time, the same holds for both halves (the bands carry r only in their type)
991def eq_half(-a: Nat, -b: Nat, e: {a == b : Nat}) -> {half(a) == half(b) : Nat}:
992  %e : {half(a) == half(_) : Nat}
993  {==}
994
995def eq_rest(-a: Nat, -b: Nat, e: {a == b : Nat}) -> {Nat.sub(a, half(a)) == Nat.sub(b, half(b)) : Nat}:
996  %e : {Nat.sub(a, half(a)) == Nat.sub(_, half(_)) : Nat}
997  {==}
998
999# does a block of n numbers starting at flat index i end before the second band of a
1000# node with r rows? does it start in the second band?
1001def bfill_l(+r: Nat, +c: Nat, +i: Nat, +n: Nat) -> Bool:
1002  Nat.is_le(Nat.add(i, n), Nat.mul(half(r), c))
1003
1004def bfill_r(+r: Nat, +c: Nat, +i: Nat) -> Bool:
1005  Nat.is_le(Nat.mul(half(r), c), i)
1006
1007# writes the first n numbers of xs at index i (and nothing past them)
1008def fill_n(n: Nat, xs: List<&2, F32>, +i: U32, a: Array<F32>) -> Array<F32>:
1009  match n xs:
1010    case 1n+p Con{h, t}:
1011      fill_n(p, t, (i + 1 : U32), Array.set(F32, a, i, h))
1012    case _ _:
1013      a
1014
1015def fill_band(-r: Nat, -c: Nat, n: Nat, xs: List<&2, F32>, +i: U32, m: Mat<r, c>) -> Mat<r, c>:
1016  match m:
1017    case Mat{d}:
1018      Mat{fill_n(n, xs, i, d)}
1019
1020# writes the first n numbers of xs at flat index i; l and rt say which bands they touch
1021# (bfill_l, bfill_r); rr is the row count r at run time. A block that crosses into the second
1022# band is not copied: the first band writes only its part, the second gets the rest by List.drop.
1023def bfill(+c: Nat, -r: Nat, b: Bands<r, c>, l: Bool, rt: Bool, +rr: Nat, -e: {rr == r : Nat}, +i: Nat, +n: Nat, +xs: List<&2, F32>) -> Bands<r, c>:
1024  match b l rt:
1025    case BLeaf{m} _ _:
1026      BLeaf{fill_band(r, c, n, xs, U32.from_nat(i), m)}
1027    case BNode{x, y} True{} _:
1028      BNode{bfill(c, half(r), x, bfill_l(half(rr), c, i, n), bfill_r(half(rr), c, i), half(rr), eq_half(rr, r, e), i, n, xs), y}
1029    case BNode{x, y} False{} True{}:
1030      BNode{x, bfill(c, Nat.sub(r, half(r)), y, bfill_l(Nat.sub(rr, half(rr)), c, Nat.sub(i, Nat.mul(half(rr), c)), n), bfill_r(Nat.sub(rr, half(rr)), c, Nat.sub(i, Nat.mul(half(rr), c))), Nat.sub(rr, half(rr)), eq_rest(rr, r, e), Nat.sub(i, Nat.mul(half(rr), c)), n, xs)}
1031    case BNode{x, y} False{} False{}:
1032      BNode{bfill(c, half(r), x, bfill_l(half(rr), c, i, Nat.sub(Nat.mul(half(rr), c), i)), bfill_r(half(rr), c, i), half(rr), eq_half(rr, r, e), i, Nat.sub(Nat.mul(half(rr), c), i), xs), bfill(c, Nat.sub(r, half(r)), y, bfill_l(Nat.sub(rr, half(rr)), c, 0n, Nat.sub(n, Nat.sub(Nat.mul(half(rr), c), i))), bfill_r(Nat.sub(rr, half(rr)), c, 0n), Nat.sub(rr, half(rr)), eq_rest(rr, r, e), 0n, Nat.sub(n, Nat.sub(Nat.mul(half(rr), c), i)), List.drop(&2, F32, xs, Nat.sub(Nat.mul(half(rr), c), i)))}
1033
1034def bfill_top(ok: Bool, +r: Nat, +c: Nat, b: Bands<r, c>, +i: Nat, +n: Nat, +xs: List<&2, F32>) -> Bands<r, c>:
1035  match ok:
1036    case True{}:
1037      bfill(c, r, b, bfill_l(r, c, i, n), bfill_r(r, c, i), r, {==}, i, n, xs)
1038    case False{}:
1039      bfill(c, r, b, bfill_l(r, c, i, Nat.sub(Nat.mul(r, c), i)), bfill_r(r, c, i), r, {==}, i, Nat.sub(Nat.mul(r, c), i), xs)
1040
1041# writes the n numbers of xs into b starting at flat index i (row-major, as Mat.fill_at);
1042# numbers past r*c are dropped. For loading a large matrix block by block.
1043def Bands.fill_at(+r: Nat, +c: Nat, +i: Nat, +n: Nat, +xs: List<&2, F32>, b: Bands<r, c>) -> Bands<r, c>:
1044  bfill_top(Nat.is_le(Nat.add(i, n), Nat.mul(r, c)), r, c, b, i, n, xs)
1045
1046# ---- y = B · x for B with r rows of c numbers (a weight matrix stored out x in) ----
1047
1048# B (intact) and y = B · x, typed like Mat.matmul_nt: x is 1 x c, y is 1 x r
1049type BV<-r: Nat, -c: Nat> is Type:
1050  BV{b: Bands<r, c>, y: Mat<1n, r>}
1051
1052# the bands and y as a list in row order (the result of Bands.matvec_l)
1053type BL<-r: Nat, -c: Nat> is Type:
1054  BL{b: Bands<r, c>, y: List<&2, F32>}
1055
1056def bv_g2(-r: Nat, -c: Nat, w: Array<F32>, al: AL) -> BL<r, c>:
1057  match al:
1058    case AL{d, l}:
1059      BL{BLeaf{Mat{w}}, l}
1060
1061# the band's 1 + m rows came out in an Array (one number per row); read them back as a list
1062def bv_g(-r: Nat, -c: Nat, +m: Nat, g: G) -> BL<r, c>:
1063  match g:
1064    case G{a, b, y}:
1065      bv_g2(r, c, b, read_l(m, 0, Nil{}, Array.get(F32, y, 0)))
1066
1067# the rows of one band, one dot product each, with the gemm of Mat.matmul_nt (n = 1), so the
1068# results are identical. Writing the results into an Array and reading them back is faster than
1069# building the list row by row (NOTES.md, exp. 14).
1070def bv_gemm(-r: Nat, +c: Nat, rows: Nat, +rr: Nat, x: Array<F32>, w: Array<F32>) -> BL<r, c>:
1071  match rows:
1072    case 0n:
1073      BL{BLeaf{Mat{w}}, Nil{}}
1074    case 1n+p:
1075      bv_g(r, c, p, gemm(1n, rr, c, U32.from_nat(c), 1, 1, U32.from_nat(c), x, w, Array.new(F32, cap_depth(rr), 0.0)))
1076
1077def bv_mat(-r: Nat, +c: Nat, +rr: Nat, x: Array<F32>, m: Mat<r, c>) -> BL<r, c>:
1078  match m:
1079    case Mat{w}:
1080      bv_gemm(r, c, rr, rr, x, w)
1081
1082def bv_join(-r: Nat, -c: Nat, p: BL<half(r), c>, q: BL<Nat.sub(r, half(r)), c>) -> BL<r, c>:
1083  match p q:
1084    case BL{bx, yx} BL{by, yy}:
1085      BL{BNode{bx, by}, List.append(&2, F32, yx, yy)}
1086
1087# the two bands of a node run in parallel, each with its own copy of x (c numbers);
1088# xp is a pair of copies of x (a leaf uses one). xp comes after the erased e on purpose:
1089# in Bend 2.0.35 an erased parameter at the end of the list turns the parallel let
1090# into two sequential calls (NOTES.md, exp. 11).
1091def bmv(+c: Nat, -r: Nat, b: Bands<r, c>, +rr: Nat, -e: {rr == r : Nat}, xp: Array<F32> & Array<F32>) -> BL<r, c>:
1092  match b xp:
1093    case BLeaf{m} Tuple{x, x2}:
1094      bv_mat(r, c, rr, x, m)
1095    case BNode{bx, by} Tuple{x1, x2}:
1096      p q = bmv(c, half(r), bx, half(rr), eq_half(rr, r, e), Array.clone(F32, x1)) bmv(c, Nat.sub(r, half(r)), by, Nat.sub(rr, half(rr)), eq_rest(rr, r, e), Array.clone(F32, x2))
1097      bv_join(r, c, p, q)
1098
1099def bv_fin(+r: Nat, -c: Nat, bl: BL<r, c>) -> BV<r, c>:
1100  match bl:
1101    case BL{b, y}:
1102      BV{b, Mat.from_list(1n, r, y)}
1103
1104# y = B · x for B (r x c, one row per output) and x (1 x c); returns B intact and y (1 x r).
1105# The same product as Mat.matmul_nt(1n, c, r, ..), and the same numbers, bit for bit.
1106def Bands.matvec(+r: Nat, +c: Nat, b: Bands<r, c>, x: Mat<1n, c>) -> BV<r, c>:
1107  match x:
1108    case Mat{xa}:
1109      bv_fin(r, c, bmv(c, r, b, r, {==}, Array.clone(F32, xa)))
1110
1111# the same product with x and y as lists (x: c numbers, y: r numbers in row order), without the
1112# Mat conversions of Bands.matvec: for callers that already hold the vector as a list
1113def Bands.matvec_l(+r: Nat, +c: Nat, b: Bands<r, c>, +x: List<&2, F32>) -> BL<r, c>:
1114  bmv(c, r, b, r, {==}, Array.clone(F32, fill_list(x, 0, Array.new(F32, cap_depth(c), 0.0))))
1115
1116# ---- reading rows and the whole matrix ----
1117
1118type BRow<-r: Nat, -c: Nat> is Type:
1119  BRow{b: Bands<r, c>, row: List<&2, F32>}
1120
1121def brow_fin(-r: Nat, -c: Nat, al: AL) -> BRow<r, c>:
1122  match al:
1123    case AL{d, l}:
1124      BRow{BLeaf{Mat{d}}, l}
1125
1126# n numbers starting at flat index i of one band (a band may have no rows)
1127def brow_leaf2(-r: Nat, -c: Nat, n: Nat, +i: U32, d: Array<F32>) -> BRow<r, c>:
1128  match n:
1129    case 0n:
1130      BRow{BLeaf{Mat{d}}, Nil{}}
1131    case 1n+p:
1132      brow_fin(r, c, read_l(p, i, Nil{}, Array.get(F32, d, i)))
1133
1134def brow_leaf(-r: Nat, -c: Nat, m: Mat<r, c>, +i: U32, n: Nat) -> BRow<r, c>:
1135  match m:
1136    case Mat{d}:
1137      brow_leaf2(r, c, n, i, d)
1138
1139def brow_l(-r: Nat, -c: Nat, p: BRow<half(r), c>, y: Bands<Nat.sub(r, half(r)), c>) -> BRow<r, c>:
1140  match p:
1141    case BRow{bx, row}:
1142      BRow{BNode{bx, y}, row}
1143
1144def brow_r(-r: Nat, -c: Nat, x: Bands<half(r), c>, q: BRow<Nat.sub(r, half(r)), c>) -> BRow<r, c>:
1145  match q:
1146    case BRow{by, row}:
1147      BRow{BNode{x, by}, row}
1148
1149# row i; left says whether i is in the first band of the node (i < half(rr))
1150def brow(+c: Nat, -r: Nat, b: Bands<r, c>, left: Bool, +rr: Nat, -e: {rr == r : Nat}, +i: Nat) -> BRow<r, c>:
1151  match b left:
1152    case BLeaf{m} _:
1153      brow_leaf(r, c, m, U32.from_nat(Nat.mul(i, c)), c)
1154    case BNode{x, y} True{}:
1155      brow_l(r, c, brow(c, half(r), x, Nat.is_lt(i, half(half(rr))), half(rr), eq_half(rr, r, e), i), y)
1156    case BNode{x, y} False{}:
1157      brow_r(r, c, x, brow(c, Nat.sub(r, half(r)), y, Nat.is_lt(Nat.sub(i, half(rr)), half(Nat.sub(rr, half(rr)))), Nat.sub(rr, half(rr)), eq_rest(rr, r, e), Nat.sub(i, half(rr))))
1158
1159# row i (c numbers), for example an embedding lookup
1160def Bands.read_row(+r: Nat, +c: Nat, b: Bands<r, c>, +i: Nat) -> BRow<r, c>:
1161  brow(c, r, b, Nat.is_lt(i, half(r)), r, {==}, i)
1162
1163def bl_join(-r: Nat, -c: Nat, p: BRow<half(r), c>, q: BRow<Nat.sub(r, half(r)), c>) -> BRow<r, c>:
1164  match p q:
1165    case BRow{bx, xs} BRow{by, ys}:
1166      BRow{BNode{bx, by}, List.append(&2, F32, xs, ys)}
1167
1168def blist(+c: Nat, -r: Nat, b: Bands<r, c>, +rr: Nat, -e: {rr == r : Nat}) -> BRow<r, c>:
1169  match b:
1170    case BLeaf{m}:
1171      brow_leaf(r, c, m, 0, Nat.mul(rr, c))
1172    case BNode{x, y}:
1173      bl_join(r, c, blist(c, half(r), x, half(rr), eq_half(rr, r, e)), blist(c, Nat.sub(r, half(r)), y, Nat.sub(rr, half(rr)), eq_rest(rr, r, e)))
1174
1175# all r*c numbers in row order (in BRow.row)
1176def Bands.to_list(+r: Nat, +c: Nat, b: Bands<r, c>) -> BRow<r, c>:
1177  blist(c, r, b, r, {==})
1178
1179# ---- the list path returns exactly r numbers ----
1180#
1181# The numbers do not matter here, only how many there are: each lemma below counts the list a
1182# function builds, following the function's own recursion.
1183
1184def bl_len(-r: Nat, -c: Nat, bl: BL<r, c>) -> Nat:
1185  match bl:
1186    case BL{b, y}:
1187      List.length(&2, F32, y)
1188
1189# s == a + (1 + b)  ->  s == 1 + (a + b)
1190def succ_out(-s: Nat, +a: Nat, +b: Nat, e: {s == Nat.add(a, 1n+b) : Nat}) -> {s == 1n+Nat.add(a, b) : Nat}:
1191  %Equal.sym(Nat, 1n+Nat.add(a, b), Nat.add(a, 1n+b), add_succ_r(a, b)) : {s == _ : Nat}
1192  e
1193
1194# s == 1 + (p + (1 + l))  ->  s == 2 + (p + l)
1195def len_step(-s: Nat, +p: Nat, +l: Nat, e: {s == 1n+Nat.add(p, 1n+l) : Nat}) -> {s == 2n+Nat.add(p, l) : Nat}:
1196  %Equal.sym(Nat, 1n+Nat.add(p, l), Nat.add(p, 1n+l), add_succ_r(p, l)) : {s == 1n+_ : Nat}
1197  e
1198
1199# s == n + 0  ->  s == n
1200def zero_out(-s: Nat, +n: Nat, e: {s == Nat.add(n, 0n) : Nat}) -> {s == n : Nat}:
1201  %add_zero_r(n) : {s == _ : Nat}
1202  e
1203
1204# reversing onto acc adds the lengths
1205def rev_len(+xs: List<&2, F32>, +acc: List<&2, F32>) -> {List.length(&2, F32, List.reverse.go(&2, F32, xs, acc)) == Nat.add(List.length(&2, F32, xs), List.length(&2, F32, acc)) : Nat}:
1206  match xs:
1207    case Nil{}:
1208      {==}
1209    case Con{h, t}:
1210      succ_out(List.length(&2, F32, List.reverse.go(&2, F32, t, h <> acc)), List.length(&2, F32, t), List.length(&2, F32, acc), rev_len(t, h <> acc))
1211
1212# appending adds the lengths
1213def app_len(+xs: List<&2, F32>, +ys: List<&2, F32>) -> {List.length(&2, F32, List.append(&2, F32, xs, ys)) == Nat.add(List.length(&2, F32, xs), List.length(&2, F32, ys)) : Nat}:
1214  match xs:
1215    case Nil{}:
1216      {==}
1217    case Con{h, t}:
1218      %app_len(t, ys) : {1n+List.length(&2, F32, List.append(&2, F32, t, ys)) == 1n+_ : Nat}
1219      {==}
1220
1221# a leaf's list: read_l reads mleft + 1 numbers onto acc and reverses them. By induction on
1222# mleft: with 0 left it reads one number (rev_len counts the reversed list); with 1 + p left it
1223# reads one and recurses, and len_step moves the 1 out of the sum.
1224law leaf_len:
1225  for -r: Nat
1226  for -c: Nat
1227  for w: Array<F32>
1228  for +mleft: Nat
1229  for +idx: U32
1230  for +acc: List<&2, F32>
1231  for rc: Array<F32> & F32
1232  {bl_len(r, c, bv_g2(r, c, w, read_l(mleft, idx, acc, rc))) == Nat.add(1n+mleft, List.length(&2, F32, acc)) : Nat}
1233
1234def leaf_len(r, c, w, mleft, idx, acc, rc):
1235  match mleft rc:
1236    case 0n Tuple{d, +v}:
1237      zero_out(List.length(&2, F32, List.reverse.go(&2, F32, v <> acc, Nil{})), 1n+List.length(&2, F32, acc), rev_len(v <> acc, Nil{}))
1238    case 1n+p Tuple{d, +v}:
1239      len_step(bl_len(r, c, bv_g2(r, c, w, read_l(p, (idx + 1 : U32), v <> acc, Array.get(F32, d, (idx + 1 : U32))))), p, List.length(&2, F32, acc), leaf_len(r, c, w, p, (idx + 1 : U32), v <> acc, Array.get(F32, d, (idx + 1 : U32))))
1240
1241# whatever the gemm wrote, reading 1 + p rows back gives 1 + p numbers (G has one constructor, so
1242# matching g opens it, and leaf_len counts the list)
1243def g_len(-r: Nat, -c: Nat, +p: Nat, g: G) -> {bl_len(r, c, bv_g(r, c, p, g)) == 1n+p : Nat}:
1244  match g:
1245    case G{a, b, y}:
1246      zero_out(bl_len(r, c, bv_g2(r, c, b, read_l(p, 0, Nil{}, Array.get(F32, y, 0)))), 1n+p, leaf_len(r, c, b, p, 0, Nil{}, Array.get(F32, y, 0)))
1247
1248# LAW (band_len): the product of one band with `rows` rows gives exactly `rows` numbers.
1249# 0 rows give the empty list; 1 + p rows go through the gemm, and g_len counts what is read back.
1250law band_len:
1251  for -r: Nat
1252  for +c: Nat
1253  for +rows: Nat
1254  for x: Array<F32>
1255  for w: Array<F32>
1256  {bl_len(r, c, bv_gemm(r, c, rows, rows, x, w)) == rows : Nat}
1257
1258def band_len(r, c, rows, x, w):
1259  match rows:
1260    case 0n:
1261      {==}
1262    case 1n+p:
1263      g_len(r, c, p, gemm(1n, 1n+p, c, U32.from_nat(c), 1, 1, U32.from_nat(c), x, w, Array.new(F32, cap_depth(1n+p), 0.0)))
1264
1265# joining two halves of h1 and h2 numbers gives h1 + h2 numbers. (The statement for the whole tree,
1266# "Bands.matvec_l gives r numbers", would apply this to the results of the two recursive calls and
1267# to the induction hypotheses about the same calls; that uses each band's Array twice, which Bend's
1268# affine rules refuse. It stays open, covered by tests: NOTES.md, v3.1.)
1269def join_len(-r: Nat, -c: Nat, -h1: Nat, -h2: Nat, p: BL<half(r), c>, q: BL<Nat.sub(r, half(r)), c>, hp: {bl_len(half(r), c, p) == h1 : Nat}, hq: {bl_len(Nat.sub(r, half(r)), c, q) == h2 : Nat}) -> {bl_len(r, c, bv_join(r, c, p, q)) == Nat.add(h1, h2) : Nat}:
1270  match p q:
1271    case BL{bx, +yx} BL{by, +yy}:
1272      %hp : {List.length(&2, F32, List.append(&2, F32, yx, yy)) == Nat.add(_, h2) : Nat}
1273      %hq : {List.length(&2, F32, List.append(&2, F32, yx, yy)) == Nat.add(List.length(&2, F32, yx), _) : Nat}
1274      app_len(yx, yy)
1275