Skip to content

Host-RAM KV cache with CPU decode attention (STRATA_KV_HOST): 128K context for a 27B model on 12 GB - #106

Open
neokuze wants to merge 3 commits into
RustingStudio:mainfrom
UnsyncLabs:kv-cpu-attn
Open

neokuze wants to merge 3 commits into
RustingStudio:mainfrom
UnsyncLabs:kv-cpu-attn

Conversation

@neokuze

@neokuze neokuze commented Nov 25, 2026 •

Copy link
Copy Markdown

Hi! I've been running RustingStrata as my daily local inference server and hit a wall with context length on a 12 GB card, so I tried keeping the KV cache in RAM. It worked well enough that I think it's worth sharing.

My setup

  • GPU: RTX 4070 SUPER, 12 GB
  • CPU: Ryzen 5 9600X (6 cores / 12 threads, AVX-512 + VNNI)
  • RAM: 60 GB DDR5
  • OS: CachyOS (Linux 7.3)

How I run models on it

  • Qwen3.6-35B-A3B Q5_K is my daily driver. The experts spill to RAM, which leaves room on the card for a 128K context: --ctx 131072 --kv q4 --chunk 512 --vram-margin 2048. It runs at ~75 tok/s with a long context and 110–120 tok/s with a short one.
  • Qwen3.8-27B (12 GB GGUF) is dense, so its weights alone fill the card. With --chunk 512 --kv q4 --vram-margin 0 it topped out at 32K, and 48K+ ran out of memory.
  • I also use Inkling 2 Mini, and DeepSeek-V4.1-Flash UD-IQ1_S (~4 tok/s, for testing only).
  • The server sits behind a Telegram bot and an editor, using the OpenAI-compatible API.

What this PR does

STRATA_KV_HOST=all (or =N for blocks N and up) keeps the KV cache of the attention layers in host RAM and computes their decode attention on the CPU. The GPU only hands over the queries and gets back the partials, which attn_merge already knows how to combine. Qwen3.8 has only 16 attention layers out of 65, so the CPU side stays light.

Qwen3.8-27B with STRATA_KV_HOST=all --ctx 131072 --kv q4 --chunk 512 --vram-margin 0:

Context Before GPU reading the cache over PCIe This PR
short 28 tok/s 28 tok/s 30 tok/s
10K 30 tok/s (32K max) — 24 tok/s
52K doesn't load 3.3 tok/s 14.7 tok/s
92K doesn't load 2.0 tok/s not measured

Every version answered correctly on a 52K-token code summary, and the output matches the scalar path.

Prefill (second commit): for each host layer, prefill DMA-copies the layer's cache prefix into a VRAM staging pair (~150 MB at 128K) and runs the usual attn_prefill on that copy, instead of the kernel reading mapped memory over PCIe:

Prompt Over PCIe Staged, --chunk 512 Staged, --chunk 1024
10K 486 tok/s 786 tok/s —
52K 183 tok/s (~4m45s) 658 tok/s 698 tok/s (~75s)

STRATA_HA_NO_STAGE turns it off. If the staging doesn't fit, the load says so and prefill falls back to PCIe.

Without the env var nothing changes: allocation and the decode path are exactly as before.

Changes

  • src/host_attn.rs: the CPU decode attention, AVX-512 with int8 VNNI scores for the q4 cache, a portable fallback, and its own rayon pool.
  • src/backend.rs: two default methods, alloc_host and attn_host, so other backends are unaffected.
  • src/cuda/mod.rs: host KV on 2 MB pages registered as mapped memory, and the hand-off through a stream host function (or a mailbox with STRATA_HA_MAILBOX).
  • src/cuda/kernels.cu: ha_post / ha_wait for the optional mailbox.
  • src/gpu_model.rs: picks host allocation per layer, takes the CPU path in decode and in the MTP head, and allocates the prefill staging.
  • src/gpu_model/prefill.rs: copies a host layer's cache prefix into the staging before its prefill attention.
  • examples/host_attn_bench.rs: a micro-benchmark for the CPU kernel.

