Files
leleka/docs/rope-and-memory-plan.md
T
Pavlo RatushnyiandClaude Opus 5.5 0103ee90aa feat(kv): per-owner resident KV window for the streamed QSA layers (kv_stream n_slots)
The resolver PTX baked 8192 resident pages (--kv-resident 32768). Port the
Original's KvStreamMap::n_slots: leleka_qsa_resolve and leleka_qsa_stream_reset
take n_slots (resealed with nvcc 13.2.86, sm_120, precise flags; digests in the
window asset, the window seal plan and the ptx_abi test). Every streamed owner
sizes its resident runs and resolver state from the process-wide window
(configure_kv_resident, default 32768 cells = the previous behaviour) and
launches with its own slot count; the verify window carries it in its KV
binding. leleka-context: resident_pages_for (layer.cpp kv_plan rule),
resident_runs, stream_map_bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 10:34:33 +02:00

115 lines
11 KiB
Markdown

# RoPE scaling, memory admission and the 262144 pin lift
Status: the Rust side of the lift is applied and type-checked against the linux target; the CUDA side is edited in source but the committed PTX is NOT regenerated. No GPU was used and no performance or model-quality claim is made. Base: `claude/port-main` (Original-literal source-port, 8651f78).
## What was added
| Location | What / which Original it ports |
| --- | --- |
| `crates/context/src/rope_scaling.rs` | `rope_scaling.hpp`, `build_rope_table` (`rope.cu`), rope knob resolution (`generate.cpp`), `resolve_rope`/`derived_factor` (`setup.py`) |
| `crates/context/src/memory_plan.rs` | `plan.hpp`, pool derivation of `plan_main.cpp`, `kv_pool_bytes` (`layer.cpp`), `kv_q8.hpp`, `kv_q4.hpp` |
| `crates/context/src/context_policy.rs` | requested slots / per-slot context / KV format / rope knobs / VRAM into an `EffectiveContext`, or a refusal |
| `crates/context/src/geometry.rs` | every byte size of the native QSA stack as a linear function of the cell count (`QsaGeometry`) |
| `crates/context/src/ptx_abi.rs` | frozen vs extended PTX argument-list detection (counts `.param` of an `.entry`) |
| `crates/cuda-driver/src/serving_context.rs` | process-wide, set-once serving context (`configure_serving_context`), mirrors the Original's `rope_scaling_set` |
| `crates/leleka-runtime/src/serving.rs` | `apply_effective_context`, `admit_context_tokens`: installs an `EffectiveContext` into the driver |
The pure modules live in a separate `leleka-context` crate because `cuda-driver` and `leleka-runtime` do not compile on macOS in this tree; everything testable without CUDA is tested there.
## The pin lift
The 262144 literal had three roles; they are separated.
1. Trained-length identity of the artifact: still checked (`model_binding/qwen4exp_input.rs` `validate` and `qwen4exp_qsa.rs` metadata tuple require 262_144). Unchanged.
2. Serving ceiling: `backend.rs` now accepts up to `MAX_CHARTER_CONTEXT` (524288) and calls `serving::admit_context_tokens`.
3. Position / buffer bound: one value, `contract::serving_cells()` (runtime) / `geometry().cells()` (driver). It is 262144 unless a context was configured, so the default (1 slot at 262144) is bit-identical: `QsaGeometry::TRAINED` is asserted equal to every frozen literal (`geometry.rs` tests).
Threaded through (all identical at 262144):
- Driver: `QSA_PROMPT_*` offsets, stage runs, page table, admit/guards, mapped host size, index sizes and `max_blocks`, resident/device/journal/transport buffers, every `A::I32(262144)` kernel argument, the MTP dense layout bound. The public `QSA_PROMPT_*` consts remain the frozen trained values.
- Runtime: `qsa_index` `CONTEXT` -> `context()`, `DEVICE_PEAK` -> `device_peak()` (128 MiB + extra pooled-index rows, `128*4 + 4` bytes per row), native state / selected cache / resident index / `NativeQsaResources` sizes, `session*` and chunk bounds, `Position`'s `Dimension` (`contract::position_dimension()`, ~55 sites), MTP bounds, spawn cap and append bounds.
- Left on purpose: vocabulary 262144 checks, `backend_measurement.rs` and `fivecase_*` / `native_down_*` / `long_public_request.rs` measurement configs, `original_session_rope.rs` `orig_ctx` (YaRN trained length), the `mtp_original_*` bank (see below).
Policy refusals in `apply_effective_context`: slots other than 1, KV format other than INT8, and an extended or scaled context against a driver whose process geometry differs.
### Refused, not resized
- The MTP drafter bank is frozen at 262144 cells (`MTP_ORIGINAL_MAX_CELLS`, physical layout, `mtp_original_full_round` cell guard). `ExperimentalMtp` with `context_tokens > 262144` is refused at spawn.
- The legacy rope ops `QsaRopeQ/K/IndexQ/QsaIndexAppend` of `qwen_dispatch::qsa_call` are refused when RoPE is scaled (they bake identity).
- `original_verify_qsa` / `OriginalVerifyRope` are wired by the Original serve stack (`RopeConstants::from_serving_context`: the analytic form of the serving context's RoPE arguments; `STRATA_ROPE_TABLE` tables are not supported). Not GPU-run.
## CUDA: what bakes a limit, and the PTX not yet regenerated
Grep of all non-vendored `.cu`/`.ptx` for 262144 / 65536 / 65537 / 65538: the only baked limits are the identity RoPE constants and one page-count loop bound. Everything else already receives the cell count as a kernel argument (now `geometry().cells()`); position guards `pos >= max_cells` return silently, so the argument must be right.
`.cu` sources edited (committed PTX NOT regenerated):
| Source | Entries | Change |
| --- | --- | --- |
| `qsa_prompt_indexer.cu` | `qsa_append_first`, `qsa_append_blocks`, `qsa_decode_append` | 5 trailing floats `freq_scale, corr_low, corr_high, ext_factor, mscale` replace the baked identity |
| `qsa_prompt_postops.cu` | `qsa_rope_rows` | same 5 floats |
| `qsa_decode_postops.cu` | `qsa_decode_rope` | same 5 floats |
| `qsa_prompt_resolver.cu` | `leleka_qsa_stream_reset`, `leleka_qsa_resolve` | trailing `int64_t n_blocks` replaces the baked 65536 in the reset; a trailing `int64_t n_slots` (the `--kv-resident` page count, see `docs/kv-streaming.md`) replaces the baked 8192 in both (`leleka_qsa_miss_copy` reads neither) |
Frozen parameter counts of the committed PTX (asserted by `ptx_abi::tests::committed_ptx_has_the_frozen_argument_lists`): first 6, blocks 13, decode_append 11, rope_rows 6, decode_rope 6 (each +5 after regeneration), stream_reset 7 (+2), resolve 10 (+1).
The Rust launch side is ABI-gated so a mismatch cannot be silent: `qsa_index_ffi.rs` (`rope_abi()`, `Arguments::for_launch`) appends the 5 floats only when the PTX is extended; scaled RoPE against frozen PTX is refused. `qsa_prompt_resolver.rs` requires the regenerated resolver (reset 9 and resolve 11 parameters) and refuses any other PTX. The default configuration therefore runs on the committed PTX unchanged, and the `Tc` reach limit is `max_blocks()`.
### Regeneration (Linux host, pinned toolkit 13.0.88)
The committed headers say CUDA 12.8.93; `scripts/build-original-verify-ptx.sh` pins V13.0.88 (`deploy/cuda-toolkit.lock.json`). For each of the four sources, with `$R` the repository root:
```sh
nvcc --ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false \
-I$R/engine/strata/include -I$R/engine/strata/third_party/ggml \
-I$R/crates/cuda-driver/src/third_party/llamacpp/ggml-cuda \
-I$R/crates/cuda-driver/src/third_party/llamacpp/ggml-include \
-I$R/crates/cuda-driver/src/third_party/llamacpp/ggml-src \
$R/crates/cuda-driver/src/<source>.cu -o $R/crates/cuda-driver/src/<source>.ptx
```
for `<source>` in `qsa_prompt_indexer`, `qsa_prompt_postops`, `qsa_decode_postops`, `qsa_prompt_resolver`. These four are not in the build script's list; add them (or run the command above) and follow the repository's PTX provenance convention (the `UNSEALED` marker). Regenerating them with 13.0.88 changes all other code in those PTX too, so they need the existing PTX test and a fresh numeric comparison against the old PTX at the default (identity constants must reproduce the old outputs). After regeneration update the `ptx_abi` test to require `Extended`.
## Verified how
- macOS: `cargo test -p leleka-context` (35 unit tests, 6 `context_lift` integration tests, 29 golden/other), `cargo clippy -p leleka-context --all-targets -- -D warnings`, `cargo fmt --check`.
- `cargo check --target x86_64-unknown-linux-gnu --all-targets -p leleka-cuda-driver --features cuda-driver -p leleka-runtime`: type-check only, passes. The tests inside `cuda-driver` and `leleka-runtime` (including `serving.rs`, `qwen_ffi` boundary tests) compile but were NOT run.
- Tests added (all in `leleka-context`, pure): default unchanged; 2x256K needs no scaling and per-slot geometry equals the trained one; 1x512K YaRN factor 2 with every buffer formula exactly scaled (mapped host 12 layers = 6_643_789_824, rope table 134_217_728); planner refusals; boundaries 262143/262144/524287/524288 (admit and table rows).
## Still needing Linux / nvcc / GPU
- Regenerate the four PTX above; run the ABI test in `Extended` mode; compare default outputs against the old PTX.
- Run the runtime and driver tests on Linux; run the default-context GPU path to confirm bit-identity of tokens (greedy) with the unlifted binary.
- Qualify 2x256K and 1x512K on hardware: the lift only proves arithmetic and types. Host-mapped KV at 512K is 6.64 GB for 12 layers; device peak and the resident pool were scaled by formula, not measured. 1x512K YaRN quality has no gate.
- Multi-slot serving is a policy extension: the runtime path accepts one slot.
- `EffectiveContext::engine_estimate` is hand-derived and advisory; the planner is conservative relative to the runtime because the runtime's KV is host-mapped.
## Verified on macOS before the lift (golden tests, unchanged)
Rope tables: `crates/context/tests/rope_plan_golden/rope_golden.json` from `gen_rope_golden.sh` (includes `rope_scaling.hpp` unmodified, extracts `build_rope_table` from `rope.cu` verbatim, `-O2 -ffp-contract=off -fno-builtin-sinf -fno-builtin-cosf`). 16 table configurations and 9 invalid ones; the Rust builder matches bit-for-bit via FNV-1a over all 524288 rows (and the first 262144) plus 10 complete rows, `corr_dims`, `kernel_args`, the validity message and the f32 analytic path. Memory plan: `gen_plan_golden.sh` builds the unmodified `strata-plan` and runs 81 argument tables; the port reproduces exit code, stdout and stderr byte for byte for the 78 planner runs. `kv_pool_bytes` (extracted from `layer.cpp`): 80 rows match. The `setup.py` and `generate.cpp` resolvers have no executable oracle on macOS; they are transcribed and unit-tested.
## Findings about the Original (kept literal)
1. Fused multiply-add changes YaRN tables: the same C++ with `-ffp-contract=on` differs from `=off` in individual entries. Rust never contracts. A contracting host build (e.g. aarch64 GCC) can differ by 1 f32 ULP in some YaRN entries.
2. Apple clang merges `sinf`/`cosf` into `__sincosf_stret`, whose `sinf` differs by 1 to 2 ULP; only the host f32 analytic helper is affected.
3. `plan.hpp` counts the indexer key store as 32 bytes per token and layer; `layer.cpp` allocates fp32 pooled keys (128). The planner under-reports by 96 bytes per token and layer, about 0.6 to 0.7 GiB on the charter profiles.
4. `strata-plan` subtracts `--dense` and `--embd` from the VRAM for the pool and `make_plan` subtracts them again; a derived pool of 0 becomes the 5.943 GB default. Both preserved.
5. `plan.hpp` models INT8 only. Other formats use `kv_pool_bytes`: fp16 2048, INT8 1056, Q4_0 576, K8V4 816 bytes per cell and layer; keyless INT8 is 528. The charter's "about 1.55 GiB per 256K" equals 12 layers of 528 bytes (keyless), not INT8 (3.19 GiB by `plan.hpp`).
6. Slots are an extension: `S` slots of `C` cells are planned as `max_context = S*C` with `S` copies of the recurrent state. Rope positions restart per slot, so scaling follows the per-slot context: 2x256K none, 1x512K YaRN factor 2.
Illustrative admission (KV bytes only; 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 | same KV | same | same | same |
## Regenerating fixtures
```sh
crates/context/tests/rope_plan_golden/gen_rope_golden.sh # clang++ or CXX=..., ~15 s
crates/context/tests/rope_plan_golden/gen_plan_golden.sh # clang++ and python3 (offline tooling only)
```
The generators read `engine/strata/` and do not modify it.