Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,18 @@ add_dependencies(npu_sampling_test mtp_draft_test)
add_executable(npu_device_lock_test tests/npu_device_lock_test.cpp)
target_include_directories(npu_device_lock_test PRIVATE app)
add_test(NAME npu_device_lock COMMAND npu_device_lock_test)
# The snapshot's two kinds of plane (npu/forward/include/q4nx_state_planes.h): the KV cut to the positions being
# snapshotted, and the GDN conv window and recurrent state carried whole, since those are one fixed block per layer
# that every position updates rather than appends to. Header only, no device, runs in CI. Regression it pins: the
# whole planes used to be cut with the per-position count, so restore_state refused every snapshot the prefix cache
# offered (`slot has no usable state`) and every shared-prefix request re-prefilled the prompt from 0.
add_executable(q4nx_state_planes_test tests/q4nx_state_planes_test.cpp)
target_include_directories(q4nx_state_planes_test PRIVATE npu/forward/include app)
add_test(NAME q4nx_state_planes COMMAND q4nx_state_planes_test)
# ci.yml's build step lists every ctest target explicitly and this branch cannot edit that file (the push token has
# no `workflow` scope), so as with mtp_draft_test the binary is pulled in as a dependency of a listed target.
add_dependencies(npu_sampling_test q4nx_state_planes_test)