Notes

  • The global pool has one thread per physical core. This kernel gains from SMT (2.8 → 2.2 ms per layer at 52K), hence the separate pool.
  • The mailbox measured the same as the host function (14.7 vs 14.6 tok/s), so the host function is the default.
  • MTP works, but at long context the CPU attention for the draft tokens costs more than MTP saves.
  • I only tested CUDA on this machine. HIP gets ha_post/ha_wait through compat.h but I couldn't try it.

Happy to rework anything. This is my first contribution here.

… host RAM and runs their decode attention on the CPU

The cache sits in mapped pinned memory on 2 MB pages; for each attention layer the GPU hands the queries to a
stream host function (or, with STRATA_HA_MAILBOX, a spinning worker), the CPU walks the cache (AVX-512, int8
VNNI scores for q4) on its own pool over all logical cores, and attn_merge applies the gate. Prefill still reads
the cache over PCIe. Qwen3.8-27B (12 GB GGUF) on an RTX 4070 SUPER 12 GB: 128K context, 14.7 tok/s at 52K.
@aletheore

aletheore Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/backend.rs"]
    n1["src/cuda/mod.rs"]
    n2["src/gpu_model.rs"]
    n3["lib.rs"]
    n4["cpu_worker.rs"]
    n5["src/deepseek/chat.rs"]
    n6["mat.rs"]
    n7["expert_cache.rs"]
    n8["src/gemma4/mod.rs"]
    n9["gguf.rs"]
    n10["src/glm/forward.rs"]
    n11["src/glm/mod.rs"]
    n12["src/hip/mod.rs"]
    n13["src/hy4/chat.rs"]
    n14["src/hy4/mod.rs"]
    n15["src/inkling2/chat.rs"]
    n16["dspark.rs"]
    n17["src/inkling2/forward.rs"]
    n18["device.rs"]
    n19["src/inkling2/mod.rs"]
    n20["src/kolibri/chat.rs"]
    n21["src/kolibri/mod.rs"]
    n22["main.rs"]
    n23["model.rs"]
    n24["ngram.rs"]
    n25["serve.rs"]
    n26["src/vulkan/mod.rs"]
    n27["preflight.rs"]
    n28["weights.rs"]
    n29["tests/backend.rs"]
    n30["tests/common/mod.rs"]
    n31["tests/gpu_model.rs"]
    n32["kernels.rs"]
    n33["kv_q8.rs"]
    n34["llama_numerics.rs"]
    n35["vision.rs"]
    n0 --> n4
    n0 --> n6
    n0 --> n7
    n0 --> n12
    n0 --> n16
    n0 --> n17
    n0 --> n18
    n0 --> n22
    n0 --> n23
    n0 --> n26
    n0 --> n29
    n0 --> n30
    n0 --> n31
    n0 --> n32
    n0 --> n33
    n0 --> n34
    n1 --> n12
    n1 --> n18
    n1 --> n26
    n1 --> n27
    n1 --> n30
    n1 --> n31
    n1 --> n33
    n1 --> n34
    n2 --> n22
    n2 --> n23
    n2 --> n26
    n2 --> n29
    n2 --> n35
    n3 --> n5
    n3 --> n6
    n3 --> n7
    n3 --> n8
    n3 --> n9
    n3 --> n10
    n3 --> n11
    n3 --> n13
    n3 --> n14
    n3 --> n15
    n3 --> n19
    n3 --> n20
    n3 --> n21
    n3 --> n22
    n3 --> n23
    n3 --> n24
    n3 --> n25
    n3 --> n27
    n3 --> n28
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 changed
    class n2 changed
    class n3 changed
    class n4 dependent
    class n5 dependent
    class n6 dependent
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
    class n14 dependent
    class n15 dependent
    class n16 dependent
    class n17 dependent
    class n18 dependent
    class n19 dependent
    class n20 dependent
    class n21 dependent
    class n22 dependent
    class n23 dependent
    class n24 dependent
    class n25 dependent
    class n26 dependent
    class n27 dependent
    class n28 dependent
    class n29 dependent
    class n30 dependent
    class n31 dependent
    class n32 dependent
    class n33 dependent
    class n34 dependent
    class n35 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • examples/host_attn_bench.rs · +27/-0 · new file, 1 symbol
  • src/backend.rs · modified · +6/-0 · +2 functions · 16 other dependents
  • src/cuda/kernels.cu · modified · +27/-0
  • src/cuda/mod.rs · modified · +88/-5 · +3 functions, +1 class · 8 other dependents
  • src/gpu_model.rs · modified · +32/-9 · +1 function · 5 other dependents
  • src/gpu_model/prefill.rs · modified · +10/-1
  • src/host_attn.rs · +379/-0 · new file, 19 symbols
  • src/lib.rs · modified · +1/-0 · 19 other dependents

Aggregate deltas

  • Modules: +2
  • Dependency graph edges: +5
  • Commits: 3

Comment thread src/host_attn.rs
let mut acc = _mm512_setzero_ps();
for j in 0..4 {
let dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), z[j], _mm512_loadu_si512(qqp.add(row * hd + 64 * j) as *const _));
let v = _mm512_fmsub_ps(_mm512_cvtepi32_ps(dot), _mm512_loadu_ps(qsp.add(row * 64 + 16 * j)), _mm512_loadu_ps(clp.add(row * 64 + 16 * j)));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 8

VNNI K-score bias omits the factor 8 of the q4 offset, so scores are wrong Nibbles are unsigned 0..15 and the true value is n-8, so sum(nq)-8sum(q) is needed. The code sets cl = dsum (no 8), so each score is off by dkqssum7. Attention weights are wrong for every token whenever the VNNI path runs (AVX-512 VNNI CPUs).

Prompt for your AI agent
File: src/host_attn.rs
Line: 165
Issue: VNNI K-score bias omits the factor 8 of the q4 offset, so scores are wrong Nibbles are unsigned 0..15 and the true value is n-8, so sum(n*q)-8*sum(q) is needed. The code sets cl = d*sum (no 8), so each score is off by dk*qs*sum*7. Attention weights are wrong for every token whenever the VNNI path runs (AVX-512 VNNI CPUs).
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/gpu_model.rs
g.attn_decode_q(eg.q.addr(), kc[self.cur].addr(), vc[self.cur].addr(), 0, eg.att.addr(),
eg.attp.addr(), h.step_buf.addr(), nh, nkv, hd, 1.0 / (hd as f32).sqrt(), gq, nt, 0, 0, 0, 0, 0)?;
if !(crate::host_attn::on_host(self.m.cfg.n_layer)
&& g.attn_host(eg.q.addr(), kc[self.cur].addr(), vc[self.cur].addr(), 0, eg.att.addr(), h.step_buf.addr(), nh, nkv, hd, 1.0 / (hd as f32).sqrt(), nt)?) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 8

eg path checks on_host(n_layer) instead of the layer index il kv_alloc places layer il's cache in device memory when il < STRATA_KV_HOST, but attn_host is called because on_host(n_layer) is true. The CPU worker then dereferences a device pointer, causing a crash or garbage attention for those layers.

Prompt for your AI agent
File: src/gpu_model.rs
Line: 3012
Symbol: mtp_forward
Issue: eg path checks on_host(n_layer) instead of the layer index il kv_alloc places layer il's cache in device memory when il < STRATA_KV_HOST, but attn_host is called because on_host(n_layer) is true. The CPU worker then dereferences a device pointer, causing a crash or garbage attention for those layers.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/gpu_model.rs
vc: (0..ns).map(|_| gpu.zeros::<u16>(gpu.kv_words(ctx * kv))).collect::<anyhow::Result<_>>()?,
kc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words(ctx * kv) * 2)).collect::<anyhow::Result<_>>()?,
vc: (0..ns).map(|_| kv_alloc(gpu.as_ref(), il, gpu.kv_words(ctx * kv) * 2)).collect::<anyhow::Result<_>>()?,
qsa: if qsa_on && il < c.n_layer && m.w.layer(il, "indexer.k_proj.weight").is_ok() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 3 of 8

Device KV caches are no longer zeroed (zeros replaced by alloc) The old code used gpu.zeros, which zeroed the cache. kv_alloc uses gpu.alloc for device layers, and alloc does not promise zeroed memory (alloc_host documents zeroing explicitly). Unwritten q4 scale bytes can be NaN or garbage, and the seq counter in HA_STAGE is also uninitialized. Output can become non-deterministic.

Prompt for your AI agent
File: src/gpu_model.rs
Line: 747
Symbol: load_part
Issue: Device KV caches are no longer zeroed (zeros replaced by alloc) The old code used gpu.zeros, which zeroed the cache. kv_alloc uses gpu.alloc for device layers, and alloc does not promise zeroed memory (alloc_host documents zeroing explicitly). Unwritten q4 scale bytes can be NaN or garbage, and the seq counter in HA_STAGE is also uninitialized. Output can become non-deterministic.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/gpu_model.rs
let aq = g.attn_decode_q(p("q"), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { p("qg") } else { 0 }, p("att"), p("attp"), step, nh, nkv, hd,
1.0 / (hd as f32).sqrt(), gq, nt, if out_gemm { 0 } else { p("attq") }, sel, sst, sink_addr, win)?;
let host = sel == 0 && sink_addr == 0 && win == 0 && crate::host_attn::on_host(il)
&& g.attn_host(p("q"), kc[self.cur].addr(), vc[self.cur].addr(), if c.q_gate { p("qg") } else { 0 }, p("att"), step, nh, nkv, hd, 1.0 / (hd as f32).sqrt(), nt)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 4 of 8

Host path skips attn_decode_q, so attq and its return value are never produced When attn_host succeeds, aq becomes 0 and attq is never written. Any later step that reads the quantized attention output (attq) or relies on aq gets stale or zero data when out_gemm or attq is in use, which silently corrupts the layer output.

Prompt for your AI agent
File: src/gpu_model.rs
Line: 3272
Symbol: layer
Issue: Host path skips attn_decode_q, so attq and its return value are never produced When attn_host succeeds, aq becomes 0 and attq is never written. Any later step that reads the quantized attention output (attq) or relies on aq gets stale or zero data when out_gemm or attq is in use, which silently corrupts the layer output.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/mod.rs
let len = bytes.max(1).next_multiple_of(HP);
let mut m = memmap2::MmapMut::map_anon(len + HP)?;
#[cfg(target_os = "linux")]
let _ = m.advise(memmap2::Advice::HugePage);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 5 of 8

Failed cuMemHostRegister or device-pointer check leaks registration and unmaps memory If cuMemHostGetDevicePointer fails or dev != h, the function returns an error before Reg is built. The MmapMut is dropped (munmap) while CUDA still holds the host registration, so the driver keeps a dangling pinned mapping. Later GPU or CUDA access to that range can fault or corrupt memory.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 948
Symbol: beside
Issue: Failed cuMemHostRegister or device-pointer check leaks registration and unmaps memory If cuMemHostGetDevicePointer fails or dev != h, the function returns an error before Reg is built. The MmapMut is dropped (munmap) while CUDA still holds the host registration, so the driver keeps a dangling pinned mapping. Later GPU or CUDA access to that range can fault or corrupt memory.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/mod.rs
}

fn attn_host(&self, q: u64, kc: u64, vc: u64, qg: u64, out: u64, step: u64, nh: usize, nkv: usize, hd: usize, scale: f32, nt: usize) -> anyhow::Result<bool> {
if self.kv_mode > 2 || nt > HA_T || hd % 32 != 0 || nh % nkv != 0 || nh * (hd + 2) > HA_W { return Ok(false); }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 6 of 8

CTX cache keyed only by (kc, vc, nt); stale HostAttn can be reused Entries omit nh, nkv, hd, scale and mode. If a model is unloaded and its KV addresses are reused by a different model config, the cached leaked HostAttn carries the old geometry and gives wrong or out-of-bounds attention. The entries are also leaked forever.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 972
Symbol: graph
Issue: CTX cache keyed only by (kc, vc, nt); stale HostAttn can be reused Entries omit nh, nkv, hd, scale and mode. If a model is unloaded and its KV addresses are reused by a different model config, the cached leaked HostAttn carries the old geometry and gives wrong or out-of-bounds attention. The entries are also leaked forever.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/host_attn.rs
let mm = parts.iter().map(|p| p.0[r]).fold(f32::NEG_INFINITY, f32::max);
let o = &mut part[r * (hd + 2)..(r + 1) * (hd + 2)];
o.fill(0.0);
let mut l = 0.0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Correctness · 7 of 8

Panic inside the extern C host callback unwinds across FFI run is called from the driver's callback thread with no catch_unwind. An index or unwrap panic in run_inner (e.g. a negative position cast to usize) unwinds through an extern "C" boundary, which aborts the process or is undefined behaviour.

Prompt for your AI agent
File: src/host_attn.rs
Line: 330
Issue: Panic inside the extern C host callback unwinds across FFI run is called from the driver's callback thread with no catch_unwind. An index or unwrap panic in run_inner (e.g. a negative position cast to usize) unwinds through an extern "C" boundary, which aborts the process or is undefined behaviour.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/host_attn.rs
let r = kc.add((p * nkv + g) * rb);
let d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(_mm_loadu_si128(r.add(hd / 2) as *const __m128i)));
let mut z = [_mm512_setzero_si512(); 4];
let mut dk = [_mm512_setzero_ps(); 4];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 8 of 8

Query int8 quantization is recomputed in every parallel chunk kscores_vnni quantizes all ntnhhd queries and allocates qq/qs/cl again for each 1024-position chunk. For a 52K-context layer that is about 50 redundant passes and allocations per call, adding avoidable latency on the decode hot path.

Prompt for your AI agent
File: src/host_attn.rs
Line: 150
Issue: Query int8 quantization is recomputed in every parallel chunk kscores_vnni quantizes all nt*nh*hd queries and allocates qq/qs/cl again for each 1024-position chunk. For a 52K-context layer that is about 50 redundant passes and allocations per call, adding avoidable latency on the decode hot path.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

@aletheore

aletheore Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

What this PR does. This PR adds an opt-in STRATA_KV_HOST mode that keeps the KV cache in registered host RAM and runs decode attention on the CPU, aiming to fit 128K context for a 27B model on a 12 GB GPU. The diff itself is a fix to the CUDA host-memory path: it moves the unregister guard so a failure after cuMemHostRegister cleans up correctly, and it widens the attention-context cache key to include head counts, dimensions, mode, and scale so a reloaded model can't pick up a stale context.

Merge confidence Review effort Merge risk
2 / 5 1 / 5 Medium
Area Files Lines
src/cuda 1 +7 −2

2 finding(s) posted as inline review comment(s). 10 earlier finding(s) from previous pushes still open.

# Severity Category Where
1 🟠 High Correctness mod.rs:984 The CTX lookup dereferences raw pointers e.3 for every entry, which dangle once a HostAttn is freed. CTX…
2 🔵 Low Maintainability mod.rs:984 Cache key is now compared field-by-field through pointers, which duplicates the key and invites drift. The…
- 🟠 High Correctness host_attn.rs:165 Earlier finding, still open
- 🟠 High Correctness gpu_model.rs:3012 Earlier finding, still open
- 🟠 High Correctness gpu_model.rs:747 Earlier finding, still open
- 🟡 Medium Correctness gpu_model.rs:3272 Earlier finding, still open
- 🟡 Medium Correctness mod.rs:948 Earlier finding, still open
- 🟡 Medium Correctness mod.rs:972 Earlier finding, still open
- 🟡 Medium Correctness host_attn.rs:330 Earlier finding, still open
- 🔵 Low Performance host_attn.rs:150 Earlier finding, still open
- 🟠 High Correctness prefill.rs:488 Earlier finding, still open
- 🔵 Low Performance prefill.rs:489 Earlier finding, still open
Review details

