Skip to content

kv-share: report the tensor table a prefill provider writes into (engine#753) - #253

Merged
bong-water-water-bong merged 2 commits into
1bit/hrx-vulkan-patchedfrom
1bit/753-tensor-map
Nov 8, 2026
Merged

bong-water-water-bong merged 2 commits into
1bit/hrx-vulkan-patchedfrom
1bit/753-tensor-map

Conversation

@bong-water-water-bong

Copy link
Copy Markdown

What this is

engine#753's NPU writer is done and measured (npu-kernels#29/#30/#31/#34/#37), and the private write path takes exactly
one thing from the decoder side: where each cache tensor sits, and how wide a position's row is. Today nothing on
this side can supply it:

  • llama_kv_share_import(ctx, regions, n) validates each region's layout hash and maps the dma-bufs over the context's
    tensors — and then drops the offsets it computed (share_layout() has them, per chunk);
  • a provider cannot re-derive them: the tensors live inside the memory classes, and ne[0] (the row a write covers) is
    not visible from outside.

So this adds the reporting, not a new mechanism.

struct llama_kv_share_tensor { uint32_t layer, is_v, region; uint64_t offset, bytes, row_elems; };
LLAMA_API size_t llama_kv_share_tensor_map(ctx, out, n_out);   /* size first with n_out = 0 */

llama_kv_cache::share_tensors walks layers[il].k/.v and reports, per tensor, its buffer base as the region and its
offset from that base. Once imported, that base is the region window, so the numbers come out in the same coordinates
the private write API takes. region is the ordinal of the first buffer the walk meets — the order share_place fills,
hence the index into the region list the decoder sent. The recurrent memory reports nothing: its state is not K/V rows
and a provider does not write it.

The gate (device-free, CPU, real model)

tools/kvshare-tensor-map loads a model, builds a context the way the serving route does (-fa on), and checks the
table:

kvshare-tensor-map: model=Qwen3-0.6B-Q4_K_M.gguf n_ctx=512 tensors=56
ok   the map reports something
ok   sizing first then filling agrees -- 56 vs 56
ok   K and V are reported per layer -- 28 K / 28 V for 28 layers
ok   every row width divides its tensor
ok   every tensor belongs to a layer of this model
ok   tensors inside one region do not overlap
ok   region ordinals are contiguous from 0
     layer 0   K  region 0  offset        0  bytes  1048576  row_elems 1024
     layer 0   V  region 0  offset  1048576  bytes  1048576  row_elems 1024
     layer 1   K  region 0  offset  2097152  bytes  1048576  row_elems 1024
PASS

The numbers are checkable by hand: 512 ctx × 1024 row_elems × 2 B = 1 048 576 B per tensor, layer 0 K at 0, its V at
1 MiB, layer 1 K at 2 MiB — the cache order llama.cpp allocates, at offsets a 4 KiB-aligned region layout gives for free.

Built and run here: configure + --target llama + --target kvshare-tensor-map, Release, CPU-only
(-DLLAMA_BUILD_TOOLS=ON -DGGML_CUDA=OFF -DGGML_VULKAN=OFF), the tool run under thermal-run.sh on
Qwen3-0.6B-Q4_K_M.gguf.

What it unblocks

The provider becomes: parse --layout/--fds like tools/kvshare-prefill does → llama_kv_share_import →
llama_kv_share_tensor_map → hand that table to the private writer with the rows the NPU prefill produced. No offset
arithmetic in the provider, which is the property the private API was built for.

Refs engine#753. No behaviour change for any existing path: the map is read-only and nothing calls it yet.

…ine#753)

llama_kv_share_import validates each region's layout hash and maps the dma-bufs over the context's KV tensors
-- and then drops the one thing the other side needs: where each tensor sits, and how wide a position's row
is. share_layout() computes exactly that internally. A provider that must WRITE the cache (the NPU one of
engine#753) cannot re-derive it: the tensors live inside the memory classes, and the row a write covers is
ne[0], which is not visible from outside.

So this adds the reporting, not a new mechanism:

  struct llama_kv_share_tensor { uint32_t layer, is_v, region; uint64_t offset, bytes, row_elems; };
  LLAMA_API size_t llama_kv_share_tensor_map(ctx, out, n_out);   // size first with n_out = 0

llama_kv_cache::share_tensors walks layers[il].k/.v and reports, per tensor, its buffer base as the region and
its offset from that base -- which is the region window once imported, so a provider gets the numbers in the
same coordinates the private write API takes them in. `region` is the ordinal of the first buffer the walk
meets, which is the order share_place fills and therefore the index into the region list the decoder sent. The
recurrent memory reports nothing: its state is not K/V rows and a provider does not write it.

tools/kvshare-tensor-map checks the arithmetic on a real model, with no dma-buf and no device: every K/V tensor
of every attention layer, row width dividing the tensor, no overlap inside a region, contiguous region ordinals.
On Qwen3-0.6B at 512 ctx: 56 tensors (28 K + 28 V), 1 MiB each, layer 0 K at 0 and V at 1 MiB, layer 1 K at
2 MiB -- 512 x 1024 x 2 B, which is the number the hand calculation gives.

Refs engine#753
@bong-water-water-bong

Copy link
Copy Markdown
Author

Extra gate run after opening this, because the first one only exercised a dense model and this API's hardest user is a
hybrid:

Qwen3.5-4B-Q4_K_M (32 layers, 24 of them gated delta-net) — PASS

kvshare-tensor-map: model=Qwen3.5-4B-Q4_K_M.gguf n_ctx=512 tensors=16
ok   the map reports something
ok   sizing first then filling agrees -- 16 vs 16
ok   K and V are reported per layer -- 8 K / 8 V for 32 layers
ok   every row width divides its tensor
ok   every tensor belongs to a layer of this model
ok   tensors inside one region do not overlap
ok   region ordinals are contiguous from 0
     layer 3   K  region 0  offset        0  bytes  1048576  row_elems 1024
     layer 3   V  region 0  offset  1048576  bytes  1048576  row_elems 1024
     layer 7   K  region 0  offset  2097152  bytes  1048576  row_elems 1024
     layer 11  K  region 0  offset  4194304  bytes  1048576  row_elems 1024
PASS

That run exercises the two paths the dense one could not: the llama_memory_hybrid recursion into its attention half
(get_mem_attn(), the same route share_rec already took for share_from), and llama_memory_recurrent::share_tensors
returning nothing — the recurrent state is not K/V rows and a provider does not write it.

And it found a trap worth naming for whoever writes the provider: a hybrid model's layer indices are sparse. 32
layers, but only 8 attention caches, at layers 3, 7, 11 … (one in four, the full_attention_interval). A provider
that indexes its rows by 0..n_layer-1 will write the prompt's K/V into the wrong tensor on every layer past the first —
and it will look like the model answering nonsense rather than an error. The map is the thing that prevents it: use
t[i].layer, never the tensor's position in the list. (The tool already asserts layer < n_layer and that K and V counts
match, which is why this stayed visible rather than silently plausible.)

@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 ae62d0b5.

The provider's half of the handoff, and the three things that would make it wrong are all right:

row_elems = t->ne[0] is the per-position width — worth checking rather than assuming, because ne[0] is the head dim for a 2-D cache and the whole row
for a 3-D one, and this branch creates them 3-D: llama-kv-cache.cpp:234-235, ggml_new_tensor_3d(ctx, type_k, n_embd_k_gqa, kv_size, n_stream). So one
position's row is ne[0] elements per stream, which is what the comment claims and what a writer needs.

The offset is bytes from the region base, taken as t->data - ggml_backend_buffer_get_base(t->buffer), and the comment names the reason that base is
the region window (ggml_backend_dev_buffer_from_dmabuf returns a buffer over it). Layer walk, K then V, null tensors skipped — which is right for a
unified cache and means a caller must read the list rather than assume a full grid, as the doc says.

And the ordinals line up with the list the decoder was given: share_import creates its buffers in region order (llama_share_import → share_wrap)
and the layers were allocated through share_place in the same order, so a first-seen region_of walk yields the same indices as the region vector.

One structural note, one line to close it. region_of derives the ordinal from the walk instead of recording it at import. Today those coincide
because every imported region is created for a layer and therefore holds K/V — so this is correct on every shape the code can currently produce, which is why
this is a READY. But if a future layout ever imports a region that holds no K/V tensor of the walked layers (a per-stream split where one stream's cache is
empty is the obvious candidate), the walk silently skips it and every later ordinal shifts — a provider writing into the wrong region, with nothing in the
message. An assert after the walk (bases.size() == regions.size(), or recording the base in share_import and matching by identity) turns that from a
silent corruption into a refusal. It is the same class as the asserts I have asked for elsewhere: cheap now, load-bearing later.

The kvshare-tensor-map probe is the right way to land this — it prints the table the caller would have to reason about, so the next reader does not have
to infer the layout from the struct.

…nstead of shifting ordinals

The review's structural note, closed the cheap way it suggested: `region_of` derives the ordinal from the walk, which
coincides with the region list today because every imported region is created for a layer and so holds K/V. A layout that
ever imports a region holding no K/V tensor of the walked layers would make the walk skip it and shift every later
ordinal -- a provider writing into the wrong region, with nothing in the message.

So the count is recorded where it is known: `llama_kv_cache::share_import` notes how many regions it consumed (`next`
delta), and `share_tensors` compares that against the buffers its walk met. A mismatch clears the output, logs which
numbers disagreed and returns false, which the public map turns into a zero-length answer -- a refusal rather than a
silently wrong table. The check only applies to a cache that imported (the counter stays 0 otherwise, so an ordinary
allocation is unaffected).

Rerun after the change, both shapes: Qwen3-0.6B (dense, 56 tensors) PASS, Qwen3.5-4B (hybrid, 16) PASS.

Refs engine#753
@bong-water-water-bong

Copy link
Copy Markdown
Author

Structural note taken, pushed immediately after the READY: 4118e1505. It was cheap now and load-bearing later, and
the shape you suggested is the one I used — record the count where it is known instead of deriving it twice:

  • llama_kv_cache::share_import notes how many regions it actually consumed (the next delta across its contexts);
  • share_tensors compares that against the buffers its walk met, and on a mismatch clears the output, logs both
    numbers and returns false
    , which llama_kv_share_tensor_map turns into a zero-length answer. So a region that held no
    K/V of the walked layers becomes a refusal instead of every later ordinal shifting by one — the silent-corruption case
    you described;
  • the check is scoped to a cache that imported (the counter stays 0 otherwise), so an ordinary allocation is untouched.

Rerun after the change, both shapes, under thermal-run.sh:

Qwen3-0.6B-Q4_K_M   tensors=56   PASS     (dense: 28 layers, one region)
Qwen3.5-4B-Q4_K_M   tensors=16   PASS     (hybrid: 8 attention caches at layers 3, 7, 11 …)

Your other two points are worth keeping in the record because they were the ones I had to check rather than assume: ne[0]
is the per-position width because this branch creates the caches 3-D (ggml_new_tensor_3d(ctx, type_k, n_embd_k_gqa, kv_size, n_stream)), and the base-is-the-region-window claim rests on
ggml_backend_dev_buffer_from_dmabuf — both now asserted by the tool's checks rather than trusted.

Re-verdict requested at 4118e1505.

@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 4118e15055856f39e98d08ea08ae67c2d096d066

Built it in my existing build dir and ran it against a real model, so the table is checked rather than described:

$ cmake --build build226 --target kvshare-tensor-map        -> [54/55] Linking CXX executable bin/kvshare-tensor-map
$ ./build226/bin/kvshare-tensor-map -m ~/models/Qwen3-0.6B-Q4_K_M.gguf --ctx 256 --ubatch 32
ok   region ordinals are contiguous from 0
     layer 0   K  region 0  offset        0  bytes 524288  row_elems 1024
     layer 0   V  region 0  offset   524288  bytes 524288  row_elems 1024
     layer 1   K  region 0  offset  1048576  bytes 524288  row_elems 1024
     layer 1   V  region 0  offset  1572864  bytes 524288  row_elems 1024
     …
PASS

and the numbers are self-consistent: 524,288 B = 262,144 f16 elements = 256 ctx × 8 kv-heads × 128 head_dim, with each successive tensor starting exactly where the previous one ended — which is what makes an offset+region pair usable as an address by the provider.

The refusal is the design decision I would have asked for: "if the walk met a different number of buffers than share_import mapped, some … n_share_regions is set there" — and the code says "A refusal, not a shifted ordinal". An ordinal-keyed table whose walk disagrees with the import by one buffer would silently point every tensor after that at the wrong region, which is the worst failure shape for a handoff: the provider writes correct bytes to the wrong place. Refusing keeps the bug at the contract instead of at the data.

ok region ordinals are contiguous from 0 is the check that the decoder's list is usable at all, and it is printed as a line rather than assumed — the same shape as the other PASS-per-property tools in this tree.

The tool lives in tools/kvshare-tensor-map/ with its own CMakeLists (+1 line in tools/CMakeLists.txt), so it builds with the tree rather than being a script someone has to keep alive.

Not run: the provider/decoder handoff itself (needs a second process on the HRX path); what I verified is the table the provider is handed and the refusal that guards it.

@bong-water-water-bong
bong-water-water-bong merged commit 932485c into 1bit/hrx-vulkan-patched Nov 8, 2026
@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT: CHANGES — at 4118e1505 (the head after the READY at ae62d0b5, so this supersedes it)

The mechanism is right and the refusal you added in the last commit is the right shape. Two things would bite the first consumer that is not Qwen3-0.6B with an f16 V cache, and one of them is an API gap rather than a nit.

1. row_elems is not a row width, and type_v may be quantized (blocking)

The struct reports row_elems = t->ne[0], i.e. elements. The tool then reconstructs bytes as row_elems * 2 with the comment "f16/bf16 cache, both 2 bytes" — but type_v is a parameter of this class (llama-kv-cache.cpp:70, tensor built at :170 with ggml_new_tensor_3d(ctx, type_v, …)), and the same file already reasons about the quantized case at :372:

ggml_is_quantized(type_v) && …

With -ctv q8_0 (a supported configuration, and the one a memory-constrained provider would ask for) a row of 1024 elements is 1024/32*34 = 1088 bytes, not 2048. Consequences, in the order they matter:

  • the private writer cannot compute the width it needs. It has row_elems and bytes (whole tensor) but not ne[1] and not the type, so for a quantized V there is no arithmetic that recovers a row's byte width. The PR's own summary says the writer needs "how wide a position's row is" — for the 2-byte case it does, for the quantized case it does not.
  • the gate has a false-red path. bytes % (row_elems * 2) is 1088 % 2048 ≠ 0 for the same model with -ctv q8_0, so every row width divides its tensor FAILs on a configuration the library supports.

Cheapest closure, and it keeps the struct honest: report the byte width as well, row_bytes = ggml_nbytes(t) / t->ne[1] (block padding included, so it is the stride a writer must use), or report the ggml_type. If the intent is genuinely "2-byte caches only", then say that in the header comment and make the tool refuse a quantized type_v explicitly instead of failing an arithmetic identity — a reader cannot tell the two FAILs apart today.

2. A count check cannot catch a permutation, which is the failure the comment describes (blocking)

n_share_regions catches "a region holds no K/V tensor of these layers, so every later ordinal shifts". But region_of assigns ordinals by first-seen order in the walk, and the count only compares sizes. If share_place fills regions in a different order than layers × (k,v) meets buffers — nothing in this diff establishes that it cannot — the counts match and every ordinal is permuted, silently: the provider writes layer 0's K into the region the decoder reserved for layer 27. Same symptom, undetected by the new guard.

The import already knows the answer: share_import maps each region's buffer, so record those bases there (std::vector<const void *> share_bases, appended in the ctxs_bufs loop) and make region_of look the base up instead of inventing an index. Then region is provably the index into the list the decoder sent, the count check becomes a redundant safety net, and the comment's claim ("the same order share_place fills") stops being an assumption that the code depends on.

3. Smaller, and only if you agree it is in scope

The device-free gate never calls share_import, so it exercises the walk on a normal context: it verifies packing, per-layer K/V, disjointness and contiguity, but not the coordinates after an import, which is the only case where region means anything. Worth one line in the gate's output or the PR body — "coordinates are checked by npu-kernels#…'s handoff run, not here" — because a reader will otherwise take ok region ordinals are contiguous from 0 as covering the mapping, and today the contiguity is true whether or not the ordinals are right.

What I did not check

No build here (and I would not build in another lane's tree); I did not run the tool. Everything above is read from the diff and from src/llama-kv-cache.cpp at this head, and #1's arithmetic is QK8_0 = 32, sizeof(block_q8_0) = 34.

The sizing-first API, the nullptr/0 convention, the recurrent "reports nothing, and says why", and the refusal-instead-of-shift are all right — the refusal is the best part of the last commit.

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