Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/06dc05c25b37eda9 # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#840 (code only) closed derived `06dc05c25b37eda9` #840 Imported from GitHub aien-dev/aien-sovereign-core-mv#840 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `85a185816307d435e89a77666de327c293c26961` · Head `2cc24642fdfd523b01dfc87d9eff946538825ca4` ### Apply it ``` git checkout -b patch-06dc05c25b37eda9 85a185816307d435e89a77666de327c293c26961 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/06dc05c25b37eda9.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 840 2cc24642fdfd523b01dfc87d9eff946538825ca4 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":840,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/840","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:06Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index a1d85d4c..aedac7bd 100644 --- a/.crumb +++ b/.crumb @@ -125,14 +125,14 @@ } ], "children_root": "sha256:05d34c0deec7c4a6cd3aa12640dca0c20bd8b2d4a4df809b234090822f422b4f", - "compiled_at": "2026-10-30T16:18:51Z", + "compiled_at": "2026-10-30T19:03:48Z", "compiler": "crumb-compile/1", - "digest": "sha256:af06cb85279b46470d7276e59a224e62adca55445ced89329d916e34a5374eda", + "digest": "sha256:3e46c88591e9580e9449b242b101999a69995a23c64e279df1ea96c4ace0a590", "evidence_files": 3602, "evidence_root": "sha256:1b8069934a4cc67803874ebd2ad5de32671fae5ccce1a3ea70aeb532fe8ea86b", "files": 8110, - "generated_at_commit": "37c2d29a321eaf169288f2b32403eff2e37197b7", - "source_tree": "sha256:66f00cf6eeab30f6701a7ec8f8a42484bfd8c2125336c6cdf39e9804f90c7e46" + "generated_at_commit": "339a09acbff9bf65f83a3ab4d90c34b166692ff7", + "source_tree": "sha256:1acb0ac14ae50d3bd0d676120b94ab7e29f6b2e6b59366d25770262dab5112fb" } }, "history": [], diff --git a/om/flint/PROFILE.md b/om/flint/PROFILE.md index f04ede04..c1075407 100644 --- a/om/flint/PROFILE.md +++ b/om/flint/PROFILE.md @@ -42,6 +42,7 @@ attention/experts on CPU with deterministic algorithms. | transformers source archive | 5d82e0de4bf993484299bcc1f2ef78d1d3f4ff23cee411f42f486b774f5f6615 | | admitted tensor inventory TSV | 60ff4dbdaa1c3632c934c6935aa60ed5b2def4e15f0ca5083ddc7dd660f083f5 | | chained forward fixture | b5e4bae28af3c1fa0c8f7454c496e72da1388e17f51bb3ec9e9b0387aac97031 | +| bf16-activation forward fixture | ac10d3254083d6768b3accb9c9b6678b3de6b751a81dae2bd9bfbf5a43949f91 | Per-shard hashes are in `PROFILE-SHARDS.sha256`; all 15 downloaded shards were rehashed and matched the source capture before this work. Storage is BF16, with @@ -68,8 +69,13 @@ Line numbers refer to pinned config.json and modeling_flint.py, respectively. Wolfram query for counts and modeled sizes is recorded in test/TOLERANCE.md. Reference behavior, not the inaccurate bias claim, is implemented. Native storage remains BF16; compute f64 vs reference f32 is an explicit numerical-profile change. -No BF16-activation, GPU, sampled-token, long-context, batching or task-quality -qualification follows from this candidate forward result. +The bf16-activation arm (#834 item 6, v3 criterion in test/TOLERANCE.md, EXERCISED on the host, +gate `OM-FLINT-MANIFEST PASS (100)` at 339a09ac) compares the native bf16-rounding forward with a +bf16 reference run. Tier A judges bf16 rounding presence and mode only at the anchor rows +(layer-0 input norm of both tokens); every later row has only the tier B gross band +`1/62898 <= M/D <= 62898`, which does not detect a missing or wrongly rounded site after the +anchor. No GPU, sampled-token, long-context, batching or task-quality qualification follows +from either forward result. ## Existing GPU contracts diff --git a/om/flint/README.md b/om/flint/README.md index 11687ac2..a7bf04b6 100644 --- a/om/flint/README.md +++ b/om/flint/README.md @@ -201,9 +201,14 @@ layer, expert index permuted (255 - e), and window 514. ## Not covered (NOT_RUN for this unit) -- bf16-activation parity: the referee runs in f32; -- generation, bf16 activations and long-context serving remain NOT_RUN; complete two-token - chained layer/intermediate/logit parity is now covered by the optional arm below; +- bf16-activation parity beyond the anchor: the optional bf16 arm below (`ops fwbf16`, v3 in + test/TOLERANCE.md) judges rounding presence and mode only at the anchor rows (layer-0 input + norm of both tokens, tier A). After the anchor it applies only the tier B gross band + (`1/62898 <= M/D <= 62898` per row), so a dropped or wrongly rounded bf16 site deeper in the + chain, up to all of them, is not detected: the `bf16-off` control stays inside the band in + almost every row and is caught only at the anchor; +- generation and long-context serving remain NOT_RUN; complete two-token chained + layer/intermediate/logit parity is covered by the optional arm below; - weight streaming and repacking, with peak allocation and residency measured during load; - per-expert layout checks before fusing; - tokenizer and control-token identity, and a load report. @@ -216,8 +221,12 @@ This unit has no GPU arm. A GGUF importer, if added, will be a separate optional It starts from two token IDs, loads real BF16 embedding rows and all selected expert weights, and compares five intermediate tensors per layer, final normalization and every vocabulary logit. The reference tensors are comparison targets, never teacher-forced inputs. -The full gate prints `OM-FLINT-MANIFEST PASS (92)` with real checkpoint inputs; wrong-token -and skipped-final-normalization source mutants must fail the comparison. +The full gate prints `OM-FLINT-MANIFEST PASS (100)` with real checkpoint inputs; wrong-token +and skipped-final-normalization source mutants must fail the comparison. It runs the same chain +a second time as the bf16-activation arm: `ops fwbf16 FX16 INVENTORY SHARDS FX32` rounds every +activation to bf16 at the reference's sites and is judged per row by the v3 criterion of +test/TOLERANCE.md, with `bf16-truncate`, `bf16-skip-final-norm` and `bf16-off` source mutants +that must FAIL and four fixture-admission refusals. See [PROFILE.md](PROFILE.md) for the frozen weight/runtime/tokenizer/template identities and the architecture audit. In particular, this checkpoint has **no expert bias**, unlike diff --git a/om/flint/check.sh b/om/flint/check.sh index 0c2b585a..a2d9734b 100755 --- a/om/flint/check.sh +++ b/om/flint/check.sh @@ -14,7 +14,10 @@ # FLINT_SHARDS=dir the 15 downloaded shards (config and index come from FLINT_SRC). # With both set, the forward-operator arm runs ops.om against test/opref.py fixtures; # FLINT_PY is the referee's interpreter (torch + transformers a672eb5f), default python3. -# FLINT_FORWARD=1 additionally runs the full 49-layer, two-token chained forward and mutants. +# FLINT_FORWARD=1 additionally runs the full 49-layer, two-token chained forward and mutants, +# twice: the f32 reference arm (ops forward) and the bf16-activation arm (ops fwbf16 FX16 ... +# FX32, v3 row criterion in test/TOLERANCE.md), each with its fixture admission controls and +# source mutants. # Needs: python3 (fixture referees only), sha256sum, cmp, timeout. Host only; no network, no GPU. set -u here=$(cd "$(dirname "$0")" && pwd) @@ -225,6 +228,13 @@ opr() { # binary op fixture; sets rc and line line=$(timeout 300 "$1" "$2" "$b/opfx/$3.bin" "$b/real.tsv" "$FLINT_SHARDS" 2>&1 < /dev/null) rc=$? } +fwmut() { # name op fixture from to [fx32]: builds ops.om ($s) with one literal swap, runs op; sets rc and line + [ "$(grep -cF -- "$4" "$here/ops.om")" = 1 ] || { bad "forward mutant $1 site"; return 1; } + printf '%s\n' "${s/"$4"/"$5"}" > "$b/fwdmut.om" + build "$b/fwdmut" "$b/fwdmut.om" || { bad "forward mutant $1 compile"; return 1; } + line=$(timeout 600 "$b/fwdmut" "$2" "$3" "$b/real.tsv" "$FLINT_SHARDS" "${@:6}" 2>&1 < /dev/null) + rc=$? +} if [ -n "${FLINT_SHARDS:-}" ] && [ -n "${FLINT_SRC:-}" ] && [ -s "$b/real.tsv" ]; then if ! build "$b/ops" "$here/ops.om"; then bad "ops: ops.om does not compile" elif ! ${FLINT_PY:-python3} "$here/test/opref.py" "$FLINT_SRC" "$FLINT_SHARDS" "$b/opfx" > "$b/opref.out" 2>&1 < /dev/null; then @@ -275,17 +285,45 @@ if [ "${FLINT_FORWARD:-0}" = 1 ]; then if [ "$rc" = 0 ] && [[ $line == *"forward layer 49 "* ]] && [[ $line == *" PASS" ]]; then ok "chained forward, all layers and vocabulary logits"; else bad "forward rc $rc"; fi s=$(cat "$here/ops.om") while IFS='|' read -r name from to; do - [ "$(grep -cF -- "$from" "$here/ops.om")" = 1 ] || { bad "forward mutant $name site"; continue; } - printf '%s\n' "${s/"$from"/"$to"}" > "$b/fwdmut.om" - build "$b/fwdmut" "$b/fwdmut.om" || { bad "forward mutant $name compile"; continue; } - line=$(timeout 600 "$b/fwdmut" forward "$b/forward.fx" "$b/real.tsv" "$FLINT_SHARDS" 2>&1 < /dev/null) - rc=$? + fwmut "$name" forward "$b/forward.fx" "$from" "$to" || continue if [ "$rc" = 1 ] && [[ $line == *" FAIL" ]]; then ok "CAUGHT forward mutant $name: ${line##*$'\n'}"; else bad "forward mutant $name rc $rc: $line"; fi done <<'FORWARD_MUTANTS' wrong-token|id = fx_w add 8 t|id = add fx_w add 8 t 1 skip-final-norm|put gfh o get gy i|put gfh o get gv i FORWARD_MUTANTS fi + # bf16-activation arm (#834 item 6): the reference runs at the shipped bf16 precision and + # ops.om fwbf16 rounds to bf16 at the same sites, budget declared in test/TOLERANCE.md. + if [ ! -s "$b/real.tsv" ] || [ ! -x "$b/ops" ]; then + echo "NOT_RUN bf16 forward (no admitted real.tsv or ops binary, failure reported above)" + elif ! ${FLINT_PY:-python3} "$here/test/fwdref.py" "$FLINT_SRC" "$FLINT_SHARDS" "$b/fwd16.fx" bf16 > "$b/fwdref16.out" 2>&1 < /dev/null; then + bad "bf16 forward referee: $(cat "$b/fwdref16.out")" + elif [ "$(sha "$b/fwd16.fx")" != ac10d3254083d6768b3accb9c9b6678b3de6b751a81dae2bd9bfbf5a43949f91 ]; then + bad "bf16 forward fixture pin mismatch: $(sha "$b/fwd16.fx")" + else + cat "$b/fwdref16.out" + line=$(timeout 600 "$b/ops" fwbf16 "$b/fwd16.fx" "$b/real.tsv" "$FLINT_SHARDS" "$b/forward.fx" 2>&1 < /dev/null) + rc=$? + echo "$line" + if [ "$rc" = 0 ] && [[ $line == *"fwbf16 layer 49 "* ]] && [[ $line == *" PASS" ]]; then ok "bf16-activation chained forward, all layers and vocabulary logits"; else bad "bf16 forward rc $rc"; fi + cp "$b/fwd16.fx" "$b/fwd16x.fx" + printf '\001' | dd of="$b/fwd16x.fx" bs=1 seek=40 conv=notrunc status=none + for c in "fwbf16 forward.fx forward.fx" "forward fwd16.fx" "fwbf16 fwd16x.fx forward.fx" "fwbf16 fwd16.fx fwd16.fx"; do + read -r o x f <<< "$c" + line=$(timeout 60 "$b/ops" "$o" "$b/$x" "$b/real.tsv" "$FLINT_SHARDS" ${f:+"$b/$f"} 2>&1 < /dev/null) + rc=$? + if [ "$rc" = 7 ] && [ "$line" = "refused 7 fixture" ]; then ok "REFUSED $c: $line"; else bad "$c not refused: rc $rc ${line##*$'\n'}"; fi + done + s=$(cat "$here/ops.om") + while IFS='|' read -r name from to; do + fwmut "$name" fwbf16 "$b/fwd16.fx" "$from" "$to" "$b/forward.fx" || continue + if [ "$rc" = 1 ] && [[ $line == *" FAIL" ]]; then ok "CAUGHT bf16 forward mutant $name: ${line##*$'\n'}"; else bad "bf16 forward mutant $name rc $rc: $line"; fi + done <<'BF16_MUTANTS' +bf16-truncate|r = and add u add 32767 and shr u 16 1 4294901760|r = and u 4294901760 +bf16-skip-final-norm|put gfh o get gy i|put gfh o get gv i +bf16-off|if ne get gbm 0 1|if true +BF16_MUTANTS + fi else echo "NOT_RUN chained forward (set FLINT_FORWARD=1)" fi diff --git a/om/flint/ops.om b/om/flint/ops.om index 9c507be3..11690bdb 100644 --- a/om/flint/ops.om +++ b/om/flint/ops.om @@ -3,7 +3,7 @@ note (aien-architecture-mv#353, aien-sovereign-core-mv#802, P0 forward lane). note note Usage: flint-ops OP FIXTURE INVENTORY SHARD_DIR note flint-ops selftest -note OP is rmsnorm, qkv, attn, router, shared, expert or moe. FIXTURE is written by +note OP is rmsnorm, qkv, attn, router, shared, expert, moe, forward or fwbf16. FIXTURE is written by note test/opref.py from the pinned reference modules; INVENTORY is the TSV flint-manifest note printed for SHARD_DIR. Each operator recomputes the reference output in f64 from the note real BF16 shard weights and carries a first-order bound E on the error of the @@ -12,7 +12,10 @@ note passes when |om - ref| <= 2 E. The router reports a token as a tie, not a m note the reference could hold the om rank-7 expert in its top-6 within those per-element bounds. note note Prints one line: flint-op OP layer L elems N worst_ppm P ties K PASS|FAIL, where P is -note max |om - ref| / (2 E) in millionths. Exit 0 PASS, 1 FAIL, 2 and up refused. +note max |om - ref| / (2 E) in millionths. Exit 0 PASS, 1 FAIL, 2 and up refused. fwbf16 +note scores rows by the v3 criterion of test/TOLERANCE.md (P is the largest row score in +note millionths of its threshold) and adds md_min_ppm, md_max_ppm (M/D) and nd_max_ppm (N/D) +note before PASS|FAIL. note note Layer kinds follow the pinned config.json (manifest CFG_PIN): no_rope_layer_indices note 0, 1, 5, 9, .., 45, 48 use full attention without RoPE; every other layer uses @@ -30,6 +33,8 @@ global gas ulong 8 global gal ulong 8 global gpth uchar 4352 global gfx uchar 8388608 +note gfz: the f32 reference fixture (op 8) that fwbf16 reads as its fifth argument +global gfz uchar 8388608 global gtsv uchar 8388608 global gstg uchar 4194304 global gw f32 16777216 @@ -74,7 +79,14 @@ global gfa f64 4096 global gfq f64 8192 global gfo f64 8192 global gfs ulong 4 +note gbm 0 is 1 in the bf16-activation forward arm (op fwbf16), where bfr rounds to bfloat16 +global gbm ulong 1 +note grw: fwbf16 open row sums 0 (om-ref16)^2, 1 (om-ref32)^2, 2 (ref16-ref32)^2, 3 elements +global grw f64 4 +note gbs: fwbf16 rows 0 min M/D, 1 max M/D, 2 max N/D, 3 rows judged +global gbs f64 4 text tofwd "forward" +text tofwb "fwbf16" text tembd "model.embed_tokens.weight" text tfnorm "model.norm.weight" text tlmhead "lm_head.weight" @@ -95,6 +107,9 @@ text tties " ties " text tpass " PASS" text tfail " FAIL" text tbf "BF16" +text tmdn " md_min_ppm " +text tmdx " md_max_ppm " +text tndx " nd_max_ppm " text tpre "model.layers." text tln0 "input_layernorm.weight" text tln1 "post_attention_layernorm.weight" @@ -264,6 +279,24 @@ op_close fd put gst 0 n end +note fwbf16 fifth argument: the f32 reference arm, same size as the bf16 fixture +fn rd_fz to void +fd = op_open op_argp 5 +n = get gst 9 +if ne n get gst 0 +op_die 7 tfx +end +o = ulong 0 +while lt o n bound 999999 +r = pread int fd gfz o sub n o long o +if le r 0 +op_die 3 tio +end +o = add o ulong r +end +op_close fd +end + fn rd_tsv to void fd = op_open op_argp 3 n = get gst 9 @@ -295,6 +328,18 @@ fn fx_f i ulong to f64 ret f64 bitcast f32 uint fx_w i end +fn fz_w i ulong to ulong +b = mul i 4 +v = or ulong get gfz b shl ulong get gfz add b 1 8 +v = or v shl ulong get gfz add b 2 16 +v = or v shl ulong get gfz add b 3 24 +ret v +end + +fn fz_f i ulong to f64 +ret f64 bitcast f32 uint fz_w i +end + fn fx_need w ulong to void if ne get gst 0 mul 4 w op_die 7 tfx @@ -353,6 +398,9 @@ ob_tx tppm ob_u ulong mul get gcm 0 1000000.0f64 ob_tx tties ob_u ulong get gcm 3 +if eq get gbm 0 1 +bf_rep +end f = gt get gcm 1 0.0f64 if f ob_tx tfail @@ -714,7 +762,7 @@ note Avoid accumulating two unused per-product error sums there. Keep the f64 pr note and reduction order identical to dotr. Router dotr remains bounded for tie reporting; note every local operator still calls the original bounded dotr path. fn matdot r ulong k ulong to f64 -if ne get gst 2 8 +if lt get gst 2 8 ret dotr r k end b = mul r k @@ -753,7 +801,7 @@ g = gam add n 6 for i ulong n w = f64 get gw add wo i v = get gv i -y = mul mul w v r +y = bfr mul mul w v r put gy i y q = add get gve i mul fabs v c q = mul q mul fabs w r @@ -778,8 +826,8 @@ note E_out = |c| E_a + |s| E_b + (|a| + |b|) E_cs + gamma_2 (|a c| + |b s|) fn rope_one pos ulong i ulong to void rope_cs pos i g2 = gam 2 -c = get gacc 3 -s = get gacc 4 +c = bfr get gacc 3 +s = bfr get gacc 4 a = get gy i b = get gy add i 64 x = mul add fabs a fabs b get gacc 5 @@ -787,8 +835,8 @@ t = add fabs mul a c fabs mul b s put gacc 9 add x mul g2 t t = add fabs mul b c fabs mul a s put gacc 10 add x mul g2 t -put gy i sub mul a c mul b s -put gy add i 64 add mul b c mul a s +put gy i bfr sub bfr mul a c bfr mul b s +put gy add i 64 bfr add bfr mul b c bfr mul a s a = get gye i b = get gye add i 64 t = add mul fabs c a mul fabs s b @@ -992,7 +1040,7 @@ z = add get gacc 8 es ez = add get gacc 9 mul es sm_eps sk 0.0f64 ez = add div ez z gam add T 4 for j ulong n -put gsc j div get gsc j z +put gsc j bfr div get gsc j z put gse j add get gse j ez end end @@ -1251,7 +1299,7 @@ put gve i get ge0 add b i end for r ulong I o = add mul add t0 t I r -put gx1 o matdot r FHID +put gx1 o bfr matdot r FHID put ge1 o dote FHID end end @@ -1266,7 +1314,7 @@ put gve i get ge0 add b i end for r ulong I o = add mul add t0 t I r -put gx2 o matdot r FHID +put gx2 o bfr matdot r FHID put ge2 o dote FHID end end @@ -1282,11 +1330,11 @@ end fn mlp_h1 o ulong to void g = get gx1 o -s = mul g om_sig g +s = bfr mul g om_sig g es = mul 1.1f64 get ge1 o es = add es mul gam 4 fabs s up = get gx2 o -h = mul s up +h = bfr mul s up put gx1 o h e = add mul fabs up es mul fabs s get ge2 o put ge1 o add e mul gam 1 fabs h @@ -1301,7 +1349,7 @@ put gve i get ge1 add b i end for r ulong FHID o = add mul add t0 t FHID r -put gx3 o matdot r I +put gx3 o bfr matdot r I put ge3 o dote I end end @@ -1345,7 +1393,7 @@ fn moe_acc t ulong w f64 ew f64 to void for i ulong FHID o = add mul t FHID i y = get gx3 o -put gacm o add get gacm o mul w y +put gacm o bfr add get gacm o bfr mul w y e = add get gace o mul fabs w get ge3 o put gace o add e mul fabs y ew put gaca o add get gaca o fabs mul w y @@ -1373,14 +1421,36 @@ put gmwe j get gtwe k end end +note moe_ex: the routed experts of token t; fwbf16 adds them in ascending expert index, the +note order of the reference's expert_hit loop, because each bf16 index_add_ rounds fn moe_ex L ulong t ulong to void for k ulong 6 -j = add mul t 6 k +j = moe_ord t k mlp L get gmk j 512 t add t 1 moe_acc t get gmw j get gmwe j end end +fn moe_ord t ulong k ulong to ulong +b = mul t 6 +if eq get gbm 0 0 +ret add b k +end +for j ulong 6 +c = ulong 0 +for i ulong 6 +if lt get gmk add b i get gmk add b j +c = add c 1 +end +end +if eq c k +ret add b j +end +end +op_die 7 tfx +ret b +end + fn moe_cmp t ulong yo ulong to void g8 = gam 8 for i ulong FHID @@ -1455,19 +1525,162 @@ end note Complete bounded host forward, two prompt tokens maximum. No teacher forcing: note only token IDs are inputs; the fixture's intermediate tensors are comparison targets. -note This f64-compute/BF16-storage numerical profile is NOT bf16-activation qualification. -note Integration acceptance is |om-ref| <= 8 gamma_2048 (1+|ref|), fixed before execution. +note forward (op 8): f64 compute, BF16 storage, against the f32 reference arm; acceptance is +note |om-ref| <= 8 gamma_2048 (1+|ref|), fixed before execution. +note fwbf16 (op 9): the same forward rounding to bfloat16 through bfr at the reference's bf16 +note sites (test/TOLERANCE.md), against both reference arms; every bf16 reference word must +note itself be a bfloat16 (low 16 bits zero) or the fixture is refused. Acceptance is the +note per-row v3 criterion of test/TOLERANCE.md, declared before the clean comparison. note The existing per-operator bounds remain the tighter local checks. fn fw_cmp n ulong to void o = get gfs 1 +if eq get gbm 0 1 +for i ulong n +bf_el add o i get gfa i +end +else for i ulong n r = fx_f add o i e = mul mul 4.0f64 gam 2048 add 1.0f64 fabs r cmp get gfa i r e end +end put gfs 1 add o n end +note bf_row: judges one complete fwbf16 row by the v3 criterion of test/TOLERANCE.md, with +note N = |om - ref16|, M = |om - ref32|, D = |ref16 - ref32|: D = 0 needs N = M = 0; every row +note with D > 0 needs 1/b <= M/D <= b, b = 62898; the anchor rows (layer-0 input norm, row T to +note 2T - 1) also need N^2 <= D^2 / 2; NaN fails. gcm 0 keeps the largest score (1 = threshold) +fn bf_row to void +n2 = get grw 0 +m2 = get grw 1 +d2 = get grw 2 +k = ulong get gbs 3 +T = get gfs 0 +s = 0.0f64 +if gt d2 0.0f64 +s = bf_scr n2 m2 d2 and ge k T lt k mul 2 T +else +if or gt n2 0.0f64 gt m2 0.0f64 +s = 1000000000.0f64 +end +end +if or or ne s s ne d2 d2 or ne n2 n2 ne m2 m2 +s = 1000000000.0f64 +end +if gt s get gcm 0 +put gcm 0 s +end +if gt s 1.0f64 +put gcm 1 add get gcm 1 1.0f64 +end +put gcm 2 add get gcm 2 get grw 3 +put gbs 3 add get gbs 3 1.0f64 +for i ulong 4 +put grw i 0.0f64 +end +end + +note bf_scr: the score of a row with D > 0, its largest ratio to a v3 threshold, capped at 10^9; +note records the extremes of M/D and N/D in gbs +fn bf_scr n2 f64 m2 f64 d2 f64 a bool to f64 +q = fsqrt div m2 d2 +p = fsqrt div n2 d2 +if lt q get gbs 0 +put gbs 0 q +end +if gt q get gbs 1 +put gbs 1 q +end +if gt p get gbs 2 +put gbs 2 p +end +b = 62898.0f64 +s = 1000000000.0f64 +if gt mul q b 1.0f64 +s = div q b +r = div div 1.0f64 q b +if gt r s +s = r +end +end +if a +r = mul p 1.4142135623730951f64 +if gt r s +s = r +end +end +if gt s 1000000000.0f64 +s = 1000000000.0f64 +end +ret s +end + +note bf_rep: the fwbf16 extremes of M/D and N/D in millionths, capped at 10^15 +fn bf_rep to void +ob_tx tmdn +bf_ppm get gbs 0 +ob_tx tmdx +bf_ppm get gbs 1 +ob_tx tndx +bf_ppm get gbs 2 +end + +fn bf_ppm x f64 to void +y = mul x 1000000.0f64 +if not le y 1000000000000000.0f64 +y = 1000000000000000.0f64 +end +ob_u ulong y +end + +note bf_el: one fwbf16 element w with native value v into the open row's sums; a row is 2048 +note values, or one token's 150144 logits, and is judged by bf_row when it is complete +fn bf_el w ulong v f64 to void +if ne and fx_w w 65535 0 +op_die 7 tfx +end +r = fx_f w +z = fz_f w +a = sub v r +b = sub v z +c = sub r z +put grw 0 add get grw 0 mul a a +put grw 1 add get grw 1 mul b b +put grw 2 add get grw 2 mul c c +put grw 3 add get grw 3 1.0f64 +n = ulong 2048 +T = get gfs 0 +if ge w add add 8 T mul mul T FHID 247 +n = 150144 +end +if eq ulong get grw 3 n +bf_row +end +end + +note bfr: in fwbf16 an activation is rounded as torch rounds a bf16 tensor, f64 to f32 (nearest +note even) and then f32 to bfloat16 by round to nearest, ties to even, on the bit pattern; +note identity in every other op +fn bfr x f64 to f64 +if ne get gbm 0 1 +ret x +end +u = bitcast uint f32 x +r = and add u add 32767 and shr u 16 1 4294901760 +ret f64 bitcast f32 r +end + +fn fw_rep to int +if eq get gbm 0 1 +q = report tofwb +ret q +end +r = report tofwd +ret r +end + fn fw_hidden to void for i ulong mul get gfs 0 FHID put gfa i get gfh i @@ -1506,7 +1719,7 @@ put gv i get gx0 add mul t FHID i put gve i 0.0f64 end for r ulong rows -put gx1 add mul t rows r matdot r FHID +put gx1 add mul t rows r bfr matdot r FHID end end end @@ -1568,7 +1781,7 @@ att_sm n get gsk h get gfs 0 put gacc 11 0.0f64 for d ulong 128 v = pv_d n add mul g 128 d -put gfo add b d v +put gfo add b d bfr v end end @@ -1602,12 +1815,12 @@ put gv i get gfo add mul t 4096 i put gve i 0.0f64 end for r ulong FHID -put gfa add mul t FHID r matdot r 4096 +put gfa add mul t FHID r bfr matdot r 4096 end end fw_cmp mul get gfs 0 FHID for i ulong mul get gfs 0 FHID -put gfh i add get gfh i get gfa i +put gfh i bfr add get gfh i get gfa i end end @@ -1629,7 +1842,7 @@ moe_ex L t end mlp L 999 1024 0 T for i ulong mul T FHID -put gx3 i add get gacm i get gx3 i +put gx3 i bfr add get gacm i get gx3 i end end @@ -1647,11 +1860,11 @@ put gfa i get gx3 i end fw_cmp mul get gfs 0 FHID for i ulong mul get gfs 0 FHID -put gfh i add get gfh i get gfa i +put gfh i bfr add get gfh i get gfa i end fw_hidden put gst 3 L -r = report tofwd +r = fw_rep if ne r 0 exit 1 end @@ -1709,7 +1922,7 @@ put gve i 0.0f64 end end v = matdot rem r 2048 FHID -put gfa 0 v +put gfa 0 bfr v fw_cmp 1 end end @@ -1731,7 +1944,7 @@ end fw_final fw_logits put gst 3 49 -r = report tofwd +r = fw_rep ret r end @@ -1760,13 +1973,32 @@ end if op_argeq 1 tofwd ret 8 end +if op_argeq 1 tofwb +ret 9 +end op_die 2 tu ret 0 end +note fwbf16 FX32 must be the f32 arm (op 8) of the same prompt: size, header words 2..7 +note and token IDs equal to the bf16 fixture's, or it is refused +fn fz_chk to void +rd_fz +if or ne fz_w 0 1347374150 ne fz_w 1 8 +op_die 7 tfx +end +n = div get gst 0 4 +for i ulong 8 +w = add i 2 +if and lt w n ne fz_w w fx_w w +op_die 7 tfx +end +end +end + fn main to int c = argcnt -if and ne c 5 ne c 2 +if and and ne c 5 ne c 2 ne c 6 op_die 2 tu end o = ulong 0 @@ -1789,6 +2021,9 @@ s = op_self ret s end op = op_code +if or and eq c 6 ne op 9 and ne c 6 eq op 9 +op_die 2 tu +end rd_fx rd_tsv if or ne fx_w 0 1347374150 ne fx_w 1 op @@ -1799,7 +2034,12 @@ put gst 3 fx_w 2 put gst 4 fx_w 3 put gst 5 fx_w 4 put gst 6 fx_w 5 -if eq op 8 +if eq op 9 +put gbm 0 1 +put gbs 0 1000000000.0f64 +fz_chk +end +if or eq op 8 eq op 9 s = op_forward ret s end diff --git a/om/flint/test/TOLERANCE.md b/om/flint/test/TOLERANCE.md index f5b7d39b..f0f5e424 100644 --- a/om/flint/test/TOLERANCE.md +++ b/om/flint/test/TOLERANCE.md @@ -219,3 +219,280 @@ returned The byte counts are modeled layout sizes, not measured memory usage. The chained fixture is pinned by SHA256 in `check.sh`; wrong-token and skipped-final-normalization source mutants must compile and return comparison exit 1, not a trap or setup refusal. + +## bf16-activation forward arm (Core #834 item 6, declared 2026-10-30 before the first comparison) + +The f32 arm above upcasts every module to f32. The checkpoint ships as bfloat16 +(`config.json` `torch_dtype: bfloat16`), so a second referee arm, `fwdref.py ... bf16` +(fixture op 9), runs the same two-token, 49-layer forward with every parameter in bfloat16 +except the model's `_keep_in_fp32_modules_strict` (`gate.weight`, `sinks`), and bfloat16 +activations. The pinned modules then round an f32 intermediate to bfloat16 (round to nearest, +ties to even) at these points, and nowhere else: + +| Site (pinned `modeling_flint.py`) | Rounded to bf16 | +|---|---| +| `FlintRMSNorm` (input, post-attention, q_norm, k_norm, final) | output `(weight * x rsqrt(..)).to(bf16)`; mean square and rsqrt stay f32 | +| every `nn.Linear` (q/k/v/o_proj, dense MLP, shared and routed experts, lm_head) | output, f32 accumulation | +| RoPE (`FlintRotaryEmbedding`, `apply_rotary_pos_emb`) | cos, sin; `q cos`; `rotate_half(q) sin`; their sum (k likewise) | +| eager attention | softmax probabilities (`.to(value.dtype)`) and the `P V` output; scores, sink and softmax stay f32 | +| MLP / experts | `silu(gate)`, `silu(gate) up` | +| `FlintExperts` | `y_e w_e` (bf16 times f32 weight is f32, then `.to(bf16)`); each `index_add_` into the bf16 accumulator, experts in ascending index order | +| `FlintSparseMoeBlock` | routed sum plus shared expert | +| `FlintDecoderLayer` | both residual adds | + +Router logits, sigmoid, top-6 and renormalized weights stay f32 (`hs.float()`, f32 weight). +Embedding rows are bf16 on disk and exact. Every value the bf16 arm writes is a bfloat16. +These semantics were probed on the pinned torch 2.14.0+cu130 CPU build before writing the arm: +bf16 `F.linear`, `matmul` and `silu` equal `bf16(f32 or f64 result)` element for element on +random inputs, `bf16 * f32` promotes to f32, and `torch.cat` of f32 and bf16 is f32. + +**What ops.om compares (option a).** `ops.om fwbf16` runs the same f64 forward with a bf16 +mode: `bfr` rounds to f32 and then to bfloat16 (nearest, ties to even, on the f32 bit +pattern, as torch does) at exactly the sites in the table, and sums routed experts in ascending +index order. Option b, the plain f64 forward against the bf16 reference, cannot see the rounding +mode at all: a native forward that rounded wrongly, or not at all, would be judged by the same +budget as one that rounds correctly. Under option a both sides round at the same sites, so most +compared elements should be bit-identical and the remaining differences are flips of one bf16 +ulp where the f32 (reference) and f64 (native) pre-rounding values straddle a rounding +boundary. The budget below then bounds how those flips propagate. + +**Budget (declared before measurement).** Per compared element +`|native - reference| <= 8 (gamma_2048 + 2 u_bf16) (1 + |reference|)`, `u_bf16 = 2^-8`. +Derivation: the f32 arm budget is 8 per-operator units of `gamma_2048` (the largest f32 +accumulation in the forward) and the measured f32 chained forward used 694277 ppm of it, so a +factor of 8 units held 49 chained layers with 31 percent headroom. In the bf16 arm each +operator output can additionally differ by one bf16 ulp, at most `2 u_bf16` relative, after the +same pre-rounding difference; the per-operator unit becomes `gamma_2048 + 2 u_bf16` and the +factor 8 is kept. Like the f32 arm, this is an explicit integration budget, **not** a derived +worst-case theorem; it is not tuned after observing the fixture. `fw_cmp` passes half of it to +`cmp`, which compares against twice the supplied bound. + +WolframLanguageEvaluator: +`u32 = 2^-24; u16 = 2^-8; g = 2048 u32/(1 - 2048 u32); b32 = 8 g; d32 = 694277/10^6 b32; b16 = 8 (g + 2 u16); {N[g, 18], N[b32, 18], N[d32, 12], N[2 u16, 18], N[b16, 18], N[b16/b32, 12], N[(g + 2 u16)/g, 12], N[b16/2, 18], N[d32/b16, 12]}` +returned +`{0.000122085215480405323, 0.000976681723843242583, 0.000678087657185, 0.0078125, 0.0634766817238432426, 64.9921875, 64.9921875, 0.0317383408619216213, 0.0106824685659}`. +So the bf16 budget is 0.0635 (1 + |ref|), 65.0 times the f32 arm budget; the f32 arm's measured +worst difference would use 1.07 percent of it. + +**Declared checks and predictions.** +- `fwbf16` on the bf16 fixture: predicted PASS. A router top-6 change caused by a flipped + bf16 input would exceed the budget and is reported as FAIL, not as a tie. +- Fixture admission: `fwbf16` refuses any fixture word that is not a bfloat16 (low 16 bits + nonzero) and an op-8 (f32) fixture; `forward` refuses an op-9 fixture. +- Mutant `bf16-truncate` (`bfr` truncates toward zero instead of rounding to nearest even): + predicted FAIL, because truncation biases every rounding toward zero and the residual stream + is rounded 98 times without renormalization. +- Mutant `bf16-skip-final-norm`: predicted FAIL. +- Control `bf16-off` (`bfr` is the identity, the plain f64 forward against the bf16 fixture, + i.e. option b) is measured and recorded whichever way it lands; it is not a gate entry, + because this budget was not derived to separate it. + +**v1 measured: FAIL at layer 1 (2026-10-30, fixture `ac10d325...`, host CPU `taskset -c 0-4`).** +The v1 budget above is kept unedited as declared in `9fb7d7ab`. `ops fwbf16` printed +`flint-op fwbf16 layer 0 elems 24576 worst_ppm 111729 ties 0 PASS` and then +`flint-op fwbf16 layer 1 elems 45056 worst_ppm 1441874 ties 0 FAIL` (rc 1). The truncation +mutant failed earlier, `layer 0 ... worst_ppm 4758150 ... FAIL`. Diagnostic builds (throwaway, +not in the tree) counted bit-identical elements per compared segment of 4096 (two tokens): +layer 0 embedding 4096, input norm 4096, attention output 4091, post-attention norm 4093, +MLP output 3410, hidden 3651; layer 1 input norm 3643, attention output 1836, post-attention +norm 2226, MLP output 1277, hidden 1813. The largest absolute attention, MLP and post-norm +difference in layer 0 is one bf16 ulp of its element. The three failing elements are +layer-1 post-attention-norm outputs 1205 and 1394 (token 0) and 2325 (token 1, channel 277), +with `|d|` 1.07 to 1.44 times the budget. Their inputs show the +mechanism, residual-add cancellation: + +| element | ref x (layer-0 hidden) | om x | ref attention | om attention | ref post-norm | om post-norm | +|---|---|---|---|---|---|---| +| 1205 | 0.00390625 | 0.0034179688 | -0.0043945312 | -0.0042419434 | -0.15234375 | -0.2578125 | +| 1394 | -0.0107421875 | -0.011230469 | 0.011657715 | 0.01171875 | 0.23730469 | 0.12695312 | +| 2325 | 0.0024414062 | 0.001953125 | 0.0007362366 | 0.00078201294 | 0.9453125 | 0.8125 | + +The layer-0 hidden `x` is itself a residual sum `h + mlp` of operands near 0.1 whose result is +near 0.004: a one-ulp flip of an operand (0.000488 near 0.11) lands on `x` as 32 of its own +ulps, and the post-attention norm multiplies it by `w_i / rms`. The error of a residual-stream +element is relative to its operands, not to `|ref_i|`, so no `(1 + |ref|)` constant bounds it, +and propagating a one-ulp flip through chained 2048-term dots worst-case grows without a useful +bound within one layer. No site mismatch was found: the differing-element counts grow from 5 +(layer-0 attention) to 686 (layer-0 MLP) to 2260 (layer-1 attention) of 4096, while the largest +absolute attention and MLP differences stay one ulp of their elements. +WolframLanguageEvaluator: +`ulp[x_] := 2^(Floor[Log2[Abs[x]]] - 7); {N[ulp[0.0039], 6], N[(0.00390625 - 0.0034179688)/ulp[0.0039], 6], N[(-0.15234375 + 0.2578125)/(0.0634766817238432426 (1 + 0.15234375)), 6], N[1 - 3410/4096, 6], N[1 - 2226/4096, 6]}` +returned `{0.0000152587890625, 31.999996723200013, 1.4418747364110336, 0.16748046875, 0.45654296875}` +(the third value is the reported worst 1441874 ppm). + +## bf16-activation forward arm, v2 criterion (declared 2026-10-30 after v1 failed, before any v2 comparison) + +v2 replaces the v1 criterion; it is not a widened v1. It was chosen after seeing the layer 0 and +1 diagnostics above and before computing any of its own quantities on either fixture. + +**Criterion.** For every compared row (one token at one compare point: 2048 values, or the +150144 logits), with `ref16` the bf16 fixture, `ref32` the f32 fixture (pinned `b5e4bae2...`, +same layout and token IDs) and `om` the native `fwbf16` value, +`N = ||om - ref16||_2` and `D = ||ref32 - ref16||_2`. **PASS iff `N <= D` for every row and no +value is NaN.** A row with `D = 0` (the exact embedding rows) passes only with `N = 0`. +`worst_ppm` reports `max N / D`. The constant 1 is the only one used and needs no data: the +native bf16 forward must be at least as close to the bf16 reference as the reference computed +without bf16 rounding is. `ops fwbf16` reads both fixtures (`fwbf16 FX16 INVENTORY SHARDS FX32`) +and refuses an `FX32` that is not op 8 with the same token IDs and size. + +**What v2 shows and does not show.** It is a discrimination criterion against the f32 referee's +own distance from the bf16 referee, not an error theorem. It detects systematic rounding +errors (a biased rounding mode, a skipped normalization, a routing change neither referee made) +through the whole chain. It does not prove each rounding site: dropping one intermediate rounding +can stay below the dense `ref32 - ref16` difference. Two tokens give attention at most two keys, +so bf16 softmax and `P V` rounding are lightly exercised. The bf16 `F.linear` probe used random +shapes, not the model's exact GEMM shapes (`[INFERENCE]` that dispatch does not change it). + +**Declared checks and predictions (v2).** +- `fwbf16` clean: predicted PASS with `N / D < 1` on every row. +- `bf16-truncate`: predicted FAIL at the layer-0 input norm, whose inputs are exact embedding + rows. There `ref32 - ref16` is the RNE rounding error, rms `1/sqrt 12` ulp, while truncation + differs from RNE by one ulp on about half the elements, rms `sqrt(1/2)` ulp: predicted + `N / D` near `sqrt 6 = 2.449`. +- `bf16-skip-final-norm`: predicted FAIL at the final-norm rows. +- Fixture admission as in v1, plus the `FX32` checks above. +- Control `bf16-off` (the plain f64 forward, option b): `om` then approximates `ref32`, so + `N / D` is predicted near 1 at the layer-0 input norm and the control is recorded, not gated. +- A routed top-6 change in `om` that neither referee made is a FAIL, reported with its layer. + +WolframLanguageEvaluator: +`{N[1/Sqrt[12], 6], N[Sqrt[1/2], 6], N[Sqrt[1/2]/(1/Sqrt[12]), 6], Sqrt[1/2]/(1/Sqrt[12])}` +returned `{0.288675134594812921, 0.7071067811865474617, 2.4494897427831780982, Sqrt[6]}`. + +## bf16-activation forward arm, v3 criterion (declared 2026-10-30 before any clean v2 or v3 comparison) + +v3 replaces v2. v2 was never run on the clean arm; the v1 record and the v2 text above are kept +unedited as history. + +**Why v2 is superseded (argument, no clean data).** Let `x` be the exact forward, +`e_om = om - x`, `e16 = ref16 - x`, and take `ref32 = x` to f32 accuracy. Then +`N^2 = M^2 + D^2 - 2 ` with `M = ||om - ref32||_2`. While the native and the reference +bf16 trajectories share their rounding outcomes, `N` is much smaller than `D`. The v1 counts above +show that they stop sharing them from layer 1 (1277 of 4096 layer-1 MLP outputs identical). With +correlation `rho` and `M` near `D`, `N / D` is near `sqrt(2 (1 - rho))`, which tends to `sqrt 2` +in deep rows. The `bf16-off` control has `om` near `ref32`, so its `N / D` is near 1 in every row. +v2 (`N <= D`) would therefore fail a correct native forward in decorrelated rows and pass +`bf16-off` there, and the same holds for any `N <= s D` or `N / ||ref16|| <= c`: in deep rows +they rank `bf16-off` closer than a correct bf16 forward. Rejecting `bf16-off` needs `M`. + +**Diagnostics seen before this declaration.** (1) Referee-only statistics of `ref16 - ref32` +(throwaway build, not in the tree, no native value involved): at the layer-0 input norm the +fresh-rounding energy `F = sum ulp_bf16(ref32_i)^2 / 12` is 0.97 to 1.02 of `D^2`; from layer 1 +on it is 0.02 to 0.06 of `D^2`, i.e. propagated noise dominates; from about layer 12 several +token-0 rows carry up to 90 percent of `D^2` in one massive-activation element (participation +ratio 1.2 to 20); at the two anchor rows below the largest single element holds 0.00338 and +0.00325 of `sum ulp_i^2`. (2) The controls `bf16-off` and `bf16-truncate` (gated mutants below) +were run with a statistics-only build of the v3 row sums before this commit: +`bf16-off` anchor `N / D` 0.999997 and 1.000000, `M / D` at most 9.5e-4 in every row and below +`1/b` in some; `bf16-truncate` anchor `N / D` 2.435 and 2.489, `M / D` 1.955 and 2.016, and +`M / D` from 0.50 to 22.8 over all rows. (3) The clean anchor outcome is already known from v1 +(all 4096 layer-0 input-norm values bit-identical, same native code path); tier A is +pre-registered against the mutants, not the clean arm. No threshold below uses (2) or (3): +`s_A` comes from the flip bound and `b` from `alpha = 0.01` and one degree of freedom. + +**Criterion.** Rows as in v2 (one token at one compare point, 2048 values, or one token's 150144 +logits; 496 rows for two tokens); `ops fwbf16 FX16 INVENTORY SHARDS FX32`. Per row: +- `D = 0` (the exact embedding rows): PASS iff `N = 0` and `M = 0`. +- Tier A, anchor rows, the layer-0 input norm of each token: PASS iff `N^2 <= D^2 / 2`. +- Tier B, every row with `D > 0`: PASS iff `1/b <= M / D <= b`, `b = 62898`. +- A NaN anywhere fails. The arm PASSes iff every row passes. +`worst_ppm` is the largest row score in parts per million of its threshold: +`N / (D / sqrt 2)` for tier A, `max(M / D, D / M) / b` for tier B; more than 10^6 is a FAIL. +The report also prints `md_min_ppm`, `md_max_ppm` (`M / D`) and `nd_max_ppm` (`N / D`). + +**Tier A derivation.** The anchor is the only compare point computed from exact inputs (bf16 +embedding rows) without cancellation: `w_i (x_i rsqrt(mean x^2 + eps))` computed in f32 (the +bf16 weight promotes to f32, `modeling_flint.py` `FlintRMSNorm`) and rounded once to bf16; the +native computes the same product in f64 and rounds once through `bfr` (f64 to f32 to bf16). A +native value can differ from the reference only where the f32 and f64 pre-rounding values +straddle a rounding boundary. Their relative difference is one common factor bounded by +`delta = gamma_2048 / 2 + 5 u_f32` (2048 positive f32 squares summed, then eps, rsqrt and two +products). An element straddles with probability at most `delta |v_i| / ulp_i <= 2^8 delta` +and then contributes `ulp_i^2` to `N^2`, while `D^2` is the fresh RNE energy `sum ulp_i^2 / 12` +(0.97 to 1.02 of it, measured on the referees). So `E[N^2] / D^2 <= 12 2^8 delta = 0.188` +(`N / D` 0.434) at the worst-case `delta`, and 0.0083 (`N / D` 0.091) at the probabilistic +`sqrt(2048) u_f32`. `bf16-off` has `N / D = 1` there and truncation `sqrt 6` (it differs from +RNE by one ulp on half the elements). The threshold `N / D <= 1/sqrt 2` sits above the +worst-case expectation and below both. Realization: with straddle indicators `B_i`, a FAIL +needs `sum B_i ulp_i^2 / sum ulp_i^2 > 0.5 / (12 1.016) = 0.0410`; one straddle adds at most +0.00338, so at least 13 straddles are needed, and Bernstein's inequality with that maximal +weight bounds the per-row false-fail probability by 0.020 at the deterministic worst-case +`delta` and by 4.1e-8 at the probabilistic one (equal weights at the worst case: binomial tail +1.4e-15). + +**Tier B derivation.** Null model for a correct native forward: `e_om` and `e16` are identically +distributed Gaussian vectors (sums of many independent roundings by the same mechanism), and +independent in decorrelated rows; positive correlation, as in early rows, only pulls `M / D` +toward 1. Among covariances `Sigma` of `a, b` independent `N(0, Sigma)`, rank 1 gives the +heaviest tail of `|a| / |b|`: proved for isotropic rank `k`, whose moments +`Gamma(k/2+s) Gamma(k/2-s) / Gamma(k/2)^2` decrease in `k`, and found numerically for the mixed +spectra sampled below; the massive-activation rows above are close to rank 1. The band +therefore uses the rank-1 tail as the conservative model: `M / D` is a ratio of two independent +half-normals, `P(M / D > t) = (2/pi) arctan(1/t)`, and the same for `D / M`. A family-wise +false-fail level `alpha = 0.01` over both tails of 494 rows (Bonferroni, no independence +needed) gives `b = cot(pi alpha / (4 494)) = 62898`. Tier B is a gross-error test: it rejects a +row more than 4.8 decades from bf16 noise parity. + +WolframLanguageEvaluator: +`{Integrate[f^2,{f,0,1/2}]+Integrate[(1-f)^2,{f,1/2,1}], Integrate[f^2,{f,0,1}], Integrate[1,{f,1/2,1}], Sqrt[(Integrate[1,{f,1/2,1}])/(Integrate[f^2,{f,0,1/2}]+Integrate[(1-f)^2,{f,1/2,1}])], Sqrt[Integrate[f^2,{f,0,1}]/(Integrate[f^2,{f,0,1/2}]+Integrate[(1-f)^2,{f,1/2,1}])]}` +returned `{1/12, 1/3, 1/2, Sqrt[6], 2}` (RNE energy, truncation energy, truncation minus RNE +energy, in ulp^2; truncation `N / D` and `M / D` at the anchor). +`u=2^-24; gam[n_]:=n u/(1-n u); d=gam[2048]/2+5u; {N[gam[2048]], N[d], N[12*2^8*d], N[12*2^8*Sqrt[2048]*u]}` +returned `{0.00012208521548040532, 0.00006134063096407961, 0.1884384183216526, 0.008286407592029853}`. +`g[a_,s_]:=Gamma[a+s]Gamma[a-s]/Gamma[a]^2; {Table[N[g[k/2,0.3]],{k,1,9,2}], Simplify[g[1/2,s]]}` +returned `{{1.7013016167040798, 1.0888330346906112, 1.0452797133029865, 1.0302276854314234, 1.0226586657017234}, (Gamma[1/2 - s]*Gamma[1/2 + s])/Pi}`. +`a=1/100; r=494; b=Cot[Pi a/(4 r)]; {N[b,8], N[1/b,8], N[2 r (2/Pi) ArcTan[1/b],8]}` +returned `{62898.0335046174539468839, 0.00001589874824825148567086119987266738, 0.01}`. +`SeedRandom[834]; n=10^6; tail[l_,t_]:=Module[{k=Length[l],a,b},a=RandomVariate[NormalDistribution[],{n,k}]^2 . l; b=RandomVariate[NormalDistribution[],{n,k}]^2 . l; N[Count[a/b,x_/;x>t^2]/n]]; specs={{1},{1,0.1},{1,0.5},{1,0.01,0.01,0.01,0.01},{1,1}}; Table[{s,tail[s,10],tail[s,100]},{s,specs}]` +returned `{{{1}, 0.063206, 0.006297}, {{1, 0.1}, 0.016694, 0.000185}, {{1, 0.5}, 0.010691, 0.00011}, {{1, 0.01, 0.01, 0.01, 0.01}, 0.010297, 2.*^-6}, {{1, 1}, 0.00968, 0.000108}}` +(`P(|a| / |b| > 10)` and `> 100`; rank 1 is heaviest in every case). +`wm=0.00338; thr=0.5/(12*1.016); bern[p_]:=Module[{t=thr-p},Exp[-t^2/(2 (p wm + wm t/3))]]; {N[thr], N[1/(12 wm)], N[bern[0.0157084]], N[bern[0.008286407592029853/12]], N[1-CDF[BinomialDistribution[2048,0.0157084],85]]}` +returned `{0.04101049868766404, 24.65483234714004, 0.01978754845307135, 4.0618080307047676*^-8, 1.4432899320127035*^-15}`. + +**What v3 shows and does not show.** Tier A alone carries the rounding-presence and +rounding-mode verdict: RMSNorm output on exact inputs, both tokens. Tier B checks every row of +the chain, including the logits, for gross divergence only. Neither tier detects any set of +dropped or wrongly rounded sites after the anchor, up to all of them: the `bf16-off` control's +`M / D` lies inside the tier B band in almost every row. With one native and one reference +trajectory, decorrelated deep rows and near-rank-1 massive-activation rows, rounding parity of +deep rows is not decidable at a useful false-fail level. "`ref32 = x` to f32 accuracy" is a +direction, not a number, in deep rows (the f32 arm used 694277 ppm of its budget); the v2 +argument does not depend on it. The per-operator bounds of ops 1 to 7 remain the tight local +checks. The v2 limitations (two keys in attention, random-shape `F.linear` probe) still apply. + +**Declared checks and predictions (v3).** +- `fwbf16` clean: predicted PASS, anchor `N / D` below 0.434 (most likely near 0, v1 saw all + 4096 anchor values bit-identical), every `M / D` inside the band. +- `bf16-off` (gated mutant: `bfr` is the identity): predicted FAIL at tier A, anchor `N / D` + near 1 (row statistics already seen, (2) above; the gated verdict is not yet run). +- `bf16-truncate`: predicted FAIL at tier A, anchor `N / D` near `sqrt 6`, `M / D` near 2 (row + statistics already seen, (2) above; the gated verdict is not yet run). +- `bf16-skip-final-norm`: predicted FAIL at tier B on the token-0 final-norm row, `M / D` near + `||ref32 layer-48 hidden|| / D = 16557.8 / 0.183 = 90480` (referee norms; 1.44 times `b`). + The token-1 row is marginal (`18530.9 / 0.287 = 64568`, 1.03 times `b`); the logits rows are + not predicted numerically (their direction under the mutant depends on `lm_head`). +- Fixture admission: v2's, including an `FX32` that is not op 8 or differs in size or token IDs. +WolframLanguageEvaluator: `{N[16557.8/0.183,6], N[18530.9/0.287,6], N[62898.0335/(16557.8/0.183)], N[Sqrt[0.1884384183216526],6], N[Sqrt[0.008286407592029853],6]}` +returned `{90479.78142076502, 64567.59581881534, 0.6951612007935837, 0.43409494159878503, 0.09102970719512314}`. + +**v3 measured (host only, EXERCISED, after declaration commit e9274902).** Full gate +`FLINT_FORWARD=1 bash om/flint/check.sh` on 8a3caf40 plus the check.sh wiring commit: +`OM-FLINT-MANIFEST PASS (100)`, 3m49.6s wall under the shared lock. +- `fwbf16` clean: `layer 49 elems 1312000 worst_ppm 179 ties 6 md_min_ppm 88417 md_max_ppm + 5041815 nd_max_ppm 5208925 PASS`; layer-0 worst_ppm 15 (anchor within tier A by far). + `M / D` stays in 0.088 to 5.04, inside the band by more than 4 decades. +- `bf16-off`: FAIL at layer 0, worst_ppm 1414212 (anchor `N / D` 1.000, tier A), md 24 to 520 ppm. +- `bf16-truncate`: FAIL at layer 0, worst_ppm 3520459 (anchor `N / D` 2.49), md_min 1.95. +- `bf16-skip-final-norm`: FAIL at layer 49, worst_ppm 1614446 (largest `M / D` 101545, 1.61 `b`). +- Fixture admission: `fwbf16 forward.fx forward.fx`, `forward fwd16.fx`, `fwbf16 fwd16x.fx + forward.fx` and `fwbf16 fwd16.fx fwd16.fx` (FX32 not op 8) each `refused 7 fixture`. +Every predicted verdict held, but the skip-final-norm prediction was wrong about where it fails. +A diagnostic build (the gated mutant plus a per-row print, run after 339a09ac, not in the tree) +shows the maximum `M / D = 101545` is row 494 (0-based), the token-0 logits row, and the only +failing row: token-1 logits (row 495) has `M / D` 32549, and the final-norm rows 492 and 493 +have 1.52 and 0.56, because the mutant feeds the unnormalized hidden state to `lm_head` while +the final-norm comparison still sees the normalized value. The mutant is therefore caught by one +row at 1.61 `b`, not by the predicted final-norm row. +WolframLanguageEvaluator: `{N[101545.459/62898.0335,6], N[32549.425/62898.0335,6]}` returned +`{1.6144456885126626, 0.5174951137383333}`. The clean v3 run is the first clean comparison +under v2 or v3, after e9274902. diff --git a/om/flint/test/fwdref.py b/om/flint/test/fwdref.py index 0861a1d5..5ef410d5 100755 --- a/om/flint/test/fwdref.py +++ b/om/flint/test/fwdref.py @@ -1,12 +1,30 @@ #!/usr/bin/env python3 """Read-only pinned Flint referee for ops.om forward, not a runtime dependency. -Usage: fwdref.py SRC SHARDS OUTPUT -Header matches opref.py, op 8, T=2, then two token IDs, embeddings, -for each of 49 layers: input norm, attention output, post-attention norm, -MLP output, residual output. Finally final norm and all vocabulary logits. -All tensors are contiguous little-endian f32. Weights stay BF16 on disk; -reference computation is float32 on CPU. No sampling or generation is claimed. +Usage: fwdref.py SRC SHARDS OUTPUT [bf16] +Header matches opref.py, op 8 (f32 arm) or 9 (bf16 arm), T=2, then two token +IDs, embeddings, for each of 49 layers: input norm, attention output, +post-attention norm, MLP output, residual output. Finally final norm and all +vocabulary logits. All tensors are written as contiguous little-endian f32. +Weights stay BF16 on disk. No sampling or generation is claimed. + +f32 arm: every module is upcast to float32, so the forward runs in f32 on CPU. + +bf16 arm: the precision the checkpoint ships with (config.json torch_dtype +bfloat16). Every parameter is bfloat16 except the model's +_keep_in_fp32_modules_strict ("gate.weight", "sinks"), which stay float32; +activations are bfloat16. The pinned modules then round to bfloat16 +(round to nearest even, from an f32 intermediate) at exactly these points +(test/TOLERANCE.md, bf16 forward arm): every nn.Linear output (q/k/v/o_proj, +gate/up/down_proj of the dense MLP, shared and routed experts, lm_head +logits); every FlintRMSNorm output (input, post-attention, q_norm, k_norm, +final); RoPE cos and sin, q*cos, rotate_half(q)*sin and their sum (same for +k); the softmax probabilities before P V and the P V output; silu(gate) and +silu(gate)*up; each routed expert output times its f32 routing weight; each +index_add_ into the bf16 accumulator (experts in ascending index order); the +routed sum plus the shared expert; both residual adds. Router logits, +sigmoid, top-k and weights, attention scores and softmax stay float32. +Every written bf16-arm value is therefore a bfloat16 (low 16 bits zero). """ import hashlib import json @@ -24,12 +42,18 @@ CFG_SHA = "849eee3068846081077a7568663355802c8c4eec3741d92cd578d222bd144d00" for path, pin in ((mf.__file__, REF_SHA), (cf.__file__, CFG_SHA)): if hashlib.sha256(open(path, "rb").read()).hexdigest() != pin: sys.exit("fwdref: reference source pin mismatch: " + path) +if mf.FlintPreTrainedModel._keep_in_fp32_modules_strict != ["gate.weight", "sinks"]: + sys.exit("fwdref: fp32 module list changed") if torch.__version__ != "2.14.0+cu130": sys.exit("fwdref: torch pin mismatch: " + torch.__version__) torch.set_num_threads(1) torch.set_grad_enabled(False) torch.use_deterministic_algorithms(True) src, shards, output = sys.argv[1:4] +BF16 = sys.argv[4:] == ["bf16"] +if not BF16 and sys.argv[4:]: + sys.exit("fwdref: usage: fwdref.py SRC SHARDS OUTPUT [bf16]") +DT = torch.bfloat16 if BF16 else torch.float32 cfg = cf.FlintConfig(**json.load(open(os.path.join(src, "config.json")))) cfg._attn_implementation = "eager" cfg._experts_implementation = "eager" @@ -47,13 +71,18 @@ def shard(name): def tensor(name): t = shard(name).get_tensor(name) assert t.dtype == torch.bfloat16, (name, t.dtype) - return t.float() + return t.to(DT) def load(module, prefix, rename=None): state = {k: tensor(prefix + (rename or {}).get(k, k)) for k in module.state_dict()} module.load_state_dict(state, strict=True) - return module.float().eval() + module.to(DT) + # The shipped bf16 model keeps mf.FlintPreTrainedModel._keep_in_fp32_modules_strict in f32. + for k, v in module.named_parameters(): + if isinstance(module, mf.FlintTopKRouter) and k == "weight" or k == "sinks": + v.data = v.data.float() + return module.eval() def norm(prefix): @@ -75,7 +104,7 @@ def sparse(prefix): c = cf.FlintConfig(**cfg.to_dict()) c._experts_implementation = "eager" c.num_experts = 1 - ex = mf.FlintExperts(c).float() + ex = mf.FlintExperts(c).to(DT) del ex.gate_up_proj, ex.down_proj ex.gate_up_proj, ex.down_proj = Lazy(prefix, "gate_up"), Lazy(prefix, "down") ex.num_experts = cfg.num_experts @@ -93,12 +122,12 @@ def write(f, x): ids = [1001, 8920] sl = shard("model.embed_tokens.weight").get_slice("model.embed_tokens.weight") -x = torch.cat([sl[i:i + 1] for i in ids]).float().unsqueeze(0) +x = torch.cat([sl[i:i + 1] for i in ids]).to(DT).unsqueeze(0) pos = torch.arange(len(ids)).unsqueeze(0) rope = mf.FlintRotaryEmbedding(cfg)(x, pos) -mask = torch.triu(torch.full((len(ids), len(ids)), torch.finfo(torch.float32).min), diagonal=1)[None, None] +mask = torch.triu(torch.full((len(ids), len(ids)), torch.finfo(DT).min), diagonal=1)[None, None] with open(output, "wb") as f: - f.write(struct.pack("<8I", 0x504F4C46, 8, 0, len(ids), 0, 0, 21400, 0)) + f.write(struct.pack("<8I", 0x504F4C46, 9 if BF16 else 8, 0, len(ids), 0, 0, 21400, 0)) f.write(struct.pack("<2I", *ids)) write(f, x) for L in range(cfg.num_hidden_layers): @@ -129,9 +158,9 @@ with open(output, "wb") as f: write(f, x) name = "lm_head.weight" sl = shard(name).get_slice(name) - # Stream the vocabulary in the same row chunks as Omega, never allocate all weights in f32. + # Stream the vocabulary in the same row chunks as Omega, never allocate all weights at once. for t in range(len(ids)): for first in range(0, cfg.vocab_size, 2048): - w = sl[first:first + 2048].float() + w = sl[first:first + 2048].to(DT) write(f, torch.nn.functional.linear(x[0, t:t + 1], w)) print("fwdref complete", hashlib.sha256(open(output, "rb").read()).hexdigest(), flush=True) ```