Skip to content

npu: the per-op forward runs GPT-OSS-20B-NPU2 on the host: D2560/MXFP4 chunks, sinks, o bias, YaRN, the top-k MoE (Refs #1786) - #2274

Merged
bong-water-water-bong merged 3 commits into
mainfrom
cl-flm/gpt-oss
Nov 12, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
cl-flm/gpt-oss

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

What

FastFlowLM's GPT-OSS-20B-NPU2 now loads on the per-op forward and answers correctly on the host. Before, it was refused at rope scaling "yarn", and past that point nothing in the forward read its container or its MoE. Refs #1786. Host-side only; the NPU is off.

On the known-answer prompt (the pack's own Harmony template, reasoning low, greedy) the full reply is:

<|channel|>analysis<|message|>Need one word: Paris.<|end|><|start|>assistant<|channel|>final<|message|>Paris<|return|>

The pieces, each with its source

  1. Two chunk kinds (q4nx_dequant.h). Each chunk is 32 rows × 128 columns, with its parameters at g*32 + r and 4-bit codes in two 16-row halves at h*1024 + c*8 + (r%16)/2:

    • D2560 (I8 [RB, CB, S, 2560]): attention q/k/v/o and the head, asymmetric bf16 scale and zero-point;
    • MX2560 (U8 [E, 69, CB, S, 2560]): the experts as MXFP4, E2M1 * 2^(e-127). Per expert, gate and up alternate by 128-row block, then 23 blocks of down.

    dequant_any now takes the tensor descriptor, so the 4-D kind is routed by its declared shape.

  2. Attention sinks. q4nx_attn::head_context takes an optional per-head sink logit that joins the softmax and carries no value. A null sink leaves every other model bit-identical (attn_math_test).

  3. o_proj bias.

  4. YaRN (Q4nxRopeYarn, q4nx_rope.h): transformers' _compute_yarn_parameters ramp, honouring truncate: false, with the attention factor on cos and sin.

  5. The MoE (gptoss_moe), as in our llama.cpp fork (openai-moe.cpp, build_moe_ffn SOFTMAX_WEIGHT, ggml-cpu swiglu_oai):

    • top-k of the biased router logits, then a softmax over those k;
    • per expert min(gate,7)·σ(1.702·gate)·(clamp(up,−7,7)+1), with the gate, up and down biases;
    • the experts are read from the MXFP4 chunks in place.

    A batched prefill of gpt_oss takes the per-token path.

How it was checked

  • Layouts, against ggml-org/gpt-oss-20b-GGUF (fetched by HTTP range, not downloaded):

    • D2560 against its Q8_0: q 0.99545, k 0.99546, o 0.99659, L13 v 0.99670, lm_head 0.99684 (4-bit against 8-bit);
    • every bf16 tensor (sinks, biases, router, norms) is exact; the embedding is 0.99994.
  • MX2560 against ggml's own MXFP4 rule. An earlier version of this branch used bias 128, in both my decoder and my GGUF reader. The two agreed bit for bit while both were wrong: every expert was half its size. It was found end to end, when a numpy forward answered <|start|>assistant with punctuation; that is fixed in the second commit. npu_dequant_bf16_test now pins one value through ggml's reading (kvalues_fp4[2] * 2^(127-128) = 1.0).

  • Real pack. A numpy GPT-OSS forward of the pack's weights puts <|channel|> first (38.3 against 18.7 for the next token). It gives the same top 5 on the GGUF's Q8_0 dense weights (logits corr 0.975). The C forward matches it: corr 1.000000, max |d| 6e-5 of 38.3.

  • New CI arm gptoss_forward. It writes a two-layer container in this format (4 experts top 2, sliding window 2, YaRN with a short original window so the rule is exercised within 6 positions, gate and up biases large enough that the clamp binds). It holds the forward to a numpy GPT-OSS forward of those bytes: corr 1.0000000, max |d| 1.9e-6. Each rule mutant fails it, while batched == sequential passes every time:

    removed corr argmax
    sinks 0.61 changes
    o bias 0.29 changes
    MXFP4 bias 127 → 128 0.84 changes
    SwiGLU clamp 0.918 changes
    YaRN attention factor 0.9941 same
    YaRN frequency rule 0.99989 same, max |d| 0.031 vs bar 0.002
    softmax over all experts instead of the top k 0.99967 same, max |d| 0.048

    The sinks, o bias and MXFP4 rows were measured on the arm's first data set; the others on the final one.

  • Unit tests: npu_rope_llama3_test gains YaRN checks (pairs 0, 31 and one inside the ramp, by hand); attn_math_test gains the sink check; npu_dequant_bf16_test gains d2560_chunks and the bias pin.

  • Full ctest: 270/270, device tests excluded. Every batch_check_state_ci.py arm and gptoss_forward pass at this head. tools/copyright.py --check rc 0.

Not in this PR: the MoE on the device, a kernel set, and a device row. The host forward runs at about 12 s/token on this box.

🤖 Generated with Claude Code

bong-water-water-bong and others added 3 commits November 12, 2026 05:02
…MX2560 MXFP4 experts) (Refs #1786)

Step 1 of the gpt_oss forward: the container's two chunk kinds, each a 32 x 128 block with its parameters
at g*32 + r and 4-bit codes in two 16-row halves at h*1024 + c*8 + (r%16)/2. D2560 (I8 [RB, CB, S, 2560])
is asymmetric bf16 scale/zero; MX2560 (U8, experts) is MXFP4 (E8M0 exponents, E2M1 codes). dequant_any now
takes the tensor's descriptor, so a 4-D D2560 tensor is routed by its declared shape.

Checked against ggml-org/gpt-oss-20b-GGUF on real chunks, through this C code: q_proj corr 0.99545 against
its Q8_0 (4-bit vs 8-bit), the MXFP4 expert blocks bit-exact (max |d| 0). npu_dequant_bf16_test: d2560_chunks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The MX2560 decoder of the previous commit halved every GPT-OSS expert. Its check was against my own GGUF
reader, which had the same slip, so the two agreed bit for bit. ggml writes the weight as
kvalues_fp4[q] * GGML_E8M0_TO_FP32_HALF(e), and kvalues_fp4 is the E2M1 table DOUBLED (0,1,2,3,4,6,8,12),
so the weight is E2M1 * 2^(e-127): OCP MX's bias. Found because a numpy GPT-OSS forward on these weights
answered '<|start|>assistant' with punctuation (<|channel|> at rank 2451); with the bias fixed, it puts
<|channel|> first at 38.3 against 18.7, on both the container's dense weights and the GGUF's Q8_0 ones.
npu_dequant_bf16_test pins the bias with one value (e = 127, E2M1 1.0 -> 1.0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…, the MXFP4 top-k MoE (Refs #1786)

GPT-OSS-20B-NPU2 now loads and its logits match a numpy GPT-OSS forward of the same weights (corr 1.000000,
max |d| 6e-5 of 38.3; '<|channel|>' first after '<|start|>assistant'). Rules transcribed from our llama.cpp
fork (openai-moe.cpp, build_moe_ffn SOFTMAX_WEIGHT, ggml-cpu swiglu_oai) and transformers' yarn:
- attention sinks: head_context takes an optional per-head sink (null keeps every model bit-identical);
- o_proj bias; YaRN (Q4nxRopeYarn: the ramp with truncate honoured, the attention factor on cos/sin);
- gptoss_moe: top-k of the biased router logits, softmax over those k, swiglu_oai with the expert biases,
  reading the MX2560 experts in place; a batched prefill takes the per-token path.
New CI arm gptoss_forward: a two-layer container written in the D2560/MX2560 format, against the reference
on its bytes (corr 1.0000000); each of seven rule mutants fails it while batched == sequential passes.
attn_math_test: the sink; npu_rope_llama3_test: yarn. ctest 270/270.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

ready for review at 878837d

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

1786 - Partially compliant

Compliant requirements:

  • it imports with zero gaps and its self-check passes against a named reference
  • it serves on --device npu
  • it answers a known-answer prompt with the model's own chat template, 3 identical requests returning identical text

Non-compliant requirements:

  • decode tok/s and time-to-first-token measured under npu-hold
  • the row names the kernel set and the engine commit that produced it

Requires further human verification:

  • decode tok/s and time-to-first-token measured under npu-hold
  • the row names the kernel set and the engine commit that produced it
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incorrect tensor shape handling for D2560 chunks

The code introduces support for D2560 chunks but the shape validation logic in declared_row_bytes may not correctly handle all cases where the tensor is shaped as [RB, CB, S, 2560]. Specifically, the condition d->shape[3] == Q4NX_CHUNK_D2560 assumes that the 4th dimension is always the chunk size, which might not be true for all tensor layouts. This could lead to incorrect dequantization of tensors that have the same chunk size but different tensor shapes.

if (d && d->ndim == 4 && d->shape[3] == Q4NX_CHUNK_D2560 && !strcmp(d->dtype, "I8")) return Q4NX_CHUNK_D2560;
Potential memory leak in MoE loading

In the load_gptoss function, memory is allocated for gpt_exps_ vector but there's no explicit check for allocation failure or a corresponding cleanup mechanism if the function fails partway through. If gpt_exps_ is not properly initialized or cleared on failure, it could lead to memory leaks or undefined behavior.

v->assign((size_t)NL, std::vector<float>());
Incorrect handling of YaRN rope scaling parameters

The YaRN rope scaling parameters are read from the config file, but the logic for determining whether the parameters are valid and usable is not robust. If the parameters are not correctly parsed or validated, it could lead to incorrect rope scaling behavior, which is critical for the model's performance.

y.factor = num("\"factor\"", 0.0);
y.original_max_position = num("\"original_max_position_embeddings\"", 0.0);
y.beta_fast = num("\"beta_fast\"", 32.0);
y.beta_slow = num("\"beta_slow\"", 1.0);
y.attention_factor = num("\"attention_factor\"", 0.0);
if (!(y.attention_factor > 0.0) && y.factor > 1.0) y.attention_factor = 0.1 * std::log(y.factor) + 1.0;
if (!(y.attention_factor > 0.0)) y.attention_factor = 1.0;
y.truncate = !(strstr(t.c_str(), "\"truncate\": false") || strstr(t.c_str(), "\"truncate\":false"));
y.on = y.factor > 0.0 && y.original_max_position > 0.0;
return y;

⚠️ Review coverage: The following files were not included in this review because of the token budget:

  • npu/forward/include/q4nx_dequant.h
  • docs/npu.md
  • CMakeLists.txt

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

I checked the two places a new architecture goes wrong, and both are right — and the sink one is right in the way a test could not have told me.

float mx = sink ? *sink : -1e30f;        // the sink joins the max
if (sink) sum += std::exp(*sink - mx);   // denominator only

A GPT-OSS sink is a per-head logit that takes probability mass and contributes no value. Both halves matter and both are handled: it enters mx, so exp(*sink - mx) <= 1 and the sink cannot make the softmax overflow when it is the largest logit; and it is added to sum only, never to the numerator, which is the part that is easy to get wrong by treating it as an extra value row. If the sink had been left out of the max, this would have passed every small-valued test and overflowed on a real pack.

The MXFP4 path is correct where it is easiest to be subtly wrong: the E2M1 codebook is the standard {0, .5, 1, 1.5, 2, 3, 4, 6} table including -0.0f at index 8, i.e. sign-magnitude nibbles rather than two's complement; and e8m0_scale returns 2^(e-127) exactly. d2560_code's (r/16)*1024 + c*8 + (r%16)/2 is self-consistent: 16 rows / 2 nibbles = 8 bytes per column, 128 columns = 1024 bytes per block, 2560/128 = 20 blocks wide.

The gate actually runs: gptoss_forward_ci.py fabricates the container — "CI has no such pack" — so SKIP_RETURN_CODE 77 fires only when numpy is missing, not because the pack is absent. And it is not a smoke test: logits after tokens 1..6 must reach corr >= 0.99999 and max|diff| <= 1e-3, with the header saying those were measured rather than chosen, and the reference transcribed rather than fitted.

Two limits I want on the record, neither a defect:

  1. The reference is transcribed by the same author as the C++ path, so it catches implementation slips — nibble order, chunk layout, the interleave, where the sink sits in the code — extremely well, and it cannot catch a shared misreading of the architecture. The sink semantics are exactly the kind of thing in that gap, which is why I verified them from the formula rather than from the two agreeing.
  2. Synthetic weights mean the container has a real pack's shape but not its magnitudes. e8m0_scale(255) would return inf; MXFP4 reserves 255 as NaN, so a refusal there is cheap insurance, and realistic exponents/large logits are the case synthetic weights are least likely to produce.

Two small notes: e8m0_scale's doubling/halving loop is correct but runs up to 127 multiplies per block — ldexpf(1.0f, e - 127) is the same value in one instruction, and on a 20B host forward that is not a rounding concern. And SKIP_RETURN_CODE 77 is honest here; naming numpy as the reason makes it clear the test is not silently declining to check the architecture.

@bong-water-water-bong
bong-water-water-bong merged commit 97719b2 into main Nov 12, 2026
10 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the cl-flm/gpt-oss branch November 12, 2026 11:02
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 878837d

848 lines is too much to verify line by line, so I checked the two places a port of this shape actually goes wrong: the borrowed formulas, and whether the correctness claim is text or token ids.

The YaRN implementation is transformers' own rule, not an approximation. q4nx_yarn_corr_dim(n, dim, base, orig) = dim * ln(orig / (n * 2π)) / (2 ln base) is _compute_correction verbatim, the blend between extrapolated and interpolated frequency is a linear ramp between the two correction dims, truncate defaults to 1 (HF's floor/ceil) with truncate: false honoured, and the attention factor falls back to 0.1 ln(factor) + 1 unless the block states one. Each of those is a place where a plausible-looking reimplementation would silently differ, and the body quotes the numeric agreement for each (attention factor 0.994, frequency rule 0.99989, swiglu clamp 0.92) rather than asserting the port is faithful.

swiglu_oai matches ggml's: min(gate, 7) * sigmoid(1.702 * gate) * (clamp(up, -7, 7) + 1) is llama.cpp's OAI activation, including the asymmetry — gate clamped, up clamped then shifted by one — which is exactly the detail a "SwiGLU with a clamp" rewrite gets wrong.

The correctness claim is text, not token ids — the full Harmony-formatted reply with Paris in the final channel. That is the opposite of the weakness I flagged on the gemma3 PR, and it makes the claim checkable by a human in one line rather than by decoding ids.

The sink line is worth keeping as written: mx = sink ? *sink : -1e30f — a sink joins the softmax as a logit and carries no value. Using a large finite negative rather than -inf means a row cannot produce NaN from an all-masked softmax, which is the failure this fleet has spent days on; the comment says the semantics, and the constant does the safe thing.

Three small things, none blocking:

  1. The experts are read in place and never expanded — worth a sentence in docs/npu.md too, not only in the code: it is the difference between a 20B model fitting and not, and it is the kind of property a later "simplification" would undo.
  2. -1e30 deserves one clause of justification at the call site (why not -INFINITY), since the choice is load-bearing for NaN-freedom and currently implicit.
  3. The four test files (gptoss_forward_ci.py, attn_math_test, npu_dequant_bf16_test, npu_rope_llama3_test) suggest the pieces are pinned separately as well as end-to-end; if the CI arm skips without a pack, make sure it skips with 77 and a printed reason, as the sibling tests do, so a green run never means "skipped".

Not verified by me: the forward on the pack. Host-side and device-free, but it needs ONEBIT_TEST_Q4NX pointing at a GPT-OSS container, which I do not have — so the numbers quoted are the author's, and the formulas above are what I checked.

@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 -- four reverse-engineered pieces, each pinned against an outside reference, and one assertion that is stated rather than demonstrated

The four pieces are individually checkable and each is anchored to something outside this tree, which is the only kind of anchor that catches a shared misconception:

  • D2560: code * scale + zero with both parameters at g*32 + r, the two 16-row halves at h*1024 + c*8 + (r%16)/2, the row-block order (tensor row rb*S*32 + s*32 + r comes from chunk [rb][cb][s]), and padding past k written 0. Asymmetric scales are where a symmetric reader silently halves the answer, so pinning + zero explicitly matters.
  • MX2560 / MXFP4: E2M1 * 2^(e-127) with the E8M0 bias cross-checked against ggml's own reading -- e = 127 with code 2 is weight 1.0, "which ggml writes as kvalues_fp4[2] = 2 times GGML_E8M0_TO_FP32_HALF(127) = 0.5". That is a reference from a different codebase, not a restatement of the implementation.
  • Attention sinks: the test computes its own reference -- an explicit softmax over [scores, sink] with max subtraction and den += exp(sink - mx) -- and checks two things, both necessary: a null sink leaves every other model's head bit-identical, and a real sink (0.7) both matches that explicit softmax and took some mass (drop, so an implementation that simply ignored the sink fails). Getting the do-no-harm arm and the anti-vacuity arm on the same function is more than most sink patches do.
  • YaRN: the per-pair ramp of transformers' _compute_yarn_parameters (truncate: false honoured, the attention factor on cos and sin), with yarn accepted only when its numbers are usable and refused without them -- so a container that declares yarn but ships nothing is rejected rather than silently treated as plain rope.

The one assertion I would make demonstrable:

check(bad == 0, "mx2560: E2M1 code (same order) * 2^(e - 127), e at g*32 + r; bytes 128..511 unread");

That checks the decode against the expected values, and says in the message that bytes 128..511 are unread -- but the fixture does not appear to put anything in those bytes, so a reader that walked them and multiplied by zero would pass identically. The property is worth having (a wrong stride that starts reading at 128 would produce noise), and proving it costs one line:

std::memset(t.data() + 128, 0x7f, 256);   // before the decode, after the scales are written

then the same check. With non-zero bytes in the "unused" region, "unread" becomes measured instead of claimed -- and if the reader is touching them, the arm fails immediately rather than at the first real pack.

Scope stated honestly: "No kernel set for its shapes was built or run" and the batched prefill takes the per-token path, so this is the host forward only -- and the end-to-end known answer (the Harmony reply in the body) is a _ci.py row that presumably skips without the 20B pack. Both are the right things to say out loud.

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.

1 participant