Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Add opt-in CK sparse prefill for MiMo on gfx1151 (#122)

zaxbysauce964438ffd813
diff --git a/doc/ck_cold128_results.md b/doc/ck_cold128_results.md
new file mode 100644
index 0000000..1022291
--- /dev/null
+++ b/doc/ck_cold128_results.md
@@ -0,0 +1,69 @@
+# Cold128K results and quality limits
+
+This supplements, rather than replaces, the short `tools/bench.sh` screen already in the PR. The long-context result uses a separate cold-prefill protocol; the two benchmark classes must not be compared as if they were one measurement.
+
+## Completed clean-PR122 cold128K screen
+
+Two paths were compared on the same gfx1151 machine: stock current-main Triton versus the default-off CK sparse implementation in PR122. The benchmark used a strict-clean source export, not a Git checkout of the PR head. A separate bounded retained-file comparison matched all fourteen PR-changed feature files in that export to the experiment's retained source-inventory pins and the corresponding blobs of commit `3f1be68b77c965ff7a019fcb56a29752e3b7ddc0`. That establishes selected feature-file byte identity, not equality of the entire source/build/runtime closure or continuous prelaunch immutability. The frozen input contract selects the same prebuilt official engine extension and local model pack for both paths. Bound pack metadata reports EXL3 2.5-bit weights; the input contract includes the `zz-e2e-step120.safetensors` overlay. Large weights were stat-pinned, not fully content-hashed. This is not an untouched upstream checkpoint.
+
+Recorded settings: FP16 global K/V, capacity 163,840 tokens, base prefill chunk 4,096, batch one, no drafter/vision configured, 131,079 rendered prompt tokens, 64-token greedy continuation budget, and sparse retention 0.30 rather than the feature's default 0.50. MiMo's recurrent sliding-window state is separate from the global-cache precision label. `reasoning_effort='none'` omits the medium-effort template instruction; it does not mean thinking-disabled.
+
+The twelve recorded legs have distinct worker PIDs and private runtime-cache roots. Each completed one unscored full-depth warmup followed by one distinct measured prompt. All three legs within each bracket shared exactly the same measured prompt; prompts differed across brackets. Every measured request reported zero cached tokens. The active CK wrapper reported real per-request page dropping, not only an enabled flag or a loaded library. No separate private first-page digest is presented here, and a no-drafter configuration is not being relabeled as a retained proposal-count measurement.
+
+| Descriptive prefill rate | Stock Triton | PR122 sparse 0.30 |
+|---|---:|---:|
+| Tokens divided by median native prefill duration (8 stock / 4 candidate durations) | 424.0355 tok/s | 710.4487 tok/s |
+
+Primary statistic: four control/candidate/control2 brackets, with `base=(control_s+control2_s)/2`, `gain=100*(base/candidate_s-1)` and repeat spread `abs(100*(control_s/control2_s-1))`. The median paired gain was **67.65766%**, all four brackets were candidate wins, and median identical-control spread was **0.25554%**. This meets the predeclared finite screen gate (>2%, four wins, gain above median spread); it is not statistical equivalence, broad quality acceptance or a default change.
+
+Per-bracket gains: 67.57782%, 68.21760%, 67.65542%, 67.65990%. Native `time_prefill` is authoritative, with API token counts, seconds/milliseconds and reported rates cross-checked. HTTP wall time was retained separately; these rates are neither HTTP TTFT nor pure GPU-kernel time. The complete producer and independent receipt/arithmetic replay cover all twelve legs. All twelve worker results record return code zero. The separately bound parent acceptance records parent return code zero and one terminal marker; a separate post-run release snapshot records the parent absent, port closed, no compute owners and GPU idle. These are retained observations, not a new or continuous host-exclusion check.
+
+In all four brackets, the two unchanged stock controls produced equal full stored decoded text. Every sparse candidate's text differed from its control. This is not a lossless result, and the continuations were not graded for answer quality.
+
+## Completed common-history logit diagnostic
+
+Separate from timing, eight fresh-process model captures completed: plain, plain-repeat, CK keep-all and CK sparse for each of FP16 and packed-int8 global caches. The eight capture results record one 131,079-token prompt, capacity 163,840, chunk 4,096 and 64 continuation positions per precision. The bound, independently reviewed capture source snapshots logits before invoking the sampler, then substitutes the reference token for each non-plain arm. The stored results record the pre-sampler capture path and common-history forcing; the source checks final emitted IDs against the precision-specific plain reference. This is source-and-receipt support, not a fresh raw-tensor replay in this supplement. This is a small correlated continuation diagnostic, not corpus perplexity or 64 independent quality examples.
+
+| Global cache | Arm versus its plain reference | Top-1 matches / 64 | Mean KL(reference ∥ candidate) | Mean reference-token NLL delta, nat |
+|---|---|---:|---:|---:|
+| FP16 | Plain repeat | 64 | 0 | 0 |
+| FP16 | CK keep-all | 58 | 0.00876574 | +0.0172508 |
+| FP16 | CK sparse 0.30 | 59 | 0.0322864 | -0.00797314 |
+| Packed int8 | Plain repeat | 64 | 0 | 0 |
+| Packed int8 | CK keep-all | 61 | 0.00939799 | -0.000722613 |
+| Packed int8 | CK sparse 0.30 | 62 | 0.0222333 | -0.0211626 |
+
+Both plain repeats were bit-exact over the stored valid-vocabulary logits. CK diverged even without dropping pages, so sparsity alone cannot explain the difference. That neither establishes a CK defect nor rules out additional sparse error. KL values against a common reference are not additive: subtracting keep-all KL from sparse KL would not isolate sparse-only damage. A negative mean NLL delta means the mean reference-token NLL decreased over these selected forced-history positions; individual positions can still worsen. It does not establish improved answers or general quality approval. No negligible-loss threshold has been calibrated or passed here.
+
+Packed-int8 rows are not identical-effective-input stock/CK comparisons: the selected CK adapter attends dequantized packed past K/V plus original FP16 current-chunk K/V, while stock's selected staged prefill attends dequantized packed past and current K/V. This source-supported difference remains at keep-all; its contribution to the retained logits has not been measured.
+
+## Historical correspondence and scope
+
+PR122 is not the complete native implementation behind the separate historical 708.4826 tok/s result. That historical dense/sparse comparison used the same FullK binary for both arms; stock-off in this PR selects normal dispatch, not historical dense FullK. Source mapping identified historical full-width K load/LDS staging and its six-panel contraction schedule, plus QK V2 selection, as missing from PR122's native specialization (which selects V2R1 under its actual predicates). The retained historical local comparison was 517.4780 to 708.4826 tok/s, median paired gain 36.65878%; it must not be relabeled as the new 424.0355 to 710.4487 comparison. Source/binary correspondence has retained-pin and end-of-run limits.
+
+The separate FullK successor is outside this PR head and this supplement's measurement claim. No FullK build, consumer-error, selected-function-byte identity, marginal model gain or publication approval is asserted here; its evidence and evaluation are separate.
+
+## Completed public-helper reproduction screen
+
+A separately derived path-parameterized [cold128 helper](../tools/strix_halo/ck_cold128/README.md) generated new public synthetic prompts without retaining private user input/completion bytes in the public files. It is not the literal runner used for the earlier private-prompt or historical measurements and does not reconstruct their prompt bytes. Its quoted-tilde/private-HOME preparation repair was independently source-reviewed. The actual repaired helper re-executed under the selected venv, generated five prompts of exactly 131,079 rendered tokens using the real tokenizer/template, and then completed its full twelve-leg model campaign. The shipped helper and test sources are byte-identical copies of that executed recipe, not separate model runs at their new repository paths.
+
+This is a separate same-machine public-synthetic screen, not an extra four replications of the earlier prompt set. It selects the same strict-clean feature export, matching prebuilt official extension, separately built clean CK specialization and effective local EXL3 model pack. Settings remain FP16 global K/V, capacity 163,840, base chunk 4,096, batch one, no drafter, 131,079 rendered prompt tokens and 64 greedy continuation tokens, with sparse retention 0.30. The 2.5-bit pack and bundled overlay qualification above still applies. No FullK successor, NPU acceleration or speculative decoding is part of this contrast.
+
+| Descriptive native prefill rate | Stock Triton | PR122 sparse 0.30 |
+|---|---:|---:|
+| Tokens divided by median duration (8 stock / 4 candidate durations) | 426.1108 tok/s | 709.2824 tok/s |
+
+| Bracket | Paired gain | Identical-stock repeat spread |
+|---|---:|---:|
+|0|66.83374%|0.06658%|
+|1|65.99329%|0.97356%|
+|2|67.21973%|0.49490%|
+|3|66.31158%|0.35621%|
+
+Median paired gain is **66.57266%**, all four brackets are wins, and median identical-control spread is **0.42556%**. The same finite screen gate (>2%, four wins, gain above median spread) passed. Each fresh server completed a full-depth unscored warmup and one distinct measured prompt; all three legs within a bracket used the same measured prompt. Native/API timing units, token/cache accounting, actual candidate dispatch/page dropping, selected library mappings, worker exit and recorded cleanup were replayed from the retained receipts. Native prefill seconds remain authoritative rather than HTTP wall time, TTFT or pure GPU kernel time. Request settings are source/worker-argv supported; raw HTTP request bodies were not retained.
+
+The final independent reader returned complete 12/12 legs and 4/4 brackets, matching the producer's complete fields, populations and rates. Its explicit post-exit input pass verified 451 selected source/metadata/native/CK files, 15 weight-file stat identities and recorded mapped device/inode correspondence; it did not content-hash the large weights. The original supervisor exited normally with status 0 and exactly one parent completion marker. A separate parent completion-boundary snapshot found the original process and cgroup absent, the port closed, no GPU/NPU compute owners and GPU idle. These checks are retained observations, not continuous exclusion or an adversarial sandbox. Hardware and unchanged policy match the preceding same-machine screen; no package-wattage measurement is claimed.
+
+Repeated stock selected API text matched in all four brackets. Candidate selected text differed in three and matched in one. Here selected text means user-facing content first, falling back to reasoning only when content is empty; it is not a claim about full stored decoded completions, raw IDs or distributions. The continuations were not graded for answer quality. No broad-quality, negligible-loss, lossless, default-enablement or adoption claim follows from this timing screen.
+
+The source-safe recipe defaults to an inert plan and requires explicit prompt preparation or model execution. It contains no retained private prompt or completion bytes; supplying the exact same local weights/overlay is the caller's responsibility. Other packs, prompts, clocks or libraries need their own measurement. The helper's seven stdlib source/planning/runtime-seam tests also passed normally and with explicit `-O`, using inert model/HTTP/tokenizer substitutions where stated; those tests do not provide model-quality evidence.
diff --git a/doc/env_vars.md b/doc/env_vars.md
index f807b12..316be72 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -144,6 +144,84 @@ affects quantized caches.
`EXL3_QC_ATTN=0`); only affects decode if `EXL3_BC_ATTN` is also disabled, since the graphed
decode path reads the packed cache directly.
+### `EXL3_CK_PAGEDKV` (default: unset) -- EXPERIMENTAL
+
+Experimental, default-off, approximate Composable Kernel sparse prefill for the MiMo
+global-attention shape on gfx1151 ROCm. Skipping past pages changes attention output and
+therefore later layers' K/V. This is research functionality, not a general quality-adoption
+recommendation. Set to `sparse` before importing the engine to register handlers for fp16 and
+8-bit KV caches when the optional library is available. The handlers own only batch-one,
+causal Q/K=192, 64-query-head/4-KV-head, V=128 prefill chunks; unsupported shapes, decode,
+SWA and unaligned past lengths fall back to the normal backend.
+
+Build the required MIT-licensed CK specialization with local `git`, `cmake`, `nm`,
+`/usr/bin/python3`, and an already-expanded ROCm SDK (including `lib/llvm/bin/clang{,++}`):
+
+```bash
+export EXL3_CK_SOURCE=/path/to/local/composable_kernel
+export EXL3_ROCM_SDK=/path/to/already-expanded/rocm-sdk
+export EXL3_CK_CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/kyojin/ck-pagedkv"
+tools/strix_halo/build_ck_pagedkv.sh
+```
+
+`EXL3_CK_SOURCE` is a read-only local Git donor containing commit
+`6f44fdf90f69adee742ec3660b95d32963b9bd2d`. The builder ignores its current HEAD and dirty
+worktree, stages that exact commit in the cache, and patches only the staged copy. It never
+fetches implicitly or sources `env.sh`. `EXL3_CK_CACHE` must be disjoint from the donor (neither
+may contain the other): choose a nonexistent directory on first use, or reuse a cache with a
+matching builder/patch/shim/SDK/commit ownership record. Existing unowned or incompatible
+caches are refused.
+
+The output is `$EXL3_CK_CACHE/libck_pagedkv.so` with a digest-bound `receipt.json`. The default
+cache is `${XDG_CACHE_HOME:-$HOME/.cache}/kyojin/ck-pagedkv`; when choosing a different cache,
+set `EXL3_CK_PAGEDKV_SO="$EXL3_CK_CACHE/libck_pagedkv.so"` before importing the engine. Build
+success proves source compilation/linking and export checks only, not native loading or
+numerical correctness. The first implementation stages all used K and V pages from an 8-bit
+cache; selected-V-only staging is not implemented yet.
+
+A missing/unloadable optional library or missing entry point warns once and leaves the normal
+handlers in place for the process. An explicit kernel rejection (`-1`) declines for that chunk;
+other invalid results and execution errors are not treated as unsupported shapes. Restart after
+building or replacing an unavailable library.
+
+The 8-bit staging pair grows in 32-page steps, capped by the packed cache's physical capacity,
+and is reused within each step. A width/bound change retires incompatible scratch; replacements
+retire the old pair first under the engine's single-stream, fully-overwritten-scratch contract.
+
+Sparse mode, retention and minimum length are frozen together at import time. Use a new process
+to change them. Sparse page hashes, disk-prefix namespaces and saved sessions are isolated from
+ordinary mode and from other sparse policies, including fallback requests in a sparse process.
+Ordinary session formats 1/2 remain readable in ordinary mode. Sparse sessions use incompatible
+formats 3/4 so older ordinary readers reject them too; current readers check the exact policy
+before restoring any pages, stash or rootless tail. The MiMo server's `+ck-sparse` model tag is
+retained as an additional separation layer.
+
+Focused CPU tests need no Torch, Triton, native extension or CUDA/HIP toolchain. Run each directly
+from the repository root to avoid package initialization:
+
+```bash
+python3 -I -S -B tests/test_ck_pagedkv_cpu.py -v
+python3 -I -S -B tests/test_ck_pagedkv_fallback_cpu.py -v
+python3 -I -S -B tests/test_ck_pagedkv_admission_cpu.py -v
+python3 -I -S -B tests/test_ck_pagedkv_sparse_memory_cpu.py -v
+python3 -I -S -B tests/test_ck_sparse_cache_cpu.py -v
+python3 -I -S -B tests/test_ck_dispatch_mode_cpu.py -v
+```
+
+### `EXL3_CK_SPARSE_RETAIN` (default: `0.5`)
+
+Nominal fraction of total pages (past plus current chunk) retained by the optional CK selector.
+Current-chunk and sink pages are always kept, even if they exceed that budget; the most-recent
+past pages are not forced. Read once before engine import and included in the sparse cache
+identity. This is a quality/performance knob; evaluate it with the same model and context before
+changing the default.
+
+### `EXL3_CK_MIN_SK` (default: `0`)
+
+Experimental minimum total KV length for sparse selection in the fp16 and packed8 handlers.
+Calls below it use the ordinary backend. Frozen at import time and included in the sparse cache
+identity. It does not enable CK for otherwise unsupported shapes.
+
### `EXL3_QC_PF_TWO_PASS_MIN_Q` (default: `256`)
Query-length threshold for the prefill staging pass at `EXL3_QC_STAGING=1`. Chunks shorter than
diff --git a/exllamav3/generator/pagetable.py b/exllamav3/generator/pagetable.py
index e0814c7..81ed124 100644
--- a/exllamav3/generator/pagetable.py
+++ b/exllamav3/generator/pagetable.py
@@ -18,12 +18,17 @@ import time
from ..cache import RecurrentCache
from ..tokenizer.mm_embedding import FIRST_MM_EMBEDDING_INDEX
from ..util import profile_opt
+from ..util.attention_mode import ATTENTION_CACHE_MODE
def _tensor_blake2b_checksum(tensor: torch.Tensor, prev_hash: bytes | None) -> bytes:
hasher = hashlib.blake2b(digest_size = 16)
if prev_hash is not None:
hasher.update(prev_hash)
+ elif ATTENTION_CACHE_MODE is not None:
+ # Salt only the root; every descendant inherits the frozen sparse policy.
+ # Normal mode keeps the exact legacy hash input and existing cache hits.
+ hasher.update(ATTENTION_CACHE_MODE.encode())
hasher.update(tensor.numpy().tobytes())
return hasher.digest()
diff --git a/exllamav3/generator/prefix_disk.py b/exllamav3/generator/prefix_disk.py
index 74895c7..4ff9d61 100644
--- a/exllamav3/generator/prefix_disk.py
+++ b/exllamav3/generator/prefix_disk.py
@@ -28,6 +28,7 @@ import time
import torch
from ..util.disk_store import DiskStore, env_dir, namespace
+from ..util.attention_mode import ATTENTION_CACHE_MODE
from .pagetable import PAGE_SIZE, _randomhash, tensor_hash_checksum
from .slot_store import SlotStore
@@ -74,7 +75,11 @@ class PagedPrefixDisk:
self.model_id = model_id
tensors = slots._tensors()
layout = [(tuple(t.shape[1:]), str(t.dtype)) for t in tensors]
- self.ns = namespace(FORMAT, model_id, layout, extra)
+ parts = (FORMAT, model_id, layout, extra)
+ # Normal mode retains the legacy namespace, including its argument count.
+ if ATTENTION_CACHE_MODE is not None:
+ parts += (ATTENTION_CACHE_MODE,)
+ self.ns = namespace(*parts)
self.disk = DiskStore(root or env_dir(), self.ns)
self.pages: dict[bytes, tuple[str, int]] = {} # page hash -> (segment, position in segment)
self.stashes: dict[bytes, tuple[str, int]] = {} # anchor hash -> (entry, depth in pages)
diff --git a/exllamav3/generator/slot_store.py b/exllamav3/generator/slot_store.py
index 6525064..938c1ce 100644
--- a/exllamav3/generator/slot_store.py
+++ b/exllamav3/generator/slot_store.py
@@ -28,9 +28,12 @@ import time
import torch
from .pagetable import PAGE_SIZE, _randomhash
+from ..util.attention_mode import ATTENTION_CACHE_MODE
FORMAT_VERSION = 1
FORMAT_VERSION_TAIL = 2 # adds the prompt-end checkpoint; older readers reject it instead of misplacing the stash
+FORMAT_VERSION_SPARSE = 3 # sparse sessions also bump the format so a legacy normal reader rejects the file
+FORMAT_VERSION_SPARSE_TAIL = 4
class SlotStore:
@@ -149,8 +152,11 @@ class SlotStore:
n_tokens = len(pages) * PAGE_SIZE
n_ids = n_tokens if tail is None else n_tokens + tail[1]["ids"].shape[-1]
data = {
- "version": FORMAT_VERSION if tail is None else FORMAT_VERSION_TAIL,
+ "version": ((FORMAT_VERSION if tail is None else FORMAT_VERSION_TAIL)
+ if ATTENTION_CACHE_MODE is None
+ else (FORMAT_VERSION_SPARSE if tail is None else FORMAT_VERSION_SPARSE_TAIL)),
"model_id": self.model_id,
+ "attention_mode": ATTENTION_CACHE_MODE,
"prompt": self.prompt,
"ids": self.ids[:n_ids].clone(),
"hashes": hashes,
@@ -183,9 +189,18 @@ class SlotStore:
def restore(self, filename: str) -> dict:
t0 = time.perf_counter()
data = torch.load(self._path(filename), map_location="cpu", weights_only=False)
- if data.get("version") not in (FORMAT_VERSION, FORMAT_VERSION_TAIL) or data.get("model_id") != self.model_id:
+ # Sparse mode reads only its own format (3/4); legacy v1/v2 files stay
+ # normal-only, and a legacy normal reader rejects the sparse versions
+ # before touching the payload.
+ accepted_versions = ((FORMAT_VERSION, FORMAT_VERSION_TAIL) if ATTENTION_CACHE_MODE is None
+ else (FORMAT_VERSION_SPARSE, FORMAT_VERSION_SPARSE_TAIL))
+ if data.get("version") not in accepted_versions or data.get("model_id") != self.model_id:
raise ValueError(f"slot file is for {data.get('model_id')!r} v{data.get('version')}, "
- f"not {self.model_id!r} v{FORMAT_VERSION_TAIL}")
+ f"not {self.model_id!r} with versions {accepted_versions}")
+ # Missing marker is a legacy normal cache. Check before tensor access or
+ # any page/stash/tail injection, including tails with no full-page hash.
+ if data.get("attention_mode") != ATTENTION_CACHE_MODE:
+ raise ValueError("slot file attention mode does not match the loaded attention mode")
tensors = self._tensors()
if len(data["tensors"]) not in (0, len(tensors)) or any(
s.shape[1:] != t.shape[1:] or s.dtype != t.dtype for s, t in zip(data["tensors"], tensors)):
diff --git a/exllamav3/modules/attention_fn/ck_pagedkv.py b/exllamav3/modules/attention_fn/ck_pagedkv.py
new file mode 100644
index 0000000..1f9127b
--- /dev/null
+++ b/exllamav3/modules/attention_fn/ck_pagedkv.py
@@ -0,0 +1,158 @@
+"""Optional Composable Kernel paged-prefill backend for MiMo qk192.
+
+This backend is deliberately narrow: ROCm gfx1151, batch one, causal MiMo global
+attention (64 query heads, 4 KV heads, Q/K=192, V=128 padded to 192), and
+page-aligned KV cache pages. It returns ``None`` for every other shape so the
+normal Triton dispatcher remains the fallback.
+
+The shared object is built from the pinned AMD Composable Kernel source by
+``tools/strix_halo/build_ck_pagedkv.sh``. No binary is checked into this
+repository. Set ``EXL3_CK_PAGEDKV_SO`` to test a different locally-built copy.
+"""
+
+import ctypes
+import math
+import os
+from pathlib import Path
+import warnings
+
+import torch
+
+from ...ext import exllamav3_ext as ext
+from .common import AttnArgs
+
+_PAGE = 256
+_fn: ctypes._CFuncPtr | None = None
+_load_failed = False
+_stats = {"accepted": 0, "rejected": 0}
+
+
+def ck_library_path() -> Path:
+ """Resolve an explicit test override or the reproducible builder output."""
+ configured = os.environ.get("EXL3_CK_PAGEDKV_SO")
+ if configured:
+ return Path(configured).expanduser()
+ cache_home = Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache"))
+ return cache_home / "kyojin" / "ck-pagedkv" / "libck_pagedkv.so"
+
+
+def _supported_device(device: torch.device) -> bool:
+ if not torch.version.hip or not torch.cuda.is_available() or device.type != "cuda":
+ return False
+ try:
+ arch = str(torch.cuda.get_device_properties(device).gcnArchName)
+ except Exception:
+ return False
+ return arch.split(":", 1)[0] == "gfx1151"
+
+
+def _kernel() -> ctypes._CFuncPtr | None:
+ """Resolve once per process; an unavailable optional library uses the fallback."""
+ global _fn, _load_failed
+ if _load_failed:
+ return None
+ if _fn is None:
+ path = ck_library_path()
+ reason = None
+ fn = None
+ if not path.is_file():
+ reason = "file not found"
+ else:
+ try:
+ library = ctypes.CDLL(str(path))
+ except OSError as exc:
+ reason = str(exc)
+ else:
+ try:
+ fn = library.ck_pagedkv_forward
+ except AttributeError as exc:
+ reason = str(exc)
+ if fn is None:
+ _load_failed = True
+ warnings.warn(
+ f"CK paged-prefill library unavailable at {path}: {reason}; "
+ "using the ordinary fallback. Build it with tools/strix_halo/build_ck_pagedkv.sh "
+ "or set EXL3_CK_PAGEDKV_SO before starting the process.",
+ RuntimeWarning, stacklevel=2,
+ )
+ return None
+ fn.restype = ctypes.c_float
+ fn.argtypes = (
+ [ctypes.c_void_p] * 4
+ + [ctypes.c_void_p] * 2
+ + [ctypes.c_int] * 3
+ + [ctypes.c_float]
+ + [ctypes.c_int] * 2
+ + [ctypes.c_void_p]
+ + [ctypes.c_int]
+ )
+ _fn = fn
+ return _fn
+
+
+def owns(args: AttnArgs) -> bool:
+ return (
+ _supported_device(args.q.device)
+ and not args.is_varlen()
+ and not args.is_swa()
+ and args.has_kv_cache()
+ and args.cu_seqlens is None
+ and args.softcap == 0.0
+ and args.sinks is None
+ and getattr(args, "ov", None) is None
+ and getattr(args, "tq", None) is None
+ and args.causal
+ and not getattr(args, "non_causal_spans", None)
+ and args.dim == 192
+ and args.num_q_heads == 64
+ and args.num_kv_heads == 4
+ and args.bsz == 1
+ and args.v_dim == 128
+ and args.kv_len == args.q_len
+ and args.q_len >= 16
+ )
+
+
+def fn_ck_paged_attn(args: AttnArgs) -> torch.Tensor | None:
+ """Run the loaded CK backend, or decline to the next dispatcher handler."""
+ if not owns(args):
+ _stats["rejected"] += 1
+ return None
+
+ kernel = _kernel()
+ if kernel is None:
+ _stats["rejected"] += 1
+ return None
+
+ q, k, v = args.q, args.k, args.v
+ k_cache, v_cache = args.k_cache, args.v_cache
+ block_table, cache_seqlens = args.block_table, args.cache_seqlens
+ q_len = q.shape[1]
+ total_kv = int(cache_seqlens[0].item()) + q_len
+ pages_needed = (total_kv + _PAGE - 1) // _PAGE
+
+ # Preserve the engine's logical page order; physical cache pages need not be contiguous.
+ ext.paged_kv_cache_update(k, v, k_cache, v_cache, block_table, cache_seqlens)
+ page_indices = block_table[0, :pages_needed].long()
+ k_canonical = k_cache[page_indices].permute(0, 2, 1, 3).contiguous()
+ v_canonical = v_cache[page_indices].permute(0, 2, 1, 3).contiguous()
+ identity_table = torch.arange(pages_needed, dtype=torch.int32, device=q.device)
+
+ value_stride = int(k_cache.shape[3])
+ out = torch.zeros(1, q_len, 64, value_stride, device=q.device, dtype=torch.float16)
+ lengths = torch.tensor([total_kv], dtype=torch.int32, device=q.device)
+ result = kernel(
+ q.data_ptr(), k_canonical.data_ptr(), v_canonical.data_ptr(), out.data_ptr(),
+ identity_table.data_ptr(), lengths.data_ptr(), q_len, total_kv, pages_needed,
+ float(args.sm_scale), 0, value_stride, torch.cuda.current_stream().cuda_stream, 0,
+ )
+ if result == -1.0:
+ # Explicit CK decline only. Invocation/device exceptions are not recoverable
+ # here. The preceding cache update does not advance cache_seqlens, so the
+ # fallback writes the same K/V to the same positions, not an extra append.
+ _stats["rejected"] += 1
+ return None
+ if not math.isfinite(result) or result <= 0:
+ raise RuntimeError(f"CK paged-prefill returned an invalid result (rc={result})")
+ _stats["accepted"] += 1
+ return out
diff --git a/exllamav3/modules/attention_fn/ck_pagedkv_sparse.py b/exllamav3/modules/attention_fn/ck_pagedkv_sparse.py
new file mode 100644
index 0000000..48c63f3
--- /dev/null
+++ b/exllamav3/modules/attention_fn/ck_pagedkv_sparse.py
@@ -0,0 +1,486 @@
+"""Page selection and compaction for optional CK sparse prefill.
+
+Selected past pages are gathered in chronological order before current pages. The
+CK kernel uses bottom-right causal alignment, so every selected past token remains
+visible to every current query while the current chunk retains its ordinary causal
+prefix. Page-aligned past context is required; a partial past page declines to the
+normal attention backend.
+"""
+
+import ctypes
+import math
+import os
+
+import torch
+
+from ...ext import exllamav3_ext as ext
+from ...util.attention_mode import CK_SPARSE_RETAIN, CK_SPARSE_MIN_SK
+from .ck_pagedkv import _kernel, _PAGE as _page, _supported_device
+
+_stats = {"dense": 0, "sparse": 0, "declined": 0}
+
+
+def compact_table(bt, past, q_len, keep_past_pages):
+ """Build the compacted physical page list and its compacted key length.
+
+ bt : [1, n_pages] int32 logical->physical
+ past : cached token length BEFORE this chunk
+ q_len : new tokens in this chunk
+ keep_past_pages : bool tensor over the past's logical pages (chronological order)
+
+ Returns (phys_pages int64 [n_compact], s_k_compact int).
+ """
+ page = _page
+ if past % page != 0:
+ raise ValueError(f"compaction requires page-aligned past, got past={past} page={page}")
+ n_past_pages = past // page
+ if keep_past_pages.numel() != n_past_pages:
+ raise ValueError(f"keep mask has {keep_past_pages.numel()} entries, expected {n_past_pages}")
+ n_cur_pages = math.ceil(q_len / page)
+ total_pages = bt.shape[1]
+ if n_past_pages + n_cur_pages > total_pages:
+ raise ValueError(f"block table too short: {n_past_pages}+{n_cur_pages} > {total_pages}")
+
+ past_phys = bt[0, :n_past_pages].long()
+ cur_phys = bt[0, n_past_pages:n_past_pages + n_cur_pages].long()
+
+ sel = past_phys[keep_past_pages] # chronological order preserved
+ pages = torch.cat([sel, cur_phys]) # current chunk LAST
+ s_k_compact = int(sel.numel()) * page + q_len
+ return pages, s_k_compact
+
+
+def fn_ck_paged_attn_sparse(args, keep_past_pages):
+ """Sparse variant of fn_ck_paged_attn: same kernel, compacted block table.
+
+ Returns the output tensor, or None if the arguments are not owned (the caller then falls
+ back to the dense path).
+ """
+ owned = (
+ _supported_device(args.q.device)
+ and not args.is_varlen()
+ and not args.is_swa()
+ and args.has_kv_cache()
+ and args.cu_seqlens is None
+ and args.softcap == 0.0
+ and args.sinks is None
+ and getattr(args, "ov", None) is None
+ and getattr(args, "tq", None) is None
+ and args.causal
+ and not getattr(args, "non_causal_spans", None)
+ and args.dim == 192
+ and args.num_q_heads == 64
+ and args.num_kv_heads == 4
+ and args.bsz == 1
+ and args.v_dim == 128
+ and args.kv_len == args.q_len
+ and args.q_len >= 16
+ )
+ if not owned:
+ _stats["declined"] += 1
+ return None
+
+ kernel = _kernel()
+ if kernel is None:
+ _stats["declined"] += 1
+ return None
+
+ q = args.q
+ k = args.k
+ v = args.v
+ k_cache = args.k_cache
+ v_cache = args.v_cache
+ bt = args.block_table
+ cs = args.cache_seqlens
+
+ q_len = q.shape[1]
+ past = int(cs[0].item())
+ s_k = past + q_len
+
+ # 1) write the new K/V rows at their TRUE logical positions (original table)
+ ext.paged_kv_cache_update(k, v, k_cache, v_cache, bt, cs)
+
+ # 2) compact the table
+ pages, s_k_compact = compact_table(bt, past, q_len, keep_past_pages)
+
+ # 3) gather ONLY the compacted pages and repack to canonical (page, head, token, dim)
+ kcan = k_cache[pages].permute(0, 2, 1, 3).contiguous()
+ vcan = v_cache[pages].permute(0, 2, 1, 3).contiguous()
+ n_pages = int(pages.numel())
+ bt_id = torch.arange(n_pages, dtype=torch.int32, device=q.device)
+
+ # 4) run the kernel with the compacted length
+ head_pad = int(k_cache.shape[3])
+ o = torch.zeros(1, q_len, 64, head_pad, device=q.device, dtype=torch.float16)
+ skl = torch.tensor([s_k_compact], dtype=torch.int32, device=q.device)
+ t = kernel(
+ q.data_ptr(), kcan.data_ptr(), vcan.data_ptr(), o.data_ptr(),
+ bt_id.data_ptr(), skl.data_ptr(),
+ q_len, s_k_compact, n_pages, float(args.sm_scale), 0, head_pad,
+ torch.cuda.current_stream().cuda_stream, 0,
+ )
+ if t == -1.0:
+ _stats["declined"] += 1
+ return None
+ if not math.isfinite(t) or t <= 0:
+ raise RuntimeError(f"CK paged-prefill returned an invalid result (rc={t})")
+ _stats["sparse"] += 1
+ return o
+
+
+# --------------------------------------------------------------------------------------
+# numerics: dense CK vs compacted CK vs a hand-masked fp32 reference over the SAME set
+# --------------------------------------------------------------------------------------
+
+def _ref_over_selected(kfull, vfull, q, dv, s_k, s, keep_token_mask):
+ """fp32 reference: dense attention over all logical tokens, masked to the selected set.
+
+ The causal mask is bottom-right (nm > s_k - s + qi), matching the shipped selftest.
+ """
+ nkv = kfull.shape[1]
+ # q is [1, s, nq, dq] -- so nq is shape[2] and dq is shape[3]. Taking them from
+ # shape[1]/shape[2] silently built a [s, nkv, s//nkv, nq] view and threw.
+ nq = q.shape[2]
+ dq = q.shape[3]
+ qf = q[0].float().view(s, nkv, nq // nkv, dq)
+ sc = torch.einsum("shgd,nhd->shgn", qf, kfull) * (dq ** -0.5)
+ qi = torch.arange(s, device=q.device).view(s, 1, 1, 1)
+ nm = torch.arange(s_k, device=q.device).view(1, 1, 1, -1)
+ causal = nm <= (s_k - s + qi)
+ sel = keep_token_mask.view(1, 1, 1, -1)
+ sc = sc.masked_fill(~(causal & sel), float("-inf"))
+ p = sc.softmax(dim=-1)
+ ref = torch.einsum("shgn,nhd->shgd", p, vfull).reshape(s, nq, dv)
+ return ref
+
+
+def numerics_test(s=512, s_k=1536, keep_pages=(0, 3), seed=0, bt_list=None, verbose=True):
+ """Compare dense CK, compacted CK, and the masked reference over the selected set."""
+ from .common import AttnArgs
+
+ torch.manual_seed(seed)
+ nq, nkv, dq, dv, page = 64, 4, 192, 128, _page
+ if s_k % page or s % page:
+ raise ValueError("test geometry must be page-aligned")
+ pages_total = s_k // page
+ if bt_list is None:
+ bt_list = list(range(pages_total))
+ dev = "cuda"
+ old = s_k - s
+
+ q = ((torch.rand(1, s, nq, dq, device=dev, dtype=torch.float16) * 2) - 1) * 0.5
+ knew = ((torch.rand(1, s, nkv, dq, device=dev, dtype=torch.float16) * 2) - 1) * 0.5
+ vnew = torch.zeros(1, s, nkv, dq, device=dev, dtype=torch.float16)
+ vnew[..., :dv].uniform_(-0.5, 0.5)
+ k_cache = torch.zeros(pages_total, page, nkv, dq, device=dev, dtype=torch.float16)
+ v_cache = torch.zeros(pages_total, page, nkv, dq, device=dev, dtype=torch.float16)
+ # fill every logical page (past pages and the current chunk's page) with random data
+ for lp, pp in enumerate(bt_list):
+ lo, hi = lp * page, min(s_k, (lp + 1) * page)
+ if hi <= lo:
+ break
+ k_cache[pp, :hi - lo] = knew.new_empty(hi - lo, nkv, dq).uniform_(-0.5, 0.5)
+ v_cache[pp, :hi - lo, :, :dv] = vnew.new_empty(hi - lo, nkv, dv).uniform_(-0.5, 0.5)
+ bt = torch.tensor(bt_list, dtype=torch.int32, device=dev).unsqueeze(0)
+ cs = torch.tensor([old], dtype=torch.int32, device=dev)
+
+ os.environ["EXL3_ATTN_BACKEND"] = "ck"
+ args = AttnArgs(
+ 1, s, nq, dq,
+ s, nkv,
+ q, knew, vnew,
+ k_cache, v_cache,
+ True,
+ float(dq) ** -0.5,
+ None, None,
+ None, 0.0,
+ bt, cs,
+ None, None, None,
+ max_kv_len=None, v_dim=dv,
+ )
+
+ n_past_pages = old // page
+ keep_mask = torch.zeros(n_past_pages, dtype=torch.bool, device=dev)
+ for p in keep_pages:
+ keep_mask[p] = True
+
+ # --- compacted CK ---
+ o_sparse = fn_ck_paged_attn_sparse(args, keep_mask)
+ torch.cuda.synchronize()
+ assert o_sparse is not None, "sparse path declined valid args"
+
+ # --- dense CK on the same data (full table) ---
+ from .ck_pagedkv import fn_ck_paged_attn
+ os.environ["EXL3_ATTN_BACKEND"] = "ck"
+ o_dense = fn_ck_paged_attn(args)
+ torch.cuda.synchronize()
+ assert o_dense is not None, "dense path declined valid args"
+
+ # --- reference: dense masked to the SAME selected set ---
+ n_idx = torch.arange(s_k, device=dev)
+ phys = torch.tensor(bt_list, device=dev)[n_idx // page] * page + (n_idx % page)
+ kfull = k_cache.view(-1, nkv, dq)[phys].float()
+ vfull = v_cache.view(-1, nkv, dq)[phys][:, :, :dv].float()
+ # the current chunk's rows are written through by the kernel call; recover them
+ kfull[old:] = knew[0].float()
+ vfull[old:] = vnew[0][:, :, :dv].float()
+
+ keep_token_mask = torch.zeros(s_k, dtype=torch.bool, device=dev)
+ for p in range(n_past_pages):
+ if keep_mask[p]:
+ keep_token_mask[p * page:(p + 1) * page] = True
+ keep_token_mask[old:] = True # the current chunk is always kept
+
+ ref = _ref_over_selected(kfull, vfull, q, dv, s_k, s, keep_token_mask)
+
+ err_sparse = (ref - o_sparse[0][..., :dv].float()).abs().max().item()
+ err_dense = (ref - o_dense[0][..., :dv].float()).abs().max().item()
+ # dense CK sees MORE keys than the reference's selected set, so it must DIFFER
+ diff_dense_vs_sparse = (o_dense[0][..., :dv].float()
+ - o_sparse[0][..., :dv].float()).abs().max().item()
+
+ ok = err_sparse < 2e-2
+ if verbose:
+ print(f"[sparse.selftest] s={s} s_k={s_k} keep_past_pages={list(keep_pages)} "
+ f"of {n_past_pages}")
+ print(f" compacted CK vs masked reference : max_abs_err={err_sparse:.5f} "
+ f"{'PASS' if ok else 'FAIL'}")
+ print(f" dense CK vs masked reference : max_abs_err={err_dense:.5f} "
+ f"(expected >0: dense sees the dropped pages)")
+ print(f" dense CK vs compacted CK : max_abs_diff={diff_dense_vs_sparse:.5f} "
+ f"(expected >0: the dropped pages must change the result)")
+ return ok
+
+
+if __name__ == "__main__":
+ import sys
+ ok1 = numerics_test(s=256, s_k=1024, keep_pages=(0, 2))
+ ok2 = numerics_test(s=512, s_k=1536, keep_pages=(0, 3), seed=7,
+ bt_list=[2, 0, 3, 1, 5, 4])
+ # keep-all control: 3 past pages exist (s_k=1024, s=256, page=256) -> keep 0,1,2.
+ # With every past page kept the compacted table equals the dense table, so the
+ # compacted result must reproduce dense CK.
+ ok3 = numerics_test(s=256, s_k=1024, keep_pages=(0, 1, 2), seed=3)
+ print(f"[sparse.selftest] dropped={ok1 and ok2} keep_all={ok3}")
+ sys.exit(0 if (ok1 and ok2 and ok3) else 1)
+
+
+# --------------------------------------------------------------------------------------
+# Page-level SHARED keep-set selector (the deployable shape)
+# --------------------------------------------------------------------------------------
+# A paged cache page holds ALL FOUR KV HEADS, so a page is kept or dropped for all heads
+# jointly: a per-KV-head keep set is NOT expressible in this cache format (see ledger
+# row 178). This selector therefore produces ONE shared keep set over pages:
+# score each page per KV head (page-mean K dotted with a strided probe of the current
+# chunk's queries, maxed over probe rows and over the query heads of the group), then
+# UNION over the 4 KV heads ("keep the page if any head wants it"), then take the top-k
+# of the UNFORCED pages. Only the attention SINKS (first past pages) and the current
+# chunk's own pages are forced; current pages carry the diagonal and are appended
+# unconditionally by compaction. Most-recent past pages are ranked, not forced.
+#
+# Scoring is the bsref pool proxy at PAGE granularity: the page's MEAN K dotted with probe
+# queries. Cost is O(n_past_pages) per call, and the mean is taken in FP32 (k_cache is
+# fp16) so a 256-row page sum neither loses precision nor overflows.
+
+def select_pages(k_cache, bt, past, q, q_len, retain=0.5, n_sink=2, n_local=1,
+ probe=512, n_heads_k=4, mode='union'):
+ """Shared keep set over PAST cache pages -> bool mask [n_past_pages].
+
+ k_cache : [n_pages, page, H_kv, D] fp16 (the engine's paged layout)
+ bt : [1, n_pages] int32 logical->physical
+ past : cached token length BEFORE this chunk (must be page-aligned)
+ q : [1, q_len, n_q_heads, D] fp16 current-chunk queries
+ mode : 'union' -- per-KV-head top-k, then union (mirrors bsref's shared=1 arm)
+ 'global' -- one global top-k over the per-head-max score
+
+ THE SCORING MIRRORS bsref's VALIDATED pool selector exactly: for each KV head h, take
+ the query heads of that head's GQA group, score each page by
+ max over (probe rows, group heads) of q . mean_k[page, h], and keep that head's top-k.
+ The two modes differ only in how the four per-head sets are COMBINED, and both are
+ offered because they have different speed/quality trade-offs that must be measured:
+ union -> up to 4x the per-head budget of pages (the inflated keep of bsref shared=1)
+ global -> exactly one budget of pages, ranked by the peak per-head demand
+ NOTE: the first version of this function scored pages with
+ einsum('pgd,nhd->pgn'), which SUMS the four KV heads instead of scoring per head. The
+ keep COUNT is budget-determined so the speed numbers were unaffected, but the RANKING was
+ not the proxy whose quality was validated. Fixed here.
+
+ FORCED SET: the current chunk's own pages are always kept (they carry the diagonal) and
+ are appended unconditionally by the compaction, so they are NOT part of this mask. The
+ past-side forced set is therefore just the attention SINKS; bsref's 'local' window is
+ the last n_local blocks of the whole sequence, which lies INSIDE the diagonal band and
+ is therefore already kept -- it must not be counted a second time (the first version
+ double-counted it in n_forced, which shrank the top-k budget).
+ """
+ import math as _math
+ page = _page
+ n_past_pages = past // page
+ if past % page != 0:
+ raise ValueError(f"page-aligned past required, got {past}")
+ phys = bt[0, :n_past_pages].long()
+ kp = k_cache[phys] # [n_past_pages, page, H, D] fp16
+ # past is page-aligned, so every past page is FULL: the mean over all `page` tokens is
+ # the valid-token mean. (An unaligned past would need a per-page valid count.)
+ mean_k = kp.mean(dim=1, dtype=torch.float32) # [n_past_pages, H, D] fp32
+ del kp
+
+ n_cur_pages = (q_len + page - 1) // page
+ nB = n_past_pages + n_cur_pages
+ n_keep_total = max(n_local, _math.ceil(retain * nB))
+ # n_forced counts what is kept WITHOUT being ranked: the current chunk's pages (always
+ # kept) plus the sinks. 'local' is inside the current chunk's band, so it is already
+ # included in n_cur_pages and is NOT counted again.
+ n_forced = n_cur_pages + min(n_sink, n_past_pages)
+ n_top = max(0, n_keep_total - n_forced)
+
+ # per-KV-head importance, mirroring bsref's validated pool selector
+ qs = q[0, ::max(1, probe)] # [P, n_q_heads, D]
+ n_q_heads = qs.shape[1]
+ G = n_q_heads // n_heads_k
+ imp_per_head = []
+ for h in range(n_heads_k):
+ qp = qs[:, h * G:(h + 1) * G, :].float() # [P, G, D]
+ sc = torch.einsum("pgd,nd->pgn", qp, mean_k[:, h])
+ imp_per_head.append(sc.amax(dim=(0, 1))) # [n_past_pages] per head
+
+ # the past-side forced set: the attention sinks only
+ mask = torch.zeros(n_past_pages, dtype=torch.bool, device=q.device)
+ if n_sink > 0:
+ mask[:min(n_sink, n_past_pages)] = True
+ n_forced_past = int(mask.sum().item())
+ keep = mask.clone()
+ avail = n_past_pages - n_forced_past
+
+ if mode == 'union':
+ # per-head top-k, then union: mirrors bsref's shared=1 arm
+ for s in imp_per_head:
+ s_r = s.masked_fill(mask, float("-inf"))
+ k_h = min(n_top, avail)
+ if k_h > 0:
+ keep[torch.topk(s_r, k=k_h, largest=True).indices] = True
+ elif mode == 'global':
+ imp = torch.stack(imp_per_head).amax(dim=0)
+ imp_r = imp.masked_fill(mask, float("-inf"))
+ k_g = min(n_top, avail)
+ if k_g > 0:
+ keep[torch.topk(imp_r, k=k_g, largest=True).indices] = True
+ else:
+ raise ValueError(f"unknown mode {mode}")
+
+ return keep, dict(n_past_pages=n_past_pages, n_cur_pages=n_cur_pages,
+ n_keep_total=n_keep_total, n_forced=n_forced,
+ n_forced_past=n_forced_past, n_top=n_top, mode=mode,
+ kept=int(keep.sum().item()))
+
+
+def _owned(args):
+ """Mirror the dense CK ownership test before spending selector work.
+
+ Unsupported devices or shapes must fall through to the normal handler without
+ selector, cache, or native work. Keep this predicate aligned with the direct
+ sparse entry's duplicated guard.
+ """
+ return (
+ _supported_device(args.q.device)
+ and not args.is_varlen()
+ and not args.is_swa()
+ and args.has_kv_cache()
+ and args.cu_seqlens is None
+ and args.softcap == 0.0
+ and args.sinks is None
+ and getattr(args, "ov", None) is None
+ and getattr(args, "tq", None) is None
+ and args.causal
+ and not getattr(args, "non_causal_spans", None)
+ and args.dim == 192
+ and args.num_q_heads == 64
+ and args.num_kv_heads == 4
+ and args.bsz == 1
+ and args.v_dim == 128
+ and args.kv_len == args.q_len
+ and args.q_len >= 16
+ )
+
+
+def fn_ck_paged_attn_sparse_auto(args, retain=None, n_sink=None, n_local=None, probe=None,
+ mode=None):
+ """ENGINE-FACING sparse path: compute the shared keep set, then run the sparse kernel.
+
+ Dispatch registers the engine wrapper at import time when EXL3_CK_PAGEDKV=sparse;
+ the wrapper calls this selector entry and declines unsupported calls to the normal
+ backend. Registration does not establish quality or end-to-end speedup.
+
+ EXL3_CK_SPARSE_RETAIN (default 0.5) is the nominal keep fraction of total pages,
+ including current pages. Current and sink pages are forced; most-recent past pages
+ are not forced. The remaining options are function arguments, not environment
+ switches: n_sink=2, n_local=1 (minimum nominal budget), probe=512, mode="global".
+ """
+ # Ownership FIRST: a shape the sparse path does not own must fall through to the dense
+ # handler without the selector having done any work.
+ if not _owned(args):
+ return None, None
+ if _kernel() is None:
+ _stats["declined"] = (_stats.get("declined") or 0) + 1
+ return None, None
+
+ retain = CK_SPARSE_RETAIN if retain is None else retain
+ n_sink = 2 if n_sink is None else n_sink
+ n_local = 1 if n_local is None else n_local
+ probe = 512 if probe is None else probe
+ mode = "global" if mode is None else mode
+
+ q = args.q
+ k_cache = args.k_cache
+ bt = args.block_table
+ cs = args.cache_seqlens
+ past = int(cs[0].item())
+ q_len = q.shape[1]
+ # Like retain, this threshold is frozen with the persistent cache identity.
+ if past + q_len < CK_SPARSE_MIN_SK:
+ _stats["declined"] += 1
+ return None, None
+ # RAGGED FINAL-CHUNK GUARD. The selector needs page-aligned `past`: every page it scores
+ # must be FULL, because mean_k averages all `page` rows of the page and a partial page would
+ # average in never-written lanes. So it refuses a misaligned past -- but it must REFUSE BY
+ # DECLINING, not by raising, because the dispatcher contract is that a backend returns None
+ # for a shape it does not own and the next function in the chain handles it. Raising here
+ # took the whole request down: the engine's last chunk of a 32775-token prefill has
+ # past=32769 (not a multiple of 256), and the first end-to-end candidate request died with
+ # RuntimeError: page-aligned past required, got 32769
+ # Dense CK tolerates exactly this shape (ck_pagedkv.py:97 ceils: pages_needed = (s_k +
+ # _page - 1) // _page), so declining hands this chunk to dense CK -- correct, and it costs
+ # only the trailing chunk.
+ #
+ # Counted separately from the generic decline so the telemetry says WHICH refusal happened:
+ # if this counter comes back as 1-2 per request the misalignment is the final chunk only and
+ # declining is all that is needed; if it tracks the chunk count, past is misaligned on every
+ # chunk and the selector needs to score floor-aligned pages and force-keep the trailing
+ # partial page (verifier ready for that: verify_select_pages.py 7/7).
+ # How many OWNED calls reach here, and what their past%page residues are. Without this
+ # the misalignment question is unanswerable: the smoke either raises on the first ragged
+ # past (loud) or declines everything (silent). The histogram separates "only the trailing
+ # chunk is ragged" (declining is correct and cheap) from "the engine's cache length carries a
+ # BOS offset so EVERY past is off by one" (declining would disable the sparse path entirely,
+ # and the selector must instead score floor-aligned pages and force-keep the partial tail).
+ _stats["owned_calls"] = (_stats.get("owned_calls") or 0) + 1
+ _pm = _stats.get("past_mods") or {}
+ _r = past % _page
+ _pm[str(_r)] = _pm.get(str(_r), 0) + 1
+ _stats["past_mods"] = _pm
+ if past % _page != 0:
+ # `_stats` values are reset to None elsewhere in this module, so `or 0` is load-
+ # bearing: `.get(k, 0)` returns None for a key that EXISTS with a None value, and
+ # None + 1 raises TypeError -- a crash on the exact path the counter exists to
+ # measure. The offline test missed it because both cases declined earlier at
+ # _owned(), so the guard never actually executed.
+ _stats["declined_unaligned"] = (_stats.get("declined_unaligned") or 0) + 1
+ if _stats["declined_unaligned"] <= 3:
+ print(f"[ck_pagedkv_sparse] DECLINED unaligned past={past} (page={_page}); "
+ f"handing this chunk to the next backend", flush=True)
+ return None, None
+ n_heads_k = k_cache.shape[2]
+ keep, info = select_pages(k_cache, bt, past, q, q_len, retain=retain,
+ n_sink=n_sink, n_local=n_local, probe=probe,
+ n_heads_k=n_heads_k, mode=mode)
+ o = fn_ck_paged_attn_sparse(args, keep)
+ return o, info
diff --git a/exllamav3/modules/attention_fn/ck_pagedkv_sparse_engine.py b/exllamav3/modules/attention_fn/ck_pagedkv_sparse_engine.py
new file mode 100644
index 0000000..4a269ca
--- /dev/null
+++ b/exllamav3/modules/attention_fn/ck_pagedkv_sparse_engine.py
@@ -0,0 +1,38 @@
+"""Install the optional CK sparse prefill handler into the normal dispatcher.
+
+Installation happens once during ``dispatch`` import when
+``EXL3_CK_PAGEDKV=sparse``. Replacing the dense CK entry in place means the
+normal dispatch hint caches this wrapper, rather than bypassing sparse prefill
+on later chunks. A declined shape returns ``None`` and therefore uses the
+existing Triton fallback.
+"""
+
+from .ck_pagedkv import fn_ck_paged_attn
+from .ck_pagedkv_sparse import fn_ck_paged_attn_sparse_auto
+
+_stats = {"accepted": 0, "declined": 0, "pages_kept": 0, "pages_total": 0}
+
+
+def fn_ck_paged_attn_sparse_engine(args):
+ output, info = fn_ck_paged_attn_sparse_auto(args)
+ if output is None:
+ _stats["declined"] += 1
+ return None
+ _stats["accepted"] += 1
+ if info:
+ _stats["pages_kept"] += int(info["kept"])
+ _stats["pages_total"] += int(info["n_past_pages"])
+ return output
+
+
+def install_sparse_engine(attn_fns):
+ """Install once and preserve the ordinary backend as a decline fallback."""
+ if fn_ck_paged_attn_sparse_engine in attn_fns:
+ return attn_fns
+ try:
+ index = attn_fns.index(fn_ck_paged_attn)
+ except ValueError:
+ attn_fns.insert(0, fn_ck_paged_attn_sparse_engine)
+ else:
+ attn_fns[index] = fn_ck_paged_attn_sparse_engine
+ return attn_fns
diff --git a/exllamav3/modules/attention_fn/ck_pagedkv_sparse_qc.py b/exllamav3/modules/attention_fn/ck_pagedkv_sparse_qc.py
new file mode 100644
index 0000000..fc3175e
--- /dev/null
+++ b/exllamav3/modules/attention_fn/ck_pagedkv_sparse_qc.py
@@ -0,0 +1,236 @@
+"""Optional sparse CK prefill over an 8-bit paged KV cache.
+
+Quantized direct-cache calls use a separate dispatcher list, so the fp16 sparse
+handler cannot see them. This adapter dequantizes the used past pages into a
+persistent fp16 staging buffer in logical order, then uses the same selector and
+CK compaction path as fp16 sparse prefill. It intentionally stages both K and V
+for all used past pages in this first implementation: K is required to score every
+page and selected-V-only staging is a future optimization, not a property claimed
+by this module.
+
+MiMo has 24 32-value quantization groups per token. The existing generic kernel
+assumes a power-of-two group count, so this dequantizer pads the Triton program to
+32 groups while masking the eight unused groups.
+"""
+import torch
+import triton
+import triton.language as tl
+
+from ...util.attention_mode import CK_SPARSE_RETAIN, CK_SPARSE_MIN_SK
+from .ck_pagedkv import _kernel, _supported_device
+from .qwrite_triton import _h32_stage
+
+_page = 256
+_R32 = 0.17677669529663688 # 1/sqrt(32), applied after the unnormalised butterfly
+
+_stats = {"qc_calls": 0, "qc_staged_pages": 0, "qc_kept_v_pages": 0}
+
+
+def _deqfull8_pad_kernel(qk, sk, qv, sv, ok, ov, btable, P, G: tl.constexpr,
+ G_PAD: tl.constexpr, TBc: tl.constexpr):
+ """True fp16 dequantisation (H32 un-rotation included) of the pages listed in btable,
+ G non-pow2 groups per token covered by G_PAD >= 2^ceil(log2(G)) with masked lanes.
+ Same float32 op order as qdeq_triton._deqfull8_kernel / ext_fallbacks.dequant_cache_cont."""
+ j = tl.program_id(0)
+ tb = tl.program_id(1)
+ page = tl.minimum(tl.maximum(tl.load(btable + j), 0), P - 1).to(tl.int64)
+ tok = (tb * TBc + tl.arange(0, TBc))[:, None, None].to(tl.int64)
+ grp = tl.arange(0, G_PAD)[None, :, None]
+ gm = grp < G
+ lane = tl.arange(0, 32)[None, None, :]
+ src = ((page * 256 + tok) * G + grp) * 32 + lane
+ sidx = (page * 256 + tok) * G + grp
+ dst = ((j.to(tl.int64) * 256 + tok) * G + grp) * 32 + lane
+ for which in tl.static_range(2):
+ if which == 0:
+ c = tl.load(qk + src, mask=gm, other=0.0).to(tl.float32)
+ sc = tl.load(sk + sidx, mask=gm, other=0.0).to(tl.float32)
+ else:
+ c = tl.load(qv + src, mask=gm, other=0.0).to(tl.float32)
+ sc = tl.load(sv + sidx, mask=gm, other=0.0).to(tl.float32)
+ x = (c - 127.5) * ((sc * 0.17677669529663688) / 128.0)
+ x = tl.reshape(x, (TBc * G_PAD, 32))
+ x = _h32_stage(x, TBc * G_PAD, 1)
+ x = _h32_stage(x, TBc * G_PAD, 2)
+ x = _h32_stage(x, TBc * G_PAD, 4)
+ x = _h32_stage(x, TBc * G_PAD, 8)
+ x = _h32_stage(x, TBc * G_PAD, 16)
+ x = tl.reshape(x, (TBc, G_PAD, 32)).to(tl.float16)
+ if which == 0:
+ tl.store(ok + dst, x, mask=gm)
+ else:
+ tl.store(ov + dst, x, mask=gm)
+
+
+def _dequant8_pages_pad(qk, sk, qv, sv, pages, out_k, out_v, G, G_PAD):
+ """qk/qv (P, 256, G*8) int32 (four 8-bit codes per word, low byte first); sk/sv (P, 256, G) fp16;
+ pages (n,) int32 logical->physical; out_k/out_v hold >= n*256 tokens x G*32 fp16 values,
+ compact in `pages` order. G may be any multiple of 1; G_PAD >= G power of two."""
+ P = qk.shape[0]
+ n = pages.shape[0]
+ assert qk.shape[1:] == (256, G * 8) and sk.shape[1:] == (256, G), (qk.shape, sk.shape)
+ assert qv.shape == qk.shape and sv.shape == sk.shape
+ assert pages.dtype == torch.int32 and pages.is_contiguous()
+ assert out_k.numel() >= n * 256 * G * 32 and out_v.numel() >= n * 256 * G * 32
+ assert out_k.dtype == out_v.dtype == torch.half and out_k.is_contiguous() and out_v.is_contiguous()
+ _deqfull8_pad_kernel[(n, 256 // 4)](
+ qk.view(torch.uint8), sk, qv.view(torch.uint8), sv, out_k, out_v, pages, P,
+ G=G, G_PAD=G_PAD, TBc=4, num_warps=4)
+
+
+# Persistent scratch, one pair per device under the engine's single-stream contract.
+# Concurrent streams/external views across growth are unsupported. Capacity grows in
+# 32-page steps, bounded by the active packed cache; a layout/bound change retires it.
+_STAGE = {}
+
+
+def _stage_buffers(dev, cap_pages, vals_per_token, max_pages=None):
+ if max_pages is not None and cap_pages > max_pages:
+ raise ValueError(f"staging needs {cap_pages} pages but packed cache holds {max_pages}")
+ st = _STAGE.get(dev)
+ if (st is None or st["cap_pages"] < cap_pages
+ or st["vals_per_token"] != vals_per_token
+ or (max_pages is not None and st["cap_pages"] > max_pages)):
+ new_cap = ((cap_pages + 31) // 32) * 32
+ if max_pages is not None:
+ new_cap = min(new_cap, max_pages)
+ # Scratch is fully overwritten on every accepted call. Retire the old pair
+ # before allocating replacements; retaining it inflates the growth peak.
+ _STAGE.pop(dev, None)
+ st = None
+ st = _STAGE[dev] = dict(
+ k=torch.empty((new_cap * 256, vals_per_token), dtype=torch.half, device=dev),
+ v=torch.empty((new_cap * 256, vals_per_token), dtype=torch.half, device=dev),
+ ident=None, # identity table, rebuilt when cap grows
+ cap_pages=new_cap,
+ vals_per_token=vals_per_token,
+ )
+ st["used_pages"] = cap_pages
+ return st
+
+
+def _owned_qc(args):
+ """Mirror of ck_pagedkv_sparse._owned plus the quantized-cache specifics this port supports."""
+ return (
+ args.q_cache is not None
+ and _supported_device(args.q.device)
+ and not args.is_varlen()
+ and not args.is_swa()
+ and args.cu_seqlens is None
+ and args.softcap == 0.0
+ and args.sinks is None
+ and getattr(args, "ov", None) is None
+ and getattr(args, "tq", None) is None
+ and args.causal
+ and not getattr(args, "non_causal_spans", None)
+ and args.dim == 192
+ and args.num_q_heads == 64
+ and args.num_kv_heads == 4
+ and args.bsz == 1
+ and args.v_dim == 128
+ and args.kv_len == args.q_len
+ and args.q_len >= 16 # prefill chunks only: decode (q_len==1) and tiny tails
+ # go to the Triton qc kernels; the selector cannot pay
+ # for itself below a chunk
+ and args.q.dtype == torch.float16
+ )
+
+
+def fn_ck_paged_attn_sparse_qc(args):
+ """Sparse CK prefill over the 8-bit paged cache: stage, select, run the unchanged fp16 path.
+
+ Returns the output tensor, or None when the shape is not owned (the dispatcher then falls
+ through to the Triton online-dequant kernels, exactly as before this module existed).
+ """
+ from .ck_pagedkv_sparse import _stats as sparse_stats, _page, select_pages, fn_ck_paged_attn_sparse
+
+ if not _owned_qc(args):
+ return None
+ if _kernel() is None:
+ return None
+ qk, sk, qv, sv, k_bits, v_bits = args.q_cache
+ if k_bits != 8 or v_bits != 8:
+ return None # the staging kernel is 8-bit specific
+
+ q = args.q
+ bt = args.block_table
+ cs = args.cache_seqlens
+ past = int(cs[0].item())
+ q_len = q.shape[1]
+ if past + q_len < CK_SPARSE_MIN_SK:
+ return None
+
+ sparse_stats["owned_calls"] = (sparse_stats.get("owned_calls") or 0) + 1
+ _r = past % _page
+ _pm = sparse_stats.get("past_mods") or {}
+ _pm[str(_r)] = _pm.get(str(_r), 0) + 1
+ sparse_stats["past_mods"] = _pm
+ if _r != 0:
+ # ragged trailing chunk: decline, the Triton qc prefill handles it (same policy as the
+ # fp16 sparse path's ragged guard)
+ sparse_stats["declined_unaligned"] = (sparse_stats.get("declined_unaligned") or 0) + 1
+ if sparse_stats["declined_unaligned"] <= 3:
+ print(f"[ck_pagedkv_sparse_qc] DECLINED unaligned past={past} (page={_page})",
+ flush=True)
+ return None
+
+ n_past_pages = past // _page
+ n_cur_pages = (q_len + _page - 1) // _page
+ n_pages_needed = n_past_pages + n_cur_pages
+ P = qk.shape[0]
+ G = sk.shape[-1] # groups per token (24 for MiMo qk192 x 4 kv heads)
+ G_PAD = max(16, 1 << (G - 1).bit_length())
+ vals = G * 32 # fp16 values per staged token (768)
+ dev = q.device
+
+ st = _stage_buffers(dev, n_pages_needed, vals, max_pages=P)
+ cap_pages = st["cap_pages"]
+ if st["ident"] is None or st["ident"].shape[0] < cap_pages:
+ st["ident"] = torch.arange(cap_pages, dtype=torch.int32, device=dev)
+
+ # 1) stage ALL past K pages (the selector needs every page's mean) and, for now, all past V.
+ # Staged in logical order (identity table slice), so logical page i lives at row i.
+ pages_k = bt[0, :n_past_pages].to(torch.int32).contiguous()
+ _dequant8_pages_pad(qk, sk, qv, sv, pages_k, st["k"], st["v"], G, G_PAD)
+ _stats["qc_calls"] += 1
+ _stats["qc_staged_pages"] += n_past_pages
+
+ # 2) build the full fp16-shape args over the staged buffers: past pages staged, current
+ # pages left as-is (zeros); fn_ck_paged_attn_sparse writes the new rows itself via
+ # ext.paged_kv_cache_update at the true positions (identity table, cs = past).
+ k_full = st["k"][: n_pages_needed * 256].view(n_pages_needed, 256, args.num_kv_heads, args.dim)
+ v_full = st["v"][: n_pages_needed * 256].view(n_pages_needed, 256, args.num_kv_heads, args.dim)
+ if n_cur_pages:
+ k_full[n_past_pages:].zero_()
+ v_full[n_past_pages:].zero_()
+ bt2 = st["ident"][:n_pages_needed][None]
+ args2 = args._replace(k_cache=k_full, v_cache=v_full, block_table=bt2, q_cache=None)
+
+ # 3) unchanged fp16 sparse machinery: select over staged K, compact, kernel
+ keep, info = select_pages(
+ k_full, bt2, past, q, q_len,
+ retain=CK_SPARSE_RETAIN,
+ n_sink=2,
+ n_local=1,
+ probe=512,
+ n_heads_k=k_full.shape[2],
+ mode="global",
+ )
+ o = fn_ck_paged_attn_sparse(args2, keep)
+ if o is None:
+ sparse_stats["declined"] = (sparse_stats.get("declined") or 0) + 1
+ return None
+
+ _stats["qc_kept_v_pages"] += int(info.get("kept", 0)) if info else 0
+ return o
+
+
+def install_sparse_qc(_fns_qc):
+ """Prepend the qc sparse wrapper to the quantized-cache dispatch chain (mirrors the
+ EXL3_ATTN_BACKEND=ck install pattern for attn_fns). No-op replaces: the Triton qc kernels
+ stay in the chain as the decline path."""
+ if any(getattr(f, "__name__", "") == "fn_ck_paged_attn_sparse_qc" for f in _fns_qc):
+ return _fns_qc
+ _fns_qc.insert(0, fn_ck_paged_attn_sparse_qc)
+ return _fns_qc
diff --git a/exllamav3/modules/attention_fn/dispatch.py b/exllamav3/modules/attention_fn/dispatch.py
index ab93d50..ea3391d 100644
--- a/exllamav3/modules/attention_fn/dispatch.py
+++ b/exllamav3/modules/attention_fn/dispatch.py
@@ -1,4 +1,7 @@
+import os
+
import torch
+from ...util.attention_mode import CK_SPARSE_ENABLED
from ...cache import CacheLayer, Cache, CacheLayer_quant
from .common import AttnArgs, AttnFn
from ...cache.kvwin import MAX_DRAFT
@@ -215,3 +218,19 @@ def attn_dispatch(
cache.update_layer(cache_idx, cache_seqlens, block_table, k_cache, v_cache, q_len, cache_instance)
return o
+
+
+# Optional MiMo sparse prefill. Kept import-time gated because dispatch caches the
+# chosen handler per layer: installing after the first call would not be reliable.
+# `sparse` installs both the fp16 and packed-8-bit KV handlers; every unsupported
+# shape returns None and retains the normal Triton fallback.
+# A missing or unloadable library leaves the normal handlers untouched (one warning, no error).
+if CK_SPARSE_ENABLED:
+ from .ck_pagedkv import _kernel
+
+ if _kernel() is not None:
+ from .ck_pagedkv_sparse_engine import install_sparse_engine
+ from .ck_pagedkv_sparse_qc import install_sparse_qc
+
+ install_sparse_engine(attn_fns)
+ install_sparse_qc(_fns_qc)
diff --git a/exllamav3/util/attention_mode.py b/exllamav3/util/attention_mode.py
new file mode 100644
index 0000000..caccf40
--- /dev/null
+++ b/exllamav3/util/attention_mode.py
@@ -0,0 +1,21 @@
+"""Frozen attention policy shared by import-time dispatch and persistent caches.
+
+EXL3_CK_PAGEDKV=sparse enables approximate prefill. EXL3_CK_SPARSE_RETAIN
+(default 0.5) and EXL3_CK_MIN_SK (default 0) affect its state and cache identity.
+Changing these environment variables requires a new process, not a new session.
+"""
+
+import os
+
+
+CK_SPARSE_ENABLED = os.environ.get("EXL3_CK_PAGEDKV", "").lower() == "sparse"
+# Ignore sparse-only parameters in normal mode, including malformed values.
+CK_SPARSE_RETAIN = float(os.environ.get("EXL3_CK_SPARSE_RETAIN", "0.5")) if CK_SPARSE_ENABLED else 0.5
+CK_SPARSE_MIN_SK = int(os.environ.get("EXL3_CK_MIN_SK", "0")) if CK_SPARSE_ENABLED else 0
+
+# None is the legacy normal mode. Version and all state-affecting sparse knobs
+# travel together so a cache cannot silently cross attention policies.
+ATTENTION_CACHE_MODE = (
+ f"ck-sparse-v1:retain={CK_SPARSE_RETAIN.hex()}:min_sk={CK_SPARSE_MIN_SK}"
+ if CK_SPARSE_ENABLED else None
+)
diff --git a/tests/test_ck_dispatch_mode_cpu.py b/tests/test_ck_dispatch_mode_cpu.py
new file mode 100644
index 0000000..a2f94c4
--- /dev/null
+++ b/tests/test_ck_dispatch_mode_cpu.py
@@ -0,0 +1,40 @@
+"""Import-time dispatch/cache policy agreement; no framework or toolchain needed."""
+import ast
+import builtins
+from pathlib import Path
+from types import SimpleNamespace
+import unittest
+
+SOURCE = Path(__file__).resolve().parents[1] / 'exllamav3/modules/attention_fn/dispatch.py'
+
+
+class DispatchModeTests(unittest.TestCase):
+ def test_shared_mode_controls_registration_not_later_environment(self):
+ tree = ast.parse(SOURCE.read_text())
+ imports = [node for node in tree.body if isinstance(node, ast.ImportFrom)
+ and node.module == 'util.attention_mode']
+ self.assertEqual(len(imports), 1, 'dispatch must import the frozen shared cache/attention mode')
+ branch = tree.body[-1]
+ self.assertIsInstance(branch, ast.If)
+ for enabled, available in ((False, False), (False, True), (True, False), (True, True)):
+ calls = []
+ def importer(name, globals=None, locals=None, fromlist=(), level=0):
+ if name == 'util.attention_mode' and level == 3:
+ return SimpleNamespace(CK_SPARSE_ENABLED=enabled)
+ if name == 'ck_pagedkv' and level == 1:
+ return SimpleNamespace(_kernel=lambda: object() if available else None)
+ if name == 'ck_pagedkv_sparse_engine' and level == 1:
+ return SimpleNamespace(install_sparse_engine=lambda handlers: calls.append('fp16'))
+ if name == 'ck_pagedkv_sparse_qc' and level == 1:
+ return SimpleNamespace(install_sparse_qc=lambda handlers: calls.append('packed8'))
+ raise AssertionError('unexpected import ' + str((name, level)))
+ namespace = {'__builtins__': dict(vars(builtins), __import__=importer),
+ 'os': SimpleNamespace(environ={'EXL3_CK_PAGEDKV': '' if enabled else 'sparse'}),
+ 'attn_fns': [], '_fns_qc': []}
+ with self.subTest(enabled=enabled, available=available):
+ exec(compile(ast.Module(body=imports + [branch], type_ignores=[]), str(SOURCE), 'exec'), namespace)
+ self.assertEqual(calls, ['fp16', 'packed8'] if enabled and available else [])
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_ck_pagedkv_admission_cpu.py b/tests/test_ck_pagedkv_admission_cpu.py
new file mode 100644
index 0000000..9b5ddd0
--- /dev/null
+++ b/tests/test_ck_pagedkv_admission_cpu.py
@@ -0,0 +1,283 @@
+"""Stdlib-only CK admission regressions; no package/framework initialization.
+
+Run directly:
+ python3 -I -S -B tests/test_ck_pagedkv_admission_cpu.py -v
+
+Extract the actual admission functions, direct sparse guard, and engine installer
+with AST. Relative CK imports bind only these inert namespaces. All selector,
+cache-update/staging, allocation, and native boundaries fail if reached. These
+checks establish Python admission behavior, not device or numerical correctness.
+"""
+
+import ast
+import builtins
+import __future__
+from pathlib import Path
+from types import SimpleNamespace
+import unittest
+
+
+_SOURCE = Path(__file__).resolve().parents[1] / "exllamav3/modules/attention_fn"
+
+
+def _tree(filename):
+ path = _SOURCE / filename
+ return path, ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+
+
+def _load(filename, names, namespace, dependencies=None):
+ path, tree = _tree(filename)
+ dependencies = dependencies or {}
+
+ def relative_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if level != 1 or name not in dependencies:
+ raise AssertionError(f"unexpected import: {level}:{name}")
+ return SimpleNamespace(**dependencies[name])
+
+ namespace["__builtins__"] = dict(vars(builtins), __import__=relative_import)
+ body: list[ast.stmt] = [node for node in tree.body
+ if (isinstance(node, ast.FunctionDef) and node.name in names)
+ or (isinstance(node, ast.ImportFrom) and node.module in dependencies)]
+ if {node.name for node in body if isinstance(node, ast.FunctionDef)} != set(names):
+ raise ValueError(f"missing extracted function in {path}")
+ exec(compile(ast.Module(body=body, type_ignores=[]), str(path), "exec",
+ flags=__future__.annotations.compiler_flag), namespace)
+ return namespace
+
+
+def _forbidden(label):
+ def fail(*args, **kwargs):
+ raise AssertionError(f"unexpected {label} work")
+ return fail
+
+
+def _entry_points():
+ half = object()
+ torch = SimpleNamespace(
+ float16=half, version=SimpleNamespace(hip="inert"),
+ cuda=SimpleNamespace(is_available=lambda: True,
+ get_device_properties=lambda device:
+ SimpleNamespace(gcnArchName=device.arch)),
+ zeros=_forbidden("allocation"), arange=_forbidden("allocation"),
+ tensor=_forbidden("allocation"),
+ )
+ ext = SimpleNamespace(paged_kv_cache_update=_forbidden("cache update"))
+ dense = _load("ck_pagedkv.py", ("_supported_device", "owns", "fn_ck_paged_attn"),
+ {"torch": torch, "ext": ext, "_PAGE": 256,
+ "_kernel": _forbidden("optional loader"),
+ "_stats": {"accepted": 0, "rejected": 0}})
+ sparse = _load(
+ "ck_pagedkv_sparse.py",
+ ("_owned", "fn_ck_paged_attn_sparse", "fn_ck_paged_attn_sparse_auto"),
+ {"torch": torch, "ext": ext, "os": SimpleNamespace(environ={}),
+ "select_pages": _forbidden("selector"),
+ "compact_table": _forbidden("compaction"),
+ "_stats": {"dense": 0, "sparse": 0, "declined": 0}},
+ {"ck_pagedkv": dense},
+ )
+ qc = _load(
+ "ck_pagedkv_sparse_qc.py", ("_owned_qc", "fn_ck_paged_attn_sparse_qc"),
+ {"torch": torch, "_page": 256, "os": SimpleNamespace(environ={}),
+ "_stage_buffers": _forbidden("cache staging"),
+ "_dequant8_pages_pad": _forbidden("dequantization"),
+ "_stats": {"qc_calls": 0, "qc_staged_pages": 0, "qc_kept_v_pages": 0}},
+ {"ck_pagedkv": dense, "ck_pagedkv_sparse": sparse},
+ )
+ engine = _load(
+ "ck_pagedkv_sparse_engine.py",
+ ("install_sparse_engine", "fn_ck_paged_attn_sparse_engine"),
+ {"_stats": {"accepted": 0, "declined": 0, "pages_kept": 0, "pages_total": 0}},
+ {"ck_pagedkv": dense, "ck_pagedkv_sparse": sparse},
+ )
+ # Execute the direct sparse entry's actual duplicated predicate separately
+ # so its accepted control needs no tensor/cache/native implementation.
+ path, tree = _tree("ck_pagedkv_sparse.py")
+ direct = next(node for node in tree.body if isinstance(node, ast.FunctionDef)
+ and node.name == "fn_ck_paged_attn_sparse")
+ guard = next(node.value for node in direct.body if isinstance(node, ast.Assign)
+ and any(isinstance(target, ast.Name) and target.id == "owned"
+ for target in node.targets))
+ guard_code = compile(ast.Expression(body=guard), str(path), "eval")
+ return SimpleNamespace(dense=dense, sparse=sparse, qc=qc, engine=engine,
+ half=half, direct_guard=guard_code)
+
+
+def _args(half, *, arch="gfx1151:sramecc-", v_dim: int | None = 128):
+ qk = SimpleNamespace(shape=(2, 256, 192))
+ sk = SimpleNamespace(shape=(2, 256, 24))
+ return SimpleNamespace(
+ q=SimpleNamespace(device=SimpleNamespace(type="cuda", arch=arch),
+ dtype=half, shape=(1, 256, 64, 192)),
+ q_len=256, kv_len=256, k=object(), v=object(),
+ k_cache=SimpleNamespace(shape=(2, 256, 4, 192)), v_cache=object(),
+ block_table=object(), cache_seqlens=[SimpleNamespace(item=lambda: 256)],
+ q_cache=(qk, sk, qk, sk, 8, 8),
+ is_varlen=lambda: False, is_swa=lambda: False, has_kv_cache=lambda: True,
+ cu_seqlens=None, softcap=0.0, sinks=None, causal=True, dim=192,
+ num_q_heads=64, num_kv_heads=4, bsz=1, v_dim=v_dim,
+ )
+
+
+class _AdmissionFixture(unittest.TestCase):
+ def setUp(self):
+ self.entries = _entry_points()
+
+ def predicates(self, args):
+ e = self.entries
+ return {
+ "dense": e.dense["owns"](args),
+ "sparse_auto": e.sparse["_owned"](args),
+ "sparse_direct": eval(e.direct_guard, dict(e.sparse, args=args)),
+ "qc": e.qc["_owned_qc"](args),
+ }
+
+ def installed(self):
+ e = self.entries
+ fallback = _forbidden("fallback")
+ handlers = [e.dense["fn_ck_paged_attn"], fallback]
+ self.assertIs(e.engine["install_sparse_engine"](handlers), handlers)
+ self.assertIs(handlers[0], e.engine["fn_ck_paged_attn_sparse_engine"])
+ self.assertIs(handlers[1], fallback)
+ return handlers[0]
+
+
+class DeviceAdmissionTests(_AdmissionFixture):
+ def test_supported_gfx1151_v128_accepts_every_predicate(self):
+ for name, owned in self.predicates(_args(self.entries.half)).items():
+ with self.subTest(entry=name):
+ self.assertTrue(owned)
+
+ def test_optional_cache_formats_decline_every_predicate(self):
+ for field in ("ov", "tq"):
+ args = _args(self.entries.half)
+ setattr(args, field, object())
+ for name, owned in self.predicates(args).items():
+ with self.subTest(field=field, entry=name):
+ self.assertFalse(owned, "CK does not implement KVWIN or TurboQuant cache semantics")
+
+ def test_unsupported_device_declines_every_predicate(self):
+ args = _args(self.entries.half, arch="gfx1100")
+ for name, owned in self.predicates(args).items():
+ with self.subTest(entry=name):
+ self.assertFalse(owned)
+
+ def test_unsupported_device_declines_installed_engine_before_work(self):
+ self.assertIsNone(self.installed()(_args(self.entries.half, arch="gfx1100")))
+ self.assertEqual(self.entries.engine["_stats"]["declined"], 1)
+
+ def test_supported_installed_engine_reaches_selector(self):
+ # Availability is checked before selection; supply an inert available entry
+ # rather than turning a native lookup into a launch or hiding that lookup.
+ self.entries.sparse["_kernel"] = lambda: object()
+ self.entries.sparse["CK_SPARSE_RETAIN"] = 0.5
+ self.entries.sparse["CK_SPARSE_MIN_SK"] = 0
+ with self.assertRaisesRegex(AssertionError, "unexpected selector work"):
+ self.installed()(_args(self.entries.half))
+
+ def test_unsupported_device_declines_direct_sparse_before_work(self):
+ self.assertIsNone(self.entries.sparse["fn_ck_paged_attn_sparse"](
+ _args(self.entries.half, arch="gfx1100"), object()))
+
+ def test_unsupported_device_declines_direct_dense_before_work(self):
+ self.assertIsNone(self.entries.dense["fn_ck_paged_attn"](
+ _args(self.entries.half, arch="gfx1100")))
+
+ def test_unsupported_device_declines_direct_qc_before_work(self):
+ self.assertIsNone(self.entries.qc["fn_ck_paged_attn_sparse_qc"](
+ _args(self.entries.half, arch="gfx1100")))
+
+
+class SpanMaskAdmissionTests(_AdmissionFixture):
+ def args_with_spans(self, spans):
+ args = _args(self.entries.half)
+ args.q.shape = (1, 64, 64, 192)
+ args.q_len = args.kv_len = 64
+ args.k_cache.shape = (3, 256, 4, 192)
+ args.q_cache[0].shape = (3, 256, 192)
+ args.q_cache[1].shape = (3, 256, 24)
+ args.cache_seqlens = [SimpleNamespace(item=lambda: 512)]
+ args.non_causal_spans = spans
+ return args
+
+ def test_nonempty_spans_decline_every_predicate(self):
+ args = self.args_with_spans([(0, 64, True)])
+ for name, owned in self.predicates(args).items():
+ with self.subTest(entry=name):
+ self.assertFalse(owned, "CK does not implement non-causal span masks")
+
+ def test_none_or_empty_spans_accept_every_predicate(self):
+ for spans in (None, []):
+ for name, owned in self.predicates(self.args_with_spans(spans)).items():
+ with self.subTest(spans=spans, entry=name):
+ self.assertTrue(owned)
+
+ def test_nonempty_spans_decline_direct_dense_before_work(self):
+ self.assertIsNone(self.entries.dense["fn_ck_paged_attn"](
+ self.args_with_spans([(0, 64, True)])))
+
+ def test_nonempty_spans_decline_direct_sparse_before_work(self):
+ self.assertIsNone(self.entries.sparse["fn_ck_paged_attn_sparse"](
+ self.args_with_spans([(0, 64, True)]), object()))
+
+ def test_nonempty_spans_decline_auto_sparse_before_work(self):
+ self.assertEqual(self.entries.sparse["fn_ck_paged_attn_sparse_auto"](
+ self.args_with_spans([(0, 64, True)])), (None, None))
+
+ def test_nonempty_spans_decline_installed_engine_before_work(self):
+ self.assertIsNone(self.installed()(self.args_with_spans([(0, 64, True)])))
+ self.assertEqual(self.entries.engine["_stats"]["declined"], 1)
+
+ def test_nonempty_spans_decline_direct_qc_before_work(self):
+ self.assertIsNone(self.entries.qc["fn_ck_paged_attn_sparse_qc"](
+ self.args_with_spans([(0, 64, True)])))
+
+ def test_none_or_empty_spans_installed_engine_reaches_selector(self):
+ self.entries.sparse["_kernel"] = lambda: object()
+ self.entries.sparse["CK_SPARSE_RETAIN"] = 0.5
+ self.entries.sparse["CK_SPARSE_MIN_SK"] = 0
+ handler = self.installed()
+ for spans in (None, []):
+ with self.subTest(spans=spans):
+ with self.assertRaisesRegex(AssertionError, "unexpected selector work"):
+ handler(self.args_with_spans(spans))
+
+
+class ValueWidthAdmissionTests(_AdmissionFixture):
+ def test_explicit_v128_accepts_every_predicate(self):
+ for name, owned in self.predicates(_args(self.entries.half, v_dim=128)).items():
+ with self.subTest(entry=name):
+ self.assertTrue(owned)
+
+ def test_implicit_or_full_v192_declines_every_predicate(self):
+ for width in (None, 192):
+ for name, owned in self.predicates(_args(self.entries.half, v_dim=width)).items():
+ with self.subTest(v_dim=width, entry=name):
+ self.assertFalse(owned)
+
+ def test_implicit_or_full_v192_declines_installed_engine_before_work(self):
+ handler = self.installed()
+ for width in (None, 192):
+ with self.subTest(v_dim=width):
+ self.assertIsNone(handler(_args(self.entries.half, v_dim=width)))
+
+ def test_implicit_or_full_v192_declines_direct_sparse_before_work(self):
+ for width in (None, 192):
+ with self.subTest(v_dim=width):
+ self.assertIsNone(self.entries.sparse["fn_ck_paged_attn_sparse"](
+ _args(self.entries.half, v_dim=width), object()))
+
+ def test_implicit_or_full_v192_declines_direct_dense_before_work(self):
+ for width in (None, 192):
+ with self.subTest(v_dim=width):
+ self.assertIsNone(self.entries.dense["fn_ck_paged_attn"](
+ _args(self.entries.half, v_dim=width)))
+
+ def test_implicit_or_full_v192_declines_direct_qc_before_work(self):
+ for width in (None, 192):
+ with self.subTest(v_dim=width):
+ self.assertIsNone(self.entries.qc["fn_ck_paged_attn_sparse_qc"](
+ _args(self.entries.half, v_dim=width)))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_ck_pagedkv_cpu.py b/tests/test_ck_pagedkv_cpu.py
new file mode 100644
index 0000000..83ab022
--- /dev/null
+++ b/tests/test_ck_pagedkv_cpu.py
@@ -0,0 +1,122 @@
+"""Stdlib-only optional CK loader and admission tests; no package initialization.
+
+Run directly: python3 -I -S -B tests/test_ck_pagedkv_cpu.py -v
+Only actual production definitions execute, with inert loader/framework boundaries.
+No native library, torch, pytest, CUDA, or exllamav3 package is imported.
+"""
+
+import ast
+import __future__
+import ctypes
+import math
+import os
+from pathlib import Path
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+import warnings
+
+
+_SOURCE = Path(__file__).resolve().parents[1] / "exllamav3/modules/attention_fn/ck_pagedkv.py"
+
+
+def _load():
+ tree = ast.parse(_SOURCE.read_text(encoding="utf-8"), filename=str(_SOURCE))
+ names = {"ck_library_path", "_kernel", "owns"}
+ body: list[ast.stmt] = [node for node in tree.body
+ if isinstance(node, ast.FunctionDef) and node.name in names]
+ namespace: dict = dict(ctypes=ctypes, math=math, os=os, Path=Path, warnings=warnings,
+ _fn=None, _load_failed=False, _supported_device=lambda _: True)
+ exec(compile(ast.Module(body=body, type_ignores=[]), str(_SOURCE), "exec",
+ flags=__future__.annotations.compiler_flag), namespace)
+ return SimpleNamespace(**namespace), namespace
+
+
+def _args(q_len=16):
+ return SimpleNamespace(
+ q=SimpleNamespace(device=object()), q_len=q_len, kv_len=q_len,
+ is_varlen=lambda: False, is_swa=lambda: False, has_kv_cache=lambda: True,
+ cu_seqlens=None, softcap=0.0, sinks=None, causal=True, dim=192,
+ num_q_heads=64, num_kv_heads=4, bsz=1, v_dim=128,
+ )
+
+
+class LibraryPathAndOwnershipTests(unittest.TestCase):
+ def setUp(self):
+ self.ck, self.namespace = _load()
+
+ def test_library_path_uses_cache(self):
+ with patch.dict(os.environ, {"XDG_CACHE_HOME": "/inert/cache"}, clear=True):
+ self.assertEqual(self.ck.ck_library_path(),
+ Path("/inert/cache/kyojin/ck-pagedkv/libck_pagedkv.so"))
+
+ def test_library_path_accepts_explicit_override(self):
+ with patch.dict(os.environ, {"EXL3_CK_PAGEDKV_SO": "~/custom.so"}, clear=True):
+ self.assertEqual(self.ck.ck_library_path(), Path.home() / "custom.so")
+
+ def test_ownership_declines_decode(self):
+ self.assertFalse(self.ck.owns(_args(q_len=1)))
+ self.assertTrue(self.ck.owns(_args()))
+
+
+class OptionalLibraryTests(unittest.TestCase):
+ def test_unloadable_library_and_missing_symbol_decline_once(self):
+ for failure in (OSError("inert bad ELF"), AttributeError("missing ck_pagedkv_forward")):
+ with self.subTest(failure=type(failure).__name__):
+ ck, namespace = _load()
+ namespace["ck_library_path"] = lambda: Path("/inert/libck.so")
+ if isinstance(failure, OSError):
+ loader: dict = dict(side_effect=failure)
+ else:
+ class MissingSymbol:
+ def __getattr__(self, name):
+ raise failure
+ loader = dict(return_value=MissingSymbol())
+ with patch.object(Path, "is_file", return_value=True), \
+ patch.object(ctypes, "CDLL", **loader) as cdll, \
+ warnings.catch_warnings(record=True) as seen:
+ warnings.simplefilter("always")
+ self.assertIsNone(ck._kernel())
+ self.assertIsNone(ck._kernel())
+ cdll.assert_called_once_with("/inert/libck.so")
+ self.assertEqual(len(seen), 1)
+ self.assertIn("fallback", str(seen[0].message).lower())
+
+ def test_unexpected_loader_error_propagates(self):
+ ck, namespace = _load()
+ namespace["ck_library_path"] = lambda: Path("/inert/libck.so")
+ failure = RuntimeError("unexpected loader logic failure")
+ with patch.object(Path, "is_file", return_value=True), \
+ patch.object(ctypes, "CDLL", side_effect=failure):
+ with self.assertRaises(RuntimeError) as caught:
+ ck._kernel()
+ self.assertIs(caught.exception, failure)
+
+ def test_successful_loader_caches_bound_function_and_float_abi(self):
+ ck, namespace = _load()
+ namespace["ck_library_path"] = lambda: Path("/inert/libck.so")
+ function = SimpleNamespace()
+ with patch.object(Path, "is_file", return_value=True), \
+ patch.object(ctypes, "CDLL", return_value=SimpleNamespace(
+ ck_pagedkv_forward=function)) as cdll:
+ self.assertIs(ck._kernel(), function)
+ self.assertIs(ck._kernel(), function)
+ cdll.assert_called_once_with("/inert/libck.so")
+ self.assertIs(function.restype, ctypes.c_float)
+ self.assertEqual(len(function.argtypes), 14)
+
+ def test_missing_library_declines_once_without_loading(self):
+ ck, namespace = _load()
+ path = SimpleNamespace(is_file=lambda: False)
+ namespace["ck_library_path"] = lambda: path
+ with patch.object(ctypes, "CDLL") as cdll, warnings.catch_warnings(record=True) as seen:
+ warnings.simplefilter("always")
+ self.assertIsNone(ck._kernel())
+ self.assertIsNone(ck._kernel())
+ cdll.assert_not_called()
+ self.assertEqual(len(seen), 1)
+ self.assertIn("fallback", str(seen[0].message).lower())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_ck_pagedkv_fallback_cpu.py b/tests/test_ck_pagedkv_fallback_cpu.py
new file mode 100644
index 0000000..e931054
--- /dev/null
+++ b/tests/test_ck_pagedkv_fallback_cpu.py
@@ -0,0 +1,277 @@
+"""Isolated Python CK fallback contracts, executed from real AST definitions.
+
+Run: python3 -I -S -B tests/test_ck_pagedkv_fallback_cpu.py -v
+Tensor, stream and native boundaries are inert; no package/framework is imported.
+"""
+
+import ast
+import builtins
+import __future__
+import math
+import os
+from pathlib import Path
+from types import SimpleNamespace
+import unittest
+
+
+_SOURCE = Path(__file__).resolve().parents[1] / "exllamav3/modules/attention_fn"
+
+
+def _load(filename, names, namespace: dict, dependencies=None) -> dict:
+ path = _SOURCE / filename
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ dependencies = dependencies or {}
+
+ def relative_import(name, globals=None, locals=None, fromlist=(), level=0):
+ if level != 1 or name not in dependencies:
+ raise AssertionError(f"unexpected import: {level}:{name}")
+ return SimpleNamespace(**dependencies[name])
+
+ namespace["__builtins__"] = dict(vars(builtins), __import__=relative_import)
+ body: list[ast.stmt] = [node for node in tree.body
+ if isinstance(node, ast.FunctionDef) and node.name in names]
+ if {node.name for node in body if isinstance(node, ast.FunctionDef)} != set(names):
+ raise ValueError(f"missing production function in {path}")
+ exec(compile(ast.Module(body=body, type_ignores=[]), str(path), "exec",
+ flags=__future__.annotations.compiler_flag), namespace)
+ return namespace
+
+
+def _forbidden(label):
+ def fail(*args, **kwargs):
+ raise AssertionError(f"unexpected {label} work")
+ return fail
+
+
+def _args():
+ half = object()
+ return SimpleNamespace(
+ q=SimpleNamespace(device="inert:0", dtype=half, shape=(1, 256, 64, 192)),
+ q_len=256, kv_len=256, k=object(), v=object(),
+ k_cache=SimpleNamespace(shape=(2, 256, 4, 192)), v_cache=object(),
+ block_table=object(), cache_seqlens=[SimpleNamespace(item=lambda: 256)],
+ q_cache=(SimpleNamespace(shape=(2, 256, 192)),
+ SimpleNamespace(shape=(2, 256, 24)), object(), object(), 8, 8),
+ is_varlen=lambda: False, is_swa=lambda: False, has_kv_cache=lambda: True,
+ cu_seqlens=None, softcap=0.0, sinks=None, causal=True, dim=192,
+ num_q_heads=64, num_kv_heads=4, bsz=1, v_dim=128, sm_scale=192 ** -0.5,
+ )
+
+
+def _entries(kernel):
+ args = _args()
+ torch = SimpleNamespace(float16=args.q.dtype,
+ zeros=_forbidden("allocation"),
+ cuda=SimpleNamespace(current_stream=_forbidden("stream lookup")))
+ common: dict = dict(torch=torch, math=math, os=os, _PAGE=256, _page=256,
+ CK_SPARSE_RETAIN=0.5, CK_SPARSE_MIN_SK=0,
+ _supported_device=lambda _: True, _kernel=kernel,
+ ext=SimpleNamespace(paged_kv_cache_update=_forbidden("cache update")))
+ dense = _load("ck_pagedkv.py", {"owns", "fn_ck_paged_attn"},
+ dict(common, _stats={"accepted": 0, "rejected": 0}))
+ sparse = _load("ck_pagedkv_sparse.py",
+ {"_owned", "fn_ck_paged_attn_sparse", "fn_ck_paged_attn_sparse_auto"},
+ dict(common, select_pages=_forbidden("selector"),
+ compact_table=_forbidden("compaction"),
+ _stats={"dense": 0, "sparse": 0, "declined": 0}))
+ qc = _load("ck_pagedkv_sparse_qc.py", {"_owned_qc", "fn_ck_paged_attn_sparse_qc"},
+ dict(common, _stage_buffers=_forbidden("staging"),
+ _dequant8_pages_pad=_forbidden("dequantization"),
+ _stats={"qc_calls": 0, "qc_staged_pages": 0, "qc_kept_v_pages": 0}),
+ {"ck_pagedkv_sparse": sparse})
+ return args, dense, sparse, qc
+
+
+class AvailabilityTests(unittest.TestCase):
+ def test_unavailable_library_declines_all_entries_before_tensor_work(self):
+ lookups = []
+
+ def unavailable():
+ lookups.append("lookup")
+ return None
+
+ args, dense, sparse, qc = _entries(unavailable)
+ entries = [
+ (dense["fn_ck_paged_attn"], (args,), None),
+ (sparse["fn_ck_paged_attn_sparse"], (args, object()), None),
+ (sparse["fn_ck_paged_attn_sparse_auto"], (args,), (None, None)),
+ (qc["fn_ck_paged_attn_sparse_qc"], (args,), None),
+ ]
+ for fn, params, expected in entries:
+ with self.subTest(entry=fn.__name__):
+ before = len(lookups)
+ self.assertEqual(fn(*params), expected)
+ self.assertEqual(len(lookups), before + 1)
+
+
+class FrozenPolicyTests(unittest.TestCase):
+ def test_modules_bind_frozen_policy_instead_of_reading_environment(self):
+ for filename, name in (("ck_pagedkv_sparse.py", "fn_ck_paged_attn_sparse_auto"),
+ ("ck_pagedkv_sparse_qc.py", "fn_ck_paged_attn_sparse_qc")):
+ with self.subTest(module=filename):
+ tree = ast.parse((_SOURCE / filename).read_text(encoding="utf-8"))
+ imported = {alias.name for node in tree.body
+ if isinstance(node, ast.ImportFrom) and node.level == 3
+ and node.module == "util.attention_mode" for alias in node.names}
+ self.assertTrue({"CK_SPARSE_RETAIN", "CK_SPARSE_MIN_SK"} <= imported)
+ function = next(node for node in tree.body if isinstance(node, ast.FunctionDef)
+ and node.name == name)
+ self.assertFalse(any(isinstance(node, ast.Constant)
+ and node.value in ("EXL3_CK_SPARSE_RETAIN", "EXL3_CK_MIN_SK")
+ for node in ast.walk(function)))
+
+ def test_qc_declines_below_frozen_threshold_before_staging(self):
+ args, _, _, qc = _entries(lambda: object())
+ qc["CK_SPARSE_MIN_SK"] = 1024
+ self.assertIsNone(qc["fn_ck_paged_attn_sparse_qc"](args))
+
+ def test_auto_uses_frozen_threshold_and_retain(self):
+ args, _, sparse, _ = _entries(lambda: object())
+ sparse["CK_SPARSE_RETAIN"] = 0.25
+ sparse["CK_SPARSE_MIN_SK"] = 1024
+ self.assertEqual(sparse["fn_ck_paged_attn_sparse_auto"](args), (None, None))
+ seen = []
+ sparse["CK_SPARSE_MIN_SK"] = 0
+ sparse["select_pages"] = lambda *params, **kwargs: (seen.append(kwargs) or object(), {})
+ sparse["fn_ck_paged_attn_sparse"] = lambda *params: "output"
+ self.assertEqual(sparse["fn_ck_paged_attn_sparse_auto"](args), ("output", {}))
+ self.assertEqual(seen[-1]["retain"], 0.25)
+ sparse["fn_ck_paged_attn_sparse_auto"](args, retain=0.75)
+ self.assertEqual(seen[-1]["retain"], 0.75)
+
+
+class _Tensor:
+ def __init__(self, shape=(), value=None):
+ self.shape = shape
+ self.value = value
+ self.device = "inert:0"
+
+ def __getitem__(self, key):
+ return self
+
+ def long(self):
+ return self
+
+ def permute(self, *dims):
+ return self
+
+ def contiguous(self):
+ return self
+
+ def numel(self):
+ return self.shape[0]
+
+ def data_ptr(self):
+ return id(self)
+
+
+def _direct_entries(result=1.0, failure=None):
+ args, dense, sparse, _ = _entries(lambda: None)
+ trace = []
+ outputs = []
+ args.q = _Tensor((1, 256, 64, 192))
+ args.q.device = "inert:0"
+ args.k_cache = _Tensor((2, 256, 4, 192))
+ args.v_cache = _Tensor((2, 256, 4, 192))
+ args.block_table = _Tensor((1, 2))
+ args.cache_seqlens = [SimpleNamespace(item=lambda: 256)]
+
+ def cache_update(k, v, kc, vc, bt, cs):
+ trace.append(("write", bt, cs, cs[0].item()))
+
+ def zeros(*shape, **kwargs):
+ out = _Tensor(shape)
+ outputs.append(out)
+ return out
+
+ def kernel(*params):
+ trace.append(("kernel", params))
+ if failure is not None:
+ raise failure
+ return result
+
+ torch = SimpleNamespace(
+ float16=object(), int32=object(), zeros=zeros,
+ arange=lambda n, **kwargs: _Tensor((n,)),
+ tensor=lambda values, **kwargs: _Tensor((len(values),)),
+ cuda=SimpleNamespace(current_stream=lambda: SimpleNamespace(cuda_stream=123)),
+ )
+ for namespace in (dense, sparse):
+ namespace.update(torch=torch, _kernel=lambda: kernel,
+ ext=SimpleNamespace(paged_kv_cache_update=cache_update))
+ sparse["compact_table"] = lambda *params: (_Tensor((2,)), 512)
+ return SimpleNamespace(args=args, dense=dense, sparse=sparse,
+ trace=trace, outputs=outputs, update=cache_update)
+
+
+class DirectResultTests(unittest.TestCase):
+ def _call(self, entry, result=1.0, failure=None):
+ fixture = _direct_entries(result, failure)
+ if entry == "dense":
+ function = fixture.dense["fn_ck_paged_attn"]
+ params = (fixture.args,)
+ else:
+ function = fixture.sparse["fn_ck_paged_attn_sparse"]
+ params = (fixture.args, object())
+ return fixture, lambda: function(*params)
+
+ def test_explicit_support_rejection_declines_to_ordinary_handler(self):
+ for entry in ("dense", "sparse"):
+ with self.subTest(entry=entry):
+ fixture, call = self._call(entry, -1.0)
+ fallback_output = object()
+ fallback_calls = []
+
+ def fallback():
+ fallback_calls.append(True)
+ return fallback_output
+
+ for handler in (call, fallback):
+ output = handler()
+ if output is not None:
+ break
+ self.assertIs(output, fallback_output)
+ self.assertEqual(fallback_calls, [True])
+ self.assertEqual([event[0] for event in fixture.trace], ["write", "kernel"])
+ self.assertIs(fixture.trace[0][1], fixture.args.block_table)
+ self.assertIs(fixture.trace[0][2], fixture.args.cache_seqlens)
+ self.assertEqual(fixture.args.cache_seqlens[0].item(), 256)
+ self.assertEqual(fixture.dense["_stats"]["accepted"], 0)
+ self.assertEqual(fixture.sparse["_stats"]["sparse"], 0)
+ counter = fixture.dense["_stats"] if entry == "dense" else fixture.sparse["_stats"]
+ self.assertEqual(counter["rejected" if entry == "dense" else "declined"], 1)
+
+ def test_success_returns_allocated_output(self):
+ for entry in ("dense", "sparse"):
+ with self.subTest(entry=entry):
+ fixture, call = self._call(entry)
+ self.assertIs(call(), fixture.outputs[0])
+ self.assertEqual([event[0] for event in fixture.trace], ["write", "kernel"])
+
+ def test_invalid_status_does_not_reach_fallback(self):
+ for entry in ("dense", "sparse"):
+ for result in (-2.0, -0.5, 0.0, float("nan"), float("inf"), -float("inf")):
+ with self.subTest(entry=entry, result=result):
+ fixture, call = self._call(entry, result)
+ with self.assertRaisesRegex(RuntimeError, "rc="):
+ for handler in (call, _forbidden("fallback")):
+ if handler() is not None:
+ break
+ self.assertEqual(fixture.dense["_stats"]["accepted"], 0)
+ self.assertEqual(fixture.sparse["_stats"]["sparse"], 0)
+
+ def test_python_visible_invocation_errors_propagate_unchanged(self):
+ # Native uncaught C++ exceptions can terminate the process; no ABI recovery
+ # is claimed by a test substituting these Python-visible callables.
+ for entry in ("dense", "sparse"):
+ for failure in (OSError("inert launch error"), RuntimeError("inert device error")):
+ with self.subTest(entry=entry, failure=type(failure).__name__):
+ fixture, call = self._call(entry, failure=failure)
+ with self.assertRaises(type(failure)) as caught:
+ call()
+ self.assertIs(caught.exception, failure)
+ self.assertEqual([event[0] for event in fixture.trace], ["write", "kernel"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_ck_pagedkv_patch_cpu.py b/tests/test_ck_pagedkv_patch_cpu.py
new file mode 100644
index 0000000..6cbbc69
--- /dev/null
+++ b/tests/test_ck_pagedkv_patch_cpu.py
@@ -0,0 +1,103 @@
+"""Real local Git patch regressions; stdlib only, no commit or build.
+
+Run directly: python3 -I -S -B tests/test_ck_pagedkv_patch_cpu.py -v
+Git accepts a bare-empty unified context line, but emits a single-space
+marker in its canonical diff. Both spellings must retain exact stage ownership.
+"""
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+from typing import Any
+import unittest
+
+
+_BUILDER = Path(__file__).resolve().parents[1] / 'tools/strix_halo/ck_pagedkv_build.py'
+_namespace: dict[str, Any] = {'__file__': str(_BUILDER), '__name__': '_ck_patch_test'}
+exec(compile(_BUILDER.read_bytes(), str(_BUILDER), 'exec'), _namespace)
+apply_patch = _namespace['apply_patch']
+BuildError = _namespace['BuildError']
+
+
[email protected](shutil.which('git'), 'git required')
+class PatchPackagingTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix='ck-patch-', dir=os.environ.get('TMPDIR'))
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.repo = self.root / 'repo'
+ self.repo.mkdir()
+ self.git('init', '-q')
+ self.original = b'alpha\n\nbefore\nomega\n'
+ self.patched = b'alpha\n\nafter\nomega\n'
+ (self.repo / 'owned.txt').write_bytes(self.original)
+ (self.repo / 'other.txt').write_bytes(b'unrelated\n')
+ self.git('add', '--', 'owned.txt', 'other.txt')
+ # A tree object suffices for diff HEAD; no commit object is created.
+ tree = self.git('write-tree').stdout.strip()
+ (self.repo / '.git/HEAD').write_bytes(tree + b'\n')
+ (self.repo / 'owned.txt').write_bytes(self.patched)
+ self.canonical = self.git('diff', '--no-ext-diff', '--no-color', '--full-index', 'HEAD', '--').stdout
+ self.assertEqual(self.canonical.count(b'\n \n'), 1)
+ self.compact = self.canonical.replace(b'\n \n', b'\n\n')
+ self.assertNotEqual(self.compact, self.canonical)
+ self.patch = self.root / 'change.patch'
+ self.patch.write_bytes(self.compact)
+ (self.repo / 'owned.txt').write_bytes(self.original)
+
+ def git(self, *args):
+ env = {k: v for k, v in os.environ.items() if not k.startswith('GIT_')}
+ env.update(GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL='/dev/null',
+ GIT_OPTIONAL_LOCKS='0', GIT_NO_REPLACE_OBJECTS='1',
+ GIT_NO_LAZY_FETCH='1', GIT_ALLOW_PROTOCOL='file', LC_ALL='C')
+ result = subprocess.run(['git', '-c', 'core.hooksPath=/dev/null', '-C', str(self.repo), *args],
+ env=env, capture_output=True)
+ self.assertEqual(result.returncode, 0, result.stderr.decode())
+ return result
+
+ def test_bare_empty_context_applies_and_retries(self):
+ self.git('apply', '--check', '--whitespace=error-all', str(self.patch))
+ self.assertEqual(apply_patch(self.repo, self.patch), 'applied')
+ self.assertEqual((self.repo / 'owned.txt').read_bytes(), self.patched)
+ self.assertEqual(apply_patch(self.repo, self.patch), 'already-applied')
+ self.assertEqual((self.repo / 'owned.txt').read_bytes(), self.patched)
+
+ def test_canonical_context_applies_and_retries(self):
+ self.patch.write_bytes(self.canonical)
+ self.assertEqual(apply_patch(self.repo, self.patch), 'applied')
+ self.assertEqual(apply_patch(self.repo, self.patch), 'already-applied')
+
+ def test_unrelated_tracked_dirt_refused_before_apply_and_retry(self):
+ other = self.repo / 'other.txt'
+ for patched in (False, True):
+ with self.subTest(patched=patched):
+ if patched:
+ self.git('apply', str(self.patch))
+ other.write_bytes(b'unrelated dirty\n')
+ before = (self.repo / 'owned.txt').read_bytes()
+ with self.assertRaisesRegex(BuildError, 'changes beyond the exact pinned patch'):
+ apply_patch(self.repo, self.patch)
+ self.assertEqual((self.repo / 'owned.txt').read_bytes(), before)
+ self.assertEqual(other.read_bytes(), b'unrelated dirty\n')
+ other.write_bytes(b'unrelated\n')
+
+ def test_source_whitespace_dirt_is_not_normalized(self):
+ self.git('apply', str(self.patch))
+ dirty = self.patched.replace(b'alpha\n', b'alpha \n')
+ (self.repo / 'owned.txt').write_bytes(dirty)
+ with self.assertRaisesRegex(BuildError, 'changes beyond the exact pinned patch'):
+ apply_patch(self.repo, self.patch)
+ self.assertEqual((self.repo / 'owned.txt').read_bytes(), dirty)
+
+ def test_untracked_dirt_refused(self):
+ extra = self.repo / 'extra.txt'
+ extra.write_bytes(b'untracked\n')
+ with self.assertRaisesRegex(BuildError, 'untracked source files'):
+ apply_patch(self.repo, self.patch)
+ self.assertEqual((self.repo / 'owned.txt').read_bytes(), self.original)
+ self.assertEqual(extra.read_bytes(), b'untracked\n')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/test_ck_pagedkv_shim_cpu.py b/tests/test_ck_pagedkv_shim_cpu.py
new file mode 100644
index 0000000..05fc00b
--- /dev/null
+++ b/tests/test_ck_pagedkv_shim_cpu.py
@@ -0,0 +1,324 @@
+"""Compile the actual C ABI shim with inert headers; never load HIP or a .so.
+
+Run directly with unittest to avoid framework-importing repository conftest files.
+CK_SHIM_CPU_RECEIPTS optionally retains generated fixtures and subprocess receipts.
+"""
+import json
+import os
+from pathlib import Path
+import resource
+import shlex
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+SHIM = ROOT / "tools/strix_halo/ck_pagedkv_shim.cpp"
+
+# Only host-side declarations consumed by the real shim. index_t matches pinned
+# CK's int32_t, including its batch/head stride fields. There is deliberately no
+# generated support dispatcher and no implementation of the primary template.
+HEADERS = {
+ "hip/hip_runtime.h": "#pragma once\nstruct ihipStream_t;\nusing hipStream_t = ihipStream_t*;\n",
+ "bias.hpp": "#pragma once\n",
+ "mask.hpp": "#pragma once\nenum class mask_enum { mask_bottom_right = 2 };\n",
+ "fmha_fwd.hpp": r"""#pragma once
+#include <cstdint>
+#include <hip/hip_runtime.h>
+namespace ck_tile {
+using index_t = std::int32_t;
+struct gfx11_t {};
+template <bool> struct SimplifiedGenericAttentionMask {};
+enum class BlockFmhaPipelineEnum { QRKSVS };
+enum class BlockAttentionBiasEnum { NO_BIAS };
+struct stream_config {
+ hipStream_t stream_id_;
+ bool time_kernel_;
+ int log_level_;
+ int cold_niters_;
+ int nrepeat_;
+ bool is_gpu_timer_;
+};
+}
+struct FmhaFwdFp16 {};
+template <ck_tile::index_t, typename, bool, ck_tile::index_t,
+ ck_tile::index_t, ck_tile::index_t, ck_tile::index_t,
+ ck_tile::index_t, ck_tile::index_t, bool,
+ ck_tile::BlockFmhaPipelineEnum, bool, typename,
+ ck_tile::BlockAttentionBiasEnum, bool, bool, bool, bool,
+ bool, bool, bool, bool, bool, int>
+struct fmha_fwd_pagedkv_traits_ {};
+struct fmha_fwd_pagedkv_args {
+ const void* q_ptr;
+ const void* k_ptr;
+ const void* v_ptr;
+ void* o_ptr;
+ void* block_table_ptr;
+ ck_tile::index_t batch_stride_block_table;
+ ck_tile::index_t page_block_size;
+ const void* seqlen_k_ptr;
+ ck_tile::index_t seqlen_q, seqlen_k, batch, max_seqlen_q;
+ ck_tile::index_t hdim_q, hdim_v, nhead_q, nhead_k;
+ float scale_s, scale_p, scale_o;
+ ck_tile::index_t window_size_left, window_size_right, mask_type;
+ ck_tile::index_t stride_q, stride_k, stride_v, stride_o;
+ ck_tile::index_t nhead_stride_q, nhead_stride_k, nhead_stride_v, nhead_stride_o;
+ ck_tile::index_t batch_stride_q, batch_stride_k, batch_stride_v, batch_stride_o;
+};
+template <typename Traits, typename Arch>
+float fmha_fwd_pagedkv_(const ck_tile::stream_config&, fmha_fwd_pagedkv_args);
+""",
+}
+
+DRIVER = r"""#include <cstdlib>
+#include <iostream>
+#include <limits>
+#include <stdexcept>
+#include "@SHIM@"
+namespace {
+int mode = 0;
+int calls = 0;
+fmha_fwd_pagedkv_args last_args{};
+ck_tile::stream_config last_config{};
+}
+template <>
+float fmha_fwd_pagedkv_<ck_trait, ck_tile::gfx11_t>(
+ const ck_tile::stream_config& config, fmha_fwd_pagedkv_args args) {
+ ++calls;
+ last_args = args;
+ last_config = config;
+ switch (mode) {
+ case 0: return 0.0f;
+ case 1: return 0.25f;
+ case 2: return -1.0f;
+ case 3: return -2.0f;
+ case 4: return std::numeric_limits<float>::quiet_NaN();
+ case 5: return std::numeric_limits<float>::infinity();
+ case 6: return -std::numeric_limits<float>::infinity();
+ // CK's HIP_CHECK_ERROR throws std::runtime_error at the host boundary.
+ case 7: throw std::runtime_error("inert HIP launch failure");
+ case 8: throw 7;
+ case 9: return -0.0f;
+ case 10: return -0.5f;
+ default: throw std::runtime_error("bad fixture mode");
+ }
+}
+int main(int argc, char** argv) {
+ if (argc != 9) return 64;
+ mode = std::atoi(argv[1]);
+ const int q_len = std::atoi(argv[2]);
+ const int kv_len = std::atoi(argv[3]);
+ const int pages = std::atoi(argv[4]);
+ const int layout = std::atoi(argv[5]);
+ const int stride = std::atoi(argv[6]);
+ const int null_pointer = std::atoi(argv[7]);
+ const int time_it = std::atoi(argv[8]);
+ int32_t storage = 0;
+ const void* q = null_pointer == 0 ? nullptr : &storage;
+ const void* k = null_pointer == 1 ? nullptr : &storage;
+ const void* v = null_pointer == 2 ? nullptr : &storage;
+ void* out = null_pointer == 3 ? nullptr : &storage;
+ const int32_t* table = null_pointer == 4 ? nullptr : &storage;
+ const int32_t* lengths = null_pointer == 5 ? nullptr : &storage;
+ const float result = ck_pagedkv_forward(
+ q, k, v, out, table, lengths, q_len, kv_len, pages, 0.5f,
+ layout, stride, nullptr, time_it);
+ // Explicit output, not C assert: checks survive Python -O and C++ NDEBUG.
+ std::cout << "{\"result\":\"" << result << "\",\"calls\":" << calls
+ << ",\"time_kernel\":" << last_config.time_kernel_
+ << ",\"null_stream\":" << (last_config.stream_id_ == nullptr)
+ << ",\"log_level\":" << last_config.log_level_
+ << ",\"cold_niters\":" << last_config.cold_niters_
+ << ",\"nrepeat\":" << last_config.nrepeat_
+ << ",\"gpu_timer\":" << last_config.is_gpu_timer_
+ << ",\"pointers_forwarded\":"
+ << (last_args.q_ptr == q && last_args.k_ptr == k &&
+ last_args.v_ptr == v && last_args.o_ptr == out &&
+ last_args.block_table_ptr == table && last_args.seqlen_k_ptr == lengths)
+ << ",\"q_len\":" << last_args.seqlen_q
+ << ",\"kv_len\":" << last_args.seqlen_k
+ << ",\"pages\":" << last_args.batch_stride_block_table
+ << ",\"page_size\":" << last_args.page_block_size
+ << ",\"batch\":" << last_args.batch
+ << ",\"max_seqlen_q\":" << last_args.max_seqlen_q
+ << ",\"hdim_q\":" << last_args.hdim_q
+ << ",\"hdim_v\":" << last_args.hdim_v
+ << ",\"nhead_q\":" << last_args.nhead_q
+ << ",\"nhead_k\":" << last_args.nhead_k
+ << ",\"scale_s\":" << last_args.scale_s
+ << ",\"scale_p\":" << last_args.scale_p
+ << ",\"scale_o\":" << last_args.scale_o
+ << ",\"window_left\":" << last_args.window_size_left
+ << ",\"window_right\":" << last_args.window_size_right
+ << ",\"mask_type\":" << last_args.mask_type
+ << ",\"stride_q\":" << last_args.stride_q
+ << ",\"head_stride_q\":" << last_args.nhead_stride_q
+ << ",\"batch_stride_q\":" << last_args.batch_stride_q
+ << ",\"stride_o\":" << last_args.stride_o
+ << ",\"head_stride_o\":" << last_args.nhead_stride_o
+ << ",\"batch_stride_o\":" << last_args.batch_stride_o
+ << ",\"stride_k\":" << last_args.stride_k
+ << ",\"head_stride_k\":" << last_args.nhead_stride_k
+ << ",\"batch_stride_k\":" << last_args.batch_stride_k
+ << ",\"stride_v\":" << last_args.stride_v
+ << ",\"head_stride_v\":" << last_args.nhead_stride_v
+ << ",\"batch_stride_v\":" << last_args.batch_stride_v
+ << "}\n";
+}
+"""
+
+
+def no_core_dump():
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
+
+
+class ShimBoundaryTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ compiler = shlex.split(os.environ.get("CXX", ""))
+ if not compiler:
+ found = shutil.which("g++") or shutil.which("clang++")
+ if not found:
+ raise unittest.SkipTest("CPU C++ compiler required")
+ compiler = [found]
+ receipt_root = os.environ.get("CK_SHIM_CPU_RECEIPTS")
+ if receipt_root:
+ cls.temporary = None
+ cls.directory = Path(tempfile.mkdtemp(prefix="cpu-shim-", dir=receipt_root))
+ else:
+ cls.temporary = tempfile.TemporaryDirectory(prefix="cpu-shim-")
+ cls.directory = Path(cls.temporary.name)
+ cls.commands = []
+ cls.binaries = {}
+ include = cls.directory / "include"
+ for relative, content in HEADERS.items():
+ path = include / relative
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content)
+ driver = cls.directory / "driver.cpp"
+ driver.write_text(DRIVER.replace("@SHIM@", SHIM.as_posix()))
+ cls.run_command(compiler + ["--version"])
+ for optimization in ("-O0", "-O2"):
+ binary = cls.directory / ("shim" + optimization)
+ cls.run_command(compiler + [
+ "-std=c++17", "-Wall", "-Wextra", "-Werror", optimization, "-Wno-cpp",
+ "-isystem", str(include), str(driver), "-o", str(binary),
+ ])
+ cls.binaries[optimization] = binary
+
+ @classmethod
+ def tearDownClass(cls):
+ if cls.temporary is not None:
+ cls.temporary.cleanup()
+
+ @classmethod
+ def run_command(cls, argv):
+ result = subprocess.run(argv, text=True, capture_output=True, preexec_fn=no_core_dump)
+ cls.commands.append({
+ "argv": [str(item) for item in argv], "returncode": result.returncode,
+ "stdout": result.stdout, "stderr": result.stderr,
+ })
+ (cls.directory / "commands.json").write_text(json.dumps(cls.commands, indent=2) + "\n")
+ if result.returncode:
+ raise AssertionError(
+ f"command failed ({result.returncode}): {argv!r}\n{result.stdout}{result.stderr}"
+ )
+ return result.stdout
+
+ def invoke(self, optimization, *, mode=0, q_len=64, kv_len=257,
+ pages=2, layout=0, stride=192, null_pointer=-1, time_it=0):
+ result = json.loads(self.run_command([
+ str(self.binaries[optimization]), *map(str, (
+ mode, q_len, kv_len, pages, layout, stride, null_pointer, time_it,
+ )),
+ ]))
+ result["result"] = float(result["result"])
+ return result
+
+ def test_success_preserves_layout_arguments_and_timing(self):
+ shapes = [(1, 1, 1), (64, 256, 1), (64, 257, 2), (64, 257, 3),
+ (174762, 174762, 683), (64, 2147483647, 8388608),
+ (64, 257, 2147483647)]
+ for optimization in self.binaries:
+ for q_len, kv_len, pages in shapes:
+ for layout in (0, 1):
+ for mode, time_it, expected in ((0, 0, 1.0), (1, 0, 1.0),
+ (1, 1, 0.25), (9, 0, 1.0)):
+ with self.subTest(optimization=optimization, q_len=q_len,
+ kv_len=kv_len, pages=pages, layout=layout,
+ mode=mode, time_it=time_it):
+ result = self.invoke(
+ optimization, mode=mode, time_it=time_it, q_len=q_len,
+ kv_len=kv_len, pages=pages, layout=layout,
+ )
+ self.assertEqual(result["result"], expected)
+ self.assertEqual(result["calls"], 1)
+ expected_fields = {
+ "time_kernel": time_it, "null_stream": 1,
+ "log_level": 0, "cold_niters": 0, "nrepeat": 1,
+ "gpu_timer": 0, "pointers_forwarded": 1,
+ "q_len": q_len, "kv_len": kv_len, "pages": pages,
+ "page_size": 256, "batch": 1, "max_seqlen_q": q_len,
+ "hdim_q": 192, "hdim_v": 128,
+ "nhead_q": 64, "nhead_k": 4,
+ "scale_s": 0.5, "scale_p": 1.0, "scale_o": 1.0,
+ "window_left": -1, "window_right": 0, "mask_type": 2,
+ "stride_q": 192 if layout else 64 * 192,
+ "head_stride_q": q_len * 192 if layout else 192,
+ "batch_stride_q": q_len * 64 * 192,
+ "stride_o": 192 if layout else 64 * 192,
+ "head_stride_o": q_len * 192 if layout else 192,
+ "batch_stride_o": q_len * 64 * 192,
+ "stride_k": 192, "head_stride_k": 256 * 192,
+ "batch_stride_k": 4 * 256 * 192,
+ "stride_v": 192, "head_stride_v": 256 * 192,
+ "batch_stride_v": 4 * 256 * 192,
+ }
+ for field, value in expected_fields.items():
+ self.assertEqual(result[field], value, field)
+
+ def test_cpp_exceptions_cannot_escape_c_abi(self):
+ for optimization in self.binaries:
+ for mode in (7, 8):
+ for time_it in (0, 1):
+ with self.subTest(optimization=optimization, mode=mode, time_it=time_it):
+ result = self.invoke(optimization, mode=mode, time_it=time_it)
+ self.assertEqual(result["result"], -2.0)
+ self.assertEqual(result["calls"], 1)
+
+ def test_invalid_elapsed_is_execution_error_not_rejection(self):
+ cases = [(mode, time_it) for mode in (2, 3, 4, 5, 6, 10) for time_it in (0, 1)]
+ cases += [(0, 1), (9, 1)]
+ for optimization in self.binaries:
+ for mode, time_it in cases:
+ with self.subTest(optimization=optimization, mode=mode, time_it=time_it):
+ result = self.invoke(optimization, mode=mode, time_it=time_it)
+ self.assertEqual(result["result"], -2.0)
+ self.assertEqual(result["calls"], 1)
+
+ def test_invalid_arguments_reject_before_specialization(self):
+ cases = [{"null_pointer": index} for index in range(6)] + [
+ {"q_len": 0}, {"q_len": -1}, {"q_len": -2147483648},
+ {"kv_len": 63}, {"kv_len": 0}, {"kv_len": -2147483648},
+ {"pages": 0}, {"pages": -1}, {"pages": -2147483648},
+ {"pages": 1}, {"layout": -1}, {"layout": 2},
+ {"stride": 128}, {"stride": 0}, {"stride": -2147483648},
+ # Actual CK stride fields are int32: both layouts must reject a
+ # batch stride that cannot be represented, before multiplication.
+ {"q_len": 174763, "kv_len": 174763, "pages": 683},
+ {"q_len": 174763, "kv_len": 174763, "pages": 683, "layout": 1},
+ {"q_len": 2147483647, "kv_len": 2147483647, "pages": 8388608},
+ {"kv_len": 2147483647, "pages": 8388607},
+ ]
+ for optimization in self.binaries:
+ for case in cases:
+ with self.subTest(optimization=optimization, case=case):
+ result = self.invoke(optimization, **case)
+ self.assertEqual(result["result"], -1.0)
+ self.assertEqual(result["calls"], 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_ck_pagedkv_sparse_memory_cpu.py b/tests/test_ck_pagedkv_sparse_memory_cpu.py
new file mode 100644
index 0000000..d6506d8
--- /dev/null
+++ b/tests/test_ck_pagedkv_sparse_memory_cpu.py
@@ -0,0 +1,275 @@
+"""Stdlib-only regressions for the two MiMo sparse scratch-memory corrections.
+
+Run directly, without pytest/package initialization:
+ python3 -I -S -B tests/test_ck_pagedkv_sparse_memory_cpu.py -v
+
+Only the production page-mean statements and _stage_buffers function are executed,
+with inert tensor/allocator doubles. These tests establish Python call and ownership
+contracts, not framework numerics, device memory peaks, or cross-stream safety.
+Scratch is fully overwritten per accepted call on the existing single-stream path;
+no persistent external views are retained across growth in these tests.
+"""
+
+import ast
+import gc
+from pathlib import Path
+from types import SimpleNamespace
+import unittest
+import weakref
+
+
+_SOURCE = Path(__file__).resolve().parents[1] / "exllamav3/modules/attention_fn"
+
+
+def _function(filename, name):
+ path = _SOURCE / filename
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ functions = [node for node in tree.body
+ if isinstance(node, ast.FunctionDef) and node.name == name]
+ if len(functions) != 1:
+ raise ValueError(f"expected exactly one {name} in {path}")
+ return path, functions[0]
+
+
+def _page_mean_code():
+ path, function = _function("ck_pagedkv_sparse.py", "select_pages")
+ start = next(i for i, node in enumerate(function.body)
+ if isinstance(node, ast.Assign)
+ and any(isinstance(target, ast.Name) and target.id == "kp"
+ for target in node.targets))
+ end = next(i for i, node in enumerate(function.body[start:], start)
+ if isinstance(node, ast.Delete)
+ and any(isinstance(target, ast.Name) and target.id == "kp"
+ for target in node.targets))
+ return compile(ast.Module(body=function.body[start:end + 1], type_ignores=[]),
+ str(path), "exec")
+
+
+class PageMeanMemoryTests(unittest.TestCase):
+ def test_page_mean_uses_fp32_reduction_without_full_prefix_float_copy(self):
+ fp32 = object()
+ physical_pages = object()
+ reduced_mean = object()
+ reductions = []
+
+ class PagePrefix:
+ def float(self):
+ raise AssertionError("full-prefix .float() copy before page mean")
+
+ def mean(self, *, dim, dtype=None):
+ reductions.append((dim, dtype))
+ return reduced_mean
+
+ class Cache:
+ def __getitem__(self, pages):
+ self.pages = pages
+ prefix = PagePrefix()
+ self.prefix_ref = weakref.ref(prefix)
+ return prefix
+
+ cache = Cache()
+ namespace = {"k_cache": cache, "phys": physical_pages,
+ "torch": SimpleNamespace(float32=fp32)}
+ exec(_page_mean_code(), namespace)
+
+ self.assertIs(cache.pages, physical_pages)
+ self.assertEqual(reductions, [(1, fp32)])
+ self.assertIs(namespace["mean_k"], reduced_mean)
+ self.assertNotIn("kp", namespace)
+ gc.collect()
+ self.assertIsNone(cache.prefix_ref(), "gathered prefix must be retired")
+
+
+def _stage_function(allocator):
+ path, function = _function("ck_pagedkv_sparse_qc.py", "_stage_buffers")
+ namespace = {"torch": allocator, "_STAGE": {}}
+ exec(compile(ast.Module(body=[function], type_ignores=[]), str(path), "exec"),
+ namespace)
+ allocator.stages = namespace["_STAGE"]
+ return namespace["_stage_buffers"], namespace["_STAGE"]
+
+
+class _InertTensor:
+ def __init__(self, shape):
+ self.shape = shape
+
+
+class _InertAllocator:
+ half = object()
+
+ def __init__(self):
+ self.calls = []
+ self.allocated_refs = []
+ self.watched_refs: tuple = ()
+ self.fail_at: int | None = None
+ self.stages = {}
+
+ def empty(self, shape, *, dtype, device):
+ # Collect unreachable objects for non-refcounted Python implementations.
+ # Snapshots and allocation records must never own the observed tensors.
+ gc.collect()
+ self.calls.append({"shape": shape, "dtype": dtype, "device": device,
+ "published": device in self.stages,
+ "watched_alive": tuple(ref() is not None
+ for ref in self.watched_refs)})
+ if len(self.calls) == self.fail_at:
+ raise MemoryError("inert second allocation failure")
+ tensor = _InertTensor(shape)
+ self.allocated_refs.append(weakref.ref(tensor))
+ return tensor
+
+
+class StageBufferMemoryTests(unittest.TestCase):
+ def setUp(self):
+ self.allocator = _InertAllocator()
+ self.stage_buffers, self.stages = _stage_function(self.allocator)
+ self.dev = "inert:0"
+ self.vals = 768
+
+ def test_coarse_capacity_grows_in_steps_but_reuses_within_step(self):
+ capacities = []
+ for pages in (2, 3, 32, 33, 63, 64, 65):
+ current = self.stage_buffers(self.dev, pages, self.vals)
+ capacity = current["cap_pages"]
+ capacities.append(capacity)
+ self.assertEqual(current["used_pages"], pages)
+ self.assertEqual(current["vals_per_token"], self.vals)
+ self.assertEqual(current["k"].shape, (capacity * 256, self.vals))
+ self.assertEqual(current["v"].shape, (capacity * 256, self.vals))
+ del current
+ self.assertEqual(capacities, [32, 32, 32, 64, 64, 64, 96])
+ self.assertEqual([call["shape"] for call in self.allocator.calls],
+ [(pages * 256, self.vals) for pages in (32, 64, 96)
+ for _ in range(2)])
+
+ def test_real_qc_caller_passes_physical_bound_and_builds_capacity_identity(self):
+ path, function = _function("ck_pagedkv_sparse_qc.py", "fn_ck_paged_attn_sparse_qc")
+ start = next(i for i, node in enumerate(function.body)
+ if isinstance(node, ast.Assign) and any(
+ isinstance(target, ast.Name) and target.id == "st" for target in node.targets))
+ body = function.body[start:start + 3]
+ calls = []
+ stage = {"k": _InertTensor((40 * 256, self.vals)), "cap_pages": 40, "ident": None}
+
+ def buffers(*args, **kwargs):
+ calls.append((args, kwargs))
+ return stage
+
+ def arange(count, **kwargs):
+ return _InertTensor((count,))
+
+ namespace = dict(_stage_buffers=buffers, dev=self.dev, n_pages_needed=33,
+ vals=self.vals, P=40,
+ torch=SimpleNamespace(arange=arange, int32=object()))
+ exec(compile(ast.Module(body=body, type_ignores=[]), str(path), "exec"), namespace)
+ self.assertEqual(calls, [((self.dev, 33, self.vals), {"max_pages": 40})])
+ self.assertEqual(stage["ident"].shape, (40,))
+
+ def test_physical_capacity_caps_final_step(self):
+ capacities = []
+ for pages in (2, 33, 40):
+ current = self.stage_buffers(self.dev, pages, self.vals, max_pages=40)
+ capacities.append(current["cap_pages"])
+ self.assertEqual(capacities, [32, 40, 40])
+ self.assertEqual(len(self.allocator.calls), 4)
+ with self.assertRaises(ValueError):
+ self.stage_buffers(self.dev, 41, self.vals, max_pages=40)
+ self.assertEqual(len(self.allocator.calls), 4)
+
+ def test_width_change_retires_incompatible_pair(self):
+ self.stage_buffers(self.dev, 2, self.vals)
+ self.allocator.watched_refs = tuple(weakref.ref(self.stages[self.dev][name])
+ for name in ("k", "v"))
+ current = self.stage_buffers(self.dev, 2, 512)
+ self.assertEqual(current["vals_per_token"], 512)
+ self.assertEqual(current["used_pages"], 2)
+ self.assertEqual(current["k"].shape, (32 * 256, 512))
+ self.assertEqual(current["v"].shape, (32 * 256, 512))
+ self.assertEqual(len(self.allocator.calls), 4)
+ for call in self.allocator.calls[2:]:
+ self.assertEqual(call["watched_alive"], (False, False))
+ self.assertFalse(call["published"])
+
+ def test_smaller_physical_cache_retires_oversized_scratch(self):
+ self.stage_buffers(self.dev, 65, self.vals, max_pages=80)
+ current = self.stage_buffers(self.dev, 2, self.vals, max_pages=8)
+ self.assertEqual(current["cap_pages"], 8)
+ self.assertEqual(current["k"].shape, (8 * 256, self.vals))
+ self.assertEqual(len(self.allocator.calls), 4)
+
+ def test_initial_allocation_publishes_only_complete_pair(self):
+ current = self.stage_buffers(self.dev, 2, self.vals)
+ self.assertIs(self.stages[self.dev], current)
+ self.assertEqual(set(current), {"k", "v", "ident", "cap_pages", "used_pages", "vals_per_token"})
+ self.assertIsNone(current["ident"])
+ self.assertEqual(len(self.allocator.calls), 2)
+ for name in ("k", "v"):
+ self.assertEqual(current[name].shape, (32 * 256, self.vals))
+ for call in self.allocator.calls:
+ self.assertEqual(call["shape"], (32 * 256, self.vals))
+ self.assertIs(call["dtype"], self.allocator.half)
+ self.assertEqual(call["device"], self.dev)
+ self.assertFalse(call["published"])
+
+ def test_equal_and_smaller_requests_reuse_pair_and_identity(self):
+ current = self.stage_buffers(self.dev, 3, self.vals)
+ current["ident"] = _InertTensor((32,))
+ identity = current["ident"]
+ for pages in (3, 2, 0):
+ self.assertIs(self.stage_buffers(self.dev, pages, self.vals), current)
+ self.assertIs(current["ident"], identity)
+ self.assertEqual(len(self.allocator.calls), 2)
+
+ def test_growth_retires_old_pair_before_first_replacement_allocation(self):
+ self.stage_buffers(self.dev, 2, self.vals)
+ for pages in (33, 65):
+ self.stages[self.dev]["ident"] = _InertTensor((pages - 1,))
+ self.allocator.watched_refs = tuple(
+ weakref.ref(self.stages[self.dev][name])
+ for name in ("k", "v", "ident"))
+ start = len(self.allocator.calls)
+ current = self.stage_buffers(self.dev, pages, self.vals)
+ self.assertEqual(len(self.allocator.calls) - start, 2,
+ "each boundary crossing must allocate a replacement pair")
+ for call in self.allocator.calls[start:]:
+ self.assertEqual(call["watched_alive"], (False, False, False),
+ "old K/V/identity still reachable during replacement")
+ self.assertFalse(call["published"])
+ self.assertIsNone(current["ident"])
+ del current
+
+ def test_failed_second_allocation_leaves_no_stage_and_retry_succeeds(self):
+ self.stage_buffers(self.dev, 2, self.vals)
+ self.stages[self.dev]["ident"] = _InertTensor((2,))
+ old_refs = tuple(weakref.ref(self.stages[self.dev][name])
+ for name in ("k", "v", "ident"))
+ self.allocator.watched_refs = old_refs
+ start = len(self.allocator.calls)
+ self.allocator.fail_at = start + 2
+ with self.assertRaisesRegex(MemoryError, "inert second allocation failure"):
+ self.stage_buffers(self.dev, 33, self.vals, max_pages=40)
+ gc.collect()
+ self.assertNotIn(self.dev, self.stages,
+ "failed replacement must not publish stale or partial scratch")
+ self.assertEqual(tuple(ref() is not None for ref in old_refs),
+ (False, False, False))
+ self.assertIsNone(self.allocator.allocated_refs[-1](),
+ "unpublished replacement K must not survive failed V")
+ self.assertEqual(len(self.allocator.calls) - start, 2)
+ for call in self.allocator.calls[start:]:
+ self.assertFalse(call["published"])
+ self.assertEqual(call["watched_alive"], (False, False, False))
+
+ self.allocator.fail_at = None
+ current = self.stage_buffers(self.dev, 33, self.vals, max_pages=40)
+ self.assertIs(self.stages[self.dev], current)
+ self.assertIsNone(current["ident"])
+ self.assertEqual(len(self.allocator.calls) - start, 4)
+ for name in ("k", "v"):
+ self.assertEqual(current[name].shape, (40 * 256, self.vals))
+ for call in self.allocator.calls[start + 2:]:
+ self.assertFalse(call["published"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_ck_sparse_cache_cpu.py b/tests/test_ck_sparse_cache_cpu.py
new file mode 100644
index 0000000..bf922ec
--- /dev/null
+++ b/tests/test_ck_sparse_cache_cpu.py
@@ -0,0 +1,529 @@
+"""Stdlib-only sparse cache isolation regressions; no package initialization.
+
+Run directly: python3 -I -S -B tests/test_ck_sparse_cache_cpu.py -v
+The frozen mode helper is loaded by file path. Heavyweight cache modules are
+AST-extracted, executing their actual functions with inert tensor/I/O seams.
+No torch, exllamav3 package, native library, CUDA, or pytest is imported.
+"""
+
+import __future__
+import ast
+from collections import deque
+import hashlib
+import importlib.util
+import os
+from pathlib import Path
+import time
+from types import SimpleNamespace
+from typing import Any
+import unittest
+from unittest.mock import patch
+
+
+_ROOT = Path(__file__).resolve().parents[1]
+_MODE_SOURCE = _ROOT / "exllamav3/util/attention_mode.py"
+
+
+def _mode(**env):
+ if not _MODE_SOURCE.is_file():
+ raise AssertionError("missing frozen attention mode helper")
+ spec = importlib.util.spec_from_file_location("_cache_test_attention_mode", _MODE_SOURCE)
+ if spec is None or spec.loader is None:
+ raise AssertionError("cannot load frozen attention mode helper")
+ module = importlib.util.module_from_spec(spec)
+ with patch.dict(os.environ, env, clear=True):
+ spec.loader.exec_module(module)
+ return module
+
+
+def _extract(relative, names, mode, **seams):
+ """Compile real production definitions, binding only their explicit mode imports."""
+ source = _ROOT / relative
+ tree = ast.parse(source.read_text(encoding="utf-8"), filename=str(source))
+ namespace = dict(seams)
+ for node in tree.body:
+ if isinstance(node, ast.ImportFrom) and node.module and node.module.endswith("attention_mode"):
+ for alias in node.names:
+ namespace[alias.asname or alias.name] = getattr(mode, alias.name)
+ body = []
+ for name in names:
+ parts = name.split(".")
+ scope = tree.body
+ if len(parts) == 2:
+ scope = next(n for n in scope if isinstance(n, ast.ClassDef) and n.name == parts[0]).body
+ node = next(n for n in scope if (
+ isinstance(n, ast.FunctionDef) and n.name == parts[-1]
+ or isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == parts[-1]
+ for t in n.targets)
+ ))
+ if isinstance(node, ast.FunctionDef):
+ node.decorator_list = [] # inert inference_mode/staticmethod boundaries, not method bodies
+ body.append(node)
+ exec(compile(ast.Module(body=body, type_ignores=[]), str(source), "exec",
+ flags=__future__.annotations.compiler_flag), namespace)
+ return SimpleNamespace(**namespace)
+
+
+class _BytesTensor:
+ """Only the CPU byte-view boundary used by the production checksum."""
+ def __init__(self, data):
+ self.data = data
+
+ def numpy(self):
+ return self
+
+ def tobytes(self):
+ return self.data
+
+
+def _checksum(mode):
+ source = "exllamav3/generator/pagetable.py"
+ code = _extract(source, ["_tensor_blake2b_checksum", "tensor_hash_checksum"], mode,
+ hashlib=hashlib)
+ if code.tensor_hash_checksum is not code._tensor_blake2b_checksum:
+ raise AssertionError("cache callers no longer use the tested production checksum")
+ return code.tensor_hash_checksum
+
+
+class _Ids:
+ def __init__(self, values):
+ self.values = tuple(values)
+ self.shape = (1, len(self.values))
+
+ def __getitem__(self, index):
+ return _Ids(self.values[index])
+
+ def clone(self):
+ return _Ids(self.values)
+
+ def cpu(self):
+ return self
+
+ def numel(self):
+ return len(self.values)
+
+ def copy_(self, other, **kwargs):
+ self.values = other.values
+
+
+class _Rows:
+ """Inert page-dimension cache tensor: observe real save/restore copy calls."""
+ dtype = "inert-cache-dtype"
+ device = "inert-device"
+
+ def __init__(self, rows):
+ self.rows = [_Ids(row) for row in rows]
+ self.shape = (len(self.rows), 2)
+
+ def index_select(self, dimension, indices):
+ if dimension != 0:
+ raise AssertionError("unexpected cache dimension")
+ return _Rows(self.rows[i].values for i in indices)
+
+ def cpu(self):
+ return self
+
+ def __getitem__(self, index):
+ return self.rows[index]
+
+
+class _Page:
+ def __init__(self, table, phash, ids, complete):
+ self.table = table
+ self.phash = phash
+ self.page_index = 0
+ self.prev_hash = None
+ self.ref_count = 0
+ self.sequence = _Ids(ids)
+ self.kv_position = 256 if complete else 0
+
+ def add_ref_clear(self, serial, phash):
+ self.table.events.append("inject-page")
+ del self.table.unreferenced_pages[self.phash]
+ self.phash = phash
+ self.ref_count = 1
+ self.table.referenced_pages[phash] = self
+
+ def sub_ref(self):
+ self.ref_count = 0
+ del self.table.referenced_pages[self.phash]
+ self.table.unreferenced_pages[self.phash] = self
+
+
+class _PageTable:
+ def __init__(self, phash, ids, complete):
+ self.events = []
+ self.access_serial = 0
+ self.referenced_pages = {}
+ self.page = _Page(self, phash, ids, complete)
+ self.unreferenced_pages = {phash: self.page}
+
+ def build_eviction_order(self, protected):
+ self.events.append("eviction-order")
+ return deque(p for h, p in self.unreferenced_pages.items() if h not in protected)
+
+ def evict(self, page, protected):
+ self.events.append("evict")
+
+
+class _SlotFixture:
+ """Actual SlotStore methods; only framework, storage and page boundaries inert."""
+ def __init__(self, mode, resident=False, payload=None):
+ self.payload: Any = payload
+ self.events = []
+ self.cache = _Rows([(31, 32)] if resident else [(0, 0)])
+ self.phash = _checksum(mode)(_BytesTensor(b"resident token page"), None)
+ self.table = _PageTable(self.phash if resident else b"empty-placeholder",
+ range(256) if resident else [0] * 256, resident)
+ generator = SimpleNamespace(pagetable=self.table, recurrent_cache=None,
+ tail_ckpts=[], tail_ckpt_max=1)
+ torch = SimpleNamespace(load=self._load, save=self._save,
+ cuda=SimpleNamespace(synchronize=lambda: self.events.append("sync")),
+ tensor=lambda values, **kwargs: values, long="inert-long")
+ paths = SimpleNamespace(expanduser=os.path.expanduser, basename=os.path.basename,
+ join=os.path.join, getsize=lambda _: 1)
+ io = SimpleNamespace(path=paths, replace=lambda *args: self.events.append("replace"))
+ code = _extract("exllamav3/generator/slot_store.py", ["FORMAT_VERSION", "FORMAT_VERSION_TAIL",
+ "FORMAT_VERSION_SPARSE", "FORMAT_VERSION_SPARSE_TAIL",
+ "SlotStore.__init__", "SlotStore._path", "SlotStore.save", "SlotStore.restore"],
+ mode, torch=torch, os=io, time=time, PAGE_SIZE=256)
+ cls = type("ExtractedSlotStore", (), {name: getattr(code, name)
+ for name in ("__init__", "_path", "save", "restore")})
+ self.slot: Any = cls(generator, [self.cache], "/inert/slots", "inert-model")
+ self.slot.ids = _Ids(range(256) if resident else [99])
+ self.slot.prompt = "saved prompt" if resident else "old prompt"
+ self.slot._resident_chain = lambda: ([self.phash], [self.table.page]) if resident else ([], [])
+ self.slot._tensors = self._tensors
+ self.slot._restore_tail = self._restore_tail
+
+ def _save(self, payload, path):
+ self.events.append("save-payload")
+ self.payload = payload
+
+ def _load(self, path, **kwargs):
+ self.events.append("load-payload")
+ return self.payload
+
+ def _tensors(self):
+ self.events.append("tensors")
+ return [self.cache]
+
+ def _restore_tail(self, *args):
+ raise AssertionError("foreign tail reached restore")
+
+
+def _sparse(retain="0.5", min_sk="0"):
+ return _mode(EXL3_CK_PAGEDKV="sparse", EXL3_CK_SPARSE_RETAIN=retain,
+ EXL3_CK_MIN_SK=min_sk)
+
+
+class FrozenModeTests(unittest.TestCase):
+ def test_mode_captures_sparse_policy_at_import_not_at_use(self):
+ cases = [
+ ({}, False, 0.5, 0),
+ ({"EXL3_CK_PAGEDKV": "dense"}, False, 0.5, 0),
+ ({"EXL3_CK_PAGEDKV": "SPARSE"}, True, 0.5, 0),
+ ({"EXL3_CK_PAGEDKV": "sparse", "EXL3_CK_SPARSE_RETAIN": "0.25",
+ "EXL3_CK_MIN_SK": "4096"}, True, 0.25, 4096),
+ ]
+ for env, enabled, retain, min_sk in cases:
+ with self.subTest(env=env):
+ mode = _mode(**env)
+ self.assertIs(mode.CK_SPARSE_ENABLED, enabled)
+ self.assertEqual(mode.CK_SPARSE_RETAIN, retain)
+ self.assertEqual(mode.CK_SPARSE_MIN_SK, min_sk)
+ marker = mode.ATTENTION_CACHE_MODE
+ self.assertEqual(marker is not None, enabled)
+ with patch.dict(os.environ, {
+ "EXL3_CK_PAGEDKV": "normal" if enabled else "sparse",
+ "EXL3_CK_SPARSE_RETAIN": "0.75", "EXL3_CK_MIN_SK": "8192",
+ }, clear=True):
+ self.assertIs(mode.CK_SPARSE_ENABLED, enabled)
+ self.assertEqual(mode.CK_SPARSE_RETAIN, retain)
+ self.assertEqual(mode.CK_SPARSE_MIN_SK, min_sk)
+ self.assertEqual(mode.ATTENTION_CACHE_MODE, marker)
+
+ def test_normal_ignores_invalid_sparse_only_settings(self):
+ for value in ("", "dense", "0", "sparse "):
+ with self.subTest(value=value):
+ mode = _mode(EXL3_CK_PAGEDKV=value, EXL3_CK_SPARSE_RETAIN="invalid",
+ EXL3_CK_MIN_SK="invalid")
+ self.assertIs(mode.CK_SPARSE_ENABLED, False)
+ self.assertIsNone(mode.ATTENTION_CACHE_MODE)
+
+ def test_sparse_marker_identifies_effective_retain_and_min_sk(self):
+ normal = _mode().ATTENTION_CACHE_MODE
+ sparse = _sparse().ATTENTION_CACHE_MODE
+ self.assertNotEqual(sparse, normal)
+ self.assertIsInstance(sparse, str)
+ self.assertEqual(sparse, _sparse(retain="0.50", min_sk="00").ATTENTION_CACHE_MODE)
+ self.assertNotEqual(sparse, _sparse(retain="0.25").ATTENTION_CACHE_MODE)
+ self.assertNotEqual(sparse, _sparse(min_sk="4096").ATTENTION_CACHE_MODE)
+
+
+class PageChecksumTests(unittest.TestCase):
+ def test_normal_checksum_is_exact_legacy_root_and_chain(self):
+ checksum = _checksum(_mode())
+ first = _BytesTensor(b"\x01\x00\x02\x00")
+ second = _BytesTensor(b"\x03\x00\x04\x00")
+ root = hashlib.blake2b(first.data, digest_size=16).digest()
+ self.assertEqual(checksum(first, None), root)
+ child = hashlib.blake2b(root + second.data, digest_size=16).digest()
+ self.assertEqual(checksum(second, root), child)
+ self.assertEqual(checksum(first, b""), root)
+
+ def test_sparse_salts_actual_root_and_inherits_isolation_through_chain(self):
+ modes = [_mode(), _sparse(), _sparse(retain="0.25"), _sparse(min_sk="4096")]
+ first, second = _BytesTensor(b"same token ids"), _BytesTensor(b"next token ids")
+ roots, children = [], []
+ for mode in modes:
+ checksum = _checksum(mode)
+ root = checksum(first, None)
+ roots.append(root)
+ child = checksum(second, root)
+ children.append(child)
+ self.assertEqual(child, hashlib.blake2b(root + second.data, digest_size=16).digest())
+ self.assertEqual(checksum(first, None), root)
+ self.assertEqual(len(set(roots)), len(modes), "normal/sparse/retain/min-sk roots must not alias")
+ self.assertEqual(len(set(children)), len(modes), "isolation must propagate along the real hash chain")
+ equivalent = _checksum(_sparse(retain="0.50"))
+ self.assertEqual(equivalent(first, None), roots[1])
+ self.assertEqual(equivalent(second, roots[1]), children[1])
+
+ def test_env_flip_cannot_switch_checksum_mode(self):
+ tensor = _BytesTensor(b"same ids after a runtime environment change")
+ for mode in (_mode(), _sparse(retain="0.25", min_sk="4096")):
+ with self.subTest(marker=mode.ATTENTION_CACHE_MODE):
+ checksum = _checksum(mode)
+ expected = checksum(tensor, None)
+ with patch.dict(os.environ, {"EXL3_CK_PAGEDKV": "sparse" if not mode.CK_SPARSE_ENABLED else "",
+ "EXL3_CK_SPARSE_RETAIN": "0.75", "EXL3_CK_MIN_SK": "8192"}, clear=True):
+ self.assertEqual(checksum(tensor, None), expected)
+ self.assertEqual(_checksum(mode)(tensor, None), expected)
+
+
+class SlotPersistenceTests(unittest.TestCase):
+ def test_sparse_save_is_unreadable_by_legacy_normal_readers(self):
+ source = _SlotFixture(_sparse(), resident=True)
+ source.slot.save("sparse.pt")
+ # Legacy SlotStore.restore accepts only v1/v2 and ignores unknown fields.
+ # A marker alone is insufficient: use an incompatible sparse version too.
+ self.assertNotIn(source.payload["version"], (1, 2),
+ "legacy normal readers must reject sparse session files")
+
+ def test_save_persists_frozen_mode_in_the_actual_payload(self):
+ for mode in (_mode(), _sparse(), _sparse(retain="0.25", min_sk="4096")):
+ with self.subTest(marker=mode.ATTENTION_CACHE_MODE):
+ with patch.dict(os.environ, {"EXL3_CK_PAGEDKV": "" if mode.CK_SPARSE_ENABLED else "sparse",
+ "EXL3_CK_SPARSE_RETAIN": "0.75", "EXL3_CK_MIN_SK": "8192"}, clear=True):
+ source = _SlotFixture(mode, resident=True)
+ result = source.slot.save("session.pt")
+ self.assertEqual(result["n_saved"], 256)
+ self.assertIn("attention_mode", source.payload)
+ self.assertEqual(source.payload["attention_mode"], mode.ATTENTION_CACHE_MODE)
+ self.assertEqual(source.payload["hashes"], [source.phash])
+ self.assertEqual(source.payload["tensors"][0][0].values, (31, 32))
+
+ def test_same_mode_save_restore_reuses_the_actual_page(self):
+ pairs = [(_mode(), _mode()), (_sparse(), _sparse(retain="0.50", min_sk="00")),
+ (_sparse(retain="0.25", min_sk="4096"), _sparse(retain="0.25", min_sk="4096"))]
+ for saved_mode, restored_mode in pairs:
+ with self.subTest(marker=saved_mode.ATTENTION_CACHE_MODE):
+ source = _SlotFixture(saved_mode, resident=True)
+ source.slot.save("session.pt")
+ with patch.dict(os.environ, {"EXL3_CK_PAGEDKV": "" if restored_mode.CK_SPARSE_ENABLED else "sparse",
+ "EXL3_CK_SPARSE_RETAIN": "0.75", "EXL3_CK_MIN_SK": "8192"}, clear=True):
+ target = _SlotFixture(restored_mode, payload=source.payload)
+ result = target.slot.restore("session.pt")
+ self.assertEqual(result["n_restored"], 256)
+ self.assertEqual(result["n_read"], 256)
+ self.assertEqual(target.table.page.phash, source.phash)
+ self.assertEqual(target.table.page.sequence.values, tuple(range(256)))
+ self.assertEqual(target.cache[0].values, (31, 32))
+ self.assertEqual(target.table.page.kv_position, 256)
+ self.assertEqual(target.slot.prompt, "saved prompt")
+ self.assertEqual(target.slot.ids.values, tuple(range(256)))
+ self.assertEqual(target.table.events.count("inject-page"), 1)
+ result = target.slot.restore("session.pt")
+ self.assertEqual(result["n_read"], 0, "resident equal-mode page should be reused, not injected again")
+ self.assertEqual(target.table.events.count("inject-page"), 1)
+
+ def test_same_mode_tail_save_restore_and_legacy_tail_acceptance(self):
+ for mode, version in ((_mode(), 2), (_sparse(), 4)):
+ with self.subTest(mode=mode.ATTENTION_CACHE_MODE):
+ source = _SlotFixture(mode, resident=True)
+ source.slot.generator.recurrent_cache = SimpleNamespace(settle=lambda: None, get=lambda _: None)
+ tail_ids = _Ids(range(17))
+ entry = dict(ids=tail_ids, page=source.table.page, stashed={}, carry=None)
+ source.slot._find_tail = lambda hashes: (0, entry)
+ source.slot.save("tail.pt")
+ self.assertEqual(source.payload["version"], version)
+ self.assertEqual(source.payload["hashes"], [])
+ self.assertEqual(source.payload["tail"]["ids"].values, tuple(range(17)))
+ payload = dict(source.payload)
+ if version == 2:
+ payload.pop("attention_mode") # old ordinary tail files had no marker
+ target = _SlotFixture(mode, payload=payload)
+ injected = []
+ target.slot._restore_tail = lambda *args: injected.append(args)
+ result = target.slot.restore("tail.pt")
+ self.assertEqual(result["n_restored"], 17)
+ self.assertEqual(len(injected), 1)
+ self.assertIs(injected[0][0], payload["tail"])
+ self.assertIsNone(injected[0][1])
+ self.assertEqual(target.slot.ids.values, tuple(range(17)))
+
+ def test_mismatched_mode_is_rejected_before_tensors_or_any_injection(self):
+ modes = [_mode(), _sparse(), _sparse(retain="0.25"), _sparse(min_sk="4096")]
+ for saved_mode in modes:
+ source = _SlotFixture(saved_mode, resident=True)
+ source.slot.save("session.pt")
+ # Supply the intended marker explicitly so a missing save field cannot hide a broken restore guard.
+ payload = dict(source.payload, attention_mode=saved_mode.ATTENTION_CACHE_MODE)
+ for restored_mode in modes:
+ if restored_mode.ATTENTION_CACHE_MODE == saved_mode.ATTENTION_CACHE_MODE:
+ continue
+ for version in ((1, 2) if saved_mode.ATTENTION_CACHE_MODE is None else (3, 4)):
+ with self.subTest(saved=saved_mode.ATTENTION_CACHE_MODE,
+ restored=restored_mode.ATTENTION_CACHE_MODE, version=version):
+ data = dict(payload, version=version)
+ if version in (2, 4):
+ data["tail"] = {"inert": "foreign prompt-end checkpoint"}
+ target = _SlotFixture(restored_mode, payload=data)
+ with self.assertRaisesRegex(ValueError, "attention mode|slot file is for"):
+ target.slot.restore("session.pt")
+ self.assertEqual(target.events, ["load-payload"])
+ self.assertEqual(target.table.events, [])
+ self.assertEqual(target.cache[0].values, (0, 0))
+ self.assertEqual(target.table.page.kv_position, 0)
+ self.assertEqual(target.slot.prompt, "old prompt")
+ self.assertEqual(target.slot.ids.values, (99,))
+
+ def test_missing_marker_is_legacy_normal_and_only_reusable_in_normal_mode(self):
+ source = _SlotFixture(_mode(), resident=True)
+ source.slot.save("legacy.pt")
+ data = dict(source.payload)
+ data.pop("attention_mode", None)
+ target = _SlotFixture(_mode(), payload=data)
+ self.assertEqual(target.slot.restore("legacy.pt")["n_read"], 256)
+ self.assertEqual(target.cache[0].values, (31, 32))
+ sparse = _SlotFixture(_sparse(), payload=data)
+ with self.assertRaisesRegex(ValueError, "attention mode|slot file is for"):
+ sparse.slot.restore("legacy.pt")
+ self.assertEqual(sparse.events, ["load-payload"])
+ self.assertEqual(sparse.table.events, [])
+
+ def test_mode_guard_also_protects_tail_only_payloads_without_a_root_hash(self):
+ for saved_mode, restored_mode in ((_mode(), _sparse()), (_sparse(), _mode())):
+ with self.subTest(saved=saved_mode.ATTENTION_CACHE_MODE):
+ payload = {"version": 2 if saved_mode.ATTENTION_CACHE_MODE is None else 4,
+ "model_id": "inert-model", "hashes": [], "tensors": [],
+ "stash": None, "tail": {"inert": "rootless foreign tail"},
+ "attention_mode": saved_mode.ATTENTION_CACHE_MODE}
+ target = _SlotFixture(restored_mode, payload=payload)
+ with self.assertRaisesRegex(ValueError, "attention mode|slot file is for"):
+ target.slot.restore("tail.pt")
+ self.assertEqual(target.events, ["load-payload"])
+ self.assertEqual(target.table.events, [])
+
+
+class _IndexDisk:
+ """In-memory stand-in for namespace-directory selection, not its composition."""
+ def __init__(self, root, ns, shared):
+ self.root = root
+ self.ns = ns
+ self.entries_by_name = shared.setdefault(ns, {})
+ self.removed = []
+
+ def entries(self):
+ return sorted(self.entries_by_name)
+
+ def read_idx(self, name):
+ return self.entries_by_name[name]
+
+ def remove(self, name):
+ self.removed.append(name)
+ del self.entries_by_name[name]
+
+
+def _prefix(mode, shared=None, extra="") -> tuple[Any, Any]:
+ shared = {} if shared is None else shared
+ namespace = _extract("exllamav3/util/disk_store.py", ["namespace"], mode,
+ hashlib=hashlib).namespace
+ slots = SimpleNamespace(_tensors=lambda: [_Rows([(0, 0)])])
+ code = _extract("exllamav3/generator/prefix_disk.py", ["FORMAT", "PagedPrefixDisk.__init__",
+ "PagedPrefixDisk.load_index"], mode, namespace=namespace,
+ DiskStore=lambda root, ns: _IndexDisk(root, ns, shared), env_dir=lambda: "/inert/env-root")
+ cls = type("ExtractedPagedPrefixDisk", (), {name: getattr(code, name) for name in ("__init__", "load_index")})
+ return cls(slots, root="/inert/cache", model_id="inert-model", extra=extra), namespace
+
+
+class PrefixNamespaceTests(unittest.TestCase):
+ def test_normal_namespace_is_exact_legacy_composition(self):
+ mode = _mode(EXL3_CK_PAGEDKV="dense", EXL3_CK_SPARSE_RETAIN="invalid", EXL3_CK_MIN_SK="invalid")
+ for extra in ("", "caller-specific-tag"):
+ with self.subTest(extra=extra):
+ prefix, namespace = _prefix(mode, extra=extra)
+ expected = namespace("paged1", "inert-model", [((2,), "inert-cache-dtype")], extra)
+ self.assertEqual(prefix.ns, expected)
+ self.assertEqual(prefix.disk.ns, expected)
+ self.assertEqual(prefix.disk.root, "/inert/cache")
+
+ def test_sparse_namespace_separates_each_state_affecting_policy(self):
+ modes = [_mode(), _sparse(), _sparse(retain="0.25"), _sparse(min_sk="4096")]
+ namespaces = [_prefix(mode)[0].ns for mode in modes]
+ self.assertEqual(len(set(namespaces)), len(modes), "normal/sparse/retain/min-sk disk namespaces must not alias")
+ self.assertEqual(_prefix(_sparse(retain="0.50", min_sk="00"))[0].ns, namespaces[1])
+ for mode, ns in zip(modes[1:], namespaces[1:]):
+ prefix, namespace = _prefix(mode)
+ self.assertEqual(prefix.ns, namespace("paged1", "inert-model", [((2,), "inert-cache-dtype")], "",
+ mode.ATTENTION_CACHE_MODE))
+ self.assertEqual(ns, prefix.disk.ns)
+
+ def test_equal_mode_loads_existing_index_but_other_modes_cannot_see_it(self):
+ shared = {}
+ modes = [_mode(), _sparse(), _sparse(retain="0.25"), _sparse(min_sk="4096")]
+ for i, mode in enumerate(modes):
+ prefix, _ = _prefix(mode, shared)
+ prefix.disk.entries_by_name[f"segment-{i}"] = {
+ "ns": prefix.ns, "k": "seg", "hashes": [bytes([i]) * 16]}
+ prefix.disk.entries_by_name[f"stash-{i}"] = {
+ "ns": prefix.ns, "k": "stash", "anchor": bytes([i]) * 16, "depth": 1}
+ prefix.disk.entries_by_name[f"rootless-tail-{i}"] = {
+ "ns": prefix.ns, "k": "tail", "prev": None, "pages": 0}
+ for i, mode in enumerate(modes):
+ with self.subTest(marker=mode.ATTENTION_CACHE_MODE):
+ prefix, _ = _prefix(mode, shared)
+ self.assertEqual(prefix.pages, {bytes([i]) * 16: (f"segment-{i}", 0)})
+ self.assertEqual(prefix.stashes, {bytes([i]) * 16: (f"stash-{i}", 1)})
+ self.assertEqual(list(prefix.tails), [f"rootless-tail-{i}"])
+ self.assertEqual(prefix.disk.removed, [])
+
+ def test_foreign_index_namespace_is_rejected_in_both_directions(self):
+ modes = [_mode(), _sparse(), _sparse(retain="0.25"), _sparse(min_sk="4096")]
+ for source_mode in modes:
+ source, _ = _prefix(source_mode)
+ for target_mode in modes:
+ if source_mode.ATTENTION_CACHE_MODE == target_mode.ATTENTION_CACHE_MODE:
+ continue
+ with self.subTest(saved=source_mode.ATTENTION_CACHE_MODE, target=target_mode.ATTENTION_CACHE_MODE):
+ prefix, _ = _prefix(target_mode)
+ prefix.disk.entries_by_name["foreign-page"] = {"ns": source.ns, "k": "seg", "hashes": [b"hash"]}
+ prefix.disk.entries_by_name["foreign-tail"] = {"ns": source.ns, "k": "tail", "prev": None}
+ self.assertEqual(prefix.load_index(), 0)
+ self.assertEqual(prefix.pages, {})
+ self.assertEqual(prefix.tails, {})
+ self.assertEqual(prefix.disk.removed, ["foreign-page", "foreign-tail"])
+
+ def test_env_flip_cannot_create_a_different_mode_disk_session(self):
+ for mode in (_mode(), _sparse(retain="0.25", min_sk="4096")):
+ with self.subTest(marker=mode.ATTENTION_CACHE_MODE):
+ expected, _ = _prefix(mode)
+ with patch.dict(os.environ, {"EXL3_CK_PAGEDKV": "" if mode.CK_SPARSE_ENABLED else "sparse",
+ "EXL3_CK_SPARSE_RETAIN": "0.75", "EXL3_CK_MIN_SK": "8192"}, clear=True):
+ new_session, _ = _prefix(mode)
+ self.assertEqual(new_session.ns, expected.ns)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/mimo/serve.py b/tools/mimo/serve.py
index 99a8e76..9f4239f 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -1075,7 +1075,9 @@ def main() -> None:
vision=not args.no_vision)
from exllamav3.generator.slot_store import SlotStore
engine.slot_store = SlotStore(engine.generator, [c for c in (engine.cache, engine.draft_cache) if c is not None],
- args.slot_save_path, args.model_id)
+ args.slot_save_path,
+ # EXL3_CK_PAGEDKV=sparse prefill writes approximate K/V: its slot files never mix with exact ones
+ args.model_id + ("+ck-sparse" if os.environ.get("EXL3_CK_PAGEDKV", "").lower() == "sparse" else ""))
template = Path(args.chat_template or DEFAULT_TEMPLATE).expanduser().read_text(encoding="utf-8")
if engine.supports_vision: # the first tower pass pays kernel setup and allocator growth: not on the first user image
from PIL import Image
diff --git a/tools/strix_halo/build_ck_pagedkv.sh b/tools/strix_halo/build_ck_pagedkv.sh
new file mode 100755
index 0000000..fa7a415
--- /dev/null
+++ b/tools/strix_halo/build_ck_pagedkv.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+# Build the optional gfx1151 MiMo d192 paged-KV backend, never in the donor tree.
+# No implicit fetch, environment sourcing, device probe, native load or install.
+# EXL3_CK_SOURCE is a read-only local Git donor; dirty worktree bytes are ignored.
+# EXL3_CK_CACHE must be a new or matching builder-owned directory, disjoint from it.
+set -euo pipefail
+SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
+exec /usr/bin/python3 -I -S "$SCRIPT_DIR/ck_pagedkv_build.py" "$@"
diff --git a/tools/strix_halo/ck_cold128/README.md b/tools/strix_halo/ck_cold128/README.md
new file mode 100644
index 0000000..9ab7458
--- /dev/null
+++ b/tools/strix_halo/ck_cold128/README.md
@@ -0,0 +1,67 @@
+# Derived public cold128K recipe
+
+This is a new, path-parameterized helper, not the literal private runner used for the retained measurements. Its default invocation only prints a plan. The seven standard-library tests exercise planning, prompt-preparation normalization/re-exec with a changed HOME and inert execve/tokenizer entry, exact-length synthetic fitting with an inert tokenizer, actual native/API response validation, per-arm environment, a real detached-child SIGTERM/reap path, and the actual run-leg receipt path with a tiny process and synthetic HTTP/native fixtures. No test result in this directory is a model performance result.
+
+The quoted-tilde/private-HOME repair passed independent source review. The actual selected-venv tokenizer/template preparation generated five new synthetic prompts of exactly 131,079 rendered tokens, followed by a completed twelve-leg full-model execution of these helper bytes. A separate frozen receipt reader replayed all twelve legs/four brackets and verified selected source/native/CK inputs and weight-file stat identities after process exit. The supervisor exited normally and the parent separately observed process/cgroup/port/compute-owner/GPU-idle release before the next experiment. This public copy is byte-identical to that executed helper and test source; it is not a separate model run at the copy path.
+
+In that public-synthetic FP16 cold128K screen, descriptive native prefill rates were 426.1108 tok/s for stock Triton and 709.2824 tok/s for sparse CK at retention 0.30 (tokens divided by median duration across eight stock and four candidate legs). Median paired gain was 66.57266%, four of four brackets won, and median identical-control spread was 0.42556%. These are this run's rates, not guaranteed reproduction targets or a transfer of historical private-prompt results. Selected API text, choosing nonempty user content before reasoning fallback, matched between the repeated stock controls in all four brackets; sparse differed in three. That comparison is not full stored decoded-text/token/logit equality or a quality grade. See [results and limitations](../../../doc/ck_cold128_results.md).
+
+The workload is newly generated public synthetic text. It contains no retained user prompts or completions and does not reconstruct the original prompt bytes. Settings match the clean PR122 screen class: FP16 K/V, capacity 163840, prefill chunks 4096, 131079 tokens after the real chat template, 64 greedy generated tokens, no drafter, sparse retention 0.30. Retention is an approximate attention setting, not a general quality approval or a physical cache-memory saving. `reasoning_effort='none'` suppresses the medium-effort system instruction; it does not disable thinking.
+
+## Inputs
+
+Use an already-built Python 3.12 ROCm Kyojin environment on gfx1151. Select the checkout containing the optional CK feature, its matching official native extension, the separately built CK library and the MiMo EXL3 pack. This helper does not install, fetch or rebuild the official engine extension. Ordinary per-kernel JIT is permitted during the discarded full-depth warmup.
+
+The example paths below are placeholders. Keep source, model, native, CK library, prompt directory, preparation directory and result directory disjoint as checked by the helper. Prompt/result roots must not already exist. The prompt preparation sibling `.public-prompts-prep` is also fresh/no-overwrite. A failed attempt is retained; choose a new prompt/output name for a retry.
+
+```bash
+PYTHON=/path/to/kyojin/.venv/bin/python
+SOURCE=/path/to/kyojin
+NATIVE=/path/to/matching/exllamav3_ext.cpython-312-x86_64-linux-gnu.so
+CK=/path/to/ck-cache/libck_pagedkv.so
+MODEL=/path/to/mimo-exl3
+PROMPTS=/path/to/new/public-prompts
+RESULTS=/path/to/new/public-results
+
+COMMON=(--source "$SOURCE" --native "$NATIVE" --ck "$CK" --model "$MODEL"
+ --python "$PYTHON" --prompts "$PROMPTS" --out "$RESULTS")
+
+# Inert plan, including all four control/candidate/control2 brackets.
+python3 cold128.py "${COMMON[@]}"
+
+# Explicit tokenizer/template preparation. Imports the selected already-built
+# engine, but allocates no model weights and sends no inference request.
+python3 cold128.py "${COMMON[@]}" --make-prompts
+
+# Explicit full-model benchmark. Run detached/supervised so a client-terminal
+# lifetime cannot cancel multi-minute inference. Never overlap another scored
+# GPU workload, NPU execution, compilation or heavy CPU/IO activity.
+python3 cold128.py "${COMMON[@]}" --execute
+```
+
+No clocks, firmware, driver, power policy, services or boot settings are changed. The caller owns the measurement window. The helper requires no other GPU/NPU compute owner and GPU idle at each launch, checks policy consistency, and refuses an occupied loopback port. It terminates and reaps only its own child, then records closed port, compute owners and GPU idle. SIGTERM unwinds cleanup; SIGKILL/power-loss cleanup is not guaranteed. Waiting heartbeats do not impose an overall benchmark deadline.
+
+## What is measured
+
+Each of twelve legs launches a fresh server with private writable runtime caches. It runs one full-depth unscored warmup and one distinct measured prompt, proving different first cache pages and zero native cached tokens on both requests. All three arms within a bracket use exactly the same measured prompt. Input source hashes, model metadata hashes and weight-file stat identities are captured before launch and checked between legs; weights are not bulk-hashed. This is ordinary cooperative experimental binding, not an adversarial sandbox or complete transitive toolchain authentication.
+
+Control and control2 use stock Triton dispatch with CK absent. Candidate installs sparse CK before import and must report actual measured page-dropping deltas plus the selected CK library mapping. The historical local dense control used FullK CK instead of stock Triton; its result is a separate contrast and cannot be transferred to this run.
+
+Primary time is the engine's native `time_prefill` in seconds, cross-checked against Chat Completions `prompt_ms`, counts and rate. It is a host-observed engine prefill interval ending before the first regular generation forward, not HTTP TTFT and not pure GPU kernel time. HTTP wall time is retained separately. Raw response bytes, full stored model text, native counters, per-request sparse counters, environment, logs, maps, cleanup and bracket results remain under RESULTS.
+
+For each bracket:
+
+ base = (control_s + control2_s) / 2
+ gain_percent = 100 * (base / candidate_s - 1)
+ spread_percent = abs(100 * (control_s / control2_s - 1))
+
+The screen gate requires all four valid brackets, four wins, median paired gain greater than 2%, and gain greater than median identical-control spread. Descriptive rates use tokens divided by median native duration and are not the median paired gain. COMPLETE means measurement completed; inspect `screen_gate` rather than treating completion as success. Instrument/engagement/cleanup failures are separate from a valid negative screen. Exact text differences are retained; they are not a calibrated quality score, and no default-enablement or broad quality adoption follows.
+
+## Tests
+
+```bash
+python3 -I -S -B test_cold128.py
+python3 -I -S -B -O test_cold128.py
+```
+
+The test fixtures deliberately use synthetic data and cannot report model speed. Their real subprocess tests open no accelerator devices and signal only children they created.
diff --git a/tools/strix_halo/ck_cold128/cold128.py b/tools/strix_halo/ck_cold128/cold128.py
new file mode 100644
index 0000000..7ba373d
--- /dev/null
+++ b/tools/strix_halo/ck_cold128/cold128.py
@@ -0,0 +1,690 @@
+#!/usr/bin/env python3
+"""Derived public cold128K recipe, not the literal measured private runner.
+
+Default: print a plan; no framework imports. --make-prompts uses the selected
+checkout's tokenizer/template but never loads model weights. --execute runs four
+fresh-server control/candidate/control2 brackets on previously generated prompts.
+Only the selected --python interpreter may perform either explicit operation.
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import sys
+
+
+CAPACITY = 163840
+CHUNK = 4096
+TOKENS = 131079
+BUDGET = 64
+
+
+def need(ok, message):
+ if not ok:
+ raise ValueError(message)
+
+
+def parser():
+ p = argparse.ArgumentParser(description=__doc__, allow_abbrev=False)
+ modes = p.add_mutually_exclusive_group()
+ modes.add_argument('--make-prompts', action='store_true')
+ modes.add_argument('--execute', action='store_true')
+ for key in ('source', 'native', 'ck', 'model', 'python', 'prompts', 'out'):
+ p.add_argument('--' + key, type=Path, required=True)
+ p.add_argument('--port', type=int, default=18748)
+ p.add_argument('--seed', type=int, default=1282026)
+ p.add_argument('--worker', type=int, choices=range(12), help=argparse.SUPPRESS)
+ return p
+
+
+def make_plan(a):
+ need(1024 <= a.port <= 65535, 'invalid port')
+ def path(name):
+ return str(getattr(a, name).expanduser().absolute())
+ brackets = []
+ for pair in range(4):
+ brackets.append([dict(arm=arm, pair=pair,
+ prompt=str(Path(path('prompts')) / f'measured-{pair}.txt'),
+ tag=f'pair{pair}-{arm}')
+ for arm in ('control', 'candidate', 'control2')])
+ return dict(status='PLANNED_NOT_EXECUTED', cache_bits=[16, 16], capacity=CAPACITY,
+ chunk_size=CHUNK, prompt_tokens=TOKENS, generated_token_budget=BUDGET,
+ retention=0.3, drafter=False, reasoning_effort='none',
+ thinking='Template none omits medium effort instruction; not thinking-disabled',
+ source=path('source'), native=path('native'), ck=path('ck'), model=path('model'),
+ python=path('python'), prompts=path('prompts'), output=path('out'), seed=a.seed, port=a.port,
+ warmup=str(Path(path('prompts')) / 'warmup.txt'), brackets=brackets,
+ control_backend='Stock Triton; not historical dense CK',
+ primary_metric='Native time_prefill seconds; not HTTP TTFT or pure GPU time',
+ warmup_policy='Full-depth unscored warmup on each fresh server; measured KV cold',
+ statistics='base=(control_s+control2_s)/2; gain=100*(base/candidate_s-1); '
+ 'spread=abs(100*(control_s/control2_s-1)); statistics.median',
+ gate='Four valid brackets, four wins, median gain>2 and greater than median spread',
+ derived_helper=True, model_tested=False, quality_adoption=False,
+ scope='Public synthetic workload, not byte-identical historical prompts or a '
+ 'transfer of historical FullK rates; no broad quality/default approval')
+
+
+def sha(path):
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
+
+
+def save(path, value):
+ with Path(path).open('x') as stream:
+ json.dump(value, stream, indent=2, allow_nan=False)
+ stream.write('\n')
+
+
+def fit_prompt(count, render, label, seed, target=TOKENS):
+ """Create only synthetic public text; count the actual rendered chat prompt."""
+ import random
+ rng = random.Random(seed)
+ words = ('archive amber birch cedar delta elm field granite harbor iris '
+ 'junction kernel lake meadow north oak pebble quartz river stone '
+ 'timber valley willow xenon yellow zinc').split()
+ head = 'Public synthetic benchmark ' + label + '.\n'
+ # Different first pages, not just a different suffix after a shared cache key.
+ head += (label + ' experiment record ') * 40 + '\n'
+ tail = '\nSummarize the experimental record.'
+ def total(body):
+ return count(render(head + body + tail))
+ need(total('') < target, 'target too short for the public prefix')
+ body = ' '.join(rng.choice(words) for _ in range(target))
+ while total(body) < target:
+ body += ' ' + ' '.join(rng.choice(words) for _ in range(target // 4 + 1))
+ # Most tokenizers have a near-monotonic length in this ASCII corpus. Binary
+ # trim is a starting point only; exactness is checked, never inferred.
+ lo, hi = 0, len(body)
+ while lo < hi:
+ mid = (lo + hi + 1) // 2
+ if total(body[:mid]) <= target:
+ lo = mid
+ else:
+ hi = mid - 1
+ body = body[:lo]
+ for _ in range(32):
+ n = total(body)
+ if n == target:
+ return head + body + tail
+ if n > target:
+ body = body[:-1]
+ else:
+ # Separated single ASCII digits offer one-token padding in MiMo;
+ # the exact tokenizer count remains authoritative at every step.
+ body += ' 0'
+ raise ValueError('cannot fit exact rendered length; no prompt was published')
+
+
+def reply_source(response):
+ message = response['choices'][0]['message']
+ source = next((name for name in ('content', 'reasoning_content')
+ if isinstance(message.get(name), str) and message[name].strip()), None)
+ need(source is not None, 'empty completed response')
+ return source
+
+
+def checked_request(row, response, expected_prompt_sha):
+ import math
+ need(row['prompt_sha256'] == expected_prompt_sha and not row['error'], 'request receipt mismatch')
+ n = row['native']
+ need(n['prompt_tokens'] == TOKENS and n['cached_tokens'] == 0 and
+ type(n['new_tokens']) in (int, float) and 0 < n['new_tokens'] <= BUDGET and
+ n['accepted_draft_tokens'] == n['rejected_draft_tokens'] == 0,
+ 'cache/token/speculation contract failure')
+ seconds = n['time_prefill']
+ need(type(seconds) in (int, float) and math.isfinite(seconds) and seconds > 0,
+ 'invalid native prefill seconds')
+ t = response['timings']
+ need(t['cache_n'] == 0 and t['prompt_n'] == TOKENS and
+ t['predicted_n'] == n['new_tokens'] and t['prompt_ms'] == seconds * 1000 and
+ math.isclose(t['prompt_per_second'], TOKENS / seconds, rel_tol=1e-12),
+ 'API/native timing mismatch')
+ return dict(prefill_s=seconds, prefill_tps=TOKENS / seconds,
+ generated_tokens=n['new_tokens'], reply_source=reply_source(response))
+
+
+def parent_signals():
+ """Let SIGTERM unwind Python finally blocks; SIGKILL cannot be handled."""
+ import contextlib
+ import signal
+ @contextlib.contextmanager
+ def installed():
+ def terminate(signum, frame):
+ raise KeyboardInterrupt('parent received signal ' + str(signum))
+ previous = signal.signal(signal.SIGTERM, terminate)
+ try:
+ yield
+ finally:
+ signal.signal(signal.SIGTERM, previous)
+ return installed()
+
+
+def stop_owned(child):
+ """Terminate and reap only this Popen child, without a forced-kill timeout."""
+ import signal
+ import subprocess
+ previous = {number: signal.signal(number, signal.SIG_IGN)
+ for number in (signal.SIGTERM, signal.SIGINT)}
+ try:
+ if child.poll() is None:
+ child.terminate()
+ while True:
+ try:
+ return child.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ print('WAIT_OWNED_TEARDOWN', child.pid, flush=True)
+ finally:
+ for number, handler in previous.items():
+ signal.signal(number, handler)
+
+
+def arm_env(a, arm, out):
+ venv = a.python.absolute().parent.parent
+ sdk = venv / 'lib/python3.12/site-packages/_rocm_sdk_devel'
+ core = venv / 'lib/python3.12/site-packages/_rocm_sdk_core/lib'
+ private = Path(out) / 'private'
+ env = dict(HOME=str(private / 'home'), PATH='/usr/bin:/bin', LC_ALL='C',
+ PYTHONDONTWRITEBYTECODE='1', PYTORCH_ROCM_ARCH='gfx1151',
+ OMP_NUM_THREADS='1', MKL_NUM_THREADS='1',
+ EXL3_ROCM_SDK=str(sdk), EXL3_HSA_LIB=str(core / 'libhsa-runtime64.so.1'),
+ LD_PRELOAD=str(core / 'libhsa-runtime64.so.1'),
+ LD_LIBRARY_PATH=f'{core}:{sdk / "lib"}', EXL3_EXPANDABLE_SEGMENTS='0',
+ EXL3_CK_PAGEDKV_SO=str(a.ck), EXL3_CK_SPARSE_RETAIN='0.3',
+ EXL3_PREFILL_CHUNK='4096', EXL3_MOE_CFG='2',
+ EXL3_HIP_PREFILL_MIN_ROWS='2', EXL3_PF_MSPLIT='2048', EXL3_MPW2X='2',
+ EXL3_LOAD_DEVICE='cuda:0', EXL3_HOST_LEAN='1', EXL3_HOST_CUTS='1',
+ EXL3_SPEC_GATE='0', KYOJIN_REQLOG_DIR='off', KYOJIN_SSE_PING_S='0')
+ for key, leaf in (('TRITON_CACHE_DIR', 'triton'), ('TORCH_EXTENSIONS_DIR', 'torch'),
+ ('XDG_CACHE_HOME', 'cache'), ('TMPDIR', 'tmp'), ('HIP_CACHE_DIR', 'hip'),
+ ('MIOPEN_USER_DB_PATH', 'miopen'), ('KYOJIN_HEALTH_DIR', 'health')):
+ env[key] = str(private / leaf)
+ env['EXL3_DENSE_GEMM_TUNE_FILE'] = str(private / 'dense-gemm-tune.txt')
+ if arm == 'candidate':
+ env['EXL3_CK_PAGEDKV'] = 'sparse'
+ return env
+
+
+def summarize_bracket(times):
+ import math
+ need(len(times) == 3 and all(type(x) in (int, float) and math.isfinite(x) and x > 0
+ for x in times), 'invalid bracket times')
+ control, candidate, control2 = times
+ base = (control + control2) / 2
+ return dict(control_s=control, candidate_s=candidate, control2_s=control2,
+ base_s=base, gain_percent=100 * (base / candidate - 1),
+ spread_percent=abs(100 * (control / control2 - 1)), win=candidate < base)
+
+
+def normalized(a):
+ for name in ('source', 'native', 'ck', 'model', 'prompts', 'out'):
+ setattr(a, name, getattr(a, name).expanduser().resolve())
+ # Do not resolve the venv executable symlink to the system interpreter.
+ a.python = a.python.expanduser().absolute()
+ protected = (a.source, a.native.parent, a.ck.parent, a.model,
+ a.python.parent.parent, Path(__file__).resolve().parent)
+ for output in (a.prompts, a.out):
+ for path in protected:
+ need(not output.is_relative_to(path) and not path.is_relative_to(output),
+ 'writable output overlaps an input: ' + str(path))
+ need(not a.out.is_relative_to(a.prompts) and not a.prompts.is_relative_to(a.out),
+ 'prompts and runtime output must be disjoint')
+ for path in (a.python, a.native, a.ck, a.source / 'tools/mimo/serve.py',
+ a.source / 'tools/mimo/chat_template.jinja', a.model / 'config.json'):
+ need(path.is_file(), 'missing input: ' + str(path))
+ return a
+
+
+def source_pins(a):
+ selected = {Path(__file__).resolve(), a.native, a.ck}
+ for directory in ('exllamav3', 'tools/mimo', 'tools/strix_halo'):
+ selected.update((a.source / directory).rglob('*.py'))
+ selected.add(a.source / 'tools/mimo/chat_template.jinja')
+ selected.add(a.prompts / 'manifest.json')
+ selected.update(a.prompts / name for name in ['warmup.txt'] +
+ [f'measured-{index}.txt' for index in range(4)])
+ for name in ('config.json', 'tokenizer.json', 'tokenizer_config.json',
+ 'generation_config.json', 'model.safetensors.index.json'):
+ path = a.model / name
+ if path.is_file():
+ selected.add(path)
+ need(len(selected) > 20, 'source inventory unexpectedly small')
+ return {str(path): sha(path) for path in sorted(selected)}
+
+
+def weight_identity(a):
+ result = {}
+ for path in sorted(a.model.glob('*.safetensors')):
+ st = path.stat()
+ result[str(path)] = [st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns]
+ need(result, 'model has no weight shards')
+ return result
+
+
+def bind_runtime(a):
+ admission = json.loads((a.out / 'admission.json').read_bytes())
+ need(admission['plan'] == make_plan(a), 'parent/worker plan differs')
+ for name, digest in admission['pins'].items():
+ need(sha(name) == digest, 'input changed: ' + name)
+ need(weight_identity(a) == admission['weights_stat'], 'weight identity changed')
+ return admission
+
+
+def load_modules(a):
+ import importlib
+ import importlib.util
+ need(sys.version_info[:2] == (3, 12), 'select the built Python3.12 venv')
+ need(Path(sys.prefix).absolute() == a.python.parent.parent,
+ 'wrong selected interpreter environment')
+ sys.path[:0] = [str(a.source), str(a.native.parent),
+ str(a.source / 'tools/mimo'), str(a.source / 'tools')]
+ need(Path(importlib.util.find_spec('exllamav3').origin).resolve() ==
+ a.source / 'exllamav3/__init__.py', 'wrong package discovery')
+ need(Path(importlib.util.find_spec('exllamav3_ext').origin).resolve() == a.native,
+ 'wrong native discovery')
+ import torch
+ import torch.utils.cpp_extension as cpp
+ def no_build(*args, **kwargs):
+ raise RuntimeError('official native extension rebuild forbidden')
+ cpp.load = no_build
+ cpp.load_inline = no_build
+ native = importlib.import_module('exllamav3_ext')
+ from exllamav3.ext import exllamav3_ext as bound
+ need(bound is native and Path(native.__file__).resolve() == a.native,
+ 'wrong loaded native extension')
+ serve = importlib.import_module('serve')
+ need(Path(serve.__file__).resolve() == a.source / 'tools/mimo/serve.py',
+ 'wrong serving module')
+ torch.set_num_threads(1)
+ torch.set_grad_enabled(False)
+ torch.backends.cuda.matmul.allow_tf32 = False
+ return torch, serve
+
+
+def rendered(a, serve, text):
+ return serve.render_prompt((a.source / 'tools/mimo/chat_template.jinja').read_text(),
+ [dict(role='user', content=text)], None,
+ reasoning_effort='none')
+
+
+def make_prompts(a):
+ _, serve = load_modules(a)
+ from exllamav3 import Config, Tokenizer
+ tokenizer = Tokenizer.from_config(Config.from_directory(str(a.model)))
+ count = lambda text: tokenizer.encode(text, encode_special_tokens=True).numel()
+ render = lambda text: rendered(a, serve, text)
+ need(not a.prompts.exists(), 'preserve existing prompt directory')
+ a.prompts.mkdir(parents=True)
+ rows, first_pages = [], set()
+ for index, name in enumerate(['warmup'] + [f'measured-{i}' for i in range(4)]):
+ text = fit_prompt(count, render, name, a.seed + index)
+ encoded = tokenizer.encode(render(text), encode_special_tokens=True).flatten()
+ need(encoded.numel() == TOKENS, 'rendered prompt is not exactly131079tokens')
+ first = tuple(encoded[:256].tolist())
+ need(first not in first_pages, 'public prompts share a first cache page')
+ first_pages.add(first)
+ path = a.prompts / (name + '.txt')
+ with path.open('x') as stream:
+ stream.write(text)
+ rows.append(dict(name=path.name, sha256=sha(path), prompt_tokens=TOKENS,
+ rendered_sha256=hashlib.sha256(render(text).encode()).hexdigest(),
+ first_page_sha256=hashlib.sha256(json.dumps(first).encode()).hexdigest()))
+ save(a.prompts / 'manifest.json', dict(schema='public-cold128-prompts-v1', seed=a.seed,
+ synthetic=True, scope='New public workload, not retained historical prompt bytes',
+ template_sha256=sha(a.source / 'tools/mimo/chat_template.jinja'),
+ tokenizer_sha256=sha(a.model / 'tokenizer.json'), rows=rows))
+ print('PUBLIC_COLD128_PROMPTS_CREATED', json.dumps(rows), flush=True)
+ return 0
+
+
+def check_prompts(a):
+ manifest = json.loads((a.prompts / 'manifest.json').read_bytes())
+ need(manifest['schema'] == 'public-cold128-prompts-v1' and manifest['synthetic'] is True,
+ 'wrong public prompt manifest')
+ need(manifest['template_sha256'] == sha(a.source / 'tools/mimo/chat_template.jinja') and
+ manifest['tokenizer_sha256'] == sha(a.model / 'tokenizer.json'),
+ 'prompt template/tokenizer differs')
+ need({row['name'] for row in manifest['rows']} ==
+ {'warmup.txt', *(f'measured-{i}.txt' for i in range(4))}, 'wrong prompt population')
+ for row in manifest['rows']:
+ need(row['prompt_tokens'] == TOKENS and sha(a.prompts / row['name']) == row['sha256'],
+ 'public prompt changed')
+ return manifest
+
+
+def checked_sparse(row):
+ name = 'ck_pagedkv_sparse_engine'
+ before, after = row['counters_before'][name], row['counters_after'][name]
+ delta = {key: after.get(key, 0) - before.get(key, 0)
+ for key in ('accepted', 'declined', 'pages_kept', 'pages_total')}
+ need(delta['accepted'] > 0 and 0 < delta['pages_kept'] < delta['pages_total'],
+ 'measured sparse page dropping not engaged')
+ return delta
+
+
+def run_worker(a):
+ import copy
+ import importlib
+ bind_runtime(a)
+ leg = [leg for group in make_plan(a)['brackets'] for leg in group][a.worker]
+ out = a.out / leg['tag']
+ expected = arm_env(a, leg['arm'], out)
+ need(all(os.environ.get(key) == value for key, value in expected.items()),
+ 'worker environment mismatch')
+ need((os.environ.get('EXL3_CK_PAGEDKV') == 'sparse') if leg['arm'] == 'candidate'
+ else 'EXL3_CK_PAGEDKV' not in os.environ, 'wrong import-time treatment')
+ torch, serve = load_modules(a)
+ dispatch = importlib.import_module('exllamav3.modules.attention_fn.dispatch')
+ active = [fn.__name__ for fn in dispatch.attn_fns]
+ need((active[0] == 'fn_ck_paged_attn_sparse_engine') if leg['arm'] == 'candidate'
+ else all(not name.startswith('fn_ck_') for name in active), 'FP16 dispatcher mismatch')
+ def counters():
+ return {name: copy.deepcopy(module._stats) for name in
+ ('ck_pagedkv', 'ck_pagedkv_sparse', 'ck_pagedkv_sparse_engine')
+ if (module := sys.modules.get('exllamav3.modules.attention_fn.' + name)) is not None}
+ request_log = (out / 'requests.jsonl').open('x', buffering=1)
+ class ObservedEngine(serve.ResidentEngine):
+ async def generate(self, prompt, **kwargs):
+ before, pieces, error = counters(), [], None
+ try:
+ async for piece in super().generate(prompt, **kwargs):
+ pieces.append(piece)
+ yield piece
+ except BaseException as exc:
+ error = type(exc).__name__ + ': ' + str(exc)
+ raise
+ finally:
+ st = self.last_stats
+ row = dict(prompt_sha256=hashlib.sha256(prompt.encode()).hexdigest(),
+ native={key: st.get(key, 0) for key in ('prompt_tokens', 'cached_tokens',
+ 'new_tokens', 'time_prefill', 'time_generate',
+ 'accepted_draft_tokens', 'rejected_draft_tokens')},
+ completion=st.get('full_completion') or ''.join(pieces),
+ counters_before=before, counters_after=counters(), error=error)
+ request_log.write(json.dumps(row, allow_nan=False) + '\n')
+ serve.SERVE_DEFAULTS.update(serve.pack_sampling(str(a.model)))
+ engine = ObservedEngine(str(a.model), drafter_path=None, ctx=CAPACITY, vision=False)
+ from exllamav3 import CacheLayer_fp16
+ need(engine.cache.initialized and len(engine.cache.layers) == 9 and
+ all(type(layer) is CacheLayer_fp16 for layer in engine.cache.layers.values()),
+ 'not the expected MiMo FP16 cache')
+ need(engine.generator.max_chunk_size == CHUNK and engine.generator.draft_model is None,
+ 'wrong chunk/drafter')
+ app = serve.create_app(engine, 'MiMo-2.6-EXL3',
+ (a.source / 'tools/mimo/chat_template.jinja').read_text())
+ async def cleanup(_):
+ engine.generator.clear_queue()
+ engine.generator.filter_pool.shutdown(wait=True)
+ engine.model.unload()
+ request_log.close()
+ app.on_cleanup.append(cleanup)
+ prompts = {path: rendered(a, serve, Path(path).read_text())
+ for path in (make_plan(a)['warmup'], leg['prompt'])}
+ counts = {path: engine.count_tokens(text) for path, text in prompts.items()}
+ need(all(n == TOKENS for n in counts.values()), 'rendered prompt token count mismatch')
+ hashes = {path: hashlib.sha256(text.encode()).hexdigest() for path, text in prompts.items()}
+ first_pages = {tuple(engine.tokenizer.encode(text, encode_special_tokens=True).flatten()[:256].tolist())
+ for text in prompts.values()}
+ need(len(set(hashes.values())) == len(first_pages) == 2, 'warmup shares prompt KV prefix')
+ save(out / 'ready.json', dict(pid=os.getpid(), arm=leg['arm'], cache_bits=[16, 16],
+ capacity=engine.cache.max_num_tokens, chunk=engine.generator.max_chunk_size,
+ prompt_counts=counts, rendered_prompt_hashes=hashes,
+ fp16_dispatch=active, native_sha256=sha(a.native), ck_sha256=sha(a.ck)))
+ serve.web.run_app(app, host='127.0.0.1', port=a.port)
+ return 0
+
+
+def lane_state():
+ owners = []
+ for proc in Path('/proc').iterdir():
+ if not proc.name.isdigit():
+ continue
+ try:
+ descriptors = list((proc / 'fd').iterdir())
+ except OSError:
+ continue
+ for fd in descriptors:
+ try:
+ target = os.readlink(fd)
+ except OSError:
+ continue
+ if target == '/dev/kfd' or target.startswith('/dev/accel/accel'):
+ owners.append(dict(pid=int(proc.name), device=target))
+ break
+ busy = {str(path): path.read_text().strip()
+ for path in Path('/sys/class/drm').glob('card[0-9]*/device/gpu_busy_percent')}
+ return dict(compute_owners=owners, busy=busy)
+
+
+def policy():
+ result = {}
+ for pattern in ('card[0-9]*/device/pp_dpm_fclk',
+ 'card[0-9]*/device/power_dpm_force_performance_level'):
+ for path in Path('/sys/class/drm').glob(pattern):
+ text = path.read_text().strip()
+ result[str(path)] = [line for line in text.splitlines() if '*' in line] if 'fclk' in pattern else text
+ for name in ('control', 'runtime_status'):
+ path = Path('/sys/class/accel/accel0/device/power') / name
+ if path.exists():
+ result[str(path)] = path.read_text().strip()
+ return result
+
+
+def port_open(a):
+ import socket
+ with socket.socket() as sock:
+ return sock.connect_ex(('127.0.0.1', a.port)) == 0
+
+
+def request(a, path, body=None):
+ import urllib.request
+ raw = json.dumps(body).encode() if body is not None else None
+ req = urllib.request.Request(f'http://127.0.0.1:{a.port}' + path, data=raw,
+ headers={'Content-Type': 'application/json'})
+ # No overall inference timeout; parent ownership and child liveness supervise it.
+ with urllib.request.build_opener(urllib.request.ProxyHandler({})).open(req) as response:
+ return response.read()
+
+
+def monitored_request(a, child, body, tag):
+ import queue
+ import threading
+ import time
+ result = queue.Queue()
+ def work():
+ try:
+ result.put((True, request(a, '/v1/chat/completions', body)))
+ except BaseException as exc:
+ result.put((False, exc))
+ thread = threading.Thread(target=work, daemon=True)
+ thread.start()
+ started = time.monotonic()
+ while True:
+ try:
+ ok, value = result.get(timeout=30)
+ if not ok:
+ raise value
+ return value
+ except queue.Empty:
+ print('COLD128_PROGRESS', tag, round(time.monotonic() - started, 1), flush=True)
+ need(child.poll() is None, 'server exited during request')
+
+
+def worker_argv(a, index):
+ argv = [str(a.python), '-I', '-B', '-u', str(Path(__file__).resolve()), '--execute']
+ for key in ('source', 'native', 'ck', 'model', 'python', 'prompts', 'out', 'port', 'seed'):
+ argv += ['--' + key, str(getattr(a, key))]
+ return argv + ['--worker', str(index)]
+
+
+def run_leg(a, index, leg, fixed):
+ import subprocess
+ import time
+ out = a.out / leg['tag']
+ out.mkdir()
+ for leaf in ('home', 'triton', 'torch', 'cache', 'tmp', 'hip', 'miopen', 'health'):
+ (out / 'private' / leaf).mkdir(parents=True)
+ state = lane_state()
+ need(not state['compute_owners'] and state['busy'] and
+ all(value == '0' for value in state['busy'].values()) and not port_open(a),
+ 'device lane occupied')
+ need(policy() == fixed, 'policy drift')
+ record = dict(leg=leg, argv=worker_argv(a, index), environment=arm_env(a, leg['arm'], out),
+ before=state, policy_before=fixed)
+ child = None
+ try:
+ with (out / 'server.log').open('xb') as log:
+ child = subprocess.Popen(record['argv'], cwd=out / 'private', env=record['environment'],
+ stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ record['pid'] = child.pid
+ record['start_ticks'] = Path(f'/proc/{child.pid}/stat').read_text().rsplit(')', 1)[1].split()[19]
+ save(out / 'launch.json', record)
+ heartbeat = 0.0
+ while True:
+ need(child.poll() is None, 'server exited before ready: ' + str(out / 'server.log'))
+ if (out / 'ready.json').is_file() and port_open(a):
+ ready = json.loads((out / 'ready.json').read_bytes())
+ need(ready['pid'] == child.pid, 'wrong ready PID')
+ if json.loads(request(a, '/health')).get('generator'):
+ break
+ if time.monotonic() - heartbeat > 30:
+ print('WAIT_READY', leg['tag'], child.pid, flush=True)
+ heartbeat = time.monotonic()
+ time.sleep(1)
+ record['effective_environment'] = dict(item.split('=', 1) for item in
+ Path(f'/proc/{child.pid}/environ').read_bytes().decode().strip('\0').split('\0'))
+ need(all(record['effective_environment'].get(key) == value
+ for key, value in record['environment'].items()), 'child environment differs')
+ for request_index, (kind, prompt_path) in enumerate(
+ (('warmup', make_plan(a)['warmup']), ('measured', leg['prompt']))):
+ body = dict(model='MiMo-2.6-EXL3', messages=[dict(role='user', content=Path(prompt_path).read_text())],
+ reasoning_effort='none', max_tokens=BUDGET, temperature=0.0, top_p=1.0, stream=False)
+ print('COLD128_BEGIN', leg['tag'], kind, flush=True)
+ started = time.perf_counter()
+ raw = monitored_request(a, child, body, leg['tag'] + ':' + kind)
+ elapsed = time.perf_counter() - started
+ with (out / (kind + '-response.json')).open('xb') as stream:
+ stream.write(raw)
+ response = json.loads(raw)
+ rows = [json.loads(line) for line in (out / 'requests.jsonl').read_text().splitlines()]
+ need(len(rows) == request_index + 1, 'missing/extra native request')
+ rendered_sha = ready['rendered_prompt_hashes'][str(prompt_path)]
+ score = checked_request(rows[-1], response, rendered_sha)
+ delta = checked_sparse(rows[-1]) if leg['arm'] == 'candidate' else None
+ if leg['arm'] != 'candidate':
+ need(not rows[-1]['counters_before'] and not rows[-1]['counters_after'],
+ 'stock control unexpectedly loaded CK')
+ record[kind] = dict(prompt=str(prompt_path), prompt_sha256=sha(prompt_path),
+ rendered_sha256=rendered_sha, native_score=score,
+ response_sha256=hashlib.sha256(raw).hexdigest(), sparse_delta=delta,
+ timings=response['timings'], client_wall_s=elapsed)
+ save(out / (kind + '-summary.json'), record[kind])
+ print('COLD128_END', leg['tag'], kind, score['prefill_tps'], flush=True)
+ maps = Path(f'/proc/{child.pid}/maps').read_text()
+ with (out / 'after-request-maps.txt').open('x') as stream:
+ stream.write(maps)
+ record['ck_mapped_after_request'] = str(a.ck) in maps
+ need(record['ck_mapped_after_request'] == (leg['arm'] == 'candidate'), 'wrong CK mapping')
+ except BaseException as exc:
+ record['error'] = type(exc).__name__ + ': ' + str(exc)
+ finally:
+ if child is not None:
+ record['server_returncode'] = stop_owned(child)
+ record['port_closed'] = not port_open(a)
+ state = lane_state()
+ while not state['compute_owners'] and state['busy'] and any(value != '0' for value in state['busy'].values()):
+ print('WAIT_GPU_IDLE', leg['tag'], state['busy'], flush=True)
+ time.sleep(2)
+ state = lane_state()
+ record['after'], record['policy_after'] = state, policy()
+ save(out / 'result.json', record)
+ need(not record.get('error') and record.get('server_returncode') == 0 and record['port_closed']
+ and not state['compute_owners'] and record['policy_after'] == fixed,
+ 'leg instrument/cleanup failure; inspect ' + str(out / 'result.json'))
+ return record
+
+
+def run_parent(a):
+ import statistics
+ check_prompts(a)
+ need(not a.out.exists(), 'preserve existing output root')
+ os.umask(0o077)
+ a.out.mkdir(parents=True)
+ fixed = policy()
+ admission = dict(plan=make_plan(a), pins=source_pins(a), weights_stat=weight_identity(a), policy=fixed,
+ meminfo=Path('/proc/meminfo').read_text(), vmstat=Path('/proc/vmstat').read_text())
+ save(a.out / 'admission.json', admission)
+ records, brackets = [], []
+ with parent_signals():
+ for index, leg in enumerate(leg for group in make_plan(a)['brackets'] for leg in group):
+ bind_runtime(a)
+ records.append(run_leg(a, index, leg, fixed))
+ if len(records) % 3 == 0:
+ group = records[-3:]
+ need(len({row['measured']['rendered_sha256'] for row in group}) == 1,
+ 'bracket prompt hashes differ')
+ score = summarize_bracket([row['measured']['native_score']['prefill_s'] for row in group])
+ score['pair'] = leg['pair']
+ brackets.append(score)
+ save(a.out / f'bracket{leg["pair"]}.json', score)
+ print('COLD128_BRACKET', json.dumps(score), flush=True)
+ bind_runtime(a)
+ gain = statistics.median(row['gain_percent'] for row in brackets)
+ spread = statistics.median(row['spread_percent'] for row in brackets)
+ wins = sum(row['win'] for row in brackets)
+ result = dict(status='PUBLIC_COLD128_COMPLETE', pairs_complete='4 of 4', brackets=brackets,
+ records=records, wins=wins, median_gain_percent=gain, median_spread_percent=spread,
+ screen_gate=wins == 4 and gain > 2 and gain > spread,
+ candidate_tps_from_median_duration=TOKENS / statistics.median(
+ row['measured']['native_score']['prefill_s'] for row in records if row['leg']['arm'] == 'candidate'),
+ control_tps_from_median_duration=TOKENS / statistics.median(
+ row['measured']['native_score']['prefill_s'] for row in records if row['leg']['arm'] != 'candidate'),
+ quality_adoption=False, default_enablement=False, plan=make_plan(a),
+ vmstat_after=Path('/proc/vmstat').read_text())
+ save(a.out / 'result.json', result)
+ print('PUBLIC_COLD128_COMPLETE', json.dumps({key: result[key] for key in
+ ('pairs_complete', 'wins', 'median_gain_percent', 'median_spread_percent', 'screen_gate')}), flush=True)
+ return 0
+
+
+def runtime(a):
+ a = normalized(a)
+ if a.make_prompts:
+ # Re-exec with the selected venv and clean import-time environment.
+ if os.environ.get('PUBLIC_COLD128_PROMPT_ENV') != '1':
+ need(not a.prompts.exists(), 'preserve existing prompt directory')
+ prep = a.prompts.parent / ('.' + a.prompts.name + '-prep')
+ for protected in (a.source, a.native.parent, a.ck.parent, a.model,
+ a.python.parent.parent, a.out, Path(__file__).resolve().parent):
+ need(not prep.is_relative_to(protected) and not protected.is_relative_to(prep),
+ 'prompt preparation overlaps an input/output')
+ prep.mkdir(parents=True, exist_ok=False)
+ env = arm_env(a, 'control', prep)
+ for key in ('HOME', 'TRITON_CACHE_DIR', 'TORCH_EXTENSIONS_DIR', 'XDG_CACHE_HOME',
+ 'TMPDIR', 'HIP_CACHE_DIR', 'MIOPEN_USER_DB_PATH', 'KYOJIN_HEALTH_DIR'):
+ Path(env[key]).mkdir(parents=True, exist_ok=True)
+ env['PUBLIC_COLD128_PROMPT_ENV'] = '1'
+ # Carry paths normalized under the caller's HOME into the private HOME.
+ argv = [str(a.python), '-I', '-B', '-u', str(Path(__file__).resolve()), '--make-prompts']
+ for key in ('source', 'native', 'ck', 'model', 'python', 'prompts', 'out', 'port', 'seed'):
+ argv += ['--' + key, str(getattr(a, key))]
+ os.execve(str(a.python), argv, env)
+ return make_prompts(a)
+ return run_worker(a) if a.worker is not None else run_parent(a)
+
+
+def main():
+ a = parser().parse_args()
+ plan = make_plan(a)
+ if not a.execute and not a.make_prompts:
+ print(json.dumps(plan, indent=2))
+ return 0
+ return runtime(a)
+
+
+if __name__ == '__main__':
+ try:
+ sys.exit(main())
+ except Exception as exc:
+ print('COLD128_INSTRUMENT_FAILED', type(exc).__name__, str(exc), file=sys.stderr, flush=True)
+ sys.exit(6)
diff --git a/tools/strix_halo/ck_cold128/test_cold128.py b/tools/strix_halo/ck_cold128/test_cold128.py
new file mode 100644
index 0000000..9b98674
--- /dev/null
+++ b/tools/strix_halo/ck_cold128/test_cold128.py
@@ -0,0 +1,284 @@
+"""Focused stdlib checks; no Kyojin/framework/device imports."""
+import importlib.util
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from unittest import mock
+
+ROOT = Path(__file__).resolve().parent
+
+
+def load():
+ spec = importlib.util.spec_from_file_location('cold128_public', ROOT / 'cold128.py')
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+class PublicPlan(unittest.TestCase):
+ def test_parameterized_inert_plan_preserves_measured_settings(self):
+ module = load()
+ args = module.parser().parse_args([
+ '--source', '/example/kyojin', '--native', '/example/native/ext.so',
+ '--ck', '/example/ck/lib.so', '--model', '/example/model',
+ '--python', '/example/venv/bin/python', '--prompts', '/example/prompts',
+ '--out', '/example/results'])
+ plan = module.make_plan(args)
+ self.assertEqual(plan['status'], 'PLANNED_NOT_EXECUTED')
+ self.assertEqual(plan['cache_bits'], [16, 16])
+ self.assertEqual(plan['capacity'], 163840)
+ self.assertEqual(plan['chunk_size'], 4096)
+ self.assertEqual(plan['prompt_tokens'], 131079)
+ self.assertFalse(plan['drafter'])
+ self.assertEqual(len(plan['brackets']), 4)
+ for bracket in plan['brackets']:
+ self.assertEqual([leg['arm'] for leg in bracket], ['control', 'candidate', 'control2'])
+ self.assertEqual(len({leg['prompt'] for leg in bracket}), 1)
+ self.assertEqual(plan['source'], '/example/kyojin')
+ self.assertEqual(plan['control_backend'], 'Stock Triton; not historical dense CK')
+
+
+class PromptPreparation(unittest.TestCase):
+ def test_reexec_preserves_normalized_paths_after_home_changes(self):
+ for spelling in ('model-tilde', 'all-tilde', 'absolute'):
+ with self.subTest(spelling=spelling), tempfile.TemporaryDirectory(dir=ROOT) as directory:
+ owned = Path(directory)
+ home = owned / 'caller-home'
+ paths = dict(source=home / 'source', native=home / 'native/ext.so',
+ ck=home / 'ck/lib.so', model=home / 'model',
+ python=home / 'venv/bin/python', prompts=home / 'prompts',
+ out=home / 'results')
+ # Only file-presence checks use these inert inputs; none is imported.
+ for path in (paths['native'], paths['ck'], paths['model'] / 'config.json',
+ paths['source'] / 'tools/mimo/serve.py',
+ paths['source'] / 'tools/mimo/chat_template.jinja'):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text('inert fixture, not an engine or model\n')
+ paths['python'].parent.mkdir(parents=True)
+ paths['python'].symlink_to(sys.executable)
+ # Honor the real script-directory/output-disjointness guard. Load
+ # identical production bytes from a disjoint, owned fixture dir.
+ script = owned / 'helper/cold128.py'
+ script.parent.mkdir()
+ script.write_bytes((ROOT / 'cold128.py').read_bytes())
+ spec = importlib.util.spec_from_file_location('cold128_prep_fixture', script)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ cli = ['--make-prompts', '--port', '23456', '--seed', '987654']
+ for key, path in paths.items():
+ value = str(path)
+ if spelling == 'all-tilde' or (spelling == 'model-tilde' and key == 'model'):
+ value = '~/' + str(path.relative_to(home))
+ cli += ['--' + key, value]
+ # Only execve and the tokenizer entry are inert. Both passes use
+ # the actual main/runtime/normalized/parser and real filesystem.
+ with mock.patch.object(module, 'make_prompts', return_value=0) as prepared, \
+ mock.patch.object(os, 'execve', side_effect=SystemExit('inert execve')) as reexec:
+ with mock.patch.dict(os.environ, {'HOME': str(home)}, clear=True), \
+ mock.patch.object(sys, 'argv', [str(script), *cli]):
+ with self.assertRaisesRegex(SystemExit, 'inert execve'):
+ module.main()
+ prepared.assert_not_called()
+ reexec.assert_called_once()
+ executable, argv, environment = reexec.call_args.args
+ self.assertEqual(executable, str(paths['python']))
+ self.assertEqual(argv[:5], [str(paths['python']), '-I', '-B', '-u', str(script)])
+ self.assertNotEqual(environment['HOME'], str(home))
+ self.assertTrue(Path(environment['HOME']).is_dir())
+ self.assertEqual(environment['PUBLIC_COLD128_PROMPT_ENV'], '1')
+ with mock.patch.dict(os.environ, environment, clear=True), \
+ mock.patch.object(sys, 'argv', argv[4:]):
+ try:
+ result = module.main()
+ except ValueError as exc:
+ self.fail('prompt re-exec changed an input after HOME switched: ' + str(exc))
+ self.assertEqual(result, 0)
+ reexec.assert_called_once()
+ prepared.assert_called_once()
+ replayed = prepared.call_args.args[0]
+ for key, path in paths.items():
+ self.assertEqual(getattr(replayed, key), path)
+ self.assertTrue(replayed.python.is_symlink())
+ self.assertNotEqual(replayed.python, replayed.python.resolve())
+ self.assertTrue(replayed.make_prompts)
+ self.assertFalse(replayed.execute)
+ self.assertIsNone(replayed.worker)
+ self.assertEqual(replayed.port, 23456)
+ self.assertEqual(replayed.seed, 987654)
+
+
+class PromptFitting(unittest.TestCase):
+ def test_exact_rendered_length_and_distinct_prefix(self):
+ module = load()
+ # A synthetic character tokenizer makes the expected length independent.
+ # Real prompt creation later uses the actual engine tokenizer and template.
+ for index in range(5):
+ text = module.fit_prompt(lambda value: len(value),
+ lambda value: 'USER:' + value + ':ASSISTANT',
+ 'case-' + str(index), 1234 + index, target=2000)
+ self.assertEqual(len('USER:' + text + ':ASSISTANT'), 2000)
+ self.assertIn('case-' + str(index), text[:80])
+ self.assertTrue(text.endswith('Summarize the experimental record.'))
+
+
+class NativeResponse(unittest.TestCase):
+ def test_native_seconds_and_reasoning_fallback(self):
+ module = load()
+ row = dict(prompt_sha256='rendered', error=None,
+ native=dict(prompt_tokens=131079, cached_tokens=0, new_tokens=64,
+ accepted_draft_tokens=0, rejected_draft_tokens=0,
+ time_prefill=200.0))
+ response = dict(timings=dict(cache_n=0, prompt_n=131079, predicted_n=64,
+ prompt_ms=200000.0, prompt_per_second=655.395),
+ choices=[dict(message=dict(content=' \n', reasoning_content='valid reasoning'))])
+ self.assertEqual(module.checked_request(row, response, 'rendered')['prefill_s'], 200.0)
+ self.assertEqual(module.reply_source(response), 'reasoning_content')
+ response['choices'][0]['message']['content'] = 'actual answer'
+ self.assertEqual(module.reply_source(response), 'content')
+ response['timings']['prompt_ms'] = 200.0
+ with self.assertRaisesRegex(ValueError, 'API/native timing mismatch'):
+ module.checked_request(row, response, 'rendered')
+
+
+class OwnedTermination(unittest.TestCase):
+ def test_sigterm_reaps_exact_detached_child(self):
+ # Exercise real subprocesses, not a mocked terminate() callback. The
+ # child/marker and output are confined to this test's owned scratch.
+ with tempfile.TemporaryDirectory(dir=ROOT) as directory:
+ owned = Path(directory)
+ probe = owned / 'probe.py'
+ probe.write_text(
+ 'import importlib.util, pathlib, subprocess, sys, time\n'
+ 's=importlib.util.spec_from_file_location("p",sys.argv[1])\n'
+ 'm=importlib.util.module_from_spec(s);s.loader.exec_module(m)\n'
+ 'child=subprocess.Popen([sys.executable,"-I","-S","-c",'
+ '"import time; time.sleep(60)"],start_new_session=True)\n'
+ 'try:\n'
+ ' with m.parent_signals():\n'
+ ' pathlib.Path(sys.argv[2]).write_text(str(child.pid))\n'
+ ' while True:time.sleep(0.05)\n'
+ 'finally:\n'
+ ' m.stop_owned(child)\n')
+ log_path = owned / 'log.txt'
+ with log_path.open('wb') as log:
+ parent = subprocess.Popen([sys.executable, '-I', '-S', '-B', str(probe),
+ str(ROOT / 'cold128.py'), str(owned / 'pid')],
+ stdout=log, stderr=subprocess.STDOUT)
+ child_pid = None
+ try:
+ for _ in range(200):
+ if (owned / 'pid').exists():
+ child_pid = int((owned / 'pid').read_text())
+ break
+ if parent.poll() is not None:
+ break
+ time.sleep(0.01)
+ self.assertIsNotNone(child_pid, log_path.read_text())
+ parent.terminate()
+ self.assertNotEqual(parent.wait(timeout=10), 0)
+ self.assertFalse(Path('/proc', str(child_pid)).exists(), log_path.read_text())
+ finally:
+ if parent.poll() is None:
+ parent.kill()
+ parent.wait()
+ # Test cleanup only, with this exact test-created child ID.
+ if child_pid is not None and Path('/proc', str(child_pid)).exists():
+ os = __import__('os')
+ os.kill(child_pid, 15)
+
+
+class TreatmentEnvironment(unittest.TestCase):
+ def test_worker_treatment_is_import_time_and_cache_private(self):
+ module = load()
+ a = module.parser().parse_args([
+ '--source', '/example/kyojin', '--native', '/example/native/ext.so',
+ '--ck', '/example/ck/lib.so', '--model', '/example/model',
+ '--python', '/example/venv/bin/python', '--prompts', '/example/prompts',
+ '--out', '/example/results'])
+ c = module.arm_env(a, 'control', Path('/example/c'))
+ t = module.arm_env(a, 'candidate', Path('/example/t'))
+ self.assertNotIn('EXL3_CK_PAGEDKV', c)
+ self.assertEqual(t['EXL3_CK_PAGEDKV'], 'sparse')
+ self.assertEqual(t['EXL3_CK_SPARSE_RETAIN'], '0.3')
+ self.assertEqual(t['EXL3_PREFILL_CHUNK'], '4096')
+ self.assertNotEqual(c['TRITON_CACHE_DIR'], t['TRITON_CACHE_DIR'])
+ self.assertEqual(t['PYTORCH_ROCM_ARCH'], 'gfx1151')
+ self.assertNotIn('PYTHONPATH', t)
+ self.assertAlmostEqual(module.summarize_bracket([200.0, 100.0, 202.0])['gain_percent'],
+ 101.0, places=12)
+
+
+class RuntimeReceipt(unittest.TestCase):
+ def test_real_owned_child_and_two_http_fixture_receipts(self):
+ # Full run_leg producer/consumer seam with an actual tiny subprocess;
+ # only the model and HTTP response producer are inert fixtures.
+ module = load()
+ with tempfile.TemporaryDirectory(dir=ROOT) as directory:
+ owned = Path(directory)
+ prompt = owned / 'prompt.txt'
+ prompt.write_text('synthetic test fixture, never a model result')
+ args = module.parser().parse_args([
+ '--source', str(owned / 'source'), '--native', str(owned / 'native/ext.so'),
+ '--ck', str(owned / 'ck/lib.so'), '--model', str(owned / 'model'),
+ '--python', sys.executable, '--prompts', str(owned / 'prompts'),
+ '--out', str(owned / 'out')])
+ args.out.mkdir()
+ leg = dict(tag='fixture-control', arm='control', pair=0, prompt=str(prompt))
+ script = owned / 'worker.py'
+ script.write_text(
+ 'import json,os,pathlib,signal,sys,time\n'
+ 'out=pathlib.Path(sys.argv[1]); prompt=sys.argv[2]\n'
+ 'ready=dict(pid=os.getpid(),rendered_prompt_hashes={prompt:"rendered"})\n'
+ '(out/"ready.json").write_text(json.dumps(ready))\n'
+ 'signal.signal(signal.SIGTERM,lambda *_:sys.exit(0))\n'
+ 'while True:time.sleep(.01)\n')
+ module.worker_argv = lambda a, index: [sys.executable, '-I', '-S', '-B',
+ str(script), str(args.out / leg['tag']), str(prompt)]
+ module.arm_env = lambda a, arm, out: dict(PATH='/usr/bin:/bin', LC_ALL='C')
+ module.lane_state = lambda: dict(compute_owners=[], busy={'inert_gpu':'0'})
+ module.policy = lambda: {'inert_policy':'fixed'}
+ module.port_open = lambda a: (args.out / leg['tag'] / 'ready.json').exists()
+ module.request = lambda a, path: b'{"generator":true}'
+ module.make_plan = lambda a: {'warmup': str(prompt)}
+ count = [0]
+ def produced(a, child, body, tag):
+ count[0] += 1
+ row = dict(prompt_sha256='rendered', error=None, counters_before={}, counters_after={},
+ completion='synthetic fixture only',
+ native=dict(prompt_tokens=131079, cached_tokens=0, new_tokens=64,
+ accepted_draft_tokens=0, rejected_draft_tokens=0,
+ time_prefill=200.0, time_generate=2.0))
+ with (args.out / leg['tag'] / 'requests.jsonl').open('a') as stream:
+ stream.write(__import__('json').dumps(row) + '\n')
+ response = dict(timings=dict(cache_n=0, prompt_n=131079, predicted_n=64,
+ prompt_ms=200000.0, prompt_per_second=655.395),
+ choices=[dict(message=dict(content='', reasoning_content='fixture'))])
+ return __import__('json').dumps(response).encode()
+ module.monitored_request = produced
+ # The current process's read-only maps are not a model map. Select a
+ # nonexistent CK pathname so the stock-control mapping assertion holds.
+ record = None
+ original_stop = module.stop_owned
+ def stop(child):
+ code = original_stop(child)
+ (args.out / leg['tag'] / 'ready.json').unlink()
+ return code
+ module.stop_owned = stop
+ with module.parent_signals():
+ record = module.run_leg(args, 0, leg, {'inert_policy':'fixed'})
+ self.assertEqual(count[0], 2)
+ self.assertEqual(record['server_returncode'], 0)
+ self.assertTrue(record['port_closed'])
+ self.assertNotIn('error', record)
+ self.assertFalse(Path('/proc', str(record['pid'])).exists())
+ self.assertEqual(record['measured']['native_score']['prefill_s'], 200.0)
+ self.assertTrue((args.out / leg['tag'] / 'result.json').is_file())
+ self.assertTrue((args.out / leg['tag'] / 'measured-response.json').is_file())
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/tools/strix_halo/ck_pagedkv_build.py b/tools/strix_halo/ck_pagedkv_build.py
new file mode 100644
index 0000000..cd2da89
--- /dev/null
+++ b/tools/strix_halo/ck_pagedkv_build.py
@@ -0,0 +1,364 @@
+#!/usr/bin/env python3
+"""Standard-library-only orchestration for the pinned optional CK backend."""
+import argparse
+import fcntl
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shlex
+import shutil
+import subprocess
+import tempfile
+
+CK_COMMIT = '6f44fdf90f69adee742ec3660b95d32963b9bd2d'
+SOURCE_SCHEMA = 'ck-pagedkv-owned-source-v1'
+INSTANCE_NAME = (
+ 'fmha_fwd_pagedkv_d192_fp16_batch_b64x64x32x128x32x192_r4x1x1_r4x1x1_'
+ 'w16x16x16_w16x16x16_qr_pagedkv_vr_pssk_nlogits_nbias_mask_nlse_nskip_nsquant_pagedkv_nsink_gfx11.cpp'
+)
+
+
+def git(repo, *args, check=True):
+ # Repository redirects/config injection must not escape -C or modify a
+ # caller-selected index/worktree. The donor is always a read-only input.
+ env = {key: value for key, value in os.environ.items() if not key.startswith('GIT_')}
+ env.update(GIT_OPTIONAL_LOCKS='0', GIT_CONFIG_NOSYSTEM='1',
+ GIT_CONFIG_GLOBAL='/dev/null', GIT_NO_REPLACE_OBJECTS='1',
+ GIT_NO_LAZY_FETCH='1', GIT_ALLOW_PROTOCOL='file', LC_ALL='C')
+ result = subprocess.run(['git', '-c', 'core.hooksPath=/dev/null', '-C', str(repo), *args],
+ env=env, capture_output=True, text=True)
+ if check and result.returncode:
+ raise BuildError('git ' + ' '.join(args) + ': ' + result.stderr.strip())
+ return result
+
+
+def apply_patch(stage, patch):
+ """Only an owned stage may be passed here. Never patch the donor worktree."""
+ # Classify the whole tracked delta BEFORE making a change. A forward
+ # apply check alone can succeed even with unrelated dirty source edits.
+ actual = git(stage, 'diff', '--no-ext-diff', '--no-color', '--full-index', 'HEAD', '--').stdout
+ # Bare-empty unified context keeps the patch file whitespace-clean. Git
+ # emits a space marker there; normalize only that empty context spelling.
+ actual = re.sub(r'(?m)^ $', '', actual)
+ expected = re.sub(r'(?m)^ $', '', patch.read_text())
+ if actual not in ('', expected):
+ raise BuildError('Owned CK stage has changes beyond the exact pinned patch')
+ if git(stage, 'ls-files', '--others', '--exclude-standard').stdout:
+ raise BuildError('Owned CK stage has untracked source files')
+ if actual == '' and git(stage, 'apply', '--check', str(patch), check=False).returncode == 0:
+ git(stage, 'apply', str(patch))
+ return 'applied'
+ if actual == expected and git(stage, 'apply', '--reverse', '--check', str(patch), check=False).returncode == 0:
+ return 'already-applied'
+ raise BuildError('CK stage is incompatible or partially patched; refusing to change it')
+
+
+def prepare_source(donor, stage, pin, patch):
+ """Use only the donor commit object. Ignore its HEAD and dirty/untracked bytes.
+
+ The real CK checkout happens only during a future real build. Unit tests use
+ two-file local repositories; no real CK archive/checkout is a preparation test.
+ """
+ if Path(stage).is_symlink():
+ raise BuildError('Refusing a symlink as the owned CK stage')
+ donor, stage, patch = Path(donor).resolve(), Path(stage).resolve(), Path(patch).resolve()
+ if donor == stage or donor in stage.parents or stage in donor.parents:
+ raise BuildError('Source stage and donor must be disjoint')
+ if not re.fullmatch(r'[0-9a-f]{40}', pin):
+ raise BuildError('CK pin must be a full 40-hex commit')
+ if git(donor, 'rev-parse', '--verify', pin + '^{commit}').stdout.strip() != pin:
+ raise BuildError('Local donor does not contain the exact CK commit')
+ expected = {'schema': SOURCE_SCHEMA, 'commit': pin,
+ 'patch_sha256': hashlib.sha256(patch.read_bytes()).hexdigest()}
+ marker = stage / '.git/ck-pagedkv-source.json'
+ if stage.exists():
+ if not marker.is_file() or json.loads(marker.read_text()) != expected:
+ raise BuildError('Refusing existing unowned or differently pinned CK stage')
+ if git(stage, 'rev-parse', 'HEAD').stdout.strip() != pin:
+ raise BuildError('Owned CK stage HEAD changed')
+ return apply_patch(stage, patch)
+ stage.parent.mkdir(parents=True, exist_ok=True)
+ temp = Path(tempfile.mkdtemp(prefix='.ck-source-', dir=stage.parent))
+ try:
+ # --shared writes only an alternates pointer in our clone. No fetch,
+ # checkout, index refresh, config edit or patch is performed in donor.
+ git(stage.parent, 'clone', '--shared', '--no-checkout', '--no-tags', '--', str(donor), str(temp))
+ git(temp, '-c', 'advice.detachedHead=false', 'checkout', '--detach', pin)
+ state = apply_patch(temp, patch)
+ (temp / '.git/ck-pagedkv-source.json').write_text(json.dumps(expected, indent=2) + '\n')
+ temp.rename(stage)
+ return state
+ finally:
+ if temp.exists():
+ shutil.rmtree(temp)
+
+
+def compile_command(entry, source, output, compiler):
+ """Retain the native selected-instance recipe, changing only its I/O paths.
+
+ Dependency paths are separate for shim and instance; warning, target,
+ language, include, optimization and ABI flags are not stripped.
+ """
+ cwd = Path(entry['directory']).resolve()
+ if not cwd.is_dir():
+ raise BuildError('Compile command directory is absent: ' + str(cwd))
+ argv = list(entry.get('arguments') or shlex.split(entry['command']))
+ if not argv or Path(argv[0]).resolve() != Path(compiler).resolve():
+ raise BuildError('Compile database did not select the explicit ROCm compiler')
+ if any(x in argv for x in ('-fno-pic', '-fno-PIC', '-fpie', '-fPIE')):
+ raise BuildError('Compile recipe has conflicting PIC/PIE flags')
+ original = Path(entry['file'])
+ original = (cwd / original).resolve() if not original.is_absolute() else original.resolve()
+ result = [argv[0]]
+ count_source = count_output = 0
+ i = 1
+ while i < len(argv):
+ item = argv[i]
+ if item in ('-o', '-MF', '-MT', '-MQ'):
+ if i + 1 == len(argv):
+ raise BuildError('Truncated compile option: ' + item)
+ replacement = str(output) + '.d' if item == '-MF' else str(output)
+ result.extend([item, replacement])
+ count_output += item == '-o'
+ i += 2
+ continue
+ if not item.startswith('-') and (cwd / item).resolve() == original:
+ result.append(str(source))
+ count_source += 1
+ else:
+ result.append(item)
+ i += 1
+ if count_source != 1 or count_output != 1 or '-c' not in argv:
+ raise BuildError('Expected exactly one compile input/output and -c')
+ if '-fPIC' not in result:
+ result.append('-fPIC')
+ return result, cwd
+
+
+def build_backend(donor, cache, sdk, shim, patch, *, pin=CK_COMMIT, tool_commands=None):
+ """Build only the exact instance and shim. tool_commands is a unit-test seam.
+
+ The public CLI never supplies tool_commands or a replacement pin. Tests pass
+ inert stdlib recorder commands and a two-file local Git fixture explicitly.
+ """
+ if Path(cache).is_symlink():
+ raise BuildError('Refusing a symlink as the owned build cache')
+ donor, cache, sdk, shim, patch = [Path(p).resolve() for p in (donor, cache, sdk, shim, patch)]
+ if donor == cache or donor in cache.parents or cache in donor.parents:
+ raise BuildError('Cache and user-supplied source must be disjoint')
+ clang, clang_c = sdk / 'lib/llvm/bin/clang++', sdk / 'lib/llvm/bin/clang'
+ for path in (clang, clang_c):
+ if not path.is_file() or not os.access(path, os.X_OK):
+ raise BuildError('Missing explicit ROCm compiler: ' + str(path))
+ for path in (shim, patch):
+ if not path.is_file():
+ raise BuildError('Missing builder input: ' + str(path))
+ identity = {'schema': 'ck-pagedkv-build-v1', 'commit': pin, 'sdk': str(sdk),
+ 'patch_sha256': hashlib.sha256(patch.read_bytes()).hexdigest(),
+ 'shim_sha256': hashlib.sha256(shim.read_bytes()).hexdigest(),
+ 'builder_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
+ 'inert_test_tools': tool_commands is not None}
+ owner = cache / 'owner.json'
+ # A matching marker is not permission to follow new administrative
+ # symlinks into a user tree on a retry. This is not an adversarial sandbox.
+ for relative in ('owner.json', 'builder.lock', 'source', 'source/.git',
+ 'source/.git/ck-pagedkv-source.json', 'build', 'receipt.json',
+ 'receipt.json.tmp', 'libck_pagedkv.so', 'libck_pagedkv.so.tmp'):
+ if (cache / relative).is_symlink():
+ raise BuildError('Refusing symlink in owned cache: ' + relative)
+ if cache.exists():
+ if not owner.is_file() or json.loads(owner.read_text()) != identity:
+ raise BuildError('Refusing existing unowned or incompatible cache; choose a fresh EXL3_CK_CACHE')
+ else:
+ cache.mkdir(parents=True)
+ owner.write_text(json.dumps(identity, indent=2) + '\n')
+ with (cache / 'builder.lock').open('a') as lock:
+ try:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError as error:
+ raise BuildError('Another builder owns this cache') from error
+ stage = cache / 'source'
+ patch_state = prepare_source(donor, stage, pin, patch)
+ build = cache / 'build'
+ build.mkdir(exist_ok=True)
+ attempt = Path(tempfile.mkdtemp(prefix='attempt-', dir=cache))
+ commands = []
+ log = attempt / 'commands.json'
+ # Never consult ambient loader overrides in compiler subprocesses.
+ env = dict(os.environ, LC_ALL='C', PYTHONDONTWRITEBYTECODE='1', TMPDIR=str(attempt))
+ for key in ('LD_PRELOAD', 'LD_LIBRARY_PATH', 'PYTHONPATH', 'PYTHONHOME', 'HSA_OVERRIDE_GFX_VERSION'):
+ env.pop(key, None)
+ def run(argv, cwd):
+ argv = [str(x) for x in argv]
+ row = {'argv': argv, 'cwd': str(cwd)}
+ commands.append(row)
+ result = subprocess.run(argv, cwd=cwd, env=env, capture_output=True, text=True)
+ row.update(returncode=result.returncode, stdout=result.stdout, stderr=result.stderr)
+ log.write_text(json.dumps(commands, indent=2) + '\n')
+ if result.returncode:
+ raise BuildError('Command failed (' + str(result.returncode) + '); see ' + str(log) + '\n' + result.stderr)
+ return result.stdout
+ tools = {'cmake': ['cmake'], 'codegen': ['/usr/bin/python3', '-I', '-S'], 'nm': ['nm']}
+ if tool_commands is not None:
+ if set(tool_commands) != set(tools):
+ raise BuildError('Tests must explicitly replace every configure/codegen/nm command')
+ tools = tool_commands
+ run(tools['cmake'] + [
+ '-S', str(stage), '-B', str(build), '-G', 'Unix Makefiles',
+ '-DCMAKE_BUILD_TYPE=Release', '-DGPU_TARGETS=gfx1151', '-DAMDGPU_TARGETS=gfx1151',
+ '-DGPU_ARCHS=', '-DCOMPILER_HAS_TARGET_ID_gfx1151=ON',
+ '-DBUILD_TESTING=OFF', '-DBUILD_DEV=ON', '-DBUILD_CK_EXAMPLES=ON',
+ '-DBUILD_CK_TILE_FMHA_TESTS=ON', '-DBUILD_CK_DEVICE_INSTANCES=OFF',
+ '-DBUILD_CK_PROFILER=OFF', '-DBUILD_CK_TUTORIALS=OFF',
+ '-DFMHA_FWD_ENABLE_APIS=pagedkv_prefill', '-DCMAKE_POSITION_INDEPENDENT_CODE=ON',
+ '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', '-DPython3_EXECUTABLE=/usr/bin/python3',
+ '-DCMAKE_PREFIX_PATH=' + str(sdk) + ';/usr', '-DROCM_DIR=' + str(sdk / 'share/rocm/cmake'),
+ '-Dhip_DIR=' + str(sdk / 'lib/cmake/hip'), '-Dhip-lang_DIR=' + str(sdk / 'lib/cmake/hip-lang'),
+ '-DCMAKE_C_COMPILER=' + str(clang_c), '-DCMAKE_CXX_COMPILER=' + str(clang),
+ '-DCMAKE_HIP_COMPILER=' + str(clang)], cache)
+ database = json.loads((build / 'compile_commands.json').read_text())
+ matches = [entry for entry in database if Path(entry['file']).name == INSTANCE_NAME]
+ if len(matches) != 1:
+ raise BuildError('Expected exactly one selected instance compile command; found ' + str(len(matches)))
+ entry = matches[0]
+ directory = Path(entry['directory']).resolve()
+ source = (directory / entry['file']).resolve()
+ if build not in source.parents or build not in directory.parents and directory != build:
+ raise BuildError('Selected compile command escaped the owned build directory')
+ # CK CMake only lists blobs at configure; the custom generation command
+ # is not run by reading compile_commands.json. Explicitly generate just
+ # this instance (and the API text, which is NOT compiled or linked).
+ codegen = stage / 'example/ck_tile/01_fmha/generate.py'
+ # -I removes script-directory imports. -S is enough for pinned CK's local
+ # codegen imports; no framework/package site initialization is needed.
+ if tool_commands is None:
+ tools['codegen'] = ['/usr/bin/python3', '-S']
+ # A prior successful attempt must not hide missing/failed fresh output.
+ source.unlink(missing_ok=True)
+ run(tools['codegen'] + [str(codegen), '--targets', 'gfx1151', '--api', 'pagedkv_prefill',
+ '--optdim', '192', '--mask', 'simplified', '--receipt', '0',
+ '--filter', INSTANCE_NAME.removesuffix('_gfx11.cpp'),
+ '--output_dir', str(source.parent)], build)
+ if not source.is_file():
+ raise BuildError('Selected instance was not generated: ' + str(source))
+ instance_obj, shim_obj = attempt / 'instance.o', attempt / 'shim.o'
+ for input_source, output in ((source, instance_obj), (shim, shim_obj)):
+ argv, cwd = compile_command(entry, input_source, output, clang)
+ run(argv, cwd)
+ if not output.is_file():
+ raise BuildError('Compiler returned success without an object: ' + str(output))
+ symbol = undefined_specialization(run(tools['nm'] + ['-P', '--no-demangle', '--undefined-only', str(shim_obj)], attempt))
+ defined = nm_symbols(run(tools['nm'] + ['-P', '--no-demangle', '--defined-only', str(instance_obj)], attempt))
+ if sum(name == symbol and kind == 'T' for name, kind in defined) != 1:
+ raise BuildError('Selected instance does not define the exact mangled shim specialization')
+ library = attempt / 'libck_pagedkv.so'
+ # The HIP link driver supplies the HIP runtime, unlike bare host linking.
+ # -z defs catches unresolved host references now rather than at dlopen.
+ run([str(clang), '-shared', '-fPIC', '--hip-link', '--offload-arch=gfx1151',
+ '--rocm-path=' + str(sdk), '-Wl,-z,defs',
+ '-Wl,-rpath,' + str(sdk / 'lib'), '-o', str(library), str(shim_obj), str(instance_obj)], attempt)
+ exported = nm_symbols(run(tools['nm'] + ['-P', '--no-demangle', '-D', '--defined-only', str(library)], attempt))
+ for expected in ('ck_pagedkv_forward', symbol):
+ if sum(name == expected and kind == 'T' for name, kind in exported) != 1:
+ raise BuildError('Missing exact shared-library export: ' + expected)
+ unresolved = nm_symbols(run(tools['nm'] + ['-P', '--no-demangle', '-D', '--undefined-only', str(library)], attempt))
+ if any('fmha_fwd_pagedkv_' in name for name, kind in unresolved):
+ raise BuildError('Shared library still has an unresolved paged-KV specialization')
+ if not library.is_file():
+ raise BuildError('Linker returned success without a library')
+ destination = cache / 'libck_pagedkv.so'
+ receipt_path = cache / 'receipt.json'
+ previous_library = attempt / 'previous-libck_pagedkv.so'
+ had_previous = destination.exists()
+ if had_previous != receipt_path.exists():
+ raise BuildError('Incomplete published pair; recover ' + str(destination) + ' and ' + str(receipt_path))
+ temporary = cache / 'libck_pagedkv.so.tmp'
+ shutil.copy2(library, temporary)
+ receipt = dict(identity, donor=str(donor), patch_state=patch_state,
+ specialization=symbol, instance=str(source), commands=str(log),
+ output=str(destination), output_sha256=hashlib.sha256(temporary.read_bytes()).hexdigest(),
+ native_load_performed=False, numerical_validation_performed=False)
+ (attempt / 'receipt.json').write_text(json.dumps(receipt, indent=2) + '\n')
+ temporary_receipt = cache / 'receipt.json.tmp'
+ temporary_receipt.write_text(json.dumps(receipt, indent=2) + '\n')
+ if had_previous:
+ shutil.copy2(destination, previous_library)
+ # Recover ordinary exceptions only, not crashes or concurrent readers.
+ # Receipt replacement is last: on failure its prior bytes stay in place.
+ library_published = False
+ try:
+ temporary.replace(destination)
+ library_published = True
+ temporary_receipt.replace(receipt_path)
+ except Exception as error:
+ if library_published:
+ try:
+ if had_previous:
+ previous_library.replace(destination)
+ else:
+ destination.unlink()
+ except Exception as recovery_error:
+ raise BuildError('Publication failed: ' + str(error) + '; recovery failed: ' + str(recovery_error)
+ + '; previous library backup (if any): ' + str(previous_library)
+ + '; preserved receipt: ' + str(receipt_path)) from error
+ raise
+ return destination
+
+
+class BuildError(RuntimeError):
+ """A prerequisite, source state, command, or symbol contract failed."""
+
+
+def nm_symbols(text):
+ """Parse GNU/LLVM nm -P --no-demangle (name, type, optional value/size)."""
+ rows = []
+ for line in text.splitlines():
+ fields = line.split()
+ if not fields:
+ continue
+ if len(fields) < 2 or not re.fullmatch(r'[A-Za-z?]', fields[1]):
+ raise BuildError('Unexpected nm -P row: ' + line)
+ rows.append((fields[0], fields[1]))
+ return rows
+
+
+def undefined_specialization(text):
+ names = [name for name, kind in nm_symbols(text)
+ if kind == 'U' and 'fmha_fwd_pagedkv_' in name]
+ if len(names) != 1:
+ raise BuildError('Expected one undefined paged-KV specialization, found ' + str(names))
+ return names[0]
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(
+ description='Build the pinned gfx1151 d192 CK backend in a separate owned cache; no implicit network.')
+ parser.add_argument('--source', default=os.environ.get('EXL3_CK_SOURCE'),
+ help='Read-only local Git donor containing the exact pin (EXL3_CK_SOURCE)')
+ parser.add_argument('--sdk', default=os.environ.get('EXL3_ROCM_SDK'),
+ help='Already-expanded ROCm SDK directory (EXL3_ROCM_SDK)')
+ default_cache = Path(os.environ.get('XDG_CACHE_HOME', str(Path.home() / '.cache'))) / 'kyojin/ck-pagedkv'
+ parser.add_argument('--cache', default=os.environ.get('EXL3_CK_CACHE', str(default_cache)),
+ help='Disjoint owned cache/output directory (EXL3_CK_CACHE)')
+ args = parser.parse_args(argv)
+ if not args.source:
+ parser.error('Set EXL3_CK_SOURCE or --source to a local Git donor containing ' + CK_COMMIT)
+ if not args.sdk:
+ parser.error('Set EXL3_ROCM_SDK or --sdk to an already-expanded SDK')
+ for command in ('git', 'cmake', 'nm'):
+ if shutil.which(command) is None:
+ parser.error('Required command is absent: ' + command)
+ here = Path(__file__).resolve().parent
+ try:
+ library = build_backend(Path(args.source), Path(args.cache), Path(args.sdk),
+ here / 'ck_pagedkv_shim.cpp', here / 'patches/ck-pagedkv-d192.patch')
+ except (BuildError, OSError, ValueError, KeyError) as error:
+ parser.exit(1, 'CK backend build stopped: ' + str(error) + '\n')
+ print('Built ' + str(library) + '; native loading and numerics were not performed')
+ return 0
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/tools/strix_halo/ck_pagedkv_shim.cpp b/tools/strix_halo/ck_pagedkv_shim.cpp
new file mode 100644
index 0000000..fcb0fd7
--- /dev/null
+++ b/tools/strix_halo/ck_pagedkv_shim.cpp
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: MIT
+// Thin C ABI wrapper for the pinned Composable Kernel paged-KV specialization.
+// Built by tools/strix_halo/build_ck_pagedkv.sh; no binary is committed.
+
+#include <cmath>
+#include <cstdint>
+#include <cstring>
+#include <limits>
+
+#include <hip/hip_runtime.h>
+#include "bias.hpp"
+#include "fmha_fwd.hpp"
+#include "mask.hpp"
+
+using ck_mask = ck_tile::SimplifiedGenericAttentionMask<true>;
+using ck_trait = fmha_fwd_pagedkv_traits_<
+ 192, FmhaFwdFp16, false, 64, 64, 32, 128, 32, 192, true,
+ ck_tile::BlockFmhaPipelineEnum::QRKSVS, false, ck_mask,
+ ck_tile::BlockAttentionBiasEnum::NO_BIAS, false, true, false, true,
+ true, false, false, false, false, -1>;
+template <>
+float fmha_fwd_pagedkv_<ck_trait, ck_tile::gfx11_t>(
+ const ck_tile::stream_config&, fmha_fwd_pagedkv_args);
+
+// Keep a prior C ABI declaration so CK's native -Weverything diagnostics
+// remain enabled, including -Wmissing-prototypes.
+extern "C" float ck_pagedkv_forward(
+ const void* q, const void* k, const void* v, void* out,
+ const int32_t* block_table, const int32_t* lengths,
+ int q_len, int kv_len, int pages, float scale, int q_head_major,
+ int value_stride, hipStream_t stream, int time_it);
+
+extern "C" float ck_pagedkv_forward(
+ const void* q, const void* k, const void* v, void* out,
+ const int32_t* block_table, const int32_t* lengths,
+ int q_len, int kv_len, int pages, float scale, int q_head_major,
+ int value_stride, hipStream_t stream, int time_it) try {
+ constexpr int q_heads = 64;
+ constexpr int kv_heads = 4;
+ constexpr int qk_dim = 192;
+ constexpr int value_dim = 128;
+ constexpr int page_size = 256;
+
+ // -1 is reserved for rejection before the specialization can launch.
+ // Null stream is valid: HIP uses it for the default stream.
+ if (q == nullptr || k == nullptr || v == nullptr || out == nullptr ||
+ block_table == nullptr || lengths == nullptr || q_len <= 0 ||
+ kv_len < q_len || (q_head_major != 0 && q_head_major != 1) ||
+ value_stride != qk_dim) {
+ return -1.0f;
+ }
+ // Avoid overflowing either ceiling division or CK's int32 stride fields.
+ const int required_pages = kv_len / page_size + (kv_len % page_size != 0 ? 1 : 0);
+ if (pages < required_pages ||
+ q_len > std::numeric_limits<ck_tile::index_t>::max() / q_heads / qk_dim) {
+ return -1.0f;
+ }
+
+ fmha_fwd_pagedkv_args args{};
+ args.q_ptr = const_cast<void*>(q);
+ args.k_ptr = const_cast<void*>(k);
+ args.v_ptr = const_cast<void*>(v);
+ args.o_ptr = out;
+ args.block_table_ptr = const_cast<int32_t*>(block_table);
+ args.batch_stride_block_table = pages;
+ args.page_block_size = page_size;
+ args.seqlen_k_ptr = const_cast<int32_t*>(lengths);
+ args.seqlen_q = q_len;
+ args.seqlen_k = kv_len;
+ args.batch = 1;
+ args.max_seqlen_q = q_len;
+ args.hdim_q = qk_dim;
+ args.hdim_v = value_dim;
+ args.nhead_q = q_heads;
+ args.nhead_k = kv_heads;
+ args.scale_s = scale;
+ args.scale_p = 1.0f;
+ args.scale_o = 1.0f;
+ args.window_size_left = -1;
+ args.window_size_right = 0;
+ args.mask_type = static_cast<ck_tile::index_t>(mask_enum::mask_bottom_right);
+ args.stride_k = qk_dim;
+ args.nhead_stride_k = static_cast<ck_tile::index_t>(page_size) * qk_dim;
+ args.batch_stride_k = kv_heads * page_size * qk_dim;
+ args.stride_v = value_stride;
+ args.nhead_stride_v = static_cast<ck_tile::index_t>(page_size) * value_stride;
+ args.batch_stride_v = kv_heads * page_size * value_stride;
+ if (q_head_major) {
+ args.stride_q = qk_dim;
+ args.nhead_stride_q = static_cast<ck_tile::index_t>(q_len) * qk_dim;
+ args.batch_stride_q = q_heads * q_len * qk_dim;
+ args.stride_o = value_stride;
+ args.nhead_stride_o = static_cast<ck_tile::index_t>(q_len) * value_stride;
+ args.batch_stride_o = q_heads * q_len * value_stride;
+ } else {
+ args.stride_q = q_heads * qk_dim;
+ args.nhead_stride_q = qk_dim;
+ args.batch_stride_q = static_cast<ck_tile::index_t>(q_len) * q_heads * qk_dim;
+ args.stride_o = q_heads * value_stride;
+ args.nhead_stride_o = value_stride;
+ args.batch_stride_o = static_cast<ck_tile::index_t>(q_len) * q_heads * value_stride;
+ }
+ const ck_tile::stream_config config{stream, time_it != 0, 0, 0, 1, false};
+ const float elapsed = fmha_fwd_pagedkv_<ck_trait, ck_tile::gfx11_t>(config, args);
+ if (!std::isfinite(elapsed) || elapsed < 0.0f) return -2.0f;
+ if (time_it == 0) return 1.0f;
+ return elapsed > 0.0f ? elapsed : -2.0f;
+} catch (...) {
+ // CK's HIP checks throw; no C++ exception may unwind into ctypes.
+ return -2.0f;
+}
diff --git a/tools/strix_halo/patches/ck-pagedkv-d192.patch b/tools/strix_halo/patches/ck-pagedkv-d192.patch
new file mode 100644
index 0000000..ad1c47c
--- /dev/null
+++ b/tools/strix_halo/patches/ck-pagedkv-d192.patch
@@ -0,0 +1,34 @@
+diff --git a/example/ck_tile/01_fmha/CMakeLists.txt b/example/ck_tile/01_fmha/CMakeLists.txt
+index 062ef427ce68d2cd1f5f3c25f97f64ae384d401a..03c0a358a9d147d17ae2383d2712caec4337dea4 100644
+--- a/example/ck_tile/01_fmha/CMakeLists.txt
++++ b/example/ck_tile/01_fmha/CMakeLists.txt
+@@ -70,7 +70,7 @@ endif()
+ if(FMHA_FWD_HAS_GFX125)
+ set(FMHA_FWD_OPTDIM 32,64,96,128,160,192,256)
+ else()
+- set(FMHA_FWD_OPTDIM 32,64,80,128,256)
++ set(FMHA_FWD_OPTDIM 32,64,80,128,192,256)
+ endif()
+
+ string(REPLACE ";" "," FMHA_FWD_APIS "${FMHA_FWD_ENABLE_APIS}")
+diff --git a/example/ck_tile/01_fmha/codegen/ops/fmha_pagedkv_prefill.py b/example/ck_tile/01_fmha/codegen/ops/fmha_pagedkv_prefill.py
+index 0044b23648a161ed32304ca4b863da50cf971808..09f1f5c7ca0f5d233bc5f5660c1125c970f945da 100644
+--- a/example/ck_tile/01_fmha/codegen/ops/fmha_pagedkv_prefill.py
++++ b/example/ck_tile/01_fmha/codegen/ops/fmha_pagedkv_prefill.py
+@@ -237,7 +237,7 @@ class FmhaFwdApiTrait:
+ else:
+ assert False
+ elif self.pipeline_tag in ["qr_pagedkv", "qs"]:
+- bk0submax = K0_MAX_SUBMAX_MAP[self.bk0max]
++ bk0submax = K0_MAX_SUBMAX_MAP[self.bn1]
+ if self.dvpad == "t":
+ return f"true /*a.hdim_v % {bk0submax} != 0*/" # TODO: order of get_pipelines() matters! (ugly)
+ else:
+@@ -613,6 +613,7 @@ class KernelComponentFactoryGfx11(KernelComponentFactoryBase):
+ # bm0, bn0, bk0, bn1, bk1,
+ # "32": FmhaFwdTileSize( 64, 64, 16, 32, 32, 32, 4, 1, 1, 4, 1, 1, 16, 16, 16, 16, 16, 16, -1),
+ # "64": FmhaFwdTileSize( 64, 64, 32, 64, 32, 64, 4, 1, 1, 4, 1, 1, 16, 16, 16, 16, 16, 16, -1),
++ "192": FmhaFwdTileSize( 64, 64, 32, 128, 32, 192, 4, 1, 1, 4, 1, 1, 16, 16, 16, 16, 16, 16, -1),
+ "128": FmhaFwdTileSize( 64, 64, 32, 128, 32, 128, 4, 1, 1, 4, 1, 1, 16, 16, 16, 16, 16, 16, -1),
+ # "192": FmhaFwdTileSize( 64, 64, 32, 128, 32, 256, 4, 1, 1, 4, 1, 1, 16, 16, 16, 16, 16, 16, -1),
+ # "256": FmhaFwdTileSize( 64, 64, 32, 256, 32, 256, 4, 1, 1, 4, 1, 1, 16, 16, 16, 16, 16, 16, -1),