# BasinKV for Qwen4: 256K Context on a 24 GB GPU

> Native QSA-guided KV offloading for Qwen4-35B-A3B in llama.cpp (API v12). Rides Qwen4's trained Query-Sparse Attention indexer behind a fixed GPU CLOCK working set, fitting 256K inside 21.8 GiB on a 24 GB L4 (43.6 tok/s decode, 1,433 tok/s prefill, where stock OOMs at 32K) while beating stock 256K decode by +14.7% on both A100 and AMD Instinct MI300X at 7.0 to 7.2 GiB less VRAM.

- URL: https://zellige.ai/research/basinkv-qwen4
- Published: 2026-12-05
- Authors: Zellige
- Tags: inference, kv-cache, long-context, qwen4, systems, open-source
- Publisher: Zellige AI (https://zellige.ai)
- Code on GitHub (zellige-ai/basinkv): https://github.com/zellige-ai/basinkv
- BasinKV Launch Post: https://zellige.ai/research/basinkv-launch
- Full Technical Paper: https://zellige.ai/research/basinkv

**Published by Zellige (2026-12-05).** BasinKV now runs **Qwen4-35B-A3B** (`LLM_ARCH_QWEN4EXP`) at 256K context inside **21.8 GiB** on a 24 GB NVIDIA L4 (where stock `llama.cpp` OOMs at 32K), while beating stock 256K decode by **+14.7%** on both NVIDIA A100-80GB (77.1 vs 67.2 tok/s) and AMD Instinct MI300X (89.8 vs 78.3 tok/s) at 7.0 to 7.2 GiB less GPU memory. For the underlying sparse-offload design and launch benchmarks, see the [launch post](https://zellige.ai/research/basinkv-launch) and [full technical paper](https://zellige.ai/research/basinkv).

---

Qwen4-35B-A3B already ships with learned Query-Sparse Attention (QSA) on its 10 full-attention layers (paired with 30 Gated DeltaNet layers): a trained indexer compresses keys in 4-token pools (r = 4) and narrows each query to the top 2,048 tokens. That reduces attention compute, but it does not reduce KV memory. Stock `llama.cpp` still holds the full 256K FP16 KV cache and full indexer cache in GPU memory, reaching 30.1 GiB (30,855 MiB) peak on A100 and 31.5 GiB (32,226 MiB) on MI300X for Qwen4-35B-A3B UD-Q4_K_M. On a 24 GB NVIDIA L4 (22,611 MiB ECC-usable), stock fits up to 16K and **hits CUDA OOM at 32K**, even with one MoE layer offloaded to CPU.

Replacing Qwen4's trained indexer with a training-free block scorer like Quest would discard model-trained selection quality. Instead, BasinKV for Qwen4 rides Qwen4's own indexer: it runs `qwen4exp`'s exact `index_k_norm` and IMRoPE/M-RoPE projection on GPU, shrinks the GPU indexer cache 8x by keeping only pooled FP16 keys on device, and places a fixed GPU CLOCK working set (4,096 tokens plus a 64-token FP16 recent ring) in front of pinned host INT8 (or opt-in WHT-INT4) KV read over zero-copy PCIe UVA. Because the GPU working set has a fixed shape, **unmodified `ggml_flash_attn_ext` and captured CUDA/HIP graphs run unchanged** for both single-token decode and native MTP verify.

---

## Live on a 24 GB NVIDIA L4: 256K where stock OOMs at 32K

Qwen4-35B-A3B UD-Q4_K_M (32.77 GiB across two GGUF shards) places roughly 10.8 GiB of PLE embedding tables in host RAM and roughly 21.2 GiB of model weights on GPU. An ECC-enabled 24 GB L4 (22,611 MiB usable) therefore has less headroom than a consumer RTX 3090 or 4090 (24,576 MiB usable).

With `-ngl 99 -c 262144 -b 2048 -ub 512`, BasinKV loads all 40 layers in 22,577 to 22,581 MiB idle on ECC L4 (overflowing by roughly 46 MiB on the first prompt), and peaks at 22.4 GiB (22,905 MiB) on A100 at `-ub 512` or 23.0 GiB (23,505 MiB) at `-ub 2048`, leaving 1.0 to 1.6 GiB of headroom inside a consumer 24.0 GiB card. On the tighter ECC L4, offloading one MoE layer's routed experts (`--n-cpu-moe 1`) keeps all 40 GDN and QSA layers on GPU and holds peak VRAM flat at **21.8 GiB (22,304 to 22,326 MiB)** from 1K through 256K. Stock `llama.cpp` with the same `--n-cpu-moe 1` still OOMs at 32K (22,608 MiB).

![Single-container 24 GB NVIDIA L4 paired decode and recall through 256K alongside the 256K peak VRAM budget on L4 and A100.](https://zellige.ai/research/basinkv-qwen4/fig1_qwen4_l4_24gb_256k.png)

| Depth (Qwen4-35B-A3B UD-Q4_K_M, single-container L4 24 GB) | Stock QSA (`--n-cpu-moe 1`) | BasinKV INT8 v12 (`--n-cpu-moe 1`, `-c 262144`) | BasinKV Prefill | Peak VRAM | Recall |
|---|---:|---:|---:|---:|---|
| 1K (934 tok) | 45.9 tok/s (`-c 8192`) | **46.4 tok/s** | 854 tok/s | 22,304 MiB | Exact |
| 16K (15,391 tok) | 46.1 tok/s (`-c 16384`) | 38.5 tok/s | 1,748 tok/s | 22,324 MiB | Exact |
| 32K (31,489 tok) | CUDA OOM (22,608 MiB) | 21.2 tok/s* | 1,634 tok/s | 22,324 MiB | Exact |
| 64K (63,443 tok) | CUDA OOM | **44.8 tok/s** | 1,642 tok/s | 22,326 MiB | Exact |
| 128K (128,024 tok) | CUDA OOM | **42.6 tok/s** | 1,545 tok/s | 22,326 MiB | Exact |
| 256K (255,978 tok) | CUDA OOM | **43.6 tok/s** | **1,433 tok/s** | 22,326 MiB | Exact |
| 256K RULER `niah_multikey_3` (256,019 tok) | CUDA OOM | **42.7 tok/s** | 1,321 tok/s | 22,326 MiB | Exact (36-char UUID) |
| 256K RULER `qa_2` (256,022 tok) | CUDA OOM | 24.9 tok/s (short answer) | 1,331 tok/s | 22,326 MiB | Exact (`Coimbra`) |

*\*On the 32K step, shared cloud vCPU contention briefly throttled the single offloaded CPU MoE layer before decode returned to 44.8, 42.6, and 43.6 tok/s at 64K, 128K, and 256K. In a separate uncontended single-container L4 sweep (`qwen4_l4_24gb_clean_paired.json`), decode held smooth at 42.4, 43.4, 41.4, 40.3, 40.2, and 38.2 tok/s from 1K to 256K. Non-ECC 24 GB cards avoid CPU MoE contention entirely by keeping `-ngl 99` on GPU.*

---

## Quality, prefill, and MTP on A100-80GB

On A100-SXM4-80GB (`-c 262144 -b 2048 -ub 2048 -np 1`), API v12 brings 256K prefill to **83.4% of stock** (3,632 vs 4,357 tok/s, 6.7x faster than our first scalar build) and pushes 256K decode **+14.7% faster than stock FP16** (77.1 vs 67.2 tok/s) while saving 7.2 GiB of VRAM (23.0 vs 30.1 GiB, or 22.4 GiB at `-ub 512`):

![Qwen4-35B-A3B quality (256K RULER and 18-turn coding), 256K prefill progression to 3,632 tok/s, and paired v12 decode and MTP on A100-80GB.](https://zellige.ai/research/basinkv-qwen4/fig2_qwen4_a100_quality_and_prefill.png)

| Benchmark (A100-80GB, Qwen4-35B-A3B UD-Q4_K_M, `-c 262144`) | Stock QSA (FP16) | BasinKV INT8 v12 (recommended) | Delta / Notes |
|---|---:|---:|---|
| 256K Peak VRAM (`-ub 2048` / `-ub 512`) | 30,855 MiB (30.1 GiB) | **23,505 (23.0 GiB) / 22,905 MiB (22.4 GiB)** | -7.2 / -7.8 GiB |
| 128K Prefill / Decode (`-ub 2048`) | 4,176 pp / 79.7 tg | **4,023 pp / 79.6 tg** | 96.3% pp / 99.9% tg |
| 256K Prefill / Decode (`-ub 2048`) | 4,357 pp / 67.2 tg | **3,632 pp / 77.1 tg** | 83.4% pp / **+14.7% faster tg** |
| 256K Prefill / Decode (`-ub 512`) | *(above)* | **2,730 pp / 76.6 tg** | fits 22.4 GiB (+13.9% vs stock tg) |
| 256K Prefill (`-b 4096 -ub 4096`) | 4,616 pp (32.2 GiB) | **3,771 pp (23.7 GiB)** | 81.7% pp, -8.5 GiB |
| 256K RULER | 12/12 (100%) | **12/12 (100%)** + **6/6 v12** (3,233 to 3,308 pp) | exact match across all 6 tasks |
| 18-Turn Hidden-pytest Coding (16K/32K) | 12/18 (66.7%, 0 stale) | **15/18 (83.3%, 0 stale)** | WHT-INT4 dropped to 6/18 (33.3%) |
| Paired 54K MTP (`draft-mtp -n 3`) | 81.5 to 91.4 tok/s (33.5 GiB) | **87.3 to 93.8 tok/s (26.2 GiB)** | faster than stock+MTP at -7.2 GiB |

**Why INT8 beats WHT-INT4 so sharply on Qwen4 coding.** Both `int8` and `wht_int4` use the exact same GPU VRAM at 256K (the quantization mode only changes host RAM) and both score 100% on 256K RULER, yet `wht_int4` fell from 15/18 to 6/18 on 18-turn coding. We verified D=256 WHT-INT4 against an FP64 reference (0 of 40,960 byte mismatches, 1.00000000 cosine) and ran a controlled 2x2 K/V quantization ablation on live Qwen4 activations (`qwen4_wht4_2x2_ablation.json`). The cause is architectural: Qwen4 applies `attn_k_norm` to K, keeping keys well-behaved, whereas unnormalized V carries 6.1x channel crest outliers (position-0 norm 129.1 vs 8.8 bulk). Quantizing V to 4-bit (K8V4, attention L2 error 0.0491) degrades outputs even more than quantizing K (K4V8, 0.0361), while symmetric INT8 (K8V8, 0.0046 L2) is 8.9x cleaner than even grouped V4 with FP16 sinks. Keep the default `--oasiskv-kv-quant int8` on Qwen4.

---

## Live on AMD Instinct MI300X and portable OKQ1 prompt caching

The same single-source CUDA/HIP core (`oasiskv_ggml_cuda.cu` and `oasiskv_gpu_compat.cuh`) was validated live on an AMD Instinct MI300X (`gfx942`, 192 GB HBM3, ROCm 7.15):

- **Standalone HIP suite (`hipcc`):** 20/20 tests pass in 9.98 s, covering both D=64 and D=256 (INT8 and WHT-INT4), MFMA scorer top-K golden parity, and `kv_rows` / Belady eviction. (The `OASISKV_DISABLE_UVA=1` toggle applies to the standard non-QSA pool; native QSA always streams cold pages over mapped host memory.)
- **Live `llama-server -DGGML_HIP=ON` (`-c 262144 -b 2048 -ub 2048`, identical prompt across all arms):** BasinKV INT8 beats stock FP16 decode at every depth while saving 7.0 GiB of VRAM (24.5 vs 31.5 GiB): 107.3 vs 100.7 tok/s (+6.5%) at 32K (6,544 pp, 98.3% of stock), 98.6 vs 89.4 tok/s (+10.3%) at 128K (6,033 pp), and **89.8 vs 78.3 tok/s (+14.7%)** at 256K (5,167 tok/s prefill, 70.0% of stock and 2.15x faster than our earlier scalar HIP scorer). WHT-INT4 reaches 90.3 tok/s (+15.3%) and 5,278 tok/s prefill at 256K. At 64K with native ROCm MTP (`draft-mtp -n 3`), BasinKV INT8 reaches **108.2 tok/s** (27.6 GiB) vs stock+MTP at 107.3 tok/s (36.4 GiB, 8.8 GiB less VRAM).
- **Portable OKQ1 v1 QSA prompt caching (`--oasiskv-cache-mode ram|nvme|mixed`):** QSA pools serialize with an 80-byte IEEE 802.3 CRC32-checked header shared across CUDA/HIP and Metal. On the same 15,976-token prompt on MI300X (all 5 arms exact):
  - **Cold prefill:** 2,795 ms prompt eval.
  - **Warm in-RAM prefix hit (15,972 cached):** **114 ms** (24.5x faster TTFT).
  - **Explicit `/slots/0?action=save` and `restore` (461.4 MiB on NVMe):** saves in 487 ms; restore plus eval takes **570 ms end-to-end wall-clock TTFT** (515 ms NVMe read plus 55 ms prompt eval, 4.9x true wall speedup). Fresh-server cross-restart restore takes 450 ms disk read plus 869 ms first-step warmup (1,318 ms total, exact match).
  - **Automatic process-local NVMe spill (`--oasiskv-cache-mode nvme`, 15,972 cached):** after evicting the slot with an unrelated request, automatic reload plus eval takes **685 ms end-to-end wall-clock TTFT** (583 ms NVMe load plus 102 ms prompt eval, 4.0x true wall speedup). Automatic `--oasiskv-cache-mode nvme|mixed` caches are process-local; use `/slots` save/restore for cross-restart persistence.

![Same-prompt paired AMD Instinct MI300X (ROCm 7.15) decode across 32K-256K and OKQ1 v1 RAM/NVMe prompt-cache TTFT including disk I/O.](https://zellige.ai/research/basinkv-qwen4/fig4_qwen4_mi300x_rocm_and_okq1.png)

---

## What makes API v12 fast on both CUDA and ROCm

1. **Compact per-8-query `ggml_flash_attn_ext_rows` and Future-Aware Belady prefill (540 to 2,428 to 3,632 tok/s on A100).** Instead of scanning a dense `[q_tile, 67840]` FP16 mask inside FlashAttention on every prefill tile, API v12 builds compact per-8-query index lists on SM 75+ GPUs (`GGML_OASISKV_CAP_QSA_KV_ROWS`, disableable via `OASISKV_QSA_KV_ROWS=0`), cutting FlashAttention tile time in half. Chunk-wide batched scoring (128 queries per launch) computes each pool's future last-tile use across the chunk so prefill eviction follows Future-Aware Belady rather than blind CLOCK, cutting host PCIe misses.
2. **CDNA `v_mfma_f32_16x16x16_f16` scorer, CDNA D=256 sparse FlashAttention, and coalesced HIP fences.** On AMD CDNA (`gfx908` through `gfx950`), `qsa_score_pools_tile_mfma_kernel` runs directly on matrix cores with zero register spills (with a bank-conflict-free `half2` path on RDNA/GCN), while `fattn.cu` unlocks upstream's `DKQ=256 (ncols1=8, ncols2=8)` sparse MMA FlashAttention kernel (+3.5% 256K prefill on MI300X; `GGML_HIP_NO_SPARSE_FA_D256=1` restores dense for A/B testing). Coalescing per-tile HIP completion fences inside graph segments keeps the 32-event ring from stalling mid-prefill.
3. **16-byte vectorized UVA miss-fill, deterministic 512-thread CLOCK, and lazy prefill scratch release.** Both decode and MTP verify use 16-byte `uint4` coalesced PCIe UVA reads sized to `4 * SM` waves, warp-aggregated radix Top-K, and a deterministic 512-thread 2-sweep CLOCK allocator. After a prompt's final chunk commits, the next decode or verify step lazily frees the per-device prefill scratch (170 to 182 MiB), and tile outputs land via an in-place `ggml_set_2d_inplace` chain rather than a 63-node concat tree.
4. **Exact trained QSA math, monotonic stale-ring exclusion (`d_ring_lo`), and ROCm rounding parity.** BasinKV keeps only pooled FP16 indexer keys on GPU (64 B/tok/layer, 8x smaller than stock), tracks a monotonic `d_ring_lo` lower bound so speculative MTP rollbacks never read stale ring slots, and inserts a zero-cost `asm volatile("" : "+v"(v))` barrier in `dequant_i8_to_hot` to stop ROCm `clang 23` from contracting `float(int8) * scale -> __half` into single-rounded `v_fma_mixlo_f16`.

---

## Try it on Qwen4-35B-A3B

*(Repository paths and CLI flags retain the `oasiskv` namespace.)*

```bash
git clone https://github.com/zellige-ai/basinkv && cd basinkv
git clone https://github.com/ggml-org/llama.cpp /tmp/llama.cpp
git -C /tmp/llama.cpp checkout 15dd330d5529f7fbb158f2b0a9e93cec5fbcf548
python3 integrations/llamacpp/apply_llamacpp_wiring.py /tmp/llama.cpp

# NVIDIA CUDA (80=A100, 86=RTX 3090, 89=L4/RTX 4090, 120=RTX 5090)
cmake -S /tmp/llama.cpp -B /tmp/llama.cpp/build-cuda \
  -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES="80;86;89" -DCMAKE_BUILD_TYPE=Release
cmake --build /tmp/llama.cpp/build-cuda --target llama-server llama-bench -j

# AMD ROCm/HIP (CMake >= 3.28 requires clang++ as CMAKE_HIP_COMPILER)
HIPCXX=/opt/rocm/llvm/bin/clang++ HIP_PATH=/opt/rocm \
cmake -S /tmp/llama.cpp -B /tmp/llama.cpp/build-hip \
  -DGGML_HIP=ON -DGPU_TARGETS="gfx942" -DCMAKE_HIP_COMPILER=/opt/rocm/llvm/bin/clang++ -DCMAKE_BUILD_TYPE=Release
cmake --build /tmp/llama.cpp/build-hip --target llama-server llama-bench -j

# Serve Qwen4-35B-A3B at 256K with OKQ1 prompt caching
# Point -m at shard 1 of Unsloth's 2-shard UD-Q4_K_M GGUF; add --n-cpu-moe 1 on ECC 24 GB L4
/tmp/llama.cpp/build-cuda/bin/llama-server \
  -m Qwen4-35B-A3B-UD-Q4_K_M-00001-of-00002.gguf -ngl 99 -c 262144 -b 2048 -ub 512 -fa on -np 1 \
  --oasiskv --oasiskv-kv-quant int8 \
  --oasiskv-cache-mode mixed --oasiskv-cache-dir /tmp/basinkv_cache --oasiskv-cache-ram-mb 8192
# Append `--spec-type draft-mtp --spec-draft-n-max 3` for native MTP speculative decoding
```

---

## Practical notes and limits

- **24 GB L4 with MTP at 256K:** Passing `--spec-draft-type-k q8_0 --spec-draft-type-v q8_0` (or `q4_0`) shrinks the 1-layer MTP draft KV cache (512 to 272 to 144 MiB), but the real 256K bottleneck on ECC L4 (22.1 GiB usable) is MTP's 1,057 MiB `graph_reserve` compute buffer. Combining 256K with `draft-mtp` needs `--n-cpu-moe 3` or `-c 131072` on ECC L4; non-ECC 24.0 GiB RTX 3090 and 4090 cards fit `-ngl 99` at 256K without MTP (22.4 to 23.0 GiB).
- **Apple Silicon Metal QSA:** All 27 MSL 2.4 QSA kernels (at most 24,576 B of threadgroup memory across all 48 Metal kernels) and `ggml-metal/oasiskv.mm` (OKQ1 v1 and `GGML_OASISKV_CAP_QSA`) pass 20/20 CPU MSL emulator tests (434 QSA checks, 6,178+ total, zero failures; `-Wall -Wextra -Werror` clean), while bare-metal Apple7+ macOS Qwen4 execution is still pending hardware access. Non-QSA Metal models are already live-verified on macOS.
- **Qwen4 on SGLang and vLLM V1:** Native QSA offloading is currently in `llama.cpp`; SGLang and vLLM V1 QSA integrations are planned.

### Other changes since the launch post

Alongside Qwen4 support, `main` includes several follow-up items requested in the launch thread:

- **Native MTP and faster prefill in `llama.cpp`:** `draft-mtp`, `draft-simple`, `draft-eagle3`, and `ngram-*` across `-np 1..256` (Qwen3.6-35B-A3B reaches 209.1 tok/s, +58% at 27K on A100), plus geometrically-grown 1-layer prefill scratch (96 to 98% of dense prefill on Qwen3.6 at 16K to 64K) and inline indexed-bias prefill for Inkling 2 Mini.
- **More model families live-verified on GPU:** Gemma 4 (31B, 26B-A4B, and E4B Shared-KV), Gemma 3 (27B, 4B), gpt-oss 20B, and Inkling 2 Mini, plus parallel slots (`-np 1..256`) and Windows MSVC fixes.
- **vLLM 0.34.0 `SupportsHMA` and SGLang SWA OKVP1:** Atomic multi-group RAM/NVMe prefix caching across Full, SWA, and lossless recurrent (`MambaSpec`) layers on unmodified vLLM 0.34.0 and SGLang.

---

## Read more

- **BasinKV launch post and paper:** [Launch Post](https://zellige.ai/research/basinkv-launch) | [Technical Paper](https://zellige.ai/research/basinkv)
- **Model compatibility and flags:** [Supported Models](https://github.com/zellige-ai/basinkv/blob/main/docs/SUPPORTED_MODELS.md) | [Tinkering & Tuning Guide](https://github.com/zellige-ai/basinkv/blob/main/docs/TINKERING_AND_TUNING.md)
- **Raw measurements and hardware logs:** [Benchmark Log](https://github.com/zellige-ai/basinkv/blob/main/docs/summaries/benchmark-track-a-oasiskv.md)
