Skip to content

npu: refuse a layer_types kind the forward cannot run, instead of serving it as full attention - #1124

Merged
bong-water-water-bong merged 5 commits into
mainfrom
npu/refuse-unknown-layer-kind
Nov 5, 2026
Merged

bong-water-water-bong merged 5 commits into
mainfrom
npu/refuse-unknown-layer-kind

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

npu: refuse a layer_types kind the forward cannot run, instead of serving it as full attention

The defect

q4nx_semantics.c maps every layer_types entry it does not recognise to Q4NX_LAYER_OTHER, and the forward's
attention path treats anything that is not SLIDING (or LINEAR, the GDN recurrence) as full attention. So a
container declaring, say, a conv attention is served as a plain decoder — fluent, wrong at every position, and silent.

Same shape as #1087 (a declared rope scaling is now refused by name rather than served as plain RoPE), and the same
rule applies: a refusal that names what it cannot run beats a fluent wrong answer.

Found while checking whether a ZAYA1-8B NPU row was "one conversion away" — its attention is CCA, the NPU ELF sets here
carry only zaya's MoE MLP roles, and the forward has no CCA path, so a container for it would have been served rather
than refused. That finding is on the decision record separately; this PR is the guard.

The change (139 lines, of which 103 are the test)

  1. npu/forward/src/q4nx_semantics.c + header: keep the first unrecognised spelling in
    Q4nxSemantics::unknown_layer_type so a refusal can quote it; correct the header's stale claim that LINEAR is
    "detected but not implemented" (it runs the GDN recurrence, lin_kd_/conv_state_).
  2. npu/forward/src/q4nx_forward.cpp: refuse at init, naming the kind — placed right after
    q4nx_semantics_from_config, because sem_ does not exist earlier in init_impl. The first version of this guard
    sat before that point and could never fire; the device probe below is what caught it
    , not the compile.
  3. tests/q4nx_layer_kinds_test.c (new, plain C, wired as ctest q4nx_layer_kinds): 12 assertions.

Verified

Unit, no model and no device — q4nx_layer_kinds 12/12:

ok   four layer_types entries parsed
ok   full_attention -> Q4NX_LAYER_FULL
ok   linear_attention -> Q4NX_LAYER_LINEAR (the GDN path)
ok   sliding_attention -> Q4NX_LAYER_SLIDING
ok   conv_attention -> Q4NX_LAYER_OTHER (nothing implements it)
ok   the refusal can quote the unknown kind by name
ok   hybrid count covers linear + sliding + other, as before
ok   known kinds only -> no refusal name (existing containers unaffected)
ok   no layer_types -> no refusal name
ok   the first unknown kind is the one quoted

Nothing that runs today is refused: every directory under ~/models/npu (18 of them, including the 27B folded
containers and the MoE 30B) declares only full_attention / linear_attention.

Known-answer device probe (~/p4-gate/layerkind-probe.sh, one npu-hold ticket, 2 s of device). Both arms are
hardlink copies, so the probe costs no disk:

=== doctored: Qwen3-0.6B with layer_types[27] = "conv_attention"
  [semantics] layer mix: full=27 sliding=0 linear=0 other=1  <- layer_types
1bit forward-serve: forward init failed: config.json layer_types names "conv_attention", a layer kind this forward
does not implement (it runs full_attention, sliding-window and linear/GDN layers), so serving it would run those
layers as full attention and be wrong at every position; file the kind you need instead of converting it

=== pristine: Qwen3-0.6B
1bit forward-serve: Qwen3-0.6B ready on http://127.0.0.1:8211 (full ELF)

Builds: both C TUs clean with -Wall -Wextra; q4nx_forward.cpp clean with this build's own flags
(-fsyntax-only, every include resolved from this worktree). The full ctest run (89/89, 0 failed) was made in the P4
worktree, which carries this change plus #808's split — the PR branch was not configured into its own build dir, and
I am not going to claim a build I did not run on it.

Scope, stated

  • A refusal, not an implementation: no new attention kind is executable.
  • Names reached only through layer_types are covered; a config with no layer_types still gets the full-attention
    default, which is correct for qwen3/qwen2/qwen3moe and is what every container here relies on.

…ving it as full attention

Found while checking whether a ZAYA1-8B NPU row was "one conversion away" (the owner's decision block, state file 18:3x):
`q4nx_semantics.c` maps every `layer_types` entry it does not recognise to `Q4NX_LAYER_OTHER`, and the forward's
attention path treats anything that is not SLIDING (or LINEAR/GDN) as full attention. So a container declaring, say, a
conv attention would be served as a plain decoder - fluent, wrong at every position, and nothing in the log to say so.
That is the same defect shape engine#1087 fixed for rope scaling: refuse by name rather than stay quiet.

Two halves, both small:

1. `q4nx_semantics.c`: keep the FIRST unrecognised spelling in `Q4nxSemantics::unknown_layer_type` (so a refusal can
   quote it), and correct the header's stale claim that LINEAR is "detected but not implemented" - it runs the GDN
   recurrence (lin_kd_/conv_state_).
2. `q4nx_forward.cpp`: refuse at init, beside the other precise refusals, naming the kind. Placed where it must be:
   right after `q4nx_semantics_from_config`, because `sem_` does not exist before that - the first version of this
   guard sat earlier in `init_impl` and could never fire (the device probe below is what caught that).

Verified, no model and no device for the unit half:

* `tests/q4nx_layer_kinds_test.c` (new, plain C, wired as ctest `q4nx_layer_kinds`): 12 assertions - the three spellings
  the containers here use map to FULL / LINEAR / SLIDING, an unknown spelling maps to OTHER and is quoted by name, the
  hybrid count is unchanged, and **known-kinds-only and no-layer_types both leave the refusal name empty**, which is every
  container on this box (checked: all 18 directories under ~/models/npu declare only full_attention / linear_attention).
  12/12 pass, and the binary passes in this worktree.
* Known-answer device probe (~/p4-gate/layerkind-probe.sh, one npu-hold ticket, 2 s of device): a hardlinked copy of
  Qwen3-0.6B with `layer_types` ending in `"conv_attention"` is refused -

      forward init failed: config.json layer_types names "conv_attention", a layer kind this forward does not
      implement (it runs full_attention, sliding-window and linear/GDN layers), so serving it would run those layers
      as full attention and be wrong at every position; file the kind you need instead of converting it

  and the untouched Qwen3-0.6B still reaches `Qwen3-0.6B ready on http://127.0.0.1:8211 (full ELF)`, so nothing that
  runs today is refused.

Builds: both C TUs compile clean with -Wall -Wextra; `q4nx_forward.cpp` compiles clean with this build's own flags
(`-fsyntax-only`, every include from this worktree). The full `ctest` run (89/89) was made in the P4 worktree, which
carries this change plus engine#808's split - the PR branch itself was not configured into its own build dir.

@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 9a4851ed — the refusal is the right shape, their 12 assertions pass (passed (0 failures), compiled standalone), and I found one place where the guard can still fail open. That one costs a line to close and refuses nothing that runs today.

What it fixes, confirmed by my own probe — I compiled the semantics TU and asked it about seven kinds:

full_attention              kind=0 (FULL)     unknown=""
sliding_attention           kind=1 (SLIDING)  unknown=""
linear_attention            kind=2 (LINEAR)   unknown=""
chunked_linear_attention    kind=2 (LINEAR)   unknown=""      <- accepted
mamba2_linear               kind=2 (LINEAR)   unknown=""      <- accepted
conv_attention              kind=3 (OTHER)    unknown="conv_attention"   <- refused by name
cca                         kind=3 (OTHER)    unknown="cca"              <- refused by name

So conv_attention and cca are caught, which is the body's case, and it is also the case the fleet actually has: ZAYA1-8B's config declares layer_types: ["hybrid"], which maps to OTHER and is now refused with its own spelling — that container can no longer be served as a plain decoder.

The remaining hole is the substring match. The parser is strcmp(nm,"full_attention"), then strstr(nm,"sliding"), then strstr(nm,"linear") — so any kind containing "linear" is accepted as the GDN recurrence and any kind containing "sliding" as the sliding block. mamba2_linear and chunked_linear_attention prove it above. That matters because "linear_attention" is ambiguous in the wild: it is GDN's spelling in Qwen3-Next models and it is also what Mamba2 hybrids declare, and the forward has one linear path. A Mamba2 container with that spelling would be served fluently and wrongly — the exact defect this PR exists to prevent, one step narrower.

The fix is free, which is what makes it worth asking for: every container on this box declares exactly full_attention and linear_attention (I checked ~40 configs: d3-lite, bonsai2, ZAYA1 — nothing else), and the PR's own comment says the same. So an exact-name whitelist (full_attention, sliding_attention, linear_attention) refuses nothing that runs today and closes the hole; a kind spelled mamba2_linear would then be refused by name, which is what the guard is for. If the substring matching was deliberate for some upstream spelling, that is worth a comment saying which spelling forced it.

Everything else is right: unknown_layer_type[40] kept as the spelling found so the message names it, set only on the first unknown entry, the refusal sits beside the other precise refusals in q4nx_forward.cpp, and the test links the semantics TU directly so it needs no model and no device. Four of its assertions are exactly the cases I would have asked for (known-only, no layer_types → no refusal name, no layer_types → zero kinds, first unknown quoted).

Comment thread tests/q4nx_layer_kinds_test.c Fixed

@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 506900b4 — the move is main's churn, not this PR: all four of its code files are byte-identical to the head I reviewed (q4nx_semantics.{c,h}, q4nx_forward.cpp, tests/q4nx_layer_kinds_test.c), and CMakeLists.txt differs only by other merged targets while this PR's own q4nx_layer_kinds_test block is intact (5 references).

My one nit is still open, and I re-checked it rather than assuming:

if (strcmp(nm, "full_attention") == 0) kind = Q4NX_LAYER_FULL;
else if (strstr(nm, "sliding"))         kind = Q4NX_LAYER_SLIDING;
else if (strstr(nm, "linear"))          kind = Q4NX_LAYER_LINEAR;

unchanged at this head. So a kind that merely contains "linear" is still routed to the GDN recurrence — my probe found mamba2_linear and chunked_linear_attention accepted as LINEAR — while "linear_attention" is ambiguous in the wild (Qwen3-Next's GDN spelling, and also what Mamba2 hybrids declare). An exact-name whitelist (full_attention, sliding_attention, linear_attention) refuses nothing on this box, since every container here declares exactly those two or three.

Not a blocker and the verdict stays READY: the guard is a real improvement on serving an unknown kind as full attention. It is one line, and the next model that declares a linear-attention block which is not GDN is the reason to take it.

mergeStateStatus is BLOCKED only on checks.

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

Follow-up on the blocked state, because "BLOCKED" on this PR is not the usual pr_agent noise:

check-runs at 506900b4:  CodeQL  completed/failure     (every other engine PR at its head: CodeQL success)
annotation:              tests/q4nx_layer_kinds_test.c:50 [failure]
                         "A file may be created here with mode 0666, which would make it world-writable."
code-scanning:           rule cpp/world-writable-file-creation, severity warning, security severity HIGH,
                         new relative to this PR's base (main carries 27 open alerts; this one is the PR's own)

Line 50 is fopen(out, "w") in write_config(), writing config.json inside the mkdtemp() directory. Practically the directory is 0700 and owned by the runner, so the world-writable half cannot be reached — but the gate is the gate: my READY was on the code (the guard refuses an unknown layer_types kind by name, and I ran their 12 assertions), and the merge cannot happen while this check is red.

Cheapest close, one line, in the fixture only: open(out, O_CREAT|O_EXCL|O_WRONLY, 0600) and fdopen, or umask(0077) before the first fopen and restore it after. Either keeps the test's behaviour identical — it only ever writes its own mkdtemp path.

Both nits from my review still stand at this head and neither is a blocker: the strstr("sliding")/strstr("linear") predicate still accepts mamba2_linear and chunked_linear_attention as the GDN recurrence, and an exact-name whitelist would refuse nothing that runs here (every container on this box declares only full_attention and linear_attention).

bong-water-water-bong and others added 2 commits November 5, 2026 14:02
…t does

CodeQL cpp/world-writable-file-creation (high) flagged fopen(...,"w") in
tests/q4nx_layer_kinds_test.c:50: the created config.json inherits the umask,
which on a permissive umask leaves it writable by every local user. mkdtemp
already gives the directory 0700, but the file's own mode is what the rule reads.

Same cure as tests/npu_forward_loader_test.c:48 (open(..., 0600) + fdopen), and
the _POSIX_C_SOURCE line that file uses so the TU stays clean under -std=c11.
Verified: strace shows openat(..., O_WRONLY|O_CREAT|O_TRUNC, 0600); 12/12
assertions still pass; strict -std=c11 -Wall -Wextra build clean.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

CodeQL cpp/world-writable-file-creation (high) fixed at 633553ab — it was a real finding in my new test

gh pr checks read BLOCKED with CodeQL fail / 1 new alert including 1 high severity security vulnerability. Read
rather than assumed, because a cancelled pr_agent looks like this too:

74 [high] cpp/world-writable-file-creation: File created without restricting permissions
  tests/q4nx_layer_kinds_test.c:50
  A file may be created here with mode 0666, which would make it world-writable.

Fair. mkdtemp gives the directory 0700, which is why I did not think about the file — but fopen(out, "w") inherits
the umask, so the fixture's own mode was whatever the box's umask said. The rule reads the file's mode, and on a
permissive umask (umask 000, or a build box that sets it) the file really is world-writable, even inside a 0700 dir
that anybody running the same umask could chmod.

Cure = the house pattern, not a suppression. tests/npu_forward_loader_test.c:48 already creates its crafted
fixtures this way:

int fd = open(out, O_WRONLY | O_CREAT | O_TRUNC, 0600);
FILE* f = fd >= 0 ? fdopen(fd, "w") : NULL;

plus the #define _POSIX_C_SOURCE 200809L /* mkdtemp */ that file carries, so this TU is also clean under
-std=c11 (gcc's gnu17 default hides nothing, but the explicit standard does without it).

Verified, three ways, no device and no model:

check result
the mode is what I now claim strace -f -e trace=openat ./q4nx_layer_kinds_test → openat(AT_FDCWD, "/tmp/q4nx-layer-kinds-…/config.json", O_WRONLY|O_CREAT|O_TRUNC, **0600**)
the test still asserts what it asserted 12/12 ok, 0 failures, same twelve lines as the body's transcript
strict build gcc -std=c11 -Wall -Wextra -O1 clean (fdopen/mkdtemp declared, no warnings)

tools/copyright.py --check → rc 0. Diff is 8 lines in one file (+8 −2), and it changes nothing about the guard or
the refusal semantics — the PR's scope line still holds: a refusal, not an implementation.

CodeQL is re-running on 633553ab. If a second alert lands I will fix that one too rather than argue with it: the
first was correct.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

#1124 ready for review at 633553a

CodeQL on the new head: pass, 0 open alerts on the PR; build pass (5m56s), Analyze (c-cpp) pass, codeql
pass. mergeStateStatus is UNSTABLE only because the required pr_agent check is cancelled — job
127469300225 ran 6 s and every step is conclusion: cancelled, the same infra event as 2026-11-04 13:4x and
2026-11-05 13:39Z, and the same shape as #808's. Nothing for me to fix there; rerunnable with gh run rerun.

Nothing merged by me — the owner merges.

@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

Re-verdicted at 633553ab. The CodeQL red is closed properly, not suppressed. tests/q4nx_layer_kinds_test.c:52-56 now creates the fixture the way the sibling loader test does:

int fd = open(out, O_WRONLY | O_CREAT | O_TRUNC, 0600);
FILE* f = fd >= 0 ? fdopen(fd, "w") : NULL;

and the rollup at this head is CodeQL SUCCESS, Analyze (c-cpp) SUCCESS, build SUCCESS, pr_agent CANCELLED (coder-llm still off, expected here and said once in my table).

The guard itself, run at this head: ninja q4nx_layer_kinds_test && ./build/q4nx_layer_kinds_test -> passed (0 failures), 10 checks, covering the refusal name (conv_attention), the first-unknown-spelling rule, and the two "nothing to refuse" cases (linear_attention/sliding_attention only, and no layer_types at all). The merge into main in the branch is clean and the change is the same five files.

One item I demonstrated and am not blocking on, because nothing in circulation hits it: the whitelist is a substring test (q4nx_semantics.c:349-350, strstr(nm, "sliding") / strstr(nm, "linear")), so the guarantee "refuse a kind the forward cannot run" is as wide as the substring. A probe linking the same q4nx_semantics.c:

mamba2_linear              -> layer[1]=LINEAR(GDN) unknown=''
chunked_linear_attention   -> layer[1]=LINEAR(GDN) unknown=''
nonlinear_attention        -> layer[1]=LINEAR(GDN) unknown=''
conv_attention             -> layer[1]=OTHER       unknown='conv_attention'
linear_attention           -> layer[1]=LINEAR(GDN) unknown=''

Three spellings that mean something else are accepted into the GDN path with no refusal, which is the same shape (linear_attention is the HF spelling the engine does implement, so the family test is right for every container on this box today). Exact match against the known set is a one-line change plus one case in this test; I am filing it as a follow-up rather than holding a guard that is a strict improvement over main, where all of these were served as full attention in silence.

@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

Re-verdicted at 50d25cf7. The only commit since 633553ab is Merge branch 'main' and the only content it carries is #1128's Laya gitlink and #1127's amdxdna README (git diff --stat 633553ab 50d25cf7 -> 2 files, +7/-3), so nothing in the guard or its test moved. CodeQL and every Analyze job are SUCCESS at this head; mergeStateStatus reads BLOCKED only because build has not concluded yet (build= empty in the rollup), not because of a finding.

The verdict from 633553ab stands unchanged: the CodeQL high is closed by construction (open(out, O_WRONLY|O_CREAT|O_TRUNC, 0600) + fdopen), q4nx_layer_kinds_test is 10/10, and the remaining item is the strstr("linear") whitelist I filed as #1156 rather than holding this PR for it.

@bong-water-water-bong
bong-water-water-bong merged commit e670036 into main Nov 5, 2026
9 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the npu/refuse-unknown-layer-kind branch November 5, 2026 19:29
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1087 - Partially compliant

Compliant requirements:

  • The PR introduces a mechanism to track and refuse unknown RoPE scaling types by name, aligning with the described behavior for layer_types.
  • The q4nx_semantics_from_config function now captures the first unrecognized layer_types entry and stores it in unknown_layer_type.
  • The q4nx_forward.cpp now checks for unknown_layer_type and refuses the container with a descriptive error message.

Non-compliant requirements:

  • The PR does not address the specific issue in tools/gguf_to_q4nx.py where rope.scaling.type is dropped during conversion.
  • The PR does not implement a refusal mechanism for RoPE scaling types in the conversion tool.

Requires further human verification:

  • The behavior of tools/gguf_to_q4nx.py needs to be verified separately to ensure it no longer silently drops rope.scaling.type.

808 - Partially compliant

Compliant requirements:

  • The PR correctly implements the split of npu/forward/src/q4nx_forward.cpp into NpuTarget interface and XdnaTarget implementation.
  • The NpuTarget interface is defined in npu/target/target.h.
  • The XdnaTarget implementation is in npu/target/xdna/.
  • The q4nx_forward.cpp file is reduced in size and complexity.
  • The Q4nxNpuForward becomes an adapter.

Non-compliant requirements:

  • The PR does not include the full implementation of the Plan fields and the filename-probe design derivation as mentioned in the ticket.
  • The PR does not include the adopt_geometry/make_ctx seam removal.

Requires further human verification:

  • The Plan fields and filename-probe design derivation need to be verified as part of the full implementation.
  • The adopt_geometry/make_ctx seam removal needs to be verified.
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Silent Failure for Unknown Layer Types

The code change introduces a check for unknown layer types and refuses containers that declare layer types not implemented by the forward. However, the check is placed after q4nx_semantics_from_config, which means it may not catch all cases where unknown layer types are present. The check should be placed earlier to ensure that unknown layer types are caught before any processing.

if (sem_.unknown_layer_type[0]) {
    err_ = std::string("config.json layer_types names \"") + sem_.unknown_layer_type +
           "\", a layer kind this forward does not implement (it runs full_attention, sliding-window and "
           "linear/GDN layers), so serving it would run those layers as full attention and be wrong at every "
           "position; file the kind you need instead of converting it";
    return false;
}
Memory Safety in Unknown Layer Type Handling

The code uses memcpy to copy the unknown layer type name into s->unknown_layer_type. While it checks for buffer overflow, it does not ensure that the source string is null-terminated, which could lead to undefined behavior if the string is not null-terminated.

    size_t k = strlen(nm);
    if (k >= sizeof(s->unknown_layer_type)) k = sizeof(s->unknown_layer_type) - 1;
    memcpy(s->unknown_layer_type, nm, k);
    s->unknown_layer_type[k] = 0;
}

bong-water-water-bong added a commit that referenced this pull request Nov 5, 2026
… is refused instead of run as GDN (#1156) (#1172)

The #1124 guard refuses an unknown layer kind by name, but it decided "known" with strstr, so its width
was the substring: chunked_linear_attention, mamba2_linear and nonlinear_attention all contain "linear"
and were mapped to Q4NX_LAYER_LINEAR, i.e. the forward would serve attention math it does not have through
the GDN recurrence - fluent, silently wrong at every position, which is the failure mode #1124 exists to
remove. sliding_window_attention hit the same branch through "sliding".

Exact match on the three spellings that name attention math this forward has (HF's own layer_types
values: full_attention, sliding_attention, linear_attention); everything else stays Q4NX_LAYER_OTHER and
is refused by name. tests/q4nx_layer_kinds_test.c pins both sides: the three known kinds still map as
before, and a spelling that merely contains a known kind is refused and quoted.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants