Skip to content

kv share: share the recurrent state too, so a hybrid model's handoff moves no bytes - #181

Merged
bong-water-water-bong merged 1 commit into
1bit/hrx-vulkan-patchedfrom
1bit/kv-share-recurrent
Nov 4, 2026
Merged

bong-water-water-bong merged 1 commit into
1bit/hrx-vulkan-patchedfrom
1bit/kv-share-recurrent

Conversation

@bong-water-water-bong

Copy link
Copy Markdown

What this fixes

llama_kv_share_* covered llama_kv_cache only, so a hybrid model (llama_memory_hybrid, e.g. qwen35 with its
GDN layers) was refused outright and fell back to a llama.cpp sequence-state file. On the 27B this lane serves,
that file is 177 MB at ~300 prompt tokens and only 20 MB of it is KV: the constant is the 151 MB of recurrent state
(48 layers × 3.14 MB), written and read on every handoff no matter how long the prompt is. It never has to leave the
box — the decoder, the GPU and the NPU all address the same DRAM.

The recurrent memory has the same shape as the KV cache (per-buffer ggml contexts, non-view tensors, cell metadata
with a per-sequence tail), so it gets the same five pieces the KV cache already had.

The change

file what
src/llama-kv-share.h/.cpp the allocate/import halves move out of llama_kv_cache into llama_share_alloc / llama_share_import; the latter takes a cursor, because a hybrid's two memories consume one region list in a defined order (attention first). share_each becomes share_rec, recursing through llama_kv_cache_iswa, llama_memory_hybrid, llama_memory_hybrid_idx and llama_memory_hybrid_iswa down to the two leaves, so one call on a llama_context covers the whole memory
src/llama-kv-cache.h/.cpp thin wrappers over those helpers; share_import takes the cursor; share_regions appends instead of clearing, so a hybrid can collect both halves
src/llama-memory-recurrent.h/.cpp exported allocation in the constructor under llama_kv_share_enabled() (the owned buffer is still cleared, like before), plus share_regions, share_from, share_import, cells_copy_from, cells_adopt. cells_copy_from copies cell metadata only (cells, rs_idx, used, head, rs_z, n) — both memories are the same buffer. cells_adopt marks cell 0 as the sequence's tail at position n−1: a whole prompt's recurrent state lives in one cell, so that is the whole bookkeeping, and it refuses if another sequence holds cell 0
src/llama-ext.h, tools/server/server-task.{h,cpp}, server-context.cpp, tools/kvshare-prefill n_rs_seq travels with the share params, because it widens the recurrent rows to (1 + n_rs_seq) and a provider must build the same width; the "hybrid is not shareable" error message is gone because it is no longer true

Nothing changes without ONEBIT_KV_SHARE=1: without it no memory is allocated as a region and every code path is the
one it was.

Measured

Ternary-Bonsai-2-27B unrot Q4_0 (plain qwen35, 48 GDN + 16 full-attention layers), engine 22d8047f, llama.cpp
e0e2c26f5, gpu-hold ticket, 0 gfxhub faults. Three prompts (prose / a list / a code question), two lengths,
three routes: A = --device hrx (reference), C = the provider prefills into the decoder's own region over
?action=share → ?action=adopt, F = the same provider and the same math with the state going through a file.

C (shared) F (file)
answer identity vs A 6/6 identical 6/6 identical
transport: C == F 6/6 —
handoff share 0.39–0.78 ms (median 0.49), adopt ≤1 ms restore 18–39 ms (median 27)

Prompt lengths were 290–296 and 847–856 tokens; the file route's cost is flat-ish in prompt length because its floor
is the recurrent state, while the shared route is flat because it moves nothing.

Limits, stated as limits

  • The CPU stand-in's writes into the region are slower than into its own heap: provider prefill 10.8/11.0/12.9 s
    into the shared region against 8.0/7.1/7.7 s into its own memory at ~300 tokens (at ~850 tokens the samples overlap:
    24.9/24.6/24.9 vs 35.7/22.6/22.1 s, the file arm noisier). The shape — a large fixed cost, then a per-token rate
    ~1.2x worse — reads as first-touch page fault-in of the dma-buf mapping, which is coherent but uncached on this
    box (that is why the original probe found no flush was needed). A device provider writing the same region through
    its own DMA does not pay it; a direct mapping-throughput probe would pin the split and is not done here.
  • adopt/restore are printed by the engine to whole milliseconds, so "≤1 ms" is a resolution limit, not a
    measurement of 1.000.
  • cells_adopt is not atomic across the two halves: if the attention half adopts and the recurrent half then refuses
    (cell 0 held by another sequence), the attention cells are already taken. In the shipped single-slot route this
    cannot fire; a multi-slot version would want the check first.
  • The provider must start from the region's empty state (that is what makes cell 0 the state for its single sequence).
  • Tested on qwen35 (llama_memory_hybrid) only. llama_memory_recurrent on its own (Mamba/RWKV) and the
    iswa/hybrid_idx wrappers are covered by the same recursion and the same methods, but no device run exercised them.
  • Numerics: C == A held at both lengths here, but that is the provider's business (CPU vs HRX math) and this PR
    makes no claim about it at longer context.

…moves no bytes

llama_kv_share_* covered llama_kv_cache only, so a hybrid model (qwen35 and the
like) was refused and fell back to a llama.cpp sequence-state FILE. On the 27B
that file is 177 MB at 307 prompt tokens and only 20 MB of it is KV: the constant
is the GDN recurrent state (48 layers, 151 MB), written and read on every
handoff whatever the prompt length is. It never has to leave the box.

The recurrent memory is the same shape as the KV cache (per-buffer contexts,
non-view tensors, cell metadata), so it gets the same five pieces: share_regions,
share_from, share_import, cells_copy_from and cells_adopt. The allocation and
import halves move out of llama_kv_cache into llama_share_alloc /
llama_share_import so both classes use one implementation, the latter taking a
cursor because a hybrid's two memories consume one region list in a defined
order. share_each recurses through the hybrid/wrapper memories, so one call on a
llama_context covers the whole memory.

cells_copy_from copies cell metadata only (cells, rs_idx, used, head, rs_z, n).
cells_adopt marks cell 0 as the sequence's tail at position n-1: a recurrent
state for a whole prompt lives in one cell, so that is the whole bookkeeping, and
it refuses when another sequence holds cell 0.

n_rs_seq now travels with the share params, since it widens the recurrent rows to
(1 + n_rs_seq) and a provider must build the same width.

Gate (t1_gate.py on Ternary-Bonsai-2-27B-PTQ1_0, routes A/C/F):
@bong-water-water-bong bong-water-water-bong added the tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied label Nov 4, 2026

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

VERDICT: READY at e0e2c26f5. Built it here and read the whole change; the three things this shape usually gets
wrong (region ordering, gating, and adopting into a memory whose bookkeeping is per-cell) are each handled.

Build, this box (~/wt/tprs-181, CPU GGML_HRX=OFF, -DLLAMA_BUILD_UI=OFF): all three touched targets link —
llama-server, llama-cli, llama-kvshare-prefill — 332/332, zero warnings.
llama-kvshare-prefill --help shows the socket-side contract (--layout/--fds/--tokens).

Region ordering. share_each now recurses through llama_kv_cache_iswa, llama_memory_hybrid,
llama_memory_hybrid_iswa and both leaves (share_rec), and both sides run the same recursion, so a hybrid's
attention-then-recurrent order is identical for owner and provider without either side encoding it. The cursor
argument is what makes a mismatch loud rather than silent: llama_kv_cache::share_from and
llama_memory_recurrent::share_from both end on share_import(regions, next) && next == regions.size(), so
leftover regions are a failure, and llama_share_import checks chunks[c].size/layout against the owner's before
mapping anything — the layout hash includes the recurrent width, so a provider built without n_rs_seq fails closed
rather than mapping the wrong stride.

Gating. ONEBIT_KV_SHARE is read in exactly two places (server-context.cpp:1228, server-prefill.cpp:60),
llama_kv_share_next(true) is only called from those, and llama_context's kv_share_scope takes-and-clears the
pending request around model.create_memory — so without the variable llama_kv_share_enabled() is false for the
whole construction and llama_memory_recurrent's constructor takes the old ggml_backend_alloc_ctx_tensors_from_buft
branch unchanged. The "nothing changes without it" claim holds by construction, not by inspection of each path.

Adopting. cells_copy_from copies metadata only and refuses on a size/seq mismatch; cells_adopt refuses when
cell 0 is held by another sequence (naming it), sets the tail, and leaves the tensors alone. cells[seq_id].tail is
the tree's convention (cells[i].tail = -1 at init, read as cells[seq_id].tail in seq_add/seq_div), and
head = 0 is safe because find_slot starts scanning at head and skips occupied cells.

One thing the PR's own limits list does not mention: cells_adopt sets rs_z = 0. rs_z is "first cell
without src refs, to use as the zero-ed state" (llama-memory-recurrent.cpp:770-790), and after adopting a prompt
state into cell 0 that cell is not zeroed. In the shipped single-slot route this is invisible (the sequence's tail
is cell 0, so the next batch's cell gets src = 0), which is presumably why it measures 6/6 identical. But a
second sequence starting fresh while cell 0 holds real state would copy the adopted state as its "zero" state. It
belongs next to the "cells_adopt is not atomic across the two halves" note — the multi-slot version needs both
fixed together.

Not reproduced here: the device measurement. It needs the 27B Bonsai pack, HRX and the provider/decoder pair on a
gpu-hold ticket; the numbers (6/6 answer identity, share 0.39–0.78 ms vs restore 18–39 ms) are the lane's, and
the limits section states the CPU stand-in's write cost honestly rather than hiding it behind the median. CI: this
is a fork PR, no engine checks; mergeStateStatus CLEAN. Merge order: any (no engine pin move needed for the code
to exist; the engine row closes on the next pin bump).

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

READY on the code, with the merge-order caveat below.

All six changed translation units compile at this head with a real HRX build's flags:

src/llama-kv-cache.cpp  src/llama-kv-share.cpp  src/llama-memory-recurrent.cpp
tools/kvshare-prefill/kvshare-prefill.cpp  tools/server/server-context.cpp  tools/server/server-task.cpp   -> rc=0 each

The change I spent the time on is share_regions() no longer clearing: that is safe because its two call sites both hand it a container whose lifetime they own (llama_kv_share_regions() fills a local vector from one d.share_regions(regions) call, and the hybrid recursion appends attention-then-recurrent in the order llama_share_import()'s cursor expects). The cursor is also checked at both ends (next == regions.size() in llama_kv_share_import() and in the recurrent share_import), so a hybrid whose two halves disagree on region count fails rather than silently importing half a state. Nothing changes without ONEBIT_KV_SHARE=1, and n_rs_seq travelling with the cparams is required for the provider to build the same row width — good catch, that would have been a silent width mismatch.

Two notes for whoever merges: it is a behaviour change to a shipped path (hybrids go from "refused, falls back to a state file" to "shares"), so it wants the device A/B in the body — the 177 MB file vs no bytes, 0 gfxhub faults — read before landing, and fork #189 touches the same server slot-action struct (leave_one_token); they are in different members so they should merge, but that is the one pair to check together.

Not re-derived here: any of the three routes' numbers (needs the 27B and a GPU ticket).

@bong-water-water-bong
bong-water-water-bong merged commit 3bb5951 into 1bit/hrx-vulkan-patched Nov 4, 2026
bong-water-water-bong pushed a commit to 1bit-MONSTER/engine that referenced this pull request Nov 6, 2026
…not the decoder's own prefill

`ONEBIT_KV_SHARE=1` makes the hybrid route hand the prompt over as dma-buf fds, and the handshake has
one failure mode with no recovery in it: when the decoder refuses `?action=share` (a params or model
mismatch, or a hybrid cache on a pin without the recurrent-state arm), `prepare()` returned the refusal
and the provider never ran, so the request fell back to the decoder prefilling the whole prompt -- the
exact cost the hybrid route exists to remove.

Now the handshake failures (share refused, no share_id, no socket) fall back to the state-file route
for that request, which still keeps the prompt off the decoder's prefill path, and say so once:
`... this decoder cannot share its KV, so the state-file route is used`, with `share 0.000 ms` in the
per-request line. A provider that already wrote into the region, or an adopt that failed after it, is
still a plain fallback: falling back there would pay for the prefill twice.

Measured with tests/fake_backend.py in a new mode (`FAKE_KVSHARE_REFUSE=1`, a decoder that answers the
real refusal), one 30-token prompt, same binary before and after:

  before  hybrid: share answered 400: {...cannot be shared}; the backend prefills this request itself
          (no provider launch, no restore, id_slot unset)
  after   hybrid: share answered 400: {...cannot be shared}; this decoder cannot share its KV, so the
          state-file route is used
          hybrid: 30 prompt tokens: prefill 0 ms, restore 2 ms, share 0.000 ms, first byte 103 ms

Gates, all on today's main (29ec80c), device-free: `hybrid_kvshare_route` PASS with 6 new checks (the
new case fails 4 of them before the change), `hybrid_route` PASS, `hybrid_e2e` PASS against a real
llama-server and Qwen3-0.6B (identical greedy reply to `--device cpu`, `prompt_n 1, plain 22`),
`ctest -R hybrid` 2/2, `tools/copyright.py --check` clean.

docs/hybrid.md also loses a stale limit: the shared region has covered a hybrid model's recurrent state
since fork 1bit-MONSTER/llama.cpp#181, and the doc still said `?action=share` refuses a hybrid cache.

Same class as engine#941 (a handoff silently thrown away); part of engine#698.
bong-water-water-bong added a commit to 1bit-MONSTER/engine that referenced this pull request Nov 6, 2026
…not the decoder's own prefill (#1203)

* serve: a decoder that cannot share its KV gets the state-file route, not the decoder's own prefill

`ONEBIT_KV_SHARE=1` makes the hybrid route hand the prompt over as dma-buf fds, and the handshake has
one failure mode with no recovery in it: when the decoder refuses `?action=share` (a params or model
mismatch, or a hybrid cache on a pin without the recurrent-state arm), `prepare()` returned the refusal
and the provider never ran, so the request fell back to the decoder prefilling the whole prompt -- the
exact cost the hybrid route exists to remove.

Now the handshake failures (share refused, no share_id, no socket) fall back to the state-file route
for that request, which still keeps the prompt off the decoder's prefill path, and say so once:
`... this decoder cannot share its KV, so the state-file route is used`, with `share 0.000 ms` in the
per-request line. A provider that already wrote into the region, or an adopt that failed after it, is
still a plain fallback: falling back there would pay for the prefill twice.

Measured with tests/fake_backend.py in a new mode (`FAKE_KVSHARE_REFUSE=1`, a decoder that answers the
real refusal), one 30-token prompt, same binary before and after:

  before  hybrid: share answered 400: {...cannot be shared}; the backend prefills this request itself
          (no provider launch, no restore, id_slot unset)
  after   hybrid: share answered 400: {...cannot be shared}; this decoder cannot share its KV, so the
          state-file route is used
          hybrid: 30 prompt tokens: prefill 0 ms, restore 2 ms, share 0.000 ms, first byte 103 ms

Gates, all on today's main (29ec80c), device-free: `hybrid_kvshare_route` PASS with 6 new checks (the
new case fails 4 of them before the change), `hybrid_route` PASS, `hybrid_e2e` PASS against a real
llama-server and Qwen3-0.6B (identical greedy reply to `--device cpu`, `prompt_n 1, plain 22`),
`ctest -R hybrid` 2/2, `tools/copyright.py --check` clean.

docs/hybrid.md also loses a stale limit: the shared region has covered a hybrid model's recurrent state
since fork 1bit-MONSTER/llama.cpp#181, and the doc still said `?action=share` refuses a hybrid cache.

Same class as engine#941 (a handoff silently thrown away); part of engine#698.

* tests: an adopt refusal is not a handshake failure, so it must not take the state-file fallback

The fallback added in the previous commit is deliberately limited to the handshake (share refused, no share_id, no
socket). The boundary is worth a case of its own, because the wrong side of it is expensive rather than wrong-looking:
if an `?action=adopt` refusal also fell back, the engine would re-run the whole prompt through the state-file route
after the provider had already prefilled it -- paying for the prefill twice, which is the failure the route exists to
avoid.

New arm: `FAKE_KVSHARE_ADOPT_REFUSE=1` makes the decoder refuse the adopt the way the real one does when another
sequence holds the cells ("Cannot adopt the shared cells: ..."). The arm asserts four things at once: the reply still
comes through, the provider *did* run and wrote into the region (its marker), the refusal is named (`adopt answered
400`), and `cannot share its KV` -- the fallback line -- does **not** appear.

`tests/hybrid_kvshare_route.sh` PASS, 28 checks (23 before this commit).

* serve: the shared route checks what the provider says it prefilled before adopting its cells

The shared route took the region on the provider's exit code alone. `?action=adopt` then hands the decoder
`ids.size()` cells whatever happened, so a provider that exits 0 after writing fewer rows than it was given leaves the
decoder decoding from a region whose last rows were never written -- a wrong answer, not a failed request, and nothing
in the log says so. The file route has carried this cross-check since engine#941 (`provider prefilled N of M tokens`,
then the state file is removed and the request goes out plain); the shared route had no equivalent.

Now it parses the provider's last stdout line the same way and refuses the adopt on a mismatch:

    hybrid: provider prefilled 29 of 30 tokens into the shared region; the backend prefills this request itself

A line that does not parse is still not an error (on this route, like on the file route, the region is the result), and
a provider's own `prefill_ms` is taken from the same line, which the file route already did -- so the two routes report
the same number for the same work.

Reproduced first, with a provider that exits 0 and claims one token fewer (`FAKE_KVSHARE_SHORT=1`): before the change
the adopt happened and the run answered from the short region (the per-request line showed `share 0.433 ms, first byte
19 ms`); after it, the three new checks pass -- the claim is named, no cells are adopted, and the decoder prefills the
prompt itself.

Gates: `tests/hybrid_kvshare_route.sh` **PASS 33 checks** (28 before this commit, 23 before the PR), `tests/hybrid_route.sh`
PASS, `ONEBIT_KV_SHARE=1 tests/hybrid_e2e.sh` against a real llama-server + Qwen3-0.6B PASS (greedy reply equal to
`--device cpu`, `prompt_n 1, plain 22`).

---------

Co-authored-by: bong-water-water-bong <[email protected]>
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/kv-share-recurrent branch November 12, 2026 21:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant