Repository navigation
perf(exl3): keep the bf16 pre-scale decision on the device, no host read per forward (#4955) - #4989
Merged
Merged
Conversation
`_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).
This was referenced Nov 18, 2026
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
ExllamaV3Linear._native_bf16_input()opened every BF16 forward withfloat(torch.linalg.vector_norm(x.detach(), ord=inf))- a device -> hostsynchronization 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?". Theper-row scale from #4870/#4966 already computes
row_amax; this PR derives thescale from it with
frexp/ldexp/whereunconditionally. A row that needs noscale gets exactly
1.0, which is the identity, so its FP16 conversion staysbit-exact and the rescale leaves it untouched.
Fixes #4955.
What Changed
gptqmodel/nn_modules/exllamav3.py:_native_bf16_input()now reducesvector_norm(inf)per row on the device and derivesoutput_scale = where(row_amax > bound, ldexp(1, frexp(row_amax / bound).exponent), 1)unconditionally. There is no
float(),.item()orbool()of anactivation per forward any more.
isfiniteis now a warmup probe: it runs once per module, on its firstBF16 forward, instead of on every forward (a per-forward
isfiniteis thesame 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
isfiniteonce at load/warmup" option from the issue.
all-ones device tensor instead of
None(Nonestill means an emptybatch, and is still what a non-finite activation returns).
Noneand 1.0encode the same decision, so the two existing assertions that pinned the
literal
Noneare relaxed to accept either.forward()applies the rescaleunconditionally; at scale 1 it is
(out - bias) * 1 + biasin FP32, thearithmetic 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 decisionand 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):Green, this PR:
Full EXL3 suite (
tests/test_exl3_wide_input.py tests/test_exl3_bf16_prescale_4870.py tests/test_exllamav3*.py tests/test_exl3_*.py):origin/main@c52ae996dThe 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]andtests/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 awarm module (one
ExllamaV3Linear, M=1, K=N=4096):origin/mainLatency
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:
_native_bf16_inputA 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
cudaStreamSynchronizeper linear.Numeric equivalence
_native_bf16_inputon the pre-fix code vs this PR, same inputs:tests/test_exl3_native_nosync_4955.py::test_scale_decision_matches_the_pre_fix_codepins 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 theexisting
docs/exl3-wide-activation-dispatch.md(updated in this PR). No newpage is needed.
Review Requirements
Kernel Accuracy Requirements
test_ordinary_rows_of_a_mixed_batch_keep_fp16_accuracyreuses [QUALITY] #4817 (fix of #4767) EXL3 bf16->fp16 pre-scale is per-tensor with threshold 64: one outlier token pushes every other row into fp16 subnormals (layer rel err up to 9.7e-2 vs 3.5e-3; Llama-1B PPL 18.855 vs 18.797) #4870'sfixture (64 rows of N(0, 0.3), one 1e4 outlier) and requires <= 5e-3 relative
error for the ordinary rows, which are bit-identical to
x.half().Notes
(112 in a 1B model, once), instead of one per linear per token.
through the native path and stays non-finite, like the FP32 path. This is the
documented trade-off of removing the per-forward
isfinite.