diff --git a/docs/inkling2-attention-reference.md b/docs/inkling2-attention-reference.md new file mode 100644 index 00000000000..90aefe9763a --- /dev/null +++ b/docs/inkling2-attention-reference.md @@ -0,0 +1,375 @@ +# Inkling 2 attention: arithmetic reference + +This page writes down the arithmetic of Inkling 2's attention as #4125's kernels run it: the values, where each one +rounds to bf16, the order of every fp32 sum, what NaN and infinity do, and a bound for an fp32 result against float64. +Beside it are a float64 host model (`zig/src/families/inkling2/attn.zig`), the fp32 model in the kernels' order +(`zig/src/families/inkling2/attn_order.zig`), the bound as code (`attn_bound.zig`), an oracle +(`zig/src/families/inkling2/oracle/attn.py`) and host tests (`attn_test.zig`, `attn_bound_test.zig`, +`attn_order_hand_test.zig`). The kernels are the reference: the host model follows their source, it does not run them. +Every statement about a kernel's source carries `file:line` at commit `6dbb32f048a6` (#4125 as merged), in the files +`zig/kernels/cuda/inkling2/attention.cu` (`attention.cu`), `prompt_attention.cu`, +`zig/src/families/inkling2/kernels.zig` (`kernels.zig`), `zig/build/cuda_kernels.zig`, `zig/build/cuda_fatbin.zig` and +`zig/tests/cuda/contract_inkling2_attn_ref.zig` (`contract_inkling2_attn_ref.zig`). Statements about `transformers` +5.23.0 cite `models/inkling2/modeling_inkling2.py` as TF523:line. Nothing here claims that fp32 scores or P give the +same tokens as higher precision; token-level gates stay with the engine. + +## Scope + +The page covers `tf_ink2_rel_table`, `tf_ink2_attn`, `tf_ink2_attn_fold`, `tf_ink2_attn_prompt` and `tf_ink2_merge`: +from the q, the key and value caches, the rel taps and `rel_logits_proj`, the sink and the gate, as bf16 values, to the +bf16 output per row, query head and output index. A sliding layer keeps the 1024 newest keys, a global layer all keys. +Query head `h` reads key head `h / (heads / kv_heads)` (`attention.cu:159`, `:182`). The prompt kernel runs the same +arithmetic as the others (`prompt_attention.cu:1`; its fold at `:37-47` and its tile body at `:154-197` repeat +`attention.cu:130-140` and `:232-267`), with the differences that matter for a non-finite value listed under NaN and +infinity. Not in scope: the preparation before this step (q and k clips, the log-tau scaling of `q` and `rel` in global +layers, `attention.cu:46-89`), the output projection, and any change to a kernel: this page changes none. + +The kernels keep a ring cache (a key at position `p` sits in slot `p % ring`, `attention.cu:87`, `:207`; +`kernels.zig:41`, `:54-56` round the ring to a multiple of 64); the host model takes a dense cache, one place per +position, which gives the same values as a ring holding every position. Its shapes are the kernels' at `hd = 128`, +`d_rel = 16` and 1024 bias columns (`kernels.zig:5-7`) and, for tests, any smaller `hd` (a head is zero-padded to a +multiple of 16: zero products add nothing), `d_rel <= 32` and any number of columns. The fp32 model in the kernels' +order has no limit on the number of keys; the float64 model in `attn.zig` takes at most `most_keys = 8192` +(`attn.zig:8`). + +## Values and where they round + +Notation: `bf(x)` is round-to-nearest-even to bf16; every input (`q`, `k`, `v`, `rel`, `proj`, `sink`, `gate`) is a +bf16 value held exactly in fp32 (`attention.cu:25`). The product of two bf16 values is exact in fp32 (a 16-bit +significand) unless it overflows or lies below `2^-134` (a sufficient condition: a 16-bit product from `2^-134` up +ends on the fp32 grid `2^-149`; below it the product may be inexact), so only additions and the operations listed +round. For row at position `t`, key `s` and `dist = t - s`: + +| Step | Value | Where | Rounded to bf16 | +|---|---|---|---| +| bias table | `tab[d] = bf(sum_j rel[j] * proj[j][d])`, `j` in order | `attention.cu:116-120` | yes, once | +| dot | `D = sum_i q[i] * k[i]`, fp32 accumulator | `attention.cu:222-231` | no | +| score | `X = (D * scale + bf(tab[dist])) * kLog2e`, `scale = 1 / sqrtf(128)` in fp32; bias 0 where `dist >= 1024` | `attention.cu:14`, `:239-240`; `kernels.zig:180` | no | +| mask | `X = -inf` for a key that is not live: `t - s >= window`, `s > t`, or outside the step | `attention.cu:237`, `:240` | n/a | +| P | `P = bf(exp2f(X - mu))`, `mu` the running maximum of the step | `attention.cu:258` | yes, once | +| denominator | `l += P` over the keys of a lane, in fp32 | `attention.cu:259` | no | +| values | `acc += P * v`, fp32 accumulator | `attention.cu:268-279` | no | +| sink | `sk = bf(sink) * kLog2e`, its term `exp2f(sk - mf)` | `attention.cu:377-380` | no | +| output | `y = o * a / (ll * a + exp2f(sk - mf))`, `out = bf(y * (1 / (1 + expf(-gate))))` | `attention.cu:380-382` | yes, once | + +The kernels round to bf16 at exactly three points: the bias table, P and the output. The score (the dot, the scale, the +bias add and the log2e product), every denominator and every sum of values stay fp32. P is rounded once and that one +value serves the products and the denominator (`attention.cu:259` adds `bf(p)`). The sink is never rounded after its +input and enters the denominator only at the merge. The scores are in log2 units; `exp2f` of a difference of two +log2-unit values is `e^x` of the natural-log difference. + +## Order of every sum + +1. Bias table: the taps `j = 0 .. 15` add into one fp32 accumulator in order, then one rounding + (`attention.cu:118-120`). +2. Score: 8 chained `k16` mma, `k = 0 .. 7`, from a zero accumulator, fp32 accumulation + (`attention.cu:224-230`; the prompt kernel adds the same 8 in the same order, `prompt_attention.cu:147-152`). Then + `(sc * scale + bias) * kLog2e` (`attention.cu:240`). +3. A step is a run of 64-key tiles (aligned to multiples of 64, `attention.cu:205`) from a fresh start: `m = -inf`, + `l = 0`, `acc = 0` (`attention.cu:201-203`). A step is a 256-key chunk on a sliding layer and a 1024-key sub-chunk on + a global layer (`kernels.zig:12-15`, `attention.cu:127`, `:198`). Per tile: + - the maximum `mx` over the tile's live keys (order does not matter), `mn = fmaxf(m, mx)`, `mu = mn == -inf ? 0 : + mn`, `alpha = exp2f(m - mu)`, `m = mn`, `l *= alpha` (`attention.cu:232-252`); + - `P = bf(exp2f(sc - mu))` and `l += P`, a lane `t = lane & 3` holding the keys `8j + 2t + {0, 1}` of the tile for + `j = 0 .. 7` in that order (`attention.cu:255-261`); then `acc *= alpha` (`attention.cu:262-267`); + - the values: for `u = 0 .. 3` one mma over 16 keys onto `acc`, so four chained mma a tile in key order + (`attention.cu:268-279`). +4. End of a step: the four lanes' `l` add as `(l0 + l1) + (l2 + l3)` (`attention.cu:281-284`, two xor shuffles; every + lane ends with the same bits since addition commutes). +5. Global layers: the sub-chunks of a chunk of 16384 keys fold in order into one `(M, L, O)`, a row folding the + sub-chunks up to its own position (`attention.cu:285-295`, `:354-365`; `prompt_attention.cu:214-228`). A fold: + `mn = fmaxf(M, m)`, `a = exp2f(M - mn)`, `b = exp2f(m - mn)`, `L = __fadd_rn(__fmul_rn(L, a), __fmul_rn(l, b))` and + the same for each output index (`attention.cu:130-140`; `prompt_attention.cu:37-47`). +6. Merge: the chunks of the row, `c = lo / chunk .. pos / chunk`, fold in order into `(mm, ll, o)` with + `mn = fmaxf(mm, m)`, `a = exp2f(mm - mn)`, `b = exp2f(m - mn)`, `ll = ll * a + l * b`, `o = o * a + po * b` + (`attention.cu:351-376`). A sliding layer's chunk is one step; a global chunk is its folded sub-chunks. +7. Sink and output: `sk = bf(sink) * kLog2e`, `mf = fmaxf(mm, sk)`, `a = exp2f(mm - mf)`, + `y = o * a / (ll * a + exp2f(sk - mf))`, then `out = bf(y * (1 / (1 + expf(-gate))))` (`attention.cu:377-382`). + +A step starts from its own maximum, so a weight rounds to bf16 against its step's running maximum, not against the +maximum of earlier steps; the maximum of earlier steps meets it at the fold and merge, by `exp2f` and a product, which +do not round to bf16. + +What the order does not fix: +- The order of the 16 products and the accumulator inside one mma, and its rounding, are the hardware's and are not + written down in the repository. The products are exact (bf16 times bf16), so only the additions round. The host model + adds them in ascending order, each rounded to nearest and unfused: that is the model's choice. +- Where the source writes a plain `*` and `+`, nvcc may contract them into one fused operation: `attention.cu:119` + (`acc += r[j] * bf(...)`), `:240` (`sc * scale + bias`), `:252` with `:259` (`l *= alpha`, then `l += P`), + `:373-374` (`ll * a + l * b`, `o * a + po * b`), `:380` (`ll * a + exp2f(...)`), `:258` (the `* kLog2e` of `:240` + with the `- mu` in `exp2f(sc - mu)`), and the same lines of `prompt_attention.cu` (`:160`, `:172`, `:185` with + `:193`, `:192`); the list names the sites found and excludes no other. The kernels build with `-O3` and no other + floating-point flag (`zig/build/cuda_kernels.zig:161-162` at that commit, passed to nvcc at + `zig/build/cuda_fatbin.zig:24`), and NVIDIA's nvcc documentation (v13.5, options `--fmad`, `--prec-div`, `--ftz`) + gives the default of `--fmad` as "This option is set to true and nvcc enables the contraction of floating-point + multiplies and adds/subtracts into floating-point multiply-add operations". We state what the source and the build + line say and nothing about the code nvcc generated. The folds at `attention.cu:134`, `:139` use `__fmul_rn` and + `__fadd_rn` and do not contract. The host model rounds the product and the sum separately at every open site; the + bound below counts roundings and holds for either choice, a fused operation having fewer. +- Two assumptions the bound rests on and no host test can check: that the tensor-core adders do not flush subnormal + numbers to zero (a flush would be an absolute error of up to `2^-126` an operand, which the bound does not count), + and that `exp2f` and `expf` on the device keep to the 2 ULP of the hypotheses below; the host model uses Zig's `@exp2` + and `@exp`, so no host test can push that 2 ULP. +- Several streams: the host model takes a call as one stream, its blocks starting at the call's first row; the kernel + forms blocks per segment (`kernels.zig:59-70`, `attention.cu:150-151`). For one stream they are the same. +- Division and subnormal numbers: the nvcc documentation says of `--prec-div` "This option is set to true and nvcc + enables the IEEE round-to-nearest mode." and of `--ftz` "This option is set to false and nvcc preserves denormal + values."; the build line sets neither. + +## NaN and infinity + +What follows is what the order above gives, taking IEEE propagation in the mma and the shuffles as given; it is a +consequence of the source and the host model, not a measurement on a device. +- A key that is not live scores `-inf` after the mma (`attention.cu:240`), so a NaN or infinite `k` at a masked key + changes nothing; its weight is `exp2f(-inf - mu) = 0`. +- `fmaxf` passes a NaN by, so a NaN score does not stop the maximum, but `exp2f(NaN)` is NaN, `P` is NaN, and so are + `l` and every output index of that row and head. +- A value `v` that is not finite at a live key keeps its output index non-finite where its weight is positive + (`inf * P`); where the weight is 0, the product is `0 * inf = NaN`. +- Masked keys that a block loads: a block loads the keys `max(step start, tile_lo) .. min(step end, tile_hi)`, where + `tile_lo` and `tile_hi` come from the first and last of its 64 (row, head) pairs, and zero-fills the rest of a + 64-key tile (`attention.cu:155-157`, `:204`, `:211-216`). A key in that range that is masked for one row (`kp > pos` + or `kp < lo`, `attention.cu:237`) meets that row's `P = 0` in the mma, so a non-finite `v` there is `0 * inf = NaN` + in the row's output index of that column (the columns of `v` where it is not finite), whatever the row's own keys + hold, and the NaN stays through the rescales, folds and the merge. The other columns of the row stay finite. Which + rows are affected depends on the call: rows of one block at different positions see each other's later keys, and in + a sliding layer a row sees the keys between the block's first window start and its own. A call of a single row has + no such key (its range is its live keys). The host model reproduces this rule for the decode kernel (`block_pairs = + 64` in the model, `tile_pairs` at `kernels.zig:10`). The prompt kernel loads `b_lo .. min(b_hi, tile_hi)` and skips + a tile past a warp's last row (`prompt_attention.cu:84`, `:60-61`, `:143`), so its set differs; the host model does + not reproduce it. +- A NaN sink gives a NaN denominator. A `+inf` sink makes `mf` infinite, `a = exp2f(mm - inf) = 0` and + `exp2f(inf - inf)` NaN: every output of that row and head is NaN. A `-inf` sink contributes 0. +- An infinite gate saturates the sigmoid: `+inf` gives 1, `-inf` gives 0 (so `y * 0` is 0, or NaN if `y` is + infinite); a NaN gate gives NaN. + +## FP64 check and its bound + +The float64 model (`attend` with `f64` in `attn.zig`, at most `most_keys = 8192` keys) evaluates the formula of the +table above without any rounding: with `x = (q . k) hd^-1/2 + bias` in natural-log units, `y = sum_s e^(x_s - M) v_s / +(sum_s e^(x_s - M) + e^(sink - M))` and `out = y * sigmoid(gate)`; the bias is the exact `sum_j rel[j] * +proj[j][dist]` where `dist < rext`. The bound's own float64 value is `head` in `attn_bound.zig`: the same formula in +log2 units, run a second time beside `attend`, without `attend`'s limit of 8192 keys. The oracle evaluates the same +formula with Python's standard library (and `transformers`, see the fidelity check). The fp32 model in the kernels' +order (`attendOrder` in `attn_order.zig`) follows the order above, rounds the bias table, P and the output to bf16 and +nothing else, and is held to float64 by the bound below. + +Domain. The bound is claimed for a row and head whose inputs satisfy these conditions, checked in float64 from the +inputs (`head` in `attn_bound.zig` returns `error.AttnDomain` outside them): every `q`, `rel`, `sink` and `gate` of +the pair, every `proj` entry it reads and every `k` and `v` of the keys its block loads is finite; `gate >= -87` for +every output index; `A_s < 2^120` and `B_s < 2^120` (below) for every live key and `|sink| < 2^120`; `nk <= 2^20` and +`nk * vmax < 2^120`. They are sufficient and not sharp, and outside them the page claims nothing. Inside them `exp(L)` +can still overflow in float64: it does once `L` is above about 709.78, and `L` grows with the size of the scores, so +well inside the domain; there the bound is infinite and claims nothing, and `limit` returns `+inf` rather than `0 * +inf`. The test `bound: where exp(L) overflows the bound is infinite, never NaN` has `q = k = 2^50` and `v = 0`: it +prints `L 6.20e24`, the model gives 0 and the bound is infinite. The need is real: at `gate = -89` the kernel's +`expf(89)` is `inf` (`e^89` is about `4.5e38`, above the largest fp32 number), the sigmoid `1 / (1 + inf)` is 0 and +the output 0, where float64 has `1 * 2.2e-39`; and at `-88` the sigmoid `2^-126.96` is already subnormal and its +quotient has more than `u` of error (`e^87` is `2^125.5`, `e^88` is `2^126.96`, `e^88.5` is `2^127.68`). + +For one row and head with `nk` live keys, let `u = 2^-24`, `u_mma = 2^-23`, `u_bf = 2^-8`, `gamma(n) = n u / (1 - n u)` +and `lambda(a) = -ln(1 - a)`. The fp32 result `y` before the output's rounding satisfies, against the float64 result +`want`, + +`|y - want| <= (1 + 2^-20) * (mag * (exp(L) - 1) + sg * (nk + 1) * (2 vmax + 1) * 2^-130 * exp(L)) + 2^-149` + +`mag = sg * sum_s (P_s |v_s|)` with `P_s` the float64 softmax weights (the sink in the denominator), `sg` the sigmoid of +the gate and `vmax` the largest `|v|` of the row's keys. The terms of `L`, with `T` the tiles of a step (16 global, 4 +sliding), `S` the sub-chunks of a chunk (16 global, 0 sliding), `C` the chunks of the row (global: `floor(t / 16384) + +1`; sliding: `floor((window - 1) / 256) + 2`, the most a window spans), `M = ceil(hd / 16)` and `E = (T - 1) + S + C + +1`: + +`L = L_num + L_den + lambda(gamma(5)) + 4 lambda(u)` + +`L_num = eta + lambda(gamma(5)) + lambda(u_bf) + E lambda(gamma(6)) + 4 T lambda(17 u_mma) + (S + C) lambda(u)` + +`L_den = eta + lambda(gamma(5)) + lambda(u_bf) + E lambda(gamma(6)) + (16 T + 2 + S + C + 1) lambda(u)` + +`eta = ln 2 * (d + u ((Xmax - Xmin) + 2 d))`, `d` the largest absolute error of a score in log2 units, over the keys and +the sink, and `Xmax`, `Xmin` the largest and smallest log2-unit score (`log2(e)` times `x`) over the keys and the sink; + +`dX_s = log2(e) * (hd^-1/2 * A_s * G_dot + B_s * G_bias) + 2^-133`, `G_dot = (1 + 17 u_mma)^M (1 + gamma(6)) - 1`, +`G_bias = (1 + gamma(d_rel)) (1 + u_bf) (1 + gamma(3)) - 1`, `A_s = sum_i |q_i k_i|`, `B_s = sum_j |rel_j proj_j|` (0 +where the key gets no bias); for the sink `gamma(2) |log2(e) sink| + 2^-133`. The same `L` with the same counts is +what `attn_bound.zig` evaluates. Each term is a count of roundings in the order above: + +- The hypotheses. `exp2f` and `expf` are within 2 ULP of the correctly rounded result: NVIDIA's CUDA Programming Guide + (v13.5, section 5.6.7.2, Exponential Functions, Table 54) lists `expf(x)` and `exp2f(x)` with "2 ULP" for `float`. + Section 5.6.7 says "The maximum ULP error is stated as the maximum observed absolute value of the difference in ULPs + between the value returned by the function and a correctly rounded result of the corresponding precision obtained + according to the round-to-nearest ties-to-even rounding mode. The error bounds are derived from extensive, though + not exhaustive, testing. Therefore, they are not guaranteed." Within 2 ULP of the correctly rounded value, which + itself is within `u`, the result is within `gamma(5)` of the exact one. The second hypothesis: an mma's result + differs from the exact sum of its 17 operands (16 products and the accumulator) by at most `17 u_mma` times the sum + of their absolute values. It is the assumption of `zig/tests/cuda/contract_inkling2_attn_ref.zig`: `u_mma = 2^-23` + "a tensor-core add: its adders may truncate" (`:24`), the dot's error `abs * scale * 136 * u_mma` (`:158`, 136 is 8 + chained mma times 17) and `tiles * (4 * 17 + 1)` in `depth` (`:85`). It is not a guarantee of the hardware, and it + covers every order inside an mma. The other fp32 operations round to nearest (above), and a fused operation has + fewer roundings than the unfused pair, so every count holds for the open sites. +- `G_dot`: `M` chained mma (the dot's error against `A_s` is `(1 + 17 u_mma)^M - 1` by induction over the chain), and + six roundings of the score: the scale constant (`1 / sqrtf(128)` is two roundings of `hd^-1/2`), the product with it, + the add of the bias, the constant `kLog2e` (one rounding of `log2(e)`) and its product. +- `G_bias`: the fp32 tap sum (`d_rel` adds), the bf16 rounding of the table (`u_bf`), and three roundings after it + (the add, `kLog2e`, the product). The table's bf16 rounding is a term of its own and the largest of the score. +- `eta`: the score's error `d` and the roundings of the differences `X - mu`, of every `exp2f` argument of a rescale + and of `sk - mf`. Each is at most `u` of its difference; all differences of a weight are `<= 0` and add up to + `Xmax' - X_s`, so a weight's exponent error is at most `u (Xmax - Xmin + 2 d)`. In natural units, a factor of `ln 2`. +- `lambda(gamma(5))`, `lambda(u_bf)`: the `exp2f` of P, and P's bf16 rounding (`attention.cu:258`): the main term of + `L`. It acts on the numerator and, because `l` sums the same rounded P (`attention.cu:259`), on the denominator. +- `E lambda(gamma(6))`: a weight meets at most `T - 1` rescales of later tiles, `S` folds of a sub-chunk, `C` merges of + a chunk and the sink's `a`, each an `exp2f` (`gamma(5)`) and a product (`u`). +- `4 T lambda(17 u_mma)`: the values' mma chain, four mma a tile over `T` tiles. `(S + C) lambda(u)`: the add of each + fold and merge. +- `16 T + 2 + S + C + 1`: the denominator's adds: 16 a tile in a lane, two combining the lanes, one for each fold or + merge (`S + C`) and the add of the sink's term. +- `lambda(gamma(5)) + 4 lambda(u)`: the sigmoid's `expf`, its add and its quotient, the quotient `o a / den` and the + final product. +- Domain: under its conditions no fp32 operation of the order overflows. A dot, its scaled and biased value and the + product with `log2(e)` stay below `2^123`; every `exp2f` has an argument `<= 0` and a result `<= 1 + gamma(5)`; a + sum of `P v` stays below `2^121`; the denominator is at least `exp(-L)` (the largest weight is 1), so `y` stays + below `2^122`; and `expf(-gate) <= e^87 < 2^126`, so `1 + expf(-gate)` stays below `2^126` and the sigmoid is a + normal number. +- The last bf16 rounding of the output is not in `L`: the bound on the bf16 result is the fp32 bound `b` plus + `u_bf (|want| + b) + 2^-134`. +- Subnormals: below `2^-126` an operation is within `2^-150` of its exact result, `exp2f` within `2^-148`, and an add + is exact; bf16's half step there is `2^-134`. A weight is off by at most `2^-133` in absolute terms, the largest + weight is `exp2f(0) = 1` so the denominator is at least `exp(-L)`, and `2^-130 (nk + 1) (2 vmax + 1)` covers the + numerator, the denominator and the absolute errors of the last operations. In `dX_s` the bias table rounds to bf16, + and where its sum is below `2^-126` that error is absolute, up to `2^-134` (half a bf16 step there), not `u_bf B_s`; + times `log2(e)` it is below `2^-133.4`, as is the sink's product with `kLog2e`, and the other subnormal contributions + (products below the fp32 grid, each at most `2^-150`) lie below `2^-140`; so `2^-133` covers the score's. The last + product `y * sigmoid` rounds absolutely, by up to `2^-150`, where its result is below `2^-126`; the term `2^-149` + after the factor `1 + 2^-20` covers that, which `sg` scales away in the other floor term. +- The factors multiply: `lambda(a)` bounds `|ln(1 + d)|` for `|d| <= a`, so `L` bounds the logarithm of each term's + relative error and `exp(L) - 1` the error of the ratio `N / D`. +- `1 + 2^-20` covers float64, in `want` and in evaluating the bound: its sums of at most `2^20` terms round at `2^-53` + each, below `2^-28` of `mag`, while `exp(L) - 1 >= 2^-8`. + +The bound is derived from these counts and the two hypotheses, not fitted to runs. It makes no claim about bit +equality with another implementation. + +The host tests evaluate the bound (`attn_bound_test.zig`, `attn_bound.zig`): the fp32 model in the kernels' order +against the float64 formula, before and after the output's rounding, on the oracle's fixture; on rows across the seams +(64, 1024 and 16384 keys, global, with the maximum rising across each; a sliding window with chunks at 256; three rows +of a block; the checkpoint's `hd = 128`, 16 taps, 1024 columns); and on a case for each term: cancellation in the +values, a large gap between scores, P nearest a bf16 half step, a dominant sink, P below the normal range, an output +below the normal range (where the last product's absolute error exceeds the sigmoid-scaled floor term), and the ends +of the domain. Every element is inside its bound, and over these cases the worst error over bound is 0.16 before and +0.26 after the output's rounding; the tests print each case. A further case aims at the table's rounding: one key's +table sum rounds up (the weak key) and the dominant key's rounds down (`bound: a table rounded up at the weak key and +down at the dominant one`). It prints 9.640e-1 before and 9.547e-1 after the output's rounding, so the bound is close +to tight for that rounding and the 0.16 and 0.26 are no margin. + +Each rounding point and each seam also has a test whose expected value is written by hand in float64 and does not come +from the model (`attn_order_hand_test.zig`): the table's tie to even, P rounded once in the products and in the +denominator, the output after the gate, the dot and scale in fp32, the sink at the merge unrounded, the window, the +bias distance, the head group, and, for the seams, sums that only the stated grouping gets right: `2^24`, ones and +`-2^24` put in different tiles, sub-chunks, sliding chunks and global chunks give 0 or 2 depending on whether the ones +meet before or after the big values. + +## Fidelity against Transformers eager (reported) + +`transformers` 5.23.0 runs this attention at eager points that are not the kernels'. In the eager path (TF523:368-399 +with the relative logits of TF523:165-188) the bf16 tensors round after the dot (TF523:383), the scale (TF523:383, +:414), the bias table (TF523:184), the biased logit (TF523:385), the normalised weights (TF523:391-392), the value sum +(TF523:396) and the gated output (TF523:496, :628): seven roundings, against the kernels' three, and the softmax +divides before P is rounded. The kernels do not follow that arithmetic and this page does not ask them to; the +comparison is a reported number, not a gate. The oracle (`zig/src/families/inkling2/oracle/attn.py`) runs +`Inkling2RelativeLogits` and `eager_attention_forward` on the same bf16 inputs as the fixture, builds the causal and +sliding mask (`masking_utils.py` of the same release, :76, :95 and :630, as TF523:1290-1291 builds it) and the gate +from the source, and the fixture keeps both its float64 result and its bf16 bits. + +- The eager-point fp32 model (`attend` with `f32` and `rounded`, in `attn.zig`, the seven roundings above with a fixed + fp32 order of its own) gives the bf16 bits of the `transformers` path on the fixture: 4800 of 4800 values equal, + none a step apart. A libm with another last bit in `exp` may flip a rounding; the test allows one value in a + thousand one step apart. +- The fp32 model in the kernels' order (`attendOrder`) against the same bits: 2118 of 4800 equal, 1689 one step apart + and 993 further; the largest difference, as `|got - transformers| / (|transformers| + top)` with `top` the head's + largest `|transformers|`, is 6.1e-2. This is the arithmetic difference between the kernels' three roundings and the + eager path's seven, on the six fixture cases (tiny-random `inkling-2`, the checkpoint's shapes among them). +- The float64 model equals the oracle's float64 values within `(|y| + top) 2^-40` per element, `top` the head's + largest `|y|`. +- The fixture `zig/src/families/inkling2/fixtures/attn_tiny.bin` (SHA-256 + `96aadd48918923fe5a4d165740bc337340476aeeacc5c3ee63600d8dcd7d0cde`) comes from `python3 + zig/src/families/inkling2/oracle/attn.py write `, run on a local copy of + `tiny-random/inkling-2@0a57c72e4e5b68aafe1d983dbb62980344a5fcd7` (`model.safetensors` SHA-256 + `ac7f0eaa84e50b53c4afce3ea7eecdc49ccca21bd467edb16f3d052d9099a3de`) with `transformers` 5.23.0 and `torch` + 2.15.0+cpu (`attn.py:13-16`). + +## Falsification + +Each single change below was made alone to the host code (the fp32 model in `attn_order.zig`, the window to `first` in +`attn.zig`, and the bound's terms and domain checks in `attn_bound.zig`), `zig build test-inkling2-host` was run on +it, and the change was reverted. The test that turns red is named (test names as in `attn_order_hand_test.zig` and +`attn_bound_test.zig`; where more than one goes red, the count is given). The unchanged tree is green: 81 tests passed +and 4 skipped. + +| Single change to the host model | A test that turns red (N red in all) | +|---|---| +| table: no bf16 rounding | `table: bf16 once, a tie to even` (2 red) | +| dot rounded to bf16 (as eager) | `score: the dot and the scale stay fp32` (2 red) | +| scaled dot rounded to bf16 | `score: the dot and the scale stay fp32` (2 red) | +| logit rounded to bf16 | `sub-chunk seam: starts from its own maximum` (5 red) | +| scale missing | `score: the dot and the scale stay fp32` (6 red) | +| scale 1/hd | `score: the dot and the scale stay fp32` (5 red) | +| bias not added | `bias: distances under rext only` (8 red) | +| P not rounded (numerator and denominator) | `P: bf16 once, in the products and the denominator` (7 red) | +| P rounded for P.V, denominator sums unrounded P | `P: bf16 once, in the products and the denominator` (8 red) | +| P.V sums unrounded P, denominator rounded | `P: bf16 once, in the products and the denominator` (7 red) | +| output not rounded | `output: bf16 once, after the gate` | +| output rounded twice (before the gate too) | `P: bf16 once, in the products and the denominator` (10 red) | +| value sum rounded to bf16 (as eager) | `bias: distances under rext only` (4 red) | +| sink term rounded to bf16 | `sink: at the merge, unrounded` (2 red) | +| sink at half its weight | `sink: at the merge, unrounded` (3 red) | +| sink left out | `sink: at the merge, unrounded` (4 red) | +| maximum at the merge without the sink | `NaN: live keys and the sink` | +| tile of 32 keys | `tile: a weak key rounds against a strong one after it` | +| tile of 128 keys | `tile seam: P rounds against its tile's maximum, then rescales` | +| sub-chunk of 512 keys | `sub-chunk: summed alone, then folded` | +| sub-chunk of 2048 keys | `sub-chunk seam: starts from its own maximum`; `sub-chunk: summed alone, then folded` (3 red) | +| sliding chunk of 128 keys | `sliding chunk: summed alone, then merged` | +| sliding chunk of 512 keys | `chunk seam at 256: sliding starts afresh, global does not`; `sliding chunk: summed alone, then merged` (3 red) | +| global chunk of 8192 keys | `global chunk: its sub-chunks fold first` | +| global chunk of 32768 keys | `global chunk: its sub-chunks fold first`; `global chunks: merge in order` (2 red) | +| no rescale between tiles (alpha 1) | `tile seam: P rounds against its tile's maximum, then rescales` (9 red) | +| denominator not rescaled between tiles | `tile seam: P rounds against its tile's maximum, then rescales` (9 red) | +| values not rescaled between tiles | `tile seam: P rounds against its tile's maximum, then rescales` (5 red) | +| fold scales swapped (old by the new part's factor) | `tile seam: P rounds against its tile's maximum, then rescales` (36 red) | +| chunks merged in reverse order | `global chunks: merge in order`; `sliding chunks: merge in order` (2 red) | +| masked key scored 0 instead of -inf | `` window: exactly `window` keys `` (29 red) | +| block loads only the row's own keys (NaN rule) | `NaN: a non-finite V at a masked key a block loads` | +| block starts at the row's own window (NaN rule) | `NaN: below the window, a key another row's block loads` | +| mu without the all-masked guard | `bound: sliding seams` | +| gate sigmoid with the wrong sign | `NaN: a masked key no block loads is harmless`; `NaN: a non-finite V at a masked key a block loads` (34 red) | +| gate missing | `gate: its sigmoid` (11 red) | +| key limit of 8192 kept in the fp32 model in the kernels' order | `shapes: over 8192 keys is accepted, a refusal stays a refusal` (4 red) | +| block of one pair (NaN rule) | `NaN: a non-finite V at a masked key a block loads`; `NaN: below the window, a key another row's block loads` (2 red) | +| window one key too wide | `` window: exactly `window` keys `` (6 red) | +| bias one distance too far | (the table read runs past the last column and `index out of bounds` aborts the test binary: 32 tests terminate, none names a rounding) | +| bias one distance too short | `bias: distances under rext only` (3 red) | +| wrong key-head group (h mod kv_heads) | `group: the group's key head` (3 red) | +| table taps summed in reverse | `table: taps in order` | +| dot summed in reverse (all dims, one chain) | `score: one chain across k16 blocks` | +| bound: no absolute term 2^-149 for the last product | `bound: an output below the normal range` | +| domain: gate bound not checked | `bound: the domain ends where fp32 overflows or the sigmoid leaves the normal range` | +| domain: dot magnitude not checked | `bound: the domain ends where fp32 overflows or the sigmoid leaves the normal range` | +| domain: live keys not limited to 2^20 | `bound: the domain ends at 2^20 live keys` | +| bound: not infinite where exp(L) overflows | `bound: where exp(L) overflows the bound is infinite, never NaN` | +| domain: infinite value at a loaded key not checked | `bound: the domain ends where fp32 overflows or the sigmoid leaves the normal range` | + +These changes leave the host tests green. They are the model's choices or equivalent forms, and their effect is one +rounding, below what a float64 hand value or the bound can separate: +- fusing the score `dot * scale + bias` into one `fma` (an open site above), or the fold's product and add (the source + pins the fold with `__fmul_rn` and `__fadd_rn`, so the model's separate roundings follow the source, not a test); +- the order of the products a tile's `P.V` adds: the model adds them in one fp32 chain, so descending key order over + the 64 keys reverses the four chained mma and the products inside each; no test pins it (the order inside an mma is + the hardware's, the order of the four is stated above); and the dot's k16 blocks summed apart and then added in + order; +- which of the four lanes holds a key of `l` and how the four lane sums add (one lane, or a chain instead of + `(l0 + l1) + (l2 + l3)`): one rounding in `l`; +- the sink folded in before the chunks instead of at the merge: the same operations in another association; +- the exponent in natural-log units with `exp` instead of log2 units with `exp2f`: the same values except where the + other fp32 rounding of the score `X` moves a P across a bf16 rounding boundary; the tests stay green with it, so + none of them pins it; +- the bound's score floor at `2^-140` instead of `2^-133`: the error it covers is below `2^-133`, while `L` is at least + `lambda(u_bf)`, about `2^-8`, so no input can tell the two apart; the value rests on the derivation above. diff --git a/zig/src/families/inkling2/attn.zig b/zig/src/families/inkling2/attn.zig new file mode 100644 index 00000000000..f6786ae8405 --- /dev/null +++ b/zig/src/families/inkling2/attn.zig @@ -0,0 +1,324 @@ +//! Inkling 2's attention on the host: the formula in float64, and in fp32 at Transformers' eager rounding points. +const std = @import("std"); +const bf16_round = @import("bf16_round"); + +/// The widest head, the most bias states and the most keys of a row for `attend`'s fp32 model. +pub const most_hd = 128; +pub const most_rel = 32; +pub const most_keys = 8192; + +/// `rows` rows from position `pos0` over the cache's positions 0 to the last row's; `window` 0: all keys. +pub const Shape = struct { rows: usize, pos0: usize, heads: usize, kv_heads: usize, hd: usize, drel: usize, rext: usize, window: usize }; + +/// The bf16 inputs as fp32: q, gate [rows, heads, hd]; k, v [pos0 + rows, kv_heads, hd]; rel; proj [drel, rext]; sink. +pub const Inputs = struct { q: []const f32, k: []const f32, v: []const f32, rel: []const f32, proj: []const f32, sink: []const f32, gate: []const f32 }; + +pub const Error = error{AttnShape}; + +/// Refuses empty sizes, ungrouped heads, sizes past the limits above, over 65535 rows and arrays of other lengths. +pub fn shaped(s: Shape, in: Inputs, out_len: usize) Error!void { + return shapedWithin(s, in, out_len, most_keys); +} + +/// `shaped` with `keys` as the most keys of a row. +pub fn shapedWithin(s: Shape, in: Inputs, out_len: usize, keys: usize) Error!void { + if (s.heads == 0 or s.kv_heads == 0 or s.heads % s.kv_heads != 0) return error.AttnShape; + if (s.hd == 0 or s.hd > most_hd or s.drel == 0 or s.drel > most_rel or s.rext == 0) return error.AttnShape; + if (s.rows == 0 or s.rows > 65535) return error.AttnShape; + const pos = s.pos0 + s.rows; + if ((if (s.window == 0) pos else s.window) > keys) return error.AttnShape; + const out = s.rows * s.heads * s.hd; + const cache = pos * s.kv_heads * s.hd; + if (out_len != out or in.q.len != out or in.gate.len != out or in.k.len != cache or in.v.len != cache) return error.AttnShape; + if (in.rel.len != s.rows * s.heads * s.drel or in.proj.len != s.drel * s.rext or in.sink.len != s.rows * s.heads) return error.AttnShape; +} + +/// The first key a row at position `t` attends. +pub fn first(s: Shape, t: usize) usize { + return if (s.window > 0 and t + 1 > s.window) t + 1 - s.window else 0; +} + +/// The reference's scale, head_dim ** -0.5, for the arithmetic type T. +pub fn scaleOf(comptime T: type, hd: usize) T { + return @floatCast(std.math.pow(f64, @floatFromInt(hd), -0.5)); +} + +/// A warp's xor-tree sum of its 32 lanes: every lane ends with the same bits. +fn tree(lane: *[32]f32) f32 { + var o: usize = 16; + while (o > 0) : (o >>= 1) { + const before = lane.*; + for (lane, 0..) |*l, i| l.* = before[i] + before[i ^ o]; + } + return lane[0]; +} + +fn rnd(rounded: bool, x: f32) f32 { + return if (rounded) bf16_round.round32(x) else x; +} + +/// The formula in float64 (T = f64), or fp32 in the eager model's order of sums, rounded as Transformers if `rounded`. +pub fn attend(comptime T: type, rounded: bool, s: Shape, in: Inputs, out: []T) Error!void { + try shaped(s, in, out.len); + for (0..s.rows) |row| for (0..s.heads) |h| head(T, rounded, s, in, row, h, out[(row * s.heads + h) * s.hd ..][0..s.hd]); +} + +fn head(comptime T: type, rounded: bool, s: Shape, in: Inputs, row: usize, h: usize, out: []T) void { + const t = s.pos0 + row; + const lo = first(s, t); + const nk = t - lo + 1; + const kh = h / (s.heads / s.kv_heads); + const hrow = row * s.heads + h; + const q = in.q[hrow * s.hd ..][0..s.hd]; + const rel = in.rel[hrow * s.drel ..][0..s.drel]; + var lg: [most_keys]T = undefined; + for (0..nk) |j| { + const key = lo + j; + const k = in.k[(key * s.kv_heads + kh) * s.hd ..][0..s.hd]; + var l: T = scaledDot(T, rounded, q, k, scaleOf(T, s.hd)); + const dist = t - key; + if (dist < s.rext) l = biased(T, rounded, l, rel, in.proj, s.rext, dist); + lg[j] = l; + } + const sink: T = in.sink[hrow]; + var m: T = sink; + for (lg[0..nk]) |l| m = @max(m, l); // a NaN logit is passed by, as fmaxf does; its exp below makes the sum NaN + var z: T = softmaxSum(T, lg[0..nk], m); + z += @exp(sink - m); + for (lg[0..nk]) |*e| e.* = if (T == f32) rnd(rounded, e.* / z) else e.* / z; + for (out, 0..) |*o, d| { + var acc: T = 0; + for (0..nk) |j| acc = @mulAdd(T, lg[j], in.v[((lo + j) * s.kv_heads + kh) * s.hd + d], acc); + const g: T = in.gate[hrow * s.hd + d]; + const y: T = if (T == f32) rnd(rounded, acc) else acc; + const gated = y * (1 / (1 + @exp(-g))); + o.* = if (T == f32) rnd(rounded, gated) else gated; + } +} + +/// (q . k) * scale: float64 in a chain, or fp32 as the eager model adds: lane l over l, l + 32, ..., then the tree. +fn scaledDot(comptime T: type, rounded: bool, q: []const f32, k: []const f32, scale: T) T { + if (T == f64) { + var sum: f64 = 0; + for (q, k) |a, b| sum += @as(f64, a) * @as(f64, b); + return sum * scale; + } + var lane: [32]f32 = @splat(0); + for (&lane, 0..) |*l, i| { + var j = i; + while (j < q.len) : (j += 32) l.* = @mulAdd(f32, q[j], k[j], l.*); + } + return rnd(rounded, rnd(rounded, tree(&lane)) * scale); +} + +/// l plus the bias r[dist] = rel . proj[:, dist]: float64, or fp32 with r a product per lane and the tree. +fn biased(comptime T: type, rounded: bool, l: T, rel: []const f32, proj: []const f32, rext: usize, dist: usize) T { + if (T == f64) { + var r: f64 = 0; + for (rel, 0..) |a, j| r += @as(f64, a) * @as(f64, proj[j * rext + dist]); + return l + r; + } + var lane: [32]f32 = @splat(0); + for (rel, 0..) |a, j| lane[j] = a * proj[j * rext + dist]; + return rnd(rounded, l + rnd(rounded, tree(&lane))); +} + +/// The keys' exp(l - m), left in `lg`, and their sum: float64 in a chain; fp32 as the block adds (threads, warps). +fn softmaxSum(comptime T: type, lg: []T, m: T) T { + if (T == f64) { + var sum: f64 = 0; + for (lg) |*l| { + l.* = @exp(l.* - m); + sum += l.*; + } + return sum; + } + var thread: [128]f32 = @splat(0); + for (lg, 0..) |*l, j| { + l.* = @exp(l.* - m); + thread[j % 128] += l.*; + } + var warp: [4]f32 = undefined; + for (&warp, 0..) |*w, i| { + var lane: [32]f32 = thread[32 * i ..][0..32].*; + w.* = tree(&lane); + } + return (warp[0] + warp[1]) + (warp[2] + warp[3]); +} + +test "attend: one key and no bias leave the softmax a sink and a key; the gate scales the output" { + const s: Shape = .{ .rows = 1, .pos0 = 0, .heads = 1, .kv_heads = 1, .hd = 2, .drel = 1, .rext = 4, .window = 0 }; + const in: Inputs = .{ .q = &.{ 1, 2 }, .k = &.{ 3, 4 }, .v = &.{ 10, 20 }, .rel = &.{0}, .proj = &.{ 0, 0, 0, 0 }, .sink = &.{0}, .gate = &.{ 0, 0 } }; + var y: [2]f64 = undefined; + try attend(f64, false, s, in, &y); + // logit = (1 * 3 + 2 * 4) / sqrt(2); p = e^l / (e^l + e^0); sigmoid(0) = 1/2 + const l: f64 = 11.0 / @sqrt(2.0); + const p = @exp(l) / (@exp(l) + 1); + try std.testing.expectApproxEqAbs(p * 10 / 2, y[0], 1e-12); + try std.testing.expectApproxEqAbs(p * 20 / 2, y[1], 1e-12); +} + +test "attend: the bias adds for distances under rext and not at or past it" { + // two keys (positions 0 and 1) for the row at position 1: distances 1 and 0; rext 1 gives a bias to distance 0 only + const s: Shape = .{ .rows = 1, .pos0 = 1, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 1, .window = 0 }; + const in: Inputs = .{ .q = &.{0}, .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .rel = &.{1}, .proj = &.{3}, .sink = &.{-100}, .gate = &.{100} }; + var y: [1]f64 = undefined; + try attend(f64, false, s, in, &y); + // logits: 0 for position 0 (distance 1: no bias), 3 for position 1 (distance 0); sink and gate do not matter + const p1 = @exp(@as(f64, 3)) / (@exp(@as(f64, 3)) + 1); + try std.testing.expectApproxEqAbs((1 - p1) * 1 + p1 * 2, y[0], 1e-12); +} + +test "attend: the window drops keys older than its width; a row at the window's edge keeps exactly `window` keys" { + const s: Shape = .{ .rows = 1, .pos0 = 3, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 8, .window = 2 }; + // keys at positions 0..3, all logits 0: the row at 3 keeps positions 2 and 3, values 30 and 40 + const zeros: [8]f32 = @splat(0); + const in: Inputs = .{ .q = &.{0}, .k = &.{ 0, 0, 0, 0 }, .v = &.{ 10, 20, 30, 40 }, .rel = &.{0}, .proj = &zeros, .sink = &.{-100}, .gate = &.{100} }; + var y: [1]f64 = undefined; + try attend(f64, false, s, in, &y); + try std.testing.expectApproxEqAbs(@as(f64, 35), y[0], 1e-9); + var wide = s; + wide.window = 3; + try attend(f64, false, wide, in, &y); + try std.testing.expectApproxEqAbs(@as(f64, 30), y[0], 1e-9); +} + +test "attend: grouped heads read their group's keys" { + const s: Shape = .{ .rows = 1, .pos0 = 0, .heads = 4, .kv_heads = 2, .hd = 1, .drel = 1, .rext = 1, .window = 0 }; + const in: Inputs = .{ .q = &.{ 0, 0, 0, 0 }, .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .rel = &.{ 0, 0, 0, 0 }, .proj = &.{0}, .sink = &.{ -100, -100, -100, -100 }, .gate = &.{ 100, 100, 100, 100 } }; + var y: [4]f64 = undefined; + try attend(f64, false, s, in, &y); + try std.testing.expectApproxEqAbs(@as(f64, 1), y[0], 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, 1), y[1], 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, 2), y[2], 1e-9); + try std.testing.expectApproxEqAbs(@as(f64, 2), y[3], 1e-9); +} + +test "attend: a NaN logit or sink makes the head NaN; an infinite value under a weight stays infinite" { + const nan = std.math.nan(f32); + const s: Shape = .{ .rows = 1, .pos0 = 1, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 2, .window = 0 }; + const base: Inputs = .{ .q = &.{1}, .k = &.{ 1, 1 }, .v = &.{ 1, 2 }, .rel = &.{0}, .proj = &.{ 0, 0 }, .sink = &.{0}, .gate = &.{0} }; + inline for (.{ f64, f32 }) |T| { + var y: [1]T = undefined; + var in = base; + in.sink = &.{nan}; + try attend(T, false, s, in, &y); + try std.testing.expect(std.math.isNan(y[0])); + in = base; + in.k = &.{ nan, 1 }; + try attend(T, false, s, in, &y); + try std.testing.expect(std.math.isNan(y[0])); + in = base; + in.v = &.{ std.math.inf(f32), 2 }; + try attend(T, false, s, in, &y); + try std.testing.expect(std.math.isInf(y[0])); + } +} + +test "attend: a +inf sink makes the head NaN" { + const s: Shape = .{ .rows = 1, .pos0 = 1, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 2, .window = 0 }; + const base: Inputs = .{ .q = &.{1}, .k = &.{ 1, 1 }, .v = &.{ 1, 2 }, .rel = &.{0}, .proj = &.{ 0, 0 }, .sink = &.{0}, .gate = &.{0} }; + inline for (.{ f64, f32 }) |T| { + var y: [1]T = undefined; + var in = base; + in.sink = &.{std.math.inf(f32)}; // m is infinite and exp(inf - inf) is NaN, so the denominator is NaN + try attend(T, false, s, in, &y); + try std.testing.expect(std.math.isNan(y[0])); + in.sink = &.{0}; // the same inputs with a finite sink are finite + try attend(T, false, s, in, &y); + try std.testing.expect(std.math.isFinite(y[0])); + } +} + +test "attend: a -inf sink adds nothing to the softmax" { + const s: Shape = .{ .rows = 1, .pos0 = 1, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 2, .window = 0 }; + // two equal logits of 1 (no bias): each weight 1/2, the output (1 + 2) / 2, the gate 0 halves it + const base: Inputs = .{ .q = &.{1}, .k = &.{ 1, 1 }, .v = &.{ 1, 2 }, .rel = &.{0}, .proj = &.{ 0, 0 }, .sink = &.{0}, .gate = &.{0} }; + inline for (.{ f64, f32 }) |T| { + var y: [1]T = undefined; + var in = base; + in.sink = &.{-std.math.inf(f32)}; // exp(-inf - m) is 0: the output of the keys alone + try attend(T, false, s, in, &y); + try std.testing.expectApproxEqAbs(@as(T, 0.75), y[0], 1e-6); + in.sink = &.{0}; // a finite sink of 0 does take weight + try attend(T, false, s, in, &y); + try std.testing.expect(y[0] < 0.7 and y[0] > 0.6); + } +} + +const big_zeros: [1 << 20]f32 = @splat(0); + +/// Arrays of the lengths `s` needs, so a refusal can only come from the shape's own condition. +fn fitting(s: Shape) Inputs { + const out = s.rows * s.heads * s.hd; + const cache = (s.pos0 + s.rows) * s.kv_heads * s.hd; + return .{ .q = big_zeros[0..out], .k = big_zeros[0..cache], .v = big_zeros[0..cache], .rel = big_zeros[0 .. s.rows * s.heads * s.drel], .proj = big_zeros[0 .. s.drel * s.rext], .sink = big_zeros[0 .. s.rows * s.heads], .gate = big_zeros[0..out] }; +} + +test "attn: shaped refuses each bad shape on its own condition, with arrays that fit the shape" { + const ok: Shape = .{ .rows = 1, .pos0 = 0, .heads = 2, .kv_heads = 1, .hd = 2, .drel = 1, .rext = 2, .window = 0 }; + try shaped(ok, fitting(ok), 4); + const bad = error.AttnShape; + var s = ok; + s.heads = 0; + try std.testing.expectError(bad, shaped(s, fitting(s), 0)); + s = ok; + s.kv_heads = 0; + try std.testing.expectError(bad, shaped(s, fitting(s), 4)); + s = ok; + s.heads = 3; // not in whole groups + s.kv_heads = 2; + try std.testing.expectError(bad, shaped(s, fitting(s), 6)); + s = ok; + s.hd = 0; + try std.testing.expectError(bad, shaped(s, fitting(s), 0)); + s = ok; + s.hd = most_hd + 1; + try std.testing.expectError(bad, shaped(s, fitting(s), 2 * (most_hd + 1))); + s = ok; + s.drel = 0; + try std.testing.expectError(bad, shaped(s, fitting(s), 4)); + s = ok; + s.drel = most_rel + 1; + try std.testing.expectError(bad, shaped(s, fitting(s), 4)); + s = ok; + s.rext = 0; + try std.testing.expectError(bad, shaped(s, fitting(s), 4)); + s = ok; + s.rows = 0; + try std.testing.expectError(bad, shaped(s, fitting(s), 0)); + s = ok; + s.rows = 65536; + s.window = 4; // a window keeps the keys few: only the rows are too many + try std.testing.expectError(bad, shaped(s, fitting(s), 65536 * 4)); + s = ok; + s.pos0 = most_keys; // a whole cache over the most keys + try std.testing.expectError(bad, shaped(s, fitting(s), 4)); + s = ok; + s.window = most_keys + 1; + try std.testing.expectError(bad, shaped(s, fitting(s), 4)); + // the lengths, each alone + const fit = fitting(ok); + try std.testing.expectError(bad, shaped(ok, fit, 3)); + var short = fit; + short.q = big_zeros[0..3]; + try std.testing.expectError(bad, shaped(ok, short, 4)); + short = fit; + short.k = big_zeros[0..1]; + try std.testing.expectError(bad, shaped(ok, short, 4)); + short = fit; + short.v = big_zeros[0..1]; + try std.testing.expectError(bad, shaped(ok, short, 4)); + short = fit; + short.rel = big_zeros[0..1]; + try std.testing.expectError(bad, shaped(ok, short, 4)); + short = fit; + short.proj = big_zeros[0..1]; + try std.testing.expectError(bad, shaped(ok, short, 4)); + short = fit; + short.sink = big_zeros[0..1]; + try std.testing.expectError(bad, shaped(ok, short, 4)); + short = fit; + short.gate = big_zeros[0..3]; + try std.testing.expectError(bad, shaped(ok, short, 4)); +} diff --git a/zig/src/families/inkling2/attn_bound.zig b/zig/src/families/inkling2/attn_bound.zig new file mode 100644 index 00000000000..1e834d7f7d9 --- /dev/null +++ b/zig/src/families/inkling2/attn_bound.zig @@ -0,0 +1,148 @@ +//! The float64 formula of one (row, head) and the page's bound on the kernels' order against it, evaluated in float64. +const std = @import("std"); +const attn = @import("attn.zig"); +const order = @import("attn_order.zig"); + +const u: f64 = 0x1p-24; // fp32 unit roundoff +const u_mma: f64 = 0x1p-23; // a tensor-core add: its adders may truncate +const u_bf: f64 = 0x1p-8; // bf16 unit roundoff +const most_live: usize = 1 << 20; // the domain's limit on the keys of a row +const huge: f64 = 0x1p120; // the domain's limit on every magnitude that enters a product or a sum +const gate_min: f64 = -87; // 1 + expf(-gate) stays below 2^126 and the sigmoid is a normal number + +pub const Error = error{AttnDomain} || std.mem.Allocator.Error; + +fn gamma(n: f64) f64 { + return n * u / (1 - n * u); +} + +fn lambda(a: f64) f64 { + return -@log(1 - a); +} + +/// One head's float64 result per output index, the magnitude of its terms and the bound's exponent and floor term. +pub const Head = struct { + want: []f64, + mag: []f64, + big: f64, // L + floor: f64, // (nk + 1) (2 vmax + 1) 2^-130, the subnormal term before its factors + sg: []f64, + + pub fn free(h: Head, a: std.mem.Allocator) void { + a.free(h.want); + a.free(h.mag); + a.free(h.sg); + } + + /// The bound on |y - want[d]| of the fp32 value before the output's rounding; +inf where exp(L) overflows. + pub fn limit(h: Head, d: usize) f64 { + const grow = @exp(h.big); + if (!std.math.isFinite(grow)) return std.math.inf(f64); + return (1 + 0x1p-20) * (h.mag[d] * std.math.expm1(h.big) + h.sg[d] * h.floor * grow) + 0x1p-149; + } + + /// The bound on the bf16-rounded output: the fp32 bound, the output's own rounding, bf16's subnormal step. + pub fn limitOut(h: Head, d: usize) f64 { + const b = h.limit(d); + return b + u_bf * (@abs(h.want[d]) + b) + 0x1p-134; + } +}; + +fn finite(xs: []const f32) bool { + for (xs) |x| if (!std.math.isFinite(x)) return false; + return true; +} + +/// Row `row`, head `h`: the formula's result and the bound's terms; error.AttnDomain outside the page's domain. +pub fn head(a: std.mem.Allocator, s: attn.Shape, in: attn.Inputs, row: usize, h: usize) Error!Head { + const hd = s.hd; + const t = s.pos0 + row; + const lo = attn.first(s, t); + const nk = t - lo + 1; + if (nk > most_live) return error.AttnDomain; + const kh = h / (s.heads / s.kv_heads); + const hrow = row * s.heads + h; + const q = in.q[hrow * hd ..][0..hd]; + const rel = in.rel[hrow * s.drel ..][0..s.drel]; + if (!finite(q) or !finite(rel) or !(@abs(@as(f64, in.sink[hrow])) < huge)) return error.AttnDomain; + for (in.gate[hrow * hd ..][0..hd]) |g| if (!std.math.isFinite(g) or @as(f64, g) < gate_min) return error.AttnDomain; + // the keys a block of this call loads: from the first row's window start to the last row's position + const loaded_lo = attn.first(s, s.pos0); + for (loaded_lo..s.pos0 + s.rows) |key| { + const base = (key * s.kv_heads + kh) * hd; + if (!finite(in.k[base..][0..hd]) or !finite(in.v[base..][0..hd])) return error.AttnDomain; + } + const sigma = std.math.pow(f64, @floatFromInt(hd), -0.5); + const l2e = std.math.log2e; + const mma: f64 = @floatFromInt((hd + 15) / 16); + const g_dot = (1 + (std.math.pow(f64, 1 + 17 * u_mma, mma) - 1)) * (1 + gamma(6)) - 1; + const g_bias = (1 + gamma(@floatFromInt(s.drel))) * (1 + u_bf) * (1 + gamma(3)) - 1; + const xs = try a.alloc(f64, nk); + defer a.free(xs); + var xmax: f64 = -std.math.inf(f64); + var xmin: f64 = std.math.inf(f64); + var dmax: f64 = 0; + for (xs, lo..) |*x, key| { + const k = in.k[(key * s.kv_heads + kh) * hd ..][0..hd]; + var dot: f64 = 0; + var abs: f64 = 0; + for (q, k) |p, r| { + dot += @as(f64, p) * r; + abs += @abs(@as(f64, p) * r); + } + if (!(abs < huge)) return error.AttnDomain; + var bias: f64 = 0; + var babs: f64 = 0; + if (t - key < s.rext) { + for (0..s.drel) |j| { + const w = @as(f64, in.rel[hrow * s.drel + j]) * in.proj[j * s.rext + t - key]; + if (!std.math.isFinite(w)) return error.AttnDomain; + bias += w; + babs += @abs(w); + } + if (!(babs < huge)) return error.AttnDomain; + } + x.* = (dot * sigma + bias) * l2e; + xmax = @max(xmax, x.*); + xmin = @min(xmin, x.*); + dmax = @max(dmax, l2e * (sigma * abs * g_dot + babs * g_bias) + 0x1p-133); + } + const xz = @as(f64, in.sink[hrow]) * l2e; + dmax = @max(dmax, gamma(2) * @abs(xz) + 0x1p-133); + xmax = @max(xmax, xz); + xmin = @min(xmin, xz); + const eta = @log(2.0) * (dmax + u * ((xmax - xmin) + 2 * dmax)); + // keys a block holds and the seams a weight crosses: tiles and sub-chunks a step, chunks a row + const global = s.window == 0; + const tiles: f64 = if (global) order.sub / order.tile else order.sliding_chunk / order.tile; + const subs: f64 = if (global) order.global_chunk / order.sub else 0; + const chunks: f64 = @floatFromInt(if (global) t / order.global_chunk + 1 else (s.window - 1) / order.sliding_chunk + 2); + const events = (tiles - 1) + subs + chunks + 1; // a rescale: exp2f and a product + const common = eta + lambda(gamma(5)) + lambda(u_bf) + events * lambda(gamma(6)); + const num = common + 4 * tiles * lambda(17 * u_mma) + (subs + chunks) * lambda(u); + const den = common + (16 * tiles + 2 + subs + chunks + 1) * lambda(u); + const big = num + den + lambda(gamma(5)) + 4 * lambda(u); + var z: f64 = std.math.exp2(xz - xmax); + for (xs) |x| z += std.math.exp2(x - xmax); + const want = try a.alloc(f64, hd); + const mag = try a.alloc(f64, hd); + const sg = try a.alloc(f64, hd); + var vmax: f64 = 0; + for (0..hd) |d| { + var num_d: f64 = 0; + var abs_d: f64 = 0; + for (xs, lo..) |x, key| { + const v: f64 = in.v[(key * s.kv_heads + kh) * hd + d]; + const p = std.math.exp2(x - xmax); + num_d += p * v; + abs_d += p * @abs(v); + vmax = @max(vmax, @abs(v)); + } + if (!(@as(f64, @floatFromInt(nk)) * vmax < huge)) return error.AttnDomain; + sg[d] = 1 / (1 + @exp(-@as(f64, in.gate[hrow * hd + d]))); + want[d] = num_d / z * sg[d]; + mag[d] = abs_d / z * sg[d]; + } + const floor = @as(f64, @floatFromInt(nk + 1)) * (2 * vmax + 1) * 0x1p-130; + return .{ .want = want, .mag = mag, .big = big, .floor = floor, .sg = sg }; +} diff --git a/zig/src/families/inkling2/attn_bound_test.zig b/zig/src/families/inkling2/attn_bound_test.zig new file mode 100644 index 00000000000..456a1962e89 --- /dev/null +++ b/zig/src/families/inkling2/attn_bound_test.zig @@ -0,0 +1,326 @@ +//! The kernels' order on the host against the float64 formula, inside the page's bound: fixture, seams, pressure. +const std = @import("std"); +const attn = @import("attn.zig"); +const order = @import("attn_order.zig"); +const bound = @import("attn_bound.zig"); +const fixture = @import("attn_test.zig"); +const bf16_round = @import("bf16_round"); + +const t = std.testing; + +/// The worst error over bound of a call, before and after the output's rounding; each element is inside its bound. +fn worst(a: std.mem.Allocator, s: attn.Shape, in: attn.Inputs) ![2]f64 { + const n = s.rows * s.heads * s.hd; + const raw = try a.alloc(f32, n); + defer a.free(raw); + const out = try a.alloc(f32, n); + defer a.free(out); + try order.attendOrder(s, in, raw, .{ .round_out = false }); + try order.attendOrder(s, in, out, .{}); + var w: [2]f64 = .{ 0, 0 }; + for (0..s.rows) |row| for (0..s.heads) |h| { + const hb = try bound.head(a, s, in, row, h); + defer hb.free(a); + for (0..s.hd) |d| { + const i = (row * s.heads + h) * s.hd + d; + const r0 = @abs(@as(f64, raw[i]) - hb.want[d]) / hb.limit(d); + const r1 = @abs(@as(f64, out[i]) - hb.want[d]) / hb.limitOut(d); + if (!(r0 <= 1) or !(r1 <= 1)) { + std.debug.print("outside the bound: row {d} head {d} d {d}: {d} vs {d}, ratios {e} {e}\n", .{ row, h, d, raw[i], hb.want[d], r0, r1 }); + return error.OutsideBound; + } + w[0] = @max(w[0], r0); + w[1] = @max(w[1], r1); + } + }; + return w; +} + +fn report(name: []const u8, w: [2]f64) void { + std.debug.print("attn bound {s}: worst error/bound {e:.2} (fp32), {e:.2} (bf16 output)\n", .{ name, w[0], w[1] }); +} + +test "bound: the fixture" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (try fixture.cases(a), 0..) |c, i| { + var buf: [32]u8 = undefined; + report(try std.fmt.bufPrint(&buf, "fixture case {d}", .{i}), try worst(a, c.shape, c.in)); + } +} + +/// A call's arrays from a spec: bf16 values from a fixed generator, amplitudes per array. +const Spec = struct { + rows: usize = 1, + pos0: usize, + heads: usize = 2, + kv_heads: usize = 1, + hd: usize = 16, + drel: usize = 4, + rext: usize = 64, + window: usize = 0, + q: f32 = 0.5, + k: f32 = 0.5, + v: f32 = 1, + rel: f32 = 0.5, + proj: f32 = 0.5, + sink: f32 = 0, + gate: f32 = 1, + rise: f32 = 0, // keys' first coordinate climbs to this over the cache, q's is 1: the maximum rises + alt: bool = false, // values alternate in sign by position + seed: u64 = 1, +}; + +const Built = struct { + s: attn.Shape, + in: attn.Inputs, + + fn free(b: Built, a: std.mem.Allocator) void { + inline for (.{ b.in.q, b.in.k, b.in.v, b.in.rel, b.in.proj, b.in.sink, b.in.gate }) |x| a.free(x); + } +}; + +fn fill(a: std.mem.Allocator, seed: *u64, n: usize, amp: f32) ![]f32 { + const out = try a.alloc(f32, n); + for (out) |*v| { + seed.* = seed.* *% 1103515245 +% 12345; + const r = @as(f32, @floatFromInt((seed.* >> 16) & 0x7fff)) / 16384.0 - 1.0; + v.* = bf16_round.round32(r * amp); + } + return out; +} + +fn build(a: std.mem.Allocator, p: Spec) !Built { + const s: attn.Shape = .{ .rows = p.rows, .pos0 = p.pos0, .heads = p.heads, .kv_heads = p.kv_heads, .hd = p.hd, .drel = p.drel, .rext = p.rext, .window = p.window }; + var seed = p.seed; + const keys = p.pos0 + p.rows; + const in: attn.Inputs = .{ + .q = try fill(a, &seed, p.rows * p.heads * p.hd, p.q), + .k = try fill(a, &seed, keys * p.kv_heads * p.hd, p.k), + .v = try fill(a, &seed, keys * p.kv_heads * p.hd, p.v), + .rel = try fill(a, &seed, p.rows * p.heads * p.drel, p.rel), + .proj = try fill(a, &seed, p.drel * p.rext, p.proj), + .sink = try fill(a, &seed, p.rows * p.heads, p.sink), + .gate = try fill(a, &seed, p.rows * p.heads * p.hd, p.gate), + }; + const q: []f32 = @constCast(in.q); + const k: []f32 = @constCast(in.k); + const v: []f32 = @constCast(in.v); + if (p.rise != 0) { + for (0..p.rows * p.heads) |i| q[i * p.hd] = 1; + for (0..keys * p.kv_heads) |i| k[i * p.hd] = bf16_round.round32(p.rise * @as(f32, @floatFromInt(i / p.kv_heads)) / @as(f32, @floatFromInt(keys))); + } + if (p.alt) for (0..keys * p.kv_heads) |i| { + for (v[i * p.hd ..][0..p.hd]) |*x| x.* = if (i / p.kv_heads % 2 == 0) @abs(x.*) + 1 else -@abs(x.*) - 1; + }; + return .{ .s = s, .in = in }; +} + +fn run(name: []const u8, p: Spec) !void { + const b = try build(t.allocator, p); + defer b.free(t.allocator); + report(name, try worst(t.allocator, b.s, b.in)); +} + +test "bound: global seams" { + inline for (.{ 62, 63, 64, 1022, 1023, 1024, 16382, 16383, 16384, 20000 }) |pos| { + var buf: [40]u8 = undefined; + try run(try std.fmt.bufPrint(&buf, "global pos {d}", .{pos}), .{ .pos0 = pos, .rise = 6, .seed = pos }); + } + try run("global 3 rows, rows on both sides of a seam", .{ .pos0 = 1022, .rows = 3, .heads = 4, .kv_heads = 2, .rise = 6 }); +} + +test "bound: sliding seams" { + inline for (.{ 100, 255, 256, 511, 700, 1023, 1024, 3000 }) |pos| { + var buf: [40]u8 = undefined; + try run(try std.fmt.bufPrint(&buf, "sliding pos {d}", .{pos}), .{ .pos0 = pos, .window = 1024, .rext = 1024, .rise = 6, .seed = pos }); + } + try run("sliding window 200, 3 rows", .{ .pos0 = 300, .rows = 3, .window = 200, .rext = 200, .rise = 4 }); + // 64 rows in one block (one head a group): the last row's window starts a tile after the first row's + try run("sliding window 200, 64 rows in a block", .{ .pos0 = 1000, .rows = 64, .heads = 1, .rext = 200, .window = 200, .rise = 4 }); +} + +test "bound: head 128" { + try run("head 128, global, pos 1500", .{ .pos0 = 1500, .hd = 128, .drel = 16, .rext = 1024, .heads = 6, .rise = 4 }); + try run("head 128, sliding, pos 1500", .{ .pos0 = 1500, .hd = 128, .drel = 16, .rext = 1024, .window = 1024, .heads = 6, .rise = 4 }); +} + +test "bound: cancellation in P.V" { + try run("cancellation", .{ .pos0 = 2000, .q = 0, .rel = 0, .alt = true, .v = 4 }); +} + +test "bound: large score gap" { + try run("large score gap", .{ .pos0 = 3000, .q = 6, .k = 6, .rel = 0, .hd = 16 }); +} + +test "bound: P on a half-step" { + // the bias b (a bf16 value) makes the other key's weight e^b against 1: pick the b whose e^b is nearest a half-step + var best: f32 = -1; + var gap: f64 = 1; + var h: u16 = 0xbc00; // -0.0078125 .. -8 + while (h < 0xc100) : (h += 1) { + const b = bf16_round.value(h); + const p: f64 = @exp(@as(f64, b)); + const step = std.math.pow(f64, 2, @floor(std.math.log2(p)) - 7); + const x = p / step; + const d = @abs(x - @floor(x) - 0.5); + if (d < gap) { + gap = d; + best = b; + } + } + std.debug.print("attn bound half-step: bias {d} gives e^b within {e:.2} of a step from the half-step\n", .{ best, gap }); + const s: attn.Shape = .{ .rows = 1, .pos0 = 1, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 1, .window = 0 }; + const in: attn.Inputs = .{ .q = &.{0}, .k = &.{ 0, 0 }, .v = &.{ 1, -1 }, .rel = &.{1}, .proj = &.{best}, .sink = &.{-20}, .gate = &.{20} }; + report("half-step", try worst(t.allocator, s, in)); +} + +test "bound: dominant sink" { + try run("dominant sink", .{ .pos0 = 1500, .sink = 0, .q = 0, .rel = 0 }); + var p: Spec = .{ .pos0 = 1500, .q = 0.1, .k = 0.1, .rel = 0 }; + p.sink = 8; + try run("dominant sink 8", p); +} + +test "bound: tiny P" { + const sh: attn.Shape = .{ .rows = 1, .pos0 = 2, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 2, .window = 0 }; + // bias -88 at distance 0 and -86 at distance 1 against 0 at distance 2: weights 2^-126.96 and 2^-124.1 (relative) + const in: attn.Inputs = .{ .q = &.{0}, .k = &.{ 0, 0, 0 }, .v = &.{ 1, 2, 3 }, .rel = &.{1}, .proj = &.{ -88, -86 }, .sink = &.{-20}, .gate = &.{20} }; + report("tiny P", try worst(t.allocator, sh, in)); +} + +/// One key at position 0, hd 1: q and k zero, the score 0, so the value `v` passes through the gate's sigmoid. +fn single(v: f32, gate: f32, sink: f32) struct { s: attn.Shape, in: attn.Inputs } { + const s: attn.Shape = .{ .rows = 1, .pos0 = 0, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 1, .window = 0 }; + const Static = struct { + var vs: [1]f32 = undefined; + var g: [1]f32 = undefined; + var sk: [1]f32 = undefined; + }; + Static.vs[0] = v; + Static.g[0] = gate; + Static.sk[0] = sink; + return .{ .s = s, .in = .{ .q = &.{0}, .k = &.{0}, .v = &Static.vs, .rel = &.{0}, .proj = &.{0}, .sink = &Static.sk, .gate = &Static.g } }; +} + +test "bound: the domain ends where fp32 overflows or the sigmoid leaves the normal range" { + const a = t.allocator; + // e^87 = 2^125.5 < 2^126, e^88 = 2^126.96, e^88.5 = 2^127.68, e^89 = 2^128.4 > FLT_MAX: -87 is the last gate inside + const ok = single(1, -87, -100); + (try bound.head(a, ok.s, ok.in, 0, 0)).free(a); + for ([_]f32{ -88, -88.5, -89, -inf32 }) |g| { + const c = single(1, g, -100); + try t.expectError(error.AttnDomain, bound.head(a, c.s, c.in, 0, 0)); + } + // a dot past 2^120: q and k of 2^70 + var c = single(1, 0, -100); + var q = [1]f32{0x1p70}; + var k = [1]f32{0x1p70}; + c.in.q = &q; + c.in.k = &k; + try t.expectError(error.AttnDomain, bound.head(a, c.s, c.in, 0, 0)); + // a non-finite value at a key another row of the block loads, though it is masked for this row + const two: attn.Shape = .{ .rows = 2, .pos0 = 0, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 1, .window = 0 }; + const masked: attn.Inputs = .{ .q = &.{ 0, 0 }, .k = &.{ 0, 0 }, .v = &.{ 1, inf32 }, .rel = &.{ 0, 0 }, .proj = &.{0}, .sink = &.{ -100, -100 }, .gate = &.{ 0, 0 } }; + try t.expectError(error.AttnDomain, bound.head(a, two, masked, 0, 0)); + // a non-finite value at a key the call loads, a non-finite tap, a sink past 2^120 + c = single(inf32, 0, -100); + try t.expectError(error.AttnDomain, bound.head(a, c.s, c.in, 0, 0)); + c = single(1, 0, 0x1p121); + try t.expectError(error.AttnDomain, bound.head(a, c.s, c.in, 0, 0)); + c = single(1, 0, -100); + c.in.proj = &.{-inf32}; + c.in.rel = &.{1}; + try t.expectError(error.AttnDomain, bound.head(a, c.s, c.in, 0, 0)); +} + +const inf32 = std.math.inf(f32); + +test "bound: the domain ends at 2^20 live keys" { + const a = t.allocator; + inline for (.{ .{ (1 << 20) - 1, true }, .{ 1 << 20, false } }) |c| { + const b = try build(a, .{ .pos0 = c[0], .heads = 1, .hd = 1, .drel = 1, .rext = 1, .q = 0, .k = 0, .rel = 0, .proj = 0, .gate = 0 }); + defer b.free(a); + if (c[1]) { + (try bound.head(a, b.s, b.in, 0, 0)).free(a); + } else { + try t.expectError(error.AttnDomain, bound.head(a, b.s, b.in, 0, 0)); + } + } +} + +test "bound: an output below the normal range" { + // a value through a tiny sigmoid: its last product rounds on the 2^-149 grid, which the scaled floor alone misses + const a = t.allocator; + var found: usize = 0; + for ([_]f32{ -87, -86 }) |gate| { + var h: u16 = 0x3200; // 2^-27 ... up + while (h < 0x3500) : (h += 1) { + const v = bf16_round.value(h); + const c = single(v, gate, -100); + var raw: [1]f32 = undefined; + try order.attendOrder(c.s, c.in, &raw, .{ .round_out = false }); + const hb = try bound.head(a, c.s, c.in, 0, 0); + defer hb.free(a); + const err = @abs(@as(f64, raw[0]) - hb.want[0]); + const without_abs = (1 + 0x1p-20) * (hb.mag[0] * std.math.expm1(hb.big) + hb.sg[0] * hb.floor * @exp(hb.big)); + if (err > without_abs) { + found += 1; + try t.expect(err <= hb.limit(0)); + if (found == 1) std.debug.print("attn bound below normal: v {e} gate {d}: error {e:.3}, bound without the absolute term {e:.3}, bound {e:.3}\n", .{ v, gate, err, without_abs, hb.limit(0) }); + } + } + } + std.debug.print("attn bound below normal: {d} of the values exceed the bound without its absolute term and stay inside the bound\n", .{found}); + try t.expect(found > 0); +} + +test "bound: where exp(L) overflows the bound is infinite, never NaN" { + // q = k = 2^50 and v = 0: the model gives 0, float64 gives 0, and mag * expm1(L) is 0 * inf + const a = t.allocator; + const s: attn.Shape = .{ .rows = 1, .pos0 = 0, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 1, .window = 0 }; + const in: attn.Inputs = .{ .q = &.{0x1p50}, .k = &.{0x1p50}, .v = &.{0}, .rel = &.{0}, .proj = &.{0}, .sink = &.{0}, .gate = &.{0} }; + const hb = try bound.head(a, s, in, 0, 0); + defer hb.free(a); + var raw: [1]f32 = undefined; + try order.attendOrder(s, in, &raw, .{ .round_out = false }); + try t.expectEqual(@as(f32, 0), raw[0]); + try t.expectEqual(@as(f64, 0), hb.want[0]); + try t.expect(hb.big > 709.8); + try t.expectEqual(std.math.inf(f64), hb.limit(0)); + try t.expectEqual(std.math.inf(f64), hb.limitOut(0)); + std.debug.print("attn bound overflow of exp(L): L {e:.2}, limit {d}\n", .{ hb.big, hb.limit(0) }); +} + +test "bound: a table rounded up at the weak key and down at the dominant one" { + // the first key dominates; the weak second key's table sum 64.2539 rounds up, the dominant one's 64.2461 down + const a = t.allocator; + const s: attn.Shape = .{ .rows = 1, .pos0 = 1, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 2, .rext = 2, .window = 0 }; + var best0: f64 = 0; + var best1: f64 = 0; + var bestk: f32 = 0; + var h: u16 = 0xc200; // -32 up + while (h < 0xc2f0) : (h += 1) { + const k1 = bf16_round.value(h); + var kk = [2]f32{ 0, k1 }; + var vv = [2]f32{ 0, 1 }; + const in: attn.Inputs = .{ .q = &.{1}, .k = &kk, .v = &vv, .rel = &.{ 1, 1 }, .proj = &.{ 64, 64, 0.25390625, 0.24609375 }, .sink = &.{-100}, .gate = &.{100} }; + var raw: [1]f32 = undefined; + var out: [1]f32 = undefined; + try order.attendOrder(s, in, &raw, .{ .round_out = false }); + try order.attendOrder(s, in, &out, .{}); + const hb = try bound.head(a, s, in, 0, 0); + defer hb.free(a); + const r0 = @abs(@as(f64, raw[0]) - hb.want[0]) / hb.limit(0); + const r1 = @abs(@as(f64, out[0]) - hb.want[0]) / hb.limitOut(0); + if (r0 > best0) { + best0 = r0; + bestk = k1; + } + best1 = @max(best1, r1); + } + std.debug.print("attn bound table adversary: worst error/bound {e:.3} (fp32) at k {d}, {e:.3} (bf16 output)\n", .{ best0, bestk, best1 }); + try t.expect(best0 <= 1 and best1 <= 1); + try t.expect(best0 > 0.5); +} diff --git a/zig/src/families/inkling2/attn_order.zig b/zig/src/families/inkling2/attn_order.zig new file mode 100644 index 00000000000..ade02b72800 --- /dev/null +++ b/zig/src/families/inkling2/attn_order.zig @@ -0,0 +1,169 @@ +//! Inkling 2's attention in the order of #4125's kernels, in fp32 on the host (docs/inkling2-attention-reference.md). +const std = @import("std"); +const attn = @import("attn.zig"); +const bf16_round = @import("bf16_round"); + +/// Keys a tile, a global sub-chunk, a sliding chunk and a global chunk hold (attention.cu kKeys, kSub; kernels.zig). +pub const tile = 64; +pub const sub = 1024; +pub const sliding_chunk = 256; +pub const global_chunk = 16384; +/// (row, head) pairs a decode block holds (kernels.zig tile_pairs): its rows decide which keys a row's block loads. +pub const block_pairs = 64; + +const log2e: f32 = 1.4426950408889634; +const inf = std.math.inf(f32); + +/// `round_out` false leaves the gated output unrounded (fp32), for the bound. +pub const Options = struct { round_out: bool = true }; + +fn rn(x: f32) f32 { + return bf16_round.round32(x); +} + +/// The kernels' scale constant: fp32 1 / sqrt(hd) (kernels.zig:180). +pub fn scale(hd: usize) f32 { + return 1.0 / @sqrt(@as(f32, @floatFromInt(hd))); +} + +/// A running (max, sum, weighted values) in log2 units. +const Acc = struct { + m: f32 = -inf, + l: f32 = 0, + o: [attn.most_hd]f32 = @splat(0), + + /// A part (m, l, o) folded in: both sides scaled by exp2 of their max less the joint max, each operation rounded. + fn fold(a: *Acc, hd: usize, m: f32, l: f32, o: []const f32) void { + const mn = @max(a.m, m); + const x = @exp2(a.m - mn); + const y = @exp2(m - mn); + a.l = a.l * x + l * y; + for (a.o[0..hd], o) |*u, w| u.* = u.* * x + w * y; + a.m = mn; + } +}; + +/// One (row, head) pair: its inputs, its key head, its position and the keys its block loads. +const Pair = struct { + s: attn.Shape, + in: attn.Inputs, + q: []const f32, + rel: []const f32, + kh: usize, + t: usize, + lo: usize, + tile_lo: usize, + tile_hi: usize, + + /// The bias table's entry: the sum over the taps in order, rounded once to bf16. + fn table(c: *const Pair, dist: usize) f32 { + var acc: f32 = 0; + for (c.rel, 0..) |a, j| acc += a * c.in.proj[j * c.s.rext + dist]; + return rn(acc); + } + + /// The key's score in log2 units: (dot * scale + bias) * log2e, the dot a chain of k16 mma (here: in order). + fn logit(c: *const Pair, key: usize) f32 { + const k = c.in.k[(key * c.s.kv_heads + c.kh) * c.s.hd ..][0..c.s.hd]; + var dot: f32 = 0; + for (c.q, k) |a, b| dot += a * b; + const dist = c.t - key; + const bias: f32 = if (dist < c.s.rext) c.table(dist) else 0; + return (dot * scale(c.s.hd) + bias) * log2e; + } + + /// Keys s_lo..s_hi as the kernel's block runs them: tiles of 64 from the block's first loaded key, a rescale each. + fn step(c: *const Pair, s_lo: usize, s_hi: usize, a: *Acc) void { + const hd = c.s.hd; + a.* = .{}; + var lane: [4]f32 = @splat(0); + const k_lo = @max(s_lo, c.tile_lo); + const k_hi = @min(s_hi, c.tile_hi); + var kt = k_lo / tile * tile; + while (kt <= k_hi) : (kt += tile) { + var sc: [tile]f32 = undefined; + var mx: f32 = -inf; + for (&sc, 0..) |*x, i| { + const key = kt + i; + const live = key >= c.lo and key <= c.t and key >= s_lo and key <= s_hi; + x.* = if (live) c.logit(key) else -inf; + mx = @max(mx, x.*); + } + const mn = @max(a.m, mx); + const mu: f32 = if (mn == -inf) 0 else mn; + const alpha = @exp2(a.m - mu); + a.m = mn; + for (&lane) |*x| x.* *= alpha; + var p: [tile]f32 = undefined; + for (&p, sc) |*x, v| x.* = rn(@exp2(v - mu)); + for (0..4) |t4| { + for (0..tile / 8) |j| { + for (0..2) |b| lane[t4] += p[8 * j + 2 * t4 + b]; + } + } + for (0..hd) |d| { + var acc = a.o[d] * alpha; + for (&p, 0..) |w, i| { + const key = kt + i; + if (key < k_lo or key > k_hi) continue; + acc += w * c.in.v[(key * c.s.kv_heads + c.kh) * hd + d]; + } + a.o[d] = acc; + } + } + a.l = (lane[0] + lane[1]) + (lane[2] + lane[3]); + } +}; + +/// Row `row`, head `h` of a call into `out[0..hd]`; its block is the 64 pairs (row, head) of its key head it sits in. +fn pair(s: attn.Shape, in: attn.Inputs, row: usize, h: usize, out: []f32, opt: Options) void { + const hd = s.hd; + const g = s.heads / s.kv_heads; + const t = s.pos0 + row; + const hrow = row * s.heads + h; + const m = row * g + h % g; + const m0 = m / block_pairs * block_pairs; + const c: Pair = .{ + .s = s, + .in = in, + .q = in.q[hrow * hd ..][0..hd], + .rel = in.rel[hrow * s.drel ..][0..s.drel], + .kh = h / g, + .t = t, + .lo = attn.first(s, t), + .tile_lo = if (s.window > 0) (s.pos0 + m0 / g + 1) -| s.window else 0, + .tile_hi = s.pos0 + @min(m0 + block_pairs - 1, s.rows * g - 1) / g, + }; + const chunk: usize = if (s.window > 0) sliding_chunk else global_chunk; + var run: Acc = .{}; + var ch = c.lo / chunk; + while (ch <= t / chunk) : (ch += 1) { + var part: Acc = .{}; + if (s.window > 0) { + c.step(ch * chunk, ch * chunk + chunk - 1, &part); + } else { + var s_lo = ch * chunk; + while (s_lo < (ch + 1) * chunk and s_lo <= t) : (s_lo += sub) { + var one: Acc = undefined; + c.step(s_lo, s_lo + sub - 1, &one); + part.fold(hd, one.m, one.l, one.o[0..hd]); + } + } + run.fold(hd, part.m, part.l, part.o[0..hd]); + } + const sk = in.sink[hrow] * log2e; + const mf = @max(run.m, sk); + const a = @exp2(run.m - mf); + const den = run.l * a + @exp2(sk - mf); + for (out, 0..) |*o, d| { + const y = run.o[d] * a / den; + const r = y * (1 / (1 + @exp(-in.gate[hrow * hd + d]))); + o.* = if (opt.round_out) rn(r) else r; + } +} + +/// The attention of `s` in the kernels' order into `out` [rows, heads, hd]: bf16 values in fp32 unless `!round_out`. +pub fn attendOrder(s: attn.Shape, in: attn.Inputs, out: []f32, opt: Options) attn.Error!void { + try attn.shapedWithin(s, in, out.len, std.math.maxInt(usize)); + for (0..s.rows) |row| for (0..s.heads) |h| pair(s, in, row, h, out[(row * s.heads + h) * s.hd ..][0..s.hd], opt); +} diff --git a/zig/src/families/inkling2/attn_order_hand_test.zig b/zig/src/families/inkling2/attn_order_hand_test.zig new file mode 100644 index 00000000000..0643eb549ad --- /dev/null +++ b/zig/src/families/inkling2/attn_order_hand_test.zig @@ -0,0 +1,301 @@ +//! The kernels' order on the host against values written out by hand in float64, one rounding point or seam at a time. +const std = @import("std"); +const attn = @import("attn.zig"); +const order = @import("attn_order.zig"); +const bf16_round = @import("bf16_round"); + +const t = std.testing; +const inf = std.math.inf(f32); +const nan = std.math.nan(f32); +const none: f32 = -100; // a sink that adds 2^-145 to a sum and a gate that leaves the sigmoid at 1 + +/// hd 1, one head: the keys' scores are `k` (q is 1), no bias, a sink of -100 and a gate of 100 unless given. +const Mini = struct { + k: []const f32, + v: []const f32, + window: usize = 0, + sink: f32 = none, + gate: f32 = 100, + rows: usize = 1, + heads: usize = 1, + kv_heads: usize = 1, + hd: usize = 1, + q: []const f32 = &.{1}, + rel: f32 = 0, + rels: []const f32 = &.{}, // the taps of rel, if more than one + proj: []const f32 = &.{0}, + rext: usize = 1, + + fn run(m: Mini, out: []f32, round_out: bool) !void { + const pos = m.k.len / m.kv_heads / m.hd; // keys of the cache + const s: attn.Shape = .{ .rows = m.rows, .pos0 = pos - m.rows, .heads = m.heads, .kv_heads = m.kv_heads, .hd = m.hd, .drel = @max(1, m.rels.len), .rext = m.rext, .window = m.window }; + var qs: [64]f32 = undefined; + var sinks: [8]f32 = undefined; + var gates: [64]f32 = undefined; + var rels: [64]f32 = undefined; + for (0..m.rows * m.heads) |i| { + for (0..m.hd) |d| { + qs[i * m.hd + d] = m.q[d % m.q.len]; + gates[i * m.hd + d] = m.gate; + } + sinks[i] = m.sink; + if (m.rels.len == 0) { + rels[i] = m.rel; + } else { + for (m.rels, 0..) |r, j| rels[i * m.rels.len + j] = r; + } + } + const in: attn.Inputs = .{ .q = qs[0 .. m.rows * m.heads * m.hd], .k = m.k, .v = m.v, .rel = rels[0 .. m.rows * m.heads * @max(1, m.rels.len)], .proj = m.proj, .sink = sinks[0 .. m.rows * m.heads], .gate = gates[0 .. m.rows * m.heads * m.hd] }; + try order.attendOrder(s, in, out, .{ .round_out = round_out }); + } +}; + +fn near(want: f64, got: f32) !void { + try t.expectApproxEqRel(want, @as(f64, got), 1e-5); +} + +test "table: bf16 once, a tie to even" { + // rel 1.5 times proj 1.0078125 = 1.51171875, halfway between 1.5078125 and 1.515625: the even one, 1.515625 + var y: [1]f32 = undefined; + try (Mini{ .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .q = &.{0}, .rel = 1.5, .proj = &.{ 1.0078125, 0 }, .rext = 2 }).run(&y, false); + // scores 0 and 1.515625 log2(e); P = bf16(2^-2.18669) = 0.2197265625 and 1: (0.2197265625 + 2) / 1.2197265625 + try near(1.8198558847077662, y[0]); +} + +test "P: bf16 once, in the products and the denominator" { + // scores 0 and -0.5 log2(e): P = 1 and bf16(e^-0.5) = 0.60546875, y = (1 - 0.60546875) / 1.60546875 + var y: [1]f32 = undefined; + try (Mini{ .k = &.{ 0, -0.5 }, .v = &.{ 1, -1 } }).run(&y, false); + try near(0.24574209245742093, y[0]); +} + +test "output: bf16 once, after the gate" { + var y: [1]f32 = undefined; + try (Mini{ .k = &.{ 0, -0.5 }, .v = &.{ 1, -1 } }).run(&y, true); + try t.expectEqual(@as(u16, 0x3e7c), bf16_round.bits(y[0])); // 0.24574209 rounds to 0.24609375 + try t.expectEqual(@as(u32, 0), @as(u32, @bitCast(y[0])) & 0xffff); +} + +test "score: the dot and the scale stay fp32" { + // q (1, 1), a key (-2, -33 2^-12): the dot -2.008056640625 is not a bf16 value; scale 1 / sqrt(2); the other key 0 + var y: [2]f32 = undefined; + try (Mini{ .k = &.{ -2, -0.008056640625, 0, 0 }, .v = &.{ 1, 1, 2, 2 }, .hd = 2, .q = &.{ 1, 1 } }).run(&y, false); + try near(1.8050314465408805, y[0]); +} + +test "sink: at the merge, unrounded" { + // one key at 0, a sink of -0.5: its term is 2^(-0.5 log2(e)) = 0.60653066, not bf16(0.60653066) + var y: [1]f32 = undefined; + try (Mini{ .k = &.{0}, .v = &.{1}, .sink = -0.5 }).run(&y, false); + try near(0.6224593312018546, y[0]); +} + +test "gate: its sigmoid" { + var y: [1]f32 = undefined; + try (Mini{ .k = &.{0}, .v = &.{1}, .sink = -0.5, .gate = 0 }).run(&y, false); + try near(0.3112296656009273, y[0]); +} + +test "gate: past -88.7 the kernel's sigmoid is 0 where float64's is not" { + // expf(89) overflows fp32: 1 / (1 + inf) = 0, so the output is 0; float64 has e^-89 = 2.2273635617957434e-39 + var y: [1]f32 = undefined; + try (Mini{ .k = &.{0}, .v = &.{1}, .gate = -89 }).run(&y, false); + try t.expectEqual(@as(f32, 0), y[0]); + var want: [1]f64 = undefined; + const s: attn.Shape = .{ .rows = 1, .pos0 = 0, .heads = 1, .kv_heads = 1, .hd = 1, .drel = 1, .rext = 1, .window = 0 }; + const in: attn.Inputs = .{ .q = &.{1}, .k = &.{0}, .v = &.{1}, .rel = &.{0}, .proj = &.{0}, .sink = &.{none}, .gate = &.{-89} }; + try attn.attend(f64, false, s, in, &want); + try t.expectApproxEqRel(2.2273635617957434e-39, want[0], 1e-9); +} + +test "window: exactly `window` keys" { + var y: [1]f32 = undefined; + try (Mini{ .k = &.{ 0, 0, 0, 0 }, .v = &.{ 10, 20, 30, 40 }, .window = 2 }).run(&y, false); + try near(35, y[0]); + try (Mini{ .k = &.{ 0, 0, 0, 0 }, .v = &.{ 10, 20, 30, 40 }, .window = 3 }).run(&y, false); + try near(30, y[0]); +} + +test "bias: distances under rext only" { + // distance 0 gets 3, distance 1 none: scores 0 and 3 log2(e), P = bf16(2^-4.328) and 1 + var y: [1]f32 = undefined; + try (Mini{ .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .q = &.{0}, .rel = 1, .proj = &.{3} }).run(&y, false); + try near(1.9525581395348837, y[0]); +} + +test "group: the group's key head" { + var y: [4]f32 = undefined; + try (Mini{ .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .heads = 4, .kv_heads = 2 }).run(&y, false); + try t.expectEqualSlices(f32, &.{ 1, 1, 2, 2 }, &y); +} + +/// `n` keys of score -1000 (weight 0) and value 0, with the given positions set. +fn keys(a: std.mem.Allocator, n: usize, at: []const struct { usize, f32, f32 }) !struct { k: []f32, v: []f32 } { + const k = try a.alloc(f32, n); + const v = try a.alloc(f32, n); + @memset(k, -1000); + @memset(v, 0); + for (at) |e| { + k[e[0]] = e[1]; + v[e[0]] = e[2]; + } + return .{ .k = k, .v = v }; +} + +fn seam(window: usize, n: usize, at: []const struct { usize, f32, f32 }) !f32 { + const kv = try keys(t.allocator, n, at); + defer t.allocator.free(kv.k); + defer t.allocator.free(kv.v); + var y: [1]f32 = undefined; + try (Mini{ .k = kv.k, .v = kv.v, .window = window }).run(&y, false); + return y[0]; +} + +test "tile seam: P rounds against its tile's maximum, then rescales" { + // key 0 at 0, key 1 at -0.5, key 64 at +0.5 (log2(e) each): tile 0 rounds P1, tile 1 rescales by 2^-0.72 + const y = try seam(0, 65, &.{ .{ 0, 0, 1 }, .{ 1, -0.5, -1 }, .{ 64, 0.5, 2 } }); + try near(1.134529258560611, y); +} + +test "tile: a weak key rounds against a strong one after it" { + const y = try seam(0, 41, &.{ .{ 0, -0.5, 1 }, .{ 40, 0, -1 } }); + try near(-0.24574209245742093, y); +} + +test "sub-chunk seam: starts from its own maximum" { + // key 1023 at 0, key 1024 at -0.5: its sub-chunk's P is 1, the fold scales it by 2^-0.72 (not bf16) + const y = try seam(0, 1025, &.{ .{ 1023, 0, 1 }, .{ 1024, -0.5, -1 } }); + try near(0.24491866240370913, y); +} + +test "chunk seam at 256: sliding starts afresh, global does not" { + const at = [_]struct { usize, f32, f32 }{ .{ 255, 0, 1 }, .{ 256, -0.5, -1 } }; + try near(0.24491866240370913, try seam(1024, 257, &at)); + try near(0.24574209245742093, try seam(0, 257, &at)); +} + +const big: f32 = 16777216; // 2^24: one more is not an fp32 value, two more are + +test "tiles: one chain, ones between 2^24 and -2^24 are absorbed" { + // the mma chain of a sub-chunk runs on across its tiles: 2^24 + 1 + 1 - 2^24 is 0, the exact sum would be 2 + const y = try seam(0, 193, &.{ .{ 0, 0, big }, .{ 64, 0, 1 }, .{ 128, 0, 1 }, .{ 192, 0, -big } }); + try t.expectEqual(@as(f32, 0), @abs(y)); +} + +test "sub-chunk: summed alone, then folded" { + // sub-chunk 1 holds the two ones (their own chain gives 2): 2^24, then 2^24 + 2, then 2; y = 2 / 4 keys + const y = try seam(0, 2049, &.{ .{ 0, 0, big }, .{ 1024, 0, 1 }, .{ 1600, 0, 1 }, .{ 2048, 0, -big } }); + try near(0.5, y); +} + +test "sliding chunk: summed alone, then merged" { + const y = try seam(1024, 513, &.{ .{ 0, 0, big }, .{ 256, 0, 1 }, .{ 448, 0, 1 }, .{ 512, 0, -big } }); + try near(0.5, y); +} + +test "global chunk: its sub-chunks fold first" { + // chunk 1 holds a one in its first sub-chunk and one in its last (folded to 2); chunk 0 holds 2^24, chunk 2 -2^24 + const y = try seam(0, 32769, &.{ .{ 0, 0, big }, .{ 16384, 0, 1 }, .{ 32000, 0, 1 }, .{ 32768, 0, -big } }); + try near(0.5, y); +} + +test "NaN: a non-finite V at a masked key a block loads" { + // rows at positions 1 and 2 share a block: the key at 2 is loaded for the row at 1 and masked there, P = 0, 0 x inf + var y: [2]f32 = undefined; + try (Mini{ .k = &.{ 0, 0, 0 }, .v = &.{ 1, 2, inf }, .rows = 2 }).run(&y, false); + try t.expect(std.math.isNan(y[0])); + try t.expect(std.math.isInf(y[1])); +} + +test "NaN: a masked key no block loads is harmless" { + // window 2, one row at 4 keeps keys 3 and 4: its block loads from key 3, so the infinite value at 1 is never read + var y: [1]f32 = undefined; + try (Mini{ .k = &.{ 0, 0, 0, 0, 0 }, .v = &.{ 1, inf, 1, 1, 1 }, .window = 2 }).run(&y, false); + try near(1, y[0]); +} + +test "NaN: a masked key's K is replaced by -inf" { + var y: [2]f32 = undefined; + try (Mini{ .k = &.{ 0, 0, nan }, .v = &.{ 1, 2, 3 }, .rows = 2 }).run(&y, false); + try t.expect(std.math.isFinite(y[0])); + try t.expect(std.math.isNan(y[1])); // the same key is live for the row at 2 + try (Mini{ .k = &.{ 0, 0, inf }, .v = &.{ 1, 2, 3 }, .rows = 2 }).run(&y, false); + try t.expect(std.math.isFinite(y[0])); +} + +test "NaN: below the window, a key another row's block loads" { + // window 2, rows at 3 and 4 in one block: the row at 4 sees keys 3 and 4, the block loads from key 2 + var y: [2]f32 = undefined; + try (Mini{ .k = &.{ 0, 0, 0, 0, 0 }, .v = &.{ 1, 1, inf, 1, 1 }, .rows = 2, .window = 2 }).run(&y, false); + try t.expect(std.math.isInf(y[0])); // key 2 is live for the row at 3 + try t.expect(std.math.isNan(y[1])); // and masked for the row at 4, whose block loads it +} + +test "NaN: live keys and the sink" { + var y: [1]f32 = undefined; + try (Mini{ .k = &.{ 0, 0 }, .v = &.{ inf, 2 } }).run(&y, false); + try t.expect(std.math.isInf(y[0])); + try (Mini{ .k = &.{ nan, 0 }, .v = &.{ 1, 2 } }).run(&y, false); + try t.expect(std.math.isNan(y[0])); + try (Mini{ .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .sink = nan }).run(&y, false); + try t.expect(std.math.isNan(y[0])); + try (Mini{ .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .sink = inf }).run(&y, false); + try t.expect(std.math.isNan(y[0])); + try (Mini{ .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .sink = -inf }).run(&y, false); + try near(1.5, y[0]); +} + +test "NaN: the gate" { + var y: [1]f32 = undefined; + try (Mini{ .k = &.{0}, .v = &.{1}, .gate = inf }).run(&y, false); + try near(1, y[0]); + try (Mini{ .k = &.{0}, .v = &.{1}, .gate = -inf }).run(&y, false); + try t.expectEqual(@as(f32, 0), y[0]); + try (Mini{ .k = &.{0}, .v = &.{1}, .gate = nan }).run(&y, false); + try t.expect(std.math.isNan(y[0])); +} + +test "sub-chunks: fold in order" { + const y = try seam(0, 3073, &.{ .{ 0, 0, big }, .{ 1024, 0, 1 }, .{ 2048, 0, 1 }, .{ 3072, 0, -big } }); + try t.expectEqual(@as(f32, 0), @abs(y)); +} + +test "sliding chunks: merge in order" { + const y = try seam(1024, 769, &.{ .{ 0, 0, big }, .{ 256, 0, 1 }, .{ 512, 0, 1 }, .{ 768, 0, -big } }); + try t.expectEqual(@as(f32, 0), @abs(y)); +} + +test "global chunks: merge in order" { + const y = try seam(0, 49153, &.{ .{ 0, 0, big }, .{ 16384, 0, 1 }, .{ 32768, 0, 1 }, .{ 49152, 0, -big } }); + try t.expectEqual(@as(f32, 0), @abs(y)); +} + +test "table: taps in order" { + // keys 0 and 1 at distance 1 and 0; the key at distance 0 gets bias 0 (absorbed), so both weigh 1 + var y: [1]f32 = undefined; + try (Mini{ .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .q = &.{0}, .rels = &.{ big, 1, -big }, .proj = &.{ 1, 0, 1, 0, 1, 0 }, .rext = 2 }).run(&y, false); + try near(1.5, y[0]); +} + +test "score: one chain across k16 blocks" { + var k: [66]f32 = @splat(0); + k[0] = big; + k[16] = 1; + k[32] = -big; + var v: [66]f32 = @splat(1); + @memset(v[33..], 2); + var y: [33]f32 = undefined; + try (Mini{ .k = &k, .v = &v, .hd = 33 }).run(&y, false); + try near(1.5, y[0]); // the first key's score is 0 as the second's: equal weights +} + +test "shapes: over 8192 keys is accepted, a refusal stays a refusal" { + const kv = try keys(t.allocator, 20000, &.{ .{ 0, 0, 1 }, .{ 19999, 0, 3 } }); + defer t.allocator.free(kv.k); + defer t.allocator.free(kv.v); + var y: [1]f32 = undefined; + try (Mini{ .k = kv.k, .v = kv.v }).run(&y, false); + try near(2, y[0]); + var z: [3]f32 = undefined; + try t.expectError(error.AttnShape, (Mini{ .k = &.{ 0, 0 }, .v = &.{ 1, 2 }, .heads = 3, .kv_heads = 2 }).run(&z, false)); +} diff --git a/zig/src/families/inkling2/attn_test.zig b/zig/src/families/inkling2/attn_test.zig new file mode 100644 index 00000000000..6f3264525e9 --- /dev/null +++ b/zig/src/families/inkling2/attn_test.zig @@ -0,0 +1,188 @@ +//! The attention's host models against the oracle's dump (tiny-random/inkling-2's bias tables, no GPU). +const std = @import("std"); +const attn = @import("attn.zig"); +const order = @import("attn_order.zig"); +const bf16_round = @import("bf16_round"); + +const t = std.testing; +const dump = @embedFile("fixtures/attn_tiny.bin"); + +pub const Case = struct { + kind: u32, // 0 sliding, 1 full + shape: attn.Shape, + in: attn.Inputs, + y: []f64, // float64 output + torch16: []u16, // the transformers functions' bf16 output bits +}; + +fn at(comptime T: type, off: usize) T { + return std.mem.readInt(T, dump[off..][0..@sizeOf(T)], .little); +} + +/// `n` bf16 values widened to fp32. +fn widen(a: std.mem.Allocator, off: *usize, n: usize) ![]f32 { + const out = try a.alloc(f32, n); + for (out) |*v| { + v.* = bf16_round.value(at(u16, off.*)); + off.* += 2; + } + return out; +} + +pub fn cases(a: std.mem.Allocator) ![]Case { + try t.expect(std.mem.eql(u8, dump[0..8], "TFINKAT1")); + const list = try a.alloc(Case, at(u32, 8)); + var off: usize = 12; + for (list) |*c| { + c.kind = at(u32, off); + const f: [8]usize = blk: { + var x: [8]usize = undefined; + for (&x, 0..) |*v, i| v.* = at(u32, off + 4 + 4 * i); + break :blk x; + }; + c.shape = .{ .heads = f[0], .kv_heads = f[1], .hd = f[2], .drel = f[3], .rext = f[4], .window = f[5], .rows = f[6], .pos0 = f[7] }; + off += 36; + const s = c.shape; + const out = s.rows * s.heads * s.hd; + const pos = s.pos0 + s.rows; + c.in.q = try widen(a, &off, out); + c.in.k = try widen(a, &off, pos * s.kv_heads * s.hd); + c.in.v = try widen(a, &off, pos * s.kv_heads * s.hd); + c.in.rel = try widen(a, &off, s.rows * s.heads * s.drel); + c.in.proj = try widen(a, &off, s.drel * s.rext); + c.in.sink = try widen(a, &off, s.rows * s.heads); + c.in.gate = try widen(a, &off, out); + c.y = try a.alloc(f64, out); + for (c.y) |*v| { + v.* = @bitCast(at(u64, off)); + off += 8; + } + c.torch16 = try a.alloc(u16, out); + for (c.torch16) |*v| { + v.* = at(u16, off); + off += 2; + } + } + try t.expectEqual(dump.len, off); + return list; +} + +/// The least bound / |e| over every head, e = got - y, bound = (|y| + the head's max |y|) 2^-k; inf where every e is 0. +fn margin(c: Case, got: []const f64, comptime k: comptime_int) f64 { + var least = std.math.inf(f64); + const hd = c.shape.hd; + for (0..c.shape.rows * c.shape.heads) |h| { + const want = c.y[h * hd ..][0..hd]; + var top: f64 = 0; + for (want) |v| top = @max(top, @abs(v)); + for (want, got[h * hd ..][0..hd]) |w, v| { + const e = @abs(v - w); + if (e != 0) least = @min(least, (@abs(w) + top) * std.math.pow(f64, 2, -k) / e); + } + } + return least; +} + +test "the inputs are bf16 values and the fixture holds both kinds, the seams and the checkpoint's tables" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const list = try cases(arena.allocator()); + var sliding: usize = 0; + for (list) |c| { + sliding += @intFromBool(c.kind == 0); + try attn.shaped(c.shape, c.in, c.y.len); + const arrays = [_][]const f32{ c.in.q, c.in.k, c.in.v, c.in.rel, c.in.proj, c.in.sink, c.in.gate }; + for (arrays) |x| for (x) |v| try t.expectEqual(@as(u32, 0), @as(u32, @bitCast(v)) & 0xffff); + } + try t.expectEqual(@as(usize, 6), list.len); + try t.expectEqual(@as(usize, 3), sliding); + // the window of 64 reaches its edge inside the rows (positions 62 to 65); one case starts at position 0 + try t.expectEqual(@as(usize, 64), list[2].shape.window); + try t.expectEqual(@as(usize, 62), list[2].shape.pos0); + try t.expectEqual(@as(usize, 0), list[4].shape.pos0); +} + +test "the float64 model equals the oracle's dump to 2^-40, per element" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (try cases(a)) |c| { + const got = try a.alloc(f64, c.y.len); + try attn.attend(f64, false, c.shape, c.in, got); + const m = margin(c, got, 40); + std.debug.print("attn f64 vs dump 2^-40 margin {d:.2}x (kind {d}, {d} rows, {d} heads)\n", .{ m, c.kind, c.shape.rows, c.shape.heads }); + try t.expect(m >= 1); + } +} + +test "eager fidelity: the eager-point model gives transformers' bf16 bits" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var total: usize = 0; + var equal: usize = 0; + var worst: u32 = 0; // in bf16 steps + for (try cases(a)) |c| { + const y32 = try a.alloc(f32, c.y.len); + try attn.attend(f32, true, c.shape, c.in, y32); + var same: usize = 0; + for (y32, c.torch16) |v, want| { + const raw: u32 = @bitCast(v); + try t.expectEqual(@as(u32, 0), raw & 0xffff); // the model rounds its output to bf16 itself + const bits: u16 = @intCast(raw >> 16); + same += @intFromBool(bits == want); + const step = @abs(@as(i32, bits) - @as(i32, want)); + worst = @max(worst, @as(u32, @intCast(step))); + } + std.debug.print("attn bf16 bits: {d} of {d} equal the module's (kind {d}, {d} rows)\n", .{ same, y32.len, c.kind, c.shape.rows }); + total += y32.len; + equal += same; + } + std.debug.print("attn bf16 bits: {d} of {d} equal, worst {d} steps apart\n", .{ equal, total, worst }); + // a libm with another last bit in exp may flip a rounding: a thousandth may differ by one step + try t.expect(equal * 1000 >= total * 999); + try t.expect(worst <= 1); +} + +test "bf16 bits: a tie goes to the even neighbour, above it up, infinity stays and a NaN stays a NaN" { + const one: u32 = @bitCast(@as(f32, 1.0)); + try t.expectEqual(@as(u16, 0x3f80), bf16_round.bits(@bitCast(one + 0x8000))); // halfway from 1 to the next: even + try t.expectEqual(@as(u16, 0x3f81), bf16_round.bits(@bitCast(one + 0x8001))); // just above it + try t.expectEqual(@as(u16, 0x3f82), bf16_round.bits(@bitCast(one + 0x10000 + 0x8000))); // halfway: the even 0x3f82 + try t.expectEqual(@as(u16, 0x7f80), bf16_round.bits(std.math.inf(f32))); + try t.expect(std.math.isNan(bf16_round.value(bf16_round.bits(std.math.nan(f32))))); +} + +/// A bf16 value's place among all bf16 values in order, so a distance counts the values between two. +fn place(bits: u16) i32 { + return if (bits & 0x8000 != 0) 0x8000 - @as(i32, bits & 0x7fff) else 0x8000 + @as(i32, bits); +} + +test "eager fidelity: the kernels' order against transformers' bf16 bits, reported" { + var arena = std.heap.ArenaAllocator.init(t.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var total: usize = 0; + var equal: usize = 0; + var one: usize = 0; + var worst: u32 = 0; // in bf16 values between + var rel: f64 = 0; // the worst |got - transformers| / (|transformers| + the head's largest) + for (try cases(a)) |c| { + const y32 = try a.alloc(f32, c.y.len); + try order.attendOrder(c.shape, c.in, y32, .{}); + const hd = c.shape.hd; + for (0..c.shape.rows * c.shape.heads) |h| { + var top: f64 = 0; + for (c.torch16[h * hd ..][0..hd]) |w| top = @max(top, @abs(bf16_round.value(w))); + for (y32[h * hd ..][0..hd], c.torch16[h * hd ..][0..hd]) |v, w| { + const step = @abs(place(bf16_round.bits(v)) - place(w)); + equal += @intFromBool(step == 0); + one += @intFromBool(step == 1); + worst = @max(worst, @as(u32, @intCast(step))); + rel = @max(rel, @abs(@as(f64, v) - bf16_round.value(w)) / (@abs(@as(f64, bf16_round.value(w))) + top)); + } + } + total += y32.len; + } + std.debug.print("attn order vs transformers bf16 bits: {d} of {d} equal, {d} one step apart, worst {d} steps, worst relative {e:.2}\n", .{ equal, total, one, worst, rel }); +} diff --git a/zig/src/families/inkling2/fixtures/attn_tiny.bin b/zig/src/families/inkling2/fixtures/attn_tiny.bin new file mode 100644 index 00000000000..6d1dcb07ec2 Binary files /dev/null and b/zig/src/families/inkling2/fixtures/attn_tiny.bin differ diff --git a/zig/src/families/inkling2/host_test.zig b/zig/src/families/inkling2/host_test.zig index 4f8b47e83b3..d9277e91fb8 100644 --- a/zig/src/families/inkling2/host_test.zig +++ b/zig/src/families/inkling2/host_test.zig @@ -1,5 +1,10 @@ //! Host-only Inkling 2 family package: config, weight map, layer plan, chat template and tokenizer. No GPU. test { + _ = @import("attn.zig"); + _ = @import("attn_bound_test.zig"); + _ = @import("attn_order.zig"); + _ = @import("attn_order_hand_test.zig"); + _ = @import("attn_test.zig"); _ = @import("config.zig"); _ = @import("config_test.zig"); _ = @import("names.zig"); diff --git a/zig/src/families/inkling2/oracle/attn.py b/zig/src/families/inkling2/oracle/attn.py new file mode 100644 index 00000000000..972034a0ebc --- /dev/null +++ b/zig/src/families/inkling2/oracle/attn.py @@ -0,0 +1,268 @@ +"""Inkling 2's decode attention in float64 (stdlib) and through transformers' relative logits and eager attention.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import struct +import sys +from importlib.metadata import version +from pathlib import Path + +MAGIC = b"TFINKAT1" +TINY = "tiny-random/inkling-2@0a57c72e4e5b68aafe1d983dbb62980344a5fcd7" +TINY_SHA256 = "ac7f0eaa84e50b53c4afce3ea7eecdc49ccca21bd467edb16f3d052d9099a3de" # model.safetensors of that revision +PINS = {"transformers": "5.23.0", "torch": "2.15.0+cpu"} # the releases the oracle requires +MODELING_SHA256 = "0364d1d73b600e1b2716febac3e4b2e14ad91b1891b02f58635a887f2bd185ce" # modeling_inkling2.py of 5.23.0 +PROJ_LOCAL = "model.llm.layers.1.attn.rel_logits_proj.proj" # [16, 1024] bf16: layer 1 is a sliding layer +PROJ_GLOBAL = "model.llm.layers.5.attn.rel_logits_proj.proj" # layer 5 is a full-attention layer +COLUMNS = 64 # the fixture keeps the table's first columns: the cases below stay within them + +# name, kind (0 sliding, 1 full), heads, kv heads, head dim, d_rel, rel extent, window (0: none), rows, first pos, table +CASES = ( + ("sliding, the tiny checkpoint's shape", 0, 8, 4, 128, 16, COLUMNS, 1024, 1, 11, PROJ_LOCAL), + ("full, three rows, the checkpoint's shape", 1, 8, 4, 128, 16, COLUMNS, 0, 3, 13, PROJ_GLOBAL), + ("sliding window of 64: rows 62 to 65", 0, 2, 1, 16, 16, 64, 64, 4, 62, None), + ("full, bias table of 64: rows 62 to 65", 1, 2, 1, 16, 16, 64, 0, 4, 62, None), + ("sliding window of 64, the first positions", 0, 2, 1, 16, 16, 64, 64, 2, 0, None), + ("full, the first position and a GQA group of 4", 1, 4, 1, 32, 8, 16, 0, 3, 0, None), +) + + +def bf16(x: float) -> float: + """x rounded to bf16, nearest even, as an fp32 value.""" + u = struct.unpack("> 16) & 1) + return struct.unpack(" int: + return struct.unpack("> 16 + + +def from_bits(h: int) -> float: + return struct.unpack("> 16) & 0x7FFF) / 16384.0 - 1.0) + return seed, out + + +def read_tensor(path: Path, name: str): + """One BF16 tensor of a safetensors file: its flat values as floats.""" + with open(path, "rb") as f: + (length,) = struct.unpack(" list: + """The formula in float64: each row's heads, `heads * hd` outputs a row (finite inputs).""" + heads, kv, hd, drel, rext, window = c["heads"], c["kv"], c["hd"], c["drel"], c["rext"], c["window"] + scale = hd**-0.5 + out = [] + for r in range(c["rows"]): + t = c["pos0"] + r + lo = max(0, t - window + 1) if window else 0 + for h in range(heads): + qv = c["q"][r * heads + h] + kh = h // (heads // kv) + rel = c["rel"][r * heads + h] + logits = [] + for s in range(lo, t + 1): + kr = c["k"][s * kv + kh] + l = sum(a * b for a, b in zip(qv, kr)) * scale + dist = t - s + if dist < rext: + l += sum(rel[j] * c["proj"][j][dist] for j in range(drel)) + logits.append(l) + sink = c["sink"][r * heads + h] + m = max(logits + [sink]) + e = [math.exp(l - m) for l in logits] + z = sum(e) + math.exp(sink - m) + for d in range(hd): + o = sum(p / z * c["v"][(lo + j) * kv + kh][d] for j, p in enumerate(e)) + g = c["gate"][(r * heads + h) * hd + d] + out.append(o / (1.0 + math.exp(-g))) + return out + + +def modules(): + """The transformers module file and torch, after the pins and the file's hash are checked.""" + import torch + from transformers.models.inkling2 import modeling_inkling2 as module + + for pin, got in ((p, version(p)) for p in PINS): + if got != PINS[pin]: + sys.exit(f"{pin} {got}, pinned {PINS[pin]}") + if hashlib.sha256(Path(module.__file__).read_bytes()).hexdigest() != MODELING_SHA256: + sys.exit("modeling_inkling2.py is not the pinned file") + return torch, module + + +def torch_attend(torch, module, c): + """The layer's path (TF523:437-498), bf16 in and out: transformers' own relative logits and eager attention.""" + import types + + heads, kv, hd, drel, rext, window = c["heads"], c["kv"], c["hd"], c["drel"], c["rext"], c["window"] + rows, pos0 = c["rows"], c["pos0"] + pos = pos0 + rows + bf = torch.bfloat16 + + def tensor(x, *shape): + return torch.tensor(x, dtype=torch.float32).reshape(*shape).to(bf) + + q = tensor(c["q"], 1, rows, heads, hd).transpose(1, 2) + k = tensor(c["k"], 1, pos, kv, hd).transpose(1, 2) + v = tensor(c["v"], 1, pos, kv, hd).transpose(1, 2) + rel = tensor(c["rel"], 1, rows, heads, drel) + sink = tensor(c["sink"], 1, rows, heads) + gate = tensor(c["gate"], 1, rows, heads * hd) + logits = module.Inkling2RelativeLogits(drel, rext) + with torch.no_grad(): + logits.proj.copy_(tensor(c["proj"], drel, rext).float()) + logits.proj.data = logits.proj.data.to(bf) + qpos = torch.arange(rows) + pos0 + kpos = torch.arange(pos) + bias = logits(rel, qpos, kpos) + # the mask as transformers' masking_utils.py builds it for TF523:1290-1291: :76 causal, :95 window, :630 its fill + allowed = kpos[None, :] <= qpos[:, None] + if window: + allowed &= (qpos[:, None] - kpos[None, :]) < window + mask = torch.where(allowed, torch.zeros((), dtype=bf), torch.full((), torch.finfo(bf).min, dtype=bf))[None, None] + layer = types.SimpleNamespace(num_key_value_groups=heads // kv, training=False) + out, _ = module.eager_attention_forward(layer, q, k, v, mask, scaling=hd**-0.5, position_bias=bias, + sinks=sink.transpose(1, 2).unsqueeze(-1)) + out = out.reshape(1, rows, -1).contiguous() + out = (out.float() * torch.sigmoid(gate.float())).to(out.dtype) # the gate as TF523:496 and :628 write it + return [int(b) & 0xFFFF for b in out.reshape(-1).view(torch.int16).tolist()] + + +def write(path: Path, cases) -> None: + """The fixture: magic, case count; per case a header, the bf16 inputs, float64 y and the module's bf16 bits.""" + with open(path, "wb") as f: + f.write(MAGIC + struct.pack(" None: + """The module's bf16 output against the float64 one, per case: the worst gap relative to the row's largest value.""" + for c in cases: + hd = c["hd"] + worst, flips = 0.0, 0 + for h in range(c["rows"] * c["heads"]): + top = max(abs(a) for a in c["y"][h * hd : (h + 1) * hd]) or 1.0 + for want, bits in zip(c["y"][h * hd : (h + 1) * hd], c["torch16"][h * hd : (h + 1) * hd]): + worst = max(worst, abs(from_bits(bits) - want) / top) + flips += bf16_bits(want) != bits + print(f"{c['name']}: bf16 output vs float64 worst {worst:.3e} of the head's top value; " + f"bits differ from the rounded float64 in {flips} of {len(c['y'])}") + + +def real_seams(torch, module) -> None: + """Not in the fixture: the real window of 1024 at its seam, the module against float64.""" + heads, kv, hd, drel, rext = 8, 4, 128, 16, 1024 + for kind, window, pos0, rows in ((0, 1024, 1022, 4), (1, 0, 1022, 4)): + pos = pos0 + rows + seed = 0xA7F0 + kind + seed, q = unit_vectors(seed, rows * heads, hd, (1.0, 6.0, 12.0, 22.0)) + seed, k = unit_vectors(seed, pos * kv, hd, (3.0, 9.0, 16.0, 22.0)) + seed, v = unit_vectors(seed, pos * kv, hd, (math.sqrt(hd),)) + seed, rel = unit_vectors(seed, rows * heads, drel, (0.5, 2.0, 5.0, 8.0)) + proj = [] + for _ in range(drel): + seed, row = fill(seed, rext) + proj.append([bf16(a * 0.75) for a in row]) + seed, sink = fill(seed, rows * heads) + seed, gate = fill(seed, rows * heads * hd) + c = dict(kind=kind, heads=heads, kv=kv, hd=hd, drel=drel, rext=rext, window=window, rows=rows, pos0=pos0, + q=q, k=k, v=v, rel=rel, proj=proj, sink=[bf16(a * 3.0) for a in sink], + gate=[bf16(a * 3.0) for a in gate], name=f"real {'sliding' if kind == 0 else 'full'}, rows {pos0}..{pos0 + rows - 1}") + c["y"] = attend(c) + c["torch16"] = torch_attend(torch, module, c) + report([c]) + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("mode", choices=("write", "check")) + ap.add_argument("model_dir", type=Path, help=f"a local copy of {TINY}") + ap.add_argument("out", type=Path, nargs="?", help="write: the fixture file") + args = ap.parse_args() + cases = build(args.model_dir) + torch, module = modules() + for c in cases: + c["torch16"] = torch_attend(torch, module, c) + if args.mode == "write": + write(args.out or Path(__file__).resolve().parent.parent / "fixtures" / "attn_tiny.bin", cases) + else: + report(cases) + real_seams(torch, module) + + +if __name__ == "__main__": + main()