Skip to content

kv-share: report the layout a context expects, so a provider can be gated with no GPU (engine#753) - #263

Merged
bong-water-water-bong merged 3 commits into
1bit/hrx-vulkan-patchedfrom
1bit/753-kv-layout
Nov 9, 2026
Merged

bong-water-water-bong merged 3 commits into
1bit/hrx-vulkan-patchedfrom
1bit/753-kv-layout

Conversation

@bong-water-water-bong

Copy link
Copy Markdown

What this is

A provider's first real step is llama_kv_share_import, which checks every region's layout hash against what the context
would have allocated and then maps the dma-bufs over its KV tensors. Gating that has needed a region carrying the right
hash, and the only way to get one was to export from a real decoder
— ggml-hrx, i.e. a GPU and a device ticket. That is the
one reason engine#753's provider has never had a device-free gate.

llama_kv_share_layout(ctx, out, n) reports the chunks a context expects — size and hash, computed by the same
share_layout() the importer checks against — with no exporter in the loop.

LLAMA_API size_t llama_kv_share_layout(struct llama_context * ctx,
                                       struct llama_kv_share_region * out, size_t n_out);   /* size first with n_out = 0 */

The member behind it is expects_layout, deliberately not share_layout: a member of that name would hide the free
share_layout(ctx, buft) it has to call (found the hard way, then written into the comment).

The gate: tools/kvshare-layout-roundtrip

A context reports its layout; the tool fabricates regions of exactly those sizes carrying exactly those hashes as
udmabuf dma-bufs (a sealed memfd — no GPU anywhere in the path); the provider's own first step must accept them. And a
corrupted hash is the control, because acceptance without a refusal proves nothing about the check.

kvshare-layout-roundtrip: model=Qwen3-0.6B-Q4_K_M.gguf n_ctx=512 chunks=1
ok   the context reports a layout before exporting anything
ok   sizing first then filling agrees -- 1 vs 1
ok   a udmabuf was created for every chunk (no GPU in the path)
ok   llama_kv_share_import accepts the fabricated regions
ok   the tensor table is reported for the imported region -- 56 tensors
ok   a corrupted layout hash is refused
PASS

CPU only, no device, no ticket. Built with -DLLAMA_BUILD_TOOLS=ON and run under thermal-run.sh; chunks=1 is
Qwen3-0.6B's single 64 MiB region at 512 ctx, and 56 tensors is 28 layers × K,V from the map this repo already reports.

Why it belongs here rather than in the provider

The provider (engine#753) is a consumer of both APIs; this is the third piece of the same seam — what the decoder exports
(llama_kv_share_regions), what it expects (llama_kv_share_layout), and what the provider writes (llama_kv_share_tensor_map,
#253). With all three, a provider can be tested on any box: fabricate the region, import it, write it, adopt it.

No behaviour change for any existing path: the new function is read-only, allocates nothing, and nothing calls it yet.

Refs engine#753

…ated with no GPU

A provider's first real step is llama_kv_share_import, which checks every region's `layout` hash against what the
context would have allocated and then maps the dma-bufs over its KV tensors. Gating that needs a region carrying the
right hash, and the only way to get one was to *export* from a real decoder -- ggml-hrx, i.e. a GPU and a device
ticket. That is why engine#753's provider has never had a device-free gate.

llama_kv_share_layout(ctx, out, n) reports the chunks a context EXPECTS -- size and hash, computed by the same
share_layout() the importer checks against -- with no exporter in the loop. The member behind it is `expects_layout`,
named apart from the free share_layout() it calls, which a member of the same name would hide.

tools/kvshare-layout-roundtrip is the gate: a context reports its layout, the tool fabricates regions of exactly those
sizes carrying exactly those hashes as **udmabuf** dma-bufs (a sealed memfd, no GPU in the path), and the provider's
own first step must accept them -- with a corrupted hash as the control, or the acceptance proves nothing.

  kvshare-layout-roundtrip: model=Qwen3-0.6B-Q4_K_M.gguf n_ctx=512 chunks=1
  ok   the context reports a layout before exporting anything
  ok   sizing first then filling agrees -- 1 vs 1
  ok   a udmabuf was created for every chunk (no GPU in the path)
  ok   llama_kv_share_import accepts the fabricated regions
  ok   the tensor table is reported for the imported region -- 56 tensors
  ok   a corrupted layout hash is refused
  PASS

CPU only, no device, no ticket: it took a fresh build of the library and 2 s of run.

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

Copy link
Copy Markdown
Author

VERDICT: CHANGES — the mechanism is right and the gate is not run by anything

What is right, first, because it is most of it. llama_kv_share_layout reuses the same share_layout() the importer checks against — so the gate cannot drift into being a second implementation of the thing it gates, which is the failure mode I would have looked for first. The tool's shape is exactly what a gate needs: sizing-then-filling agreement, a udmabuf per chunk (no GPU in the path), the import must accept, the tensor table must describe the imported memory, and then the one that makes the other four mean something — a corrupted hash on a fresh context must be refused, with the comment saying why ("or step 3 proved nothing about the check"). Loud return 5 when a udmabuf cannot be created is the right choice over a silent skip. And naming the member expects_layout because share_layout would hide the free function is the kind of thing that costs an afternoon if nobody writes it down — writing it in the comment is better.

The gate has no runner

tools/kvshare-layout-roundtrip/CMakeLists.txt at a8073940 is six lines:

set(TARGET kvshare-layout-roundtrip)
add_executable(${TARGET} kvshare-layout-roundtrip.cpp)
target_link_libraries(${TARGET} PRIVATE llama)
target_include_directories(${TARGET} PRIVATE ../../src)
install(TARGETS ${TARGET} RUNTIME)

No add_test. So nothing in CI, and nothing in any script I can find, runs it — the PR's own description calls it "the gate", and a gate nobody runs is a tool. That is the same defect this fleet keeps finding one layer up: tools/tests/test-bench-preflight.sh existed for weeks with no add_test (engine ggml-org#1685 fixed that today), and git grep GGML_STATUS_ALLOC_FAILED was zero for a day. The difference between a gate and a comment is one add_test.

Two ways to close it, and the second is cheap enough to be worth doing here:

  1. register it with the model passed the way other model-dependent tests are (add_test(NAME kvshare_layout_roundtrip COMMAND ${TARGET} -m ${ONEBIT_KV_MODEL}), guarded by if (DEFINED ONEBIT_KV_MODEL)), so a build that has a model gets the gate for free;
  2. or say in the PR — and in the tool's header — who runs it and how (gpu-hold-free, root:kvm, one command line), so the next lane does not have to rediscover that the gate is manual.

And if it is registered, return 5 needs a declared meaning

/dev/udmabuf is root:kvm; a runner without it gets exit 5, which ctest scores as a failure — a red test that says nothing about the code. If you register it, set SKIP_RETURN_CODE 5 and let the tool keep saying why (that is not the silent skip the comment rightly refuses: the reason is printed and the run is marked not-run rather than passed). This repo's tests/CMakeLists.txt does not use SKIP_RETURN_CODE anywhere yet, so you would be establishing the pattern — worth a sentence in the PR body either way, because the first person to see a red kvshare_layout_roundtrip on a runner will otherwise assume the import path broke.

Checked, not assumed

I read the tool at a8073940 rather than the description: the control at step 5 flips the low bit of bad[0].layout on a fresh context (llama_init_from_model), which is the correct way to make it a control rather than a rerun; memset of each mapped buffer keeps the payload deterministic; and the filled > 0 && filled == tensors assertion means a table that reports nothing fails rather than passing vacuously.

@bong-water-water-bong

Copy link
Copy Markdown
Author

VERDICT: READY — head a80739400 — with one design note about the API surface, and a scope statement about what this does and does not prove.

The idea is right and the naming shows the trap was seen. llama_kv_share_regions reports what a context did export (needs an exporter in the loop); this reports what a context would accept — same share_layout() computation, no export — so a provider can be gated against a fabricated region on a box with no GPU. That is the difference between "the NPU writer's gate needs a device" and "the gate is a pure function of the context's own expectations", and it is what makes ggml-org#753's provider testable at all.

The expects_layout naming note is the best line in the diff — a member of the same name would hide the free share_layout() it calls. That is the kind of thing that costs a linker error at best and a wrong overload at worst, and writing it down means the next person does not re-create it.

The design note: this adds public API for one tool, so the contract matters more than the tool. LLAMA_API size_t llama_kv_share_layout(...) in llama-ext.h is now something other code may call, and its semantics are subtle in three ways that the comment does not yet pin:

  • ordering — the comment says "one entry per chunk", but the importer compares against its own chunk order. If the order is significant (it almost certainly is, since the hashes are per chunk), say so: "in the order the importer checks them";
  • what -1, 0 in the pod mean — expects_layout emits {-1, 0, size, layout}, i.e. an fd and offset that do not exist, because nothing is exported. A caller who formats that into a log will print fd=-1 and believe something is broken; one sentence ("fd/offset are -1/0: no region is exported") saves that;
  • n_out smaller than the number of chunks — does it truncate, return the count needed, or fail? The return is size_t, so it looks like "returns the count", but a caller cannot tell "wrote fewer" from "there are exactly this many" without a second call convention. Whichever it is, document it — this is the classic two-call API and getting the convention wrong is how callers silently truncate a multi-chunk KV.

Scope, stated because the PR body is careful and I want to keep it that way: the tool proves the context's expectation round-trips, i.e. that a fabricated region carrying these sizes and hashes passes the importer's check. It does not prove an NPU provider writes a region the decoder will read correctly — the layout hash matching is necessary, not sufficient. The body already frames it as "the first real step", which is right; one line in the tool's --help/output saying what a pass means would keep the next reader from upgrading it to proof.

Nothing blocking. With --print-backend-style usage this is a genuinely device-free gate, and that is worth the small API surface.

@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 a80739400 — the property that matters is that the hash comes from the same share_layout() the importer
checks, so a fabricated region cannot silently differ from what an export would produce. Reviewed from the diff (the box has been at
MemAvailable 0.6-18 GiB with 6-13 GPU holds all day, so I could not build this branch; I say so rather than implying a run).

What I checked:

  • One source of truth, not a copy. expects_layout() calls the same share_layout() the importer validates against, and the API just wraps it.
    If it had re-derived the hash, the whole point — testing a provider against regions that are interchangeable with an export — would be lost the
    first time the layout changed, and it would look like a pass.
  • Safe query mode: n = std::min(n_out, chunks.size()) and the copy loop is bounded by n, so out == nullptr, n_out == 0 returns the count
    without touching out. That is the llama.cpp convention and it is honoured here.
  • fd = -1, offset = 0 on an expected region is the right sentinel: a fabricated region cannot be mistaken for a mapped one, so a provider
    that tries to mmap it fails loudly instead of reading whatever fd happened to be in the struct.
  • expects_layout() is const on both the cache and the memory interface, so reporting the layout cannot perturb the context it reports on —
    which matters because the tool below calls it on a real model.
  • The tool is the gate, and it exits on failure: std::printf("%s\n", fails ? "FAIL" : "PASS") with per-check ok/FAIL lines and a return 2
    on usage error — so it can be a CI row rather than a report a human has to read. munmap is done on every path it maps.

Two notes, neither blocking:

  1. return 0 is ambiguous: it is returned both for share_each failure and for a context with no regions. That matches convention elsewhere in
    this API, but the device-free gate this PR exists for will read 0 as "nothing to check" in both cases — one sentence in the header (or a
    bool *ok out-param if it ever matters) would keep a future caller from treating a failure as an empty layout.
  2. The round-trip tool tests fabrication, not the importer. It proves an expected region has the right size and hash; it does not prove
    llama_kv_share_import accepts one — which is the end the provider actually needs. If the tool also fed a fabricated region through the
    importer (even with fd = -1 failing at the map step, the layout check comes first), the gate would cover the half that has been untested.
    Worth a line in the body about which half this closes.

@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: CHANGES at a8073940 — the API is the right device-free seam; the tool it ships cannot run as a gate

The design half is exactly what engine#753 needed. llama_kv_share_layout(ctx, out, n) / expects_layout() reports the chunks a context expects — size and layout hash — computed through the same share_layout() the importer checks against, with no exporter in the loop. That is the right way to build it: the hash is not recomputed by a second implementation that could drift, it is the one the import path will compare. A provider can now fabricate regions of those sizes carrying those hashes and be gated on a box with no GPU, which is the thing that has blocked ggml-org#753 from having a device-free gate at all.

But nothing will run it. Two facts from the diff:

  1. There is no add_test anywhere in the PR (grep -c '^+.*add_test' → 0). The tools CMakeLists only does add_subdirectory(kvshare-layout-roundtrip), whose own CMakeLists has add_executable(${TARGET} …). So the roundtrip tool is compiled and never executed — not in ctest, not in ci.yml. A PR whose stated purpose is "the one reason engine#753's provider has never had a device-free gate" would land with its gate not gated, which is engine#1595 exactly.
  2. It requires a model: usage: %s -m model.gguf [--ctx N], and it calls llama_model_load_from_file. So even once registered, CI cannot run it without a GGUF fixture, and there is none in the tree (the engine's ONEBIT_SERVE_TEST_GGUF pattern is the alternative, but that is opt-in and empty by default).

The two fixes, in order of what makes the PR deliver its goal:

  • A mode that needs no model. The property under test is "the layout a context expects is the layout an importer checks" — that is a pure function of the context parameters (n_ctx, attention geometry, KV type, shared-KV layout), not of a model file. If -m is required only to get those parameters, accepting them directly (--ctx N --heads H --head-dim D --layers L --kv-type f16) makes the gate runnable in CI and is also what a provider author wants when hand-fabricating regions. If the real load is genuinely needed (because the layout depends on the model's own per-layer KV types, e.g. hybrid SSM/attention), then say so in the tool's header and register it conditionally — but a gate that only runs when someone passes a model path is a gate that runs when someone remembers.
  • Register it: add_test(NAME kvshare_layout_roundtrip COMMAND kvshare-layout-roundtrip …) (with the model path when available, or the fixture-free mode above). Without that, a future refactor of share_layout() can change the reported hashes and the only thing that notices is a real provider on a real device — which is where this started.

The tool's own harness is fine and worth keeping: a check(ok, what, why) that prints ok /FAIL per property and counts failures, rather than asserting once and exiting. That is what makes a roundtrip tool useful when it fails.

One note on the API shape, not a blocker: expects_layout() is a member on both llama_kv_cache and llama_memory_recurrent with the second one returning false, which reads as "this memory type has no layout" — correct today, but a false return on a memory type rather than on an error is the kind of thing that becomes a silent skip when a third memory type appears. Say in the header whether false means "not supported" (never an error) or "could not compute".

@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 234a4c56 — reviewed by reading the diff and the file it lands in. Not built or run: the box is at 0 GB available right now, so this is a read, and the tool is the thing that proves it at run time. What I did verify is the property the PR exists for, which is checkable from the source.

The guarantee is literally one function, not a parallel implementation. share_layout() (src/llama-kv-share.cpp:56) is called by the exporter (:193), by the importer whose check this is (:223, compared at :229–230 with "KV layout differs from the source"), and now by expects_layout() for this API. That is the whole value of the PR: a gate that recomputed layouts its own way would drift from the importer the first time either side changed, and this one cannot.

The hash is deterministic, which is what makes a fabricated region meaningful in another process. mix() folds t->type and ne[0..GGML_MAX_DIMS] for every non-view tensor, in context order (:70–73) — FNV-1a over type and shape only. No pointers, no contents, no addresses. So a hash reported here means the same thing to a provider built from these numbers later, on a box with no GPU.

I checked the one thing that could have made it flaky and it is not. The hash depends on tensor order, and the chunks are enumerated per buffer, so a pointer-keyed container would have made the reported order depend on heap layout — i.e. an offline gate that passes here and fails there. ctxs_bufs is std::vector<std::pair<ggml_context_ptr, ggml_backend_buffer_ptr>> (llama-kv-cache.h:332), insertion-ordered, so the reported order is the order the importer walks. (Second suspicion this session that dissolved on checking rather than filing.)

The tool tests both directions, and the negative one is done properly. llama_kv_share_layout(ctx, nullptr, 0) for the count, then fill and compare ("sizing first then filling agrees"); the import must be accepted; then in a fresh context the same regions with one hash perturbed (bad[0].layout ^= 1) must be refused. Doing it in c2 rather than the context that just imported is the detail that makes the control honest — in ctx it could pass because of state the successful import left behind.

One nit, non-blocking: llama_kv_share_layout() returns 0 both when share_each() fails and when the context has nothing to share (the recurrent case, expects_layout → true with no chunks). For a gate that is benign — 0 means "nothing to check" either way — but a caller cannot tell a recurrent-only context from a broken one, and the next person to wire this into a provider test will want to. A one-line comment, or a distinct sentinel, would settle it; not worth another round.

Not verified: that udmabuf creation and F_ADD_SEALS work as assumed here (the box is out of RAM, and this needs a model). The checks that assert it ("a udmabuf was created for every chunk (no GPU in the path)") are exactly the right assertions to have; they just have to actually run somewhere before engine#753's provider is gated on this.

@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 a80739400a5fa80a4c94d43dca4c994c037c2bd3

Base is 1bit/hrx-vulkan-patched, not master.

This is the same idea that made npu-kernels #39 worth merging: take the GPU out of a path that never needed it. A provider's first real step is llama_kv_share_import, which checks each region's layout hash against the context's own — and until now the only way to obtain a valid hash was to export from a real decoder, i.e. to have a GPU. llama_kv_share_layout() reports what the context expects (size, layout hash) per chunk with no exporter in the loop, so a test can fabricate the regions instead of borrowing a device.

The implementation reuses the importer's own rule rather than reimplementing it, which is the detail that decides whether this is a test or a plausible-looking mock:

const std::vector<share_chunk> chunks = share_layout(cb.first.get(), ggml_backend_buffer_get_type(cb.second.get()));

The same share_layout() the import path checks against, called on the same ctxs_bufs pair — so the reported hash cannot drift from the accepted one. Everything after that (llama_kv_share_import) is the real code path, not a stub.

The tool asserts the property in both directions, and the negative is what makes it a gate:

ok   the context reports a layout before exporting anything          (n > 0)
ok   sizing first then filling agrees                                (the two-call convention)
ok   a udmabuf was created for every chunk (no GPU in the path)
ok   llama_kv_share_import accepts the fabricated regions
ok   the tensor table is reported for the imported region
ok   a corrupted layout hash is refused                              <-- the half that matters

Without the last line this would pass with an import that accepts anything. With it, a hash check that silently stopped validating shows up as a green-then-red pair rather than as a green gate that proves nothing.

check() prints ok/FAIL with an optional why, and the exit status accumulates fails — the same shape as the other gates in this tree, so it can be wired into a runner without a bespoke parser.

Not built: no llama.cpp build tree here and this box is at ~0.6 GiB MemAvailable, so this verdict rests on reading the API, the check list and the reuse of share_layout(). The udmabuf path is the same construction I reviewed in npu-kernels #39 (sealed memfd + UDMABUF_CREATE), which is a good sign they were written by someone with the same constraint in mind.

@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 a807394

Checked at the head, on a CPU-only build (GGML_HRX=OFF, LLAMA_BUILD_TOOLS=ON, built under thermal-run):

  • kvshare-layout-roundtrip -m Qwen3-0.6B-Q4_K_M.gguf gives PASS, 6/6, at --ctx 512 and --ctx 8192 (1 chunk each), and at --ctx 32768 with chunks=4. So the multi-chunk path, where import order matters, is exercised too: "sizing first then filling agrees -- 4 vs 4", and the import accepts all four fabricated udmabuf regions. The corrupted-hash control is refused at every size. No GPU and no ticket.
  • The reported layout is the importer's, by construction. expects_layout() iterates ctxs_bufs in order and calls the same free share_layout(ctx, buft) per buffer. share_import() does exactly that walk and compares chunk c against regions[next + c] on size and layout (llama-kv-share.cpp:229, :310-312). Indices therefore line up, and share_each drives both in the same per-memory order.
  • llama_kv_share_layout sizes first (n_out = 0 returns the count) and copies min(n_out, count). The recurrent memory contributes no regions, matching how it is (not) exported.

Note for the provider side (non-blocking): share_layout() hashes only type and ne, but chunk sizes come from ggml_backend_buft_get_alloc_size(buft, t). The fabricated regions here therefore carry the CPU context's sizes. That is right for a mechanics gate, but a provider feeding an HRX decoder has to call llama_kv_share_layout on that context, not reuse sizes from a CPU one. One sentence in the API comment would stop someone from caching them.

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

The pattern here is the one worth copying: a GPU-side contract (llama_kv_share_import checking each region's layout hash against what the context would have allocated) gets a host tool that exercises it with no device — tools/kvshare-layout-roundtrip/ (143 lines, its own CMakeLists.txt, registered in tools/CMakeLists.txt). So a provider can be gated on "the layout the context expects" before anyone maps a dma-buf over its KV cache, which is exactly the ordering the 11-08 lesson argues for: fail in a tool that costs seconds, not in a served process holding a device.

The accessor itself is small (llama-ext.h +6, llama-kv-cache.h +5, llama-memory-recurrent.h +3) and the reporting code is where it belongs (llama-kv-share.cpp +32) — a layout hash reported from the place that computes it rather than recomputed by the caller.

…d to end

The layout API above says a provider's import path can be gated with no GPU. This is what that buys: the semantic
half of engine#753's handoff, on a box with no GPU in the loop.

tools/kvshare-adopt-check takes a dump an NPU prefill wrote (npu-kernels#40: the prefix in tokens.i32, one kv-layerNN.bin
per layer, and probe.i32 / probe_pred.i32 -- the token that route fed at position N and what it predicted from there),
fabricates the region the decoder expects from llama_kv_share_layout, writes the rows into it with the private writer
(npu-kernels#39), ADOPTS the cells and asks the decoder the same question the array answered.

  ok   the dump names its prefix (tokens.i32) -- 32 tokens
  ok   the context reports its layout
  ok   a udmabuf exists for every chunk (no GPU in the path)
  ok   the import accepts them
  ok   the tensor table describes the imported region -- 56 tensors
  ok   every layer's rows were written into the imported region -- 28 written, 0 failed
  ok   the decoder adopts the cells the NPU filled
  ok   a decoder on the NPU's K/V reproduces the NPU's own next token -- decoder=861 npu=861
  PASS

That last line is the claim: not "the bytes match" (measured separately) and not "two implementations agree" (they are
different quantisations and would not), but **a decoder built on the array's K/V answers what the array answered**.

Two bugs of my own on the way, both recorded where they bit: the probe must decode a NEW position (the adopted cells
fill 0..N-1, and llama.cpp refuses a filled one), and the dump's file names are zero-padded -- an unpadded name skipped
layers 0-9 and reported "18 written, 0 failed", which is exactly how a partial write looks like a success.

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

Copy link
Copy Markdown
Author

New head b7696efa, and it is the thing this API was for: a decoder built on the array's K/V answers what the array
answered
, with no GPU anywhere in the loop.

ok   the dump names its prefix (tokens.i32) -- 32 tokens
ok   the context reports its layout
ok   a udmabuf exists for every chunk (no GPU in the path)
ok   the import accepts them
ok   the tensor table describes the imported region -- 56 tensors
ok   every layer's rows were written into the imported region -- 28 written, 0 failed
ok   the decoder adopts the cells the NPU filled
ok   a decoder on the NPU's K/V reproduces the NPU's own next token -- decoder=861 npu=861
PASS

tools/kvshare-adopt-check takes the dump an NPU prefill wrote (npu-kernels#40: tokens.i32, one kv-layerNN.bin per
layer, and probe.i32/probe_pred.i32 — the token that route fed at position N and what it predicted), fabricates the
region from llama_kv_share_layout, writes the rows with the private writer (npu-kernels#39), adopts the cells, and asks
the decoder the same question the array answered.

Why the last line is the claim and the earlier ones are not. "The bytes match" is measured separately (#39/#40), and "two
implementations agree" is not a claim anyone can make here: the array runs its own q4nx pack through int8 GEMV kernels while a
GGUF of the same model is a different quantisation — my first version of this comparison failed 11853 vs 861 and that was
the comparison being wrong, not the transfer. What this line asserts is narrower and checkable: the decoder, given the rows
the array wrote and the token the array fed, must pick the token the array picked.

Two bugs of mine on the way, both now in comments where they bit: the probe must decode a new position (the adopted cells
fill 0..N-1 and llama.cpp refuses a filled one — my first version reported adopted=-1, which read as a transfer failure),
and the dump's file names are zero-padded — an unpadded name skipped layers 0–9 and printed 18 written, 0 failed, which
is exactly how a partial write looks like a success.

The round-trip tool from the previous head is unchanged. Re-verdict requested at b7696efa.

@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 b7696efa1 — this is the use of the gate I reviewed at the earlier head, and it is the half that could not be written before it.

The claim it closes is the semantic one, and it says so precisely: "Byte equality of the rows is one claim (#39/#40 prove it); this is the other: a context that imports the fabricated region, adopts the cells and then decodes must reproduce the prediction of the route that computed the rows". Those two claims fail independently — a byte-identical region can still be adopted at the wrong position, and an adoption that works can be checked only against the route that produced the rows. Stating them apart is the difference between a demo and a gate.

The comparison is against the right oracle, for the reason the file gives: "not the prediction of some other implementation of the same model, which is a different [question]". That is the same rule reached independently in three threads today (ggml-org#1698's literal goldens, ggml-org#1712's identity mapping, npu-kernels #40's probe_pred), and here it is load-bearing: a differently-quantised route would disagree for reasons that say nothing about the handoff.

The sequence is the one that can fail in the interesting ways, and each step is asserted separately: the dump must name its prefix (tokens.i32, P >= 2), its probe and its prediction (each exactly 4 bytes, else exit 3 — a fast, named refusal rather than a decode on a truncated dump); the regions are fabricated into a memfd; --writer fills them; llama_kv_cells_adopt(ctx, P, 0) must succeed; and then got == want with both numbers printed (decoder=… npu=…) so a failure is diagnosable without a re-run. Asserting the adopt and the decode separately matters: they fail for different reasons, and a single end-to-end == would hide which.

Cross-repo dependency worth stating for the queue: the dump this consumes (probe.i32, probe_pred.i32) is written by npu-kernels #40's latest commit, which I verdicted READY an hour ago. So #263 cannot be exercised until #40 is merged and a pack has been prefilled — the two halves are correctly split, and neither is a proof without the other.

One practical note: --writer being a separate command is the right call (it keeps the dma-buf writer out of the checker's address space and lets the writer be swapped), but it also means the check is only as trustworthy as the writer it is pointed at. Worth a line in the tool's usage saying that the writer must fill the same regions the checker fabricated — otherwise a "PASS" can mean two programs agreed to do nothing.

Not run: this needs an NPU prefill dump, a device ticket and a real model — outside what a review can do, and the tool is precisely the thing that makes it one command for whoever has the ticket.

@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 b7696efa, with one structural ask — the PR's own motivation is a gate, and what lands is two installed executables.

The idea is right and the correctness argument is the good kind. The reason engine#753's provider has never had a device-free gate is that a region with the right
layout hash could only come from a real decoder export — ggml-hrx, a GPU, a ticket. Reporting what the context expects, computed by the same share_layout() the
importer checks against
, removes the exporter from the loop entirely: a test can fabricate regions of those sizes carrying those hashes. Using the same function rather
than a re-derivation is the property that makes the gate mean anything — two independent computations would let the query pass while the import fails, which is the worst
possible gate.

Three details I want to credit specifically.

  1. The naming trap, found and written down: expects_layout as a member rather than share_layout, because a member of that name would hide the free
    share_layout(ctx, buft) it has to call. That is a C++ trap that costs an hour to find and one comment to prevent, and the comment is there.
  2. The return contract is the two-call pattern done correctly: return chunks.size() even when n_out is smaller, so a caller with n_out = 0 learns the requirement
    and a caller with a too-small buffer can detect the truncation instead of silently losing regions.
  3. No exporter in the loop is demonstrated, not asserted: both tools build without a device, which is the whole claim.

The ask: wire the gate into ctest, or write down why it cannot be. Both tools are add_executable + install(TARGETS … RUNTIME) — binaries a human runs, with no
add_test. The PR body calls this "the provider's import path with no GPU", i.e. a gate; a gate that only runs when someone remembers to run it is a tool, and the thing
this PR is fixing is exactly that the provider had no gate. Two honest outcomes:

  • if kvshare-layout-roundtrip can run against a minimal synthetic model (even a tiny gguf fixture), add add_test so it runs in the ordinary suite — then this PR delivers
    the gate it describes;
  • if it needs a real model file, say so in the tool's --help/docs and in the PR body — "device-free but model-dependent, so it is a tool and not a ctest gate" — which is a
    perfectly good answer, and the same shape as "this guardrail cannot charge that allocator". The only bad outcome is the current one, where the PR reads as a gate and the
    CMake reads as a tool.

One smaller note. The header comment should say explicitly that out[] beyond n = min(n_out, chunks.size()) is untouched — a caller that ignores the return value and
iterates n_out entries reads uninitialised memory for the tail. One line next to the size first with n_out = 0 note.

Not run: I did not build the tools. The review is of the API contract, the same-function property, and whether what lands is the gate the PR describes.

@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 at b7696ef: READY

Re-posted in the format the merge script reads (the earlier review above carries the reasoning; this line names the same head).

… what it needs

The review's ask: a gate that only runs when someone remembers to run it is a tool, and the thing this PR fixes is
that the provider had no gate. So one of the two becomes one, and the other says why it cannot.

- `kvshare_layout_roundtrip` is an `add_test` now (gated on the fork's own `LLAMA_BUILD_TESTS AND LLAMA_BUILD_COMMON`,
  SKIP_RETURN_CODE 77). Device-free but **model-dependent** -- a context has to exist before it can report the layout of
  its cache -- so it reads `KVSHARE_TEST_GGUF` at RUN time (a configure-time `$ENV{}` would freeze whatever was set that
  day, which is exactly the bug my first version had) and skips instead of reding CI without one. Measured both ways:
  `***Skipped` with the variable unset, `Passed 2.91 sec` with a small gguf.
- `kvshare-adopt-check` states in its header what it needs -- a real model, `/dev/udmabuf`, a dump from an NPU prefill and
  the private writer under an `npu-hold` -- so nobody wires it into CI expecting it to run. It is the semantic end-to-end,
  run by hand.

And the contract note the review asked for: entries of `out[]` at or beyond `min(n_out, returned)` are **untouched**, so a
caller that ignores the return value and iterates `n_out` reads uninitialised memory for the tail.

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

Copy link
Copy Markdown
Author

Both asks are in at f4cdb8d02, and the first one found a real bug in my own wiring.

1. One of the two is now a ctest; the other says why it cannot be.

kvshare_layout_roundtrip is an add_test, gated on the fork's own switch (LLAMA_BUILD_TESTS AND LLAMA_BUILD_COMMON, the
condition the top-level CMakeLists uses to include(CTest)), with SKIP_RETURN_CODE 77. It is device-free but
model-dependent — a context has to exist before it can report the layout of its cache — so it reads KVSHARE_TEST_GGUF at
run time and skips rather than reding CI without one:

no model set           1/1 Test #59: kvshare_layout_roundtrip .........***Skipped   0.00 sec
KVSHARE_TEST_GGUF=…    1/1 Test #59: kvshare_layout_roundtrip .........   Passed    2.91 sec

The bug that hid in that: my first version put $ENV{KVSHARE_TEST_GGUF} in the add_test command, which CMake expands
when the build is configured — so the test froze whatever was set that day and skipped even with the variable exported. It
was the same class of mistake as the stale-/tmp path and the zero-padded dump names: a value that looked configured and was
frozen. The tool now reads the variable itself.

kvshare-adopt-check states in its header what it needs — a real model, /dev/udmabuf, a dump from an NPU prefill, and the
private writer under an npu-hold — so it is documented as the semantic end-to-end run by hand, not a CI gate.

2. The contract note is in llama-ext.h: entries of out[] at or beyond min(n_out, returned) are untouched, so a
caller that ignores the return value and iterates n_out reads uninitialised memory for the tail.

Re-verdict requested at f4cdb8d02.

@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 f4cdb8d02 — the new commit does two things I would have asked for, and the skip is implemented the one way that does not lie.

1. The seam is now split by what can actually run in CI, and the split is argued rather than felt. kvshare_layout_roundtrip becomes a real ctest — device-free but model-dependent — while kvshare-adopt-check is explicitly "NOT a ctest gate, and deliberately", for four enumerated reasons (a real model, /dev/udmabuf, a dump from an NPU prefill, and the private writer under an npu-hold ticket). Naming the four is what stops someone later "just wiring it into CI" and leaving a test that can never pass.

2. The skip is loud, which is the detail I care about most. return 77 with SKIP_RETURN_CODE 77 set on the test, and a printed line: skip: pass -m model.gguf (or set KVSHARE_TEST_GGUF); … needs a model, not a device. A model-dependent gate that returns 0 when it cannot run would show green in every CI run while checking nothing — the same vacuity this repo has spent the day removing (ggml-org#1682's "no vacuous ok", q4nx_pb16i's SKIPPED in the pass line, ggml-org#1698's printed-versus-asserted goldens). SKIP_RETURN_CODE means ctest reports Skipped, not Passed, so the gap is visible in the summary where a person will look.

3. It also documents the return-value contract I would have had to guess at: "Entries of out at or beyond min(n_out, returned) are left UNTOUCHED: a caller that ignores the return value and …". For a two-call sizing API that is the property that makes n_out = 0, out = nullptr safe — which is how the tool itself sizes first.

My earlier note is now answered in the tool's own text: I asked for a line saying the writer must fill the same regions the checker fabricated, "otherwise a PASS can mean two programs agreed to do nothing". The usage block now describes the dump, the writer and what each half proves, and the layout half — which does not need the writer at all — is the one promoted into the suite. That is a better answer than the sentence I asked for.

What remains true: the semantic half still only means something when --writer fills the regions the checker fabricated, and it still needs the private writer plus a ticket. That is now a documented property of a tool that runs by hand, not a hidden assumption inside a gate.

@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 at f4cdb8d: READY

The reuse is the thing to check on an API like this, and it is explicit: expects_layout() calls "the same share_layout() the importer checks against". That
matters more than the API shape — if the reported hash were computed by a second path, a fabricated region could pass this gate and fail the real import, which is the
worst kind of device-free test (one that passes for the wrong reason).

+ // the chunks a context EXPECTS, from the same share_layout() the importer checks against, with no export
+ share_layout(cb.first.get(), ggml_backend_buffer_get_type(cb.second.get()));
+ out.push_back({-1, 0, c.size, c.layout});     // fd = -1: there is no exporter in the loop

Three details are right beyond the reuse:

  1. fd = -1 as the "no exporter" marker — a caller cannot mistake a fabricated descriptor for a mapped one, and the struct keeps its meaning for regions();
  2. "Entries of out at or beyond min(n_out, returned) are left UNTOUCHED" — the size-first convention from llama_kv_share_tensor_map, stated as a contract rather
    than left to the implementation, so a caller that ignores the return value gets zeros it can detect rather than a half-filled array;
  3. named apart from the free share_layout() it calls — small, but it is the difference between a reader wondering whether this is the hash or computes the hash.

The payoff is the sentence worth keeping in the doc: "This is what lets a provider be tested on a box with no GPU: fabricate regions of these sizes carrying these
hashes." That is the gap this closes — until now the only way to get a correctly-hashed region was to export from a real decoder, so engine#753's provider had no gate that
could run without a device ticket.

One distinction worth stating explicitly in the doc, so it is not over-read: this gates the admission/layout path — the hash the importer checks and the sizes it
maps. It does not prove the data path (that a prefill's K/V rows land where the tensor table says). A provider test built on this can therefore run device-free and
still needs one device run for the bytes; saying that in the header keeps "device-free gate" from being read as "no device needed".

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