From 7c000ce93fa71f712431ecfae15c52e5ffffab13 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 23 Nov 2026 09:34:33 +0100 Subject: [PATCH] CI workflows (oracle numpy pin per interpreter, copy-source test harness), ignore rules, root files without docs/ links; AGENTS.md is a local pointer to the MCP (STRA-382) --- .dockerignore | 1 - .gitattributes | 6 +- .github/workflows/desktop.yml | 2 +- .github/workflows/port.yml | 25 +- .github/workflows/product.yml | 6 +- .gitignore | 5 + AGENTS.md | 58 - Cargo.toml | 2 +- PORT-GAPS-MODE17.md | 4 +- README.md | 20 +- ...cuda-seal-plan-additions-experimental.json | 444 ++-- engine/upstream.md | 178 ++ engine/upstream/local-patches-on-0.1.35.patch | 2147 ++++++++++++++++ engine/upstream/local-patches-on-0.1.50.patch | 2243 +++++++++++++++++ paper/README.md | 35 + paper/leleka.tex | 632 +++++ 16 files changed, 5504 insertions(+), 304 deletions(-) delete mode 100644 AGENTS.md create mode 100644 engine/upstream.md create mode 100644 engine/upstream/local-patches-on-0.1.35.patch create mode 100644 engine/upstream/local-patches-on-0.1.50.patch create mode 100644 paper/README.md create mode 100644 paper/leleka.tex diff --git a/.dockerignore b/.dockerignore index 6d88d703..cf5dc200 100644 --- a/.dockerignore +++ b/.dockerignore @@ -13,7 +13,6 @@ engine/strata/* engine/strata/serve/* !engine/strata/serve/chat_template.jinja benchmarks/ -docs/ target/ dist/ **/target/ diff --git a/.gitattributes b/.gitattributes index 87b05f77..61da554d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -8,9 +8,9 @@ scripts/gpu-bringup/**/*.py text=auto eol=lf scripts/e2e/codex/tasks/** -text scripts/e2e/codex/delta/** text eol=lf -# Release reproducibility (docs/release/5090-v0.1-checklist.md): the sealed PTX files are pinned by SHA-256 in the sources, so the bytes in the +# Release reproducibility: the sealed PTX files are pinned by SHA-256 in the sources, so the bytes in the # working tree must be the bytes in the index on every platform. Without this line a Windows checkout with core.autocrlf=true turns 212 of the -# 273 .ptx files into CRLF (the other 61 end in a NUL byte, which git treats as binary) so the embedded PTX is not the sealed one (a CRLF checkout built a binary 9 MB smaller than every earlier one, docs/experiments/baseline-pair-5090.md part d). +# 273 .ptx files into CRLF (the other 61 end in a NUL byte, which git treats as binary) so the embedded PTX is not the sealed one (a CRLF checkout built a binary 9 MB smaller than every earlier one). *.ptx -text # The release packager and the files it copies into the tarball are POSIX shell and systemd text: LF everywhere. scripts/release/** text eol=lf @@ -19,7 +19,7 @@ deploy/rust-runtime/** text eol=lf # The embedded expert profile is pinned by SHA-256 in the sources: the bytes in the working tree must be the bytes in the index on every platform. crates/deploy/data/expert-profile.bin -text binary -# CI entry points run on Linux runners: LF whatever the checkout host's autocrlf says (docs/ci-audit.md). +# CI entry points run on Linux runners: LF whatever the checkout host's autocrlf says. scripts/ci/** text eol=lf scripts/check-local.sh text eol=lf scripts/check-clippy-limits.sh text eol=lf diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index d7502ddf..4b872f08 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -29,7 +29,7 @@ jobs: - name: Tests run: cargo test --locked --manifest-path desktop-core/Cargo.toml - name: Lints - # --no-deps: the path dependencies (leleka-model-format, leleka-cuda-driver, leleka-runtime) carry reported Clippy debt of their own (docs/ci-audit.md) + # --no-deps: the path dependencies (leleka-model-format, leleka-cuda-driver, leleka-runtime) carry reported Clippy debt of their own run: cargo clippy --locked --manifest-path desktop-core/Cargo.toml --all-targets --no-deps -- -D warnings - name: Hardware smoke (no inference) # desktop-core ships six binaries and no default-run: name the one this smoke test runs diff --git a/.github/workflows/port.yml b/.github/workflows/port.yml index 523e6b4d..278bf5b2 100644 --- a/.github/workflows/port.yml +++ b/.github/workflows/port.yml @@ -1,6 +1,6 @@ name: Rust port -# Checks for the Rust port of the Original engine (docs/port-status.md). Everything here runs without a GPU, model +# Checks for the Rust port of the Original engine. Everything here runs without a GPU, model # weights or tokens. The existing "Linux" workflow is unchanged; the jobs below add the port-specific gates: # port-fast fmt, Clippy and tests on the host-buildable crates (scripts/check-local.sh --fast) # port-typecheck Linux-only crates (cuda-driver with the cuda-driver feature, leleka-runtime) type-checked, not run @@ -54,7 +54,7 @@ jobs: cargo clippy --locked --target x86_64-unknown-linux-gnu --no-deps -p leleka-cuda-model -p leleka-cuda-driver --features cuda-driver -p leleka-engine-qwen35-cuda -p leleka-runtime --all-targets -- -D warnings port-oracles: - # CPU oracle differentials: the Rust side against the UNMODIFIED Python tools (docs/offline-port.md) and the + # CPU oracle differentials: the Rust side against the UNMODIFIED Python tools and the # sampler host shim. Optional until it has run green on the hosted runner; the committed goldens are replayed by # port-fast regardless. runs-on: ubuntu-latest @@ -66,9 +66,22 @@ jobs: - name: Install pinned Rust run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy - name: Oracle Python environment (no model data) + # numpy 2.5.x needs Python >= 3.12 and the runner's distro Python is older, so the numpy pin follows the + # interpreter exactly as engine/strata/requirements.txt does (2.5.4 on 3.12+, 2.4.6 on 3.11, 2.2.6 below). + # The oracle differentials compare against recorded goldens with tolerances, not against a numpy build. run: | python3 -m venv "$RUNNER_TEMP/oracle-venv" - "$RUNNER_TEMP/oracle-venv/bin/pip" install --disable-pip-version-check numpy==2.5.4 PyYAML==6.0.3 tqdm==4.70.1 Jinja2==3.1.6 regex==2026.9.10 + cat > "$RUNNER_TEMP/oracle-requirements.txt" <<'EOF' + numpy==2.5.4; python_version >= "3.12" + numpy==2.4.6; python_version == "3.11" + numpy==2.2.6; python_version < "3.11" + PyYAML==6.0.3 + tqdm==4.70.1 + Jinja2==3.1.6 + regex==2026.9.10 + EOF + "$RUNNER_TEMP/oracle-venv/bin/python" --version + "$RUNNER_TEMP/oracle-venv/bin/pip" install --disable-pip-version-check -r "$RUNNER_TEMP/oracle-requirements.txt" - name: Fetch the pinned llama.cpp gguf-py run: | commit="$(sed -n 's/^LLAMA_CPP_COMMIT = "\(.*\)"$/\1/p' engine/strata/setup.py)" @@ -104,7 +117,13 @@ jobs: run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y docker.io - name: Linux test harness if: steps.present.outputs.present == 'true' + # The job runs in a container and uses the host's Docker daemon: the checkout path does not exist on that host, + # so the harness copies the source into the test container instead of bind-mounting it. + env: + LELEKA_TEST_COPY_SOURCE: '1' run: scripts/linux-tests/run.sh - name: Fake-libcuda mock gates (CPU-only ELF protocol tests of the driver) if: steps.present.outputs.present == 'true' + env: + LELEKA_TEST_COPY_SOURCE: '1' run: scripts/linux-tests/run.sh --mocks diff --git a/.github/workflows/product.yml b/.github/workflows/product.yml index ef77cc9f..d1259430 100644 --- a/.github/workflows/product.yml +++ b/.github/workflows/product.yml @@ -1,6 +1,6 @@ name: Product -# Builds and tests what actually ships (docs/ci-audit.md). The other workflows cover the legacy Strata-Next static CLI (linux.yml), +# Builds and tests what actually ships. The other workflows cover the legacy Strata-Next static CLI (linux.yml), # the host-buildable port crates (port.yml) and desktop-core (desktop.yml); none of them built the `leleka` deploy binary, ran the # tests of leleka-deploy, leleka-memory, leleka-runtime-client, leleka-runtime or leleka-cuda-driver, or compiled the six release # binaries. This job runs `scripts/check-local.sh --product`, the same command a developer runs locally: @@ -8,12 +8,12 @@ name: Product # - scripts/check-architecture.py: dependency direction between layers, adapter edges, no new .rs over 400 lines, source ratchets # (architecture.json is the policy, architecture-baseline.json the debt that may only fall; self-tests in check_architecture_test.py) # - cargo build --locked (every default-member) and the release build of leleka, leleka-api, leleka-inference, leleka-daemon, -# leleka-cli, leleka-seal-exec (docs/deploy.md section 8) +# leleka-cli, leleka-seal-exec # - cargo check of the CUDA-feature crates (leleka-cuda-driver --features cuda-driver, leleka-runtime) # - cargo test of the product crates; the deploy end-to-end tests run against scripts/ci/nvidia-smi, a hermetic stand-in # - rustfmt and Clippy -D warnings on the shipped crates; the known debt is reported (STRICT_DEBT=1 makes it fatal) # No GPU, model weights or token is used. A green run proves the product compiles, links and passes its CPU-side tests; it does not -# prove any GPU kernel, model quality or speed (docs/ci-audit.md, section "What CI cannot prove"). +# prove any GPU kernel, model quality or speed. on: push: diff --git a/.gitignore b/.gitignore index e1643bac..8482252b 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,8 @@ dist/ # The one binary kept in Git: upstream Strata's ranked expert profile (196,632 B, MIT, sha256 8f59b4aa...388975baf), embedded in `leleka` # (crates/deploy/src/expert_profile.rs; attribution in crates/deploy/data/expert-profile.NOTICE). Every other *.bin stays ignored. !crates/deploy/data/expert-profile.bin + +# LeaseVibe (generated, host-local) +/AGENTS.md +/.leasevibe.yaml +/.claude/hooks/ diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index cf3ce5e4..00000000 --- a/AGENTS.md +++ /dev/null @@ -1,58 +0,0 @@ -# Repository instructions - -Read `PROJECT_CHARTER.md` before changing architecture, performance policy, or scope. The charter is the source of truth for goals and milestones. - -## Priorities - -1. Preserve protocol correctness and successful task completion. -2. Preserve model quality and tool-call integrity. -3. Improve end-to-end agent throughput, then decode/prefill throughput. - -## Change rules - -- Keep production serving independent of Python. Python is allowed for offline conversion, calibration, experiments, and evaluations. -- Keep model weights, request captures, credentials, logs, and generated artifacts out of Git. Use external volumes or ignored local paths. Sanitize any fixture committed to the repository. -- Do not enable lossy optimizations by default until their separate quality gate passes. Mark experimental modes explicitly. Recorded exception: the 5090 profiles run the lossy route tail skip by default, an explicit owner decision of 2026-11-13 that overrode the open points of its quality gate (`docs/deploy.md` section 4). -- For non-lossy changes, compare greedy output or tensor values against the defined baseline and record numerical tolerances. -- Do not label a change as a performance improvement without paired A/B measurements on the same workload and a quality result. Record hardware, software, model digest, configuration, cache state, token counts, and distributions as required by the charter. -- Do not conflate a synthetic kernel gain with an end-to-end agent workload gain. Report both when relevant. -- Dependency direction, file sizes and source patterns are gated by `scripts/check-architecture.py` (policy `architecture.json`, debt `architecture-baseline.json`, run by `scripts/check-local.sh --product`). A number in the baseline may only fall; lower it with `--update-baseline`, never raise it without `--allow-increase` and a reason in review. -- Keep the Strata upstream commit and local changes traceable. Do not overwrite or silently replace the upstream provenance record. - -## Repository state - -The Strata source is present under `engine/strata/` at the commit recorded in `docs/upstream.md` and is not modified. `engine/strata` is the -reference (the "Original"); the product is the Rust/CUDA port of its Original mode17 serve path: - -* `crates/engine-qwen35-cuda` (the Qwen3.5 CUDA engine family: prefill, MTP speculative decode, expert tiers, KV streaming; `crates/leleka-runtime` is its facade), `crates/engine-core` (the pure engine domain: prefix cache, conversation policy, prompt plan, speculative-decoding policies, request lifecycle, the `EngineFamily` seam), `crates/engine-fake` (the scripted engine family for GPU-free tests), `crates/cuda-driver` - (CUDA Driver API, sealed PTX, NVML sampler; its pure host-side models are `crates/cuda-model`), `crates/leleka-memory` (memory governor, pressure gate, telemetry), `desktop-core` and - `crates/runtime-client` (the gRPC contract between the engine process and the gateway), `control-plane` (HTTP/Responses gateway), `crates/deploy` - (the `leleka` binary: `up/run/status/verify`, memory profiles, resource presets). -* The layers (L0 to L4), the ports, how to add an engine family and what the architecture gates check: `docs/architecture/hexagonal.md`. -* Measured on an RTX 5090 server with real Codex CLI sessions (`docs/e2e-run.md`, `docs/ledger.md`, `docs/quality-gate.md`, `docs/prefix-cache.md`, - `docs/deploy.md`, `docs/roofline.md`); the RTX 3080 laptop is a secondary, experimental target (`docs/laptop-profile.md`). -* The port is complete for the 5090 serve path; open work is listed in `docs/port-remaining.md` and the ledger. -* The CPU/iGPU/NPU runtime for gpt-oss (`crates/cpu-*`, `gptoss*`, `harmony`, `igpu*`, `npu-*`, `gguf`, `kar-codec`; `docs/cpu-runtime.md`) is served through the same - control plane: `codec::TextCodec` selects the family (Qwen3.5 or gpt-oss/Harmony) and `engine.extra_workers` runs a worker pool (`docs/worker-pool.md`). - The pool, `lazy_load`/`idle_unload_s`, `vision` and the `runtime` block are separate modes; the config rejects combining them (`docs/api-contract.md`). - -## Worktrees - -- Create worktrees inside the main repository's git directory, never as sibling folders of `~/work`: `scripts/dev/worktree.sh new []` makes `.git/wt/`. The files are ordinary; only the location is hidden from the file listing. -- Clean up when a branch has been merged: `scripts/dev/worktree.sh clean` lists the clean, merged worktrees and `--yes` removes them. Uncommitted changes block the removal; commit them to the branch first. Do this at the end of every task that created a worktree and before starting a new batch, so no more than a handful exist at a time. -- Build output (`target/`, `dist/`) lives in the worktree and goes with it; a removed worktree never deletes its branch. - -## Workspace layout - -One folder per machine (owner rule, 2026-10-29). Outside it, read only: no creating, moving, renaming or deleting anything, and no relocating other people's files. - -- Laptop: `C:\Users\pavel\work\leleka` (worktrees, build output and run directories under `.git/wt`). Never create, list or clean sibling folders of the repository, and keep WSL builds inside it too (`CARGO_TARGET_DIR` inside the worktree). -- 5090 server (`rnr5090`): `~/work/leleka/` only, the same name as on the laptop. It is a symlink to `/data/leleka-e2e/` because the root disk is small; the data lives on `/data`. Do not add anything to `~/work` itself or to any other folder. Known exception until the holder is re-homed: the GPU queue (`~/work/gpu-runs/holder2/jobs/` stubs and `PRIORITY`) is written there, nothing else. -- Models live inside the work folder too (owner decision, 2026-10-29): server `~/work/leleka/models/{leleka-gates,deepseek-v41-flash}/` (absolute `/home/para/work/leleka/models/...`), laptop `C:\Users\pavel\work\leleka\models\`. Scripts, profiles and docs name those paths; a model path outside the work folder is a bug. -- Name each path after its task (`` or `-`); one directory per task, not one per attempt. -- Clean up your own paths at the end of the task. Do not hard-delete: anything deletable goes into the `garbage/` folder inside the work folder (laptop `leleka/garbage`, server `~/work/leleka/garbage`) with a line in `garbage/LOG.txt`. The owner empties it. -- Evidence cited in a task record keeps its path until the cited change is merged; after a move, update the record with the new path. -- An agent's final report lists every path it created, and any path outside the places above is moved in before the task is closed. -- Measurement inputs are not scratch: a corpus, expert profile, prompt set, binary or helper script that a measurement depends on lives in one named directory (server: `/data/leleka-e2e/decode/` or the task's own directory), is frozen read-only, and is recorded with its sha256 in a manifest and in the run metadata. A run refuses to start when an input is missing or its digest differs. Never read an input from `~/work`, a home directory or a sibling folder that nobody owns. The 2026-10-29 incident: the 245k corpus lived in an unowned folder, a cleanup removed it, and the "256k" session silently became ~300 tokens. - -Read `engine/strata/AGENTS.md` before modifying imported engine code. diff --git a/Cargo.toml b/Cargo.toml index 2bd10733..97e0a8cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ unsafe_code = "forbid" [workspace.lints.clippy] all = "warn" -# Opt-in profile for paired A/B builds (STRA-245 parity audit, docs/experiments/parity-audit-5090.md item 10). The workspace has no +# Opt-in profile for paired A/B builds (STRA-245 parity audit). The workspace has no # [profile] section, so every shipped binary (bin-e2e4, crates/deploy) is the cargo release default: opt-level 3, no LTO, # 16 codegen units, panic=unwind, no RUSTFLAGS and no target-cpu (the last on purpose: the CPU kernels select their GGML # arithmetic branches with cfg!(target_feature), see crates/native-cpu-expert/src/rust_ggml_native.rs, so target-cpu would change bits). diff --git a/PORT-GAPS-MODE17.md b/PORT-GAPS-MODE17.md index 015cd245..3a7c141e 100644 --- a/PORT-GAPS-MODE17.md +++ b/PORT-GAPS-MODE17.md @@ -10,7 +10,7 @@ This is a bounded core-path ledger, not a whole-project completion certificate. | Original source / function | Current Rust boundary | Required completion | | --- | --- | --- | | `src/core/mtp.cpp:143` `MtpDrafter::load`; `:380` `bind`; `:677` `kv_restore`; `include/strata/core/mtp.hpp` `idle/device/tensor_*` | SOURCE-COMPLETE, NOT GPU-RUN (2026-10-14, branch `claude/port-mtp-loader`). `original_mtp_rt.rs` reads dense.txt/dense.bin/experts.bin/draft_vocab.bin; `original_mtp_bank.rs` places them (Original order, nine-name check last); `original_mtp_loader.rs` plans geometry/session/KV/coupled and admits the retained ring; `original_mtp_draft_head.rs` gathers the subset head; `original_mtp_actor_loaded.rs` adopts the genuine drafter and links `idle/device/kv_restore/set_*/draft*/coupled`. Runtime: `RetainedOriginalMtpWeights::from_rt_bank`, `OriginalMtpFullOwner::assemble_rt`, `OriginalPromptExecutor::select_rt_mtp` and the actor-driven `draft_committed_mtp`/`draft_first_committed_mtp`. | Remaining is GPU-only evidence: run the ignored `original_mtp_bank_gpu` tests (`LELEKA_MTP_RT_BANK_GPU=yes`), a real-pack load, and compare drafts with the Original. `OriginalServeStack::open` (`qwen_forward/original_serve_stack.rs`) now calls `select_rt_mtp` (option `--mtp-rt-dir`) or the pinned-pack assembly, and the serve loop drives `draft_committed_mtp` (`OriginalServeHost::draft_committed`); `draft_first` stays CLI-only (the serve loop never reaches it). Not repeated: Original `cudaMemset(cring_, 0xff)`; the Original single-allocation `dense_` (each indexed tensor is its own allocation, same total bytes); `tensor_f32/bf16/q8` host accessors (roles are the retained `Rc` bank). | -| `src/core/verify.cpp:405` `record_window`, `:925` `capture`, `:988` `capture_commit`, `:1054` `run` | `original_verify.rs:235` defines `OriginalVerifyGraphResources`; `original_verify_schedule.rs` owns real streams/graphs/doorbells and accepts a caller recording closure. The concrete aggregate is `OriginalVerifyWindowResources` (`original_verify_window_ops.rs`). | `OriginalVerifyWindowOps` now has capture-time producers for every former `UNBOUND_PRODUCERS` entry (pure planners over SHA-pinned sealed PTX: projections/head, GR, GDN, QSA, MoE; unit-tested against verify.cpp order). Still open: seal `original_verify_window_moe_experts.ptx` and `original_verify_window_qsa_gate.ptx` (`docs/cuda-seal-plan-additions-window.json`; the window fails closed with those names until then), GPU smokes/golden comparisons per kernel and for a whole window, the fast-math re-seal question listed in that JSON, and the hardware run. The runtime-side wiring (weights, QSA/PLE journals, CPU pool callbacks, graph registration before `run`) is SOURCE-WIRED, NOT GPU-RUN on `claude/port-serve-host`: `original_serve_verifier::assemble` builds the canonical GDN image, the QSA journal over the prompt executor's twelve resident owners, the PLE history and the window/commit aggregates per decode phase; `original_serve_pool` is the CPU callback (all-CPU expert tier: the driver publishes the empty plan). The asset probe (`original_serve_asset_status`) lists the unsealed assets and any producer still unbound, so `--backend-mode auto` stays on the preview path until they are sealed and `original` refuses naming them. | +| `src/core/verify.cpp:405` `record_window`, `:925` `capture`, `:988` `capture_commit`, `:1054` `run` | `original_verify.rs:235` defines `OriginalVerifyGraphResources`; `original_verify_schedule.rs` owns real streams/graphs/doorbells and accepts a caller recording closure. The concrete aggregate is `OriginalVerifyWindowResources` (`original_verify_window_ops.rs`). | `OriginalVerifyWindowOps` now has capture-time producers for every former `UNBOUND_PRODUCERS` entry (pure planners over SHA-pinned sealed PTX: projections/head, GR, GDN, QSA, MoE; unit-tested against verify.cpp order). Still open: seal `original_verify_window_moe_experts.ptx` and `original_verify_window_qsa_gate.ptx` (`crates/cuda-driver/seal-plans/cuda-seal-plan-additions-window.json`; the window fails closed with those names until then), GPU smokes/golden comparisons per kernel and for a whole window, the fast-math re-seal question listed in that JSON, and the hardware run. The runtime-side wiring (weights, QSA/PLE journals, CPU pool callbacks, graph registration before `run`) is SOURCE-WIRED, NOT GPU-RUN on `claude/port-serve-host`: `original_serve_verifier::assemble` builds the canonical GDN image, the QSA journal over the prompt executor's twelve resident owners, the PLE history and the window/commit aggregates per decode phase; `original_serve_pool` is the CPU callback (all-CPU expert tier: the driver publishes the empty plan). The asset probe (`original_serve_asset_status`) lists the unsealed assets and any producer still unbound, so `--backend-mode auto` stays on the preview path until they are sealed and `original` refuses naming them. | | `mtp.cpp` `draft/draft_first` and `verify.cpp` `run/commit/wait_commit`, used together by mode17 generation | SOURCE-WIRED, NOT GPU-RUN. `OriginalServeEngine` implements `OriginalSpecEngine` over `NativeServePort`, which binds the driver `OriginalVerifier`; `OriginalServeHost` (`original_serve_host.rs`) supplies the owners (window PLE rows, penalty-history sampling, expert pool, lineage ledger, session publication of the accepted prefix, MTP history/restore/drain) and `OriginalServeStack` drives prompt + decode. `OriginalServeSettings::controller` is called by the stack; `--backend-mode` selects it in the serving owner. Commit and draft are serialized (the commit event completes and the session is published before the draft launches), so the Original's commit/draft overlap is not reproduced. | Hardware run of `backend_original_serve_smoke.rs` (`LELEKA_ORIGINAL_SERVE_SMOKE=yes`), then parity and a keep-the-overlap pass. | | `include/strata/core/verify.hpp` `set_stage/set_next`; `src/core/verify.cpp:191,1054,1382,1412`; `core/on_device.hpp` | `OriginalVerifier` loops all 48 layers, has no next-stage owner or stage handoff fields. Context identity exists, but the unselected MTP actor cannot infer an actual current CUDA device ordinal. | Port stage bounds, mapped portable R+pending-bo+inject handoff, next-user CPU dispatch and last-stage head/sampling/final_R/commit forwarding. This is an absent multi-GPU mode17 leaf, not a single-device quality defect. | | `verify.cpp:137,158,899,1323,1422` public release/diag/profile/logprob/logit APIs | Internal Rust bounded wait release, commit event and completed-row bridge are present. No equivalent public diagnostic/watchdog registry, profile report, window_logprobs or copy_logits API was found in the inspected Original Rust modules. | Expose the actual live verifier release/diagnostic owner; port literal GPU-stage stamps and completed logit/logprob readout (including LOGPOS_TOPK). Keep capture-only graphs inadmissible for readout. Do not call the existing internal release absent. | @@ -21,7 +21,7 @@ This is a bounded core-path ledger, not a whole-project completion certificate. mapped/fallback embedding, T1..8 head rows, request sampling/history and MTP head-weight loans. `model-format/src/gguf_native_head.rs` has shard/architecture and `strata-embd` override parsing. The owners are bound by `OriginalServeStack`/`OriginalServeHost` - (see docs/original-serve.md); the remaining gap is the unbound window producers and the GPU run. + (see spec node original-serve.md); the remaining gap is the unbound window producers and the GPU run. - NativeHead's earlier penalties-off empty-history refusal is already corrected in current `native_head.rs:140..158`; do not reopen that stale finding. - Verifier GDN/QSA accepted-prefix journals, stream release and async commit event diff --git a/README.md b/README.md index 085bfa5b..0adac84c 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,11 @@ Leleka is a Rust/CUDA inference runtime for coding agents. Release **0.1** serves one model, **Qwen3.8-Flash-Next IQ3_S** (KAR level-2 PLE, MTP speculative decode), on **one RTX 5090 (32 GB)** at **262,144 tokens of context**, to Codex CLI and other clients over the Responses, Chat Completions and Messages APIs. It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (reference copy in `engine/strata/`, pinned at -upstream `41cf05a0`, see `docs/upstream.md`). Serving needs no Python and no CUDA toolkit on the host. +upstream `41cf05a0`, see `engine/upstream.md`). Serving needs no Python and no CUDA toolkit on the host. **Status of 0.1.** It runs real Codex sessions to completion and decodes about 155 tok/s on the 245k-token benchmark of the 5090 server (section "Numbers"). -It is **not a formally quality-gated profile**, only the RTX 5090 is supported, and the limits below are real. Release notes: `docs/release/RELEASE-NOTES-5090-v0.1.md`; -every gate and its evidence: `docs/release/5090-v0.1-checklist.md`. +It is **not a formally quality-gated profile**, only the RTX 5090 is supported, and the limits below are real. Release notes: `spec node release/RELEASE-NOTES-5090-v0.1.md`; +every gate and its evidence: `spec node release/5090-v0.1-checklist.md`. ## Requirements @@ -30,21 +30,21 @@ curl -H "Authorization: Bearer $(cat STATE/api-key)" http://127.0.0.1:8081/v1/mo ``` The API listens on loopback only (use an SSH tunnel); the key is in `STATE/api-key`. Codex CLI: `wire_api = "responses"`, `base_url = "http://127.0.0.1:8081/v1"`, `web_search = "disabled"`. -Details, every flag, upgrade and rollback: `docs/deploy.md`, `docs/unattended.md` (running it as a boot-time service: `scripts/ops/`, installed by the owner of the machine, never by the release). +Details, every flag, upgrade and rollback: `spec node deploy.md`, `spec node unattended.md` (running it as a boot-time service: `scripts/ops/`, installed by the owner of the machine, never by the release). Upgrade: stop the service, keep a copy of `STATE/*.json`, unpack the new release, run its `install.sh` with the same flags. Rollback: restore the copies and run the previous release's `install.sh`. ## Numbers (measured, paired, one workload) Decode tok/s on the frozen 245k-token corpus (5 turns x 300 output tokens, greedy, RTX 5090, Ryzen 9 9950X3D), ours against vanilla Strata 0.2.6 on fresh boots, vanilla in its good -huge-page state (`docs/experiments/baseline-pair-5090.md`, section 10, 3 balanced blocks): **ours 155.4** (sd 2.4), vanilla v1 (its shipped lossy defaults) 137.0 (ahead of it in 3 of 3 blocks, +13.5 %), +huge-page state (`spec node experiments/baseline-pair-5090.md`, section 10, 3 balanced blocks): **ours 155.4** (sd 2.4), vanilla v1 (its shipped lossy defaults) 137.0 (ahead of it in 3 of 3 blocks, +13.5 %), vanilla v2 (lossless-comparable) 144.7 (ahead in **2 of 3** blocks, +9.2 %; vanilla v2 is bimodal and ran 171.2 once, 10.8 % faster than ours). Later changes: the faster draft attention is bitwise identical and shortens a round by 2.7 % (tok/s +0.5 % +- 0.6 %, not significant); the window policy default +1.1 % +- 1.2 % (not resolved, no speedup claimed); the single-copy memory layout -(`docs/kar-sparse-memfd.md`) is identical in output (2057/2057 logprob rows, 1036/1036 draft traces) and frees 36.6 GiB of RAM at 245k (MemAvailable 8.5 to 45.1 GiB; tok/s +0.58 %, n.s.). +(`spec node kar-sparse-memfd.md`) is identical in output (2057/2057 logprob rows, 1036/1036 draft traces) and frees 36.6 GiB of RAM at 245k (MemAvailable 8.5 to 45.1 GiB; tok/s +0.58 %, n.s.). These are decode speeds of a benchmark, not agent-task times. ## Quality and limits -* Not bit-identical to the Original; deviations are inside the Original's own rounding envelope where tested (`docs/quality-gate.md`), and **there is no 245k port-versus-Original equality gate yet** (STRA-337). +* Not bit-identical to the Original; deviations are inside the Original's own rounding envelope where tested (`spec node quality-gate.md`), and **there is no 245k port-versus-Original equality gate yet** (STRA-337). KAR level-2 PLE, chain kernels, prefill chunk 8192, request-end prefix checkpoints and the adaptive expert tier have no 256k gate. All evidence is greedy. * Lossy modes are **off**: route tail skip gave +15 % decode but failed its quality gate; keyless KV failed too. Tool calls are the model's: malformed ones are refused, not repaired. * One generation at a time (queue of 16); images and `reasoning_budget_tokens` are refused; RTX 3080 and Windows are not part of 0.1; no multi-hour soak on the release commit (post-release feedback). @@ -78,7 +78,7 @@ What the service is doing, and why a request was slow or failed, is in its logs; - `control-plane/`, `desktop-core/` — the HTTP/Responses gateway (`leleka-api`) and the engine/daemon processes. - `engine/strata/` — the pinned upstream Strata, the reference (unmodified by Leleka). - `deploy/`, `scripts/` — profiles, service templates, release packager (`scripts/release/`), test and measurement tooling (Python is allowed there, never in serving). -- `PROJECT_CHARTER.md`, `docs/` — requirements, provenance, decisions, gates and measurements. Architecture: `docs/architecture/hexagonal.md`. +- `PROJECT_CHARTER.md`, the LeaseVibe spec (imported repository documentation) — requirements, provenance, decisions, gates and measurements. Architecture: spec node `architecture/hexagonal.md`. Model weights, request captures, credentials, logs and generated artifacts stay outside Git. @@ -87,9 +87,9 @@ Model weights, request captures, credentials, logs and generated artifacts stay ```sh cargo test --workspace --locked cargo clippy --workspace --all-targets --all-features -- -D warnings -scripts/release/package-5090.sh check # the release gates; `package` builds the release set (docs/release/5090-v0.1-checklist.md) +scripts/release/package-5090.sh check # the release gates; `package` builds the release set (spec node release/5090-v0.1-checklist.md) ``` ## Licence -MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `docs/release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`engine/strata/LICENSE`). +MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`engine/strata/LICENSE`). diff --git a/crates/cuda-driver/seal-plans/cuda-seal-plan-additions-experimental.json b/crates/cuda-driver/seal-plans/cuda-seal-plan-additions-experimental.json index fffc6a97..2a9107ca 100644 --- a/crates/cuda-driver/seal-plans/cuda-seal-plan-additions-experimental.json +++ b/crates/cuda-driver/seal-plans/cuda-seal-plan-additions-experimental.json @@ -1,222 +1,222 @@ -{ - "schema": 1, - "note": "Additions for the experimental Strata modes. None of these six .cu files has been compiled; PINS in experimental.rs are all zero and admit_ptx refuses every asset until Root builds the PTX and freezes the digests. Flags follow engine/strata/CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list (native_* only) and the strata_kernels target adds no other CUDA flag besides CUDA_STANDARD 17, so the build is precise (no --use_fast_math) with default -fmad contraction.", - "assets": [ - { - "cu": "crates/cuda-driver/src/experimental_kv_q4.cu", - "cu_pin": { - "sha256": "378058e82084b697e13e8ac3cd25520372d2848ed3ebec78ac5e369ee9a91720", - "bytes": 17507 - }, - "ptx": "crates/cuda-driver/src/experimental_kv_q4.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). FWHT-256 + Q4_0 append (step/batched) + gather; Original kv_q4.cu precise (default flags, not in the fast-math list); K8V4's Q4_0 V half and rotated INT8's FWHT", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/kv_q4.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[0].source_sha256", - "PINS[0].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "74665b016fde9dc4f50a36e62cbf2e578c735e48e3be51b70734e9e53942cde7", - "seal_length": 36319 - }, - { - "cu": "crates/cuda-driver/src/experimental_kv_q8.cu", - "cu_pin": { - "sha256": "007f00692c702313a79dee0f1aa433c3412f6b4d73de620b02e136d960203c9f", - "bytes": 13448 - }, - "ptx": "crates/cuda-driver/src/experimental_kv_q8.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). INT8 append (K+V, K8V4 K half, V-only) + gather; Original kv_q8.cu precise", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/kv_q8.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[1].source_sha256", - "PINS[1].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "43c308960830833e29329907e27be5203ef3bc89cc7d0a9176270dc18732d600", - "seal_length": 32973 - }, - { - "cu": "crates/cuda-driver/src/experimental_kv_stream.cu", - "cu_pin": { - "sha256": "8c9fe1c0e4164ac2b40304a389710615829842a2ac47ab4b4ef92b3ace5d5a4f", - "bytes": 12456 - }, - "ptx": "crates/cuda-driver/src/experimental_kv_stream.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). CLOCK residency resolver, block copy, ring table, u4 copy; Original kv_stream.cu precise; integer only", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/kv_stream.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[2].source_sha256", - "PINS[2].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "4f71e720e0ca950d321ba3cbb20082ca473e9839b76d08898e95b6623bfffe50", - "seal_length": 34329 - }, - { - "cu": "crates/cuda-driver/src/experimental_keyless.cu", - "cu_pin": { - "sha256": "77c50e5baff842e31f0d71624a5706f46ed74a56cdfc5e4211086d2ef08671c5", - "bytes": 1987 - }, - "ptx": "crates/cuda-driver/src/experimental_keyless.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). per-head query routing (fmaf-ordered 256x256); Original keyless.cu precise", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/keyless.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[3].source_sha256", - "PINS[3].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "1ab8b8156e8c824131c00cecda177fe57d74b286a02b7e5afdfa39acadaa33e6", - "seal_length": 3760 - }, - { - "cu": "crates/cuda-driver/src/experimental_qsa_attn.cu", - "cu_pin": { - "sha256": "907ffc8f7504efd0655d2311ac4787fb131dfd1ef7cbf1aebfdddf1b9d31c505", - "bytes": 23119 - }, - "ptx": "crates/cuda-driver/src/experimental_qsa_attn.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). experimental attention modes 2/3/4 + merge; Original qsa_decode_attn.cu precise (expf/exp2f exact, not in the fast-math list)", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/qsa_decode_attn.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[4].source_sha256", - "PINS[4].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "5623a5ae9b2ebd2fa010c334367ffc54879ac6df76aef08381dbd32b0f7ef311", - "seal_length": 128247 - }, - { - "cu": "crates/cuda-driver/src/experimental_cvec.cu", - "cu_pin": { - "sha256": "d4fe221b11569db73247644bb79118b34d040b49c14897e0bac158dcd4ca356e", - "bytes": 4783 - }, - "ptx": "crates/cuda-driver/src/experimental_cvec.ptx", - "flags": [ - "-ptx", - "-O3", - "-arch=sm_120", - "-std=c++17" - ], - "policy": "EXPERIMENTAL, off by default (OptIn). control-vector apply; Original cvec.cu default flags (its own __expf in sigmoidf_ is explicit in the source)", - "direct_original_headers": [], - "original": "engine/strata/src/kernels/cuda/cvec.cu", - "rust_consumers": { - "experimental.rs": { - "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", - "bytes": 36646 - }, - "experimental_gpu.rs": { - "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", - "bytes": 32785 - } - }, - "rust_fields_to_fill": { - "experimental.rs": [ - "PINS[5].source_sha256", - "PINS[5].ptx_sha256" - ] - }, - "encoding": "concat_include_str", - "seal_sha256": "193add5cb448f5e193f20ff248ca4459abb962b472663c00d18941313bfa3ebc", - "seal_length": 28943 - } - ] -} +{ + "schema": 1, + "note": "Additions for the experimental Strata modes. None of these six .cu files has been compiled; PINS in experimental.rs are all zero and admit_ptx refuses every asset until Root builds the PTX and freezes the digests. Flags follow engine/strata/CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list (native_* only) and the strata_kernels target adds no other CUDA flag besides CUDA_STANDARD 17, so the build is precise (no --use_fast_math) with default -fmad contraction.", + "assets": [ + { + "cu": "crates/cuda-driver/src/experimental_kv_q4.cu", + "cu_pin": { + "sha256": "378058e82084b697e13e8ac3cd25520372d2848ed3ebec78ac5e369ee9a91720", + "bytes": 17507 + }, + "ptx": "crates/cuda-driver/src/experimental_kv_q4.ptx", + "flags": [ + "-ptx", + "-O3", + "-arch=sm_120", + "-std=c++17" + ], + "policy": "EXPERIMENTAL, off by default (OptIn). FWHT-256 + Q4_0 append (step/batched) + gather; Original kv_q4.cu precise (default flags, not in the fast-math list); K8V4's Q4_0 V half and rotated INT8's FWHT", + "direct_original_headers": [], + "original": "engine/strata/src/kernels/cuda/kv_q4.cu", + "rust_consumers": { + "experimental.rs": { + "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", + "bytes": 36646 + }, + "experimental_gpu.rs": { + "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", + "bytes": 32785 + } + }, + "rust_fields_to_fill": { + "experimental.rs": [ + "PINS[0].source_sha256", + "PINS[0].ptx_sha256" + ] + }, + "encoding": "concat_include_str", + "seal_sha256": "74665b016fde9dc4f50a36e62cbf2e578c735e48e3be51b70734e9e53942cde7", + "seal_length": 36319 + }, + { + "cu": "crates/cuda-driver/src/experimental_kv_q8.cu", + "cu_pin": { + "sha256": "007f00692c702313a79dee0f1aa433c3412f6b4d73de620b02e136d960203c9f", + "bytes": 13448 + }, + "ptx": "crates/cuda-driver/src/experimental_kv_q8.ptx", + "flags": [ + "-ptx", + "-O3", + "-arch=sm_120", + "-std=c++17" + ], + "policy": "EXPERIMENTAL, off by default (OptIn). INT8 append (K+V, K8V4 K half, V-only) + gather; Original kv_q8.cu precise", + "direct_original_headers": [], + "original": "engine/strata/src/kernels/cuda/kv_q8.cu", + "rust_consumers": { + "experimental.rs": { + "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", + "bytes": 36646 + }, + "experimental_gpu.rs": { + "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", + "bytes": 32785 + } + }, + "rust_fields_to_fill": { + "experimental.rs": [ + "PINS[1].source_sha256", + "PINS[1].ptx_sha256" + ] + }, + "encoding": "concat_include_str", + "seal_sha256": "43c308960830833e29329907e27be5203ef3bc89cc7d0a9176270dc18732d600", + "seal_length": 32973 + }, + { + "cu": "crates/cuda-driver/src/experimental_kv_stream.cu", + "cu_pin": { + "sha256": "8c9fe1c0e4164ac2b40304a389710615829842a2ac47ab4b4ef92b3ace5d5a4f", + "bytes": 12456 + }, + "ptx": "crates/cuda-driver/src/experimental_kv_stream.ptx", + "flags": [ + "-ptx", + "-O3", + "-arch=sm_120", + "-std=c++17" + ], + "policy": "EXPERIMENTAL, off by default (OptIn). CLOCK residency resolver, block copy, ring table, u4 copy; Original kv_stream.cu precise; integer only", + "direct_original_headers": [], + "original": "engine/strata/src/kernels/cuda/kv_stream.cu", + "rust_consumers": { + "experimental.rs": { + "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", + "bytes": 36646 + }, + "experimental_gpu.rs": { + "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", + "bytes": 32785 + } + }, + "rust_fields_to_fill": { + "experimental.rs": [ + "PINS[2].source_sha256", + "PINS[2].ptx_sha256" + ] + }, + "encoding": "concat_include_str", + "seal_sha256": "4f71e720e0ca950d321ba3cbb20082ca473e9839b76d08898e95b6623bfffe50", + "seal_length": 34329 + }, + { + "cu": "crates/cuda-driver/src/experimental_keyless.cu", + "cu_pin": { + "sha256": "77c50e5baff842e31f0d71624a5706f46ed74a56cdfc5e4211086d2ef08671c5", + "bytes": 1987 + }, + "ptx": "crates/cuda-driver/src/experimental_keyless.ptx", + "flags": [ + "-ptx", + "-O3", + "-arch=sm_120", + "-std=c++17" + ], + "policy": "EXPERIMENTAL, off by default (OptIn). per-head query routing (fmaf-ordered 256x256); Original keyless.cu precise", + "direct_original_headers": [], + "original": "engine/strata/src/kernels/cuda/keyless.cu", + "rust_consumers": { + "experimental.rs": { + "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", + "bytes": 36646 + }, + "experimental_gpu.rs": { + "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", + "bytes": 32785 + } + }, + "rust_fields_to_fill": { + "experimental.rs": [ + "PINS[3].source_sha256", + "PINS[3].ptx_sha256" + ] + }, + "encoding": "concat_include_str", + "seal_sha256": "1ab8b8156e8c824131c00cecda177fe57d74b286a02b7e5afdfa39acadaa33e6", + "seal_length": 3760 + }, + { + "cu": "crates/cuda-driver/src/experimental_qsa_attn.cu", + "cu_pin": { + "sha256": "907ffc8f7504efd0655d2311ac4787fb131dfd1ef7cbf1aebfdddf1b9d31c505", + "bytes": 23119 + }, + "ptx": "crates/cuda-driver/src/experimental_qsa_attn.ptx", + "flags": [ + "-ptx", + "-O3", + "-arch=sm_120", + "-std=c++17" + ], + "policy": "EXPERIMENTAL, off by default (OptIn). experimental attention modes 2/3/4 + merge; Original qsa_decode_attn.cu precise (expf/exp2f exact, not in the fast-math list)", + "direct_original_headers": [], + "original": "engine/strata/src/kernels/cuda/qsa_decode_attn.cu", + "rust_consumers": { + "experimental.rs": { + "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", + "bytes": 36646 + }, + "experimental_gpu.rs": { + "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", + "bytes": 32785 + } + }, + "rust_fields_to_fill": { + "experimental.rs": [ + "PINS[4].source_sha256", + "PINS[4].ptx_sha256" + ] + }, + "encoding": "concat_include_str", + "seal_sha256": "5623a5ae9b2ebd2fa010c334367ffc54879ac6df76aef08381dbd32b0f7ef311", + "seal_length": 128247 + }, + { + "cu": "crates/cuda-driver/src/experimental_cvec.cu", + "cu_pin": { + "sha256": "d4fe221b11569db73247644bb79118b34d040b49c14897e0bac158dcd4ca356e", + "bytes": 4783 + }, + "ptx": "crates/cuda-driver/src/experimental_cvec.ptx", + "flags": [ + "-ptx", + "-O3", + "-arch=sm_120", + "-std=c++17" + ], + "policy": "EXPERIMENTAL, off by default (OptIn). control-vector apply; Original cvec.cu default flags (its own __expf in sigmoidf_ is explicit in the source)", + "direct_original_headers": [], + "original": "engine/strata/src/kernels/cuda/cvec.cu", + "rust_consumers": { + "experimental.rs": { + "sha256": "efdff8bf38d53c7b3825316a86169a56c8d3ca166e39a2ed889872de52c15981", + "bytes": 36646 + }, + "experimental_gpu.rs": { + "sha256": "8ef8c9a74092e2b273c9caa49a6af7d190f844d139ffc89a61f038690d2131b4", + "bytes": 32785 + } + }, + "rust_fields_to_fill": { + "experimental.rs": [ + "PINS[5].source_sha256", + "PINS[5].ptx_sha256" + ] + }, + "encoding": "concat_include_str", + "seal_sha256": "193add5cb448f5e193f20ff248ca4459abb962b472663c00d18941313bfa3ebc", + "seal_length": 28943 + } + ] +} diff --git a/engine/upstream.md b/engine/upstream.md new file mode 100644 index 00000000..e27a68f8 --- /dev/null +++ b/engine/upstream.md @@ -0,0 +1,178 @@ +# Strata upstream provenance + +**Status:** `engine/strata/` was brought to upstream `41cf05a0` (engine 0.1.50, app 0.2.5) on 2026-10-25 on branch +`claude/upstream-sync`, with the local patches re-applied. The previous pin (`d9ab8435`, engine 0.1.35) is kept below and in Git +history (`570201a:engine/strata`). Nothing was pushed. The quality-gate reference build (`stra169-ladder` Original) stays a build of the +OLD pin plus the old local patches; the new subtree is not that reference (see "What this does to the quality reference"). + +## Current pin + +| Field | Value | +| --- | --- | +| Upstream repository URL | https://github.com/Niko1221/Strata.git | +| Upstream commit SHA | `41cf05a06a25dd29103b7b27a2279a3f60c21876` | +| Upstream commit date | 2026-10-25 11:35 +0100 ("README (all 7 languages): models in the order Qwen3.8-Flash-Next, Qwen3.6-35B-A3B, DeepSeek V4.1-Flash") | +| Upstream version at the pin | engine and Control 0.1.50, Terminal and app 0.2.5 (`1aff6d14`, 2026-10-24) | +| Upstream tree object of the pin | not recorded (the subtree is the pin plus local patches and omissions; the exact differences are listed below) | +| Local repository path | `engine/strata/` | +| Update date | 2026-10-25 | +| Update method | documented tree replacement: 3-way `git merge-tree` of the old subtree against the new upstream, base = the old pin (see "How this update was made") | +| Hosted project repository URL | https://github.com/paveldhq/leleka-api (private) | +| Engine build instructions | `scripts/build-cpu.sh` for source checks (needs network once: it fetches llama.cpp `3cf03257f` through CMake FetchContent); CUDA builds: see `deploy/README.md` and `docs/build-validation.md`. Upstream's `packaging/build_cuda_linux.sh` and `packaging/build_dsv41_cuda.sh` are the reference recipes and have not been run here | + +## Pin history + +| Pin | Upstream commit | Date | Engine | In this repository | +| --- | --- | --- | --- | --- | +| 1 (initial import) | `d9ab8435f654c368c586340d490915f6addf56a3` | 2026-10-02 | 0.1.35 | `engine/strata/` up to `570201a` (git subtree merge `c4e2137` of squash `906afc5de9dd` in the pre-squash history; later squashed into `4013e0c`) | +| 2 (this update) | `41cf05a06a25dd29103b7b27a2279a3f60c21876` | 2026-10-25 | 0.1.50 | `engine/strata/` on `claude/upstream-sync` | + +**Upstream rewrote its history.** `d9ab8435` is not an ancestor of upstream `origin/main` (`git merge-base --is-ancestor` fails). Its +tree is identical (`git diff` is empty, tree `487c4cc0`) to upstream commit `5b734e42` ("Engine 0.1.35", same date), which is an +ancestor of `41cf05a0`. So the real distance from the old pin to the new one is 3630 commits (`git rev-list 5b734e42..origin/main`), not +the 4175 that `git rev-list d9ab8435..origin/main` prints. Both SHAs identify the same source tree; record both when comparing. + +The local Git remote `strata-upstream` points to the URL above. Do not silently advance to whatever happens to be latest: choose a +specific commit, fetch it, review the diff from the pin, and update this file in the same commit. + +## How this update was made (repeat it the same way) + +The pre-squash `git subtree` metadata does not exist in this repository's history (the project history was rebuilt from snapshots), +so `git subtree pull` has nothing to anchor on. The update therefore used a tree replacement that still keeps a true 3-way merge: + +1. In a scratch clone of upstream: `base` = tree of the old pin, `ours` = `git rev-parse 570201a:engine/strata` (the old subtree with + the local patches), `theirs` = upstream `41cf05a0`. +2. `git merge-tree --write-tree --merge-base= `; conflicts were resolved by hand (below); the result was checked by + listing every blob that differs from upstream `41cf05a0` (only the 21 patched files, the 4 added files and the left-out files differ). +3. The result tree went into `engine/strata/` with `git read-tree --prefix=engine/strata/ -u` (`core.autocrlf=false`, LF kept), then the + left-out files were removed from the index and the working tree. +4. `docs/upstream/local-patches-on-0.1.35.patch` is the patch that was re-applied (old pin to old subtree, 25 files); + `docs/upstream/local-patches-on-0.1.50.patch` is the same patches as they stand on the new pin (new pin to new subtree, 25 files). + The next update should treat the second file as its `ours` side: the merge base is then `41cf05a0`. + +## Local patches (as re-applied, 2026-10-25) + +All of them are default-off or build-profile only. None changes the default behaviour of the engine. + +| Local patch | Files | Status after the update | +| --- | --- | --- | +| `STRATA_CUDA_STATIC` CMake profile (static CUDA toolkit libraries and GNU C++ runtime, Linux; STRA-23, `a36e45a`) | `CMakeLists.txt` | Re-applied. Added `OR STRATA_HIP_GFX906` to its refusal condition (upstream added a gfx906 compat build that also sets `STRATA_ENABLE_CUDA`). Upstream's own tests that link `CUDA::cudart` directly are not switched to the static target (as before) | +| `STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS`: native verifier cache-miss callback to the external `gpu/kar` component (`87fdec7`, `53c9d7b`, `33f075f`, `b6563e3`) | `CMakeLists.txt`, `include/strata/core/expert_source.hpp`, `src/core/expert_source.cpp`, `src/program/generate.cpp` | Re-applied. The callback now runs before the CPU-work scan so `any_cpu` sees what is left; a completed row (`kind == 3`) is excluded from the new zeroing, offload-count and peer-count rules. Compiles (sm_86 objects, with `STRATA_NEXT_KAR_DIR=gpu/kar` of this repository); never run, and not exercised against upstream's new device-plan and route-tail-skip paths | +| Experimental KAR PLE CPU quality arm and compressed GPU row cache, PLE row trace (`80f6670`, `e4d0c2d`, `36e512a`, `78e92d5` telemetry) | `include/strata/kernels/ngram.hpp`, `src/kernels/ngram.cpp`, `src/prefill/prefill.cpp`, `src/program/generate.cpp`, `CMakeLists.txt` | Re-applied on top of upstream's table-driven PLE formats (`fmt->dequant`, recursive mutex, `wait_prefetches`). The GPU-cache arm lands its rows through upstream's new `ple_land` path. Compiles with `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON` and `STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON` (sm_86 objects); never run | +| Keyless V-only QSA arm (`a8411b5`; failed its quality gate, see `docs/experiments/2026-10-04-keyless-runtime.md`, `docs/keyless-runtime.md`) | `include/strata/core/keyless.hpp`, `src/core/keyless.cpp`, `src/kernels/cuda/keyless.cu`, `src/kernels/keyless_parity.cpp` (new files), plus `layer.cpp/.hpp`, `verify.cpp/.hpp`, `prefill.cpp`, `src/prefill/kernels.cu`, `kv_q8.cu`, `kv_stream.cu/.hpp`, `qsa_decode_attn.cu/.hpp`, `kv_stream_parity.cpp`, `conversation_snapshot.cpp/_test.cpp`, `mtp.cpp`, `generate.cpp` | Re-applied by hand (see conflicts). Needs `STRATA_KEYLESS_ROUTING` and `--kv int8`; refuses K8V4 and the new fused norm+rope; no slots / rows attention variant (falls back to per-query calls) | +| Mode bits | `setup.sh` | The 0644 mode our 2026-10-14 snapshot (`7f896a8`) set on `setup.sh` and `docker-entrypoint.sh` is not carried: `setup.sh` is 0755 as upstream; upstream deleted `docker-entrypoint.sh` (it is `docker/entrypoint.sh` now) | + +Other commits that touched `engine/strata` in the pre-squash history (`b1da05f` first-window logits capture, `78e92d5` telemetry) are +either not part of the tracked snapshot at `570201a` or are the telemetry line listed above; `git grep` for the capture finds nothing in +`570201a:engine/strata`, so nothing was lost by this update. + +### Conflicts and how they were resolved + +Content conflicts (15 files, 44 hunks) and one modify/delete. Everything else in the 25 patched files merged cleanly. + +| File | Conflict | Resolution | +| --- | --- | --- | +| `CMakeLists.txt` (4) | STATIC option next to upstream's new gfx906 block; PLE/KAR targets next to upstream's new gfx1100 score test; `strata_engine` source list (upstream added `remote_expert_opt.cu`, `dflash2`, `peer_experts`, `vmm`, ...); `strata` link options next to upstream's Windows HIP delay-load and the whole `strata-dsv41` block | Union. `keyless.cpp` added to upstream's longer `strata_engine` source list. `STRATA_CUDA_STATIC` refuses `STRATA_HIP_GFX906` | +| `kv_stream.hpp` | Our `kKvValueInt8 = 4` against upstream's new `kKvHybrid = 3` (K8V4 streaming) and its two helper functions | Both: `kKvF16=0, kKvInt8=1, kKvQ4=2, kKvHybrid=3, kKvValueInt8=4` | +| `layer.hpp` | `qsa_kv_format()`: our hard refusal of hybrid state vs upstream's `kKvHybrid` | Upstream's hybrid line first, then ours for `without_key`. The old "hybrid never reaches the block movers" exit is gone because it is now false | +| `kv_stream.cu` (2) | `runs_of()` and `kv_block_bytes()` | Chain `kKvHybrid`, `kKvValueInt8`, `kKvQ4`, `kKvInt8` | +| `kv_q8.cu` | `is_v` computation vs upstream's `MULTI` template parameter | `k_q == nullptr \|\| (MULTI ? (z & 1) : z == 1)`. With keyless + `kv_append_q8_steps` the grid is 2 x tokens and both halves write the same V (redundant, correct) | +| `qsa_decode_attn.cu` (4) | Upstream split the dispatch into `launch_chunks_batch`, `launch_merge_batch`, `qsa_decode_attn_slots`, `qsa_decode_attn_batch_rows`, added lane-cell/gfx906/`attn_v3`/daily variants | Took upstream's structure; `attn_kv_mode()` knows mode 4; mode 4 is dispatched in `launch_chunks_batch` and `qsa_decode_attn_step`; lane-cell is disabled for it; the slots variant returns false and the rows variant goes per row so they fall back to the per-query calls | +| `verify.hpp` / `verify.cpp` (7 hunks) | Our keyless trace members and query routing against upstream's new fused norm+rope, `side_proj`/`q_chain`, `mm()` helper, `collect_profile()`, `launch_o->finish()` | Query routing moved into `norm_rope_on` (between norm and RoPE, all callers go through it); `fuse_nr` is off for keyless; K projection and K norm skipped for keyless; trace members renamed `kl_trace_*` because upstream already owns `trace_h_` (found only by compiling: a clean textual merge produced a duplicate member); the trace writer was re-added after the window's synchronize | +| `layer.cpp` (3) | `qsa_layer` is one giant line; upstream dropped `n_bid`/`width` and re-wrapped the gemv lines | Upstream's text with our `without_key` guards re-inserted | +| `expert_source.cpp` (2) | KAR miss callback vs upstream's `dec_batch`/`gpu_zeroes_hits`/`any_cpu`/`kind == -2` tail skip | Callback first, then upstream's block; kind 3 handled as above | +| `ngram.cpp` (5) | KAR PLE vs `PleFormat` table, `std::recursive_mutex`, `wait_prefetches()` | Upstream's format table; KAR decode and cleanup kept under their macro; `close()` waits for prefetches first; `format()` falls back to `fmt->name` | +| `prefill.cpp` (3) | PLE gpu-cache branch vs upstream's `ple_land`, `C`, pageable PLE ring | GPU-cache branch gathers on the device; else upstream's code | +| `generate.cpp` (9) | Includes, options struct, keyless trace check vs upstream's host-core / pool-cores / aux-cpus / memory-guard blocks, KAR PLE open vs the new direct-read probe, `Drive` setup, request keys, serve-loop epilogue | Union; the PLE direct-read probe is skipped for the KAR PLE arm | +| `kv_stream_parity.cpp` (2) | `append()` and the format name | Both formats | +| `expert_source.hpp`, `verify.hpp`, `kv_stream.hpp` | adjacent member / enum additions | Union | +| `docker-entrypoint.sh` | modified (mode only) by us, deleted by upstream | Deleted (upstream moved it to `docker/entrypoint.sh`) | + +### What this does to the quality reference + +`engine/strata/` on this branch is a different engine from the one the `stra169-ladder` Original was built from: with default flags it +behaves differently from the old pin (upstream flipped defaults on: route tail skip, PcieAuto, sm_120 and sm_86 kernel sets, fused int8 +prompt experts, auto conversation cache; see `docs/upstream-digest-2026-10-25.md`). Do not use a build of this subtree for the greedy/tensor +baselines of `docs/quality-gate.md`. The old pin remains reproducible from `git show 570201a:engine/strata` and from the upstream tree +`487c4cc0` (upstream commit `5b734e42` / `d9ab8435`). Anything compared against the new subtree must set the old behaviour explicitly +(the digest lists the switches). + +## Left out of the subtree (rule: weights, captures, credentials, logs, media and generated artifacts stay out of Git) + +Upstream content at `41cf05a0` that was not committed (2140 files in total; everything else in the upstream tree is committed byte for byte). +The root `.gitignore` already drops `*.bin`, `*.gguf`, `*.log` and `models/`; the rest was left out by the rules below. + +| Group | Files | Why | Where it is | +| --- | --- | --- | --- | +| New `bench/results/**` (community benchmark runs: request captures `requests/*.json.gz`, `*-request.json` prompts, engine logs `*.log`, monitor screenshots, build recipes, fixtures) | 2022 added | request captures and logs; 23 MB; the 162 older files of that directory that the first import carried are unchanged | upstream `bench/results/` | +| Binary media and assets added by upstream | 61 | `apps/desktop/src-tauri/icons/**` and `nsis/*.bmp` (app icons), `apps/host/public/**` (favicons, three GT Walsheim Pro `*.woff2` commercial fonts, an example gif/mp4/pdf), `docs/terminal-previews/*.png` (7), `docs/media/*.png` (2), `docs/media/models/*` | upstream | +| `docs/work/evidence/**` | 24 | test-run transcripts and JSON self-test output (logs) | upstream | +| Model-adjacent binaries that the root `.gitignore` also matches | `data/dsv41/profile-2.00.bin`, `profile-2.25.bin` (hot-expert profiles for the DeepSeek packs), `data/draft_vocab_fr.bin`, `data/expert-profile-sycl.bin`, `tests/fixtures/dsv41/engram-final-header.gguf` | binary data files; needed only to run the DeepSeek engine or its SYCL path | upstream | +| Already left out by the first import and still left out | `data/draft_vocab.bin`, `data/draft_vocab_cyrillic.bin`, `data/draft_vocab_en.bin`, `data/expert-profile.bin` (since the embedded-profile commit it is in Git at `crates/deploy/data/expert-profile.bin`, the one `.gitignore` exception, compiled into `leleka` and written by `leleka up` after a SHA-256 check; download from the pinned commit is the fallback; `crates/deploy/src/expert_profile.rs`), `data/expert-profile-coder.bin`, `data/experimental-speed-projection/*.gguf`, `bench/results/2026-09-30-community-rtx-5090/engine.log` | same rule | upstream | + +Kept on purpose although they look large: `apps/host` and `apps/desktop` source (TypeScript / Rust text; 8 MB), `tools/qwen35/pictures/*.png` +(three small test inputs), `docs/work/*.md`, `bench/prompts/**` (frozen benchmark prompts, hashed byte for byte), `sycl/`, `metal/`, +`packaging/` (installer scripts, text), `third_party/` (ggml-tq headers, Project Maya license and notice). A scan of every kept blob found +no private key, token or credential pattern. The kept scripts and installers are source only; none of them was run. + +Consequences to know: `data/dsv41/profile-*.bin` must be fetched from upstream if the DeepSeek engine is ever built from this tree; +`apps/host`, `apps/desktop` and the packaging flow will not build from this tree without the left-out icons and fonts. Neither is used by +Leleka. Also, upstream's own `AGENTS.md` and `docs/AI_SETUP.md` tell an agent to run installers and `strata launch --yes`; they are +upstream's instructions for its product and do not apply to work in this repository. + +## Verification of this update + +| Check | Result | +| --- | --- | +| Tree identity: every blob of `engine/strata/` compared with upstream `41cf05a0` | identical except the 21 patched files + 4 new files (and the left-out files) | +| `git diff --stat` for line-ending churn | none (LF kept, `core.autocrlf=false`; the nested `.gitattributes` of the subtree sets `eol=crlf` for `*.bat/*.cmd/*.ps1` as upstream does) | +| `scripts/build-cpu.sh` in WSL Ubuntu 24.04, GCC 13.3, CMake 3.31.6 | 16 of 16 ctest tests pass (the script's target list had to be extended: upstream registers 11 more CPU tests than the old pin; `Not Run` otherwise) | +| CUDA compile (sm_86 only, `nvcc` 13.2, no GPU use) of the patched translation units: `kv_q8.cu`, `kv_stream.cu`, `qsa_decode_attn.cu`, `keyless.cu`, `prefill/kernels.cu`, `prefill.cpp`, `layer.cpp`, `verify.cpp`, `expert_source.cpp`, `mtp.cpp`, `conversation_snapshot.cpp`, `keyless.cpp`, `ngram.cpp`, `generate.cpp`, `kv_stream_parity.cpp`, `keyless_parity.cpp` | all 17 objects compile (warnings only) in the default configuration; the 7 objects that depend on the KAR/PLE macros (`ngram.cpp`, `expert_source.cpp`, `prefill.cpp`, `generate.cpp`, `kar_ple_cache.cu`, `kar_expert.cu`, `kar_expert_miss.cpp`) also compile with `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`, `STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=ON`, `STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON`. The compile found one error a textual merge cannot (a duplicate `trace_h_` member in `verify.hpp`), fixed by renaming ours to `kl_trace_*`. Not built: link, the `strata` binary, the parity tests, the sm_120 PTX | +| GPU parity, quality gate, any model run | not run (by instruction); the keyless, KAR and PLE arms are default off and unexercised | +| Port crates that `include_str!` files from `engine/strata` | none of those files changed upstream (`LICENSE`, `serve/chat_template.jinja`, `serve/chat_golden.json`, `tests/data/native_experts/*.txt`, `serve/mcp_fake_server.py`, `tools/mtp_rt.py`) | + +## Local CUDA validation, 2026-10-04 + +The upstream identity above is unchanged. The local Keyless opt-in fork compiled +on Linux with CUDA 13.2.86 for RTX 5090 (SM 120). Query-routing numerical parity, +V-only streaming and conversation snapshots passed. Pretrained-model quality +failed; see [the report](experiments/2026-10-04-keyless-runtime.md). The ordinary +K+V profile remains the production choice. + +(That validation was on the 0.1.35 sources; it has not been repeated on the merged tree.) + +## Local Linux packaging profile, 2026-10-04 + +STRA-23 adds the default-off `STRATA_CUDA_STATIC` CMake profile: static toolkit +runtime/BLAS targets and GNU C++ runtime linkage for Linux. The imported source +commit above remains unchanged; this is a local build-policy patch. A complete +CUDA 13.2/SM 120 compilation and ELF audit passed without GPU inference. The +candidate still needs host glibc 2.43 and an NVIDIA driver; model qualification +is pending. See `deploy/README.md` and `docs/build-validation.md` for the exact +scope, artifact identity and remaining packaging limits. + +(Re-applied on the 0.1.50 `CMakeLists.txt`; the ELF audit has not been repeated.) + +## Experimental KAR expert integration, 2026-10-05 + +The pinned upstream commit remains unchanged. Local default-off +`STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS` adds a native verifier cache-miss callback, +linked to the separate `gpu/kar` component. Resident native hits and batched prefill +retain their IQ weights; short prompt ingestion uses the verifier and therefore +also exercises KAR misses. The runtime requires explicit archive and precision +environment settings, validates the archive payload and expert geometry, and +rejects unsupported pool/multi-device configurations. This is an experimental +quality arm, not full compressed-model residency or a qualified speedup. + +(Written against the 0.1.35 sources; re-applied on 0.1.50, see the table above.) + +## Port provenance, 2026-10-25 + +The Leleka runtime under `crates/`, `desktop-core/` and `control-plane/` is a Rust/CUDA port of the Original mode17 serve path written +for this project; it shares the model artifacts and the algorithms (not the C++ code) with Strata. The Original used as the quality +reference and for the vanilla baselines is a separate build of the OLD pin (`d9ab8435` / `5b734e42`, engine 0.1.35) plus the local +patches that were in `engine/strata/` before this update; `engine/strata/` itself is no longer that source. The agreement of the port +with the Original is measured in `docs/quality-gate.md`; the request-end prefix checkpoints (`docs/prefix-cache.md`) and the chain +kernels (`docs/chain-kernels.md`) are port-side additions with their own gates. + +A digest of what changed upstream and what is worth taking is in [upstream-digest-2026-10-25.md](upstream-digest-2026-10-25.md). diff --git a/engine/upstream/local-patches-on-0.1.35.patch b/engine/upstream/local-patches-on-0.1.35.patch new file mode 100644 index 00000000..8afc4cee --- /dev/null +++ b/engine/upstream/local-patches-on-0.1.35.patch @@ -0,0 +1,2147 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 4efc2976..4d9f2ca1 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -34,6 +34,15 @@ endif() + + option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF) + option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1030 unvalidated)" OFF) ++option(STRATA_CUDA_STATIC "Linux GNU engine: static CUDA toolkit and C++ runtimes (host glibc and NVIDIA driver required)" OFF) ++if(STRATA_CUDA_STATIC) ++ if(NOT STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" ++ OR NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU") ++ message(FATAL_ERROR "STRATA_CUDA_STATIC requires Linux, GNU C++, and STRATA_ENABLE_CUDA=ON (HIP disabled)") ++ endif() ++ # Applies to subsequently created CUDA targets, including device-link runtime edges. ++ set(CMAKE_CUDA_RUNTIME_LIBRARY Static) ++endif() + option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) + # CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads + # every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every +@@ -110,6 +119,16 @@ if(STRATA_ENABLE_CUDA) + message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}") + set(_strata_gpu_runtime_target CUDA::cudart) + set(_strata_gpu_blas_target CUDA::cublas) ++ if(STRATA_CUDA_STATIC) ++ foreach(_required CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static CUDA::culibos) ++ if(NOT TARGET ${_required}) ++ message(FATAL_ERROR "STRATA_CUDA_STATIC requires toolkit archive target ${_required}") ++ endif() ++ endforeach() ++ set(_strata_gpu_runtime_target CUDA::cudart_static) ++ set(_strata_gpu_blas_target CUDA::cublas_static) ++ message(STATUS "Strata: static CUDA toolkit libraries; host glibc and NVIDIA driver remain required") ++ endif() + set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + elseif(STRATA_ENABLE_HIP) + set(_strata_gpu_runtime_target strata_hip_runtime) +@@ -257,6 +276,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + src/kernels/cuda/fused_gr.cu + src/kernels/cuda/cvec.cu + src/kernels/cuda/qsa_decode_attn.cu ++ src/kernels/cuda/keyless.cu + src/kernels/cuda/qsa_prompt_attn.cu + src/kernels/cuda/fused_gdn.cu + src/kernels/cuda/dequant_bf16.cu +@@ -267,12 +287,41 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + src/ngram/ple_reader.cpp + src/platform/direct_file.cpp) + target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact) ++ option(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE "Capture private PLE row traces for offline cache studies" OFF) ++ if(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++ if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "The experimental PLE row trace requires Linux") ++ endif() ++ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=1) ++ endif() ++ option(STRATA_NEXT_EXPERIMENTAL_KAR_PLE "Build optional KAR PLE CPU and GPU-cache experiment arms" OFF) ++ set(STRATA_NEXT_KAR_DIR "" CACHE PATH "Path to strata-next/gpu/kar (required for KAR PLE)") ++ if(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "The experimental KAR PLE quality arm requires Linux CUDA") ++ endif() ++ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu") ++ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to the strata-next/gpu/kar source directory") ++ endif() ++ add_library(strata_next_kar STATIC ++ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cache.cu") ++ target_include_directories(strata_next_kar PUBLIC ++ "${STRATA_NEXT_KAR_DIR}/vendor" ++ "${STRATA_NEXT_KAR_DIR}/include") ++ target_link_libraries(strata_next_kar PUBLIC ${_strata_gpu_runtime_target}) ++ set_target_properties(strata_next_kar PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) ++ target_link_libraries(strata_kernels PUBLIC strata_next_kar) ++ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_KAR_PLE=1) ++ add_executable(strata_next_kar_ple_probe "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cpu_probe.cpp") ++ target_link_libraries(strata_next_kar_ple_probe PRIVATE strata_kernels) ++ endif() + # perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with + # the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON. CUDA only: HIP compiles the tensor-core kernel out. + if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA) + add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp) + target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) +- target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) ++ target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() + # the QSA selection (block scores on the warp kernel and the tensor-core one, top-k): a GPU bench with a + # scorer-vs-scorer comparison and an FP64 accuracy gate (synthetic, no model); the ctest runs a 32K context under a +@@ -338,11 +387,35 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + # already links `strata_core` - putting `gdn_layer` in core would make the two mutually dependent. A third + # library is the honest shape of the dependency graph: core knows about devices and weights, kernels know + # about arithmetic, and this one knows the ORDER the arithmetic happens in. +- add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp ++ add_library(strata_engine STATIC src/core/keyless.cpp src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp + src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp + src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp) + target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) + target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) ++ option(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS "Build the opt-in KAR native decode cache-miss arm" OFF) ++ if(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "Experimental KAR experts require Linux CUDA") ++ endif() ++ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") ++ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to strata-next/gpu/kar") ++ endif() ++ add_library(strata_next_kar_experts STATIC ++ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_expert.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") ++ target_include_directories(strata_next_kar_experts PUBLIC ++ "${STRATA_NEXT_KAR_DIR}/vendor" "${STRATA_NEXT_KAR_DIR}/include") ++ target_link_libraries(strata_next_kar_experts PUBLIC ${_strata_gpu_runtime_target}) ++ set_target_properties(strata_next_kar_experts PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) ++ target_compile_features(strata_next_kar_experts PRIVATE cxx_std_20) ++ target_link_libraries(strata_engine PUBLIC strata_next_kar_experts) ++ target_compile_definitions(strata_engine PUBLIC STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=1) ++ endif() ++ add_executable(keyless_parity src/kernels/keyless_parity.cpp) ++ target_link_libraries(keyless_parity PRIVATE strata_engine) ++ add_test(NAME keyless_parity COMMAND keyless_parity) ++ set_tests_properties(keyless_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp") + enable_testing() + add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp) +@@ -369,6 +442,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + set_tests_properties(expert_cache_per_layer_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() + if(STRATA_BUILD_CONVERSATION_TESTS) ++ add_executable(keyless_stream_parity src/kernels/kv_stream_parity.cpp) ++ target_link_libraries(keyless_stream_parity PRIVATE strata_engine) ++ add_test(NAME keyless_stream_parity COMMAND keyless_stream_parity --v-only) ++ set_tests_properties(keyless_stream_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp) + target_link_libraries(conversation_snapshot_test PRIVATE strata_engine) + add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test) +@@ -406,6 +483,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + add_executable(strata src/program/generate.cpp) + target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) ++ if(STRATA_CUDA_STATIC) ++ target_link_options(strata PRIVATE -static-libstdc++ -static-libgcc) ++ set_target_properties(strata PROPERTIES SKIP_BUILD_RPATH TRUE INSTALL_RPATH "") ++ endif() + + if(STRATA_ENABLE_HIP) + enable_testing() +diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp +index 307edd98..e2669ebe 100644 +--- a/include/strata/core/expert_source.hpp ++++ b/include/strata/core/expert_source.hpp +@@ -211,6 +211,12 @@ struct GpuPlanSink { + + /// The adapter's own state. One per session, reused every layer so the token path allocates nothing (P2.T10). + struct ExpertDispatch { ++ // Default-off local extension. The callback owns only kind==-1 entries and ++ // marks completed host rows as kind=3. Native hits/PCIe/remote rows are untouched. ++ using ExperimentalMiss = bool (*)(void*, int64_t, const float*, const int32_t*, ++ int64_t, int64_t, int32_t*, float*, std::string&); ++ ExperimentalMiss experimental_miss = nullptr; ++ void* experimental_miss_user = nullptr; + strata::kernels::cpu::ExpertPool* pool = nullptr; + ExpertSource* src = nullptr; + RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts +diff --git a/include/strata/core/keyless.hpp b/include/strata/core/keyless.hpp +new file mode 100644 +index 00000000..4665c458 +--- /dev/null ++++ b/include/strata/core/keyless.hpp +@@ -0,0 +1,11 @@ ++#pragma once ++#include "strata/core/layout.hpp" ++#include ++namespace strata::core { ++bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error); ++const float* keyless_routing(int64_t layer); ++} ++namespace strata::kernels { ++// In-place, one independent matrix for each query head. No cached keys are produced. ++void keyless_route_query(float* q, const float* output_major_matrices, int64_t tokens, int heads, int dim, void* stream); ++} +diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp +index a8965da1..e7cfeb24 100644 +--- a/include/strata/core/layer.hpp ++++ b/include/strata/core/layer.hpp +@@ -204,6 +204,7 @@ struct QsaState { + uint16_t* k_pool = nullptr; ///< [page][kv_head][page_size][head_dim] fp16 (null in INT8 mode) + uint16_t* v_pool = nullptr; + /// Plan v0.3 P7: INT8 KV (qsa_set_kv_int8). Codes [page][kv_head][page_size][head_dim], one FP16 scale per 64. ++ bool without_key = false; + bool kv_int8 = false; + int8_t* k_q = nullptr; + int8_t* v_q = nullptr; +@@ -282,6 +283,8 @@ uint64_t qsa_kv_host_bytes(); + /// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and + /// initializing the session; default off until gate G-C accepts it. + void qsa_set_kv_int8(bool enabled); ++void qsa_set_without_key(bool enabled); ++bool qsa_without_key(); + /// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1) + void qsa_set_kv_int8_rotate(bool enabled); + bool qsa_kv_int8(); +@@ -299,6 +302,7 @@ inline int qsa_kv_format(const QsaState& st) { + std::fprintf(stderr, "strata: qsa_kv_format: a hybrid K8V4 state must never reach the block movers\n"); + std::exit(1); // the kernels' own "unsupported geometry" convention (kv_q8.cu, qsa_decode_attn.cu) + } ++ if (st.without_key) return strata::kernels::kKvValueInt8; + return st.kv_q4 ? strata::kernels::kKvQ4 : st.kv_int8 ? strata::kernels::kKvInt8 : strata::kernels::kKvF16; + } + uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st, +diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp +index 5717eb4f..29b064fb 100644 +--- a/include/strata/core/verify.hpp ++++ b/include/strata/core/verify.hpp +@@ -213,6 +213,10 @@ private: + int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}] + float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd + int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids ++ float* trace_h_ = nullptr; // optional pinned K/V activation trace for offline keyless study ++ std::FILE* trace_file_ = nullptr; ++ float* trace_q_h_ = nullptr; // first accepted token's Q, per QSA layer ++ std::FILE* trace_q_file_ = nullptr; + float* h_x_ = nullptr; float* m_x_ = nullptr; // doorbell payload: T * n_embd + int32_t* h_ids_ = nullptr; int32_t* m_ids_ = nullptr; // T * k + float* h_w_ = nullptr; float* m_w_ = nullptr; // T * k +diff --git a/include/strata/kernels/kv_stream.hpp b/include/strata/kernels/kv_stream.hpp +index b3ebee34..90483fa0 100644 +--- a/include/strata/kernels/kv_stream.hpp ++++ b/include/strata/kernels/kv_stream.hpp +@@ -38,12 +38,12 @@ struct KvHostPools { + uint16_t* v_scale = nullptr; + uint8_t* k_q4 = nullptr; ///< q4_0 mode (kv_q4.hpp): block_q4_0 codes, 144 B per cell and head + uint8_t* v_q4 = nullptr; +- bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr; } ++ bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr || v_q != nullptr; } + }; + + /// The KV storage format, for the functions below that move whole blocks (`fmt`): fp16, int8 (+ scales), q4_0. + /// (A bool `int8` argument still reads as kKvF16 / kKvInt8.) +-enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2 }; ++enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2, kKvValueInt8 = 4 }; + + /// The residency map of a streamed layer, all device memory at fixed addresses (the graphs bake them in). + struct KvStreamMap { +diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp +index 3c6f8fab..688c74d9 100644 +--- a/include/strata/kernels/ngram.hpp ++++ b/include/strata/kernels/ngram.hpp +@@ -22,6 +22,7 @@ + // All of those are asserted observable in `ple_parity.cpp` rather than trusted. + #pragma once + ++#include + #include + #include + +@@ -139,6 +140,21 @@ public: + /// Open with an explicit I/O mode. The two-argument `open` below is the default (Direct). + bool open(const std::string& gguf_path, std::string& err, const PleIoOptions& io); + ++ /// Experimental CPU quality arm: read rows from a verified KAR-2 archive ++ /// while the rest of the engine continues to use its normal model pack. ++ /// The CUDA selective-row path is measured separately and is not used here. ++ bool open_kar(const std::string& kar_path, uint32_t level, std::string& err, ++ uint64_t expected_rows = PLE_TABLE_ROWS); ++ ++ /// Experimental bounded compressed-row cache. It accepts only the ++ /// level-2/group-32 KAR PLE layout and leaves the CPU gather available ++ /// for consumers that still use mapped host memory. ++ bool enable_kar_gpu_cache(uint32_t cache_mib, std::string& err); ++ bool kar_gpu_cache_enabled() const; ++ bool collect_device(float* device_out2560, void* stream, std::string& err); ++ bool gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, ++ void* stream, std::string& err); ++ + /// The split the plan asks for: `issue` as soon as the token id is known, `collect` just before layer 1 + /// needs the rows. `gather` is `issue` followed by `collect`. In Mmap mode `issue` only prefetches. + bool issue(const uint32_t* rows16); +diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp +index 45c0f301..f67bfad2 100644 +--- a/include/strata/kernels/qsa_decode_attn.hpp ++++ b/include/strata/kernels/qsa_decode_attn.hpp +@@ -21,6 +21,11 @@ + namespace strata::kernels { + + struct QsaAttnPools { ++ bool without_key = false; ++ const float* keyless_cos = nullptr; ++ const float* keyless_sin = nullptr; ++ int keyless_n_rot = 0; ++ const int32_t* keyless_mrope = nullptr; // optional per-cell time/height/width positions + const uint16_t* k_pool = nullptr; ///< fp16 [page][kv_head][page_size][head_dim], or null when int8 + const uint16_t* v_pool = nullptr; + const int8_t* k_q = nullptr; ///< int8 codes, same layout +diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp +index 759daa65..0d8453d9 100644 +--- a/src/core/conversation_snapshot.cpp ++++ b/src/core/conversation_snapshot.cpp +@@ -59,6 +59,7 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index + } + l.value_data = l.data; + l.value_scales = l.scales; ++ if (st.without_key) { l.data = 0; l.scales = 0; } + if (st.kv_hybrid) { + if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv, + (uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) { +@@ -98,7 +99,7 @@ bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error + } + } + if (st.kv_mode == 2 && (!st.page_table || +- (st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale ++ (st.without_key ? !st.v_q || !st.v_scale : st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale + : !st.k_pool || !st.v_pool))) { + error = "conversation snapshot: invalid draft ring"; + return false; +diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp +index da95113c..3792cd4b 100644 +--- a/src/core/conversation_snapshot_test.cpp ++++ b/src/core/conversation_snapshot_test.cpp +@@ -42,13 +42,14 @@ struct Fixture { + } + Fixture(int fmt, int mode) { + auto& st = state; +- st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; ++ st.kv_mode = mode; st.without_key = fmt==kKvValueInt8; st.kv_int8 = fmt==kKvInt8 || st.without_key; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; + st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages; + st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode==2 ? 2 : st.max_cells/4+2; + const size_t per = fmt==kKvQ4 ? kv_q4_bytes_per_head((int)g.head_dim) : g.head_dim*((st.kv_int8 || st.kv_hybrid) ? 1:2); + const size_t rows = st.max_cells*g.n_head_kv, slot_rows = st.n_slots*4*g.n_head_kv; +- sizes = {rows*per, rows*per, fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, +- fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; ++ sizes = {rows*per, rows*per, (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0, ++ (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; ++ if (st.without_key) { sizes[0]=0; sizes[2]=0; } + if (fmt==3) { + sizes = {rows*per, rows*kv_q4_bytes_per_head((int)g.head_dim), rows*(g.head_dim/64)*2, 0, + (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; +@@ -58,9 +59,11 @@ struct Fixture { + alloc(st.k_q4,slot_rows*per); alloc(st.v_q4,slot_rows*per); + if (mode) {alloc(st.host.k_q4,sizes[0],true); alloc(st.host.v_q4,sizes[1],true);} + sources[0]=mode?st.host.k_q4:st.k_q4; sources[1]=mode?st.host.v_q4:st.v_q4; +- } else if (fmt==kKvInt8) { +- alloc(st.k_q,slot_rows*per); alloc(st.v_q,slot_rows*per); +- alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); alloc(st.v_scale,slot_rows*(g.head_dim/64)*2); ++ } else if (st.kv_int8) { ++ if (!st.without_key) alloc(st.k_q,slot_rows*per); ++ alloc(st.v_q,slot_rows*per); ++ if (!st.without_key) alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); ++ alloc(st.v_scale,slot_rows*(g.head_dim/64)*2); + if (mode) { + alloc(st.host.k_q,sizes[0],true); alloc(st.host.v_q,sizes[1],true); + alloc(st.host.k_scale,sizes[2],true); alloc(st.host.v_scale,sizes[3],true); +@@ -105,7 +108,7 @@ bool equal(const ConversationKv& a,const ConversationKv& b) { + } + + void full_session(int fmt, int mode, int experts) { +- Fixture main(fmt,mode), draft(fmt==3?kKvInt8:fmt,2); ++ Fixture main(fmt,mode), draft((fmt==3 || fmt==kKvValueInt8)?kKvInt8:fmt,2); + auto& g=main.g; + g.n_layers=4; g.n_expert=experts; + g.ssm_state_size=2; g.ssm_v_heads=2; g.ssm_conv_channels=8; +@@ -162,7 +165,7 @@ void full_session(int fmt, int mode, int experts) { + check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore growth fixture base"); + ConversationKvReuse reuse{a.kv,65,dirty}; + const uint8_t* original = nullptr; +- reuse.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;}); ++ reuse.kv[0].v.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;}); + main.fill_after(91,dirty); draft.fill_after(91,std::max(0,dirty-1)); + cuda_check(cudaMemset(ss.gdn_state,91,sizes.gdn)); + ids.resize(70); +@@ -179,7 +182,7 @@ void full_session(int fmt, int mode, int experts) { + incremental.live.dead==fresh.live.dead && equal(incremental.kv[0],fresh.kv[0]) && + equal(incremental.kv[1],fresh.kv[1]),"incremental capture equals full capture after growth or rewind"); + check((dirty>=4)==(reused>0),"only complete unchanged pages or rows are retained"); +- incremental.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){ ++ incremental.kv[0].v.visit(0,1,[&](const uint8_t* p,size_t,size_t){ + check(p==original,"growth never reallocates the retained payload");return true; + }); + check(conversation_snapshot_restore(incremental,ss,g,draft.state,err)==ConversationRestore::restored,"restore segmented incremental snapshot"); +@@ -198,7 +201,7 @@ void full_session(int fmt, int mode, int experts) { + int main() { + int devices=0; + if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77; +- for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) { ++ for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3,kKvValueInt8}) for (int mode : {0,1,2}) { + if (fmt==3 && mode!=0) continue; + Fixture f(fmt,mode); + if (fmt==3) { +@@ -227,6 +230,12 @@ int main() { + ConversationKv a,b,restored; + cuda_check(cudaDeviceSynchronize()); + check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A"); ++ if (fmt==kKvValueInt8) { ++ check(a.k.empty() && a.k_scale.empty() && !f.state.k_q && !f.state.host.k_q, ++ "V-only snapshot and resident/host pools have no K"); ++ auto wrong=a; wrong.format=kKvInt8; ++ check(!conversation_kv_restore(wrong,f.state,f.g,upto,index,err),"reject K+V snapshot in V-only state"); ++ } + check(a.bytes()==conversation_kv_bytes(f.state,f.g,upto,index),"size estimate equals snapshot payload"); + f.fill(177); + check(conversation_kv_save(b,f.state,f.g,upto,index,err),"save B"); +@@ -247,13 +256,13 @@ int main() { + const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max(0,b1-f.state.n_slots); + const size_t block=kv_block_bytes(s,fmt)/2; + // Codes and scales are separate in INT8; check code bytes here. +- const size_t code_block=fmt==kKvInt8 ? s.page_size*s.n_head_kv*s.head_dim : block; +- const void* slots=fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool; ++ const size_t code_block=(fmt==kKvInt8 || fmt==kKvValueInt8) ? s.page_size*s.n_head_kv*s.head_dim : block; ++ const void* slots=fmt==kKvValueInt8?(void*)f.state.v_q:fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool; + std::vector got(code_block); + for (int64_t page=b0;page expected(code_block); +- check(a.k.read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); ++ check((fmt==kKvValueInt8?a.v:a.k).read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); + check(got == expected,"draft ring contains restored pages"); + } + } +@@ -276,7 +285,7 @@ int main() { + } + } + } +- for (int fmt : {kKvF16,kKvInt8,kKvQ4}) for (int mode : {0,1}) for (int experts : {256,512}) ++ for (int fmt : {kKvF16,kKvInt8,kKvQ4,kKvValueInt8}) for (int mode : {0,1}) for (int experts : {256,512}) + full_session(fmt,mode,experts); + for (int experts : {256,512}) full_session(3,0,experts); + std::printf("conversation_snapshot_test: %d checks passed\n",checks); +diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp +index 087854ed..4d3cb759 100644 +--- a/src/core/expert_source.cpp ++++ b/src/core/expert_source.cpp +@@ -1745,6 +1745,13 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 + for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2; + } + } ++ if (d.experimental_miss != nullptr) { ++ static thread_local std::string miss_error; ++ if (!d.experimental_miss(d.experimental_miss_user, d.layers, x_f, ids, ++ n_tok, k, kind, out, miss_error)) { ++ d.failed = true; d.fail = miss_error.c_str(); d.fail_layer = d.layers; return; ++ } ++ } + const auto c1 = std::chrono::steady_clock::now(); + if (native && lay.fmt[(size_t) d.layers].gu_type == 42) // a native Q2_0 pack: the Q2_0 kernels' activations + for (int64_t t = 0; t < n_tok; ++t) act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]); +@@ -1776,9 +1783,10 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 + d.fail_expert = e; + return; + } +- if (kind[i] >= 0) { // CUDA0, PCIe, or a remote result staged into this row below ++ if (kind[i] >= 0) { // CUDA0, PCIe, remote, or completed experimental host row + if (kind[i] == 0) ++d.cache_hits; +- std::memset(row, 0, (size_t) H * sizeof(float)); ++ if (kind[i] == 3) ++d.cache_refused; ++ else std::memset(row, 0, (size_t) H * sizeof(float)); + continue; + } + ++d.cache_refused; +diff --git a/src/core/keyless.cpp b/src/core/keyless.cpp +new file mode 100644 +index 00000000..7699b579 +--- /dev/null ++++ b/src/core/keyless.cpp +@@ -0,0 +1,79 @@ ++#include "strata/core/keyless.hpp" ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace strata::core { ++namespace { ++std::map routes; ++uint32_t u32(std::istream& f) { ++ unsigned char b[4]{}; f.read((char*) b, 4); ++ return (uint32_t)b[0] | (uint32_t)b[1]<<8 | (uint32_t)b[2]<<16 | (uint32_t)b[3]<<24; ++} ++uint64_t u64(std::istream& f) { const uint64_t a = u32(f); return a | (uint64_t)u32(f)<<32; } ++} ++const float* keyless_routing(int64_t layer) { ++ const auto it = routes.find(layer); ++ return it == routes.end() ? nullptr : it->second; ++} ++bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error) { ++ if (!routes.empty()) { error = "keyless routing already loaded"; return false; } ++ std::ifstream f(path, std::ios::binary); ++ std::array magic{}; f.read(magic.data(), 8); ++ const uint32_t version = u32(f), layers = u32(f), heads = u32(f), dim = u32(f); ++ if (!f || std::memcmp(magic.data(), "SKLROUT1", 8) || version != 1 || ++ layers != (uint32_t)g.n_qsa_layers() || heads != (uint32_t)g.n_head || dim != (uint32_t)g.head_dim || dim != 256) { ++ error = "invalid keyless artifact header/geometry"; return false; ++ } ++ std::map pending; ++ auto fail = [&](const std::string& why) { ++ error = why; for (auto& row : pending) cudaFree(row.second); return false; ++ }; ++ for (uint32_t ordinal = 0; ordinal < layers; ++ordinal) { ++ const uint32_t layer = u32(f); ++ if (!f || layer >= g.n_layers || !is_qsa_layer(g, layer) || pending.count(layer)) ++ return fail("keyless artifact has invalid/duplicate layer"); ++ for (const char* role : {"q", "k", "v"}) { ++ const uint32_t kind = u32(f); const uint64_t bytes = u64(f), wanted = u64(f); ++ const auto* w = weights.find("blk." + std::to_string(layer) + ".attn_" + role + ".weight"); ++ // Quantized projection size is recorded by the source decoder. Bound before any device read. ++ const uint64_t expected_elements = (uint64_t)g.n_embd * g.head_dim * ++ (std::strcmp(role,"q") == 0 ? g.n_head * 2 : g.n_head_kv); ++ if (!f || !w || !w->native_data || w->native_type != (int)kind || ++ bytes == 0 || bytes > expected_elements * 4 || expected_elements != (uint64_t)w->elements) ++ return fail("keyless artifact source projection geometry/type mismatch"); ++ // NativeDense owns source GGUF blocks. Verify the artifact was derived from these actual bytes. ++ // Source byte length must agree with ggml geometry; ne0/ne1 cannot validate a quantized byte span. ++ const uint64_t block_elements = kind == 42 ? 64 : kind == 8 ? 32 : 256; ++ const uint64_t block_bytes = kind == 42 ? 18 : kind == 11 ? 110 : kind == 12 ? 144 : ++ kind == 13 ? 176 : kind == 14 ? 210 : kind == 23 ? 136 : kind == 8 ? 34 : 0; ++ if (!block_bytes || expected_elements % block_elements || bytes != expected_elements / block_elements * block_bytes) ++ return fail("keyless artifact unsupported/mismatched native projection encoding"); ++ std::vector raw((size_t)bytes); ++ if (cudaMemcpy(raw.data(), w->native_data, raw.size(), cudaMemcpyDeviceToHost) != cudaSuccess) ++ return fail("keyless source projection readback failed"); ++ uint64_t hash = 0xcbf29ce484222325ull; ++ for (uint8_t byte : raw) hash = (hash ^ byte) * 0x100000001b3ull; ++ if (hash != wanted) return fail("keyless artifact source projection fingerprint mismatch"); ++ } ++ std::vector matrix((size_t)heads * dim * dim); ++ f.read((char*)matrix.data(), matrix.size()*sizeof(float)); ++ if (!f || !std::all_of(matrix.begin(), matrix.end(), [](float v) { return std::isfinite(v); })) ++ return fail("truncated/nonfinite keyless query matrix"); ++ float* device = nullptr; ++ if (cudaMalloc((void**)&device, matrix.size()*sizeof(float)) != cudaSuccess) ++ return fail("keyless query matrices do not fit in GPU memory"); ++ pending[layer] = device; ++ if (cudaMemcpy(device, matrix.data(), matrix.size()*sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) ++ return fail("keyless query matrix upload failed"); ++ } ++ if (f.peek() != std::char_traits::eof()) return fail("keyless artifact has trailing data"); ++ routes = std::move(pending); ++ return true; ++} ++} +diff --git a/src/core/layer.cpp b/src/core/layer.cpp +index ff7fc17b..7e132895 100644 +--- a/src/core/layer.cpp ++++ b/src/core/layer.cpp +@@ -1,6 +1,7 @@ + + // src/core/layer.cpp - the GDN layer, composed. See the header for the operation order and its traps. + #include "strata/core/layer.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/native_head.hpp" + #include "strata/kernels/bf16_bits.hpp" + #include "strata/kernels/bf16_gemv.hpp" +@@ -173,7 +174,9 @@ if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, + // namespace + void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; } + void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; } +-namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } ++namespace { bool g_without_key = false, g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } ++void qsa_set_without_key(bool enabled) { g_without_key = enabled; } ++bool qsa_without_key() { return g_without_key; } + void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; } + void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; } + bool qsa_kv_int8() { return g_kv_int8; } +@@ -512,6 +515,7 @@ KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) { + return p; + } + uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) { ++ if (g_without_key) return (uint64_t)pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) / 2 + 64; + if (hybrid) { // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation) + const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv; + return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 + +@@ -552,6 +556,7 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + const KvPlan p = kv_plan(s, max_cells, ring_cells); + const int64_t pages = p.pages; + Cursor c{(uint8_t*) base}; ++ st.without_key = g_without_key; + st.kv_int8 = g_kv_int8 && !g_kv_q4; + st.kv_q4 = g_kv_q4; + // Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 - +@@ -578,9 +583,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + st.k_q4 = c.take(rows * q4_row); + st.v_q4 = c.take(rows * q4_row); + } else if (st.kv_int8) { // st, not the global: the drafter's ring is INT8 under --kv k8v4 too +- st.k_q = c.take(rows * s.head_dim); ++ if (!st.without_key) st.k_q = c.take(rows * s.head_dim); + st.v_q = c.take(rows * s.head_dim); +- st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); ++ if (!st.without_key) st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.v_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.k_pool = c.take(rows * s.head_dim); +@@ -646,9 +651,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + st.host.k_q4 = hc.take(hrows * q4_row); + st.host.v_q4 = hc.take(hrows * q4_row); + } else if (st.kv_int8) { +- st.host.k_q = hc.take(hrows * s.head_dim); ++ if (!st.without_key) st.host.k_q = hc.take(hrows * s.head_dim); + st.host.v_q = hc.take(hrows * s.head_dim); +- st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); ++ if (!st.without_key) st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.host.v_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.host.k_pool = hc.take(hrows * s.head_dim); +@@ -689,16 +694,16 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { + cudaStream_t cs = (cudaStream_t) stream; + const size_t rows = (size_t) st.n_slots * s.n_head_kv * s.page_size; + if (st.kv_hybrid) { +- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); +- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); ++ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); ++ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_q4) { + cudaMemsetAsync(st.k_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_int8) { +- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); ++ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); + cudaMemsetAsync(st.v_q, 0, rows * s.head_dim, cs); +- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); ++ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + } else { + cudaMemsetAsync(st.k_pool, 0, rows * s.head_dim * 2, cs); +@@ -716,6 +721,8 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { + strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) { + strata::kernels::QsaAttnPools pools; + pools.page_table = st.page_table; ++ pools.without_key = st.without_key; ++ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + if (st.kv_hybrid) { pools.k_q = st.k_q; pools.k_scale = st.k_scale; pools.v_q4 = st.v_q4; } + else if (st.kv_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; } + else if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; } +@@ -845,11 +852,12 @@ void stage_timing_report(int64_t n_layers) { + // needs nothing from the layer it is called for beyond its index. + static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off, + uint64_t n, void* stream); +-bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_width(kTopkMaxCells, s); ++bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; if (st.without_key && pos_base != 0) { err = "V-only requires zero position base"; return false; } /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t n_bid = n_kv / s.idx_block; const int64_t width = qsa_selection_width(n_kv, s); const int64_t cap = qsa_selection_width(kTopkMaxCells, s); + const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, int cols) { + 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 (st.without_key && data == b.qcur) keyless_route_query(data, keyless_routing(layer), 1, (int)g.n_head, (int)g.head_dim, 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; +@@ -893,7 +901,7 @@ SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight" + // k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this + // artifact, but the dispatch is here for the same reason it is in `gdn_layer`: the pack decides per tensor, + // and "it happens to be uniform here" is the assumption that was wrong for `attn_q`. +-if (!gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); if (!normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; ++if (!st.without_key && !gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, !st.without_key && w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); if (!st.without_key && !normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; + // ---- 5. into the cache, and the indexer's append (which pools AND rotates on a block completion). + // EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every + // launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed. The +@@ -947,7 +955,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; + // KV streaming: every block the selection names is made resident before anything reads it + qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = +- if (g_fast_attn && !native_flash_attn_short && dump == nullptr) { ++ if (st.without_key || (g_fast_attn && !native_flash_attn_short && dump == nullptr)) { + const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st); + strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream); + } else { +@@ -1269,6 +1277,13 @@ bool ple_issue_token(const PleRun& p, std::string& err) { + + bool ple_finish_token(const PleRun& p, void* stream, std::string& err) { + if (!p.ready()) { err = "ple_finish_token: the PLE run is not ready"; return false; } ++ if (p.table->kar_gpu_cache_enabled()) { ++ if (!p.table->collect_device(p.emb_dev, stream, err)) { ++ err = "ple_finish_token: " + err; ++ return false; ++ } ++ return true; ++ } + if (!p.table->collect(p.emb_host, err)) { err = "ple_finish_token: " + err; return false; } + if (cudaMemcpyAsync(p.emb_dev, p.emb_host, (size_t) strata::kernels::NG_N_EMBD * sizeof(float), + cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { +diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp +index 17e36556..5db90887 100644 +--- a/src/core/mtp.cpp ++++ b/src/core/mtp.cpp +@@ -212,6 +212,11 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session + int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0; + // K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats + // only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback). ++ struct RestoreKeylessMode { ++ bool previous = qsa_without_key(); ++ ~RestoreKeylessMode() { qsa_set_without_key(previous); } ++ } restore_keyless_mode; ++ qsa_set_without_key(false); + const bool kv_hybrid_was = qsa_kv_hybrid(); + const bool kv_int8_was = qsa_kv_int8(); + qsa_set_kv_hybrid(false); +diff --git a/src/core/verify.cpp b/src/core/verify.cpp +index 999f85d8..58f7594b 100644 +--- a/src/core/verify.cpp ++++ b/src/core/verify.cpp +@@ -1,5 +1,6 @@ + // src/core/verify.cpp - see include/strata/core/verify.hpp. + #include "strata/core/verify.hpp" ++#include "strata/core/keyless.hpp" + #if defined(_WIN32) + #include + #endif +@@ -179,7 +180,9 @@ Verifier::~Verifier() { + if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } + if (commit_done_) cudaEventDestroy(commit_done_); + if (arena_) cudaFree(arena_); +- void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, ++ if (trace_file_) std::fclose(trace_file_); ++ if (trace_q_file_) std::fclose(trace_q_file_); ++ void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, trace_h_, trace_q_h_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, + h_flagA_, h_plan_, h_flagB_}; + for (void* h : hosts) + if (h) cudaFreeHost(h); +@@ -202,6 +205,21 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& + hits_ = hits; + head_ = head; + max_t_ = max_t; ++ if (const char* path = std::getenv("STRATA_KEYLESS_TRACE")) { ++ if (!*path) { err = "verify: STRATA_KEYLESS_TRACE needs a private output path"; return false; } ++ trace_file_ = std::fopen(path, "wb"); ++ trace_q_file_ = std::fopen((std::string(path) + ".q").c_str(), "wb"); ++ const size_t trace_bytes = (size_t) g.n_qsa_layers() * (size_t) max_t * ++ (size_t) g.n_head_kv * (size_t) g.head_dim * 2 * sizeof(float); ++ const size_t query_bytes = (size_t) g.n_qsa_layers() * (size_t) g.n_head * ++ (size_t) g.head_dim * sizeof(float); ++ if (!trace_file_ || !trace_q_file_ || ++ cudaHostAlloc((void**) &trace_h_, trace_bytes, cudaHostAllocDefault) != cudaSuccess || ++ cudaHostAlloc((void**) &trace_q_h_, query_bytes, cudaHostAllocDefault) != cudaSuccess) { ++ err = "verify: cannot create pinned keyless activation trace"; ++ return false; ++ } ++ } + sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise + sampling_.temperature = 0.0f; + if (max_t < 2 || max_t > strata::kernels::kVerifyMaxT || max_t > strata::kernels::cpu::MAXT) { +@@ -557,6 +575,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 (st.without_key && norm == wqn) keyless_route_query(data, keyless_routing(l), rows / (int)NH, (int)NH, (int)HD, 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); + }; +@@ -569,16 +588,29 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + else for (int t = tb; t < te; ++t) + bf16_gemv_fp32_mmvf(mixed_ + t * N, (const uint16_t*) wik->data, idx_raw + t * ID, (int) N, (int) ID, cs); + stamp(l, 7, grp); +- native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); ++ if (!st.without_key) native_mmvq(wk->native_type, wk->native_data, xq_, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); + native_mmvq(wv->native_type, wv->native_data, xq_, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD), n, cs); +- if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); +- else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); ++ if (!st.without_key && qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); ++ else if (!st.without_key) for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); + if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp) + fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } else if (st.kv_hybrid) { // K8V4: only V is rotated + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } ++ if (trace_h_) { ++ const size_t width = (size_t) NKV * HD; ++ for (int t = tb; t < te; ++t) { ++ float* dst = trace_h_ + ((size_t) qi * max_t_ + t) * 2 * width; ++ if (cudaMemcpyAsync(dst, kcur_ + (size_t) t * width, width * sizeof(float), ++ cudaMemcpyDeviceToHost, cs) != cudaSuccess || ++ cudaMemcpyAsync(dst + width, vcur_ + (size_t) t * width, width * sizeof(float), ++ cudaMemcpyDeviceToHost, cs) != cudaSuccess) { ++ err = "verify: keyless trace copy could not be captured"; ++ return false; ++ } ++ } ++ } + stamp(l, 8, grp); + if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs); + for (int t = tb; t < te; ++t) { +@@ -646,6 +678,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + const QsaAttnPools pools = qsa_attn_pools(st); + qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_, + s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs); ++ if (trace_q_h_ && tb == 0 && ++ cudaMemcpyAsync(trace_q_h_ + (size_t) qi * NH * HD, qcur_, ++ (size_t) NH * HD * sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess) { ++ err = "verify: keyless query trace copy could not be captured"; ++ return false; ++ } + stamp(l, 13, grp); + if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H + if (qb) native_qsa_gate_apply(attn_ + tb * NH * HD, qfull_ + tb * NH * 2 * HD, attn32_ + tb * NH * HD, +@@ -1127,6 +1165,30 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, + // beside the expert workers). + const cudaError_t se = cudaStreamSynchronize(cs_); + if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } ++ if (trace_file_) { ++ const uint32_t count = (uint32_t) T; ++ const size_t width = (size_t) g_->n_head_kv * (size_t) g_->head_dim; ++ bool written = std::fwrite(&count, sizeof(count), 1, trace_file_) == 1 && ++ std::fwrite(&pos0, sizeof(pos0), 1, trace_file_) == 1; ++ for (int64_t q = 0; written && q < g_->n_qsa_layers(); ++q) ++ for (int t = 0; written && t < T; ++t) ++ written = std::fwrite(trace_h_ + ((size_t) q * max_t_ + t) * 2 * width, ++ sizeof(float), 2 * width, trace_file_) == 2 * width; ++ if (!written || std::fflush(trace_file_) != 0) { ++ err = "verify: cannot write keyless activation trace"; ++ return false; ++ } ++ const size_t query_width = (size_t) g_->n_head * (size_t) g_->head_dim; ++ bool q_written = std::fwrite(&count, sizeof(count), 1, trace_q_file_) == 1 && ++ std::fwrite(&pos0, sizeof(pos0), 1, trace_q_file_) == 1 && ++ std::fwrite(trace_q_h_, sizeof(float), ++ (size_t) g_->n_qsa_layers() * query_width, trace_q_file_) == ++ (size_t) g_->n_qsa_layers() * query_width; ++ if (!q_written || std::fflush(trace_q_file_) != 0) { ++ err = "verify: cannot write keyless query trace"; ++ return false; ++ } ++ } + progress_at("verify window: waiting for the expert copies", (int64_t) T); + cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one + if (prof_on_ && G == 1) { // the window's GPU stage stamps +diff --git a/src/kernels/cuda/keyless.cu b/src/kernels/cuda/keyless.cu +new file mode 100644 +index 00000000..16485d30 +--- /dev/null ++++ b/src/kernels/cuda/keyless.cu +@@ -0,0 +1,25 @@ ++#include "strata/core/keyless.hpp" ++#include ++#include ++namespace strata::kernels { ++namespace { ++__global__ void route_kernel(float* q, const float* matrices, int heads) { ++ __shared__ float row[256]; ++ const int d = threadIdx.x, h = blockIdx.x % heads; ++ float* query = q + (size_t)blockIdx.x * 256; ++ row[d] = query[d]; ++ __syncthreads(); ++ const float* weight = matrices + ((size_t)h * 256 + d) * 256; ++ float sum = 0; ++ for (int i = 0; i < 256; ++i) sum = fmaf(row[i], weight[i], sum); ++ query[d] = sum; ++} ++} ++void keyless_route_query(float* q, const float* matrices, int64_t tokens, int heads, int dim, void* stream) { ++ if (!q || !matrices || tokens < 1 || heads < 1 || dim != 256 || tokens > INT32_MAX / heads) ++ throw std::runtime_error("invalid keyless query routing geometry or artifact"); ++ route_kernel<<<(unsigned)(tokens*heads),256,0,(cudaStream_t)stream>>>(q, matrices, heads); ++ const auto error = cudaGetLastError(); ++ if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); ++} ++} +diff --git a/src/kernels/cuda/kv_q8.cu b/src/kernels/cuda/kv_q8.cu +index fb2ccec4..077e3167 100644 +--- a/src/kernels/cuda/kv_q8.cu ++++ b/src/kernels/cuda/kv_q8.cu +@@ -34,7 +34,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict + int head_dim, int page_size, KvHostPools host) { + const long long pos = (long long) __ldg(step + kStepPos); + const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x; +- const bool is_v = blockIdx.z == 1; ++ const bool is_v = k_q == nullptr || blockIdx.z == 1; + const int groups = head_dim / KV_Q8_GROUP; + const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t]; + // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order +@@ -58,7 +58,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict + (is_v ? v_q : k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? v_scale : k_scale)[row * groups + g] = sbits; + } +- if (host.k_q != nullptr) { ++ if ((is_v ? host.v_q : host.k_q) != nullptr) { + const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); + (is_v ? host.v_q : host.k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? host.v_scale : host.k_scale)[row * groups + g] = sbits; +@@ -104,7 +104,7 @@ void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_ + const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, + const KvHostPools* host) { + validate(s, "kv_append_q8"); +- const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), 2); ++ const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), k_q ? 2 : 1); + kv_append_q8_kernel<<>>( + k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, + (int) s.page_size, host ? *host : KvHostPools{}); +diff --git a/src/kernels/cuda/kv_stream.cu b/src/kernels/cuda/kv_stream.cu +index ec01ff22..ae78d8f0 100644 +--- a/src/kernels/cuda/kv_stream.cu ++++ b/src/kernels/cuda/kv_stream.cu +@@ -33,7 +33,11 @@ struct Runs { + Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const QsaShapes& s) { + const int rows = (int) (s.n_head_kv * s.page_size); + Runs r{}; +- if (fmt == kKvQ4) { ++ if (fmt == kKvValueInt8) { ++ r.src[0] = (const uint8_t*) host.v_q; r.dst[0] = (uint8_t*) slots.v_q; r.len[0] = rows * (int)s.head_dim; ++ r.src[1] = (const uint8_t*) host.v_scale; r.dst[1] = (uint8_t*) slots.v_scale; r.len[1] = rows * (int)(s.head_dim / KV_Q8_GROUP) * 2; ++ r.n = 2; ++ } else if (fmt == kKvQ4) { + const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim); + r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes; + r.src[1] = (const uint8_t*) host.v_q4; r.dst[1] = (uint8_t*) slots.v_q4; r.len[1] = bytes; +@@ -191,6 +195,7 @@ __global__ void ring_kernel(int32_t* table, long long n_blocks, long long n_slot + + uint64_t kv_block_bytes(const QsaShapes& s, int fmt) { + const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size); ++ if (fmt == kKvValueInt8) return rows * ((uint64_t)s.head_dim + (uint64_t)(s.head_dim / KV_Q8_GROUP)*2); + if (fmt == kKvQ4) return rows * kv_q4_bytes_per_head((int) s.head_dim) * 2; + return fmt == kKvInt8 ? rows * (uint64_t) s.head_dim * 2 + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 * 2 + : rows * (uint64_t) s.head_dim * 2 * 2; +diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu +index 4035999a..c59f21d4 100644 +--- a/src/kernels/cuda/qsa_decode_attn.cu ++++ b/src/kernels/cuda/qsa_decode_attn.cu +@@ -1,5 +1,6 @@ + // src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp. + #include "strata/kernels/qsa_decode_attn.hpp" ++#include "strata/kernels/mrope.hpp" + #include "strata/kernels/kv_q8.hpp" + #include "strata/kernels/kv_q4.hpp" + +@@ -71,7 +72,7 @@ __device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long + template + __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out); +- else if constexpr (KV_MODE == 1) load8_q8(p, value, row, d0, out); ++ else if constexpr (KV_MODE == 1 || KV_MODE == 4) load8_q8(p, value, row, d0, out); + else if constexpr (KV_MODE == 3) { + // hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call + // reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review) +@@ -127,7 +128,22 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest + continue; + } + float k8[8]; +- load8(p, false, srow[c], lane * 8, k8); ++ load8(p, KV_MODE == 4, srow[c], lane * 8, k8); ++ if constexpr (KV_MODE == 4) { ++ const int d0 = lane * 8, half = p.keyless_n_rot / 2; ++ if (d0 < p.keyless_n_rot) { ++ float paired[8]; ++ load8_q8(p, true, srow[c], d0 < half ? d0 + half : d0 - half, paired); ++ const int cell = ids[c0 + c]; ++ for (int d = 0; d < 8; ++d) { ++ const int pair = (d0 + d) % half; ++ const int rotary_pos = mrope_pos(p.keyless_mrope, cell, pair); ++ const float co = p.keyless_cos[(size_t)rotary_pos * half + pair]; ++ const float si = p.keyless_sin[(size_t)rotary_pos * half + pair]; ++ k8[d] = d0 < half ? k8[d]*co - paired[d]*si : k8[d]*co + paired[d]*si; ++ } ++ } ++ } + #pragma unroll + for (int h = 0; h < G; ++h) { + const float4 qa = *reinterpret_cast(&sq[h][lane * 8]); +@@ -160,7 +176,7 @@ __global__ void __launch_bounds__(THREADS) attn_chunk_kernel(const float* __rest + float v; + if constexpr (KV_MODE == 0) { + v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t])); +- } else if constexpr (KV_MODE == 1) { ++ } else if constexpr (KV_MODE == 1 || KV_MODE == 4) { + const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP])); + v = (float) p.v_q[srow[c] * HD + t] * sc; + } else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back +@@ -211,13 +227,18 @@ __global__ void __launch_bounds__(HD) attn_merge_kernel(const float* __restrict_ + void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, int64_t n_q, void* stream) { + if (n_q <= 0) return; +- if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !steps || ++ if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !steps || + !pools.page_table || n_q > 65535) { + std::fprintf(stderr, "qsa_decode_attn_batch: unsupported geometry or missing buffers\n"); + std::exit(1); + } +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 ++ const int kv_mode = pools.without_key ? 4 : pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); ++ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || ++ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { ++ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); ++ std::exit(1); ++ } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + // per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); +@@ -227,7 +248,9 @@ void qsa_decode_attn_batch(const float* q, const QsaAttnPools& pools, const int3 + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv, (unsigned) n_q); + cudaStream_t st = (cudaStream_t) stream; +- if (kv_mode == 3) ++ if (kv_mode == 4) ++ attn_chunk_kernel<4><<>>(q, pools, ids, steps, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks, (int)cap, stride); ++ else if (kv_mode == 3) + attn_chunk_kernel<3><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks, (int) cap, stride); + else if (kv_mode == 2) +@@ -255,19 +278,25 @@ uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) { + + void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) { +- if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !step || ++ if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !step || + !pools.page_table) { + std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n"); + std::exit(1); + } +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 ++ const int kv_mode = pools.without_key ? 4 : pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 + : (pools.k_q != nullptr ? 1 : 0)); +- if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) ++ if (kv_mode == 4 ? (!pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64) ++ : (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) + : (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale) +- : (!pools.k_pool || !pools.v_pool)))) { ++ : (!pools.k_pool || !pools.v_pool))))) { + std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n"); + std::exit(1); + } ++ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || ++ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { ++ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); ++ std::exit(1); ++ } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; +@@ -275,7 +304,9 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv); + cudaStream_t st = (cudaStream_t) stream; +- if (kv_mode == 3) ++ if (kv_mode == 4) ++ attn_chunk_kernel<4><<>>(q, pools, ids, step, (int)s.n_head_kv, (int)s.page_size, scale, part_acc, part_m, part_l, n_chunks); ++ else if (kv_mode == 3) + attn_chunk_kernel<3><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, + scale, part_acc, part_m, part_l, n_chunks); + else if (kv_mode == 2) +diff --git a/src/kernels/keyless_parity.cpp b/src/kernels/keyless_parity.cpp +new file mode 100644 +index 00000000..107ebf2b +--- /dev/null ++++ b/src/kernels/keyless_parity.cpp +@@ -0,0 +1,119 @@ ++// Independent CPU reference for query routing and physical V-only attention. ++#include "strata/core/keyless.hpp" ++#include "strata/core/layer.hpp" ++#include "strata/kernels/qsa_decode_attn.hpp" ++#include "strata/kernels/f16_bits.hpp" ++#include "strata/kernels/kv_stream.hpp" ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace { ++void check(cudaError_t e) { if (e != cudaSuccess) throw std::runtime_error(cudaGetErrorString(e)); } ++template T* device(const std::vector& values) { ++ T* p; check(cudaMalloc((void**)&p, values.size()*sizeof(T))); ++ check(cudaMemcpy(p, values.data(), values.size()*sizeof(T), cudaMemcpyHostToDevice)); return p; ++} ++} ++int main() { ++ using namespace strata::kernels; ++ try { ++ int count=0; if (cudaGetDeviceCount(&count)!=cudaSuccess || count==0) return 77; ++ constexpr int H=24, D=256, KV=2, CELLS=96, PAGE=4, BATCH=3, CAP=96; ++ std::vector query(BATCH*H*D), routing(H*D*D), routed(query.size()), co(CELLS*32), si(co.size()); ++ for (size_t i=0;i actual(query.size()); check(cudaMemcpy(actual.data(),dq,actual.size()*4,cudaMemcpyDeviceToHost)); ++ double route_error=0; for(size_t i=0;i2e-6) throw std::runtime_error("query routing disagrees with independent matrix product"); ++ const int pos[BATCH]={31,63,95}; ++ for(int p=0;p unrotated=routed; ++ std::vector positions(CELLS*3); ++ for(int cell=0;cell table(CELLS/PAGE), ids(BATCH*CAP,-1), steps(BATCH*kStepCount); ++ for(int page=0;page values(CELLS*KV*D); ++ std::vector scales(CELLS*KV*4); ++ for(int cell=0;cell scratch(BATCH*qsa_decode_attn_scratch_floats(CAP,qsa_real_shapes())), result(BATCH*H*D); ++ float *dsc=device(scratch), *dout=device(result); ++ qsa_decode_attn_batch(dq,pools,di,ds,CAP,qsa_real_shapes(),dsc,dout,BATCH,nullptr); ++ check(cudaMemcpy(result.data(),dout,result.size()*4,cudaMemcpyDeviceToHost)); ++ double error_sq=0, reference_sq=0, max_error=0; ++ for(int b=0;b scores(width), weights(width), reference(D,0); ++ for(int j=0;j1e-5 || max_error>1e-5) throw std::runtime_error("V-only attention disagrees with positional CPU reference"); ++ if(kv_block_bytes(qsa_real_shapes(),kKvValueInt8)*2!=kv_block_bytes(qsa_real_shapes(),kKvInt8)) ++ throw std::runtime_error("V-only block accounting is not half of K+V"); ++ std::printf("mrope=%d query_max_abs_error=%.9g attention_relative_l2=%.9g attention_max_abs_error=%.9g\n",vision,route_error,l2,max_error); ++ } ++ ++ std::printf("PASS: routed queries; three causal selections; permuted pages; raw value retrieval; no K allocation\n"); ++ return 0; ++ } catch(const std::exception& e) { std::fprintf(stderr,"keyless parity: %s\n",e.what()); return 1; } ++} +diff --git a/src/kernels/kv_stream_parity.cpp b/src/kernels/kv_stream_parity.cpp +index 07557347..e8b28765 100644 +--- a/src/kernels/kv_stream_parity.cpp ++++ b/src/kernels/kv_stream_parity.cpp +@@ -24,11 +24,13 @@ + #include + #include + #include ++#include + + namespace k = strata::kernels; + + namespace { + int g_fail = 0; ++float *keyless_cos=nullptr, *keyless_sin=nullptr; + void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } + } +@@ -55,10 +57,10 @@ struct Pools { // one K/V pool set of `pages` pages + const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim); + p.k_q4 = host ? halloc(b) : dalloc(b); + p.v_q4 = host ? halloc(b) : dalloc(b); +- } else if (fmt == k::kKvInt8) { +- p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); ++ } else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) { ++ if (fmt != k::kKvValueInt8) p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); + p.v_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); +- p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); ++ if (fmt != k::kKvValueInt8) p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + p.v_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + } else { + p.k_pool = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); +@@ -68,6 +70,8 @@ struct Pools { // one K/V pool set of `pages` pages + k::QsaAttnPools attn(const int32_t* table) const { + k::QsaAttnPools a; + a.k_pool = p.k_pool; a.v_pool = p.v_pool; a.k_q = p.k_q; a.v_q = p.v_q; a.k_scale = p.k_scale; ++ a.without_key = p.v_q && !p.k_q; ++ a.keyless_cos=keyless_cos; a.keyless_sin=keyless_sin; a.keyless_n_rot=64; + a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table; + return a; + } +@@ -76,7 +80,7 @@ struct Pools { // one K/V pool set of `pages` pages + void append(const Pools& pl, const int32_t* table, const int32_t* step, const float* kc, const float* vc, + const k::QsaShapes& s, int fmt, const k::KvHostPools* host) { + if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host); +- else if (fmt == k::kKvInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); ++ else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); + else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host); + } + +@@ -103,7 +107,7 @@ std::vector selection(int64_t n_kv, int64_t width, std::mt19937& rng) { + } + + bool run(int fmt) { +- const char* name = fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; ++ const char* name = fmt == k::kKvValueInt8 ? "v-only-int8" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; + k::QsaShapes s = k::qsa_real_shapes(); + const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700; // must evict: slots < blocks + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8; +@@ -111,6 +115,16 @@ bool run(int fmt) { + std::mt19937 rng(7 + 4 * fmt); + std::normal_distribution nd(0.f, 1.f); + ++ if (fmt == k::kKvValueInt8) { ++ std::vector co(N*32), si(N*32); ++ for(int64_t pos=0;pos(co.size()); keyless_sin=dalloc(si.size()); ++ ck(cudaMemcpy(keyless_cos,co.data(),co.size()*4,cudaMemcpyHostToDevice),"cos"); ++ ck(cudaMemcpy(keyless_sin,si.data(),si.size()*4,cudaMemcpyHostToDevice),"sin"); ++ } + Pools ref, slots, host; + ref.alloc(n_blocks, s, fmt, false); + slots.alloc(n_slots, s, fmt, false); +@@ -225,7 +239,9 @@ bool run(int fmt) { + } + } // namespace + +-int main() { ++int main(int argc, char** argv) { ++ int count=0; if(cudaGetDeviceCount(&count)!=cudaSuccess || !count) return 77; ++ if(argc==2 && std::strcmp(argv[1],"--v-only")==0) return run(k::kKvValueInt8)?0:1; + std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n"); + const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4); + if (!a || !b || !c) ++g_fail; +diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp +index 1a1552bf..bcb611c1 100644 +--- a/src/kernels/ngram.cpp ++++ b/src/kernels/ngram.cpp +@@ -11,12 +11,31 @@ + #include + #include + #include ++#include ++#include ++#include + #if !defined(_WIN32) + #include + #endif + #include + #include + ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++#include ++#include ++#endif ++ ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) || defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++#include ++#include ++#endif ++ ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++#include "kar_ple_cache.hpp" ++#include "libkar.h" ++#include ++#endif ++ + #if defined(_WIN32) + // `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below. + #define WIN32_LEAN_AND_MEAN +@@ -29,6 +48,69 @@ namespace strata::kernels { + namespace { + /// The A/B arm. Host-token-path only, so it needs no atomics; see the note on `ple_prefetch_enable`. + bool g_ple_prefetch = true; ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++struct PleRowTrace { ++ int fd = -1; ++ std::mutex lock; ++ bool failed = false; ++ ++ PleRowTrace() { ++ const char* path = std::getenv("STRATA_PLE_ROW_TRACE_PATH"); ++ if (!path) return; ++ if (!*path) { ++ std::fprintf(stderr, "PLE row trace needs a private output path\n"); ++ return; ++ } ++ fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); ++ if (fd < 0) { ++ std::perror("cannot create private PLE row trace"); ++ return; ++ } ++ constexpr char header[] = "# strata-ple-rows v1: 16 global u32 row IDs per line\n"; ++ if (write(fd, header, sizeof(header) - 1) != static_cast(sizeof(header) - 1)) { ++ std::fprintf(stderr, "cannot write PLE row trace header\n"); ++ failed = true; ++ } ++ } ++ ++ ~PleRowTrace() { if (fd >= 0) close(fd); } ++ ++ void emit(const uint32_t* rows) { ++ if (fd < 0) return; ++ std::lock_guard guard(lock); ++ if (failed) return; ++ char line[PLE_N_HEADS * 12]; ++ size_t used = 0; ++ for (int h = 0; h < PLE_N_HEADS; ++h) { ++ const int written = std::snprintf(line + used, sizeof(line) - used, "%u%c", ++ rows[h], h + 1 == PLE_N_HEADS ? '\n' : ' '); ++ if (written < 0 || static_cast(written) >= sizeof(line) - used) { ++ failed = true; ++ std::fprintf(stderr, "PLE row trace line exceeded its buffer\n"); ++ return; ++ } ++ used += static_cast(written); ++ } ++ size_t done = 0; ++ while (done < used) { ++ const ssize_t n = write(fd, line + done, used - done); ++ if (n < 0 && errno == EINTR) continue; ++ if (n <= 0) { ++ failed = true; ++ if (n < 0) std::perror("cannot write PLE row trace"); ++ else std::fprintf(stderr, "cannot write PLE row trace: short write\n"); ++ return; ++ } ++ done += static_cast(n); ++ } ++ } ++}; ++ ++PleRowTrace& ple_row_trace() { ++ static PleRowTrace trace; ++ return trace; ++} ++#endif + } // namespace + + void ple_prefetch_enable(bool on) { g_ple_prefetch = on; } +@@ -89,6 +171,9 @@ void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const + out[i * PLE_N_HEADS + h] = (uint32_t) (mixed % c.vocab[h] + c.offset[h]); + } + } ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++ ple_row_trace().emit(out + i * PLE_N_HEADS); ++#endif + } + } + +@@ -153,6 +238,51 @@ struct PleTable::Impl { + bool fp8 = false; // F8_E4M3 rows (tools/ple_fp8_pack.py); else IQ4_NL + float scale = 1.0f; // the FP8 table's one scale + uint32_t rb = PLE_ROW_BYTES; // bytes per row ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ struct KarPart { ++ uint32_t number = 0; ++ uint64_t row_base = 0; ++ const kar_tensor_info* tensor = nullptr; ++ }; ++ kar_archive* kar = nullptr; ++ int kar_fd = -1; ++ const uint8_t* kar_map = nullptr; ++ size_t kar_bytes = 0; ++ uint32_t kar_level = 0; ++ std::string kar_format; ++ std::vector kar_parts; ++ std::unique_ptr kar_gpu_cache; ++ void decode_kar_row(uint32_t row, float* out160) const { ++ const auto part = std::lower_bound(kar_parts.begin(), kar_parts.end(), row, ++ [](const KarPart& item, uint32_t wanted) { ++ return item.row_base + item.tensor->row_count <= wanted; ++ }); ++ const kar_tensor_info* t = part->tensor; ++ const uint64_t local_row = uint64_t(row) - part->row_base; ++ const uint64_t first_word = local_row * t->row_words; ++ const uint64_t book_offset = t->books_offset + ((uint64_t{1} << kar_level) - 2) * 2; ++ for (uint32_t word = 0; word < t->row_words; ++word) { ++ const uint64_t source_word = first_word + word; ++ const uint64_t scale_offset = t->scales_offset + 2 * (source_word / (t->group / 32)); ++ const float scale = strata::fp16_to_fp32(strata::read_u16(kar_map + scale_offset)); ++ uint32_t bits[8] = {}; ++ for (uint32_t level = 0; level < kar_level; ++level) { ++ const uint8_t* p = kar_map + t->planes_offset + uint64_t(level) * t->plane_stride_bytes ++ + source_word * 4; ++ bits[level] = uint32_t(p[0]) | (uint32_t(p[1]) << 8) | ++ (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); ++ } ++ for (uint32_t bit = 0; bit < 32; ++bit) { ++ uint32_t code = 0; ++ for (uint32_t level = 0; level < kar_level; ++level) ++ code = (code << 1) | ((bits[level] >> bit) & 1u); ++ const float book = strata::fp16_to_fp32(strata::read_u16(kar_map + book_offset + code * 2)); ++ out160[word * 32 + bit] = book * scale; ++ } ++ } ++ bytes_read += t->row_words * (uint64_t(kar_level) * 4 + 2); ++ } ++#endif + void decode(const uint8_t* row, float* out160) const { + if (fp8) fp8_e4m3_dequant_row(row, scale, out160); + else if (q5_0) +@@ -164,6 +294,177 @@ struct PleTable::Impl { + PleTable::PleTable() : impl_(new Impl) {} + PleTable::~PleTable() { close(); delete impl_; } + ++bool PleTable::open_kar(const std::string& kar_path, uint32_t level, std::string& err, ++ uint64_t expected_rows) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) kar_path; (void) level; (void) expected_rows; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ close(); ++ if (level < 1 || level > 8 || expected_rows == 0) { ++ err = "KAR PLE level or expected row count is invalid"; ++ return false; ++ } ++ kar_archive* archive = nullptr; ++ const kar_status status = kar_open(kar_path.c_str(), KAR_OPEN_VERIFY_PAYLOAD, &archive); ++ if (status != KAR_OK) { ++ err = std::string("KAR PLE archive: ") + kar_strerror(status) + ": " + kar_last_error(); ++ return false; ++ } ++ impl_->kar = archive; ++ impl_->kar_fd = ::open(kar_path.c_str(), O_RDONLY | O_CLOEXEC); ++ struct stat file_info {}; ++ if (impl_->kar_fd < 0 || fstat(impl_->kar_fd, &file_info) || file_info.st_size <= 0 || ++ uint64_t(file_info.st_size) != kar_info(impl_->kar)->archive_bytes) { ++ err = "KAR PLE cannot reopen the verified archive at its expected length"; ++ close(); ++ return false; ++ } ++ impl_->kar_bytes = size_t(file_info.st_size); ++ void* map = mmap(nullptr, impl_->kar_bytes, PROT_READ, MAP_PRIVATE, impl_->kar_fd, 0); ++ if (map == MAP_FAILED) { ++ err = "KAR PLE cannot map the verified archive"; ++ close(); ++ return false; ++ } ++ impl_->kar_map = static_cast(map); ++ const std::string parent = "per_layer_token_embd.weight"; ++ const std::string prefix = parent + "#strata-part-"; ++ uint32_t declared_parts = 0; ++ for (uint32_t i = 0; i < kar_tensor_count(impl_->kar); ++i) { ++ const kar_tensor_info* t = kar_tensor(impl_->kar, i); ++ const std::string name = t->name; ++ uint32_t number = 0, total = 0; ++ if (name == parent) { ++ number = total = 1; ++ } else if (name.rfind(prefix, 0) == 0) { ++ char extra = 0; ++ if (std::sscanf(name.c_str() + prefix.size(), "%u-of-%u%c", &number, &total, &extra) != 2) { ++ err = "KAR PLE part name is malformed"; ++ close(); ++ return false; ++ } ++ } else { ++ continue; ++ } ++ if (!number || !total || number > total || (declared_parts && declared_parts != total) || ++ t->storage_class != KAR_NESTED || t->source_dtype != KAR_F32 || ++ t->nesting != KAR_TOPDOWN || t->n_dims != 2 || ++ t->dims[0] != PLE_HEAD_DIM || t->row_words != PLE_HEAD_DIM / 32 || ++ t->n_elements % PLE_HEAD_DIM || t->group < 32 || t->group % 32 || ++ level < t->planes_min || level > t->planes_max) { ++ err = "KAR PLE part geometry or precision level differs from the model"; ++ close(); ++ return false; ++ } ++ declared_parts = total; ++ impl_->kar_parts.push_back({number, 0, t}); ++ } ++ std::sort(impl_->kar_parts.begin(), impl_->kar_parts.end(), ++ [](const Impl::KarPart& left, const Impl::KarPart& right) { ++ return left.number < right.number; ++ }); ++ if (!declared_parts || impl_->kar_parts.size() != declared_parts) { ++ err = "KAR PLE parts are absent or incomplete"; ++ close(); ++ return false; ++ } ++ uint64_t rows = 0; ++ for (uint32_t i = 0; i < impl_->kar_parts.size(); ++i) { ++ auto& part = impl_->kar_parts[i]; ++ if (part.number != i + 1 || part.tensor->row_count == 0 || ++ part.tensor->row_count > expected_rows - rows) { ++ err = "KAR PLE parts are out of order or exceed expected rows"; ++ close(); ++ return false; ++ } ++ part.row_base = rows; ++ rows += part.tensor->row_count; ++ } ++ if (rows != expected_rows) { ++ err = "KAR PLE row count differs from the model"; ++ close(); ++ return false; ++ } ++ impl_->n_rows = rows; ++ impl_->kar_level = level; ++ impl_->kar_format = "KAR-L" + std::to_string(level) + "-CPU"; ++ impl_->mode = PleIo::Mmap; ++ return true; ++#endif ++} ++ ++bool PleTable::enable_kar_gpu_cache(uint32_t cache_mib, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) cache_mib; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar || impl_->kar_level != 2 || impl_->kar_gpu_cache) { ++ err = "KAR PLE GPU cache requires an open level-2 archive and no existing cache"; ++ return false; ++ } ++ std::vector parts; ++ parts.reserve(impl_->kar_parts.size()); ++ for (const auto& part : impl_->kar_parts) parts.push_back({part.row_base, part.tensor}); ++ auto cache = std::make_unique(); ++ if (!cache->open(impl_->kar_map, impl_->kar_bytes, parts, cache_mib, 65536, err)) return false; ++ impl_->kar_gpu_cache = std::move(cache); ++ impl_->kar_format = "KAR-L2-GPU-cache"; ++ return true; ++#endif ++} ++ ++bool PleTable::kar_gpu_cache_enabled() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ return impl_->kar_gpu_cache != nullptr; ++#else ++ return false; ++#endif ++} ++ ++bool PleTable::collect_device(float* device_out2560, void* stream, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) device_out2560; (void) stream; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar_gpu_cache || !impl_->pending) { ++ err = "KAR PLE GPU collect requires a cache and an issued token"; ++ return false; ++ } ++ if (!impl_->kar_gpu_cache->enqueue(impl_->rows, PLE_N_HEADS, device_out2560, ++ reinterpret_cast(stream), err)) return false; ++ impl_->pending = false; ++ return true; ++#endif ++} ++ ++bool PleTable::gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, ++ void* stream, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) rows; (void) n_tokens; (void) device_out; (void) stream; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar_gpu_cache || impl_->pending || !rows || !device_out || ++ n_tokens == 0 || n_tokens > 65536) { ++ err = "KAR PLE GPU gather requires a cache, no pending token, and 1..65536 tokens"; ++ return false; ++ } ++ const size_t count = n_tokens * PLE_N_HEADS; ++ const size_t chunk_rows = std::min(65536, impl_->kar_gpu_cache->slots()); ++ for (size_t offset = 0; offset < count; offset += chunk_rows) { ++ const size_t length = std::min(chunk_rows, count - offset); ++ if (!impl_->kar_gpu_cache->enqueue(rows + offset, length, ++ device_out + offset * PLE_HEAD_DIM, ++ reinterpret_cast(stream), err)) return false; ++ } ++ return true; ++#endif ++} ++ + bool PleTable::open(const std::string& gguf_path, std::string& err) { + return open(gguf_path, err, PleIoOptions{}); + } +@@ -280,6 +581,19 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoO + } + + void PleTable::close() { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ impl_->kar_gpu_cache.reset(); ++ if (impl_->kar_map) munmap(const_cast(impl_->kar_map), impl_->kar_bytes); ++ impl_->kar_map = nullptr; ++ impl_->kar_bytes = 0; ++ if (impl_->kar_fd >= 0) ::close(impl_->kar_fd); ++ impl_->kar_fd = -1; ++ if (impl_->kar) kar_close(impl_->kar); ++ impl_->kar = nullptr; ++ impl_->kar_parts.clear(); ++ impl_->kar_level = 0; ++ impl_->kar_format.clear(); ++#endif + impl_->reader.close(); + impl_->pending = false; + impl_->locked = false; // the unmap below releases the lock +@@ -293,14 +607,31 @@ void PleTable::close() { + impl_->fp8 = false; + } + +-bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } ++bool PleTable::is_open() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) return true; ++#endif ++ return impl_->data != nullptr || impl_->reader.is_open(); ++} + bool PleTable::locked() const { return impl_->locked; } +-const char* PleTable::format() const { return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; } ++const char* PleTable::format() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) return impl_->kar_format.c_str(); ++#endif ++ return impl_->fp8 ? "F8_E4M3" : impl_->q5_0 ? "Q5_0" : "IQ4_NL"; ++} + PleIo PleTable::mode() const { return impl_->mode; } + uint64_t PleTable::rows() const { return impl_->n_rows; } + uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } + + void PleTable::read_row(uint32_t row, float* out160) const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) { ++ if (row >= impl_->n_rows) std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); ++ else impl_->decode_kar_row(row, out160); ++ return; ++ } ++#endif + if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { + uint8_t raw[PLE_ROW_BYTES_MAX]; + std::string err; +@@ -378,6 +709,21 @@ bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, s + void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delay_us(us); } + + std::string PleTable::io_report() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar_gpu_cache) { ++ const auto s = impl_->kar_gpu_cache->stats(); ++ char buf[300]; ++ std::snprintf(buf, sizeof buf, ++ "PLE GPU cache: %llu hits, %llu misses (%.2f%% hit), %u slots (%.1f MiB compressed), " ++ "%llu compressed bytes, %llu H2D argument bytes", ++ (unsigned long long) s.hits, (unsigned long long) s.misses, ++ s.hits + s.misses ? 100.0 * double(s.hits) / double(s.hits + s.misses) : 0.0, ++ impl_->kar_gpu_cache->slots(), double(impl_->kar_gpu_cache->slots()) * 64.0 / 1048576.0, ++ (unsigned long long) s.compressed_bytes, ++ (unsigned long long) s.host_to_device_bytes); ++ return buf; ++ } ++#endif + if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {}; + const strata::ngram::ReaderStats s = impl_->reader.snapshot(); + char buf[400]; +diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu +index de833442..4c5f4b82 100644 +--- a/src/prefill/kernels.cu ++++ b/src/prefill/kernels.cu +@@ -604,8 +604,9 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res + uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + strata::kernels::KvHostPools host, strata::kernels::KvHostPools stage) { + const int64_t t = blockIdx.x; +- const int kvh = blockIdx.y, g = blockIdx.z >> 1; +- const bool is_v = (blockIdx.z & 1) != 0; ++ const bool value_only = k_pool == nullptr && k_q == nullptr; ++ const int kvh = blockIdx.y, g = value_only ? blockIdx.z : blockIdx.z >> 1; ++ const bool is_v = value_only || (blockIdx.z & 1) != 0; + const int d = g * 64 + threadIdx.x; + const float x = (is_v ? V : K)[t * 512 + kvh * 256 + d]; + const int64_t pos = pos0 + t; +@@ -633,11 +634,11 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res + (is_v ? v_q : k_q)[row * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? v_scale : k_scale)[row * 4 + g] = sb; + } +- if (host.k_q != nullptr) { ++ if ((is_v ? host.v_q : host.k_q) != nullptr) { + (is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb; + } +- if (stage.k_q != nullptr) { ++ if ((is_v ? stage.v_q : stage.k_q) != nullptr) { + (is_v ? stage.v_q : stage.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb; + } +@@ -665,7 +666,7 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in + uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) { + if (T <= 0) return; +- kv_append_kernel<<>>( ++ kv_append_kernel<<>>( + K, V, pos0, page_table, page_size, k_pool, v_pool, k_q, v_q, k_scale, v_scale, + host ? *host : strata::kernels::KvHostPools{}, stage ? *stage : strata::kernels::KvHostPools{}); + check("kv_append"); +diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp +index ed47b975..37edb9f0 100644 +--- a/src/prefill/prefill.cpp ++++ b/src/prefill/prefill.cpp +@@ -13,10 +13,12 @@ + #include "strata/kernels/iq_kernels.hpp" + #include "strata/kernels/cpu/expert_layout.hpp" + #include "strata/kernels/qsa.hpp" ++#include "strata/kernels/mrope.hpp" + #include "strata/kernels/kv_stream.hpp" + #include "strata/kernels/cvec.hpp" + #include "strata/kernels/kv_q4.hpp" + #include "strata/core/layer.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/native_head.hpp" + #include "strata/kernels/verify_kernels.hpp" + #include "strata/kernels/qsa_decode_attn.hpp" +@@ -40,6 +42,8 @@ + #include + #include + #include ++#include ++#include + + #ifndef STRATA_PREFILL_MMQ + // A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere. +@@ -386,9 +390,9 @@ void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::k + st.k_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + st.v_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + } else if (q0.kv_int8) { +- st.k_q = o.take(rows * s.head_dim, ok); ++ if (!q0.without_key) st.k_q = o.take(rows * s.head_dim, ok); + st.v_q = o.take(rows * s.head_dim, ok); +- st.k_scale = o.take(rows * (s.head_dim / 64), ok); ++ if (!q0.without_key) st.k_scale = o.take(rows * (s.head_dim / 64), ok); + st.v_scale = o.take(rows * (s.head_dim / 64), ok); + } else { + st.k_pool = o.take(rows * s.head_dim, ok); +@@ -998,6 +1002,21 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + const core::ModelGeometry& g = *m.g; + core::SessionState& ss = *m.ss; + const auto t_start = Clock::now(); ++ // Offline teacher capture for fitting only the paper's query-routing parameters. ++ // Explicitly bounded and prohibited in serving; this path never predicts or stores K in V-only mode. ++ std::ofstream keyless_trace; ++ if (const char* path = std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) { ++ if (!*path || n > 4096 || pos0 != 0 || ss.qsa_states[0].without_key || std::filesystem::exists(path)) { ++ err = "keyless teacher trace requires a new private file, ordinary K+V and at most 4096 prompt tokens"; ++ return false; ++ } ++ keyless_trace.open(path, std::ios::binary); ++ if (!keyless_trace) { err = "cannot open keyless teacher trace"; return false; } ++ std::filesystem::permissions(path, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write); ++ keyless_trace.write("SKLTRACE", 8); ++ const uint32_t header[5] = {1, (uint32_t)g.n_qsa_layers(), (uint32_t)g.n_head, (uint32_t)g.n_head_kv, (uint32_t)g.head_dim}; ++ keyless_trace.write((const char*)header, sizeof(header)); ++ } + const int64_t LB = stage_lb_, LE = stage_le_; + // the next stage reads chunk c on a thread while this one reads chunk c + 1 (declared first: an early return + // waits for it before anything it reads goes away) +@@ -1020,6 +1039,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + // after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows + // depend only on the tokens (the two before a position name its n-grams), so this is the same data. + const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE; ++ const bool ple_gpu_cache = ple_on && ss.ple.table->kar_gpu_cache_enabled(); + // the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token); + // STRATA_PLE_BATCH=0 keeps the per-token block (the A/B) + static const bool ple_batch_env = [] { +@@ -1030,7 +1050,7 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + (ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) && + m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64; + const int32_t prev0[2] = {prev[0], prev[1]}; +- auto ple_gather = [&m, &ss, tokens, n, prev0](int64_t c0, int buf, std::string& e) -> bool { ++ auto ple_gather = [&m, &ss, tokens, n, prev0, ple_gpu_cache](int64_t c0, int buf, std::string& e) -> bool { + const int64_t T = std::min(m.T, n - c0); + auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; }; // prev0, then the tokens + int32_t pv[2] = {at(c0), at(c0 + 1)}; +@@ -1041,7 +1061,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + pv[0] = pv[1]; + pv[1] = tok; + } +- return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e); ++ return ple_gpu_cache || ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, ++ m.ple_emb_host[buf], e); + }; + std::string ple_next_err; + std::future ple_next; // declared after everything it reads: an early return waits for it +@@ -1112,21 +1133,27 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + // ---- the PLE rows of the whole chunk, one batched SSD request (read ahead on a thread, see ple_gather) + if (ple_on) { + const auto tp = Clock::now(); +- if (!ple_next.valid()) { ++ if (ple_gpu_cache) { ++ if (!ple_gather(c0, 0, err) || ++ !ss.ple.table->gather_batch_device(m.ple_rows[0].data(), (size_t) T, ++ m.ple_emb, m.cs, err)) return false; ++ } else if (!ple_next.valid()) { + if (!ple_gather(c0, ple_buf, err)) return false; + } else if (!ple_next.get()) { + err = ple_next_err; + return false; + } +- cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs); +- cudaEventRecord(m.ple_copied[ple_buf], m.cs); +- if (c0 + m.T < n) { +- cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done +- ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { +- return ple_gather(c1, b, ple_next_err); +- }); ++ if (!ple_gpu_cache) { ++ cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs); ++ cudaEventRecord(m.ple_copied[ple_buf], m.cs); ++ if (c0 + m.T < n) { ++ cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done ++ ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { ++ return ple_gather(c1, b, ple_next_err); ++ }); ++ } ++ ple_buf ^= 1; + } +- ple_buf ^= 1; + stats_.ms_ple += ms_since(tp); + } + for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1]; prev[1] = (int32_t) tokens[c0 + t]; } +@@ -1374,13 +1401,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + *wikn = need(v, "indexer.k_norm.weight", err); + if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false; + pt.mark(kPfQsa, cs); +- if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; ++ if (!st.without_key && !native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; + if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false; + if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false; + if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) 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, strata::kernels::rope_scaling(), m.cs); ++ if (!st.without_key) rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); ++ if (!st.without_key) 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; +@@ -1413,6 +1440,19 @@ 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); ++ if (keyless_trace.is_open()) { ++ const int32_t record[3] = {(int32_t)l, (int32_t)p0, (int32_t)T}; ++ keyless_trace.write((const char*)record, sizeof(record)); ++ for (const auto& tensor : std::vector>{ ++ {m.q,(size_t)T*24*256}, {m.Kc,(size_t)T*2*256}, {m.Vc,(size_t)T*2*256}}) { ++ std::vector host(tensor.second); ++ if (cudaMemcpyAsync(host.data(), tensor.first, host.size()*sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess || ++ cudaStreamSynchronize(cs) != cudaSuccess) { err="keyless teacher readback failed"; return false; } ++ keyless_trace.write((const char*)host.data(), host.size()*sizeof(float)); ++ } ++ if (!keyless_trace) { err="keyless teacher trace write failed"; return false; } ++ } ++ if (st.without_key) strata::kernels::keyless_route_query(m.q, core::keyless_routing(l), T, 24, 256, m.cs); + rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); + if (st.kv_rot) 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); +@@ -1539,15 +1579,17 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e + } + } + } +- const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) ++ strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) + : core::qsa_attn_pools(st); ++ pools.without_key = st.without_key; ++ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + pt.mark(kPfQsaAttn, cs); + // perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level + // accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the + // decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K, + // V dequantized from its q4_0 blocks to fp16 at gather) + static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr; +- if (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, ++ if (st.without_key || old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, + m.attn, T, m.cs)) + for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) { + const int64_t nb = std::min(m.attn_batch, T - t0); +diff --git a/src/program/generate.cpp b/src/program/generate.cpp +index 53c38a00..1e8cdfa3 100644 +--- a/src/program/generate.cpp ++++ b/src/program/generate.cpp +@@ -20,6 +20,9 @@ + #include "strata/core/conversation_memory.hpp" + #include "strata/core/coupled_draft.hpp" + #include "strata/core/expert_source.hpp" ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++#include "kar_expert_miss.hpp" ++#endif + #include "strata/core/pinned.hpp" + #include "strata/core/remote_experts.hpp" + #include "strata/core/on_device.hpp" +@@ -50,6 +53,7 @@ + #include "strata/core/mtp.hpp" + #include "strata/prefill/prefill.hpp" + #include "strata/core/native_dense.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/program/logits_selection.hpp" + #include "strata/program/conv_cache.hpp" + #include "strata/spec/draft_policy.hpp" +@@ -220,6 +224,9 @@ struct Options { + std::string embd_gguf; + /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. + std::string ple_io = "direct"; ++ std::string ple_kar; ///< experimental PLE-only KAR quality arm; all other weights stay native ++ uint32_t ple_kar_level = 2; ++ uint32_t ple_kar_gpu_cache_mib = 0; ///< opt-in bounded compressed GPU PLE cache; 0 keeps CPU gather + int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables + int ple_inflight = 64; + double ple_delay_us = 0; ///< fault injection: every row read completes no earlier than this +@@ -423,6 +430,9 @@ void usage() { + " --tokens-file PATH pretokenized prompt, commas or whitespace (alternative to --tokens)\n" + " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" + " shard that holds per_layer_token_embd.weight when not given\n" ++ " --ple-kar PATH experimental PLE-only KAR CPU quality arm (requires a KAR-enabled build)\n" ++ " --ple-kar-level N precision of the experimental PLE KAR arm (default 2)\n" ++ " --ple-kar-gpu-cache-mib N experimental compressed PLE row cache in VRAM (1..1024; level 2)\n" + " --no-ple explicit diagnostic ablation of the PLE layer\n" + " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" + " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" +@@ -1053,6 +1063,29 @@ int main(int argc, char** argv) { + else if (a == "--dump-halves") o.dump_halves = next("--dump-halves"); + else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); + else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); ++ else if (a == "--ple-kar") o.ple_kar = next("--ple-kar"); ++ else if (a == "--ple-kar-level") { ++ const std::string value = next("--ple-kar-level"); ++ unsigned level = 0; ++ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), level); ++ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || ++ level < 1 || level > 8) { ++ std::fprintf(stderr, "strata generate: --ple-kar-level must be an integer from 1 to 8\n"); ++ return 2; ++ } ++ o.ple_kar_level = level; ++ } ++ else if (a == "--ple-kar-gpu-cache-mib") { ++ const std::string value = next("--ple-kar-gpu-cache-mib"); ++ unsigned mib = 0; ++ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), mib); ++ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || ++ mib < 1 || mib > 1024) { ++ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib must be 1..1024\n"); ++ return 2; ++ } ++ o.ple_kar_gpu_cache_mib = mib; ++ } + else if (a == "--no-ple") o.no_ple = true; + else if (a == "--ple-io") o.ple_io = next("--ple-io"); + else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); +@@ -1254,6 +1287,10 @@ int main(int argc, char** argv) { + } + } + strata::core::set_coupled_draft(o.coupled_draft); ++ if ((std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) && (o.serve || o.max_new > 512)) { ++ std::fprintf(stderr, "strata generate: STRATA_KEYLESS_TRACE is offline only and needs --max-new <= 512\n"); ++ return 2; ++ } + if (o.serve && o.conversation_cache_mib > 0 && (o.prompt_cache == 0 || o.conversation_cache_slots == 0)) + std::fprintf(stderr, "strata serve: warning: conversation caching is disabled by %s\n", + o.prompt_cache == 0 ? "--prompt-cache 0" : "--conversation-cache-slots 0"); +@@ -1469,6 +1506,11 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n"); + return 2; + } ++ const char* keyless_path = std::getenv("STRATA_KEYLESS_ROUTING"); ++ if (keyless_path && (!*keyless_path || o.kv != "int8" || o.gpu_stages || !o.dump_halves.empty() || std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE") || (std::getenv("STRATA_KV_ROT") && std::getenv("STRATA_KV_ROT")[0] == '1'))) { ++ std::fprintf(stderr, "strata: keyless requires INT8, no Hadamard rotation, one GPU stage and no diagnostic dumps\n"); return 2; ++ } ++ strata::core::qsa_set_without_key(keyless_path != nullptr); + strata::core::qsa_set_kv_int8(o.kv == "int8"); + strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) + // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to +@@ -1547,6 +1589,15 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n"); + return 2; + } ++ if ((o.no_ple && !o.ple_kar.empty()) || (o.ple_kar.empty() && o.ple_kar_level != 2) || ++ (!o.ple_kar.empty() && (o.ple_kar_level < 1 || o.ple_kar_level > 8 || o.ple_io != "direct"))) { ++ std::fprintf(stderr, "strata generate: --ple-kar requires PLE, level 1..8, and default --ple-io\n"); ++ return 2; ++ } ++ if (o.ple_kar_gpu_cache_mib && (o.ple_kar.empty() || o.ple_kar_level != 2)) { ++ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib requires --ple-kar at level 2\n"); ++ return 2; ++ } + if (o.native_ple_postops && o.no_ple) { + std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n"); + return 2; +@@ -1843,6 +1894,37 @@ int main(int argc, char** argv) { + rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); + } + } ++ const char* kar_expert_archive = std::getenv("STRATA_NEXT_KAR_EXPERTS_ARCHIVE"); ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ strata::kar::ExpertMiss kar_expert_miss; ++ if (kar_expert_archive != nullptr) { ++ const char* level_text = std::getenv("STRATA_NEXT_KAR_EXPERTS_LEVEL"); ++ if (!native_pack || o.no_pool || !split_devs.empty() || remote_caches || ++ !level_text || std::strlen(level_text) != 1 || level_text[0] < '1' || level_text[0] > '8' || ++ g.n_embd != strata::kernels::cpu::H) { ++ std::fprintf(stderr, "strata generate: experimental KAR misses require a native pack, one GPU, " ++ "the expert pool and explicit STRATA_NEXT_KAR_EXPERTS_LEVEL=1..8\n"); ++ return 2; ++ } ++ for (const auto& f : strata::kernels::cpu::expert_layout().fmt) ++ if (f.n_embd != strata::kernels::cpu::H || f.n_ff != strata::kernels::cpu::FF) { ++ std::fprintf(stderr, "strata generate: unsupported KAR expert geometry\n"); return 2; ++ } ++ if (!kar_expert_miss.open(kar_expert_archive, (uint32_t) g.n_layers, (uint32_t) g.n_expert, ++ (uint32_t) g.n_embd, strata::kernels::cpu::FF, ++ (uint32_t) (level_text[0] - '0'), err)) { ++ std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; ++ } ++ // Native resident hits are the baseline. Route all otherwise CPU/PCIe ++ // misses to the explicit experimental arm; use pcie-frac=0 in its baseline. ++ o.pcie_frac = 0; ++ } ++#else ++ if (kar_expert_archive != nullptr) { ++ std::fprintf(stderr, "strata generate: this build has no experimental KAR expert support\n"); ++ return 2; ++ } ++#endif + strata::core::NativeEmbed native_embed; + if (native_pack) { + if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical || +@@ -1965,6 +2047,10 @@ int main(int argc, char** argv) { + return 2; + } + ++ if (keyless_path && !strata::core::keyless_load(keyless_path, wt, g, err)) { ++ std::fprintf(stderr, "strata: keyless routing: %s\n", err.c_str()); return 1; ++ } ++ if (keyless_path) std::fprintf(stderr, "strata: experimental V-only QSA query routing; indexer and MTP keys retained; quality gate pending\n"); + strata::core::SessionState ss; + void* sbuf = nullptr; // allocated after the layer-split search, sized to CUDA0's own layer range (the carve) + // **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session +@@ -2041,15 +2127,26 @@ int main(int argc, char** argv) { + pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; + if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; + } +- if (!ple_table.open(o.ple_gguf, err, pio)) { ++ const bool ple_open = o.ple_kar.empty() ? ple_table.open(o.ple_gguf, err, pio) ++ : ple_table.open_kar(o.ple_kar, o.ple_kar_level, err); ++ if (!ple_open) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } ++ if (o.ple_kar_gpu_cache_mib && !ple_table.enable_kar_gpu_cache(o.ple_kar_gpu_cache_mib, err)) { ++ std::fprintf(stderr, "strata generate: PLE GPU cache: %s\n", err.c_str()); ++ return 1; ++ } + if (pio.lock) + std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", + ple_table.locked() ? "locked in RAM" : "loaded (not locked)", + std::chrono::duration(Clock::now() - tpl).count()); +- if (pio.keepalive_ms > 0) ++ if (!o.ple_kar.empty()) ++ std::fprintf(stderr, "strata generate: experimental PLE KAR %s arm at level %u%s\n", ++ o.ple_kar_gpu_cache_mib ? "bounded GPU-cache" : "CPU quality", ++ o.ple_kar_level, ++ o.ple_kar_gpu_cache_mib ? " (prefill/decode CUDA, speculative verification CPU)" : ""); ++ else if (pio.keepalive_ms > 0) + std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " + "%.0f ms without a read, until %.0f s after the last request " + "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); +@@ -2468,7 +2565,8 @@ int main(int argc, char** argv) { + return 1; + } + std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n", +- (unsigned long long) ple_table.rows(), o.ple_gguf.c_str()); ++ (unsigned long long) ple_table.rows(), ++ o.ple_kar.empty() ? o.ple_gguf.c_str() : o.ple_kar.c_str()); + } + } + for (size_t i = 0; i < stages.size(); ++i) { +@@ -3022,6 +3120,12 @@ int main(int argc, char** argv) { + } + + Drive drive; ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if (kar_expert_archive != nullptr) { ++ drive.d.experimental_miss = &strata::kar::ExpertMiss::dispatch; ++ drive.d.experimental_miss_user = &kar_expert_miss; ++ } ++#endif + for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) + drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r]; + drive.d.hit_cpu_order = o.expert_cache_cpu_order; +@@ -4791,6 +4895,10 @@ int main(int argc, char** argv) { + // unknown keys are skipped: the ids start at the first token without '=' + } + } ++ if (kar_expert_archive != nullptr && req_pcie_frac != 0.0) { ++ std::printf("ERR experimental KAR misses require pcie_frac=0\n"); ++ continue; ++ } + std::string emb_path; + if (geni && endp != nullptr) { + while (*endp == ' ') ++endp; +@@ -5586,6 +5694,8 @@ int main(int argc, char** argv) { + const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); + a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b}, + {h ? st.host.k_scale : st.k_scale, scb}}; ++ } else if (st.without_key) { ++ a = {{h ? st.host.v_q : st.v_q, kvb}, {h ? st.host.v_scale : st.v_scale, scb}}; + } else if (st.kv_int8) { + a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb}, + {h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}}; +@@ -5651,6 +5761,11 @@ int main(int argc, char** argv) { + 100.0 * (double) req_hits / (double) req_look, + (long long) req_hits, (long long) req_look); + } ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if (kar_expert_archive != nullptr) ++ std::fprintf(stderr, "strata serve: KAR verifier entries computed since startup: %llu\n", ++ (unsigned long long) kar_expert_miss.computed()); ++#endif + // the resident RAM mode, cumulative: experts read from experts.bin since the copy was made (what the plain + // mmap mode reads through the OS file cache, from the SSD when the RAM could not keep it) + if (src.complement_ready()) +@@ -5703,6 +5818,8 @@ int main(int argc, char** argv) { + remote_experts[(size_t) r].ms_begin() - begin_before[(size_t) r], + remote_experts[(size_t) r].ms_wait() - wait_before[(size_t) r]); + } ++ if (o.stats && ple_table.kar_gpu_cache_enabled()) ++ std::fprintf(stderr, "strata serve: %s\n", ple_table.io_report().c_str()); + return 0; + } + diff --git a/engine/upstream/local-patches-on-0.1.50.patch b/engine/upstream/local-patches-on-0.1.50.patch new file mode 100644 index 00000000..79d4a0e0 --- /dev/null +++ b/engine/upstream/local-patches-on-0.1.50.patch @@ -0,0 +1,2243 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 46ebf034..ef1a1aec 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -80,6 +80,15 @@ if(STRATA_HIP_GFX906) + set(STRATA_ENABLE_CUDA ON CACHE BOOL "" FORCE) + endif() + option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1012/gfx1030 unvalidated)" OFF) ++option(STRATA_CUDA_STATIC "Linux GNU engine: static CUDA toolkit and C++ runtimes (host glibc and NVIDIA driver required)" OFF) ++if(STRATA_CUDA_STATIC) ++ if(NOT STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP OR STRATA_HIP_GFX906 OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" ++ OR NOT CMAKE_CXX_COMPILER_ID STREQUAL "GNU") ++ message(FATAL_ERROR "STRATA_CUDA_STATIC requires Linux, GNU C++, and STRATA_ENABLE_CUDA=ON (HIP disabled)") ++ endif() ++ # Applies to subsequently created CUDA targets, including device-link runtime edges. ++ set(CMAKE_CUDA_RUNTIME_LIBRARY Static) ++endif() + option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) + # MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K (Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF + # projections, STRATA_DENSE_MMQ). On by default since MODEL-UPDATE Phase 1: on CUDA they are their own library +@@ -220,6 +229,16 @@ elseif(STRATA_ENABLE_CUDA) + message(STATUS "Strata: CUDA enabled, arch ${CMAKE_CUDA_ARCHITECTURES}") + set(_strata_gpu_runtime_target CUDA::cudart) + set(_strata_gpu_blas_target CUDA::cublas) ++ if(STRATA_CUDA_STATIC) ++ foreach(_required CUDA::cudart_static CUDA::cublas_static CUDA::cublasLt_static CUDA::culibos) ++ if(NOT TARGET ${_required}) ++ message(FATAL_ERROR "STRATA_CUDA_STATIC requires toolkit archive target ${_required}") ++ endif() ++ endforeach() ++ set(_strata_gpu_runtime_target CUDA::cudart_static) ++ set(_strata_gpu_blas_target CUDA::cublas_static) ++ message(STATUS "Strata: static CUDA toolkit libraries; host glibc and NVIDIA driver remain required") ++ endif() + set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) + elseif(STRATA_ENABLE_HIP) + set(_strata_gpu_runtime_target strata_hip_runtime) +@@ -415,6 +434,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + src/kernels/cuda/fused_gr.cu + src/kernels/cuda/cvec.cu + src/kernels/cuda/qsa_decode_attn.cu ++ src/kernels/cuda/keyless.cu + src/kernels/cuda/qsa_prompt_attn.cu + src/kernels/cuda/fused_gdn.cu + src/kernels/cuda/dequant_bf16.cu +@@ -426,6 +446,35 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + src/ngram/ple_reader.cpp + src/platform/direct_file.cpp) + target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact) ++ option(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE "Capture private PLE row traces for offline cache studies" OFF) ++ if(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++ if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "The experimental PLE row trace requires Linux") ++ endif() ++ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=1) ++ endif() ++ option(STRATA_NEXT_EXPERIMENTAL_KAR_PLE "Build optional KAR PLE CPU and GPU-cache experiment arms" OFF) ++ set(STRATA_NEXT_KAR_DIR "" CACHE PATH "Path to strata-next/gpu/kar (required for KAR PLE)") ++ if(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "The experimental KAR PLE quality arm requires Linux CUDA") ++ endif() ++ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu") ++ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to the strata-next/gpu/kar source directory") ++ endif() ++ add_library(strata_next_kar STATIC ++ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cache.cu") ++ target_include_directories(strata_next_kar PUBLIC ++ "${STRATA_NEXT_KAR_DIR}/vendor" ++ "${STRATA_NEXT_KAR_DIR}/include") ++ target_link_libraries(strata_next_kar PUBLIC ${_strata_gpu_runtime_target}) ++ set_target_properties(strata_next_kar PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) ++ target_link_libraries(strata_kernels PUBLIC strata_next_kar) ++ target_compile_definitions(strata_kernels PRIVATE STRATA_NEXT_EXPERIMENTAL_KAR_PLE=1) ++ add_executable(strata_next_kar_ple_probe "${STRATA_NEXT_KAR_DIR}/src/kar_ple_cpu_probe.cpp") ++ target_link_libraries(strata_next_kar_ple_probe PRIVATE strata_kernels) ++ endif() + # Exact gfx1100 prompt scorer (PR1825 method port): optional standalone test, + # also available where the published source omits tests/. + option(STRATA_PARITY_GFX1100_QSA_SCORES "Build the exact gfx1100 QSA score/ID check" OFF) +@@ -446,7 +495,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA) + add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp) + target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) +- target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) ++ target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() + # PR #600: the Volta (sm_70) prompt attention's latency pipeline against the FP32 kernel it replaces. Only in the + # experimental sm_60/sm_70 build, where prompt_attn_v70_kernel is compiled in. +@@ -580,7 +629,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + # already links `strata_core` - putting `gdn_layer` in core would make the two mutually dependent. A third + # library is the honest shape of the dependency graph: core knows about devices and weights, kernels know + # about arithmetic, and this one knows the ORDER the arithmetic happens in. +- add_library(strata_engine STATIC src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp ++ add_library(strata_engine STATIC src/core/keyless.cpp src/core/layer.cpp src/core/session.cpp src/core/expert_source.cpp src/core/remote_experts.cpp + src/core/remote_expert_opt.cu + src/core/expert_cache.cpp src/core/native_head.cpp src/core/native_dense.cpp src/core/verify.cpp src/core/mtp.cpp src/core/dflash2.cpp + src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp +@@ -611,6 +660,30 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + set_tests_properties(memory_guard_test PROPERTIES TIMEOUT 60) + endif() + ++ option(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS "Build the opt-in KAR native decode cache-miss arm" OFF) ++ if(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if(NOT STRATA_ENABLE_CUDA OR NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") ++ message(FATAL_ERROR "Experimental KAR experts require Linux CUDA") ++ endif() ++ if(NOT EXISTS "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") ++ message(FATAL_ERROR "Set STRATA_NEXT_KAR_DIR to strata-next/gpu/kar") ++ endif() ++ add_library(strata_next_kar_experts STATIC ++ "${STRATA_NEXT_KAR_DIR}/vendor/libkar.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_expert.cu" ++ "${STRATA_NEXT_KAR_DIR}/src/kar_expert_miss.cpp") ++ target_include_directories(strata_next_kar_experts PUBLIC ++ "${STRATA_NEXT_KAR_DIR}/vendor" "${STRATA_NEXT_KAR_DIR}/include") ++ target_link_libraries(strata_next_kar_experts PUBLIC ${_strata_gpu_runtime_target}) ++ set_target_properties(strata_next_kar_experts PROPERTIES CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) ++ target_compile_features(strata_next_kar_experts PRIVATE cxx_std_20) ++ target_link_libraries(strata_engine PUBLIC strata_next_kar_experts) ++ target_compile_definitions(strata_engine PUBLIC STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=1) ++ endif() ++ add_executable(keyless_parity src/kernels/keyless_parity.cpp) ++ target_link_libraries(keyless_parity PRIVATE strata_engine) ++ add_test(NAME keyless_parity COMMAND keyless_parity) ++ set_tests_properties(keyless_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp") + enable_testing() + add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp) +@@ -682,6 +755,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + set_tests_properties(expert_cache_slot_guard_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) + endif() + if(STRATA_BUILD_CONVERSATION_TESTS) ++ add_executable(keyless_stream_parity src/kernels/kv_stream_parity.cpp) ++ target_link_libraries(keyless_stream_parity PRIVATE strata_engine) ++ add_test(NAME keyless_stream_parity COMMAND keyless_stream_parity --v-only) ++ set_tests_properties(keyless_stream_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120) + add_executable(conversation_snapshot_test src/core/conversation_snapshot_test.cpp) + target_link_libraries(conversation_snapshot_test PRIVATE strata_engine) + add_test(NAME conversation_snapshot_test COMMAND conversation_snapshot_test) +@@ -760,6 +837,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) + strata_utf8_manifest(strata) + target_include_directories(strata PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(strata PRIVATE strata_engine strata_prefill strata_spec ${_strata_gpu_runtime_target}) ++ if(STRATA_CUDA_STATIC) ++ target_link_options(strata PRIVATE -static-libstdc++ -static-libgcc) ++ set_target_properties(strata PROPERTIES SKIP_BUILD_RPATH TRUE INSTALL_RPATH "") ++ endif() + if(WIN32 AND STRATA_ENABLE_HIP) + # 0.2.1.2: the ROCm math libraries live in \rocm\bin, which is on PATH only when the launcher starts the engine; load them on first + # use (main() adds that folder to the DLL search first) so `strata.exe --version` works from the package folder. amdhip64_7.dll and the +diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp +index 3ab77dc2..d73d1492 100644 +--- a/include/strata/core/expert_source.hpp ++++ b/include/strata/core/expert_source.hpp +@@ -484,6 +484,12 @@ struct ForesightSwap; + + struct ExpertDispatch { + ForesightSwap* fs = nullptr; ///< Foresight swap space (STRATA_FS_SLOTS; null = off) ++ // Default-off local extension. The callback owns only kind==-1 entries and ++ // marks completed host rows as kind=3. Native hits/PCIe/remote rows are untouched. ++ using ExperimentalMiss = bool (*)(void*, int64_t, const float*, const int32_t*, ++ int64_t, int64_t, int32_t*, float*, std::string&); ++ ExperimentalMiss experimental_miss = nullptr; ++ void* experimental_miss_user = nullptr; + strata::kernels::cpu::ExpertPool* pool = nullptr; + ExpertSource* src = nullptr; + RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts +diff --git a/include/strata/core/keyless.hpp b/include/strata/core/keyless.hpp +new file mode 100644 +index 00000000..4665c458 +--- /dev/null ++++ b/include/strata/core/keyless.hpp +@@ -0,0 +1,11 @@ ++#pragma once ++#include "strata/core/layout.hpp" ++#include ++namespace strata::core { ++bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error); ++const float* keyless_routing(int64_t layer); ++} ++namespace strata::kernels { ++// In-place, one independent matrix for each query head. No cached keys are produced. ++void keyless_route_query(float* q, const float* output_major_matrices, int64_t tokens, int heads, int dim, void* stream); ++} +diff --git a/include/strata/core/layer.hpp b/include/strata/core/layer.hpp +index 9e0361ac..44c7001f 100644 +--- a/include/strata/core/layer.hpp ++++ b/include/strata/core/layer.hpp +@@ -210,6 +210,7 @@ struct QsaState { + uint16_t* k_pool = nullptr; ///< [page][kv_head][page_size][head_dim] fp16 (null in INT8 mode) + uint16_t* v_pool = nullptr; + /// Plan v0.3 P7: INT8 KV (qsa_set_kv_int8). Codes [page][kv_head][page_size][head_dim], one FP16 scale per 64. ++ bool without_key = false; + bool kv_int8 = false; + int8_t* k_q = nullptr; + int8_t* v_q = nullptr; +@@ -309,6 +310,8 @@ uint64_t qsa_kv_host_bytes(); + /// Plan v0.3 P7: store K/V as INT8 with FP16 scales per 64 values (half the VRAM of FP16). Set before sizing and + /// initializing the session; default off until gate G-C accepts it. + void qsa_set_kv_int8(bool enabled); ++void qsa_set_without_key(bool enabled); ++bool qsa_without_key(); + /// INT8 K/V through the Hadamard rotation (off by default: STRATA_KV_ROT=1) + void qsa_set_kv_int8_rotate(bool enabled); + bool qsa_kv_int8(); +@@ -321,6 +324,7 @@ bool qsa_kv_hybrid(); + /// The state's KV format for the block-moving functions of kv_stream.hpp (kKvF16 / kKvInt8 / kKvQ4 / kKvHybrid). + inline int qsa_kv_format(const QsaState& st) { + if (st.kv_hybrid) return strata::kernels::kKvHybrid; // K8V4: its own three runs (kv_stream.cu) ++ if (st.without_key) return strata::kernels::kKvValueInt8; // local keyless arm (default off) + return st.kv_q4 ? strata::kernels::kKvQ4 : st.kv_int8 ? strata::kernels::kKvInt8 : strata::kernels::kKvF16; + } + uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st, +diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp +index dc6613da..3b24d4cb 100644 +--- a/include/strata/core/verify.hpp ++++ b/include/strata/core/verify.hpp +@@ -563,6 +563,10 @@ private: + int32_t* h_commit_ = nullptr; int32_t* m_commit_ = nullptr; // [n_keep, n_keep-1, pos_0 .. pos_{T-1}] + float* h_ple_ = nullptr; float* m_ple_ = nullptr; // T * n_embd + int32_t* h_out_ = nullptr; int32_t* m_out_ = nullptr; // T argmax ids ++ float* kl_trace_h_ = nullptr; // optional pinned K/V activation trace for offline keyless study ++ std::FILE* kl_trace_file_ = nullptr; ++ float* kl_trace_q_h_ = nullptr; // first accepted token's Q, per QSA layer ++ std::FILE* kl_trace_q_file_ = nullptr; + // STRATA_TAP_FILE (off by default; nothing is allocated or captured without it): the DFlash2 experiment's hook. + // After each layer in STRATA_TAP_LAYERS (default 5,15,25,35,45) the window copies the layer's completed output + // (the residual with its pending FFN write applied, the mean of the hc streams) per row; run() appends +diff --git a/include/strata/kernels/kv_stream.hpp b/include/strata/kernels/kv_stream.hpp +index 8108795b..8e630031 100644 +--- a/include/strata/kernels/kv_stream.hpp ++++ b/include/strata/kernels/kv_stream.hpp +@@ -38,14 +38,14 @@ struct KvHostPools { + uint16_t* v_scale = nullptr; + uint8_t* k_q4 = nullptr; ///< q4_0 mode (kv_q4.hpp): block_q4_0 codes, 144 B per cell and head + uint8_t* v_q4 = nullptr; +- bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr; } ++ bool present() const { return k_pool != nullptr || k_q != nullptr || k_q4 != nullptr || v_q != nullptr; } + }; + + /// The KV storage format, for the functions below that move whole blocks (`fmt`): fp16, int8 (+ scales), q4_0, and + /// K8V4 (`--kv k8v4`: K as int8 codes + scales, V as rotated q4_0 - three runs, `k_q`, `k_scale`, `v_q4`). + /// (A bool `int8` argument still reads as kKvF16 / kKvInt8.) kKvHybrid is 3, the number conversation snapshots +-/// already give K8V4. +-enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2, kKvHybrid = 3 }; ++/// already give K8V4. kKvValueInt8 (4) is the local, default-off V-only (keyless) format: int8 V + scales only. ++enum KvFormat : int { kKvF16 = 0, kKvInt8 = 1, kKvQ4 = 2, kKvHybrid = 3, kKvValueInt8 = 4 }; + + /// K8V4's halves as the single-format append kernels see them, so a hybrid layer's host copy (and the prompt path's + /// staging pool) is written by the same calls that write its VRAM pools: K is "int8 whose V is K", V is "q4_0 whose +diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hpp +index 4452b4f6..ec62a24e 100644 +--- a/include/strata/kernels/ngram.hpp ++++ b/include/strata/kernels/ngram.hpp +@@ -22,6 +22,7 @@ + // All of those are asserted observable in `ple_parity.cpp` rather than trusted. + #pragma once + ++#include + #include + #include + +@@ -176,6 +177,21 @@ public: + /// Open with an explicit I/O mode. The two-argument `open` below is the default (Direct). + bool open(const std::string& gguf_path, std::string& err, const PleIoOptions& io); + ++ /// Experimental CPU quality arm: read rows from a verified KAR-2 archive ++ /// while the rest of the engine continues to use its normal model pack. ++ /// The CUDA selective-row path is measured separately and is not used here. ++ bool open_kar(const std::string& kar_path, uint32_t level, std::string& err, ++ uint64_t expected_rows = PLE_TABLE_ROWS); ++ ++ /// Experimental bounded compressed-row cache. It accepts only the ++ /// level-2/group-32 KAR PLE layout and leaves the CPU gather available ++ /// for consumers that still use mapped host memory. ++ bool enable_kar_gpu_cache(uint32_t cache_mib, std::string& err); ++ bool kar_gpu_cache_enabled() const; ++ bool collect_device(float* device_out2560, void* stream, std::string& err); ++ bool gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, ++ void* stream, std::string& err); ++ + /// The split the plan asks for: `issue` as soon as the token id is known, `collect` just before layer 1 + /// needs the rows. `gather` is `issue` followed by `collect`. In Mmap mode `issue` only prefetches. + bool issue(const uint32_t* rows16); +diff --git a/include/strata/kernels/qsa_decode_attn.hpp b/include/strata/kernels/qsa_decode_attn.hpp +index e782035d..4e9adb46 100644 +--- a/include/strata/kernels/qsa_decode_attn.hpp ++++ b/include/strata/kernels/qsa_decode_attn.hpp +@@ -21,6 +21,11 @@ + namespace strata::kernels { + + struct QsaAttnPools { ++ bool without_key = false; ++ const float* keyless_cos = nullptr; ++ const float* keyless_sin = nullptr; ++ int keyless_n_rot = 0; ++ const int32_t* keyless_mrope = nullptr; // optional per-cell time/height/width positions + const uint16_t* k_pool = nullptr; ///< fp16 [page][kv_head][page_size][head_dim], or null when int8 + const uint16_t* v_pool = nullptr; + const int8_t* k_q = nullptr; ///< int8 codes, same layout +diff --git a/src/core/conversation_snapshot.cpp b/src/core/conversation_snapshot.cpp +index 76e69b5f..c4f7355a 100644 +--- a/src/core/conversation_snapshot.cpp ++++ b/src/core/conversation_snapshot.cpp +@@ -61,6 +61,7 @@ bool layout(const QsaState& st, const ModelGeometry& g, int64_t upto, bool index + } + l.value_data = l.data; + l.value_scales = l.scales; ++ if (st.without_key) { l.data = 0; l.scales = 0; } + if (st.kv_hybrid) { + if (!product(l.value_data, {(uint64_t) cells, (uint64_t) g.n_head_kv, + (uint64_t) strata::kernels::kv_q4_bytes_per_head((int) g.head_dim)})) { +@@ -102,7 +103,7 @@ bool valid(const QsaState& st, const Layout& l, int64_t upto, std::string& error + } + } + if (st.kv_mode == 2 && (!st.page_table || +- (st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale ++ (st.without_key ? !st.v_q || !st.v_scale : st.kv_q4 ? !st.k_q4 || !st.v_q4 : st.kv_int8 ? !st.k_q || !st.v_q || !st.k_scale || !st.v_scale + : !st.k_pool || !st.v_pool))) { + error = "conversation snapshot: invalid draft ring"; + return false; +diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp +index 074a3ae9..37335f4b 100644 +--- a/src/core/conversation_snapshot_test.cpp ++++ b/src/core/conversation_snapshot_test.cpp +@@ -48,13 +48,14 @@ struct Fixture { + } + Fixture(int fmt, int mode) { + auto& st = state; +- st.kv_mode = mode; st.kv_int8 = fmt==kKvInt8; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; ++ st.kv_mode = mode; st.without_key = fmt==kKvValueInt8; st.kv_int8 = fmt==kKvInt8 || st.without_key; st.kv_q4 = fmt==kKvQ4; st.kv_hybrid = fmt==3; + st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages; + st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode==2 ? 2 : st.max_cells/4+2; + const size_t per = fmt==kKvQ4 ? kv_q4_bytes_per_head((int)g.head_dim) : g.head_dim*((st.kv_int8 || st.kv_hybrid) ? 1:2); + const size_t rows = st.max_cells*g.n_head_kv, slot_rows = st.n_slots*4*g.n_head_kv; +- sizes = {rows*per, rows*per, fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, +- fmt==kKvInt8 ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; ++ sizes = {rows*per, rows*per, (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0, ++ (fmt==kKvInt8 || fmt==kKvValueInt8) ? rows*(g.head_dim/64)*2:0, (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; ++ if (st.without_key) { sizes[0]=0; sizes[2]=0; } + if (fmt==3) { + sizes = {rows*per, rows*kv_q4_bytes_per_head((int)g.head_dim), rows*(g.head_dim/64)*2, 0, + (size_t)st.idx_pooled_rows*g.idx_key_dim*4}; +@@ -64,9 +65,11 @@ struct Fixture { + alloc(st.k_q4,slot_rows*per); alloc(st.v_q4,slot_rows*per); + if (mode) {alloc(st.host.k_q4,sizes[0],true); alloc(st.host.v_q4,sizes[1],true);} + sources[0]=mode?st.host.k_q4:st.k_q4; sources[1]=mode?st.host.v_q4:st.v_q4; +- } else if (fmt==kKvInt8) { +- alloc(st.k_q,slot_rows*per); alloc(st.v_q,slot_rows*per); +- alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); alloc(st.v_scale,slot_rows*(g.head_dim/64)*2); ++ } else if (st.kv_int8) { ++ if (!st.without_key) alloc(st.k_q,slot_rows*per); ++ alloc(st.v_q,slot_rows*per); ++ if (!st.without_key) alloc(st.k_scale,slot_rows*(g.head_dim/64)*2); ++ alloc(st.v_scale,slot_rows*(g.head_dim/64)*2); + if (mode) { + alloc(st.host.k_q,sizes[0],true); alloc(st.host.v_q,sizes[1],true); + alloc(st.host.k_scale,sizes[2],true); alloc(st.host.v_scale,sizes[3],true); +@@ -111,7 +114,7 @@ bool equal(const ConversationKv& a,const ConversationKv& b) { + } + + void full_session(int fmt, int mode, int experts) { +- Fixture main(fmt,mode), draft(fmt==3?kKvInt8:fmt,2); ++ Fixture main(fmt,mode), draft((fmt==3 || fmt==kKvValueInt8)?kKvInt8:fmt,2); + auto& g=main.g; + g.n_layers=4; g.n_expert=experts; + g.ssm_state_size=2; g.ssm_v_heads=2; g.ssm_conv_channels=8; +@@ -228,7 +231,7 @@ void full_session(int fmt, int mode, int experts) { + check(conversation_snapshot_restore(a,ss,g,draft.state,err)==ConversationRestore::restored,"restore growth fixture base"); + ConversationKvReuse reuse{a.kv,65,dirty}; + const uint8_t* original = nullptr; +- reuse.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;}); ++ reuse.kv[0].v.visit(0,1,[&](const uint8_t* p,size_t,size_t){original=p;return true;}); + main.fill_after(91,dirty); draft.fill_after(91,std::max(0,dirty-1)); + cuda_check(cudaMemset(ss.gdn_state,91,sizes.gdn)); + ids.resize(70); +@@ -245,7 +248,7 @@ void full_session(int fmt, int mode, int experts) { + incremental.live.dead==fresh.live.dead && equal(incremental.kv[0],fresh.kv[0]) && + equal(incremental.kv[1],fresh.kv[1]),"incremental capture equals full capture after growth or rewind"); + check((dirty>=4)==(reused>0),"only complete unchanged pages or rows are retained"); +- incremental.kv[0].k.visit(0,1,[&](const uint8_t* p,size_t,size_t){ ++ incremental.kv[0].v.visit(0,1,[&](const uint8_t* p,size_t,size_t){ + check(p==original,"growth never reallocates the retained payload");return true; + }); + check(conversation_snapshot_restore(incremental,ss,g,draft.state,err)==ConversationRestore::restored,"restore segmented incremental snapshot"); +@@ -305,7 +308,7 @@ void full_session(int fmt, int mode, int experts) { + int main() { + int devices=0; + if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77; +- for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) { ++ for (int fmt : std::array{kKvF16,kKvInt8,kKvQ4,3,kKvValueInt8}) for (int mode : {0,1,2}) { + if (fmt==3 && mode!=0) continue; + Fixture f(fmt,mode); + if (fmt==3) { +@@ -334,6 +337,12 @@ int main() { + ConversationKv a,b,restored; + cuda_check(cudaDeviceSynchronize()); + check(conversation_kv_save(a,f.state,f.g,upto,index,err),"save A"); ++ if (fmt==kKvValueInt8) { ++ check(a.k.empty() && a.k_scale.empty() && !f.state.k_q && !f.state.host.k_q, ++ "V-only snapshot and resident/host pools have no K"); ++ auto wrong=a; wrong.format=kKvInt8; ++ check(!conversation_kv_restore(wrong,f.state,f.g,upto,index,err),"reject K+V snapshot in V-only state"); ++ } + check(a.bytes()==conversation_kv_bytes(f.state,f.g,upto,index),"size estimate equals snapshot payload"); + f.fill(177); + check(conversation_kv_save(b,f.state,f.g,upto,index,err),"save B"); +@@ -373,13 +382,13 @@ int main() { + const int64_t b1=(upto+s.page_size-1)/s.page_size,b0=std::max(0,b1-f.state.n_slots); + const size_t block=kv_block_bytes(s,fmt)/2; + // Codes and scales are separate in INT8; check code bytes here. +- const size_t code_block=fmt==kKvInt8 ? s.page_size*s.n_head_kv*s.head_dim : block; +- const void* slots=fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool; ++ const size_t code_block=(fmt==kKvInt8 || fmt==kKvValueInt8) ? s.page_size*s.n_head_kv*s.head_dim : block; ++ const void* slots=fmt==kKvValueInt8?(void*)f.state.v_q:fmt==kKvQ4?(void*)f.state.k_q4:fmt==kKvInt8?(void*)f.state.k_q:(void*)f.state.k_pool; + std::vector got(code_block); + for (int64_t page=b0;page expected(code_block); +- check(a.k.read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); ++ check((fmt==kKvValueInt8?a.v:a.k).read(expected.data(), page*code_block, code_block),"read segmented expected draft page"); + check(got == expected,"draft ring contains restored pages"); + } + } +@@ -402,7 +411,7 @@ int main() { + } + } + } +- for (int fmt : {kKvF16,kKvInt8,kKvQ4}) for (int mode : {0,1}) for (int experts : {256,512}) ++ for (int fmt : {kKvF16,kKvInt8,kKvQ4,kKvValueInt8}) for (int mode : {0,1}) for (int experts : {256,512}) + full_session(fmt,mode,experts); + for (int experts : {256,512}) full_session(3,0,experts); + std::printf("conversation_snapshot_test: %d checks passed\n",checks); +diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp +index b8ad8fb4..66b60d9b 100644 +--- a/src/core/expert_source.cpp ++++ b/src/core/expert_source.cpp +@@ -4986,6 +4986,13 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 + for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2; + } + } ++ if (d.experimental_miss != nullptr) { ++ static thread_local std::string miss_error; ++ if (!d.experimental_miss(d.experimental_miss_user, d.layers, x_f, ids, ++ n_tok, k, kind, out, miss_error)) { ++ d.failed = true; d.fail = miss_error.c_str(); d.fail_layer = d.layers; return; ++ } ++ } + static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }(); + // the GPU's copy_rows_from_mapped zeroes the rows it computed itself (dec_batch); STRATA_VERIFY_DEVICE_PLAN's + // copy_or_zero_from_mapped copies every row, so there the host still zeroes them +@@ -5078,13 +5085,14 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 + ++d.tail_skipped; + continue; + } +- if (kind[i] >= 0) { // CUDA0, PCIe, or a remote/peer result staged into this row below ++ if (kind[i] >= 0) { // CUDA0, PCIe, a remote/peer result staged into this row below, or a completed experimental KAR host row (kind 3) + if (kind[i] == 0) ++d.cache_hits; ++ else if (kind[i] == 3) ++d.cache_refused; // local KAR arm: the row already holds its result, never zeroed + else ++d.offload_entries; // #588: PCIe or another GPU + if (kind[i] == 2 && d.peer != nullptr) ++d.peer_entries; + // multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it; + // dec_batch: copy_rows_from_mapped_kernel already zeroes kind 0/1 rows on the GPU +- if (!((kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()) || ++ if (kind[i] != 3 && !((kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()) || + (gpu_zeroes_hits && (kind[i] == 0 || kind[i] == 1)))) + std::memset(row, 0, (size_t) H * sizeof(float)); + continue; +diff --git a/src/core/keyless.cpp b/src/core/keyless.cpp +new file mode 100644 +index 00000000..7699b579 +--- /dev/null ++++ b/src/core/keyless.cpp +@@ -0,0 +1,79 @@ ++#include "strata/core/keyless.hpp" ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace strata::core { ++namespace { ++std::map routes; ++uint32_t u32(std::istream& f) { ++ unsigned char b[4]{}; f.read((char*) b, 4); ++ return (uint32_t)b[0] | (uint32_t)b[1]<<8 | (uint32_t)b[2]<<16 | (uint32_t)b[3]<<24; ++} ++uint64_t u64(std::istream& f) { const uint64_t a = u32(f); return a | (uint64_t)u32(f)<<32; } ++} ++const float* keyless_routing(int64_t layer) { ++ const auto it = routes.find(layer); ++ return it == routes.end() ? nullptr : it->second; ++} ++bool keyless_load(const char* path, const WeightTable& weights, const ModelGeometry& g, std::string& error) { ++ if (!routes.empty()) { error = "keyless routing already loaded"; return false; } ++ std::ifstream f(path, std::ios::binary); ++ std::array magic{}; f.read(magic.data(), 8); ++ const uint32_t version = u32(f), layers = u32(f), heads = u32(f), dim = u32(f); ++ if (!f || std::memcmp(magic.data(), "SKLROUT1", 8) || version != 1 || ++ layers != (uint32_t)g.n_qsa_layers() || heads != (uint32_t)g.n_head || dim != (uint32_t)g.head_dim || dim != 256) { ++ error = "invalid keyless artifact header/geometry"; return false; ++ } ++ std::map pending; ++ auto fail = [&](const std::string& why) { ++ error = why; for (auto& row : pending) cudaFree(row.second); return false; ++ }; ++ for (uint32_t ordinal = 0; ordinal < layers; ++ordinal) { ++ const uint32_t layer = u32(f); ++ if (!f || layer >= g.n_layers || !is_qsa_layer(g, layer) || pending.count(layer)) ++ return fail("keyless artifact has invalid/duplicate layer"); ++ for (const char* role : {"q", "k", "v"}) { ++ const uint32_t kind = u32(f); const uint64_t bytes = u64(f), wanted = u64(f); ++ const auto* w = weights.find("blk." + std::to_string(layer) + ".attn_" + role + ".weight"); ++ // Quantized projection size is recorded by the source decoder. Bound before any device read. ++ const uint64_t expected_elements = (uint64_t)g.n_embd * g.head_dim * ++ (std::strcmp(role,"q") == 0 ? g.n_head * 2 : g.n_head_kv); ++ if (!f || !w || !w->native_data || w->native_type != (int)kind || ++ bytes == 0 || bytes > expected_elements * 4 || expected_elements != (uint64_t)w->elements) ++ return fail("keyless artifact source projection geometry/type mismatch"); ++ // NativeDense owns source GGUF blocks. Verify the artifact was derived from these actual bytes. ++ // Source byte length must agree with ggml geometry; ne0/ne1 cannot validate a quantized byte span. ++ const uint64_t block_elements = kind == 42 ? 64 : kind == 8 ? 32 : 256; ++ const uint64_t block_bytes = kind == 42 ? 18 : kind == 11 ? 110 : kind == 12 ? 144 : ++ kind == 13 ? 176 : kind == 14 ? 210 : kind == 23 ? 136 : kind == 8 ? 34 : 0; ++ if (!block_bytes || expected_elements % block_elements || bytes != expected_elements / block_elements * block_bytes) ++ return fail("keyless artifact unsupported/mismatched native projection encoding"); ++ std::vector raw((size_t)bytes); ++ if (cudaMemcpy(raw.data(), w->native_data, raw.size(), cudaMemcpyDeviceToHost) != cudaSuccess) ++ return fail("keyless source projection readback failed"); ++ uint64_t hash = 0xcbf29ce484222325ull; ++ for (uint8_t byte : raw) hash = (hash ^ byte) * 0x100000001b3ull; ++ if (hash != wanted) return fail("keyless artifact source projection fingerprint mismatch"); ++ } ++ std::vector matrix((size_t)heads * dim * dim); ++ f.read((char*)matrix.data(), matrix.size()*sizeof(float)); ++ if (!f || !std::all_of(matrix.begin(), matrix.end(), [](float v) { return std::isfinite(v); })) ++ return fail("truncated/nonfinite keyless query matrix"); ++ float* device = nullptr; ++ if (cudaMalloc((void**)&device, matrix.size()*sizeof(float)) != cudaSuccess) ++ return fail("keyless query matrices do not fit in GPU memory"); ++ pending[layer] = device; ++ if (cudaMemcpy(device, matrix.data(), matrix.size()*sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) ++ return fail("keyless query matrix upload failed"); ++ } ++ if (f.peek() != std::char_traits::eof()) return fail("keyless artifact has trailing data"); ++ routes = std::move(pending); ++ return true; ++} ++} +diff --git a/src/core/layer.cpp b/src/core/layer.cpp +index 273b2293..978d41b5 100644 +--- a/src/core/layer.cpp ++++ b/src/core/layer.cpp +@@ -1,6 +1,7 @@ + + // src/core/layer.cpp - the GDN layer, composed. See the header for the operation order and its traps. + #include "strata/core/layer.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/pin_budget.hpp" + #include "strata/core/native_dense.hpp" + #include "strata/core/native_head.hpp" +@@ -201,7 +202,9 @@ if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, + // namespace + void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; } + void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; } +-namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } ++namespace { bool g_without_key = false, g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; } ++void qsa_set_without_key(bool enabled) { g_without_key = enabled; } ++bool qsa_without_key() { return g_without_key; } + void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; } + void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; } + bool qsa_kv_int8() { return g_kv_int8; } +@@ -755,6 +758,7 @@ KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) { + return p; + } + uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) { ++ if (g_without_key) return (uint64_t)pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) / 2 + 64; + if (hybrid) { // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation) + const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv; + return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 + +@@ -796,6 +800,7 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + const KvPlan p = kv_plan(s, max_cells, ring_cells); + const int64_t pages = p.pages; + Cursor c{(uint8_t*) base}; ++ st.without_key = g_without_key; + st.kv_int8 = g_kv_int8 && !g_kv_q4; + st.kv_q4 = g_kv_q4; + // Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 - +@@ -854,9 +859,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + st.k_q4 = c.take(rows * q4_row); + st.v_q4 = c.take(rows * q4_row); + } else if (st.kv_int8) { // st, not the global: the drafter's ring is INT8 under --kv k8v4 too +- st.k_q = c.take(rows * s.head_dim); ++ if (!st.without_key) st.k_q = c.take(rows * s.head_dim); + st.v_q = c.take(rows * s.head_dim); +- st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); ++ if (!st.without_key) st.k_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.v_scale = c.take(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.k_pool = c.take(rows * s.head_dim); +@@ -926,9 +931,9 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q + st.host.k_q4 = hc.take(hrows * q4_row); + st.host.v_q4 = hc.take(hrows * q4_row); + } else if (st.kv_int8) { +- st.host.k_q = hc.take(hrows * s.head_dim); ++ if (!st.without_key) st.host.k_q = hc.take(hrows * s.head_dim); + st.host.v_q = hc.take(hrows * s.head_dim); +- st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); ++ if (!st.without_key) st.host.k_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + st.host.v_scale = hc.take(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP)); + } else { + st.host.k_pool = hc.take(hrows * s.head_dim); +@@ -971,16 +976,16 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { + const int64_t live_slots = st.kv_elastic >= 0 ? pool_slots_mapped(*g_pools[(size_t) st.kv_elastic]) : st.n_slots; + const size_t rows = (size_t) live_slots * s.n_head_kv * s.page_size; + if (st.kv_hybrid) { +- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); +- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); ++ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); ++ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_q4) { + cudaMemsetAsync(st.k_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs); + } else if (st.kv_int8) { +- cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); ++ if (st.k_q) cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs); + cudaMemsetAsync(st.v_q, 0, rows * s.head_dim, cs); +- cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); ++ if (st.k_scale) cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + cudaMemsetAsync(st.v_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs); + } else { + cudaMemsetAsync(st.k_pool, 0, rows * s.head_dim * 2, cs); +@@ -998,6 +1003,8 @@ void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) { + strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState& st) { + strata::kernels::QsaAttnPools pools; + pools.page_table = st.page_table; ++ pools.without_key = st.without_key; ++ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + if (st.kv_hybrid) { pools.k_q = st.k_q; pools.k_scale = st.k_scale; pools.v_q4 = st.v_q4; } + else if (st.kv_q4) { pools.k_q4 = st.k_q4; pools.v_q4 = st.v_q4; } + else if (st.kv_int8) { pools.k_q = st.k_q; pools.v_q = st.v_q; pools.k_scale = st.k_scale; pools.v_scale = st.v_scale; } +@@ -1127,11 +1134,12 @@ void stage_timing_report(int64_t n_layers) { + // needs nothing from the layer it is called for beyond its index. + static void dump_slot(float* dump, const ModelGeometry& g, int64_t layer, const float* src, uint64_t off, + uint64_t n, void* stream); +-bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t cap = qsa_selection_width(kTopkMaxCells, s); ++bool qsa_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t pos, int32_t pos_base, const QsaState& st, const QsaBuffers& b, const float* x, float* out, void* stream, std::string& err, float* dump) { using namespace strata::kernels; const QsaShapes s = qsa_shapes(g); const LayerView v(tables, layer); const int64_t n_kv = pos + 1; if (st.without_key && pos_base != 0) { err = "V-only requires zero position base"; return false; } /* P7 audit: RoPE reads cos/sin row pos_base + pos, and the table holds max_cells rows. */ if ((int64_t) pos_base + pos >= st.max_cells || pos_base < 0) { err = "qsa_layer: position " + std::to_string((long long) pos_base + pos) + " is outside the RoPE table (" + std::to_string((long long) st.max_cells) + " rows)"; return false; } const int64_t cap = qsa_selection_width(kTopkMaxCells, s); + const auto normalize_rotate = [&](float* data, const WeightRef* norm, int rows, int cols) { + 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 (st.without_key && data == b.qcur) keyless_route_query(data, keyless_routing(layer), 1, (int)g.n_head, (int)g.head_dim, 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; +@@ -1197,9 +1205,9 @@ SForm f_k, f_v, f_o, f_q; if (!sform_of(*w_attnk, f_k, v.name("attn_k.weight" + // k and v, with the activation THIS layer's tensors ask for. Both are K-quants in every QSA layer of this + // artifact, but the dispatch is here for the same reason it is in `gdn_layer`: the pack decides per tensor, + // and "it happens to be uniform here" is the assumption that was wrong for `attn_q`. +-if (!gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; +- if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); +- if (!normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; ++if (!st.without_key && !gemv_quantized(*w_attnk, p_k, f_k, b.x_q8_0, b.x_q8k, b.kcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_k.weight"), stream, err, x)) return false; ++ if (!gemv_quantized(*w_attnv, p_v, f_v, b.x_q8_0, b.x_q8k, b.vcur, g.n_embd, g.n_head_kv * g.head_dim, v.name("attn_v.weight"), stream, err, x, !st.without_key && w_attnk->native_data && w_attnv->native_data)) return false; dump_slot(dump, g, layer, b.vcur, (uint64_t) 2 * g.n_embd + 2 * g.hc + (uint64_t) g.n_head * g.head_dim, (uint64_t) g.n_head_kv * g.head_dim, stream); ++ if (!st.without_key && !normalize_rotate(b.kcur, w_kn, (int) g.n_head_kv, (int) g.head_dim)) return false; + // ---- 5. into the cache, and the indexer's append (which pools AND rotates on a block completion). + // EVERY ENTRY POINT FROM HERE ON IS THE CAPTURABLE ONE: the per-token counts come from `st.step` and every + // launch is sized from a capacity in `st`/`b`, so this sequence can be captured and replayed. The +@@ -1261,7 +1269,7 @@ int64_t max_blocks = (st.max_cells / s.idx_block) + 2; + // KV streaming: every block the selection names is made resident before anything reads it + qsa_kv_resolve(st, g, b.ids, st.step, 1, cap, stream); + if (st.kv_rot) strata::kernels::fwht256_inplace_cuda(b.qcur, g.n_head, stream); // = +- if (g_fast_attn && !native_flash_attn_short && dump == nullptr) { ++ if (st.without_key || (g_fast_attn && !native_flash_attn_short && dump == nullptr)) { + const strata::kernels::QsaAttnPools pools = qsa_attn_pools(st); + strata::kernels::qsa_decode_attn_step(b.qcur, pools, b.ids, st.step, cap, s, b.attn_scratch, b.attn, stream); + } else { +@@ -1586,6 +1594,13 @@ bool ple_issue_token(const PleRun& p, std::string& err) { + + bool ple_finish_token(const PleRun& p, void* stream, std::string& err) { + if (!p.ready()) { err = "ple_finish_token: the PLE run is not ready"; return false; } ++ if (p.table->kar_gpu_cache_enabled()) { ++ if (!p.table->collect_device(p.emb_dev, stream, err)) { ++ err = "ple_finish_token: " + err; ++ return false; ++ } ++ return true; ++ } + if (!p.table->collect(p.emb_host, err)) { err = "ple_finish_token: " + err; return false; } + if (cudaMemcpyAsync(p.emb_dev, p.emb_host, (size_t) strata::kernels::NG_N_EMBD * sizeof(float), + cudaMemcpyHostToDevice, (cudaStream_t) stream) != cudaSuccess) { +diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp +index f4b82b33..4b4a0d9e 100644 +--- a/src/core/mtp.cpp ++++ b/src/core/mtp.cpp +@@ -345,6 +345,11 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session + int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0; + // K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats + // only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback). ++ struct RestoreKeylessMode { ++ bool previous = qsa_without_key(); ++ ~RestoreKeylessMode() { qsa_set_without_key(previous); } ++ } restore_keyless_mode; ++ qsa_set_without_key(false); + const bool kv_hybrid_was = qsa_kv_hybrid(); + const bool kv_int8_was = qsa_kv_int8(); + qsa_set_kv_hybrid(false); +diff --git a/src/core/verify.cpp b/src/core/verify.cpp +index 3d6f48b2..1859853b 100644 +--- a/src/core/verify.cpp ++++ b/src/core/verify.cpp +@@ -4,6 +4,7 @@ + #include "strata/core/sm120_series.hpp" + #include "strata/kernels/gfx_arch.hpp" + #include "strata/core/verify.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/pin_budget.hpp" + #if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) + #include "strata/core/host_graph_launch.hpp" +@@ -654,8 +655,10 @@ Verifier::~Verifier() { + for (cudaEvent_t e : df_join_) + if (e) cudaEventDestroy(e); + if (arena_) cudaFree(arena_); ++ if (kl_trace_file_) std::fclose(kl_trace_file_); ++ if (kl_trace_q_file_) std::fclose(kl_trace_q_file_); + if (hcount_d_) cudaFree(hcount_d_); +- void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, ++ void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, kl_trace_h_, kl_trace_q_h_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, + h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_, h_bal_}; + for (void* h : hosts) + if (h) cudaFreeHost(h); +@@ -711,6 +714,21 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& + hits_ = hits; + head_ = head; + max_t_ = max_t; ++ if (const char* path = std::getenv("STRATA_KEYLESS_TRACE")) { ++ if (!*path) { err = "verify: STRATA_KEYLESS_TRACE needs a private output path"; return false; } ++ kl_trace_file_ = std::fopen(path, "wb"); ++ kl_trace_q_file_ = std::fopen((std::string(path) + ".q").c_str(), "wb"); ++ const size_t trace_bytes = (size_t) g.n_qsa_layers() * (size_t) max_t * ++ (size_t) g.n_head_kv * (size_t) g.head_dim * 2 * sizeof(float); ++ const size_t query_bytes = (size_t) g.n_qsa_layers() * (size_t) g.n_head * ++ (size_t) g.head_dim * sizeof(float); ++ if (!kl_trace_file_ || !kl_trace_q_file_ || ++ cudaHostAlloc((void**) &kl_trace_h_, trace_bytes, cudaHostAllocDefault) != cudaSuccess || ++ cudaHostAlloc((void**) &kl_trace_q_h_, query_bytes, cudaHostAllocDefault) != cudaSuccess) { ++ err = "verify: cannot create pinned keyless activation trace"; ++ return false; ++ } ++ } + sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise + sampling_.temperature = 0.0f; + #if defined(STRATA_GPU_METAL) +@@ -1560,12 +1578,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + cudaStream_t sx) { + if (native_qsa_enabled()) native_qsa_rms_norm_weighted(data, (const float*) norm->data, data, cols, rows, EPS, sx); + else rms_norm_weighted(data, (const float*) norm->data, rows, cols, EPS, sx); ++ if (st.without_key && norm == wqn) keyless_route_query(data, keyless_routing(l), rows / (int) NH, (int) NH, (int) HD, sx); // local keyless arm, between the norm and the rope + if (native_rope_enabled()) native_rope_apply(data, data, rows, cols, (int) s.n_rot, rope_scaling(), pos, sx); + else rope_neox_apply(data, data, rows, cols, (int) s.n_rot, st.cos_tab, st.sin_tab, pos, sx); + }; + // #783 PR-f (stuchapin909): the per-head RMSNorm and the rope in one launch, bit-identical to the pair + // (rope_parity check 6); STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes +- const bool fuse_nr = native_qsa_enabled() && native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot); ++ const bool fuse_nr = !st.without_key && native_qsa_enabled() && native_rope_enabled() && native_norm_rope_usable((int) HD, (int) s.n_rot); + auto norm_rope = [&](float* data, const WeightRef* norm, int rows, int cols, const int32_t* pos) { + if (fuse_nr && native_norm_rope_usable(cols, (int) s.n_rot)) { + native_qsa_rms_norm_rope(data, cols, (const float*) norm->data, data, rows, cols, (int) s.n_rot, EPS, +@@ -1726,16 +1745,29 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + } + if (!sidem) idx_key(cs); + stamp(l, 7, grp); +- mm(wk, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); ++ if (!st.without_key) mm(wk, kcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); // V-only (keyless) arm: no K + mm(wv, vcur_ + tb * NKV * HD, (int) N, (int) (NKV * HD)); +- if (qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); +- else for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); ++ if (!st.without_key && qb) norm_rope(kcur_ + tb * NKV * HD, wkn, (int) (n * NKV), (int) HD, pos_k + tb * NKV); ++ else if (!st.without_key) for (int t = tb; t < te; ++t) norm_rope(kcur_ + t * NKV * HD, wkn, (int) NKV, (int) HD, pos_ + t * NH); + if (st.kv_rot) { // K and V rotated before they are stored (kv_q4.hpp) + fwht256_inplace_cuda(kcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } else if (st.kv_hybrid) { // K8V4: only V is rotated + fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); + } ++ if (kl_trace_h_) { ++ const size_t width = (size_t) NKV * HD; ++ for (int t = tb; t < te; ++t) { ++ float* dst = kl_trace_h_ + ((size_t) qi * max_t_ + t) * 2 * width; ++ if (cudaMemcpyAsync(dst, kcur_ + (size_t) t * width, width * sizeof(float), ++ cudaMemcpyDeviceToHost, cs) != cudaSuccess || ++ cudaMemcpyAsync(dst + width, vcur_ + (size_t) t * width, width * sizeof(float), ++ cudaMemcpyDeviceToHost, cs) != cudaSuccess) { ++ err = "verify: keyless trace copy could not be captured"; ++ return false; ++ } ++ } ++ } + stamp(l, 8, grp); + if (!sidem) idx_snap(cs); + // #783 PR-d (stuchapin909): the window's K/V cells in one launch per pool instead of one per token (a +@@ -1896,6 +1928,12 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { + (uint64_t) n * (uint64_t) attn_scratch_floats_, attn_ + tb * NH * HD, n, cs))) + qsa_decode_attn_batch(qcur_ + tb * NH * HD, pools, sel_ + (size_t) tb * cap_, step_ + tb * kStepCount, cap_, + s, attn_scratch_ + (size_t) tb * attn_scratch_floats_, attn_ + tb * NH * HD, n, cs); ++ if (kl_trace_q_h_ && tb == 0 && ++ cudaMemcpyAsync(kl_trace_q_h_ + (size_t) qi * NH * HD, qcur_, ++ (size_t) NH * HD * sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess) { ++ err = "verify: keyless query trace copy could not be captured"; ++ return false; ++ } + } + stamp(l, 13, grp); + if (st.kv_rot || st.kv_hybrid) fwht256_inplace_cuda(attn_ + tb * NH * HD, (int64_t) n * NH, cs); // back: H^-1 = H +@@ -3140,6 +3178,30 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, + const cudaError_t se = cudaStreamSynchronize(cs_); + trace_ev("SYNCED", -1, -1, (int64_t) se); + if (se != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(se); return false; } ++ if (kl_trace_file_) { // local keyless study (STRATA_KEYLESS_TRACE): the window's K/V and first query, written once the GPU has finished ++ const uint32_t count = (uint32_t) T; ++ const size_t width = (size_t) g_->n_head_kv * (size_t) g_->head_dim; ++ bool written = std::fwrite(&count, sizeof(count), 1, kl_trace_file_) == 1 && ++ std::fwrite(&pos0, sizeof(pos0), 1, kl_trace_file_) == 1; ++ for (int64_t q = 0; written && q < g_->n_qsa_layers(); ++q) ++ for (int t = 0; written && t < T; ++t) ++ written = std::fwrite(kl_trace_h_ + ((size_t) q * max_t_ + t) * 2 * width, ++ sizeof(float), 2 * width, kl_trace_file_) == 2 * width; ++ if (!written || std::fflush(kl_trace_file_) != 0) { ++ err = "verify: cannot write keyless activation trace"; ++ return false; ++ } ++ const size_t query_width = (size_t) g_->n_head * (size_t) g_->head_dim; ++ bool q_written = std::fwrite(&count, sizeof(count), 1, kl_trace_q_file_) == 1 && ++ std::fwrite(&pos0, sizeof(pos0), 1, kl_trace_q_file_) == 1 && ++ std::fwrite(kl_trace_q_h_, sizeof(float), ++ (size_t) g_->n_qsa_layers() * query_width, kl_trace_q_file_) == ++ (size_t) g_->n_qsa_layers() * query_width; ++ if (!q_written || std::fflush(kl_trace_q_file_) != 0) { ++ err = "verify: cannot write keyless query trace"; ++ return false; ++ } ++ } + if (handoff_failed(err)) return false; // a stale hand-off: nothing of this window is used + if (ar_on() && h_plan_err_ != nullptr && *(volatile uint32_t*) h_plan_err_ != 0) { // #871: refresh_ar saw the table whole + *(volatile uint32_t*) h_plan_err_ = 0; +diff --git a/src/kernels/cuda/keyless.cu b/src/kernels/cuda/keyless.cu +new file mode 100644 +index 00000000..16485d30 +--- /dev/null ++++ b/src/kernels/cuda/keyless.cu +@@ -0,0 +1,25 @@ ++#include "strata/core/keyless.hpp" ++#include ++#include ++namespace strata::kernels { ++namespace { ++__global__ void route_kernel(float* q, const float* matrices, int heads) { ++ __shared__ float row[256]; ++ const int d = threadIdx.x, h = blockIdx.x % heads; ++ float* query = q + (size_t)blockIdx.x * 256; ++ row[d] = query[d]; ++ __syncthreads(); ++ const float* weight = matrices + ((size_t)h * 256 + d) * 256; ++ float sum = 0; ++ for (int i = 0; i < 256; ++i) sum = fmaf(row[i], weight[i], sum); ++ query[d] = sum; ++} ++} ++void keyless_route_query(float* q, const float* matrices, int64_t tokens, int heads, int dim, void* stream) { ++ if (!q || !matrices || tokens < 1 || heads < 1 || dim != 256 || tokens > INT32_MAX / heads) ++ throw std::runtime_error("invalid keyless query routing geometry or artifact"); ++ route_kernel<<<(unsigned)(tokens*heads),256,0,(cudaStream_t)stream>>>(q, matrices, heads); ++ const auto error = cudaGetLastError(); ++ if (error != cudaSuccess) throw std::runtime_error(cudaGetErrorString(error)); ++} ++} +diff --git a/src/kernels/cuda/kv_q8.cu b/src/kernels/cuda/kv_q8.cu +index a03e171b..3610dbfa 100644 +--- a/src/kernels/cuda/kv_q8.cu ++++ b/src/kernels/cuda/kv_q8.cu +@@ -42,7 +42,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict + } + const long long pos = (long long) __ldg(step + kStepPos); + const int h = blockIdx.x, g = blockIdx.y, t = threadIdx.x; +- const bool is_v = MULTI ? (blockIdx.z & 1) == 1 : blockIdx.z == 1; ++ const bool is_v = k_q == nullptr || (MULTI ? (blockIdx.z & 1) == 1 : blockIdx.z == 1); // k_q == nullptr: V-only (keyless) arm + const int groups = head_dim / KV_Q8_GROUP; + const float x = (is_v ? vcur : kcur)[h * head_dim + g * KV_Q8_GROUP + t]; + // max |x| over the 64 values: two warps, then combine through shared memory in a fixed order +@@ -66,7 +66,7 @@ __global__ void kv_append_q8_kernel(int8_t* __restrict__ k_q, int8_t* __restrict + (is_v ? v_q : k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? v_scale : k_scale)[row * groups + g] = sbits; + } +- if (host.k_q != nullptr) { ++ if ((is_v ? host.v_q : host.k_q) != nullptr) { + const long long row = ((pos / page_size) * kv_heads + h) * page_size + (pos % page_size); + (is_v ? host.v_q : host.k_q)[row * head_dim + g * KV_Q8_GROUP + t] = (int8_t) q; + if (t == 0) (is_v ? host.v_scale : host.k_scale)[row * groups + g] = sbits; +@@ -183,7 +183,7 @@ void kv_append_q8_step(int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_ + const int32_t* step, const float* kcur, const float* vcur, const QsaShapes& s, void* stream, + const KvHostPools* host) { + validate(s, "kv_append_q8"); +- const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), 2); ++ const dim3 grid((unsigned) s.n_head_kv, (unsigned) (s.head_dim / KV_Q8_GROUP), k_q ? 2 : 1); + kv_append_q8_kernel<<>>( + k_q, v_q, k_scale, v_scale, page_table, step, kcur, vcur, (int) s.n_head_kv, (int) s.head_dim, + (int) s.page_size, host ? *host : KvHostPools{}); +diff --git a/src/kernels/cuda/kv_stream.cu b/src/kernels/cuda/kv_stream.cu +index 209984b4..dc8ece7b 100644 +--- a/src/kernels/cuda/kv_stream.cu ++++ b/src/kernels/cuda/kv_stream.cu +@@ -40,6 +40,10 @@ Runs runs_of(const QsaAttnPools& slots, const KvHostPools& host, int fmt, const + r.src[1] = (const uint8_t*) host.k_scale; r.dst[1] = (uint8_t*) slots.k_scale; r.len[1] = scales; + r.src[2] = (const uint8_t*) host.v_q4; r.dst[2] = (uint8_t*) slots.v_q4; r.len[2] = v; + r.n = 3; ++ } else if (fmt == kKvValueInt8) { // local keyless arm: V codes + scales only ++ r.src[0] = (const uint8_t*) host.v_q; r.dst[0] = (uint8_t*) slots.v_q; r.len[0] = rows * (int)s.head_dim; ++ r.src[1] = (const uint8_t*) host.v_scale; r.dst[1] = (uint8_t*) slots.v_scale; r.len[1] = rows * (int)(s.head_dim / KV_Q8_GROUP) * 2; ++ r.n = 2; + } else if (fmt == kKvQ4) { + const int bytes = rows * (int) kv_q4_bytes_per_head((int) s.head_dim); + r.src[0] = (const uint8_t*) host.k_q4; r.dst[0] = (uint8_t*) slots.k_q4; r.len[0] = bytes; +@@ -198,6 +202,7 @@ __global__ void ring_kernel(int32_t* table, long long n_blocks, long long n_slot + + uint64_t kv_block_bytes(const QsaShapes& s, int fmt) { + const uint64_t rows = (uint64_t) (s.n_head_kv * s.page_size); ++ if (fmt == kKvValueInt8) return rows * ((uint64_t)s.head_dim + (uint64_t)(s.head_dim / KV_Q8_GROUP)*2); + if (fmt == kKvHybrid) + return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / KV_Q8_GROUP) * 2 + + rows * kv_q4_bytes_per_head((int) s.head_dim); +diff --git a/src/kernels/cuda/qsa_decode_attn.cu b/src/kernels/cuda/qsa_decode_attn.cu +index fbbef636..bffbf8c2 100644 +--- a/src/kernels/cuda/qsa_decode_attn.cu ++++ b/src/kernels/cuda/qsa_decode_attn.cu +@@ -1,5 +1,6 @@ + // src/kernels/cuda/qsa_decode_attn.cu - see include/strata/kernels/qsa_decode_attn.hpp. + #include "strata/kernels/qsa_decode_attn.hpp" ++#include "strata/kernels/mrope.hpp" + #include "strata/core/sm75_series.hpp" + #include "strata/core/sm120_series.hpp" + #include "strata/core/geometry.hpp" +@@ -79,7 +80,7 @@ __device__ __forceinline__ void load8_q4(const QsaAttnPools& p, bool value, long + template + __device__ __forceinline__ void load8(const QsaAttnPools& p, bool value, long long row, int d0, float* out) { + if constexpr (KV_MODE == 0) load8_f16(p, value, row, d0, out); +- else if constexpr (KV_MODE == 1) load8_q8(p, value, row, d0, out); ++ else if constexpr (KV_MODE == 1 || KV_MODE == 4) load8_q8(p, value, row, d0, out); + else if constexpr (KV_MODE == 3) { + // hybrid K8V4: both sides are defined - K unrotated INT8, V rotated Q4_0 - so a value=true call + // reads the Q4_0 pool instead of dereferencing the null v_q (no call site does today; PR review) +@@ -230,7 +231,22 @@ __device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, Qsa + if ((lane & 1) == 0 && head < G) sp[head][c] = score * scale; + } else { + float k8[8]; +- load8(p, false, srow[c], lane * 8, k8); ++ load8(p, KV_MODE == 4, srow[c], lane * 8, k8); ++ if constexpr (KV_MODE == 4) { ++ const int d0 = lane * 8, half = p.keyless_n_rot / 2; ++ if (d0 < p.keyless_n_rot) { ++ float paired[8]; ++ load8_q8(p, true, srow[c], d0 < half ? d0 + half : d0 - half, paired); ++ const int cell = ids[c0 + c]; ++ for (int d = 0; d < 8; ++d) { ++ const int pair = (d0 + d) % half; ++ const int rotary_pos = mrope_pos(p.keyless_mrope, cell, pair); ++ const float co = p.keyless_cos[(size_t)rotary_pos * half + pair]; ++ const float si = p.keyless_sin[(size_t)rotary_pos * half + pair]; ++ k8[d] = d0 < half ? k8[d]*co - paired[d]*si : k8[d]*co + paired[d]*si; ++ } ++ } ++ } + #pragma unroll + for (int h = 0; h < G; ++h) { + const int qflip = QUERY_SWIZZLE ? (lane & 4) : 0; +@@ -265,7 +281,7 @@ __device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, Qsa + float v; + if constexpr (KV_MODE == 0) { + v = __half2float(__ushort_as_half(p.v_pool[srow[c] * HD + t])); +- } else if constexpr (KV_MODE == 1) { ++ } else if constexpr (KV_MODE == 1 || KV_MODE == 4) { + const float sc = __half2float(__ushort_as_half(p.v_scale[srow[c] * (HD / KV_Q8_GROUP) + t / KV_Q8_GROUP])); + v = (float) p.v_q[srow[c] * HD + t] * sc; + } else { // modes 2 and 3: V is rotated Q4_0 (kv_q4.hpp); the caller rotates the output back +@@ -917,9 +933,9 @@ bool lane_cell_attn() { + return on; + } + +-// 0 fp16, 1 int8, 2 q4_0, 3 int8 K with q4_0 V ++// 0 fp16, 1 int8, 2 q4_0, 3 int8 K with q4_0 V, 4 (local, default-off keyless arm) int8 V only, K rebuilt from V + int attn_kv_mode(const QsaAttnPools& p) { +- return p.k_q4 != nullptr ? 2 : (p.k_q != nullptr && p.v_q4 != nullptr ? 3 : (p.k_q != nullptr ? 1 : 0)); ++ return p.without_key ? 4 : p.k_q4 != nullptr ? 2 : (p.k_q != nullptr && p.v_q4 != nullptr ? 3 : (p.k_q != nullptr ? 1 : 0)); + } + + // STRATA_ATTN_MERGE_V2: 1 merges with attn_merge_v2_kernel, 0 with attn_merge_kernel. Unset it follows +@@ -947,8 +963,12 @@ void launch_merge(int v2, const float* part_acc, const float* part_m, const floa + // kernel where it is built (the parity harness: never the environment). + void launch_chunks_batch(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* steps, + int64_t cap, const QsaShapes& s, float* scratch, int64_t n_q, cudaStream_t st, int kernel) { +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 +- : (pools.k_q != nullptr ? 1 : 0)); ++ const int kv_mode = attn_kv_mode(pools); ++ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || ++ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { ++ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); ++ std::exit(1); ++ } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + // per query: [acc: n_chunks*n_head*HD][m: n_chunks*n_head][l: n_chunks*n_head], all offsets from one stride + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); +@@ -961,7 +981,7 @@ void launch_chunks_batch(const float* q, const QsaAttnPools& pools, const int32_ + const bool pre = kernel < 0 ? pre75_attn() : kernel == 1; + #endif + // S25: STRATA_ATTN_LANECELL=1 - the score phase one cell per thread (bit-identical scores, no shuffle reductions) +- const bool lane_cell = kernel < 0 && lane_cell_attn(); ++ const bool lane_cell = kernel < 0 && lane_cell_attn() && kv_mode != 4; // the keyless arm has no lane-cell variant + #if defined(STRATA_HIP_GFX906) + static const bool query_swizzle = [] { + const char* v = std::getenv("STRATA_GFX906_ATTN_QUERY_SWIZZLE"); return v && v[0] == '1'; +@@ -1014,6 +1034,10 @@ void launch_chunks_batch(const float* q, const QsaAttnPools& pools, const int32_ + } + } else + #endif ++ if (kv_mode == 4) // local keyless arm (default off): V-only int8 pools, K rebuilt from V and the RoPE tables ++ attn_chunk_kernel<4><<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, scale, ++ part_acc, part_m, part_l, n_chunks, (int) cap, stride); ++ else + #if !defined(__HIPCC__) + if (kernel < 0 && kv_mode == 1 && attn_v3_on()) // (the parity harness names its kernel: never the environment) + attn_chunk_q8_v3_kernel<<>>(q, pools, ids, steps, (int) s.n_head_kv, (int) s.page_size, +@@ -1078,6 +1102,7 @@ bool qsa_decode_attn_slots(const float* q, const QsaAttnSlotPools& pools, const + std::exit(1); + } + const int kv_mode = attn_kv_mode(pools.p[0]); ++ if (kv_mode == 4) return false; // the keyless arm keeps the per-query calls (no slots kernel for it) + for (int64_t z = 0; z < n_q; ++z) { + if (!pools.p[z].page_table) { + std::fprintf(stderr, "qsa_decode_attn_slots: missing page table\n"); +@@ -1136,8 +1161,7 @@ void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, co + std::fprintf(stderr, "qsa_decode_attn_batch_rows: unsupported geometry or missing buffers\n"); + std::exit(1); + } +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 +- : (pools.k_q != nullptr ? 1 : 0)); ++ const int kv_mode = attn_kv_mode(pools); + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + const long long stride = (long long) qsa_decode_attn_scratch_floats(cap, s); + float* part_acc = scratch; +@@ -1149,7 +1173,7 @@ void qsa_decode_attn_batch_rows(const float* q, const QsaAttnPoolsRows& rows, co + // The plain kernel is what qsa_decode_attn_batch runs unless one of its variants is on (lane-cell scoring, the + // pre-sm_75 / gfx103x kernel, the gfx906 swizzle): there each row goes through that call, one launch per row. + static const bool lane_cell_rows = [] { const char* v = std::getenv("STRATA_ATTN_LANECELL"); return v && v[0] == '1'; }(); +- bool per_row = lane_cell_rows; ++ bool per_row = lane_cell_rows || kv_mode == 4; // the keyless arm has no rows kernel: one qsa_decode_attn_batch per row + #if defined(STRATA_ATTN_PRE75_BUILT) + per_row = per_row || pre75_attn(); + #endif +@@ -1186,19 +1210,24 @@ uint64_t qsa_decode_attn_scratch_floats(int64_t cap, const QsaShapes& s) { + + void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32_t* ids, const int32_t* step, + int64_t cap, const QsaShapes& s, float* scratch, float* attn, void* stream) { +- if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !scratch || !ids || !step || ++ if (s.head_dim != HD || s.n_head != (int64_t) G * s.n_head_kv || cap <= 0 || !q || !attn || !scratch || !ids || !step || + !pools.page_table) { + std::fprintf(stderr, "qsa_decode_attn: unsupported geometry or missing buffers\n"); + std::exit(1); + } +- const int kv_mode = pools.k_q4 != nullptr ? 2 : (pools.k_q != nullptr && pools.v_q4 != nullptr ? 3 +- : (pools.k_q != nullptr ? 1 : 0)); +- if (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) ++ const int kv_mode = attn_kv_mode(pools); ++ if (kv_mode == 4 ? (!pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64) ++ : (kv_mode == 3 ? (!pools.k_scale || !pools.v_q4) + : (kv_mode == 2 ? (!pools.v_q4) : (kv_mode == 1 ? (!pools.v_q || !pools.k_scale || !pools.v_scale) +- : (!pools.k_pool || !pools.v_pool)))) { ++ : (!pools.k_pool || !pools.v_pool))))) { + std::fprintf(stderr, "qsa_decode_attn: incomplete KV pools\n"); + std::exit(1); + } ++ if (kv_mode == 4 && (pools.k_pool || pools.k_q || pools.k_scale || pools.k_q4 || ++ !pools.v_q || !pools.v_scale || !pools.keyless_cos || !pools.keyless_sin || pools.keyless_n_rot != 64)) { ++ std::fprintf(stderr, "qsa_decode_attn: V-only requires only V codes/scales and RoPE tables\n"); ++ std::exit(1); ++ } + const int n_chunks = (int) ((cap + CHUNK - 1) / CHUNK); + float* part_acc = scratch; + float* part_m = scratch + (size_t) n_chunks * s.n_head * HD; +@@ -1206,6 +1235,10 @@ void qsa_decode_attn_step(const float* q, const QsaAttnPools& pools, const int32 + const float scale = 1.0f / sqrtf((float) HD); + const dim3 grid((unsigned) n_chunks, (unsigned) s.n_head_kv); + cudaStream_t st = (cudaStream_t) stream; ++ if (kv_mode == 4) // local keyless arm (default off) ++ attn_chunk_kernel<4><<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, scale, ++ part_acc, part_m, part_l, n_chunks, 0, 0); ++ else + #if !defined(__HIPCC__) + if (kv_mode == 1 && attn_v3_on()) + attn_chunk_q8_v3_kernel<<>>(q, pools, ids, step, (int) s.n_head_kv, (int) s.page_size, +diff --git a/src/kernels/keyless_parity.cpp b/src/kernels/keyless_parity.cpp +new file mode 100644 +index 00000000..107ebf2b +--- /dev/null ++++ b/src/kernels/keyless_parity.cpp +@@ -0,0 +1,119 @@ ++// Independent CPU reference for query routing and physical V-only attention. ++#include "strata/core/keyless.hpp" ++#include "strata/core/layer.hpp" ++#include "strata/kernels/qsa_decode_attn.hpp" ++#include "strata/kernels/f16_bits.hpp" ++#include "strata/kernels/kv_stream.hpp" ++#include ++#include ++#include ++#include ++#include ++#include ++ ++namespace { ++void check(cudaError_t e) { if (e != cudaSuccess) throw std::runtime_error(cudaGetErrorString(e)); } ++template T* device(const std::vector& values) { ++ T* p; check(cudaMalloc((void**)&p, values.size()*sizeof(T))); ++ check(cudaMemcpy(p, values.data(), values.size()*sizeof(T), cudaMemcpyHostToDevice)); return p; ++} ++} ++int main() { ++ using namespace strata::kernels; ++ try { ++ int count=0; if (cudaGetDeviceCount(&count)!=cudaSuccess || count==0) return 77; ++ constexpr int H=24, D=256, KV=2, CELLS=96, PAGE=4, BATCH=3, CAP=96; ++ std::vector query(BATCH*H*D), routing(H*D*D), routed(query.size()), co(CELLS*32), si(co.size()); ++ for (size_t i=0;i actual(query.size()); check(cudaMemcpy(actual.data(),dq,actual.size()*4,cudaMemcpyDeviceToHost)); ++ double route_error=0; for(size_t i=0;i2e-6) throw std::runtime_error("query routing disagrees with independent matrix product"); ++ const int pos[BATCH]={31,63,95}; ++ for(int p=0;p unrotated=routed; ++ std::vector positions(CELLS*3); ++ for(int cell=0;cell table(CELLS/PAGE), ids(BATCH*CAP,-1), steps(BATCH*kStepCount); ++ for(int page=0;page values(CELLS*KV*D); ++ std::vector scales(CELLS*KV*4); ++ for(int cell=0;cell scratch(BATCH*qsa_decode_attn_scratch_floats(CAP,qsa_real_shapes())), result(BATCH*H*D); ++ float *dsc=device(scratch), *dout=device(result); ++ qsa_decode_attn_batch(dq,pools,di,ds,CAP,qsa_real_shapes(),dsc,dout,BATCH,nullptr); ++ check(cudaMemcpy(result.data(),dout,result.size()*4,cudaMemcpyDeviceToHost)); ++ double error_sq=0, reference_sq=0, max_error=0; ++ for(int b=0;b scores(width), weights(width), reference(D,0); ++ for(int j=0;j1e-5 || max_error>1e-5) throw std::runtime_error("V-only attention disagrees with positional CPU reference"); ++ if(kv_block_bytes(qsa_real_shapes(),kKvValueInt8)*2!=kv_block_bytes(qsa_real_shapes(),kKvInt8)) ++ throw std::runtime_error("V-only block accounting is not half of K+V"); ++ std::printf("mrope=%d query_max_abs_error=%.9g attention_relative_l2=%.9g attention_max_abs_error=%.9g\n",vision,route_error,l2,max_error); ++ } ++ ++ std::printf("PASS: routed queries; three causal selections; permuted pages; raw value retrieval; no K allocation\n"); ++ return 0; ++ } catch(const std::exception& e) { std::fprintf(stderr,"keyless parity: %s\n",e.what()); return 1; } ++} +diff --git a/src/kernels/kv_stream_parity.cpp b/src/kernels/kv_stream_parity.cpp +index 722b7bc1..1b884944 100644 +--- a/src/kernels/kv_stream_parity.cpp ++++ b/src/kernels/kv_stream_parity.cpp +@@ -25,11 +25,13 @@ + #include + #include + #include ++#include + + namespace k = strata::kernels; + + namespace { + int g_fail = 0; ++float *keyless_cos=nullptr, *keyless_sin=nullptr; + void ck(cudaError_t e, const char* w) { + if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); } + } +@@ -61,10 +63,10 @@ struct Pools { // one K/V pool set of `pages` pages + const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim); + p.k_q4 = host ? halloc(b) : dalloc(b); + p.v_q4 = host ? halloc(b) : dalloc(b); +- } else if (fmt == k::kKvInt8) { +- p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); ++ } else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) { ++ if (fmt != k::kKvValueInt8) p.k_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); + p.v_q = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); +- p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); ++ if (fmt != k::kKvValueInt8) p.k_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + p.v_scale = host ? halloc(rows * 4) : dalloc(rows * 4); + } else { + p.k_pool = host ? halloc(rows * s.head_dim) : dalloc(rows * s.head_dim); +@@ -74,6 +76,8 @@ struct Pools { // one K/V pool set of `pages` pages + k::QsaAttnPools attn(const int32_t* table) const { + k::QsaAttnPools a; + a.k_pool = p.k_pool; a.v_pool = p.v_pool; a.k_q = p.k_q; a.v_q = p.v_q; a.k_scale = p.k_scale; ++ a.without_key = p.v_q && !p.k_q; ++ a.keyless_cos=keyless_cos; a.keyless_sin=keyless_sin; a.keyless_n_rot=64; + a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table; + return a; + } +@@ -88,7 +92,7 @@ void append(const Pools& pl, const int32_t* table, const int32_t* step, const fl + host ? &hk : nullptr); + k::kv_append_q4_step(pl.p.v_q4, pl.p.v_q4, table, step, vc, vc, s, nullptr, host ? &hv : nullptr); + } else if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host); +- else if (fmt == k::kKvInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); ++ else if (fmt == k::kKvInt8 || fmt == k::kKvValueInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host); + else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host); + } + +@@ -115,7 +119,7 @@ std::vector selection(int64_t n_kv, int64_t width, std::mt19937& rng) { + } + + bool run(int fmt) { +- const char* name = fmt == k::kKvHybrid ? "k8v4" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; ++ const char* name = fmt == k::kKvValueInt8 ? "v-only-int8" : fmt == k::kKvHybrid ? "k8v4" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16"; + k::QsaShapes s = k::qsa_real_shapes(); + const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700; // must evict: slots < blocks + const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8; +@@ -123,6 +127,16 @@ bool run(int fmt) { + std::mt19937 rng(7 + 4 * fmt); + std::normal_distribution nd(0.f, 1.f); + ++ if (fmt == k::kKvValueInt8) { ++ std::vector co(N*32), si(N*32); ++ for(int64_t pos=0;pos(co.size()); keyless_sin=dalloc(si.size()); ++ ck(cudaMemcpy(keyless_cos,co.data(),co.size()*4,cudaMemcpyHostToDevice),"cos"); ++ ck(cudaMemcpy(keyless_sin,si.data(),si.size()*4,cudaMemcpyHostToDevice),"sin"); ++ } + Pools ref, slots, host; + ref.alloc(n_blocks, s, fmt, false); + slots.alloc(n_slots, s, fmt, false); +@@ -237,7 +251,9 @@ bool run(int fmt) { + } + } // namespace + +-int main() { ++int main(int argc, char** argv) { ++ int count=0; if(cudaGetDeviceCount(&count)!=cudaSuccess || !count) return 77; ++ if(argc==2 && std::strcmp(argv[1],"--v-only")==0) return run(k::kKvValueInt8)?0:1; + std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n"); + const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4), d = run(k::kKvHybrid); + if (!a || !b || !c || !d) ++g_fail; +diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cpp +index 07636d0f..b8c2e7f8 100644 +--- a/src/kernels/ngram.cpp ++++ b/src/kernels/ngram.cpp +@@ -12,6 +12,9 @@ + #include + #include + #include ++#include ++#include ++#include + #include + #if !defined(_WIN32) + #include +@@ -23,6 +26,22 @@ + #include + #include + ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++#include ++#include ++#endif ++ ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) || defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++#include ++#include ++#endif ++ ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++#include "kar_ple_cache.hpp" ++#include "libkar.h" ++#include ++#endif ++ + #if defined(_WIN32) + // `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below. + #define WIN32_LEAN_AND_MEAN +@@ -35,6 +54,69 @@ namespace strata::kernels { + namespace { + /// The A/B arm. Host-token-path only, so it needs no atomics; see the note on `ple_prefetch_enable`. + bool g_ple_prefetch = true; ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++struct PleRowTrace { ++ int fd = -1; ++ std::mutex lock; ++ bool failed = false; ++ ++ PleRowTrace() { ++ const char* path = std::getenv("STRATA_PLE_ROW_TRACE_PATH"); ++ if (!path) return; ++ if (!*path) { ++ std::fprintf(stderr, "PLE row trace needs a private output path\n"); ++ return; ++ } ++ fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); ++ if (fd < 0) { ++ std::perror("cannot create private PLE row trace"); ++ return; ++ } ++ constexpr char header[] = "# strata-ple-rows v1: 16 global u32 row IDs per line\n"; ++ if (write(fd, header, sizeof(header) - 1) != static_cast(sizeof(header) - 1)) { ++ std::fprintf(stderr, "cannot write PLE row trace header\n"); ++ failed = true; ++ } ++ } ++ ++ ~PleRowTrace() { if (fd >= 0) close(fd); } ++ ++ void emit(const uint32_t* rows) { ++ if (fd < 0) return; ++ std::lock_guard guard(lock); ++ if (failed) return; ++ char line[PLE_N_HEADS * 12]; ++ size_t used = 0; ++ for (int h = 0; h < PLE_N_HEADS; ++h) { ++ const int written = std::snprintf(line + used, sizeof(line) - used, "%u%c", ++ rows[h], h + 1 == PLE_N_HEADS ? '\n' : ' '); ++ if (written < 0 || static_cast(written) >= sizeof(line) - used) { ++ failed = true; ++ std::fprintf(stderr, "PLE row trace line exceeded its buffer\n"); ++ return; ++ } ++ used += static_cast(written); ++ } ++ size_t done = 0; ++ while (done < used) { ++ const ssize_t n = write(fd, line + done, used - done); ++ if (n < 0 && errno == EINTR) continue; ++ if (n <= 0) { ++ failed = true; ++ if (n < 0) std::perror("cannot write PLE row trace"); ++ else std::fprintf(stderr, "cannot write PLE row trace: short write\n"); ++ return; ++ } ++ done += static_cast(n); ++ } ++ } ++}; ++ ++PleRowTrace& ple_row_trace() { ++ static PleRowTrace trace; ++ return trace; ++} ++#endif + } // namespace + + void ple_prefetch_enable(bool on) { g_ple_prefetch = on; } +@@ -95,6 +177,9 @@ void ngram_rows(const int32_t* tokens, const int32_t* prev, int n_tokens, const + out[i * PLE_N_HEADS + h] = (uint32_t) (mixed % c.vocab[h] + c.offset[h]); + } + } ++#if defined(STRATA_NEXT_EXPERIMENTAL_PLE_TRACE) ++ ple_row_trace().emit(out + i * PLE_N_HEADS); ++#endif + } + } + +@@ -242,12 +327,228 @@ struct PleTable::Impl { + uint8_t prefetch_raw[kMaxPrefetch][PLE_N_HEADS * PLE_ROW_BYTES_MAX] = {}; + float scale = 1.0f; // the FP8 table's one scale + uint32_t rb = PLE_ROW_BYTES; // bytes per row ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ struct KarPart { ++ uint32_t number = 0; ++ uint64_t row_base = 0; ++ const kar_tensor_info* tensor = nullptr; ++ }; ++ kar_archive* kar = nullptr; ++ int kar_fd = -1; ++ const uint8_t* kar_map = nullptr; ++ size_t kar_bytes = 0; ++ uint32_t kar_level = 0; ++ std::string kar_format; ++ std::vector kar_parts; ++ std::unique_ptr kar_gpu_cache; ++ void decode_kar_row(uint32_t row, float* out160) const { ++ const auto part = std::lower_bound(kar_parts.begin(), kar_parts.end(), row, ++ [](const KarPart& item, uint32_t wanted) { ++ return item.row_base + item.tensor->row_count <= wanted; ++ }); ++ const kar_tensor_info* t = part->tensor; ++ const uint64_t local_row = uint64_t(row) - part->row_base; ++ const uint64_t first_word = local_row * t->row_words; ++ const uint64_t book_offset = t->books_offset + ((uint64_t{1} << kar_level) - 2) * 2; ++ for (uint32_t word = 0; word < t->row_words; ++word) { ++ const uint64_t source_word = first_word + word; ++ const uint64_t scale_offset = t->scales_offset + 2 * (source_word / (t->group / 32)); ++ const float scale = strata::fp16_to_fp32(strata::read_u16(kar_map + scale_offset)); ++ uint32_t bits[8] = {}; ++ for (uint32_t level = 0; level < kar_level; ++level) { ++ const uint8_t* p = kar_map + t->planes_offset + uint64_t(level) * t->plane_stride_bytes ++ + source_word * 4; ++ bits[level] = uint32_t(p[0]) | (uint32_t(p[1]) << 8) | ++ (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); ++ } ++ for (uint32_t bit = 0; bit < 32; ++bit) { ++ uint32_t code = 0; ++ for (uint32_t level = 0; level < kar_level; ++level) ++ code = (code << 1) | ((bits[level] >> bit) & 1u); ++ const float book = strata::fp16_to_fp32(strata::read_u16(kar_map + book_offset + code * 2)); ++ out160[word * 32 + bit] = book * scale; ++ } ++ } ++ bytes_read += t->row_words * (uint64_t(kar_level) * 4 + 2); ++ } ++#endif + void decode(const uint8_t* row, float* out160) const { fmt->dequant(row, scale, out160); } + }; + + PleTable::PleTable() : impl_(new Impl) {} + PleTable::~PleTable() { close(); delete impl_; } + ++bool PleTable::open_kar(const std::string& kar_path, uint32_t level, std::string& err, ++ uint64_t expected_rows) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) kar_path; (void) level; (void) expected_rows; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ close(); ++ if (level < 1 || level > 8 || expected_rows == 0) { ++ err = "KAR PLE level or expected row count is invalid"; ++ return false; ++ } ++ kar_archive* archive = nullptr; ++ const kar_status status = kar_open(kar_path.c_str(), KAR_OPEN_VERIFY_PAYLOAD, &archive); ++ if (status != KAR_OK) { ++ err = std::string("KAR PLE archive: ") + kar_strerror(status) + ": " + kar_last_error(); ++ return false; ++ } ++ impl_->kar = archive; ++ impl_->kar_fd = ::open(kar_path.c_str(), O_RDONLY | O_CLOEXEC); ++ struct stat file_info {}; ++ if (impl_->kar_fd < 0 || fstat(impl_->kar_fd, &file_info) || file_info.st_size <= 0 || ++ uint64_t(file_info.st_size) != kar_info(impl_->kar)->archive_bytes) { ++ err = "KAR PLE cannot reopen the verified archive at its expected length"; ++ close(); ++ return false; ++ } ++ impl_->kar_bytes = size_t(file_info.st_size); ++ void* map = mmap(nullptr, impl_->kar_bytes, PROT_READ, MAP_PRIVATE, impl_->kar_fd, 0); ++ if (map == MAP_FAILED) { ++ err = "KAR PLE cannot map the verified archive"; ++ close(); ++ return false; ++ } ++ impl_->kar_map = static_cast(map); ++ const std::string parent = "per_layer_token_embd.weight"; ++ const std::string prefix = parent + "#strata-part-"; ++ uint32_t declared_parts = 0; ++ for (uint32_t i = 0; i < kar_tensor_count(impl_->kar); ++i) { ++ const kar_tensor_info* t = kar_tensor(impl_->kar, i); ++ const std::string name = t->name; ++ uint32_t number = 0, total = 0; ++ if (name == parent) { ++ number = total = 1; ++ } else if (name.rfind(prefix, 0) == 0) { ++ char extra = 0; ++ if (std::sscanf(name.c_str() + prefix.size(), "%u-of-%u%c", &number, &total, &extra) != 2) { ++ err = "KAR PLE part name is malformed"; ++ close(); ++ return false; ++ } ++ } else { ++ continue; ++ } ++ if (!number || !total || number > total || (declared_parts && declared_parts != total) || ++ t->storage_class != KAR_NESTED || t->source_dtype != KAR_F32 || ++ t->nesting != KAR_TOPDOWN || t->n_dims != 2 || ++ t->dims[0] != PLE_HEAD_DIM || t->row_words != PLE_HEAD_DIM / 32 || ++ t->n_elements % PLE_HEAD_DIM || t->group < 32 || t->group % 32 || ++ level < t->planes_min || level > t->planes_max) { ++ err = "KAR PLE part geometry or precision level differs from the model"; ++ close(); ++ return false; ++ } ++ declared_parts = total; ++ impl_->kar_parts.push_back({number, 0, t}); ++ } ++ std::sort(impl_->kar_parts.begin(), impl_->kar_parts.end(), ++ [](const Impl::KarPart& left, const Impl::KarPart& right) { ++ return left.number < right.number; ++ }); ++ if (!declared_parts || impl_->kar_parts.size() != declared_parts) { ++ err = "KAR PLE parts are absent or incomplete"; ++ close(); ++ return false; ++ } ++ uint64_t rows = 0; ++ for (uint32_t i = 0; i < impl_->kar_parts.size(); ++i) { ++ auto& part = impl_->kar_parts[i]; ++ if (part.number != i + 1 || part.tensor->row_count == 0 || ++ part.tensor->row_count > expected_rows - rows) { ++ err = "KAR PLE parts are out of order or exceed expected rows"; ++ close(); ++ return false; ++ } ++ part.row_base = rows; ++ rows += part.tensor->row_count; ++ } ++ if (rows != expected_rows) { ++ err = "KAR PLE row count differs from the model"; ++ close(); ++ return false; ++ } ++ impl_->n_rows = rows; ++ impl_->kar_level = level; ++ impl_->kar_format = "KAR-L" + std::to_string(level) + "-CPU"; ++ impl_->mode = PleIo::Mmap; ++ return true; ++#endif ++} ++ ++bool PleTable::enable_kar_gpu_cache(uint32_t cache_mib, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) cache_mib; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar || impl_->kar_level != 2 || impl_->kar_gpu_cache) { ++ err = "KAR PLE GPU cache requires an open level-2 archive and no existing cache"; ++ return false; ++ } ++ std::vector parts; ++ parts.reserve(impl_->kar_parts.size()); ++ for (const auto& part : impl_->kar_parts) parts.push_back({part.row_base, part.tensor}); ++ auto cache = std::make_unique(); ++ if (!cache->open(impl_->kar_map, impl_->kar_bytes, parts, cache_mib, 65536, err)) return false; ++ impl_->kar_gpu_cache = std::move(cache); ++ impl_->kar_format = "KAR-L2-GPU-cache"; ++ return true; ++#endif ++} ++ ++bool PleTable::kar_gpu_cache_enabled() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ return impl_->kar_gpu_cache != nullptr; ++#else ++ return false; ++#endif ++} ++ ++bool PleTable::collect_device(float* device_out2560, void* stream, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) device_out2560; (void) stream; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar_gpu_cache || !impl_->pending) { ++ err = "KAR PLE GPU collect requires a cache and an issued token"; ++ return false; ++ } ++ if (!impl_->kar_gpu_cache->enqueue(impl_->rows, PLE_N_HEADS, device_out2560, ++ reinterpret_cast(stream), err)) return false; ++ impl_->pending = false; ++ return true; ++#endif ++} ++ ++bool PleTable::gather_batch_device(const uint32_t* rows, size_t n_tokens, float* device_out, ++ void* stream, std::string& err) { ++#if !defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ (void) rows; (void) n_tokens; (void) device_out; (void) stream; ++ err = "experimental KAR PLE support is not compiled into this engine"; ++ return false; ++#else ++ if (!impl_->kar_gpu_cache || impl_->pending || !rows || !device_out || ++ n_tokens == 0 || n_tokens > 65536) { ++ err = "KAR PLE GPU gather requires a cache, no pending token, and 1..65536 tokens"; ++ return false; ++ } ++ const size_t count = n_tokens * PLE_N_HEADS; ++ const size_t chunk_rows = std::min(65536, impl_->kar_gpu_cache->slots()); ++ for (size_t offset = 0; offset < count; offset += chunk_rows) { ++ const size_t length = std::min(chunk_rows, count - offset); ++ if (!impl_->kar_gpu_cache->enqueue(rows + offset, length, ++ device_out + offset * PLE_HEAD_DIM, ++ reinterpret_cast(stream), err)) return false; ++ } ++ return true; ++#endif ++} ++ + bool PleTable::open(const std::string& gguf_path, std::string& err) { + return open(gguf_path, err, PleIoOptions{}); + } +@@ -450,6 +751,19 @@ void PleTable::prefetch_rows(const uint32_t* rows16) { + + void PleTable::close() { + wait_prefetches(); ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ impl_->kar_gpu_cache.reset(); ++ if (impl_->kar_map) munmap(const_cast(impl_->kar_map), impl_->kar_bytes); ++ impl_->kar_map = nullptr; ++ impl_->kar_bytes = 0; ++ if (impl_->kar_fd >= 0) ::close(impl_->kar_fd); ++ impl_->kar_fd = -1; ++ if (impl_->kar) kar_close(impl_->kar); ++ impl_->kar = nullptr; ++ impl_->kar_parts.clear(); ++ impl_->kar_level = 0; ++ impl_->kar_format.clear(); ++#endif + impl_->reader.close(); + impl_->pending = false; + impl_->locked = false; // the unmap below releases the lock +@@ -464,15 +778,32 @@ void PleTable::close() { + impl_->bytes_read = 0; + } + +-bool PleTable::is_open() const { return impl_->data != nullptr || impl_->reader.is_open(); } ++bool PleTable::is_open() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) return true; ++#endif ++ return impl_->data != nullptr || impl_->reader.is_open(); ++} + bool PleTable::locked() const { return impl_->locked; } +-const char* PleTable::format() const { return impl_->fmt->name; } ++const char* PleTable::format() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) return impl_->kar_format.c_str(); ++#endif ++ return impl_->fmt->name; ++} + PleIo PleTable::mode() const { return impl_->mode; } + uint64_t PleTable::rows() const { return impl_->n_rows; } + uint64_t PleTable::bytes_read() const { return impl_->bytes_read; } + + void PleTable::read_row(uint32_t row, float* out160) const { + std::lock_guard lk(impl_->mu); ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar) { ++ if (row >= impl_->n_rows) std::memset(out160, 0, (size_t) PLE_HEAD_DIM * sizeof(float)); ++ else impl_->decode_kar_row(row, out160); ++ return; ++ } ++#endif + if (impl_->mode == PleIo::Direct && impl_->reader.is_open()) { + uint8_t raw[PLE_ROW_BYTES_MAX]; + std::string err; +@@ -620,6 +951,21 @@ bool PleTable::gather_batch(const uint32_t* rows, size_t n_tokens, float* out, s + void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delay_us(us); } + + std::string PleTable::io_report() const { ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_PLE) ++ if (impl_->kar_gpu_cache) { ++ const auto s = impl_->kar_gpu_cache->stats(); ++ char buf[300]; ++ std::snprintf(buf, sizeof buf, ++ "PLE GPU cache: %llu hits, %llu misses (%.2f%% hit), %u slots (%.1f MiB compressed), " ++ "%llu compressed bytes, %llu H2D argument bytes", ++ (unsigned long long) s.hits, (unsigned long long) s.misses, ++ s.hits + s.misses ? 100.0 * double(s.hits) / double(s.hits + s.misses) : 0.0, ++ impl_->kar_gpu_cache->slots(), double(impl_->kar_gpu_cache->slots()) * 64.0 / 1048576.0, ++ (unsigned long long) s.compressed_bytes, ++ (unsigned long long) s.host_to_device_bytes); ++ return buf; ++ } ++#endif + if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {}; + const strata::ngram::ReaderStats s = impl_->reader.snapshot(); + char buf[400]; +diff --git a/src/prefill/kernels.cu b/src/prefill/kernels.cu +index a4f56f10..c549feb3 100644 +--- a/src/prefill/kernels.cu ++++ b/src/prefill/kernels.cu +@@ -2175,8 +2175,9 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res + uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + strata::kernels::KvHostPools host, strata::kernels::KvHostPools stage) { + const int64_t t = blockIdx.x; +- const int kvh = blockIdx.y, g = blockIdx.z >> 1; +- const bool is_v = (blockIdx.z & 1) != 0; ++ const bool value_only = k_pool == nullptr && k_q == nullptr; ++ const int kvh = blockIdx.y, g = value_only ? blockIdx.z : blockIdx.z >> 1; ++ const bool is_v = value_only || (blockIdx.z & 1) != 0; + const int d = g * 64 + threadIdx.x; + const float x = (is_v ? V : K)[t * 512 + kvh * 256 + d]; + const int64_t pos = pos0 + t; +@@ -2204,11 +2205,11 @@ __global__ void kv_append_kernel(const float* __restrict__ K, const float* __res + (is_v ? v_q : k_q)[row * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? v_scale : k_scale)[row * 4 + g] = sb; + } +- if (host.k_q != nullptr) { ++ if ((is_v ? host.v_q : host.k_q) != nullptr) { + (is_v ? host.v_q : host.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? host.v_scale : host.k_scale)[row_id * 4 + g] = sb; + } +- if (stage.k_q != nullptr) { ++ if ((is_v ? stage.v_q : stage.k_q) != nullptr) { + (is_v ? stage.v_q : stage.k_q)[row_id * 256 + d] = (int8_t) q; + if (threadIdx.x == 0) (is_v ? stage.v_scale : stage.k_scale)[row_id * 4 + g] = sb; + } +@@ -2443,7 +2444,7 @@ void kv_append(const float* K, const float* V, int64_t T, int64_t pos0, const in + uint16_t* k_pool, uint16_t* v_pool, int8_t* k_q, int8_t* v_q, uint16_t* k_scale, uint16_t* v_scale, + void* stream, const strata::kernels::KvHostPools* host, const strata::kernels::KvHostPools* stage) { + if (T <= 0) return; +- kv_append_kernel<<>>( ++ kv_append_kernel<<>>( + K, V, pos0, page_table, page_size, k_pool, v_pool, k_q, v_q, k_scale, v_scale, + host ? *host : strata::kernels::KvHostPools{}, stage ? *stage : strata::kernels::KvHostPools{}); + check("kv_append"); +diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp +index 6cb888e5..6dbf4156 100644 +--- a/src/prefill/prefill.cpp ++++ b/src/prefill/prefill.cpp +@@ -30,10 +30,12 @@ + #include "strata/kernels/cpu/expert_layout.hpp" + #include "strata/kernels/cpu/hadamard.hpp" + #include "strata/kernels/qsa.hpp" ++#include "strata/kernels/mrope.hpp" + #include "strata/kernels/kv_stream.hpp" + #include "strata/kernels/cvec.hpp" + #include "strata/kernels/kv_q4.hpp" + #include "strata/core/layer.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/core/native_dense.hpp" + #include "strata/core/native_head.hpp" + #include "strata/kernels/verify_kernels.hpp" +@@ -65,6 +67,8 @@ + #include + #include + #include ++#include ++#include + + #ifndef STRATA_PREFILL_MMQ + // A build without the llama.cpp sources (no STRATA_NATIVE_EXPERTS): no MMQ, the FP16 expert path everywhere. +@@ -1035,9 +1039,9 @@ void take_stage(Alloc& o_borrowed, const core::SessionState& ss, const strata::k + st.k_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + st.v_q4 = o.take(rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), ok); + } else if (q0.kv_int8) { +- st.k_q = o.take(rows * s.head_dim, ok); ++ if (!q0.without_key) st.k_q = o.take(rows * s.head_dim, ok); + st.v_q = o.take(rows * s.head_dim, ok); +- st.k_scale = o.take(rows * (s.head_dim / 64), ok); ++ if (!q0.without_key) st.k_scale = o.take(rows * (s.head_dim / 64), ok); + st.v_scale = o.take(rows * (s.head_dim / 64), ok); + } else { + st.k_pool = o.take(rows * s.head_dim, ok); +@@ -2594,6 +2598,21 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + const core::ModelGeometry& g = *m.g; + core::SessionState& ss = *m.ss; + const auto t_start = Clock::now(); ++ // Offline teacher capture for fitting only the paper's query-routing parameters. ++ // Explicitly bounded and prohibited in serving; this path never predicts or stores K in V-only mode. ++ std::ofstream keyless_trace; ++ if (const char* path = std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) { ++ if (!*path || n > 4096 || pos0 != 0 || ss.qsa_states[0].without_key || std::filesystem::exists(path)) { ++ err = "keyless teacher trace requires a new private file, ordinary K+V and at most 4096 prompt tokens"; ++ return false; ++ } ++ keyless_trace.open(path, std::ios::binary); ++ if (!keyless_trace) { err = "cannot open keyless teacher trace"; return false; } ++ std::filesystem::permissions(path, std::filesystem::perms::owner_read | std::filesystem::perms::owner_write); ++ keyless_trace.write("SKLTRACE", 8); ++ const uint32_t header[5] = {1, (uint32_t)g.n_qsa_layers(), (uint32_t)g.n_head, (uint32_t)g.n_head_kv, (uint32_t)g.head_dim}; ++ keyless_trace.write((const char*)header, sizeof(header)); ++ } + const int64_t LB = stage_lb_, LE = stage_le_; + // The direct successor's future lives on the Prefill object. Intermediate + // stages therefore do not drain the complete remaining GPU chain here. +@@ -2667,6 +2686,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + // after this one is read on a thread while the GPU runs this one, into the other of two buffers. The rows + // depend only on the tokens (the two before a position name its n-grams), so this is the same data. + const bool ple_on = ss.ple.ready() && LB <= 1 && 1 < LE; ++ const bool ple_gpu_cache = ple_on && ss.ple.table->kar_gpu_cache_enabled(); + // the PLE block batched over the chunk: the pinned postops and a BF16 or GGUF-native key (else token by token); + // STRATA_PLE_BATCH=0 keeps the per-token block (the A/B) + static const bool ple_batch_env = [] { +@@ -2677,7 +2697,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + (ss.ple.w.key_bf16 != nullptr || ss.ple.w.key_native_data != nullptr) && + m.region_bytes / ((uint64_t) (3 * strata::kernels::NG_HC_DIM + N + 4) * 4 + (uint64_t) N * 2 + 4096) >= 64; + const int32_t prev0[2] = {prev[0], prev[1]}; +- auto ple_gather = [&m, &ss, tokens, n, prev0, C](int64_t c0, int buf, std::string& e) -> bool { ++ auto ple_gather = [&m, &ss, tokens, n, prev0, C, ple_gpu_cache](int64_t c0, int buf, std::string& e) -> bool { + const int64_t T = std::min(C, n - c0); + auto at = [&](int64_t i) { return i < 2 ? prev0[i] : (int32_t) tokens[i - 2]; }; // prev0, then the tokens + int32_t pv[2] = {at(c0), at(c0 + 1)}; +@@ -2688,7 +2708,8 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + pv[0] = pv[1]; + pv[1] = tok; + } +- return ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, m.ple_emb_host[buf], e); ++ return ple_gpu_cache || ss.ple.table->gather_batch(m.ple_rows[buf].data(), (size_t) T, ++ m.ple_emb_host[buf], e); + }; + std::string ple_next_err; + std::future ple_next; // declared after everything it reads: an early return waits for it +@@ -2838,31 +2859,38 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + if (!ple_pending) return true; + ple_pending = false; + const auto tp = Clock::now(); +- if (!ple_next.get()) { +- err = ple_next_err; +- return false; +- } +- // #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before +- if ((m.ple_pageable[ple_buf].empty() +- ? cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs) +- : m.up_ring.h2d(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, m.cs)) != +- cudaSuccess || +- cudaEventRecord(m.ple_copied[ple_buf], m.cs) != cudaSuccess) { +- err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); +- return false; +- } +- if (c0 + C < n) { +- // the other buffer's upload (a chunk ago) is done before the SSD thread refills it +- if (cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]) != cudaSuccess) { ++ if (ple_gpu_cache) { // local KAR PLE GPU row cache (default off): ple_gather only computed the n-gram rows ++ if (!ple_next.get()) { ++ err = ple_next_err; ++ return false; ++ } ++ if (!ss.ple.table->gather_batch_device(m.ple_rows[0].data(), (size_t) T, m.ple_emb, m.cs, err)) return false; ++ } else { ++ if (!ple_next.get()) { ++ err = ple_next_err; ++ return false; ++ } ++ // #1996: the pageable fallback (no RAM to pin) goes up through a pinned slot; the pinned buffers as before ++ if ((m.ple_pageable[ple_buf].empty() ++ ? cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs) ++ : m.up_ring.h2d(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, m.cs)) != ++ cudaSuccess || ++ cudaEventRecord(m.ple_copied[ple_buf], m.cs) != cudaSuccess) { + err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } +- ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + C, b = ple_buf ^ 1] { +- strata::aux_cpus::pin_current_thread(); +- return ple_gather(c1, b, ple_next_err); +- }); ++ if (c0 + C < n) { ++ // the other buffer's upload (a chunk ago) is done before the SSD thread refills it ++ if (cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]) != cudaSuccess) { ++ err = std::string("prefill: the PLE rows' upload failed: ") + cudaGetErrorString(cudaGetLastError()); ++ return false; ++ } ++ ple_next = std::async(std::launch::async, [&ple_gather, &ple_next_err, c1 = c0 + C, b = ple_buf ^ 1] { ++ strata::aux_cpus::pin_current_thread(); ++ return ple_gather(c1, b, ple_next_err); ++ }); ++ } + } +- ple_buf ^= 1; + stats_.ms_ple += ms_since(tp); + return true; + }; +@@ -3291,13 +3319,13 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + *wikn = need(v, "indexer.k_norm.weight", err); + if (!wq || !wk || !wv || !wo || !wik || !wiq || !wqn || !wkn || !wiqn || !wikn) return false; + pt.mark(kPfQsa, cs); +- if (!native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; ++ if (!st.without_key && !native_proj(m.gemm, wk, m.mixed_h, m.Kc, T, v.name("attn_k.weight"), err)) return false; + if (!native_proj(m.gemm, wv, m.mixed_h, m.Vc, T, v.name("attn_v.weight"), err)) return false; + if (!native_proj(m.gemm, wq, m.mixed_h, m.Qf, T, v.name("attn_q.weight"), err)) return false; + if (!bf16_proj(m.gemm, wik, m.mixed_bf, m.idx_raw, T, v.name("indexer.k_proj.weight"), err, 0, m.mixed_bf_lo)) return false; + if (!bf16_proj(m.gemm, wiq, m.mixed_bf, m.q_idx, T, v.name("indexer.q_proj.weight"), err, 0, m.mixed_bf_lo)) 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, strata::kernels::rope_scaling(), m.cs); ++ if (!st.without_key) rms_rows(m.Kc, (const float*) wkn->data, T * 2, 256, 256, EPS, m.cs); ++ if (!st.without_key) 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; +@@ -3360,6 +3388,19 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + if (staged) pf_step("reading the prompt (batched, step sync): the K/V append at layer", l); + split_q(m.Qf, m.q, T, m.cs); + rms_rows(m.q, (const float*) wqn->data, T * 24, 256, 256, EPS, m.cs); ++ if (keyless_trace.is_open()) { ++ const int32_t record[3] = {(int32_t)l, (int32_t)p0, (int32_t)T}; ++ keyless_trace.write((const char*)record, sizeof(record)); ++ for (const auto& tensor : std::vector>{ ++ {m.q,(size_t)T*24*256}, {m.Kc,(size_t)T*2*256}, {m.Vc,(size_t)T*2*256}}) { ++ std::vector host(tensor.second); ++ if (cudaMemcpyAsync(host.data(), tensor.first, host.size()*sizeof(float), cudaMemcpyDeviceToHost, cs) != cudaSuccess || ++ cudaStreamSynchronize(cs) != cudaSuccess) { err="keyless teacher readback failed"; return false; } ++ keyless_trace.write((const char*)host.data(), host.size()*sizeof(float)); ++ } ++ if (!keyless_trace) { err="keyless teacher trace write failed"; return false; } ++ } ++ if (st.without_key) strata::kernels::keyless_route_query(m.q, core::keyless_routing(l), T, 24, 256, m.cs); + rope(m.q, T, 24, 256, 6144, p0, strata::kernels::rope_scaling(), m.cs); + if (st.kv_rot) 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); +@@ -3495,15 +3536,17 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri + } + } + } +- const strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) ++ strata::kernels::QsaAttnPools pools = staged ? pools_of(m.stage, m.ident_table) + : core::qsa_attn_pools(st); ++ pools.without_key = st.without_key; ++ pools.keyless_cos = st.cos_tab; pools.keyless_sin = st.sin_tab; pools.keyless_n_rot = 64; pools.keyless_mrope = strata::kernels::mrope_table(); + pt.mark(kPfQsaAttn, cs); + // perf-review D-1: the whole chunk on tensor cores, one block per (query, KV head), FP32-level + // accuracy but not bitwise (qsa_prompt_attn.hpp). Q4_0 KV, or STRATA_PROMPT_ATTN_OLD=1: the + // decode kernel, 32 queries at a time (K8V4 runs the tensor kernel's mode 3: INT8 K, + // V dequantized from its q4_0 blocks to fp16 at gather) + static const bool old_attn = std::getenv("STRATA_PROMPT_ATTN_OLD") != nullptr; +- if (old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, ++ if (st.without_key || old_attn || !strata::kernels::qsa_prompt_attn_batch(m.q, pools, m.sel_ids, m.steps_dev, m.cap, s, + m.attn, T, m.cs)) + for (int64_t t0 = 0; t0 < T; t0 += m.attn_batch) { + const int64_t nb = std::min(m.attn_batch, T - t0); +diff --git a/src/program/generate.cpp b/src/program/generate.cpp +index d381227d..370e310f 100644 +--- a/src/program/generate.cpp ++++ b/src/program/generate.cpp +@@ -31,6 +31,9 @@ + #include "strata/core/conversation_memory.hpp" + #include "strata/core/coupled_draft.hpp" + #include "strata/core/expert_source.hpp" ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++#include "kar_expert_miss.hpp" ++#endif + #include "strata/core/foresight_swap.hpp" + #include "strata/core/pinned.hpp" + #include "strata/core/pin_budget.hpp" +@@ -76,6 +79,7 @@ + #include "strata/prefill/moe_mmq.hpp" + #endif + #include "strata/core/native_dense.hpp" ++#include "strata/core/keyless.hpp" + #include "strata/program/batch_read.hpp" + #include "strata/program/logits_selection.hpp" + #include "strata/program/conv_cache.hpp" +@@ -479,6 +483,9 @@ struct Options { + std::string embd_gguf; + /// Plan v0.3 P2: how the n-gram table is read. Direct (default) = unbuffered SSD reads, table never in RAM. + std::string ple_io = "direct"; ++ std::string ple_kar; ///< experimental PLE-only KAR quality arm; all other weights stay native ++ uint32_t ple_kar_level = 2; ++ uint32_t ple_kar_gpu_cache_mib = 0; ///< opt-in bounded compressed GPU PLE cache; 0 keeps CPU gather + bool ple_io_explicit = false; ///< --ple-io was given: the engine only warns when direct measures slow + int64_t ple_row_cache = 1 << 20; ///< bounded row cache (rows of 90 B); 0 disables + int ple_inflight = 256; // the prompt path reads a chunk's rows at once: 64 left the SSD half idle (32K: 303 -> 189 ms) +@@ -818,6 +825,9 @@ void usage() { + " so a caller never has to export environment variables\n" + " --ple-gguf PATH required PLE table (original second GGUF shard); with --native, the model's\n" + " shard that holds per_layer_token_embd.weight when not given\n" ++ " --ple-kar PATH experimental PLE-only KAR CPU quality arm (requires a KAR-enabled build)\n" ++ " --ple-kar-level N precision of the experimental PLE KAR arm (default 2)\n" ++ " --ple-kar-gpu-cache-mib N experimental compressed PLE row cache in VRAM (1..1024; level 2)\n" + " --no-ple explicit diagnostic ablation of the PLE layer\n" + " --ple-io direct|mmap|ram n-gram table reads (plan v0.3 P2). direct (default): unbuffered SSD\n" + " reads, the table never enters RAM or the file cache; mmap: A/B arm;\n" +@@ -2476,6 +2486,29 @@ int main(int argc, char** argv) { + else if (a == "--dump-halves") o.dump_halves = next("--dump-halves"); + else if (a == "--dump-routing") o.dump_routing = next("--dump-routing"); + else if (a == "--ple-gguf") o.ple_gguf = next("--ple-gguf"); ++ else if (a == "--ple-kar") o.ple_kar = next("--ple-kar"); ++ else if (a == "--ple-kar-level") { ++ const std::string value = next("--ple-kar-level"); ++ unsigned level = 0; ++ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), level); ++ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || ++ level < 1 || level > 8) { ++ std::fprintf(stderr, "strata generate: --ple-kar-level must be an integer from 1 to 8\n"); ++ return 2; ++ } ++ o.ple_kar_level = level; ++ } ++ else if (a == "--ple-kar-gpu-cache-mib") { ++ const std::string value = next("--ple-kar-gpu-cache-mib"); ++ unsigned mib = 0; ++ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), mib); ++ if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || ++ mib < 1 || mib > 1024) { ++ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib must be 1..1024\n"); ++ return 2; ++ } ++ o.ple_kar_gpu_cache_mib = mib; ++ } + else if (a == "--no-ple") o.no_ple = true; + else if (a == "--ple-io") { o.ple_io = next("--ple-io"); o.ple_io_explicit = true; } + else if (a == "--ple-row-cache") o.ple_row_cache = std::atoll(next("--ple-row-cache")); +@@ -2895,6 +2928,10 @@ int main(int argc, char** argv) { + } + #endif + strata::core::set_coupled_draft(o.coupled_draft); ++ if ((std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE")) && (o.serve || o.max_new > 512)) { ++ std::fprintf(stderr, "strata generate: STRATA_KEYLESS_TRACE is offline only and needs --max-new <= 512\n"); ++ return 2; ++ } + { // --host-core / STRATA_HOST_CORE, before the pool and the session pin any thread + std::string hc = o.host_core; + if (hc.empty()) +@@ -3193,6 +3230,11 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: --kv must be fp16, int8, q4_0 or k8v4\n"); + return 2; + } ++ const char* keyless_path = std::getenv("STRATA_KEYLESS_ROUTING"); ++ if (keyless_path && (!*keyless_path || o.kv != "int8" || o.gpu_stages || !o.dump_halves.empty() || std::getenv("STRATA_KEYLESS_TRACE") || std::getenv("STRATA_KEYLESS_PREFILL_TRACE") || (std::getenv("STRATA_KV_ROT") && std::getenv("STRATA_KV_ROT")[0] == '1'))) { ++ std::fprintf(stderr, "strata: keyless requires INT8, no Hadamard rotation, one GPU stage and no diagnostic dumps\n"); return 2; ++ } ++ strata::core::qsa_set_without_key(keyless_path != nullptr); + strata::core::qsa_set_kv_int8(o.kv == "int8"); + strata::core::qsa_set_kv_q4(o.kv == "q4_0"); // PR #21: 4-bit codes after a Hadamard rotation (kv_q4.hpp) + // STRATA_KV_ROT=1: INT8 K/V through the Hadamard rotation --kv q4_0 already uses. Opt-in: first-token KL to +@@ -3296,6 +3338,15 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: --no-ple and --ple-gguf are mutually exclusive\n"); + return 2; + } ++ if ((o.no_ple && !o.ple_kar.empty()) || (o.ple_kar.empty() && o.ple_kar_level != 2) || ++ (!o.ple_kar.empty() && (o.ple_kar_level < 1 || o.ple_kar_level > 8 || o.ple_io != "direct"))) { ++ std::fprintf(stderr, "strata generate: --ple-kar requires PLE, level 1..8, and default --ple-io\n"); ++ return 2; ++ } ++ if (o.ple_kar_gpu_cache_mib && (o.ple_kar.empty() || o.ple_kar_level != 2)) { ++ std::fprintf(stderr, "strata generate: --ple-kar-gpu-cache-mib requires --ple-kar at level 2\n"); ++ return 2; ++ } + if (o.native_ple_postops && o.no_ple) { + std::fprintf(stderr, "strata generate: --native-ple-postops requires PLE enabled\n"); + return 2; +@@ -3755,6 +3806,37 @@ int main(int argc, char** argv) { + rope_cfg.type == RST::YaRN ? "YaRN" : "--yarn-attn-factor", rope_cfg.mscale()); + } + } ++ const char* kar_expert_archive = std::getenv("STRATA_NEXT_KAR_EXPERTS_ARCHIVE"); ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ strata::kar::ExpertMiss kar_expert_miss; ++ if (kar_expert_archive != nullptr) { ++ const char* level_text = std::getenv("STRATA_NEXT_KAR_EXPERTS_LEVEL"); ++ if (!native_pack || o.no_pool || !split_devs.empty() || remote_caches || ++ !level_text || std::strlen(level_text) != 1 || level_text[0] < '1' || level_text[0] > '8' || ++ g.n_embd != strata::kernels::cpu::H) { ++ std::fprintf(stderr, "strata generate: experimental KAR misses require a native pack, one GPU, " ++ "the expert pool and explicit STRATA_NEXT_KAR_EXPERTS_LEVEL=1..8\n"); ++ return 2; ++ } ++ for (const auto& f : strata::kernels::cpu::expert_layout().fmt) ++ if (f.n_embd != strata::kernels::cpu::H || f.n_ff != strata::kernels::cpu::FF) { ++ std::fprintf(stderr, "strata generate: unsupported KAR expert geometry\n"); return 2; ++ } ++ if (!kar_expert_miss.open(kar_expert_archive, (uint32_t) g.n_layers, (uint32_t) g.n_expert, ++ (uint32_t) g.n_embd, strata::kernels::cpu::FF, ++ (uint32_t) (level_text[0] - '0'), err)) { ++ std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; ++ } ++ // Native resident hits are the baseline. Route all otherwise CPU/PCIe ++ // misses to the explicit experimental arm; use pcie-frac=0 in its baseline. ++ o.pcie_frac = 0; ++ } ++#else ++ if (kar_expert_archive != nullptr) { ++ std::fprintf(stderr, "strata generate: this build has no experimental KAR expert support\n"); ++ return 2; ++ } ++#endif + strata::core::NativeEmbed native_embed; + if (native_pack) { + if (o.native_preset.empty() || o.spec < 2 || o.keep_canonical || +@@ -3978,6 +4060,10 @@ int main(int argc, char** argv) { + return 2; + } + ++ if (keyless_path && !strata::core::keyless_load(keyless_path, wt, g, err)) { ++ std::fprintf(stderr, "strata: keyless routing: %s\n", err.c_str()); return 1; ++ } ++ if (keyless_path) std::fprintf(stderr, "strata: experimental V-only QSA query routing; indexer and MTP keys retained; quality gate pending\n"); + strata::core::SessionState ss; + void* sbuf = nullptr; // allocated after the layer-split search, sized to CUDA0's own layer range (the carve) + // **THE ENGINE RAN ON THE LEGACY DEFAULT STREAM, WHICH ON WDDM IS THE SLOW PATH.** All four session +@@ -4054,13 +4140,19 @@ int main(int argc, char** argv) { + pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0; + if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0; + } +- if (!ple_table.open(o.ple_gguf, err, pio)) { ++ const bool ple_open = o.ple_kar.empty() ? ple_table.open(o.ple_gguf, err, pio) ++ : ple_table.open_kar(o.ple_kar, o.ple_kar_level, err); ++ if (!ple_open) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); + return 1; + } ++ if (o.ple_kar_gpu_cache_mib && !ple_table.enable_kar_gpu_cache(o.ple_kar_gpu_cache_mib, err)) { ++ std::fprintf(stderr, "strata generate: PLE GPU cache: %s\n", err.c_str()); ++ return 1; ++ } + // Recommend, never force: when the default direct reads measure slow, switch to the mapped reads (40-100x + // faster on the reporters' drives); an explicit --ple-io direct is kept and only warned about. +- if (pio.mode == strata::kernels::PleIo::Direct && std::getenv("STRATA_PLE_PROBE") == nullptr) { ++ if (o.ple_kar.empty() && pio.mode == strata::kernels::PleIo::Direct && std::getenv("STRATA_PLE_PROBE") == nullptr) { // (not for the local KAR PLE arm) + constexpr double kSlowRowsPerS = 15000.0; // ~60 MB/s of 4 KiB pages; a healthy NVMe is >100k + const double rps = ple_direct_rows_per_s(ple_table); + if (rps >= kSlowRowsPerS) +@@ -4109,7 +4201,12 @@ int main(int argc, char** argv) { + std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n", + ple_table.locked() ? "locked in RAM" : "loaded (not locked)", + std::chrono::duration(Clock::now() - tpl).count()); +- if (pio.keepalive_ms > 0) ++ if (!o.ple_kar.empty()) ++ std::fprintf(stderr, "strata generate: experimental PLE KAR %s arm at level %u%s\n", ++ o.ple_kar_gpu_cache_mib ? "bounded GPU-cache" : "CPU quality", ++ o.ple_kar_level, ++ o.ple_kar_gpu_cache_mib ? " (prefill/decode CUDA, speculative verification CPU)" : ""); ++ else if (pio.keepalive_ms > 0) + std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after " + "%.0f ms without a read, until %.0f s after the last request " + "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s); +@@ -5245,7 +5342,8 @@ int main(int argc, char** argv) { + return 1; + } + std::fprintf(stderr, "strata generate: PLE on, table %llu rows of %s\n", +- (unsigned long long) ple_table.rows(), o.ple_gguf.c_str()); ++ (unsigned long long) ple_table.rows(), ++ o.ple_kar.empty() ? o.ple_gguf.c_str() : o.ple_kar.c_str()); + } + } + mem_mark("the session (KV, GDN state, PLE history)"); +@@ -6773,6 +6871,12 @@ int main(int argc, char** argv) { + + if (remote_opt && !remote_opt->init(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + Drive drive; ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if (kar_expert_archive != nullptr) { ++ drive.d.experimental_miss = &strata::kar::ExpertMiss::dispatch; ++ drive.d.experimental_miss_user = &kar_expert_miss; ++ } ++#endif + // #731 (opt-in, STRATA_DISJOINT_ADAPT=1): the adaptive tiers leave an expert a helper GPU holds out of the primary's + // promotion candidates (it would sit in both caches). Asked live, from the helper's own cache (RemoteExperts::holds, + // #854), so an expert the helper's tier swaps in or out later is followed - never a copy taken at load. +@@ -12402,6 +12506,10 @@ int main(int argc, char** argv) { + // unknown keys are skipped: the ids start at the first token without '=' + } + } ++ if (kar_expert_archive != nullptr && req_pcie_frac != 0.0) { ++ std::printf("ERR experimental KAR misses require pcie_frac=0\n"); ++ continue; ++ } + strata::prefill::Prefill::set_pipe_request(req_pipe); // every request sets it: none carries over + std::vector req_bias; + std::string bias_error; +@@ -15376,6 +15484,8 @@ int main(int argc, char** argv) { + const int64_t q4b = (int64_t) strata::kernels::kv_q4_bytes_per_head((int) qs.head_dim); + a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q4 : st.v_q4, q4b}, + {h ? st.host.k_scale : st.k_scale, scb}}; ++ } else if (st.without_key) { ++ a = {{h ? st.host.v_q : st.v_q, kvb}, {h ? st.host.v_scale : st.v_scale, scb}}; + } else if (st.kv_int8) { + a = {{h ? st.host.k_q : st.k_q, kvb}, {h ? st.host.v_q : st.v_q, kvb}, + {h ? st.host.k_scale : st.k_scale, scb}, {h ? st.host.v_scale : st.v_scale, scb}}; +@@ -15579,6 +15689,11 @@ int main(int argc, char** argv) { + 100.0 * (double) req_hits / (double) req_look, + (long long) req_hits, (long long) req_look, off); + } ++#if defined(STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS) ++ if (kar_expert_archive != nullptr) ++ std::fprintf(stderr, "strata serve: KAR verifier entries computed since startup: %llu\n", ++ (unsigned long long) kar_expert_miss.computed()); ++#endif + if (drive.d.tail_experts > 0) // STRATA_ROUTE_TAIL_SKIP, cumulative + std::fprintf(stderr, "strata serve: route tail skip: %lld missed experts skipped (%lld entries) since the " + "start\n", (long long) drive.d.tail_experts, (long long) drive.d.tail_skipped); +@@ -15745,6 +15860,8 @@ int main(int argc, char** argv) { + helper_bytes_before = bytes; + } + } ++ if (o.stats && ple_table.kar_gpu_cache_enabled()) ++ std::fprintf(stderr, "strata serve: %s\n", ple_table.io_report().c_str()); + save_profile("exit"); // #477: QUIT, or the server closed stdin + #if defined(STRATA_GPU_METAL) + // the stdin reader (detached above) may still take in_mu when the server closes the pipe after QUIT; on macOS diff --git a/paper/README.md b/paper/README.md new file mode 100644 index 00000000..2fb237f8 --- /dev/null +++ b/paper/README.md @@ -0,0 +1,35 @@ +# Рукопис Leleka для arXiv + +**Leleka: Model Compression and Session Multiplexing for Long-Context Coding Agents on One GPU.** + +Англомовний рукопис містить метод, виміри, аналіз якості, пов’язані роботи та додаток із походженням експериментів. У `leleka.tex` вбудовано бібліографію. Для компіляції достатньо стандартних пакетів LaTeX. + +## Що саме додає Leleka + +- **KAR.** Вкладене кодування походить із Koference. Han та співавтори вже квантують ту саму n-грамну таблицю Qwen3.8-Flash-Next до 13,4 ГБ за двобітного коду й відновлюють лише вибрані рядки. Внесок Leleka — шлях від конверсії GGUF з обмеженою пам’яттю до обслуговування з розрідженого `memfd`. Він зберігає вихідні офсети архіву та перевіряє хеш списку діапазонів і їхніх байтів. Виміряні 36,6 ГіБ стосуються повної та розрідженої копій **того самого** KAR. [N-Gram Memories at Two Bits](https://arxiv.org/abs/2610.21810v3), [SlackTier](https://arxiv.org/abs/2611.13413), [реалізація розрідженого завантаження](../kar-sparse-memfd.md). +- **Мультиплексування.** Strata вже паркує сесії в RAM і дозволяє запозичити чекпойнт, SGLang уже вирівнює певні рекурентні чекпойнти за сіткою, а Marconi та HiState оцінюють вартість рекомп’ютації та пам’яті. Внесок Leleka — конкретний спосіб відновлення одного слота Qwen: спільні блоки K/V та індексу, узгоджені стани GDN, історії PLE і MTP, імпорт лише відсутніх блоків та оцінка витіснення за приростом повторної обробки відносно найближчого вцілілого предка на байт, який справді вивільниться. 5-кратна різниця p95 TTFT виміряна проти контрольного режиму з однією активною історією. [Strata](https://github.com/Niko1221/Strata/blob/41cf05a06a25dd29103b7b27a2279a3f60c21876/docs/DETAILS.md), [SGLang](https://github.com/sgl-project/sglang/blob/99e4233f633a9835987308e6f0a7fb262fc34d62/python/sglang/srt/managers/schedule_policy.py), [Marconi](https://arxiv.org/abs/2411.19379), [HiState](https://arxiv.org/abs/2610.41508), [заміри Leleka](../prefix-cache.md). + +## Джерела результатів + +| Твердження | Запис і прив’язка до історії | +| --- | --- | +| Архів KAR level 2 займає 55,296 ГБ проти 83,618 ГБ вихідних GGUF. Розмір і відносну похибку також виміряли для рівнів 2 і 3 на двох вибраних зрізах. | [Перевірка повної конверсії та зрізів](../build-validation.md). Техніка вкладених бітових площин походить із Koference, ревізія `806d2398`. Походження декодера зафіксовано в [GPU KAR](../../gpu/kar/README.md). | +| Таблиця PLE займає 16,0 ГБ проти 28,8 ГБ. У парному replay prefill становить 4 206 проти 3 741 токенів/с. Різниця у швидкості decode невизначена, зміна логітів вимірювана. | `740d84113`, `5cc2257ea`. [Парні заміри KAR і GGUF](../experiments/kar-off-ab-5090.md), [швидкість](../e2e-data/kar-off-ab/speed/speed.md), [числова якість](../e2e-data/kar-off-ab/quality-a-kar-vs-gguf.txt). | +| Розріджений `memfd` вивільняє 36,6 ГіБ проти повної копії того самого KAR. Записані top-16 log-probabilities і draft traces збігаються побітно. | `4c1b10e2b`, `2a23976c5`, `0111c3dc6`. [Перелік діапазонів](../kar-sparse-memfd.md), [релізні результати Q12 та A6](../release/5090-v0.1-checklist.md). | +| У синтетичній трасі чотирьох сесій p95 TTFT зменшується з 27,6 до 5,5 с. Для двох сесій із приблизно 180k токенів TTFT повернення становить 2,72–4,76 с, імпорт стану — 175–194 мс. | `8ad4dd5d7`, `d53db650f`, `25538a830`, `44e57ee30`. Контроль — режим одного активного стану в тестовому рушії. [Префіксний кеш, розділ Results](../prefix-cache.md). | +| Живий Codex із трьома сесіями здійснив 48 перемикань, медіана імпорту 29 мс. Максимум черги 51 с. | `7d580590d`, `b54e334a8`. [Звіт живого запуску](../experiments/orchestrator-subagents-smoke.md). | + +Усі наведені GPU-результати взято з історії репозиторію. Числові висновки в рукописі розрізняють розмір файлів, резидентну пам’ять, швидкість prefill, TTFT і час завершення задачі. Порівняння з іншими реалізаціями кешування подано в огляді літератури. Походження коду Strata описано в [upstream.md](../upstream.md). + +## Збірка й подання + +Команди для TeX Live з кореня репозиторію. + +```powershell +New-Item -ItemType Directory -Force dist/leleka-arxiv | Out-Null +pdflatex -interaction=nonstopmode -halt-on-error -output-directory=dist/leleka-arxiv docs/paper/leleka.tex +pdflatex -interaction=nonstopmode -halt-on-error -output-directory=dist/leleka-arxiv docs/paper/leleka.tex +tar.exe -czf dist/leleka-arxiv/leleka-source.tar.gz -C docs/paper leleka.tex +``` + +Робоча основна категорія `cs.DC`. Ім’я **Pavlo Ratushnyi** взято з історії Git. Перед поданням узгодьте список авторів, афіліації й контакт, а також посилання на матеріали, які можна відкрити читачам. Пакет вихідного коду містить лише `leleka.tex`. [Вимоги arXiv до TeX](https://info.arxiv.org/help/submit_tex.html), [інструкції з подання](https://info.arxiv.org/help/submit/index.html). diff --git a/paper/leleka.tex b/paper/leleka.tex new file mode 100644 index 00000000..6e260251 --- /dev/null +++ b/paper/leleka.tex @@ -0,0 +1,632 @@ +\documentclass[11pt]{article} +\usepackage[T1]{fontenc} +\usepackage{lmodern} +\usepackage[letterpaper,margin=0.95in]{geometry} +\usepackage{microtype} +\usepackage{amsmath} +\usepackage{booktabs} +\usepackage[hidelinks]{hyperref} +\urlstyle{same} +\setlength{\emergencystretch}{2em} + +\title{Leleka: Model Compression and Session Multiplexing\\ +for Long-Context Coding Agents on One GPU} +\author{Pavlo Ratushnyi} +\date{November 2026} + +\begin{document} +\maketitle + +\begin{abstract} +Leleka serves long-context coding agents on one RTX 5090. It +integrates Koference's nested bit-plane encoding with a verified +sparse archive view for a 51.2-billion-weight n-gram embedding table. +The view preserves file offsets and materializes only the pages +covering the serving path's reads. Level-2 KAR reduces the per-layer +embedding (PLE) representation from 28.8 to 16.0~GB relative to GGUF. +Separately, sparse materialization reclaims 36.6~GiB relative to a +full copy of the same KAR archive, with bitwise agreement on recorded +output traces. The KAR--GGUF comparison changes 4.27\% of teacher-forced +argmaxes against 1.50--1.87\% across same-encoding runs. +Leleka multiplexes sessions at request boundaries using +reference-counted attention blocks and checkpoints of recurrent, +embedding-history and speculative draft state on a common prefill +grid. It imports only blocks absent from the live slot and ranks +checkpoints by marginal prefill savings per reclaimable byte. On 96 +synthetic requests from four interleaved sessions, p95 time to first +token falls from 27.6 to 5.5~s against a single-active-history cache. +Returning sessions at about 180k tokens see 2.72--4.76~s versus +53.1--53.7~s, with agreement on tested greedy continuations against a +full read on the same grid. A live Codex run records a 29~ms median +state import on session switches and a 51~s maximum queue wait. +\end{abstract} + +\section{Introduction} + +Coding agents repeatedly send histories of source files, model replies +and tool results. Interleaving requests can overwrite a reusable +history when the engine keeps one active slot. For a hybrid model, +each reused prefix needs its matching recurrent state as well as +attention data. + +Leleka serves Qwen3.8-Flash-Next IQ3\_S in one active slot with a +262,144-token context limit. It inherits Strata's quantized experts, +attention-cache streaming, multi-token prediction (MTP), and sparse +PLE lookup \cite{strata,leleka}. Strata supports conversation parking, +and prior work compresses this same Qwen table \cite{strata,twobitngram}. +Leleka adds two serving mechanisms. + +\begin{enumerate} +\item \textbf{Verified sparse loading of KAR.} Leleka converts GGUF to + Koference's KAR with bounded memory \cite{koference} and stages + packed PLE rows for CUDA reconstruction. Its sealed memory file + preserves offsets and contains only verified ranges used in + serving. We measure re-encoding and sparse loading separately. +\item \textbf{Single-slot restoration of hybrid model state.} Sessions + share attention and index blocks and checkpoint recurrent, PLE + and MTP state on the same grid as cold prefill. Leleka imports + missing blocks into the live slot and scores eviction by marginal + prefill work per byte actually released. We check greedy output + agreement and measure both state import and queue latency. +\end{enumerate} + +\section{Weight encoding and selective materialization} +\label{sec:encoding} + +\paragraph{Koference encoding and the Leleka converter.} +KAR-2 is the container version used in the Koference reference +\cite{koference}. A quantization \emph{level} is the number of bit planes +read for a tensor. Leleka ports the offline encoder and range decoder. +For a group of $g$ source weights, it rounds the maximum absolute weight +to an FP16 scale $s$ and uses a small positive scale for an all-zero group. +It fits a tree of scalar partitions to a sample of the normalized weights. +At each depth it splits each parent cell at a boundary minimizing the +sum of squared errors of the two child cells. The reconstruction value +for a cell is its sample mean rounded to FP16. The encoder stores the +leaf index most-significant plane first. Reading the first $\ell$ planes +selects an ancestor cell and reconstructs $\hat{w}_i^{(\ell)}$ as +\[ + \hat{w}_i^{(\ell)} = + s_{\lfloor i/g \rfloor}\, + c_\ell\!\left[\sum_{j=0}^{\ell-1} 2^{\ell-1-j} b_j(i)\right], +\] +where $c_\ell$ is the table of $2^\ell$ reconstruction values, and $b_j(i)$ +is the bit for weight $i$ in plane $j$. Ignoring padding, codebooks and +metadata, the encoding costs $\ell + 16/g$ bits per weight. The serving +experiment uses $\ell=2$ and $g=32$ throughout the PLE table. The streamed +converter reads bounded GGUF chunks, samples at most 65,536 normalized +values per tensor or partition, and writes per-tensor sections. It splits +the PLE tensor at row boundaries to respect the container's 32-bit plane +stride. The converter hashes the physical GGUF data and the decoded FP32 +stream without writing that expanded stream to disk. It verifies the +archive and its tensor checksums. + +\paragraph{Random access in the PLE table.} +The evaluated level-2 table has 320,001,536 rows of 160 weights, stored +in two partitions. Each row needs 10 bytes of scales and two 20-byte +plane slices, for 50 bytes per row or 2.5 bits per weight. The native +IQ4\_NL GGUF PLE table uses 90 bytes per row. The CUDA-serving path +stages the packed rows selected by the PLE lookup, maintains a bounded +device row cache, and gathers and reconstructs rows on the device. +The routed experts in both serving arms come from the same native +quantized GGUF bank. The full KAR archive is also measured as an offline +artifact, which establishes a storage rate for that encoding. + +\paragraph{Verified sparse archive view.} +The loader derives the union of the metadata and all codebook, scale +and bit-plane ranges reachable by any legal PLE row lookup. It rounds +that union to page boundaries and merges the resulting extents. The +loader copies only those extents into a sealed Linux memory file +(\texttt{memfd}) of the original length. The engine can therefore +use the archive's existing offsets and row decoder. The sparse +verifier derives the same extents, checks that they cover all allowed +reads, and validates a pinned SHA-256 digest that binds their lengths, +offsets and bytes. The residency guard uses the verified extent list. +Direct I/O avoids a second copy in the disk page cache, and the memory +governor locks and repopulates only the copied extents. This last detail +matters because populating holes would allocate zero pages. The sparse +view serves the same encoded PLE bytes as the full in-memory KAR archive. + +\section{Request-boundary session multiplexing} +\label{sec:mux} + +\paragraph{Canonical checkpoints.} +One request owns the execution state from prefill to completion or +cancellation. For a prompt with $n$ tokens, grid-mode prefill ends +chunks on a fixed global token grid, with the final chunk ending at +$n-1$ before the first verification step. Chunk boundaries can affect +floating-point arithmetic. A continuation restored from a grid point +therefore follows the same suffix chunk schedule as a full grid-mode +prefill of that prompt. + +The store holds two kinds of records. A shared block holds quantized +attention K/V cells and pooled attention-index rows for one consecutive +token span. A checkpoint holds the model's Gated DeltaNet (GDN) +recurrent state, PLE history, attention-index tails and MTP draft state, +plus references to its blocks. Blocks are indexed by a hash chain over +the token prefix. The runtime compares the token IDs on lookup so a +collision cannot produce a cache hit. In the measured configuration, +shared block data costs 14,208 bytes per token and each checkpoint +carries about 127~MB of additional state. + +\paragraph{Restoring into one slot.} +The runtime uses the deepest matching checkpoint at or before $n-1$. +It tracks the valid leading span of that prefix in the live slot, +skips its complete blocks, and imports the remaining blocks up to the +checkpoint. The restore refreshes +the device attention index, invalidates stale resident K/V entries, and +installs the recurrent, embedding and draft state before prefilling the +suffix. A continuing session can reuse the live K/V without copying it. +The engine publishes completed chunks and discards an invalid cache on +restore failure so it can read the full prompt again. A separate +request-end mode can save the committed reply state with decode-generated +cells. The grid-mode equality results apply to prefills on the same grid. + +\paragraph{Eviction under a shared byte cap.} +Under a byte cap, the policy ranks each candidate for eviction by a +heuristic +\[ + \frac{p_v\,(\ell_v-\ell_{\mathrm{ancestor}(v)})}{m_{\mathrm{freed}}(v)}. +\] +Here $\ell_v$ is the length of the node's prefix, +$\ell_{\mathrm{ancestor}(v)}$ is that of its nearest surviving ancestor, +$p_v$ incorporates recency, evidence of branch reuse and a prior for +session frontiers, and $m_{\mathrm{freed}}(v)$ counts the checkpoint +and any blocks that would lose their last reference, excluding blocks +needed by the incoming checkpoint. After selecting a victim, the policy +recomputes both the fallback ancestor and the reclaimable bytes for the +remaining candidates. Thus the score reflects work that the next +eviction would add and memory it would free in the shared host store. + +\section{Evaluation} + +The experiments use one RTX 5090 (32~GB) and a Ryzen 9 9950X3D host +with approximately 121~GiB of usable RAM. We compare KAR against native +GGUF PLE inside the same runtime, sparse against full materialization of +identical KAR bytes, and grid checkpointing against a legacy +single-active-history policy. A live gateway smoke test exercises three +Codex sessions. The appendix gives the software and model +identities available from the measurement records \cite{leleka}. GB +denotes $10^9$ bytes and GiB denotes $2^{30}$ bytes. + +\subsection{Size and numerical cost of compression} + +\begin{table}[ht] + \centering + \small + \begin{tabular}{@{}lrrr@{}} + \toprule + Comparison & Reference & KAR or sparse & Reduction \\ + \midrule + Complete source shards vs.\ level-2 archive (GB) & 83.618 & 55.296 & 33.87\% \\ + GGUF vs.\ level-2 PLE representation (GB) & 28.800 & 16.000 & 44.44\% \\ + Full vs.\ sparse KAR memory file (GiB) & 51.50 & 14.90 & 36.60 GiB \\ + \bottomrule + \end{tabular} + \caption{Three byte comparisons at different boundaries. The first + measures offline conversion. The second measures the serving table. + The third measures allocated archive pages at the same encoding.} + \label{tab:size} +\end{table} + +The complete level-2 archive contains 1,225 records at an accounted +2.500025 bits per source weight (Table~\ref{tab:size}). The largest +per-tensor relative $\ell_2$ reconstruction error is 0.6801. A separate +57.64~MB sample containing expert and embedding slices illustrates +the rate--distortion trade-off. Level 2 produces 36.97~MB with a maximum +relative $\ell_2$ error of 0.334. Level 3 produces 51.76~MB with error +0.160. These errors are relative to decoded source GGUF weights. For +serving, the sparse view copies 16,000,348,672 bytes of the level-2 +archive in two extents. + +In the paired sparse/full comparison, six balanced blocks use the same +five-turn, roughly 245k-token workload. At the end of turn five, +system \texttt{Shmem} is 55.2~GiB with the full archive and 18.6~GiB +with the sparse view, and \texttt{MemAvailable} rises from 8.5 to +45.1~GiB. The output check compares 2,057 top-16 log-probability rows +and 1,036 draft-trace entries with bitwise agreement. The measured +decode-rate difference is $+0.58\%$ (standard error 0.91 percentage +points). + +\begin{table}[ht] + \centering + \small + \begin{tabular}{@{}lrr@{}} + \toprule + Replay metric & GGUF PLE & KAR level-2 PLE \\ + \midrule + Prefill (tokens/s) & $3{,}741 \pm 5$ & $4{,}206 \pm 28$ \\ + Decode (tokens/s) & $181.6 \pm 0.8$ & $180.5 \pm 1.2$ \\ + Per-request prefill p10/p50/p90 & 1,394 / 2,366 / 4,717 & 1,440 / 2,560 / 5,449 \\ + Per-request decode p10/p50/p90 & 149.5 / 170.3 / 209.0 & 140.9 / 167.8 / 207.6 \\ + \bottomrule + \end{tabular} + \caption{Paired replay with 59 fixed requests and three interleaved + passes per arm. Aggregate rates are pass means $\pm$ sample standard + deviation. Per-request prefill percentiles use requests with at least + 1,000 uncached tokens and decode percentiles use requests with at + least 100 generated tokens.} + \label{tab:replay} +\end{table} + +Table~\ref{tab:replay} holds the request sequence fixed across arms. +The prefix store starts empty for each pass, both PLE tables are in +host memory, and each pass processes 555,449 uncached prompt tokens. +KAR increases prefill tokens/s by 12.4\% relative to GGUF, or about +16.5 seconds less prefill across the trace. With three paired passes, +the descriptive 95\% $t$ interval for the prefill difference is roughly +$[383,547]$ tokens/s and that for the decode difference is +$[-3.8,1.6]$ tokens/s, calculated from the rounded paired summaries. +The sample comes from a single boot. The arms generate their own replies +without feeding them into subsequent prompts, so total decode times +reflect different output token counts. + +\begin{table}[ht] + \centering + \small + \begin{tabular}{@{}lrrrr@{}} + \toprule + PLE comparison & Top-1 $\lvert\Delta\log p\rvert$ p99 + & Argmax flips & Margin $\geq 0.25$ & Top-5 overlap \\ + \midrule + GGUF vs.\ GGUF & 0.162 & 56 (1.87\%) & 5 & 0.967 \\ + KAR vs.\ KAR & 0.146 & 45 (1.50\%) & 3 & 0.968 \\ + KAR vs.\ GGUF & 0.468 & 128 (4.27\%) & 44 & 0.919 \\ + \bottomrule + \end{tabular} + \caption{Teacher-forced numerical comparison at 3,000 positions per + arm. Top-1 change measures the reference argmax's log-probability + where it is present in both traces. The margin column counts flips + where the reference top two tokens differ by at least 0.25 nats.} + \label{tab:quality} +\end{table} + +The teacher-forced experiment uses two recorded 300-token continuations +at each of five prompt lengths from 45,766 to 242,849 tokens. It uses +repeated same-source runs to estimate the numerical variation of this +configuration. The cross-encoding comparison exceeds the same-source +variation (Table~\ref{tab:quality}). The two other cross-encoding +pairings give 4.20\% and 4.70\% argmax flips. In a separate live +comparison, two coding tasks with three runs per encoding give 12 +completions. All pass the final static acceptance checks, including +re-scoring both arms after a shared acceptance-check correction. +Browser probes identify a restart-button defect in one KAR-generated +solution and inconclusive interaction failures in two others. This +small task sample leaves the impact on agent quality unresolved. + +\subsection{Interleaved session latency} + +\begin{table}[ht] + \centering + \small + \begin{tabular}{@{}lrr@{}} + \toprule + Four-session trace metric & Legacy & Shared prefix store \\ + \midrule + Prompt tokens reused & 580,618 (26.5\%) & 1,927,168 (88.0\%) \\ + Prompt tokens processed anew & 1,608,955 & 262,405 \\ + TTFT mean / p50 (s) & 12.5 / 11.3 & 2.5 / 1.7 \\ + TTFT p95 / max (s) & 27.6 / 27.6 & 5.5 / 5.8 \\ + Sum of per-request TTFT (s) & 1,200 & 244 \\ + \bottomrule + \end{tabular} + \caption{A seeded synthetic coding-agent workload of 24 requests + per session. TTFT is time to first token. The sum aggregates request + latencies across the trace.} + \label{tab:short} +\end{table} + +The four-session test models interleaved coding histories with +heavy-tailed tool outputs. Each session grows from roughly 3k to 40k +tokens and shares about 2.5k initial tokens with the other sessions. +Both modes use the same workload generator and serve one request at a +time. The legacy arm uses the port's single-active-history cache with +conversation parking unavailable in that arm. It loses the private +active history when another session overwrites it. The shared store retains reusable blocks on a +2,048-token grid within a 7.8~GiB cap. On the 96 requests covering +2,189,573 prompt tokens, the store reduces p95 TTFT by a factor of 5.0 +(Table~\ref{tab:short}). The experiment is one recorded run per policy. +Re-running the last request of each session with cache lookup and +insertion bypassed reproduces all four tested greedy token sequences. + +\begin{table}[ht] + \centering + \small + \begin{tabular}{@{}lrrrr@{}} + \toprule + Prompt tokens / turn & Legacy TTFT (s) & Grid TTFT (s) + & Grid reuse & Import (ms) \\ + \midrule + 103,051 / 2 & 28.1--28.2 & 2.33 & 98,304 & 101 \\ + 106,082 / 3 & 28.6 & 2.79 & 98,304 & 101 \\ + 183,051 / 2 & 53.1 & 4.76 & 172,032 & 175--177 \\ + 186,082 / 3 & 53.6--53.7 & 2.72 & 180,224 & 182--194 \\ + \bottomrule + \end{tabular} + \caption{Returning requests for two alternating sessions at each + context scale, on an 8,192-token grid. Ranges cover sessions A and B. + Import time is a component of the request, separate from suffix prefill.} + \label{tab:long} +\end{table} + +In the long-context experiment, two sessions alternate for three turns. +They share about 8k tokens and add about 3k per turn. Each session's +first request is cold in grid mode because the shared prefix is shorter +than one grid block. For returning requests, the legacy policy reuses +7,998 tokens, whereas the new policy restores up to 180,224 tokens. +Table~\ref{tab:long} shows an 11.2--19.7$\times$ TTFT ratio at the +180k scale. End-of-third-turn greedy outputs match the cache-bypassed +full grid prefill for both sessions at both depths. Cancellation during +prefill and decode was exercised at 100k, with agreement on retry. + +\subsection{Live gateway and queueing} + +In a Codex CLI smoke test, an orchestrator and two workers share the +same engine while implementing a web application. Of 122 requests, 44 +overlap another at the gateway and 48 switch the engine's live session. +The median import time on a switch is 29~ms (max 48~ms), and 98.1\% of +prompt tokens are reused. The p90 queue wait is 5.0~s and the maximum +is 51~s. All 122 responses complete and all 161 function calls pass +the recorded name and argument checks. The task takes 791~s, compared +with 766~s for a same-boot single-agent run. Each arm has one trial and +uses a different agent trajectory (127,288 versus 96,647 output tokens). +This is evidence of working session alternation and a measurement of +head-of-line blocking. The effect on time to task completion remains +uncertain. + +\section{Related work} + +\paragraph{Progressive weights and sparse lookup.} +Any-Precision LLM, Matryoshka Quantization, AnyBCQ and MatGPTQ support +multiple precisions from one set of weights +\cite{anyprecision,matquant,anybcq,matgptq}. MatMoE varies the precision +of routed experts \cite{matmoe}. In particular, non-uniform Any-Precision +also refines clusters and uses a codebook at each bit width +\cite{anyprecision,matgptq}. KAR's grouping and scalar split rule come +from Koference. Leleka serves PLE at a fixed precision in the evaluated +profile, with the same Strata-derived expert path in both arms +\cite{strata,fiddler}. + +Engram uses token-derived n-gram lookups that support host placement +and prefetch \cite{engram}. Strata reads selected rows from the native +IQ4\_NL table of the same Qwen model \cite{strata}. The closest +quantization comparison is Han et al.'s Conditional Program (CP), +which uses Gaussian trellis codes and independently decodable rows. +Their Qwen3.8-Flash-Next evaluation reports 13.4~GB at a two-bit code +rate and 10.2~GB at a 1.5-bit code rate, including scale overhead. +Their serving tests use DeepSeek on four or eight H200 GPUs +\cite{twobitngram}. SlackTier evaluates lookup scheduling and tier +placement by prefetch deadlines \cite{slacktier}. Leleka's deployment +contribution is a KAR loader that materializes and verifies the +reachable pages of a larger archive, preserves offsets for the +existing row reader, and serves those rows from host RAM on one GPU. +Comparing CP and KAR on the same runtime, weight source and request +trace remains open. + +\paragraph{Prefix reuse and recurrent checkpoints.} +PagedAttention enables block-granular sharing, vLLM's automatic prefix +cache uses parent hashes and reference counts, and SGLang and +CachedAttention reuse prefixes across requests \cite{pagedattention, +vllmhash,sglang,cachedattention}. SGLang's hybrid cache stores K/V and +recurrent checkpoints with separate replacement lists, and its +scheduler supports aligning chunks to a recurrent checkpoint grid +\cite{sglanghybrid,sglanggrid}. Sparse Prefix Caching studies exact +resume from selected recurrent states and optimizes their placement +from a distribution of prefix overlaps \cite{sparseprefix}. The grid +in Leleka serves a particular role in the port: it ties cache +checkpoints to the floating-point chunk schedule while the saved state +also includes the attention-index tails, embedding history and MTP ring. + +Marconi combines recency and compute saved per footprint +\cite{marconi}. HiState also accounts for reclaimed storage and added +recomputation, using adaptive checkpoint spacing and separate SSD +storage for historical states \cite{histate}. Leleka implements an +online score for its shared host store in which token savings are +measured relative to the nearest surviving ancestor and memory savings +depend on block references after each tentative eviction. Upstream +Strata parks conversation images in host RAM, lets another conversation +borrow a checkpoint, and offers optional batched generation +\cite{strata}. Leleka's design shares individual prefix blocks among +checkpoints and restores the missing portion into one live slot. +The measured latency comparison uses the port's single-active-history +control. Relative performance against Strata's parking or batching and +other hybrid caches remains an empirical question. + +\section{Discussion and conclusion} + +The two contributions address different parts of the serving state. +The verified sparse loader keeps the compressed PLE path intact while +removing the resident archive pages that the model never reads. +The session store retains shared attention blocks and coupled model +checkpoints so returning requests can resume in the same slot. +The two mechanisms share the host memory budget. Measuring their joint +effect would require varying both factors on the same workload. + +The data cover one model and one primary GPU, mostly greedy inference, +two coding tasks for the PLE comparison, and one live orchestration +trial. Exact grid-resume checks compare short greedy continuations +against a full read on the same grid. The configured 256k capacity, +approximately 245k compression replay and 180k interleaved workload +measure different operating points. The strongest demonstrated benefits +are reduced host residency and time to first token for returning +sessions, while the live trial identifies queueing as a separate limit +on interactive performance. + +\appendix +\section{Experiment provenance} + +\begin{table}[!ht] + \centering + \small + \setlength{\tabcolsep}{4pt} + \begin{tabular}{@{}ll@{}} + \toprule + Item & Git SHA or SHA-256 \\ + \midrule + Leleka snapshot & \texttt{5db2a5da3d8230764201efa7a8994601df974e47} \\ + Strata reference & \texttt{41cf05a06a25dd29103b7b27a2279a3f60c21876} \\ + Koference codec & \texttt{806d2398ae1daaceb2917242911e5680cbfb3608} \\ + GGUF model pair & \texttt{80d5e3333801cedbca81a5c19c24ed6bb48fd56977acd190318f66b23a1766a3} \\ + KAR archive & \texttt{536d612ca60eab460cb978f51748fc6fa4e9d611d4601e777884e8b51385afa5} \\ + \bottomrule + \end{tabular} + \caption{Source and artifact identifiers. The experiment descriptions + give the builds used for each comparison.} + \label{tab:revisions} +\end{table} + +\small +\begin{description} +\item[Source history.] The source revisions and weight digests are + listed in Table~\ref{tab:revisions}. The local Strata import and patch + set are documented in \path{docs/upstream.md}. +\item[Weights.] The model-pair SHA-256 is the identity recorded by the + KAR/GGUF PLE comparison. The records and aggregate results are listed in + \path{docs/build-validation.md}, \path{docs/kar-sparse-memfd.md} + and the release checklist (\texttt{Q12}, \texttt{A6}). +\item[Sparse/full comparison.] The three-arm harness + \path{scripts/e2e/decode/single-copy-ab.sh} compares the pre-change + full copy, sparse copy and file-backed source in balanced order. + The full/sparse results here use a fixed five-turn corpus, a + 300-token output cap, an 8,192-token grid, a 6,144~MiB prefix cap, + disabled placement seeding and the same resident GGUF expert bank. +\item[KAR/GGUF A/B.] Same rebuilt release package in both arms, based + on \texttt{17e372944279} with opt-in native PLE changes and + results in \path{docs/experiments/kar-off-ab-5090.md} + (evidence commits \texttt{740d84113}, \texttt{5cc2257ea}). + Ubuntu 26.04, Linux 7.0.0-38, CUDA toolkit 13.2.2, + cuBLAS 12.9.1.4, NVIDIA driver 595.99.02 and Codex CLI 0.163.0. + The server release record lists a 600~W GPU power limit. + The replay uses INT8 K/V, request-end checkpoints and a 6,144~MiB + prefix cap. Serialized pass order is KAR, GGUF, GGUF, KAR, KAR, GGUF. + GGUF PLE is prewarmed in the page cache and KAR PLE uses a sparse + sealed memory file. The paired numerical check uses a static expert + tier. Aggregate tables and analysis are under + \path{docs/e2e-data/kar-off-ab/}. +\item[Session-cache controlled tests.] Generator introduced in + \texttt{d53db650f}, policy introduced in \texttt{8ad4dd5d7}. + Jobs 923 and 927 are the legacy and grid-cache four-session runs. + \path{docs/prefix-cache.md} sections 2 and 3 report the four-session + and alternating long-context results. The harness uses greedy decoding, + 16--24 tokens for the reported equality checks, MTP, static expert + placement with seeding disabled, INT8 K/V and a 20,480-token + GPU-resident K/V window. The driver series is 595.99 and the + model shard 0 digest begins \texttt{4c1eb2ce}. The workloads are + synthetic and run the real model. +\item[Live smoke.] Package commit \texttt{83bdd85bb482} with Codex CLI + 0.163.0. Report and harness are recorded in \texttt{b54e334a8} and + \texttt{7d580590d}, respectively. The warm-up precedes both task + cells. Raw request captures and weights are outside the paper + source package. +\end{description} + +\normalsize + +\begin{thebibliography}{99} +\bibitem{strata} +Strata project. +\href{https://github.com/Niko1221/Strata/blob/41cf05a06a25dd29103b7b27a2279a3f60c21876/docs/DETAILS.md}{\emph{Strata -- the details}}. +Engine documentation at \texttt{41cf05a0}, October 2026. + +\bibitem{leleka} +Leleka project. \emph{Leleka source and measurement records}. Repository +snapshot \texttt{5db2a5da3}, 2026. Evidence paths in Appendix~A. + +\bibitem{koference} +Koference project. \emph{KAR v2 format specification and reference +decoder}. Revision \texttt{806d2398}, local research source. Reference +decoder provenance is recorded in Leleka's \path{gpu/kar/README.md}. + +\bibitem{anyprecision} +Yeonhong Park et al. +\emph{Any-Precision LLM: Low-Cost Deployment of Multiple, +Different-Sized LLMs}. ICML, 2024. +\url{https://arxiv.org/abs/2402.10517}. + +\bibitem{matquant} +Pranav Nair et al. \emph{Matryoshka Quantization}. 2025. +\url{https://arxiv.org/abs/2502.06786}. + +\bibitem{anybcq} +Gunho Park et al. \emph{AnyBCQ: Hardware Efficient Flexible +Binary-Coded Quantization for Multi-Precision LLMs}. 2026. +\url{https://arxiv.org/abs/2510.10467}. + +\bibitem{matgptq} +Maximilian Kleinegger, Elvir Crn\v{c}evi\'c, and Dan Alistarh. +\emph{MatGPTQ: Efficient and Accurate Inference over Nested +Quantized Models}. 2026. \url{https://arxiv.org/abs/2602.03537}. + +\bibitem{matmoe} +Renjie Wei et al. \emph{MatMoE: Matryoshka Mixture-of-Experts with +Dynamic Mixed-Precision Quantization for Efficient Inference}. 2026. +\url{https://arxiv.org/abs/2611.01704}. + +\bibitem{fiddler} +Keisuke Kamahori et al. +\emph{Fiddler: CPU-GPU Orchestration for Fast Inference of +Mixture-of-Experts Models}. ICLR, 2025. +\url{https://arxiv.org/abs/2402.07033}. + +\bibitem{engram} +Xin Cheng et al. \emph{Conditional Memory via Scalable Lookup: +A New Axis of Sparsity for Large Language Models}. 2026. +\url{https://arxiv.org/abs/2601.07372}. + +\bibitem{twobitngram} +Donghoon Han, Minseop Jung, Dong Woo Kwak, SeungJae Lee, and +Junhoo Lee. \emph{N-Gram Memories at Two Bits: Quantizing Lookup Tables +in Large Language Models}. 2026. +\url{https://arxiv.org/abs/2610.21810v3}. + +\bibitem{slacktier} +Wen Huang and Jack Liu. \emph{Placing LLM Lookup Tables by Per-Layer +Prefetch Deadlines}. 2026. \url{https://arxiv.org/abs/2611.13413}. + +\bibitem{pagedattention} +Woosuk Kwon et al. \emph{Efficient Memory Management for Large Language +Model Serving with PagedAttention}. SOSP, 2023. +\url{https://arxiv.org/abs/2309.06180}. + +\bibitem{vllmhash} +vLLM project. \emph{Automatic Prefix Caching}. Design documentation, +v0.15.0. \url{https://docs.vllm.ai/en/v0.15.0/design/prefix_caching/}. + +\bibitem{sglang} +Lianmin Zheng et al. \emph{SGLang: Efficient Execution of Structured +Language Model Programs}. NeurIPS, 2024. +\url{https://arxiv.org/abs/2312.07104}. + +\bibitem{sglanghybrid} +SGLang project. +\href{https://pytorch.org/blog/hybrid-models-meet-sglang-more-than-full-attention/}{% + \emph{Hybrid Models Meet SGLang: More than Full Attention}}. +PyTorch Foundation technical article. + +\bibitem{sglanggrid} +SGLang project. +\href{https://github.com/sgl-project/sglang/blob/99e4233f633a9835987308e6f0a7fb262fc34d62/python/sglang/srt/managers/schedule_policy.py}{% + \emph{Prefill scheduler and recurrent checkpoint alignment}}. +Source code at \texttt{99e4233f}, November 2026. + +\bibitem{cachedattention} +Bin Gao et al. \emph{Cost-Efficient Large Language Model Serving for +Multi-turn Conversations with CachedAttention}. USENIX ATC, 2024. +\url{https://www.usenix.org/conference/atc24/presentation/gao-bin-cost}. + +\bibitem{marconi} +Rui Pan et al. \emph{Marconi: Prefix Caching for the Era of Hybrid +LLMs}. MLSys, 2025. \url{https://arxiv.org/abs/2411.19379}. + +\bibitem{sparseprefix} +Mikhail Shirokikh and Sergey Nikolenko. +\emph{Sparse Prefix Caching for Hybrid and Recurrent LLM Serving}. +2026. \url{https://arxiv.org/abs/2605.05219}. + +\bibitem{histate} +Zaifeng Pan et al. \emph{HiState: Hierarchical Prefix Cache Management +for Hybrid LLM Serving in Agentic Workloads}. 2026. +\url{https://arxiv.org/abs/2610.41508}. +\end{thebibliography} + +\end{document}