Skip to content

npu: the /v1/systemone decision route on the d3 contract (#653) - #775

Merged
bong-water-water-bong merged 2 commits into
mainfrom
1bit/npu-systemone-route
Nov 1, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
1bit/npu-systemone-route

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

What

The route half of #653: POST /v1/systemone (alias POST /v1/decisions) answers choice / noul /
score questions about a state, and GET /v1/systemone/models lists the decision model. When
decision_config.json and decision.q4nx sit next to model.q4nx, the decision routes come up beside the
chat ones; a pack without them is a chat model, which is the normal case.

A decision is one backbone prefill per question, the pooled last hidden state, the pack's readout
(npu/decision.h, #763) and a temperature softmax over that question's options. No sampling, no grammar,
no stream. To pool it, Q4nxNpuForward gains last_hidden() — the post-final-norm vector that both
step() and step_batch() already compute for the LM head, so nothing new is calculated.

It stands on npu/systemone.h and npu/decision.h, both on main now (#765 1d42bad, #763 dcf4751).

The envelope is copied, not guessed

npu/systemone.h reproduces the pack's d3_format.py; the HTTP envelope had to come from the pack's
server, so I fetched vllm-sr/d3-lite's d3_server.py / d3_runtime.py at the same revision
(2fc06364…) and copied what it does. Four things the issue text does not say and a guess would have got wrong:

  • questions is an object (id → question), and those ids are the keys of answers, in request order.
  • usage is {input_tokens, output_tokens: 0} where input_tokens is the sum of every answered question's
    prompt length
    , not the state's.
  • A malformed question is 422 {"detail": {"invalid_questions": {id: "why"}}} and nothing runs; a
    question that is valid but over the input limit is instead an entry inside answers
    ({"type", "error": "max_length_exceeded", "message"}, HTTP 200) and the other questions are still
    answered, with nothing truncated. So these routes answer 422, not the chat route's 400 — the
    interop contract with vLLM Semantic Router wins here, and docs/npu.md says why.
  • The prompt is the pack's chat template with enable_thinking=False, which opens the assistant turn with an
    empty think block. Those bytes are model input: reusing chatml() would be a different request. The
    wrapper is byte-compared against all nine committed fixtures from npu: the d3 question/answer contract, byte-equal to the pack's d3_format.py (#653) #765.

DECISION_API_KEY, when set, gates the decision routes exactly as upstream's server does (401 +
WWW-Authenticate: Bearer, constant-time compare, /health open and reporting "authentication": true).
/health only gains the d3 fields when a head is loaded, so a chat-only deployment keeps the body it had.

Measured

Device: strixhalo, Qwen3-0.6B with a SYNTHETIC 255×1024 readout head (the d3 container layout, random
weights) — the route is what is under test; the choice means nothing. NPU_INFER_HOST_GEMM=1 under
npu-hold -l npufeat, one run at a time, 0 amdxdna.*ERROR after each.

row result
ctest npu_sampling / systemone_contract / systemone_route / decision_head PASS (4/4); the new systemone_route adds 30 assertions
tools/copyright.py --check rc 0
choice, 2 options 200 {"choice":"fast","confidence":0.685,"probabilities":{"cheap":0.057,"fast":0.943}}, input_tokens 97
alias /v1/decisions, noul 200 {"noul":0.046}
score, 3 levels 200 {"score":0.0724,"confidence":0.759,"probabilities":{…},"legend":{…}}
3 questions in one request 200, all three answered in request order, usage.input_tokens 269
unknown field 422 {"detail":"temprature not understood; a request may carry state, questions, model"}
two malformed questions 422 {"detail":{"invalid_questions":{"bad1":"…needs at least one option","bad2":"…is not served by this build"}}}, nothing ran
images sent 422 "images: this build serves the text path only"
no bearer key with DECISION_API_KEY set 401
one question over the limit, one far under huge → max_length_exceeded (34086 > 32768, "nothing was truncated"), small → answered; usage.input_tokens 90
chat route on the same server unchanged, 200

Two things this caught that no ctest would have:

  1. curl's default content type is application/x-www-form-urlencoded, and httplib parses a form body with
    an 8 KB cap, answering 413 before any handler runs. My first limit row looked like a route bug and was
    a client bug: with Content-Type: application/json the same 170 KB body works. Documented, because a real d3
    caller (a 32k-token state is ~100 KB) will hit it if it leaves the header at curl's default.
  2. A shared state counts against every question's limit, so "one question over the limit, one under"
    cannot be built with a big state — the over-limit question has to differ from the others (I used a huge
    instructions), otherwise the test measures the state and not the split.

Not in this PR, and no number claimed for it

A real d3-lite backbone. I downloaded the real pack (1.7 GB backbone + readout + contract files) and could
not convert it, for three concrete reasons — this is the next piece, not something to fake a row for:

gap evidence
the converter assumes 2-D tensors tools/safetensors_to_q4nx.py pack dies on linear_attn.conv1d.weight [6144,1,4]: ValueError: too many values to unpack (expected 2, got 3); the pack has 235 non-2-D tensors incl. a 5-D visual.patch_embed.proj.weight
the pack's names are HF's, not the engine's pack: language_model.layers.N.linear_attn.{in_proj_qkv,in_proj_a,in_proj_b,conv1d,dt_bias,norm,out_proj}; engine: model.layers.N.linear_attn.{qkv_proj,ssm_alpha_proj,ssm_beta_proj,ssm_conv1d,ssm_dt.bias,ssm_norm,ssm_out_proj}
the GGUF shortcut is closed too ggml-org/vllm-d3-lite-GGUF is general.architecture = qwen35, and tools/gguf_to_q4nx.py accepts only qwen3/qwen2

Also not here: images/videos (vision tower + FFmpeg, refused by name), upstream's "state computed once per
request" optimisation (that is the prefix cache's job, #650), and the pack's noncausal_full_attention
attention mode — so no accuracy claim against upstream is made.

Files

app/npu_systemone.h (new, 152 lines, device-free), app/forward_serve.cpp (+190: routes, head loading,
/health), npu/forward/include/q4nx_forward.h + src/q4nx_forward.cpp (last_hidden()),
tests/systemone_route_test.cpp (new), CMakeLists.txt, docs/npu.md ("Decisions").

The route half of #653, on npu/systemone.h's contract (#765) and npu/decision.h's
readout (#763): `POST /v1/systemone` (alias `/v1/decisions`) answers `choice`/`noul`/
`score` questions about a `state`, and `GET /v1/systemone/models` lists the decision
model. When `decision_config.json` and `decision.q4nx` sit next to `model.q4nx` the
decision routes come up beside the chat ones; a pack without them is a chat model.

A decision is one backbone prefill per question, the pooled last hidden state, the
pack's readout and a temperature softmax over that question's options -- no sampling,
no grammar, no stream. To pool it, Q4nxNpuForward gains last_hidden(): the
post-final-norm vector both step() and step_batch() already compute for the LM head.

The envelope is copied from the d3 server vLLM Semantic Router already speaks
(`vllm-sr/d3-lite`'s d3_server.py at 2fc06364), not invented -- `questions` is an
object whose ids are the keys of `answers`, `usage` is {input_tokens, output_tokens: 0},
a malformed question gives 422 {"detail":{"invalid_questions":...}} and nothing runs,
and an over-limit question is a per-question `max_length_exceeded` entry with **nothing
truncated** while the other questions are still answered. That means 422 on these
routes rather than the chat route's 400; app/npu_systemone.h is device-free so the
envelope, the refusals and the prompt wrapper are tested with no model.

The prompt is the pack's chat template with enable_thinking=False, so the assistant
turn opens with an EMPTY think block: those bytes are input, and reusing chatml()
would change them.

Measured (strixhalo, Qwen3-0.6B with a SYNTHETIC 255x1024 readout -- the route is
what is under test, the choice means nothing; host GEMM under npu-hold, 0 amdxdna
errors): choice/noul/score answers, 3 questions in one request (order kept, usage
269 tokens), /v1/decisions alias, 422 unknown field / invalid_questions / images,
401 without the bearer key, and max_length_exceeded at 34086 > 32768 with the other
question answered (usage 90). ctest npu_sampling, systemone_contract, systemone_route
and decision_head pass; copyright rc 0.

Not in it, and no row claimed: a real d3-lite backbone. Its HF Qwen3_5Model pack
cannot be converted yet -- tools/safetensors_to_q4nx.py assumes 2-D tensors (the GDN
conv1d is [6144,1,4]), the pack's names are HF's (language_model.*, linear_attn.
conv1d/in_proj_*) not the engine's (model.*, ssm_conv1d/qkv_proj/...), and the GGUF on
the Hub is arch `qwen35`, which tools/gguf_to_q4nx.py does not accept. That is the
next piece, not something to fake a number for.
@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit 4a70862)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

653 - Partially compliant

Compliant requirements:

  • Implement the /v1/systemone decision endpoint
  • Support POST /v1/systemone and GET /v1/systemone/models endpoints
  • Handle decision models with decision_config.json and readout.safetensors
  • Support choice, noul, and score question kinds
  • Implement 32,768 tokens per question limit with max_length_exceeded error
  • Maintain interop contract with vLLM Semantic Router

Non-compliant requirements:

  • Support state computed once per request optimization via prefix cache (this is noted as "not implemented" in docs)

Requires further human verification:

  • Verification that the state computed once per request optimization works as expected with prefix cache
  • Accuracy verification against upstream BF16 model on Decision Index public suite

763 - Partially compliant

Compliant requirements:

  • Implement safetensors to Q4NX converter
  • Implement d3 readout head loader
  • Support decision_config.json and readout.safetensors loading
  • Implement DecisionHead class with logits() and probabilities_over() methods
  • Support exact checks for 32,768 tokens per question limit
  • Support 255 options for choice questions and 2-10 levels for score questions

Non-compliant requirements:

  • None

Requires further human verification:

  • Verification that the real d3 head round-trips bit-exactly
  • Verification that the converter's backbone path is proven on synthetic fixtures and real head is proven against real pack

765 - Partially compliant

Compliant requirements:

  • Implement d3 question/answer contract
  • Ensure byte-exact match with pack's d3_format.py
  • Support question kinds: choice, noul, score
  • Implement user_prompt() method for byte-exact prompt generation
  • Implement answer_of() method for proper answer shapes
  • Support candidate_codes() for option codes
  • Ensure state order is preserved in prompt generation

Non-compliant requirements:

  • None

Requires further human verification:

  • Verification that all nine fixtures produce byte-identical prompts to upstream
  • Verification that the option rules (1-255, score 2-10 distinct non-empty) are properly enforced
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Security Issue

The constant-time string comparison used for API key validation in decision_authorized() function may not be fully secure against timing attacks if the strings have different lengths. While the code attempts to prevent early exit by comparing lengths first, an attacker might still be able to infer information about the key through careful timing analysis if the key length varies. The comparison should be made with a fixed number of operations regardless of input length.

unsigned diff = unsigned(got.size() ^ want.size());
for (size_t i = 0; i < got.size() && i < want.size(); i++) diff |= unsigned(got[i] ^ want[i]);
return diff == 0;
Possible Performance Issue

The code uses std::filesystem::exists() to check for the existence of decision configuration files. This operation can be expensive in terms of system calls, especially if called frequently. Consider caching the result or using a more efficient method to check for file existence, particularly in a high-frequency request environment.

if (std::filesystem::exists(decision_cfg) && std::filesystem::exists(decision_readout)) {
Incorrect Error Handling

In handle_systemone() function, when a question prompt exceeds the token limit, the code sets an error in the answers object and continues processing other questions. However, the input_tokens calculation includes the tokens from the over-length question, which may not be accurate since that question was not actually processed. The token count should only include successfully processed questions.

if (ids.size() > limit) {
    answers[q.id] = npu::systemone_question_error(q.question.kind, "max_length_exceeded",
                                                  npu::systemone_length_message(ids.size(), limit));
    continue;
Potential Memory Issue

The systemone_chat() function creates a string by concatenating several string literals and variables. While this is generally safe, if the user parameter becomes very large, it could lead to memory issues or performance degradation due to string concatenation. Consider using a more memory-efficient approach for building large strings.

inline std::string systemone_chat(const std::string& user) {
    return std::string("<|im_start|>system\n") + d3::kSystemPrompt + "<|im_end|>\n" + "<|im_start|>user\n" +
           user + "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n";
}
Possible Memory Leak

The last_hidden_ member variable is assigned in both step_batch() and step() functions. If there's a case where one of these functions fails or is not called, the last_hidden_ might not be properly initialized, leading to undefined behavior when accessed. Ensure proper initialization and error handling.

    last_hidden_ = fnorm;  // for last_hidden(): the same vector the head reads, last position only
    const bool ok = run_lm_head(fnorm, logits);
    if (getenv("NPU_INFER_DUMP_LAYERS")) {
        int best[5] = {-1, -1, -1, -1, -1};
        for (int i = 0; i < (int)logits.size(); i++) {
            for (int r = 0; r < 5; r++) {
                if (best[r] < 0 || logits[(size_t)i] > logits[(size_t)best[r]]) {
                    for (int q = 4; q > r; q--) best[q] = best[q - 1];
                    best[r] = i;
                    break;
                }
            }
        }
        fprintf(stderr, "  [TB] M=%d start=%d top:", M, start_pos);
        for (int r = 0; r < 5; r++) fprintf(stderr, " %d=%.4f", best[r], (double)logits[(size_t)best[r]]);
        fprintf(stderr, "\n");
    }
    if (batch_check) {
        int ba = 0;
        for (size_t i = 1; i < logits.size(); i++)
            if (logits[i] > logits[(size_t)ba]) ba = (int)i;
        std::fprintf(stderr, "[batchcheck] M=%d start=%d seq_argmax=%d batch_argmax=%d %s\n",
                     M, start_pos, seq_argmax, ba, seq_argmax == ba ? "MATCH" : "MISMATCH");
    } else if (getenv("NPU_BATCH_DBG")) {
        std::fprintf(stderr, "[batch] M=%d start=%d batched (%d layers, two_widths=%d)\n",
                     M, start_pos, c_.NL, (int)two_widths);
    }
    return ok;
}

int Q4nxNpuForward::max_batch_rows() const {
    // A pb16i container only packs images for its M=16 decode family, so a batch is
    // whatever that family takes: a prompt is walked in 16-row chunks, which streams
    // the weights 8x more often than M=128 but at ~5x the rate -- measured, see the
    // lane's state file.  Every other layout keeps the M=128 chunk.
    if (pb16i_) {
        for (int i = 0; i < ndesigns_; i++)
            if (ctx16_[i]) return ctx16_[i]->MD;
    }
    for (int i = 0; i < ndesigns_; i++)
        if (ctx_[i]) return ctx_[i]->MD;
    return 1;  // host_gemm_ / not initialised: keep batches trivially small
}

// --------------------------------------------------------------------------
// host helpers (float32, matching the Python reference)
// --------------------------------------------------------------------------
float Q4nxNpuForward::rmsnorm(const float* x, const float* w, int n, float* out) const {
    LhScope _tlh(LH_RMS);
    double ss = 0.0;
    for (int i = 0; i < n; i++) ss += (double)x[i] * (double)x[i];
    const float inv = 1.0f / std::sqrt((float)(ss / (double)n) + sem_.eps);
    if (sem_.rmsnorm_offset) {
        // Gemma convention: y = x/rms * (1 + w)
        for (int i = 0; i < n; i++) out[i] = x[i] * inv * (1.0f + w[i]);
    } else {
        for (int i = 0; i < n; i++) out[i] = x[i] * inv * w[i];
    }
    return inv;
}

/* Scale-free RMSNorm: Gemma4's v_norm is built with_scale=False. */
float Q4nxNpuForward::rmsnorm_noweight(const float* x, int n, float* out) const {
    double ss = 0.0;
    for (int i = 0; i < n; i++) ss += (double)x[i] * (double)x[i];
    const float inv = 1.0f / std::sqrt((float)(ss / (double)n) + sem_.eps);
    for (int i = 0; i < n; i++) out[i] = x[i] * inv;
    return inv;
}

// ---------------------------------------------------------------------------
// MLA + MoE (deepseek2 / GLM-4.7-Flash)
// ---------------------------------------------------------------------------
// Dequantize one expert's slice out of the pooled [n_expert][tiles][5120] tensor.
// MEASURED (not inferred): the converter's unpack TRANSPOSES, so although the GGUF
// stores {K, N, n_expert} (llama.cpp's create_tensor_gate_up_exps), the Q4NX slice
// is [N][K] -- corr 0.996969 against the GGUF read as [N][K] vs 0.0157 as [K][N].
// So dequant straight into [N][K], which is what assemble_B wants.
bool Q4nxNpuForward::mla_expert(const uint8_t* pool, size_t per_expert, int e,
                                int N, int K, std::vector<float>& out) {
    if (!pool || per_expert == 0 || e < 0) return false;
    // Dequantize straight into `out`: the old path materialized a `kn` temporary
    // and then copied it -- an extra (K*N) allocation plus a full copy per expert,
    // ~960 experts/token.
    out.resize((size_t)N * (size_t)K);
    // Do NOT transpose.  The tile decode at (rows=K, cols=N) already reproduces the
    // GGUF's flat order, and that flat sequence IS the logical [N][K] = [out][in]
    // weight.  Verified elementwise against the GGUF per expert: reshape(N,K) gives
    // corr 0.999198 (gate) / 0.996949 (down), while transposing gives -0.001079 /
    // 0.000417 -- i.e. the transpose destroyed the expert entirely, making every
    // routed expert's contribution ~10-20x wrong and flipping the top-k selection.
    if (dequant_any(pool + (size_t)e * per_expert, per_expert, K, N, out.data()) != 0)
        return false;
    return true;
}

// MLA attention for one layer.  q_a -> norm -> q_b, kv_a -> norm -> k_b/v_b, with
// RoPE applied to the LAST rope_dim_ of each q head and to the single shared
// rope slice carried inside kv_a (LLM_ARCH_DEEPSEEK2's MLA).
bool Q4nxNpuForward::mla_attn(int l, const std::vector<float>& x, std::vector<float>& o,
                              int pos) {
    const int H = c_.H, NH = c_.NH;
    const int qh = qk_nope_ + rope_dim_;         // per-head q width (192+64)
    const int kv_real = kv_lora_ + rope_dim_;    // 576
    const int i_qa = idx_of(Q4NX_DESIGN_QA), i_qb = idx_of(Q4NX_DESIGN_QB);
    const int i_kva = idx_of(Q4NX_DESIGN_KVA), i_o = idx_of(Q4NX_DESIGN_O);
    if (i_qa < 0 || i_qb < 0 || i_kva < 0 || i_o < 0) { err_ = "MLA designs missing"; return false; }

    std::vector<float> qa, qan, q, kva;
    {   // q_a: [H] -> [q_lora]
        const Q4nxDesignGeom* g = &designs_[i_qa];
        Q4nxProjections p{}; p.q = w_qa_.data();
        if (!weight_cached(0) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble q_a"; return false; }
        npu_gemm(*ctx_[i_qa], x.data(), g->K, g->N, B_.data(), qa, 0);
    }
    qan.resize(q_lora_);
    rmsnorm(qa.data(), mla_qan_.data(), q_lora_, qan.data());
    {   // q_b: [q_lora] -> [NH*qh]
        const Q4nxDesignGeom* g = &designs_[i_qb];
        Q4nxProjections p{}; p.k = w_qb_.data();
        if (!weight_cached(1) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble q_b"; return false; }
        npu_gemm(*ctx_[i_qb], qan.data(), g->K, g->N, B_.data(), q, 1);
    }
    {   // kv_a: [H] -> [kv_real] (+ zero pad to the kernel's n-tile)
        const Q4nxDesignGeom* g = &designs_[i_kva];
        Q4nxProjections p{}; p.v = w_kva_.data();
        if (!weight_cached(6) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble kv_a"; return false; }
        npu_gemm(*ctx_[i_kva], x.data(), g->K, g->N, B_.data(), kva, 6);
    }
    if ((int)kva.size() < kv_real) { err_ = "kv_a short"; return false; }
    std::vector<float> kl(kv_lora_);
    rmsnorm(kva.data(), mla_kvan_.data(), kv_lora_, kl.data());

    // RoPE on the shared slice and on each q head's tail.
    std::vector<float> kr(rope_dim_);
    for (int i = 0; i < rope_dim_; i++) kr[i] = kva[(size_t)kv_lora_ + i];
    if (!mla_rope(q, NH, qh, qk_nope_, kr, pos)) { err_ = "mla rope"; return false; }

    // Cache the reconstructed k_nope / shared k_rope / v for this position.
    const int kh = qk_nope_, vh = v_head_;
    std::vector<float>& kn = mla_kn_[l];
    std::vector<float>& krc = mla_kr_[l];
    std::vector<float>& vc = mla_v_[l];
    const size_t old = kn.size() / ((size_t)NH * kh);
    kn.resize((old + 1) * (size_t)NH * kh);
    vc.resize((old + 1) * (size_t)NH * vh);
    krc.resize((old + 1) * (size_t)rope_dim_);
    // k_b[h] : [kh][kv_lora] (stored padded to a 32-row tile, so read kh real rows)
    for (int h = 0; h < NH; h++) {
        // k_b: Q4NX tile grid [kv_lora][nope padded to 256], indexed flat[n*kv_lora+k].
        // v_b: the Q4NX tiles v_b with cols=256 while its LOGICAL row is 512 wide, so
        // the per-head [512][256] tile grid is NOT the logical matrix.  Decoding the
        // whole tensor at (rows=10240, cols=256) reproduces the GGUF's flat order
        // exactly (corr 0.996860 vs the 0.996870 a faithful Q4_1 requant scores),
        // i.e. the logical index is (h*256+n)*512 + k = out-major.  Indexing flat
        // [k*vh+n] instead permuted the whole MLA value path; the earlier check that
        // "pinned" it compared a single SUM, which a permutation can still match.
        const float* wk = &w_kb_[(size_t)h * (size_t)kv_lora_ * (size_t)kb_rows_];
        const float* wv = &w_vb_[(size_t)h * (size_t)kv_lora_ * (size_t)vh];
        float* dk = &kn[old * (size_t)NH * kh + (size_t)h * kh];
        float* dv = &vc[old * (size_t)NH * vh + (size_t)h * vh];
        for (int n = 0; n < kh; n++) {
            float s = 0.0f;
            for (int k = 0; k < kv_lora_; k++) s += wk[(size_t)n * kv_lora_ + k] * kl[k];
            dk[n] = s;
        }
        for (int n = 0; n < vh; n++) {
            float s = 0.0f;
            for (int k = 0; k < kv_lora_; k++) s += wv[(size_t)n * kv_lora_ + k] * kl[k];
            dv[n] = s;
        }
    }
    for (int i = 0; i < rope_dim_; i++) krc[old * (size_t)rope_dim_ + i] = kr[i];

    // Scores and softmax over the cache, then the weighted sum of v.
    const int T = pos + 1;
    const float scale = 1.0f / std::sqrt((float)(qh));
    std::vector<float> ctx((size_t)NH * vh, 0.0f);
    std::vector<float> score(T);
    for (int h = 0; h < NH; h++) {
        const float* qn = &q[(size_t)h * qh];
        const float* qr = qn + qk_nope_;
        float mx = -1e30f;
        for (int t = 0; t < T; t++) {
            const float* kt = &kn[(size_t)t * NH * kh + (size_t)h * kh];
            const float* rt = &krc[(size_t)t * rope_dim_];
            float s = 0.0f;
            for (int i = 0; i < kh; i++) s += qn[i] * kt[i];
            for (int i = 0; i < rope_dim_; i++) s += qr[i] * rt[i];
            score[t] = s * scale;
            if (score[t] > mx) mx = score[t];
        }
        float sum = 0.0f;
        for (int t = 0; t < T; t++) { score[t] = std::exp(score[t] - mx); sum += score[t]; }
        const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
        float* out = &ctx[(size_t)h * vh];
        for (int t = 0; t < T; t++) {
            const float pm = score[t] * inv;
            const float* vt = &vc[(size_t)t * NH * vh + (size_t)h * vh];
            for (int i = 0; i < vh; i++) out[i] += pm * vt[i];
        }
    }
    {   // o_proj: [NH*v_head] -> [H]
        const Q4nxDesignGeom* g = &designs_[i_o];
        Q4nxProjections p{}; p.o = w_o_.data();
        if (!weight_cached(7) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble o"; return false; }
        npu_gemm(*ctx_[i_o], ctx.data(), g->K, g->N, B_.data(), o, 7);
    }
    return true;
}

// RoPE for MLA.  llama.cpp's llama_model_rope_type() returns LLAMA_ROPE_TYPE_NORM
// for LLM_ARCH_DEEPSEEK2 ("normal RoPE, operating on pairs of CONSECUTIVE head
// values"), so the rotation pairs (2i, 2i+1) -- NOT (i, i+half) as the paired/NeoX
// convention would.  Using the paired form here was a bug of exactly the class
// that broke MiniCPM4/MiniCPM5.
bool Q4nxNpuForward::mla_rope(std::vector<float>& q, int NH, int qh, int nope,
                              std::vector<float>& kr, int pos) {
    const int half = rope_dim_ / 2;
    std::vector<float> cs(half), sn(half);
    for (int i = 0; i < half; i++) {
        const double inv = 1.0 / std::pow((double)sem_.rope_theta, (double)i / (double)half);
        const double ang = (double)pos * inv;
        cs[i] = (float)std::cos(ang); sn[i] = (float)std::sin(ang);
    }
    auto rot = [&](float* v) {
        for (int i = 0; i < half; i++) {
            const float a = v[2 * i], b = v[2 * i + 1];
            v[2 * i] = a * cs[i] - b * sn[i];
            v[2 * i + 1] = a * sn[i] + b * cs[i];
        }
    };
    for (int h = 0; h < NH; h++) rot(&q[(size_t)h * qh + nope]);
    rot(kr.data());
    return true;
}

// MoE FFN: router (host, N=64 cannot tile) -> gating -> top-k -> per-expert G/U/D
// on the NPU -> weighted sum, plus the shared expert.
bool Q4nxNpuForward::moe_mlp(int l, const std::vector<float>& xn, std::vector<float>& d) {
    const int H = c_.H;
    const int i_g = idx_of(Q4NX_DESIGN_G), i_u = idx_of(Q4NX_DESIGN_U), i_d = idx_of(Q4NX_DESIGN_D);
    if (i_g < 0 || i_u < 0 || i_d < 0) { err_ = "MoE designs missing"; return false; }
    d.assign(H, 0.0f);

    // Router.  llama.cpp: probs = sigmoid(logits) UNBIASED; selection_probs =
    // probs + exp_probs_b (the bias is added AFTER the sigmoid and used ONLY for
    // the top-k selection -- "leave probs unbiased as it's later used to get
    // expert weights").  Adding the bias to the logit before the sigmoid, as I
    // had, corrupts both the selection and the weights.
    std::vector<float> probs(n_expert_), selprobs(n_expert_), logits(n_expert_);
    for (int e = 0; e < n_expert_; e++) {
        const float* row = &moe_router_[(size_t)e * H];
        float s = 0.0f;
        for (int i = 0; i < H; i++) s += row[i] * xn[i];
        logits[e] = s;
        // llama.cpp's deepseek2 expert_gating_func: 2 = sigmoid, 1 = softmax.
        probs[e] = expert_gating_sigmoid_ ? (1.0f / (1.0f + std::exp(-s))) : s;
    }
    if (!expert_gating_sigmoid_) {
        float mx = *std::max_element(probs.begin(), probs.end());
        float sum = 0.0f;
        for (int e = 0; e < n_expert_; e++) { probs[e] = std::exp(probs[e] - mx); sum += probs[e]; }
        for (int e = 0; e < n_expert_; e++) probs[e] /= sum;
    }
    for (int e = 0; e < n_expert_; e++)
        selprobs[e] = probs[e] + (moe_router_b_.empty() ? 0.0f : moe_router_b_[e]);
    std::vector<int> idx(n_expert_);
    for (int e = 0; e < n_expert_; e++) idx[e] = e;
    std::partial_sort(idx.begin(), idx.begin() + top_k_, idx.end(),
                      [&](int a, int b) { return selprobs[a] > selprobs[b]; });
    std::vector<int> sel(idx.begin(), idx.begin() + top_k_);
    // Weights come from the UNBIASED probs, sum-normalised, then scaled.
    std::vector<float> r(n_expert_, 0.0f);
    for (int e : sel) r[e] = probs[e];
    // expert_weights_norm: llama.cpp's deepseek2 normalises the SELECTED weights by
    // their SUM (ggml_div(weights, ggml_sum_rows(weights))), not by their L2 norm,
    // and only then applies expert_weights_scale.  Using L2 here was a bug.
    float wsum = 0.0f;
    for (int e : sel) wsum += r[e];
    if (wsum > 0.0f) for (int e : sel) r[e] = r[e] / wsum * expert_w_scale_;

    // Per-layer MoE dump, laid out to compare directly against llama.cpp's
    // llama-eval-callback sums (ffn_moe_logits/probs/weights, ffn_moe_*).
    const bool dump = getenv("NPU_INFER_DUMP_MOE") && std::atoi(getenv("NPU_INFER_DUMP_MOE")) == l;
    if (dump) {
        auto sm = [](const std::vector<float>& v) { double s = 0; for (float f : v) s += f; return s; };
        double rawsum = 0; for (float f : logits) rawsum += f;
        double xnsq = 0; for (float f : xn) xnsq += (double)f * f;
        fprintf(stderr, "  [moe] L%d xn_sum=%.6f xn_rms=%.6f router_rms=%.6f\n",
                l, sm(xn), std::sqrt(xnsq / H),
                [&] { double s = 0; for (float f : moe_router_) s += (double)f * f;
                      return std::sqrt(s / moe_router_.size()); }());
        fprintf(stderr, "  [moe] L%d logits=%.6f probs=%.6f biased=%.6f sel=[%d,%d,%d,%d] "
                        "w=[%.6f,%.6f,%.6f,%.6f] wsum_raw=%.6f scaled=%.6f\n",
                l, rawsum, sm(probs), sm(selprobs), sel[0], sel[1], sel[2], sel[3],
                r[sel[0]], r[sel[1]], r[sel[2]], r[sel[3]], wsum, wsum * expert_w_scale_);
    }
    std::vector<float> g, u, dd, go, uo;
    double moe_g = 0, moe_u = 0, moe_sw = 0, moe_dn = 0;
    const int i_gb = idx_of(Q4NX_DESIGN_GB), i_ub = idx_of(Q4NX_DESIGN_UB);
    if (i_gb >= 0 && i_ub >= 0 && !getenv("NPU_NO_EXPERT_BATCH")) {
        // One gate GEMM and one up GEMM over ALL selected experts (they share xn),
        // instead of 2*top_k dispatches.  Expert j's weights occupy columns
        // [j*IM, (j+1)*IM) of a [K][top_k*IM] B; the design's N is wider, so
        // npu_gemm packs only the real columns and the tail stays zero.
        const int K = H, tk = (int)sel.size(), N = tk * expert_im_;
        static std::vector<float> Bg, Bu;   // reused across layers; fully written below
        Bg.resize((size_t)K * N);
        Bu.resize((size_t)K * N);
        std::vector<std::vector<float>> gs(tk), us(tk), ds(tk);
        for (int j = 0; j < tk; j++) {
            if (!mla_expert(exp_g_, exp_g_bytes_, sel[j], expert_im_, K, gs[j])) { err_ = "expert gate"; return false; }
            if (!mla_expert(exp_u_, exp_u_bytes_, sel[j], expert_im_, K, us[j])) { err_ = "expert up"; return false; }
            if (!mla_expert(exp_d_, exp_d_bytes_, sel[j], K, expert_im_, ds[j])) { err_ = "expert down"; return false; }
        }
        #pragma omp parallel for schedule(static)
        for (int j = 0; j < tk; j++) {
            for (int n = 0; n < expert_im_; n++) {
                const float* rg = &gs[j][(size_t)n * K];
                const float* ru = &us[j][(size_t)n * K];
                for (int i = 0; i < K; i++) {
                    Bg[(size_t)i * N + (size_t)j * expert_im_ + n] = rg[i];
                    Bu[(size_t)i * N + (size_t)j * expert_im_ + n] = ru[i];
                }
            }
        }
        std::vector<float> go_all, uo_all;
        npu_gemm(*ctx_[i_gb], xn.data(), designs_[i_gb].K, N, Bg.data(), go_all);
        npu_gemm(*ctx_[i_ub], xn.data(), designs_[i_ub].K, N, Bu.data(), uo_all);
        for (int j = 0; j < tk; j++) {
            const int e = sel[j];
            std::vector<float> act((size_t)expert_im_);
            for (int i = 0; i < expert_im_; i++) {
                const float gv = go_all[(size_t)j * expert_im_ + i];
                act[i] = (gv / (1.0f + std::exp(-gv))) * uo_all[(size_t)j * expert_im_ + i];
            }
            const Q4nxDesignGeom* gd = &designs_[i_d];
            std::vector<float> ed;
            Q4nxProjections p{}; p.down = ds[j].data();
            if (q4nx_assemble_B(gd, &p, B_.data()) != 0) { err_ = "assemble expert down"; return false; }
            npu_gemm(*ctx_[i_d], act.data(), gd->K, gd->N, B_.data(), ed);
            if (dump) {
                for (int i = 0; i < expert_im_; i++) { moe_g += go_all[(size_t)j * expert_im_ + i]; moe_u += uo_all[(size_t)j * expert_im_ + i]; }
                for (float f : act) moe_sw += f;
                for (float f : ed) moe_dn += f;
            }
            for (int i = 0; i < H; i++) d[i] += r[e] * ed[i];
        }
    } else {
    for (int e : sel) {
        if (!mla_expert(exp_g_, exp_g_bytes_, e, expert_im_, H, g)) { err_ = "expert gate"; return false; }
        if (!mla_expert(exp_u_, exp_u_bytes_, e, expert_im_, H, u)) { err_ = "expert up"; return false; }
        if (!mla_expert(exp_d_, exp_d_bytes_, e, H, expert_im_, dd)) { err_ = "expert down"; return false; }
        // gate/up are GEMMs against xn (the dequantized matrices are weights, not
        // outputs): run them on the NPU through the G/U designs.
        {
            const Q4nxDesignGeom* gg = &designs_[i_g];
            Q4nxProjections p{}; p.gate = g.data();
            if (q4nx_assemble_B(gg, &p, B_.data()) != 0) { err_ = "assemble expert gate"; return false; }
            npu_gemm(*ctx_[i_g], xn.data(), gg->K, gg->N, B_.data(), go);
        }
        {
            const Q4nxDesignGeom* gu = &designs_[i_u];
            Q4nxProjections p{}; p.up = u.data();
            if (q4nx_assemble_B(gu, &p, B_.data()) != 0) { err_ = "assemble expert up"; return false; }
            npu_gemm(*ctx_[i_u], xn.data(), gu->K, gu->N, B_.data(), uo);
        }
        std::vector<float> act((size_t)expert_im_);
        for (int i = 0; i < expert_im_; i++)
            act[i] = (go[i] / (1.0f + std::exp(-go[i]))) * uo[i];
        const Q4nxDesignGeom* gd = &designs_[i_d];
        std::vector<float> ed;
        Q4nxProjections p{}; p.down = dd.data();
        if (q4nx_assemble_B(gd, &p, B_.data()) != 0) { err_ = "assemble expert down"; return false; }
        npu_gemm(*ctx_[i_d], act.data(), gd->K, gd->N, B_.data(), ed);
        if (dump) {
            for (float f : go) moe_g += f;
            for (float f : uo) moe_u += f;
            for (float f : act) moe_sw += f;
            for (float f : ed) moe_dn += f;
        }
        for (int i = 0; i < H; i++) d[i] += r[e] * ed[i];
    }
    }
    double moe_d_sum = 0; for (float f : d) moe_d_sum += f;
    // Shared expert, always on.
    double shexp_sum = 0;
    if (!share_g_.empty()) {
        std::vector<float> act((size_t)expert_im_);
        for (int i = 0; i < expert_im_; i++) {
            const float* rg = &share_g_[(size_t)i * H];
            const float* ru = &share_u_[(size_t)i * H];
            float sg = 0.0f, su = 0.0f;
            for (int k = 0; k < H; k++) { sg += rg[k] * xn[k]; su += ru[k] * xn[k]; }
            act[i] = (sg / (1.0f + std::exp(-sg))) * su;
        }
        const Q4nxDesignGeom* gd = &designs_[i_d];
        Q4nxProjections p{}; p.down = share_d_.data();
        if (!weight_cached(5) && q4nx_assemble_B(gd, &p, B_.data()) != 0) { err_ = "assemble shared down"; return false; }
        std::vector<float> sd;
        npu_gemm(*ctx_[i_d], act.data(), gd->K, gd->N, B_.data(), sd, 5);
        if (dump) {
            double ss = 0; for (float f : act) ss += f;
            fprintf(stderr, "  [moe] L%d expert gate=%.6f up=%.6f swiglu=%.6f down=%.6f weighted=%.6f | "
                            "shexp_swiglu=%.6f\n", l, moe_g, moe_u, moe_sw, moe_dn, moe_d_sum, ss);
        }
        for (float f : sd) shexp_sum += f;
        // Qwen MoE (qwen35moe) gates the shared expert with sigmoid(x . g), a [H]
        // vector; deepseek2 has no such gate (share_router_ empty -> scale 1).
        float sgate = 1.0f;
        if (!share_router_.empty()) {
            float g = 0.0f;
            for (int i = 0; i < H; i++) g += share_router_[i] * xn[i];
            sgate = 1.0f / (1.0f + std::exp(-g));
        }
        for (int i = 0; i < H; i++) d[i] += sgate * sd[i];
    }
    if (dump) {
        double tot = 0; for (float f : d) tot += f;
        fprintf(stderr, "  [moe] L%d moe_out=%.6f shexp=%.6f ffn_out=%.6f\n", l, moe_d_sum, shexp_sum, tot);
    }
    return true;
}

// The leading dense layer (leading_dense_block_count=1): DG/DU/DD designs.
bool Q4nxNpuForward::dense_mlp(int l, const std::vector<float>& xn, std::vector<float>& d) {
    const int H = c_.H;
    const int i_dg = idx_of(Q4NX_DESIGN_DG), i_du = idx_of(Q4NX_DESIGN_DU), i_dd = idx_of(Q4NX_DESIGN_DD);
    if (i_dg < 0 || i_du < 0 || i_dd < 0) { err_ = "dense designs missing"; return false; }
    std::vector<float> g, u;
    {
        const Q4nxDesignGeom* gd = &designs_[i_dg];
        Q4nxProjections p{}; p.gate = dense_g_.data();
        if (q4nx_assemble_B(gd, &p, B_.data()) != 0) { err_ = "assemble dense gate"; return false; }
        npu_gemm(*ctx_[i_dg], xn.data(), gd->K, gd->N, B_.data(), g);
    }
    {
        const Q4nxDesignGeom* gd = &designs_[i_du];
        Q4nxProjections p{}; p.up = dense_u_.data();
        if (q4nx_assemble_B(gd, &p, B_.data()) != 0) { err_ = "assemble dense up"; return false; }
        npu_gemm(*ctx_[i_du], xn.data(), gd->K, gd->N, B_.data(), u);
    }
    std::vector<float> act((size_t)dense_im_);
    for (int i = 0; i < dense_im_; i++)
        act[i] = (g[i] / (1.0f + std::exp(-g[i]))) * u[i];
    if (getenv("NPU_INFER_DUMP_DENSE")) {
        auto sm = [](const std::vector<float>& v) {
            double s = 0; for (float f : v) s += f; return s;
        };
        fprintf(stderr, "  [dense] gate n=%zu sum=%.6f | up n=%zu sum=%.6f | act n=%zu sum=%.6f\n",
                g.size(), sm(g), u.size(), sm(u), act.size(), sm(act));
    }
    const Q4nxDesignGeom* gd = &designs_[i_dd];
    Q4nxProjections p{}; p.down = dense_d_.data();
    if (q4nx_assemble_B(gd, &p, B_.data()) != 0) { err_ = "assemble dense down"; return false; }
    npu_gemm(*ctx_[i_dd], act.data(), gd->K, gd->N, B_.data(), d);
    return true;
}

bool Q4nxNpuForward::attention(const std::vector<float>& qkv, int pos,
                               std::vector<float>& ctx, int head_dim,
                               int n_kv_heads, float theta, int rotary_dim,
                               bool proportional, int window,
                               int kv_layer, bool append_kv) {
    const int NH = c_.NH;
    const int HD = head_dim;      /* per layer type (Gemma4: 256 or 512) */
    const int NKV = n_kv_heads;
    const int gqa = NH / NKV;

    std::vector<float> q((size_t)NH * HD), k((size_t)NKV * HD), v((size_t)NKV * HD);
    for (int i = 0; i < NH * HD; i++) q[i] = qkv[i];
    for (int i = 0; i < NKV * HD; i++) k[i] = qkv[NH * HD + i];
    for (int i = 0; i < NKV * HD; i++) v[i] = qkv[NH * HD + NKV * HD + i];
    // Qwen2.5-style attention biases: the q/k/v projections carry a per-output
    // bias (config attention_bias=true). Added before qk-norm/RoPE.
    if (sem_.attention_bias) {
        for (int i = 0; i < NH * HD; i++) q[i] += q_bias_[cur_layer_][i];
        for (int i = 0; i < NKV * HD; i++) k[i] += k_bias_[cur_layer_][i];
        for (int i = 0; i < NKV * HD; i++) v[i] += v_bias_[cur_layer_][i];
    }

    // per-head RMSNorm on q and k, only for architectures that have it.  A KV-shared
    // layer (Gemma4) computed no k at all, so its k is never normalized or used.
    if (sem_.qk_norm) {
        std::vector<float> t(HD);
        for (int h = 0; h < NH; h++) {
            rmsnorm(&q[(size_t)h * HD], q_norm_[cur_layer_].data(), HD, t.data());
            memcpy(&q[(size_t)h * HD], t.data(), sizeof(float) * HD);
        }
        if (append_kv) {
            for (int h = 0; h < NKV; h++) {
                rmsnorm(&k[(size_t)h * HD], k_norm_[cur_layer_].data(), HD, t.data());
                memcpy(&k[(size_t)h * HD], t.data(), sizeof(float) * HD);
            }
        }
    }
    // Gemma4 normalises v with a SCALE-FREE RMSNorm (its v_norm has no weight).
    if (sem_.v_norm && append_kv) {
        std::vector<float> tv(HD);
        for (int h = 0; h < NKV; h++) {
            rmsnorm_noweight(&v[(size_t)h * HD], HD, tv.data());
            memcpy(&v[(size_t)h * HD], tv.data(), sizeof(float) * HD);
        }
    }

    // RoPE: half-split over the first `rot` channels (rot == HD means full).
    // Gemma4's full layers use "proportional" RoPE: the pairing spans the WHOLE
    // head_dim, but the frequencies past rot/2 are zero, so those pairs are the
    // identity (_compute_proportional_rope_parameters).
    const int rot = (rotary_dim > 0 && rotary_dim <= HD) ? rotary_dim : HD;
    {
        const int half = proportional ? HD / 2 : rot / 2;
        std::vector<float> cos_(half), sin_(half);
        for (int i = 0; i < half; i++) {
            double inv;
            if (proportional) {
                inv = 1.0 / std::pow((double)theta, 2.0 * (double)i / (double)HD);
                if (i >= rot / 2) inv = 0.0;
            } else {
                inv = 1.0 / std::pow((double)theta, (double)i / (double)half);
                // LongRoPE (MiniCPM4): ggml's rope applies the factor as
                // `rope_yarn(theta / ff, ...)` (ggml-cpu/ops.cpp
                // ggml_rope_cache_init), i.e. the angle is DIVIDED by
                // freq_factors.  So divide the inv_freq here.  Multiplying (the
                // engine route's 599ac77) blows the high dims up by up to 31x
                // and yields garbage logits.  NPU_INFER_ROPE_FACTOR_MUL=1 keeps
                // the old multiply for A/B.
                if (i < (int)rope_scale_.size()) {
                    const char* mul = getenv("NPU_INFER_ROPE_FACTOR_MUL");
                    if (mul && mul[0] == '1') inv *= (double)rope_scale_[i];
                    else                       inv /= (double)rope_scale_[i];
                }
            }
            const double ang = (double)pos * inv;
            cos_[i] = (float)std::cos(ang);
            sin_[i] = (float)std::sin(ang);
        }
        auto rot_half = [&](float* x) {
            // pairs (i, i + half) inside the rotated block; the rest passes through
            for (int i = 0; i < half; i++) {
                const float x1 = x[i], x2 = x[i + half];
                x[i] = x1 * cos_[i] - x2 * sin_[i];
                x[i + half] = x1 * sin_[i] + x2 * cos_[i];
            }
        };
        for (int h = 0; h < NH; h++) rot_half(&q[(size_t)h * HD]);
        for (int h = 0; h < NKV; h++) rot_half(&k[(size_t)h * HD]);
    }

    // append to cache (a KV-shared layer reuses its owner's, which the owner has
    // already appended earlier in this same step).
    if (append_kv) {
        kcache_[kv_layer].insert(kcache_[kv_layer].end(), k.begin(), k.end());
        vcache_[kv_layer].insert(vcache_[kv_layer].end(), v.begin(), v.end());
    }

    const int T = pos + 1;
    // Gemma4 sets attention scaling to 1.0 (q/k carry an RMSNorm); everyone else
    // uses the usual 1/sqrt(head_dim).
    const float scale = sem_.attn_scaling_one ? 1.0f : 1.0f / std::sqrt((float)HD);
    // Sliding-window attention: ignore positions older than the window.
    const int t0 = (window > 0 && pos + 1 > window)
                       ? pos + 1 - window : 0;
    ctx.assign((size_t)NH * HD, 0.0f);
    std::vector<float> score(T);
    for (int h = 0; h < NH; h++) {
        const int kh = h / gqa;
        const float* qh = &q[(size_t)h * HD];
        float mx = -1e30f;
        for (int t = 0; t < T; t++) {
            if (t < t0) { score[t] = -1e30f; continue; }
            const float* kt = &kcache_[kv_layer][((size_t)t * NKV + kh) * HD];
            float d = 0.0f;
            for (int i = 0; i < HD; i++) d += qh[i] * kt[i];
            score[t] = d * scale;
            if (score[t] > mx) mx = score[t];
        }
        float sum = 0.0f;
        for (int t = 0; t < T; t++) {
            if (t < t0) { score[t] = 0.0f; continue; }
            score[t] = std::exp(score[t] - mx);
            sum += score[t];
        }
        const float inv = sum > 0 ? 1.0f / sum : 0.0f;
        float* out = &ctx[(size_t)h * HD];
        for (int t = t0; t < T; t++) {
            const float p = score[t] * inv;
            const float* vt = &vcache_[kv_layer][((size_t)t * NKV + kh) * HD];
            for (int i = 0; i < HD; i++) out[i] += p * vt[i];
        }
    }
    return true;
}

// SiLU(gate) * up from either a fused GU result or separate G and U results.
bool Q4nxNpuForward::mlp(const std::vector<float>& gu, std::vector<float>& h, int im) {
    LhScope _tlh(LH_MLP);
    h.resize(im);
    const int gelu = (sem_.mlp_act == Q4NX_ACT_GELU);
    for (int i = 0; i < im; i++) {
        const float g = gu[i];
        const float u = gu[im + i];
        float a;
        if (gelu) {
            // tanh approximation (gelu_pytorch_tanh), as HF uses for Gemma
            const float c = 0.7978845608028654f;   // sqrt(2/pi)
            a = 0.5f * g * (1.0f + std::tanh(c * (g + 0.044715f * g * g * g)));
        } else {
            a = g / (1.0f + std::exp(-g));         // SiLU
        }
        h[i] = a * u;
    }
    return true;
}

// --------------------------------------------------------------------------
// step
// --------------------------------------------------------------------------
bool Q4nxNpuForward::step(int token, int pos, std::vector<float>& logits) {
    if (!ready_) { err_ = "not initialised"; return false; }
    const long step_d0 = prof_dec_n_;
    // Phase attribution (NPU_PHASE_PROF=1): named phases summing to this step's wall.
    const bool ph = phprof_on();
    const auto tp_step = ph ? std::chrono::steady_clock::now()
                            : std::chrono::steady_clock::time_point{};
    auto tp_lap = tp_step;
    if (ph) {
        g_ph = StepPhases{};
        for (int i = 0; i < LH_LAYER_N; i++) { g_lh[i] = 0.0; g_lh_n[i] = 0; }
    }
    const int H = c_.H;
    if (token < 0 || token >= c_.NV) { err_ = "token out of range"; return false; }

    const int i_qkv = idx_of(Q4NX_DESIGN_QKV);
    const int i_o = idx_of(Q4NX_DESIGN_O);
    const int i_gu = idx_of(Q4NX_DESIGN_GU);
    const int i_g = idx_of(Q4NX_DESIGN_G);
    const int i_u = idx_of(Q4NX_DESIGN_U);
    const int i_d = idx_of(Q4NX_DESIGN_D);
    const int i_qkv2 = idx_of(Q4NX_DESIGN_QKV2);   /* 2nd attention type (Gemma4) */
    const int i_o2 = idx_of(Q4NX_DESIGN_O2);

    std::vector<float> x(H), xn(H), o(H), d(H), h, ctx;
    // The stored embedding is PRE-SCALED by the architecture's embedding scale
    // (Gemma4 bakes sqrt(hidden_size) into the tensor), so no scale is applied
    // here; the LM head divides it back out (see run_lm_head).
    for (int k = 0; k < H; k++)
        x[k] = embed_at(token, k) * embed_scale_;
    if (pos == 0 && getenv("NPU_INFER_DUMP_LAYERS")) {
        double s = 0;
        float mx = 0;
        for (int k = 0; k < H; k++) {
            const float a = std::fabs(x[(size_t)k]);
            s += a;
            if (a > mx) mx = a;
        }
        fprintf(stderr, "  [L] -1 %.6f %.4f\n", s / H, mx);
    }

    // Gemma4 needs this token's per-layer inputs before the layer loop.
    if (ple_dim_ > 0) build_ple_inputs(token);
    if (ph) { g_ph.embed = ph_ms(tp_step); tp_lap = std::chrono::steady_clock::now(); }

    for (int l = 0; l < c_.NL; l++) {
        cur_layer_ = l;
        // Dense models: once this layer's projections are packed (after the
        // first token), the f32 weights are no longer read, so skip the per-token
        // Q4NX dequant.  GDN/MLA/PLE load members used outside the GEMMs, so they
        // keep loading every token.
        const bool dense_weights_cached = lin_kd_ == 0 && !mla_ && ple_dim_ == 0 && n_expert_ == 0 && weight_cached(0);
        {
            LhScope _tlh(LH_LOAD);
        if (!dense_weights_cached && !load_layer(l)) { if (err_.empty()) err_ = "dequant failed"; return false; }
        }
        // MLA + MoE layers have no plain q/k/v/o or single-MLP structure, so they
        // take their own path through this loop body and skip the rest.
        if (mla_) {
            // The attention input is the NORMALISED hidden state (input_layernorm),
            // exactly as the standard path does; feeding the raw residual here was
            // a bug.
            rmsnorm(x.data(), in_norm_[l].data(), H, xn.data());
            if (!mla_attn(l, xn, o, pos)) return false;
            { LhScope _tlh(LH_RES);
            for (int k = 0; k < H; k++) x[k] += o[k] * residual_scale_; }
#ifdef NPU_INFER_DEBUG_DUMPS
            if (l == 0 && pos == 0 && getenv("NPU_INFER_DUMP_ATTN")) {
                FILE* f = open_debug_dump(getenv("NPU_INFER_DUMP_ATTN"));
                if (f) { fwrite(x.data(), sizeof(float), (size_t)H, f); fclose(f); }
            }
#endif
            rmsnorm(x.data(), post_norm_[l].data(), H, xn.data());
            if (l < leading_dense_) {
                if (!dense_mlp(l, xn, d)) return false;
            } else {
                if (!moe_mlp(l, xn, d)) return false;
            }
            { LhScope _tlh(LH_RES);
            for (int k = 0; k < H; k++) x[k] += d[k] * residual_scale_; }
            // Dump one layer's post-residual hidden state for the Python reference
            // comparison (NPU_INFER_DUMP_LN names the layer).
#ifdef NPU_INFER_DEBUG_DUMPS
            if (getenv("NPU_INFER_DUMP_LN") && l == atoi(getenv("NPU_INFER_DUMP_LN")) && pos == 0) {
                const char* p = getenv("NPU_INFER_DUMP_L0");
                FILE* f = open_debug_dump(p ? p : "/tmp/npu_layer.bin");
                if (f) { fwrite(x.data(), sizeof(float), (size_t)H, f); fclose(f); }
                fprintf(stderr, "  [mla] dumped layer-%d x (%d floats)\n", l, H);
            }
#endif
            if (pos == 0 && getenv("NPU_INFER_DUMP_LAYERS")) {
                auto am = [&](const std::vector<float>& v) {
                    float m = 0.0f;
                    for (float f : v) m = std::max(m, std::fabs(f));
                    return m;
                };
                fprintf(stderr, "  [mla] L%d attn_absmax=%.4f mlp_absmax=%.4f x_absmax=%.4f\n",
                        l, am(o), am(d), am(x));
            }
            continue;
        }
        // KV sharing (Gemma4): a layer past num_kv_shared_layers carries no k/v
        // weights and reuses the K/V of the last non-shared layer of its own
        // attention type, which that layer already appended earlier this step.
        const bool kv_shared = (l < (int)kv_owner_.size() && kv_owner_[l] != l);
        const int kv_layer = (l < (int)kv_owner_.size()) ? kv_owner_[l] : l;
        // use_double_wide_mlp: the shared layers run a 2*IM-wide MLP (GU2/D2).
        const bool wide = kv_shared && sem_.double_wide_mlp;
        const int i_gu_l = wide ? idx_of(Q4NX_DESIGN_GU2) : i_gu;
        const int i_d_l = wide ? idx_of(Q4NX_DESIGN_D2) : i_d;
        const int im_l = wide ? 2 * c_.IM : c_.IM;

        // ---- per-layer-type attention geometry ----
        // Gemma4's full_attention layers use global_head_dim (512) where its
        // sliding layers use head_dim (256), so BOTH the attention width and the
        // QKV/O geometry differ by layer type; every other model has one type.
        const int lt = (l < sem_.n_layer_types) ? sem_.layer_types[l]
                                                : Q4NX_LAYER_FULL;
        const bool l_full = (lt != Q4NX_LAYER_SLIDING);
        const bool two_widths = (i_qkv2 >= 0);
        const int i_qkv_l = (two_widths && l_full) ? i_qkv2 : i_qkv;
        const int i_o_l = (two_widths && l_full) ? i_o2 : i_o;
        const int l_qrows_all = designs_[i_qkv_l].q_rows;   // q_proj rows (x2 if gated)
        const int l_hd = (attn_gate_ ? l_qrows_all / 2 : l_qrows_all) / c_.NH;
        const int l_nkv_heads = (l_hd > 0) ? designs_[i_qkv_l].k_rows / l_hd : c_.NKV;
        const float l_theta = l_full ? sem_.rope_theta : sem_.rope_theta_sliding;
        const int l_rot = l_full ? sem_.rotary_dim : sem_.rotary_dim_sliding;
        const bool l_prop = l_full && sem_.proportional_rope;
        const int l_win = l_full ? 0 : sem_.sliding_window;
        // Debug aid: with NPU_INFER_NANCHECK set, stop at the first layer that
        // produces a non-finite hidden state (the offline host-GEMM run made
        // NaN-hunting cheap this way).
        auto nancheck = [&](const char* where) -> bool {
            if (!getenv("NPU_INFER_NANCHECK")) return true;
            for (int k = 0; k < H; k++) {
                if (!std::isfinite(x[(size_t)k])) {
                    fprintf(stderr, "  [nan] pos=%d layer=%d (%s) after %s\n", pos, l,
                            (lin_kd_ > 0 && lt == Q4NX_LAYER_LINEAR) ? "linear" : "full", where);
                    return false;
                }
            }
            return true;
        };

        // ---- attention ---- (or, for a GDN layer, gdn_layer below)
        rmsnorm(x.data(), in_norm_[l].data(), H, xn.data());
        if (lin_kd_ > 0 && lt == Q4NX_LAYER_LINEAR) {
            LhScope _tlh(LH_GDN);
            if (!gdn_layer(l, xn, o)) return false;
        } else {
        {
            const Q4nxDesignGeom* g = &designs_[i_qkv_l];
            Q4nxProjections p{};
            p.q = wq_.data(); p.k = wk_.data(); p.v = wv_.data();
            // A shared layer has no k/v weights at all: only its q is real and the
            // k/v half of the GEMM output is discarded.  Reusing wq_ for those
            // slots keeps assemble_B's row counts in bounds (q_rows >= k_rows).
            if (kv_shared) { p.k = wq_.data(); p.v = wq_.data(); }
            if (!pb16i_ && !weight_cached(0) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble qkv"; return false; }
            std::vector<float> qkv;
            if (pb16i_ && i_qhalf_ >= 0) {
                // pb16i has no 14336-wide full-attention QKV kernel: four launches, the two
                // q halves (q, and the output gate) plus k and v on their own geometry.
                // They fill the same [q|gate|k|v] order the fused launch would.
                const int nhd = c_.NH * c_.HD, nkv = c_.NKV * c_.HD;
                std::vector<float> qh0, qh1, kvk, kvv;
                const Q4nxDesignGeom* gq = &designs_[i_qhalf_];
                const Q4nxDesignGeom* gk = &designs_[i_kv_];
                npu_gemm(*ctx16_[i_qhalf_], xn.data(), gq->K, gq->N, nullptr, qh0, 10, "attn_q_h0");
                npu_gemm(*ctx16_[i_qhalf_], xn.data(), gq->K, gq->N, nullptr, qh1, 11, "attn_q_h1");
                npu_gemm(*ctx16_[i_kv_], xn.data(), gk->K, gk->N, nullptr, kvk, 12, "attn_k");
                npu_gemm(*ctx16_[i_kv_], xn.data(), gk->K, gk->N, nullptr, kvv, 13, "attn_v");
                if ((int)qh0.size() < nhd || (int)qh1.size() < nhd || (int)kvk.size() < nkv ||
                    (int)kvv.size() < nkv || !err_.empty()) {
                    if (err_.empty()) err_ = "pb16i full-attention QKV split returned short";
                    return false;
                }
                qkv.assign((size_t)2 * nhd + (size_t)2 * nkv, 0.0f);
                memcpy(qkv.data(), qh0.data(), (size_t)nhd * sizeof(float));
                memcpy(qkv.data() + nhd, qh1.data(), (size_t)nhd * sizeof(float));
                memcpy(qkv.data() + 2 * nhd, kvk.data(), (size_t)nkv * sizeof(float));
                memcpy(qkv.data() + 2 * nhd + nkv, kvv.data(), (size_t)nkv * sizeof(float));
            } else {
                npu_gemm(*ctx_[i_qkv_l], xn.data(), g->K, g->N, B_.data(), qkv, 0, "attn_qkv");
            }
            // attn_output_gate: the fused QKV is [q | gate | k | v], so attention()
            // must not see the gate half; the gate multiplies ctx afterwards.
            std::vector<float> qkv_use;
            const int nhd = c_.NH * l_hd;
            const float* gate_ptr = nullptr;
            if (attn_gate_) {
                const int kvsz = g->k_rows + g->v_rows;
                qkv_use.resize((size_t)nhd + (size_t)kvsz);
                memcpy(qkv_use.data(), qkv.data(), (size_t)nhd * sizeof(float));
                memcpy(qkv_use.data() + nhd, qkv.data() + 2 * nhd,
                       (size_t)kvsz * sizeof(float));
                gate_ptr = qkv.data() + nhd;
            } else {
                qkv_use = qkv;
            }
            {
            LhScope _tlh(LH_ATTN);
            if (!attention(qkv_use, pos, ctx, l_hd, l_nkv_heads, l_theta, l_rot, l_prop,
                           l_win, kv_layer, !kv_shared)) {
                err_ = "attention failed";
                return false;
            }
            }
            if (gate_ptr)
                for (int i = 0; i < nhd; i++)
                    ctx[i] *= 1.0f / (1.0f + expf(-gate_ptr[i]));
        }
        {
            const Q4nxDesignGeom* g = &designs_[i_o_l];
            Q4nxProjections p{};
            p.o = wo_.data();
            if (!pb16i_ && !weight_cached(1) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble o"; return false; }
            npu_gemm(*ctx_[i_o_l], ctx.data(), g->K, g->N, B_.data(), o, 1,
                     l_full ? "attn_output" : "ssm_out");
        }
        }  // end non-GDN attention
        if (gemma4_layer_) {
            // Gemma4 normalises the attention output BEFORE the residual add.
            rmsnorm(o.data(), post_norm_[l].data(), H, xn.data());
            for (int k = 0; k < H; k++) x[k] += xn[k];
        } else {
            { LhScope _tlh(LH_RES);
            for (int k = 0; k < H; k++) x[k] += o[k] * residual_scale_; }
        }
        if (!nancheck("attention")) return false;

        // ---- MLP ----
        // Gemma4 normalises with pre_feedforward_layernorm and applies
        // post_feedforward_layernorm to the down-projection output; the plain
        // decoder normalises x with post_attention_layernorm instead.
        if (gemma4_layer_) {
            rmsnorm(x.data(), pre_ff_norm_[l].data(), H, xn.data());
        } else {
            rmsnorm(x.data(), post_norm_[l].data(), H, xn.data());
        }
        if (n_expert_ > 0) {
            // Qwen MoE layer (qwen3moe / qwen35moe): the FFN is router -> top-k
            // experts, not a dense gate/up/down.  moe_mlp writes the whole FFN
            // delta into d.  (deepseek2/GLM MoE layers never reach here -- the MLA
            // branch above handles attn+MoE and continues.)
            if (!moe_mlp(l, xn, d)) return false;
            { LhScope _tlh(LH_RES);
            for (int k = 0; k < H; k++) x[k] += d[k] * residual_scale_; }
            if (!nancheck("moe")) return false;
            continue;
        }
        std::vector<float> act;
        if (i_gu_l >= 0) {
            const Q4nxDesignGeom* g = &designs_[i_gu_l];
            Q4nxProjections p{};
            p.gate = wg_.data(); p.up = wu_.data();
            if (!pb16i_ && !weight_cached(2) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble gu"; return false; }
            npu_gemm(*ctx_[i_gu_l], xn.data(), g->K, g->N, B_.data(), act, 2, "ffn_gate_up");
        } else if (i_g >= 0 && i_u >= 0) {
            // split gate/up: two kernels, then SiLU(gate) * up
            std::vector<float> gv, uv;
            const Q4nxDesignGeom* gg = &designs_[i_g];
            Q4nxProjections pg{}; pg.gate = wg_.data();
            if (!pb16i_ && !weight_cached(2) && q4nx_assemble_B(gg, &pg, B_.data()) != 0) { err_ = "assemble g"; return false; }
            npu_gemm(*ctx_[i_g], xn.data(), gg->K, gg->N, B_.data(), gv, 2, "ffn_gate");

            const Q4nxDesignGeom* gu = &designs_[i_u];
            Q4nxProjections pu{}; pu.up = wu_.data();
            if (!pb16i_ && !weight_cached(3) && q4nx_assemble_B(gu, &pu, B_.data()) != 0) { err_ = "assemble u"; return false; }
            npu_gemm(*ctx_[i_u], xn.data(), gu->K, gu->N, B_.data(), uv, 3, "ffn_up");

            act.resize((size_t)im_l * 2);
            for (int i = 0; i < im_l; i++) {
                act[i] = gv[(size_t)i];
                act[im_l + i] = uv[(size_t)i];
            }
        } else {
            err_ = "no gate/up design";
            return false;
        }
        mlp(act, h, im_l);
        {
            const Q4nxDesignGeom* g = &designs_[i_d_l];
            Q4nxProjections p{};
            p.down = wd_.data();
            if (!pb16i_ && !weight_cached(4) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble d"; return false; }
            npu_gemm(*ctx_[i_d_l], h.data(), g->K, g->N, B_.data(), d, 4, "ffn_down");
        }
        if (!gemma4_layer_) {
            { LhScope _tlh(LH_RES);
            for (int k = 0; k < H; k++) x[k] += d[k] * residual_scale_; }
            if (!nancheck("mlp")) return false;
            if (pos == 0 && getenv("NPU_INFER_DUMP_LAYERS")) {
                double s = 0;
                float mx = 0;
                for (int k = 0; k < H; k++) {
                    const float a = std::fabs(x[(size_t)k]);
                    s += a;
                    if (a > mx) mx = a;
                }
                fprintf(stderr, "  [L] %d %.6f %.4f\n", l, s / H, mx);
            }
            continue;
        }
        // post_feedforward_layernorm, then the residual add.
        rmsnorm(d.data(), post_ff_norm_[l].data(), H, xn.data());
        for (int k = 0; k < H; k++) x[k] += xn[k];

        // ---- per-layer embedding block (PLE) ----
        // x = x + post_per_layer_input_norm( per_layer_projection(
        //         act_fn(per_layer_input_gate(x)) * per_layer_input[l] ) )
        if (ple_dim_ > 0) {
            const int i_pg = idx_of(Q4NX_DESIGN_PLEGATE);
            const int i_pp = idx_of(Q4NX_DESIGN_PLEPROJ);
            std::vector<float> pg, pp;
            {
                const Q4nxDesignGeom* g = &designs_[i_pg];
                Q4nxProjections p{};
                p.ple = inp_gate_[l].data();
                if (!weight_cached(0) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble plegate"; return false; }
                npu_gemm(*ctx_[i_pg], x.data(), g->K, g->N, B_.data(), pg, 0);
            }
            const int gelu = (sem_.mlp_act == Q4NX_ACT_GELU);
            for (int i = 0; i < ple_dim_; i++) {
                float a;
                if (gelu) {
                    const float cc = 0.7978845608028654f;
                    a = 0.5f * pg[i] *
                        (1.0f + std::tanh(cc * (pg[i] + 0.044715f * pg[i] * pg[i] * pg[i])));
                } else {
                    a = pg[i] / (1.0f + std::exp(-pg[i]));
                }
                pg[i] = a * ple_input_[(size_t)l * ple_dim_ + i];
            }
            {
                const Q4nxDesignGeom* g = &designs_[i_pp];
                Q4nxProjections p{};
                p.ple = ple_proj_[l].data();
                if (!weight_cached(1) && q4nx_assemble_B(g, &p, B_.data()) != 0) { err_ = "assemble pleproj"; return false; }
                npu_gemm(*ctx_[i_pp], pg.data(), g->K, g->N, B_.data(), pp, 1);
            }
            rmsnorm(pp.data(), post_ln_[l].data(), H, xn.data());
            for (int k = 0; k < H; k++) x[k] += xn[k];
        }
        // layer_scalar (layer_output_scale) closes the Gemma4 layer.
        const float ls = (l < (int)layer_scale_.size()) ? layer_scale_[l] : 1.0f;
        if (ls != 1.0f)
            for (int k = 0; k < H; k++) x[k] *= ls;
    }
    if (ph) { g_ph.layer = ph_ms(tp_lap); tp_lap = std::chrono::steady_clock::now(); }

    rmsnorm(x.data(), final_norm_.data(), H, xn.data());
    last_hidden_ = xn;  // for last_hidden(): the post-final-norm state of this position

@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

Reviewed the new surface as code and verified every envelope claim against the pack's own sources on this box, not
against the PR's description of them.

Ran:

$ g++-16 -std=c++26 -O1 -Iapp -Inpu -isystem …/json-src/include tests/systemone_route_test.cpp && ./systemone_route_test tests/golden/systemone/prompts.json
systemone_route: ok                                                     rc 0
$ g++-16 -DONEBIT_NPU_RUNTIME_OWN -std=c++26 -fsyntax-only … npu/forward/src/q4nx_forward.cpp   ok
$ g++-16 -DONEBIT_NPU_RUNTIME_OWN -std=c++26 -fsyntax-only … app/forward_serve.cpp              ok
$ python3 tools/copyright.py --check                                                            rc 0

(CI builds neither NPU lane, so the two hand compiles are the only compile evidence that exists for these files.)

The prompt wrapper is checked, not asserted. The test walks all 9 fixtures in tests/golden/systemone/prompts.json
(choice_two_one_null … score_json_levels) and byte-compares
<|im_start|>system\n{system}<|im_end|>\n<|im_start|>user\n{expected_user_prompt}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n
against systemone_prompt(), then asserts the wrapper differs from chatml() — so the empty think block really is in
the bytes and the "reuse chatml()" shortcut cannot pass.

The envelope matches the pack's server (/tmp/d3meta/s2.py, whose docstring says it is d3_server.py, plus
d3_runtime.py):

  • POST /v1/systemone takes questions (object) plus optional state/images/videos/model; anything outside
    that list or of the wrong type is 422 {"detail": "<reason>"} — s2.py's own docstring says exactly this;
  • malformed questions → 422 {"detail": {"invalid_questions": {id: reason}}} and nothing runs (s2.py:164);
  • usage is {"input_tokens": tokens, "output_tokens": 0} (d3_runtime.py:2048) and tokens is the sum of the
    questions' prompt lengths (d3_runtime.py:2021-2023), not the state's — the PR's point, confirmed;
  • an over-limit question stays an entry inside answers with
    {"type", "error": "max_length_exceeded", "message": "… over the maximum context length …; nothing was truncated"}
    (d3_runtime.py:1438-1444), other questions still answered — HTTP 200, no truncation;
  • answers is keyed by question id in request order (for key in prepared.keys, d3_runtime.py:2033);
  • enable_thinking=False (d3_format.py:85, d3_runtime.py:1335/1347) — which is the empty think block above.

The one route this PR touches that everything else uses is preserved byte for byte. /health and /v1/health were
refactored into one health() lambda; with no decision head loaded it emits {"status":"ok"} (and {"status":"loading"}
with 503 before ready) exactly as the deleted inline handlers did, and the d3 fields (model, max_input_tokens,
modalities, authentication) are added only under if (e.head).

Not verified: the device rows (choice 0.685 / noul 0.046 / score 0.0724, input_tokens 97 and 269, the 401 with
DECISION_API_KEY, the 34086 > 32768 refusal) and the synthetic 255×1024 head they were taken with. Those need
forward-serve built with the NPU lane plus a decision pack, under npu-hold; they are the lane's numbers, and the
routes are what I checked.

@bong-water-water-bong bong-water-water-bong added the tprs-ready TPRS: review verdict READY posted by the standing reviewer; merge gate satisfied label Nov 1, 2026

@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

Confirmation at 4a708620 after update-branch (the branch now carries #768's squash 7f4e98a as a main merge; the
author commit 8a9afdc is unchanged, so the content is byte-identical to what I reviewed at 8a9afdce). Build green.
The evidence stands: systemone_route_test green over all 9 fixtures with the wrapper byte-compared including the empty
think block, both changed NPU-lane TUs compiled by hand, the envelope verified against the pack's s2.py/d3_runtime.py,
and the shared /health route preserved byte for byte. Device rows remain the lane's. tprs-ready stays.

@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Persistent review updated to latest commit 4a70862

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