-
Notifications
You must be signed in to change notification settings - Fork 2k
[TRTLLM-8533][chore] extract weights loading related logic to model loader #7579
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Signed-off-by: junq <22017000+QiJune@users.noreply.github.com>
|
/bot run |
|
PR_Github #17837 [ run ] triggered by Bot |
📝 WalkthroughWalkthroughReplaces PyTorchModelEngine’s inline loading with a ModelLoader-driven pipeline. Adds a new model_loader module implementing config validation, quantization handling, meta initialization/materialization, weight loading, MOE integration, and optional drafting wrapper. Updates two bench modules to import validate_and_set_kv_cache_quant from model_loader. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant App as PyTorchModelEngine
participant ML as ModelLoader
participant CL as CheckpointLoader
participant MOE as MoeLoadBalancer
participant CUDA as CUDA Device
App->>ML: construct(pytorch_backend_config, mapping, spec_config, max_tokens, max_seq_len, lora_config)
App->>ML: load(checkpoint_dir, checkpoint_loader, drafting_loop_wrapper)
ML->>CL: load_config(...flags from backend/spec/lora/moe...)
ML->>ML: validate kv_cache & mamba_ssm dtypes
ML->>MOE: optional: enter load-balancer context
ML->>ML: init model (meta) with config
ML->>ML: materialize to CUDA
ML->>CUDA: allocate params/buffers
ML->>CL: load_weights(checkpoint_dir, weight_mapper[, drafts])
CL-->>ML: weights loaded
ML->>MOE: optional: finalize MOE
ML->>ML: optional: apply drafting_loop_wrapper
ML-->>App: return model (wrapped or raw)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
tensorrt_llm/bench/benchmark/utils/general.py (2)
1-1: Add mandatory NVIDIA Apache-2.0 header (2025).Apply:
+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +limitations under the License.
21-24: Bug: NVFP4 mapped to "fp8"._KV_CACHE_MAP incorrectly maps QuantAlgo.NVFP4.value to "fp8". Should be "nvfp4". This will select the wrong KV-cache dtype.
Apply:
_KV_CACHE_MAP = { QuantAlgo.FP8.value: "fp8", - QuantAlgo.NVFP4.value: "fp8", + QuantAlgo.NVFP4.value: "nvfp4", }tensorrt_llm/bench/dataclasses/reporting.py (1)
1-1: Add mandatory NVIDIA Apache-2.0 header (2025).Apply:
+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +limitations under the License.tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
1-1: Add NVIDIA Apache-2.0 header (2025).This file is missing the required license header per repo guidelines.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License.
🧹 Nitpick comments (3)
tensorrt_llm/_torch/pyexecutor/model_loader.py (2)
283-287: Initialize dummy weights under no_grad and avoid .data where possible.Wrap ops in torch.no_grad() to avoid autograd tracking. Keep the existing logic but minimize .data usage.
Apply:
def _initialize_dummy_weights(model: torch.nn.Module, low: float = -1e-3, high: float = 1e-3, seed: int = 0) -> None: """Initializes model weights with random dummy values for testing purposes.""" # This function's logic is copied directly from the original file def _get_random_min_max(dtype: torch.dtype) -> Tuple[int, int]: @@ - for param in model.state_dict().values(): - generator = torch.Generator(device=param.data.device) - generator.manual_seed(seed) - dtype = param.data.dtype - - if param.data.element_size() < 2: - tmp_param = torch.empty_like(param.data, - dtype=torch.float16, - device=param.data.device) - quant_min, quant_max = _get_random_min_max(dtype) - tmp_param.uniform_(quant_min, quant_max, generator=generator) - param.data.copy_(tmp_param.to(dtype)) - elif torch.is_floating_point(param): - param.uniform_(low, high, generator=generator) + with torch.no_grad(): + for tensor in model.state_dict().values(): + generator = torch.Generator(device=tensor.device) + generator.manual_seed(seed) + dtype = tensor.dtype + + if tensor.element_size() < 2: + tmp_param = torch.empty_like(tensor, + dtype=torch.float16, + device=tensor.device) + quant_min, quant_max = _get_random_min_max(dtype) + tmp_param.uniform_(quant_min, quant_max, generator=generator) + tensor.copy_(tmp_param.to(dtype)) + elif torch.is_floating_point(tensor): + tensor.uniform_(low, high, generator=generator)Also applies to: 298-312
230-244: KV/mamba dtype validation usage looks consistent. Minor: log the resolved values.In addition to mutating config, consider logging the final kv_cache_quant_algo and mamba_ssm_cache_dtype to aid debugging.
Example:
validate_and_set_kv_cache_quant( config, self.pytorch_backend_config.kv_cache_dtype) validate_and_set_mamba_ssm_cache_dtype( config, self.pytorch_backend_config.mamba_ssm_cache_dtype) + logger.info(f"Resolved kv_cache_quant_algo={config.quant_config.kv_cache_quant_algo}, " + f"mamba_ssm_cache_dtype={getattr(config.quant_config, 'mamba_ssm_cache_dtype', None)}")tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
38-41: Prefer module import over direct class import to match style guide.Import the module and reference the class via the module to keep namespace clean.
-from ..models.modeling_utils import DecoderModelForCausalLM +from ..models import modeling_utilsAnd later:
- if isinstance(self.model, DecoderModelForCausalLM): + if isinstance(self.model, modeling_utils.DecoderModelForCausalLM):
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
tensorrt_llm/_torch/pyexecutor/model_engine.py(4 hunks)tensorrt_llm/_torch/pyexecutor/model_loader.py(1 hunks)tensorrt_llm/bench/benchmark/utils/general.py(1 hunks)tensorrt_llm/bench/dataclasses/reporting.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use only spaces, no tabs; indent with 4 spaces.
Files:
tensorrt_llm/bench/benchmark/utils/general.pytensorrt_llm/bench/dataclasses/reporting.pytensorrt_llm/_torch/pyexecutor/model_loader.pytensorrt_llm/_torch/pyexecutor/model_engine.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.
Files:
tensorrt_llm/bench/benchmark/utils/general.pytensorrt_llm/bench/dataclasses/reporting.pytensorrt_llm/_torch/pyexecutor/model_loader.pytensorrt_llm/_torch/pyexecutor/model_engine.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).
Files:
tensorrt_llm/bench/benchmark/utils/general.pytensorrt_llm/bench/dataclasses/reporting.pytensorrt_llm/_torch/pyexecutor/model_loader.pytensorrt_llm/_torch/pyexecutor/model_engine.py
🧠 Learnings (2)
📚 Learning: 2025-08-26T09:37:10.463Z
Learnt from: jiaganc
PR: NVIDIA/TensorRT-LLM#7031
File: tensorrt_llm/bench/dataclasses/configuration.py:90-104
Timestamp: 2025-08-26T09:37:10.463Z
Learning: In TensorRT-LLM's bench configuration, the `get_pytorch_perf_config()` method returns `self.pytorch_config` which is a Dict[str, Any] that can contain default values including `cuda_graph_config`, making the fallback `llm_args["cuda_graph_config"]` safe to use.
Applied to files:
tensorrt_llm/bench/dataclasses/reporting.py
📚 Learning: 2025-08-19T12:45:11.997Z
Learnt from: amitz-nv
PR: NVIDIA/TensorRT-LLM#7033
File: tensorrt_llm/_torch/pyexecutor/model_engine.py:0-0
Timestamp: 2025-08-19T12:45:11.997Z
Learning: In tensorrt_llm/_torch/pyexecutor/model_engine.py, DoRA (Delta Orthogonal Rank Adaptation) functionality was removed from the PyTorch flow to eliminate issues with inverted DoRA detection logic. The original is_dora condition was checking if scaling_vec_pointer == 0, which was potentially incorrect.
Applied to files:
tensorrt_llm/_torch/pyexecutor/model_engine.py
🧬 Code graph analysis (2)
tensorrt_llm/_torch/pyexecutor/model_loader.py (9)
tensorrt_llm/mapping.py (1)
Mapping(32-513)tensorrt_llm/quantization/mode.py (1)
QuantAlgo(23-47)tensorrt_llm/_torch/models/checkpoints/base_checkpoint_loader.py (3)
BaseCheckpointLoader(19-87)get_initialized_weight_mapper(70-87)load_config(53-54)tensorrt_llm/_torch/models/modeling_utils.py (2)
MetaInitMode(51-94)timing(32-36)tensorrt_llm/_torch/modules/fused_moe/moe_load_balancer.py (1)
maybe_create_moe_load_balancer(954-979)tensorrt_llm/_torch/pyexecutor/config.py (1)
PyTorchConfig(17-115)tensorrt_llm/_torch/speculative/interface.py (1)
need_load_draft_weights(79-84)tensorrt_llm/_torch/models/modeling_speculative.py (1)
load_draft_weights(480-485)tensorrt_llm/_torch/pyexecutor/model_engine.py (1)
load_weights_from_target_model(2111-2120)
tensorrt_llm/_torch/pyexecutor/model_engine.py (2)
tensorrt_llm/_torch/pyexecutor/config.py (1)
PyTorchConfig(17-115)tensorrt_llm/_torch/pyexecutor/model_loader.py (2)
ModelLoader(84-311)load(116-171)
🪛 Ruff (0.12.2)
tensorrt_llm/_torch/pyexecutor/model_loader.py
91-91: Undefined name DecodingBaseConfig
(F821)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Pre-commit Check
🔇 Additional comments (5)
tensorrt_llm/bench/benchmark/utils/general.py (1)
11-12: Import path update: LGTM.The function moved; usage remains unchanged.
tensorrt_llm/bench/dataclasses/reporting.py (1)
7-8: Import path update: LGTM.Matches the new location of validate_and_set_kv_cache_quant.
tensorrt_llm/_torch/pyexecutor/model_engine.py (3)
17-17: Import additions look correct.trace_func is used in model_forward; torch_dtype_to_str is used later; both are appropriate.
49-49: LGTM on config import.Consistent with local package structure.
55-55: Approve changes No stale imports remain; all uses of validate_and_set_kv_cache_quant and validate_and_set_mamba_ssm_cache_dtype import from model_loader instead of model_engine.
|
PR_Github #17837 [ run ] completed with state |
|
/bot run |
|
PR_Github #18100 [ run ] triggered by Bot |
|
PR_Github #18100 [ run ] completed with state |
|
/bot run |
|
PR_Github #18253 [ run ] triggered by Bot |
|
/bot run |
|
PR_Github #18389 [ run ] triggered by Bot |
|
/bot run |
|
PR_Github #19497 [ run ] triggered by Bot |
|
PR_Github #19497 [ run ] completed with state |
|
/bot run |
|
PR_Github #19677 [ run ] triggered by Bot |
|
PR_Github #19677 [ run ] completed with state |
|
/bot run |
|
PR_Github #19692 [ run ] triggered by Bot |
|
PR_Github #19692 [ run ] completed with state |
|
/bot run |
|
PR_Github #19739 [ run ] triggered by Bot |
|
PR_Github #19739 [ run ] completed with state |
|
/bot run |
|
/bot run |
|
PR_Github #19903 [ run ] triggered by Bot |
|
/bot run |
|
PR_Github #19933 [ run ] triggered by Bot |
|
PR_Github #19903 [ run ] completed with state |
|
PR_Github #19933 [ run ] completed with state |
Summary by CodeRabbit
New Features
Refactor
Chores
Description
Test Coverage
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)
Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
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
/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...Provide a user friendly way for developers to interact with a Jenkins server.
Run
/bot [-h|--help]to print this help message.See details below for each supported subcommand.
Details
run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]Launch build/test pipelines. All previously running jobs will be killed.
--reuse-test (optional)pipeline-id(OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.--disable-reuse-test(OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.--disable-fail-fast(OPTIONAL) : Disable fail fast on build/tests/infra failures.--skip-test(OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.--stage-list "A10-PyTorch-1, xxx"(OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.--gpu-type "A30, H100_PCIe"(OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.--test-backend "pytorch, cpp"(OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.--only-multi-gpu-test(OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.--disable-multi-gpu-test(OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.--add-multi-gpu-test(OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.--post-merge(OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx"(OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".--detailed-log(OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.--debug(OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in thestage-listparameter to access the appropriate container environment. Note: Does NOT update GitHub check status.For guidance on mapping tests to stage names, see
docs/source/reference/ci-overview.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip testing for latest commit on pull request.
--comment "Reason for skipping build/test"is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.reuse-pipeline
reuse-pipelineReuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.