Reviewed 1 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 2 of 2 proposed finding(s).

Fix all with your agent
File: src/cuda/mod.rs
Line: 984
Symbol: host_mailbox
Issue: The CTX lookup dereferences raw pointers e.3 for every entry, which dangle once a HostAttn is freed. CTX stores each cached HostAttn as a raw address (e.3). If a model is unloaded and its HostAttn is dropped without removing the CTX entry, the next call to the find closure dereferences the freed pointer. That is undefined behaviour: it can read garbage fields, match a wrong entry, or crash. The new closure reads every entry on each lookup, so it widens the window in which a stale entry is touched.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

File: src/cuda/mod.rs
Line: 984
Symbol: host_mailbox
Issue: Cache key is now compared field-by-field through pointers, which duplicates the key and invites drift. The key is spelled out across eight comparisons in the closure and stored only indirectly through e.3. Adding or renaming a field in HostAttn, or changing the mode cast, can silently leave the key incomplete, so two distinct configurations match the same cached attention object. Keeping a derived PartialEq key struct next to the pointer in CTX would remove both the unsafe deref and the duplicated comparison list.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

The pull request description says: "HIP gets ha_post/ha_wait through compat.h but I couldn't try it.". This review read the diff only: it did not compile or run the code, so it cannot confirm that part works.

Blast radius: 58 other file(s) depend on what this PR changes (10 directly, 48 indirectly)

Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.

  • src/cuda/mod.rs is imported by src/backend.rs, src/hip/mod.rs, src/inkling2/forward/device.rs, src/lib.rs (+6 more)

Indirectly affected: examples/gguf_dump.rs, src/chat.rs, src/config.rs, src/cpu_moe.rs, src/cpu_worker.rs, src/deepseek/chat.rs (+42 more)

… staging pair and runs the usual attention on it

