Skip to content

perf(exl3): fuse the bf16 pre-scale and re-scale into one launch each (#5148) - #5184

Merged
Qubitium merged 1 commit into
mainfrom
fix/5148-exl3-bf16-prescale
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5148-exl3-bf16-prescale

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #5148. EXL3 BF16 decode ran ~2.7x slower than the same checkpoint in
FP16 because the per-row pre-scale (_native_bf16_input) and the re-scale
(_rescale_native_output) were chains of ~12 eager elementwise kernels per
linear. #4989 removed the host sync, but at M=1 the 33 us GEMM starved behind
~90 us of host dispatch. Both halves are now one CUDA launch each, in the
existing gptqmodel_exllamav3 extension, and are bit-identical to the eager
sequence, which stays as the reference and fallback.

Net: 9 files changed (+1040/-28), 4 of them new; BF16 decode on sm_120 goes from
8.84 ms to 5.27 ms per step on the 8-layer harness (FP16: 4.52 ms), and
mlp.gate_proj M=1 from 88.2 us to 35.8 us (FP16: 32.8 us).

Root cause

ExllamaV3Linear._native_bf16_input + _rescale_native_output
(gptqmodel/nn_modules/exllamav3.py:411-449 at 17a488e) ran
vector_norm(inf), .float(), div, frexp, ones_like x2, ldexp,
where, x / scale, .to(fp16), then result.to(fp32), - bias,
* scale, + bias, .to(bf16). Every one is a separate kernel launch; each
launch is ~5-7 us of host dispatch against ~2 us of GPU work.

Before (per BF16 linear):

flowchart LR
    X["BF16 x"] --> A1["vector_norm inf"]
    A1 --> A2[".float"]
    A2 --> A3["div by bound"]
    A3 --> A4["frexp"]
    A4 --> A5["ones_like x2"]
    A5 --> A6["ldexp"]
    A6 --> A7["where"]
    A7 --> A8["x / scale"]
    A8 --> A9["to FP16"]
    A9 --> G["EXL3 GEMM"]
    G --> B1["to FP32"]
    B1 --> B2["- bias"]
    B2 --> B3["* scale"]
    B3 --> B4["+ bias"]
    B4 --> B5["to BF16"]
Loading

After:

flowchart LR
    X["BF16 x"] --> P["bf16_prescale<br/>one launch: row amax,<br/>power-of-two scale, FP16 cast"]
    P --> G["EXL3 GEMM<br/>FP16 in, FP16 out"]
    G --> R["bf16_rescale<br/>one launch: FP32 bias math,<br/>BF16 cast"]
    R --> Y["BF16 y"]
Loading

Failure path (unchanged behaviour, now explicit):

flowchart TD
    A["ExllamaV3Linear.forward bf16"] --> B{"trellis on CUDA?"}
    B -->|no| T["portable FP32 reconstruction"]
    B -->|yes| C{"fused op present,<br/>contiguous, warm module?"}
    C -->|no| E["eager reference sequence"]
    C -->|yes| F["bf16_prescale"]
    E --> G["EXL3 GEMM"]
    F --> G
    G --> H{"fused op present?"}
    H -->|no| I["eager re-scale, FP32"]
    H -->|yes| J["bf16_rescale, BF16"]
    I --> K["BF16 output"]
    J --> K
    A -->|non-finite first probe| T
Loading

What changed

  • gptqmodel_ext/exllamav3/bf16_scale.cu (new): bf16_prescale (one program
    per row: amax, frexp(amax / bound) decoded from the exponent field,
    multiply by the exact power-of-two reciprocal, single RTNE FP16 cast) and
    bf16_rescale (__fsub_rn/__fmul_rn/__fadd_rn, never an FMA, then one
    RTNE BF16 cast). A HIP shim mirrors gptqmodel_ext/paro/rotation.cuh.
  • gptqmodel_ext/exllamav3/bindings.cpp: registers
    bf16_prescale(Tensor x, float bound) -> (Tensor, Tensor) and
    bf16_rescale(Tensor result, Tensor scale, Tensor? bias, int n_cols) -> Tensor.
  • gptqmodel/exllamav3/ext.py: adds the new source to the JIT build.
  • gptqmodel/nn_modules/exllamav3_bf16_kernels.py (new): op lookup and the
    shape/dtype/device/stride guards that decide whether the fused path may run.
  • gptqmodel/nn_modules/exllamav3.py: _native_bf16_input uses the fused
    pre-scale once the module is warm; the eager sequence moves to
    _prescale_from_row_amax and remains the reference/fallback. forward uses
    the fused re-scale (which writes BF16 directly). No new host sync; the
    isfinite warmup probe is unchanged.
  • docs/exl3-wide-activation-dispatch.md: mechanism page updated with the
    before/after and failure-path diagrams, the bitwise contract and the measured
    table; linked from the EXL3 row in README.md.
  • tests/test_exl3_bf16_fused_prescale_5148.py (new).

No expanded/dequantized weight is cached: the kernels allocate their transient
FP16/BF16 outputs per call, and a test asserts no retained tensor reaches the
dense weight size after repeated forwards.

Measurements

RTX 5090 (sm_120), torch 2.15.0+cu132, CUDA 13.2, CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=2. Eight Llama-3.1-8B-geometry decoder layers quantized to
EXL3 W4 with EXL3Config's quantizer (no EXL3 checkpoint was available offline,
so weights are random but the projections, shapes and kernels are the real
ones). Batch 1 unless noted; decode is ms per generated token over 128 tokens.

Configuration decode bs1 decode bs8 prefill 2048 generate() 128 tok
dense HF BF16 3.74 ms 4.22 ms 48.0 ms 267 tok/s
EXL3 FP16 4.52 ms 4.53 ms 44.4 ms 221 tok/s
EXL3 BF16 before (eager chain) 8.84 ms 8.88 ms 54.9 ms 113 tok/s
EXL3 BF16 after (fused) 5.27 ms 5.37 ms 46.6 ms 190 tok/s

Single mlp.gate_proj (4096 -> 14336), M=1, minimum CUDA-event time per call:

us/call vs FP16
FP16 32.8 1.00x
BF16, eager (before) 88.2 2.69x
BF16, fused (after) 35.8 1.09x

Bitwise equality

The fused path is compared with the eager sequence by raw bits (.view(int16)
/ .view(int32)), not by tolerance, for:

  • the pre-scale and its scale at M=1/8/512/2048, magnitudes 0.5/1e5/3e38;
  • adversarial rows: all zeros, 1e-40 denormal, 65504, 0.99x and 1.01x
    the safe bound, 3e38, a 1e5 outlier row mixed with ordinary rows,
    negative, and inf/nan rows;
  • the re-scale with FP16/BF16/FP32/no bias, logical width below the padded
    stored width, and scales 1.0, 2^17, 2^60;
  • the complete forward at M=1/8/512/2048 and on every adversarial row.

Red evidence: the same test file run against 17a488e in a disposable
worktree (only the new exllamav3_bf16_kernels.py added so the module imports)
gives fp16 32.84 us, bf16 96.59 us (2.94x) and the registration test fails
because the ops do not exist — the intended assertions, not an import error.

Tests

# new regression suite (23 passed)
CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=2 PYTHONPATH=$PWD \
  HF_HUB_OFFLINE=1 /root/venv/bin/python -m pytest \
  tests/test_exl3_bf16_fused_prescale_5148.py -q -ra
# 23 passed

# red on 17a488e41 (disposable worktree /tmp/issue5148-red-*)
#   FAILED test_fused_ops_are_registered_in_the_extension
#   FAILED test_bf16_decode_is_within_1_3x_of_fp16_per_linear
#   fp16 32.84 us, bf16 96.59 us (2.94x)

# EXL3 family
CUDA_DEVICE_ORDER=PCI_BUS_ID CUDA_VISIBLE_DEVICES=2 PYTHONPATH=$PWD \
  HF_HUB_OFFLINE=1 /root/venv/bin/python -m pytest \
  tests/test_exl3*.py tests/test_exllamav3*.py -q -ra

# lint
uvx [email protected] check gptqmodel docs/eora tests setup.py

The timing test is marked slow. It measures FP16, BF16 and the eager chain in
the same process, asserts bf16 <= 1.3x fp16, and additionally asserts the
eager chain breaches that bound so a regression cannot pass silently. It skips
only when the FP16 baseline is under 20 us, where a fixed ~10 us of fused
launches cannot meet any ratio bound.

Unverified

  • ROCm/HIP: the new .cu maps __nv_bfloat16/<cuda_fp16.h> onto HIP the
    way gptqmodel_ext/paro/rotation.cuh does, but only the CUDA build was
    compiled here.
  • Real EXL3 checkpoint: no EXL3 checkpoint exists in the offline cache, so
    the harness uses random weights with real Llama-3.1-8B geometry. The fused
    path is bitwise identical to the shipped eager path, so accuracy is
    unchanged by construction; the tok/s figures are a launch-overhead proxy.
  • CUDA graph capture of the new path was not re-captured; the sync-debug
    test (set_sync_debug_mode("error")) still passes for eight consecutive
    warm forwards.
  • The 8-layer harness was measured on sm_120 only. The single-linear check
    was also run on an RTX 4090 (sm_89): FP16 32.8 us, BF16 fused 35.8 us
    (1.09x), BF16 eager 88.2 us (2.69x) - the same shape of improvement, but
    the decode/prefill table above is sm_120.

…#5148)

#4989 removed the per-forward host sync from the EXL3 BF16 path, but the
mapping was still ~12 eager kernels per linear: vector_norm, .float(), div,
frexp, ones_like x2, ldexp, where, divide, cast, then to(fp32), -bias,
*scale, +bias, to(bf16). At decode each is a microsecond kernel behind a full
host dispatch, so the 33 us GEMM starved behind ~90 us of launches and BF16
decode ran 2.7x slower than FP16.

Both halves are now one CUDA launch each in the existing
gptqmodel_exllamav3 extension:

* bf16_prescale: one program per row; row amax, frexp(amax/bound) decoded from
  the exponent field, multiply by the exact power-of-two reciprocal, single
  RTNE FP16 cast, FP32 per-row scale. No host read.
* bf16_rescale: (out - bias) * scale + bias with __fsub_rn/__fmul_rn/__fadd_rn
  (never an FMA) and one RTNE BF16 cast.

The eager sequence stays as the reference and the fallback (missing ops in a
stale build, non-contiguous/FP16/FP32/empty input, cold module), and the two
paths are bit-identical: the division by a power of two is exact, so only the
single FP16/BF16 cast rounds.

sm_120 (RTX 5090), 8 Llama-3.1-8B-geometry layers, EXL3 W4:
decode bs1 8.84 -> 5.27 ms/token (FP16 4.52), bs8 8.88 -> 5.37, prefill 2048
54.9 -> 46.6 ms. gate_proj M=1: FP16 32.8 us, BF16 88.2 -> 35.8 us.

Tests: bitwise equality of pre-scale/re-scale/forward across shapes, bias
dtypes, padded widths and adversarial rows; fallbacks; no retained dense
weight; and an M=1 bf16 <= 1.3x fp16 bound that measures the eager chain in
the same process (2.94x on 17a488e, 1.09x here).

Fixes #5148
@Qubitium
Qubitium marked this pull request as ready for review November 18, 2026 09:26
@Qubitium
Qubitium merged commit 23db39b into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5148-exl3-bf16-prescale branch November 18, 2026 09:26
Qubitium added a commit that referenced this pull request Nov 18, 2026
)

#5184 added gptqmodel_ext/exllamav3/bf16_scale.cu. Its HIP shim aliased only
the type (__nv_bfloat16 = __hip_bfloat16), but the store uses the CUDA
intrinsic __float2bfloat16_rn, which hipcc does not provide. So
gptqmodel_exllamav3_ops no longer built on ROCm at all and every EXL3 quantize
there failed at layer 0.

HIP's only scalar spelling is __float2bfloat16, which converts through clang's
__bf16 and therefore rounds to nearest-even - the same rounding as CUDA's
__float2bfloat16_rn. Declare a static __device__ __forceinline__ shim carrying
the CUDA name over it, so the kernel bodies stay identical on both platforms.
This is the gptqmodel_ext/paro/rotation.cuh pattern, which #5184 claimed to
mirror. The CUDA branch and both kernel bodies are byte-for-byte untouched, so
the #5148 fused==eager bitwise arithmetic is unchanged.

Also extend tests/test_rocm_kernel_contracts.py with a CPU-only contract that
walks the preprocessor regions of every hipified source under gptqmodel_ext/
and requires each __-prefixed symbol hipcc will see to be HIP-native,
hipify-rewritten, or declared by that file's HIP shim. The issue noted that
test_rocm_kernel_contracts.py passed while the extension could not build; this
closes that gap without ROCm hardware. 12 hipified files, 26 ms.

Red before the shim (real node): "gptqmodel_ext/exllamav3/bf16_scale.cu:173:
__float2bfloat16_rn is CUDA-only and not declared by the file's HIP shim".
Green after: test_rocm_kernel_contracts.py 464 passed;
tests/test_exl3_bf16_fused_prescale_5148.py 23 passed.
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