>:
match a b:
case OneMom{x} OneMom{y}: OneMom{Two{x, y}}
case TwoMom{x, u} TwoMom{y, v}: TwoMom{Two{x, y}, Two{u, v}}
case Packed{x} Packed{y}: Packed{PNode{x, y}}
case _ _: NoMom{}
# what an optimizer step returns: the new parameters, the zeroed gradient, the optimizer state
type Step<-P: Type> is Type:
Step{p: P, g: P, st: OptState}
# The optimizer, with the scalars of the current step. Adam's `step` is lr / (1 - b1^t) and `bc2` is
# sqrt(1 - b2^t), as PyTorch computes them; `Opt.at` fills them from an `OptCfg` and the step count.
# `dec` picks AdamW's decoupled weight decay (w *= 1 - lr*wd) over Adam's (g += wd*w).
type Opt is Data:
SGD{lr: F32}
Momentum{lr: F32, mu: F32}
Adam{lr: F32, b1: F32, b2: F32, eps: F32, wd: F32, dec: Bool, step: F32, bc2: F32, c1: F32, c2: F32}
# Parameters and their flat dump in a fixed order. Loading has a separate array cursor (PA).
type PL<-P: Type> is Type:
PL{p: P, xs: List<&2, F32>}
# Loading cursor: the shared source array and next element offset, handed back without a list or a clone.
# The IO boundary checks the source length against Layer.count before calling the pure loaders.
type PA<-P: Type> is Type:
PA{p: P, xs: Array, off: U32}
type Layer<-P: Type, -X: Type, -Y: Type, -S: Type> is Type:
Layer{fwd: P -> X -> Fwd, bwd: P -> S -> Y -> P -> Bwd
, step: Opt -> P -> P -> OptState
-> Step
, zeros: Unit -> P, dump: P -> PL
, load: P -> Array -> U32 -> PA, store: P -> Array -> U32 -> PA, count: Unit -> U32}
def Layer.fwd(-P: Type, -X: Type, -Y: Type, -S: Type, l: Layer
, p: P, x: X) -> Fwd
:
match l:
case Layer{fwd, bwd, step, zeros, dump, load, store, count}:
fwd(p, x)
def Layer.bwd(-P: Type, -X: Type, -Y: Type, -S: Type, l: Layer
, p: P, s: S, dy: Y, g: P) -> Bwd
:
match l:
case Layer{fwd, bwd, step, zeros, dump, load, store, count}:
bwd(p, s, dy, g)
def Layer.step(-P: Type, -X: Type, -Y: Type, -S: Type, l: Layer
, +o: Opt, p: P, g: P, st: OptState
) -> Step
:
match l:
case Layer{fwd, bwd, step, zeros, dump, load, store, count}:
step(o, p, g, st)
def Layer.zeros(-P: Type, -X: Type, -Y: Type, -S: Type, l: Layer
) -> P:
match l:
case Layer{fwd, bwd, step, zeros, dump, load, store, count}:
zeros(Unit{})
# every number of the parameters, in the layer's fixed order (the parameters handed back)
def Layer.dump(-P: Type, -X: Type, -Y: Type, -S: Type, l: Layer
, p: P) -> PL
:
match l:
case Layer{fwd, bwd, step, zeros, dump, load, store, count}:
dump(p)
# Parameters overwritten from xs at an element offset, in dump order; xs and the next offset come back.
def Layer.load(-P: Type, -X: Type, -Y: Type, -S: Type, l: Layer
, p: P, xs: Array, off: U32) -> PA:
match l:
case Layer{fwd, bwd, step, zeros, dump, load, store, count}: load(p, xs, off)
# The parameters copied into xs from an element offset, in dump order (load's inverse); xs and the next offset come back.
def Layer.store(-P: Type, -X: Type, -Y: Type, -S: Type, l: Layer
, p: P, xs: Array, off: U32) -> PA:
match l:
case Layer{fwd, bwd, step, zeros, dump, load, store, count}: store(p, xs, off)
def Layer.count(-P: Type, -X: Type, -Y: Type, -S: Type, l: Layer
) -> U32:
match l:
case Layer{fwd, bwd, step, zeros, dump, load, store, count}: count(Unit{})
# =====================================================================================================
# Element-wise kernels (templates: one copy per function, no closure at run time)
# =====================================================================================================
# a[t] = f(a[t]) for the n numbers from t; ra holds the array and a[t], already read
def ew1_l(~f: @+a: F32 -> F32, nleft: Nat, +t: U32, ra: Array & F32) -> Array:
match nleft ra:
case 0n Tuple{a, v}:
a
case 1n+p Tuple{a, +v}:
ew1_l(~f, p, (t + 1 : U32), Array.get(F32, Array.set(F32, a, t, f(v)), (t + 1 : U32)))
# a[t] = f(a[t], b[t]): the result replaces a; b comes back unchanged
def ew2_l(~f: @+a: F32 -> @+b: F32 -> F32, nleft: Nat, +t: U32, ra: Array & F32, rb: Array & F32) -> TA.P2:
match nleft ra rb:
case 0n Tuple{a, v} Tuple{b, w}:
TA.P2{a, b}
case 1n+p Tuple{a, +v} Tuple{b, +w}:
ew2_l(~f, p, (t + 1 : U32), Array.get(F32, Array.set(F32, a, t, f(v, w)), (t + 1 : U32)), Array.get(F32, b, (t + 1 : U32)))
def Ew.map(~f: @+a: F32 -> F32, +r: Nat, +c: Nat, m: TA.Mat) -> TA.Mat:
match m:
case TA.Mat{d}:
TA.Mat{ew1_l(~f, Nat.mul(r, c), 0, Array.get(F32, d, 0))}
def ew2_fin(-r: Nat, -c: Nat, p: TA.P2) -> TA.MPair:
match p:
case TA.P2{a, b}:
TA.MPair{TA.Mat{a}, TA.Mat{b}}
# (f(a, b), b), element by element
def Ew.zip(~f: @+a: F32 -> @+b: F32 -> F32, +r: Nat, +c: Nat, a: TA.Mat, b: TA.Mat) -> TA.MPair:
match a b:
case TA.Mat{x} TA.Mat{y}:
ew2_fin(r, c, ew2_l(~f, Nat.mul(r, c), 0, Array.get(F32, x, 0), Array.get(F32, y, 0)))
def f32_add(+a: F32, +b: F32) -> F32:
(a + b : F32)
def f32_mul(+a: F32, +b: F32) -> F32:
(a * b : F32)
# (a + b, b)
def Mat.add(+r: Nat, +c: Nat, a: TA.Mat, b: TA.Mat) -> TA.MPair:
Ew.zip(~f32_add, r, c, a, b)
def zero_of(+x: F32) -> F32:
0.0
# the smallest d with 2^d >= n (TA.cap_depth's answer), by doubling a U32: log2(n) cheap steps, where cap_depth
# compares Nats one unit at a time at each doubling; f is fuel (32 doublings cover every U32)
def depth_go(f: Nat, ok: Bool, +n: U32, +p: U32, d: Nat) -> Nat:
match f ok:
case _ True{}:
d
case 0n False{}:
d
case 1n+g False{}:
depth_go(g, U32.is_le(n, (p + p : U32)), n, (p + p : U32), 1n+d)
def depth(+n: Nat) -> Nat:
depth_go(32n, U32.is_le(U32.from_nat(n), 1), U32.from_nat(n), 1, 0n)
# =====================================================================================================
# Optimizers: one pass over a parameter, its gradient and the two moment buffers; the gradient is zeroed
# =====================================================================================================
type Q3 is Type:
Q3{w: Array, g: Array, m: Array}
type Q4 is Type:
Q4{w: Array, g: Array, m: Array, v: Array}
type MatStep<-r: Nat, -c: Nat> is Type:
MatStep{w: TA.Mat, g: TA.Mat, st: OptState>}
# w <- w + (-lr)*g, as PyTorch's p.add_(g, alpha=-lr)
def sgd_l(nleft: Nat, +t: U32, +lr: F32, rw: Array & F32, rg: Array & F32) -> TA.P2:
match nleft rw rg:
case 0n Tuple{w, x} Tuple{g, y}:
TA.P2{w, g}
case 1n+p Tuple{w, +x} Tuple{g, +y}:
sgd_l(p, (t + 1 : U32), lr, Array.get(F32, Array.set(F32, w, t, (x + (F32.neg(lr) * y : F32) : F32)), (t + 1 : U32)), Array.get(F32, Array.set(F32, g, t, 0.0), (t + 1 : U32)))
# buf <- buf*mu + g; w <- w + (-lr)*buf, as PyTorch's SGD with momentum (no dampening, not Nesterov)
def mom_l(nleft: Nat, +t: U32, +lr: F32, +mu: F32, rw: Array & F32, rg: Array & F32, rm: Array & F32) -> Q3:
match nleft rw rg rm:
case 0n Tuple{w, x} Tuple{g, y} Tuple{m, b}:
Q3{w, g, m}
case 1n+p Tuple{w, +x} Tuple{g, +y} Tuple{m, +b}:
+nb = ((b * mu : F32) + y : F32)
+u = (t + 1 : U32)
mom_l(p, u, lr, mu, Array.get(F32, Array.set(F32, w, t, (x + (F32.neg(lr) * nb : F32) : F32)), u), Array.get(F32, Array.set(F32, g, t, 0.0), u), Array.get(F32, Array.set(F32, m, t, nb), u))
# the Adam family, in PyTorch's order of operations (torch.optim.adam._single_tensor_adam):
# g' = g + wd*w (Adam) or w' = w*(1 - lr*wd) (AdamW); m = m + (1-b1)*(g' - m) (lerp); v = v*b2 + (1-b2)*g'*g';
# w = w' + (-step*m) / (sqrt(v)/bc2 + eps)
def adam_grad(dec: Bool, +wd: F32, +w: F32, +g: F32) -> F32:
match dec:
case True{}:
g
case False{}:
(g + (w * wd : F32) : F32)
def adam_decay(dec: Bool, +lr: F32, +wd: F32, +w: F32) -> F32:
match dec:
case True{}:
(w * (1.0 - (lr * wd : F32) : F32) : F32)
case False{}:
w
# c1 = 1 - b1 and c2 = 1 - b2 are given as their own constants (0.1, 0.001), as PyTorch computes 1 - beta in float64
# before rounding: 1 - b2 taken in F32 from b2 = 0.999 (0.99900001287 in F32) is 1.3e-5 too small, and over 100 steps
# that alone put the tiny Llama 21x further from float64 than PyTorch's float32 (NOTES, 2026-10-18)
def adam_m(+c1: F32, +m: F32, +g: F32) -> F32:
(m + (c1 * (g - m : F32) : F32) : F32)
def adam_v(+b2: F32, +c2: F32, +v: F32, +g: F32) -> F32:
((v * b2 : F32) + ((c2 * g : F32) * g : F32) : F32)
def adam_w(+step: F32, +bc2: F32, +eps: F32, +w: F32, +m: F32, +v: F32) -> F32:
(w + ((F32.neg(step) * m : F32) / ((F32.sqrt(v) / bc2 : F32) + eps : F32) : F32) : F32)
def adam_l(nleft: Nat, +t: U32, +lr: F32, +c1: F32, +b2: F32, +c2: F32, +eps: F32, +wd: F32, +dec: Bool, +step: F32, +bc2: F32, rw: Array & F32, rg: Array & F32, rm: Array & F32, rv: Array & F32) -> Q4:
match nleft rw rg rm rv:
case 0n Tuple{w, x} Tuple{g, y} Tuple{m, a} Tuple{v, b}:
Q4{w, g, m, v}
case 1n+p Tuple{w, +x} Tuple{g, +y} Tuple{m, +a} Tuple{v, +b}:
+gg = adam_grad(dec, wd, x, y)
+nm = adam_m(c1, a, gg)
+nv = adam_v(b2, c2, b, gg)
+nw = adam_w(step, bc2, eps, adam_decay(dec, lr, wd, x), nm, nv)
+u = (t + 1 : U32)
adam_l(p, u, lr, c1, b2, c2, eps, wd, dec, step, bc2, Array.get(F32, Array.set(F32, w, t, nw), u), Array.get(F32, Array.set(F32, g, t, 0.0), u), Array.get(F32, Array.set(F32, m, t, nm), u), Array.get(F32, Array.set(F32, v, t, nv), u))
# ---- AdamW over packed BF16 moments (CAdamWBF16) ----
# The same F32 arithmetic as adam_l, element by element: each moment is read from its half of a word (BF16 -> F32 is
# exact), updated in F32, rounded to BF16 (to nearest, ties to even; a NaN becomes 0xFFFF, as torch/dtype.bend and
# PyTorch's CPU kernel do) and written back into its half; the weight update reads the stored, rounded moments, as
# PyTorch's AdamW does with BF16 state. The weights and the gradient stay F32.
def ph_f2u(x: F32) -> U32:
match x:
case F32{w}:
U32{w}
def ph_u2f(u: U32) -> F32:
match u:
case U32{w}:
F32{w}
def ph_pick(b: Bool, +x: U32, +y: U32) -> U32:
match b:
case True{}:
x
case False{}:
y
# F32 -> BF16 bits (dtype.bend's BF16.of_f32): add 0x7FFF plus the lowest kept bit, keep the top half; NaN -> 0xFFFF
def ph_of_bits(+u: U32) -> U32:
ph_pick(U32.is_gt((u .&. 2147483647 : U32), 2139095040), 65535, U32.shrn(((u + 32767 : U32) + (U32.shrn(u, 16n) .&. 1 : U32) : U32), 16n))
def ph_of(x: F32) -> U32:
ph_of_bits(ph_f2u(x))
# BF16 bits -> F32, exact
def ph_to(+h: U32) -> F32:
ph_u2f(U32.shln(h, 16n))
# the half of word w that element t uses (odd t: the high half), and w with that half replaced by h
def ph_half(odd: Bool, +w: U32) -> U32:
match odd:
case True{}:
U32.shrn(w, 16n)
case False{}:
(w .&. 65535 : U32)
def ph_put(odd: Bool, +w: U32, +h: U32) -> U32:
match odd:
case True{}:
((w .&. 65535 : U32) .|. U32.shln(h, 16n) : U32)
case False{}:
((w .&. 4294901760 : U32) .|. h : U32)
type PQ is Type:
PQ{w: Array, g: Array, m: Array, v: Array}
type PQV is Type:
PQV{w: Array, g: Array, m: Array, v: Array}
# m and v packed. rm and rv hold the word of element t (index t >> 1), read after the previous element's write.
def adamh_l(nleft: Nat, +t: U32, +lr: F32, +c1: F32, +b2: F32, +c2: F32, +eps: F32, +wd: F32, +dec: Bool, +step: F32, +bc2: F32, rw: Array & F32, rg: Array & F32, rm: Array & U32, rv: Array & U32) -> PQ:
match nleft rw rg rm rv:
case 0n Tuple{w, x} Tuple{g, y} Tuple{m, a} Tuple{v, b}:
PQ{w, g, m, v}
case 1n+p Tuple{w, +x} Tuple{g, +y} Tuple{m, +a} Tuple{v, +b}:
+odd = U32.is_eq((t .&. 1 : U32), 1)
+gg = adam_grad(dec, wd, x, y)
+hm = ph_of(adam_m(c1, ph_to(ph_half(odd, a)), gg))
+hv = ph_of(adam_v(b2, c2, ph_to(ph_half(odd, b)), gg))
+nw = adam_w(step, bc2, eps, adam_decay(dec, lr, wd, x), ph_to(hm), ph_to(hv))
+u = (t + 1 : U32)
+k = U32.shrn(t, 1n)
+ku = U32.shrn(u, 1n)
adamh_l(p, u, lr, c1, b2, c2, eps, wd, dec, step, bc2, Array.get(F32, Array.set(F32, w, t, nw), u), Array.get(F32, Array.set(F32, g, t, 0.0), u), Array.get(U32, Array.set(U32, m, k, ph_put(odd, a, hm)), ku), Array.get(U32, Array.set(U32, v, k, ph_put(odd, b, hv)), ku))
# m packed, v in F32 (one cell an element, as adam_l's)
def adamhv_l(nleft: Nat, +t: U32, +lr: F32, +c1: F32, +b2: F32, +c2: F32, +eps: F32, +wd: F32, +dec: Bool, +step: F32, +bc2: F32, rw: Array & F32, rg: Array & F32, rm: Array & U32, rv: Array & F32) -> PQV:
match nleft rw rg rm rv:
case 0n Tuple{w, x} Tuple{g, y} Tuple{m, a} Tuple{v, b}:
PQV{w, g, m, v}
case 1n+p Tuple{w, +x} Tuple{g, +y} Tuple{m, +a} Tuple{v, +b}:
+odd = U32.is_eq((t .&. 1 : U32), 1)
+gg = adam_grad(dec, wd, x, y)
+hm = ph_of(adam_m(c1, ph_to(ph_half(odd, a)), gg))
+nv = adam_v(b2, c2, b, gg)
+nw = adam_w(step, bc2, eps, adam_decay(dec, lr, wd, x), ph_to(hm), nv)
+u = (t + 1 : U32)
adamhv_l(p, u, lr, c1, b2, c2, eps, wd, dec, step, bc2, Array.get(F32, Array.set(F32, w, t, nw), u), Array.get(F32, Array.set(F32, g, t, 0.0), u), Array.get(U32, Array.set(U32, m, U32.shrn(t, 1n), ph_put(odd, a, hm)), U32.shrn(u, 1n)), Array.get(F32, Array.set(F32, v, t, nv), u))
# the words of n packed values: ceil(n / 2), in a block of the next power of two
def ph_words(+n: Nat) -> Array:
Array.new(U32, depth(Nat.div(Nat.add(n, 1n), 2n)), 0)
def ph_fin(-r: Nat, -c: Nat, +n: U32, q: PQ) -> MatStep:
match q:
case PQ{w, g, m, v}: MatStep{TA.Mat{w}, TA.Mat{g}, Packed{PLeaf{n, m, v}}}
def phv_fin(-r: Nat, -c: Nat, +n: U32, q: PQV) -> MatStep:
match q:
case PQV{w, g, m, v}: MatStep{TA.Mat{w}, TA.Mat{g}, Packed{PLeafV{n, m, v}}}
# one matrix's step on its leaf; anything else leaves the values untouched, as Opt.mat's fallback
def adamh_leaf(+r: Nat, +c: Nat, +o: Opt, wa: Array, ga: Array, t: PTree) -> MatStep:
match o t:
case Adam{lr, b1, b2, eps, wd, dec, step, bc2, c1, c2} PLeaf{+n, ma, va}:
ph_fin(r, c, n, adamh_l(Nat.mul(r, c), 0, lr, c1, b2, c2, eps, wd, dec, step, bc2, Array.get(F32, wa, 0), Array.get(F32, ga, 0), Array.get(U32, ma, 0), Array.get(U32, va, 0)))
case Adam{lr, b1, b2, eps, wd, dec, step, bc2, c1, c2} PLeafV{+n, ma, va}:
phv_fin(r, c, n, adamhv_l(Nat.mul(r, c), 0, lr, c1, b2, c2, eps, wd, dec, step, bc2, Array.get(F32, wa, 0), Array.get(F32, ga, 0), Array.get(U32, ma, 0), Array.get(F32, va, 0)))
case _ t:
MatStep{TA.Mat{wa}, TA.Mat{ga}, Packed{t}}
# the leaf of a matrix on its first step: zeros (BF16 0x0000 is +0.0)
def ph_new(+n: Nat, v16: Bool) -> PTree:
match v16:
case True{}:
PLeaf{U32.from_nat(n), ph_words(n), ph_words(n)}
case False{}:
PLeafV{U32.from_nat(n), ph_words(n), Array.new(F32, depth(n), 0.0)}
def adamh_mat(+r: Nat, +c: Nat, +o: Opt, wa: Array, ga: Array, t: PTree) -> MatStep:
match t:
case PNew{v16}:
adamh_leaf(r, c, o, wa, ga, ph_new(Nat.mul(r, c), v16))
case t:
adamh_leaf(r, c, o, wa, ga, t)
# One matrix step, with only the buffers this optimizer reads.
def Opt.sgd_fin(-r: Nat, -c: Nat, q: TA.P2) -> MatStep:
match q:
case TA.P2{w, g}: MatStep{TA.Mat{w}, TA.Mat{g}, NoMom{}}
def Opt.mom_fin(-r: Nat, -c: Nat, q: Q3) -> MatStep:
match q:
case Q3{w, g, m}: MatStep{TA.Mat{w}, TA.Mat{g}, OneMom{TA.Mat{m}}}
def Opt.fin(-r: Nat, -c: Nat, q: Q4) -> MatStep:
match q:
case Q4{w, g, m, v}: MatStep{TA.Mat{w}, TA.Mat{g}, TwoMom{TA.Mat{m}, TA.Mat{v}}}
# A mismatched state is initialized only at the training boundary; Opt.mat requires the matching variant.
# The fallback leaves the values untouched, so it cannot fabricate a moment buffer.
def Opt.mat(+r: Nat, +c: Nat, +o: Opt, w: TA.Mat, g: TA.Mat, st: OptState>) -> MatStep:
match o w g st:
case SGD{lr} TA.Mat{wd} TA.Mat{gd} _:
Opt.sgd_fin(r, c, sgd_l(Nat.mul(r, c), 0, lr, Array.get(F32, wd, 0), Array.get(F32, gd, 0)))
case Momentum{lr, mu} TA.Mat{wd} TA.Mat{gd} OneMom{TA.Mat{md}}:
Opt.mom_fin(r, c, mom_l(Nat.mul(r, c), 0, lr, mu, Array.get(F32, wd, 0), Array.get(F32, gd, 0), Array.get(F32, md, 0)))
case Adam{lr, b1, b2, eps, wd2, dec, step, bc2, c1, c2} TA.Mat{wd} TA.Mat{gd} TwoMom{TA.Mat{md}, TA.Mat{vd}}:
Opt.fin(r, c, adam_l(Nat.mul(r, c), 0, lr, c1, b2, c2, eps, wd2, dec, step, bc2, Array.get(F32, wd, 0), Array.get(F32, gd, 0), Array.get(F32, md, 0), Array.get(F32, vd, 0)))
case Adam{lr, b1, b2, eps, wd2, dec, step, bc2, c1, c2} TA.Mat{wd} TA.Mat{gd} Packed{t}:
adamh_mat(r, c, o, wd, gd, t)
case _ w g st:
MatStep{w, g, st}
# What the user picks; `Opt.at` turns it into the step's `Opt` from q1 = 1 - b1^t and q2 = 1 - b2^t (t = 1 on the
# first step). Adam's c1 and c2 are 1 - b1 and 1 - b2, written as their own constants (adam_m above). CAdamWBF16 is
# AdamW with its first moment (and its second, when v16) stored as packed BF16 (PTree); weights and gradient stay F32.
type OptCfg is Data:
CSGD{lr: F32}
CMomentum{lr: F32, mu: F32}
CAdam{lr: F32, b1: F32, b2: F32, eps: F32, wd: F32, c1: F32, c2: F32}
CAdamW{lr: F32, b1: F32, b2: F32, eps: F32, wd: F32, c1: F32, c2: F32}
CAdamWBF16{lr: F32, b1: F32, b2: F32, eps: F32, wd: F32, c1: F32, c2: F32, v16: Bool}
def Opt.at(+cfg: OptCfg, +q1: F32, +q2: F32) -> Opt:
match cfg:
case CSGD{lr}:
SGD{lr}
case CMomentum{lr, mu}:
Momentum{lr, mu}
case CAdam{lr, b1, b2, eps, wd, c1, c2}:
Adam{lr, b1, b2, eps, wd, False{}, (lr / q1 : F32), F32.sqrt(q2), c1, c2}
case CAdamW{lr, b1, b2, eps, wd, c1, c2}:
Adam{lr, b1, b2, eps, wd, True{}, (lr / q1 : F32), F32.sqrt(q2), c1, c2}
case CAdamWBF16{lr, b1, b2, eps, wd, c1, c2, v16}:
Adam{lr, b1, b2, eps, wd, True{}, (lr / q1 : F32), F32.sqrt(q2), c1, c2}
def OptCfg.b1(+cfg: OptCfg) -> F32:
match cfg:
case CAdam{lr, b1, b2, eps, wd, c1, c2}:
b1
case CAdamW{lr, b1, b2, eps, wd, c1, c2}:
b1
case CAdamWBF16{lr, b1, b2, eps, wd, c1, c2, v16}:
b1
case _:
0.0
def OptCfg.b2(+cfg: OptCfg) -> F32:
match cfg:
case CAdam{lr, b1, b2, eps, wd, c1, c2}:
b2
case CAdamW{lr, b1, b2, eps, wd, c1, c2}:
b2
case CAdamWBF16{lr, b1, b2, eps, wd, c1, c2, v16}:
b2
case _:
0.0
def OptCfg.c1(+cfg: OptCfg) -> F32:
match cfg:
case CAdam{lr, b1, b2, eps, wd, c1, c2}:
c1
case CAdamW{lr, b1, b2, eps, wd, c1, c2}:
c1
case CAdamWBF16{lr, b1, b2, eps, wd, c1, c2, v16}:
c1
case _:
0.0
def OptCfg.c2(+cfg: OptCfg) -> F32:
match cfg:
case CAdam{lr, b1, b2, eps, wd, c1, c2}:
c2
case CAdamW{lr, b1, b2, eps, wd, c1, c2}:
c2
case CAdamWBF16{lr, b1, b2, eps, wd, c1, c2, v16}:
c2
case _:
0.0
# c = 1 - b up to F32's rounding, with 0 < c <= 1 (PyTorch's 0 <= beta < 1). For b in [0, 1), 1 - b taken in F32 is
# within half an ulp of the exact value and c's own rounding adds at most as much, so a c written as 1 - b is always
# under 2^-23 from it, while a typo (0.01 for 0.001, c1 and c2 swapped) is far above. A NaN fails every comparison.
def beta_ok(+b: F32, +c: F32) -> Bool:
+d = ((1.0 - b : F32) - c : F32)
Bool.and(Bool.and((c > 0.0 : F32), (c <= 1.0 : F32)), ((d * d : F32) <= 0.0000000000000142108547152020037174224853515625 : F32))
# True unless an Adam configuration's c1, c2 disagree with its b1, b2. Train.new poisons the state of a configuration
# that fails (every loss after the first is NaN); a program checks it first with OptCfg.check to stop with a message.
def OptCfg.ok(+cfg: OptCfg) -> Bool:
match cfg:
case CAdam{lr, b1, b2, eps, wd, c1, c2}:
Bool.and(beta_ok(b1, c1), beta_ok(b2, c2))
case CAdamW{lr, b1, b2, eps, wd, c1, c2}:
Bool.and(beta_ok(b1, c1), beta_ok(b2, c2))
case CAdamWBF16{lr, b1, b2, eps, wd, c1, c2, v16}:
Bool.and(beta_ok(b1, c1), beta_ok(b2, c2))
case _:
True{}
def cfg_stop(ok: Bool) -> IO(Unit):
match ok:
case True{}:
IO.pure(Unit, Unit{})
case False{}:
IO.die(Unit, 1, "CAdam/CAdamW: c1, c2 do not match b1, b2 (c1 = 1 - b1, c2 = 1 - b2, e.g. 0.9, 0.999 with 0.1, 0.001)")
def OptCfg.check(+cfg: OptCfg) -> IO(Unit):
cfg_stop(OptCfg.ok(cfg))
# dump and load for a matrix: its r*c numbers, row by row
def mat_dump_fin(-r: Nat, -c: Nat, ml: TA.ML) -> PL>:
match ml:
case TA.ML{m, xs}:
PL{m, xs}
def Mat.dump(+r: Nat, +c: Nat, m: TA.Mat) -> PL>:
mat_dump_fin(r, c, TA.Mat.to_list(r, c, m))
def load_cells(left: Nat, +i: U32, +off: U32, rx: Array & F32, dst: Array) -> TA.P2:
match left rx:
case 0n Tuple{xs, v}: TA.P2{xs, dst}
case 1n+q Tuple{xs, v}:
load_cells(q, (i + 1 : U32), (off + 1 : U32), Array.get(F32, xs, (off + 1 : U32)), Array.set(F32, dst, i, v))
def mat_restore_fin(-r: Nat, -c: Nat, +off: U32, q: TA.P2) -> PA>:
match q:
case TA.P2{xs, dst}: PA{TA.Mat{dst}, xs, off}
def Mat.restore(+r: Nat, +c: Nat, m: TA.Mat, xs: Array, +off: U32) -> PA>:
match m:
case TA.Mat{dst}:
mat_restore_fin(r, c, (off + U32.from_nat(Nat.mul(r, c)) : U32), load_cells(Nat.mul(r, c), 0, off, Array.get(F32, xs, off), dst))
# load_cells' inverse: copies the matrix's cells i.. into xs from `off`; both arrays come back (the matrix's first)
def store_cells(left: Nat, +i: U32, +off: U32, rm: Array & F32, xs: Array) -> TA.P2:
match left rm:
case 0n Tuple{ma, v}: TA.P2{ma, xs}
case 1n+q Tuple{ma, v}:
store_cells(q, (i + 1 : U32), (off + 1 : U32), Array.get(F32, ma, (i + 1 : U32)), Array.set(F32, xs, off, v))
def mat_store_fin(-r: Nat, -c: Nat, +off: U32, q: TA.P2) -> PA>:
match q:
case TA.P2{ma, xs}: PA{TA.Mat{ma}, xs, off}
def Mat.store(+r: Nat, +c: Nat, m: TA.Mat, xs: Array, +off: U32) -> PA>:
match m:
case TA.Mat{ma}:
mat_store_fin(r, c, (off + U32.from_nat(Nat.mul(r, c)) : U32), store_cells(Nat.mul(r, c), 0, off, Array.get(F32, ma, 0), xs))
def pa_second(-A: Type, -B: Type, a: A, rb: PA) -> PA>:
match rb:
case PA{b, xs, off}: PA{Two{a, b}, xs, off}
def pl_pair(-A: Type, -B: Type, ra: PL, rb: PL) -> PL>:
match ra rb:
case PL{a, xa} PL{b, xb}:
PL{Two{a, b}, List.append(&2, F32, xa, xb)}
def pl_second(-A: Type, -B: Type, a: A, rb: PL) -> PL>:
match rb:
case PL{b, rest}:
PL{Two{a, b}, rest}
# =====================================================================================================
# Linear: y = x·Wᵀ + b, with W stored out x in (PyTorch's nn.Linear layout); saves its input
# =====================================================================================================
type Lin<-i: Nat, -o: Nat> is Type:
Lin{w: TA.Mat, b: TA.Mat<1n, o>}
def lin_f3(-n: Nat, -i: Nat, -o: Nat, w: TA.Mat, x: TA.Mat, r: TA.MBias) -> Fwd, TA.Mat, TA.Mat>:
match r:
case TA.MBias{y, b}:
Fwd{Lin{w, b}, y, x}
def lin_f2(+n: Nat, -i: Nat, +o: Nat, b: TA.Mat<1n, o>, r: TA.MMulNT) -> Fwd, TA.Mat, TA.Mat>:
match r:
case TA.MMulNT{x, w, z}:
lin_f3(n, i, o, w, x, TA.Mat.add_row(n, o, z, b))
def lin_fwd(+n: Nat, +i: Nat, +o: Nat, par: Nat, p: Lin, x: TA.Mat) -> Fwd, TA.Mat, TA.Mat>:
match p:
case Lin{w, b}:
lin_f2(n, i, o, b, TA.Mat.matmul_nt(n, i, o, par, x, w))
def lin_b4(-n: Nat, -i: Nat, -o: Nat, w: TA.Mat, b: TA.Mat<1n, o>, dx: TA.Mat, gw: TA.Mat, r: TA.MColSum) -> Bwd, TA.Mat>:
match r:
case TA.MColSum{dy, gb}:
Bwd{Lin{w, b}, dx, Lin{gw, gb}}
def lin_b3(+n: Nat, -i: Nat, +o: Nat, w: TA.Mat, b: TA.Mat<1n, o>, dx: TA.Mat, gb: TA.Mat<1n, o>, r: TA.MMulTN) -> Bwd, TA.Mat>:
match r:
case TA.MMulTN{dy, x, gw}:
lin_b4(n, i, o, w, b, dx, gw, TA.Mat.col_sums_acc(n, o, dy, gb))
def lin_b2(+n: Nat, +i: Nat, +o: Nat, par: Nat, b: TA.Mat<1n, o>, x: TA.Mat, g: Lin, r: TA.MMul) -> Bwd, TA.Mat>:
match g r:
case Lin{gw, gb} TA.MMul{dy, w, dx}:
lin_b3(n, i, o, w, b, dx, gb, TA.Mat.matmul_tn_acc(o, n, i, par, dy, x, gw))
# dX = dY·W, dW += dYᵀ·X, db += the column sums of dY; the two sums are added straight into the gradient (the
# accumulating products of bend-ml-tensor-array 0.1.10.0), with the bits of computing them apart and adding them
def lin_bwd(+n: Nat, +i: Nat, +o: Nat, +par: Nat, p: Lin, x: TA.Mat, dy: TA.Mat, g: Lin) -> Bwd, TA.Mat>:
match p:
case Lin{w, b}:
lin_b2(n, i, o, par, b, x, g, TA.Mat.matmul_precise(n, o, i, par, dy, w))
def pair_s3(-P1: Type, -P2: Type, r1: Step, r2: Step) -> Step>:
match r1 r2:
case Step{p1, g1, s1} Step{p2, g2, s2}:
Step{Two{p1, p2}, Two{g1, g2}, OptState.join(P1, P2, s1, s2)}
def lin_pair(-i: Nat, -o: Nat, p: Lin) -> Two, TA.Mat<1n, o>>:
match p:
case Lin{w, b}: Two{w, b}
def lin_unpair(-i: Nat, -o: Nat, p: Two, TA.Mat<1n, o>>) -> Lin:
match p:
case Two{w, b}: Lin{w, b}
def lin_s2(-i: Nat, -o: Nat, a: MatStep, c: MatStep<1n, o>) -> Step>:
match a c:
case MatStep{w, gw, sw} MatStep{b, gb, sb}:
Step{Lin{w, b}, Lin{gw, gb}, OptState.map(Two, TA.Mat<1n, o>>, Lin, OptState.join(TA.Mat, TA.Mat<1n, o>, sw, sb), x => lin_unpair(i, o, x), x => lin_unpair(i, o, x))}
def lin_step2(+i: Nat, +o: Nat, +op: Opt, p: Lin, g: Lin, st: Two>, OptState>>) -> Step>:
match p g st:
case Lin{w, b} Lin{gw, gb} Two{sw, sb}:
lin_s2(i, o, Opt.mat(o, i, op, w, gw, sw), Opt.mat(1n, o, op, b, gb, sb))
def lin_step(+i: Nat, +o: Nat, +op: Opt, p: Lin, g: Lin, st: OptState>) -> Step>:
lin_step2(i, o, op, p, g, OptState.split(TA.Mat, TA.Mat<1n, o>, OptState.map(Lin, Two, TA.Mat<1n, o>>, st, x => lin_pair(i, o, x), x => lin_pair(i, o, x))))
def lin_dump2(-i: Nat, -o: Nat, r: PL, TA.Mat<1n, o>>>) -> PL>:
match r:
case PL{Two{w, b}, xs}:
PL{Lin{w, b}, xs}
def lin_dump(+i: Nat, +o: Nat, p: Lin) -> PL>:
match p:
case Lin{w, b}:
lin_dump2(i, o, pl_pair(TA.Mat, TA.Mat<1n, o>, Mat.dump(o, i, w), Mat.dump(1n, o, b)))
def lin_load3(-i: Nat, -o: Nat, r: PA, TA.Mat<1n, o>>>) -> PA>:
match r:
case PA{Two{w, b}, xs, off}: PA{Lin{w, b}, xs, off}
def lin_load2(+i: Nat, +o: Nat, b: TA.Mat<1n, o>, r: PA>) -> PA>:
match r:
case PA{w, xs, off}:
lin_load3(i, o, pa_second(TA.Mat, TA.Mat<1n, o>, w, Mat.restore(1n, o, b, xs, off)))
def lin_load(+i: Nat, +o: Nat, p: Lin, xs: Array, off: U32) -> PA>:
match p:
case Lin{w, b}: lin_load2(i, o, b, Mat.restore(o, i, w, xs, off))
def lin_store2(+i: Nat, +o: Nat, b: TA.Mat<1n, o>, r: PA>) -> PA>:
match r:
case PA{w, xs, off}:
lin_load3(i, o, pa_second(TA.Mat, TA.Mat<1n, o>, w, Mat.store(1n, o, b, xs, off)))
def lin_store(+i: Nat, +o: Nat, p: Lin, xs: Array, off: U32) -> PA>:
match p:
case Lin{w, b}: lin_store2(i, o, b, Mat.store(o, i, w, xs, off))
def lin_zeros(+i: Nat, +o: Nat) -> Lin:
Lin{TA.Mat.zeros(o, i), TA.Mat.zeros(1n, o)}
# a linear layer from i to o features on batches of n rows; its products run in 2^par blocks of rows
def Linear(+n: Nat, +i: Nat, +o: Nat, +par: Nat) -> Layer, TA.Mat, TA.Mat, TA.Mat>:
Layer{p => x => lin_fwd(n, i, o, par, p, x), p => s => dy => g => lin_bwd(n, i, o, par, p, s, dy, g), op => p => g => st => lin_step(i, o, op, p, g, st), u => lin_zeros(i, o), p => lin_dump(i, o, p), p => xs => off => lin_load(i, o, p, xs, off), p => xs => off => lin_store(i, o, p, xs, off), u => U32.from_nat(Nat.mul(o, 1n+i))}
# the first layer of a model, whose input (the data) needs no gradient, as an input without requires_grad in PyTorch:
# the backward pass computes dW and db only, skipping dX = dY·W (a third of a linear layer's work), and returns zeros
# as dX. Use it only where nothing before the layer has parameters.
def linf_b3(+n: Nat, +i: Nat, +o: Nat, w: TA.Mat, b: TA.Mat<1n, o>, gb: TA.Mat<1n, o>, r: TA.MMulTN) -> Bwd, TA.Mat>:
match r:
case TA.MMulTN{dy, x, gw}:
lin_b4(n, i, o, w, b, TA.Mat.zeros(n, i), gw, TA.Mat.col_sums_acc(n, o, dy, gb))
def linf_bwd(+n: Nat, +i: Nat, +o: Nat, +par: Nat, p: Lin, x: TA.Mat, dy: TA.Mat, g: Lin) -> Bwd, TA.Mat>:
match p g:
case Lin{w, b} Lin{gw, gb}:
linf_b3(n, i, o, w, b, gb, TA.Mat.matmul_tn_acc(o, n, i, par, dy, x, gw))
def LinearFirst(+n: Nat, +i: Nat, +o: Nat, +par: Nat) -> Layer, TA.Mat, TA.Mat, TA.Mat>:
Layer{p => x => lin_fwd(n, i, o, par, p, x), p => s => dy => g => linf_bwd(n, i, o, par, p, s, dy, g), op => p => g => st => lin_step(i, o, op, p, g, st), u => lin_zeros(i, o), p => lin_dump(i, o, p), p => xs => off => lin_load(i, o, p, xs, off), p => xs => off => lin_store(i, o, p, xs, off), u => U32.from_nat(Nat.mul(o, 1n+i))}
# =====================================================================================================
# Layers without parameters
# =====================================================================================================
def pick(b: Bool, +x: F32, +y: F32) -> F32:
match b:
case True{}:
x
case False{}:
y
def no_step(-P: Type, +op: Opt, p: P, g: P, st: OptState) -> Step
:
Step{p, g, st}
# an element-wise activation that saves a copy of its output (relu, sigmoid, tanh: their derivative is a function of
# the output). `f` is the activation, `d(dy, y)` the gradient of its input.
def act_f2(-n: Nat, -c: Nat, r: TA.MM2) -> Fwd, TA.Mat>:
match r:
case TA.MM2{y, s}:
Fwd{Unit{}, y, s}
def act_b2(-n: Nat, -c: Nat, r: TA.MPair) -> Bwd>:
match r:
case TA.MPair{dx, y}:
Bwd{Unit{}, dx, Unit{}}
def ActOut(~f: @+a: F32 -> F32, ~d: @+a: F32 -> @+b: F32 -> F32, +n: Nat, +c: Nat) -> Layer, TA.Mat, TA.Mat>:
Layer{p => x => act_f2(n, c, TA.Mat.clone(n, c, Ew.map(~f, n, c, x))), p => s => dy => g => act_b2(n, c, Ew.zip(~d, n, c, dy, s)), op => p => g => st => no_step(Unit, op, p, g, st), u => Unit{}, p => PL{p, Nil{}}, p => xs => off => PA{p, xs, off}, p => xs => off => PA{p, xs, off}, u => 0}
# relu(x) = x unless x < 0 (so relu(NaN) = NaN and relu(-0) = -0); its gradient is +0 where the output is <= 0 and
# passes everywhere else, NaN included (PyTorch's threshold_backward)
def relu_v(+x: F32) -> F32:
pick(F32.is_lt(x, 0.0), 0.0, x)
def relu_d(+dy: F32, +y: F32) -> F32:
pick(F32.is_le(y, 0.0), 0.0, dy)
def ReLU(+n: Nat, +c: Nat) -> Layer, TA.Mat, TA.Mat>:
ActOut(~relu_v, ~relu_d, n, c)
# =====================================================================================================
# Seq: la then lb. Parameters, gradients, saved values and optimizer state are pairs of the two layers'.
# =====================================================================================================
def seq_f3(-P1: Type, -P2: Type, -Z: Type, -S1: Type, -S2: Type, p1: P1, s1: S1, r: Fwd) -> Fwd, Z, Two>:
match r:
case Fwd{p2, z, s2}:
Fwd{Two{p1, p2}, z, Two{s1, s2}}
def seq_f2(~P2: Type, ~Y: Type, ~Z: Type, ~S2: Type, ~lb: Layer, -P1: Type, -S1: Type, p2: P2, r: Fwd) -> Fwd, Z, Two>:
match r:
case Fwd{p1, y, s1}:
seq_f3(P1, P2, Z, S1, S2, p1, s1, Layer.fwd(P2, Y, Z, S2, lb, p2, y))
def seq_fwd(~P1: Type, ~P2: Type, ~X: Type, ~Y: Type, ~Z: Type, ~S1: Type, ~S2: Type, ~la: Layer, ~lb: Layer, p: Two, x: X) -> Fwd, Z, Two>:
match p:
case Two{p1, p2}:
seq_f2(~P2, ~Y, ~Z, ~S2, ~lb, P1, S1, p2, Layer.fwd(P1, X, Y, S1, la, p1, x))
def seq_b3(-P1: Type, -P2: Type, -X: Type, p2: P2, g2: P2, r: Bwd) -> Bwd, X>:
match r:
case Bwd{p1, dx, g1}:
Bwd{Two{p1, p2}, dx, Two{g1, g2}}
def seq_b2(~P1: Type, ~X: Type, ~Y: Type, ~S1: Type, ~la: Layer, -P2: Type, p1: P1, s1: S1, g1: P1, r: Bwd) -> Bwd, X>:
match r:
case Bwd{p2, dy, g2}:
seq_b3(P1, P2, X, p2, g2, Layer.bwd(P1, X, Y, S1, la, p1, s1, dy, g1))
def seq_bwd(~P1: Type, ~P2: Type, ~X: Type, ~Y: Type, ~Z: Type, ~S1: Type, ~S2: Type, ~la: Layer, ~lb: Layer, p: Two, s: Two, dz: Z, g: Two) -> Bwd, X>:
match p s g:
case Two{p1, p2} Two{s1, s2} Two{g1, g2}:
seq_b2(~P1, ~X, ~Y, ~S1, ~la, P2, p1, s1, g1, Layer.bwd(P2, Y, Z, S2, lb, p2, s2, dz, g2))
def seq_s3(-P1: Type, -P2: Type, r1: Step, r2: Step) -> Step>:
pair_s3(P1, P2, r1, r2)
def seq_s2(~P2: Type, ~Y: Type, ~Z: Type, ~S2: Type, ~lb: Layer, -P1: Type, +op: Opt, p2: P2, g2: P2, s2: OptState, r1: Step) -> Step>:
seq_s3(P1, P2, r1, Layer.step(P2, Y, Z, S2, lb, op, p2, g2, s2))
def seq_step2(~P1: Type, ~P2: Type, ~X: Type, ~Y: Type, ~Z: Type, ~S1: Type, ~S2: Type, ~la: Layer