Skip to content

feat(quant): NVFP4 lanes on the TM channel — SM80 family, native global scales (SM75–SM90) - #5173

Open
windreamer wants to merge 28 commits into
stack/c6-graphfrom
stack/c7-nvfp4
Open

windreamer wants to merge 28 commits into
stack/c6-graphfrom
stack/c7-nvfp4

Conversation

@windreamer

@windreamer windreamer commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

Follow-up to #5171. The NVFP4 lane on the hybrid TurboMind channel, built ON #5142 (@richardclli) rather than parallel to it: all five commits cherry-picked with authorship preserved, and our SM80 family lands on their bridge — our independent port converged with it (nvfp4.h deltas were comment-only).

On top we added native per-tensor global scales across SM75/80/86/89/90: LlamaLinear::Arguments already plumbed global_scale end-to-end but every kernel impl discarded it; we consume it in the s16816 epilogue (per-group for grouped GEMM) and unify SM75/80 to the raw representation — SM90's family (upstream bc9a5548) already consumed global scales natively; the SM75/80 fold and its underflow guard are deleted (superseded). Numerics: the global factor applies in the epilogue after fp32 accumulation instead of folding into fp16 scales first — no subnormal loss on small scales.

Depends on #5142: this branch carries #5142's five commits cherry-picked. Once it merges, we rebase onto main and the diff reduces to our NVFP4 layers.

Modification

  • feat(turbomind): support SM75 NVFP4 dense and grouped GEMM #5142 ×5 (cherry-picked, pristine — patch-id verified): NVFP4Format, converter acceptance, SM75 family, dense+grouped builders.
  • SM80 NVFP4 family (823eb3ba equiv.): Config_NVFP4 + nvfp4_packer + family registration on their bridge.
  • Native global scales (3 commits): s16816 epilogue consumes Arguments.global_scale (null → bit-identical fast path; TM_CHECKed [1,1] fp32, per-group resolution for grouped GEMM); SM75+SM80 flip to raw e4m3 + reciprocal-global in the bundle; the fold and its underflow guard are deleted (superseded). Kernel-level proof: native GEMM vs fp32 first-principles reference ≤1e-2 on SM86; the retired fold emulation agrees. Grouped per-expert global scales: addressing verified end-to-end (SM75/80/86 s16816 epilogue ≡ SM90 mixed kernel param_G), deterministic grouped proof added with a wrong-scale sensitivity control.
  • Guards: w1/w3 merge rejects differing/mixed-presence global scales (the merged layout has one gs slot); fuse_weight rejects gs-carrying bundles (fused-SiLU cannot carry a global scale); AliasLinear carries gs through meta-pack aliasing with an all-or-none LinkLinearExperts presence check.
  • PT engine entry (nvfp4 half): from_config parses nvfp4-pack-quantized; dispatch + PT route through the TM channel (checkpoint-suffix params load raw).
  • Deferred (named): PT MoE grouped route for ct_fp8-models; per-tensor W8A8 CT.

BC-breaking

