Skip to content

npu: cache the dense FFN tail for GDN models by default (#587) - #637

Merged
bong-water-water-bong merged 2 commits into
mainfrom
npu-587-dense-tail-default
Oct 30, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
npu-587-dense-tail-default

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

What this does

step()'s dense_weights_cached guard cannot fire for a hybrid GDN model — it requires
lin_kd_ == 0, and lin_kd_ = lin_nkh_ * lin_khd_ is model-level — so a qwen3_5 model
re-dequantised each layer's 17408-wide dense FFN tail on every token, even after those weights
were packed on the device. ffn_tail_cached() closes that hole (the three f32 wg_/wu_/wd_
buffers are read only by q4nx_assemble_B(), which the MLP sections skip once the layer's packed
weights are resident).

This PR lands that mechanism and makes it the default for GDN models on the NPU route, with a
size/footprint guard, instead of leaving it as an env-only knob.

Measured, not guessed

~/lb/587-cache-20261030/run-20261030T030506Z (driver + results.tsv + logs), Qwen3.8-27B-NPU2 on
strixhalo, 5 rounds x 3 arms interleaved, 0 void rows, arm order rotated, 8-token request:

arm wall (s) CPU/request (s) CPU/token (s)
guard as shipped 117.403 ± 0.195 506.4 63.30
guard forced false 117.443 ± 0.156 506.1 63.26
ffn_tail_cached() on 104.524 ± 0.553 182.8 22.85
  • guard forced false vs shipped: paired Δ −0.040 ± 0.102 s — identical because they are the
    same branch
    (lin_kd_ == 0 short-circuits to false on this model). The guard line is dead code
    for GDN; it stays because it is still right for dense models.
  • tail cache vs shipped: −11.0% wall, −64% CPU per token, negative in all five rounds, same
    generated text ( 4, 5, 6) in every arm, and no change in residency (MemAvailable 76.3–76.8 G
    after, every arm).
  • Reported on the issue: NPU: Qwen3.8-27B-NPU2 (FastFlowLM Q4NX, 17.1 GB) on the NPU route and as the hybrid prefill side #587 (comment)

The guard

ffn_cache_ is tri-state: -1 auto (new default), 0/1 forced by NPU_FFN_CACHE=0|1 as before.
ffn_cache_default() enables the cache when all of:

  • lin_kd_ > 0 — a GDN/hybrid model, the only case the step() guard cannot cover;
  • weight_cache_ — the packed-weight cache is on, so the tail can actually become resident;
  • not host_gemm_ — a host-GEMM run never packs, and keeps its legacy behaviour;
  • dense tail ≥ 256 MB per layer (3 * IM * H * 4) — 1.07 GB/layer on the 27B, so a small GDN model
    keeps the old behaviour rather than taking an unasked behaviour change for no gain.

ffn_tail_cached() still requires each layer's packed BOs to be present (weight_cached(2),
weight_cached(4), plus 3 on a split gate/up design), so the first use of every layer stays
correct. The resolved state is logged once at init:

[ffn] dense-tail cache on (default; lin_kd=2048 IM=17408 H=5120)
[ffn] dense-tail cache off (NPU_FFN_CACHE; lin_kd=2048 IM=17408 H=5120)

so a measurement can always tell "off" from "never asked".

Proof status

Draft PR: the confirmation run (~/lb/587-default-20261030/drv.sh, three interleaved arms —
default / NPU_FFN_CACHE=0 / NPU_FFN_CACHE=1, same driver shape as the A/B, plus a self-check
that each arm logs the state its name claims) is queued on /tmp/1bit-npu-device.lock, which the
owner's Bonsai job holds. It gates with flock -n and waits; it never evicts the owner. Expected:
default ≡ NPU_FFN_CACHE=1 ≈ 104.5 s, NPU_FFN_CACHE=0 ≈ 117.4 s. I will post the numbers here and
mark the PR ready before the orchestrator merges.

Known limit, stated rather than hidden: the below-threshold branch of ffn_cache_default() is
unexercised — there is no small GDN model on the box to run it against.

Files

  • npu/forward/src/q4nx_forward.cpp — the tail cache, its guard, the resolved-state log
  • npu/forward/include/q4nx_forward.h — ffn_tail_cached() / ffn_cache_default(), tri-state flag
  • docs/npu.md — "The dense FFN tail cache (hybrid GDN models)"

