Repository navigation
[TRTLLM-16725][feat] Add selective Model Streamer loading for Kimi K3 - #20782
yijingl-nvidia wants to merge 3 commits into
Conversation
c9bdeb0 to
db0aa91
Compare
sunnyqgg
left a comment
There was a problem hiding this comment.
Follow-up to my review of 2026-11-03: 16 of the 19 lower-priority points I left out of it still apply at db0aa91. The other 3 are fixed or no longer apply. They are marked [Nice to have] and none blocks the merge on its own.
- [Nice to have] There is no
/bot runon this PR yet, and the description lists the new tests without results, so nothing shows that they run and pass. Please post/bot runonce the stack allows and link the run. It should show the 8test_model_streamer_matches_regular_loadercases and the 4test_kimi_k3_model_streamer.pycases passing rather than skipped (the expert test callspytest.importorskip("fla")), and the CPU stage passing the changed_model_streamer_loadhelper intest_model_loader_checkpoint_io.py.
|
|
||
| def load_weights(self, weights) -> None: | ||
| """Load vision + projector + LLM weights from checkpoint.""" | ||
| self._ensure_mm_encoder() |
There was a problem hiding this comment.
[Nice to have] load_weights() now calls self._ensure_mm_encoder() first, but test_language_weights_preserve_checkpoint_dir (test_modeling_kimi_k25.py:269-273) calls it on a SimpleNamespace without that method, so the test now fails with AttributeError. CI stays green only because that file has no cpu_only marker and is in no test list. It is the only test of the checkpoint_dir/checkpoint_prefix pass-through that K3's per-file expert loading needs (modeling_kimi_k3_loader.py:1247-1251). Please add _ensure_mm_encoder=lambda: None to the stand-in and mark the test pytest.mark.cpu_only, so the unittest/_torch/modeling entry in l0_cpu.yml:68 runs it.
| self.loaded_weights = weights | ||
|
|
||
| monkeypatch.setattr(modeling_kimi_k25, "_has_meta_tensors", lambda model: False) | ||
| model = _multimodal_wrapper(TextModel(), VisionModel()) |
There was a problem hiding this comment.
[Nice to have] Both VL plan tests make _ensure_mm_encoder() a no-op: this one passes a ready VisionModel(), and the text-only test sets disable_mm_encoder=True (test_kimi_k3_model_streamer.py:83). In production, MetaInitMode leaves mm_encoder as None until the plan rebuilds it (modeling_kimi_k3_vl.py:574), so removing that call keeps these tests green while multimodal streamer loads lose the vision group. The KeyError at modeling_kimi_k3_vl.py:588 is untested too. Please add a case that starts from mm_encoder=None with a fake _VISION_MODEL_CLS and _vlm_pretrained_config and checks that the last group loads into the rebuilt encoder, plus a no-vision-keys case that expects the KeyError.
| ) | ||
| assert sorted(regular_events) == expected_events | ||
| assert sorted(streamed_events) == expected_events | ||
| assert [len({_expert_layer(name) for name in batch}) for batch in streamed_batches] == [ |
There was a problem hiding this comment.
[Nice to have] This test never checks which tensors were streamed: it compares what the fake loader read, the prepare/finalize events and the layers per batch. The fake loader (test_kimi_k3_model_streamer.py:133-143) reads only its own expert, so a plan whose groups also named expert 1 (owned by another rank) would still pass, although each node would then read experts its ranks do not own, which defeats the selective load. Please assert the exact set, e.g. set().union(*streamed_batches) == expected, where expected holds experts 2 and 0 x w1/w2/w3 x kinds for every layer, plus expert 2's w1.pre_quant_scale.
| def build() -> KimiLinearForCausalLM: | ||
| with torch.device("cuda"): | ||
| model = KimiLinearForCausalLM( | ||
| _config(fp8, mapping=mapping, prefix=prefix, deferred=False, cute_bmm=True) |
There was a problem hiding this comment.
[Nice to have] This test builds only deferred=False, cute_bmm=True, and FP8 only with weight_scale_inv (test_kimi_k3_checkpoint.py:255). So MLA never creates k_b_proj_trans_dequant/v_b_proj_dequant (mla.py:802), although that is the default SM100 path (use_cute_dsl_blockscaling_bmm defaults to False, llm_args.py:7232); the loop at test_kimi_k3_checkpoint.py:310-315 compares None with None, and the weight_scale branch of tensor_and_scale_names (modeling_kimi_k3_loader.py:721) never runs. Please reuse the sibling test's (deferred, cute_bmm) pairs and three (fp8, scale_name) pairs (test_kimi_k3_checkpoint.py:126-129); the trailing loop can then go, since named_parameters() covers those parameters.
| # not be kept for runtime forward. | ||
| self.mm_encoder = None | ||
| if not DISAGG: | ||
| if not DISAGG and not model_config.disable_mm_encoder: |
There was a problem hiding this comment.
[Nice to have] No test builds the real KimiK25ForConditionalGeneration or KimiK3ForConditionalGeneration with disable_mm_encoder=True; the streamer tests use a wrapper that skips __init__ and forward. If this guard (or modeling_kimi_k3_vl.py:498) is reverted, a model built without MetaInitMode still builds and loads the vision tower, and without the check at modeling_kimi_k25.py:1791 an image request fails on None.forward, with no test noticing. Mistral3 has such a test (test_modeling_mistral.py:182). Please add construction tests for both classes with the flag, with and without MetaInitMode (no mm_encoder.* parameters, encoder still None after load_weights), and a forward test that expects the rejection.
| self._load_trunk_params, | ||
| params={name: params[name]}, | ||
| name_map={name: key}, | ||
| log_summary=False, |
There was a problem hiding this comment.
[Nice to have] The streamed load drops diagnostics that the native load prints: the plan never runs _validate_checkpoint_keys, so the unmatched-key warning (modeling_kimi_k3_loader.py:916-920) is gone, and with log_summary=False on every group the KV-B summary (:1124-1127) is never logged. A checkpoint with stray tensors therefore warns under native and is silent under model_streamer. K2.5/K3 also log nothing when disable_mm_encoder skips the encoder (modeling_kimi_k25.py:1632, modeling_kimi_k3_vl.py:498), unlike modeling_qwen3vl.py:1565-1569. Please run the unmatched-key check from the plan, log the KV-B summary once in finish(), and add the same info line when the encoder is skipped.
| load runs `run_model_streamer()` for real. The returned list records the names | ||
| that the fake streamer delivered. | ||
| """ | ||
| from tensorrt_llm._torch.models.modeling_kimi_linear import KimiLinearForCausalLM |
There was a problem hiding this comment.
[Nice to have] This generic ModelLoader helper now imports the Kimi K3 model, and through kimi_kda_mixer.py:27 the fla package, only to spec a MagicMock, so any Kimi/KDA/fla import problem breaks unrelated loader tests. A small local nn.Module subclass that defines load_weights and plan_model_streamer_load would serve as the spec. Also, test_kimi_k3_model_streamer.py calls pytest.importorskip("fla") only in the expert test (test_kimi_k3_model_streamer.py:101), but its two multimodal tests import the same chain and would error instead of skip; please move it to module level, and consider putting that file in tests/unittest/_torch/modeling/ with the other Kimi tests.
| self._ensure_mm_encoder() | ||
| if self.mm_encoder is not None: | ||
| # Name prefixes of vision encoder and projector tensors. | ||
| vision_prefixes = ( |
There was a problem hiding this comment.
[Nice to have] These prefixes copy the _detect_prefix candidates in KimiK25VisionModel.load_weights (modeling_kimi_k25.py:910 and :917). If the vision loader learns a new prefix and this tuple is not updated, the streamed load skips those tensors or raises the KeyError at modeling_kimi_k3_vl.py:588, while the native load works. Please hoist the two candidate lists into module constants in modeling_kimi_k25.py and build this tuple from them.
| name_map: Dict[str, str], | ||
| log_summary: bool = True, | ||
| ) -> int: | ||
| """Load every non-expert trunk parameter concurrently (with the |
There was a problem hiding this comment.
[Nice to have] Several docstrings no longer match the code. This one says it loads "every non-expert trunk parameter concurrently", but the plan passes one parameter; _load_attention_fp8 (modeling_kimi_k3_loader.py:386) does not document projection_names; the class docstring (:335-342) is vague ("mixin-like", "would read") where it should say the methods work only as a base of KimiLinearForCausalLM. In modeling_kimi_k3_vl.py, :458-461 says "only __init__ differs", :495-496 says the encoder is recreated in load_weights (the plan now does it too), and :557-558 says every rank keeps the whole vision encoder, which is false when the tower is TP-sharded (modeling_kimi_k25.py:383-385). Please update them.
| key for key in checkpoint_keys if key.startswith(vision_prefixes) | ||
| } | ||
| if not vision_keys: | ||
| raise KeyError("Kimi K3 Model Streamer found no vision weights") |
There was a problem hiding this comment.
[Nice to have] With checkpoint_io_policy=model_streamer, a checkpoint that declares a vision tower but stores no vision or projector tensors fails here on every rank, while the native load only warns and continues (modeling_kimi_k25.py:923-925). Raising is safer than serving an uninitialized tower, but the message gives the user no way forward. Please list the searched prefixes and suggest disable_mm_encoder: true, e.g. KeyError(f"Kimi K3 Model Streamer found no tensors starting with {vision_prefixes}; set disable_mm_encoder: true to load only the language model").
2a12f1e to
3a29fdc
Compare
2e158ca to
c8b0cc8
Compare
da61750 to
764e372
Compare
There was a problem hiding this comment.
My previous comments have been addressed; thanks. 2 follow-up comments:
-
Reject media requests before scheduling. With
disable_mm_encoder=True, image or video requests fail inside batchedforward(). The executor then fails all active requests, including valid text requests, and consumes its error budget. Please reject media throughvalidate_multimodal_request_data()before scheduling. Add a mixed batch of separate text and media requests, and verify that only the media request fails. See the forward check. -
Update the existing K2.5 test double. The new
_ensure_mm_encoder()call breakstest_language_weights_preserve_checkpoint_dir. ItsSimpleNamespacelacks that method, so the test raisesAttributeErrorbefore it checks checkpoint metadata. Please update the test double and run the test. See the new helper call.
|
Could you please rebase this branch onto the latest upstream |
a96c366 to
24c35ed
Compare
24c35ed to
1f2541a
Compare
Move the weight-loading methods of KimiLinearForCausalLM and the helpers that only they use into the new file modeling_kimi_k3_loader.py. modeling_kimi_linear.py had over 3,300 lines, and about 1,100 of them only turn checkpoint tensors into model parameters. The code moves unchanged: KimiLinearForCausalLM inherits the methods from KimiK3WeightLoaderMixin, and tests import the moved helpers from the new file. The inference module _Fp8BlockScaleWeightReadLinear stays in modeling_kimi_linear.py; the loader imports it inside the functions that use it, because modeling_kimi_linear.py imports the loader. No functional change. Signed-off-by: Yijing Li <[email protected]>
Add checkpoint_io_policy="model_streamer", which loads a Hugging Face checkpoint with Run:ai Model Streamer. Model Streamer reads each byte from storage once per node and shares it among the ranks of the node, so large checkpoints load faster. A model describes what it needs in plan_model_streamer_load(), which returns a ModelStreamerPlan: groups of checkpoint tensor names, each with a function that loads the group. The new models/checkpoints/model_streamer/model_loading.py streams only the tensors that the ranks of a node need, with run_model_streamer(), and loads each group as soon as its tensors arrive. A separate draft checkpoint, such as a DSpark drafter, is read with the regular checkpoint reader. Model Streamer's NCCL group can start NCCL before TRTLLM's communicators do, so it first sets TRTLLM's NCCL environment defaults through the new C++ helper setNcclEnvDefaults(), which getComm() and NcclCommunicator::createComm() now share. The next commit adds this for Kimi K3. Signed-off-by: Yijing Li <[email protected]>
Implement plan_model_streamer_load() for Kimi K3 and its multimodal wrapper, with the ModelStreamerPlan from the previous commit. Each rank lists only the tensors that it needs, for example its own experts, so each node streams only what its ranks use. Also support Kimi K3 language-only loads that skip the multimodal encoder, document Model Streamer loading in the Kimi K3 README, and add tests. Signed-off-by: Yijing Li <[email protected]>
Description
This PR adds the Model Streamer load for Kimi K3. Each rank lists only the checkpoint tensors that it needs, for example its own experts, so each node streams only what its ranks use.
It also supports Kimi K3 language-only loads, which skip the multimodal encoder (
disable_mm_encoder), and adds a Model Streamer section to the Kimi K3 README.The regular Kimi K3 load (
_load_expert_slices()) and the Model Streamer load put every routed expert into its MoE backend slot with the same two functions ofmodeling_kimi_k3_loader.py._load_expert_into_slot()prepares a layer's staging buffers on its first expert and finalizes the layer when its last slot fills._check_expert_slots()checks at the end that every slot is filled and every staged layer is finalized. So a change to these steps lands in both loads.This PR must merge after #20717 and #20781. Its branch contains the commits of #20717 and #20781. Review only the last commit: https://github.com/NVIDIA/TensorRT-LLM/pull/20782/files/c7a24d605e6caf9c7810a71b01f0d2f42a402d95..08b71ff03efd49d5ec56a224632e550071231a88
The Model Streamer expert load also streams the optional per-expert tensors that the checkpoint stores, such as the AWQ pre-quant scale, and gives them to the Kimi K3 expert loaders through their
get_optional_tensorargument (#20823).test_streamer_expert_loading_matches_regular_loadercovers experts with and without the optional tensor.Test Coverage
4 tests added, 0 tests changed:
tests/unittest/_torch/modeling/test_kimi_k3_checkpoint.pytests/unittest/_torch/models/test_kimi_k3_model_streamer.pyThe new tests build their checkpoint with
mla_checkpoint(), which this PR splits out of the test helperload_mla_checkpoint(). It keeps the helper'srandom_gate_upoption from #20717.tests/unittest/_torch/models/test_kimi_k3_model_streamer.pynow runs in the B200 pre-merge list (l0_b200.yml).Load-time experiment
This experiment checks the Model Streamer change from the review:
stream_files(..., owned=False), and notorch.cuda.synchronize()after each streamed tensor. With the change, the weights and the outputs stay the same, and Model Streamer loads the weights about 6% faster.Setup:
quick_start_kimi_k3.py.1.4.0rc3.dev202610290007with the Python files of commitddfeb9abf9, and runai-model-streamer 0.17.1. This branch differs from that commit in the checks, errors, names and process-group setup of the Model Streamer load, and its Kimi K3 expert-load steps are in functions that the regular load shares. In the setup of this experiment, each node still streams the tensors that its 4 ranks need, and the 4 ranks share the reads.model_loading.pybefore the change (defaultowned=True, sync after each tensor). New code: this branch.Load time in seconds for the slowest of the 8 ranks, with the median rank in parentheses:
checkpoint_io_policyweight_population_secondstotal_model_loading_secondsmodel_streamer_secondsnativemodel_streamermodel_streamermodel_streamermodel_streamernativemodel_streamer_seconds, because the test hook that records this value started after run 2.Accuracy: all six runs gave the same weights. On each of the 8 ranks, the checksums of all 3,296 parameters and buffers (209 GB for each rank) are equal. Greedy outputs (temperature 0, 8 prompts, 128 tokens for each prompt) have the same token IDs in all six runs.
PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
If PR introduces API changes, an appropriate PR label is added - either
api-compatibleorapi-breaking. Forapi-breaking, includeBREAKINGin the PR title.Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
Update tava architecture diagram if there is a significant design change in PR.
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
To see a list of available CI bot commands, please comment
/bot help.PRs in this series
These PRs refactor checkpoint loading and add Model Streamer loading. They merge in this order, top to bottom.
checkpoint_io_policyfrom plain strings to the string enumCheckpointIOPolicy.CheckpointFormatfor the built-in checkpoint formats, make the checkpoint I/O helpers take onlyLoadFormat, and make the checkpoint I/O policy resolution easier to read.distributed/initialization.py.ModelLoader.load()shorter: move its MX, GMS, memory and model-hook helpers to new files inmodels/checkpoints/.BaseCheckpointLoader.modeling_kimi_linear.pytomodeling_kimi_k3_loader.py.checkpoint_io_policy="model_streamer", which loads a checkpoint with Run:ai Model Streamer.🤖 Generated with Claude Code