diff --git a/CLAIMS.md b/CLAIMS.md index 16f5d9457..a0ddb08c0 100644 --- a/CLAIMS.md +++ b/CLAIMS.md @@ -87,3 +87,4 @@ tracked file, which both scripts resolve (they check that it exists, not what it | `inkling-layer0-mlp-fidelity-228` | Inkling 2 Mini layer-0 routed MLP under main's integer rules, real NVFP4 weights, open loop vs float64: FAIL vs prereg on both bars. Layer 0's top-8 sigmoid-routed MoE block of thinkingmachines/Inkling-2-Mini (ed40e7da) computed with main's integer rules (12-bit cells, 13-bit per-tensor weights, docs/model.md router and sigmoid table, two new 2^-8-step tables for the soft-capped SwiGLU, a rounded-division routing weight at 2^13) against our own numpy float64 version of the same block, on the 10 frozen prompt texts of 20261109-8 (2,426 tokens), exact float64 input, open loop. B1 (Qwen A2 shape, per prompt): rel_y median 0.0218, max 0.0304 vs median <= 0.01, max <= 0.05: FAIL. B2: the top-8 expert set differs on 91 of 2,426 tokens (3.75%) vs <= 1%: FAIL; each flip changes exactly one expert. B3 range: IN-BOUND, 0 events at every site. With the float set and float weights the integer expert arithmetic alone gives pooled rel_y 0.0079 (descriptive). Deterministic, two processes bit-identical. Measured, unreplicated. Float reference is our reading of open transformers PR 51050 (6173a2f6), not checked against the publisher's runtime. One block, no logits, no proof | negative, unreplicated | unreplicated | [experiments/20261121-228-inkling-layer0-fidelity/RESULTS.md](experiments/20261121-228-inkling-layer0-fidelity/RESULTS.md) | #230 | | `qwen-silu-step-vs-clip-221` | Qwen3.8-27B abliterated layers 31 to 63: SiLU table step vs domain clip, one change at a time (M31-C clip removed, M31-T step removed), issue #221: Registered diagnostic, valid (G1 REF top-1 = PR 173: True; G2 M31-C#2 bit-equal: True; G3 no guard error: True). From PR 167's layer-30 REF residual, abliterated layers 31 to 63, 1461 positions of 10 frozen prompts, float64 heads/attention/norms/lm_head; one change at a time to PR 138's SiLU lookup. M31-C: top-1 1459 of 1461 (99.86%), KL median 2.06e-06, max 0.00215 nats; M31-T: top-1 1424 of 1461 (97.47%), KL median 0.00146, max 1.93 nats. H-C (removing only the clip halves PR 202's M31 KL median 1.466e-3): ratio 0.001408, HOLDS. H-T (removing only the step halves it): ratio 0.9948, DOES NOT HOLD. Registered outcome: H-C only: the clip carries the token error; the step alone does not halve it. Diagnostic arms, not operators; chooses no repair. No proof | measured, unreplicated | unreplicated | [experiments/20261118-221-silu-step-clip/RESULTS.md](experiments/20261118-221-silu-step-clip/RESULTS.md), [experiments/20261118-221-silu-step-clip/runs/summary.json](experiments/20261118-221-silu-step-clip/runs/summary.json), [experiments/20261118-221-silu-step-clip/runs/e2e-abl.json](experiments/20261118-221-silu-step-clip/runs/e2e-abl.json), [experiments/20261118-221-silu-step-clip/ENV.json](experiments/20261118-221-silu-step-clip/ENV.json), [experiments/20261118-221-silu-step-clip/PREREG.md](experiments/20261118-221-silu-step-clip/PREREG.md) | #224 | | `qwen-weight-cell-classes-239` | Qwen3.8-27B weight-cell classes (DESIGN 6.2) on all 48 DeltaNet layers: conv taps, gains, cA, dt_bias, honest conversion, both checkpoints (issue #239): PASS vs prereg. Every honestly converted conv tap, gain x sqrt(128), cA and dt_bias integer (DESIGN 5.0, merged exponent_of, one exponent per tensor per layer) on all 48 DeltaNet layers lies in its DESIGN 6.2 class: 0 out of class of 1,976,832 integers per checkpoint; every exponent in 1..24 (e_conv 12-13, e_gain 7-8, e_A 4-13). For taps, gains and cA (1,974,528 of the 1,976,832 integers per checkpoint) being in class follows from the exponent rule, so an honest conversion cannot fail there; what could have failed is the exponent admission (144 exponents per checkpoint, 288 over both, each in 1..24) and the dt_bias class (2,304 values per checkpoint). The four tensors have equal SHA-256 per tensor in the stock and abliterated checkpoints (192 of 192, byte-identical), so one answer covers both. Descriptive: dt_bias alone puts the softplus input outside v1's [-8, 8) on 17 of 2,304 heads (16 at or above 8: 15 on layer 0, 1 on layer 58; 1 below -8 on layer 1); offset range -8.94 to 19.25. cA keeps as few as 2 significant bits (357 of 2,304 heads at 5 bits or fewer; the smallest head of a layer keeps fewer than 5 bits on 18 of 48 layers, 2 bits on layers 12, 28 and 44). Integer counts only, no proof, no matrix weights, no activations | measured, unreplicated | unreplicated | [experiments/20261129-239-qwen-weight-cell-classes/RESULTS.md](experiments/20261129-239-qwen-weight-cell-classes/RESULTS.md), [experiments/20261129-239-qwen-weight-cell-classes/PREREG.md](experiments/20261129-239-qwen-weight-cell-classes/PREREG.md), [experiments/20261129-239-qwen-weight-cell-classes/ENV.json](experiments/20261129-239-qwen-weight-cell-classes/ENV.json), [experiments/20261129-239-qwen-weight-cell-classes/runs/summary.json](experiments/20261129-239-qwen-weight-cell-classes/runs/summary.json), [experiments/20261129-239-qwen-weight-cell-classes/runs/ckpt-compare.json](experiments/20261129-239-qwen-weight-cell-classes/runs/ckpt-compare.json) | #243 | +| `fold-constants-214` | Fold constants computed by the rule for any width and head size in weight_sums (Python and C++), byte-identical at 5,120 / 128 (issue #214, CPU part): Measured, unreplicated, deterministic, CPU only. weight_sums.py and bin/weight_sums compute the two fold constants with fold_constants(width, head) (t the largest integer with 4^t <= d, c = sqrt(d) / 2^t, c_0 = RN32(c), c_q = RN32(c / sqrt(dh)), one rounding of the exact real) instead of literals. docs/model.md section 11.3 and scales/README.md state the constant as sqrt(d) / 64, right for 5,120 / 128 only; that equals c where t = 6 (widths 4,096 to 16,383, 5,120 included). For other widths, using c is a choice made in this PR: no document on main states it, it is not tested against the scales of scales/, and the tests check only the arithmetic of the formula. At (5,120, 128) both programs give 0x3F8F1BBD and 0x3DCA62C2, main's literals (also a C++ static_assert). 19 of 19 sums files of the existing suite's inputs (oracle seeds 1-4 and 100-102 at e_res 11, seed 1 at e_res 10, seed 2 with --decode-twice, the make_model model; both programs where the suite runs both) are byte-identical between base and head and equal the expected files; run_tests.sh passes every step at base (26) and head (27, one new). Independent values (mpmath at 256 bits and exact integer roots) at (5,120, 256): c_0 0x3F8F1BBD, c_q 0x3D8F1BBD. NOT established: the shape gates of weight_sums and the prover still accept only 5,120 / 128 (no admission gate opened); the CUDA reader and its gate are unchanged and not compiled (the needed change is an open item in RESULTS.md); no Qwen commit, no weights; partial rotary and the dh = 256 no-wrap barrier untouched | measured, unreplicated | unreplicated | [experiments/20261129-214-fold-constants/RESULTS.md](experiments/20261129-214-fold-constants/RESULTS.md), [experiments/20261129-214-fold-constants/PREREG.md](experiments/20261129-214-fold-constants/PREREG.md), [experiments/20261129-214-fold-constants/ENV.json](experiments/20261129-214-fold-constants/ENV.json), [experiments/20261129-214-fold-constants/values.json](experiments/20261129-214-fold-constants/values.json), [experiments/20261129-214-fold-constants/runs/compare.json](experiments/20261129-214-fold-constants/runs/compare.json), [experiments/20261129-214-fold-constants/runs/run_tests.base.txt](experiments/20261129-214-fold-constants/runs/run_tests.base.txt), [experiments/20261129-214-fold-constants/runs/run_tests.head.txt](experiments/20261129-214-fold-constants/runs/run_tests.head.txt) | #234 | diff --git a/README.md b/README.md index 1d7affcc5..29a607ca2 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ Every number below comes from a file on `main` (the one exception, a reviewer fi | Inkling 2 Mini layer-0 routed MLP under main's integer rules, real NVFP4 weights, open loop vs float64 | negative, unreplicated | FAIL vs prereg on both bars. Layer 0's top-8 sigmoid-routed MoE block of thinkingmachines/Inkling-2-Mini (ed40e7da) computed with main's integer rules (12-bit cells, 13-bit per-tensor weights, docs/model.md router and sigmoid table, two new 2^-8-step tables for the soft-capped SwiGLU, a rounded-division routing weight at 2^13) against our own numpy float64 version of the same block, on the 10 frozen prompt texts of 20261109-8 (2,426 tokens), exact float64 input, open loop. B1 (Qwen A2 shape, per prompt): rel_y median 0.0218, max 0.0304 vs median <= 0.01, max <= 0.05: FAIL. B2: the top-8 expert set differs on 91 of 2,426 tokens (3.75%) vs <= 1%: FAIL; each flip changes exactly one expert. B3 range: IN-BOUND, 0 events at every site. With the float set and float weights the integer expert arithmetic alone gives pooled rel_y 0.0079 (descriptive). Deterministic, two processes bit-identical. Measured, unreplicated. Float reference is our reading of open transformers PR 51050 (6173a2f6), not checked against the publisher's runtime. One block, no logits, no proof | CPU only, numpy and tokenizers only (no torch, no transformers); weights by HTTP range reads of layer 0 and 317 embedding rows (630 MB of 19.5 GB); NVFP4 decode per the PR's dequantise op, checked D1-D4 (max \|w\| / amax = 1.000 every expert); gate/up order from the PR's Interleave + chunk; input exponent fitted in-sample (Em = 6); attention sub-block float64 only; one layer, open loop; shared loaded host | [experiments/20261121-228-inkling-layer0-fidelity/RESULTS.md](experiments/20261121-228-inkling-layer0-fidelity/RESULTS.md) | | Qwen3.8-27B abliterated layers 31 to 63: SiLU table step vs domain clip, one change at a time (M31-C clip removed, M31-T step removed), issue #221 | measured, unreplicated | Registered diagnostic, valid (G1 REF top-1 = PR 173: True; G2 M31-C#2 bit-equal: True; G3 no guard error: True). From PR 167's layer-30 REF residual, abliterated layers 31 to 63, 1461 positions of 10 frozen prompts, float64 heads/attention/norms/lm_head; one change at a time to PR 138's SiLU lookup. M31-C: top-1 1459 of 1461 (99.86%), KL median 2.06e-06, max 0.00215 nats; M31-T: top-1 1424 of 1461 (97.47%), KL median 0.00146, max 1.93 nats. H-C (removing only the clip halves PR 202's M31 KL median 1.466e-3): ratio 0.001408, HOLDS. H-T (removing only the step halves it): ratio 0.9948, DOES NOT HOLD. Registered outcome: H-C only: the clip carries the token error; the step alone does not halve it. Diagnostic arms, not operators; chooses no repair. No proof | Preregistered (experiments/20261118-221-silu-step-clip/PREREG.md); start state PR 167's ckpt.npz sha256 22dff8b92107511838e50e4b26d6e91a2b55d09064711c638042c4c18fb80009, next_layer 31, checked before registration and re-hashed in the job, REF entries only, layers 0 to 30 not regenerated; abliterated layers 31 to 63, final norm, lm_head; PR 124's frozen prompts teacher-forced; PR 202 harness, PR 138 mlp_int stages, PR 124 logits_metrics, PR 88 forward reused; M31 and M31-S not rerun (PR 202 values cited); CPU, taskset 8 to 13, one deterministic run with an in-run duplicate path; shared loaded host; no GPU, no serving route, no proof | [experiments/20261118-221-silu-step-clip/RESULTS.md](experiments/20261118-221-silu-step-clip/RESULTS.md) | | Qwen3.8-27B weight-cell classes (DESIGN 6.2) on all 48 DeltaNet layers: conv taps, gains, cA, dt_bias, honest conversion, both checkpoints (issue #239) | measured, unreplicated | PASS vs prereg. Every honestly converted conv tap, gain x sqrt(128), cA and dt_bias integer (DESIGN 5.0, merged exponent_of, one exponent per tensor per layer) on all 48 DeltaNet layers lies in its DESIGN 6.2 class: 0 out of class of 1,976,832 integers per checkpoint; every exponent in 1..24 (e_conv 12-13, e_gain 7-8, e_A 4-13). For taps, gains and cA (1,974,528 of the 1,976,832 integers per checkpoint) being in class follows from the exponent rule, so an honest conversion cannot fail there; what could have failed is the exponent admission (144 exponents per checkpoint, 288 over both, each in 1..24) and the dt_bias class (2,304 values per checkpoint). The four tensors have equal SHA-256 per tensor in the stock and abliterated checkpoints (192 of 192, byte-identical), so one answer covers both. Descriptive: dt_bias alone puts the softplus input outside v1's [-8, 8) on 17 of 2,304 heads (16 at or above 8: 15 on layer 0, 1 on layer 58; 1 below -8 on layer 1); offset range -8.94 to 19.25. cA keeps as few as 2 significant bits (357 of 2,304 heads at 5 bits or fewer; the smallest head of a layer keeps fewer than 5 bits on 18 of 48 layers, 2 bits on layers 12, 28 and 44). Integer counts only, no proof, no matrix weights, no activations | Preregistered (experiments/20261129-239-qwen-weight-cell-classes/PREREG.md, amendments A1, A2 before the runs they cover by commit order; A3 corrects the times typed into them); 192 tensors per checkpoint by HTTP range with the merged fetch code, each SHA-256 equal to the merged stream manifest; unit test of every class edge (31 cases, synthetic); five identical analysis runs (deterministic); CPU, cores 0-1 of a shared loaded host | [experiments/20261129-239-qwen-weight-cell-classes/RESULTS.md](experiments/20261129-239-qwen-weight-cell-classes/RESULTS.md) | +| Fold constants computed by the rule for any width and head size in weight_sums (Python and C++), byte-identical at 5,120 / 128 (issue #214, CPU part) | measured, unreplicated | Measured, unreplicated, deterministic, CPU only. weight_sums.py and bin/weight_sums compute the two fold constants with fold_constants(width, head) (t the largest integer with 4^t <= d, c = sqrt(d) / 2^t, c_0 = RN32(c), c_q = RN32(c / sqrt(dh)), one rounding of the exact real) instead of literals. docs/model.md section 11.3 and scales/README.md state the constant as sqrt(d) / 64, right for 5,120 / 128 only; that equals c where t = 6 (widths 4,096 to 16,383, 5,120 included). For other widths, using c is a choice made in this PR: no document on main states it, it is not tested against the scales of scales/, and the tests check only the arithmetic of the formula. At (5,120, 128) both programs give 0x3F8F1BBD and 0x3DCA62C2, main's literals (also a C++ static_assert). 19 of 19 sums files of the existing suite's inputs (oracle seeds 1-4 and 100-102 at e_res 11, seed 1 at e_res 10, seed 2 with --decode-twice, the make_model model; both programs where the suite runs both) are byte-identical between base and head and equal the expected files; run_tests.sh passes every step at base (26) and head (27, one new). Independent values (mpmath at 256 bits and exact integer roots) at (5,120, 256): c_0 0x3F8F1BBD, c_q 0x3D8F1BBD. NOT established: the shape gates of weight_sums and the prover still accept only 5,120 / 128 (no admission gate opened); the CUDA reader and its gate are unchanged and not compiled (the needed change is an open item in RESULTS.md); no Qwen commit, no weights; partial rotary and the dh = 256 no-wrap barrier untouched | CPU only, cores 14-15 of a shared loaded host, suite runs through the heavy-job gate; g++ 13.3.0 with weight_sums' own flags; Python 3.12.3 venv with numpy 2.3.5, gguf 0.19.0, mpmath 1.3.0; PREREG first and alone, one amendment (implementation choices) before the runs; debug only on oracle seed 7 | [experiments/20261129-214-fold-constants/RESULTS.md](experiments/20261129-214-fold-constants/RESULTS.md) | _Last regenerated from `research/results.yaml` on 2026-11-29 (UTC), against main `57460851`._ diff --git a/experiments/20261129-214-fold-constants/ENV.json b/experiments/20261129-214-fold-constants/ENV.json new file mode 100644 index 000000000..5d5e768bb --- /dev/null +++ b/experiments/20261129-214-fold-constants/ENV.json @@ -0,0 +1,25 @@ +{ + "experiment": "20261129-214-fold-constants", + "commits": { + "base_main": "cdf78449d390a1f62dc77d28c5cf6cb8c0bb1b02", + "prereg": "3ee789bb7b38c61ae9f4e46070191871c83404fb", + "amendment_A1_before_runs": "38413939ca8328c24d51ddcd2560f3c2bbd56558", + "code_before_runs": "92e1dc1b1609a92d35c594b72ffb8cd79af6bae9", + "note": "the base arm of every comparison is a detached checkout of base_main with its own bin/weight_sums; the head arm is code_before_runs with its own" + }, + "toolchain": { + "cxx": "g++ 13.3.0 (Ubuntu 13.3.0-6ubuntu2~24.04.1)", + "flags": "those of weight_sums/build.sh and weight_sums/tests/run_tests.sh, unchanged: -std=c++17 -O2 -fno-ipa-modref -ffp-contract=off -pthread", + "python": "3.12.3", + "python_packages": {"numpy": "2.3.5", "gguf": "0.19.0", "mpmath": "1.3.0"}, + "python_environment": "a fresh venv first on PATH for both arms (PREREG A1)" + }, + "hardware": { + "kind": "cpu-epyc-rome-kvm-16", + "cores_used": "14-15 (taskset)", + "shared": "shared, loaded host; other lanes ran beside this one; the suite runs went through the host's heavy-job gate" + }, + "seeds": [1, 2, 3, 4, 100, 101, 102], + "seeds_note": "oracle.py seeds of the registered suite, all at e_res 11, plus seed 1 at e_res 10 and seed 2 with --decode-twice (Python); make_model arguments 4 40 8 2048 1024 16 2048 30 as in run_tests.sh. Debug only on oracle seed 7. Every output is deterministic; no randomness enters fold_constants", + "gpu": "none; no CUDA file was built or changed" +} diff --git a/experiments/20261129-214-fold-constants/PREREG.md b/experiments/20261129-214-fold-constants/PREREG.md new file mode 100644 index 000000000..ab0e6be4a --- /dev/null +++ b/experiments/20261129-214-fold-constants/PREREG.md @@ -0,0 +1,81 @@ +# PREREG: 20261129-214-fold-constants + +Issue: #214. Lane: fold214. Date (UTC): 2026-11-29 02:00. Base commit: cdf78449d390a1f62dc77d28c5cf6cb8c0bb1b02. + +CPU only. No weights, no GPU, no CUDA file is edited or compiled in this step. + +## The rule, quoted from main + +`scales/README.md` line 541 to 543 (the issue cites 542): "The conversion ([../docs/model.md](../docs/model.md), section 11.3) multiplies a norm's gains and the constant sqrt(d) / 64 into every matrix that reads the norm's output, and 1 / sqrt(dh) into the query matrix." + +`scales/README.md` lines 594 to 601: "Let t be the largest integer with 4^t <= d, and c = sqrt(d / 4^t), so that sqrt(d) = c * 2^t and 1 <= c < 2; at d = 5,120, t = 6 and c = sqrt(1.25). [...] In a product with a weight matrix the conversion's constant sqrt(d) / 64 cancels c only where t = 6. So the shifts below and E_logit are right for widths from 4,096 to 16,383 only; the conversion accepts only 5,120." + +Check of the issue's question "is `sqrt(d) / 64` only the t = 6 case of `c`": sqrt(d) / 64 = c * 2^t / 2^6, which equals c exactly when t = 6, that is for 4,096 <= d < 16,384. For other widths the README's own text says the constant sqrt(d) / 64 does not cancel c. So the general constant that keeps the norm's output scale of step 2 is c itself, and the rule under test is: + +- t = the largest integer with 4^t <= d +- c = sqrt(d) / 2^t = sqrt(d / 4^t), with 1 <= c < 2 +- c_0 = RN32(c) (the norm constant) +- c_q = RN32(c / sqrt(dh)) = RN32(sqrt(d / (4^t dh))) (the query constant) + +RN32 is the binary32 number nearest to the exact real value, ties to even, applied ONCE to the exact real (not RN32(RN32(c) / sqrt(dh)) and not a rounding of a binary64 intermediate). + +## Hypothesis + +The rule above, computed exactly, gives the bit patterns 0x3F8F1BBD (c_0) and 0x3DCA62C2 (c_q) at (d, dh) = (5,120, 128), the literals on main, so `weight_sums` built with `fold_constants(width, head)` in place of the literals writes byte-identical sums files on every input of its existing test suite. + +## Expected words + +- (5,120, 128): t = 6, c = sqrt(1.25). Expected c_0 = 0x3F8F1BBD, c_q = 0x3DCA62C2 (main's literals). +- (5,120, 256): t = 6, c_0 unchanged (0x3F8F1BBD); c_q = RN32(sqrt(1.25) / 16). Because 16 is a power of two, c_q is expected to be c_0 with its exponent lowered by 4, 0x3D8F1BBD. This is a prediction written before any computation; the independent computation decides it. + +## Metric + +1. The two 32-bit words returned by the new Python `fold_constants(width, head)` (in `weight_sums/weight_sums.py`) and by its C++ twin (in `weight_sums/weight_sums.cpp`) at (5,120, 128) and (5,120, 256). +2. The same words from an independent computation: mpmath at 256 bits of precision (binary search of the nearest binary32 on the mpf value, ties checked) and, separately, exact rational arithmetic (integer square roots), in a script under this directory. Both results committed in a values file. +3. Byte comparison (`cmp`) of sums files written by `bin/weight_sums` and `weight_sums.py` built from the base commit and from the branch head on the suite's own inputs: oracle seeds 1, 2, 3, 4, 100, 101, 102 at e_res 11, seed 1 at e_res 10, seed 2 with `--decode-twice` (Python), and the `make_model` model, plus the pass/fail line of every step of `weight_sums/tests/run_tests.sh` at base and at head. + +## Acceptance threshold + +PASS, item by item: +- P1: Python and C++ `fold_constants(5120, 128)` both return exactly (0x3F8F1BBD, 0x3DCA62C2). +- P2: the independent computation (both methods) gives the same words at (5,120, 128) as P1, and both methods agree with Python and C++ at (5,120, 256). +- P3: every sums file of metric 3 at head equals the base's byte for byte, for both programs; and `run_tests.sh` at head has the same set of passed steps as at base (no step passes at base and fails at head). +- P4: new unit tests (Python and C++) pass: the literals at (5,120, 128), the recorded values at (5,120, 256), and agreement of Python and C++ on a fixed list of further shapes. + +## Kill criterion + +- Negative result, stop at once and change nothing further: the exact rule does not give 0x3F8F1BBD and 0x3DCA62C2 at (5,120, 128), or any byte of any sums file of metric 3 differs between base and head. Report the difference. +- Stop and report: the Python and C++ CPU parts cannot change without a CUDA file changing in the same step (for example a shared header). +- Hard stop 2026-11-29T04:20Z (150 minutes after the lane's first STATE line at 01:50Z). Whatever is done by then is committed and written up as partial. + +## Runs + +The outputs are deterministic functions of their inputs (integer and exact arithmetic, sums files hashed), so variance is not a property of interest: each comparison is run once per arm (base, head), and a single differing byte is a FAIL. Order: base arm first, then head arm, same host, same compiler (g++ 13.3.0), same Python environment. Cores 14-15 (`taskset -c 14-15`). The registered suite (metric 3, run_tests.sh) is not run at any size before the code is complete; development debugging uses oracle seed 7 at e_res 11, which the suite does not use, and the shapes of P4. Nothing excluded. + +## Scope cut (by the coordinator, before registration) + +This host has no GPU. The CUDA reader (`prover/weights_commitment/fold_weights.cuh`, `reads()`) and its shape gate (`prover/weights_commitment/fold_source.cuh`, `FoldSource::open`) are NOT changed; RESULTS.md will state the exact change they need as an open item, not made and not compiled. The shape gates in `weight_sums.py` and `weight_sums.cpp` that accept only (5,120, 128) also stay as they are in this step: opening them while the CUDA side still refuses every other shape would make `weight_sums` write files the prover cannot use, and no admission gate is opened here. The constants are computed by the rule; the shapes admitted are unchanged. + +## Prior art + +The rule is the repository's own (`scales/README.md`, `docs/model.md` section 11.3). Folding a norm's gain and sqrt(width) into the next matrix: QuaRot (arXiv:2404.00456) and SliceGPT (arXiv:2401.15024), as cited in `weight_sums.py`. Correctly rounded square roots in binary32: IEEE 754-2019 requires sqrt to be correctly rounded; here the operand d / (4^t dh) is rational, so the exact rounding is done with integer square roots instead of a library call. The issue names a public fork (marcellobardus/FlashProve-TinyLlama1.1B, commit c0eb59e07283) that reports the same change for TinyLlama; it was not read for this step and no code is taken from it. What is new here: an exact computation of both words for any width and head size, checked against main's literals, and the values for dh = 256. + +## Amendments + +### A1 (2026-11-29 02:12 UTC, after code and the seed-7 debug run, BEFORE any registered run) +Concrete choices the code makes that the registration did not fix. None changes a threshold, an input or a pass rule. +- Python environment for both arms: a fresh venv with numpy 2.3.5, gguf 0.19.0 (the versions `weight_sums.py` names) and mpmath 1.3.0; the host's system python has no gguf, so `run_tests.sh` would otherwise skip every Python step. +- Metric 3 is run by `compare_base_head.py` in this directory: base checkout = a detached worktree at the base commit with its own `bin/weight_sums`, head checkout = the branch with its own. Inputs are written once by the head's `tests/oracle.py` (unchanged by this PR) and by one `make_model` built from the head's `prover/` (unchanged by this PR). Each sums file is also compared with the expected file of oracle.py / make_model. Output `runs/compare.json`. +- `run_tests.sh` is run once at the base and once at the head, each with the venv first on PATH, output `runs/run_tests.base.txt` and `runs/run_tests.head.txt`. The head adds one step (`fold-constants.py`), so P3's "same set of passed steps" means: every step passed at base also passes at head. +- `values.json` (metric 2) was written by `independent_values.py` before this amendment; it is not a run of the registered suite. P4's C++ test pins the (5,120, 256) words of values.json and, at five further shapes, words that `fold_constants_test.py` checks for Python against an independent bisection. +- C++: `fold_constants` is `constexpr` with a `static_assert` that it gives main's literals at (5,120, 128), so a build that would change them does not compile. The shape gates of both programs are unchanged (PREREG "Scope cut"). +- Debug: one comparison on oracle seed 7, e_res 11 (not a registered input), both languages, base vs head: byte-identical. Output not kept as evidence. + +### A2 (2026-11-29 04:10 UTC, after the review of head 111b104d; text only) +A review of this PR (PR comment 7249850873) found a citation that says more than the cited documents do. The docstring of `fold_constants` in `weight_sums/weight_sums.py`, the matching comment in `weight_sums/weight_sums.cpp`, a sentence in `weight_sums/README.md`, the ledger row's summary and the RESULTS section "The answer to the issue's first question" present the general rule c = sqrt(d) / 2^t as stated by `scales/README.md` and `docs/model.md`, section 11.3. Read again for this amendment: +- `docs/model.md`, section 11.3, states the constants as RN32(sqrt(d)/64) and, for the query matrix, RN32(sqrt(d)/64/sqrt(dh)), and says they are right for d = 5,120 and dh = 128 only. It has no t and no c. +- `scales/README.md` states the conversion's constant as sqrt(d) / 64 (lines 541 to 543). Its lines 594 to 601 define t and c for the exponents of the fit's norm sites and say that the conversion's constant sqrt(d) / 64 cancels c only where t = 6. It does not say that the conversion uses c at other widths. + +So what the documents state is sqrt(d) / 64. That equals c where t = 6, for widths from 4,096 to 16,383, Qwen's 5,120 included. For every other width, using c = sqrt(d) / 2^t in `fold_constants` is a choice made in this PR, argued in "The rule, quoted from main" above. No document on main states it, and it is not tested against the scales of `scales/`. Example of the difference: at d = 2,048 and dh = 64 the function returns 0x3FB504F3 for the norm constant, while sqrt(d) / 64 rounds to 0x3F3504F3. The sentence "The rule is the repository's own (`scales/README.md`, `docs/model.md` section 11.3)" under "Prior art" above carries the same overstatement; it is corrected here and not edited. + +What this step changes: comments and text only. The five places named above are reworded to cite the documents for what they state and to name the general rule as this PR's, one line number in RESULTS is corrected, and the PR description is brought up to date. No code line, test, run file, threshold, count or verdict changes. No registered run is repeated and nothing is built. No earlier text of this file is edited. diff --git a/experiments/20261129-214-fold-constants/RESULTS.md b/experiments/20261129-214-fold-constants/RESULTS.md new file mode 100644 index 000000000..86db2b67d --- /dev/null +++ b/experiments/20261129-214-fold-constants/RESULTS.md @@ -0,0 +1,70 @@ +# RESULTS: 20261129-214-fold-constants + +Issue #214 (CPU part). Base `cdf78449d390a1f62dc77d28c5cf6cb8c0bb1b02`. Runs at code commit `92e1dc1b1609a92d35c594b72ffb8cd79af6bae9`. CPU only, no weights, no GPU, no CUDA file changed or compiled. + +## In plain words + +The two numbers that fold a norm's gains into the next matrix were typed into `weight_sums` as literals that are right only for width 5,120 and head size 128. Both programs (`weight_sums.py` and `bin/weight_sums`) now compute them with `fold_constants(width, head)`. For widths from 4,096 to 16,383 the function gives the constant the documents state, sqrt(d) / 64; for other widths it uses a rule chosen in this PR, which no document on main states (see "The answer to the issue's first question"). The function gives exactly the old literals at (5,120, 128), and every sums file of the existing test suite is byte-for-byte the same as before. At Qwen's shape (5,120, 256) the norm constant stays 0x3F8F1BBD and the query constant becomes 0x3D8F1BBD. The shapes the programs accept did not change, and the GPU side still uses the literals and refuses every other shape. + +## Verdicts (PREREG "Acceptance threshold") + +| item | verdict | evidence | +|---|---|---| +| P1 Python and C++ `fold_constants(5120, 128)` = (0x3F8F1BBD, 0x3DCA62C2) | PASS | `weight_sums/tests/fold_constants_test.py` (step `fold-constants.py`), the C++ `static_assert` in `weight_sums/weight_sums.cpp` and `test_fold_constants` in `weight_sums/tests/unit_test.cpp` (step `unit`); `runs/run_tests.head.txt` | +| P2 independent computation agrees, (5,120, 128) and (5,120, 256) | PASS | `values.json` from `independent_values.py`: mpmath at 256 bits and exact integer square roots agree with each other and with both programs | +| P3 sums files byte-identical, base vs head, both programs; no step lost | PASS | `runs/compare.json`: 19 of 19 comparisons byte-identical to the base and to the expected file of oracle.py / make_model; `runs/run_tests.base.txt` 26 of 26 steps passed, `runs/run_tests.head.txt` 27 of 27 (the base's 26 plus `fold-constants.py`), 0 skipped | +| P4 new unit tests pass | PASS | `fold_constants_test.py`: 0 failed checks (23 shapes against an independent Fraction bisection, plus 6 refused arguments); `unit_test`: 0 of 20,066,032 checks failed (includes 7 `fold_constants` shapes) | + +The registered negative result (the rule does not reproduce the literals, or a byte moves at (5,120, 128)) did not occur. + +## The answer to the issue's first question + +What the documents state: `docs/model.md`, section 11.3, gives the two constants as RN32(sqrt(d)/64) and, for the query matrix, RN32(sqrt(d)/64/sqrt(dh)), and says they are right for d = 5,120 and dh = 128 only. `scales/README.md` line 542 gives the conversion's constant as sqrt(d) / 64 too. Its lines 594 to 600 define t and c = sqrt(d / 4^t) = sqrt(d) / 2^t for the exponents of the fit's norm sites, not as the conversion's constant, and say that sqrt(d) / 64 cancels c only where t = 6. + +sqrt(d) / 64 equals c exactly when t = 6, that is for 4,096 <= d < 16,384. So `sqrt(d) / 64` is the t = 6 case of c, and at every width in that range, Qwen's 5,120 included, `fold_constants` returns what the documents state. + +For t != 6 the function uses c_0 = RN32(c) and c_q = RN32(c / sqrt(dh)) with c = sqrt(d) / 2^t, each one rounding of the exact real. That is a choice made in this PR, argued in PREREG ("The rule, quoted from main"). `docs/model.md` section 11.3 does not state it, no document on main does, and it is not tested against the scales of `scales/`. For those widths the function does not return RN32(sqrt(d) / 64). The review's example (PR comment 7249850873): at d = 2,048 and dh = 64 the function gives 0x3FB504F3 for c_0 (c = sqrt(2), pinned in `weight_sums/tests/unit_test.cpp`), while sqrt(2,048) / 64 is half of that and rounds to 0x3F3504F3. Which of the two is right for a width outside 4,096 to 16,383 is open. No such width is admitted by any gate. The tests of this PR check the arithmetic of the formula (two programs and a second exact computation of the same formula give the same words); they do not test the choice of c. + +## Values (from `values.json`) + +| d | dh | t | c_0 word | c_q word | c_q exact, 40 digits | +|---|---|---|---|---|---| +| 5,120 | 128 | 6 | 0x3F8F1BBD | 0x3DCA62C2 | 0.09882117688026185412496542326352245417874 | +| 5,120 | 256 | 6 | 0x3F8F1BBD | 0x3D8F1BBD | 0.06987712429686842801278667714785238235752 | + +At dh = 256, c / sqrt(dh) = c / 16, a power of two, so c_q is c_0 with the exponent lowered by 4 (0x3F8F1BBD - 4 * 2^23 = 0x3D8F1BBD), as the PREREG predicted before any computation. + +## Commands (from the repository root) + +- `python3 weight_sums/tests/fold_constants_test.py` (needs numpy and gguf 0.19.0) +- `weight_sums/tests/run_tests.sh` (builds `bin/weight_sums`, runs `unit`, `fold-constants.py` and every older step) +- `python3 experiments/20261129-214-fold-constants/independent_values.py --check` (needs mpmath; compares with `values.json`, writes nothing) +- `python3 experiments/20261129-214-fold-constants/compare_base_head.py []`, each checkout with its own `bin/weight_sums` built by `weight_sums/build.sh`; `make_model` from `cd prover && OUT= ./build.sh make_model` + +## Open item: the CUDA side (NOT made, NOT compiled) + +This host has no GPU, so none of this was edited or built. What a GPU lane would need to change for the prover to fold Qwen's query weights by the rule: + +1. `prover/weights_commitment/fold_weights.cuh` lines 174 to 188 (comment, `struct Reads`, `reads(const std::string &kind)`): give `reads` the shape, `inline Reads reads(const std::string &kind, uint32_t d, uint32_t dh)`, and replace the literal `0x3DCA62C2u` (attn_q) by `fold_constants(d, dh).query` and each `0x3F8F1BBDu` (attn_k, attn_v, the seven ffn kinds, output) by `fold_constants(d, dh).norm`, where `fold_constants` / `rn32_sqrt_word` are the host functions of `weight_sums/weight_sums.cpp` (they use `unsigned __int128`, which nvcc accepts in host code; to be checked). The comment at lines 174 and 175 changes accordingly. Moving them into a small shared header (for example `common/fold_constants.h`) that both `weight_sums.cpp` and `fold_weights.cuh` include would keep one copy; this PR did not do that, so that no file the CUDA build includes changes. +2. Callers of `reads()` pass the file's shape: `prover/hash_commitment/hf_commit_weights.cuh` line 283 (`::fold::reads(kind)`, `source.file.embedding_length`, `source.file.key_length`) and `prover/weights_blocks/gguf_source.cuh` line 120 (`fold::reads(kind(stream, layer))`, `file_.embedding_length`, `file_.key_length`). +3. Shape gates: `prover/weights_commitment/fold_source.cuh` line 136 (`if (file.embedding_length != 5120 || file.key_length != 128)`) and `prover/weights_blocks/gguf_source.cuh` line 29 (same test). The issue asks for "positive whole shape that matches the policy": replace with `embedding_length >= 1 && embedding_length < 2^32 && key_length >= 1 && key_length < 2^32` AND the shape equal to the parameter file's (`gguf_source.cuh` lines 30 to 32 already compare with `shape.d`, `shape.dh`). This lifts an admission gate, so it is a separate decision; this PR does not take it. +4. The same literals also sit in `prover/tests/weights_blocks/make_model.cpp` line 504 (`C`, `C_Q`), which writes the suite's synthetic model at (5,120, 128), and in `integrations/vllm/integer_model/integer_model/block_weights.py` lines 306 and 307 (`_C0`, `_C0_QUERY`). At (5,120, 128) they are right; a model of another shape needs them computed too. +5. The gates in `weight_sums.py` (`model_layers`, `select`) and `weight_sums.cpp` (`plan()`, lines with `kWidth` and `kHeadDimension`) also stay at (5,120, 128) in this PR, so `weight_sums` and the prover keep refusing the same shapes. When the gates open, the per-shape constants must come from `fold_constants(width, head)` at run time instead of `NORM_CONSTANT` / `kNormConstant` for (5,120, 128), and the matrix-width and norm-length checks must use the file's width. + +## What is NOT established + +- No Qwen commit was made and no Qwen weight was read; no sums file was written for any shape other than (5,120, 128). +- No admission gate was opened: `weight_sums.py`, `bin/weight_sums` and the prover still accept only width 5,120 and head size 128. +- No GPU build, no CUDA change; the prover still uses its literals. +- Partial rotary and the dh = 256 no-wrap barrier are untouched, as is every other Qwen admission condition of `docs/qwen-port.md`. +- Whether c = sqrt(d) / 2^t (rather than sqrt(d) / 64) is right for the integer norm's other constants and the shifts of `scales/` at widths outside 4,096 to 16,383 is not tested here; at Qwen's width t = 6 and the two agree. +- The words at shapes other than (5,120, 128) and (5,120, 256) are checked only between three computations written in this PR (the Python function, the C++ twin, an independent Fraction bisection), not against any external source. +- Not checked: the public fork the issue names; nothing was read or copied from it. + +## Deviations + +None from the registered thresholds. Implementation choices are listed in PREREG Amendment A1, committed before the runs. + +## Changed after review (PREREG Amendment A2, 2026-11-29; text only) + +A review of head 111b104d (PR comment 7249850873) found that this file and the code comments presented c = sqrt(d) / 2^t as a rule stated by `scales/README.md` and `docs/model.md` section 11.3. They state sqrt(d) / 64. Reworded for that reason: one sentence of "In plain words" and the section "The answer to the issue's first question" here, the `fold_constants` docstring in `weight_sums/weight_sums.py`, the matching comment in `weight_sums/weight_sums.cpp`, one passage of `weight_sums/README.md` and the ledger row's summary. No code line, test, run file, verdict, count or threshold changed, no run was repeated, and nothing was built for this step. diff --git a/experiments/20261129-214-fold-constants/compare_base_head.py b/experiments/20261129-214-fold-constants/compare_base_head.py new file mode 100644 index 000000000..faef25451 --- /dev/null +++ b/experiments/20261129-214-fold-constants/compare_base_head.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +# Copyright 2026 Anthropic PBC +# SPDX-License-Identifier: Apache-2.0 + +"""PREREG metric 3: byte comparison of the sums files that weight_sums writes at the base commit and at the head. + +usage: python3 compare_base_head.py [--debug] [] + +Each checkout must have bin/weight_sums built from its own weight_sums/weight_sums.cpp. For every input of +weight_sums/tests/run_tests.sh (oracle seeds 1, 2, 3, 4, 100, 101, 102 at e_res 11; seed 1 at e_res 10; +seed 2 with --decode-twice for weight_sums.py; and, if is given, the make_model model with the +arguments run_tests.sh uses), the inputs are written once with the HEAD checkout's tests/oracle.py (oracle.py +is not changed by this experiment) and each of the four programs (base C++, base Python, head C++, head +Python) writes a sums file. Recorded per input and program: exit status, SHA-256 of the file, and whether it +equals the base file of the same language and the expected file of oracle.py / make_model byte for byte. +The output json contains no path. It never prints a weight (the inputs are synthetic in any case). +""" + +import hashlib +import json +import os +import subprocess +import sys + +CASES = [(seed, 11, []) for seed in (1, 2, 3, 4, 100, 101, 102)] + [(1, 10, ["--eres", "10"])] +PY_ONLY = [(2, 11, ["--decode-twice"])] + + +def sha(path): + with open(path, "rb") as file: + return hashlib.sha256(file.read()).hexdigest() + + +def run(command, out): + status = subprocess.run(command + ["--out", out], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode + return status, (sha(out) if status == 0 and os.path.exists(out) else None) + + +def programs(checkout): + return { + "cpp": [os.path.join(checkout, "bin", "weight_sums"), "--threads", "2"], + "py": [sys.executable, "-B", os.path.join(checkout, "weight_sums", "weight_sums.py"), "--workers", "2"], + } + + +def main(argv): + global CASES, PY_ONLY + if argv[:1] == ["--debug"]: # oracle seed 7 only, which the registered suite does not use (PREREG "Runs") + CASES, PY_ONLY, argv = [(7, 11, [])], [], argv[1:] + if len(argv) not in (4, 5): + print(__doc__) + return 2 + base, head, work, output = (os.path.abspath(a) for a in argv[:4]) + make_model = os.path.abspath(argv[4]) if len(argv) == 5 else None + os.mkdir(work) + arms = {"base": programs(base), "head": programs(head)} + rows = [] + + def compare(name, shards, expected, extra, languages): + expected_sha = sha(expected) + for language in languages: + results = {} + for arm in ("base", "head"): + out = os.path.join(work, f"{name}.{arm}.{language}.txt") + results[arm] = run(arms[arm][language] + extra + shards, out) + rows.append({ + "input": name, + "program": language, + "extra_arguments": extra, + "base_status": results["base"][0], + "head_status": results["head"][0], + "base_sha256": results["base"][1], + "head_sha256": results["head"][1], + "expected_sha256": expected_sha, + "head_equals_base": results["head"][1] is not None and results["head"][1] == results["base"][1], + "head_equals_expected": results["head"][1] == expected_sha, + }) + + for seed, eres, extra in CASES + PY_ONLY: + folder = os.path.join(work, f"oracle_{seed}_{eres}") + if not os.path.exists(folder): + subprocess.run([sys.executable, "-B", os.path.join(head, "weight_sums", "tests", "oracle.py"), str(seed), + str(eres), folder], check=True, stdout=subprocess.DEVNULL) + shards = [os.path.join(folder, f"oracle-0000{i}-of-00002.gguf") for i in (1, 2)] + name = f"oracle.{seed}.eres{eres}" + ("".join(extra[:1]) if extra and extra[0] != "--eres" else "") + languages = ["py"] if (seed, eres, extra) in PY_ONLY else ["cpp", "py"] + compare(name, shards, os.path.join(folder, "expected.txt"), extra, languages) + + if make_model: + folder = os.path.join(work, "model") + subprocess.run([make_model, folder, "4", "40", "8", "2048", "1024", "16", "2048", "30"], check=True, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + shards = [os.path.join(folder, f"made-0000{i}-of-00002.gguf") for i in (1, 2)] + compare("make_model", shards, os.path.join(folder, "wsums.txt"), [], ["cpp", "py"]) + + every = all(r["head_equals_base"] and r["head_equals_expected"] and r["base_status"] == 0 for r in rows) + with open(output, "x", encoding="ascii") as file: + json.dump({"rows": rows, "comparisons": len(rows), "all_byte_identical": every}, file, indent=2) + file.write("\n") + print(f"comparisons: {len(rows)}, all byte-identical to base and to expected: {every}") + return 0 if every else 1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/experiments/20261129-214-fold-constants/independent_values.py b/experiments/20261129-214-fold-constants/independent_values.py new file mode 100644 index 000000000..6c165d3c2 --- /dev/null +++ b/experiments/20261129-214-fold-constants/independent_values.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +# Copyright 2026 Anthropic PBC +# SPDX-License-Identifier: Apache-2.0 + +"""Independent computation of the two fold constants at the registered shapes (PREREG metric 2). + +Does not import weight_sums. Two methods: + mpmath the root at 256 bits of precision; the nearest binary32 is found by stepping from a + float64 guess over neighbouring binary32 numbers and comparing distances in mpmath; a + distance tie (impossible for an irrational root) is reported, not resolved. + exact integer arithmetic: floor of the scaled root by math.isqrt, rounding by exact squaring. +Writes values.json next to this file (refuses to overwrite) and prints it. +usage: python3 independent_values.py [--check] (--check: compare with the existing values.json, write nothing) +""" + +import json +import math +import os +import struct +import sys + +import mpmath + +PRECISION_BITS = 256 +SHAPES = [(5120, 128), (5120, 256)] + + +def t_of(width): + t = 0 + while 4 ** (t + 1) <= width: + t += 1 + return t + + +def f32_word(x): + return struct.unpack("= 0: the smallest k with numerator * 4^k >= denominator * 2^46. + if numerator >= denominator * 2**46: + raise SystemExit("this method assumes q < 2^46") + k = 0 + while numerator * 4**k < denominator * 2**46: + k += 1 + big_n, big_d = numerator * 4**k, denominator + assert big_d * 2**46 <= big_n < big_d * 2**48 + m = math.isqrt(big_n // big_d) + if 4 * big_n > (2 * m + 1) ** 2 * big_d or (4 * big_n == (2 * m + 1) ** 2 * big_d and m % 2): + m += 1 + exponent = 23 - k + if m == 2**24: + m, exponent = m // 2, exponent + 1 + return ((exponent + 127) << 23) | (m - 2**23) + + +def compute(): + rows = [] + for width, head in SHAPES: + t = t_of(width) + row = {"width": width, "head": head, "t": t} + for name, den in (("c_0", 4**t), ("c_q", 4**t * head)): + word_m, decimal = by_mpmath(width, den) + word_e = by_exact(width, den) + if word_m != word_e: + raise SystemExit(f"the two methods differ at {width}, {head}, {name}") + row[name] = { + "exact_real": f"sqrt({width} / {den})", + "decimal_40_digits": decimal, + "word": f"0x{word_m:08X}", + "binary32_value": repr(f32_value(word_m)), + } + rows.append(row) + return { + "experiment": "20261129-214-fold-constants", + "rule": "t = largest integer with 4^t <= width; c_0 = RN32(sqrt(width / 4^t)); " + "c_q = RN32(sqrt(width / (4^t * head))); RN32 = nearest binary32, ties to even, one rounding", + "methods": [f"mpmath {mpmath.__version__} at {PRECISION_BITS} bits", "exact integer square roots"], + "values": rows, + } + + +def main(): + result = json.dumps(compute(), indent=2) + "\n" + path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "values.json") + if sys.argv[1:] == ["--check"]: + with open(path, encoding="ascii") as file: + same = file.read() == result + print("values.json matches" if same else "values.json DIFFERS") + return 0 if same else 1 + if os.path.exists(path): + raise SystemExit("values.json exists; this script does not overwrite it") + with open(path, "x", encoding="ascii") as file: + file.write(result) + print(result, end="") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/experiments/20261129-214-fold-constants/runs/compare.json b/experiments/20261129-214-fold-constants/runs/compare.json new file mode 100644 index 000000000..c22e8e25b --- /dev/null +++ b/experiments/20261129-214-fold-constants/runs/compare.json @@ -0,0 +1,242 @@ +{ + "rows": [ + { + "input": "oracle.1.eres11", + "program": "cpp", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "c140c7ae1eee83176c72a7ae723f147345d48ed31bc1fdd19af104a7f859313a", + "head_sha256": "c140c7ae1eee83176c72a7ae723f147345d48ed31bc1fdd19af104a7f859313a", + "expected_sha256": "c140c7ae1eee83176c72a7ae723f147345d48ed31bc1fdd19af104a7f859313a", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.1.eres11", + "program": "py", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "c140c7ae1eee83176c72a7ae723f147345d48ed31bc1fdd19af104a7f859313a", + "head_sha256": "c140c7ae1eee83176c72a7ae723f147345d48ed31bc1fdd19af104a7f859313a", + "expected_sha256": "c140c7ae1eee83176c72a7ae723f147345d48ed31bc1fdd19af104a7f859313a", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.2.eres11", + "program": "cpp", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "a8195662ab61568742450be6c41a38539cc7ddc7e3b4925f092c23d3fc10f854", + "head_sha256": "a8195662ab61568742450be6c41a38539cc7ddc7e3b4925f092c23d3fc10f854", + "expected_sha256": "a8195662ab61568742450be6c41a38539cc7ddc7e3b4925f092c23d3fc10f854", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.2.eres11", + "program": "py", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "a8195662ab61568742450be6c41a38539cc7ddc7e3b4925f092c23d3fc10f854", + "head_sha256": "a8195662ab61568742450be6c41a38539cc7ddc7e3b4925f092c23d3fc10f854", + "expected_sha256": "a8195662ab61568742450be6c41a38539cc7ddc7e3b4925f092c23d3fc10f854", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.3.eres11", + "program": "cpp", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "d2812035bc633de725c47e1d14fdf61c51b96a2ac6639fc5b7864f6231497600", + "head_sha256": "d2812035bc633de725c47e1d14fdf61c51b96a2ac6639fc5b7864f6231497600", + "expected_sha256": "d2812035bc633de725c47e1d14fdf61c51b96a2ac6639fc5b7864f6231497600", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.3.eres11", + "program": "py", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "d2812035bc633de725c47e1d14fdf61c51b96a2ac6639fc5b7864f6231497600", + "head_sha256": "d2812035bc633de725c47e1d14fdf61c51b96a2ac6639fc5b7864f6231497600", + "expected_sha256": "d2812035bc633de725c47e1d14fdf61c51b96a2ac6639fc5b7864f6231497600", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.4.eres11", + "program": "cpp", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "6ad6feb139725dab390de7b53e5d6a1d241f112b6d88c8f3073d72a14ef84744", + "head_sha256": "6ad6feb139725dab390de7b53e5d6a1d241f112b6d88c8f3073d72a14ef84744", + "expected_sha256": "6ad6feb139725dab390de7b53e5d6a1d241f112b6d88c8f3073d72a14ef84744", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.4.eres11", + "program": "py", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "6ad6feb139725dab390de7b53e5d6a1d241f112b6d88c8f3073d72a14ef84744", + "head_sha256": "6ad6feb139725dab390de7b53e5d6a1d241f112b6d88c8f3073d72a14ef84744", + "expected_sha256": "6ad6feb139725dab390de7b53e5d6a1d241f112b6d88c8f3073d72a14ef84744", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.100.eres11", + "program": "cpp", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "76e8d371c6b13a7f4a3fc7922d0c007efa711255ce4ef131c26c227b1a12b2e2", + "head_sha256": "76e8d371c6b13a7f4a3fc7922d0c007efa711255ce4ef131c26c227b1a12b2e2", + "expected_sha256": "76e8d371c6b13a7f4a3fc7922d0c007efa711255ce4ef131c26c227b1a12b2e2", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.100.eres11", + "program": "py", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "76e8d371c6b13a7f4a3fc7922d0c007efa711255ce4ef131c26c227b1a12b2e2", + "head_sha256": "76e8d371c6b13a7f4a3fc7922d0c007efa711255ce4ef131c26c227b1a12b2e2", + "expected_sha256": "76e8d371c6b13a7f4a3fc7922d0c007efa711255ce4ef131c26c227b1a12b2e2", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.101.eres11", + "program": "cpp", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "28838848b76487444a1b4f56a98201e74a7a85f37ebf1e3b4baef64a457f04c5", + "head_sha256": "28838848b76487444a1b4f56a98201e74a7a85f37ebf1e3b4baef64a457f04c5", + "expected_sha256": "28838848b76487444a1b4f56a98201e74a7a85f37ebf1e3b4baef64a457f04c5", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.101.eres11", + "program": "py", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "28838848b76487444a1b4f56a98201e74a7a85f37ebf1e3b4baef64a457f04c5", + "head_sha256": "28838848b76487444a1b4f56a98201e74a7a85f37ebf1e3b4baef64a457f04c5", + "expected_sha256": "28838848b76487444a1b4f56a98201e74a7a85f37ebf1e3b4baef64a457f04c5", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.102.eres11", + "program": "cpp", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "faac162054551dd0fc0f7a0c565064647f23501a872b6d455b5c64bfafd6c8a4", + "head_sha256": "faac162054551dd0fc0f7a0c565064647f23501a872b6d455b5c64bfafd6c8a4", + "expected_sha256": "faac162054551dd0fc0f7a0c565064647f23501a872b6d455b5c64bfafd6c8a4", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.102.eres11", + "program": "py", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "faac162054551dd0fc0f7a0c565064647f23501a872b6d455b5c64bfafd6c8a4", + "head_sha256": "faac162054551dd0fc0f7a0c565064647f23501a872b6d455b5c64bfafd6c8a4", + "expected_sha256": "faac162054551dd0fc0f7a0c565064647f23501a872b6d455b5c64bfafd6c8a4", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.1.eres10", + "program": "cpp", + "extra_arguments": [ + "--eres", + "10" + ], + "base_status": 0, + "head_status": 0, + "base_sha256": "ff6ae0e28cdda827089fde935b6a71fabd8364a83a62eaed88d60b0ccc0fa93c", + "head_sha256": "ff6ae0e28cdda827089fde935b6a71fabd8364a83a62eaed88d60b0ccc0fa93c", + "expected_sha256": "ff6ae0e28cdda827089fde935b6a71fabd8364a83a62eaed88d60b0ccc0fa93c", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.1.eres10", + "program": "py", + "extra_arguments": [ + "--eres", + "10" + ], + "base_status": 0, + "head_status": 0, + "base_sha256": "ff6ae0e28cdda827089fde935b6a71fabd8364a83a62eaed88d60b0ccc0fa93c", + "head_sha256": "ff6ae0e28cdda827089fde935b6a71fabd8364a83a62eaed88d60b0ccc0fa93c", + "expected_sha256": "ff6ae0e28cdda827089fde935b6a71fabd8364a83a62eaed88d60b0ccc0fa93c", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "oracle.2.eres11--decode-twice", + "program": "py", + "extra_arguments": [ + "--decode-twice" + ], + "base_status": 0, + "head_status": 0, + "base_sha256": "a8195662ab61568742450be6c41a38539cc7ddc7e3b4925f092c23d3fc10f854", + "head_sha256": "a8195662ab61568742450be6c41a38539cc7ddc7e3b4925f092c23d3fc10f854", + "expected_sha256": "a8195662ab61568742450be6c41a38539cc7ddc7e3b4925f092c23d3fc10f854", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "make_model", + "program": "cpp", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "1bb95443573883e36231cf48975932b81b6435ebea72ad50dbd70d6ad0cf275e", + "head_sha256": "1bb95443573883e36231cf48975932b81b6435ebea72ad50dbd70d6ad0cf275e", + "expected_sha256": "1bb95443573883e36231cf48975932b81b6435ebea72ad50dbd70d6ad0cf275e", + "head_equals_base": true, + "head_equals_expected": true + }, + { + "input": "make_model", + "program": "py", + "extra_arguments": [], + "base_status": 0, + "head_status": 0, + "base_sha256": "1bb95443573883e36231cf48975932b81b6435ebea72ad50dbd70d6ad0cf275e", + "head_sha256": "1bb95443573883e36231cf48975932b81b6435ebea72ad50dbd70d6ad0cf275e", + "expected_sha256": "1bb95443573883e36231cf48975932b81b6435ebea72ad50dbd70d6ad0cf275e", + "head_equals_base": true, + "head_equals_expected": true + } + ], + "comparisons": 19, + "all_byte_identical": true +} diff --git a/experiments/20261129-214-fold-constants/runs/run_tests.base.txt b/experiments/20261129-214-fold-constants/runs/run_tests.base.txt new file mode 100644 index 000000000..3a281b8b6 --- /dev/null +++ b/experiments/20261129-214-fold-constants/runs/run_tests.base.txt @@ -0,0 +1,27 @@ +passed: build +passed: unit +passed: oracle.1.cpp +passed: oracle.1.py +passed: oracle.2.cpp +passed: oracle.2.py +passed: oracle.3.cpp +passed: oracle.3.py +passed: oracle.4.cpp +passed: oracle.4.py +passed: oracle.100.cpp +passed: oracle.100.py +passed: oracle.101.cpp +passed: oracle.101.py +passed: oracle.102.cpp +passed: oracle.102.py +passed: oracle.2.py.decode-twice +passed: oracle.1.eres10.cpp +passed: oracle.1.eres10.py +passed: edge.cpp +passed: edge.py +passed: refusals.cpp +passed: refusals.py +passed: fork-failure.py +passed: model.cpp +passed: model.py +run_tests: every step that ran passed; 0 skipped diff --git a/experiments/20261129-214-fold-constants/runs/run_tests.head.txt b/experiments/20261129-214-fold-constants/runs/run_tests.head.txt new file mode 100644 index 000000000..c5a1eb1a7 --- /dev/null +++ b/experiments/20261129-214-fold-constants/runs/run_tests.head.txt @@ -0,0 +1,28 @@ +passed: build +passed: unit +passed: fold-constants.py +passed: oracle.1.cpp +passed: oracle.1.py +passed: oracle.2.cpp +passed: oracle.2.py +passed: oracle.3.cpp +passed: oracle.3.py +passed: oracle.4.cpp +passed: oracle.4.py +passed: oracle.100.cpp +passed: oracle.100.py +passed: oracle.101.cpp +passed: oracle.101.py +passed: oracle.102.cpp +passed: oracle.102.py +passed: oracle.2.py.decode-twice +passed: oracle.1.eres10.cpp +passed: oracle.1.eres10.py +passed: edge.cpp +passed: edge.py +passed: refusals.cpp +passed: refusals.py +passed: fork-failure.py +passed: model.cpp +passed: model.py +run_tests: every step that ran passed; 0 skipped diff --git a/experiments/20261129-214-fold-constants/values.json b/experiments/20261129-214-fold-constants/values.json new file mode 100644 index 000000000..c0e3d46ef --- /dev/null +++ b/experiments/20261129-214-fold-constants/values.json @@ -0,0 +1,44 @@ +{ + "experiment": "20261129-214-fold-constants", + "rule": "t = largest integer with 4^t <= width; c_0 = RN32(sqrt(width / 4^t)); c_q = RN32(sqrt(width / (4^t * head))); RN32 = nearest binary32, ties to even, one rounding", + "methods": [ + "mpmath 1.3.0 at 256 bits", + "exact integer square roots" + ], + "values": [ + { + "width": 5120, + "head": 128, + "t": 6, + "c_0": { + "exact_real": "sqrt(5120 / 4096)", + "decimal_40_digits": "1.11803398874989484820458683436563811772", + "word": "0x3F8F1BBD", + "binary32_value": "1.1180340051651" + }, + "c_q": { + "exact_real": "sqrt(5120 / 524288)", + "decimal_40_digits": "0.09882117688026185412496542326352245417874", + "word": "0x3DCA62C2", + "binary32_value": "0.09882117807865143" + } + }, + { + "width": 5120, + "head": 256, + "t": 6, + "c_0": { + "exact_real": "sqrt(5120 / 4096)", + "decimal_40_digits": "1.11803398874989484820458683436563811772", + "word": "0x3F8F1BBD", + "binary32_value": "1.1180340051651" + }, + "c_q": { + "exact_real": "sqrt(5120 / 1048576)", + "decimal_40_digits": "0.06987712429686842801278667714785238235752", + "word": "0x3D8F1BBD", + "binary32_value": "0.06987712532281876" + } + } + ] +} diff --git a/research/results.yaml b/research/results.yaml index 29912a2ce..6102c1f83 100644 --- a/research/results.yaml +++ b/research/results.yaml @@ -2090,3 +2090,15 @@ results: - {"name": "wcc_softplus_offset_heads_outside", "stat": "count", "value": 17, "total": 2304, "unit": "count", "n": 2304, "spread": null, "hardware": "cpu-epyc-rome-kvm-16", "date": "2026-11-29", "commit": "ec2d02e63456e0ac19191414c6c25fde1c5778d7", "source": "experiments/20261129-239-qwen-weight-cell-classes/runs/summary.json", "note": "Measured, unreplicated, descriptive (no bar); heads whose dt_bias alone (dt_int / 4,096) lies outside softplus v1's [-8, 8): 16 at or above 8 (layer 0: 15, layer 58: 1), 1 below -8 (layer 1); bias only, not activations (PR #146)"} - {"name": "wcc_cA_min_sig_bits", "stat": "single", "value": 2, "unit": "int", "n": 2304, "spread": null, "hardware": "cpu-epyc-rome-kvm-16", "date": "2026-11-29", "commit": "ec2d02e63456e0ac19191414c6c25fde1c5778d7", "source": "experiments/20261129-239-qwen-weight-cell-classes/runs/summary.json", "note": "Measured, unreplicated, descriptive; smallest bit length of a head's cA_int over 2,304 heads (layers 12, 28, 44); 357 heads at 5 bits or fewer, 0 at zero; one cA exponent per layer"} - {"name": "wcc_tensors_identical_stock_abl", "stat": "count", "value": 192, "total": 192, "unit": "count", "n": 192, "spread": null, "hardware": "cpu-epyc-rome-kvm-16", "date": "2026-11-29", "commit": "acd0e4b1fbb1f5a74f764d50c09f51ebea992bbb", "source": "experiments/20261129-239-qwen-weight-cell-classes/runs/ckpt-compare.json", "note": "Measured; conv1d, norm, A_log, dt_bias of 48 layers with equal SHA-256 in both pinned checkpoints"} + + - id: fold-constants-214 + title: "Fold constants computed by the rule for any width and head size in weight_sums (Python and C++), byte-identical at 5,120 / 128 (issue #214, CPU part)" + status: "measured" + replication: "unreplicated" + pr: 234 + summary: "Measured, unreplicated, deterministic, CPU only. weight_sums.py and bin/weight_sums compute the two fold constants with fold_constants(width, head) (t the largest integer with 4^t <= d, c = sqrt(d) / 2^t, c_0 = RN32(c), c_q = RN32(c / sqrt(dh)), one rounding of the exact real) instead of literals. docs/model.md section 11.3 and scales/README.md state the constant as sqrt(d) / 64, right for 5,120 / 128 only; that equals c where t = 6 (widths 4,096 to 16,383, 5,120 included). For other widths, using c is a choice made in this PR: no document on main states it, it is not tested against the scales of scales/, and the tests check only the arithmetic of the formula. At (5,120, 128) both programs give 0x3F8F1BBD and 0x3DCA62C2, main's literals (also a C++ static_assert). 19 of 19 sums files of the existing suite's inputs (oracle seeds 1-4 and 100-102 at e_res 11, seed 1 at e_res 10, seed 2 with --decode-twice, the make_model model; both programs where the suite runs both) are byte-identical between base and head and equal the expected files; run_tests.sh passes every step at base (26) and head (27, one new). Independent values (mpmath at 256 bits and exact integer roots) at (5,120, 256): c_0 0x3F8F1BBD, c_q 0x3D8F1BBD. NOT established: the shape gates of weight_sums and the prover still accept only 5,120 / 128 (no admission gate opened); the CUDA reader and its gate are unchanged and not compiled (the needed change is an open item in RESULTS.md); no Qwen commit, no weights; partial rotary and the dh = 256 no-wrap barrier untouched" + conditions: "CPU only, cores 14-15 of a shared loaded host, suite runs through the heavy-job gate; g++ 13.3.0 with weight_sums' own flags; Python 3.12.3 venv with numpy 2.3.5, gguf 0.19.0, mpmath 1.3.0; PREREG first and alone, one amendment (implementation choices) before the runs; debug only on oracle seed 7" + evidence: ["experiments/20261129-214-fold-constants/RESULTS.md", "experiments/20261129-214-fold-constants/PREREG.md", "experiments/20261129-214-fold-constants/ENV.json", "experiments/20261129-214-fold-constants/values.json", "experiments/20261129-214-fold-constants/runs/compare.json", "experiments/20261129-214-fold-constants/runs/run_tests.base.txt", "experiments/20261129-214-fold-constants/runs/run_tests.head.txt"] + metrics: + - {"name": "fold214_sums_byte_identical", "stat": "count", "value": 19, "total": 19, "unit": "count", "n": 1, "spread": null, "source": "experiments/20261129-214-fold-constants/runs/compare.json", "note": "Measured, unreplicated; sums files written at head equal to those at base and to oracle.py / make_model's expected file, byte for byte, over the suite's inputs; deterministic, one run per arm, spread null", "hardware": "cpu-epyc-rome-kvm-16", "date": "2026-11-29", "commit": "b1939005f282493a42157df073b63439fd097d7d"} + - {"name": "fold214_run_tests_head_passed", "stat": "count", "value": 27, "total": 27, "unit": "count", "n": 1, "spread": null, "source": "experiments/20261129-214-fold-constants/runs/run_tests.head.txt", "note": "Measured, unreplicated; weight_sums/tests/run_tests.sh steps passed at head, 0 skipped; base 26 of 26 (runs/run_tests.base.txt); deterministic", "hardware": "cpu-epyc-rome-kvm-16", "date": "2026-11-29", "commit": "b1939005f282493a42157df073b63439fd097d7d"} diff --git a/weight_sums/README.md b/weight_sums/README.md index 9fa382e49..d6130ed26 100644 --- a/weight_sums/README.md +++ b/weight_sums/README.md @@ -226,7 +226,15 @@ decodes it (Q8_0, F16 and BF16: as gguf-py does); in a matrix that reads a norma by that normalization's weight and a constant; each matrix gets the largest exponent e for which every value times 2^e rounds to at most 4,095 in absolute value; and each integer is the value times 2^e, rounded to nearest, ties to even. The embedding's exponent is e_res, and its integers must stay -below 2^30 in absolute value. The scaling steps are common in the quantization of neural networks +below 2^30 in absolute value. The two constants are computed by `fold_constants(width, head)` in +both programs. docs/model.md, section 11.3, states them as RN32(sqrt(d) / 64) and, for the query +matrix, RN32(sqrt(d) / 64 / sqrt(dh)), right for d = 5,120 and dh = 128 only: the bit patterns +0x3F8F1BBD and 0x3DCA62C2, which the function returns there and which `tests/fold_constants_test.py` +and the unit test check. The function computes c_0 = RN32(c) and c_q = RN32(c / sqrt(dh)), each one +rounding of the exact value, with t the largest integer with 4^t <= d and c = sqrt(d) / 2^t. That is +sqrt(d) / 64 where t = 6, for widths from 4,096 to 16,383. For other widths, c is a choice made with +this function: docs/model.md does not state it, and it is not tested against the scales of `scales/`. +The programs still accept only that width and head dimension. The scaling steps are common in the quantization of neural networks (in the table, the gains of a norm are the normalization's weights, and d is the model's width): | method | publication | diff --git a/weight_sums/tests/fold_constants_test.py b/weight_sums/tests/fold_constants_test.py new file mode 100644 index 000000000..d921aa8ca --- /dev/null +++ b/weight_sums/tests/fold_constants_test.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +# Copyright 2026 Anthropic PBC +# SPDX-License-Identifier: Apache-2.0 + +"""Tests fold_constants() of weight_sums/weight_sums.py against main's literals and an independent computation. + +fold_constants(width, head) returns the binary32 bit patterns of the two constants of the conversion rule +(scales/README.md, "The exponent of each cell", step 2). This test checks: +1. at (5120, 128) the words 0x3F8F1BBD and 0x3DCA62C2, the literals that weight_sums.py and bin/weight_sums held + before fold_constants() existed; +2. at (5120, 256) the words recorded in experiments/20261129-214-fold-constants/values.json; +3. at a fixed list of shapes, agreement with a second computation written here independently of + weight_sums.py: the nearest binary32 number to the root, found with fractions.Fraction (exact) by + bisection over the binary32 numbers, with the tie rule checked by exact squaring. +It needs numpy and gguf-py, because it imports weight_sums.py. Exit status 0 if every check passes, else 1. +usage: python3 weight_sums/tests/fold_constants_test.py +""" + +import os +import struct +import sys +from fractions import Fraction + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) +import weight_sums # noqa: E402 (the path is set first) + +SHAPES = [ + (5120, 128), (5120, 256), (5120, 64), (2048, 64), (4096, 128), (4095, 128), (16383, 128), (16384, 128), + (8192, 128), (7168, 128), (3072, 128), (1, 1), (2, 1), (3, 1), (4, 1), (2**32 - 1, 1), (1, 2**32 - 1), + (2**32 - 1, 2**32 - 1), (5120, 3), (5120, 96), (5120, 192), (6144, 128), (12288, 128), +] + + +def value_of(word): + """The exact value of a positive normal binary32 bit pattern, as a Fraction.""" + return Fraction(struct.unpack(" midpoint**2 or (square == midpoint**2 and low % 2 == 1): + return low + 1 + return low + + +def independent(width, head): + t = 0 + while 4 ** (t + 1) <= width: + t += 1 + return nearest_word(Fraction(width, 4**t)), nearest_word(Fraction(width, 4**t * head)) + + +def main(): + failures = [] + + def check(passed, text): + if not passed: + failures.append(text) + + found = weight_sums.fold_constants(5120, 128) + check(found == (0x3F8F1BBD, 0x3DCA62C2), f"(5120, 128) gives {found[0]:#010x}, {found[1]:#010x}") + check( + weight_sums.NORM_CONSTANT.view("= 2^-64, so 0 <= k <= 56 below. + while (num < (den << 46)) { + ++k; + num <<= 2; + } + while (num >= (den << 48)) { // only if n / d >= 2^48, which the callers exclude; kept for completeness + --k; + den <<= 2; + } + const U floor_q = num / den; // floor(sqrt(num / den)) = isqrt(floor(num / den)) + U m = 0; + for (int bit = 24; bit >= 0; --bit) { // floor_q < 2^48, so its root is below 2^24 + const U trial = m | (U(1) << bit); + if (trial * trial <= floor_q) m = trial; + } + const U left = 4 * num, right = (2 * m + 1) * (2 * m + 1) * den; + if (left > right || (left == right && (m & 1) == 1)) ++m; + int exponent = 23 - k; + if (m == (U(1) << 24)) { + m >>= 1; + ++exponent; + } + return (static_cast(exponent + 127) << 23) | static_cast(m - (U(1) << 23)); +} + +// The two fold constants for a width d and a head size dh, both from 1 to 2^32 - 1, as binary32 bit +// patterns: t is the largest integer with 4^t <= d, c = sqrt(d) / 2^t, norm = RN32(c) and query = +// RN32(c / sqrt(dh)), each one rounding of the exact real. +// What the documents state: docs/model.md, section 11.3, gives the constants as RN32(sqrt(d) / 64) and, +// for the query matrix, RN32(sqrt(d) / 64 / sqrt(dh)), and says they are right for d = 5,120 and +// dh = 128 only. scales/README.md gives the conversion's constant as sqrt(d) / 64 too. Neither states +// sqrt(d) / 2^t as the conversion's constant. For 4,096 <= d < 16,384, t = 6 and c = sqrt(d) / 64, the +// documented constant. For every other width (t != 6), using c is a choice made with this function, +// not a rule that those documents state. c is what scales/README.md ("The exponent of each cell", +// step 2) defines for the exponents of the fit's norm sites, and that README says sqrt(d) / 64 cancels +// c only where t = 6. For t != 6 the words differ from the documented form: at (2048, 64), norm is +// 0x3FB504F3 (sqrt(2)), while sqrt(2048) / 64 is half of that, 0x3F3504F3. The choice is argued in +// experiments/20261129-214-fold-constants/PREREG.md and is not tested against the scales of scales/. +// What is tested is the arithmetic, not the choice: tests/unit_test.cpp (test_fold_constants) pins the +// words at seven shapes, (2048, 64) among them, and tests/fold_constants_test.py compares +// weight_sums.py's words with a second exact computation of the same formula. plan() accepts +// (5120, 128) only, so no other shape reaches a sums file. weight_sums.py's fold_constants() computes +// the same words. +struct FoldConstants { + std::uint32_t norm; + std::uint32_t query; +}; +constexpr FoldConstants fold_constants(std::uint32_t width, std::uint32_t head) { + int t = 0; + while (t < 15 && (std::uint64_t{1} << (2 * (t + 1))) <= width) ++t; + const std::uint64_t four_t = std::uint64_t{1} << (2 * t); + return {rn32_sqrt_word(width, four_t), rn32_sqrt_word(width, four_t * head)}; +} + // The only model width (metadata key embedding_length) and head dimension (attention.key_length) -// that plan() accepts. The two constants below are right for these values only. kQueryConstant -// includes the attention scale, 1 / sqrt(128). +// that plan() accepts. The two constants are computed by fold_constants() for these values; at +// (5120, 128) the rule gives 0x3F8F1BBD and 0x3DCA62C2 (checked below and in tests/unit_test.cpp). +// kQueryConstant includes the attention scale, 1 / sqrt(128). constexpr std::uint32_t kWidth = 5120; constexpr std::uint32_t kHeadDimension = 128; -constexpr std::uint32_t kNormConstant = 0x3F8F1BBDu; // RN32(sqrt(5120) / 64), as a binary32 bit pattern -constexpr std::uint32_t kQueryConstant = 0x3DCA62C2u; // RN32(sqrt(5120) / 64 / sqrt(128)), as a binary32 bit pattern +constexpr std::uint32_t kNormConstant = fold_constants(kWidth, kHeadDimension).norm; // RN32(sqrt(5120) / 64) +constexpr std::uint32_t kQueryConstant = fold_constants(kWidth, kHeadDimension).query; // RN32(sqrt(5120) / 64 / sqrt(128)) +static_assert(kNormConstant == 0x3F8F1BBDu && kQueryConstant == 0x3DCA62C2u, + "the rule must give main's two literals at width 5120 and head dimension 128"); // A tensor with the role matrix or embedding is committed. The output head has the role matrix. enum class Role { ignored, norm, matrix, embedding }; diff --git a/weight_sums/weight_sums.py b/weight_sums/weight_sums.py index cb44803b1..4078ca373 100755 --- a/weight_sums/weight_sums.py +++ b/weight_sums/weight_sums.py @@ -143,12 +143,80 @@ def say(text): # Quantization for Deep Learning Inference: Principles and Empirical Evaluation", # arXiv:2004.09602, section 3.4. -# NORM_CONSTANT and QUERY_CONSTANT are valid only for this width (embedding_length in GGUF) and this -# head dimension. QUERY_CONSTANT includes the attention scale, 1 / sqrt(HEAD_DIMENSION). + +def rn32_sqrt_word(numerator, denominator): + """Return the binary32 bit pattern of RN32(sqrt(numerator / denominator)), for positive integers. + + RN32 rounds the exact real root to the nearest binary32 number, ties to even, once. The work is in + integers only: m = sqrt(q) * 2^k is brought into [2^23, 2^24), m0 = floor(m) is an integer square + root, and m is compared with m0 + 1/2 by squaring. The result must be a normal binary32 number. + """ + if numerator <= 0 or denominator <= 0: + raise ValueError("the operand of the root must be positive") + # k with 2^46 <= q * 4^k < 2^48, that is 2^23 <= sqrt(q) * 2^k < 2^24. k may be negative. + k = 23 - (numerator.bit_length() - denominator.bit_length()) // 2 + while True: + scaled_num = numerator << (2 * k) if k >= 0 else numerator + scaled_den = denominator if k >= 0 else denominator << (-2 * k) + if scaled_num < scaled_den << 46: + k += 1 + elif scaled_num >= scaled_den << 48: + k -= 1 + else: + break + m = math.isqrt(scaled_num // scaled_den) # floor(sqrt(N / D)) = isqrt(floor(N / D)) + # Compare sqrt(N / D) with m + 1/2: 4 N against (2 m + 1)^2 D. + left, right = 4 * scaled_num, (2 * m + 1) ** 2 * scaled_den + if left > right or (left == right and m % 2 == 1): + m += 1 + exponent = 23 - k # sqrt(q) is about m * 2^-k = (m / 2^23) * 2^exponent + if m == 1 << 24: + m, exponent = m >> 1, exponent + 1 + if not -126 <= exponent <= 127: + raise ValueError("the root is not a normal binary32 number") + return ((exponent + 127) << 23) | (m - (1 << 23)) + + +def fold_constants(width, head): + """Return (c_0, c_q), the binary32 bit patterns of the two fold constants for a width and a head size. + + What this function computes: t is the largest integer with 4^t <= width, c = sqrt(width) / 2^t (so + 1 <= c < 2), c_0 = RN32(c) is multiplied in with the gains of a norm, and c_q = RN32(c / sqrt(head)), + which also holds the attention scale, with the gains of the norm that the query matrix reads. Each + word is one rounding of the exact real value. + What the documents state: docs/model.md, section 11.3, gives the constants as RN32(sqrt(d) / 64) and, + for the query matrix, RN32(sqrt(d) / 64 / sqrt(dh)), and says they are right for d = 5,120 and + dh = 128 only. scales/README.md gives the conversion's constant as sqrt(d) / 64 too. Neither states + sqrt(d) / 2^t as the conversion's constant. For 4,096 <= width < 16,384, t = 6 and c = + sqrt(width) / 64, the documented constant; at (5120, 128) the words are the documented bit patterns. + For every other width (t != 6), using c is a choice made with this function, not a rule that those + documents state. c is what scales/README.md ("The exponent of each cell", step 2) defines for the + exponents of the fit's norm sites, and that README says sqrt(d) / 64 cancels c only where t = 6. For + t != 6 the words differ from the documented form: at (2048, 64), c_0 is 0x3FB504F3 (sqrt(2)), while + sqrt(2048) / 64 is half of that, 0x3F3504F3. The choice is argued in + experiments/20261129-214-fold-constants/PREREG.md and is not tested against the scales of scales/. + What is tested is the arithmetic, not the choice: weight_sums/tests/fold_constants_test.py compares + the words with a second exact computation of the same formula at a fixed list of shapes, (2048, 64) + among them, and weight_sums/tests/unit_test.cpp pins words of bin/weight_sums. The shape gates + below accept (5120, 128) only, so no other shape reaches a sums file. + Width and head size are whole numbers from 1 to 2^32 - 1 (bin/weight_sums has the same limits). + """ + for what, value in (("width", width), ("head size", head)): + if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value < 2**32: + raise ValueError(f"the {what} must be a whole number from 1 to 2^32 - 1") + t = (width.bit_length() - 1) // 2 # 4^t <= width < 4^(t + 1) + return rn32_sqrt_word(width, 4**t), rn32_sqrt_word(width, 4**t * head) + + +# The shape gates below accept this width (embedding_length in GGUF) and this head dimension only. The +# two constants are computed by fold_constants() for them; at (5120, 128) the rule gives the bit patterns +# 0x3F8F1BBD and 0x3DCA62C2 (weight_sums/tests/fold_constants_test.py checks this). QUERY_CONSTANT +# includes the attention scale, 1 / sqrt(HEAD_DIMENSION). WIDTH = 5120 HEAD_DIMENSION = 128 -NORM_CONSTANT = np.uint32(0x3F8F1BBD).view(np.float32) # sqrt(5120) / 64, rounded to binary32 -QUERY_CONSTANT = np.uint32(0x3DCA62C2).view(np.float32) # sqrt(5120) / 64 / sqrt(128), rounded to binary32 +_NORM_WORD, _QUERY_WORD = fold_constants(WIDTH, HEAD_DIMENSION) +NORM_CONSTANT = np.uint32(_NORM_WORD).view(np.float32) # RN32(sqrt(5120) / 64) +QUERY_CONSTANT = np.uint32(_QUERY_WORD).view(np.float32) # RN32(sqrt(5120) / 64 / sqrt(128)) # A layer's matrices are named blk...weight, with in decimal and no leading # zero. Each kind maps to the norm of the same layer whose output it reads, and to the constant that