Skip to content

feat(w4a16): graft TurboMind W4A16 GEMM into the PyTorch engine - #5158

Open
windreamer wants to merge 8 commits into
mainfrom
stack/c1-w4a16-dense
Open

windreamer wants to merge 8 commits into
mainfrom
stack/c1-w4a16-dense

Conversation

@windreamer

@windreamer windreamer commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

TurboMind's strongest-performing assets are its mixed-precision W4A16 GEMM kernels, but the TurboMind runtime is being retired in favor of the PyTorch engine. This stack grafts the W4A16 GEMM family into the PyTorch engine: weights are packed into TurboMind kernels at load time, forward runs on TurboMind kernels, and the PyTorch engine keeps owning scheduling, KV-cache management, and CUDA graphs.

This PR is the foundation of the nine-PR stack (dense W4A16 graft → compressed-tensors normalization → GPTQ repack → grouped MoE → EP fill-in #5169 → CUDA graph #5171 → NVFP4 lanes #5173 → CT-FP8 lanes #5176 → MXFP4 MoE #5177): it introduces the TurboMind GEMM channel, the unified kernel switch, and the dense W4A16 route.

Modification

  • Unified kernel switch LMDEPLOY_TM_KERNELS (off/auto/all + per-class overrides), with the legacy LMDEPLOY_W4A16_GEMM_BACKEND honored and conflicts warned once. Later PRs extend the switch per format, each class landing together with its live consumer (feat(quant): NVFP4 lanes on the TM channel — SM80 family, native global scales (SM75–SM90) #5173: nvfp4/ct_fp8; feat(moe): serve gpt-oss MXFP4 experts through the TurboMind channel #5174: mxfp4); declarations without consumers are removed rather than kept.
  • Kernel-registry probe: per-module capability check; auto falls back to the AWQ Triton kernel per module, forced turbomind raises, off keeps the Triton path; per-module routing decisions logged.
  • TmGemmLinear (plain / merged / QKV): AWQ weights packed into the TurboMind Linear API at load time without a per-module sync; forward runs on TM kernels.
  • Weight-spill release: packed GPU weights spill to an exact CPU copy and are freed; hot updates restore and re-pack. MLA-absorbed modules keep their torch copies. (Superseded by CPU-direct packing later in the series; the spill machinery is retired in feat(moe): serve gpt-oss MXFP4 experts through the TurboMind channel #5177.)
  • Merged gate/up packs as one concatenated GEMM in this PR; the fused gate/up epilogue machinery is introduced here and first wired live by the MoE route in feat(moe): grouped W4A16 MoE via the TM GEMM channel #5161 (registry-gated by family capability), separate w1/w3 handles otherwise.
  • Removes the SM90-only turbomind_awq_modules prototype this replaces.
  • CPU-direct dense loading: the dense AWQ route's raw weights stay resident on CPU
    through transform/packing; only the packed result copies H2D — eliminating the GPU
    round-trip for this lane (part of the series' load-path rework; sleep/wakeup re-packs
    from the CPU source of truth).

BC-breaking

Code importing lmdeploy.pytorch.backends.cuda.turbomind_awq_modules (the removed prototype) breaks; the new route engages automatically under the same env values. Downstream projects should switch to the documented LMDEPLOY_TM_KERNELS switch.

Use cases

W4A16 (INT4/INT8 weight, FP16 activation) inference with TurboMind GEMM kernels, enabled via LMDEPLOY_TM_KERNELS=all or the default auto on supported hardware.

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: kernel parity vs the AWQ Triton path (argmax agreement, truncated KL), spill and hot-update round-trips, three-state routing with per-module fallback logging, and an engine-level golden gate against real weights; the kv-connector sleep test fakes adapt to the TM sleep-release module walk added here.
  3. No new downstream dependencies.
  4. Docstrings and the kernel-switch documentation are updated accordingly.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unguarded TurboMind imports break PyTorch-only installations, while weight updates can leave captured CUDA graphs referencing freed native allocations.

4 open issues
What changed in this PR

Grafts TurboMind’s W4A16 GEMM kernels into the PyTorch engine while leaving scheduling, KV-cache management, and CUDA graphs under PyTorch’s control.

Changes:

  • Adds unified kernel selection with legacy environment compatibility and per-module capability checks.
  • Introduces TurboMind-backed plain, merged, and QKV AWQ layers, with weight packing, CPU spill, and hot-update restoration.
  • Replaces the SM90-only prototype and adds routing, numerical parity, weight-lifecycle, and real-checkpoint tests.
File Description
tests/​pytorch/​kernel/​test_w4a16_routing.py Tests backend selection and probe rejection reasons.
tests/​pytorch/​kernel/​test_w4a16_engine_routing.py Tests layer-builder routing, fallback, and logging.
tests/​pytorch/​kernel/​test_tm_gemm_linear.py Tests parity, backend fusion, spill, and hot updates.
tests/​pytorch/​engine/​w4a16_golden.py Adds fixed prompts and engine comparison helpers.
tests/​pytorch/​engine/​test_w4a16_golden_gate.py Adds real-checkpoint numerical acceptance checks.
lmdeploy/​pytorch/​nn/​linear/​tm_gemm.py Adds TurboMind-backed AWQ layer variants.
lmdeploy/​pytorch/​nn/​linear/​awq.py Extracts an overridable backend-construction method.
lmdeploy/​pytorch/​nn/​linear/​__init__.py Routes AWQ builders to the new layer variants.
lmdeploy/​pytorch/​envs.py Adds unified kernel-switch parsing and legacy precedence.
lmdeploy/​pytorch/​backends/​tm_gemm_modules.py Defines the TurboMind linear build specification.
lmdeploy/​pytorch/​backends/​cuda/​turbomind_awq_modules.py Removes the previous TurboMind AWQ prototype.
lmdeploy/​pytorch/​backends/​cuda/​tm_weight_release.py Adds CPU spill copies and loader-triggered restoration.
lmdeploy/​pytorch/​backends/​cuda/​tm_probe.py Checks registry support and shape constraints.
lmdeploy/​pytorch/​backends/​cuda/​tm_gemm_modules.py Implements native packing, execution, and backend selection.
lmdeploy/​pytorch/​backends/​cuda/​op_backend.py Registers the new build-spec dispatch.
lmdeploy/​pytorch/​backends/​cuda/​awq_modules.py Connects legacy AWQ dispatch to the shared probe and implementation.

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Hot updates can free native weight buffers while earlier forwards on other streams still read them, creating a critical use-after-free risk during inference.

1 open issue
4 previously missed issues

In code that hasn't changed since last review

Medium severity Convert activations to FP16 for the native W4A16 route

lmdeploy/​pytorch/​backends/​cuda/​tm_gemm_modules.py:198

This forwards non-FP16 activations unchanged, unlike the AWQ implementation's FP16 conversion and output-dtype restoration. The packed W4A16 plan uses FP16 input, and native Family::ConvertInput asserts that unquantized input matches that dtype, so BF16/FP32 callers that work with Triton now fail when auto routing selects TurboMind. Preserve the existing activation-dtype conversion contract around the native call.

Medium severity Avoid creating and destroying an executor per module probe

lmdeploy/​pytorch/​backends/​cuda/​tm_probe.py:40

During model construction, this probe adds executor creation/destruction and a device-wide synchronization for every module. get_linear() caches executors only weakly, the returned plan does not retain one, and dropping the temporary executor invokes Linear.close() (turbomind/linear.py:162–168,217–223,574–584). Reuse an executor with a defined per-device lifetime, or cache capability results using device and format keys.

Medium severity Preserve positional arguments in the weight-loader wrapper

lmdeploy/​pytorch/​backends/​cuda/​tm_weight_release.py:57

The restore wrapper drops positional loader arguments. For example, SiglipVisionModel.load_weights calls QKV loaders as weight_loader(param, loaded_weight, shard_id) (models/siglip.py:389), so updating an already-spilled AWQ QKV projection raises TypeError before restoration. Preserve both positional and keyword arguments when delegating to the original loader.

Medium severity Wire merged projections into the advertised SiLU fusion path

lmdeploy/​pytorch/​nn/​linear/​tm_gemm.py:172

Merged engine projections never use the gate/up SiLU fusion advertised in the PR, even on supported SM90 hardware. The inherited _build_impl leaves fusion_type=None, and LlamaMLP.forward still applies SiluAndMul separately. Connect a capability-aware fused route to the model's activation bypass with an unfused fallback, or explicitly defer this feature in the PR description.

4 resolved since last review

Review effort: Balanced

- Route AWQ W4A16 linears through TurboMind's grouped GEMM channel: a kernel-registry probe replaces the SM90-only capability table, activation quantization runs inside the kernel epilogue, and initial loads publish packed weights without a per-module sync.
- Spill packed torch weights to an exact CPU copy and free the GPU storage; hot updates restore and re-pack. MLA-absorbed modules keep their torch copies.
- Introduce the unified LMDEPLOY_TM_KERNELS switch (off/auto/all plus per-class overrides). The w4a16 class reads it with LMDEPLOY_W4A16_GEMM_BACKEND as legacy fallback; conflicts warn once and the big env wins. Other kernel classes are declared in the switch plane and their consumers land in the following commits.
- Supersede and remove the SM90-only turbomind_awq_modules prototype.
- Tests: kernel parity vs the AWQ Triton path (argmax agreement, truncated KL), spill and hot-update round-trips, routing under the three states with per-module fallback, and an engine-level golden gate running one public AWQ checkpoint twice (Triton reference vs TurboMind route).
…p and hot updates

Guard the lmdeploy.turbomind channel imports behind an availability check so PyTorch-only installations keep importing the model tree; auto routing falls back to the AWQ Triton kernel with a readable reason and forced turbomind still raises.
Route update_params(finished=True) through _finalize_updated_weights() so captured CUDA graphs are reset after TurboMind repacking closes the native allocations they reference.
Add a sleep_release/sleep_wakeup protocol on the TurboMind linears: the packed native handle is freed before Module.to on sleep, and wakeup restores the spilled torch weights, re-packs, and re-spills to keep the post-wakeup steady state identical to a hot update.
Track armed spill loaders by live Parameter objects instead of bare ids so a recycled id cannot skip arming a fresh loader and send a hot update into empty spilled storage.
… activation contract

Restore the release of the previous packed weight at the start of hot updates: the device-wide synchronize in _release waits for in-flight forwards on any engine stream before the old native buffers close, so replacement can no longer free storage that another stream is still reading.
Convert non-fp16 activations to fp16 for the native call and cast the output back, keeping the AWQ Triton activation contract for bf16 callers instead of failing the native input-dtype assert.
Memoize registry plan constraints per (group_size, dtype, device) so per-module probes during model construction stop creating and destroying a linear executor each time.
Forward positional loader arguments through the restore-on-touch wrapper so vision QKV loaders called with shard_id keep working on spilled projections.
- Both classes had no live consumers: the attn_int8_kv consumer module (backends/tm_kv.py) never entered git history (local-only during the c1 session, later cleaned), and the gdn consumer was removed by 6d313f1 (revert(gdn): keep fla - adapter bridge overhead is net negative). Setting LMDEPLOY_TM_KERNELS=attn_int8_kv=<state> or gdn=<state> was a silent no-op.
- PT-side GDN continues to run on the fla-backed CUDA impl directly (unrelated to this switch); attention int8-kv kernels do not exist in-tree.
- If a TurboMind gdn or attention int8-kv kernel lane ever lands, re-declare the class here; the unified-switch semantics are unchanged for every live class (w4a16, moe_grouped, and the mxfp4/nvfp4/fp8 additions in later commits of this stack).
Step 3 of the CPU-direct packing sequence: the TurboMind dense W4A16
route routes its packed storages (qweight/scales/qzeros) to the host at
module build time, so the loader fills CPU buffers and update_weights
packs from host memory. The raw weights never occupy device memory and
the former spill has nothing left to free.

- TmGemmLinearMixin: cpu_resident property; register_all_parameters
  replaces the untouched CUDA empties with host empties at build time
  (later registrations re-register verbatim); _apply pins the three
  storages out of module moves while bias and the rest still travel;
  sleep paths collapse to release + re-pack (no spill/restore).
- release_torch_weights=False keeps its MLA semantics: device-resident
  registered copies (get_unquantized_weight forwards through the packed
  channel on device, so the exempt module cannot go CPU-direct).
- Builders (build_linear/build_merged_colwise_linear/build_qkv_proj/
  build_colwise_linear) forward release_torch_weights so callers can
  exempt at construction time.
- The Triton per-module fallback keeps CUDA-resident weights.
- The checkpoint-engine bucket feed (_load_updated_weight_bucket) wraps
  its loader writes in inference_mode: the initial load creates
  inference-tensor storages and a hot update mutates them outside that
  mode, which the former spill-based restore used to mask.

Evidence:
- tm_gemm + engine routing suites green (module tests rewritten for the
  CPU-direct steady state; spill-class tests unchanged).
- engine golden gate Qwen2.5-0.5B-AWQ (ModelScope) passes: top1 1.0,
  greedy agreement and truncated KL within thresholds vs the Triton
  reference.
44e3441 removed declarations without live consumers; moe_grouped has none in this PR (its first live consumer is the MoE route in #5161). It re-lands with that consumer.
Comment thread lmdeploy/pytorch/nn/linear/tm_gemm.py Resolved
- DeepseekV2Attention builds kv_b_proj with release_torch_weights=False: MLA
  absorption reads the weight through a device-side forward
  (get_unquantized_weight), so the packed storages must share the identity's
  execution device (PR 5158 review thread 4691048889).
- Regression: behavioral device-coherence test through the real absorption
  path in tests/pytorch/kernel/test_tm_gemm_linear.py (red pre-fix: qweight
  CPU-resident vs CUDA identity).

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