# general.architecture from a GGUF header (app/gguf_meta.h), which routes fork-only
# architectures to our llama.cpp; header only, runs in CI.
add_executable(gguf_meta_test tests/gguf_meta_test.cpp)
Expand Down
51 changes: 33 additions & 18 deletions app/forward_serve.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,9 @@ void handle_generate(ForwardEngine& e, const httplib::Request& req, httplib::Res
if (e.prefix && e.prefix->enabled()) {
const npu::PrefixDecision d = e.prefix->lookup(ids);
stats.prefix = d;
const int want = std::min(d.cached_tokens, int(ids.size()) - 1);
// One token short of both the slot and the prompt: the snapshot stops one token short (see the save
// below), and the last token is run again for the logits the answer is drawn from.
const int want = npu::resume_point(d, ids.size());
// The forward clears itself only when a batch starts at 0 (step_batch), and a resumed
// prefill starts above 0, so the previous request's state has to go first.
if (d.slot >= 0 && want > 0) {
Expand All @@ -266,25 +268,38 @@ void handle_generate(ForwardEngine& e, const httplib::Request& req, httplib::Res
}
{
const int chunk_max = std::max(1, e.fwd->max_batch_rows());
for (int off = resume; off < (int)ids.size(); off += chunk_max) {
const int take = std::min(chunk_max, (int)ids.size() - off);
std::vector<int> chunk(ids.begin() + off, ids.begin() + off + take);
const int n = int(ids.size());
for (int off = resume; off < n;) {
const int take = std::min(chunk_max, n - off);
// The state the prefix cache keeps is taken one token short of the prompt, because the answer is
// drawn from the last position's logits and a snapshot holds state, not logits -- so the snapshot
// is saved just before the last token and that token is run again on a resume. On a GDN model
// this is also the only exact point: the conv window and the recurrent state are updated in
// place, so a snapshot taken *after* the last token cannot be restored to just before it.
// Splitting the final chunk costs one launch.
if (off + take == n && take > 1) {
const std::vector<int> head(ids.begin() + off, ids.begin() + off + take - 1);
if (!e.fwd->step_batch(head, off, logits))
throw std::runtime_error(std::string("forward step failed: ") + e.fwd->last_error());
off += take - 1;
continue;
}
if (off + take == n && e.prefix && e.prefix->enabled()) {
Q4nxNpuForward::StateSnapshot snap;
if (e.fwd->snapshot_state(off, snap)) {
std::string why;
const int slot = e.prefix->insert(ids, snap.bytes(), stats.prefix.slot, &why);
if (slot >= 0 && size_t(slot) < e.prefix_state.size()) {
e.prefix_state[size_t(slot)] = std::move(snap);
std::fprintf(stderr, "[prefix] saved slot=%d tokens=%d bytes=%zu %s\n", slot, off,
e.prefix_state[size_t(slot)].bytes(), why.c_str());
}
}
}
const std::vector<int> chunk(ids.begin() + off, ids.begin() + off + take);
if (!e.fwd->step_batch(chunk, off, logits))
throw std::runtime_error(std::string("forward step failed: ") + e.fwd->last_error());
}
}
// Save the prompt's own state for the next request that shares it: taken here, at the
// prefill boundary, because the decode loop appends the answer to the same cache.
if (e.prefix && e.prefix->enabled() && !ids.empty()) {
Q4nxNpuForward::StateSnapshot snap;
if (e.fwd->snapshot_state(int(ids.size()), snap)) {
std::string why;
const int slot = e.prefix->insert(ids, snap.bytes(), stats.prefix.slot, &why);
if (slot >= 0 && size_t(slot) < e.prefix_state.size()) {
e.prefix_state[size_t(slot)] = std::move(snap);
std::fprintf(stderr, "[prefix] saved slot=%d tokens=%zu bytes=%zu %s\n", slot, ids.size(),
e.prefix_state[size_t(slot)].bytes(), why.c_str());
}
off += take;
}
}

Expand Down
12 changes: 12 additions & 0 deletions app/npu_prefix_cache.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,18 @@ struct PrefixDecision {
std::string reason; // "hit", "off", "no slot shares a prefix", "slot has no state", ...
};

// Where a hit may resume. A slot's snapshot is taken one token short of the prompt it was saved for
// (forward-serve splits the last prefill chunk and saves before it, because the answer is drawn from the last
// position's logits and a snapshot holds state, not logits), so the positions it can restore are `cached - 1`,
// and the resume never goes past the prompt's own last token either. On a GDN model restoring `cached - 1`
// of a snapshot taken at `cached` would apply the last token's in-place recurrence update twice, which answers
// the same prompt differently -- measured 2026-11-04, engine#984.
inline int resume_point(const PrefixDecision& d, size_t prompt_tokens) {
if (d.slot < 0 || d.cached_tokens <= 0 || prompt_tokens == 0) return 0;
const int cached = std::min(d.cached_tokens, int(prompt_tokens));
return cached > 0 ? cached - 1 : 0;
}

struct PrefixSlot {
std::vector<int> ids; // the tokens this slot covers, from position 0
size_t bytes = 0; // what its snapshot costs in the budget
Expand Down
29 changes: 29 additions & 0 deletions docs/npu.md
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,35 @@ or `=1` forces it either way, and the resolved state is logged once as
interleaved 5-round A/B (`~/lb/587-cache-20261030`) measured an 8-token request at 104.5 s against
117.4 s (**−11%**), CPU per token 22.9 s against 63.3 s (**−64%**), same text in every arm.

### The prefix cache's snapshot: two kinds of plane

`snapshot_state`/`restore_state` (`npu/forward/include/q4nx_forward.h`) hand a prefill's state to the next
request that shares its prompt (`app/npu_prefix_cache.h`, issue #650). A snapshot is not just the KV: a GDN layer
also carries a conv window and a recurrent state, and the two kinds of plane are cut differently.

- **Per position** (`kcache_`, `vcache_`): a layer holds `[NKV][HD]` floats for every position it has seen, so a
snapshot of the first `tokens` positions keeps exactly `tokens * NKV * HD` floats of each.
- **Whole** (`conv_state_`, `rec_state_`): the conv window and the recurrent state are one fixed block per layer
that each position *updates*, not appends to, so they are carried and restored whole at any prompt length.

Both live in `npu/forward/include/q4nx_state_planes.h`, header-only and unit-tested without a device
(`tests/q4nx_state_planes_test.cpp`, ctest `q4nx_state_planes`). Cutting the whole planes with the per-position
count was the shipped behaviour until 2026-11-04, and it cost the cache every request: on a GDN model the conv
plane (30,720 floats for Bonsai-2-27B) can never cover `tokens * 1024`, so `restore_state` refused every snapshot
of a prompt longer than 30 tokens and the serve logged `[prefix] slot=-1 cached=0 … reason=slot has no usable
state` and re-prefilled from 0 — 5 of 5 long requests measured, and a repeat of an 849-token prompt paid its full
prefill twice. Shorter prompts had the mirror-image problem: below 768 tokens the 786,432-float recurrent plane
was silently truncated (23 % of it kept at 180 tokens). A truncated plane is now *refused* rather than installed
short, so the fallback is a full prefill instead of a wrong state.

The whole planes also fix where the snapshot may be *taken*: they are updated in place, so there is no "restore
these positions of that state". `forward-serve` therefore saves a prompt's state one token short of the prompt —
splitting the final prefill chunk, one extra launch — and the resume point is `cached - 1`, running the last token
again to get the logits the answer is drawn from. Restoring `cached - 1` positions out of a snapshot taken at
`cached` is what the KV alone would allow, and it applies the last token's GDN update twice: measured on the first
version of this fix, the cache hit (`[prefix] slot=0 cached=179 of 180 reason=hit`, TTFT 5.3 s against 15.6 s) and
answered the same prompt with different, fragmented text.

### Sampling and structured output

`1bit serve -m <NPU model dir> --device npu` serves through `1bit forward-serve`
Expand Down
85 changes: 85 additions & 0 deletions npu/forward/include/q4nx_state_planes.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// Copyright 2026 bong-water-water-bong
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// q4nx_state_planes.h -- the plane-copy half of a state snapshot, in isolation so it can be tested without a
// device (tests/q4nx_state_planes_test.cpp). Two kinds of plane go into a snapshot and they are cut differently:
//
// PER-POSITION (kcache_/vcache_): one layer holds [NKV][HD] floats for every position it has seen, so a
// snapshot of the first `tokens` positions keeps `tokens * NKV * HD` floats of it and no more.
//
// WHOLE (conv_state_/rec_state_): the GDN conv window and the recurrent state are one fixed block per layer
// that is *updated* by each position, not appended to. Its size has nothing to do with `tokens`, so it is
// always carried and restored whole.
//
// Applying the per-position cut to a whole plane truncates it (a 786,432-float recurrent plane keeps only
// `tokens * 1024` of itself, 23 % of it at 180 tokens), and the restore then refuses the snapshot because the
// plane cannot cover the positions being restored -- which is why the prefix cache answered every request with
// `slot has no usable state` and re-prefilled, measured 2026-11-04 on the shipped Bonsai-2 serve.
#ifndef Q4NX_STATE_PLANES_H
#define Q4NX_STATE_PLANES_H

#include <algorithm>
#include <cstddef>
#include <vector>

namespace q4nx_state {

// Snapshot side: keep the first `want` floats of each per-position layer (empty layers stay empty).
inline void take_per_pos(const std::vector<std::vector<float>>& src, std::vector<std::vector<float>>& dst,
size_t want) {
dst.resize(src.size());
for (size_t l = 0; l < src.size(); l++) {
const size_t n = std::min(want, src[l].size());
dst[l].assign(src[l].begin(), src[l].begin() + long(n));
}
}

// Snapshot side: carry a whole plane as it stands.
inline void take_whole(const std::vector<std::vector<float>>& src, std::vector<std::vector<float>>& dst) {
dst = src;
}

// Restore side: a per-position layer must cover the positions being restored, and an empty layer means the
// plane is not this layer's to hold (a shared-KV layer), so the destination is left empty rather than filled
// with another layer's keys.
inline bool give_per_pos(const std::vector<std::vector<float>>& src, std::vector<std::vector<float>>& dst,
size_t want) {
if (dst.size() < src.size()) return false;
for (size_t l = 0; l < src.size(); l++) {
if (src[l].empty()) {
dst[l].clear();
continue;
}
if (src[l].size() < want) return false;
dst[l].assign(src[l].begin(), src[l].begin() + long(want));
}
return true;
}

// Restore side: a whole plane is accepted only at the size this forward allocated. A truncated one is refused
// (the caller falls back to a full prefill) instead of being installed short, which would leave the GDN step
// reading past the end of the plane.
inline bool give_whole(const std::vector<std::vector<float>>& src, std::vector<std::vector<float>>& dst) {
if (dst.size() < src.size()) return false;
for (size_t l = 0; l < src.size(); l++) {
if (src[l].size() != dst[l].size()) return false;
dst[l] = src[l];
}
return true;
}

} // namespace q4nx_state

#endif // Q4NX_STATE_PLANES_H
45 changes: 16 additions & 29 deletions npu/forward/src/q4nx_forward.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
// Numerics follow tools/q4nx_forward_ref.py so the two can be compared
// element-wise.
#include "q4nx_forward.h"
#include "q4nx_state_planes.h" // the plane-copy half of a snapshot, device-free and unit-tested
#include <algorithm>
#include <fcntl.h>
#include <unistd.h> // mkstemp/close: the pb16i activation probe's dump
Expand Down Expand Up @@ -277,17 +278,14 @@ bool Q4nxNpuForward::snapshot_state(int tokens, StateSnapshot& out) const {
out.tokens = tokens;
out.per_pos = per;
const size_t want = size_t(tokens) * per;
auto copy = [&](const std::vector<std::vector<float>>& src, std::vector<std::vector<float>>& dst) {
dst.resize(src.size());
for (size_t l = 0; l < src.size(); l++) {
const size_t n = std::min(want, src[l].size());
dst[l].assign(src[l].begin(), src[l].begin() + long(n));
}
};
copy(kcache_, out.k);
copy(vcache_, out.v);
copy(conv_state_, out.conv);
copy(rec_state_, out.rec);
// KV is per position, so a snapshot of the first `tokens` positions keeps exactly that many; the GDN conv
// window and recurrent state are fixed-size blocks updated per position, so they go in whole. Cutting them
// with `want` truncated them (23 % of the recurrent plane at 180 tokens) and made restore_state refuse the
// snapshot -- the prefix cache's `slot has no usable state`, which cost a full re-prefill on every request.
q4nx_state::take_per_pos(kcache_, out.k, want);
q4nx_state::take_per_pos(vcache_, out.v, want);
q4nx_state::take_whole(conv_state_, out.conv);
q4nx_state::take_whole(rec_state_, out.rec);
return true;
}

Expand All @@ -296,24 +294,13 @@ bool Q4nxNpuForward::restore_state(const StateSnapshot& in, int tokens) {
const size_t per = size_t(c_.NKV) * size_t(c_.HD);
if (in.per_pos != per) return false;
const size_t want = size_t(tokens) * per;
auto put = [&](const std::vector<std::vector<float>>& src, std::vector<std::vector<float>>& dst) {
if (dst.size() < src.size()) return false;
for (size_t l = 0; l < src.size(); l++) {
// A layer that holds KV must cover the positions being restored, or attention() would
// read past the end of a shorter array.
if (!src[l].empty() && src[l].size() < want) return false;
if (src[l].empty()) {
// A layer whose KV is shared (Gemma style) carries none of its own: leave it empty
// rather than filling it with the owner's, which attention() reads by kv_layer.
dst[l].clear();
continue;
}
dst[l].assign(src[l].begin(), src[l].begin() + long(std::min(want, src[l].size())));
}
return true;
};
if (!put(in.k, kcache_) || !put(in.v, vcache_)) return false;
if (!put(in.conv, conv_state_) || !put(in.rec, rec_state_)) return false;
// Same split as snapshot_state: KV is restored per position (a layer whose KV is shared carries none of its
// own, so an empty plane leaves the destination empty rather than filling it with the owner's), and the GDN
// planes are restored whole -- refusing a truncated one instead of installing it short.
if (!q4nx_state::give_per_pos(in.k, kcache_, want)) return false;
if (!q4nx_state::give_per_pos(in.v, vcache_, want)) return false;
if (!q4nx_state::give_whole(in.conv, conv_state_)) return false;
if (!q4nx_state::give_whole(in.rec, rec_state_)) return false;
return true;
}

Expand Down
Loading
Loading