Skip to content

npu forward: split ffn_down's outlier channels out of the int8 activation (Fixes #2536) - #2552

Merged
bong-water-water-bong merged 1 commit into
mainfrom
cl-npuperf/2536-act-outliers
Nov 15, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
cl-npuperf/2536-act-outliers

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Fixes #2536

What was wrong

Both AMD Qwen2.5-3B-Instruct packs (1.9.0 NPU and 1.7.1 hybrid) import byte-exact. Even so, serve --device npu garbled one date:

  • 1.9.0: Neil Armstrong, on July 20, 1鹅1969
  • 1.7.1: ... 1 lick this out 1969

The cause is the i8 GEMM's one activation scale per row (amax/127). Traced at the failing position, prefix ...July 20, 1:

path next tokens
--device npu lick this
NPU_INFER_HOST_GEMM=i8 lick this
NPU_INFER_HOST_GEMM=1 (f32, same container weights) 969,
device, with only ffn_down (or only ffn_gate_up) moved to host f32 96
device, with only attn_qkv / attn_output moved to host f32 钿1

The ffn_down input rows run at amax/rms 38 (median over 36 layers) to 100 (L35, one channel at 1200).

The change

An LLM.int8-style outlier-channel split for the ffn_down GEMM, applied per row on the device path:

  1. Channels with |x| > tau * rms (at most 16) are zeroed in the int8 activation.
  2. Their x_c * W[:, c] is added on the host in f32, from the layer's own down_proj column.

How the columns are read:

  • Columns are decoded one 256-wide tile block at a time (act_outlier_gather_block + q4nx_dequant_tensor_chunked) instead of the whole tensor.
  • They are cached per (layer, channel), capped at 8192 columns.
  • The first block of each layer is checked bit-for-bit against the full decode; on any difference the code falls back and logs [outlier].

Rows without an outlier run the plain launch. Host-GEMM runs are not changed.

On by default at tau 40. NPU_ACT_OUTLIER_TAU=0 turns it off; NPU_ACT_OUTLIER_KMAX caps the channels per row.

Measured (strixhalo, serve --device npu, each row in its own npu-hold ticket, dmesg clean)

Teacher-forced top-1 against HF fp32, 64 positions, the same probes in every column:

model off tau 20 tau 40 reply
Qwen2.5-3B-Instruct 1.7.1 hybrid 54/64 57/64 60/64 off garbles the date; 20 and 40 give "July 20, 1969, as part of the Apollo 11 mission."
Qwen2.5-0.5B-Instruct 1.9.0 53/64 53/64 51/64 same answers
SmolLM2-135M-Instruct 1.9.0 53/64 51/64 53/64 same answers

The ±2 swings on the small models are near-tie flips; a 64-position top-1 cannot resolve finer than that. For reference, RTN int4 of the HF Qwen2.5-3B scores 58/64.

Speed on Qwen2.5-3B, 96-token reply, A B A B in one ticket (tau 20): off 1.900 / 2.018 tok/s, on 1.888 / 1.963 tok/s. The 0.6-2.7 % difference is inside run-to-run scatter.

Tests

tests/act_outliers_test.cpp (ctest -R act_outliers) covers:

  • Picking: an outlier row yields exactly its channels; a flat row yields none, so the plain path is kept; kmax keeps the largest; tau 0 is off; padded strides are handled.
  • Arithmetic: on a row with one channel at 100x rms, the per-row int8 GEMM has rel_err 0.098 without the split and 0.0031 with it.
  • Gather: the gathered block decodes bit-identical to that block of the full decode on q4_1 tiles, and a wrong block does not match.

Two mutants make the test fail: picking never selects, and the gather reads tile column 0.

Docs: docs/npu.md, section NPU_ACT_OUTLIER_TAU.

🤖 Generated with Claude Code

