Skip to content

perf(exl3): keep the bf16 pre-scale decision on the device, no host read per forward (#4955) - #4989

Merged
Qubitium merged 1 commit into
mainfrom
root/exl3-nosync-4955
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
root/exl3-nosync-4955

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

ExllamaV3Linear._native_bf16_input() opened every BF16 forward with
float(torch.linalg.vector_norm(x.detach(), ord=inf)) - a device -> host
synchronization on every native EXL3 linear. On a 1B model that is 112 syncs
per decoded token (224 on 8B): the host has to wait for the whole CUDA queue
before it can enqueue the next layer, decode runs 4-8x slower than the same
math without the read, and CUDA-graph capture of the BF16 path is impossible.

The read only answered two questions, and both are decidable on the device:
"is any row above _FP16_SAFE_AMAX?" and "is any row non-finite?". The
per-row scale from #4870/#4966 already computes row_amax; this PR derives the
scale from it with frexp/ldexp/where unconditionally. A row that needs no
scale gets exactly 1.0, which is the identity, so its FP16 conversion stays
bit-exact and the rescale leaves it untouched.

Fixes #4955.

What Changed

  • gptqmodel/nn_modules/exllamav3.py: _native_bf16_input() now reduces
    vector_norm(inf) per row on the device and derives
    output_scale = where(row_amax > bound, ldexp(1, frexp(row_amax / bound).exponent), 1)
    unconditionally. There is no float(), .item() or bool() of an
    activation per forward any more.
  • Non-finite activations still take the FP32 Torch reconstruction, but
    isfinite is now a warmup probe: it runs once per module, on its first
    BF16 forward, instead of on every forward (a per-forward isfinite is the
    same device->host sync). A module whose first BF16 activation is non-finite
    keeps the FP32 path and probes again on its next forward; once an activation
    is finite the module stays on the native path. This is the "check isfinite
    once at load/warmup" option from the issue.
  • Behaviour change: for a non-empty input the "nothing scaled" signal is now an
    all-ones device tensor instead of None (None still means an empty
    batch, and is still what a non-finite activation returns). None and 1.0
    encode the same decision, so the two existing assertions that pinned the
    literal None are relaxed to accept either. forward() applies the rescale
    unconditionally; at scale 1 it is (out - bias) * 1 + bias in FP32, the
    arithmetic the scaled path already used (measured: 0 / 204800 bf16 round-trip
    mismatches over random FP16 outputs and biases).
  • ExllamaV3TorchLinear, the FP16 path and the bias handling are untouched.
  • docs/exl3-wide-activation-dispatch.md: documents the device-side decision
    and the warmup probe.

Tests

New tests/test_exl3_native_nosync_4955.py (9 tests).

Red, unmodified origin/main @ c52ae996d (test copied into a clean worktree):

cd /root/worktrees/root-4955-base && <env> /root/venv-kernels/bin/python /tmp/root-rt.py \
  tests/test_exl3_native_nosync_4955.py -q -o addopts= -o log_cli=false -p no:cacheprovider
# 2 failed, 7 passed
# FAILED test_bf16_forward_is_sync_free_after_warmup
#   RuntimeError: called a synchronizing CUDA operation     (exllamav3.py:406)
# FAILED test_bf16_prescale_returns_a_device_scale_without_host_reads
#   AssertionError: host read of a CUDA tensor               (the float(amax) read)

Green, this PR:

cd /root/worktrees/root-4955 && <env> /root/venv-kernels/bin/python /tmp/root-rt.py \
  tests/test_exl3_native_nosync_4955.py tests/test_exl3_bf16_prescale_4870.py \
  tests/test_exl3_wide_input.py -q -o addopts= -o log_cli=false -p no:cacheprovider
# 48 passed

Full EXL3 suite (tests/test_exl3_wide_input.py tests/test_exl3_bf16_prescale_4870.py tests/test_exllamav3*.py tests/test_exl3_*.py):

tree result
origin/main @ c52ae996d 3 failed, 485 passed, 13 skipped
this PR 3 failed, 494 passed, 13 skipped

The same 3 nodes fail on both trees (pre-existing, unrelated):
tests/test_exl3_auto_nf12_recovery.py::test_exl3_bf16_quantizes_with_the_default_source_cast[default-auto-nf12],
...[off] and
tests/test_exl3_projection_resume.py::test_process_resumes_from_packed_checkpoint_without_requantizing.

Lint:

/root/venv-py3.14t-gil0/bin/ruff check gptqmodel/nn_modules/exllamav3.py \
  tests/test_exl3_native_nosync_4955.py tests/test_exl3_wide_input.py \
  tests/test_exl3_bf16_prescale_4870.py
# All checks passed!

Sync evidence

torch.cuda.set_sync_debug_mode("error"), 20 consecutive BF16 forwards of a
warm module (one ExllamaV3Linear, M=1, K=N=4096):

tree sync errors / 20
origin/main 20
this PR 0

Latency

8x PG506, GPU 7 shared with other agents. Interleaved A/B in one process, a
deep queue of 8 background GEMMs before each call (the serving case the issue
measured), best of 3 x 100 iterations:

variant ms / call sync errors / 20
pre-fix _native_bf16_input 1.040 20
device-only decision 0.480 0
speedup 2.16x

A second run gave 1.093 -> 0.442 ms (2.47x). The host read has to drain the
queued work, which is exactly the stall the issue reports; without a queue the
delta is one cudaStreamSynchronize per linear.

Numeric equivalence

_native_bf16_input on the pre-fix code vs this PR, same inputs:

input pre-fix this PR same
zeros fp16, scale None (1) fp16, scale 1 yes
tiny 1e-30 fp16, scale None (1) fp16, scale 1 yes
1.0 fp16, scale None (1) fp16, scale 1 yes
at bound (5789.8) fp16, scale 2 fp16, scale 2 yes
just over bound fp16, scale 4 fp16, scale 4 yes
1e5 fp16, scale 32 fp16, scale 32 yes
row0=1e5, rest 1.0 fp16, scale {1, 32} fp16, scale {1, 32} yes
row0=inf None (FP32 path) None (FP32 path) yes
row0=nan None (FP32 path) None (FP32 path) yes

tests/test_exl3_native_nosync_4955.py::test_scale_decision_matches_the_pre_fix_code
pins the table against a verbatim copy of the pre-fix implementation, so the
per-row + bound behaviour is unchanged and only the host read is gone.

Model Support / Module Plan

Not applicable: no model, alias, registry or definition change.

Logic Flow Documentation

This replaces a host decision with a device-side computation inside
_native_bf16_input; the flow and the warmup probe are documented in the
existing docs/exl3-wide-activation-dispatch.md (updated in this PR). No new
page is needed.

Review Requirements

  • Reviewed this PR.
  • Matches existing project structure, APIs and conventions.
  • No monkeypatching: the change is inside the existing method.
  • Impacted surface minimized: one method, one doc page, one new test file.
  • Regressions considered: numeric equivalence table + full EXL3 suite delta.

Kernel Accuracy Requirements

Notes

  • The warmup probe costs one host read per module on its first BF16 forward
    (112 in a 1B model, once), instead of one per linear per token.
  • A non-finite activation that appears after a module's warmup probe goes
    through the native path and stays non-finite, like the FP32 path. This is the
    documented trade-off of removing the per-forward isfinite.

`_native_bf16_input` started every BF16 forward with
`float(torch.linalg.vector_norm(x, inf))`, a device -> host synchronization on
every native EXL3 linear: 112 syncs per decoded token on a 1B model (224 on
8B), 4-8x slower decode than the same math without it, and no CUDA-graph
capture of the BF16 path.

The read only decided "is any row above `_FP16_SAFE_AMAX`" and "is any row
non-finite". The per-row scale from #4870/#4966 already computes `row_amax`, so
the scale is now derived from it unconditionally on the device with
`frexp`/`ldexp`/`where`; a row that needs no scale gets exactly 1.0, which is
the identity, so its FP16 conversion stays bit-exact.

`isfinite` becomes a warmup probe: once per module, on its first BF16 forward,
instead of once per forward (the issue's "check isfinite once at load/warmup").
A module whose first BF16 activation is non-finite keeps the FP32 Torch
reconstruction and probes again next call.

The "nothing scaled" signal for a non-empty input is now an all-ones device
tensor rather than None; None still means an empty batch and is still what a
non-finite activation returns. None and 1.0 are the same decision, so the two
tests that pinned the literal None accept either. ExllamaV3TorchLinear, the FP16
path and the bias handling are unchanged.

Tests: tests/test_exl3_native_nosync_4955.py (new, 9 tests). On main the two
decisive CUDA tests fail with "called a synchronizing CUDA operation" /
"host read of a CUDA tensor"; here 48/48 pass for the new + prescale + wide
files. The EXL3 suite is 3 failed / 485 passed / 13 skipped on main and
3 failed / 494 passed / 13 skipped here - the same pre-existing nf12 and
projection-resume nodes.

Measured on 8x PG506 (GPU 7 shared): 20/20 forwards sync on main, 0/20 here;
interleaved A/B with a deep queue, one ExllamaV3Linear M=1: 1.040 -> 0.480 ms
per call (2.16x), second run 1.093 -> 0.442 ms (2.47x).
@Qubitium
Qubitium merged commit 450774e into main Nov 17, 2026
9 checks passed
@Qubitium
Qubitium deleted the root/exl3-nosync-4955 branch November 17, 2026 21:11
Qubitium added a commit that referenced this pull request Nov 18, 2026
…#5148) (#5184)

#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
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