Skip to content

feat(moe): serve gpt-oss MXFP4 experts through the TurboMind channel - #5174

Closed
windreamer wants to merge 36 commits into
stack/c7-nvfp4from
stack/c8-mxfp4
Closed

windreamer wants to merge 36 commits into
stack/c7-nvfp4from
stack/c8-mxfp4

Conversation

@windreamer

@windreamer windreamer commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

8th of the series (follow-up to #5173). gpt-oss-20b (MXFP4: e2m1 codes + e8m0 group-32 scales) could run on the TurboMind engine but not the PyTorch engine — the bf16-dequant alternative needs 38.2 GB of expert weights, dead on 24 GB cards. This PR grafts the existing SM80/86 mxfp4 C++ family (registered as-is at sm80_16816_4.cu, bf16 compute, supports_mxfp4 + mxfp4_packer) onto the PyTorch engine's grouped MoE route: zero new kernel code on either side — the same MXFP4Format the TM engine loads with packs the weights byte-identically, and the TurboMind engine on the same GPU serves as the golden baseline (PT↔TM cross-check in place).

Modification

  • Config/dispatch: quant_method: mxfp4 parses (implicit block 32, bf16 compute placeholder); get_quant_method sends linear/norm to bf16 passthrough and moe to the mxfp4 route. The dtype-less auto fallback now mirrors the TM converter's capability rule (bf16 when supported), so both engines resolve a dtype-less checkpoint identically.
  • Kernel switch: the LMDEPLOY_TM_KERNELS mxfp4 class gets its consumer — off raises naming the offline-dequant alternative, auto probes the grouped registry, on is strict.
  • Implementation (TurbomindMoeMXFP4Impl): mirrors the proven W4A16 grouped lifecycle (pack-once, sticky fused-SiLU probe only for plain-SiLU models, hot-update publish sync, sleep/wakeup re-pack). gpt-oss's clamped activation takes the split gate/up path with python-side act; expert bias applies at slot granularity and frees with the handles. _slot_experts keeps a static slots-length output with the sentinel bin parked at expert 0 — removing both the EP bias-gather crash and the graph-capture D2H sync from repeat_interleave (no output_size forces a device-to-host size read mid-capture).
  • Loader: gpt_oss suffix dispatch checks _blocks/_scales before the plain-projection substring (the substring false-catch crashed on packed uint8), flattens the 4D grouped block layout, deinterleaves gate/up at load. process_weights_after_loading sweeps the caching allocator per spilling module so the native pack allocations stay under VRAM.

BC-breaking

One default changes: a model config without torch_dtype now resolves bf16-before-fp16 (capability-based), mirroring the TurboMind converter — both engines then agree on one checkpoint. All fixtures in-tree pin their dtypes; no test asserted the old fp16 fallback.

Use cases

gpt-oss-20b serves through the PyTorch engine on a 24 GB GPU (packed experts 10.3 GB): native e2e greedy generation matches the TurboMind golden byte-for-byte on 5/6 prompts (the sixth diverges only at token 20/24 on a whitespace variant of the same word), CUDA graphs on, no OOM. 19 new tests: kernel parity vs the fp32 dequant reference (including sentinel routing), route env matrix, loader suffix dispatch, CUDA-graph capture with bitwise replay.

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 (see above), two independent review rounds (7/10 → 9/10 COMMIT-READY) with a runtime revert-check proving the sentinel regression test bites, and the PT↔TM e2e cross-check described above.
  3. No new downstream dependencies.
  4. Documentation updated accordingly (env matrix docstring; loader and spill comments).

windreamer and others added 19 commits November 19, 2026 17:34
- Group-128 compressed-tensors dense checkpoints normalize to the canonical AWQ layout at load time (ct_repack), so the TurboMind W4A16 channel serves them without an offline conversion step.
- The normalization is opt-in per load entry point - initial, draft, memdecode, hot-update buckets and update_params - gated on quant method == compressed-tensors with group size 128, so fp8-static weight_scale parameters and group-32 packed ct keys (MoE experts) pass through untouched.
- ct_to_awq allocates on the source device, keeping CUDA hot-update streams intact.
- The compressed-tensors dispatch sends group-128 dense linears to the awq family; group 32 keeps the packed ct modules. Hot-update buckets flow through the same translation on all update paths.
- Tests: ct->AWQ round-trip and staging-order unit tests, a seeded tiny ct checkpoint generator, and engine-level gates (conversion, TM route, spill, hot-update A-B-A roundtrip, CUDA-graph replay) sourced from one public AWQ checkpoint via HF/ModelScope.
…across shards

Force fp16 only for compressed-tensors checkpoints whose group_size is 128: those normalize into the fp16 AWQ family. Group-32 packed-ct keeps its configured dtype, restoring bf16 (and DeepEP) deployments the blanket force broke.
Let normalize_ct_weights carry staging across calls through a shared state so a linear whose weight_packed/weight_scale split across safetensors shards converts instead of failing checkpoint-integrity validation; load_model_weights spans one state over all shards and finalizes after the loop. The single-call contract is unchanged.
Guard the group_size extraction against malformed config_groups so a broken checkpoint fails with the parser's ValueError instead of an AttributeError before it can raise.
…nd gate the eager reference

Validate and consume per-linear weight_shape metadata during ct normalization instead of forwarding it: AWQ modules have no such parameter and real llm-compressor exports carry it. The tiny HF fixture now includes the metadata so the load path is covered.
Keep one ct staging state per update transaction: a module split across update buckets no longer fails with an incomplete-shard error, staged tensors clone their storage so reused IPC buffers cannot corrupt them, and _finalize_updated_weights validates leftovers and resets the state.
Move the pure-torch AWQ unpack helpers into ct_repack so test collection and awq_dequant work on installations without the TurboMind extension; weight_format re-exports them.
Run the golden gate reference pipeline with eager_mode instead of clearing capture batch sizes, which merely restored default capture sizes and kept the graph runner active.
Update the weight-update test fixtures to the current agent contract (model_config and ct staging state).
- GPTQ dense checkpoints repack to the canonical AWQ layout at load time (gptq_repack): pack axis, nibble order, and the zero-point offset are absorbed in-flight, so the AWQ and TurboMind W4A16 channels serve GPTQ without an offline conversion.
- The repack rejects desc_act (act-order) checkpoints loudly and verifies geometry on demand with a synthesized symmetric zero reference.
- GPTQ dispatches dense linears to the awq family and honors ignored modules; MoE keeps the raw method and fails loudly (no GPTQ MoE implementation). bits != 4 is rejected at parse.
- The load-time repack gate is QuantizationConfig.load_normalize(), shared by the initial, draft, memdecode, and hot-update paths; fp8-static and group-32 ct keys pass through untouched.
- Tests: repack round-trips and trap guards (nibble order, zero offset, geometry rejections, desc_act), kernel parity on CUDA, and config dispatch; the TM cross-check skips cleanly without a built extension.
… route MoE through AWQ

Accept AutoGPTQ's identity group-index buffers: a non-decreasing consecutive g_idx is the default no-act-order export and is consumed; only a reordered mapping raises. desc_act is also rejected at config parse.
Keep a staged GPTQ module until its components arrive instead of flushing on the next prefix: shard and bucket boundaries can interleave a module's tensors, and an early flush synthesized a wrong asymmetric pad.
Allocate repacked outputs on the input device so hot-update IPC tensors do not mix CPU and CUDA operands, and gather quant components across all safetensors shards in convert_checkpoint: the converted output is a single model.safetensors with the quant config rewritten to AWQ and identity g_idx dropped.
Route GPTQ MoE through the AWQ family like dense linears: normalize_gptq_weights covers expert prefixes, so grouped experts land on the same verified route as ct group-128.
…oad fake

- c3 renamed the load-time normalization kwarg normalize_ct -> normalize_quant (d4fea0f); the fake fixed for the c2 signature went stale again from this branch up.
- Follows the c2 fix (8cf6d79 pre-restack) which is still correct at its own layer; this commit adapts the same fake to the c3+ signature so the test stays green through c4/c5.
- Route the AWQ + MoE combination to TurboMind's grouped GEMM: expert tensors pack once into the channel (g128 layout, fused gate/up where the device exposes a gated-silu family, separate w1/w3 handles otherwise), forward runs the blocked slot layout and reduces in fp32.
- The moe_grouped class of LMDEPLOY_TM_KERNELS decides the route; a declined route keeps the historical unsupported error with the probe reason attached.
- DeepseekV2 marks kv_b_proj as an MLA-absorption module so its torch copies stay resident for get_unquantized_weight.
- Tests: impl-level gate against an elementwise fp32 reference on the GLM-5.3 sparse geometry, triton fused_moe route anchors, routing under the three states, and an engine-level golden gate comparing the tiny ct MoE checkpoint against its unquantized twin.
…publish

Give FusedMoETmW4A16 sleep_release/sleep_wakeup hooks so ModelAgent's module walk frees the packed native expert handles before Module.to and restores, re-packs, and re-spills after the model returns, mirroring the dense route's steady state.
Pack grouped expert weights into locals and publish all handles only after a stream synchronize on hot updates: forward reads the handle fields directly, so in-flight packing must never be visible to a concurrent forward.
Add a no-op sleep_release to the grouped-impl protocol and guard __del__ with a device context plus a handle-existence check so a pack that failed mid-way cannot leak its handles.
…ct the g32 anchor

Propagate spec.output_dtype through the grouped builder into the implementation and use it for the weight plans: the scales' storage is always fp16, so reading the plan dtype from scales handed an accepted bf16 route fp16 expert handles that fail the native input-dtype check.
Defer the TurboMind channel imports behind an availability loader: weight_format dereferences the native extension at module scope, so importing the MoE backend crashed PyTorch-only installations before the route could decline. The route now falls back to the triton MoE with the availability reason.
Quantize the packed-g32 test anchor zero-centered: the packed kernel decodes (code - 8) * scale, so min-shifted codes compared different weights instead of a different quantization group size.
Add a GPTQ-MoE numeric gate: gptq_to_awq-converted expert tensors ride the grouped route against their dequant reference, closing plan item 'GPTQ MoE dispatch' acceptance.
- TmMoeWeights grows the EP view (num_local_experts / first_local_expert / expert_map), modeled on the compressed-tensors route; the loader now accepts rank-local experts only - foreign keys are skipped before the ledger, a missing local key still fails the loud completeness check, and out-of-range global ids raise.
- Forward remaps global expert ids to local slots before blocked_route: the TM blocked slot layout indexes prefix sums by raw expert id (spike S10), so under EP the remap (with the sentinel moved to num_local_experts) is what keeps foreign routes inside the zeroed skip block instead of silently corrupting the sum.
- EP combine is a single all-reduce over the ep group: DistConfig forces world_size == ep, so the group is the whole world and per-rank partials are disjoint additive contributions. The ep>1 + moe_tp>1 corner is now a loud guard - expert blocks and moe-TP width shards cannot co-exist (each expert would materialize at partial width on one rank).
- Divisible-experts, dp>1 (DP attention needs all-to-all), EPLB and microbatch keep loud raises; the route boundary comment is rewritten and the sync-only wait() contract is untouched.
- Tests: in-process EP=2 (two rank modules over disjoint expert subsets, full global weight stream through the real loader) vs an ep=1 monolith aligns within 1e-6 at tokens=1 (2.4e-7) and tokens=64 with 45 split routes (4.8e-7); loader filtering/mapping/completeness, combine-group, and four build-guard cases.
… path

- qwen2_moe threads quantization_config into build_fused_moe like its siblings (qwen3_moe, mixtral); without it the GPTQ MoE dispatch never left the default dense route and a 7.8 GiB checkpoint OOMed building ~20 GB of bf16 experts.
- The checkpoint ships verified-zero bias tensors for the bias-free expert linears (4320 keys, GPTQ artifact): drop them behind an exact abs().max() == 0 gate, raise loudly on any non-zero orphan, and keep the loud KeyError for every other unmatched name.
- _is_sequential_g_idx now honors its own documented contract: arange(n) // run_len blockwise-identity buffers (Qwen1.5-MoE materializes g_idx with per-proj group sizes 128/32) are the identity mapping and are consumed; act-order permutations and shifted buffers still reject.
- The shared-expert add is rank-normalized: both W4A16 impls promote 2D input to [1, m, n] ("always 3D"), while the fused experts stay [m, n]; reshaping the add makes the model shape-independent of which backend impl the selector picked.
- Evidence: pipeline e2e on Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4, PyTorch engine vs TurboMind engine, 4 prompts x 100 greedy tokens, zero NaN; prompts 2/3 byte-identical, prompt 1 common prefix 1256/1348 chars. Regression: 58 passed / 1 pre-existing skip across the moe/gptq/golden-gate suites; ruff clean.
…oute

- DLPack exports in the captured path now pass the consumer stream explicitly: ExportDLPack in bind.cpp (kDLCUDA guard, pointer-0 legacy fallback, TypeError fallback) and _from_dlpack at every import site in the Linear API. Behavior-neutral outside the pytorch/pytorch#150217..#163242 window (verified against the installed torch 2.12.1 source) and required for the pinned 2.0.0-2.12.1 range; stream handles carried at full width (LLP64-safe).
- PiecewiseGraphManager.prepare runs eager warmup under the exact stream capture will use: a cold TurboMind call inside capture would run the per-stream workspace ctor cudaStreamSynchronize and abort the process (reproduced, pinned by a subprocess test). The full-graph path already co-streams warmup and capture; the invariant is now documented and tested.
- graph_runner README documents that TM packed expert weights are non-tensor native handles invisible to tensor-based reset checks; hot updates and sleep/wakeup must reset the graph runner around the swap.
- In-piece capture: FusedMoETmW4A16Impl stays invisible to piecewise discovery and captures as ordinary kernels (TritonFusedMoEImpl precedent). #5149 audit: the TM route consumes no valid-token/mask binding - sentinel-only capture replays real routing bitwise-equal, and dummy-capture-to-real-replay is pinned by test.
- Evidence: capture/replay bitwise equality (acceptance 5), #5149 scenario, subprocess cold-capture abort pin, PCG warmup_iterations=0 flow; stack regression 45 passed / 2 hardware-capability skips, full-graph suites 366 passed, piecewise suites 100 passed; ruff clean.
Add NVFP4Format for compressed-tensors nvfp4-pack-quantized checkpoints:
E2M1 weights, group-16 fp16 block scales after folding the per-tensor
global scale, and a dequant reference for mixed-format fusion. Keep the
per-tensor global scale out of TP splits.

Add CPU coverage for the format contract, the E2M1 dequant table, and
the global-scale folding.
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.
bltcn and others added 8 commits November 19, 2026 20:33
…P8 (Ornith)

Some compressed-tensors checkpoints (e.g. Ornith-1.5) store FP8 weights in
the float-quantized format with a per-output-channel .weight_scale
(BF16, shape [N, 1]) instead of the blocked .weight_scale_inv
([K//128, N//128]). The converter rejected them outright
(pack-quantized-only assert) and the FP8 path did not recognize the
.weight_scale key.

- converter: accept float-quantized 8-bit float compressed-tensors groups
  (group_0 / config_group_0), map to FP8Format(block_out=1) for
  per-channel and block_out=128 for blocked
- FP8Format: recognize .weight_scale, accept per-channel [N, 1] scales,
  add post_process hook that expands per-channel scales to the K-grouped
  kernel layout [K//128, N] (identical rows; weight bytes unchanged)
- WeightFormat: identity post_process hook on the base class

The C++ side already supports per-channel FP8 (groupwise 128x1 e4m3,

(cherry picked from commit 086de96)
…_process

normalize() transposes 2-D tensors to TM layout before post_process runs, so
the per-channel weight_scale [N, 1] reaches the hook as [1, N]. Match the
transposed shape when expanding to [K//128, N]; guard also rejects any
other layout instead of crashing on expand.

(cherry picked from commit dc6e9b9)
…ors float-quantized checkpoints

Ornith-style checkpoints carry quant_method=compressed-tensors with
float-quantized FP8 weights. The production startup script passes an
explicit --model-format fp8, which previously hit the strict
'user input == quant_method' assert. fp8 and compressed-tensors float-quantized
are the same underlying format, so accept the override; the float-quantized
branch still validates 8-bit float weights.

(cherry picked from commit 807189e)
CI lint/unit_test fixes for the per-channel FP8 PR:
- converter.py: wrap the _build_quantized_formats signature to respect the
  120-char line-length limit (ruff E501).
- test_fp8_per_channel.py: sort imports (ruff I001) and fix the two test
  cases that call FP8Format.post_process / dequant directly to pass the
  normalize()-transposed per-channel scale [1, N] (not the raw [N, 1]);
  this matches the production path where normalize() transposes 2-D
  tensors to TM layout before post_process runs.

Verified in a real-CUDA container (lmdeploy 0.18.0, cu128): all 6 tests
pass; regression A/B (patched vs pristine) on the existing linear tests is
identical (1 pre-existing skip-path failure in both), so the patch breaks
nothing.

(cherry picked from commit 1a6b71f)
CI lint's docformatter hook (v1.7.7, --wrap-descriptions 120) requires a
blank line after the summary sentence of the base-class post_process
docstring I added. Split it into summary + body so pre-commit passes.

(cherry picked from commit 8fde62a)
Re-apply the true delta of our earlier 8450610 on top of bltcn's #5018
commits (community-first re-stack):

- The hook is named `finalize` (the base convention NVFP4Format already
  uses and _build_linear already invokes) instead of bltcn's
  `post_process`: rename the FP8Format override, drop the now-redundant
  identity base-class `post_process` hook, and update their tests.
- Keep our extra coverage that bltcn's chain lacked: the blocked format
  must reject a per-channel scale, `_build_quantized_formats` must build
  the blocked (fp8_block_out=128) CT arm, the builder path
  (normalize -> finalize) must yield K-grouped scales, and a native
  per-channel FP8 forward check against the dequant reference on SM86.

No converter changes: the nvfp4 coexistence was already resolved inside
the cherry-picks, and the ct_fp8 env gate lands separately in the
upcoming kernel-switch commit.
…ernel switch

- Declare two new classes in the unified LMDEPLOY_TM_KERNELS matrix: nvfp4 (ct nvfp4-pack-quantized checkpoints, SM80 family) and ct_fp8 (compressed-tensors float-quantized FP8, per-channel/blocked), both with no legacy env and defaulting to auto, mirroring the w4a16/moe_grouped precedent.
- The converter arms consult their class state: off raises loudly naming the offline-dequant alternative (neither format has a non-TM fallback path), auto proceeds capability-based (downstream gemm.data_types/family probes stay the loud capability check), on is strict.
- Evidence: tm_kernel_state semantics verified (defaults auto, per-class off/on override, global off propagation, cross-class isolation); converter nvfp4 arm raises under nvfp4=off and returns NVFP4Format under auto; ct_fp8=off/on semantics verified; nvfp4+fp8 suites 17 passed; TM linear/routing regression 44 passed.

(cherry picked from commit 855470d)
- 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.
- `_parse_compressed_tensors_config` gains two format branches alongside the byte-identical `pack-quantized` validation: nvfp4 (4-bit float tensor_group, group 16) and float-quantized FP8 (per-channel `channel` or 128-blocked), rejecting static input activation schemes and int weights. Unknown top-level keys (`producer`, `sparsity_config`, `transform_config`, `kv_cache_scheme`) are tolerated.
- `QuantizationConfig` carries the parsed `ct_format`; `get_quant_method` dispatches nvfp4/ct_fp8 for linear and moe kinds (norm -> None, ignore rules unchanged), and `load_normalize` stays off for the float lanes so raw checkpoint suffixes reach the modules.
- `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 register checkpoint-suffix parameter names (`weight_packed`/`weight_scale`/`weight_global_scale`, or `weight`/`weight_scale` for FP8), 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) and ct_fp8 (bf16 compute, fp8 input query, in-kernel dynamic activation quant). The build consults the same `nvfp4`/`ct_fp8` TM kernel classes as the converter arms: 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`/`ct_fp8`; 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 both lanes plus loader/env-gate coverage in tests/pytorch/nn/test_tm_quant_linear.py.
- Parse: initialize `ct_format` for non-CT configs (gptq/awq configs crashed with UnboundLocalError), and name the static per-tensor W8A8 rejection explicitly.
- FP8Format.finalize raises on per-channel scales with K % 128 != 0 instead of silently skipping the K-group expansion (silent wrong-numerics risk); blocked scales stay untouched.
- PT blocked lane: module scales follow the format accepts convention [ceil(N/128), ceil(K/128)] (one scale per output block per input group), shard slicing moves in output blocks, and blocked TP sharding is rejected loudly. Kernel-level numeric test for the blocked lane added.
The PT engine now runs gpt-oss-20b natively: MXFP4 experts (e2m1 codes + e8m0 group-32 scales) pack through the same MXFP4Format the TurboMind engine uses and execute the registered SM80/86 mxfp4 C++ family via the grouped TM channel. No new kernel code on either side - plumbing over the proven W4A16 grouped route.
- config: parse quant_method mxfp4 (implicit block 32, bf16 compute placeholder); get_quant_method sends linear/norm to bf16 passthrough and moe to the mxfp4 route. The dtype-less auto fallback now mirrors the TM converter capability rule (bfloat16 when supported), so both engines resolve a dtype-less checkpoint identically.
- switch: the LMDEPLOY_TM_KERNELS mxfp4 class gets its consumer - off raises naming the offline-dequant alternative (no fallback lane exists on SM80), auto probes the grouped registry, on is strict.
- impl: TurbomindMoeMXFP4Impl mirrors the W4A16 lifecycle (pack-once, sticky fused-silu probe only for plain-silu models, hot-update publish sync, sleep/wakeup re-pack). Custom clamped activations (gpt-oss) take the split gate/up path with python-side act; expert bias applies at slot granularity and frees with the handles. _slot_experts keeps a static slots-length output with the sentinel bin parked at expert 0 - this removes both the EP bias-gather crash and the graph-capture D2H sync from repeat_interleave.
- loader: gpt_oss suffix dispatch checks _blocks/_scales before the plain-projection substring (the substring false-catch crashed on packed uint8), flattens 4D grouped blocks, deinterleaves gate/up at load. process_weights_after_loading sweeps the caching allocator per spilling module so native pack allocations stay under VRAM.
- evidence: two independent review rounds (7/10 -> 9/10 COMMIT-READY) with a runtime revert-check proving the sentinel regression test bites; native gpt-oss-20b e2e on SM86 - PT greedy 5/6 byte-exact vs the TM golden (one whitespace near-tie), CUDA graphs on, no OOM; 19 new tests green (parity vs fp32 dequant reference incl. sentinel routing, route env matrix, loader suffix dispatch, graph capture with bitwise replay); ruff clean.
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