…tion (Fixes #2536)

The i8 GEMM quantises each activation row with one scale (amax/127). Qwen2.5-3B's ffn_down rows run at
amax/rms 38-100, so a typical channel kept 1-3 int8 levels and both AMD Qwen2.5-3B packs garbled
"July 20, 1969" into "1 lick this out 1969". Per row, the channels above tau*rms (at most 16) now leave
the int8 activation and their x_c*W[:,c] is added on the host in f32 from the layer's down_proj column,
decoded one 256-wide tile block at a time (checked bit-for-bit against the full decode once per layer).
On by default at tau 40; NPU_ACT_OUTLIER_TAU=0 turns it off.

Qwen2.5-3B 1.7.1: teacher-forced top-1 vs HF fp32 54 -> 60/64 and the date is right; Qwen2.5-0.5B and
SmolLM2-135M keep their answers (+-2/64, near ties); decode speed within noise.

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

Copy link
Copy Markdown
Collaborator Author

ready for review at de09d4d

Full ctest at this head (strixhalo, inside npu-hold): 336/337 passed. The one failure, gpu_hold_child_identity, is an artefact of running the suite inside a real NPU ticket: its 'refuse a foreign token' case found my live token. It passes 1/1 rerun outside a ticket. npu_dmabuf_import and npu_rt_shim were excluded: both fail to link against this box's release-rc NPU runtime (undefined npu_rt_api::ext::bo::bo(...)), which this change does not touch.

pi-i679: thanks for standing back on the issue. The ~/models/oga-2536/ copy is not needed for this PR; I used my own import.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

2536 - Partially compliant

Compliant requirements:

  • Fix the garbled token output on Qwen2.5-3B-Instruct when using --device npu
  • The fix addresses the issue with per-row int8 activation scale causing incorrect outputs
  • The solution splits outlier channels out of the int8 activation for ffn_down GEMM
  • The fix is implemented to not affect models without outliers (the plain launch is used when no outliers are found)
  • The fix is configurable via environment variables NPU_ACT_OUTLIER_TAU and NPU_ACT_OUTLIER_KMAX
  • Documentation has been updated to reflect the new behavior and configuration options

Non-compliant requirements:

  • None

Requires further human verification:

  • None
⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Potential Performance Regression

The outlier channel detection and handling logic in ffn_down_outliers function introduces additional overhead by scanning rows and potentially decoding full weight tensors for outlier channels. This could lead to performance degradation, especially when many rows have outliers or when the number of outlier channels is high. The performance impact should be measured against the baseline to ensure it's acceptable.

// engine#2536: ffn_down with its outlier channels split out (act_outliers.h). Runs on the device path only (a host-GEMM
// run returns before the hook). Returns false when no row has an outlier: the caller then runs the plain launch, so a
// model without outliers pays one scan of its rows.
bool Q4nxNpuForward::ffn_down_outliers(const float* A, int M, int a_k, int K, int N, const float* Bmat,
                                       std::vector<float>& out, int wkey, int role, bool rows_form, bool decode_twin) {
    const int w = (a_k > 0 && a_k < K) ? a_k : K;
    const int stride = rows_form ? onebit::npu::row_stride(a_k, K) : w;
    std::vector<onebit::npu::ActOutlier> picks;
    onebit::npu::act_outlier_pick(A, M, stride, w, outl_tau_, outl_kmax_, picks);
    if (picks.empty()) return false;
    const int L = cur_layer_, rowsW = c_.H, colsW = q4nx_pad_k(c_.IM);
    auto key_of = [L](int ch) { return ((uint64_t)(uint32_t)L << 32) | (uint32_t)ch; };
    std::vector<int> blocks;
    for (const auto& pk : picks)
        if (!outl_cols_.count(key_of(pk.ch))) blocks.push_back(pk.ch / Q4NX_TILE_COLS);
    std::sort(blocks.begin(), blocks.end());
    blocks.erase(std::unique(blocks.begin(), blocks.end()), blocks.end());
    if (!blocks.empty()) {
        TensorDesc* d = &mw_->layers[L].down_proj_weight;
        const uint8_t* raw = (const uint8_t*)model_tensor_data(mw_, d);
        if (!raw) return false;
        if (outl_cols_.size() > 8192) outl_cols_.clear();   // 8192 columns x H floats: 64 MB at H 2048
        // A column of a [rowsW, colsW] tile tensor lives in one 256-wide block (tile (tr, c/256) of every tile-row).
        // For uniform chunked tiles in row-major tile order, that block decodes on its own as a [rowsW, 256] tensor.
        // The first block of each layer is checked bit-for-bit against the full decode; a difference turns the
        // gather off for good and says so, and every other layout takes the full decode.
        const int TR = rowsW / Q4NX_TILE_ROWS, TC = colsW / Q4NX_TILE_COLS;
        const size_t ntiles = (size_t)TR * (size_t)TC;
        const int cb = (ntiles && rowsW % Q4NX_TILE_ROWS == 0 && colsW % Q4NX_TILE_COLS == 0)
                           ? (int)((size_t)d->data_size / ntiles) : 0;
        const bool chunked = cb > 0 && (size_t)cb * ntiles == (size_t)d->data_size &&
                             (cb == Q4NX_TILE_BYTES || cb == Q4NX_CHUNK_Q4K || cb == Q4NX_CHUNK_Q8 || cb == Q4NX_CHUNK_Q4S) &&
                             !(d->ndim == 2 && !strcmp(d->dtype, "BF16"));
        bool full_done = false;
        auto full_decode = [&]() -> bool {
            if (full_done) return true;
            outl_scratch_.resize((size_t)rowsW * (size_t)colsW);
            if (dequant_any(raw, (size_t)d->data_size, rowsW, colsW, outl_scratch_.data(), d) != 0) return false;
            full_done = true;
            return true;
        };
        std::vector<uint8_t> gbuf;
        std::vector<float> bout;
        for (int tc : blocks) {
            const float* src = nullptr;
            int ld = colsW, off = tc * Q4NX_TILE_COLS;
            if (chunked && outl_gather_ok_) {
                onebit::npu::act_outlier_gather_block(raw, TR, TC, cb, tc, gbuf);
                bout.resize((size_t)rowsW * Q4NX_TILE_COLS);
                if (q4nx_dequant_tensor_chunked(gbuf.data(), gbuf.size(), rowsW, Q4NX_TILE_COLS, cb, bout.data()) != 0)
                    return false;
                if (!outl_checked_.count(L)) {
                    if (!full_decode()) return false;
                    bool same = true;
                    for (int n = 0; n < rowsW && same; n++)
                        same = std::memcmp(&bout[(size_t)n * Q4NX_TILE_COLS], &outl_scratch_[(size_t)n * colsW + off],
                                           Q4NX_TILE_COLS * sizeof(float)) == 0;
                    outl_checked_.insert(L);
                    if (!same) {
                        outl_gather_ok_ = false;
                        std::fprintf(stderr, "  [outlier] layer %d: a gathered down_proj column block differs from the "
                                             "full decode; every later column takes the full decode\n", L);
                    }
                }
                if (outl_gather_ok_) { src = bout.data(); ld = Q4NX_TILE_COLS; off = 0; }
            }
            if (!src) {
                if (!full_decode()) return false;
                src = outl_scratch_.data();
            }
            for (const auto& pk : picks) {
                if (pk.ch / Q4NX_TILE_COLS != tc || outl_cols_.count(key_of(pk.ch))) continue;
                std::vector<float> col((size_t)rowsW);
                const int cc = off + pk.ch % Q4NX_TILE_COLS;
                for (int n = 0; n < rowsW; n++) col[(size_t)n] = src[(size_t)n * ld + cc];
                outl_cols_.emplace(key_of(pk.ch), std::move(col));
            }
        }
    }
    std::vector<float> Az(A, A + (size_t)(M - 1) * (size_t)stride + (size_t)w);
    for (const auto& pk : picks) Az[(size_t)pk.row * (size_t)stride + (size_t)pk.ch] = 0.0f;
    outl_busy_ = true;
    if (rows_form) npu_gemm_rows(role, Az.data(), M, K, N, Bmat, out, wkey, "ffn_down", a_k, decode_twin);
    else npu_gemm(role, Az.data(), K, N, Bmat, out, wkey, "ffn_down", a_k);
    outl_busy_ = false;
    if (out.size() < (size_t)M * (size_t)N) return true;   // the launch failed and set err_; keep its message
    const int nn = std::min(N, rowsW);
    for (const auto& pk : picks) {
        const std::vector<float>& col = outl_cols_[key_of(pk.ch)];
        float* y = &out[(size_t)pk.row * (size_t)N];
        for (int n = 0; n < nn; n++) y[n] += pk.x * col[(size_t)n];
    }
    return true;
}

Memory Usage Concern
The act_outliers.h header introduces caching of decoded weight columns (outl_cols_) which can grow quite large (up to 8192 columns x H floats, ~64 MB at H 2048). While there's a mechanism to clear the cache when it exceeds 8192 entries, this could still lead to significant memory usage during inference, particularly for models with many layers or high hidden dimensions. This needs to be monitored to ensure it doesn't cause memory pressure.

Cache Invalidation Logic

The cache invalidation logic for outl_cols_ (clearing when size exceeds 8192) may not be optimal for all scenarios. If a model has a large number of unique outlier patterns, the cache might be frequently cleared, leading to repeated decoding of weight columns. This could impact performance and should be validated with different models and usage patterns.

if (outl_cols_.size() > 8192) outl_cols_.clear();   // 8192 columns x H floats: 64 MB at H 2048

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

READY — the bisection table is the part that makes this reviewable, and it is what I would keep above the prose.

path next tokens
--device npu lick this
NPU_INFER_HOST_GEMM=i8 lick this
NPU_INFER_HOST_GEMM=1 (f32) 969,
device, only ffn_down on host f32 96
device, only attn_qkv/attn_output on host f32 钿1

Four rows do the work of a page of argument: i8 reproduces the bug on the host (so it is the quantiser, not the device), f32 does not (so it is precision, not a wiring error), and moving exactly one GEMM to f32 localises it. That last pair is the strongest form of this experiment — a per-GEMM bisection that produces different wrong answers per GEMM, which rules out "everything is slightly off" and points at one bucket. amax/rms 38 (median) to 100 (L35, one channel at 1200) is the measurement that explains why.

Three questions, in order of what I would want answered before merge:

  1. What happens when a row has more than 16 channels over tau*rms? "at most 16" reads as a cap, and a cap silently leaves the excess in the int8 activation — i.e. the exact error this PR removes, in the rows that need it most. If the cap is a bound that cannot be exceeded at this model's distribution, say with what margin; if it can be exceeded, log or refuse rather than truncate, because a truncated outlier set produces plausible output and no failure.
  2. The cost of the f32 host add on the product path. Per row: up to 16 x_c * W[:,c] terms of width down_proj's output — during decode that is a per-token host computation in a path we advertise at 0.3 s/window. Was tok/s or per-forward time measured before/after on the NPU device path? The table shows correctness; the PR body should not leave the impression that it is free.
  3. The 8192-column cache cap — eviction, or refusal? Columns are keyed per (layer, channel) and this model has 36 layers × up to 16 channels of tens of KB each, so if the cap is reachable the behaviour matters; a silent LRU is fine and should be named.

One request on the evidence, because it is the difference between "fixed" and "differently wrong": the table shows device-only-ffn_down-on-host reaching 96. State explicitly that the device output after this change equals the f32 reference for a long prefix (how many tokens, and does it hold to the end of the sentence?) rather than one next-token match — that is the claim a reader will otherwise assume and it is cheap to quote.

Credited, beyond the table: the bit-for-bit check of the first tile block against the full decode, with a hard fallback on any difference — validating the column reader against the thing it replaces is the check that keeps the gather from being plausible-but-shifted, and it is exactly the class of bug a 256-wide tile block invites. Caching per (layer, channel) with a cap is also the right shape: the alternative (re-decode per row) would have made the fix cost more than the bug.

Not verified by me: the device numbers and the pack results. The bisection logic, the amax/rms distribution and the column-reader validation are what I can check, and all three are right.

@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 de09d4d: CHANGES

The split is the right fix and its host half is well pinned. The column cache's eviction can read out of bounds.

Measured, host side. I built tests/act_outliers_test.cpp with npu/forward/src/q4nx_dequant.c from git merge-tree origin/main de09d4d, then ran it and three mutants of act_outliers.h:

act_outliers_test                                  ok   (int8 row vs f32: plain rel_err 0.0977, split rel_err 0.0031)
mutant: partial_sort keeps the SMALLEST kmax      FAIL :96  kmax 1 keeps the largest |x|
mutant: gather always reads tile-column 0         FAIL :180 block 1/2/3: 192 of 192 rows differ from the full decode
mutant: threshold tau*mean(x^2) instead of rms    FAIL :81/:88/:96

The bug, in Q4nxNpuForward::ffn_down_outliers. The order is:

  1. blocks is built from the picks whose column is not cached (if (!outl_cols_.count(key_of(pk.ch))) blocks.push_back(…)).
  2. Then, inside if (!blocks.empty()): if (outl_cols_.size() > 8192) outl_cols_.clear();.
  3. Only the picks in blocks are decoded back in (if (pk.ch / Q4NX_TILE_COLS != tc || outl_cols_.count(key_of(pk.ch))) continue;).
  4. The add loop then does const std::vector<float>& col = outl_cols_[key_of(pk.ch)] for every pick, and reads col[(size_t)n] for n < nn.

Take a call where the cache holds more than 8192 columns and the picks mix a cached channel A with an uncached one B. A is skipped in (1), wiped in (2), and not re-decoded in (3). outl_cols_ is an unordered_map (q4nx_forward.h:485), so operator[] in (4) default-inserts an empty vector, and col[n] reads past its end for all nn outputs. That is out-of-bounds reads into the ffn_down output, or a crash. At Qwen2.5-3B's measured rate (at most 16 channels × 36 layers) the cache may never reach 8192, but a model with more varied outliers over a long prompt can, and the failure is silent garbage, which is #2536's own symptom again.

The ask: evict before deciding what to decode. Move the size() > 8192 clear above the blocks computation, so a cleared pick is decoded again in the same call. Or replace operator[] with at()/find() so a miss is loud. An arm would pin it: drive ffn_down_outliers' bookkeeping, or a small extracted helper, with a pre-filled cache over the cap and one cached plus one uncached pick, and assert every pick's column has rowsW entries.

Nit: the new block went in between the existing comment "When the dense-tail cache is on by default (… ffn_cache_policy.h) …" and the ffn_cache_policy_test target it describes (CMakeLists.txt:1762-1768), so that comment now sits above act_outliers_test. Moving the insertion two lines up keeps each comment on its own target.

Not run by me: the device path, the teacher-forced 60/64, or the reply text. Those are npu-hold runs.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2552

The bisection table is the part that makes this reviewable, and it is the right shape: one variable per row, and the two rows that did not fix it (attn_qkv / attn_output on host f32 → 钿1, still garbage) are as informative as the ones that did. Isolating ffn_down and then showing amax/rms at 38–100 with one channel at 1200 is a mechanism, not a correlation — the per-row amax/127 scale is dominated by a single outlier, so every other channel in that row is quantised into a handful of levels.

Four asks, in descending value:

  1. verify numerically per token, not by text. The text test is a weak oracle and this PR proves it: the packs imported byte-exact and still garbled, so "the sentence is right now" can pass with a materially wrong vector. Compare ffn_down's output against the f32 path at the failing position and report the relative error before/after — that number is what makes the fix a measurement rather than a sighting;
  2. tau and the 16-channel cap need their provenance. "channels with |x| > tau * rms (at most 16)" is two hyperparameters with a cliff: a channel just below tau is still clipped, and a row with 17 outliers clips the 17th silently. State how tau was chosen and what the cap does when exceeded — even "logged and clipped" is fine, but silently is not;
  3. name the 1200 channel if it is knowable. An outlier that extreme usually has a cause (a bias term, a padding row, a feature the model uses as a sentinel). If it is identifiable, one line in the PR saves the next person from re-deriving it; if it is not, saying "not identified" is worth more than silence;
  4. measure the cost of the split. A second GEMM for outlier channels is an extra pass on the NPU path, where prefill is already the slow half. Even a rough before/after on the same prompt is enough to know the price.

And one regression ask: the test should pin the exact prompt that garbled (Neil Armstrong, on July 20, 1969) as a golden and run the numeric comparison — the golden catches this instance, the numeric comparison catches the next one that changes the text somewhere else.

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.

npu: the i8 GEMM path's per-row int8 activation scale garbles tokens on Qwen2.5-3B (host f32 GEMM on the same container is right)

1 participant