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/89b4608d5787da5f # 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#838 (code only) closed derived `89b4608d5787da5f` #838 Imported from GitHub aien-dev/aien-sovereign-core-mv#838 (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 `1beb5600367c0ed200588e49f1faa2fa25257e41` ### Apply it ``` git checkout -b patch-89b4608d5787da5f 85a185816307d435e89a77666de327c293c26961 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/89b4608d5787da5f.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 838 1beb5600367c0ed200588e49f1faa2fa25257e41 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":838,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/838","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:38:06Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index a1d85d4c..47dc5115 100644 --- a/.crumb +++ b/.crumb @@ -125,14 +125,14 @@ } ], "children_root": "sha256:05d34c0deec7c4a6cd3aa12640dca0c20bd8b2d4a4df809b234090822f422b4f", - "compiled_at": "2026-10-30T16:18:51Z", + "compiled_at": "2026-10-30T18:12:25Z", "compiler": "crumb-compile/1", - "digest": "sha256:af06cb85279b46470d7276e59a224e62adca55445ced89329d916e34a5374eda", + "digest": "sha256:add9ac23ba8a621b5fe14319ec1eddfe1bd18d33e348fc0bf5be0517ce5220d5", "evidence_files": 3602, "evidence_root": "sha256:1b8069934a4cc67803874ebd2ad5de32671fae5ccce1a3ea70aeb532fe8ea86b", "files": 8110, - "generated_at_commit": "37c2d29a321eaf169288f2b32403eff2e37197b7", - "source_tree": "sha256:66f00cf6eeab30f6701a7ec8f8a42484bfd8c2125336c6cdf39e9804f90c7e46" + "generated_at_commit": "8be54048a14984e5c2c630d11a3b025e46d1cd04", + "source_tree": "sha256:cc3bf7e73d2119bacab6097a5875cce7980b41bd975ab397a79d1aac8141d2ba" } }, "history": [], diff --git a/om/flint/README.md b/om/flint/README.md index 11687ac2..2515d843 100644 --- a/om/flint/README.md +++ b/om/flint/README.md @@ -202,8 +202,9 @@ 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 activations and long-context serving remain NOT_RUN; complete two-token chained + layer/intermediate/logit parity and 16-token greedy generation are covered by the optional + arms 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,13 +217,35 @@ 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 +The full gate prints `OM-FLINT-MANIFEST PASS (95)` with real checkpoint inputs; wrong-token and skipped-final-normalization source mutants must fail the comparison. +`flint-ops decode` runs the same fixture as a KV-cache decode: one row per chunk, each layer +appends that row's K/V to a per-layer cache (49 layers x 32 positions x 512) and attention reads +every earlier position only from that cache. It must PASS the same reference within the same +budget and element count as the batch forward (a tolerance check, not a bitwise decode-vs-batch +comparison); the `kv-slot-overwrite` mutant (cache row written at slot 0) must fail. The cache +holds `FKVP` = 32 positions per layer and `fw_kv` refuses `P+n > FKVP` (`refused 7 kv-cache-bound`); +the gate rebuilds with `FKVP` 1 and requires that refusal. + +## Greedy generation + +`FLINT_GEN=1` (with `FLINT_SRC`, `FLINT_SHARDS` and `FLINT_PY`) adds `flint-ops generate`. +[test/genref.py](test/genref.py) renders `What is 2+2?` with the pinned chat template +(`[150003, 2387, 332, 220, 17, 10, 17, 30, 150004]`, no BOS) and greedy-generates 16 tokens with +the pinned f32 reference and its KV cache; the fixture (sha256 pinned in check.sh) holds the prompt +IDs and each step's reference top-1/top-2 IDs and logits. The .om side runs the prompt one row at a +time through its KV cache, takes its own argmax, feeds that token back, and applies the rule frozen +in [test/TOLERANCE.md](test/TOLERANCE.md) (greedy generation parity) on every step; each step prints +the .om and reference IDs and logits. The gate requires `flint-gen matched 16 of 16` and a PASS +verdict, requires the `skip-kv-append-L0` mutant (layer 0 never appends K/V) to FAIL, and rebuilds +with `FKVP` 8 to require `refused 7 kv-cache-bound` at position 8. Measured on host CPU (cores 0-4): +16 of 16 tokens, about 24 s per generated token; see TOLERANCE.md for the numbers. + 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 the requested selection-only bias description. [test/TOLERANCE.md](test/TOLERANCE.md) declares the candidate integration budget separately from the tighter per-operator bounds. Native f64 computation with BF16 storage is compared to reference f32 computation. This is host-forward evidence only: no serving API, task completion, quantized model, -KV-cache, long-context batching or GPU/backend qualification is claimed. +paged/ring KV-cache beyond 32 positions, long-context batching or GPU/backend qualification is claimed. diff --git a/om/flint/check.sh b/om/flint/check.sh index 0c2b585a..d523298c 100755 --- a/om/flint/check.sh +++ b/om/flint/check.sh @@ -15,6 +15,7 @@ # 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_GEN=1 runs greedy 16-token generation from a chat-template prompt against test/genref.py. # Needs: python3 (fixture referees only), sha256sum, cmp, timeout. Host only; no network, no GPU. set -u here=$(cd "$(dirname "$0")" && pwd) @@ -273,22 +274,81 @@ if [ "${FLINT_FORWARD:-0}" = 1 ]; then rc=$? echo "$line" if [ "$rc" = 0 ] && [[ $line == *"forward layer 49 "* ]] && [[ $line == *" PASS" ]]; then ok "chained forward, all layers and vocabulary logits"; else bad "forward rc $rc"; fi + # KV-cache decode: one row per chunk, earlier K/V only from the cache, same fixture and budget + dline=$(timeout 900 "$b/ops" decode "$b/forward.fx" "$b/real.tsv" "$FLINT_SHARDS" 2>&1 < /dev/null) + rc=$? + dlast=${dline##*$'\n'}; de=${dlast##*elems }; fe=${line##*elems } + echo "$dlast" + if [ "$rc" = 0 ] && [[ $dlast == "flint-op decode layer 49 "* ]] && [[ $dlast == *" PASS" ]] && [ "${de%% *}" = "${fe%% *}" ]; then ok "KV-cache decode passes the same forward reference within budget, same element count"; else bad "decode rc $rc"; fi + # cache bound: with FKVP 1 the two-row decode must be refused (7), never overrun the next layer + [ "$(grep -c '^const FKVP ulong 32$' "$here/ops.om")" = 1 ] || bad "kv guard: FKVP site" + { s=$(cat "$here/ops.om"); printf '%s\n' "${s/const FKVP ulong 32/const FKVP ulong 1}"; } > "$b/kvg.om" + if build "$b/kvg" "$b/kvg.om"; then + gline=$(timeout 900 "$b/kvg" decode "$b/forward.fx" "$b/real.tsv" "$FLINT_SHARDS" 2>&1 < /dev/null); rc=$? + if [ "$rc" = 7 ] && [[ $gline == *"refused 7 kv-cache-bound"* ]]; then ok "KV cache bound refuses P+n > FKVP (rc 7)"; else bad "kv guard rc $rc: ${gline##*$'\n'}"; fi + else bad "kv guard compile"; fi s=$(cat "$here/ops.om") - while IFS='|' read -r name from to; do + while IFS='|' read -r name op 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) + line=$(timeout 900 "$b/fwdmut" "$op" "$b/forward.fx" "$b/real.tsv" "$FLINT_SHARDS" 2>&1 < /dev/null) rc=$? - if [ "$rc" = 1 ] && [[ $line == *" FAIL" ]]; then ok "CAUGHT forward mutant $name: ${line##*$'\n'}"; else bad "forward mutant $name rc $rc: $line"; fi + if [ "$rc" = 1 ] && [[ $line == *" FAIL" ]]; then ok "CAUGHT $op mutant $name: ${line##*$'\n'}"; else bad "$op 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 +wrong-token|forward|id = get gtok add get gfs 2 t|id = add get gtok add get gfs 2 t 1 +skip-final-norm|forward|put gfh o get gy i|put gfh o get gv i +kv-slot-overwrite|decode|c = mul add add mul L FKVP P j 512|c = mul add mul L FKVP j 512 FORWARD_MUTANTS fi else echo "NOT_RUN chained forward (set FLINT_FORWARD=1)" fi +# 6. greedy generation (Core #834 item 5), opt-in: 24 one-row host forwards and 16 vocabulary passes. +# test/genref.py renders "What is 2+2?" with the pinned chat template and greedy-generates 16 +# tokens with the pinned reference in f32 (KV cache); the fixture holds the prompt IDs and each +# step's reference top-1/top-2 IDs and logits. ops.om generate feeds its own argmax tokens back +# through its KV cache and must meet test/TOLERANCE.md (greedy generation parity) on every step. +# Controls: the K/V append skipped for layer 0 must FAIL (rc 1, the comparison); with FKVP 8 the +# request must be refused at position 8 (rc 7), never overrun the cache. +GEN_PIN=d5d3daecc777532638758402839a0bdfcdc9455ea913cd48c4941390c69c95e9 +genr() { # binary; sets rc, gline, glast + gline=$(timeout 3600 "$1" generate "$b/gen.fx" "$b/real.tsv" "$FLINT_SHARDS" 2>&1 < /dev/null) + rc=$? + glast=${gline##*$'\n'} +} +if [ "${FLINT_GEN:-0}" = 1 ]; then + if [ -z "${FLINT_SRC:-}" ] || [ -z "${FLINT_SHARDS:-}" ] || [ ! -s "$b/real.tsv" ] || [ ! -x "$b/ops" ]; then + bad "generate requested without FLINT_SRC, FLINT_SHARDS, admitted real.tsv and a compiled ops.om" + elif ! ${FLINT_PY:-python3} "$here/test/genref.py" "$FLINT_SRC" "$FLINT_SHARDS" "$b/gen.fx" > "$b/genref.out" 2>&1 < /dev/null; then + bad "generate referee: $(tail -c 300 "$b/genref.out")" + elif [ "$(sha "$b/gen.fx")" != "$GEN_PIN" ]; then + bad "generate fixture pin mismatch: $(sha "$b/gen.fx")" + else + cat "$b/genref.out" + genr "$b/ops" + echo "$gline" + if [ "$rc" = 0 ] && [[ $gline == *"flint-gen matched 16 of 16"* ]] && [[ $glast == "flint-op generate layer 49 "* ]] && [[ $glast == *" PASS" ]]; then ok "greedy generation, 16 of 16 tokens match the reference"; else bad "generate rc $rc: $glast"; fi + s=$(cat "$here/ops.om") + from='kvn = get gfs 0' + if [ "$(grep -cF -- "$from" "$here/ops.om")" != 1 ]; then bad "generate mutant skip-kv-append-L0 site" + else + printf '%s\n' "${s/"$from"/kvn = mul get gfs 0 sub 1 div 1 add L 1}" > "$b/genmut.om" + if build "$b/genmut" "$b/genmut.om"; then + genr "$b/genmut" + if [ "$rc" = 1 ] && [[ $glast == *" FAIL" ]]; then ok "CAUGHT generate mutant skip-kv-append-L0: $glast"; else bad "generate mutant skip-kv-append-L0 rc $rc: $glast"; fi + else bad "generate mutant compile"; fi + fi + printf '%s\n' "${s/const FKVP ulong 32/const FKVP ulong 8}" > "$b/genkv.om" + if build "$b/genkv" "$b/genkv.om"; then + genr "$b/genkv" + if [ "$rc" = 7 ] && [[ $gline == *"refused 7 kv-cache-bound"* ]]; then ok "generate with FKVP 8 refused at the cache bound (rc 7)"; else bad "generate kv guard rc $rc: $glast"; fi + else bad "generate kv guard compile"; fi + fi +else + echo "NOT_RUN greedy generation (set FLINT_GEN=1)" +fi + n=$((pass + fail)) if [ "$fail" = 0 ]; then echo "OM-FLINT-MANIFEST PASS ($n)"; else echo "OM-FLINT-MANIFEST FAIL ($fail of $n)"; exit 1; fi diff --git a/om/flint/ops.om b/om/flint/ops.om index 9c507be3..3d7cfa07 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 decode. 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 @@ -74,7 +74,28 @@ global gfa f64 4096 global gfq f64 8192 global gfo f64 8192 global gfs ulong 4 +note gkc/gvc: per-layer K and V cache, 49 layers x FKVP positions x 512 (4 kv heads x 128); +note the global size 802816 = 49 x FKVP x 512 must change with FKVP. fw_kv refuses P+n > FKVP. +note FKVP 32 holds the generate fixture: 9 prompt positions + 15 fed-back tokens = 24. +const FKVP ulong 32 +global gkc f64 802816 +global gvc f64 802816 +note gtok: token ID per position (fixture prompt, then generated); ggi/ggt: generate top-1/top-2 +note IDs and logits (slots 0, 1) and the reference top-1/top-2 IDs with the om logits there (2, 3) +global gtok ulong 1024 +global ggi ulong 4 +global ggt f64 4 text tofwd "forward" +text todec "decode" +text togen "generate" +text tgst "flint-gen step " +text tgom " om" +text tgat " at-ref" +text tgrf " ref" +text tgamb " ambiguous" +text tgbig " nan-or-big" +text tgmt "flint-gen matched " +text tgof " of " text tembd "model.embed_tokens.weight" text tfnorm "model.norm.weight" text tlmhead "lm_head.weight" @@ -84,6 +105,7 @@ text tu "usage: flint-ops OP FIXTURE INVENTORY SHARD_DIR | flint-ops selftest" text tio "io" text tnreg "not-regular-file" text tfx "fixture" +text tkv "kv-cache-bound" text tnf "tensor-not-in-inventory" text tdt "tensor-dtype-or-shape" text tref "refused " @@ -714,7 +736,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 @@ -1458,14 +1480,38 @@ note only token IDs are inputs; the fixture's intermediate tensors are compariso 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 The existing per-operator bounds remain the tighter local checks. -fn fw_cmp n ulong to void -o = get gfs 1 +note gfs slots: 0 rows n in this chunk, 1 tensor index, 2 first position P, 3 mode (1 decode). +note A chunk computes rows P .. P+n only; attention reads earlier K/V from gkc/gvc. +note forward runs one chunk of T rows; decode runs T chunks of one row (KV-cache decode). +fn fw_cmpat o ulong n ulong to void +if eq get gfs 3 2 +ret +end 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 -put gfs 1 add o n +end + +note fixture tensor s holds T rows of FHID after the header and IDs; rows P .. P+n are contiguous +fn fw_cmp n ulong to void +T = get gst 4 +o = add add 8 T mul add mul get gfs 1 T get gfs 2 FHID +fw_cmpat o n +put gfs 1 add get gfs 1 1 +end + +fn fw_rep to int +if eq get gfs 3 2 +ret 0 +end +if eq get gfs 3 1 +r = report todec +ret r +end +r = report tofwd +ret r end fn fw_hidden to void @@ -1519,7 +1565,7 @@ put gve d 0.0f64 end rmsv 128 0 if rp -ropev t +ropev add get gfs 2 t end for d ulong 128 if eq nh 32 @@ -1563,8 +1609,8 @@ for d ulong 128 put gv d get gfq add b d end g = div h 8 -n = att_sc g t 0 -att_sm n get gsk h get gfs 0 +n = att_sc g add get gfs 2 t 0 +att_sm n get gsk h add get gfs 2 get gfs 0 put gacc 11 0.0f64 for d ulong 128 v = pv_d n add mul g 128 d @@ -1572,6 +1618,34 @@ put gfo add b d v end end +note fw_kv: append this chunk's K (gx2) and V (gx3) rows to layer L's cache at positions +note P .. P+n, then rebuild gx2/gx3 positions 0 .. P+n from the cache for attention +fn fw_kv L ulong to void +P = get gfs 2 +if gt add P get gfs 0 FKVP +op_die 7 tkv +end +kvn = get gfs 0 +for j ulong kvn +c = mul add add mul L FKVP P j 512 +for i ulong 512 +put gkc add c i get gx2 add mul j 512 i +put gvc add c i get gx3 add mul j 512 i +end +end +fw_kvr L add P get gfs 0 +end + +fn fw_kvr L ulong m ulong to void +for p ulong m +c = mul add mul L FKVP p 512 +for i ulong 512 +put gx2 add mul p 512 i get gkc add c i +put gx3 add mul p 512 i get gvc add c i +end +end +end + fn fw_att L ulong to void fw_qk L true fw_qk L false @@ -1582,6 +1656,7 @@ fw_proj 512 for i ulong mul get gfs 0 512 put gx3 i get gx1 i end +fw_kv L nm_lay L nm_tx tsnk ld_t 32 0 @@ -1651,7 +1726,7 @@ put gfh i 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 @@ -1659,7 +1734,7 @@ end fn fw_embed to void for t ulong get gfs 0 -id = fx_w add 8 t +id = get gtok add get gfs 2 t if ge id 150144 op_die 7 tfx end @@ -1692,6 +1767,13 @@ end fw_cmp mul get gfs 0 FHID end +note fw_lgo: fixture offset of logit r of chunk row t, after the 247 hidden-size tensors +fn fw_lgo t ulong r ulong to ulong +T = get gst 4 +o = add add 8 T mul mul T FHID 247 +ret add o add mul add get gfs 2 t 150144 r +end + fn fw_logits to void for t ulong get gfs 0 for r ulong 150144 @@ -1710,9 +1792,26 @@ end end v = matdot rem r 2048 FHID put gfa 0 v -fw_cmp 1 +fw_cmpat fw_lgo t r 1 +if eq get gfs 3 2 +gn_lg r v +end +end end end + +fn fw_chunk P ulong n ulong to void +put gfs 0 n +put gfs 1 0 +put gfs 2 P +fw_embed +for L ulong 49 +fw_layer L +end +if or ne get gfs 3 2 ge add P n get gst 4 +fw_final +fw_logits +end end fn op_forward to int @@ -1722,16 +1821,191 @@ op_die 7 tfx end note words = header + IDs + embeddings + five tensors/layer + final norm + logits fx_need add add add 8 T mul mul T FHID 247 mul T 150144 -put gfs 0 T -put gfs 1 add 8 T -fw_embed -for L ulong 49 -fw_layer L +for i ulong T +put gtok i fx_w add 8 i +end +if eq get gfs 3 1 +for P ulong T +fw_chunk P 1 +end +else +fw_chunk 0 T end -fw_final -fw_logits put gst 3 49 -r = report tofwd +r = fw_rep +ret r +end + +note generate (Core #834 item 5, test/TOLERANCE.md greedy generation parity): T prompt IDs, then +note N greedy steps; per step k the fixture holds the reference top-1 ID, logit, top-2 ID, logit at +note word 8 + T + 4 k. tau(x) = 8 gamma_2048 (1 + |x|), the forward integration budget. +fn gn_tau x f64 to f64 +ret mul mul 8.0f64 gam 2048 add 1.0f64 fabs x +end + +fn gn_amb T ulong N ulong to void +for k ulong N +o = add add 8 T mul 4 k +a = fx_f add o 1 +b = fx_f add o 3 +if le sub a b add gn_tau a gn_tau b +put gcm 3 add get gcm 3 1.0f64 +end +end +end + +fn gn_pre k ulong to void +o = add add 8 get gst 4 mul 4 k +put ggi 0 0 +put ggi 1 0 +put ggi 2 fx_w o +put ggi 3 fx_w add o 2 +for i ulong 4 +put ggt i neg 1.0e300f64 +end +end + +note gn_lg: logit v of vocabulary row r; strict gt keeps the lowest index on an exact tie +fn gn_lg r ulong v f64 to void +if eq r get ggi 2 +put ggt 2 v +end +if eq r get ggi 3 +put ggt 3 v +end +if gt v get ggt 0 +put ggt 1 get ggt 0 +put ggi 1 get ggi 0 +put ggt 0 v +put ggi 0 r +else +if gt v get ggt 1 +put ggt 1 v +put ggi 1 r +end +end +end + +note ob_f: signed decimal with 6 fraction digits; NaN or |v| >= 1e15 prints nan-or-big +fn ob_f v f64 to void +a = fabs v +if not le a 1.0e15f64 +ob_tx tgbig +ret +end +if lt v 0.0f64 +ob_c 45 +end +ip = ulong a +fr = ulong mul sub a f64 ip 1000000.0f64 +ob_u ip +ob_c 46 +q = ulong 100000 +for j ulong 5 +if lt fr q +ob_c 48 +end +q = div q 10 +end +ob_u fr +end + +fn gn_iv i ulong v f64 to void +ob_c 32 +ob_u i +ob_c 32 +ob_f v +end + +fn gn_line k ulong amb bool to void +o = add add 8 get gst 4 mul 4 k +put gst 8 0 +ob_tx tgst +ob_u add k 1 +ob_tx tgom +gn_iv get ggi 0 get ggt 0 +gn_iv get ggi 1 get ggt 1 +ob_tx tgat +ob_c 32 +ob_f get ggt 2 +ob_c 32 +ob_f get ggt 3 +ob_tx tgrf +gn_iv fx_w o fx_f add o 1 +gn_iv fx_w add o 2 fx_f add o 3 +if amb +ob_tx tgamb +end +ob_c 10 +ob_flush 1 +end + +note gn_step: 0 matched, 1 declared ambiguous stop (om took the reference top-2), 2 FAIL +fn gn_step k ulong to ulong +o = add add 8 get gst 4 mul 4 k +a = fx_f add o 1 +b = fx_f add o 3 +f = get gcm 1 +cmp get ggt 2 a mul 0.5f64 gn_tau a +cmp get ggt 3 b mul 0.5f64 gn_tau b +amb = le sub a b add gn_tau a gn_tau b +gn_line k amb +w = get ggi 0 +if gt get gcm 1 f +ret 2 +end +if eq w get ggi 2 +ret 0 +end +if and amb eq w get ggi 3 +ret 1 +end +put gcm 1 add get gcm 1 1.0f64 +ret 2 +end + +fn gn_end m ulong N ulong to void +put gst 8 0 +ob_tx tgmt +ob_u m +ob_tx tgof +ob_u N +ob_c 10 +ob_flush 1 +end + +fn op_gen to int +T = get gst 4 +N = get gst 5 +if or or eq T 0 eq N 0 gt add T N 1024 +op_die 7 tfx +end +fx_need add add 8 T mul 4 N +for i ulong T +put gtok i fx_w add 8 i +end +m = ulong 0 +for P ulong sub add T N 1 +g = ge add P 1 T +if g +gn_pre sub add P 1 T +end +fw_chunk P 1 +if g +s = gn_step sub add P 1 T +if ne s 0 +break +end +m = add m 1 +put gtok add P 1 get ggi 0 +end +end +gn_end m N +note the forward overwrote gst 3 (layer) and gcm 3 (router ties); ties here = ambiguous steps +put gst 3 49 +put gcm 3 0.0f64 +gn_amb T N +r = report togen ret r end @@ -1760,6 +2034,14 @@ end if op_argeq 1 tofwd ret 8 end +if op_argeq 1 todec +put gfs 3 1 +ret 8 +end +if op_argeq 1 togen +put gfs 3 2 +ret 9 +end op_die 2 tu ret 0 end @@ -1803,6 +2085,10 @@ if eq op 8 s = op_forward ret s end +if eq op 9 +s = op_gen +ret s +end if eq op 1 s = op_rmsn ret s diff --git a/om/flint/test/TOLERANCE.md b/om/flint/test/TOLERANCE.md index f5b7d39b..9bfe0855 100644 --- a/om/flint/test/TOLERANCE.md +++ b/om/flint/test/TOLERANCE.md @@ -219,3 +219,66 @@ 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. + +## Greedy generation parity (Core #834 item 5), frozen before the first comparison + +`ops.om generate` starts from the token IDs of a chat-template-rendered prompt and generates N +tokens greedily (argmax of its own f64 logits, lowest index on an exact tie), feeding its own +tokens back through the KV cache, one host forward per position. `test/genref.py` is the referee: +the pinned transformers modules in f32 on CPU, the same prompt IDs, greedy argmax with a +`DynamicCache`, one position per step after the prompt. Per step k = 1..N the fixture records the +reference top-1 ID and logit `l1` and the top-2 ID and logit `l2` (f32). + +Per-logit budget: `tau(x) = 8 gamma_2048 (1 + |x|)`, the integration budget of the chained forward +above (`fw_cmpat`), unchanged. +`WolframLanguageEvaluator: u = 2^-24; g[n_] := n u/(1 - n u); N[8 g[2048], 18] -> 0.000976681723843242583`. + +Ambiguity is a property of the reference alone, declared before the .om run: step k is +**ambiguous** when `l1 - l2 <= tau(l1) + tau(l2)`, i.e. when an .om logit vector that meets the +budget on both entries could rank the reference top-2 first. `genref.py` prints the ambiguous +steps when it writes the fixture, and the gate prints them again before the .om run; the rule is +not changed after a run. + +Per step, in order, while every earlier step matched (so the .om prefix equals the reference prefix): + +1. Logits: the .om logits at the reference top-1 and top-2 IDs must each be within `tau` of `l1` + and `l2`; otherwise FAIL (logit). +2. Token, non-ambiguous step: the .om argmax must equal the reference top-1; otherwise FAIL (token). +3. Token, ambiguous step: the .om argmax equal to the reference top-1 continues; equal to the + reference top-2 ends the comparison at step k without FAIL (the sequences no longer share a + prefix, so later fixture steps do not apply), and the receipt reports k - 1 matched steps, which + is then not N-token parity; any other ID is FAIL (token). + +The verdict line is `flint-op generate layer 49 elems S worst_ppm P ties A PASS|FAIL`, where S +counts compared logits (two per compared step), P is the worst `|om - ref| / tau` over the compared top-1/top-2 logits in +millionths, and A counts the declared ambiguous steps of the fixture. Every step also prints its +.om top-1/top-2 IDs and logits next to the reference values, so a divergence comes with its logits. + +The KV cache holds FKVP positions per layer; a request with prompt + N - 1 > FKVP positions is +refused (`refused 7 kv-cache-bound`) at the first position past the bound, never overrun. This is +a host check (f64 compute, BF16 storage, f32 referee); it is not bf16-activation, GPU or serving +evidence. + +### Measured (host, 2026-10-30) + +Referee `test/genref.py` (f32, pinned torch 2.14.0+cu130 and transformers a672eb5f, cores 0-4): +prompt `<|user|>What is 2+2?<|assistant|>` = `[150003, 2387, 332, 220, 17, 10, 17, 30, 150004]` +(no BOS; `add_bos_token` false), 16 greedy tokens `[150006, 16, 13, 220, 937, 74091, 269, 101439, +10117, 14679, 279, 461, 256, 450, 1464, 14313]` = `"1. **Analyze the User's Request**:\n +* The user asks"`, fixture sha256 `d5d3daec...c69c95e9`, 381 s wall, 25.9 GB peak RSS. +No step is ambiguous: the smallest top-1/top-2 margin is 0.264313 (step 10), against +`tau(-0.503171) + tau(-0.767484)` there; WolframLanguageEvaluator +`0.264313/(8 (2048 2^-24/(1 - 2048 2^-24)) (2 + 0.503171 + 0.767484))` -> 82.7429, so the margin is +about 83 times the summed budget. + +`flint-ops generate` (FKVP 32, `gkc`/`gvc` 49 x 32 x 512 = 802816 f64 each): all 16 tokens equal +the reference, `flint-gen matched 16 of 16`, worst `|om - ref| / tau` 22984 ppm over the 32 compared +logits (WolframLanguageEvaluator `N[22984/10^6, 6]` -> 0.022984). Wall 741.08 s for 16 tokens, +64.8 MB peak RSS: 383 s until the first token (nine prompt positions, one vocabulary pass), then +23.8667 s per generated token (`N[(18*3600+11*60+9 - (18*3600+5*60+11))/15, 6]` -> 23.8667, steps 2 +to 16 from the per-step line timestamps); `N[741.08/16, 6]` -> 46.3175 s per token overall. +Fail-first control: the same request with FKVP 8 is refused at position 8, `refused 7 +kv-cache-bound`, rc 7, after 172.09 s (`N[172.09/8, 6]` -> 21.5113 s per one-row forward). +The first .om run printed `layer 48 ... ties 131`: the forward had overwritten the layer slot and +the router tie counter; `op_gen` now resets both before the verdict, so `ties` counts declared +ambiguous steps only. The 16 per-step comparisons did not change. diff --git a/om/flint/test/genref.py b/om/flint/test/genref.py new file mode 100755 index 00000000..1bb8246b --- /dev/null +++ b/om/flint/test/genref.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""Read-only pinned Flint referee for ops.om generate (Core #834 item 5), not a runtime dependency. + +Usage: genref.py SRC SHARDS OUTPUT +Renders PROMPT with the pinned chat template (add_generation_prompt), then greedy-generates N +tokens with the pinned transformers modules in f32 on CPU: one prefill over the prompt, then one +position per step through a DynamicCache, argmax of the last row's logits. Layers are built +layer by layer from the BF16 shards as in fwdref.py; routed experts load lazily. +Fixture (little-endian u32 words, f32 logits): header magic, op 9, 0, T (prompt length), N, 0, +21400 (torch 2.14.0), 0; then T prompt IDs; then per step: top-1 ID, top-1 logit, top-2 ID, +top-2 logit. Ambiguous steps follow test/TOLERANCE.md (greedy generation parity), printed here +before any .om run. +""" +import hashlib +import json +import os +import struct +import sys + +import torch +from safetensors import safe_open +from transformers import AutoTokenizer +from transformers.cache_utils import DynamicCache +from transformers.models.flint import configuration_flint as cf +from transformers.models.flint import modeling_flint as mf + +REF_SHA = "f0540832049f0d67eee9eadd2d8ed42e320388b6b3330e74c8821a5c4eac0c09" +CFG_SHA = "849eee3068846081077a7568663355802c8c4eec3741d92cd578d222bd144d00" +TOK_SHA = { # PROFILE.md + "tokenizer.json": "a263cce0b7e2b03f7ee07ce809783ef4b47f160c3f268a4ea1524f638da45b68", + "tokenizer_config.json": "159ac88217e90ffd0a4a294726048bb302829e82e1958dc85bb203aa79138fbf", + "chat_template.jinja": "7940f4ffa3275c36caa4a582f845aaad79da11018b3961e8fbcad6ae29733466", +} +PROMPT = "What is 2+2?" +PROMPT_IDS = [150003, 2387, 332, 220, 17, 10, 17, 30, 150004] +N = 16 +for path, pin in ((mf.__file__, REF_SHA), (cf.__file__, CFG_SHA)): + if hashlib.sha256(open(path, "rb").read()).hexdigest() != pin: + sys.exit("genref: reference source pin mismatch: " + path) +if torch.__version__ != "2.14.0+cu130": + sys.exit("genref: 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] +for name, pin in TOK_SHA.items(): + if hashlib.sha256(open(os.path.join(src, name), "rb").read()).hexdigest() != pin: + sys.exit("genref: tokenizer pin mismatch: " + name) +tok = AutoTokenizer.from_pretrained(src) +ids = tok.apply_chat_template([{"role": "user", "content": PROMPT}], tokenize=True, add_generation_prompt=True) +ids = list(ids["input_ids"] if isinstance(ids, dict) or hasattr(ids, "keys") else ids) +if ids != PROMPT_IDS: + sys.exit("genref: rendered prompt IDs %s differ from the frozen %s" % (ids, PROMPT_IDS)) +cfg = cf.FlintConfig(**json.load(open(os.path.join(src, "config.json")))) +cfg._attn_implementation = "eager" +cfg._experts_implementation = "eager" +wmap = json.load(open(os.path.join(src, "model.safetensors.index.json")))["weight_map"] +handles = {} + + +def shard(name): + f = wmap[name] + if f not in handles: + handles[f] = safe_open(os.path.join(shards, f), framework="pt") + return handles[f] + + +def tensor(name): + t = shard(name).get_tensor(name) + assert t.dtype == torch.bfloat16, (name, t.dtype) + return t.float() + + +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() + + +def norm(prefix): + return load(mf.FlintRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps), prefix) + + +class Lazy: + def __init__(self, prefix, part): + self.prefix, self.part = prefix, part + + def __getitem__(self, e): + p = self.prefix + "experts.%d." % int(e) + if self.part == "gate_up": + return torch.cat([tensor(p + "gate_proj.weight"), tensor(p + "up_proj.weight")], dim=0) + return tensor(p + "down_proj.weight") + + +def sparse(prefix): + c = cf.FlintConfig(**cfg.to_dict()) + c._experts_implementation = "eager" + c.num_experts = 1 + ex = mf.FlintExperts(c).float() + 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 + blk = mf.FlintSparseMoeBlock.__new__(mf.FlintSparseMoeBlock) + torch.nn.Module.__init__(blk) + blk.gate = load(mf.FlintTopKRouter(cfg), prefix + "gate.") + blk.experts = ex + blk.shared_expert = load(mf.FlintMLP(cfg, cfg.shared_expert_intermediate_size), prefix + "shared_expert.") + return blk + + +def layer(L): + p = "model.layers.%d." % L + m = mf.FlintDecoderLayer.__new__(mf.FlintDecoderLayer) + torch.nn.Module.__init__(m) + m.self_attn = load(mf.FlintAttention(cfg, L), p + "self_attn.", {"sinks": "softmax_offset"}) + m.input_layernorm = norm(p + "input_layernorm.") + m.post_attention_layernorm = norm(p + "post_attention_layernorm.") + m.mlp = load(mf.FlintMLP(cfg), p + "mlp.") if L < 2 else sparse(p + "mlp.") + return m.eval() + + +layers = [layer(L) for L in range(cfg.num_hidden_layers)] +fnorm = norm("model.norm.") +rot = mf.FlintRotaryEmbedding(cfg) +esl = shard("model.embed_tokens.weight").get_slice("model.embed_tokens.weight") +lsl = shard("lm_head.weight").get_slice("lm_head.weight") +cache = DynamicCache() +g = 2048 * 2.0 ** -24 / (1 - 2048 * 2.0 ** -24) + + +def tau(x): + return 8 * g * (1 + abs(x)) + + +def step(tokens, p0): + """Run positions p0 .. p0+len(tokens) through all layers; return the f32 logits of the last row.""" + x = torch.cat([esl[t:t + 1] for t in tokens]).float().unsqueeze(0) + pos = torch.arange(p0, p0 + len(tokens)).unsqueeze(0) + rope = rot(x, pos) + n = len(tokens) + mask = None + if n > 1: + mask = torch.triu(torch.full((n, n), torch.finfo(torch.float32).min), diagonal=1)[None, None] + for m in layers: + x = m(x, attention_mask=mask, position_ids=pos, past_key_values=cache, use_cache=True, position_embeddings=rope) + h = fnorm(x)[0, -1:] + # Stream the vocabulary in 2048-row chunks as Omega does. + return torch.cat([torch.nn.functional.linear(h, lsl[f:f + 2048].float())[0] + for f in range(0, cfg.vocab_size, 2048)]) + + +rows = [] +logits = step(ids, 0) +for k in range(N): + v, i = torch.topk(logits, 2) + l1, l2 = float(v[0]), float(v[1]) + a1, a2 = int(i[0]), int(i[1]) + if a1 != int(torch.argmax(logits)): + sys.exit("genref: topk and argmax disagree") + amb = l1 - l2 <= tau(l1) + tau(l2) + rows.append((a1, l1, a2, l2)) + print("genref step %d top1 %d %.6f top2 %d %.6f margin %.6f%s" % ( + k + 1, a1, l1, a2, l2, l1 - l2, " AMBIGUOUS" if amb else ""), flush=True) + if k + 1 < N: + logits = step([a1], len(ids) + k) +gen = [r[0] for r in rows] +with open(output, "wb") as f: + f.write(struct.pack("<8I", 0x504F4C46, 9, 0, len(ids), N, 0, 21400, 0)) + f.write(struct.pack("<%dI" % len(ids), *ids)) + for a1, l1, a2, l2 in rows: + f.write(struct.pack("