docs: rope scaling and memory-plan port status, findings and pin-lift hunk

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 14:42:42 +02:00
co-authored by Claude Sonnet 5.5
parent 7092d7e756
commit 9d581c441b
+81
View File
@@ -0,0 +1,81 @@
# RoPE scaling and memory-admission port (macOS-verified, CUDA open)
Status: host-side Rust ports with golden fixtures from the Original. No GPU was used. No performance or model-quality claim is made here.
## What was added
| Module (`crates/leleka-runtime/src/`) | Original it ports |
| --- | --- |
| `rope_scaling.rs` | `include/strata/kernels/rope_scaling.hpp`, `build_rope_table` in `src/kernels/cuda/rope.cu`, rope knob resolution in `src/program/generate.cpp`, `resolve_rope`/`derived_factor` in `setup.py` |
| `memory_plan.rs` | `include/strata/plan/plan.hpp`, the pool derivation in `src/plan/plan_main.cpp`, `kv_pool_bytes` in `src/core/layer.cpp`, `kernels/kv_q8.hpp`, `kernels/kv_q4.hpp` |
| `context_policy.rs` | composition of the two above: requested slots, per-slot context, KV format, rope knobs and VRAM into an effective configuration, or a refusal |
`lib.rs` gets three `pub mod` lines; `Cargo.toml` gets `serde_json` as a dev-dependency (already in `Cargo.lock`). Nothing else existing is modified.
## Verified on macOS (arm64, Apple clang 21, `cargo test -p leleka-runtime`)
Rope tables. Fixtures `tests/rope_plan_golden/rope_golden.json` come from `gen_rope_golden.sh`: it includes `rope_scaling.hpp` unmodified and extracts both `build_rope_table` definitions from `rope.cu` verbatim (awk, no retyping), compiled `-O2 -ffp-contract=off -fno-builtin-sinf -fno-builtin-cosf`. 16 configurations with tables (none, none with inert knobs, linear 1.5/2, linear with raw `freq_scale`, linear with `attn_factor`, YaRN 1/1.5/2/4, YaRN with other betas / half `ext_factor` / other trained length / `ext_factor` 0 / `n_rot` 128 / `n_rot` 4) and 9 invalid ones. For every table case the Rust builder matches bit-for-bit: FNV-1a 64 over all 524288 rows (and the first 262144) of both the cos and the sin table, plus 10 complete sample rows. Also bit-exact: `corr_dims`, `kernel_args`, the validity message, the f32 analytic `rope_scaled_angle` path (24 samples per config). `freq_scale` and `mscale` are compared exactly on macOS.
Memory plan. `gen_plan_golden.sh` builds the unmodified `strata-plan` CLI (header-only, `plan_main.cpp`) and runs 81 argument tables (contexts 20480 to 524288, 3 to 48 GB, `--dense/--embd/--workspace/--state/--pool`, refusals). The Rust port reproduces exit code, stdout and stderr byte for byte for the 78 planner runs (the other three are `--help` and argument errors). `kv_pool_bytes` is the Original's own function extracted from `layer.cpp`; 80 rows (5 formats, 4 shapes, 4 page counts) match.
Policy and arithmetic unit tests cover the setup.py and generate.cpp resolution rules. Those two resolvers have no executable oracle on macOS (`generate.cpp` and `setup.py` cannot be run here); they are transcribed and unit-tested against the source text, not golden-tested.
## Findings about the Original (kept literal in the port)
1. Fused multiply-add changes YaRN tables. The same extracted C++ compiled with the default `-ffp-contract=on` differs from `=off` in individual entries (the fixture hashes change). Rust never contracts. An engine host build that contracts (for example aarch64 GCC defaults) can therefore differ by 1 f32 ULP in some YaRN entries from an x86-64 build without FMA. The CMake file sets no contraction flag for `rope.cu`'s host code.
2. Apple clang merges `sinf` and `cosf` of one argument into `__sincosf_stret`, whose `sinf` differs from a standalone `sinf` by 1 to 2 ULP. This affects only the host f32 analytic helper (on CUDA, device `sinf` applies). The f64 tables are unaffected. The fixture uses separate calls, like Rust.
3. `plan.hpp` counts the indexer key store as `key_heads * key_dim / qsa_block = 32` bytes per token and layer. `layer.cpp` allocates fp32 pooled keys (128 bytes per token and layer, the "50 MiB at 32K" quoted in `qsa.hpp`). The planner therefore under-reports by 96 bytes per token and layer. On the charter profiles that is about 0.6 to 0.7 GiB (`EffectiveContext::engine_estimate`, hand-derived, advisory only).
4. `strata-plan` subtracts `--dense` and `--embd` from the VRAM to form the pool and `make_plan` subtracts them again. With non-zero weights the CLI answer is more conservative than a single subtraction. A derived pool of 0 becomes the 5.943 GB default pool. Both are preserved because the requirement is identical answers to `strata-plan`.
5. `plan.hpp` models INT8 KV only. The other formats use the Original's `kv_pool_bytes`: fp16 2048, INT8 1056, Q4_0 576, K8V4 816 bytes per cell and layer. The experimental keyless mode (`STRATA_KEYLESS_ROUTING`) is half of INT8 (528). The charter's "about 1.55 GiB per 256K" equals 12 layers of 528 bytes without the indexer term, that is the keyless/value-only figure, not INT8 (3.19 GiB by plan.hpp). This is an observation from the arithmetic, not a verified statement about the charter's intent.
6. The planner sizes one `max_context`. Slots are an extension: `S` slots of `C` cells are planned as `max_context = S*C` with `S` copies of the per-sequence recurrent state, which is exactly what `strata-plan --max-context S*C --state S*state_bytes` prints. Rope positions restart in each slot, so scaling is chosen from the per-slot context: 2x256K needs none, 1x512K resolves to YaRN factor 2 (`setup.py` rule).
Illustrative admission results (`strata-plan` arithmetic, no resident weights supplied, KV bytes only; the pool is what the KV, state and expert cache share, so real use must pass `dense`/`embd`/`workspace`):
| Profile | fp16 | INT8 | Q4_0 | K8V4 |
| --- | --- | --- | --- | --- |
| 1x512K | refused at 12 GiB, ok at 16 GiB (KV 12.19 GiB) | ok at 12 GiB (KV 6.38 GiB) | ok (3.56 GiB) | ok (4.97 GiB) |
| 2x256K | refused at 12 GiB, ok at 16 GiB (KV 12.19 GiB) | ok at 12 GiB (KV 6.38 GiB) | ok (3.56 GiB) | ok (4.97 GiB) |
Both profiles have identical KV bytes under the planner; 2x256K carries twice the recurrent state (0.22 GiB vs 0.11 GiB).
## Open (not verified, not done)
- No CUDA kernel was run. Whether the PTX rope kernels consume these tables, or the analytic constants (`RopeKernelArgs`), is untouched: the Rust runtime's rope lives inside PTX unscaled today.
- No libm other than macOS was compared. On other platforms the tests allow 1 ULP (table rows) and 2 ULP (f32 analytic), report but do not assert the table hashes, and the tolerance has not been measured on Linux.
- The `EffectiveContext::engine_estimate` formulas are hand-derived from `qsa_state_bytes`; only the `kv_pool_bytes` part is golden-tested. It ignores the step/position state, alignment, and `--kv-resident` streaming (mode 1/2 pools are not modelled; K8V4 is incompatible with it in the Original).
- No quality gate exists for scaled contexts or for Q4_0/K8V4/keyless KV. The policy refuses `Int8Keyless` unless `allow_experimental` is set; lossy KV formats are the caller's explicit choice.
- Multi-slot memory behaviour in the real runtime (shared rope table, per-slot states) is the extension described above, not an Original behaviour.
## Lifting the 262144 pin (not applied)
The pin is in three roles that must be separated, otherwise the artifact identity check is lost:
1. Trained-length identity of the artifact: keep checking `t.context_length() == 262144` (`model_binding/qwen4exp_input.rs:133` and the metadata tuple at `model_binding/qwen4exp_qsa.rs:154`). This is the trained length and is correct.
2. Serving ceiling: `backend.rs:91`.
3. `Position`/`Dimension` bound reading `InputConstants::context_length()`: `backend.rs:972-985` (`native_position`), `qwen_forward/session.rs:520`, `qwen_forward/executor.rs:152`, `qwen_forward/input.rs:165`.
Smallest consistent change for 1x512K on the Rust side (written for Root; `cargo check` is not claimed for it):
```diff
--- a/crates/leleka-runtime/src/backend.rs
- || config.context_tokens > 262_144
+ || u64::from(config.context_tokens) > crate::rope_scaling::MAX_CHARTER_CONTEXT
--- a/crates/leleka-runtime/src/model_binding/qwen4exp_input.rs (from_artifact)
+ if t.context_length() != 262_144 { return Err(InputBindingError::Metadata); } // trained identity
- context_length: t.context_length(),
+ context_length: crate::rope_scaling::MAX_CHARTER_CONTEXT as u32, // serving bound used by Position
--- same file (validate)
- if self.eos != 248_044 || self.context_length != 262_144 {
+ if self.eos != 248_044 || self.context_length != 524_288 {
```
Then every other hard-coded 262144 is a functional blocker for positions at or above 262144 and must be raised to the same bound or read from the constants: `qwen_forward/qsa_index.rs:20` (`CONTEXT`, used at lines 140, 223, 391, 864, 982), `qwen_forward/mtp_attention.rs:382`, `qwen_forward/mtp_state.rs:41`, `qwen_forward/mtp.rs:45,88`, `qwen_forward/mtp_decode.rs:227,281`, `qwen_forward/session.rs:782`. Test-only literals in `executor.rs`, `gdn*.rs` and `input.rs` follow. The CUDA allocations behind those buffers (KV arena, 128 MiB `DEVICE_PEAK`, page tables) and a rope kernel that reads the scaled table must then be sized from `context_policy::resolve_context`; none of that is verified here. The runtime should call `resolve_context` before any allocation and use `EffectiveContext::{rope, rope_table_rows, plan}`.
## Regenerating fixtures
```sh
crates/leleka-runtime/tests/rope_plan_golden/gen_rope_golden.sh # clang++ or CXX=..., ~15 s
crates/leleka-runtime/tests/rope_plan_golden/gen_plan_golden.sh # clang++ and python3 (offline tooling only)
```
The generators read `engine/strata/` and do not modify it.