A DMA copy instead of the attention kernel reading mapped memory over PCIe. Qwen3.8-27B, RTX 4070 SUPER: prefill
at 52K from 183 to 658 tok/s (--chunk 512) or 698 tok/s (--chunk 1024); 10K from 486 to 786 tok/s.
STRATA_HA_NO_STAGE turns it off; without the VRAM for it the load says so and prefill reads over PCIe as before.
Comment thread src/gpu_model/prefill.rs
let (kca, vca) = match &self.kv_stage {
Some((sk, sv)) if crate::host_attn::on_host(il) => {
let bytes = (g.kv_words((self.pos + t) * kv) * 2).min(sk.len());
g.dtod(&kc[self.cur], 0, sk, 0, bytes)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 2 of 4

Byte count assumes 2 bytes per element and is silently clamped with min(). The * 2 assumes a 2-byte cache element, but this run uses --kv q4, where elements are quantized and the size differs. If kv_words returns a count that does not match the stored layout, bytes is too small. The .min(sk.len()) clamp then hides the mismatch: the copy stops short without an error, and attention reads a truncated or misaligned prefix with no diagnostic.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 488
Symbol: prefill_chunk
Issue: Byte count assumes 2 bytes per element and is silently clamped with min(). The `* 2` assumes a 2-byte cache element, but this run uses `--kv q4`, where elements are quantized and the size differs. If kv_words returns a count that does not match the stored layout, `bytes` is too small. The `.min(sk.len())` clamp then hides the mismatch: the copy stops short without an error, and attention reads a truncated or misaligned prefix with no diagnostic.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/gpu_model/prefill.rs
Some((sk, sv)) if crate::host_attn::on_host(il) => {
let bytes = (g.kv_words((self.pos + t) * kv) * 2).min(sk.len());
g.dtod(&kc[self.cur], 0, sk, 0, bytes)?;
g.dtod(&vc[self.cur], 0, sv, 0, bytes)?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Performance · 3 of 4

Each prefill chunk re-copies the full cache prefix to VRAM, giving quadratic PCIe traffic. With chunk 512 and a 128K prompt there are 256 chunks. Chunk i copies roughly i512 tokens of K and V per host layer. Total copy volume is about n^2/(2chunk) tokens per layer, around 16G token-KV entries for 16 layers. Prefill throughput collapses at long context, which is the case this PR targets. Copying only the new chunk's region, or keeping the prefix resident, would avoid this.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 489
Symbol: prefill_chunk
Issue: Each prefill chunk re-copies the full cache prefix to VRAM, giving quadratic PCIe traffic. With chunk 512 and a 128K prompt there are 256 chunks. Chunk i copies roughly i*512 tokens of K and V per host layer. Total copy volume is about n^2/(2*chunk) tokens per layer, around 16G token-KV entries for 16 layers. Prefill throughput collapses at long context, which is the case this PR targets. Copying only the new chunk's region, or keeping the prefix resident, would avoid this.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

…ot by the cache addresses and token count (a model loaded later could reuse a freed cache's addresses with other head shapes); a failed device-pointer lookup unregisters the host range before the mapping is freed
Comment thread src/cuda/mod.rs
// Keyed by every field: a model loaded later can reuse a freed cache's addresses with other shapes.
let same = |a: &crate::host_attn::HostAttn| a.kc == kc as usize && a.vc == vc as usize && a.nt == nt && a.nh == nh
&& a.nkv == nkv && a.hd == hd && a.mode == self.kv_mode as u32 && a.scale.to_bits() == scale.to_bits();
match c.iter().find(|e| same(unsafe { &*(e.3 as *const crate::host_attn::HostAttn) })) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Correctness · 1 of 2

The CTX lookup dereferences raw pointers e.3 for every entry, which dangle once a HostAttn is freed. CTX stores each cached HostAttn as a raw address (e.3). If a model is unloaded and its HostAttn is dropped without removing the CTX entry, the next call to the find closure dereferences the freed pointer. That is undefined behaviour: it can read garbage fields, match a wrong entry, or crash. The new closure reads every entry on each lookup, so it widens the window in which a stale entry is touched.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 984
Symbol: host_mailbox
Issue: The CTX lookup dereferences raw pointers e.3 for every entry, which dangle once a HostAttn is freed. CTX stores each cached HostAttn as a raw address (e.3). If a model is unloaded and its HostAttn is dropped without removing the CTX entry, the next call to the find closure dereferences the freed pointer. That is undefined behaviour: it can read garbage fields, match a wrong entry, or crash. The new closure reads every entry on each lookup, so it widens the window in which a stale entry is touched.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Comment thread src/cuda/mod.rs
// Keyed by every field: a model loaded later can reuse a freed cache's addresses with other shapes.
let same = |a: &crate::host_attn::HostAttn| a.kc == kc as usize && a.vc == vc as usize && a.nt == nt && a.nh == nh
&& a.nkv == nkv && a.hd == hd && a.mode == self.kv_mode as u32 && a.scale.to_bits() == scale.to_bits();
match c.iter().find(|e| same(unsafe { &*(e.3 as *const crate::host_attn::HostAttn) })) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low · Maintainability · 2 of 2

Cache key is now compared field-by-field through pointers, which duplicates the key and invites drift. The key is spelled out across eight comparisons in the closure and stored only indirectly through e.3. Adding or renaming a field in HostAttn, or changing the mode cast, can silently leave the key incomplete, so two distinct configurations match the same cached attention object. Keeping a derived PartialEq key struct next to the pointer in CTX would remove both the unsafe deref and the duplicated comparison list.

Prompt for your AI agent
File: src/cuda/mod.rs
Line: 984
Symbol: host_mailbox
Issue: Cache key is now compared field-by-field through pointers, which duplicates the key and invites drift. The key is spelled out across eight comparisons in the closure and stored only indirectly through e.3. Adding or renaming a field in HostAttn, or changing the mode cast, can silently leave the key incomplete, so two distinct configurations match the same cached attention object. Keeping a derived PartialEq key struct next to the pointer in CTX would remove both the unsafe deref and the duplicated comparison list.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant