Skip to content

npu: attention.mode, so a noncausal_full_attention pack (d3-lite) is not answered causally (#847) - #861

Merged
bong-water-water-bong merged 3 commits into
mainfrom
npu/noncausal-attn
Nov 3, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
npu/noncausal-attn

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Engine #847: a pack whose own decision_config.json says attention_mode: noncausal_full_attention (d3-lite) is no longer answered with a causal mask. The mode is read from the pack, carried in the stream plan, and honoured by the forward's full-attention layers; generation is refused by name instead.

Why

npu/forward had exactly one mask. d3-lite's pack is trained with every full-attention layer reading the whole prompt (d3_runtime.PromptEncoder: a boolean key mask [B,1,1,L] on the softmax layers, the GDN scan still causal, stock RoPE positions, pooled at [:, -1]), and its own runtime says that choice alone is worth 0.2869 worst |Δp| against the same pack run causally (~/lb/d3parity/ref_causal.py). The engine answered causally and said nothing, so the #796 parity gap of 0.72 began with a mask the engine could not express.

What

  • npu/plan/plan.h — attention.mode is an optional field of 1bit-npu-plan/1 ("causal" default, or "noncausal_full_attention"). Not a format bump: a plan written before the field loads and means exactly what it meant then. Any other string is a plan refusal naming it, never a default — the two modes give different numbers and a guessed mask is a different model.
  • tools/npu_plan.py (1.1) — the mode comes from the pack's own decision_config.json; no such file means causal. An unknown attention_mode is refused with the path.
  • q4nx_forward.cpp — for a noncausal plan, step_batch() fills each full-attention layer's K/V cache for all rows first and only then attends (kv_len = start_pos + M), so row r sees rows after it. GDN layers keep their causal recurrence and a sliding layer stays causal, exactly as the reference splits them. attention() gained an optional kv_len (rope, qk-norm and the cache append are position-local and unchanged).
  • Refusals instead of a silent causal answer, which is the point of the change:
    • step_batch() called with start_pos > 0 → the earlier positions were already encoded causally and cannot be repaired;
    • step() (generation) → the mode cannot generate at all;
    • a noncausal pack sent to /v1/chat/completions therefore fails loudly;
  • docs/npu.md — the field, its two shapes, and why an unknown mode is a refusal.

Measured (strixhalo, Qwen3.5-0.6B-free: the real d3-lite pack, host-GEMM, no device opened; one npu-hold -l npufeat ticket 01793655369698324085, amdxdna errors 0 before and after)

Two binaries, so every row is attributable: /tmp/1bit-pre built from 40d9632 (before this change) and the PR head.

row result
ctest npu_plan, npu_plan_generate, npu_sampling, decision_head, systemone_contract, systemone_route 6/6 PASS (9 new assertions: 5 in npu_plan, 4 in npu_plan_generate)
tools/copyright.py --check rc 0
plan generation on the real pack … attention noncausal_full_attention; on the causal synth pack (decision_config.json says causal) → attention causal; --check matches on both
before, noncausal plan, old binary loads, prints no [plan] attention.mode line, and answers exactly the causal numbers — worst
after, noncausal plan [plan] attention.mode noncausal_full_attention: … at init, and the answers move: per case max
identical weights, plan switched to causal answers differ from the noncausal run by the same amounts, i.e. the only difference between the two runs is the mask
causal pack (d3-synth-0.6b, plan causal) old binary and new binary produce byte-identical JSON for all ten requests
POST /v1/chat/completions on the noncausal pack refused by name: forward step failed: attention.mode noncausal_full_attention is a prompt-encoding mode and step() generates: …
POST /v1/systemone on the noncausal pack answers all ten contract requests; usage.input_tokens unchanged from the causal run (102/123/94/92/98/95/90/94/106/329)

Per-case, noncausal vs causal, engine (probability fields):

score_three_levels   0.0166    score_json_levels  0.0153
multi_three          0.0163    choice_unicode     0.0020
choice_three_json    0.0152    choice_instructions 0.0009   choice_two_one_null 0.0004

The part that does not meet the acceptance, stated rather than rounded

pi-issues asked for noncausal vs causal to differ by at least the reference's own 0.2869. It does not: the engine moves 0.0166 at worst, i.e. 3×–290× smaller per case than the reference on the same requests. What that means, without over-reading it:

  • the mask is applied (0 in the old binary, 0.0166 here, and the causal pack is byte-identical, so it is not numerical noise);
  • the ordering only partly agrees: score_three_levels is the largest case in both (0.2869 ref / 0.0166 engine), score_json_levels and choice_three_json are high in both — but choice_instructions is the reference's second-largest (0.2587) and among the engine's smallest (0.0009);
  • the reason is not isolated and I am not claiming it is the mask implementation. The engine's forward already disagrees with the reference by up to 0.72 with the weights held identical (#796, and #849 is the other known cause of that gap), so the mask's contribution cannot be validated in magnitude until that is closed. The diagnostic that decides it — dump the pooled last_hidden() in both modes and compare the two hidden vectors, then the same prompt against the reference's PromptEncoder on/off — is written and queued behind a contended NPU queue; its numbers will be a comment on this PR, not a claim in this body.

So: the mode is implemented, refuses to lie about what it cannot do, and provably changes the answer; it is not yet shown to reproduce the reference's magnitude. #847 stays open for the magnitude until that diagnostic lands.

Device

Host-GEMM throughout (NPU_INFER_HOST_GEMM=1): weights decoded, designs derived, no ELF set needed (#833), no device context and no firmware command — the six designs print (host-GEMM, no ELF: …). One ticket for the whole matrix, tokens released, owner serve on :18097 never touched.

Apache notice on every file touched; npu/plan/plan.h, tools/npu_plan.py, npu/forward/**, tests/*, docs/npu.md, configs/plans/* (the four reference plans carry the new attention block, --check matches).

…(d3-lite) is not answered causally (#847)

A d3 readout pack is trained with every full-attention layer seeing the whole prompt
(its decision_config.json says attention_mode: noncausal_full_attention), and the
forward was causal-only, so engine answers disagreed with the pack's own runtime by
up to 0.72 |dp| with the weights held identical. The reference says the mode alone is
worth 0.2869.

- npu/plan/plan.h: optional attention.mode ('causal' default, or
  'noncausal_full_attention'); an unknown string is a plan refusal, not a default.
  Not a format bump: a plan written before the field loads and means causal.
- tools/npu_plan.py: the mode comes from the pack's own decision_config.json.
- q4nx_forward: step_batch fills the K/V cache for every row first and only then
  attends over the whole prompt for full-attention layers; GDN keeps its causal
  recurrence and a sliding layer stays causal. A chunk starting above 0 is refused
  by name (earlier positions were already encoded causally) and step() refuses to
  generate, so a d3 pack on the chat route is an error rather than a causal answer.
- docs/npu.md, npu_plan tests, npu_plan_generate tests.
@github-actions

github-actions Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit aee8279)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

847 - Partially compliant

Compliant requirements:

  • The engine now reads attention_mode from the pack's decision_config.json
  • The full-attention path honours the noncausal mode for prompt-only forward
  • Bidirectional mask is used for full-attention layers when noncausal_full_attention is set
  • GDN layers keep their causal recurrence
  • Decode is causal by construction and noncausal packs are refused for generation
  • Tests validate that noncausal vs causal modes produce different results
  • Causal models remain byte-identical

Non-compliant requirements:

  • The PR does not include a test that compares against the reference d3_runtime.py with known-answer checks

Requires further human verification:

  • Validation against the reference d3_runtime.py with the exact same weights and prompt
  • Verification that the engine's output matches the reference's output within the measured tolerance
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Noncausal Attention Implementation

The implementation of noncausal attention in q4nx_forward.cpp introduces a new code path for handling full-attention layers when noncausal_attn_ is true. The code fills the K/V cache for all rows first and then performs attention, which is correct for noncausal mode. However, the implementation assumes that all full-attention layers are processed in a single batch, which may not be true for all cases. The code also introduces a new parameter kv_len to the attention function, which is used to control the attention window, but it's not clear if this is sufficient to handle all edge cases of noncausal attention.

if (noncausal_attn_ && l_full) {
    for (int m = 0; m < M; m++)
        if (!row_attn(m, nullptr, true, 0)) return false;
    for (int m = 0; m < M; m++)
        if (!row_attn(m, CTX.data() + (size_t)m * ctx_w, false, start_pos + M))
            return false;
} else {
    for (int m = 0; m < M; m++)
        if (!row_attn(m, CTX.data() + (size_t)m * ctx_w, true, 0)) return false;
}
Attention Mode Validation

The attention_mode function in tools/npu_plan.py validates that the attention mode is either "causal" or "noncausal_full_attention", but it does not check if the mode is valid for the specific model or layer types. This could lead to incorrect behavior if a model is configured with a mode that is not appropriate for its architecture.

def attention_mode(model_dir: str) -> str:
    """The mask the pack itself declares, from `decision_config.json` beside the model.

    A d3 readout pack is trained noncausal on its full-attention layers and says so; every other model
    on this box has no `decision_config.json` and is causal, which is also the field's default in
    `npu/plan/plan.h`.  An unknown value is refused here rather than defaulted, because the two modes
    produce different numbers and a guessed mask is a silently different model.
    """
    path = os.path.join(model_dir, "decision_config.json")
    if not os.path.isfile(path):
        return "causal"
    try:
        with open(path, "rb") as f:
            cfg = json.load(f)
    except (OSError, ValueError) as exc:
        raise SystemExit(f"{path}: cannot read the attention mode ({exc})")
    mode = cfg.get("attention_mode", "causal")
    if mode not in ("causal", "noncausal_full_attention"):
        raise SystemExit(f"{path}: attention_mode {mode!r} is not causal or noncausal_full_attention")
    return mode

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

The pooled-hidden diagnostic landed — the mask is applied and the two-pass fill is provably neutral; the magnitude gap is real

Two follow-up runs, both under npu-hold -l npufeat, host-GEMM on the real d3-lite pack, amdxdna errors 0:
ticket 01793657852024066470 (168 s wait, 141 s hold) for the dump, ticket 01793658256851343732 (10 s, 102 s) for the
control below.

1. The engine's last_hidden() in both modes (temporary NPU_DUMP_HIDDEN build, not committed):

case engine |Δh|/|h| engine cos reference |Δh|/|h|
score_three_levels 0.0349 0.9994 0.2487
choice_instructions 0.0355 0.9994 0.1896
choice_three_json_desc 0.0333 0.9995 0.1340
noul_criteria 0.0352 0.9994 0.1330
score_json_levels 0.0337 0.9994 0.1072
noul_plain 0.0345 0.9994 0.1045
noul_instructions 0.0348 0.9994 0.0929
choice_unicode 0.0353 0.9994 0.0758
choice_two_one_null 0.0335 0.9994 0.0757

So the mask perturbs the pooled state by 3.4 % in the engine and by 7.6–25 % in the reference
(~/lb/d3parity/ref_hidden.py, the pack's own runtime, same prompt bytes). The engine's perturbation is also
case-independent — the delta vectors across all twelve prompts have pairwise cosine 0.97–0.998 with the same
dominant dimensions — while the reference's is case-dependent (0.076 → 0.249). That is a different propagation, not a
missing mask: 3.4 % is 2–7× smaller and it is not the fork the pack's own runtime takes.

2. Is the two-pass fill itself changing anything? The restructure could in principle perturb the state by itself, so
I checked it instead of assuming: with the plan still noncausal, a temporary NPU_NC_DEBUG_CAUSAL build makes the second
pass read causally (kv_len = pos+1), and the answers come back byte-identical to the ordinary causal path —
max |Δ| = 0.0 over 35 fields, identical JSON — while the true noncausal run differs from it by 0.0203. So:

  • the fill-then-attend restructure is exactly neutral;
  • the 0.0004–0.0166 delta reported in the body is only the mask.

What that leaves. The mode is correct as far as this pack can show: it is applied, it is neutral when it should be,
and it refuses to generate. It does not reproduce the reference's magnitude, and the reason is now located in the
forward's propagation of earlier positions into the pooled state (3.4 % fixed direction vs 7.6–25 % content-dependent),
which is the same place the existing 0.72 parity gap lives (#796, and #849's pack nibbles). I am not going to express
that as a pass: #847 stays open for the magnitude, with this comment as its measured state.

Not committed on purpose: both diagnostics were temporary builds (NPU_DUMP_HIDDEN, NPU_NC_DEBUG_CAUSAL) plus
~/lb/d3parity/{hidden_run.sh,ref_hidden.py,ncdbg_run.sh}. A ctest cannot cover the "noncausal ≠ causal on the same
weights" row because it needs a real noncausal pack, which CI does not have; the unit-level coverage in this PR is the
plan field, the generator, the refusals, and the causal path staying byte-identical.

Ticket ledger this PR: 01793655369698324085 (the row matrix, 12 s wait, ~8 min), 01793657852024066470 (dump),
01793658256851343732 (control); one npu-hold at a time, all tokens released, owner serve on :18097 never touched.

@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 at 1b5291885.

Rebuilt the NPU lane at this head (-DONEBIT_NPU=ON -DONEBIT_NPU_HOST=ON -DONEBIT_NPU_RUNTIME=own -DONEBIT_NPU_RT_DIR=…, GCC, thermal-run -j4) and ran the two halves myself, device-free (NPU_INFER_HOST_GEMM=1 NPU_NO_DEVICE_LOCK=1, no lock taken, :18097 untouched).

Tests: 6/6. ctest -R "npu_plan|npu_plan_generate|npu_sampling|decision_head|systemone_contract|systemone_route" -> all pass, and the 9 new assertions are exactly where the body says (5 in npu_plan: default causal, noncausal read, explicit causal, unknown mode refused, non-string mode refused; 4 in npu_plan_generate: no decision_config.json -> causal, the pack's attention_mode -> noncausal, --check passes, unknown attention_mode refused). tools/copyright.py --check rc 0.

The generator half, re-derived on a real pack. tools/npu_plan.py on a copy of ~/models/npu/d3-lite-conv (whose decision_config.json says noncausal_full_attention) wrote "attention": {"mode": "noncausal_full_attention"} with generated_by 1.1; the same tool on d3-synth-0.6b (attention_mode: causal) wrote causal. Both plans loaded.

The forward half, run, not read. 1bit forward-serve -m <copy>/model.q4nx on the noncausal copy prints
[plan] attention.mode noncausal_full_attention: full-attention layers read the whole prompt (a prompt-encoding model; it cannot generate)
and then refuses generation on both routes, by name:

POST /v1/chat/completions -> {"error":{"message":"forward step failed: attention.mode noncausal_full_attention is a
  prompt-encoding mode and step() generates: … (use step_batch() with the whole prompt at position 0)"}}
POST /v1/completions      -> same refusal
POST /v1/systemone        -> answers: {"answers":{"q1":{"choice":"b","confidence":0.0957,
  "probabilities":{"a":0.3199,"b":0.6800}}, …}, "usage":{"input_tokens":102,"output_tokens":0}}

input_tokens: 102 is the first row of the body's own 102/123/94/… list, so the prompt path is the one it was measured on.

The regression that matters for shipping, checked: the causal pack (d3-synth-0.6b, plan regenerated -> causal) prints no attention.mode line and generates normally on /v1/chat/completions (6 tokens, prompt_tokens: 14, total_tokens: 20). So a causal model is not on this code path at all.

Read, not run: the two forward refusals (step_batch with start_pos > 0, step()), the fill-then-attend ordering (M fills with append=true, then M reads with kv_len = start_pos + M), GDN taking its own branch before the attention block (l_full is lt != Q4NX_LAYER_SLIDING, so the GDN Q4NX_LAYER_LINEAR layers never reach it), sliding layers staying causal, and the cache reset at start_pos == 0 that makes a repeated one-pass prompt read position 0 again rather than the previous prompt's rows.

Nits, none a gate:

  1. The fill pass computes a context per row and throws it away. In the noncausal_attn_ && l_full arm the first loop calls attention(…, ctx_scratch, append=true, kvlen=0), which runs the whole softmax plus the V accumulation for that row and is then discarded. That is the whole attention cost paid twice on this route (at prompt length L, the fills add ~L²/2 of the same work the reads do). A fill_only flag that skips the score/softmax/V loop after the append would remove it; today the route is correct but ~2x in attention.
  2. The two new forward refusals have no test. All 9 new assertions are plan-level; nothing in ctest calls step_batch(…, start_pos > 0) on a noncausal plan or step() on one. Both are one-line guards and the step() one I exercised above by hand, but a future edit could delete either without a red test.
  3. docs/npu.md says the mode "reads the same numbers only in one shape" and then lists the two conditions — the sentence reads as if the two modes agree in that shape, which is not what the body measured (0.0166 at worst vs the reference's 0.2869). Worth one clause there, since the body is where the honesty is.

Not verified by me, and the body does not claim otherwise: the magnitude against the reference's 0.2869 (the body states it does not reproduce it and keeps #847 open), and the step_batch start_pos > 0 refusal at runtime.

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 77d01af

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit aee8279

@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

At aee8279d9 (branch updated onto current main), superseding my line at 1b5291885.

The update is a pure merge — the branch's only author commit is still 1b5291885, the two later commits are
Merge branch 'main' — so its own patch is untouched. Blob identity is not the right instrument here (main's own
work has since changed q4nx_forward.cpp, plan.h and docs/npu.md), so I re-ran the changed code at this head instead:

$ g++ -std=c++17 -Inpu -isystem <nlohmann> -o npu_plan_test tests/npu_plan_test.cpp && ./npu_plan_test
npu_plan: ok
$ python3 tests/npu_plan_generate_test.py tools/npu_plan.py
npu_plan_generate: ok

Both compiled/fetched from this head, so plan.h's new attention.mode field and the tool that writes it are exercised
together. From the head I reviewed, the rest of the evidence: npu_plan.py writes noncausal_full_attention on a copy of
d3-lite-conv and causal on d3-synth-0.6b, and the forward run shows the noncausal pack printing the [plan] attention.mode line, refusing /v1/chat/completions and /v1/completions by name, and answering /v1/systemone with
input_tokens: 102 while the causal pack generates.

CI at aee8279d9: build success (checked at 01:58Z); CodeQL + Analyze x4 green.

@bong-water-water-bong
bong-water-water-bong merged commit efada52 into main Nov 3, 2026
8 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the npu/noncausal-attn branch November 3, 2026 01:59
bong-water-water-bong added a commit that referenced this pull request Nov 6, 2026
…can verify it causally (#847) (#1282)

step_batch_all() is the batched pass that returns every row's logits for a speculative decoder to check
drafted tokens against. step() refuses a noncausal pack and step_batch() refuses a batch that starts above
position 0, but step_batch_all() forwarded into step_batch() at start_pos 0, where a noncausal pass has every
row attending to the rows after it -- so its per-row logits are not prefix-conditioned and no draft may be
checked against them. Refused by name, same wording family as the other two; header and docs/npu.md carry the
contract. docs/npu.md also still listed the mode itself as not implemented (stale since #861).

Unreachable while a d3 pack ships no draft head; measured inert on the path it cannot reach: both mask arms,
host-GEMM, 20/20 answers byte-identical to the pre-change arms, arm-vs-arm numbers unchanged.

Co-authored-by: pi-npufeat <npufeat@strixhalo>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Review effort 4/5 tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant