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
[OMNIML-6079] [2/3] Add the Kimi-K3 expert-parallel adapter - #2749
[2/3] of the Kimi-K3 split. [1/3] is #3132: the fixes the checkpoint's own modeling code needs on current transformers and fla-core, with their tests, moved out of this PR at the reviewers' request into modelopt/torch/models/kimi_k3/_remote_fixes.py. It merged on 2026-10-30. [3/3] is #3370, a draft stacked on this PR: a Kimi-K3 PTQ recipe (model_type/kimi_k3) that keeps the layers vLLM builds unquantized in BF16, so its exports load in vLLM. Every other PR of the expert-parallel PTQ series has merged.
Base:main. The branch is rebased onto main 3497c11 as 8c2b209 (2026-11-23). Everything it builds on has merged:
Kimi-K3's text backbone, kimi_linear, has no native transformers modeling to swap in, so the adapter patches the checkpoint's remote code in place:
It replaces the MoE block's per-expert ModuleList with fused experts that dispatch through the experts interface. This keeps K3's latent expert space and its custom SwiGLU. Their eager loop, which runs outside expert parallelism and is the GPU test's whole-model reference, sums a token's weighted results in the routing weights' dtype and casts once, as the checkpoint's own moe_infer does.
It registers torch_a2a with transformers; that is the experts implementation it names on the text config. Transformers refuses to build a model whose experts implementation it has not registered. prepare runs only on the expert-parallel route, so that is the only route that registers it.
Before it builds the model, it applies the fixes the remote model needs for the expert-parallel load and calibration:
KDA's A_log shape and sigmoid(beta);
the causal-mask and cache signatures;
the kwargs newer transformers pass to tie_weights;
What runs before deciding: only the spec's make_buildable. It installs the OutputRecorder shim, stages the code's imports, and adapts the VLM class's tie_weights to the arguments post_init passes it. None of this changes what the model computes or loads.
Where the decision looks: it reads the plan the spec states, on text_config, and finds the experts in the model the checkpoint's own code builds.
What other loads see: a whole-model or FSDP2 load never meets Kimi-K3's patches, unless an expert-parallel load of it ran first in the same process. The patches are process-wide and stay after that load. The spec says so (prepare_patches_every_load), and load_pretrained then refuses a whole-model or FSDP2-sharded load of Kimi-K3 in that process before anything is built.
What is left alone: a block built before prepare, such as one in a model loaded earlier in the process, keeps its per-expert experts and its own forward. The other fixes are ones the remote code needs on current transformers and fla-core anyway. torch_a2a goes only on the prepared copy, and the decompressor rewrites only configs it marked.
for a quantized checkpoint, whatever the decompressor would refuse: a dtype other than bf16, a scheme it cannot read, compressed-tensors missing or older than 0.16, or a process that is already decompressing a checkpoint compressed differently.
With the EP degree left to auto, such a checkpoint is planned without expert parallelism, and the warning names the reason. prepare itself checks all of these before it installs the decompressor or patches anything, so a refusal leaves the process as it was.
Why Kimi-K3 refuses its later loads in the process, instead of choosing its structure and converters per config as Kimi-VL and Kimi-K2.5 do (_kimi._native_for_the_prepared_config):
How Kimi-VL and Kimi-K2.5 do it: those two swap in transformers' native DeepSeek-V3. One module-level name decides which language model their VLM builds. The config their prepare makes is transformers' own DeepseekV3Config, which tells it apart from the checkpoint's own config class.
What Kimi-K3 does instead: it has no native backbone to swap in. Its prepare patches the checkpoint's own KimiSparseMoeBlock class in place (its __init__ and forward), keeps that patch on later copies of the code, and registers the fused-expert converters in transformers' conversion registry under the backbone's model type, kimi_linear.
Why that reaches every later load: that registry entry belongs to the model type, not to a checkpoint or a config. So every later load in the process of a checkpoint on that backbone gets the fusion, including a text-only kimi_linear one. A checkpoint whose blocks are not the patched ones would have its per-expert weights fused into parameters its blocks do not have, and would load its experts newly initialized.
Why not choose per config: that would need a block class that dispatches on the config, and a hook on transformers' conversion lookup for the configs prepare made, across every patch above. A new process already serves that case.
So the spec states that prepare patches every later load of kimi_k3 and kimi_linear (prepare_patches_every_load). load_pretrained then refuses any whole-model or FSDP2-sharded load of either in that process, of any checkpoint, before it builds anything, and names a new process as the way out.
It needs transformers 5.13, the release it was developed and validated against. Its spec declares that, so an older release is refused before prepare runs. Its spec states the plan prepare attaches, as the Kimi-VL and Kimi-K2.5 specs do (#3138), so a run at an EP degree of 1 still finds its experts (#2780).
Usage
There is nothing to call. apply_distributed_support picks the adapter for a kimi_k3 checkpoint once the run is planned expert-parallel, as examples/hf_ptq/hf_ptq.py plans it under torchrun (#3139; see its README section "Expert-Parallel Post-Training Quantization for MoE Models"). The load needs:
trust_remote_code;
transformers 5.13 or newer;
compressed-tensors 0.16 or newer, for the packed MXFP4 checkpoint;
flash-linear-attention, which the checkpoint's own KDA layers need.
Testing
Current state, rebased onto main 3497c11 as 8c2b209 (2026-11-23). These tests and runs show the adapter computes what the checkpoint's own code computes. The table below says which ran at which head. The commits after de4a053 change only docs, the CHANGELOG and CPU tests, and fc05b0a and 8c2b209 are rebases onto main, with the PR's own diff unchanged.
CPU unit tests. They are in tests/unit/torch/models/kimi_k3/test_ep.py, plus the cases this PR adds to tests/unit/torch/utils/test_model_load_utils.py. Each test fails on a deliberate break of the code it covers. They compare against tests/_test_utils/torch/kimi_k3_remote.py, a stand-in whose MoE block computes what the checkpoint's modeling_kimi_linear.py computes: the tanh-based situ in fp32, the sigmoid router with its correction bias, grouped routing, renormalization and scaling factor, RMSNorm, and moe_infer's sum in the routing weights' dtype. The patch keeps the remote module's gate, situ and norm, and swaps only the experts container and the block's forward.
The patched MoE block reproduces the stand-in's per-expert block (test_the_patched_block_reproduces_the_remote_per_expert_forward, assert_close), in fp32 and in bf16, in seven variants: latent with and without the norm, no latent, grouped routing, no shared experts, silu without renormalization, and situ without linear_beta. A block built before the patch keeps its per-expert experts and its own forward. The test fails in these mutations:
w1 and w3 swapped: 14 of 14 cases;
each token's routing weights reversed across its experts: 14 of 14, with a 2–46% max relative difference;
the latent norm skipped: the 10 cases that have it.
A dropped scaling factor also fails all 14 cases. But in the 10 cases with the latent RMSNorm, it fails only through the norm's eps (0.4–2.0%), because a uniform scale cancels in the norm. So only the 4 cases without the norm test the scale itself (8–47%).
Against the checkpoint's shipped MoE code itself, outside the test suite: cjluo-nv's check in the review runs the shipped KimiSparseMoeBlock against the patched block in the same seven variants. In fp32 they match to about 1e-7; at de4a053 the patched block's bf16 error equals the shipped code's in all seven.
The eager loop's sum: in bf16, the fused experts' eager loop matches moe_infer's combine of the same expert results exactly. Both weight each result in the fp32 routing weights, sum in fp32 and cast once (test_the_eager_loop_sums_a_tokens_results_in_the_routing_weights_dtype).
Conversions: the registered converters fuse each expert's w1/w3 into gate_up_proj and stack w2 into down_proj, exactly. The plan, the converters and the fused parameters name the same tensors.
Export: it names packed experts back to the checkpoint's w1/w3/w2 (test_packed_experts_export_under_the_checkpoints_names).
prepare:
it runs only on an expert-parallel plan, and at an EP degree of 1 the plan decision builds the checkpoint's own per-expert MoE blocks;
before it changes anything, it refuses a missing checkpoint path, untrusted code, a config naming no model class, and whatever the decompressor refuses;
it patches the module that defines the MoE block, once;
it keeps its patches on a copy of the code loaded through another path to the checkpoint;
it records its lasting patch even when a later step raises.
A model builds from the prepared config with torch_a2a registered, and a transformers older than 5.13 is refused before prepare runs.
Later loads:load_pretrained refuses a whole-model or FSDP2-sharded load of Kimi-K3, or of a kimi_linear checkpoint, after a prepare in the same process. The plan decision plans a packed Kimi-K3 that prepare would refuse without expert parallelism.
GPU, on 2 and 4 GPUs (tests/gpu/torch/utils/test_expert_parallel_load.py::test_kimi_k3_packed_experts_load_calibrate_and_name_back_expert_parallel). A tiny Kimi-K3-shaped remote checkpoint (tests/_test_utils/torch/kimi_k3_tiny_modeling.py) has a dense layer, then an MoE layer: 8 packed MXFP4 routed experts, top-2, in a latent expert space, with one shared expert. It loads expert-parallel through the spec. Each rank then checks itself against the whole model loaded on one GPU:
it holds exactly its own experts' slices, decompressed as they loaded, equal to the checkpoint's;
its logits on its own batch match the whole model's;
FP8 calibration over every rank's batch gives every amax the whole model's value, to one bf16 step. The latent-expert projections stay unquantized on both sides, as nvidia/Kimi-K3-NVFP4 and the Kimi-K3 recipe keep them;
the export names each expert back to w1/w3/w2;
another load refuses the returned model.config, and a whole-model load in the same process is refused too.
Its whole-model reference runs this PR's own fused block, eager. So the test shows that the all-to-all path matches the eager loop; the CPU checks above and the check below tie that loop to the checkpoint's code.
GPU, against the checkpoint's own code (check 1 of cjluo-nv's review). A standalone script, outside the repo, builds a random tiny Kimi-K3 with the checkpoint's own modeling files:
4 layers: a dense first layer, KDA in layers 0 to 2 and MLA in layer 3;
64 packed MXFP4 routed experts, top-8, run at the latent width with its norm, plus 2 shared experts, with situ;
grouped noaux_tc routing with the correction bias and a routed_scaling_factor of 2.5.
The reference is the checkpoint's code in its own process, unpatched apart from _remote_fixes' compatibility fixes, with its experts decompressed by compressed-tensors. The candidate is hf_ptq.py's expert-parallel load at an EP degree equal to the world size: 2, 4 and 8. It ran on 8 GB200 GPUs over 2 nodes, with transformers 5.18.0, compressed-tensors 0.17.1 and flash-linear-attention 0.5.0, at de4a053; modelopt/ is the same at 729fdce.
Compared with the reference, at EP 2, 4 and 8
bf16 (TF32 on)
fp32 (TF32 off)
Each rank's expert weights
bit-exact
not compared
Every MoE block, fed the reference's input
bit-exact
within 3.1e-7 relative
Every MoE block and the logits, end to end
bit-exact, also at EP4 with the dense part FSDP2-sharded
the same top-1 token everywhere; about 1e-4 apart by the third MoE layer
The fp32 end-to-end difference builds up in the non-MoE layers across the two nodes. On one node (TF32 off), the MoE layers' inputs are bit-identical to the reference's, and every check passes.
The container enables TF32 for fp32 GEMMs by default (TORCH_ALLOW_TF32_CUBLAS_OVERRIDE=1), which puts about 1e-4 on every fp32 comparison until it is turned off. TF32 touches only fp32 GEMMs, so the bf16 results, from the run with it on, stand.
Each of these fails the comparison: w1 and w3 swapped, the expert index rolled, and results returned to the wrong tokens.
Real model, EP64, before this PR. This ran before this PR opened on 2026-10-12, on the series as it stood then. Check 2 below exported the real model again, at de4a053. Kimi-K3 was quantized to NVFP4 on 64 GB200 GPUs (16 nodes), at EP64 with the dense part FSDP2-sharded, on transformers 5.13. It loaded and calibrated with no NaN, and its export checked out against the source checkpoint:
all 92 router correction biases matched the checkpoint, to BF16 rounding of its F32 values;
routed experts exported as experts.N.w1/w2/w3 and shared experts as gate_proj/up_proj/down_proj, the naming vLLM 0.28's Kimi-K3 loader reads;
in that export, the latent-expert projections, the residual gates and mm_projector were BF16, as the Kimi-K3 recipe keeps them, and vLLM 0.28 loaded it and started serving at TP=32.
vLLM 0.28 cannot serve such an export with an FP8 KV cache: its Kimi-K3 FP8-KV path needs an FP8 prefill query, which its NVFP4 linears reject. nvidia/Kimi-K3-NVFP4 ships without a quantized KV cache.
Real model, weights only (check 2 of cjluo-nv's review).
The export:
hf_ptq.py ran expert-parallel at EP64 on 64 GPUs (16 nodes), on moonshotai/Kimi-K3 at revision 9f62e4e9, with the recipe models/moonshotai/Kimi-K3/ptq/nvfp4_experts-fp8_pb_attention. This is the first time that recipe has gone through hf_ptq.py.
The code was at de4a053; modelopt/ is unchanged at 729fdce. Versions: transformers 5.13.0, compressed-tensors 0.17.1, flash-linear-attention 0.5.0, torch 2.15.0a0.
No calibration forward ran. The recipe fixes the expert input amax, so input_scale is 1.0, and it quantizes the attention weights only, to FP8.
The comparison with the source checkpoint uses compressed-tensors' own MXFP4 decompression (0.20.1 in the comparison tooling):
What was compared
Result
Expert projections under the checkpoint's names (92 layers × 896 × w1/w2/w3)
all 247,296 on both sides, none missing or extra
Non-expert tensors
all 2,467 present
Each export expert's best match among its layer's 896 source experts, by cosine on sampled rows
the same index for all 247,296; worst-case margin over the second best 0.73
Tensors with quantization scales
only the recipe's 12 attention projections (696 tensors), in the block layout [ceil(R/128), 1, ceil(C/128), 1] that nvidia/Kimi-K3-NVFP4 uses
Expert input_scale
exactly 1.0 everywhere
FP8 attention weights against the bf16 source
relative Frobenius error: median 2.65% over all 696 (range 2.51–2.67%)
NVFP4 experts against the MXFP4 source
relative Frobenius error: median 6.47% over a stratified 1,932 tensors (range 6.27–7.16%)
Unquantized tensors
1,564 byte-identical; 368 fp32 source tensors written as bf16, each within one bf16 ulp
FP8 attention: the few elements flushed to zero lie below E4M3's subnormal floor.
The 1,932 expert tensors: they cover all 92 layers and the experts on each side of every EP64 rank boundary. The seven experts on either side of the EP64 rank boundaries (0, 13, 14, 447, 881, 882, 895) have median relative Frobenius errors between 6.469% and 6.480%, each measured against its own source expert over all 92 layers and 3 projections.
Why the experts' error is higher:hf_ptq.py re-quantizes the decompressed bf16 experts with amax-based NVFP4 scales. The streaming converter instead keeps the MXFP4 codes bit-exact wherever a block's exponent fits. So this path is lossier than the converter's, though structurally identical.
The 368 tensors written as bf16:e_score_correction_bias ×92, KDA q/k/v_conv1d weights ×207 and attention o_norm ×69. The streaming converter keeps them in fp32. No tensor differs in value at the same dtype.
Check 4: the export served by vLLM, gsm8k against the MXFP4 source (2026-11-13).
The export loads in the model card's vLLM image, and its gsm8k score matches the MXFP4 source within one question.
Checkpoint
gsm8k 5-shot, strict
flexible
MXFP4 source (moonshotai/Kimi-K3 @ 9f62e4e9)
96.29% ± 0.52
96.29% ± 0.52
This export: NVFP4 routed experts
96.21% ± 0.53
96.21% ± 0.53
McNemar on the 1,319 paired questions:
1,253 right in both, 17 right only in the source, 16 right only in the export;
exact two-sided p = 1, paired difference −0.08 points (95% CI −0.93 to +0.78);
a control that flips 12 of the export's correct answers to wrong gives p = 0.0005, so a difference of that size would show.
Revisions:
This PR's code at 4990ab6, then based on main 814e6b4. The PR has since been rebased onto main as 8c2b209 with its own changes as they were: the CHANGELOG entry moved to the 0.50.0 section, and modelopt_recipes/ptq.md keeps main's new Kimi-K3.1-Pro line next to this PR's.
The recipe is the general nvfp4_experts_only-kv_fp8_cast plus six exclusions. They keep in BF16 the layers vLLM's Kimi-K3 model builds without a quantization config: the latent-MoE routed_expert_{up,down}_proj, the three *_res_proj and KDA's [qkv]_conv1d.
Export checks:
All 92 router e_score_correction_bias tensors match the source layer by layer, within BF16 rounding.
The 578 modules the recipe keeps in BF16 have no quantization scales, and all 184 latent projections are named in both exclude_modules and ignore.
The shared experts' gate and up weight_scale_2 are equal in all 92 layers.
Same setup on both arms: the same vLLM image and flags apart from the model path and the KV dtype, the same lm-eval 0.4.13, datasets 5.2.0 and huggingface-hub 1.33.0, and an identical gsm8k task config.
Commands
Quantize: 64 GB200 GPUs (16 nodes × 4), DistributionPlan(world_size=64, ep_size=64, dense='fsdp'). Versions: transformers 5.13.0, compressed-tensors 0.17.1, flash-linear-attention 0.5.0, torch 2.11. Env: MODELOPT_EP_DEGREE=64 MODELOPT_FSDP_SIZE=64 HF_HUB_OFFLINE=1. The cnn_dailymail calibration set must be a prepared datasets cache for an offline run.
Serve: the model card's image vllm/vllm-openai:kimi-k3 (vLLM 0.1.dev19262+gb6bbf29dd), with the card's runtime_patches on PYTHONPATH, on 32 GB200 GPUs (8 nodes × 4). No --quantization flag: vLLM reads the checkpoint's own config. Env: KIMI_K3_FIX_MM_PROMPT_UPDATES=1 KIMI_K3_NVFP4_SITU_G1_SCALE=1 KIMI_K3_FP8_PB=1 VLLM_USE_DEEP_GEMM=0 VLLM_USE_V2_MODEL_RUNNER=1 VLLM_USE_RUST_FRONTEND=0.
After merge: 3. EP4 against EP8 on the real model cut to a few layers, comparing every amax and input scale.
To be decided: whether the full release evals, the rest of 4, come before or after merge.
Revision history, 2026-10-12 to 2026-11-23
Unless an entry says otherwise, each revision below passed pre-commit against main (mypy included). Each one that changed code also passed its CPU unit tests on torch 2.14, with transformers 5.18 and 5.5.4. Each fix came with a test that fails without it.
Bases
Before 2026-10-27: this PR was part 20 of a 21-PR stack on main c6fa613. Pre-commit passed at every PR of the stack. At the stack's tip, the full tests/unit (transformers 5.18 and 5.5, and torch 2.8) and the hf_ptq example tests showed only main's own failures in each environment.
2026-10-30: split as described in the note at the top. Every test of the former PR is in exactly one of the two PRs, unchanged apart from names and imports. The stand-in remote module moved to tests/_test_utils/torch/kimi_k3_remote.py, which both PRs import. Two rebases followed, each with its own diff unchanged:
2026-11-06, 7912d31: rebased onto main c35d7bd, with its own diff unchanged.
2026-11-12, fc05b0a: rebased onto main 814e6b4, 21 commits on, with its own diff unchanged and no conflicts. Two patches changed only in context: the model packages' import list, and the hf_ptq README's footnote 13 beside footnote 15.
2026-11-23, 8c2b209: rebased onto main 3497c11, 68 commits on, with its own diff unchanged. modelopt_recipes/ptq.md keeps main's new Kimi-K3.1-Pro line next to this PR's, and the CHANGELOG entry moved from 0.49.0, now cut, to 0.50.0's Quantization - Export & Deployment.
prepare installs the decompressor before it patches anything (a78d656). The refusal test has the real decompressor refuse an unparsable scheme and a dtype other than bf16. It checks that the remote block, the config, the converter registry, the experts implementations and the loader hooks are unchanged.
prepare also reads compression from the checkpoint's own config.json (ea287d8). A config that has lost its scheme and the mark is refused, instead of loading the experts newly initialized.
2026-10-31, 63c8267: restacked onto [OMNIML-6078] [2/2] Add the Kimi-K2.5 expert-parallel adapter #2748, whose prepare runs only on the expert-parallel route. The spec names its build step, puts its plan on text_config, and names compressed-tensors among its formats (c459add). New test: test_only_an_expert_parallel_plan_patches_kimi_k3s_code[fsdp2|whole|expert-parallel|expert-parallel-packed].
A whole-model or FSDP2 load after an expert-parallel one in the same process is refused before anything is built (EPSpec.prepare_patches_every_load; test_a_load_after_a_prepare_that_patched_every_load_is_refused[whole|fsdp2]).
The build step adapts the VLM's tie_weights.
The checkpoint-config read covers llm_config.
The tests moved to tests/unit/torch/models/kimi_k3/test_ep.py.
2026-10-31, 4389363 (Claude):prepare records its lasting patch where it makes it (test_a_prepare_that_raises_after_patching_still_records_it). In f186098 that record keys on kimi_k3.ep.MODEL_TYPE.
2026-10-31, a209248: the GPU case compares each amax with the whole model's to one bf16 step, elementwise (rtol=2**-7), instead of a relative-norm tolerance of 2e-2.
2026-10-31, 85e7c50 (cjluo-nv):test_an_ep_degree_of_1_builds_kimi_k3s_own_code_to_decide[whole|fsdp2] plans a tiny Kimi-K3 at ep_size=1 through the real meta build.
2026-10-31, 76fcf09: the GPU test's checkpoint writer builds the tiny class with the tie_weights shim.
2026-10-31, 1d549fc: the build step installs nothing when there is nothing to build (test_the_build_step_installs_nothing_when_there_is_nothing_to_build[no-checkpoint|untrusted]). Before this, five Kimi prepare tests failed after the left-whole test ran in the same process.
prepare_patches_every_load also names kimi_linear: [its-backbone-whole].
The patched block's __init__ passes on any argument beyond the config (test_the_patched_block_takes_what_else_the_remote_one_takes).
2026-11-01:
140cd26 (cjluo-nv): the tiny modeling is imported after the transformers guard, so collecting the tests without transformers skips them. This was checked on transformers 5.18 and in an environment without transformers.
fdb723f, d199fce and 777f110 change only comments, a docstring and the source link's full hash.
2026-11-02, 883a88e:test_a_remote_kimi_k3_whose_prepare_attaches_its_plan_left_whole_is_an_error skips below the spec's transformers release. The tests also pass without transformers.
2026-11-03:
8f87468: Kimi-K3's spec states what its prepare refuses (EPSpec.prepare_refusal).
1704a33 (Claude) asks the shared decompression_refusal.
72de70f (Claude) follows the decompressor's own lookup of a quantization_config.
cd556bf (Claude) drops quantization_config at every level the decompressor reads one.
2026-11-04, 5d6a6ab (cjluo-nv): the refusal says what a new process loads. This is a message and docstring change only.
2026-11-06, 25d6aac: this PR's Kimi lines in the shared default disabled-quantizer unit, which applies to every model, came out again, along with the preset test this PR had added to pin them. Since then the PR changes nothing under modelopt_recipes/ or tests/unit/recipe/. Kimi-K3's own recipe keeps those projections BF16. The GPU case now disables the latent-expert projections itself.
prepare checks the config's model class before it installs the decompressor or any shim (cc447eb). test_prepare_refusal_finds_a_config_naming_no_model_class runs the real prepare and checks that the loader hooks, the config and its scheme are unchanged.
prepare keeps its patches on every copy of the checkpoint's code that transformers loads, with _remote_code.keep_patched (99cddd3, 8556cf9). test_prepare_s_patches_stay_on_the_code_loaded_through_another_path resolves the class through a symlink to the checkpoint.
KimiK3Experts' eager loop had summed a token's weighted results in bf16. It now sums them in the routing weights' dtype (fp32 under Kimi-K3's gate) and casts once, as the checkpoint's moe_infer, transformers' grouped forwards and the torch_a2a combine do.
test_the_eager_loop_sums_a_tokens_results_in_the_routing_weights_dtype compares the loop in bf16 with moe_infer's combine of the same bf16 expert results. Without the change, 114 of 384 elements differ.
Pre-commit passed against main cf56451. The CPU tests passed on torch 2.14 with transformers 5.18, 5.13 and 5.5.4; the counts are in "Where each check ran" above.
The reviewer's check against the checkpoint's shipped MoE code now gives the loop the same bf16 error as the shipped code in all seven variants; fp32 is unchanged.
f85ccd5: examples/hf_ptq/README.md and modelopt_recipes/ptq.md tell the expert-parallel hf_ptq.py flow apart from the streaming converter, and the README lists what that flow needs. Its stale footnote said Kimi K3 does not use hf_ptq.py.
45bb553: a CHANGELOG line for Kimi-K3's expert-parallel PTQ.
729fdce: the stand-in's MoE block computes what the shipped one computes, and the block-parity test runs in the reviewer's seven variants, in fp32 and in bf16. It fails with w1 and w3 swapped and with the latent norm skipped. A dropped scaling factor fails it through the scale itself only in the 4 variants without the latent norm. The rest of that measurement is in the parity bullet above; this was corrected on 2026-11-12.
Pre-commit passed against main f036ffa. The CPU tests passed on torch 2.14 with transformers 5.18, 5.13 and 5.5.4; the counts are in "Where each check ran" above. No product code or GPU test changed, so the GPU run at de4a053 stands.
The Kimi-K3 spec registers through main's model registry as before. It has no PTQ section, so hf_ptq.py treats Kimi-K3 with its generic behaviour, as it did before the registry took over its per-model rules.
Pre-commit passed against main 814e6b4, mypy and the MODELOPT_* knob check included.
On CPU with torch 2.14, tests/unit/torch/models and test_model_load_utils.py passed: 943 on transformers 5.18; 929, with 3 skipped, on 5.13; and 651, with 116 skipped, on 5.5.4.
prepare keeps its patches on later copies of the checkpoint's code: it records a callback in _remote_code._KEPT_PATCHES and wraps get_class_in_module. No fixture of these tests put either back, so a test that ran prepare left the callback on for later ones.
The module's autouse fixture now restores both, as the Kimi-VL and Kimi-K2.5 fixtures do.
test_an_ep_degree_of_1_builds_kimi_k3s_own_code_to_decide now asserts that every MoE block of the model the plan decision builds keeps per-expert experts. Without the isolation it fails in the file's order; with it, the file passes.
Pre-commit passed against main 73b3f74, and the CPU counts are unchanged.
GPU runs of tests/gpu/torch/utils/test_expert_parallel_load.py
All runs used transformers 5.18. On 2 GPUs, the cases with a half-width expert-parallel group ([ep-half]) skip, because they need 4.
The same jobs ran 8556cf9, with identical results per test id
End-to-end run through hf_ptq.py, 2026-10-25. This used a tiny Kimi-K3 (bf16, 4 layers, 32 experts, KDA and full-attention layers) on 2 GPUs at EP 2, with the dense part replicated:
transformers 5.18 and fla-core 0.5.0;
--qformat nvfp4 --kv_cache_qformat fp8;
max calibration on 64 samples of the default text blend, at sequence length 128 and batch size 2.
It decided its plan, previewed before and after PTQ on both ranks, calibrated and exported. Before that revision, it had failed while deciding its plan, because torch_a2a was not registered. With that fixed, it failed in generate, on the cache's query offset.
Step
Value
Calibration
51 s
End to end
4 min 28 s
Memory per GPU
13.9 GB
Before your PR is "Ready for review"
Is this change backward compatible?: ✅ Additive. One effect reaches beyond the expert-parallel path. prepare, which only an expert-parallel plan runs, patches the checkpoint's own code for the rest of the process, including later copies of it. A later whole-model or FSDP2 load of Kimi-K3 or kimi_linear in that process is therefore refused (see above).
If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: ✅ The fused parameters and eager loop of KimiK3Experts are adapted from MiniMaxM3VLExperts in transformers v5.18.0 (Apache-2.0).
The file header carries the source link at a full commit hash and the original notice.
LICENSE lists the copyright holder, and the license-header hook excludes the file.
Did you get Claude approval on this PR?: ❌ Not as an approval. Claude's review of de4a053 (2026-11-10) found the eager-loop fix correct and no new code issue. It left three things open: the decision on the stand-in, since settled in 729fdce; the pre-merge checks listed under Testing; and the licensing confirmation, which is a human reviewer's call.
Additional Information
Size, by main's rule (AGENTS.md, "Sizing and splitting PRs", as #3163 softened it). About 500 added source lines is a guideline. Tests, docs, config, comments and blank lines don't count.
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.
The pull request adds Kimi-K3 model registration and an expert-parallel adapter for remote MoE code. It configures fused expert execution and checkpoint weight conversion, handles quantized checkpoints and compatibility patches, and adds process-level load safeguards with unit and distributed tests.
Changes: Kimi-K3 expert parallelism
Layer / File(s)
Summary
Fused experts and checkpoint conversion modelopt/torch/models/kimi_k3/ep.py, tests/_test_utils/torch/kimi_k3_remote.py, tests/_test_utils/torch/kimi_k3_tiny_modeling.py, tests/unit/torch/models/kimi_k3/*
The adapter defines a grouped-gemm expert-parallel plan, fuses gate/up and down parameters, and dispatches through ExpertsInterface. It registers converters for checkpoint w1, w3, and w2 weights. Test fixtures and unit tests cover routed outputs and weight conversion.
The Kimi-K3 spec connects preparation, refusal handling, and quantized-checkpoint support. Preparation loads and patches remote code, configures expert parallelism, registers converters, and updates quantization configuration. Tests cover preparation conditions, compatibility behavior, and spec selection.
Persistent patch tracking and load safeguards modelopt/torch/models/specs.py, modelopt/torch/utils/moe.py, modelopt/torch/utils/plugins/model_load_utils.py, tests/unit/torch/utils/test_model_load_utils.py
EPSpec declares model types whose later loads are affected by preparation patches. The loader records those types and rejects non-expert-parallel loads for them. Tests also cover Kimi-K3 load planning.
The GPU test creates a packed MXFP4 checkpoint and compares per-rank expert weights, logits, quantizer scales, and export names with a whole-model reference.
sequenceDiagram
participant ModelLoader
participant KimiK3Spec
participant Prepare
participant RemoteKimiMoE
participant ExpertsInterface
ModelLoader->>KimiK3Spec: select expert-parallel spec
KimiK3Spec->>Prepare: invoke preparation
Prepare->>RemoteKimiMoE: load and patch remote MoE
Prepare->>ModelLoader: configure EP plan and torch_a2a
ModelLoader->>ExpertsInterface: dispatch fused expert parameters
Loading
Merge Risk: Low · up to 78dad
A malformed compressed checkpoint configuration could pass preparation without the required decompression setup, risking incorrect expert loading. Narrow the exception handling before merging.
Pre-merge checks: 3
Check name
Status
Explanation
Title check
The title "[OMNIML-6079] [2/3] Add the Kimi-K3 expert-parallel adapter" matches the main change. The PR adds the Kimi-K3 expert-parallel adapter in modelopt/torch/models/kimi_k3/ep.py, with its spec, …
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Security Anti-Patterns
Checked the PR's changed files against base 3497c11 for the six security anti-patterns in the custom check. 1. torch.load(..., weights_only=False): no added occurrence in the diff. 2. numpy.load(.…
Full details: Title check
Explanation
The title "[OMNIML-6079] [2/3] Add the Kimi-K3 expert-parallel adapter" matches the main change. The PR adds the Kimi-K3 expert-parallel adapter in modelopt/torch/models/kimi_k3/ep.py, with its spec, test stand-ins, and unit and GPU tests. The ticket prefix and the [2/3] series marker add noise but do not make the title unclear. The title is 59 characters and one sentence.
Full details: Security Anti-Patterns
Explanation
Checked the PR's changed files against base 3497c11 for the six security anti-patterns in the custom check. 1. torch.load(..., weights_only=False): no added occurrence in the diff. 2. numpy.load(..., allow_pickle=True): no added occurrence, and no allow_pickle or pickle usage in the diff. 3. trust_remote_code hardcoded to True in the modelopt package: no. Every modelopt/ occurrence is a caller-configurable parameter that defaults to False. This includes prepare, prepare_refusal, make_buildable and _force_load_remote_modeling in modelopt/torch/models/kimi_k3/ep.py. prepare refuses when the flag is False, and the value is passed through to get_class_from_dynamic_module. The other modelopt/ hits are a docstring and a CLI doc line in examples/hf_ptq/README.md that tells the user to pass --trust_remote_code. True literals appear only in tests/unit and tests/gpu fixtures. Those files are outside the scope the check names (modelopt package and examples), and they load local tmp-dir checkpoints. 4. eval() or exec(): no added occurrence. 5. # nosec or Bandit suppressions: none in the changed files. 6. New pip dependencies: pyproject.toml and requirements files are unchanged against the base, so no new dependency is added. No pattern matches a FAIL condition. The check is satisfied on the shipped code.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
❌ Patch coverage is 99.47917% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 83.35%. Comparing base (3497c11) to head (8c2b209).
shengliangxu
changed the title
[14/19] Add the Kimi-K3 expert-parallel adapter
[OMNIML-6079] [14/19] Add the Kimi-K3 expert-parallel adapter
Oct 12, 2026
shengliangxu
changed the title
[OMNIML-6079] [14/19] Add the Kimi-K3 expert-parallel adapter
[OMNIML-6079] [14/20] Add the Kimi-K3 expert-parallel adapter
Oct 13, 2026
shengliangxu
changed the title
[OMNIML-6079] [14/20] Add the Kimi-K3 expert-parallel adapter
[OMNIML-6079] [16/21] Add the Kimi-K3 expert-parallel adapter
Oct 13, 2026
…n it reads
From Claude's review of the refusal:
- The record that a prepare patched every later load landed only once
prepare returned, so a step after the MoE block's patch that raised
left the process patched but unrecorded. Kimi-K3's prepare now calls
moe.mark_patched_every_load right after that patch;
apply_distributed_support still records a prepare that completes.
test_a_prepare_that_raises_after_patching_still_records_it fails
without the early mark.
- _checkpoint_quantized is the one place prepare reads the checkpoint
itself, and prepare is handed no hub options: its docstring now says a
hub id is read at its default revision, a local checkpoint as it is.
Signed-off-by: Shengliang Xu <[email protected]>
… refusal precedes
From Claude's review:
- The early record of prepare's lasting patch spelled kimi_k3 as a
literal, which had to equal the spec's model_type. kimi_k3.ep.MODEL_TYPE
is now the one definition the spec registers and the record keys on,
and the test checks the record against the spec.
- The refusal precedes the load's build, not the plan decision's
throwaway meta build, which runs earlier: the docs now say a refused
load is refused before it builds or loads the model, and that under
torchrun an EP degree of 1 meets the decision's own refusal first.
Signed-off-by: Shengliang Xu <[email protected]>
…-tensors 0.16
Signed-off-by: Shengliang Xu <[email protected]>
#3137 now refuses an older compressed-tensors, whose compressors take no scheme: the Kimi-K3 tests that parse or load a compressed checkpoint through the real library skip there, as the decompressor's own do.
An amax is a max, and the expert-parallel and whole models take it over the same bf16 activations: all that precedes Kimi-K3's one MoE layer is dense and replicated. The relative-norm tolerance of 2e-2 came from a test whose amaxes are summed over other orders; here one bf16 step (2**-7 of the value) covers the experts' down_proj input, which their grouped and eager GEMMs may round apart.
Signed-off-by: Shengliang Xu <[email protected]>
… real build
The tiny Kimi-K3 remote modeling now has the no-keyword tie_weights the checkpoint ships, and a test plans a tiny Kimi-K3 checkpoint at ep_size=1 through the real meta build of that code: refused whole on 4 ranks, or planned FSDP2. Without the build step at that degree (#2748) the build fails on tie_weights(recompute_mapping=False).
Signed-off-by: Shengliang Xu <[email protected]>
The tiny Kimi-K3 remote modeling now has the no-keyword tie_weights Kimi-K3's own code ships, and the GPU test's checkpoint writer built that class directly to read its state-dict shapes: on transformers 5.18, post_init's tie_weights(recompute_mapping=False) raised. The writer now builds it with the adapter's tie_weights shim, patched onto the class for that build only, so the loads in the test still meet the unshimmed checkpoint code.
Signed-off-by: Shengliang Xu <[email protected]>
Kimi-K3's make_buildable made the code importable, installing the OutputRecorder shim and the remote-code staging for the process, before it checked for a checkpoint path and trusted code, so a plan decision with neither still patched the process. Since the decision runs the build step at an EP degree of 1 too, the Kimi-K3 left-whole refusal test left the staging installed, and five Kimi prepare tests that compare it failed when they ran later in the same process. The build step now returns first, as the Kimi-VL and Kimi-K2.5 one does; the remote-module load it goes on to makes the code importable itself. A test pins that it installs nothing then, and the left-whole refusal test records the build step instead of running it, checking that the decision runs it once.
Signed-off-by: Shengliang Xu <[email protected]>
…else it takes
Kimi-K3's prepare registers its fused-expert converters under its backbone's model type, kimi_linear, for the whole process, but recorded only kimi_k3 as spoiled. A later whole-model load of a text-only kimi_linear checkpoint then built its own unpatched block, whose per-expert experts the converters fuse into parameters it does not have, so they loaded newly initialized with only a warning. EPSpec.prepare_patches_every_load now names the model types a prepare spoils; Kimi-K3's are kimi_k3 and kimi_linear, recorded where prepare first patches and again once it returns. The refusal says what loaded expert-parallel without naming the refused type as that load's. The patched block's __init__ passes on any argument beyond the config, as a revision adding a layer index would need.
Signed-off-by: Shengliang Xu <[email protected]>
The model-type constants added above the plan left its comment, on the plan's base-relative globs, its block_sparse_moe experts and its missing ep_router entry, standing over MODEL_TYPE instead. Comment only.
Signed-off-by: Shengliang Xu <[email protected]>
…s guard
The tiny modeling imports transformers at module scope, so importing it above the guard made collecting the file without the optional [hf] extra fail on ModuleNotFoundError instead of skipping.
Signed-off-by: Shengliang Xu <[email protected]>
EPSpec.prepare_patches_every_load's model types are recorded once prepare returns, so a prepare that can raise after a lasting patch must record it where it patches, as Kimi-K3's does. Docstring only.
Signed-off-by: Shengliang Xu <[email protected]>
GitHub does not resolve the short hash the link used; the full one is the v5.18.0 commit, whose file holds the same copyright line and MiniMaxM3VLExperts. Header comment only.
Signed-off-by: Shengliang Xu <[email protected]>
Below the transformers release Kimi-K3's spec needs, no Kimi-K3 could
be expert-parallel, so one left whole on every rank is not refused: it
loads as a dense model does, with a warning. This test expects the
refusal an expert-parallel-capable MoE gets, so it skips below that
floor, as the Kimi-VL and Kimi-K2.5 left-whole test does, rather than
expecting the RuntimeError the decision used to raise there.
Signed-off-by: Shengliang Xu <[email protected]>
…rallelism
Kimi-K3's spec counts compressed-tensors checkpoints as ones the
expert-parallel load takes, since its prepare installs the decompressor.
With compressed-tensors missing or older than 0.16, a scheme or dtype
the decompressor cannot take, a config naming no model class, or code
the load may not run, prepare refused on every rank after the decision
had chosen expert parallelism. The spec now states those refusals
(EPSpec.prepare_refusal), sharing prepare's own checks. So an EP degree
left to auto plans the model without expert parallelism, with the
warning naming why, and one asked for still meets prepare's refusal.
Signed-off-by: Shengliang Xu <[email protected]>
Kimi-K3's prepare_refusal mirrored the decompressor's refusals itself
and missed one: a process already decompressing a checkpoint compressed
differently. It now asks decompression_refusal, which states every check
install_onfly_decompress makes before it installs anything, beside
Kimi-K3's own refusals.
Signed-off-by: Shengliang Xu <[email protected]>
Whether prepare installs the decompressor looked for a
quantization_config on the config and its text_config only, while the
decompressor reads llm_config too. The two now agree, through the
decompressor's own lookup, so a config spelling its language model's
llm_config is not left undecompressed.
Signed-off-by: Shengliang Xu <[email protected]>
From Claude's review: whether prepare installs the decompressor follows
the decompressor's lookup, over config_levels, llm_config included, but
prepare dropped quantization_config from the top level and text_config
only. It now drops it at every level config_levels gives. The prepare
test gains an llm_config scheme, whose drop fails without this.
Signed-off-by: Shengliang Xu <[email protected]>
From cjluo-nv's review: the refusal of a whole-model or FSDP2 load in a
process an expert-parallel load patched advised a new process, but a new
process builds the checkpoint's own code as it ships. Kimi-K3's needs the
fixes in kimi_k3._remote_fixes to import, build, load and run on current
transformers and fla-core, and only its prepare applies them, so there
it loads expert-parallel only; a text-only kimi_linear checkpoint that
transformers' own class builds loads whole there. The message and the
docstring now say so. Message and docstring only.
Signed-off-by: Shengliang Xu <[email protected]>
The default disabled-quantizer unit applies to every model, so it takes
no Kimi-only lines: the latent-expert projections, the residual gates
and mm_projector come out of it again, with the preset test that pinned
them. Kimi-K3's checkpoint recipe already keeps these layers BF16, as it
enables only the routed experts and the attention projections.
The Kimi-K3 GPU test quantized with the default FP8 preset and compared
every calibrated amax between the expert-parallel and the whole model,
relying on the unit to keep the latent-expert projections out. It now
disables them itself, as nvidia/Kimi-K3-NVFP4 and the recipe keep them,
so the comparison stays on what both sides compute identically. The
tiny Kimi-K3 has no residual gates.
Signed-off-by: Shengliang Xu <[email protected]>
…anything
From cjluo-nv's review: prepare installed the decompressor for a packed
checkpoint, marking its config and patching transformers' loader for the
process, and the import shims, before it found that the config's
auto_map names no model class to load the code through. A plan handed
in reaches prepare without the decision's prepare_refusal, so a caught
refusal left the process decompressing the refused checkpoint's format.
prepare now checks the model class first, and the code's force-load
checks it before it installs the shims.
The no-model-class test now also runs the real prepare on a packed
checkpoint naming none: the decompressor's hooks, the config's mark and
scheme, and the staging stay as they were. It fails with the check
after the install.
Signed-off-by: Shengliang Xu <[email protected]>
From cjluo-nv's review: prepare patched only the module of the
checkpoint's code it imported. transformers executes a module again
when the files it hashes change, and loads another copy for another
path to the same checkpoint, so a plan and prepared config made through
one path and loaded through another (the prepared config handed to
load_pretrained skips prepare) built from a fresh module, with neither
the fused-expert block nor the tie_weights shim the config and the
registered converters assume.
prepare now keeps its patches with _remote_code.keep_patched, as the
other Kimi adapters keep theirs: one patch per module, the fused-expert
block and the fixes on the module defining KimiSparseMoeBlock and the
tie_weights shim on the one defining the VLM class, re-applied to every
such module when transformers resolves a class. A new CPU test prepares
a tiny Kimi-K3 through one path and resolves its class through a
symlink to the same checkpoint, with the real dynamic loader; the copy
loaded there is patched, and the test fails when prepare patches only
the module it imported.
Signed-off-by: Shengliang Xu <[email protected]>
keep_patched applies a patch only to modules transformers loaded
remote, by name. prepare now applies its patches to the module it
imported directly, as before, and keeps them for any copy loaded later,
so the fixes never depend on how the module is named. The test of a
prepare that finds no module defining the MoE block gives its config
the auto_map entry prepare now checks first.
Signed-off-by: Shengliang Xu <[email protected]>
…'s eager loop
KimiK3Experts' eager loop, the GPU test's whole-model reference and the
fallback outside expert parallelism, added each weighted expert result
into a buffer of the hidden states' bf16, rounding every result on the
way. The checkpoint's own moe_infer, transformers' grouped forwards and
the torch_a2a combine weight the results in the routing weights' dtype
(fp32 under Kimi-K3's gate), sum them there and cast once. The loop now
sums the same way.
The new test runs the loop in bf16 and compares it with moe_infer's
combine of the same bf16 expert results; it fails without the change,
with 114 of 384 elements off. Against the checkpoint's shipped MoE code,
the loop's bf16 error now equals the shipped code's in all seven variants
of the reviewer's check.
Signed-off-by: Shengliang Xu <[email protected]>
…reaming converter
examples/hf_ptq/README.md said Kimi-K3 does not use hf_ptq.py, and
modelopt_recipes/ptq.md pointed only at the streaming converter. With
this PR, hf_ptq.py quantizes Kimi-K3 expert-parallel under torchrun.
Both files now tell the two flows apart. The streaming converter casts
the packed MXFP4 experts to NVFP4 without loading the model or
calibrating. The expert-parallel flow decompresses each rank's experts
to bf16 and calibrates the model with the recipe passed to --recipe.
The README lists what that flow needs:
- --trust_remote_code;
- transformers 5.13 or newer and compressed-tensors 0.16 or newer;
- flash-linear-attention for the KDA layers;
- an expert-parallel degree that divides the 896 routed experts, with
about 85 GB of bf16 experts per GPU at EP64.
Signed-off-by: Shengliang Xu <[email protected]>
The expert-parallel PTQ entry names no models. Kimi-K3 needs more than
the other MoEs do: --trust_remote_code, transformers 5.13 or newer and
compressed-tensors 0.16 or newer, so that each rank can decompress its
own share of the packed MXFP4 routed experts. Its release note says so,
and points to the streaming converter as the way to reproduce
nvidia/Kimi-K3-NVFP4.
Signed-off-by: Shengliang Xu <[email protected]>
The unit tests compared the patched block with a stand-in whose MoE math
was simpler than the checkpoint's modeling_kimi_linear.py: another situ
formula, a router without correction bias, grouped routing,
renormalization or scaling factor, LayerNorm for RMSNorm, and a sum in
the hidden dtype.
The stand-in now follows the shipped code on all of these:
- the tanh-based situ in fp32, with and without linear_beta;
- the sigmoid router with its correction bias, grouped routing,
renormalization and routed_scaling_factor;
- RMSNorm;
- moe_infer's sum in the routing weights' dtype.
The block-parity test runs in the seven variants a reviewer checked
against the shipped code, in fp32 and in bf16:
- latent with and without the norm;
- no latent;
- grouped routing;
- no shared experts;
- silu without renormalization;
- situ without linear_beta.
The test fails with w1 and w3 swapped (14 of 14) and with the scaling
factor dropped (14 of 14). With the latent norm skipped, it fails in
every variant that has the norm (10 of 14).
Signed-off-by: Shengliang Xu <[email protected]>
prepare keeps its patches on later copies of the checkpoint's code
through _remote_code.keep_patched. That records a callback in
_KEPT_PATCHES and wraps transformers' get_class_in_module. No fixture of
the Kimi-K3 adapter tests put either back. So a test that ran prepare,
such as test_prepare_sets_the_plan_..., left the .modeling_kimi_k3
callback on for later tests. test_an_ep_degree_of_1_builds_kimi_k3s_own_
code_to_decide then built its tiny checkpoint's MoE blocks fused, though
it replaces prepare with a failure; its plan assertions passed anyway.
The module's autouse fixture now restores both, as the Kimi-VL and
Kimi-K2.5 tests' fixtures do. One test's own copy of those two lines is
dropped. The degree-1 test now also checks that the model it builds keeps
per-expert experts in every MoE block. Without the isolation, that check
fails in the file's order; with it, the file passes.
Signed-off-by: Shengliang Xu <[email protected]>
Export arm: vLLM generation and gsm8k against the MXFP4 source. Done, and recorded under Testing ("Check 4") with its commands and revisions.
The export loads and serves in the model card's Kimi-K3 vLLM image, TP16 × PP2 on 32 GB200 GPUs.
gsm8k 5-shot over all 1,319 questions: 96.21% ± 0.53 for the export against 96.29% ± 0.52 for the MXFP4 source.
McNemar on the paired questions: 17 right only in the source, 16 only in the export, p = 1. A control that flips 12 of the export's correct answers to wrong gives p = 0.0005, so a difference that size would have shown.
I've since rebased the PR onto main as 8c2b209. Its own changes are the same as at 4990ab6: the CHANGELOG entry moved to the 0.50.0 section, and modelopt_recipes/ptq.md keeps main's new Kimi-K3.1-Pro line next to this PR's.
Licensing: I signed off as the PR's author on 11-01 (comment 6564038146), after checking kimi_k3/ep.py against CONTRIBUTING.md's "Copying code from other sources":
the source link at its commit, with the upstream notice above the NVIDIA header;
SPDX unchanged, since both sides are Apache-2.0;
the LICENSE entry;
the insert-license hook exclusion.
Nothing in that code has changed since. The remaining human step is a code-owner approval of the PR.
This branch has not been deployed
No deployments
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.
Note
[2/3] of the Kimi-K3 split. [1/3] is #3132: the fixes the checkpoint's own modeling code needs on current transformers and fla-core, with their tests, moved out of this PR at the reviewers' request into
modelopt/torch/models/kimi_k3/_remote_fixes.py. It merged on 2026-10-30. [3/3] is #3370, a draft stacked on this PR: a Kimi-K3 PTQ recipe (model_type/kimi_k3) that keeps the layers vLLM builds unquantized in BF16, so its exports load in vLLM. Every other PR of the expert-parallel PTQ series has merged.Base:
main. The branch is rebased onto main 3497c11 as 8c2b209 (2026-11-23). Everything it builds on has merged:prepareonly once the plan is expert-parallel;Series layout
main, which holds every other PR of the series. These include the load path this PR extends: [OMNIML-6063] [1/3] Stage and keep patched a checkpoint's own modeling code #3130, [OMNIML-6060] [1/3] Add require_transformers, and build a VLM without its LM head #3131, [OMNIML-6079] [1/2] Fix Kimi-K3's own modeling code for current transformers and fla-core #3132, [OMNIML-6076] [1/3] Describe expert parallelism in the model specs #3134, [OMNIML-6076] [2/3] Prepare a model's config for expert parallelism from its spec #3135, [OMNIML-6060] [2/3] Load an MoE expert-parallel: shard the experts at load time #3136, [OMNIML-6054] [1/2] Move fsdp2_wrap out of distributed.py into fsdp2_utils #3140, [OMNIML-6054] [2/2] Route load_pretrained by the distribution plan #2779, [OMNIML-6060] Load an expert-parallel plan through load_pretrained, and apply the model spec when deciding and loading it #2780, [OMNIML-6073] Quantize Nemotron-H's experts under grouped_mm, with their wrapper in its model folder #3067, [OMNIML-6073] [2/2] Calibrate fused experts on grouped_mm and torch_a2a instead of forcing eager #3074, [OMNIML-6071] Calibrate a distributed model on per-rank data #2740, [OMNIML-6060] [3/3] Refuse an expert-parallel load that would calibrate the experts wrong #2741, [OMNIML-6061] Load the dense part sharded, and size the load warmup to each rank #2742, [OMNIML-6062] Dequantize block-FP8 checkpoints as they load expert-parallel #2743, [OMNIML-6063] [2/2] Decompress compressed-tensors MoE experts as they load, expert-parallel loads included #3137 and [OMNIML-6078] Add the Kimi-VL and Kimi-K2.5 expert-parallel adapters #3138. They also include [OMNIML-6085] Run expert-parallel PTQ from hf_ptq.py, with lockstep previews #3139, which runs expert-parallel PTQ fromhf_ptq.py([OMNIML-6085] [3/3] Run expert-parallel PTQ from hf_ptq.py #2754 folded in).What does this PR do?
Type of change: New feature
Kimi-K3's text backbone,
kimi_linear, has no native transformers modeling to swap in, so the adapter patches the checkpoint's remote code in place:It replaces the MoE block's per-expert
ModuleListwith fused experts that dispatch through the experts interface. This keeps K3's latent expert space and its custom SwiGLU. Their eager loop, which runs outside expert parallelism and is the GPU test's whole-model reference, sums a token's weighted results in the routing weights' dtype and casts once, as the checkpoint's ownmoe_inferdoes.It registers converters that fuse the checkpoint's per-expert
w1/w3intogate_up_projand stackw2intodown_proj. The MXFP4 experts are decompressed as they load ([OMNIML-6063] [2/2] Decompress compressed-tensors MoE experts as they load, expert-parallel loads included #3137).It registers
torch_a2awith transformers; that is the experts implementation it names on the text config. Transformers refuses to build a model whose experts implementation it has not registered.prepareruns only on the expert-parallel route, so that is the only route that registers it.Before it builds the model, it applies the fixes the remote model needs for the expert-parallel load and calibration:
A_logshape andsigmoid(beta);tie_weights;OutputRecorderimport.These are [1/3] of this split, [OMNIML-6079] [1/2] Fix Kimi-K3's own modeling code for current transformers and fla-core #3132, which describes each one. Transformers can load further copies of the checkpoint's code later in the process: one for each other path to the same checkpoint, and a fresh one when the code's files change.
preparekeeps these fixes and the fused MoE block on every such copy through_remote_code.keep_patched([OMNIML-6063] [1/3] Stage and keep patched a checkpoint's own modeling code #3130), as the Kimi-VL and Kimi-K2.5 adapters do.prepareruns only once the plan is decided expert-parallel ([OMNIML-6078] Add the Kimi-VL and Kimi-K2.5 expert-parallel adapters #3138).make_buildable. It installs theOutputRecordershim, stages the code's imports, and adapts the VLM class'stie_weightsto the argumentspost_initpasses it. None of this changes what the model computes or loads.text_config, and finds the experts in the model the checkpoint's own code builds.prepare_patches_every_load), andload_pretrainedthen refuses a whole-model or FSDP2-sharded load of Kimi-K3 in that process before anything is built.prepare, such as one in a model loaded earlier in the process, keeps its per-expert experts and its own forward. The other fixes are ones the remote code needs on current transformers and fla-core anyway.torch_a2agoes only on the prepared copy, and the decompressor rewrites only configs it marked.Before deciding, the plan decision also asks the spec what
preparewould refuse (prepare_refusal, [OMNIML-6078] Add the Kimi-VL and Kimi-K2.5 expert-parallel adapters #3138):With the EP degree left to auto, such a checkpoint is planned without expert parallelism, and the warning names the reason.
prepareitself checks all of these before it installs the decompressor or patches anything, so a refusal leaves the process as it was.Why Kimi-K3 refuses its later loads in the process, instead of choosing its structure and converters per config as Kimi-VL and Kimi-K2.5 do (
_kimi._native_for_the_prepared_config):preparemakes is transformers' ownDeepseekV3Config, which tells it apart from the checkpoint's own config class.preparepatches the checkpoint's ownKimiSparseMoeBlockclass in place (its__init__andforward), keeps that patch on later copies of the code, and registers the fused-expert converters in transformers' conversion registry under the backbone's model type,kimi_linear.preparemade, across every patch above. A new process already serves that case.So the spec states that
preparepatches every later load ofkimi_k3andkimi_linear(prepare_patches_every_load).load_pretrainedthen refuses any whole-model or FSDP2-sharded load of either in that process, of any checkpoint, before it builds anything, and names a new process as the way out.It needs transformers 5.13, the release it was developed and validated against. Its spec declares that, so an older release is refused before
prepareruns. Its spec states the planprepareattaches, as the Kimi-VL and Kimi-K2.5 specs do (#3138), so a run at an EP degree of 1 still finds its experts (#2780).Usage
There is nothing to call.
apply_distributed_supportpicks the adapter for akimi_k3checkpoint once the run is planned expert-parallel, asexamples/hf_ptq/hf_ptq.pyplans it undertorchrun(#3139; see its README section "Expert-Parallel Post-Training Quantization for MoE Models"). The load needs:trust_remote_code;Testing
Current state, rebased onto main 3497c11 as 8c2b209 (2026-11-23). These tests and runs show the adapter computes what the checkpoint's own code computes. The table below says which ran at which head. The commits after de4a053 change only docs, the CHANGELOG and CPU tests, and fc05b0a and 8c2b209 are rebases onto main, with the PR's own diff unchanged.
CPU unit tests. They are in
tests/unit/torch/models/kimi_k3/test_ep.py, plus the cases this PR adds totests/unit/torch/utils/test_model_load_utils.py. Each test fails on a deliberate break of the code it covers. They compare againsttests/_test_utils/torch/kimi_k3_remote.py, a stand-in whose MoE block computes what the checkpoint'smodeling_kimi_linear.pycomputes: the tanh-basedsituin fp32, the sigmoid router with its correction bias, grouped routing, renormalization and scaling factor, RMSNorm, andmoe_infer's sum in the routing weights' dtype. The patch keeps the remote module's gate,situand norm, and swaps only the experts container and the block's forward.The patched MoE block reproduces the stand-in's per-expert block (
test_the_patched_block_reproduces_the_remote_per_expert_forward,assert_close), in fp32 and in bf16, in seven variants: latent with and without the norm, no latent, grouped routing, no shared experts, silu without renormalization, andsituwithoutlinear_beta. A block built before the patch keeps its per-expert experts and its own forward. The test fails in these mutations:w1andw3swapped: 14 of 14 cases;A dropped scaling factor also fails all 14 cases. But in the 10 cases with the latent RMSNorm, it fails only through the norm's eps (0.4–2.0%), because a uniform scale cancels in the norm. So only the 4 cases without the norm test the scale itself (8–47%).
Against the checkpoint's shipped MoE code itself, outside the test suite: cjluo-nv's check in the review runs the shipped
KimiSparseMoeBlockagainst the patched block in the same seven variants. In fp32 they match to about 1e-7; at de4a053 the patched block's bf16 error equals the shipped code's in all seven.The eager loop's sum: in bf16, the fused experts' eager loop matches
moe_infer's combine of the same expert results exactly. Both weight each result in the fp32 routing weights, sum in fp32 and cast once (test_the_eager_loop_sums_a_tokens_results_in_the_routing_weights_dtype).Conversions: the registered converters fuse each expert's
w1/w3intogate_up_projand stackw2intodown_proj, exactly. The plan, the converters and the fused parameters name the same tensors.Export: it names packed experts back to the checkpoint's
w1/w3/w2(test_packed_experts_export_under_the_checkpoints_names).prepare:A model builds from the prepared config with
torch_a2aregistered, and a transformers older than 5.13 is refused beforeprepareruns.Later loads:
load_pretrainedrefuses a whole-model or FSDP2-sharded load of Kimi-K3, or of a kimi_linear checkpoint, after apreparein the same process. The plan decision plans a packed Kimi-K3 thatpreparewould refuse without expert parallelism.GPU, on 2 and 4 GPUs (
tests/gpu/torch/utils/test_expert_parallel_load.py::test_kimi_k3_packed_experts_load_calibrate_and_name_back_expert_parallel). A tiny Kimi-K3-shaped remote checkpoint (tests/_test_utils/torch/kimi_k3_tiny_modeling.py) has a dense layer, then an MoE layer: 8 packed MXFP4 routed experts, top-2, in a latent expert space, with one shared expert. It loads expert-parallel through the spec. Each rank then checks itself against the whole model loaded on one GPU:w1/w3/w2;model.config, and a whole-model load in the same process is refused too.Its whole-model reference runs this PR's own fused block, eager. So the test shows that the all-to-all path matches the eager loop; the CPU checks above and the check below tie that loop to the checkpoint's code.
GPU, against the checkpoint's own code (check 1 of cjluo-nv's review). A standalone script, outside the repo, builds a random tiny Kimi-K3 with the checkpoint's own modeling files:
situ;noaux_tcrouting with the correction bias and arouted_scaling_factorof 2.5.The reference is the checkpoint's code in its own process, unpatched apart from
_remote_fixes' compatibility fixes, with its experts decompressed by compressed-tensors. The candidate ishf_ptq.py's expert-parallel load at an EP degree equal to the world size: 2, 4 and 8. It ran on 8 GB200 GPUs over 2 nodes, with transformers 5.18.0, compressed-tensors 0.17.1 and flash-linear-attention 0.5.0, at de4a053;modelopt/is the same at 729fdce.TORCH_ALLOW_TF32_CUBLAS_OVERRIDE=1), which puts about 1e-4 on every fp32 comparison until it is turned off. TF32 touches only fp32 GEMMs, so the bf16 results, from the run with it on, stand.w1andw3swapped, the expert index rolled, and results returned to the wrong tokens.Real model, EP64, before this PR. This ran before this PR opened on 2026-10-12, on the series as it stood then. Check 2 below exported the real model again, at de4a053. Kimi-K3 was quantized to NVFP4 on 64 GB200 GPUs (16 nodes), at EP64 with the dense part FSDP2-sharded, on transformers 5.13. It loaded and calibrated with no NaN, and its export checked out against the source checkpoint:
experts.N.w1/w2/w3and shared experts asgate_proj/up_proj/down_proj, the naming vLLM 0.28's Kimi-K3 loader reads;mm_projectorwere BF16, as the Kimi-K3 recipe keeps them, and vLLM 0.28 loaded it and started serving at TP=32.vLLM 0.28 cannot serve such an export with an FP8 KV cache: its Kimi-K3 FP8-KV path needs an FP8 prefill query, which its NVFP4 linears reject. nvidia/Kimi-K3-NVFP4 ships without a quantized KV cache.
Real model, weights only (check 2 of cjluo-nv's review).
The export:
hf_ptq.pyran expert-parallel at EP64 on 64 GPUs (16 nodes), onmoonshotai/Kimi-K3at revision 9f62e4e9, with the recipemodels/moonshotai/Kimi-K3/ptq/nvfp4_experts-fp8_pb_attention. This is the first time that recipe has gone throughhf_ptq.py.modelopt/is unchanged at 729fdce. Versions: transformers 5.13.0, compressed-tensors 0.17.1, flash-linear-attention 0.5.0, torch 2.15.0a0.input_scaleis 1.0, and it quantizes the attention weights only, to FP8.The comparison with the source checkpoint uses compressed-tensors' own MXFP4 decompression (0.20.1 in the comparison tooling):
w1/w2/w3)[ceil(R/128), 1, ceil(C/128), 1]that nvidia/Kimi-K3-NVFP4 usesinput_scalehf_ptq.pyre-quantizes the decompressed bf16 experts with amax-based NVFP4 scales. The streaming converter instead keeps the MXFP4 codes bit-exact wherever a block's exponent fits. So this path is lossier than the converter's, though structurally identical.e_score_correction_bias×92, KDAq/k/v_conv1dweights ×207 and attentiono_norm×69. The streaming converter keeps them in fp32. No tensor differs in value at the same dtype.Check 4: the export served by vLLM, gsm8k against the MXFP4 source (2026-11-13).
The export loads in the model card's vLLM image, and its gsm8k score matches the MXFP4 source within one question.
moonshotai/Kimi-K3@ 9f62e4e9)modelopt_recipes/ptq.mdkeeps main's new Kimi-K3.1-Pro line next to this PR's.model_type/kimi_k3/ptq/nvfp4_experts_only-kv_fp8_cast, from [OMNIML-6079] [3/3] Add a Kimi-K3 PTQ recipe that keeps the layers vLLM builds unquantized in BF16 #3370 at 39276b1. [OMNIML-6079] [3/3] Add a Kimi-K3 PTQ recipe that keeps the layers vLLM builds unquantized in BF16 #3370 adds only that recipe; itsmodelopt/tree is identical to this PR's. [OMNIML-6079] [3/3] Add a Kimi-K3 PTQ recipe that keeps the layers vLLM builds unquantized in BF16 #3370 now composes the recipe's NVFP4 entries from the shared units, with the same composed config.nvfp4_experts_only-kv_fp8_castplus six exclusions. They keep in BF16 the layers vLLM's Kimi-K3 model builds without a quantization config: the latent-MoErouted_expert_{up,down}_proj, the three*_res_projand KDA's[qkv]_conv1d.e_score_correction_biastensors match the source layer by layer, within BF16 rounding.exclude_modulesandignore.weight_scale_2are equal in all 92 layers.Commands
Quantize: 64 GB200 GPUs (16 nodes × 4),
DistributionPlan(world_size=64, ep_size=64, dense='fsdp'). Versions: transformers 5.13.0, compressed-tensors 0.17.1, flash-linear-attention 0.5.0, torch 2.11. Env:MODELOPT_EP_DEGREE=64 MODELOPT_FSDP_SIZE=64 HF_HUB_OFFLINE=1. The cnn_dailymail calibration set must be a prepareddatasetscache for an offline run.Serve: the model card's image
vllm/vllm-openai:kimi-k3(vLLM 0.1.dev19262+gb6bbf29dd), with the card'sruntime_patchesonPYTHONPATH, on 32 GB200 GPUs (8 nodes × 4). No--quantizationflag: vLLM reads the checkpoint's own config. Env:KIMI_K3_FIX_MM_PROMPT_UPDATES=1 KIMI_K3_NVFP4_SITU_G1_SCALE=1 KIMI_K3_FP8_PB=1 VLLM_USE_DEEP_GEMM=0 VLLM_USE_V2_MODEL_RUNNER=1 VLLM_USE_RUST_FRONTEND=0.The source arm ran the same command on
moonshotai/Kimi-K3@ 9f62e4e9, without--kv-cache-dtype(its KV cache is bf16 by default).Evaluate:
Where each check ran:
test_remote_code.pyandtest_model_load_utils.pylinuxjobtest_model_load_utils.pygpujob, one GPUmodelopt/unchanged since de4a053modelopt/unchanged since de4a053No Kimi-K3 GPU test runs in CI. CI is green at 8556cf9, at de4a053 and at 729fdce.
fc05b0a is 729fdce rebased onto main 814e6b4, with the PR's own diff unchanged. At fc05b0a:
4990ab6 changes only the Kimi-K3 unit tests. At 4990ab6:
8c2b209 is 4990ab6 rebased onto main 3497c11, with the PR's own diff unchanged; the CHANGELOG entry moved to the 0.50.0 section. At 8c2b209:
ptq.mdCPU tests passed: 571 on transformers 5.18, 569 (2 skipped) on 5.13 and 358 (97 skipped) on 5.5.4;Open as of 2026-11-23. The numbers are those of cjluo-nv's review. Checks 1, 2 and 4 are done (above).
models/moonshotai/Kimi-K3/ptq/nvfp4_experts-fp8_pb_attention, with [OMNIML-6073] [2/2] Calibrate fused experts on grouped_mm and torch_a2a instead of forcing eager #3074's expert weight-scale fix.Revision history, 2026-10-12 to 2026-11-23
Unless an entry says otherwise, each revision below passed pre-commit against main (mypy included). Each one that changed code also passed its CPU unit tests on torch 2.14, with transformers 5.18 and 5.5.4. Each fix came with a test that fails without it.
Bases
tests/unit(transformers 5.18 and 5.5, and torch 2.8) and the hf_ptq example tests showed only main's own failures in each environment.test_model_load_utils.py.tests/_test_utils/torch/kimi_k3_remote.py, which both PRs import. Two rebases followed, each with its own diff unchanged:modelopt_recipes/ptq.mdkeeps main's new Kimi-K3.1-Pro line next to this PR's, and the CHANGELOG entry moved from 0.49.0, now cut, to 0.50.0's Quantization - Export & Deployment.Review rounds
functools.wraps. Both wrappers now ship in [OMNIML-6079] [1/2] Fix Kimi-K3's own modeling code for current transformers and fla-core #3132.preparekeeps its own forward.w1/w3/w2. Without [OMNIML-6063] [3/3] Load a checkpoint its model spec decompresses through the expert-parallel loader #2747's decompressor fix it fails with an arity mismatch.test_kimi_k3_packed_experts_load_calibrate_and_name_back_expert_parallel.KimiK3Expertsis attributed to transformers'MiniMaxM3VLExperts(file header,LICENSE, license-hook exclusion).AutoModelgets noprepare; without [OMNIML-6076] [3/3] Apply the model spec when deciding and loading expert-parallel #2746's model-class check it fails.prepareinstalls the decompressor before it patches anything (a78d656). The refusal test has the real decompressor refuse an unparsable scheme and a dtype other than bf16. It checks that the remote block, the config, the converter registry, the experts implementations and the loader hooks are unchanged.preparealso reads compression from the checkpoint's ownconfig.json(ea287d8). A config that has lost its scheme and the mark is refused, instead of loading the experts newly initialized.prepareruns only on the expert-parallel route. The spec names its build step, puts its plan ontext_config, and names compressed-tensors among its formats (c459add). New test:test_only_an_expert_parallel_plan_patches_kimi_k3s_code[fsdp2|whole|expert-parallel|expert-parallel-packed].EPSpec.prepare_patches_every_load;test_a_load_after_a_prepare_that_patched_every_load_is_refused[whole|fsdp2]).tie_weights.llm_config.tests/unit/torch/models/kimi_k3/test_ep.py.preparerecords its lasting patch where it makes it (test_a_prepare_that_raises_after_patching_still_records_it). In f186098 that record keys onkimi_k3.ep.MODEL_TYPE.rtol=2**-7), instead of a relative-norm tolerance of 2e-2.test_an_ep_degree_of_1_builds_kimi_k3s_own_code_to_decide[whole|fsdp2]plans a tiny Kimi-K3 atep_size=1through the real meta build.tie_weightsshim.test_the_build_step_installs_nothing_when_there_is_nothing_to_build[no-checkpoint|untrusted]). Before this, five Kimipreparetests failed after the left-whole test ran in the same process.prepare_patches_every_loadalso nameskimi_linear:[its-backbone-whole].__init__passes on any argument beyond the config (test_the_patched_block_takes_what_else_the_remote_one_takes).test_a_prepare_that_patched_every_load_is_recorded_though_it_returns_no_config).test_a_remote_kimi_k3_whose_prepare_attaches_its_plan_left_whole_is_an_errorskips below the spec's transformers release. The tests also pass without transformers.preparerefuses (EPSpec.prepare_refusal).decompression_refusal.quantization_config.quantization_configat every level the decompressor reads one.modelopt_recipes/ortests/unit/recipe/. Kimi-K3's own recipe keeps those projections BF16. The GPU case now disables the latent-expert projections itself.preparechecks the config's model class before it installs the decompressor or any shim (cc447eb).test_prepare_refusal_finds_a_config_naming_no_model_classruns the realprepareand checks that the loader hooks, the config and its scheme are unchanged.preparekeeps its patches on every copy of the checkpoint's code that transformers loads, with_remote_code.keep_patched(99cddd3, 8556cf9).test_prepare_s_patches_stay_on_the_code_loaded_through_another_pathresolves the class through a symlink to the checkpoint.KimiK3Experts' eager loop had summed a token's weighted results in bf16. It now sums them in the routing weights' dtype (fp32 under Kimi-K3's gate) and casts once, as the checkpoint'smoe_infer, transformers' grouped forwards and thetorch_a2acombine do.test_the_eager_loop_sums_a_tokens_results_in_the_routing_weights_dtypecompares the loop in bf16 withmoe_infer's combine of the same bf16 expert results. Without the change, 114 of 384 elements differ.examples/hf_ptq/README.mdandmodelopt_recipes/ptq.mdtell the expert-parallelhf_ptq.pyflow apart from the streaming converter, and the README lists what that flow needs. Its stale footnote said Kimi K3 does not usehf_ptq.py.w1andw3swapped and with the latent norm skipped. A dropped scaling factor fails it through the scale itself only in the 4 variants without the latent norm. The rest of that measurement is in the parity bullet above; this was corrected on 2026-11-12.hf_ptq.pytreats Kimi-K3 with its generic behaviour, as it did before the registry took over its per-model rules.MODELOPT_*knob check included.tests/unit/torch/modelsandtest_model_load_utils.pypassed: 943 on transformers 5.18; 929, with 3 skipped, on 5.13; and 651, with 116 skipped, on 5.5.4.preparekeeps its patches on later copies of the checkpoint's code: it records a callback in_remote_code._KEPT_PATCHESand wrapsget_class_in_module. No fixture of these tests put either back, so a test that ranprepareleft the callback on for later ones.test_an_ep_degree_of_1_builds_kimi_k3s_own_code_to_decidenow asserts that every MoE block of the model the plan decision builds keeps per-expert experts. Without the isolation it fails in the file's order; with it, the file passes.GPU runs of
tests/gpu/torch/utils/test_expert_parallel_load.pyAll runs used transformers 5.18. On 2 GPUs, the cases with a half-width expert-parallel group (
[ep-half]) skip, because they need 4.model.configEnd-to-end run through
hf_ptq.py, 2026-10-25. This used a tiny Kimi-K3 (bf16, 4 layers, 32 experts, KDA and full-attention layers) on 2 GPUs at EP 2, with the dense part replicated:--qformat nvfp4 --kv_cache_qformat fp8;It decided its plan, previewed before and after PTQ on both ranks, calibrated and exported. Before that revision, it had failed while deciding its plan, because
torch_a2awas not registered. With that fixed, it failed ingenerate, on the cache's query offset.Before your PR is "Ready for review"
Is this change backward compatible?: ✅ Additive. One effect reaches beyond the expert-parallel path.
prepare, which only an expert-parallel plan runs, patches the checkpoint's own code for the rest of the process, including later copies of it. A later whole-model or FSDP2 load of Kimi-K3 or kimi_linear in that process is therefore refused (see above).If you copied code from any other sources or added a new PIP dependency, did you follow guidance in
CONTRIBUTING.md: ✅ The fused parameters and eager loop ofKimiK3Expertsare adapted fromMiniMaxM3VLExpertsin transformers v5.18.0 (Apache-2.0).LICENSElists the copyright holder, and the license-header hook excludes the file.flash-linear-attention is a runtime requirement of the checkpoint's own remote code, not of ModelOpt.
Did you write any new necessary tests?: ✅
Did you update Changelog?: ✅ A line for Kimi-K3's expert-parallel PTQ and its prerequisites, beside the expert-parallel entry [OMNIML-6085] Run expert-parallel PTQ from hf_ptq.py, with lockstep previews #3139 added ([OMNIML-6085] [3/3] Run expert-parallel PTQ from hf_ptq.py #2754 was folded into [OMNIML-6085] Run expert-parallel PTQ from hf_ptq.py, with lockstep previews #3139).
Did you get Claude approval on this PR?: ❌ Not as an approval. Claude's review of de4a053 (2026-11-10) found the eager-loop fix correct and no new code issue. It left three things open: the decision on the stand-in, since settled in 729fdce; the pre-merge checks listed under Testing; and the licensing confirmation, which is a human reviewer's call.
Additional Information
Size, by main's rule (AGENTS.md, "Sizing and splitting PRs", as #3163 softened it). About 500 added source lines is a guideline. Tests, docs, config, comments and blank lines don't count.
No split is needed.
This PR is part of expert-parallel PTQ for Hugging Face MoE models; before the series was re-cut on 2026-10-27, it was part 20 of 21.
Summary by CodeRabbit