`step()`'s `dense_weights_cached` guard can never fire for a hybrid GDN
model: it requires `lin_kd_ == 0`, and `lin_kd_` is model-level, so a
qwen3_5 model re-dequantised each layer's 17408-wide dense FFN tail on
every token even after those weights were packed on the device.  A
measured 5-round interleaved A/B on Qwen3.8-27B-NPU2 shows the guard line
forced to `false` and left alone are the same code path (117.403 vs
117.443 s for an 8-token request, paired delta -0.040 +/- 0.102 s), while
skipping the reload through `ffn_tail_cached()` cuts the same request to
104.524 s (-11.0%) and CPU per token from 63.30 to 22.85 s (-64%), with
identical text (~/lb/587-cache-20261030).

So the cache becomes the default where it is safe and worth it rather
than opt-in: a GDN model on the NPU route, the packed-weight cache on, not
a host-GEMM run, and a dense tail of at least 256 MB per layer.
`ffn_cache_default()` is that rule, `ffn_cache_` is tri-state (-1 auto,
0/1 forced by NPU_FFN_CACHE as before), the resolved state is logged once
as `[ffn] dense-tail cache on|off (default|NPU_FFN_CACHE; ...)`, and
docs/npu.md gains a subsection with the numbers and the two env knobs.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Proof status, with the failure stated rather than hidden.

Attempt 1 deadlocked, my bug. The driver held an exclusive flock on /tmp/1bit-npu-device.lock
for the whole arm, and the engine binary itself takes that lock at startup (app/forward_serve.cpp:404,
[npu] waiting for the exclusive device lock (…)...). flock is per open file description, so the server
waited on a lock its own parent owned: never healthy, 0 rows. It also returned exit 0 on an empty run,
which is fixed — the driver now fails when the row count is short.

Attempt 2 is running with the lock discipline inverted: the driver only probes the lock
(flock -n, released at once), requires zero foreign 1bit forward-serve, and lets the server take
the lock itself — which is also exactly the lane rule (run only when the device is free, never evict).
It is measured lean because the owner's Bonsai jobs run back to back (~2 h each; the gap I observed was
52 s): 8-token requests only, 2 rounds x 3 arms, one round per window, so ~2 min of device per window.

Arms and the self-check: default must log on (default; …), NPU_FFN_CACHE=0 must log
off (NPU_FFN_CACHE; …), NPU_FFN_CACHE=1 must log on (NPU_FFN_CACHE; …); the driver aborts
otherwise, before spending a window on a run that cannot mean anything. Expected, from the A/B:
default ≡ NPU_FFN_CACHE=1 ≈ 104.5 s, NPU_FFN_CACHE=0 ≈ 117.4 s, against a ±0.2 s noise floor.

I will post the numbers here and mark this ready when a window lands.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Proof is in — the default does what the PR says, measured on the device.

Run ~/lb/587-default-20261030/run-20261030T110721Z (driver drv.sh, results.tsv, logs), strixhalo
2026-10-30 11:07–11:22 UTC on a real free device window, 2 rounds × 3 arms rotated (default /
NPU_FFN_CACHE=0 / NPU_FFN_CACHE=1), same binary 0c1cbf94…, 8-token request, 0 void rows,
server pid + /proc start time + port owner checked per request, identical text ( 4, 5, 6) in all
six requests.

Each arm logged the state its name claims — this is asserted by the driver, not eyeballed:

default     [ffn] dense-tail cache on (default; lin_kd=2048 IM=17408 H=5120)
forced-off  [ffn] dense-tail cache off (NPU_FFN_CACHE; lin_kd=2048 IM=17408 H=5120)
forced-on   [ffn] dense-tail cache on (NPU_FFN_CACHE; lin_kd=2048 IM=17408 H=5120)
arm CPU over the 8-token request (s) CPU/token (s) wall (s)
default 579.42 / 548.98 72.43 / 68.62 153.80 / 137.66
NPU_FFN_CACHE=1 561.71 / 548.20 70.21 / 68.53 138.75 / 135.62
NPU_FFN_CACHE=0 892.70 / 838.72 111.59 / 104.84 150.55 / 152.68
  • default ≡ NPU_FFN_CACHE=1: +3.2% and +0.1% of CPU, i.e. the same path. Wall agrees once
    cold start is out of it (the very first server of the run, default r1, paid 153.80 s against its
    own 137.66 s in r2, and against NPU_FFN_CACHE=1's 138.75/135.62).
  • NPU_FFN_CACHE=0 costs +53% and +59% CPU (+331 s and +290 s per request) and ~10% wall
    (150.55/152.68 against 138.75/135.62). That is the pre-change behaviour this PR replaces, and the
    override still works.
  • The override is honoured in both directions and the resolved state is visible at startup, so
    "off" can no longer be confused with "never asked".

Caveat, stated rather than smoothed: absolute seconds are not comparable with the 03:05 UTC A/B
(104.5 / 117.4 s there). This window ran on a busier box — MemAvailable 95–97 G against 119 G then —
so every arm is ~30% slower in wall. The comparison that matters is inside this window: the arms are
interleaved, so the CPU gap (+53–59%) and the wall gap (~10%) are both measured on the same box
state. CPU is the stable signal here; wall carries the cold-start variance.

Known limit, unchanged: the below-threshold branch of ffn_cache_default() is unexercised — there is
no small GDN model on this box to run it against. The device lock is released; no NPU process of mine
is running.

@bong-water-water-bong
bong-water-water-bong marked this pull request as ready for review October 30, 2026 11:23

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT: READY (posted as a comment: GitHub refuses --request-changes/--approve on a PR owned by the same account).

Built it, and re-derived the proof from the artifacts rather than from the table.

Build: -DONEBIT_NPU=ON -DONEBIT_NPU_RT_DIR=<the private runtime>, gcc-16, Release, under ~/lb/thermal-run.sh at e972701 — 37/37, 1bit links (3.7 MB, forward-serve present in --help), and the only five warnings in the whole build are the pre-existing nlohmann is_trivial deprecation; none from q4nx_forward.cpp. The new dense-tail cache log string is in the binary.

The proof numbers are exactly ~/lb/587-default-20261030/run-20261030T110721Z/results.tsv:

round  arm         wall_s   ncpu_s  cpu_s_per_tok  ffn
1      default     153.795  579.42  72.428         on (default; lin_kd=2048 IM=17408 H=5120)
1      forced-off  150.547  892.70  111.588        off (NPU_FFN_CACHE; ...)
1      forced-on   138.752  561.71  70.214         on (NPU_FFN_CACHE; ...)
2      forced-off  152.675  838.72  104.840        off (...)
2      forced-on   135.623  548.20  68.525         on (...)
2      default     137.662  548.98  68.623         on (default; ...)

so 579.42/548.98, 561.71/548.20, 892.70/838.72 s CPU and 153.80/137.66, 138.75/135.62, 150.55/152.68 s wall are the measured values, void=0 in all six rows, text is 4, 5, 6 in all six, and no arm's logged state contradicts its name. Re-derived: default vs forced-on is +3.15 % (r1) and +0.14 % (r2); forced-off is +59.0 % / +53.0 % CPU against the forced-on arms (+331 s / +290 s), and 8.5 % / 12.6 % wall. All as stated.

The binary is a build of this change: driver.log records sha256=0c1cbf9425f2… for /home/bcloud/wt/w-587-def-build/1bit, that file still hashes to the same value, and it carries the new dense-tail cache string that only exists with this PR. The 03:05Z A/B behind docs/npu.md also checks out as stated, as means not bests: ~/lb/587-cache-20261030/run-20261030T030506Z 8-token rows, 5 rounds each — tail-cached 104.52 s / 22.85 s per token against 117.40 and 117.44 s / 63.30 and 63.26 s, i.e. −11 % and −64 %, which is where "104.5 / 117.4 s, 22.9 / 63.3 s" comes from.

The correctness argument holds by reading, and this is the part that matters for a default-on skip. wg_, wu_, wd_ are read only through q4nx_assemble_B() (the p.gate = wg_.data() assignments are pointer setup; mlp() and moe_mlp() never touch them). step() gates those assembles per key (2, then 3 for a split GU, then 4) — exactly the set ffn_tail_cached() requires, including the fused-GU case where key 3 does not exist, so the guard cannot be silently dead. And the load-time guard can never leave a stale tail where an assemble still runs: at a layer's first forward nothing is packed yet, so ffn_tail_cached() is false and the dequant happens; afterwards keys 0 (attention) is packed before 2/3/4 in the same layer, so any later state where 2/3/4 are cached also has step_batch()'s key-0 gate closed. Host-GEMM (NPU_INFER_HOST_GEMM) and NPU_NO_WCACHE both resolve the cache off, so the paths that really need the f32 weights keep them.

I could not run the device myself: the owner's Bonsai serve holds /tmp/1bit-npu-device.lock, and the lane rules put that job first, so the device numbers above are yours (recorded binary hash, per-request pid/port-owner checks, and the [ffn] state line in every arm are what make them checkable — thank you for that).

Two nits, neither blocking:

  1. NPU_FFN_CACHE is parsed as atoi(v) != 0, so NPU_FFN_CACHE=on (or true, yes) resolves to off — the opposite of what the operator just wrote, and the opposite of every other presence-based switch in this file (NPU_NO_WCACHE, NPU_INFER_HOST_GEMM). Either document "=0 or =1 only, anything else is off" in docs/npu.md, or treat a non-numeric value as on.
  2. ffn_tail_cached() is weaker than step_batch()'s gate: that function uses one cached = weight_cached(0) for the whole layer (attention and MLP assembles), while step() gates per key as this guard does. It is consistent today for the reason above, but the invariant "key 0 cached implies 2/3/4 cached" is now load-bearing across two functions and lives only in this PR's reasoning — one line in ffn_tail_cached() saying so would stop the next reader from "tightening" either guard.

Also recording the author's stated limit as mine: the below-256 MB branch of ffn_cache_default() is unexercised (no small GDN model on this box), and it is the branch that would decide the default on a different GDN model.

@bong-water-water-bong
bong-water-water-bong merged commit b6511c0 into main Oct 30, 2026
7 of 8 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the npu-587-dense-tail-default branch October 30, 2026 15:09
bong-water-water-bong pushed a commit that referenced this pull request Oct 30, 2026
…the device already holds

Decode on the 27B container was 13.3 s/token on the shipping build and 11.5 s/token with the M=16
twins passed in by hand; it is 8.87 s/token out of the box with this, and a 1-token request drops
from 26.5 s to 9.2 s (the serve half is the next commit).  The dense-FFN-tail cache that used to be
part of this commit landed upstream as #637, so this is what is left on top of it:

1. The M=16 decode twins are found without an extra flag.  The loader looks for
   full_i8_<ROLE>_K<K>_N<N>_m16.elf in <model dir>/kernels-m16, then <kernels>/m16, then <kernels>,
   so a model directory can ship its own decode family and a plain
   `--kernels <model>/kernels` serve runs M=16.  A role with no twin still falls back to M=128, so a
   kernel dir without twins behaves exactly as before.  Until now the twins were opt-in through
   NPU_DECODE_M16 plus a hand-built --kernels directory, which is why the shipped serve ran m16=0
   and paid the 1.16x.  (Twins are bit-exact against the M=128 kernels: NPU_M16_CHECK=1,
   mismatched=0, worst int32 maxdiff=0.)

2. ctx_for() gives the twin to any pass with <=16 rows, not just rows==1, so a short prompt's
   prefill chunk also stops streaming 128 MAC rows for <=16 useful ones.  Chunks wider than 16 keep
   M=128, so long prefill is unchanged.

3. lm_head is packed once into resident weight BOs (same packer, same padded KD x ND BO, same
   per-column scales, so the packed bytes are bit-identical) instead of re-gathering 5.09 GB of f32
   and re-running packB on all 15 tiles every token; lm_head_f_ / lm_head_tiles_ are released
   afterwards, 10.4 GB of RSS returned.  Measured 1251 ms -> 419 ms for the head on the H2
   container (-0.83 s/token), RSS after load 60 GB -> 18 GB.

Also carries the env-gated NPU_PHASE_PROF attribution used to find (3) and the earlier host work:
one [ph] line per decode step whose named phases sum to its wall time, plus the ranked layer-loop
host call sites.  Nothing in the compute path reads it and it is free when the variable is unset.
It also carries m16_check_gemm_rows(), the multi-row half of the NPU_M16_CHECK gate, without which
change (2) would be outside the bit-exact gate.

Measured, decode step, 368 launches, 7 roles all at M=16: wall 8.87 s (layers 8.44 = wait 7.60 +
host 0.61 + quantise/launch 0.22, head 0.42).  Greedy text identical on 9 requests.
bong-water-water-bong added a commit that referenced this pull request Oct 30, 2026
…en re-dequant) (#661)

* npu: decode at M=16 from the model dir, and stop per-token host work the device already holds

Decode on the 27B container was 13.3 s/token on the shipping build and 11.5 s/token with the M=16
twins passed in by hand; it is 8.87 s/token out of the box with this, and a 1-token request drops
from 26.5 s to 9.2 s (the serve half is the next commit).  The dense-FFN-tail cache that used to be
part of this commit landed upstream as #637, so this is what is left on top of it:

1. The M=16 decode twins are found without an extra flag.  The loader looks for
   full_i8_<ROLE>_K<K>_N<N>_m16.elf in <model dir>/kernels-m16, then <kernels>/m16, then <kernels>,
   so a model directory can ship its own decode family and a plain
   `--kernels <model>/kernels` serve runs M=16.  A role with no twin still falls back to M=128, so a
   kernel dir without twins behaves exactly as before.  Until now the twins were opt-in through
   NPU_DECODE_M16 plus a hand-built --kernels directory, which is why the shipped serve ran m16=0
   and paid the 1.16x.  (Twins are bit-exact against the M=128 kernels: NPU_M16_CHECK=1,
   mismatched=0, worst int32 maxdiff=0.)

2. ctx_for() gives the twin to any pass with <=16 rows, not just rows==1, so a short prompt's
   prefill chunk also stops streaming 128 MAC rows for <=16 useful ones.  Chunks wider than 16 keep
   M=128, so long prefill is unchanged.

3. lm_head is packed once into resident weight BOs (same packer, same padded KD x ND BO, same
   per-column scales, so the packed bytes are bit-identical) instead of re-gathering 5.09 GB of f32
   and re-running packB on all 15 tiles every token; lm_head_f_ / lm_head_tiles_ are released
   afterwards, 10.4 GB of RSS returned.  Measured 1251 ms -> 419 ms for the head on the H2
   container (-0.83 s/token), RSS after load 60 GB -> 18 GB.

Also carries the env-gated NPU_PHASE_PROF attribution used to find (3) and the earlier host work:
one [ph] line per decode step whose named phases sum to its wall time, plus the ranked layer-loop
host call sites.  Nothing in the compute path reads it and it is free when the variable is unset.
It also carries m16_check_gemm_rows(), the multi-row half of the NPU_M16_CHECK gate, without which
change (2) would be outside the bit-exact gate.

Measured, decode step, 368 launches, 7 roles all at M=16: wall 8.87 s (layers 8.44 = wait 7.60 +
host 0.61 + quantise/launch 0.22, head 0.42).  Greedy text identical on 9 requests.

* serve: do not spend a decode step on logits nobody reads

The generate loop sampled the token from the current logits, emitted it, and
then always ran one more forward to produce the NEXT position's logits -- even
when that token was the last one the request could produce.  On the 27B that
step is a whole weight stream (8.9 s), so max_tokens=1 cost two full passes for
one token: 26.5 s -> 9.2 s wall, and n=4 66.5 s -> 36.1 s.

Skipping it is behaviour-preserving: the loop can only end after this token if
it was the limit-th one, and the KV/recurrent state is reset per request.

* npu: drop the NPU_KERNELS_M16 override (cpp/path-injection), one name for twins

CodeQL's cpp/path-injection on the new kernel-dir discovery is right: taking a
directory out of the environment and fopen()ing <it>/<elf> is user input
reaching a file access, the same shape as #640's ONEBIT_NPU_DEVICE_LOCK alert.
The override buys nothing the two derived candidates do not already give:
<model dir>/kernels-m16 and <kernels>/m16 both come from the -m and --kernels
paths the serve was already started with, so a model directory still ships its
own decode family and a plain `--kernels <model>/kernels` serve still runs M=16.
Search order is now: <model dir>/kernels-m16, <kernels>/m16, <kernels>.

Also removes the second way of spelling a decode twin's artifact name:
set_elf_name() keeps its original un-suffixed form (every caller is a prefill
design) and q4nx_derive_decode_designs() remains the only place that inserts
"_m16".

Verified after the change: 7/7 roles load at M=16 from
<model dir>/kernels-m16 with no environment variable, n=1 9.23 s / n=4 35.42 s
on the H2 container, greedy text unchanged (' Paris', ' Paris.\nThe').

---------

Co-authored-by: bong-water-water-bong <[email protected]>
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