Fix AutoRound gradients for Kimi-VL routed experts - #2097
Draft
lesj0610 wants to merge 1 commit into
Draft
Conversation
lesj0610
force-pushed
the
fix/kimi-vl-expert-grad
branch
2 times, most recently
from
July 28, 2026 22:30
91207f9 to
063a0e6
Compare
Temporarily bypass only verified torch grad-mode wrappers while SignRound tunes Kimi-VL routed experts. Keep eval-mode routing, reject unsupported expert parallelism, and restore the exact instance state on every exit. Scan only the current block while tuning. Make prepare_run() validation-only: it rejects unrecognized decorators and ep_size > 1 before block iteration and logs the target count. The public quantize_block() and LLM-Compressor paths use the same block-local scan without prepare_run(). Add realistic gradient, lifecycle, negative, and inherited-quantizer regressions. Signed-off-by: lesj0610 <lesj0610@gmail.com>
lesj0610
force-pushed
the
fix/kimi-vl-expert-grad
branch
from
July 28, 2026 23:27
063a0e6 to
219119b
Compare
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.
Purpose
moonshotai/Kimi-VL-A3B-Thinking-2506is listed as a supported model, but its routed experts cannot be gradient-tuned by SignRound wheniters > 0. The model remains quantizable with RTN, while iterativeW4A16_MIXEDtuning silently leaves the routed-expert tuning parameters without gradients (or fails at backward when no other differentiable path is present). This matters because the mixed recipe intentionally assigns INT4 only to the routed experts.Root cause
AutoRound correctly keeps the model in eval mode during block tuning. Kimi-VL's remote
DeepseekV3MoE.forwardtherefore selectsmoe_infer, which is decorated with@torch.no_grad(). The routed experts execute inside that decorator, so their AutoRound tuning parameters are disconnected from autograd. The shared-expert path is outsidemoe_infer, which can make a block loss require gradients while still leaving every routed expert untuned.Switching the block to training mode is not valid: Kimi-VL's
noaux_tcrouting path asserts inference mode and training mode would change routing semantics. Existing unfused/fused MoE patches do not cover this class because the top-level model type iskimi_vl, and this remote implementation uses aModuleListrather than the Transformers 5 fused-expert interface.Design
This change adds an instance-local context manager around
SignRoundQuantizer.quantize_block:model_type == "kimi_vl"anditers > 0.DeepseekV3MoEthrough the class MRO and temporarily binds the callable exposed bymoe_infer.__wrapped__to that instance.torch.no_gradwrapper during optimization.iters == 0), other model types, and unrelated MoE classes.ep_size > 1: the Kimi-VL expert-parallelall_to_allpath does not preserve routed-expert gradients. Quantize withep_size=1or useiters=0(RTN).prepare_run()is validation-only: before block iteration it scans the model to reject unrecognized grad-mode decorators andep_size > 1, then logs the validated target count. It caches neither target descriptors nor runtime state. Everyquantize_block()invocation—including the normal orchestrator path and the public/LLM-Compressor path—lazily scans only the current block and opens exactly one block-scoped context, so the public path behaves identically withoutprepare_run().The runtime patch is scoped to block tuning instead of globally modifying remote model source. It also avoids
.train()and avoids reimplementing Kimi's routing logic. AdamRound and SignRoundV2 inherit the samequantize_blockimplementation, so they receive the same scoped behavior.W4A16_MIXEDand MLA preservationA meta-device inventory of the actual local Kimi-VL model applied the current
W4A16_MIXEDrecipe withgroup_size=32:Linearmodules in total.26 MoE layers × 64 routed experts × 3 projections; all use group size 32 and integer weight quantization.language_model.lm_headis excluded fromlayer_config, and the vision patch-embedding convolution is also untouched.Safetensors metadata was inspected without loading tensor values. All corresponding checkpoint tensors are BF16: 4,992 routed weights, 78 shared weights, 108 MLA projection weights, 329 vision tensors, 6 projector tensors, and the
lm_headweight. The patch does not alter this recipe or MLA execution.Before-fix reproduction
On upstream
mainat54b4b84cdfcbd985a00264048a288a224e2a76c0, a CPU reproducer using Kimi's eval-mode MoE path producedloss.requires_grad == False;backward()failed with:The remote
moe_infermethod was confirmed to carry thetorch.no_gradwrapper, while the top-level config reportsmodel_type="kimi_vl".Unit and regression tests
Executed locally with CUDA hidden and Hugging Face/Transformers offline mode:
test/test_cpu/models/test_kimi_vl.py: 22 passed. The tests cover the Kimi-VLmoe_inferdataflow, realquantize_blockloss/backward/step behavior, active/inactive expert gradient and update behavior, output parity, eval-mode preservation, normal and exceptional restoration, the context manager's explicit reentrancy contract, lazy current-block scoping with sibling-block exclusion, the public/LLM-Compressor path withoutprepare_run(),prepare_run()rejection of unrecognized decorators andep_size > 1before block iteration, multiple targets, exact-MRO inclusion and exclusion, the original scatter-reduce failure mode, inherited quantizers, and the mixed recipe.test/test_cpu/models/test_moe_experts_interface.py: 7 passed.test/test_cpu/models/test_vlm_ram_reduction.py: 14 passed.pre-commit run --all-filespassed every configured hook, including Black, isort, Ruff, Bandit, codespell, and license checks.git diff --checkpassed.Actual Kimi GPU smoke test
The first actual MoE decoder block (
language_model.model.layers.1) was tested on one RTX 3090 24 GB with PyTorch 2.11.0+cu130, Transformers 5.10.2, and the editable AutoRound checkout.Settings:
W4A16_MIXED, weight INT4, group size 32, activation 16-bit,iters=1, sequence length 32, one sample, batch size 1, seed 42,quant_nontext_module=False. The actual remoteDeepseekV3MoEimplementation and 197 block tensors were strict-loaded from the local checkpoint (571,080,768 parameters). No model files were modified.Results:
max_abs_diff=0) and the model remained in eval mode.quantize_block()path scanned the current block, found oneDeepseekV3MoEtarget, and recorded one active patch at context depth 1.0.007146065589040518.None, finite, nonzero gradients, and all 441 update probes changed.grad is None, and all 135 full tensors remained unchanged.Transformers 5.10.2 no longer exposes
transformers.utils.import_utils.is_torch_fx_available, which the Transformers-4-era remote code imports. The smoke harness added an in-process compatibility alias returningTrue; neither AutoRound nor the checkpoint files were modified.A separate full-model meta instantiation verified all module names and recipe assignments in 13.09 seconds with 2,828,012 KiB maximum RSS. It did not load full weights or run full-model quantization.
Relationship to prior work
iters=0, so it cannot detect missing routed-expert gradients.deepseek_v3model type; Kimi-VL reportskimi_vl, so that patch does not apply.ModuleListand has no matching fused-expert interface/decorator.trust_remote_codewhile checking unfused MoE configurations, which is a prerequisite but not a Kimi-VL autograd fix.Validation not completed
A complete CPU test suite was not practical in this environment:
test/test_cpu/utils/test_alg_ext.py::TestAlgExt::test_alg_extbecause the installedggufpackage lacksMODEL_ARCH.DFLASH; bundled llama.cpp conversion then reportedQwen3ForCausalLMunsupported. This path does not import or execute the changed Kimi/SignRound code.test_w4a16_mixed_mllmfixture stopped making progress while fetching Qwen2.5-VL data. It was interrupted after 19:06; the preceding selected tests reported8 passed, 26 deselected. No generated model fixture remains in the worktree.Full Kimi-VL checkpoint quantization, export/reload, vLLM/Marlin loading, end-to-end multimodal generation with real image inputs, and quality benchmarks were not run. No claim is made here about accuracy, reasoning quality, hallucination rate, or end-to-end compression quality. Maintainers should separately validate this patch with a Transformers combination supported by the repository and run a representative Kimi-VL calibration/evaluation/export cycle before declaring quality parity.
Artifacts and remaining checks
This PR contains only two source files and one CPU regression-test file. It contains no model weights, quantized outputs, caches, logs, or generated artifacts.
The context is designed for AutoRound's serial block-tuning flow and is reentrant. Simultaneous multi-thread tuning of the same module instance was not validated. Maintainers should also confirm the remote-code compatibility matrix for the repository's supported Transformers versions and run full-model quality/export validation on the target checkpoint.