You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat(w4a16): graft TurboMind W4A16 GEMM into the PyTorch engine - #5158
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.
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
Pre-commit or other linting tools are used to fix the potential lint issues.
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.
No new downstream dependencies.
Docstrings and the kernel-switch documentation are updated accordingly.
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.
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.
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.
Preserve positional arguments in the weight-loader wrapper
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.
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.
- 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.
- 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 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
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.
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
LMDEPLOY_TM_KERNELS(off/auto/all + per-class overrides), with the legacyLMDEPLOY_W4A16_GEMM_BACKENDhonored 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.autofalls back to the AWQ Triton kernel per module, forcedturbomindraises,offkeeps 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.turbomind_awq_modulesprototype this replaces.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 documentedLMDEPLOY_TM_KERNELSswitch.Use cases
W4A16 (INT4/INT8 weight, FP16 activation) inference with TurboMind GEMM kernels, enabled via
LMDEPLOY_TM_KERNELS=allor the defaultautoon supported hardware.Checklist