None. (Note: dtype resolution — models without torch_dtype resolving bf16-before-fp16 — lands in #5177, not this PR.)

Use cases

  • PT engine: NVFP4 (QUASAR-QAT/Qwen3.5-4B-QUASAR-NVFP4) loads and generates on SM86; PT and TM engines share the TurboMind GEMM channel — outputs agree semantically while per-token bitwise equality is not expected across engines.
  • TM engine: NVFP4 on SM75–SM90 (native global scales) — the QUASAR checkpoint loads directly.
  • Registry probes on SM86 accept NVFP4 dense+grouped (K-align 16).

Checklist

  1. Pre-commit or other linting tools are used to fix the potential lint issues.
  2. The modification is covered by complete unit tests: NVFP4 native kernel proof (dense + grouped, wrong-scale sensitivity control), format contract suite, w1/w3 guard matrix (mismatched raises / equal merges / mixed-presence raises / both-absent merges), PT parse/dispatch tests; the cherry-picked bases were patch-id audited against upstream — pristine.
  3. No new downstream dependencies.
  4. Documentation updated accordingly (nvfp4.h/convert_v3.cu comments aligned with the native convention; env matrix docstring).

@windreamer
windreamer added this pull request to stack #5162 November 19, 2026 12:00
@windreamer windreamer changed the title feat(turbomind): add NVFP4 weight format feat(turbomind): NVFP4 SM80 family and CT per-channel FP8 via the TM channel Nov 19, 2026
@windreamer windreamer changed the title feat(turbomind): NVFP4 SM80 family and CT per-channel FP8 via the TM channel feat(quant): NVFP4 and CT-FP8 lanes on the TM channel — native global scales, PT engine entry Nov 19, 2026
@windreamer
windreamer removed this pull request from stack #5162 November 20, 2026 05:16
@windreamer
windreamer added this pull request to stack #5178 November 20, 2026 05:16
@windreamer windreamer changed the title feat(quant): NVFP4 and CT-FP8 lanes on the TM channel — native global scales, PT engine entry feat(quant): NVFP4 lanes on the TM channel — SM80 family, native global scales (SM75–SM90) Nov 20, 2026
windreamer added a commit that referenced this pull request Nov 23, 2026
A fused single-key checkpoint (e.g. in_proj_qkv.weight_global_scale [1])
loads with no shard id; the old default shard_id='q' wrote slot 0 only
and _lane_shards packed torch.empty garbage into k/v shards (NaN forward,
falsifying the byte-exact-vs-TM claim). global_scale_loader now defaults
shard_id=None and broadcasts the scalar into every slot; explicit shard
ids keep per-slot routing (QUASAR's unfused q/k/v_proj keys). The
identical QKV override is deleted — inherited behavior covers both.

qwen3_5.py: the numel < sum(sections) guard claimed to handle per-tensor
metadata but never ran (float-lane modules bind gs params to
global_scale_loader, never to the section-splitting loader); removed
honestly with a note.

Folded from build/stack-review/patches/fix-5173-p1.patch (patch-id
78e9b6ef; PR #5173 review F1, verified by R5173 + independent fix agent).
windreamer added a commit that referenced this pull request Nov 23, 2026
…e control

_quantize_nvfp4 kept the historical missing-gs construction (groups /
scale) -> 0.0% nonzero magnitude codes; the kernel proof passed
vacuously (codes == ref == 0, wrong-scale changes nothing). Aligned to
the TM-side helper (codes = round(w * gs / scale)), 46.2% nonzero codes.

New tests: test_quantizer_produces_nonzero_codes (the vacuous-proof
detector), test_plain_wrong_global_scale_is_loud (8x wrong epilogue gs
must move the output far from ref), TestQkvGlobalScale (fused broadcast
reaches all 3 shards; per-slot shard_id routing preserved). The merged
per-shard gs test now dequantizes refs with the loaded slot values
instead of the quantizer gs (second vacuous-proof repair).

Folded from build/stack-review/patches/fix-5173-p1.patch (PR #5173
review F2, verified by R5173 + independent fix agent).
windreamer added a commit that referenced this pull request Nov 23, 2026
The C++ supports_nvfp4 bridge and prepare_weight(global_scale=None)
accepted a raw bundle without a per-tensor global scale silently: the
epilogue skips its multiply and every output is off by gs.

Python-side loud gates (no C++ change):
- NVFP4Format.finalize raises on a missing global_scale and on a
  non-finite one. Format dispatch never selects nvfp4 without
  .weight_global_scale (accepts rejects it), so reaching finalize
  without gs means an incomplete bundle; other families keep their
  null fast-path finalize untouched.
- TmQuantLinear initializes weight_global_scale to NaN instead of
  torch.empty and update_weights refuses to pack any non-finite slot:
  a checkpoint that never delivers a shard's gs fails at prepare with
  an actionable error instead of packing garbage (PR #5173 review F4).

Regression tests: test_nvfp4_finalize_rejects_gs_less_bundle_loudly,
test_gs_less_bundle_raises_at_prepare. Both fail pre-fix (finalize
returned the bundle unchanged; the empty-init slot read 4.8e-29 and
passed the isfinite check).
richardclli and others added 27 commits November 25, 2026 16:46
Detect compressed-tensors nvfp4-pack-quantized (4-bit float, group 16)
and map it to model_format='nvfp4'. Keep the existing pack-quantized
int4 path unchanged.
Add Config_NVFP4 and the nvfp4 packer for E2M1 weights with group-16
fp16 scales, registered on the sm75_16816_4 dense u4 tiling. Keep fp16
scales intact in PackQParams so the MXFP4 e8m0 fix-up is not applied.

The row-major packed B (align.y = 1) lets the fused GDN projection run
directly on the 4-bit kernel; no dequant fallback is needed.
Call the format's finalize() hook after resolving the weight bundle, so
NVFP4 folds the per-tensor global scale into fp16 block scales before
packing. The default hook is an identity, so other formats are
unchanged.
Add Config_NVFP4_g and the nvfp4_g family for grouped MoE expert FFNs,
reusing the dense NVFP4 packed-B layout and group-16 fp16 scales on the
grouped u4 tiling.
- Port the NVFP4 family onto #5142's SM80 lane: Config_NVFP4 (Operand_A_Pack<fp4_e2m1_t> + Operand_UV_Pack<uint16_t> folded-fp16 scales, group 16, half compute) reusing the MXFP4 tiling list with align_k tightened to 16, registered as family 40 for dense and grouped (SM80/86/89).
- The bridge (kernel/nvfp4.h) and the guarded e8m0 convert_v3.cu fixup already landed with #5142's SM75 family; only this lane was missing.
- Evidence: get_weight_plan accepts {kFloat4_e2m1,{16,1},kFP16} dense+grouped on SM86 (K-alignment 16 = the NVFP4 group size); QUASAR NVFP4 e2e canary 3/3.
- Declare the nvfp4 class in the unified LMDEPLOY_TM_KERNELS matrix (ct nvfp4-pack-quantized checkpoints, SM80 family), no legacy env, defaulting to auto, mirroring the w4a16/moe_grouped precedent.
- The converter nvfp4 arm consults the class state: off raises loudly naming the offline-dequant alternative (the format has no non-TM fallback path), auto proceeds capability-based (downstream gemm.data_types/family probes stay the loud capability check), on is strict.

(nvfp4 half of the lane split; the CT FP8 half lands in the follow-up branch)
- KernelImpl::Launch forwards the per-group global scale into
  EpilogueParam; the epilogue multiplies the output by it after the
  alpha/beta combine (per-group via resolve, so grouped GEMMs read
  their own scalar). Null keeps the existing fast path, leaving every
  other family bit-identical; a non-null scale must be a [1,1] fp32
  layout (checked).
- supports_nvfp4 now accepts only the raw checkpoint layout (e4m3
  block scales + separate global scale) and returns a bridge that
  widens the scales to half -- exact, every e4m3 value fits fp16.
  The folded-kHalf representation matches no family anymore.
- The SM80 nvfp4 family (id 40) and both SM75 families (ids 13/14)
  flip to the native lane. The SM90 nvfp4 family (id 31, upstream
  bc9a554) already consumed raw scales + global via the mixed
  kernel, so all archs now share one representation.
- SM75 is compile-verified only (no SM75 hardware in tree); the
  kernels are the same s16816 family the folded lane used, with the
  global multiply moved from the Python fold into the epilogue.
… the bundle

- NVFP4Format.finalize no longer folds: it copies the bundle, keeps
  the raw e4m3 scales and stores 1/global_scale (fp32) as the module's
  global_scale, which the GEMM epilogue multiplies the output by. The
  checkpoint's weight_global_scale is a divisor, so the math
  (codes * scales / gs) is unchanged end to end, but small block
  scales no longer pass through fp16 subnormals.
- This removes the fold-underflow guard: with the fold gone there is
  no fp16 division to underflow. Supersedes fd4d1cb (raise on NVFP4
  fold underflow); its test is dropped with the fold in the test
  commit.
- dequant handles the native bundle (codes * scales * stored global)
  and prepare_weight grows a global_scale argument (dense and grouped)
  so the standalone Linear API can serve NVFP4.
- transform_output_dim bypasses per-tensor kinds (global_scale has no
  output dimension) and duplicates them into every output bucket, so
  fused GDN splits keep the scale instead of unflatten-crashing on it.
- Kernel-level proof on SM80/SM86: raw NVFP4 weights prepared through
  the native path (e4m3 scales + reciprocal global scale) match the
  fp32 first-principles reference (codes * scales / gs) and the
  retired fold emulation within 1e-2 on two shapes. Ignoring the
  scale would be off by ~gs, so this is the load-bearing check.
- Format tests: raw scales pass finalize untouched with the fp32
  reciprocal stored, no caller-dict mutation, dequant divides by the
  checkpoint global scale, and the raw-format plan query selects the
  native bridge (fp16 widening) while the retired folded format has
  no family. The fd4d1cb underflow test is dropped with the fold.
- transform_output_dim unit test: global_scale bypasses split_qkv and
  lands in every output Linear.
- Restructure _parse_compressed_tensors_config into a per-format dispatch: pack-quantized keeps its historical validation (extracted into _validate_pack_quantized_group), the nvfp4-pack-quantized branch validates the weight-only float layout (num_bits 4, group 16, tensor_group), and shared ignore/weights validation is hoisted.
- QuantizationConfig carries the parsed ct_format; get_quant_method dispatches nvfp4 for linear and moe kinds (norm -> None, ignore rules unchanged), and load_normalize stays off for the float lane so raw checkpoint suffixes reach the modules.

(nvfp4 half of the lane split; the CT float-quantized half lands in the follow-up branch)
- `Linear._normalize_params` now runs the weight format's `finalize` last, so `prepare_weight`/`fuse_weight` consume raw checkpoint-layout tensors end to end: per-channel FP8 scales expand to the K-grouped kernel layout and the NVFP4 per-tensor global scale (a divisor) becomes the epilogue reciprocal inside the call.
- The native NVFP4 forward test passes the raw checkpoint global scale instead of the pre-finalized reciprocal, matching the new single convention (the builder path already finalized on its side).
- New TmQuantLinear/MergedTmQuantLinear/QKVTmQuantLinear modules (shared float-lane infra) register checkpoint-suffix parameter names (weight_packed/weight_scale/weight_global_scale), so raw checkpoint keys load with no stream-level renaming; merged projections keep one packed handle per shard because NVFP4 global scales are per checkpoint module, and forward concatenates shard outputs.
- New CUDA backend impl TurbomindQuantLinearImpl packs via Linear.prepare_weight and serves nvfp4 (fp16 compute, python-side input conversion). The build consults the nvfp4 TM kernel class: off raises naming the offline-dequant alternative, auto/on probe the registry and fail loudly when no family accepts the plan.
- build_linear/build_merged_colwise_linear/build_qkv_proj dispatch nvfp4; routed experts raise a named NotImplementedError until a PT grouped module exists. Qwen3.5 GatedDeltaNet builds pass canonical prefixes (ignore-rule dispatch requires them), and the fused in_proj_qkv loader passes per-tensor metadata through untouched.
- Kernel-level numeric proof on SM86 for the nvfp4 lane plus loader/env-gate coverage in tests/pytorch/nn/test_tm_quant_linear.py.

(nvfp4 half of the lane split; the CT FP8 route hunks land in the follow-up branch)
…e convention

The nvfp4.h pack comment and the convert_v3.cu kHalf-branch comment still described the retired fold design (SM75 folded, global pre-folded). Since the three-arch unification, every NVFP4 family arrives with raw e4m3 scales exact-widened to half and the global scale is consumed in the epilogue; comments now say so.
The merged w1w3 layout has a single per-tensor global-scale slot and
transform_output_dim keeps only the first input's per-tensor tensors, so
separately-quantized gate/up with differing global scales silently
applied the gate's scale to the whole fused output in the GEMM epilogue.
Raise a loud ValueError at the merge point; fused checkpoints sharing one
scale (QUASAR) keep merging.
AliasLinear copied weight/bias/scales/zeros but dropped the per-tensor
global_scale, so aliased quantized experts reached LinkLinearExperts with
an empty scale and the GEMM epilogue silently skipped its multiply. Also
guard LinkLinearExperts against mixed global_scale presence: the linked
{n}-expert scale table is indexed by expert id, and a single expert
missing its scale would shorten the table and read out of bounds.
Add the grouped (MoE) proof: three experts with 10x-stepped amplitudes
(pairwise-distinct per-tensor global scales), uneven int32 offsets, exact
quantized reconstruction within 1e-2, and a mandatory wrong-scale
sensitivity control asserting the shared-gs error exceeds 1.0.

Fix _quantize_nvfp4 while at it: codes must be round(w * gs / scale);
the historical groups/scale missed the global-scale factor, collapsing
negative and small-amplitude weights onto the zero code (the dense proof
passed vacuously). With the fix the dense proof exercises real codes.
fuse_weight now accepts a global_scale argument that must stay None: the
fused-SiLU lane has one per-tensor scale slot and one scalar cannot serve
two differently-scaled projections, so a globally scaled bundle must use
the split path. Pure insurance today (nvfp4 disables gate_up fusion and
AWQ bundles carry no global scale); the full plumb is future work if a
fused globally-scaled family ever lands.
(nvfp4 half of the lane split; the CT FP8 parity-gate half lands in the follow-up branch)
From the C7FixBatch verification review (P2): the guard returned early when
exactly one of gate/up carried a per-tensor global_scale, silently merging —
transform_output_dim adopts the first input's scalar, so a gate-only gs
mis-scaled the whole fused output and an up-only gs was silently dropped.
Mixed presence now raises, matching the all-or-none convention
LinkLinearExperts enforces; both-absent still merges without gs semantics.
Test updated: one-sided raises both ways, both-absent plain merge asserted.
- The checkpoint-layout quant params are CPU-resident and the single source of truth (single occupancy): the TurboMind channel packs from the host via its device-agnostic prepare_weight; module moves pin the quant params so the engine's to(cuda) never re-uploads them; sleep/wakeup re-pack from the unchanged host params -- the torch-weight spill machinery is not needed on this path.
- Gated by the CPU-source parity probes (nvfp4 raw-e4m3 + reciprocal-global dense; grouped nvfp4 covered by the grouped proof).

(nvfp4 half of the lane split; the CT FP8 packing half lands in the follow-up branch)
A fused single-key checkpoint (e.g. in_proj_qkv.weight_global_scale [1])
loads with no shard id; the old default shard_id='q' wrote slot 0 only
and _lane_shards packed torch.empty garbage into k/v shards (NaN forward,
falsifying the byte-exact-vs-TM claim). global_scale_loader now defaults
shard_id=None and broadcasts the scalar into every slot; explicit shard
ids keep per-slot routing (QUASAR's unfused q/k/v_proj keys). The
identical QKV override is deleted — inherited behavior covers both.

qwen3_5.py: the numel < sum(sections) guard claimed to handle per-tensor
metadata but never ran (float-lane modules bind gs params to
global_scale_loader, never to the section-splitting loader); removed
honestly with a note.

Folded from build/stack-review/patches/fix-5173-p1.patch (patch-id
78e9b6ef; PR #5173 review F1, verified by R5173 + independent fix agent).
…e control

_quantize_nvfp4 kept the historical missing-gs construction (groups /
scale) -> 0.0% nonzero magnitude codes; the kernel proof passed
vacuously (codes == ref == 0, wrong-scale changes nothing). Aligned to
the TM-side helper (codes = round(w * gs / scale)), 46.2% nonzero codes.

New tests: test_quantizer_produces_nonzero_codes (the vacuous-proof
detector), test_plain_wrong_global_scale_is_loud (8x wrong epilogue gs
must move the output far from ref), TestQkvGlobalScale (fused broadcast
reaches all 3 shards; per-slot shard_id routing preserved). The merged
per-shard gs test now dequantizes refs with the loaded slot values
instead of the quantizer gs (second vacuous-proof repair).

Folded from build/stack-review/patches/fix-5173-p1.patch (PR #5173
review F2, verified by R5173 + independent fix agent).
The C++ supports_nvfp4 bridge and prepare_weight(global_scale=None)
accepted a raw bundle without a per-tensor global scale silently: the
epilogue skips its multiply and every output is off by gs.

Python-side loud gates (no C++ change):
- NVFP4Format.finalize raises on a missing global_scale and on a
  non-finite one. Format dispatch never selects nvfp4 without
  .weight_global_scale (accepts rejects it), so reaching finalize
  without gs means an incomplete bundle; other families keep their
  null fast-path finalize untouched.
- TmQuantLinear initializes weight_global_scale to NaN instead of
  torch.empty and update_weights refuses to pack any non-finite slot:
  a checkpoint that never delivers a shard's gs fails at prepare with
  an actionable error instead of packing garbage (PR #5173 review F4).

Regression tests: test_nvfp4_finalize_rejects_gs_less_bundle_loudly,
test_gs_less_bundle_raises_at_prepare. Both fail pre-fix (finalize
returned the bundle unchanged; the empty-init slot read 4.8e-29 and
passed the isfinite check).
- `QuantizationConfig.from_config` bound `ct_format` only inside the compressed-tensors branch but always forwarded it to the constructor, so every awq/gptq/fp8/modelslim/smooth_quant checkpoint raised `UnboundLocalError`.
- Initialize `ct_format = None` next to the other optional fields; non-ct configs keep reporting no compressed-tensors format.
- TmQuantLinear.__init__ gains internal out_features_local: callers that pass
  already-distributed sizes (MergedTmQuantLinear._update_all_out_features, QKV
  head widths) no longer get divided a second time; plain linear path unchanged
  (PR 5173 review thread 4691023864).
- Regression: mocked-rank TP=2 rank-0 loader tests for merged gate/up and fused
  QKV (red pre-fix: allocation halved, split fails).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants