Skip to content

[OMNIML-6078] Add the Kimi-VL and Kimi-K2.5 expert-parallel adapters - #3138

Merged
shengliangxu merged 51 commits into
mainfrom
shengliangx/hfep-11b0-kimi-vl
Nov 4, 2026
Merged

shengliangxu merged 51 commits into
mainfrom
shengliangx/hfep-11b0-kimi-vl

Conversation

@shengliangxu

@shengliangxu shengliangxu commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Note

#2748 folded in (2026-11-03): at the user's request to fold the series backward, this PR now also carries #2748, the Kimi-K2.5 adapter and prepare on the expert-parallel route only, with its commits as they were. #2748 is closed and keeps its review history; its ticket is this one, OMNIML-6078.

Split out of #2748 at the reviewers' request (2026-10-30), and joined with it again: the Kimi-VL adapter, the patch it shares with the Kimi-K2.5 adapter, the shared deepseek_v3 plan, and the Kimi-K2.5 adapter.

Base: main, which holds what this PR builds on since they merged on 2026-11-03: #3137 (on-the-fly decompression, with #2747 folded in) and #2780 (the model specs, with #2746 folded in), and the remote-code helpers (#3130). The branch shengliangx/hfep-base-11b-kimi that joined #2780 and #3137 for this PR is retired.

Series layout

What does this PR do?

Type of change: New feature

Kimi-VL ships its own modeling. It builds the language model's MoE from an nn.ModuleList of per-expert Linears, which transformers' expert-parallel machinery cannot shard. Its text backbone is DeepSeek-V3, so the adapter swaps in transformers' native deepseek_v3 language model (fused gate_up_proj/down_proj experts, and the plan to shard them). It keeps the bundled vision tower and projector from the checkpoint's own code.

  • The patch Kimi-VL and Kimi-K2.5 share, in modelopt/torch/models/_kimi.py:
    • Refusals before anything changes: transformers' own Kimi-K2.5 port (from 5.13) of a quantized checkpoint, which the patch never reaches (the port of an unquantized one loads as it is, below); a config with no text_config; a missing checkpoint path; untrusted remote code (get_class_from_dynamic_module runs the checkpoint's code without checking trust_remote_code); and a quantization scheme on text_config alone, which the native text config drops.
    • Import shims for the symbols the checkpoint's modeling imports that transformers 5 dropped (is_torch_fx_available, ...). They stub only code paths the native language model never runs.
    • The swap itself: the checkpoint's module-level DeepseekV3ForCausalLM builds the native class from the native DeepseekV3Config prepare puts on text_config, and the checkpoint's own class from its own config. A tie_weights wrapper covers the recompute_mapping newer transformers passes. A remote module that defines no module-level DeepseekV3ForCausalLM stops the load instead of passing for already patched.
    • Why the swap reads the config: deciding the plan runs prepare on a copy of the config on every rank before the plan is known, and the patch lasts for the process. A plan that then keeps the load off expert parallelism (replicated, or FSDP2) builds from the config as read, so it gets the checkpoint's own language model, as with no patch. Before, the native class was handed the checkpoint's own text config, which it cannot take. The other effects of prepare are harmless off expert parallelism: the import shims only add symbols the remote code imports, the staging copies its sibling modules, the tie_weights wrapper only drops keyword arguments for these untied checkpoints, and Kimi-K2.5's decompressor rewrites only the configs it marked, which are the prepared copies.
    • The swap is kept, through keep_patched ([OMNIML-6063] [1/3] Stage and keep patched a checkpoint's own modeling code #3130), on a module transformers executes again or loads again under another name. The reasons are in [OMNIML-6063] [1/3] Stage and keep patched a checkpoint's own modeling code #3130's description.
    • Rank 0 only: the adapters' notes and the shims' warnings print there, labeled kimi.
  • The native backbone config: to_native_backbone_config, in _onfly_decompress.py, rebuilds the VLM's bundled text config as a native transformers backbone config, carrying the decompression mark. Both adapters' prepare call it; it moved here from [OMNIML-6063] [2/2] Decompress compressed-tensors MoE experts as they load, expert-parallel loads included #3137, which has no caller of it.
  • The adapter is an EPSpec.prepare hook on the kimi_vl spec, so nothing outside modelopt/torch/models learns about Kimi.
    • The spec registers only the expert-parallel section. The MoE and export sections stay deepseek_v3's, and sharing them is left to a follow-up.
    • The spec states the plan prepare attaches (EPSpec.prepared_ep_plan, [OMNIML-6076] [3/3] Apply the model spec when deciding and loading expert-parallel #2746): deepseek_v3's, now a shared BASE_MODEL_EP_PLAN. So a run at an EP degree of 1, which skips prepare, still finds the experts the checkpoint's own code builds, and refuses to hold them whole on every rank.
The adapter's walkthrough (moved from kimi_vl/ep.py's module docstring)
DP=EP a2a support for Kimi-VL-A3B (``kimi_vl``).

a remote-code VLM whose text backbone is a Moonlight (DeepSeek-V3-lite: MLA, ``q_lora_rank=None``, 64 routed experts, 2
shared) MoE and whose vision tower is MoonViT. The bf16 sibling of ``kimi_k25`` -- SAME shape, but NO compressed-tensors
decompressor (the checkpoint ships plain bf16 per-expert weights).

Challenge (identical to kimi_k25): the bundled ``modeling_kimi_vl.py`` builds its language model from
an INLINE ``DeepseekV3ForCausalLM`` whose ``DeepseekV3MoE`` is an ``nn.ModuleList`` of per-expert
``gate_proj``/``up_proj``/``down_proj`` Linears -- incompatible with transformers' EP machinery, which
needs the FUSED 3-D ``gate_up_proj``/``down_proj`` Parameters the transformers-native ``deepseek_v3``
modeling ships.

Solution (mirrors kimi_k25):
  1. Shim the import symbols ``modeling_kimi_vl`` needs that newer transformers dropped (e.g.
     ``is_torch_fx_available``) so the module IMPORTS -- they only guard torch.fx / legacy attn-mask
     paths that our native-LM + MoonViT forward never execute.
  2. Swap ``hf_config.text_config`` to a transformers-native ``DeepseekV3Config`` (drops the remote
     ``auto_map`` so the native class -- and its ``base_model_ep_plan`` -- is used for the LM).
  3. Apply the deepseek_v3 EP plan to that native ``text_config`` (post_init prefixes it to the VLM
     root as ``language_model.model.layers.*.mlp.experts.{gate_up_proj,down_proj}``).
  4. Monkey-patch ``modeling_kimi_vl.DeepseekV3ForCausalLM`` -> the transformers-native class, so
     ``KimiVLForConditionalGeneration.__init__`` (``self.language_model = DeepseekV3ForCausalLM(
     config.text_config)``) builds the EP-capable native LM while MoonViT + the KimiVL wrapper stay
     from the bundled code. Native deepseek_v3's per-expert WeightConverter fuses the checkpoint's
     per-expert ``.weight`` tensors into the 3-D params on load (no decompressor -- weights are bf16).

Version: no floor beyond the EP framework's 5.7; validated on transformers 5.9.0. The compat shims
stand in for the symbols the remote code imports that later releases dropped.

The Kimi-K2.5 adapter (folded in from #2748):

Kimi-K2.5 (and Kimi-K2.6 and Kimi-K2.7-Code, which share its model type) is Kimi-VL's shape with compressed-tensors INT4 experts. Its adapter swaps in transformers' native deepseek_v3 language model as Kimi-VL's does (above), through the patch they share, and decompresses the experts as they load (#3137).

  • Install order. The checkpoint's config.json keeps the compressed-tensors config under text_config, and its config class also copies it to the top level, which the expert-parallel load drops. prepare installs the decompressor first of all, so a checkpoint the decompressor refuses leaves the config and the loader untouched.
  • Which checkpoints decompress. It installs the decompressor only for a checkpoint whose quantization_config declares compressed-tensors, as Kimi-K2.5, K2.6 and K2.7-Code all do.
    • A bf16 checkpoint of the model type loads as Kimi-VL's does.
    • Any other scheme is left to the expert-parallel load's format handling, which reads the copy of quantization_config the config class keeps on the top level.
    • A scheme on text_config alone, with no top-level copy, is refused before anything changes.
  • transformers floor. The spec declares the transformers 5.8 the decompression needs.

prepare now runs only on the expert-parallel route. Before, the plan decision ran a model spec's prepare on a copy of the config before the plan was known, and the Kimi patches it made (the swapped language-model class, the decompressor's loader hooks) stayed in the process when the plan came out FSDP2-sharded, or whole and refused. Now:

  • the decision reads the plan the spec states (prepared_ep_plan, on text_config for both Kimi specs) and finds the experts through it in the model the checkpoint's own code builds;
  • before that it runs only EPSpec.make_buildable, what the checkpoint's own code needs to import and build on the installed transformers: the import shims, the staging of the code's two-deep imports, and the VLM class's tie_weights adapted to the keyword arguments post_init passes it. It changes nothing the model computes or loads, warns rather than fails where it cannot adapt the class, and patches no MoE or expert class, config, weight converter or weight-loading hook;
  • it asks the spec why prepare would refuse this checkpoint (EPSpec.prepare_refusal), found without changing anything: transformers' own Kimi-K2.5 port of a quantized checkpoint, code the load may not run, experts the decompressor cannot take. With the EP degree left to auto, such a checkpoint is planned without expert parallelism, with the decision's warning;
  • only an expert-parallel plan then runs prepare, on every rank, and returns that config; any other plan returns the config as read.

EPSpec.prepare's, prepared_ep_plan's and resolve_distribution_plan's docs say so, replacing #2746's interim contract. Kimi-VL's spec takes it too, and Kimi-K3 (#2749), on this PR, uses it.

transformers' own Kimi-K2.5 port. transformers 5.13 added a Kimi-K2.5 port, which a load without trust_remote_code builds. Its language model is a native deepseek_v3 with fused experts, and its text config carries deepseek_v3's plan:

  • An unquantized checkpoint read that way loads expert-parallel on that plan without these patches, as it did before this PR: the adapter's prepare_refusal and prepare leave its config as it is.
  • A quantized checkpoint read that way is refused before anything changes, naming trust_remote_code=True from a checkpoint whose auto_map names its own AutoConfig as the way in: here only the checkpoint's own code decompresses its experts.
  • Export names: the port re-implements the vision tower and the projector under other names. Its load-time conversions rename the vision blocks' norms, MLPs and output projection and the projector, and split the fused wqkv into q/k/v, so its export names differ from the checkpoint's however it is distributed. Mapping them back is a question for the export.

The spec records the 5.13 release.

Why it patches the checkpoint's module, and again on every class resolution: see #3130, where keep_patched lives.

  • The VLM class builds its language model from a name it looks up in its module's globals.
  • transformers re-executes or re-imports that module under the loaders that resolve the class.

Usage

Picked automatically by apply_distributed_support for kimi_vl and kimi_k25 configs under torchrun; see #2754.

Testing

Tests folded in from #2748:

  • tests/unit/torch/models/kimi_k25/test_ep.py, against a stand-in remote module, covers:

    • the text config rebuilt as a clean native DeepseekV3Config for compressed-tensors, bf16 and block-FP8 experts, with the decompressor installed for compressed-tensors ones only. The bf16 and block-FP8 cases fail with an unconditional install.
    • the decompressor installed first, while the scheme on text_config is still present, and a decompressor refusal leaving text_config and the remote-code staging untouched;
    • transformers 5.7 refused by the spec.
  • The shared adapter tests (tests/unit/torch/models/kimi_vl/test_ep.py) and the remote-Kimi refusal test in test_model_load_utils.py gain their Kimi-K2.5 cases.

  • The plan decision with prepare on the expert-parallel route only:

    • test_only_an_expert_parallel_plan_patches_the_checkpoint_s_code[fsdp2|whole|expert-parallel] runs the real Kimi-VL and Kimi-K2.5 prepare through the decision; only an expert-parallel plan patches the checkpoint's code;
    • test_a_checkpoint_its_spec_decompresses_is_decided_expert_parallel: a compressed-tensors Kimi-K2.5 checkpoint left to the decision is planned expert-parallel, and a Kimi-VL one is not;
    • the build step (make_buildable) lets the checkpoint's own VLM build on transformers 5.18 (test_the_build_step_lets_the_checkpoint_s_own_vlm_build_on_this_transformers), installs nothing when there is nothing to build, and runs at an EP degree of 1 too (test_an_ep_degree_of_1_builds_the_checkpoint_s_own_vlm_to_decide);
    • test_ep_specs.py's spec-field checks: a spec with a prepare states its plan, and a build step, decompressed formats or a prepared plan each come with a prepare.
  • The decision's cost, measured on the real Kimi-K2.5 code and config (61 layers, 384 routed experts) on the meta device, transformers 5.18, one process; only rank 0 builds:

    The decision builds Build time Modules Parameters Peak host RSS
    the prepared config: native DeepSeek-V3, fused experts (before) 0.59 s 1,455 1,250 0.62 GiB
    the checkpoint's own code: per-expert experts (after) 31.6 s 116,655 70,310 5.16 GiB
  • Real-model runs, as [OMNIML-6078] [2/2] Add the Kimi-K2.5 expert-parallel adapter #2748 recorded them (with the module-reload fix, through the decompressor): Kimi-K2.7-Code, expert-parallel over 32 GPUs (8 nodes, EP32), transformers 5.13.0, compressed-tensors 0.17.1, recipe nvfp4_experts_only_mse-kv_fp8_cast, 4096 calibration samples of 4096 tokens, batch 1. Load, calibration and export completed:

    Runs Count Result
    without the reload fix, first 1 failed before loading weights: some ranks built the checkpoint's own DeepseekV3ForCausalLM on the native config
    without the reload fix, later 2 load, calibration and export completed
    with the reload fix 2 load, calibration and export completed, through the decompressor
  • [OMNIML-6078] [2/2] Add the Kimi-K2.5 expert-parallel adapter #2748's dated testing history stays on [OMNIML-6078] [2/2] Add the Kimi-K2.5 expert-parallel adapter #2748.

Before your PR is "Ready for review"

  • Is this change backward compatible?: ✅ Additive. Registering the Kimi-VL and Kimi-K2.5 specs reaches beyond the expert-parallel load only in the plan decision of a multi-rank run: every rank runs the spec's build step (make_buildable: the import shims, the staging of the code's imports, and tie_weights adapted to the keyword arguments post_init passes), which changes nothing the model computes or loads. prepare runs only once the plan is decided expert-parallel. A run that would leave an expert-parallel-capable MoE whole on every rank, with nothing asking for that, is refused, as other expert-parallel MoEs are. A single-process load is unchanged.
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: N/A. The feature's entry lands with [OMNIML-6085] [3/3] Run expert-parallel PTQ from hf_ptq.py #2754.
  • Did you get Claude approval on this PR?: ❌ Not yet for the folded change; requested on 2026-11-03.

Additional Information

Part of expert-parallel PTQ for Hugging Face MoE models: the Kimi-VL and Kimi-K2.5 adapters, which #2748's split had made [1/2] (this PR) and [2/2] (#2748), are one PR again.

Jira: OMNIML-6078, which #2748 shared.

Summary by CodeRabbit

  • New Features
    • Added expert-parallel loading support for Kimi-VL and Kimi-K2.5, including compatible K2.6 and K2.7-Code checkpoints.
    • Supported Kimi-K2.5 compressed checkpoints can now be decompressed during expert-parallel loading.
    • Kimi-VL vision components are retained while its language model uses native DeepSeek-V3 support.
  • Improvements
    • Checkpoint compatibility is checked before expert-parallel preparation. Automatic selection can fall back to standard loading with a warning; explicitly requested expert parallelism reports why it cannot proceed.
    • Preparation runs only when expert-parallel loading is selected.

@shengliangxu
shengliangxu requested review from a team as code owners October 30, 2026 00:31
@shengliangxu
shengliangxu requested review from cjluo-nv and meenchen and removed request for a team October 30, 2026 00:31
@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

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.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The changes add Kimi-VL and Kimi-K2.5 expert-parallel adapters. They separate expert-parallel plan selection from preparation, add preparation-refusal checks, and extend decompression validation and native backbone config conversion.

Changes: Expert-parallel planning and preparation

