Repository navigation
kv-share: report the tensor table a prefill provider writes into (engine#753) - #253
Conversation
…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
|
Extra gate run after opening this, because the first one only exercised a dense model and this API's hardest user is a Qwen3.5-4B-Q4_K_M (32 layers, 24 of them gated delta-net) — PASS That run exercises the two paths the dense one could not: the And it found a trap worth naming for whoever writes the provider: a hybrid model's |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
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
|
Structural note taken, pushed immediately after the READY:
Rerun after the change, both shapes, under Your other two points are worth keeping in the record because they were the ones I had to check rather than assume: Re-verdict requested at |
bong-water-water-bong
left a comment
There was a problem hiding this comment.
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.
VERDICT: CHANGES — at
|
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 exactlyone 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'stensors — and then drops the offsets it computed (
share_layout()has them, per chunk);ne[0](the row a write covers) isnot visible from outside.
So this adds the reporting, not a new mechanism.
llama_kv_cache::share_tensorswalkslayers[il].k/.vand reports, per tensor, its buffer base as the region and itsoffset 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.
regionis the ordinal of the first buffer the walk meets — the ordershare_placefills,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-maploads a model, builds a context the way the serving route does (-faon), and checks thetable:
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 at1 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 underthermal-run.shonQwen3-0.6B-Q4_K_M.gguf.What it unblocks
The provider becomes: parse
--layout/--fdsliketools/kvshare-prefilldoes →llama_kv_share_import→llama_kv_share_tensor_map→ hand that table to the private writer with the rows the NPU prefill produced. No offsetarithmetic 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.