diff --git a/README.md b/README.md index 3863e63f..c5424d0a 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,9 @@ App). Everything else - Python, the engine, the model - is set up for you. 2. Double-click **`START-HERE.bat`**. 3. Answer a few questions - or just press Enter each time for the recommended choice: - **Which model and size?** The original or Swift 1.5, and Q2_0, IQ2_XS, IQ3_XXS or IQ3_S - see [above](#which-model-should-i-pick) - - **How much context?** How much text it can keep in mind at once (it suggests one for your card) + - **How much context?** How much text it can keep in mind at once (it suggests one for your card). 384K and + 512K (experimental) extend the model past its trained 262K by rope scaling - the setup turns it on itself (yarn and a + covering factor; `--rope-scaling`/`--rope-scale` override) ([details](docs/DETAILS.md)) - **Images?** Whether it should also read pictures - **Experimental speed projection?** Off unless you say yes - [read what it does](docs/DETAILS.md#experimental-speed-projection-experimental-off-by-default) first diff --git a/bench/results/2026-09-28-rope-scaling/README.md b/bench/results/2026-09-28-rope-scaling/README.md new file mode 100644 index 00000000..1624f43e --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/README.md @@ -0,0 +1,49 @@ +# Rope scaling: needle recall past the trained 262K + +The feature (PR #84, experimental): `--rope-scaling none|linear|yarn` extends the context past the model's +trained 262,144 positions by rescaling the rotary angles - llama.cpp's types, ggml's `rope_yarn` +arithmetic, one process config applied at the cos/sin table (default path) and as kernel constants +(`--native-rope`, the native indexer, prefill). The three tables here are the first end-to-end check +that a scaled run actually recalls past the trained end. + +**Hardware:** RTX 4070 Ti SUPER 16 GB, Ryzen 9 5900X (no AVX-512 - the IQ3_XXS native pack runs its +expert kernels on AVX-2), 125 GB RAM, Linux. **Engine:** this branch built from source (the log records +`rope scaling ... --max-context ... against a trained context of 262144` at startup). The runs below +were taken on the rope tree built over the 0.1.17-era base; the branch then rebased onto main (engine +0.1.20) - the drift touches none of the rope files - and the rebase was re-validated: `rope_parity` +green, a 64-token greedy run token-identical to the plain 0.1.20 build, and the yarn 262k probe +repeated green (see the last table row). Baseline arm A also re-checked the default is the stock +model: a 64-token greedy run produces the same token ids as the ready-made 0.1.17 engine, and +`rope_parity` holds the `none` table bit-identical to the pre-scaling builder. +**Method:** `tools/needle_bench.py` against a running server (launch recipes in `config-*.json`), +`temperature 0`, thinking off, depth 50%, one probe per length. + +| Arm | Scaling | Context | Probe | Prompt tokens | Result | Probe time | +| --- | --- | --- | --- | --- | --- | --- | +| A | none | 262,144 | 1k @ 50% | 1,442 | FOUND | 4 s | +| A | none | 262,144 | 32k @ 50% | 31,763 | FOUND | 27 s | +| A | none | 262,144 | 128k @ 50% | 128,328 | FOUND | 86 s | +| B | linear, factor 2 | 560,000 | 262k @ 50% | 274,222 | FOUND | 232 s | +| B | linear, factor 2 | 560,000 | 512k @ 50% | 527,051 | FOUND | 619 s | +| C | yarn, factor 2 | 560,000 | 262k @ 50% | 274,215 | FOUND | 236 s | +| C | yarn, factor 2 | 560,000 | 512k @ 50% | 526,988 | FOUND | 615 s | +| C | yarn, factor 2 | 560,000 | 262k @ 50% (the rebase re-check) | 273,708 | FOUND | 235 s | + +All 8 of 8 probes found the needle; JSON per arm: `needle-A-none.json`, `needle-B-linear2.json`, +`needle-B-linear2-512k.json`, `needle-C-yarn2.json` (+ the rebase re-check in +`needle-C-yarn2-rebased.json`); server and engine logs alongside. + +What this establishes, and what it does not: + +- **Past the trained end the model still reads.** 512k probes are 2.01x the trained 262,144 - position + interpolation (B) and YaRN (C) both hold a mid-context lookup there. +- **Scaled runs within the trained range are a slightly different model.** `yarn`'s mscale applies at + every position (a 64-token greedy prompt diverges from the stock run after ~19 tokens); arm A is the + stock model, arms B/C are not, by design. +- **One depth, one needle, one machine.** A single probe per (length, arm) at depth 50% says "recall + works there", not "no degradation anywhere" - a full depth sweep and a longer-length ladder (768K, + 1M) on the bench machine (64 GB RAM there vs 125 GB here, so 262K IQ3_XXS fits either way) is the + natural follow-up. 512K prompts prefill at ~850-950 tokens/s on this card; the probe time is almost + entirely prefill. +- **The `560,000` context** in arms B/C is headroom for the needle harness's tokenizer overshoot + (a "512k" probe tokenizes to ~527k); 524,288 exactly would refuse the probe. diff --git a/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json b/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json new file mode 100644 index 00000000..528fc9f6 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/config-A-none-262144.json @@ -0,0 +1,38 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "262144" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-A-none-262144.log" +} \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/config-B-linear2.json b/bench/results/2026-09-28-rope-scaling/config-B-linear2.json new file mode 100644 index 00000000..30b31d7d --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/config-B-linear2.json @@ -0,0 +1,42 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "560000", + "--rope-scaling", + "linear", + "--rope-scale", + "2" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-B-linear2-524288.log" +} \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json b/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json new file mode 100644 index 00000000..6172a63a --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/config-C-yarn2.json @@ -0,0 +1,42 @@ +{ + "exe": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/build/strata", + "cwd": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata", + "tokenizer": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_xxs-rope-scaling", + "lib_dirs": [ + "/usr/local/cuda/bin", + "/usr/local/cuda/lib64" + ], + "port": 8130, + "args": [ + "--pack", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/packs/iq3_xxs", + "--native", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", + "--ple-gguf", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/models/IQ3_XXS/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf", + "--expert-profile", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata-data/mtp/rt", + "--kv", + "int8", + "--kv-resident", + "32768", + "--max-context", + "560000", + "--rope-scaling", + "yarn", + "--rope-scale", + "2" + ], + "log": "/home/jakub/workspace/deepseek-harness/harnes_workspace/Strata/bench/results/2026-09-28-rope-scaling/engine-C-yarn2-524288.log" +} \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json b/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json new file mode 100644 index 00000000..526b7514 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/kv-sweep-tgs.json @@ -0,0 +1,121 @@ +[ + { + "length": "128k", + "round": 0, + "kind": "decode", + "prompt_tok": 128401, + "read": 52, + "gen": 357, + "read_tok_s": 79.2, + "gen_tok_s": 56.3, + "drafts_ok": 182, + "drafts_all": 305, + "seg_blocks": 3284340, + "seg_mib": 370.0, + "seg_misses": 91744, + "seg_hit_pct": 97.207, + "kib_per_token": 1061.29 + }, + { + "length": "128k", + "round": 1, + "kind": "read", + "prompt_tok": 128357, + "read": 128357, + "gen": 24, + "read_tok_s": 1389.2, + "gen_tok_s": 41.7, + "drafts_ok": 11, + "drafts_all": 23, + "seg_blocks": -3253560, + "seg_mib": -391.7, + "seg_misses": -97147, + "seg_hit_pct": 97.014, + "kib_per_token": -3.12 + }, + { + "length": "128k", + "round": 1, + "kind": "decode", + "prompt_tok": 128402, + "read": 52, + "gen": 388, + "read_tok_s": 76.5, + "gen_tok_s": 54.6, + "drafts_ok": 195, + "drafts_all": 363, + "seg_blocks": 3752616, + "seg_mib": 463.5, + "seg_misses": 114911, + "seg_hit_pct": 96.938, + "kib_per_token": 1223.26 + }, + { + "length": "512k", + "round": 0, + "kind": "read", + "prompt_tok": 522983, + "read": 522983, + "gen": 24, + "read_tok_s": 868.4, + "gen_tok_s": 42.4, + "drafts_ok": 13, + "drafts_all": 16, + "seg_blocks": -3808056, + "seg_mib": -387.8, + "seg_misses": -96113, + "seg_hit_pct": 97.476, + "kib_per_token": -0.76 + }, + { + "length": "512k", + "round": 0, + "kind": "decode", + "prompt_tok": 523028, + "read": 52, + "gen": 402, + "read_tok_s": 63.3, + "gen_tok_s": 48.4, + "drafts_ok": 221, + "drafts_all": 348, + "seg_blocks": 3580056, + "seg_mib": 920.4, + "seg_misses": 228658, + "seg_hit_pct": 93.613, + "kib_per_token": 2344.5 + }, + { + "length": "512k", + "round": 1, + "kind": "read", + "prompt_tok": 522984, + "read": 522984, + "gen": 24, + "read_tok_s": 857.1, + "gen_tok_s": 35.5, + "drafts_ok": 9, + "drafts_all": 18, + "seg_blocks": -3555408, + "seg_mib": -905.8, + "seg_misses": -225016, + "seg_hit_pct": 93.671, + "kib_per_token": -1.77 + }, + { + "length": "512k", + "round": 1, + "kind": "decode", + "prompt_tok": 523029, + "read": 52, + "gen": 402, + "read_tok_s": 61.3, + "gen_tok_s": 42.8, + "drafts_ok": 192, + "drafts_all": 388, + "seg_blocks": 4005216, + "seg_mib": 1079.9, + "seg_misses": 268221, + "seg_hit_pct": 93.303, + "kib_per_token": 2750.79 + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-A-none.json b/bench/results/2026-09-28-rope-scaling/needle-A-none.json new file mode 100644 index 00000000..099bd36b --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-A-none.json @@ -0,0 +1,29 @@ +[ + { + "length": "1k", + "depth": 50, + "prompt_tokens": 1442, + "seconds": 3.7, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "32k", + "depth": 50, + "prompt_tokens": 31763, + "seconds": 27.5, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + }, + { + "length": "128k", + "depth": 50, + "prompt_tokens": 128328, + "seconds": 86.1, + "found": true, + "word": "willow-cobalt-696", + "answer": "willow-cobalt-696" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json b/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json new file mode 100644 index 00000000..e93f21d4 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-B-linear2-512k.json @@ -0,0 +1,11 @@ +[ + { + "length": "512k", + "depth": 50, + "prompt_tokens": 527051, + "seconds": 619.0, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json b/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json new file mode 100644 index 00000000..7a987877 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-B-linear2.json @@ -0,0 +1,16 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 274222, + "seconds": 232.2, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "512k", + "depth": 50, + "error": "HTTP Error 400: Bad Request" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json new file mode 100644 index 00000000..659f51a3 --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2-rebased.json @@ -0,0 +1,11 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 273708, + "seconds": 234.8, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + } +] \ No newline at end of file diff --git a/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json new file mode 100644 index 00000000..2dfa146d --- /dev/null +++ b/bench/results/2026-09-28-rope-scaling/needle-C-yarn2.json @@ -0,0 +1,20 @@ +[ + { + "length": "262k", + "depth": 50, + "prompt_tokens": 274215, + "seconds": 235.5, + "found": true, + "word": "meadow-copper-504", + "answer": "meadow-copper-504" + }, + { + "length": "512k", + "depth": 50, + "prompt_tokens": 526988, + "seconds": 615.0, + "found": true, + "word": "falcon-quartz-940", + "answer": "falcon-quartz-940" + } +] \ No newline at end of file diff --git a/docs/DETAILS.md b/docs/DETAILS.md index c0911f69..29ad2811 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -449,6 +449,43 @@ it needs, prefer read-only tools, and don't add servers you don't trust. The too page itself (a request with another site's Origin or without a JSON content type is refused); if Strata is reachable from other devices, set an API key. +**Context extension past 262K (rope scaling, EXPERIMENTAL, off unless you pick it).** The model was trained on +262,144 positions (rotary base 1e7). Rope scaling rescales the rotation angles so that longer contexts stay usable, +with llama.cpp's types and flag names. `linear` is Position Interpolation: every angle is shrunk by the factor. +`yarn` keeps the high-frequency angles, interpolates the low-frequency ones, and adds the magnitude correction +that keeps the attention temperature where training put it. **Without the flags nothing changes:** an unscaled +run computes exactly what it did before the feature existed, bit for bit. Scaled contexts need proportionally +more VRAM/RAM for the KV cache and the rope tables (~13 KB and ~0.26 KB per token). + +What was measured (contributors' runs, RTX 5080 + IQ3_S, native path, in PR #84): per-position perplexity on the +same tokens, with only the scaling flag changed. At 293K tokens (1.12x the trained length), `yarn` with factor 2 +lowered the NLL by 0.18 nats against both `none` and `linear` 2 (2.04 vs 2.22 / 2.22). That is 3-4x the path noise +measured at the same length. `linear` 2 was indistinguishable from `none`. At 2.7K and 32K no arm separated from the +noise. Needle tests do not tell the arms apart: the unscaled model also finds a needle at 413K. Long real-document +Q&A worked with `yarn` 2 at 421K and `yarn` 4 at 714K (8/8 each), and a 1M-token `yarn` 4 run read end to end. +Taken together, use **yarn**. It is still experimental: the numbers come from one machine and one quant. + +- setup: `START-HERE.bat --setup --context 393216` asks nothing extra - it picks the method (yarn; one + question when run interactively) and derives the factor from the final context for you (final context / + 262,144, at least 1: 1.5 at 393K, 2 at 512K, 1 inside the trained range; `--rope-scaling`/`--rope-scale` + override; an explicit `--rope-scale` is kept as given even when it is too small for the context actually + served, so check it if you set one). An explicit `--rope-scaling none` for a context past + 262,144 is refused: the setup will not configure a run with the stock angles past the trained range. If + the RAM check reduces a chosen 384K/512K back inside the trained range, an omitted method adds no + scaling, and an explicitly chosen one stays at factor 1 - the trained angles, no expansion (not a + switch for rope as a whole: explicitly supplied rope settings keep their behavior). +- engine: `--rope-scaling none|linear|yarn`, `--rope-scale F`, and the raw ggml knobs `--rope-freq-base`, + `--rope-freq-scale`, `--yarn-orig-ctx` (default 262,144), `--yarn-ext-factor`, `--yarn-attn-factor`, + `--yarn-beta-fast` (32), `--yarn-beta-slow` (1). The model file's `rope.scaling.*` keys, when a + fine-tune ships them, are the defaults the flags override. + +The scaling is fixed for the whole run - the engine stores keys in its cache after rotating them, so one +cache must never mix two scalings, and there is no per-request form. Within the trained 262,144 a scaled +run is a slightly different model: the rescaled angles, and `yarn`'s magnitude correction, apply at every +position, not only past the trained end. That is why the setup turns scaling on only for a context past +262,144. Pictures read the same scaled table (their (t, h, w) positions feed it). That should work, but it is +unmeasured: all the runs above are text. + --- ## Images (vision) @@ -578,6 +615,7 @@ the document, +0.4% on the chat. Details: `bench/results/2026-09-27-esp/`. | `the engine stopped unexpectedly (exit code ...)` | The engine process ended mid-answer - usually out of RAM (Linux ends the biggest program: `sudo dmesg \| grep -i -E 'killed process\|out of memory'`). The next request starts it again by itself. If it repeats: close other programs or pick a smaller size. The server also warns at start when the model's experts leave less than ~6 GB of RAM for everything else. | | Slow output, disk light busy | Not enough free RAM: close other programs, or choose Q2_0 / IQ2_XS. | | `prompt ... exceeds the context` | The request is longer than the context you chose: run setup again with a bigger `--context`. | +| `the setup refuses --rope-scaling none for a past-trained context` | A context past the trained 262,144 needs the rotary angles rescaled (experimental rope scaling), and the setup will not configure one with the stock angles there. Let it pick (`START-HERE.bat --setup --context 393216` adds yarn and a covering factor), or pass `--rope-scaling linear` or `yarn` yourself. | | Slower than the tables | The monitor plugged into the GPU and other GPU programs take VRAM from the expert cache; RAM running below its rated speed (enable EXPO/XMP in the BIOS) slows the CPU half. | | `this server was started without the vision encoder` | The model was set up for text only: run setup again with `--vision gpu`. | | A picture is refused or `cannot read the image` | The file is not a picture Pillow can open (JPEG, PNG, WebP, GIF, BMP, TIFF, AVIF work). | diff --git a/include/strata/kernels/native_qsa_indexer.hpp b/include/strata/kernels/native_qsa_indexer.hpp index 560b12b5..fe66d4b0 100644 --- a/include/strata/kernels/native_qsa_indexer.hpp +++ b/include/strata/kernels/native_qsa_indexer.hpp @@ -1,5 +1,6 @@ #pragma once #include "strata/kernels/qsa.hpp" +#include "strata/kernels/rope_scaling.hpp" namespace strata::kernels { @@ -20,6 +21,9 @@ bool native_qsa_indexer_enabled(); // contiguous, with nonnegative pos_base divisible by four. Clear state before // starting a new sequence. Completed block b rotates at pos_base+4*b; the spare // always rotates at zero, including nonzero sequence bases, as in the oracle. +// Under rope scaling (rope_scaling.hpp) the zero angle keeps the spare's +// rotation an identity; YaRN's mscale rides in through cos(0) on both the pooled +// keys and the indexer queries, so selection is unchanged. // // Explicit nonnull stream; no allocation or synchronization. All spans must be // aligned and disjoint, remain valid through replay, and contain finite values; @@ -32,11 +36,11 @@ bool native_qsa_indexer_enabled(); // Host-side positions (not for a captured graph). void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma, float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells, - float freq_base, void* stream); + const RopeScaling& scaling, void* stream); void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base, const float* gamma, float epsilon, const QsaIndexerBuffers& buffers, const QsaShapes& shapes, - int64_t max_cells, float freq_base, void* stream); + int64_t max_cells, const RopeScaling& scaling, void* stream); } // namespace strata::kernels diff --git a/include/strata/kernels/native_rope.hpp b/include/strata/kernels/native_rope.hpp index 24bffe61..95511b88 100644 --- a/include/strata/kernels/native_rope.hpp +++ b/include/strata/kernels/native_rope.hpp @@ -1,14 +1,20 @@ #pragma once +#include "strata/kernels/rope_scaling.hpp" + namespace strata::kernels { void native_rope_set_enabled(bool enabled); bool native_rope_enabled(); -// Pinned CUDA text-only IMRoPE: F32 rows, 64 rotated channels, no YaRN/frequency -// factors, equal text positions in all four IMRoPE sections. Each device position -// must be nonnegative. The position buffer remains live through graph replay. -// Supports head_dim 128/256 and exact x==out; partial overlap is rejected. +// Pinned CUDA text-only IMRoPE: F32 rows, 64 rotated channels, equal text positions in all four +// IMRoPE sections. Each device position must be nonnegative. The position buffer remains live +// through graph replay. Supports head_dim 128/256 and exact x==out; partial overlap is rejected. // Explicit stream required. No allocation or synchronization. +// +// The scaling (rope_scaling.hpp) rides in as the resolved process config: none reproduces the +// original contract exactly, linear/YaRN apply ggml's rope_yarn - the interpolation mix, the +// corr_dims ramp along the pairs, and the mscale magnitude correction folded into cos and sin. +// The struct's knobs are process constants, so kernel arguments baked at graph capture stay valid. void native_rope_apply(const float* x, float* out, int rows, int head_dim, - int n_rot, float freq_base, const int* positions, void* stream); + int n_rot, const RopeScaling& scaling, const int* positions, void* stream); } diff --git a/include/strata/kernels/qsa.hpp b/include/strata/kernels/qsa.hpp index e6090abf..dc26024a 100644 --- a/include/strata/kernels/qsa.hpp +++ b/include/strata/kernels/qsa.hpp @@ -118,7 +118,10 @@ inline QsaShapes qsa_real_shapes() { /// The one legal RMSNorm epsilon for this artifact (`attention.layer_norm_rms_epsilon`). inline float qsa_rms_eps() { return 1e-6f; } -/// `rope.freq_base`, no rope.scaling keys, so freq_scale = 1 and no YaRN. +/// `rope.freq_base`, the DEFAULT frequency base. The artifact ships no `rope.scaling` keys, so the +/// process's rope scaling starts at none - the runtime configuration lives in `rope_scaling.hpp` +/// (`rope_scaling_set`, once at startup, before the table is built and any graph captured), and this +/// constant is what that config's `freq_base` defaults to and what CLI `--rope-freq-base` overrides. inline double qsa_freq_base() { return 1e7; } /// The selection width: `min(n_kv, idx_top_k + idx_block - 1)`. diff --git a/include/strata/kernels/rope.hpp b/include/strata/kernels/rope.hpp index 59b66c88..45e54faf 100644 --- a/include/strata/kernels/rope.hpp +++ b/include/strata/kernels/rope.hpp @@ -6,10 +6,18 @@ // The cos/sin table is built on the HOST in float64 (see src/kernels/cuda/rope.cu for why) and the kernel is // a pure rotation over it. The table depends on (n_rot, theta, position) and not on the token, so it is worth // caching; `build_rope_table` fills `max_pos` positions of `n_rot/2` pairs each. +// +// ROPE SCALING RIDES IN THE TABLE, NOT IN THE KERNEL. The kernels below read cos/sin values and +// cannot tell a scaled table from an unscaled one - with scaling on, the scaled angles (and YaRN's +// mscale magnitude correction, folded into the same values) simply ARE the table. That is why +// neither `rope_neox_apply` nor the indexer's pooling kernel takes any scaling argument: the config +// enters once, here, at build time (`rope_scaling.hpp`). #pragma once #include +#include "strata/kernels/rope_scaling.hpp" + #if defined(__CUDACC__) || defined(__HIPCC__) #define STRATA_ROPE_HD __host__ __device__ #else @@ -38,6 +46,12 @@ STRATA_ROPE_HD inline void rope_neox_pair(float a, float b, float c, float s, fl void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab); +/// The same table under the process's rope scaling (rope_scaling.hpp). For `RopeScalingType::None` +/// this IS the five-argument builder above - the parity test holds the two to be bit-identical - and +/// for linear/YaRN the scaled angles (YaRN's mscale included) replace them. The math is ggml's, +/// transcribed; see the header of `rope_scaling.hpp` for what arrives from where. +void build_rope_table(int n_rot, const RopeScaling& scaling, int max_pos, float* cos_tab, float* sin_tab); + // `x` and `out` are (rows, head_dim) and `pos` is (rows,) - one position per row, so a batch of heads at // different sequence positions is one call. `cos_tab`/`sin_tab` are (max_pos, n_rot/2). `out` may equal `x`. // diff --git a/include/strata/kernels/rope_scaling.hpp b/include/strata/kernels/rope_scaling.hpp new file mode 100644 index 00000000..b494ddc7 --- /dev/null +++ b/include/strata/kernels/rope_scaling.hpp @@ -0,0 +1,193 @@ +// include/strata/kernels/rope_scaling.hpp - rope scaling: extending the context past the trained one. +// +// WHAT IT IS. The artifact's RoPE is trained over `orig_ctx` positions (the artifact ships no +// `rope.scaling` keys, so this is a pure runtime feature). Scaling re-uses positions past that by +// rescaling the rotation angles. Three types, the llama.cpp set: +// +// none freq_scale 1, no correction - today's behaviour, exactly +// linear Position Interpolation: angles shrunk by 1/factor - every position fits again, all +// frequencies compressed uniformly +// yarn YaRN: high-frequency pairs keep their trained angles (extrapolate), low-frequency +// pairs are interpolated, and the pairs in between blend - plus a magnitude correction +// `mscale` that keeps the attention temperature where training put it +// +// THE MATH IS GGML'S, TRANSCRIBED, NOT RE-DERIVED. `third_party/llama.cpp` is vendored and is the +// numerical contract (the same standing `native_rope.cu` declares): ramp, correction dims, the +// interpolation mix and the mscale formula below are line-for-line that source, with the MIT +// attribution at each helper. The one deliberate deviation is bookkeeping: ggml's device kernel +// speaks in even dim indices (`i0`) and halves them inside the ramp, while every Strata rope kernel +// speaks in PAIR indices - so `rope_yarn_ramp` here takes the pair index and compares it against +// `corr_dims` directly. Same numbers, one less division per call site. +// +// HOW IT REACHES THE ROPE. Two forms, one config: +// +// - the TABLE path (the default decode path, the indexer's pooled key) never changes its kernels: +// scaling is baked into the cos/sin contents by `build_rope_table`, which the parity test checks +// bit-exactly against a float64 reference; +// - the ANALYTIC paths (`--native-rope`, the native indexer, prefill) get the resolved constants +// as kernel arguments. +// +// **PROCESS CONSTANTS, SET ONCE BEFORE CAPTURE.** A CUDA graph bakes kernel ARGUMENTS at capture +// time, so the scaling must be fixed before `session_init` captures the layers - which is exactly +// the constraint the per-token values already respect by living in device memory (`st.pos_dev`). +// `rope_scaling_set()` is called once from the engine's startup, after CLI and GGUF defaults meet, +// before any graph exists. There is deliberately no way to change it mid-process: the K already in +// the cache is stored POST-RoPE, so a mid-run change would mix two scalings in one cache. +#pragma once + +#include + +#if defined(__CUDACC__) || defined(__HIPCC__) +#define STRATA_ROPE_SCALING_HD __host__ __device__ +#else +#define STRATA_ROPE_SCALING_HD +#endif + +namespace strata::kernels { + +enum class RopeScalingType { None, Linear, YaRN }; + +/// The float32 constants the ANALYTIC rotation kernels take (`rope_scaled_angle`'s arguments). The defaults are +/// the identity: freq_scale 1, no correction, magnitude 1 - with them the helper computes `cosf(theta) * 1.0f` +/// on `1.0f * theta`, which is exactly today's unscaled `cosf(theta)` bit for bit. +struct RopeKernelArgs { + float freq_scale = 1.0f; + float corr_low = 0.0f; + float corr_high = 0.0f; + float ext_factor = 0.0f; + float attn_factor = 1.0f; +}; + +/// The one rope configuration, as the CLI flag family and the (future) GGUF rope keys resolve to. +/// +/// Default-constructed this is EXACTLY today's engine: freq_scale 1, mscale 1, no correction. That +/// identity is a regression gate, not a coincidence - the parity test compares the default's table +/// against the pre-scaling builder bit for bit. +struct RopeScaling { + RopeScalingType type = RopeScalingType::None; + double freq_base = 1e7; ///< `rope.freq_base` (the value pinned by `qsa_freq_base()`) + double factor = 1.0; ///< `--rope-scale`: how far past the trained context the run goes + double freq_scale_in = 0; ///< `--rope-freq-scale`: the raw ggml knob; 0 = 1/factor + double orig_ctx = 262144; ///< `--yarn-orig-ctx`: the context the model was trained over + double ext_factor = 0; ///< `--yarn-ext-factor`: correction depth; 0 = off, 1 = full YaRN + double attn_factor = 1.0; ///< `--yarn-attn-factor`: extra magnitude scale (ggml's attn_factor) + double beta_fast = 32.0; ///< `--yarn-beta-fast` + double beta_slow = 1.0; ///< `--yarn-beta-slow` + + /// The angle shrink. ggml's `freq_scale`: 1 means "the trained angles", 1/factor squeezes + /// `factor` positions into the trained range. + double freq_scale() const { + if (type == RopeScalingType::None) return 1.0; + return freq_scale_in > 0 ? freq_scale_in : 1.0 / factor; + } + + /// The magnitude correction. ggml's `rope_yarn` multiplies cos and sin by this; the log term + /// rides on `ext_factor != 0` (not on the type), exactly as that source has it. With the + /// default knobs YaRN factor F gives `1 + 0.1*ln(F)` - YaRN's temperature correction. + double mscale() const { + if (ext_factor == 0) return attn_factor; + return attn_factor * (1.0 + 0.1 * std::log(1.0 / freq_scale())); + } + + /// The correction window, in PAIR indices: below `out[0]` pairs extrapolate (keep the trained + /// angles), above `out[1]` they interpolate, in between they blend. Transcribed from ggml's + /// `ggml_rope_yarn_corr_dims` (see the derivation comment at `rope_yarn_corr_dim` below). + void corr_dims(int n_rot, double out[2]) const { + const double start = std::floor(rope_yarn_corr_dim(n_rot, orig_ctx, beta_fast, freq_base)); + const double end = std::ceil(rope_yarn_corr_dim(n_rot, orig_ctx, beta_slow, freq_base)); + out[0] = start < 0 ? 0 : start; + out[1] = end > (double) (n_rot - 1) ? (double) (n_rot - 1) : end; + } + + /// The analytic kernels' constants. `none` returns the identity constants WHATEVER the other knobs hold - + /// the table builder ignores them for `none` too, so the two rotation forms cannot disagree there, and an + /// unscaled run computes exactly what it computed before scaling existed. Linear/YaRN: ggml's `rope_yarn` + /// arguments (`attn_factor` is the raw knob; the helper applies the log term when correcting). + RopeKernelArgs kernel_args(int n_rot) const { + RopeKernelArgs a; + if (type == RopeScalingType::None) return a; + double cd[2]; + corr_dims(n_rot, cd); + a.freq_scale = (float) freq_scale(); + a.corr_low = (float) cd[0]; + a.corr_high = (float) cd[1]; + a.ext_factor = (float) ext_factor; + a.attn_factor = (float) attn_factor; + return a; + } + +private: + /// ggml/src/ggml.c: "Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` + /// for x, we get `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`". + /// float64 rather than ggml's float32: the table path computes in float64 and is held to a + /// bit-exact float64 reference, so its inputs are float64 too. + static double rope_yarn_corr_dim(int n_dims, double n_ctx_orig, double n_rot, double base) { + return (double) n_dims * std::log(n_ctx_orig / (n_rot * 2.0 * 3.14159265358979323846)) / + (2.0 * std::log(base)); + } +}; + +/// The ramp between extrapolation (1) and interpolation (0). +/// +/// ggml/src/ggml-cuda/rope.cu `rope_yarn_ramp`: `1 - clamp(y, 0, 1)` with +/// `y = (i0 / 2 - low) / max(0.001, high - low)`. ggml passes the even dim index `i0`; this takes +/// the pair index (ggml's `i0/2`) so Strata's pair-indexed kernels don't re-derive the mapping. The +/// 0.001 floor on the denominator is ggml's, kept verbatim: `corr_dims` can produce low == high. +STRATA_ROPE_SCALING_HD inline float rope_yarn_ramp(float low, float high, int pair) { + const float y = ((float) pair - low) / (high - low > 0.001f ? high - low : 0.001f); + const float clamped = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y); + return 1.0f - clamped; +} + +/// The scaled angle for one pair, float32, the ANALYTIC paths' contract (pinned ggml arithmetic). +/// +/// Takes `theta_extrap` - the position times that pair's trained `inv_freq` - and returns the angle +/// to take cos/sin of, with ggml's mscale already folded in. `mscale_in` must be `attn_factor` +/// (ggml's kernels receive the raw knob and apply the log term here, where it is per-pair constant; +/// this helper keeps that shape so the native path reads against ggml line by line). +STRATA_ROPE_SCALING_HD inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low, + float corr_high, float ext_factor, float mscale_in, + int pair, float& cos_out, float& sin_out) { + // The interpolation, always applied; the correction mixed in on top (ggml-cuda/rope.cu rope_yarn). + float theta = freq_scale * theta_extrap; + float mscale = mscale_in; + if (ext_factor != 0.0f) { + const float ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor; + theta = theta * (1.0f - ramp_mix) + theta_extrap * ramp_mix; + // "Get n-d magnitude scaling corrected for interpolation" - the log term only when correcting. + mscale *= 1.0f + 0.1f * logf(1.0f / freq_scale); + } + cos_out = cosf(theta) * mscale; + sin_out = sinf(theta) * mscale; +} + +/// The ONE validity rule for a resolved configuration, shared by the engine's startup check and every rotation +/// site that takes the struct, so a bad knob cannot pass one site and trip (or silently NaN) another. Returns +/// nullptr when the configuration is usable, else what is wrong. Every value is tested with `std::isfinite` +/// FIRST: a NaN passes every `<`/`<=` range comparison, which is how a `--rope-scale nan` would otherwise slip +/// through. `none` passes with any knob values - the knobs are inert there (the resolution resets them). +inline const char* rope_scaling_invalid(const RopeScaling& s) { + if (!std::isfinite(s.freq_base) || s.freq_base <= 1.0) return "the frequency base must be a finite value above 1"; + if (s.type == RopeScalingType::None) return nullptr; + if (!std::isfinite(s.factor) || s.factor < 1.0) return "the scaling factor must be a finite value >= 1"; + if (!std::isfinite(s.freq_scale_in) || s.freq_scale_in < 0.0) + return "the frequency scale must be finite and positive (0 = 1/factor)"; + const double fs = s.freq_scale(); + if (!std::isfinite(fs) || fs <= 0.0) return "the resolved frequency scale must be a finite positive value"; + if (!std::isfinite(s.orig_ctx) || s.orig_ctx < 1.0) return "the original (trained) context must be finite and > 0"; + if (!std::isfinite(s.ext_factor) || s.ext_factor < 0.0) return "the YaRN ext factor must be finite and >= 0"; + if (!std::isfinite(s.attn_factor) || s.attn_factor <= 0.0) return "the attention factor must be finite and > 0"; + if (!std::isfinite(s.beta_fast) || s.beta_fast <= 0.0 || !std::isfinite(s.beta_slow) || s.beta_slow <= 0.0) + return "the YaRN betas must be finite and > 0"; + if (!std::isfinite(s.mscale()) || s.mscale() <= 0.0) return "the resolved magnitude correction must be finite and > 0"; + return nullptr; +} + +/// The process's one rope configuration. Set it ONCE at startup, after the CLI and the model file +/// have agreed on the values and BEFORE `session_init` (which builds the rope table and captures the +/// graphs); read it at table build time and when launching the analytic kernels. Plain storage, no +/// atomics: one writer on the startup thread, every reader after it. +void rope_scaling_set(const RopeScaling& scaling); +const RopeScaling& rope_scaling(); + +} // namespace strata::kernels diff --git a/include/strata/prefill/kernels.hpp b/include/strata/prefill/kernels.hpp index f4256945..3a4d1ca6 100644 --- a/include/strata/prefill/kernels.hpp +++ b/include/strata/prefill/kernels.hpp @@ -6,6 +6,7 @@ #pragma once #include "strata/kernels/kv_stream.hpp" +#include "strata/kernels/rope_scaling.hpp" #include @@ -65,8 +66,10 @@ void moe_combine(const float* D, const int32_t* slot, const float* w, const floa // ---- QSA helpers /// In place: x[r, :] = x[r, :] * rsqrt(mean x^2 + eps) * w over rows of `cols` (row stride `ld`). void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, float eps, void* stream); -/// NEOX rotary on the first 64 dims of each head: x [T, heads, dim] at positions pos0 + t. -void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, float freq_base, void* stream); +/// NEOX rotary on the first 64 dims of each head: x [T, heads, dim] at positions pos0 + t. The rope +/// scaling (rope_scaling.hpp) rides in as the process config - none is today's arithmetic exactly. +void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, + const strata::kernels::RopeScaling& scaling, void* stream); /// q_full [T, 24, 512] (q | gate per head) -> q [T, 24, 256] void split_q(const float* q_full, float* q, int64_t T, void* stream); /// attn[t, h, d] *= sigmoid(q_full[t, h, 256 + d]) -> out16 (fp16 bits: the o-projection is quantized) diff --git a/setup.py b/setup.py index daecede8..13813a32 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,10 @@ What the first run does (each step is skipped when it is already done): 6. prepares the model for Strata and fetches the MTP draft layer (~5 GB, from the original Qwen checkpoint) 7. writes run-.bat / run-.sh and starts the model -Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --vision yes|no|gpu|cpu, --port 8080, --yes (recommended +Options: --family qwen|swift, --model Q2_0|IQ2_XS|IQ3_XXS|IQ3_S, --context 32768, --rope-scaling none|linear|yarn +(--rope-scale F; past the trained 262144 the setup adds yarn and the factor is the final context over 262144, +at least 1 - an explicit --rope-scaling none is refused for such a context), --vision yes|no|gpu|cpu, --port +8080, --yes (recommended answers, no questions), --setup (install another model / change settings instead of starting), --no-start, --host 0.0.0.0 --api-key KEY (reach it from other devices on your network), --experimental-speed-projection on|off (EXPERIMENTAL, off by default), @@ -77,7 +80,12 @@ MODELS = { "IQ1_M": {"about": "the Coder's only size: half the experts, stored like IQ3_S (3.5 bits)", "download_gb": 58.4, "ram_gb": 32, "arena_gb": 23.4, "families": ("coder",)}, } -CONTEXTS = [8192, 32768, 65536, 131072, 262144] +# Contexts past 262144 (the model's trained length) extend it by rope scaling: for the context it will +# serve the setup resolves the method (yarn, or one question when interactive) and derives the factor +# from the final context (final / 262144, at least 1) itself (below), keeps an explicit +# --rope-scaling/--rope-scale, and refuses an explicit --rope-scaling none there - the stock angles past +# the trained range are out of spec. +CONTEXTS = [8192, 32768, 65536, 131072, 262144, 393216, 524288] # The model families: the same architecture, weights in the same three GSQ-RCO sizes, different files. FAMILIES = { "qwen": {"title": "Qwen3.8-Flash-Next", "by": "Qwen; GSQ-RCO quants by ISTA-DASLab", @@ -1587,12 +1595,56 @@ def write_run_script(model, cfg_path, port): return script +# ------------------------------------------------------------------------------------------------ the rope config +def derived_factor(ctx: int, trained: int = 262144) -> float: + """The automatic extension factor: the FINAL context over the trained one, at least 1. + + Factor 1 removes the automatic expansion - the trained angles stand as they are - but it is not a + switch for rope as a whole: an explicitly chosen method's settings keep their defined behavior. + """ + return max(1.0, float(ctx) / float(trained)) + + +def resolve_rope(ctx: int, scaling, scale, trained: int = 262144): + """The rope config for the context ACTUALLY SERVED: (scaling, scale); scaling None = no scaling flags. + + An explicit --rope-scaling/--rope-scale always wins - a user-supplied factor is kept verbatim even + when a reduction changed the context. Past the trained range an omitted method defaults to yarn - + llama.cpp's extension method: the trained angles survive on the high-frequency pairs and the + magnitude correction keeps the attention temperature - and an omitted factor is derived from the + final context (final / trained, at least 1), as is an explicitly chosen method's missing factor + inside the trained range: factor 1, the trained angles, no expansion. An explicit none is refused + past the trained range (the setup will not configure a run it knows is out of spec) rather than + silently overridden. + """ + if ctx <= trained: + if scale is not None and scaling in (None, "none"): + raise ValueError("--rope-scale needs --rope-scaling linear or yarn (the chosen context fits the " + "trained 262144, so there is nothing to scale)") + if scaling in (None, "none"): + return None, None # the stock model, by choice or by default + return scaling, scale if scale is not None else derived_factor(ctx, trained) + if scaling == "none": + raise ValueError(f"a {ctx // 1024}K context is past the model's trained 262144, and --rope-scaling none " + "keeps the stock angles there - the model has never seen those positions, so the setup " + "refuses the combination instead of quietly overriding it. Pick --rope-scaling yarn or " + "linear, or rerun with --context 262144 or lower") + return scaling or "yarn", scale if scale is not None else derived_factor(ctx, trained) + + # ------------------------------------------------------------------------------------------------ main def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--family", choices=list(FAMILIES), help="qwen = Qwen3.8-Flash-Next, swift = Swift 1.5") ap.add_argument("--model", choices=list(MODELS)) ap.add_argument("--context", type=int) + ap.add_argument("--rope-scaling", choices=["none", "linear", "yarn"], + help="the RoPE extension for a context past the model's trained 262144: linear (position " + "interpolation) or yarn - llama.cpp's types. Omitted with a scaled context, the setup " + "picks yarn; 'none' is refused for such a context") + ap.add_argument("--rope-scale", type=float, + help="the extension factor (default: the final context over the trained 262144, at least 1 - " + "1.5 for 384K, 2 for 512K, 1 inside the trained range)") ap.add_argument("--kv", choices=["int8", "q4_0", "k8v4"], help="KV cache precision above 8K context: int8 (default), q4_0 (half the memory, a little less " "precise) or k8v4 (hybrid: INT8 K + 4-bit V, 816 B/cell)") @@ -1856,17 +1908,43 @@ def main() -> int: say(" Context length = how much text the model can see at once (your chat, files, tool output).") say(" Longer needs more VRAM for it, so fewer experts fit on the GPU:") for i, c in enumerate(CONTEXTS, 1): - say(f" {i}) {c // 1024}K tokens" + (" (recommended for your GPU)" if c == rec_ctx else "")) - ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, 6)], str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] - # The experts' arena plus the context's KV (in RAM from 64K up: ~13.7 KB/token at 8 bits) must fit, with room - # for everything else. Counted, not a fixed 90 GB: 24 GB of room keeps the rule for 64 GB PCs as it was (128K - # for both 3-bit models), while a box with ~84 GB keeps the 262K it asked for (measured: a Colab A100-40G runs - # IQ3_S at 262K with images in 56 of its 83.5 GiB). + note = (" (recommended for your GPU)" if c == rec_ctx else "") + \ + (" (experimental: setup adds rope scaling)" if c > 262144 else "") + say(f" {i}) {c // 1024}K tokens{note}") + ctx = CONTEXTS[int(ask("Context?", [str(i) for i in range(1, len(CONTEXTS) + 1)], + str(CONTEXTS.index(rec_ctx) + 1), a.yes)) - 1] + # the RAM limit comes FIRST: the rope config must cover the context the engine will actually serve - + # a reduced 384K can land back inside the trained 262144, and then nothing needs scaling (§4). Counted, + # not a fixed 90 GB (the 0.1.29 arithmetic): arena + the context's KV + 24 GB of room for everything else. + asked_ctx = ctx need_gb = MODELS[model].get("arena_gb", 0) + ctx * 13 * 1056 / 1e9 + 24 if model in ("IQ3_XXS", "IQ3_S") and ram < need_gb and ctx > 131072: warn(f"{model} with a {ctx // 1024}K context needs about {need_gb:.0f} GB of RAM " f"({MODELS[model]['arena_gb']:.0f} GB of experts + the context + room for the rest): using 128K") ctx = 131072 + scaling = a.rope_scaling + if ctx > 262144 and scaling is None and not a.yes: + # the interactive path: one question, yarn preselected (llama.cpp's extension method, recall-tested + # here at 512K). With --yes nothing prints: resolve_rope takes yarn below and the ok() line says so. + say() + say(f" A {ctx // 1024}K context runs the model past its trained 262,144 positions: the rotary angles") + say(" get rescaled (llama.cpp's RoPE extension). yarn keeps the trained angles on the high-frequency") + say(" pairs and corrects the magnitudes; linear shrinks every angle. Override any time with") + say(" --rope-scaling.") + scaling = ask("RoPE extension method?", ["yarn", "linear"], "yarn", a.yes) + try: + scaling, rope_scale = resolve_rope(ctx, scaling, a.rope_scale) + except ValueError as e: + fail(str(e)) + if scaling is not None: + origin = ("final context / trained 262144; override with --rope-scale" if a.rope_scale is None + else "as requested") + ok(f"rope scaling: {scaling}, factor {rope_scale:g} ({origin})") + elif asked_ctx > 262144: + ok(f"the RAM limit brings the context to {ctx // 1024}K, inside the trained 262,144: no rope scaling") + if scaling is not None and asked_ctx > 262144 and ctx <= 262144: + warn(f"the RAM limit reduced the context to {ctx // 1024}K, inside the trained 262,144; keeping your " + f"explicit rope scaling ({scaling}) anyway - drop --rope-scaling for the completely stock model") ok(f"context: {ctx} tokens") # the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21) kv = "fp16" if ctx <= 8192 else (a.kv or "int8") @@ -2031,6 +2109,8 @@ def main() -> int: "--expert-profile", str(ROOT / "data" / fam.get("profile", "expert-profile.bin")), "--expert-cache", "auto", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", str(rt), "--max-context", str(ctx)] + if scaling is not None: # the resolved config: explicit flags as given, or the automatic yarn+factor + args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"] if ctx > 8192: args += ["--kv", kv] if low_ram: diff --git a/src/core/layer.cpp b/src/core/layer.cpp index 5c6c06ef..8ad9f41a 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -655,9 +655,10 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q // THE ROPE TABLE IS BUILT ON THE HOST IN FLOAT64 and uploaded once, because the reference computes its // frequencies in float64 and reproducing that on device means double-precision `pow`/`cos` that need not // agree with the host's libm. A table shorter than the sequence would have the rotation read past it. + // The process's rope scaling (none by default) is INSIDE the table - the rotation kernels cannot tell. if (share_rope == nullptr) { std::vector hc((size_t) max_cells * (s.n_rot / 2)), hs((size_t) max_cells * (s.n_rot / 2)); - strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::qsa_freq_base(), (int) max_cells, + strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::rope_scaling(), (int) max_cells, hc.data(), hs.data()); cudaMemcpy(st.cos_tab, hc.data(), hc.size() * 4, cudaMemcpyHostToDevice); cudaMemcpy(st.sin_tab, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice); @@ -843,7 +844,7 @@ const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, try { if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, RMS_EPS, stream); else rms_norm_weighted(data, (const float*) norm->data, rows, cols, RMS_EPS, stream); - if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, (float) qsa_freq_base(), st.pos_dev, stream); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), st.pos_dev, stream); else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, st.pos_dev, stream); return true; } catch (const std::exception& error) { @@ -905,7 +906,7 @@ if (st.kv_hybrid) { } else if (st.kv_int8) kv_append_q8_step(st.k_q, st.v_q, st.k_scale, st.v_scale, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); else kv_append_step(st.k_pool, st.v_pool, st.page_table, st.step, b.kcur, b.vcur, s, stream, &st.host); { const uint64_t nvk = (uint64_t) g.n_head_kv * g.head_dim; const uint64_t base = (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim + 2 * nvk + 8; if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.k_pool, base, nvk / 2, stream); if (!st.kv_int8 && !st.kv_hybrid) dump_slot(dump, g, layer, (const float*) st.v_pool, base + nvk / 2, nvk / 2, stream); dump_slot(dump, g, layer, b.vcur, base + nvk, nvk, stream); dump_slot(dump, g, layer, b.kcur, base + 2 * nvk, nvk, stream); } { const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; if (native_qsa_indexer_enabled()) { try { native_qsa_indexer_append(b.idx_raw, st.step + kStepPos, pos_base, - (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, (float) qsa_freq_base(), stream); + (const float*) w_ikn->data, RMS_EPS, ib, s, st.max_cells, rope_scaling(), stream); } catch (const std::exception& error) { err = v.name("native_indexer") + ": " + error.what(); return false; } } else indexer_key_append(b.idx_raw, st.pos_dev, pos_base, (const float*) w_ikn->data, RMS_EPS, ib, s, st.cos_tab, st.sin_tab, stream); } diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index e73b58b1..e063b4f6 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -395,7 +395,7 @@ bool MtpDrafter::record_forward(int T, int step_row0, cudaStream_t cs, std::stri // ---- attention: K/V into the layer's own cache, then (full) dense attention over every cell auto norm_rope = [&](float* data, const float* gamma, int rows, int cols, const int32_t* p) { native_qsa_rms_norm_weighted(data, gamma, data, cols, rows, EPS, cs); - if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, (float) qsa_freq_base(), p, cs); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), p, cs); else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st_.cos_tab, st_.sin_tab, p, cs); }; native_quantize_q8_1(mixed_, xq_, (int) N, T, cs); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 223d1753..cea630ec 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -492,7 +492,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) { if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, cs); else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, cs); - if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, (float) qsa_freq_base(), pos, cs); + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, cs); else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, cs); }; float* idx_raw = idx_raw_L_ + (size_t) qi * MT * ID; @@ -537,7 +537,7 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { for (int t = tb; t < te; ++t) native_qsa_indexer_append(idx_raw + t * ID, step_ + t * kStepCount + kStepPos, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, - (float) qsa_freq_base(), cs); + rope_scaling(), cs); stamp(l, 9, grp); native_mmvq(wq->native_type, wq->native_data, xq_, qfull_ + tb * NH * 2 * HD, (int) N, (int) (NH * 2 * HD), n, cs); @@ -923,7 +923,7 @@ bool Verifier::capture_commit(std::string& err) { for (int64_t t = 0; t < MT; ++t) native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commit_ + 2 + t, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, - (float) qsa_freq_base(), cs_); + rope_scaling(), cs_); ++qsa_index; } } diff --git a/src/kernels/cuda/native_qsa_indexer.cu b/src/kernels/cuda/native_qsa_indexer.cu index 8a5ecbc3..299199a9 100644 --- a/src/kernels/cuda/native_qsa_indexer.cu +++ b/src/kernels/cuda/native_qsa_indexer.cu @@ -43,7 +43,9 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ int pos_base, const float* __restrict__ gamma, float epsilon, float* __restrict__ tail, float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, - int max_cells, float theta_scale, const int32_t* __restrict__ mtab) { + int max_cells, float theta_scale, float freq_scale, float corr_low, + float corr_high, float ext_factor, float mscale, + const int32_t* __restrict__ mtab) { const int pos = *pos_dev, d = threadIdx.x; if (pos < 0 || pos >= max_cells) return; const int slot = pos % R; @@ -83,8 +85,11 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ float y = values[d]; if (d < ROT) { const int pair = d % (ROT / 2); - const float theta = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); - const float c = cosf(theta), s = sinf(theta); + // The spare (pos == 0) keeps its zero angle; under YaRN the mscale magnitude still rides in + // through cos(0) - which is exactly what the queries are scaled by, so the top-k is unmoved. + const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + float c, s; + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); const float a = values[pair], z = values[pair + ROT / 2]; y = d < ROT / 2 ? a * c - z * s : a * s + z * c; } @@ -99,12 +104,17 @@ __global__ void append(const float* __restrict__ raw, const int32_t* __restrict_ // (cell >= p0) or the tail the previous batch left (cell < p0). Only the batch's last completed block writes the // spare after it (every earlier one's is overwritten by the next block in order). __device__ __forceinline__ float pooled_value(const float* values, int d, int rope_pos, float theta_scale, - const int32_t* mtab, bool zero_pos) { + float freq_scale, float corr_low, float corr_high, + float ext_factor, float mscale, const int32_t* mtab, bool zero_pos) { float y = values[d]; if (d < ROT) { const int pair = d % (ROT / 2); - const float theta = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); - const float c = cosf(theta), s = sinf(theta); + // The same rotation the single append applies, rope_scaling.hpp's helper shared: under none this is + // today's cosf/sinf; under linear/YaRN the pooled keys move with the cache's K, and the spare's zero + // angle carries the mscale magnitude through cos(0) exactly as the single append's does. + const float theta_extrap = (zero_pos ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(theta_scale, float(pair)); + float c, s; + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); const float a = values[pair], z = values[pair + ROT / 2]; y = d < ROT / 2 ? a * c - z * s : a * s + z * c; } @@ -123,6 +133,7 @@ __device__ __forceinline__ float norm_scale(float mean, float* partials, int d) // cell 0 of a sequence: the spare (every gather index names cell 0), written to pooled[0] and dead __global__ void append_first(const float* __restrict__ raw, const float* __restrict__ gamma, float epsilon, float* __restrict__ dead, float* __restrict__ pooled, float theta_scale, + float freq_scale, float corr_low, float corr_high, float ext_factor, float mscale, const int32_t* __restrict__ mtab) { const int d = threadIdx.x; __shared__ float values[D]; @@ -140,14 +151,17 @@ __global__ void append_first(const float* __restrict__ raw, const float* __restr if (d < D) values[d] = scale * mean * gamma[d]; __syncthreads(); if (d >= D) return; - const float y = pooled_value(values, d, 0, theta_scale, mtab, true); + const float y = pooled_value(values, d, 0, theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale, + mtab, true); pooled[d] = y; dead[d] = y; } __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t p0, int pos_base, const float* __restrict__ gamma, float epsilon, const float* __restrict__ tail, const float* __restrict__ dead, float* __restrict__ pooled, int32_t* __restrict__ block_pos, - int64_t first_block, int64_t last_block, float theta_scale, const int32_t* __restrict__ mtab) { + int64_t first_block, int64_t last_block, float theta_scale, float freq_scale, + float corr_low, float corr_high, float ext_factor, float mscale, + const int32_t* __restrict__ mtab) { const int64_t b = first_block + blockIdx.x; const int d = threadIdx.x; __shared__ float values[D]; @@ -169,7 +183,8 @@ __global__ void append_blocks(const float* __restrict__ raw, int64_t n, int64_t __syncthreads(); if (d >= D) return; const int rope_pos = pos_base + R * (int) b; - pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, mtab, false); + pooled[std::size_t(b) * D + d] = pooled_value(values, d, rope_pos, theta_scale, freq_scale, corr_low, corr_high, + ext_factor, mscale, mtab, false); if (b == last_block) { pooled[std::size_t(b + 1) * D + d] = dead[d]; if (d == 0) *block_pos = rope_pos; @@ -200,42 +215,47 @@ void native_qsa_indexer_set_enabled(bool value) { enabled.store(value, std::memo bool native_qsa_indexer_enabled() { return enabled.load(std::memory_order_relaxed); } void native_qsa_indexer_append(const float* raw, const int32_t* relative_pos_device, int32_t pos_base, const float* gamma, float epsilon, const QsaIndexerBuffers& b, - const QsaShapes& s, int64_t max_cells, float freq_base, void* stream) { + const QsaShapes& s, int64_t max_cells, const RopeScaling& scaling, void* stream) { if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || max_cells < 1 || max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX || !std::isfinite(epsilon) || epsilon <= 0.0f || - !std::isfinite(freq_base) || freq_base <= 1.0f) - throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency and explicit stream"); + rope_scaling_invalid(scaling) != nullptr) + throw std::invalid_argument("native QSA indexer requires fixed geometry, aligned position base, positive capacity/epsilon, valid frequency/scaling and explicit stream"); const Span spans[] = {{raw,D*4},{relative_pos_device,4},{gamma,D*4},{b.tail,(R-1)*D*4}, {b.dead,D*4},{b.pooled,std::size_t(max_cells/R+1)*D*4},{b.block_pos,4}}; for (const auto& span : spans) validate(span); for (int i = 0; i < 7; ++i) for (int j = i + 1; j < 7; ++j) if (overlaps(spans[i], spans[j])) throw std::invalid_argument("native QSA indexer buffers overlap"); - const float theta_scale = powf(freq_base, -2.0f / ROT); + const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); + const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants append<<<1,THREADS,0,static_cast(stream)>>>(raw,relative_pos_device,pos_base,gamma,epsilon, - b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,mrope_table()); + b.tail,b.dead,b.pooled,b.block_pos,int(max_cells),theta_scale,k.freq_scale, + k.corr_low,k.corr_high,k.ext_factor,k.attn_factor,mrope_table()); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } void native_qsa_indexer_append_batch(const float* raw, int64_t n, int64_t p0, int32_t pos_base, const float* gamma, float epsilon, const QsaIndexerBuffers& b, const QsaShapes& s, int64_t max_cells, - float freq_base, void* stream) { + const RopeScaling& scaling, void* stream) { if (n <= 0) return; if (!stream || s.idx_dim != D || s.idx_block != R || s.n_rot != ROT || p0 < 0 || p0 + n > max_cells || max_cells > INT32_MAX || pos_base < 0 || pos_base % R || int64_t(pos_base) + max_cells > INT32_MAX || - !std::isfinite(epsilon) || epsilon <= 0.0f || !std::isfinite(freq_base) || freq_base <= 1.0f) - throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions or parameters"); - const float theta_scale = powf(freq_base, -2.0f / ROT); + !std::isfinite(epsilon) || epsilon <= 0.0f || rope_scaling_invalid(scaling) != nullptr) + throw std::invalid_argument("native QSA indexer (batch): bad geometry, positions, parameters or scaling"); + const float theta_scale = powf((float) scaling.freq_base, -2.0f / ROT); + const RopeKernelArgs k = scaling.kernel_args(ROT); // none: the identity constants + const float fsf = k.freq_scale, cl = k.corr_low, ch = k.corr_high, ef = k.ext_factor, ms = k.attn_factor; const cudaStream_t st = static_cast(stream); const int32_t* mtab = mrope_table(); - if (p0 == 0) append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, mtab); + if (p0 == 0) append_first<<<1, THREADS, 0, st>>>(raw, gamma, epsilon, b.dead, b.pooled, theta_scale, + fsf, cl, ch, ef, ms, mtab); // completed blocks: those whose last cell (4b+3) lies in [p0, p0 + n) const int64_t first = p0 <= R - 1 ? 0 : (p0 - (R - 1) + R - 1) / R; // the smallest b with 4b+3 >= p0 const int64_t hi = p0 + n - 1 >= R - 1 ? (p0 + n - 1 - (R - 1)) / R : -1; // the largest b with 4b+3 <= p0+n-1 if (hi >= first) append_blocks<<<(unsigned) (hi - first + 1), THREADS, 0, st>>>(raw, n, p0, pos_base, gamma, epsilon, b.tail, b.dead, b.pooled, b.block_pos, first, hi, - theta_scale, mtab); + theta_scale, fsf, cl, ch, ef, ms, mtab); append_tail<<>>(raw, n, p0, b.tail); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); diff --git a/src/kernels/cuda/native_rope.cu b/src/kernels/cuda/native_rope.cu index 6dd3f6b5..46311720 100644 --- a/src/kernels/cuda/native_rope.cu +++ b/src/kernels/cuda/native_rope.cu @@ -39,7 +39,8 @@ bool overlaps(const void* a, size_t an, const void* b, size_t bn) { return x <= y ? y - x < an : x - y < bn; } __global__ void apply(const float* x, float* out, int rows, int width, - int n_rot, float theta_scale, const int* positions, const int32_t* mtab) { + int n_rot, float theta_scale, float freq_scale, float corr_low, float corr_high, + float ext_factor, float mscale, const int* positions, const int32_t* mtab) { const int row = blockIdx.y; const int pair = blockIdx.x * blockDim.x + threadIdx.x; if (row >= rows || pair >= width / 2) return; @@ -51,8 +52,9 @@ __global__ void apply(const float* x, float* out, int rows, int width, } return; } - const float theta = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); - const float c = cosf(theta), s = sinf(theta); + const float theta_extrap = mrope_pos(mtab, positions[row], pair) * powf(theta_scale, float(pair)); + float c, s; + rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, pair, c, s); const float a = x[start + pair], b = x[start + pair + n_rot / 2]; out[start + pair] = a * c - b * s; out[start + pair + n_rot / 2] = a * s + b * c; @@ -73,13 +75,13 @@ const int32_t* mrope_table() { return mrope_tab[mrope_dev()].load(std::memory_or void native_rope_set_enabled(bool value) { enabled.store(value, std::memory_order_relaxed); } bool native_rope_enabled() { return enabled.load(std::memory_order_relaxed); } void native_rope_apply(const float* x, float* out, int rows, int head_dim, - int n_rot, float freq_base, const int* positions, void* stream) { + int n_rot, const RopeScaling& scaling, const int* positions, void* stream) { if (!x || !out || !positions || !stream || rows < 1 || rows > 65535 || (head_dim != 128 && head_dim != 256) || n_rot != 64 || - !std::isfinite(freq_base) || freq_base <= 1.0f || + rope_scaling_invalid(scaling) != nullptr || reinterpret_cast(x) % 4 || reinterpret_cast(out) % 4 || reinterpret_cast(positions) % 4) { - throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base and explicit stream"); + throw std::invalid_argument("native RoPE requires aligned F32 rows, width 128/256, rotation 64, valid base/scaling and explicit stream"); } const size_t bytes = size_t(rows) * head_dim * sizeof(float); if ((x != out && overlaps(x, bytes, out, bytes)) || @@ -88,9 +90,12 @@ void native_rope_apply(const float* x, float* out, int rows, int head_dim, throw std::invalid_argument("native RoPE buffers partially overlap"); } // Match pinned host-side float powf before device fast powf/trigonometry. - const float theta_scale = powf(freq_base, -2.0f / n_rot); + const float theta_scale = powf((float) scaling.freq_base, -2.0f / n_rot); + const RopeKernelArgs k = scaling.kernel_args(n_rot); // none: the identity constants apply<<(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, positions, mrope_table()); + static_cast(stream)>>>(x, out, rows, head_dim, n_rot, theta_scale, + k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, + k.attn_factor, positions, mrope_table()); const auto error = cudaGetLastError(); if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); } diff --git a/src/kernels/cuda/qsa.cu b/src/kernels/cuda/qsa.cu index f783164e..d1338969 100644 --- a/src/kernels/cuda/qsa.cu +++ b/src/kernels/cuda/qsa.cu @@ -184,10 +184,18 @@ __global__ void indexer_key_append_kernel(const float* __restrict__ raw, const i ss = __dadd_rn(ss, __dmul_rn(v, v)); } const double inv = __ddiv_rn(1.0, __dsqrt_rn(ss / (double) idx_dim + (double) eps)); - dead[d] = (float) (p * inv * (double) w_k_norm[d]); - // rope at position 0 is the identity here (cos = 1, sin = 0 exactly), so no rotation is applied and - // the parity test asserts the value is bit-exact - which is what makes skipping it legitimate. - pooled[d] = dead[d]; + float y = (float) (p * inv * (double) w_k_norm[d]); + // The spare rotates at position 0 - ALWAYS row 0 of the table, whatever `pos_base` is, as the native + // indexer's spare does. At angle 0 the sine is exactly 0 in every scaling (sin(0) * mscale), so the + // pair rotation reduces to `v * cos_tab[pair]` with no partner element to read (and no barrier). + // Unscaled, row 0 is exactly (1, 0) and `v * 1.0f` is `v` bit for bit - today's value, which the + // parity test holds bit-exact. Under YaRN row 0 is (mscale, 0): the rotated dims carry the magnitude + // correction exactly like every other pooled row and like the native kernel's spare (the unrotated + // dims pass through, as in the rotation of the completed blocks below). Skipping the rotation here, + // as this kernel once did, left `dead` and `pooled[0]` the only unscaled keys of a scaled cache. + if (d < n_rot) y *= cos_tab[d % (n_rot / 2)]; + dead[d] = y; + pooled[d] = y; } if (slot != r - 1) return; diff --git a/src/kernels/cuda/rope.cu b/src/kernels/cuda/rope.cu index 2bb1735a..807545eb 100644 --- a/src/kernels/cuda/rope.cu +++ b/src/kernels/cuda/rope.cu @@ -20,6 +20,11 @@ // Building the table once on the host and passing it in makes the TABLE exactly the reference's values and // leaves the kernel a pure rotation, so each half can be checked tightly instead of both halves sharing one // loose tolerance. The engine wants a cached table anyway: it is per (n_rot, theta, position), not per token. +// +// THE SCALED TABLE IS THE SAME IDEA WITH MORE MATH IN THE HOST LOOP. Linear rescales the angle by +// `freq_scale`; YaRN blends extrapolation and interpolation along the pairs (ggml's `rope_yarn`) and folds +// the mscale magnitude correction into the same cos/sin values. All of it float64, in the reference's +// order, so `rope_parity` can hold every variant to a bit-exact float64 transcription of the same spec. #include "strata/kernels/rope.hpp" #include "strata/kernels/mrope.hpp" @@ -31,6 +36,15 @@ namespace strata::kernels { +namespace { +// The process's rope config (rope_scaling.hpp). One writer - the engine's startup thread, before +// session_init builds any table or captures any graph - and readers after it. +RopeScaling g_rope_scaling; +} // namespace + +void rope_scaling_set(const RopeScaling& scaling) { g_rope_scaling = scaling; } +const RopeScaling& rope_scaling() { return g_rope_scaling; } + void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab) { const int half = n_rot / 2; for (int p = 0; p < max_pos; ++p) { @@ -44,6 +58,33 @@ void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, floa } } +void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab) { + if (sc.type == RopeScalingType::None) { + build_rope_table(n_rot, sc.freq_base, max_pos, cos_tab, sin_tab); // the original loop, verbatim + return; + } + const int half = n_rot / 2; + const double fs = sc.freq_scale(); + const double ms = sc.mscale(); + double cd[2]; + sc.corr_dims(n_rot, cd); + const bool correct = sc.ext_factor != 0; // ggml: the correction rides on ext_factor, not the type + for (int p = 0; p < max_pos; ++p) { + for (int i = 0; i < half; ++i) { + const double inv = std::pow(sc.freq_base, -2.0 * (double) i / (double) n_rot); + const double extrap = (double) p * inv; // the trained angle, ggml's theta_extrap + const double interp = fs * extrap; // ggml's theta_interp + double ang = interp; + if (correct) { + const double ramp = (double) rope_yarn_ramp((float) cd[0], (float) cd[1], i) * sc.ext_factor; + ang = interp * (1.0 - ramp) + extrap * ramp; + } + cos_tab[(size_t) p * half + i] = (float) (std::cos(ang) * ms); + sin_tab[(size_t) p * half + i] = (float) (std::sin(ang) * ms); + } + } +} + namespace { // ONE THREAD PER ROW, not per (row, pair). The first version had one thread per pair and did the tail copy diff --git a/src/kernels/qsa_parity.cpp b/src/kernels/qsa_parity.cpp index 5a8186dd..55dec2d3 100644 --- a/src/kernels/qsa_parity.cpp +++ b/src/kernels/qsa_parity.cpp @@ -47,6 +47,7 @@ // 1e-3 for FP16 paths. That difference is the FP16 CACHE's cost, not the kernel's, and it is kept // separate so a kernel bug cannot hide inside it. #include "strata/kernels/qsa.hpp" +#include "strata/kernels/native_qsa_indexer.hpp" #include "strata/kernels/f16_bits.hpp" #include "strata/kernels/rope.hpp" @@ -1376,6 +1377,177 @@ int main(int argc, char** argv) { check(cudaGraphDestroy(g2), "gd"); } + // ================= the NATIVE indexer's batched append vs the sequential one ================= + // The prefill path appends a chunk in one native_qsa_indexer_append_batch call, the decode path appends + // token by token - and one cache must never be able to tell which path filled it (rope_scaling.hpp's + // one-rotation rule). So the batch's whole end state must be BIT-IDENTICAL to the sequential appends', + // under all three scaling configs: none (today's rotation), linear 2 (pure angle shrink, no correction) + // and yarn 2 (corr-dims ramp and the mscale magnitude) - both kernels must take the same RopeScaling. + // "Bit-identical" is asserted on the bit representations (memcmp of the state words): float != would + // pass a NaN-payload or -0.0 flip that the claim does not cover. Eight cells: exactly two completed + // blocks, so the paths' end states agree on block_pos too (a mid-block chunk end leaves the sequential + // path pointing at the open block's base and the batch at the last completed one's - upstream C-2's own + // semantics, the same for every scaling; see native_qsa_indexer.hpp's block_pos contract). + { + std::printf("\n-- the native indexer's batched append vs the sequential one\n"); + const int64_t NB = 8; // exactly two complete blocks of r=4 + const int32_t BASE = 100; // positions 100..107, not cell indices 0..7 + const int64_t MC = 1024; // the capacity both sides validate against + using RST = strata::kernels::RopeScalingType; + struct Variant { const char* name; RST type; double factor; double ext; }; + const Variant variants[] = {{"none", RST::None, 1.0, 0.0}, + {"linear 2", RST::Linear, 2.0, 0.0}, + {"yarn 2", RST::YaRN, 2.0, 1.0}}; + std::vector raws((size_t) NB * IDXD); + for (int64_t t = 0; t < NB; ++t) + for (int64_t d = 0; d < IDXD; ++d) + raws[(size_t) t * IDXD + d] = (float) (gauss(rng) * std::pow(4.0, (double) (t % 4))); + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "cs"); + std::vector none_pooled; + for (const Variant& var : variants) { + strata::kernels::RopeScaling sc; + sc.type = var.type; + sc.factor = var.factor; + sc.ext_factor = var.ext; + const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD; + Dev pooledA(prows), deadA(IDXD), tailA(trows), pooledB(prows), deadB(IDXD), tailB(trows); + Dev bposA(1), bposB(1), dpos(1); + for (Dev* dp : {&pooledA, &deadA, &tailA, &pooledB, &deadB, &tailB}) + check(cudaMemset(dp->p, 0, dp == &pooledA || dp == &pooledB ? prows * 4 + : dp == &deadA || dp == &deadB ? IDXD * 4 : trows * 4), "zero"); + check(cudaMemset(bposA.p, 0, 4), "zero"); check(cudaMemset(bposB.p, 0, 4), "zero"); + Dev draw((size_t) IDXD), drawAll; + drawAll.put(raws); + strata::kernels::QsaIndexerBuffers bufsA{tailA.p, deadA.p, pooledA.p, bposA.p}; + strata::kernels::QsaIndexerBuffers bufsB{tailB.p, deadB.p, pooledB.p, bposB.p}; + for (int64_t t = 0; t < NB; ++t) { // the sequential side: one cell, its device position + check(cudaMemcpy(draw.p, &raws[(size_t) t * IDXD], (size_t) IDXD * 4, cudaMemcpyHostToDevice), "raw"); + const int32_t tp = (int32_t) t; + check(cudaMemcpy(dpos.p, &tp, 4, cudaMemcpyHostToDevice), "pos"); + strata::kernels::native_qsa_indexer_append(draw.p, dpos.p, BASE, dw_kn.p, EPS, bufsA, S, MC, sc, cs); + } + strata::kernels::native_qsa_indexer_append_batch(drawAll.p, NB, 0, BASE, dw_kn.p, EPS, bufsB, S, MC, sc, cs); + check(cudaStreamSynchronize(cs), "sync"); + const std::vector pa = pooledA.get(prows), pb = pooledB.get(prows); + const std::vector da = deadA.get((size_t) IDXD), db = deadB.get((size_t) IDXD); + const std::vector ta = tailA.get(trows), tbb = tailB.get(trows); + const std::vector ba = bposA.get(1), bb = bposB.get(1); + long long bad = 0; + for (size_t i = 0; i < pa.size(); ++i) bad += std::memcmp(&pa[i], &pb[i], 4) != 0; + for (size_t i = 0; i < da.size(); ++i) bad += std::memcmp(&da[i], &db[i], 4) != 0; + for (size_t i = 0; i < ta.size(); ++i) bad += std::memcmp(&ta[i], &tbb[i], 4) != 0; + bad += std::memcmp(&ba[0], &bb[0], 4) != 0; + std::printf(" %-44s %s (%lld of %zu state words differ)\n", + (std::string("batch vs sequential, ") + var.name).c_str(), + bad ? "*** WRONG ***" : "bit-identical", bad, pa.size() + da.size() + ta.size() + 1); + if (bad) ++g_bad; + if (var.type == RST::None) none_pooled = pa; + else { + int moved = 0; + for (size_t i = 0; i < pa.size(); ++i) moved += std::memcmp(&pa[i], &none_pooled[i], 4) != 0; + std::printf(" %-44s %d of %zu pooled words differ from the none baseline\n", + (std::string("the scaling is visible, ") + var.name).c_str(), moved, pa.size()); + if (!moved) { std::printf(" *** the batched append ignored its scaling ***\n"); ++g_bad; } + } + } + check(cudaStreamDestroy(cs), "csd"); + } + + // ================= the spare (position 0) under rope scaling: the table indexer vs the native one ========= + // The spare key (`dead`, and `pooled[0]` until the first block completes) rotates at angle 0. Its sine is + // 0 in every scaling, so the rotation is `v * cos_tab[0][pair]`: exactly `v` unscaled (row 0 is (1, 0), the + // bit-exact value section 2 asserts), `v * mscale` under YaRN - the magnitude every other pooled row and + // the native kernel's spare carry. The table kernel used to skip the rotation at position 0, which left + // the spare the one unscaled key of a scaled cache. Asserted per variant: the table spare is BIT-EXACTLY + // the unscaled spare times row 0 on the rotated dims and the unscaled spare past them; `pooled[0]` equals + // `dead`; the native spare carries the same factor (to f32 rounding: its mscale is formed in float); and + // under YaRN the factor is observable (row 0 is not 1). + { + std::printf("\n-- the spare key (position 0) under rope scaling: table indexer vs native indexer\n"); + using RST = strata::kernels::RopeScalingType; + struct Variant { const char* name; RST type; double factor; double ext; }; + const Variant variants[] = {{"none", RST::None, 1.0, 0.0}, + {"linear 2", RST::Linear, 2.0, 0.0}, + {"yarn 2", RST::YaRN, 2.0, 1.0}}; + const int64_t MC = 64, HALF = S.n_rot / 2, NROT = S.n_rot; + std::vector raw0((size_t) IDXD); + for (int64_t d = 0; d < IDXD; ++d) raw0[(size_t) d] = rnd(3.0); + Dev draw0; + draw0.put(raw0); + Dev dpos0(1); + const int32_t zero = 0; + check(cudaMemcpy(dpos0.p, &zero, 4, cudaMemcpyHostToDevice), "pos0"); + cudaStream_t cs = nullptr; + check(cudaStreamCreate(&cs), "cs"); + const size_t prows = (size_t) (MC / R + 1) * IDXD, trows = (size_t) (R - 1) * IDXD; + // one cell at position 0 through either kernel; returns (dead, pooled[0]) + auto spare = [&](bool native, const strata::kernels::RopeScaling& sc, std::vector& dead, + std::vector& pooled0) { + Dev pooled(prows), dd((size_t) IDXD), tail(trows); + Dev bpos(1); + check(cudaMemset(pooled.p, 0, prows * 4), "zero"); + check(cudaMemset(dd.p, 0, (size_t) IDXD * 4), "zero"); + check(cudaMemset(tail.p, 0, trows * 4), "zero"); + check(cudaMemset(bpos.p, 0, 4), "zero"); + strata::kernels::QsaIndexerBuffers bufs{tail.p, dd.p, pooled.p, bpos.p}; + if (native) { + strata::kernels::native_qsa_indexer_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, MC, sc, cs); + } else { + std::vector tc((size_t) (MC * HALF)), ts(tc.size()); + strata::kernels::build_rope_table((int) NROT, sc, (int) MC, tc.data(), ts.data()); + Dev dc, dsn; + dc.put(tc); + dsn.put(ts); + strata::kernels::indexer_key_append(draw0.p, dpos0.p, 0, dw_kn.p, EPS, bufs, S, dc.p, dsn.p, cs); + } + check(cudaStreamSynchronize(cs), "sync"); + dead = dd.get((size_t) IDXD); + pooled0 = pooled.get((size_t) IDXD); + }; + std::vector t_none, t_none_p, n_none, n_none_p; + for (const Variant& var : variants) { + strata::kernels::RopeScaling sc; + sc.type = var.type; + sc.factor = var.factor; + sc.ext_factor = var.ext; + std::vector row0c((size_t) (MC * HALF)), row0s(row0c.size()); + strata::kernels::build_rope_table((int) NROT, sc, (int) MC, row0c.data(), row0s.data()); + std::vector td, tp, nd, np; + spare(false, sc, td, tp); + spare(true, sc, nd, np); + if (var.type == RST::None) { t_none = td; t_none_p = tp; n_none = nd; n_none_p = np; } + long long tbad = 0, pbad = 0, sin_bad = 0; + double nworst = 0; + for (int64_t i = 0; i < HALF; ++i) sin_bad += row0s[(size_t) i] != 0.0f; + for (int64_t d = 0; d < IDXD; ++d) { + const float c0 = d < NROT ? row0c[(size_t) (d % HALF)] : 1.0f; + const float want = d < NROT ? t_none[(size_t) d] * c0 : t_none[(size_t) d]; + tbad += std::memcmp(&td[(size_t) d], &want, 4) != 0; + pbad += std::memcmp(&tp[(size_t) d], &td[(size_t) d], 4) != 0; + const double nwant = (double) n_none[(size_t) d] * (double) c0; + const double den = std::max(std::fabs(nwant), 1e-6); + nworst = std::max(nworst, std::fabs((double) nd[(size_t) d] - nwant) / den); + } + require(std::string(" ") + var.name + ": row 0 of the table is (c, 0)", sin_bad == 0, + std::to_string(sin_bad) + " nonzero sines"); + require(std::string(" ") + var.name + ": the table spare is the unscaled spare times row 0, BIT-EXACT", + tbad == 0, std::to_string(tbad) + " of " + std::to_string(IDXD) + " wrong"); + require(std::string(" ") + var.name + ": the table's pooled[0] is its spare", pbad == 0, + std::to_string(pbad) + " wrong"); + require(std::string(" ") + var.name + ": the native spare carries the same row-0 factor", nworst <= 4e-7, + "worst relative " + std::to_string(nworst)); + if (var.type == RST::YaRN) { + int moved = 0; + for (int64_t d = 0; d < NROT; ++d) moved += std::memcmp(&td[(size_t) d], &t_none[(size_t) d], 4) != 0; + require(" yarn 2: the magnitude correction is observable on the table spare", + row0c[0] != 1.0f && moved > NROT / 2, + "row0 cos " + std::to_string(row0c[0]) + ", " + std::to_string(moved) + " dims moved"); + } + } + check(cudaStreamDestroy(cs), "csd"); + } + std::printf("\nqsa: %d failures\n", g_bad); if (g_bad) return 1; if (selftest) std::printf("qsa_parity OK\n"); diff --git a/src/kernels/rope_parity.cpp b/src/kernels/rope_parity.cpp index 8460b487..39ba116a 100644 --- a/src/kernels/rope_parity.cpp +++ b/src/kernels/rope_parity.cpp @@ -12,7 +12,20 @@ // A single end-to-end comparison would have had to carry one loose tolerance for both, and the interesting // failure - the NEOX pairing being wrong - is a PERMUTATION that a loose tolerance over all 256 dims would // happily accept. +// +// Check 4 extends the same discipline to the SCALED tables (rope scaling: none/linear/YaRN). The rotation +// kernel cannot see scaling - it lives in the table contents - so each variant's TABLE is held to a float64 +// transcription of ggml's `rope_yarn` spec (the ramp helper is shared, the `rope_neox_pair` convention), and +// the two properties a tolerance could never fake get their own structural checks: at position 0 every pair's +// angle is 0, so YaRN's mscale stands naked in cos_tab[0], and at a far position the first pair must match +// EXTRAPOLATION while the last matches INTERPOLATION. An observability assertion closes it: if the scaled +// and unscaled tables were indistinguishable, every green number above would be vacuous. +// +// Check 5 holds the TWO PATHS together: the table path's float64 host trig and the native path's float32 +// fast-math device trig must answer to the same `RopeScaling`, yarn and none alike, so one cache never +// mixes two rotations. #include "strata/kernels/rope.hpp" +#include "strata/kernels/native_rope.hpp" #include @@ -164,6 +177,264 @@ int main(int argc, char** argv) { if (!(neox_moved && !adjacent_moved)) ++bad; } + // ---- 4. THE SCALED TABLES (rope_scaling.hpp). Scaling lives in the table contents, so each variant is + // a table check: a float64 transcription of the ggml spec, bit-exact after the float32 cast, plus the + // structural and observability checks the tolerances cannot cover. + { + // 4a. type None IS the five-argument builder above - bit for bit. + std::vector nc((size_t) max_pos * half), ns((size_t) max_pos * half); + strata::kernels::RopeScaling none; + none.freq_base = theta; + strata::kernels::build_rope_table(n_rot, none, max_pos, nc.data(), ns.data()); + const long long none_bad = + (long long) (std::memcmp(nc.data(), hcos.data(), nc.size() * 4) != 0) + + (long long) (std::memcmp(ns.data(), hsin.data(), ns.size() * 4) != 0); + std::printf(" scaled table, None vs unscaled builder %s\n", none_bad ? "*** WRONG ***" : "bit-identical"); + bad += (int) none_bad; + + // 4b. LINEAR, factor 4: `ang = p * inv / 4` in float64. The factor is a power of two on purpose - + // dividing by it is exact, so no multiplication-order rounding can sneak between spec and builder. + strata::kernels::RopeScaling lin; + lin.type = strata::kernels::RopeScalingType::Linear; + lin.freq_base = theta; + lin.factor = 4.0; + std::vector lc((size_t) max_pos * half), ls((size_t) max_pos * half); + strata::kernels::build_rope_table(n_rot, lin, max_pos, lc.data(), ls.data()); + long long lin_bad = 0; + for (int p = 0; p < max_pos; ++p) { + for (int i = 0; i < half; ++i) { + const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); + const double ang = (double) p * inv / 4.0; + const float rc = (float) std::cos(ang), rs = (float) std::sin(ang); + if (std::memcmp(&rc, &lc[(size_t) p * half + i], 4) != 0) ++lin_bad; + if (std::memcmp(&rs, &ls[(size_t) p * half + i], 4) != 0) ++lin_bad; + } + } + std::printf(" scaled table, linear factor 4 %s (%lld of %d entries differ)\n", + lin_bad ? "*** WRONG ***" : "bit-exact", lin_bad, max_pos * half * 2); + bad += (int) lin_bad; + + // 4c. THE INTERPOLATION CLAIM ITSELF: linear(4) at position p is `none` at p/4 - the same table row, + // bit for bit, at every position divisible by the factor. + std::vector wc((size_t) 4 * max_pos * half), ws((size_t) 4 * max_pos * half); + strata::kernels::build_rope_table(n_rot, lin, 4 * max_pos, wc.data(), ws.data()); + long long equiv_bad = 0; + for (int p = 0; p < 4 * max_pos; p += 4) { + for (int i = 0; i < half; ++i) { + if (std::memcmp(&wc[(size_t) p * half + i], &hcos[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad; + if (std::memcmp(&ws[(size_t) p * half + i], &hsin[(size_t) (p / 4) * half + i], 4) != 0) ++equiv_bad; + } + } + std::printf(" linear(4) @ p == none @ p/4 %s (%lld of %d rows differ)\n", + equiv_bad ? "*** WRONG ***" : "bit-identical", equiv_bad, max_pos); + bad += (int) equiv_bad; + + // 4d. YARN vs a float64 transcription of ggml's rope_yarn (factor 4, the default correction knobs). + // The ramp helper is shared with the builder (the rope_neox_pair convention: one definition, not two + // transcriptions of it); the interpolation mix and the mscale formula are written here from the ggml + // source lines, which is the spec being tested. + strata::kernels::RopeScaling yarn; + yarn.type = strata::kernels::RopeScalingType::YaRN; + yarn.freq_base = theta; + yarn.factor = 4.0; + yarn.ext_factor = 1.0; + std::vector yc((size_t) max_pos * half), ys((size_t) max_pos * half); + strata::kernels::build_rope_table(n_rot, yarn, max_pos, yc.data(), ys.data()); + const double fs = yarn.freq_scale(); // 0.25 + const double ms = yarn.mscale(); // attn_factor * (1 + 0.1*ln(4)) + double cd[2]; + yarn.corr_dims(n_rot, cd); + long long yarn_bad = 0; + for (int p = 0; p < max_pos; ++p) { + for (int i = 0; i < half; ++i) { + const double inv = std::pow(theta, -2.0 * (double) i / (double) n_rot); + const double extrap = (double) p * inv; + const double interp = fs * extrap; + const double ramp = (double) strata::kernels::rope_yarn_ramp((float) cd[0], (float) cd[1], i) * + yarn.ext_factor; + const double ang = interp * (1.0 - ramp) + extrap * ramp; + const float rc = (float) (std::cos(ang) * ms), rs = (float) (std::sin(ang) * ms); + if (std::memcmp(&rc, &yc[(size_t) p * half + i], 4) != 0) ++yarn_bad; + if (std::memcmp(&rs, &ys[(size_t) p * half + i], 4) != 0) ++yarn_bad; + } + } + std::printf(" scaled table, yarn factor 4 %s (%lld of %d entries differ)\n", + yarn_bad ? "*** WRONG ***" : "bit-exact", yarn_bad, max_pos * half * 2); + bad += (int) yarn_bad; + + // 4e. THE STRUCTURE a tolerance cannot fake. At position 0 every pair's angle is 0, so YaRN's whole + // magnitude correction stands naked: cos_tab[0] == mscale. At the far end of the table the first + // pair (the highest trained frequency) must match EXTRAPOLATION and the last INTERPOLATION. The two + // halves need different observables: at the first pair cos separates the hypotheses outright, but at + // the last they differ by ~4 microradians here, invisible to cos near 1 - sin sees it, because near + // zero sin IS the angle. That asymmetry is the YaRN design: interpolation happens where angles are + // small. Both hypotheses go through the same mix formula the builder uses, so the bit comparison is + // spec against spec, not shortcut against implementation. + { + const float msv = (float) ms; + const bool zero_ok = std::memcmp(&msv, &yc[0], 4) == 0 && ys[0] == 0.0f; + const int far = max_pos - 1; + const double inv_f = 1.0; // pair 0: theta ** 0 + const double extrap_f = (double) far * inv_f, interp_f = fs * extrap_f; + const double inv_l = std::pow(theta, -2.0 * (double) (half - 1) / (double) n_rot); + const double extrap_l = (double) far * inv_l, interp_l = fs * extrap_l; + const float ef = (float) (std::cos(interp_f * (1.0 - 1.0) + extrap_f * 1.0) * ms); + const float itf = (float) (std::cos(interp_f * (1.0 - 0.0) + extrap_f * 0.0) * ms); + const float sl_e = (float) (std::sin(interp_l * (1.0 - 1.0) + extrap_l * 1.0) * ms); + const float sl_i = (float) (std::sin(interp_l * (1.0 - 0.0) + extrap_l * 0.0) * ms); + const float got_f = yc[(size_t) far * half], got_l = ys[(size_t) far * half + (half - 1)]; + const bool first_extrapolates = std::memcmp(&got_f, &ef, 4) == 0; + const bool last_interpolates = std::memcmp(&got_l, &sl_i, 4) == 0; + const bool distinguishable = std::fabs((double) ef - (double) itf) > 1e-3 && + std::fabs((double) sl_e - (double) sl_i) > 1e-8; + std::printf(" yarn structure: cos_tab[0]==mscale %.4f, first pair extrapolates, last interpolates " + "%s\n", (double) msv, + zero_ok && first_extrapolates && last_interpolates && distinguishable + ? "confirmed" + : "*** WRONG ***"); + if (!(zero_ok && first_extrapolates && last_interpolates && distinguishable)) ++bad; + } + + // 4f. THE OBSERVABILITY assertion: the fixtures must SEE scaling. If the builder ignored its config, + // linear(2) would equal `none` everywhere and 4b-4e would be green on a broken builder. + { + strata::kernels::RopeScaling lin2; + lin2.type = strata::kernels::RopeScalingType::Linear; + lin2.freq_base = theta; + lin2.factor = 2.0; + std::vector l2c((size_t) 101 * half), l2s((size_t) 101 * half); + strata::kernels::build_rope_table(n_rot, lin2, 101, l2c.data(), l2s.data()); + const float c_none = (float) std::cos(100.0); // pair 0, position 100, unscaled: ang = 100 + const float c_lin = l2c[(size_t) 100 * half]; // pair 0, position 100, linear(2): ang = 50 + const bool sees = std::fabs((double) c_none - (double) c_lin) > 1e-3; + std::printf(" observability: none vs linear(2) at position 100 %s (|%.4f - %.4f|)\n", + sees ? "visible" : "*** VACUUM ***", (double) c_none, (double) c_lin); + if (!sees) ++bad; + } + + // 4g. THE ROTATION under a scaled table. The kernel is table-agnostic and must not know or care: + // the host reference is the same rope_neox_pair walk as check 2, over the YaRN table. + std::vector ref2(x.size()); + for (int r = 0; r < rows; ++r) { + const float* xr = &x[(size_t) r * head_dim]; + float* orow = &ref2[(size_t) r * head_dim]; + for (int d = 0; d < head_dim; ++d) orow[d] = xr[d]; + for (int i = 0; i < half; ++i) { + float c = yc[(size_t) pos[(size_t) r] * half + i], s = ys[(size_t) pos[(size_t) r] * half + i]; + strata::kernels::rope_neox_pair(xr[i], xr[half + i], c, s, orow[i], orow[half + i]); + } + } + check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x"); + check(cudaMemcpy(d_cos, yc.data(), yc.size() * sizeof(float), cudaMemcpyHostToDevice), "copy ycos"); + check(cudaMemcpy(d_sin, ys.data(), ys.size() * sizeof(float), cudaMemcpyHostToDevice), "copy ysin"); + check(cudaMemcpy(d_pos, pos.data(), pos.size() * sizeof(int), cudaMemcpyHostToDevice), "copy pos"); + strata::kernels::rope_neox_apply(d_x, d_out, rows, head_dim, n_rot, d_cos, d_sin, d_pos, nullptr); + std::vector got2(ref2.size()); + check(cudaMemcpy(got2.data(), d_out, got2.size() * sizeof(float), cudaMemcpyDeviceToHost), "back"); + long long rot2_bad = 0; + double worst2 = 0.0; + for (size_t i = 0; i < ref2.size(); ++i) { + const double a = ref2[i], b = got2[i]; + const double rel = std::fabs(a - b) / row_scale[i / (size_t) head_dim]; + worst2 = std::max(worst2, rel); + if (!(rel <= 1e-6)) ++rot2_bad; + } + std::printf(" rope rotation over the yarn table %s (%lld of %zu over 1e-6, worst rel %.3e)\n", + rot2_bad ? "*** WRONG ***" : "agrees", rot2_bad, ref2.size(), worst2); + bad += (int) rot2_bad; + } + + // ---- 5. THE TWO PATHS MUST AGREE. The table path (the default) computes cos/sin on the host in float64; + // the native path (`--native-rope`) computes the same angles on device in float32 under `--use_fast_math`. + // They answer to ONE config - `RopeScaling` - and a disagreement between them would put differently-rotated + // K into the cache depending on which path ran. The tolerance is NOT the 1e-6 of checks 2/4g: the device + // side takes fast-math trig at angles up to ~2048 rad, where the fp32 range reduction alone is worth ~1e-4, + // so the bar is the row-magnitude-relative 3e-3 and the test keeps the positions where that holds. (The + // engine's default is the table path precisely because float64 host trig has no such floor.) + { + const int npos = 2048; + strata::kernels::RopeScaling yarn; + yarn.type = strata::kernels::RopeScalingType::YaRN; + yarn.factor = 2.0; + yarn.ext_factor = 1.0; + std::vector sc((size_t) npos * half), ss((size_t) npos * half); + strata::kernels::build_rope_table(n_rot, yarn, npos, sc.data(), ss.data()); + std::mt19937 rng2(23); + std::normal_distribution gauss2(0.0f, 1.0f); + const int nrows = 24 * 16; // 16 positions spread over the table's range + std::vector x2((size_t) nrows * head_dim); + for (auto& v : x2) v = gauss2(rng2); + std::vector pos2((size_t) nrows); + for (int r = 0; r < nrows; ++r) pos2[(size_t) r] = (r * 127) % npos; + + float *d_x2 = nullptr, *d_t2 = nullptr, *d_n2 = nullptr, *d_c2 = nullptr, *d_s2 = nullptr; + int* d_p2 = nullptr; + check(cudaMalloc(&d_x2, x2.size() * sizeof(float)), "malloc x2"); + check(cudaMalloc(&d_t2, x2.size() * sizeof(float)), "malloc t2"); + check(cudaMalloc(&d_n2, x2.size() * sizeof(float)), "malloc n2"); + check(cudaMalloc(&d_c2, sc.size() * sizeof(float)), "malloc c2"); + check(cudaMalloc(&d_s2, ss.size() * sizeof(float)), "malloc s2"); + check(cudaMalloc(&d_p2, pos2.size() * sizeof(int)), "malloc p2"); + check(cudaMemcpy(d_x2, x2.data(), x2.size() * sizeof(float), cudaMemcpyHostToDevice), "copy x2"); + check(cudaMemcpy(d_c2, sc.data(), sc.size() * sizeof(float), cudaMemcpyHostToDevice), "copy c2"); + check(cudaMemcpy(d_s2, ss.data(), ss.size() * sizeof(float), cudaMemcpyHostToDevice), "copy s2"); + check(cudaMemcpy(d_p2, pos2.data(), pos2.size() * sizeof(int), cudaMemcpyHostToDevice), "copy p2"); + // The native path demands an explicit stream - a null one is refused by validation, not defaulted. + cudaStream_t cs5 = nullptr; + check(cudaStreamCreate(&cs5), "stream5"); + strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr); + strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, yarn, d_p2, cs5); + check(cudaStreamSynchronize(cs5), "sync5"); + std::vector got_t(x2.size()), got_n(x2.size()); + check(cudaMemcpy(got_t.data(), d_t2, got_t.size() * sizeof(float), cudaMemcpyDeviceToHost), "back t2"); + check(cudaMemcpy(got_n.data(), d_n2, got_n.size() * sizeof(float), cudaMemcpyDeviceToHost), "back n2"); + long long agree_bad = 0; + double worst = 0.0; + for (int r = 0; r < nrows; ++r) { + double m = 0; + for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d])); + const double scale = m > 1e-30 ? m : 1e-30; + for (int d = 0; d < head_dim; ++d) { + const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] - + (double) got_n[(size_t) r * head_dim + d]) / scale; + worst = std::max(worst, rel); + if (!(rel <= 3e-3)) ++agree_bad; + } + } + std::printf(" native path vs table path, yarn factor 2 %s (%lld of %d over 3e-3, worst rel %.3e)\n", + agree_bad ? "*** WRONG ***" : "agrees", agree_bad, nrows * head_dim, worst); + bad += (int) agree_bad; + + // and the None config: the native path against the UNSCALED table - the identity this feature must + // not disturb. + strata::kernels::RopeScaling none5; // all defaults: type None, freq_scale 1, mscale 1 + strata::kernels::native_rope_apply(d_x2, d_n2, nrows, head_dim, n_rot, none5, d_p2, cs5); + check(cudaStreamSynchronize(cs5), "sync5b"); + check(cudaMemcpy(got_n.data(), d_n2, got_n.size() * sizeof(float), cudaMemcpyDeviceToHost), "back n2b"); + std::vector nc5((size_t) npos * half), ns5((size_t) npos * half); + strata::kernels::build_rope_table(n_rot, none5, npos, nc5.data(), ns5.data()); + check(cudaMemcpy(d_c2, nc5.data(), nc5.size() * sizeof(float), cudaMemcpyHostToDevice), "copy c2b"); + check(cudaMemcpy(d_s2, ns5.data(), ns5.size() * sizeof(float), cudaMemcpyHostToDevice), "copy s2b"); + strata::kernels::rope_neox_apply(d_x2, d_t2, nrows, head_dim, n_rot, d_c2, d_s2, d_p2, nullptr); + check(cudaMemcpy(got_t.data(), d_t2, got_t.size() * sizeof(float), cudaMemcpyDeviceToHost), "back t2b"); + long long none_bad5 = 0; + double worst5 = 0.0; + for (int r = 0; r < nrows; ++r) { + double m = 0; + for (int d = 0; d < head_dim; ++d) m = std::max(m, (double) std::fabs(x2[(size_t) r * head_dim + d])); + const double scale = m > 1e-30 ? m : 1e-30; + for (int d = 0; d < head_dim; ++d) { + const double rel = std::fabs((double) got_t[(size_t) r * head_dim + d] - + (double) got_n[(size_t) r * head_dim + d]) / scale; + worst5 = std::max(worst5, rel); + if (!(rel <= 3e-3)) ++none_bad5; + } + } + std::printf(" native path vs table path, none %s (%lld of %d over 3e-3, worst rel %.3e)\n", + none_bad5 ? "*** WRONG ***" : "agrees", none_bad5, nrows * head_dim, worst5); + bad += (int) none_bad5; + } + std::printf("\nrope: %d failures\n", bad); if (bad) return 1; if (selftest) std::printf("rope_parity OK\n"); diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu index 50984ec9..25226735 100644 --- a/src/prefill/kernels.cu +++ b/src/prefill/kernels.cu @@ -526,13 +526,17 @@ __global__ void rms_rows_kernel(float* __restrict__ x, const float* __restrict__ for (int64_t c = threadIdx.x; c < cols; c += blockDim.x) r[c] = s * r[c] * w[c]; } __global__ void rope_kernel(float* __restrict__ x, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, - float theta_scale, const int32_t* __restrict__ mtab) { + float theta_scale, float freq_scale, float corr_low, float corr_high, + float ext_factor, float mscale, const int32_t* __restrict__ mtab) { const int64_t row = blockIdx.x; // t * heads + h const int pair = threadIdx.x; // 0..31 const int64_t t = row / heads, h = row % heads; float* p = x + t * ld + h * dim; - const float theta = (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); - const float c = cosf(theta), s = sinf(theta); + const float theta_extrap = + (float) strata::kernels::mrope_pos(mtab, (int) (pos0 + t), pair) * powf(theta_scale, (float) pair); + float c, s; + strata::kernels::rope_scaled_angle(theta_extrap, freq_scale, corr_low, corr_high, ext_factor, mscale, + pair, c, s); const float a = p[pair], b = p[pair + 32]; p[pair] = a * c - b * s; p[pair + 32] = a * s + b * c; @@ -757,9 +761,19 @@ void rms_rows(float* x, const float* w, int64_t rows, int64_t cols, int64_t ld, rms_rows_kernel<<<(unsigned) rows, 256, 0, (cudaStream_t) stream>>>(x, w, cols, ld, eps); check("rms_rows"); } -void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, float freq_base, void* stream) { - const float theta_scale = powf(freq_base, -2.0f / 64.0f); - rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>(x, heads, dim, ld, pos0, theta_scale, strata::kernels::mrope_table()); +void rope(float* x, int64_t T, int64_t heads, int64_t dim, int64_t ld, int64_t pos0, + const strata::kernels::RopeScaling& scaling, void* stream) { + // The engine validates the resolved config at startup with the same rule (generate.cpp), so this only + // fires for a caller that bypassed it; the prompt path has no error return here, so it stops the process. + if (const char* why = strata::kernels::rope_scaling_invalid(scaling)) { + std::fprintf(stderr, "prefill rope: invalid rope scaling: %s\n", why); + std::exit(1); + } + const float theta_scale = powf((float) scaling.freq_base, -2.0f / 64.0f); + const strata::kernels::RopeKernelArgs k = scaling.kernel_args(64); // none: the identity constants + rope_kernel<<<(unsigned) (T * heads), 32, 0, (cudaStream_t) stream>>>( + x, heads, dim, ld, pos0, theta_scale, k.freq_scale, k.corr_low, k.corr_high, k.ext_factor, k.attn_factor, + strata::kernels::mrope_table()); check("rope"); } void split_q(const float* q_full, float* q, int64_t T, void* stream) { diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index e2468f00..116094ad 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -810,7 +810,7 @@ bool Prefill::draft_kv(core::MtpDrafter& mtp, const float* R_rows, const int32_t proj(mixed, mixed_h, w_k, Kc, nb, KV, Nn, 0); proj(mixed, mixed_h, w_v, Vc, nb, KV, Nn, 0); rms_rows(Kc, w_kn, nb * g.n_head_kv, g.head_dim, g.head_dim, EPS, m.cs); - rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, (float) strata::kernels::qsa_freq_base(), m.cs); + rope(Kc, nb, g.n_head_kv, g.head_dim, KV, c0, strata::kernels::rope_scaling(), m.cs); if (st.kv_q4) { strata::kernels::fwht256_inplace_cuda(Kc, nb * g.n_head_kv, m.cs); strata::kernels::fwht256_inplace_cuda(Vc, nb * g.n_head_kv, m.cs); @@ -1311,7 +1311,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err)) return false; if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err)) return false; rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); - rope(m.Kc, T, 2, 256, 512, p0, (float) strata::kernels::qsa_freq_base(), m.cs); + rope(m.Kc, T, 2, 256, 512, p0, strata::kernels::rope_scaling(), m.cs); // KV streaming: this layer's cells [0, p0) come in from the host copy to the staging pool, and the // chunk's cells go to the host copy, the staging pool, and the VRAM slots of resident blocks const bool staged = st.kv_mode == 1; @@ -1341,10 +1341,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } split_q(m.Qf, m.q, T, m.cs); rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); - rope(m.q, T, 24, 256, 6144, p0, (float) strata::kernels::qsa_freq_base(), m.cs); + rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); if (st.kv_q4) strata::kernels::fwht256_inplace_cuda(m.q, T * 24, m.cs); rms_rows(m.q_idx, (const float*) wiqn->data, T * 4, 128, 128, EPS, m.cs); - rope(m.q_idx, T, 4, 128, 512, p0, (float) strata::kernels::qsa_freq_base(), m.cs); + rope(m.q_idx, T, 4, 128, 512, p0, strata::kernels::rope_scaling(), m.cs); // the indexer appends, token by token; then scores + selection for many queries at once: // a query reads completed blocks (final once completed) and `dead` for its own tail block const strata::kernels::QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; @@ -1356,13 +1356,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e if (!per_token) { strata::kernels::native_qsa_indexer_append_batch(m.idx_raw, T, p0, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, - (float) strata::kernels::qsa_freq_base(), m.cs); + strata::kernels::rope_scaling(), m.cs); } for (int64_t t = 0; per_token && t < T; ++t) { const int32_t* step_t = m.steps_dev + t * strata::kernels::kStepCount; strata::kernels::native_qsa_indexer_append(m.idx_raw + t * 128, step_t + strata::kernels::kStepPos, 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, - (float) strata::kernels::qsa_freq_base(), m.cs); + strata::kernels::rope_scaling(), m.cs); } } catch (const std::exception& e) { err = std::string("prefill indexer: ") + e.what(); return false; } pt.mark(kPfQsaSel, cs); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 1412652b..e1e84e61 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -129,6 +129,20 @@ struct Options { bool native_flash_attn_short = false; // diagnostic pinned attention, context <=256 bool native_qsa_indexer = false; // pinned F16 key cache and F32 pooling bool native_qsa = false; // pinned F32 QSA norms and gate + /// THE CONTEXT EXTENSION (rope scaling, rope_scaling.hpp). These knobs resolve to ONE process config, + /// set once before `session_init` builds the rope table and the graphs capture the kernels. There is + /// deliberately no per-request form: K sits in the cache POST-RoPE, so one cache must never mix two + /// scalings. Precedence: an EXPLICIT flag over the model file's rope keys over the struct defaults - + /// `none` and `1` are explicit values (the opt-outs), the absent flag is not. + std::string rope_scaling; ///< --rope-scaling none|linear|yarn (llama.cpp's names); empty = the flag is absent + double rope_scale = 0; ///< --rope-scale F: the extension factor; 0 = the flag is absent (the model file's, else 1 = off) + double rope_freq_base = 0; ///< --rope-freq-base N: 0 = the model's (1e7) + double rope_freq_scale = 0; ///< --rope-freq-scale F: the raw ggml knob; 0 = 1/--rope-scale + double yarn_orig_ctx = 0; ///< --yarn-orig-ctx N: 0 = the model's, else 262144 + double yarn_ext_factor = -1.0; ///< --yarn-ext-factor F: <0 = auto (1 for yarn, 0 otherwise) + double yarn_attn_factor = 1.0; ///< --yarn-attn-factor F + double yarn_beta_fast = 32.0; ///< --yarn-beta-fast F + double yarn_beta_slow = 1.0; ///< --yarn-beta-slow F bool native_rope = false; // pinned text-only CUDA rotary arithmetic bool native_ple_postops = false; // pinned PLE postprojection arithmetic bool native_router = false; // pinned fused 512-expert top-10 router @@ -361,6 +375,17 @@ void usage() { " --expert-cache-cpu-order experimental GPU expert reduction matching CPU order\n" " --max-new N tokens to generate (default 16)\n" " --max-context N KV/state capacity (default 4096)\n" + " --rope-scaling T extend the context past the trained one: none, linear\n" + " (position interpolation) or yarn - llama.cpp's types and names.\n" + " Default: the model file's rope keys, else none. Fixed at startup:\n" + " K in the cache is post-RoPE, so one run one scaling\n" + " --rope-scale F the extension factor for linear/yarn (default: the model file's\n" + " factor, else 1 = off)\n" + " --rope-freq-base N the raw ggml knobs: the frequency base (0 = the model's 1e7) and\n" + " --rope-freq-scale F the angle shrink (0 = 1/--rope-scale)\n" + " --yarn-orig-ctx N the trained context the correction targets (0 = 262144)\n" + " --yarn-ext-factor F --yarn-attn-factor F --yarn-beta-fast F --yarn-beta-slow F\n" + " YaRN's knobs; defaults: -1 (auto: 1 for yarn), 1, 32, 1\n" " --greedy argmax (the default)\n" " --seed S enable sampling with this Philox seed\n" " --top-k N --top-p F --temperature F\n" @@ -935,6 +960,15 @@ int main(int argc, char** argv) { } else if (a == "--max-new") o.max_new = std::atoll(next("--max-new")); else if (a == "--max-context") o.max_context = std::atoll(next("--max-context")); + else if (a == "--rope-scaling") o.rope_scaling = next("--rope-scaling"); + else if (a == "--rope-scale") o.rope_scale = std::atof(next("--rope-scale")); + else if (a == "--rope-freq-base") o.rope_freq_base = std::atof(next("--rope-freq-base")); + else if (a == "--rope-freq-scale") o.rope_freq_scale = std::atof(next("--rope-freq-scale")); + else if (a == "--yarn-orig-ctx") o.yarn_orig_ctx = std::atof(next("--yarn-orig-ctx")); + else if (a == "--yarn-ext-factor") o.yarn_ext_factor = std::atof(next("--yarn-ext-factor")); + else if (a == "--yarn-attn-factor") o.yarn_attn_factor = std::atof(next("--yarn-attn-factor")); + else if (a == "--yarn-beta-fast") o.yarn_beta_fast = std::atof(next("--yarn-beta-fast")); + else if (a == "--yarn-beta-slow") o.yarn_beta_slow = std::atof(next("--yarn-beta-slow")); else if (a == "--greedy") o.greedy = true; else if (a == "--seed") { o.seed = (uint64_t) std::atoll(next("--seed")); o.greedy = false; } else if (a == "--top-k") o.top_k = std::atoi(next("--top-k")); @@ -1297,6 +1331,46 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: positive --max-new and --max-context must fit the prompt and generation\n"); return 2; } + // THE ROPE KNOBS (rope_scaling.hpp). Anything invalid dies here, at second zero, rather than becoming a + // NaN angle inside one of the twelve QSA layers. Only the RANGES are checked - the config itself is + // resolved after the model file has had its say, right before session_init. + strata::kernels::RopeScaling rope_cfg; // type filled here; the rest at the resolution below + { + using RST = strata::kernels::RopeScalingType; + // an absent --rope-scaling (the empty default) leaves the type to the model file's rope keys, + // resolved below; anything present must be one of the three names + if (o.rope_scaling == "none") rope_cfg.type = RST::None; + else if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; + else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; + else if (!o.rope_scaling.empty()) { + std::fprintf(stderr, "strata generate: --rope-scaling must be none, linear or yarn (got '%s')\n", + o.rope_scaling.c_str()); + return 2; + } + // every knob FINITE first: `atof("nan")` is NaN, and a NaN passes every range comparison below + for (const double v : {o.rope_scale, o.rope_freq_base, o.rope_freq_scale, o.yarn_orig_ctx, o.yarn_ext_factor, + o.yarn_attn_factor, o.yarn_beta_fast, o.yarn_beta_slow}) + if (!std::isfinite(v)) { + std::fprintf(stderr, "strata generate: a rope scaling knob is not a finite number (%g)\n", v); + return 2; + } + // 0 is the absent default; an explicit factor must extend, not shrink + if (o.rope_scale != 0 && o.rope_scale < 1.0) { + std::fprintf(stderr, "strata generate: --rope-scale %g must be >= 1 (it extends the context, not shrinks it)\n", + o.rope_scale); + return 2; + } + if (o.rope_freq_base != 0 && o.rope_freq_base <= 1.0) { + std::fprintf(stderr, "strata generate: --rope-freq-base must be a base above 1 (0 = the model's)\n"); + return 2; + } + if (o.rope_freq_scale < 0 || o.yarn_orig_ctx < 0 || o.yarn_ext_factor < -1.0 || o.yarn_attn_factor <= 0 || + o.yarn_beta_fast <= 0 || o.yarn_beta_slow <= 0) { + std::fprintf(stderr, "strata generate: invalid rope scaling knob (see usage: --yarn-ext-factor <0 = auto, " + "--yarn-orig-ctx 0 = default, the rest positive)\n"); + return 2; + } + } if (!std::isfinite(o.temperature) || o.temperature < 0 || !std::isfinite(o.top_p) || o.top_p <= 0 || o.top_p > 1 || o.top_k < 0 || o.expert_cache < -1 || o.pool_workers < 0 || std::any_of(o.expert_cache_remote.begin(), o.expert_cache_remote.end(), @@ -1400,6 +1474,109 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: this CPU has no AVX-512: the expert kernels run on %s " "(multi-token for the i-quant gate/up rows)\n", std::getenv("STRATA_NO_IQ256") == nullptr ? "AVX-2" : "ggml-cpu vec_dot (STRATA_NO_IQ256 set)"); + strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below + int64_t K = 10; + // THE ROPE CONFIG RESOLVES HERE, BEFORE ANY WEIGHT MOVES - the CLI and the model file have both spoken, + // and `session_init` below builds the rope table from it and captures the kernels reading its constants + // (rope_scaling.hpp); the only hard constraint is "set before that", and dying on a bad rope key beats + // scanning gigabytes of shards first. Precedence: an EXPLICIT flag over the model file's rope keys over + // the struct defaults. The empty --rope-scaling and the 0 --rope-scale mean the flag is absent, so the + // model file decides; an explicit value - `none` and `1` included, the opt-outs - wins over the model file. + { + // The model file's rope keys (llama.cpp's names under the arch prefix), when it carries any - the + // artifact today ships none, so this is a no-op defaults channel for future fine-tunes. + std::string gguf_rope_type; + double gguf_rope_base = 0, gguf_rope_factor = 0, gguf_rope_orig_ctx = 0; + if (!o.native_preset.empty()) { + // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file + // is the authority on its own MoE shape - everything else in the geometry is unchanged + try { + strata::GgufFile model_gguf(o.native_preset); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.freq_base")) gguf_rope_base = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.type")) gguf_rope_type = v->s; + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.factor")) gguf_rope_factor = v->num(); + if (const strata::MetaValue* v = model_gguf.get("qwen4exp.rope.scaling.original_context_length")) + gguf_rope_orig_ctx = v->num(); + } catch (const std::exception& e) { + std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n", + o.native_preset.c_str(), e.what()); + return 1; + } + } + using RST = strata::kernels::RopeScalingType; + if (!o.rope_scaling.empty()) { + // the early validation pinned the spelling; `none` here is the CLI opting OUT of the model file's keys + if (o.rope_scaling == "linear") rope_cfg.type = RST::Linear; + else if (o.rope_scaling == "yarn") rope_cfg.type = RST::YaRN; + else rope_cfg.type = RST::None; + } else if (!gguf_rope_type.empty()) { + if (gguf_rope_type == "linear") rope_cfg.type = RST::Linear; + else if (gguf_rope_type == "yarn") rope_cfg.type = RST::YaRN; + else if (gguf_rope_type != "none") { + std::fprintf(stderr, "strata generate: %s carries rope.scaling.type '%s' - none, linear or yarn only\n", + o.native_preset.c_str(), gguf_rope_type.c_str()); + return 2; + } + } + if (o.rope_scale > 0) rope_cfg.factor = o.rope_scale; // an explicit factor, 1 included + else if (gguf_rope_factor > 1.0) rope_cfg.factor = gguf_rope_factor; + if (o.rope_freq_base > 0) rope_cfg.freq_base = o.rope_freq_base; + else if (gguf_rope_base > 1.0) rope_cfg.freq_base = gguf_rope_base; + if (o.yarn_orig_ctx > 0) rope_cfg.orig_ctx = o.yarn_orig_ctx; + else if (gguf_rope_orig_ctx >= 1) rope_cfg.orig_ctx = gguf_rope_orig_ctx; + rope_cfg.freq_scale_in = o.rope_freq_scale; + rope_cfg.ext_factor = o.yarn_ext_factor >= 0 ? o.yarn_ext_factor + : (rope_cfg.type == RST::YaRN ? 1.0 : 0.0); + rope_cfg.attn_factor = o.yarn_attn_factor; + rope_cfg.beta_fast = o.yarn_beta_fast; + rope_cfg.beta_slow = o.yarn_beta_slow; + if (rope_cfg.type == RST::None) { + // none is the trained rotation, exactly: the scaling knobs are inert (the table builder and + // `kernel_args` ignore them), and resetting them keeps the logged/queried config honest. Only the + // frequency base survives - it is the rotation itself, not a scaling knob. + const bool knobs = o.rope_scale > 1.0 || o.rope_freq_scale > 0 || o.yarn_ext_factor > 0 || + o.yarn_attn_factor != 1.0; + const double base = rope_cfg.freq_base; + rope_cfg = strata::kernels::RopeScaling{}; + rope_cfg.freq_base = base; + if (knobs) + std::fprintf(stderr, "strata generate: note: no rope scaling is active (none), so --rope-scale, " + "--rope-freq-scale and the --yarn-* knobs have no effect\n"); + } + // THE RESOLVED CONFIG IS VALIDATED AS A WHOLE, with the one rule every rotation site also applies + // (rope_scaling.hpp): the CLI ranges above cannot see a model-file value, nor a combination such as a + // --rope-freq-scale that turns the resolved factor non-finite. + if (const char* why = strata::kernels::rope_scaling_invalid(rope_cfg)) { + std::fprintf(stderr, "strata generate: invalid rope scaling configuration: %s (type %s, factor %g, " + "freq_scale %g, base %g, original context %g)\n", + why, rope_cfg.type == RST::YaRN ? "yarn" : rope_cfg.type == RST::Linear ? "linear" : "none", + rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.orig_ctx); + return 2; + } + strata::kernels::rope_scaling_set(rope_cfg); + if (rope_cfg.type != RST::None) { + const char* tn = rope_cfg.type == RST::YaRN ? "yarn" : "linear"; + std::fprintf(stderr, + "strata generate: rope scaling %s, factor %.6g (freq_scale %.6g, base %.6g, mscale %.6f), " + "--max-context %lld against a trained context of %.0f\n", + tn, rope_cfg.factor, rope_cfg.freq_scale(), rope_cfg.freq_base, rope_cfg.mscale(), + (long long) o.max_context, rope_cfg.orig_ctx); + if ((double) o.max_context <= rope_cfg.orig_ctx) + std::fprintf(stderr, + "strata generate: note: the context is within the trained %.0f - no position needs the " + "extension, and the resolved scaling still applies to every angle\n", + rope_cfg.orig_ctx); + // only when there IS a magnitude correction: YaRN's log term (ext_factor != 0) or an explicit + // --yarn-attn-factor; plain linear (mscale 1) has none, and saying otherwise was TODO 22 + if (rope_cfg.mscale() != 1.0) + std::fprintf(stderr, + "strata generate: note: the %s magnitude correction scales cos and sin by %.6f " + "at every position\n", + rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); + } + } strata::core::NativeEmbed native_embed; if (native_pack) { if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical || @@ -1501,21 +1678,6 @@ int main(int argc, char** argv) { strata::kernels::mrope_table_set(d_mrope); } strata::kernels::ple_set_native_postops(o.native_ple_postops); - strata::core::ModelGeometry g; // canonical defaults; the model file overrides the MoE shape below - int64_t K = 10; - if (!o.native_preset.empty()) { - // a pruned variant (GSQ-RCO Coder) ships fewer experts than the canonical 512x10; the model file - // is the authority on its own MoE shape - everything else in the geometry is unchanged - try { - strata::GgufFile model_gguf(o.native_preset); - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_count")) g.n_expert = (int64_t) v->u; - if (const strata::MetaValue* v = model_gguf.get("qwen4exp.expert_used_count")) K = (int64_t) v->u; - } catch (const std::exception& e) { - std::fprintf(stderr, "strata generate: reading the model's expert shape from %s: %s\n", - o.native_preset.c_str(), e.what()); - return 1; - } - } // before session_init: every graph captured from here on has the vector's kernels where it applies std::string cvec_summary = "0"; if (!o.cvec_files.empty()) { diff --git a/tools/test_setup_rope.py b/tools/test_setup_rope.py new file mode 100644 index 00000000..85b47f98 --- /dev/null +++ b/tools/test_setup_rope.py @@ -0,0 +1,121 @@ +"""Tests for setup.py's automatic rope configuration (§4 + §6): the factor derives from the FINAL context +actually served - RAM reductions first, then final / trained 262144 clamped at 1 - explicit +--rope-scaling/--rope-scale choices win verbatim, an explicit none is refused past the trained range, and +nothing turns on by itself inside it. Pure functions - no GPU, no downloads, no prompts. + + python -m unittest tools.test_setup_rope +""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +class DerivedFactor(unittest.TestCase): + """The formula itself: max(1.0, final / trained).""" + + def test_the_task_table(self): + self.assertEqual(setup.derived_factor(131072), 1.0) # below the trained range: clamped at 1 + self.assertEqual(setup.derived_factor(262144), 1.0) # exactly the trained range: 1 + self.assertEqual(setup.derived_factor(393216), 1.5) # 384K + self.assertEqual(setup.derived_factor(524288), 2.0) # 512K + + def test_free_form_contexts_get_the_exact_ratio(self): + # /262144 = /2**18 is exact in binary floating point, so no dust + self.assertEqual(setup.derived_factor(600000), 600000 / 262144) + self.assertGreater(setup.derived_factor(600000), 2.0) + + def test_the_clamp_is_what_keeps_128k_at_one(self): + self.assertEqual(setup.derived_factor(131072), 1.0) # NOT the raw 0.5 + + +class ResolveRope(unittest.TestCase): + # ---- the automatic flow the docs promise (an omitted flag, --yes or the interactive default) + def test_omitted_384k_gets_yarn_and_1_5(self): + self.assertEqual(setup.resolve_rope(393216, None, None), ("yarn", 1.5)) + + def test_omitted_512k_gets_yarn_and_2(self): + self.assertEqual(setup.resolve_rope(524288, None, None), ("yarn", 2.0)) + + def test_deterministic_for_yes(self): + # --yes never prompts, so the resolution must be a pure function of its inputs + for _ in range(3): + self.assertEqual(setup.resolve_rope(524288, None, None), ("yarn", 2.0)) + + def test_omitted_method_with_an_explicit_factor(self): + # --rope-scale alone still expresses the intent to extend: the method defaults, the factor is kept + self.assertEqual(setup.resolve_rope(393216, None, 1.8), ("yarn", 1.8)) + + # ---- explicit selections are respected, verbatim + def test_explicit_method_gets_the_derived_factor(self): + self.assertEqual(setup.resolve_rope(524288, "linear", None), ("linear", 2.0)) + + def test_explicit_method_and_factor_are_kept_verbatim(self): + self.assertEqual(setup.resolve_rope(393216, "linear", 2.0), ("linear", 2.0)) + self.assertEqual(setup.resolve_rope(524288, "yarn", 1.5), ("yarn", 1.5)) + + def test_an_explicit_override_survives_a_context_reduction(self): + # §4: the RAM check reduced the final context to 128K - a user-supplied factor is NOT recalculated + self.assertEqual(setup.resolve_rope(131072, "yarn", 2.0), ("yarn", 2.0)) + self.assertEqual(setup.resolve_rope(131072, "linear", 1.75), ("linear", 1.75)) + + # ---- an explicit none past the trained range is refused with an explanation, not overridden + def test_explicit_none_past_trained_is_refused(self): + with self.assertRaises(ValueError) as cm: + setup.resolve_rope(524288, "none", None) + self.assertIn("262144", str(cm.exception)) + self.assertIn("yarn", str(cm.exception)) # the message names the way out + + def test_explicit_none_within_trained_is_the_stock_model(self): + self.assertEqual(setup.resolve_rope(131072, "none", None), (None, None)) + + # ---- inside the trained range nothing turns on by itself; a chosen method gets factor 1 + def test_omitted_within_trained_adds_nothing(self): + self.assertEqual(setup.resolve_rope(262144, None, None), (None, None)) + self.assertEqual(setup.resolve_rope(131072, None, None), (None, None)) + + def test_a_scale_alone_within_trained_is_rejected(self): + with self.assertRaises(ValueError): + setup.resolve_rope(131072, None, 2.0) + + def test_a_chosen_method_within_trained_gets_factor_1(self): + # no more unconditional factor 2: 1 = the trained angles, no automatic expansion + self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 1.0)) + self.assertEqual(setup.resolve_rope(262144, "linear", None), ("linear", 1.0)) + + # ---- §4 coordination: the RAM reduction lands BEFORE the rope config, so the factor matches the + # context actually served - the 512K-on-IQ3_S-with-under-90-GB case from the task, end to end + def test_512k_on_a_small_ram_machine_resolves_to_128k_factor_1(self): + # asked 524288 with --rope-scaling yarn and no factor; the RAM check brings the final context to 131072 + self.assertEqual(setup.resolve_rope(131072, "yarn", None), ("yarn", 1.0)) + + def test_no_reduction_384k_and_512k_resolve_as_documented(self): + self.assertEqual(setup.resolve_rope(393216, "yarn", None), ("yarn", 1.5)) + self.assertEqual(setup.resolve_rope(524288, "yarn", None), ("yarn", 2.0)) + + # ---- the short-context item's own table: no factor-2 fallback inside the trained window, for either + # method, with the explicit override column kept verbatim + def test_the_short_context_table(self): + cases = [ + (131072, None, "yarn", 1.0), # --context 131072 --rope-scaling yarn + (262144, None, "yarn", 1.0), # --context 262144 --rope-scaling yarn + (393216, None, "yarn", 1.5), + (524288, None, "yarn", 2.0), + (131072, 2.0, "yarn", 2.0), # --rope-scale 2 is kept inside the window + ] + for ctx, scale, method, want in cases: + self.assertEqual(setup.resolve_rope(ctx, method, scale), (method, want), f"ctx {ctx}") + + def test_linear_gets_the_same_rule_as_yarn(self): + # the old fallback applied to both methods, so the fix must too + self.assertEqual(setup.resolve_rope(131072, "linear", None), ("linear", 1.0)) + self.assertEqual(setup.resolve_rope(393216, "linear", None), ("linear", 1.5)) + + +if __name__ == "__main__": + unittest.main()