1 # bend-ml-tensor-array: tensors over a flat Array, with the shape in the type. 2 # 3 # import bend-ml-tensor-array@0.1.7.0/main.bend as TA 4 # 5 # Mat stores r*c numbers in an Array, 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 18 import Base 19 20 # --------------------------------------------------------------------- 21 # helper types 22 # --------------------------------------------------------------------- 23 24 type R is Type: 25 R{a: Array, b: Array, x: F32} 26 27 type G is Type: 28 G{a: Array, b: Array, c: Array} 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). 35 def dotr(k: Nat, +ia: U32, +ib: U32, +sa: U32, +sb: U32, a0: F32, a1: F32, a2: F32, a3: F32, ra: Array & F32, rb: Array & 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 42 def dotg(k: Nat, +ia: U32, +ib: U32, +sa: U32, +sb: U32, acc: F32, ra: Array & F32, rb: Array & 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 47 def gcols(mleft: Nat, +kn: Nat, +ia0: U32, +ib0: U32, +sa: U32, +sb: U32, +bcol: U32, +cidx: U32, c: Array, 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 54 def 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 63 def gemm(+n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array, b: Array, c: Array) -> 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 72 type S3 is Type: 73 S3{a: Array, b: Array, out: List<&2, F32>} 74 75 def 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 82 def 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 89 def lblock_fin(st: S3) -> List<&2, F32>: 90 match st: 91 case S3{a, b, out}: 92 List.reverse(&2, F32, out) 93 94 def lblock(cnt: Nat, +mm1: Nat, +kn: Nat, +i: U32, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array, b: Array) -> List<&2, F32>: 95 lblock_fin(lrows(cnt, mm1, kn, i, arow, sa, sb, bcol, S3{a, b, Nil{}})) 96 97 def lpar(d: Nat, +cnt: Nat, +mm1: Nat, +kn: Nat, +i: U32, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, ra: Array & Array, rb: Array & Array) -> 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 105 def write_l(xs: List<&2, F32>, +idx: U32, c: Array) -> Array: 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 114 def gp3(a: Array, b: Array, c: Array, xs: List<&2, F32>) -> G: 115 G{a, b, write_l(xs, 0, c)} 116 117 def gp2(d: Nat, +n: Nat, +mm1: Nat, +kn: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, c: Array, pa: Array & Array, pb: Array & Array) -> 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 124 def gemm_par(d: Nat, +n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array, b: Array, c: Array) -> 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 133 def 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 140 def cblock_go(cnt1: Nat, +kn: Nat, +ia0: U32, +j0: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array, b: Array) -> 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 143 def cblock(cnt: Nat, +kn: Nat, +ia0: U32, +j0: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array, b: Array) -> 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 150 def cpar(d: Nat, +cnt: Nat, +kn: Nat, +ia0: U32, +j0: U32, +sa: U32, +sb: U32, +bcol: U32, ra: Array & Array, rb: Array & Array) -> 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 158 def cp2(d: Nat, +m: Nat, +kn: Nat, +sa: U32, +sb: U32, +bcol: U32, c: Array, pa: Array & Array, pb: Array & Array) -> 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 165 def gemm_par_cols(d: Nat, +m: Nat, +k: Nat, +sa: U32, +sb: U32, +bcol: U32, a: Array, b: Array, c: Array) -> 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 179 type P2 is Type: 180 P2{a: Array, b: Array} 181 182 type AL is Type: 183 AL{c: Array, l: List<&2, F32>} 184 185 # list of m elements starting at idx (reads with Array.get, returning the array) 186 187 def read_l(mleft: Nat, +idx: U32, acc: List<&2, F32>, rc: Array & 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 196 def addl(xs: List<&2, F32>, +idx: U32, rc: Array & F32) -> Array: 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 205 def bias_rows(nleft: Nat, +i: U32, +mu: U32, +bl: List<&2, F32>, c: Array) -> Array: 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 214 def relu_l(nleft: Nat, +t: U32, rc: Array & F32) -> Array: 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 221 def pos2(b: Bool) -> F32: 222 match b: 223 case True{}: 224 1.0 225 case False{}: 226 0.0 227 228 def 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 233 def mask_l(nleft: Nat, +t: U32, rd: Array & F32, rh: Array & 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 242 def 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 249 def 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 256 def 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 263 def 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 270 def 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 277 def softmax2(+es: List<&2, F32>) -> List<&2, F32>: 278 divl(es, suml(es, 0.0)) 279 280 def softmax(+xs: List<&2, F32>) -> List<&2, F32>: 281 softmax2(expl(xs, maxl(xs))) 282 283 # p[label] 284 285 def sgd_l(nleft: Nat, +t: U32, +lr: F32, rw: Array & F32, rd: Array & 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 296 def 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 307 def hit(b: Bool) -> F32: 308 match b: 309 case True{}: 310 1.0 311 case False{}: 312 0.0 313 314 def 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 321 type L2 is Type: 322 L2{loss: F32, c: Array} 323 324 def ce_row2(+ps: List<&2, F32>, +label: Nat, +nf: F32, +idx: U32, loss: F32, c: Array) -> 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 327 def 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 334 type Mat<-r: Nat, -c: Nat> is Type: 335 Mat{d: Array} 336 337 def 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 346 type CR is Type: 347 CR{c: Array, n: Nat} 348 349 def 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 356 def 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 365 def 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 372 def one(b: Bool) -> Nat: 373 match b: 374 case True{}: 375 1n 376 case False{}: 377 0n 378 379 def 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 384 def 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 (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 405 def 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 413 def 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 422 def 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) 430 def 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 437 def 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 442 def 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 449 def fst_nat(r: Nat & Nat) -> Nat: 450 match r: 451 case Tuple{d, p}: 452 d 453 454 def 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 460 def cap_depth(n: Nat) -> Nat: 461 fst_nat(cap_pair(n)) 462 463 # ---- lemmas ---- 464 465 # a <= b -> a <= 1 + b 466 def 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 477 def 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 485 def 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 496 def 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 507 def 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 515 def 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 520 def 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 525 def 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 534 def 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 539 def 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 545 def 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 552 def 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. 559 law cap_ok: 560 for +n: Nat 561 {True{} == leb(n, pow2(cap_depth(n))) : Bool} 562 563 def 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 568 def Mat.zeros(+r: Nat, +c: Nat) -> Mat: 569 Mat{Array.new(F32, cap_depth(Nat.mul(r, c)), 0.0)} 570 571 def Mat.fill(+r: Nat, +c: Nat, +v: F32) -> Mat: 572 Mat{Array.new(F32, cap_depth(Nat.mul(r, c)), v)} 573 574 def fill_list(xs: List<&2, F32>, +i: U32, a: Array) -> Array: 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 581 def 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 590 def Mat.of_list2(-r: Nat, -c: Nat, +rr: Nat, +cc: Nat, ok: Bool, xs: List<&2, F32>) -> Maybe<&1, Mat>: 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 from r*c numbers in row order; None if the size does not match 598 599 def Mat.of_list(+r: Nat, +c: Nat, +xs: List<&2, F32>) -> Maybe<&1, Mat>: 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 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 607 def Mat.from_list(+r: Nat, +c: Nat, xs: List<&2, F32>) -> Mat: 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. 612 def Mat.fill_at(-r: Nat, -c: Nat, +i: U32, xs: List<&2, F32>, m: Mat) -> Mat: 613 match m: 614 case Mat{d}: 615 Mat{fill_list(xs, i, d)} 616 617 type ML<-r: Nat, -c: Nat> is Type: 618 ML{m: Mat, l: List<&2, F32>} 619 620 def Mat.to_list2(-r: Nat, -c: Nat, al: AL) -> ML: 621 match al: 622 case AL{d, l}: 623 ML{Mat{d}, l} 624 625 # two independent copies 626 627 def Mat.to_list(+r: Nat, +c: Nat, m: Mat) -> ML: 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 632 type MM2<-r: Nat, -c: Nat> is Type: 633 MM2{a: Mat, b: Mat} 634 635 def Mat.clone2(-r: Nat, -c: Nat, p: Array & Array) -> MM2: 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 644 def Mat.clone(-r: Nat, -c: Nat, m: Mat) -> MM2: 645 match m: 646 case Mat{d}: 647 Mat.clone2(r, c, Array.clone(F32, d)) 648 649 type MMul<-n: Nat, -k: Nat, -m: Nat> is Type: 650 MMul{a: Mat, b: Mat, c: Mat} 651 652 # C = A(n x k) · Bᵀ, with B stored m x k 653 654 type MMulNT<-n: Nat, -k: Nat, -m: Nat> is Type: 655 MMulNT{a: Mat, b: Mat, c: Mat} 656 657 # C = Aᵀ · B, with A stored k x n 658 659 type MMulTN<-n: Nat, -k: Nat, -m: Nat> is Type: 660 MMulTN{a: Mat, b: Mat, c: Mat} 661 662 def gemm_any3(cols: Bool, d: Nat, +n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array, b: Array, c: Array) -> 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 669 def gemm_any2(d: Nat, +n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array, b: Array, c: Array) -> 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 676 def gemm_any(d: Nat, +n: Nat, +m: Nat, +k: Nat, +arow: U32, +sa: U32, +sb: U32, +bcol: U32, a: Array, b: Array, c: Array) -> G: 677 gemm_any2(d, n, m, k, arow, sa, sb, bcol, a, b, c) 678 679 def mmul_fin(-n: Nat, -k: Nat, -m: Nat, g: G) -> MMul: 680 match g: 681 case G{a, b, c}: 682 MMul{Mat{a}, Mat{b}, Mat{c}} 683 684 def mmul_nt_fin(-n: Nat, -k: Nat, -m: Nat, g: G) -> MMulNT: 685 match g: 686 case G{a, b, c}: 687 MMulNT{Mat{a}, Mat{b}, Mat{c}} 688 689 def mmul_tn_fin(-n: Nat, -k: Nat, -m: Nat, g: G) -> MMulTN: 690 match g: 691 case G{a, b, c}: 692 MMulTN{Mat{a}, Mat{b}, Mat{c}} 693 694 def mm_a(+n: Nat, +k: Nat, +m: Nat, d: Nat, a: Array, b: Array) -> MMul: 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 699 def Mat.matmul(+n: Nat, +k: Nat, +m: Nat, par: Nat, a: Mat, b: Mat) -> MMul: 700 match a b: 701 case Mat{x} Mat{y}: 702 mm_a(n, k, m, par, x, y) 703 704 def mm_nt(+n: Nat, +k: Nat, +m: Nat, d: Nat, a: Array, b: Array) -> MMulNT: 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 709 def Mat.matmul_nt(+n: Nat, +k: Nat, +m: Nat, par: Nat, a: Mat, b: Mat) -> MMulNT: 710 match a b: 711 case Mat{x} Mat{y}: 712 mm_nt(n, k, m, par, x, y) 713 714 def mm_tn(+n: Nat, +k: Nat, +m: Nat, d: Nat, a: Array, b: Array) -> MMulTN: 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 719 def Mat.matmul_tn(+n: Nat, +k: Nat, +m: Nat, par: Nat, a: Mat, b: Mat) -> MMulTN: 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 728 type MBias<-n: Nat, -m: Nat> is Type: 729 MBias{c: Mat, b: Mat<1n, m>} 730 731 def add_row2(-n: Nat, -m: Nat, +nn: Nat, +mm: Nat, cd: Array, al: AL) -> MBias: 732 match al: 733 case AL{bd, bl}: 734 MBias{Mat{bias_rows(nn, 0, U32.from_nat(mm), bl, cd)}, Mat{bd}} 735 736 def Mat.add_row(+n: Nat, +m: Nat, c: Mat, b: Mat<1n, m>) -> MBias: 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 743 type MPair<-r: Nat, -c: Nat> is Type: 744 MPair{a: Mat, b: Mat} 745 746 def mpair_fin(-r: Nat, -c: Nat, p: P2) -> MPair: 747 match p: 748 case P2{a, b}: 749 MPair{Mat{a}, Mat{b}} 750 751 def relu_fin(-r: Nat, -c: Nat, d: Array) -> Mat: 752 Mat{d} 753 754 def Mat.relu(+r: Nat, +c: Nat, a: Mat) -> Mat: 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 761 def Mat.relu_bwd(+r: Nat, +c: Nat, dy: Mat, h: Mat) -> MPair: 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 768 def Mat.sgd(+r: Nat, +c: Nat, +lr: F32, w: Mat, dw: Mat) -> MPair: 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 775 def Mat.add(+r: Nat, +c: Nat, a: Mat, b: Mat) -> MPair: 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 782 type MColSum<-n: Nat, -m: Nat> is Type: 783 MColSum{a: Mat, s: Mat<1n, m>} 784 785 def colsum_fin(-n: Nat, -m: Nat, g: G) -> MColSum: 786 match g: 787 case G{ones, a, s}: 788 MColSum{Mat{a}, Mat{s}} 789 790 def Mat.col_sums(+n: Nat, +m: Nat, a: Mat) -> MColSum: 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 798 type MCE<-n: Nat, -c: Nat> is Type: 799 MCE{loss: F32, grad: Mat} 800 801 def ce_fin(-n: Nat, -c: Nat, +nf: F32, r: L2) -> MCE: 802 match r: 803 case L2{loss, d}: 804 MCE{(loss / nf : F32), Mat{d}} 805 806 def Mat.softmax_ce(+n: Nat, +c: Nat, z: Mat, labels: List<&2, Nat>) -> MCE: 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 813 type MHits<-n: Nat, -c: Nat> is Type: 814 MHits{z: Mat, hits: Nat} 815 816 def hits_fin(-n: Nat, -c: Nat, r: CR) -> MHits: 817 match r: 818 case CR{d, k}: 819 MHits{Mat{d}, k} 820 821 def Mat.count_correct(+n: Nat, +c: Nat, z: Mat, labels: List<&2, Nat>) -> MHits: 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 828 type MRow<-r: Nat, -c: Nat> is Type: 829 MRow{m: Mat, row: List<&2, F32>} 830 831 def row_fin(-r: Nat, -c: Nat, al: AL) -> MRow: 832 match al: 833 case AL{d, l}: 834 MRow{Mat{d}, l} 835 836 def Mat.read_row(+r: Nat, +c: Nat, m: Mat, +i: U32) -> MRow: 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 841 def Mat.write_row(-r: Nat, +c: Nat, m: Mat, +i: U32, xs: List<&2, F32>) -> Mat: 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)? 849 def 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 858 def ce_checked(ok: Bool, +n: Nat, +c: Nat, z: Mat, labels: List<&2, Nat>) -> Maybe<&1, MCE>: 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 866 def Mat.softmax_ce_checked(+n: Nat, +c: Nat, z: Mat, +labels: List<&2, Nat>) -> Maybe<&1, MCE>: 867 ce_checked(labels_len_is(labels, n), n, c, z, labels) 868 869 def hits_checked(ok: Bool, +n: Nat, +c: Nat, z: Mat, labels: List<&2, Nat>) -> Maybe<&1, MHits>: 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 877 def Mat.count_correct_checked(+n: Nat, +c: Nat, z: Mat, +labels: List<&2, Nat>) -> Maybe<&1, MHits>: 878 hits_checked(labels_len_is(labels, n), n, c, z, labels) 879 880 # --------------------------------------------------------------------- 881 # Bands: 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. 896 def 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 907 def half(n: Nat) -> Nat: 908 half.go(n, 0n) 909 910 # a <= a 911 def 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) 919 def 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 928 def 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 937 def 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 950 def 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) 955 def 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. 970 law half_cover: 971 for +n: Nat 972 {n == Nat.add(half(n), Nat.sub(n, half(n))) : Nat} 973 974 def half_cover(n): 975 add_sub(half(n), n, half_le(n)) 976 977 type Bands<-r: Nat, -c: Nat> is Type: 978 BLeaf{m: Mat} 979 BNode{x: Bands, y: Bands} 980 981 # r x c of zeros in 2^d bands (d = 0: a single band, the same as a Mat) 982 def Bands.zeros(+d: Nat, +r: Nat, +c: Nat) -> Bands: 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) 991 def eq_half(-a: Nat, -b: Nat, e: {a == b : Nat}) -> {half(a) == half(b) : Nat}: 992 %e : {half(a) == half(_) : Nat} 993 {==} 994 995 def 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? 1001 def 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 1004 def 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) 1008 def fill_n(n: Nat, xs: List<&2, F32>, +i: U32, a: Array) -> Array: 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 1015 def fill_band(-r: Nat, -c: Nat, n: Nat, xs: List<&2, F32>, +i: U32, m: Mat) -> Mat: 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. 1023 def bfill(+c: Nat, -r: Nat, b: Bands, l: Bool, rt: Bool, +rr: Nat, -e: {rr == r : Nat}, +i: Nat, +n: Nat, +xs: List<&2, F32>) -> Bands: 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 1034 def bfill_top(ok: Bool, +r: Nat, +c: Nat, b: Bands, +i: Nat, +n: Nat, +xs: List<&2, F32>) -> Bands: 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. 1043 def Bands.fill_at(+r: Nat, +c: Nat, +i: Nat, +n: Nat, +xs: List<&2, F32>, b: Bands) -> Bands: 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 1049 type BV<-r: Nat, -c: Nat> is Type: 1050 BV{b: Bands, y: Mat<1n, r>} 1051 1052 # the bands and y as a list in row order (the result of Bands.matvec_l) 1053 type BL<-r: Nat, -c: Nat> is Type: 1054 BL{b: Bands, y: List<&2, F32>} 1055 1056 def bv_g2(-r: Nat, -c: Nat, w: Array, al: AL) -> BL: 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 1062 def bv_g(-r: Nat, -c: Nat, +m: Nat, g: G) -> BL: 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). 1070 def bv_gemm(-r: Nat, +c: Nat, rows: Nat, +rr: Nat, x: Array, w: Array) -> BL: 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 1077 def bv_mat(-r: Nat, +c: Nat, +rr: Nat, x: Array, m: Mat) -> BL: 1078 match m: 1079 case Mat{w}: 1080 bv_gemm(r, c, rr, rr, x, w) 1081 1082 def bv_join(-r: Nat, -c: Nat, p: BL, q: BL) -> BL: 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). 1091 def bmv(+c: Nat, -r: Nat, b: Bands, +rr: Nat, -e: {rr == r : Nat}, xp: Array & Array) -> BL: 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 1099 def bv_fin(+r: Nat, -c: Nat, bl: BL) -> BV: 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. 1106 def Bands.matvec(+r: Nat, +c: Nat, b: Bands, x: Mat<1n, c>) -> BV: 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 1113 def Bands.matvec_l(+r: Nat, +c: Nat, b: Bands, +x: List<&2, F32>) -> BL: 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 1118 type BRow<-r: Nat, -c: Nat> is Type: 1119 BRow{b: Bands, row: List<&2, F32>} 1120 1121 def brow_fin(-r: Nat, -c: Nat, al: AL) -> BRow: 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) 1127 def brow_leaf2(-r: Nat, -c: Nat, n: Nat, +i: U32, d: Array) -> BRow: 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 1134 def brow_leaf(-r: Nat, -c: Nat, m: Mat, +i: U32, n: Nat) -> BRow: 1135 match m: 1136 case Mat{d}: 1137 brow_leaf2(r, c, n, i, d) 1138 1139 def brow_l(-r: Nat, -c: Nat, p: BRow, y: Bands) -> BRow: 1140 match p: 1141 case BRow{bx, row}: 1142 BRow{BNode{bx, y}, row} 1143 1144 def brow_r(-r: Nat, -c: Nat, x: Bands, q: BRow) -> BRow: 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)) 1150 def brow(+c: Nat, -r: Nat, b: Bands, left: Bool, +rr: Nat, -e: {rr == r : Nat}, +i: Nat) -> BRow: 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 1160 def Bands.read_row(+r: Nat, +c: Nat, b: Bands, +i: Nat) -> BRow: 1161 brow(c, r, b, Nat.is_lt(i, half(r)), r, {==}, i) 1162 1163 def bl_join(-r: Nat, -c: Nat, p: BRow, q: BRow) -> BRow: 1164 match p q: 1165 case BRow{bx, xs} BRow{by, ys}: 1166 BRow{BNode{bx, by}, List.append(&2, F32, xs, ys)} 1167 1168 def blist(+c: Nat, -r: Nat, b: Bands, +rr: Nat, -e: {rr == r : Nat}) -> BRow: 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) 1176 def Bands.to_list(+r: Nat, +c: Nat, b: Bands) -> BRow: 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 1184 def bl_len(-r: Nat, -c: Nat, bl: BL) -> 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) 1190 def 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) 1195 def 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 1200 def 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 1205 def 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 1213 def 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. 1224 law leaf_len: 1225 for -r: Nat 1226 for -c: Nat 1227 for w: Array 1228 for +mleft: Nat 1229 for +idx: U32 1230 for +acc: List<&2, F32> 1231 for rc: Array & 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 1234 def 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) 1243 def 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. 1250 law band_len: 1251 for -r: Nat 1252 for +c: Nat 1253 for +rows: Nat 1254 for x: Array 1255 for w: Array 1256 {bl_len(r, c, bv_gemm(r, c, rows, rows, x, w)) == rows : Nat} 1257 1258 def 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.) 1269 def join_len(-r: Nat, -c: Nat, -h1: Nat, -h2: Nat, p: BL, q: BL, 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