Layer / File(s) Summary
Expert-parallel planning and preparation
modelopt/torch/models/specs.py, modelopt/torch/utils/moe.py, modelopt/torch/utils/plugins/model_load_utils.py, tests/unit/torch/models/test_ep_specs.py, tests/unit/torch/utils/test_model_load_utils.py, tests/unit/torch/utils/test_unplaced_source_keys.py
EP specs now define buildability, preparation-refusal, and decompressed-format hooks. Distribution planning checks refusals before selecting EP, separates buildability from preparation, and prepares the config only for an EP plan. Tests cover staged planning and preparation behavior.
Decompression checks and native backbone conversion
modelopt/torch/models/_onfly_decompress.py, tests/unit/torch/models/test_onfly_decompress.py
Decompression validation now checks installation conditions before loader changes and can report refusals. VLM text configs can be converted to native backbone configs with remote-code and quantization metadata removed.
Kimi adapters and model registration
modelopt/torch/models/__init__.py, modelopt/torch/models/_kimi.py, modelopt/torch/models/deepseek_v3/specs.py, modelopt/torch/models/kimi_k25/*, modelopt/torch/models/kimi_vl/*
Kimi model packages register EP specs. Their adapters validate remote-code checkpoints and prepare text configs for DeepSeek-V3 EP. Shared helpers stage remote imports and patch language-model construction.
Kimi adapter and distributed loading validation
tests/_test_utils/torch/kimi_vl_tiny_modeling.py, tests/unit/torch/models/kimi_k25/*, tests/unit/torch/models/kimi_vl/*, tests/gpu/torch/utils/test_expert_parallel_load.py
Tests cover adapter preparation, native model substitution, refusal cases, and remote-code compatibility. The distributed GPU test checks expert placement, vision and projector weights, and logits.

Estimated code review effort: 4 (Complex) | ~50 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant ModelLoadUtils
  participant KimiEPSpec
  participant KimiAdapter
  participant TransformersLoader
  ModelLoadUtils->>KimiEPSpec: Check refusal and select an EP plan
  ModelLoadUtils->>KimiAdapter: Prepare the selected EP configuration
  KimiAdapter->>KimiAdapter: Convert text_config and patch language-model construction
  ModelLoadUtils->>TransformersLoader: Load the prepared model
Loading
Merge Risk: Minimal · previous review f48c6

The previously reported test-comment issue is fixed; no remaining issue in this review prevents merging after normal checks.

Pre-merge checks: Passed 5 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 76.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 5 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely identifies the main change: adding Kimi-VL and Kimi-K2.5 expert-parallel adapters.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed No listed security anti-pattern was introduced in changed modelopt or examples Python code. Remote-code loader calls pass the caller-controlled trust_remote_code value, whose adapter defaults ar…
Full details: Security Anti-Patterns

Explanation

No listed security anti-pattern was introduced in changed modelopt or examples Python code. Remote-code loader calls pass the caller-controlled trust_remote_code value, whose adapter defaults are False; no hardcoded trust_remote_code=True loading call exists. The diff adds no torch.load, numpy.load(..., allow_pickle=True), eval, exec, or # nosec, and it changes no dependency files.

Full details: Docstring Coverage

Explanation

Docstring coverage is 76.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 64 functions across 23 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

Finishing Touches
Generate docstrings
  • Commit to this branch
  • Create a new PR
Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.
Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between e2550e9 and f48c6eb.

Files selected for processing: 1
  • tests/unit/torch/utils/test_model_load_utils.py
Files skipped from review as they are similar to previous changes: 1
  • tests/unit/torch/utils/test_model_load_utils.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 8 remain after this review.

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 3dbb3e2

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

Comment on lines +118 to +128
def _drop_tie_weights_kwargs(orig_tie):
"""Wrap a remote ``tie_weights()`` that predates the kwargs newer transformers pass to it.

Dropping ``missing_keys`` as well as ``recompute_mapping`` is safe because the remote
``tie_weights`` only calls its language model's, and the Kimi checkpoints set
``tie_word_embeddings=False``: nothing is tied, so no tied key is left to report to the load.
"""

def _tie_weights(self, *args, **kwargs): # drop recompute_mapping etc.
return orig_tie(self)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] The shim's safety rests on tie_word_embeddings=False, which nothing checks at runtime.

Dropping recompute_mapping is unconditionally fine, but dropping missing_keys is only fine under the docstring's premise that nothing is tied. to_native_backbone_config carries tie_word_embeddings over from the remote text_config verbatim, so a Kimi-VL/K2.5 variant (or a user-edited config) that ties embeddings would silently lose the tied-key bookkeeping: the native LM ties the weight but lm_head.weight is never removed from the load's missing_keys, so a strict load reports a spurious missing key — or, depending on the release's ordering, re-initializes it.

Cheap guard inside the wrapper, where the config is reachable:

def _tie_weights(self, *args, **kwargs):  # drop recompute_mapping etc.
    text_config = getattr(self.config, "text_config", self.config)
    if getattr(text_config, "tie_word_embeddings", False):
        raise RuntimeError(
            "kimi: the tie_weights shim drops missing_keys, which is only safe for an untied "
            "checkpoint, but this one sets tie_word_embeddings=True."
        )
    return orig_tie(self)

That turns an assumption documented in a comment into one the code enforces, at no cost on the supported checkpoints.

(2) Why it matters: the failure is silent-to-confusing at load time rather than at patch time, on a path that only triggers for a checkpoint nobody tested. (3) Fix: the guard above, or state the assumption as a refusal in checkpoint_to_patch next to the other pre-patch refusals.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Declined. I'm not adding the guard, because a tied checkpoint loads correctly through the shim. I documented what the shim loses instead, in d6ca10f.

I checked this with a small VLM whose tie_weights() takes no kwargs, as the Kimi remote code's does, wrapped by this shim:

  • Its native DeepSeek-V3 language model has tie_word_embeddings=True.
  • I saved it without lm_head.weight and loaded it with from_pretrained.
  • On transformers 5.18 and 5.5.4, lm_head.weight comes back as the same tensor as the embedding, holding the saved values.
  • The only loss is the bookkeeping: lm_head.weight stays in the load's missing-keys report. Nothing is re-initialized.

A refusal would therefore block a load that works. No supported checkpoint is tied in any case: Kimi-VL-A3B (Instruct and Thinking-2506) and Kimi-K2.5, K2.6 and K2.7-Code all set tie_word_embeddings=false at the top level and on text_config.

Comment thread modelopt/torch/models/kimi_vl/specs.py Outdated
model_type="kimi_vl",
modeling_source="remote_code",
# prepare swaps a native deepseek_v3 in as the language model, with deepseek_v3's plan.
ep_spec=EPSpec(prepare=prepare, prepared_ep_plan=BASE_MODEL_EP_PLAN),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] With only the EP section registered, is_moe(block, "kimi_vl") returns False for the very blocks prepare installs.

The docstring says the MoE/export sections "stay deepseek_v3's, so lookups by kimi_vl find neither yet", but it's worth being explicit about what that costs, because is_moe has fallbacks that do not rescue this case. After prepare, the language model's MoE blocks are native DeepseekV3MoE, and:

  • match_moe_block(module, "kimi_vl") → the spec has no moe_spec → None;
  • the name fallback misses ("deepseekv3moe" ends in neither sparsemoeblock nor contains moelayer);
  • the structural fallback misses (the router is gate, not router).

That is exactly what deepseek_v3/specs.py documents as the reason it needs block_names=("DeepseekV3MoE",). So modelopt/torch/export/unified_export_hf.py:565/:949 and layer_utils.py:369 will skip the experts of a kimi_vl model rather than fail loudly. get_expert_linear_names happens to survive via its fused-container fallback, which makes the gap quieter, not smaller.

Nothing in this PR reaches those call sites, and kimi_vl was unregistered before, so there's no regression — hence a suggestion rather than a blocker. But since the follow-up that wires the PTQ entrypoint (#2754) will need it, and BASE_MODEL_EP_PLAN already establishes the precedent of sharing deepseek_v3's constants, reusing its sections here is a two-line change that closes the hole before anything can silently take the non-MoE path:

from ..deepseek_v3.specs import BASE_MODEL_EP_PLAN
from ..specs import EPSpec, ExportSpec, ModelSpec, MoESpec, register

register(
    ModelSpec(
        model_type="kimi_vl",
        modeling_source="remote_code",
        # prepare swaps a native deepseek_v3 in as the language model, with deepseek_v3's plan.
        ep_spec=EPSpec(prepare=prepare, prepared_ep_plan=BASE_MODEL_EP_PLAN),
        # prepare's language model is native deepseek_v3: its MoE blocks and export are too.
        moe_spec=MoESpec(
            block_names=("DeepseekV3MoE",),
            expert_linear_names=("gate_proj", "down_proj", "up_proj"),
            ...,  # deepseek_v3's, ideally hoisted to a shared constant as the plan was
        ),
        export_spec=ExportSpec(grouped_expert_export=True),
    )
)

If you'd rather keep this PR to the EP section, consider making the gap loud instead of silent — e.g. have the follow-up tracked in the docstring name the lookups that miss (is_moe, hence the HF export's expert handling), so the next reader doesn't read "find neither yet" as "falls back to the generic detection".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Taking the docstring half in d6ca10f; the shared sections stay with the follow-up.

The docstring now names the miss: is_moe's name and structure fallbacks do not recognize the native DeepseekV3MoE blocks that prepare installs, so the HF export's MoE-block handling skips them. #2748 adds the same sentence to Kimi-K2.5's spec, which has the same gap.

I'm keeping the sections out of this PR because registering them changes how the HF export treats these models:

  • It enables the MoE pre-processing at the two export call sites you name.
  • It enables grouped expert export.

That needs its own real-model export check, for both Kimi-VL and Kimi-K2.5 together. Today, for the fused experts these models load with, the skipped input-preparation handler is a no-op, since the amax fallback for fused experts runs during export. The AWQ pre_quant_scale averaging is the step that is actually skipped.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Claude review passed — no blocking issues found. LGTM

Scope: full review (the trigger comment carried no extra scoping). All 8 changed files opened (638 added lines): modelopt/torch/models/{_kimi.py, kimi_vl/{__init__,ep,specs}.py, deepseek_v3/specs.py, __init__.py} and both test files. Also read the base-branch machinery the adapter rides on — _remote_code.py (keep_patched, stage_full_remote_closure), _onfly_decompress.to_native_backbone_config, specs.py (EPSpec), utils/moe.py (apply_distributed_support, _ep_config, _routed_expert_keys, is_moe) — since the correctness of this PR is almost entirely in how it composes with them.

Findings

CRITICAL: 0 · IMPORTANT: 0 · SUGGESTION: 2

  1. _kimi.py:118 — the tie_weights shim drops missing_keys on the premise tie_word_embeddings=False, which nothing enforces; to_native_backbone_config carries that flag over from the remote config verbatim. A one-line guard in the wrapper turns the documented assumption into an enforced one.
  2. kimi_vl/specs.py:37 — registering only the EP section means is_moe(block, "kimi_vl") is False for the native DeepseekV3MoE blocks prepare installs: both of is_moe's fallbacks miss it (name doesn't end in sparsemoeblock; router is gate, not router), which is precisely why deepseek_v3 needs block_names. Not a regression — kimi_vl was unregistered before, and no path here reaches the export call sites — but the follow-up will need it and it's a two-line reuse.

What I checked and found correct

  • Plan plumbing. prepare attaches the plan to text_config, and _ep_config reads the nested text config when the root has none, so the globs land on the tree they're written against. plan_config_attr being unset is right: base_model_ep_plan is None on this spec, so the attr never selects a target.
  • prepared_ep_plan vs. what prepare actually attaches. The stated plan's routed-expert keys reduce to {layers.*.mlp.experts} under _routed_expert_keys — identical whether modelopt's BASE_MODEL_EP_PLAN or transformers' own 5.13 plan wins, since the extra ep_router gate entry is in neither _EXPERTS_STYLES nor grouped_gemm. So the EP-degree-1 refusal finds the ModuleList experts the checkpoint's own code builds (language_model.model.layers.*.mlp.experts, matched by endswith), and the test asserts exactly this equivalence rather than the literal dict.
  • No aliasing through the shared constant. BASE_MODEL_EP_PLAN is now one dict referenced by two specs, but every consumer copies (dict(ep.base_model_ep_plan) in apply_distributed_support, dict(...) in _spec_ep_plan), so neither spec can mutate the other's plan.
  • Refuse-before-mutate. All five refusals in checkpoint_to_patch / refuse_quantization_only_on_text_config run before the shims, the staging wrapper, the config swap and the remote import — and the test asserts the loader is left unwrapped and the checkpoint's code unimported. The trust_remote_code refusal in particular is load-bearing, since get_class_from_dynamic_module doesn't check it itself. The startswith("transformers.") port test doesn't false-positive on transformers_modules.* (the trailing dot).
  • Shim targets match the remote import sites. The three stubs are set on the submodules DeepSeek's remote modeling imports from directly (transformers.utils.import_utils, transformers.pytorch_utils, transformers.modeling_attn_mask_utils), not on the transformers.utils namespace — which is what makes from X import Y see them. is_torch_fx_available() -> False keeps the torch.fx.wrap branch (and hence the _prepare_4d_causal_attention_mask stub) unreached; the stub raises rather than returning something plausible, which is the right call.
  • Patch durability. keep_patched is given the module suffix, so the swap survives transformers re-executing the module or loading it afresh under another hash — and since re-execution rebinds the VLM class too, to_native's early return False on an already-native module can't leave a fresh unshimmed tie_weights behind. Failing loudly when there's no module-level DeepseekV3ForCausalLM, rather than treating it as "already patched", is the correct choice: silence there would build the per-expert layout EP cannot shard.
  • Version floor. ep.py's "no floor beyond the EP framework's 5.7" matches _EP_MIN_TRANSFORMERS = "5.7", so the omitted requires_transformers is right, and the test's module-level skip agrees.
  • Lazy imports. modelopt.torch.utils{,.moe} are imported inside functions with the circularity reason named; _remote_code is stdlib-only at module scope, so the registry import stays clean.
  • Tests. The refusal table, both loud-failure modes, shim installation, idempotency of the tie_weights wrap, and the EP-degree-1 refusal against a ModuleList stand-in are all covered, with process-wide patches restored per test. The install_onfly_decompress monkeypatch in the first test is vacuous for Kimi-VL (bf16, nothing calls it) but reads as a deliberate guard on the shared path, so I left it alone.

Risk

Low. Additive and confined to the expert-parallel path: a new model type, one shared helper module, and a constant hoisted out of deepseek_v3's spec with no behavior change (the comment that moved with it is intact and still accurate). The only process-wide mutations are idempotent and installed after the refusals. The 184-line _kimi.py is shared with #2748, so its two parametrize lists standing at one entry each is expected rather than dead scaffolding.

🤖 Generated with Claude Code

@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-11b0-kimi-vl branch from 3dbb3e2 to e41e06d Compare October 30, 2026 00:59
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-base-11b-kimi branch from 6c49640 to 0864f57 Compare October 30, 2026 00:59
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test e41e06d

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test d6ca10f

@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-base-11b-kimi branch from 0864f57 to a5d243e Compare October 30, 2026 01:52
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-11b0-kimi-vl branch from d6ca10f to 4a459dc Compare October 30, 2026 01:52
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 4a459dc

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 9e2cd9a

@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/claude review

Comment on lines +134 to +149
def _native_for_the_prepared_config(own_class, native_class):
"""The ``DeepseekV3ForCausalLM`` the patched module builds its language model with.

transformers' native class for the native ``DeepseekV3Config`` ``prepare`` puts on
``text_config``, and the checkpoint's own class for its own config. Deciding the plan prepares a
copy of the config before the plan is known, and the patch outlives that copy: a load the plan
keeps off expert parallelism builds from the config as read, and so gets the checkpoint's own
language model, as it would with no patch.
"""
from transformers import DeepseekV3Config

def build(config, *args, **kwargs):
built = native_class if isinstance(config, DeepseekV3Config) else own_class
return built(config, *args, **kwargs)

setattr(build, "_kimi_native_swap", True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] The swap now binds a plain function where a class used to live, so modeling_kimi_vl.DeepseekV3ForCausalLM stops behaving like a class for anything other than a direct call.

Under the two routes this PR exercises that holds — the LM is only ever built by the VLM's self.language_model = DeepseekV3ForCausalLM(config.text_config) — but any class-shaped access on that name now fails with an opaque AttributeError/TypeError instead of working: .from_pretrained, ._from_config, .config_class, issubclass, or AutoModelForCausalLM.from_config(text_config) resolving a text_config.auto_map["AutoModelForCausalLM"] that names modeling_kimi_vl.DeepseekV3ForCausalLM (a non-EP run keeps the checkpoint's auto_map on text_config, and keep_patched's get_class_in_module wrapper hands the patched binding back to from_pretrained). _BaseAutoModelClass.register would even accept it, since hasattr(build, "config_class") is False, and only fail a line later on _from_config.

A callable object that forwards attribute lookups to the native class keeps the dispatch and the class-like surface, for about the same number of lines:

def _native_for_the_prepared_config(own_class, native_class):
    """..."""
    from transformers import DeepseekV3Config

    class _Build:
        _kimi_native_swap = True

        def __call__(self, config, *args, **kwargs):
            built = native_class if isinstance(config, DeepseekV3Config) else own_class
            return built(config, *args, **kwargs)

        def __getattr__(self, name):  # from_pretrained, config_class, ... land on the native class
            return getattr(native_class, name)

    return _Build()

getattr(current, "_kimi_native_swap", False) in to_native keeps working unchanged. If you'd rather keep the function, a sentence in the docstring saying the binding is no longer a class, and that only a direct call is supported, would at least make the constraint explicit for the next reader.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Kept as a function: nothing reaches this name except the direct call.

  • The checkpoints' own code. In both Kimi-VL's modeling_kimi_vl.py and Kimi-K2.5's modeling_kimi_k25.py, the module-level name's only use is self.language_model = DeepseekV3ForCausalLM(config.text_config). Nothing takes isinstance/issubclass of it, subclasses it, or reads an attribute from it.
  • transformers' auto paths. get_class_in_module, including the keep_patched wrapper, is only asked for names an auto_map declares.
    • The top-level auto_maps name the VLM classes.
    • Kimi-VL's text_config has no auto_map.
    • Kimi-K2.5, K2.6 and K2.7-Code name modeling_deepseek.DeepseekV3ForCausalLM. That module's class is the one the swap leaves alone: the swap rebinds only the name modeling_kimi_k25 imported, and keep_patched applies only to modules named *.modeling_kimi_k25 / *.modeling_kimi_vl.
  • Our code. ModelOpt refers to DeepseekV3ForCausalLM only as an architecture string.

The forwarding object would also make config_class, from_pretrained and similar answer for the native class even when the call would build the checkpoint's own. A docstring line stating the call-only contract is owed for this PR's next push.

Comment thread modelopt/torch/models/kimi_vl/ep.py Outdated
Comment on lines +32 to +42
2. Swap ``hf_config.text_config`` to a transformers-native ``DeepseekV3Config`` (drops the remote
``auto_map`` so the native class -- and its ``base_model_ep_plan`` -- is used for the LM).
3. Apply the deepseek_v3 EP plan to that native ``text_config`` (post_init prefixes it to the VLM
root as ``language_model.model.layers.*.mlp.experts.{gate_up_proj,down_proj}``).
4. Monkey-patch ``modeling_kimi_vl.DeepseekV3ForCausalLM`` -> the transformers-native class, so
``KimiVLForConditionalGeneration.__init__`` (``self.language_model = DeepseekV3ForCausalLM(
config.text_config)``) builds the EP-capable native LM while MoonViT + the KimiVL wrapper stay
from the bundled code. Native deepseek_v3's per-expert WeightConverter fuses the checkpoint's
per-expert ``.weight`` tensors into the 3-D params on load (no decompressor -- weights are bf16).

Version: no floor beyond the EP framework's 5.7; validated on transformers 5.9.0. The compat shims

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[SUGGESTION] Three lines of this module docstring now describe the swap as it was before _native_for_the_prepared_config landed, and one records a transformers version the PR no longer tests:

  • Step 2 (line 32-33) and the comment on line 67 both say dropping the remote auto_map is what makes the native class get used for the LM. It is not, any more: the VLM's __init__ calls the module-level DeepseekV3ForCausalLM, and which class that builds is now decided by isinstance(config, DeepseekV3Config). Dropping auto_map still matters (it keeps text_config from naming remote classes), but it is no longer the mechanism.
  • Step 4 (line 36) says the patch points the name at "the transformers-native class". It points it at a factory that picks the native class for the prepared config and the checkpoint's own class for the config as read — which is the whole point of the load-off-EP fix, and the one thing a reader of this file would most want to know.
  • Line 42 says "validated on transformers 5.9.0", while the PR reports 5.5.4 and 5.18.

Per CLAUDE.md's "Keep skill/doc edits concise … comments say why, not what", this is a tightening pass rather than new text — e.g. fold steps 2 and 4 into one line saying the native config selects the native LM, and update the version to the pair actually run.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed; postponed to this PR's next push to save a CI round on an approved PR. The pass will:

  • fold steps 2 and 4 into one line saying the native config selects the native language model, and that dropping auto_map only keeps text_config from naming remote classes;
  • describe step 4 as the per-config build;
  • replace "validated on transformers 5.9.0" with the versions this PR runs.

Kimi-K2.5's module docstring in #2748 says the same about the swap, so it gets the same pass.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Claude review passed — no blocking issues found. LGTM

Scope: full review (the trigger comment carried no extra scoping). All 8 changed files opened (686 added lines): modelopt/torch/models/{_kimi.py, kimi_vl/{__init__,ep,specs}.py, deepseek_v3/specs.py, __init__.py} and both test files. The checkout is shallow, so I could not diff against the previously-approved head (3dbb3e2) directly and re-reviewed the whole PR diff instead; per the description the only code delta since that approval is _native_for_the_prepared_config, plus docstrings answering last round's two suggestions.

Findings

CRITICAL: 0 · IMPORTANT: 0 · SUGGESTION: 2

  1. _kimi.py:134 — the swap now binds a plain function where a class was, so .from_pretrained / ._from_config / .config_class / issubclass on modeling_kimi_vl.DeepseekV3ForCausalLM fail opaquely. Correct for the two routes here (the LM is only ever built by a direct call), but a callable object forwarding __getattr__ to the native class keeps the class-like surface for the same line count.
  2. kimi_vl/ep.py:32 — three docstring lines (steps 2 and 4, and the comment on line 67) still say dropping the remote auto_map is what selects the native LM; the factory's isinstance check is. And line 42's "validated on transformers 5.9.0" is behind the 5.5.4/5.18 the PR reports.

What I checked and found correct

  • The new fix is right, and necessary. resolve_distribution_plan returns prepared[0] only when plan.is_expert_parallel, and the unprepared hf_config otherwise (model_load_utils.py:1789) — while the patch is process-wide, installed by the apply_distributed_support every rank ran before the plan was known. So a replicate or FSDP2 plan builds the VLM from the config as read, and previously handed the native class the checkpoint's own text config. Dispatching on isinstance(config, DeepseekV3Config) picks the checkpoint's own class there, which is what no patch at all would have done. The FSDP2 route confirms it independently: model_load_utils.py:862 re-reads the config fresh and _sharded_load_kwargs prepares only for _EXPERT_PARALLEL.
  • The EP path keeps the native type end to end. Nothing between prepare and the build serializes the config: _decide_distribution and load_pretrained:877 use copy.deepcopy (type-preserving), the plan broadcast carries the plan only (each rank prepares its own copy), and _from_config's own deepcopy preserves it too. A to_dict()/from_dict() round trip would have rebuilt text_config through the remote KimiVLConfig.__init__ and silently selected own_class under an EP plan; there is no such round trip on these paths.
  • Idempotency and durability of the swap. prepare runs twice in a real EP load (deciding, then load_pretrained:883); the second to_native returns False on the _kimi_native_swap marker, and keep_patched still reports a non-empty patched list (it lists matched module names, not changed ones), so no spurious RuntimeError. On re-execution the module-level name is the fresh remote class, unmarked, so both the swap and the tie_weights shim re-apply together — they are coupled on the same branch, which is what keeps a re-executed module from ending up swapped but unshimmed.
  • Plan plumbing. plan_config_attr being unset is right: base_model_ep_plan is None on this spec, so the attrs branch in apply_distributed_support never selects a target, and prepare attaches the plan to text_config itself where _ep_config reads it. apply_distributed_support("deepseek_v3", text_config) cannot recurse (deepseek_v3 has no prepare), and its floor is the framework's 5.7, matching ep.py's claim and the test's module-level skip.
  • prepared_ep_plan matches what the model actually builds. _routed_expert_keys(BASE_MODEL_EP_PLAN) reduces to {layers.*.mlp.experts} — identical whether modelopt's plan or transformers' own 5.13 plan wins, since the extra ep_router gate entry is in neither _EXPERTS_STYLES nor grouped_gemm — and _routed_expert_modules matches language_model.model.layers.*.mlp.experts by endswith. So the EP-degree-1 refusal finds the ModuleList experts the checkpoint's own code builds, and test_model_load_utils.py's new test exercises exactly that with prepare stubbed to fail if it runs.
  • No aliasing through the hoisted constant. BASE_MODEL_EP_PLAN is one dict referenced by two specs, but apply_distributed_support and _spec_ep_plan both copy it, so neither spec can mutate the other's plan. The comment that moved with it is intact and still accurate.
  • Refuse-before-mutate. All five refusals run before the shims, the staging wrapper, the config swap and the remote import, and the test asserts the loader is left unwrapped and the checkpoint's code unimported. The trust_remote_code refusal is load-bearing, since get_class_from_dynamic_module does not check it. The startswith("transformers.") port test does not false-positive on transformers_modules.* (the trailing dot).
  • Registering kimi_vl is safe for the existing spec suites. modeling_source="remote_code" with min_transformers_version=None satisfies test_specs_vs_transformers.py:119, and transformers ships no kimi_vl, so test_remote_code_models_are_really_absent holds. The EP_MODEL_TYPES sweeps in test_ep_specs.py pass: the plan is well formed, prepare satisfies the declares-something check, and plan_config_attr is empty. deepseek_v3 is imported before kimi_vl in the isort: skip block, and the transitive import from kimi_vl.specs could not double-register either way.
  • Lazy imports. modelopt.torch.utils{,.moe} are imported inside functions with the circularity reason named; _remote_code is stdlib-only at module scope, so the registry import stays clean.
  • Tests. The _restore helper's absent-attribute branch unwinds correctly (monkeypatch undoes in reverse, leaving the attr deleted), so the compat shims do not leak across tests. The two single-entry parametrize lists are scaffolding for #2748's cases, as the description says, not dead code.

Last round's two suggestions were answered by docstrings rather than code — the tie_weights shim now states that a tied checkpoint still loads with lm_head.weight reported missing, and kimi_vl/specs.py states that is_moe misses the native DeepseekV3MoE blocks until the MoE and export sections are shared. Both are the author's call and I am not re-raising them.

Risk

Low. Additive and confined to the expert-parallel path. The one new code path narrows a previously unconditional monkey-patch, and the narrowing is in the safe direction: off expert parallelism the model is now built exactly as it would be with no patch at all, which is what the new test pins.

🤖 Generated with Claude Code

@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-11b0-kimi-vl branch from 9e2cd9a to c22b9b2 Compare October 30, 2026 19:22
@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-base-11b-kimi branch from a5d243e to a4cfa16 Compare October 30, 2026 19:22
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test c22b9b2

… build step

At an EP degree of 1 the decision ran the spec's build step on the config it then returns for the load to build from, while the plan arm hands it a copy: the build step changes no config, but it now gets a copy too. The build step runs only where prepare does not, for the decision, so a spec stating one and no prepare would load expert-parallel with nothing making the checkpoint's code build: a test now requires a prepare beside a build step, as one already requires a stated plan beside a prepare.

Signed-off-by: Shengliang Xu <[email protected]>
The decision counts a spec's decompressed_formats as formats the expert-parallel load takes, because its prepare installs the decompressor; a spec stating them and no prepare would have a quantized checkpoint planned expert-parallel that nothing decompresses. A test now catches that at the spec, beside the checks that a prepare states its plan and a build step comes with a prepare.

Signed-off-by: Shengliang Xu <[email protected]>
The decision reads a spec's prepared_ep_plan and may plan the model
expert-parallel on it, but only prepare attaches that plan for the load:
a spec stating it and no prepare would have the expert-parallel load
refuse the model after the decision, with no plan on its config. A test
now catches that at the spec, beside the checks that a prepare states
its plan and that a build step and decompressed formats come with a
prepare.

Signed-off-by: Shengliang Xu <[email protected]>
… again

The build step adapted the VLM class's tie_weights once. transformers
executes a remote module again when the files it hashes change, and
loads it afresh for another path to the checkpoint; either way the class
is rebound without the shim. A plan kept off expert parallelism runs no
prepare to put it back, so its load would fail at construction on the
keyword arguments post_init passes. The shim is now kept as prepare's
swap is, and a module the step cannot find to shim fails the step
rather than pass unshimmed.

Signed-off-by: Shengliang Xu <[email protected]>
…rallelism

prepare runs only once the plan is decided expert-parallel, and refuses
some checkpoints its spec counts as ones the expert-parallel load takes:
transformers' own Kimi-K2.5 port, code the load may not run, or experts
the decompressor cannot take. Such a run decided expert parallelism and
then failed on every rank in prepare, where an EP degree left to auto
should plan the model without it. EPSpec.prepare_refusal states those
refusals, found without changing anything. The decision asks it beside
the load's own refusals, so auto plans the model without expert
parallelism, with the warning naming why; an EP degree asked for still
meets prepare's refusal. The Kimi-VL and Kimi-K2.5 specs state theirs.

Signed-off-by: Shengliang Xu <[email protected]>
Every plan the decision reaches runs the build step, and a load kept off
expert parallelism builds the checkpoint's own code from its auto_map,
whatever its modeling module is named. A module the step could not load
by the name it knows, or did not find loaded, failed that load, though
the step changes nothing the model computes or loads. It now warns on
rank 0 and returns; a build the shim was needed for fails on its own,
naming the keyword arguments.

Signed-off-by: Shengliang Xu <[email protected]>
The build step keeps its tie_weights shim under the same module name
prepare keeps its swap under, so the later of the two replaces the
other. The comment now says so, and the order the expert-parallel route
relies on: the build step in the plan decision, then prepare, whose swap
shims tie_weights too.

Signed-off-by: Shengliang Xu <[email protected]>
Under init_quantized_weights with a dense layout left to auto or
replicated, the plan decision returns before it builds the model, yet
the build step has run on every rank. It is not wasted: it keeps its
shims on the checkpoint's module, and the whole load that follows builds
the checkpoint's own code from it. The comment above the step now says
so.

Signed-off-by: Shengliang Xu <[email protected]>
Kimi-K2.5's prepare_refusal mirrored part of what install_onfly_decompress
refuses before it installs anything: the dtype at every config level and
the checkpoint's scheme. It missed a config with nothing to decompress
and a process already decompressing a checkpoint compressed differently.
decompression_refusal now states all four, next to the install it
mirrors, for each spec that installs the decompressor to ask, and a test
holds it to the install: it finds a refusal exactly where the install
raises one.

Signed-off-by: Shengliang Xu <[email protected]>
install_onfly_decompress refuses a transformers older than 5.8 before it
reads the scheme, and decompression_refusal left that to the caller's
spec floor, which Kimi-K2.5's happens to state: a spec without it would
have counted an older release as taking the decompression, and read the
loader hook that release lacks. The shared check now reports the floor
itself, and its parity test with the install covers it.

Signed-off-by: Shengliang Xu <[email protected]>
prepare and prepare_refusal each read the checkpoint's scheme to choose
between the decompressor and the text-config-only refusal, in two copies
that had to stay alike: a mismatch is the very disagreement between the
decision and prepare that prepare_refusal exists to prevent. One helper
now answers for both.

Signed-off-by: Shengliang Xu <[email protected]>
From meenchen-nv's review: decompression_refusal repeated the install's
checks, and missed one of them, the raw dict the install refuses. Both
now run _checked_compression, which raises what the install refuses
and changes nothing: the refusal returns its message, and the install
goes on from the compression it read. The 5.8 floor stays ahead of the
loader read. The parity test gains a raw-dict case, which fails without
this.

Signed-off-by: Shengliang Xu <[email protected]>
From Claude's review: the build step loads and runs the checkpoint's
modeling code, which can raise more than OSError, ImportError or
AttributeError, a SyntaxError or a ValueError from a check in its module
body among them. Every plan runs this step, so it now warns on any
Exception, as it does on those three, and a build the shim was needed
for fails on its own. The warning test gains a case whose code raises as
it runs, which fails with the narrower except.

Signed-off-by: Shengliang Xu <[email protected]>
From meenchen-nv's review, the documentation pass agreed for both
adapters: Kimi-K2.5's module docstring is now the adapter's contract,
as Kimi-VL's is, naming the model family, the native language model,
the vision tower and projector kept, the compressed-tensors
decompression and transformers 5.8. The step comments in both prepares
now say that the native config's type is what has the swapped name
build the native class, a per-config build, and that dropping auto_map
only keeps that config from naming the checkpoint's classes. Comments
and docstrings only.

Signed-off-by: Shengliang Xu <[email protected]>
From Claude's review: EPSpec.make_buildable read as if every load ran
it, but only the plan decision of a multi-rank run does. A single
process, or a plan handed in, decides nothing, and its load builds the
checkpoint's code as from_pretrained does, without the step. Docstring
only.

Signed-off-by: Shengliang Xu <[email protected]>
… own plan

From meenchen-nv's review, reaffirmed: before this PR, an unquantized
Kimi-K2.5 checkpoint read without trust_remote_code built transformers'
own port (from 5.13), whose text config carries deepseek_v3's plan, and
an EP degree left to auto planned it expert-parallel on that plan. The
adapter's refusal of the port turned that into a dense plan, which for
a model too big for one GPU is FSDP2, whose load takes no image-text
config. Refusing the port does not fix the export names either: a dense
load builds the same port.

Kimi-K2.5's prepare_refusal and prepare now leave the port of an
unquantized checkpoint whose text config carries a plan as it is, so it
is planned and loaded expert-parallel on that plan, as before this PR.
The port of a quantized checkpoint is still refused: here only the
checkpoint's own code decompresses its experts.

Tests, with the port as transformers 5.18 ships it: the adapter returns
an unquantized port unchanged and refuses a compressed one, and the
decision plans the real port, built on the meta device, expert-parallel
with its dense part replicated on a GPU the whole model overfills but a
rank's share fits. Both fail without the change.

Signed-off-by: Shengliang Xu <[email protected]>
From CodeRabbit's review: the decompressed-load test imported
transformers.core_model_loading and modeling_utils in the test, giving
transformers 4 as the reason, but ModelOpt needs transformers 5.5,
which has both, and the module already imports transformers at the top.
They are now imported there, so an import error surfaces at collection.
The decompressor's own comment on the same import now gives the reason
that holds: transformers is optional there.

Signed-off-by: Shengliang Xu <[email protected]>
From CodeRabbit's review: transformers ships the Kimi-K2.5 port's
configuration module only from 5.13, so importing it at module scope
would break the file's collection on older releases. The import now
names that reason. Comment only.

Signed-off-by: Shengliang Xu <[email protected]>
… own code does

From Claude's review: the build step's adaptations stay in place for a
load off expert parallelism -- the import shims, the staging and the
tie_weights wrapper -- so that load is not of unpatched code. A tiny
Kimi-VL checkpoint, tied and untied, loaded after the build step holds
every stored tensor as stored, ties its embedding exactly when the
checkpoint does, and computes the same logits as the checkpoint's own
language model built with no patch. A wrapper that skips the
checkpoint's own tie_weights fails the tied case.

Signed-off-by: Shengliang Xu <[email protected]>
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test 5e1bf0e

@shengliangxu
shengliangxu force-pushed the shengliangx/hfep-11b0-kimi-vl branch from 84b5029 to 5e1bf0e Compare November 3, 2026 21:02
The docstring said the FSDP2 load takes no image-text config, which no
longer holds now that main's FSDP2 load takes vision-language models for
text-only calibration. The test still checks what it did: with the
experts' share fitting a GPU the whole model overfills, the decision
shards the experts. Docstring only.

Signed-off-by: Shengliang Xu <[email protected]>
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test dc6a858

@kevalmorabia97 kevalmorabia97 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM. Earlier review threads are fixed or answered; the unit tests pass and mutating the key logic fails them, and the 2-GPU Kimi-VL expert-parallel test passes against the whole model. CI is green.

@shengliangxu
shengliangxu merged commit e47c253 into main Nov 4, 2026
49 checks passed
@shengliangxu
shengliangxu deleted the shengliangx/hfep-11b0-kimi-vl branch November 4, 2026 06:40
shengliangxu added a commit that referenced this pull request Nov 4, 2026
…reviews (#3139)

> [!NOTE]
> **Folded on 2026-11-03.** #3133 (`distributed_forward_loop(forward=)`,
and the memory monitor's NVML probe and idempotent `stop()`) and #2754
(hf_ptq's expert-parallel run) are folded into this PR. Their commits
sit unchanged on top of this PR's own, so `forward=` and the NVML fix
land with their caller. Their review history stays on #3133 and #2754.
Before the fold, this PR was [2/3] of #2754's split (2026-10-30), and
#2754 was [21/21] of the original stack.
>
> **Base:** `main`. Every PR this one builds on has merged: #2780
(expert-parallel load routing, with #2746's model specs folded in),
#2742 (dense sharding) and #2752 (no-gather export, with #2753's
expert-parallel export folded in). The diff below is this PR's alone.

<details><summary>Series layout</summary>

This PR's chain only.

- `main` (#2745, #2736, #2739, #2737, #3088, #3099, #3100, #3101, #2750,
#3122, #3131, #2751, #3134, #3074, #3140, #2779, #3135, #3067, #2740,
#3136, #2780, #3137, #2742, #2741, #2743, #3138 and #2752 merged)
- **#3139 expert-parallel PTQ from hf_ptq.py, with lockstep previews
(this PR)**

</details>

### What does this PR do?

Type of change: New feature and bug fix

`hf_ptq.py` had one distributed path, `--use_fsdp2`, which shards a
dense model and replicates every expert of an MoE. This PR wires the
expert-parallel path (the rest of the series; see the layout above) into
it, so the documented CLI reaches an expert-parallel run: recipes,
export formats, deprecations. It also does three more things:
- keeps the generation previews of a model distributed over several
ranks in lockstep;
- pins a replicated model's whole copy to each rank's GPU;
- carries the two library changes the run needs.

- **Process group.** `main()` runs inside `distributed_run` (#2736),
which owns the process group on a distributed launch.
- The run takes this process's `DistributedState` (rank, size, device)
from it, with `--device` for a single process.
- FSDP2 on one rank still shards through a process group of one. The
load sets it up (#2779), and `distributed_run` destroys it with the run.
- The example's own `DistributedState`, `setup_distributed_args` and
process-group helpers are gone.
- **One decision, read everywhere.** `load_model` decides the plan once
and loads every model by it through `load_pretrained` (#2779):
expert-parallel, FSDP2, `get_model`'s whole-model loads and the
low-memory load.
- The decision is `resolve_distribution_plan` (#2737, #2780), wrapped in
`example_utils.resolve_distribution`, which adds this script's checks.
- `load_pretrained` records the plan, so the script records none itself:
#2752's record after the `--use_fsdp2` load is gone.
- Everything after reads the plan back from the model, not the flag or
the process group: the calibration device, the data sharding, the
calibration loop, the previews, and `get_model`'s GPU placement.
- `MODELOPT_EP_DEGREE` and `MODELOPT_FSDP_SIZE` override the automatic
choices.
- `--use_fsdp2` asks the decision for FSDP2 and no expert parallelism.
Its `--experts_implementation` (#3074) still goes on the config the
FSDP2 load builds from.
- `--use_fsdp2` now loads through `load_pretrained`'s FSDP2 route, which
#2779 opens to the text-only Qwen3.5 and Qwen3.5-MoE VLMs. Main's FSDP2
path has calibrated them since #2676.
- **Refusals.** Each is refused before anything loads unless noted.

  | Refused | When | Why |
  |---|---|---|
| A plan that shards the whole model with FSDP2 | Without `--use_fsdp2`
| That flag is what this script's FSDP2 checks hang on; they now run
before anything is set up. |
| A plan that would quietly replicate an expert-parallel-capable MoE |
Any run (`resolve_distribution_plan` refuses it) | Every rank would hold
every expert. |
| A model whose spec refuses expert parallelism (GPT-OSS, Llama-4;
#2780) | An EP degree above 1 asked for | The expert-parallel load
cannot take it. Left to decide, the plan goes without expert parallelism
and warns why. |
| Asking to FSDP2-shard the dense part within several expert-parallel
groups | Any run; the error names the settings that avoid it | The
export cannot write that layout yet. Left to decide, the plan replicates
such a dense part. |
| An AutoQuantize recipe | Expert-parallel and replicated routes | Its
search scores each rank's shard without reducing the scores.
`--use_fsdp2` keeps main's warning. |
| `--low_memory_mode`, `--use_seq_device_map`, `--offload_folder` (and
with it `--max_cpu_memory_gb` / `--max_gpu_memory_gb`) | Expert-parallel
and replicated routes | They configure a single process's load. An
expert-parallel run never reaches those loaders, and a replicated one
pins each rank's copy to its GPU. A single process and `--use_fsdp2`
keep main's handling. |
| `--vllm_fakequant_export` | Expert-parallel route | That exporter
writes the whole model from each process it runs in. A replicated run
keeps it (rank 0 exports), and `--use_fsdp2` keeps its parsing-time
refusal. |
| `--experts_implementation` (#3074) | Expert-parallel route | The
expert-parallel load runs the routed experts through `torch_a2a`
whatever backend the flag names. `--use_fsdp2`, a replicated run and a
single process load by it. |

- **Export.**
- A model the plan replicates, such as a small dense model under
torchrun, is exported by rank 0 alone. Every rank used to write the same
directory and race on `config.json`.
  - A multimodal model's source config is rank 0's in every plan.
- A speculative-decoding model's export, which writes the whole
checkpoint from one process, is refused on every rank when the model is
sharded.
- **Calibration.**
- Every distributed run calibrates on its own 1/world shard of the data
(#2740), the offline speculative-decoding loader included. A loader of a
kind that cannot be split is refused. The image-text loader shards its
own stream (#3172), so each rank drops its own undecodable images and
pads to the others' batch count.
- Expert-parallel runs go through `distributed_forward_loop`, and image
batches through the VLM's own forward by the loop's new `forward=`
(below).
- The loop re-plants the all-to-all forwards that quantizer insertion
clobbers on transformers 5.16 and later. From 5.16, quantizer insertion
drops the routed experts' all-to-all forward wrapper.
- Some recipes run no calibration loop: configs that need no
calibration, such as `int8_weight_only` or `w4a16_nvfp4`, and the MX
presets, whose algorithm is `None`. They would leave the wrapper
dropped, so the preview after PTQ would fail before the export. Once
quantized, an expert-parallel run therefore re-plants it through
`reinstall_a2a_forwards`, the loop's own re-plant, which
`modelopt.torch.utils.distributed` now makes public.
- On 5.15 and earlier the TP transforms are forward hooks that insertion
leaves in place, and the re-plant finds nothing to restore.
- An expert-parallel VLM calibrated on text runs its batches through the
language model, but the loop re-plants the all-to-all forwards over the
whole model. Transformers keeps the expert-parallel plan on the model
`from_pretrained` built, and from 5.16 a VLM's language model reports
none of its own. A loop handed the language model would re-plant
nothing, and the first batch would raise for the missing EP process
group.
- The `--qformat` path of an expert-parallel VLM also needs #2740's
guard fix. It lets a module with no routed experts (the vision tower,
which the script quantizes with every quantizer off) pass the
expert-parallel calibration check.
- FSDP2 and a model replicated on every rank keep main's plain loop. On
a plan of several ranks that loop retries no batch that runs out of
memory (#2752). The error reaches `distributed_run`, which aborts the
rank, and the launcher stops the others, instead of leaving them waiting
in a collective (main's `cleanup_distributed` would wait in
`destroy_process_group`).
  - The calibration algorithms under a plan that spans several ranks:

    | | Algorithms |
    |---|---|
| Supported and run on GPUs | `max` (amax all-reduced over the data-,
expert- and tensor-parallel groups), `mse` (searches the weights max
leaves identical on every rank) |
| Supported, not yet run on GPUs | `gptq` (Hessians merged across each
module's data-parallel replicas), `smoothquant` (scales from max's
synced amax), `awq_clip` (each candidate clip's loss averaged over the
ranks), `nvfp4_act_headroom` (activation scales MAX-reduced over data
parallelism) |
| Refused before quantizing (#2740) | `awq_lite`, `awq_full`,
`svdquant`, `local_hessian`, `imatrix`, and `max` or `mse` with
`distributed_sync` off, also as another algorithm's weight or scale
algorithm: each keeps its statistics on its rank, so the ranks' copies
of a weight would come out different |
| Runs with a warning | `lsq` on the expert-parallel and replicated
routes: its first scale calibration follows the rows above, but nothing
has checked its learnable scales across ranks |

- **Previews keep a sharded model's ranks decoding together.** This
covers the expert-parallel runs, Nemotron-VL's previews included, and
`--use_fsdp2` on several GPUs.
- Each rank previews the first sample of its own calibration shard, so
the ranks finish decoding at different steps. When the plan shards the
model (expert parallelism, or FSDP2 over several ranks), every forward
runs a collective, so a rank that stopped decoding left the others
blocked in it.
- `preview_generate_kwargs` hands `generate` `synced_gpus=True` for such
a plan: in the previews before and after quantization, and in
Nemotron-VL's.
- The ranks vote on whether to run Nemotron-VL's image preview (an
`all_reduce` of whether each found a sample image), so every rank
previews or none does. Each node reads the images from its own checkout,
and the repository ships none.
- Under `synced_gpus` a failing preview raises instead of being skipped,
since its peers would wait for it. This covers the VL previews and the
preview after quantization. A failed preview after quantization stops
the run before the export, with a message that names `--skip_generate`.
A single process keeps the best-effort skip (NVBug 6752977).
- On a run of several ranks, `distributed_run` aborts a rank that
raised, so `torchrun` stops the others, rather than tear the process
group down while they wait in a collective that rank never reaches.
- **`generate` keeps a MoE's experts on their backend.**
- On a GPU, `generate` switches the experts of a `grouped_mm` MoE to
`batched_mm` for decoding (`_optimize_model_for_decode`, transformers
5.0 and later). `batched_mm` bypasses the quantizers, so the preview
after PTQ decoded unquantized experts.
- Transformers also refuses the switch for an FSDP2-wrapped model:
`FSDPQwen3MoeForCausalLM does not support setting experts
implementation`.
- `keep_the_experts_implementation` keeps every module of the model that
has the hook from switching. A model can generate through a submodule,
as a Nemotron-VL model's `chat` does through its language model.
- It puts back a hook a module holds itself, so a hook bound per
instance survives and previews nest.
- This holds for every run, a single process included: there too the
preview after PTQ now decodes on the quantized experts.
- **`get_model(..., distribution=plan)` pins a whole model to the rank's
GPU.** A replicated run loads through it.
- When the plan gives each of several ranks the whole model, every load
path places it on the rank's own `cuda:<local_rank>`: the plain load,
the pack-quantized and MXFP4 loads, and DiffusionGemma's sequential map.
Accelerate's "auto" would run its placement in every rank alike and
could put every rank's copy on the same idle GPU.
- There, `--use_seq_device_map` and a device that names no GPU index are
refused. A pinned copy is not sized against the node's GPUs, a limit its
one-device map would ignore.
- A single process keeps "auto", as before. The device is compared by
type, since a run's `torch.device` never equals a string such as
`"cpu"`.
- A plan that shards the model (expert parallelism, or FSDP2) is
refused: `get_model` loads the whole model on every rank, and hf_ptq
hands such plans to `load_pretrained`.
- `get_model` hands `load_pretrained` only a plan its caller gave.
Without one, the load decides as before, and it refuses `MODELOPT_*`
knobs that ask to shard over a launch whose process group is not set up.
- **`distributed_forward_loop(..., forward=None)`** (from #3133).
- The loop calibrates by calling `model(**batch)`. A batch that needs
its own call into the model cannot go through it: a VLM's image-text
batch, say, which runs through the VLM's own forward with the keyword
arguments that forward accepts.
- The loop now takes an optional `forward(batch)`, and still moves each
batch to the device and calibrates with the cache disabled.
- `forward` is typed as taking a `Mapping`. It gets a new dict when
`device` is given, and the loader's own mapping otherwise.
  - The expert-parallel image calibration above uses it.
- **Memory monitor** (from #3133). `hf_ptq.py` starts it on each node's
first rank, since it reads every GPU on its node.
- `launch_memory_monitor` checks that NVML can report memory before it
starts the monitor. But the probe ran before `nvmlInit`, so every probe
raised `NVMLError_Uninitialized`. The monitor never started on any host
where nothing else had initialized NVML.
- The probe now initializes NVML itself and shuts it down afterwards,
keeping NVML's reference count balanced.
- Since the monitor now starts, its `stop()`, which also runs at exit,
does nothing on a monitor already stopped.
- `stop()` joins the polling thread before it reads and prints the
peaks, so a sampling pass in flight finishes first.
- **Slurm example.** New `examples/hf_ptq/slurm/multinode_ep_ptq.slurm`,
following `multinode_fsdp2_ptq.slurm`. Not run on a cluster yet.
- Its `EXPORT_PATH` and `HF_HOME` must be on storage every node can see:
every rank writes its share of the checkpoint, and rank 0 downloads a
repo id for the others to read.
- Every node runs the editable install from the one mounted clone, so
the nodes take turns under `flock` where the filesystem offers it.
- It launches one `torchrun` per node, which spawns one process per GPU,
and `hf_ptq.py` shards the routed experts over all ranks.
- It installs the transformers 5.7 or newer that expert parallelism
needs, and prints the version into the job log.
  - Its defaults quantize Qwen3-235B-A22B to NVFP4 with an FP8 KV cache.
- **Docs.** The README section "Expert-Parallel Post-Training
Quantization for MoE Models" covers:
  - how to launch, and what the knobs override;
  - which models are refused;
- that GPT-OSS and Llama-4 quantize in a single process: expert
parallelism refuses them, and `--use_fsdp2` refuses their released MXFP4
/ multimodal checkpoints;
  - which calibrations have run on GPUs on more than one rank.

The out-of-memory note covers every `torchrun` launch of several ranks,
not only `--use_fsdp2`. A multi-node run needs the export directory and
the Hugging Face cache on storage every node can see.

### Usage

```bash
# One node, 8 GPUs: the experts shard over all 8 ranks, each calibrating its own data.
torchrun --nproc_per_node 8 examples/hf_ptq/hf_ptq.py \
    --pyt_ckpt_path Qwen/Qwen3-30B-A3B --qformat nvfp4 --export_path /out/qwen3-30b-a3b-nvfp4
```

```python
# Each rank of a replicated run loads the whole model onto its own GPU.
model = get_model(ckpt_path, device=f"cuda:{local_rank}", distribution=DistributionPlan(world_size))

# Run each image-text batch through the VLM's own forward, e.g. with filtered kwargs.
forward_loop = distributed_forward_loop(model, loader, device=device, forward=vlm_forward)
```

### Testing

- New `tests/examples/hf_ptq/test_hf_ptq_expert_parallel.py` (57 cases).
The decision itself is tested in #2737 and #2780. It covers:
- what the script adds to the decision: FSDP2 without expert parallelism
for `--use_fsdp2`, and FSDP2 sharding refused unless `--use_fsdp2`;
- `load_model` loading by the plan: an EP plan and `--use_fsdp2` through
`load_pretrained` and no other loader, a data-parallel one through
`get_model`;
- the single-process load options (`--low_memory_mode`,
`--use_seq_device_map`, `--offload_folder`) refused on the
expert-parallel and replicated routes and kept by a single process;
- `main()` running inside `distributed_run`, which it leaves even when
the run raises, and handing the run the state `distributed_run` yields,
with `--device` for a single process;
- per-rank calibration data, the offline speculative-decoding loader
included;
- the distributed loop, with the EP mesh, for an expert-parallel plan,
and the plain one for FSDP2;
- exporting a replicated model from rank 0 only, and every rank of a
sharded one;
- a sharded speculative-decoding model refused at export on every rank,
with nothing written;
- the plan the export cannot write refused before loading, while the
world-size degree still resolves;
- the vLLM fake-quant export refused on the expert-parallel route and
kept by replicated and single-process runs;
- an AutoQuantize recipe refused, and an LSQ recipe warned about, on the
routes this script adds;
- a failed preview raising on an expert-parallel model, Nemotron-VL's
included, and skipped, with the export still run, on a replicated one;
- the all-to-all forwards re-planted after a quantization that runs no
calibration loop, for an expert-parallel plan only;
- a tiny Qwen3-VL-MoE, as the expert-parallel load leaves it, calibrated
on text over a one-rank gloo group. It fails without the fix on
transformers 5.18 and skips below 5.16.

The DeepSeek-V3 multi-rank cases skip below transformers 5.7, where
#2780 refuses expert parallelism before the route they exercise. Their
single-process and `--use_fsdp2` cases still run there.
- New `tests/examples/hf_ptq/test_hf_ptq_previews.py`:
- the previews before and after quantization, and Nemotron-VL's text,
fallback and image generations, use `synced_gpus` exactly when the plan
shards the model;
  - the VL image preview passes the kwargs it is handed to `chat`;
  - the ranks skip the image preview together when one has no image;
  - a failing text-only VL preview raises under `synced_gpus`.
- `tests/examples/hf_ptq/test_example_utils.py`:
- `get_model`'s pin on every load path, a pinned copy not held to a
node-wide memory limit, a single process left on "auto", and a CPU
device given as a `torch.device`;
- the refusals of the sequential map, of a device without a GPU index,
and of a plan that shards the model;
- `get_model` without a plan leaving the decision to `load_pretrained`;
- the experts guard: the previews keep `generate` from switching the
experts implementation, also on a language model that a model around it
generates through (fails without the fix); a model without the decode
hook is previewed as it is; and a decode hook the model holds itself is
put back, also when previews nest.
- `tests/examples/hf_ptq/test_hf_ptq_args.py`:
- a sharded model's failed preview after quantization stops the run
before the export (an FSDP2 plan of two ranks), while NVBug 6752977's
single-process skip is unchanged;
  - the memory monitor starts on each node's first rank only.
- `tests/examples/hf_ptq/test_hf_ptq_model_type.py`: the preview tests'
stand-in models are modules, since the previews read their plan.
- `tests/unit/torch/utils/test_distributed_calibration.py`: two batches
run through a given forward, on the device and with the cache disabled.
- New `tests/unit/torch/utils/test_memory_monitor.py`, against a fake
reference-counted NVML:
- the monitor starts when NVML can report memory (this fails on the old
code), and is skipped with NVML shut down when it cannot;
  - a second `stop()` does nothing;
  - on two GPUs, `stop()` waits for the sampling pass in flight.
- Mutation-checked: each test fails under a deliberate break of the code
it covers.
- New 2-GPU smoke test `test_ptq_qwen3_moe_sharded`
(`tests/examples/hf_ptq/test_llm_ptq.py`). It is the tests' one real
sharded run of the script; the files above cover the wiring with
stand-ins.
- It runs `torchrun --nproc_per_node 2 hf_ptq.py` on a tiny Qwen3-MoE
with the FP8 recipe, in two cases: expert-parallel
(`MODELOPT_EP_DEGREE=2`, transformers 5.7 or later) and `--use_fsdp2`.
  - Both preview before and after calibration, and export.
- The test checks that every expert of every layer is exported FP8 with
its weight scale, and that the config names FP8.
  - It skips on CI's 1-GPU PR runner and runs on 2-GPU runners.
- Results at db78d0e (2026-10-30), on 2 GB200s with torch 2.11.0a0
and transformers 5.9.0:

    | Test | Result | Time |
    |---|---|---|
| `tests/examples/hf_ptq/test_llm_ptq.py::test_ptq_qwen3_moe_sharded` |
2 passed (`expert_parallel`, `fsdp2`) | 146 s |
| `tests/gpu/torch/quantization/test_fsdp2_autoquant.py` | 6 passed |
213 s |

- The re-plant was checked with a 2-GPU A/B on an earlier revision.
Setup: a tiny Qwen3-MoE at EP 2 with the dense part replicated, MXFP8 on
weight and input quantizers with algorithm `None`, previews on.

  | Transformers | Without the re-plant | With it |
  |---|---|---|
| 5.18 | Failed in the post-quantization preview on both ranks
("torch_a2a experts forward requires the EP process_group"); no
checkpoint written | Completed, restoring 8 forward wrappers, and
exported |
| 5.9.0 (nothing to re-plant: up to 5.15 the TP transforms are hooks
that quantizer insertion leaves alone) | Exported | Exported,
byte-identical files |

- A tiny Kimi-K3 VLM MoE (bf16, 32 experts) ran on 2 GPUs at EP 2, with
transformers 5.18 and NVFP4 with an FP8 KV cache. It calibrated on text
and previewed before and after PTQ on both ranks. The calibration loop
re-installed its 3 experts' forward wrappers, and the run exported.
- These GPU results were measured on earlier revisions of this series,
before this script's loads moved onto `load_pretrained` (#2779, #2780).
This revision's GPU tests run in CI only.
- The series' GPU tests: 19 passed on a 4-GPU node. On 1 GPU (CI's PR
runner), 6 passed and 13 skipped. They cover the expert-parallel load
with the dense part replicated and sharded, at EP 4 and EP 2; amax sync;
and the distributed export.
  - Against the series' base on one GPU node:

    | Suite | Outcome against the base |
    |---|---|
| `nox -s gpu` (all of `tests/gpu`, 1 GPU, CI's PR-runner shape) | Every
test failing here also fails at the base; the only new tests are the
series' own |
| hf_ptq example lane (`tests/examples/hf_ptq`, TensorRT-LLM image, 1
GPU) | No outcome changes on the 296 shared tests; the series' 30 pass,
except 2 that need transformers 5.7 |
| `tests/gpu_megatron` (2 GPUs) | No outcome changes over the 311 tests
both runs reached; the rest time out identically at the base in that
image |

- Expert-parallel runs end to end. All of them predate #3074's expert
weight-scale fix. Before that fix, on every rank but rank 0, an expert's
weight scale came out too large wherever rank 0's expert at the same
index had the larger one. That costs precision but never clips; the fix
can only tighten such scales.
  - Qwen3-30B-A3B at EP16 over 4 nodes, NVFP4 and FP8:
- The exports with the dense part FSDP-sharded over the world and with
it replicated have byte-identical weights and weight scales. Only
calibration-derived input scales differ.
- Every dense FP8 weight is FP8 with its scale, and no NVFP4 weight has
the all-zero high nibbles of a lost pack shift.
- Qwen3-VL-30B and MiniMax-M3: tensor counts match single-GPU exports,
and every expert weight is packed.
  - MiniMax-M2.7 (block-FP8 source) at EP16 over 4 nodes, NVFP4:
- Every exported weight name is the source checkpoint's, and routed
experts are `block_sparse_moe.experts.N.w1/w2/w3`.
- Served by vLLM (0.30 dev build, TP4), it scores close to the FP8
source on gsm8k (5-shot, 100 samples):

      | Checkpoint | Flexible | Strict |
      |---|---|---|
      | This export (NVFP4) | 0.94 | 0.93 |
      | FP8 source | 0.93 | 0.95 |
  - DeepSeek-V3 and GLM: on an earlier revision.
- Kimi-K3 NVFP4 at EP64 over 16 GB200 nodes, in 10 minutes (peak 155 GiB
per GPU on an earlier build of this series). Checked against the source
checkpoint:
    - the router correction biases match;
- routed and shared experts carry the names vLLM 0.28's loader reads;
    - dense weights dequantize back to the BF16 source at cosine 0.9955;
- the remote code, tokenizer and processor files ship with the export;
- the modules vLLM builds unquantized stay BF16, as in
nvidia/Kimi-K3-NVFP4.

The same checks flag the export made before this series' fixes. vLLM
0.28 loads the export and starts serving. But it cannot serve a Kimi-K3
NVFP4 export with an FP8 KV cache: its FP8-KV path needs an FP8 prefill
query, which its NVFP4 linears reject. TBD: generation and gsm8k from
the checkpoint-mirror recipe
`models/moonshotai/Kimi-K3/ptq/nvfp4_experts-fp8_pb_attention`, on this
series' code with the #3074 fix.
- Folded on 2026-11-03, on main a6cc167, on `hfep-base-14-hf-ptq`
rebuilt from #2780, #2742 and #2752's content:
- This PR's 6 commits, #3133's 6 and #2754's 10 are unchanged:
range-diff shows each as `=`. The own diff equals the three PRs' own
diffs combined, line for line.
  - Pre-commit, mypy included, passes against main.
  - On CPU:

    | Tests | transformers 5.18 | transformers 5.5.4 |
    |---|---|---|
| hf_ptq example tests that run without a GPU (`tests/examples/hf_ptq`
minus `test_llm_ptq.py`, `test_vlm_ptq.py` and
`test_convert_ggml_to_int8.py`) | 313 passed, 17 skipped | 302 passed,
28 skipped |
| `test_distributed_calibration.py`, `test_distributed.py`,
`test_memory_monitor.py` | 109 passed | 109 passed |
| `test_model_load_utils.py`, `test_moe_a2a.py`,
`tests/unit/torch/models` | 630 passed | 528 passed, 91 skipped |

- Review fixes, 2026-11-03 (Claude, on the folded diff): the Slurm
example and the README say that the export directory and `HF_HOME` must
be on storage every node can see. The example's editable install takes
turns under `flock`, and runs unlocked where the filesystem has no
flock. `--node_rank` is dropped, since the c10d rendezvous ignores it.
`reinstall_a2a_forwards` is the re-plant function itself rather than an
alias of a private one. Pre-commit passes against main. On CPU:

    | Tests | transformers 5.18 | transformers 5.5.4 |
    |---|---|---|
| `test_distributed_calibration.py`, `test_distributed.py`,
`test_memory_monitor.py` | 109 passed | 109 passed |
| hf_ptq example tests that run without a GPU | 313 passed, 17 skipped |
302 passed, 28 skipped |

- Rebased on 2026-11-03 onto main 7d44246 (after #2780 merged), on
`hfep-base-14-hf-ptq` rebuilt from #2742 and #2752:
- Two CHANGELOG conflicts were in context only: main's new entries, and
#2752's new no-gather wording.
  - The own diff is unchanged. Pre-commit passes against main.
  - On CPU:

    | Tests | transformers 5.18 | transformers 5.5.4 |
    |---|---|---|
| `test_distributed_calibration.py`, `test_distributed.py`,
`test_memory_monitor.py` | 109 passed | 109 passed |
| hf_ptq example tests that run without a GPU | 313 passed, 17 skipped |
302 passed, 28 skipped |
| `test_model_load_utils.py`, `test_moe_a2a.py`,
`tests/unit/torch/models` | 630 passed | 528 passed, 91 skipped |

- Rebased on 2026-11-03 onto main 5870698 (after #3137 merged), on
`hfep-base-14-hf-ptq` rebuilt from #2742 and #2752:
- No conflicts, and the own diff is unchanged. Pre-commit passes against
main.
  - On CPU:

    | Tests | transformers 5.18 | transformers 5.5.4 |
    |---|---|---|
| `test_distributed_calibration.py`, `test_distributed.py`,
`test_memory_monitor.py` | 109 passed | 109 passed |
| hf_ptq example tests that run without a GPU | 313 passed, 17 skipped |
302 passed, 28 skipped |
| `test_model_load_utils.py`, `test_moe_a2a.py`,
`tests/unit/torch/models` | 687 passed | 534 passed, 92 skipped |

- Rebased on 2026-11-04 onto main c785ca9 after #2752 merged, and
retargeted to `main`; the `hfep-base-14-hf-ptq` helper is retired.
  - Conflicts:
- imports in `hf_ptq.py` and `example_utils.py`: main's
`fsdp2_root_unsharded` and `resolve_model_class` are kept, and
`is_fsdp2_text_only_vlm`, gone from main, is dropped;
- `create_vlm_calibration_forward`'s header, next to main's new
`forward_requires_images`.
- Main's VLM support under `--use_fsdp2` (#3127, #3172) is kept: the
image loop runs inside `fsdp2_root_unsharded`, and text calibration and
the batch-size probe run inside `fsdp2_call_context`.
- New commit: the image-text loader now shards its stream by the plan on
every distributed plan, and nothing shards it again.
    - Before it, a `--use_fsdp2` image run was sharded twice.
- An expert-parallel or replicated image run was sharded without #3172's
per-rank image filter, so one rank's empty batch would leave the others
in a collective.
    - Its new test fails without it.
- New commit: two calibration-loop tests' stand-in arguments carry
`--use_fsdp2`, which main's FSDP2 text loop reads.
- Pre-commit passes against main. On CPU, with the same failures as main
in this environment (four diffusers SDPA backward tests and one ONNX
import error):

    | Tests | transformers 5.18 | transformers 5.5.4 | no transformers |
    |---|---|---|---|
| hf_ptq example tests that run without a GPU | 331 passed, 17 skipped |
320 passed, 28 skipped | skipped (need transformers) |
| `tests/unit/torch/utils` and `tests/unit/torch/quantization` | 2572
passed, 3 skipped | 2476 passed, 99 skipped | 1718 passed, 58 skipped |

  - Core logic by `.agents/review-guidelines/code-review.md`:

    | | Lines |
    |---|---|
    | Added Python | 552 |
    | Core Python | 388 |
    | Core shell (Slurm example) | 40 |
    | Core total | 428 |

- Review history: #2754 (2026-10-11 to 11-02) and #3133 (2026-10-30 to
11-02) for their changes. This PR's own fixes before the fold are listed
below; their rebases are in its timeline.
- Review fix, 2026-10-30 (Claude): `get_model` hands `load_pretrained`
only a plan its caller gave (new test fails without it).
- Review fixes, 2026-10-30 (cjluo-nv's bot): `get_model` refuses a plan
that shards the model.
- Review fix, 2026-10-30 (cjluo-nv's bot and Claude, on the maintainers'
decision): a sharded model's failed preview after quantization stops the
run before the export.
- Review fix, 2026-10-30 (Claude round 4): a rank that raised on a run
of several ranks aborts instead of tearing the group down.

### Before your PR is "*Ready for review*"

- Is this change backward compatible?: ❌ A `torchrun` launch of several
ranks without `--use_fsdp2` now runs as one distributed job (an MoE
expert-parallel, any other model replicated) instead of one independent
run per process. It refuses there the single-process load options,
AutoQuantize and layerwise-export recipes, and the TensorRT-LLM export.
This is listed under Backward Breaking Changes in the CHANGELOG.
- Single-process and `--use_fsdp2` runs behave as before, with these
exceptions:
- Any multi-rank launch now refuses a `--device` other than `cuda` (by
`distributed_run`, #2736). Main's `--use_fsdp2` ignored it and ran each
rank on `cuda:<local_rank>`.
- On transformers 5.0 and later, a preview of a `grouped_mm` MoE on a
GPU keeps the experts' backend, in a single process too. The preview
after PTQ now decodes on the quantized experts.
    - `--use_fsdp2` previews on several GPUs decode in lockstep.
- A `--use_fsdp2` run on several GPUs whose preview after quantization
fails now stops before the export. Main skipped the preview and
exported. `--skip_generate` runs it without the previews.
  - `forward=` is optional; the memory monitor change is a fix.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A
- Did you write any new necessary tests?: ✅
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅ New feature and Backward Breaking Changes, 0.49.0.
- Did you get Claude approval on this PR?: ❌ A re-review is requested
after the fold. #2754 was approved on 2026-10-27 and 2026-10-29, and
#3133 before its last rebase.

### Additional Information

The last PR of expert-parallel PTQ for Hugging Face MoE models. Every PR
it builds on has merged, and it targets `main`. #3133 and #2754 are
folded in (2026-11-03) and closed; their review history stays there.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **New Features**
* Added expert-parallel post-training quantization for supported MoE
models, with multi-node launch guidance and a Slurm example.
* Distributed runs split calibration data across ranks and coordinate
previews; replicated-model exports are written by rank 0.
* **Breaking Changes**
* Multi-rank launches without FSDP2 now run as one distributed job:
eligible MoE models use expert parallelism, while other models are
replicated. Some export and calibration options are rejected in
distributed modes.
* Multi-GPU FSDP2 calibration no longer retries with smaller batches
after an out-of-memory error.
* **Documentation**
* Expanded guidance on distributed calibration requirements and
limitations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Shengliang Xu <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants