Skip to content

fix(exl3): scale BF16 activations per row, not per tensor (#4870) - #4938

Merged
Qubitium merged 2 commits into
mainfrom
fix/exl3-per-row-prescale
Nov 17, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/exl3-per-row-prescale

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4870.

TL;DR

ExllamaV3Linear._native_bf16_input() now scales per row and only for rows
above _FP16_SAFE_AMAX, so one massive activation can no longer push the rest
of the batch into FP16 subnormals. Measured on layers.1.mlp.down_proj of
Llama-3.2-1B-Instruct-EXL3-W4: max per-row relative error of the ordinary rows
9.891e-02 → 2.731e-03 (fp16 native: 2.148e-03).

1. The problem

#4817 routed BF16 activations onto the FP16-only native kernels. The bridge
computed one amax over the whole tensor and, when it exceeded
_FP16_SAFE_AMAX = 64, divided the whole tensor by the same power of two:

flowchart TD
    A["BF16 x, one row with amax 1176"] --> B["amax over the whole tensor = 1176"]
    B --> C{"amax <= 64?"}
    C -- "no" --> D["scale = 2**11 = 2048<br/>applied to EVERY row"]
    D --> E["ordinary rows ~0.4 / 2048 = 2e-4"]
    E --> F["FP16 subnormals (smallest normal 6.1e-5)<br/>most precision lost"]
    F --> G["rows 1..63 rel err 9.9e-2"]
    style D fill:#fff1f0,stroke:#d4380d
    style F fill:#fff1f0,stroke:#d4380d
    style G fill:#fff1f0,stroke:#d4380d
    style C fill:#e6f4ff,stroke:#0958d9
Loading

The docs claimed "power-of-two scaling is exact, so relative rounding is
unchanged". That only holds while every value stays a normal FP16 number.
Real models hit this during prefill: layers.1.mlp.down_proj sees amax 1176 on
2 of 512 rows while the median row amax is 0.43.

2. The fix

row_amax = x.detach().float().abs().amax(dim=-1, keepdim=True)
_, exponent = torch.frexp(row_amax)
output_scale = torch.where(
    row_amax > _FP16_SAFE_AMAX,
    torch.ldexp(torch.ones_like(row_amax), exponent),
    torch.ones_like(row_amax),
)
return (x / output_scale).to(torch.float16), output_scale
flowchart TD
    A["BF16 x"] --> B{"tensor amax finite?"}
    B -- "no" --> Z["_ensure_torch_inner (FP32)"]
    B -- "yes" --> C{"tensor amax <= 64?"}
    C -- "yes" --> D["cast to FP16, scale None<br/>(bit-exact, unchanged path)"]
    C -- "no" --> E["row_amax = amax(dim=-1, keepdim=True)"]
    E --> F{"row_amax > 64"}
    F -- "yes" --> G["scale = 2**frexp_exp(row_amax)"]
    F -- "no" --> H["scale = 1"]
    G --> I["x / scale -> FP16"]
    H --> I
    I --> J["kernel"]
    J --> K["output * scale, bias excluded<br/>(broadcasts per row)"]
    style D fill:#e6f4ff,stroke:#0958d9
    style G fill:#e6f4ff,stroke:#0958d9
    style H fill:#e6f4ff,stroke:#0958d9
Loading

Only rows above the threshold change; every other row keeps scale 1 and
converts to FP16 bit-exactly, exactly as before this PR. The tensor-wide fast
path is untouched, so an input that never needed scaling behaves identically.

One contract change

_native_bf16_input used to signal "nothing was scaled" with the float 1.0.
A tensor scale cannot be compared with != 1.0 without an ambiguous-truth-value
error, so the signal is now None:

Return Before After
No scaling (x.half(), 1.0) (x.half(), None)
Scaled (x.half(), 1024.0) (x.half(), tensor of per-row scales)

forward() becomes if output_scale is not None: result = self._rescale_native_output(result, output_scale), which also removes the
float comparison.

3. Before / after

Situation Before After
Batch where one row has a 1e4 outlier Every row divided by 2^14; ordinary rows subnormal Only the outlier row scaled; ordinary rows bit-exact
Uniformly wide input (all rows 1e4) Each row scaled by the same factor Each row scaled by its own factor (same value)
Input entirely below 64 Cast, no scaling Cast, no scaling (None)
Non-finite input FP32 Torch path FP32 Torch path
Row mixing 1e4 with 0.3 Subnormal on its small elements Still subnormal on its own small elements — inherent to FP16 range, but it no longer affects other rows

4. Tests

tests/test_exl3_wide_input.py:

Test Invariant
test_bfloat16_prescale_is_per_row_not_per_tensor (new) One 1e4 outlier: only row 0 is scaled, rows 1..63 are bit-identical to the input
test_bfloat16_normal_range_cast_is_exact No scaling → output_scale is None, cast is bit-exact
test_bfloat16_wide_input_is_power_of_two_prescaled A power-of-two scale, round-trip within 1e-6
test_bfloat16_wide_input_prescale_handles_amax_above_fp16 1e5 stays finite

5. Validation

Red, origin/main @ 1ad4f64, exllamav3.py unchanged:

$ python repro_4870.py            # real EXL3 checkpoint, layers.1.mlp.down_proj
RESULT bf16_native_rel_err=9.891e-02 fp16_native_rel_err=2.148e-03

$ pytest test_exl3_wide_input.py -q
6 failed, 22 passed

Green, same host, with the fix:

$ python repro_4870.py
RESULT bf16_native_rel_err=2.731e-03 fp16_native_rel_err=2.148e-03

$ pytest test_exl3_wide_input.py -q
28 passed

The repro is the issue's own: 64 rows of N(0, 0.3) with x[0, 5] = 1e4,
mod = layers.1.mlp.down_proj, reference mod._ensure_torch_inner(), and the
max per-row relative error over rows 1..63. bf16 is now within 1.3x of fp16
instead of 46x.

$ pytest test_exl3_wide_input.py test_exl3_in_session_fp16_4789.py \
         test_exllamav3_inner_handle_4793.py -q
41 passed

test_docs_contract_refs.py reports the same 4 failures it reports on clean
origin/main (drifted base.py line refs in awq-scale-folding.md,
calibration-replay.md x2 and fp8-scale-semantics.md); this PR touches none
of those pages.

ruff check passes on both changed Python files.

6. Docs

docs/exl3-wide-activation-dispatch.md gains the per-row rule, the subnormal
failure mode it removes, and the remaining inherent limitation.

Claim: agent-11788dff99fd, workload 4a0c4b8f301a.

gptqmodel-agent added 2 commits November 17, 2026 19:15
_native_bf16_input computed one amax over the whole activation tensor and, when
it exceeded _FP16_SAFE_AMAX (64), divided the entire tensor by the same power of
two. On a real prefill a single massive activation (a BOS outlier, amax 1176 on
layers.1.mlp.down_proj) therefore scaled every other row of the batch down to
~1e-4, and those rows lost most of their precision to FP16 subnormals (smallest
normal 6.1e-5). The docs' "relative rounding is unchanged" only holds while
every value stays normal.

The scale is now per row, and only rows above _FP16_SAFE_AMAX are scaled at all,
so the ordinary rows keep scale 1 and convert to FP16 bit-exactly. The rescale
broadcasts the same per-row factor over the output. Power-of-two scaling stays
exact, and the tensor-wide amax fast path is unchanged, so an input that never
needed scaling behaves exactly as before.

The contract's "no scaling" signal is now None instead of 1.0: a tensor scale
cannot be compared with != without an ambiguous-truth-value error.

Measured on Llama-3.2-1B-Instruct-EXL3-W4 layers.1.mlp.down_proj, 64 rows of
N(0, 0.3) with one 1e4 element in row 0, max per-row relative error of rows
1..63 against the FP32 Torch reconstruction: bf16 native 9.891e-02 -> 2.731e-03
(fp16 native 2.148e-03).
The page said a power-of-two pre-scale leaves relative rounding unchanged,
which only holds while every value stays a normal FP16 number. Record that the
scale is per row, why a per-tensor scale lost the ordinary rows to FP16
subnormals, and that a row mixing a huge outlier with small values still goes
subnormal on its own small elements.
@Qubitium
Qubitium merged commit 68cf61f into main Nov 17, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/exl3-per-row-prescale branch November 17, 2026 19:24
sLaffey pushed a commit to sLaffey/GPTQModel that referenced this pull request Nov 18, 2026
) (ModelCloud#4966)

ModelCloud#4938 made the pre-scale per row but kept the trigger at 64 and normalized a
scaled row to (0.5, 1]. Two items from ModelCloud#4870 were left:

* A row whose own maximum is between 64 and 5789 - the real Llama-1B layers
  from the issue see 260 and 1176 - was divided by a power of two even though
  FP16 holds it untouched.
* The row that carries the massive activation was divided by its whole amax,
  so its own small elements fell into FP16 subnormals. On a row with amax 1176
  and elements around 1e-2 the small elements' norm error was 3.6e-3, and
  5.6e-2 at amax 20000.

`_FP16_SAFE_AMAX` is now `65504 / sqrt(128) ~= 5789.8`, the Hadamard bound the
issue proposed, and the per-row exponent is `frexp(row_amax / bound)`, so a
scaled row lands in `(bound / 2, bound]`: the smallest power of two that fits
instead of a normalization to 1. Rows at or below the bound keep scale 1 and
convert bit-exactly, and the rows that used to lose up to 5.6e-2 of their small
elements now round-trip exactly.

Tests: `tests/test_exl3_bf16_prescale_4870.py` (new) fails 7 of its 11 cases on
main and passes all 11 here;
`tests/test_exl3_wide_input.py`'s two `<= 1.0` assertions now pin the bound.
The required EXL3 suite is 19 failed / 484 passed / 13 skipped on main and
19 failed / 495 passed / 13 skipped here - same pre-existing host failures, 11
new passing tests. Docs updated.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant