-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[None][chore] [WIP] Create PyExecutor from TorchLlmArgs Part 2 #7202
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
[None][chore] [WIP] Create PyExecutor from TorchLlmArgs Part 2 #7202
Conversation
Signed-off-by: leslie-fang25 <[email protected]>
Signed-off-by: leslie-fang25 <[email protected]>
Signed-off-by: leslie-fang25 <[email protected]>
Signed-off-by: leslie-fang25 <[email protected]>
Signed-off-by: leslie-fang25 <[email protected]>
Signed-off-by: leslie-fang25 <[email protected]>
Signed-off-by: leslie-fang25 <[email protected]>
Signed-off-by: leslie-fang25 <[email protected]>
Signed-off-by: leslie-fang25 <[email protected]>
📝 WalkthroughWalkthroughRefactors executor configuration to be driven by llm_args across the codebase. Public APIs now pass Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant App as Application
participant LLM as LLM/_TorchLLM/_TrtLLM
participant Exec as GenerationExecutor.create
participant Proxy as GenerationExecutorProxy
participant Worker as GenerationExecutorWorker
participant Args as llm_args (BaseLlmArgs/TorchLlmArgs)
participant PyExec as create_py_executor
participant AD as create_autodeploy_executor
App->>LLM: initialize(args, tokenizer, hf_model_dir)
LLM->>Exec: create(engine, executor_config=None, hf_model_dir, tokenizer, llm_args)
Exec->>Proxy: init(worker_kwargs={hf_model_dir, tokenizer, llm_args, ...})
Proxy->>Worker: spawn(worker_kwargs)
Worker->>Args: inspect backend / parallel_config
alt backend == "pytorch"
Worker->>Args: get_executor_config(hf_model_dir, tokenizer)
Worker->>PyExec: create_py_executor(llm_args, checkpoint_dir=hf_model_dir, tokenizer, ...)
PyExec-->>Worker: PyTorch executor
else backend == "_autodeploy"
Worker->>AD: create_autodeploy_executor(ad_config=llm_args)
AD-->>Worker: AD executor
else
Worker->>Worker: fallback legacy engine path
end
Worker-->>Proxy: ready
Proxy-->>App: executor ready
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. 📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
✨ 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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
|
/bot run |
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: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
tensorrt_llm/_torch/auto_deploy/shim/ad_executor.py (2)
64-68: Fix logging: passing args without placeholders raises runtime error
ad_logger.info("...:", self.num_blocks)will trigger string formatting in the logger and crash because the message has no%splaceholder. Use f-string or add a placeholder.Apply this diff:
- ad_logger.info("Using fake cache manager with head_dim=0 and num pages:", self.num_blocks) + ad_logger.info(f"Using fake cache manager with head_dim=0 and num pages: {self.num_blocks}")
272-273: Device selection uses global rank; will fail on multi-GPU/multi-node setupsSetting
torch.cuda.set_device(rank)assumesrank < device_counton every node. On multi-node jobs (or even single node with >1 process per GPU), this can select an invalid device. Use local device id (e.g., modulo device count) or a local rank.Apply this diff:
- torch.cuda.set_device(rank) + device_count = torch.cuda.device_count() + assert device_count > 0, "No CUDA devices found" + torch.cuda.set_device(rank % device_count)Optionally prefer a true local-rank if available from MPI/env.
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)
246-246: Fix logging: passing args without placeholders raises runtime error
logger.info("ATTENTION RUNTIME FEATURES: ", attn_runtime_features)will try to format the string and fail. Use one formatted string.Apply this diff:
- logger.info("ATTENTION RUNTIME FEATURES: ", attn_runtime_features) + logger.info(f"ATTENTION RUNTIME FEATURES: {attn_runtime_features}")
🧹 Nitpick comments (27)
tests/unittest/api_stability/references/llm.yaml (1)
98-101: Public API addition aligns with TorchLlmArgs.mm_encoder_only; consider clarifying backend scope.The parameter is correctly typed, defaulted, and marked prototype. Since mm_encoder_only is Torch-only today, consider adding a short note in the API docs (or description string where this YAML is surfaced) indicating it applies to the PyTorch backend. This avoids confusion for TRT users seeing it in the global init signature.
tensorrt_llm/llmapi/llm_args.py (3)
1-1: Add 2025 NVIDIA copyright header.Per repo guidelines, prepend the current-year NVIDIA header to all Python files.
Apply at the top of the file:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
1840-1914: New BaseLlmArgs.get_executor_config: solid unification; add docstring, remove duplicate assignment, and guard deterministic toggle.
- Public method needs a Google-style docstring per guidelines.
- executor_config.max_beam_width is set twice; the second assignment is redundant.
- Deterministic-mode KV toggling should guard against None to be defensive (even though kv_cache_config currently defaults to a value).
Apply this diff within the method:
- def get_executor_config( + def get_executor_config( self, _hf_model_dir: Optional[Path] = None, tokenizer: Optional[TokenizerBase] = None, ) -> _ExecutorConfig: - executor_config = _ExecutorConfig( + """Build and return an ExecutorConfig derived from LLM args. + + Args: + _hf_model_dir: Local HF model directory (if applicable). + tokenizer: Tokenizer instance to enrich guided decoding config. + + Returns: + A configured _ExecutorConfig reflecting runtime knobs and backend specifics. + """ + executor_config = _ExecutorConfig( max_beam_width=self.max_beam_width, scheduler_config=PybindMirror.maybe_to_pybind( self.scheduler_config), max_batch_size=self.max_batch_size, max_num_tokens=self.max_num_tokens, gather_generation_logits=self.gather_generation_logits, fail_fast_on_attention_window_too_large=getattr( self, 'fail_fast_on_attention_window_too_large', False), ) @@ - if os.getenv("FORCE_DETERMINISTIC", "0") == "1": + if os.getenv("FORCE_DETERMINISTIC", "0") == "1" and getattr(executor_config, "kv_cache_config", None) is not None: # Disable KV cache reuse for deterministic mode executor_config.kv_cache_config.enable_block_reuse = False executor_config.kv_cache_config.enable_partial_reuse = False @@ - executor_config.enable_chunked_context = self.enable_chunked_prefill - executor_config.max_beam_width = self.max_beam_width + executor_config.enable_chunked_context = self.enable_chunked_prefillOptional follow-up (API polish): consider renaming parameter
_hf_model_dirtohf_model_dir(leading underscore reads as private) while keeping a backwards-compatible alias in the signature.
2460-2469: TorchLlmArgs.get_executor_config override: propagation is correct; add a brief docstring.Setting executor_config.mm_encoder_only from args is the right place. Add a short docstring to comply with project style.
Apply this diff:
def get_executor_config( self, _hf_model_dir: Optional[Path] = None, tokenizer: Optional[TokenizerBase] = None, ) -> _ExecutorConfig: + """Extend BaseLlmArgs.get_executor_config with Torch-specific flags.""" executor_config = super().get_executor_config(_hf_model_dir, tokenizer) executor_config.mm_encoder_only = self.mm_encoder_only return executor_configtests/unittest/llmapi/test_llm_args.py (3)
1-1: Add 2025 NVIDIA copyright header.Tests are Python source and should carry the standard header.
Apply at the top of the file:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
441-447: Avoid depending on private attribute llm._hf_model_dir in tests.Accessing a private field in tests couples them to internals. Prefer a public accessor (e.g., llm.hf_model_dir) or update get_executor_config to not require a leading-underscore param or to infer the path internally when used via LLM.
Two options:
- Expose a public property on LLM for HF model dir and switch the test to it.
- Change get_executor_config’s parameter name to hf_model_dir (no underscore) and accept None when the path isn’t required for the assertion performed here.
If you want, I can draft a small PR to add LLM.hf_model_dir and update call sites.
441-447: Add a focused test for mm_encoder_only propagation (Torch).Current tests validate runtime sizes; add coverage to assert mm_encoder_only flows into executor_config when set on TorchLlmArgs.
Example (add near Torch tests):
def test_torch_llm_args_mm_encoder_only_flag_propagates(): args = TorchLlmArgs.from_kwargs(model=llama_model_path, mm_encoder_only=True) # Tokenizer/HF dir may not be needed for this assertion exec_cfg = args.get_executor_config(_hf_model_dir=None, tokenizer=None) assert getattr(exec_cfg, "mm_encoder_only", False) is Truetensorrt_llm/llmapi/mm_encoder.py (1)
1-1: Add 2025 NVIDIA copyright header.Please prepend the standard header.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.tensorrt_llm/executor/proxy.py (1)
1-1: Add 2025 NVIDIA copyright header.Please prepend the standard header.
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.tensorrt_llm/_torch/auto_deploy/shim/ad_executor.py (3)
277-279: Update assertion message and type checkThe assertion message mentions
pytorch_backend_config, but the parameter isad_config. Make message accurate and consider a clearer failure mode.Apply this diff:
- msg = "pytorch_backend_config must be an AD LlmArgs object" - assert isinstance(ad_config, LlmArgs), msg + msg = "ad_config must be an AutoDeploy LlmArgs object" + if not isinstance(ad_config, LlmArgs): + raise TypeError(msg)
154-156: Reconsider hardcoded random seedHardcoding
torch.manual_seed(1234)makes results deterministic but can be surprising in production. Consider making this configurable onad_config(e.g.,random_seed: Optional[int]) and only seeding if provided.Apply this diff:
- # start fresh with fixed seed - torch.manual_seed(1234) + # Optional, user-configurable seed for reproducibility + seed = getattr(self, "random_seed", None) + if seed is not None: + torch.manual_seed(seed)And add
random_seed: Optional[int] = NonetoLlmArgsif not already present.
1-1: Add NVIDIA copyright headerPer repository guidelines, prepend the current-year NVIDIA header.
Apply this diff at the top of the file:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (5)
31-33: Duplicate import of is_mla; remove ambiguity
is_mlais imported from two modules, which is confusing and error-prone. Keep one source.Apply this diff:
-from ._util import (KvCacheCreator, _adjust_torch_mem_fraction, - create_py_executor_instance, instantiate_sampler, is_mla) -from .config_utils import is_mla +from ._util import (KvCacheCreator, _adjust_torch_mem_fraction, + create_py_executor_instance, instantiate_sampler) +from .config_utils import is_mla
210-217: Document the new llm_args-driven APIAdd a concise docstring to clarify behavior and parameters, especially the relation between
llm_argsand derivedexecutor_config.Apply this diff:
def create_py_executor( llm_args: TorchLlmArgs, - checkpoint_dir: str = None, + checkpoint_dir: str = None, tokenizer: Optional[TokenizerBase] = None, lora_config: Optional[LoraConfig] = None, logits_post_processor_config: Optional[LogitsPostProcessorConfig] = None, parallel_config: Optional[ParallelConfig] = None, ) -> PyExecutor: + """ + Create a PyExecutor for the PyTorch backend driven by TorchLlmArgs. + + Args: + llm_args: TorchLlmArgs instance. Source of truth for executor configuration. + checkpoint_dir: HF model directory (optional). If provided, used to locate weights/config. + tokenizer: Optional tokenizer instance. Required for some guided decoding backends. + lora_config: Optional LoRA configuration. + logits_post_processor_config: Optional logits post-processing configuration. + parallel_config: Optional explicit parallel configuration; overrides derived mapping if set. + Returns: + PyExecutor instance ready to start_worker(). + """
212-213: Broaden checkpoint_dir type to Path-like
checkpoint_diroften comes as aPath. Widen the type hint to accept both.Apply this diff:
-from typing import Optional +from typing import Optional, Union +from pathlib import Path ... - checkpoint_dir: str = None, + checkpoint_dir: Optional[Union[str, Path]] = None,
186-196: Avoid shadowing LoadFormat with a second import
LoadFormatis already imported from.config. Re-importing with the same name fromllm_argsis confusing. Either alias the second import or reuse the existing one if compatible.Apply this diff:
- from tensorrt_llm.llmapi.llm_args import LoadFormat - pytorch_backend_config.mm_encoder_only = True - pytorch_backend_config.load_format = LoadFormat.VISION_ONLY + # Reuse LoadFormat imported from .config + pytorch_backend_config.mm_encoder_only = True + pytorch_backend_config.load_format = LoadFormat.VISION_ONLYIf the enums differ, import with an alias instead:
from tensorrt_llm.llmapi.llm_args import LoadFormat as LlmArgsLoadFormat pytorch_backend_config.load_format = LlmArgsLoadFormat.VISION_ONLY
1-1: Add NVIDIA copyright headerPer repository guidelines, prepend the current-year NVIDIA header.
Apply this diff at the top of the file:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.tensorrt_llm/executor/executor.py (2)
346-362: Update create() docstring for new parametersThe public factory signature now includes
hf_model_dir,tokenizer, andllm_args. Add a docstring to prevent misuse and document backward-incompatible change.Apply this diff:
def create( engine: Union[Path, Engine], executor_config: Optional[tllm.ExecutorConfig] = None, batched_logits_processor: Optional[BatchedLogitsProcessor] = None, model_world_size: int = 1, world_size: int = 0, mpi_session: Optional[MpiSession] = None, reuse_mpi_comm: bool = False, return_logits: bool = False, postproc_worker_config: Optional[PostprocWorkerConfig] = None, is_llm_executor: Optional[bool] = None, lora_config: Optional[LoraConfig] = None, hf_model_dir: Optional[Path] = None, tokenizer: Optional[TokenizerBase] = None, llm_args: Optional[BaseLlmArgs] = None, ) -> Union["GenerationExecutorProxy", "GenerationExecutorWorker"]: + """ + Create a GenerationExecutor (proxy or worker). + + Args: + engine: Engine path or Engine object. + executor_config: Legacy runtime config; pass None when using PyTorch/AutoDeploy llm_args path. + batched_logits_processor: Optional batched logits processor. + model_world_size: Number of model ranks (TPxPP). + world_size: Total MPI world size; 0 means auto-detect. + mpi_session: Optional external MPI session. + reuse_mpi_comm: Reuse communicator when launched via mpirun. + return_logits: Use single-process worker path to optimize logits gathering for TP1. + postproc_worker_config: Post-processing parallelism configuration. + is_llm_executor: Mark the main LLM executor instance. + lora_config: Optional LoRA configuration. + hf_model_dir: Optional HF model directory (used by PyTorch backend). + tokenizer: Optional tokenizer instance (used by PyTorch backend and guided decoding). + llm_args: LLM argument object driving backend configuration ("pytorch" or "_autodeploy"). + """
1-1: Add NVIDIA copyright headerPer repository guidelines, prepend the current-year NVIDIA header.
Apply this diff at the top of the file:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.tensorrt_llm/llmapi/llm.py (1)
1-1: Add NVIDIA copyright headerPer repository guidelines, prepend the current-year NVIDIA header.
Apply this diff at the top of the file:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.tensorrt_llm/executor/worker.py (7)
105-146: Backend-dispatch in _create_py_executor is clear; add a GPU-availability guardWhen computing
device_id = self.global_rank % torch.cuda.device_count(), add a guard fordevice_count == 0to emit a clearer error. Also, when backend is "pytorch", consider validatinghf_model_direxists to fail fast.Apply this diff:
- device_id = self.global_rank % torch.cuda.device_count() + dev_cnt = torch.cuda.device_count() + if dev_cnt == 0: + raise RuntimeError("CUDA device not available; PyTorch backend requires GPU.") + device_id = self.global_rank % dev_cntAnd optionally:
- args["checkpoint_dir"] = hf_model_dir + if hf_model_dir is None: + logger.warning("hf_model_dir is None; relying on checkpoint loader to locate weights.") + args["checkpoint_dir"] = hf_model_dir
148-168: Fallback TRT engine path: ensure non-None executor_config or construct a safe defaultConstructing
tllm.ExecutorConfig(1)is a bit magical. If this code path can be hit by users, consider documenting why1is used or copying minimal fields from engine config to avoid surprising defaults.Proposed improvement:
- Read
max_batch_size,max_seq_lenfromEngineConfigwhen available and set them on the defaultExecutorConfig.
463-473: Overlap + disaggregated context-only rejection: good guard; improve errorThe error explains the limitation well. Add a hint how to proceed (disable overlap or use context+generation).
Apply this diff:
- raise ValueError( - "Context only requests are not supported in pytorch backend when overlap is enabled." - ) + raise ValueError( + "Context-only requests are not supported in the PyTorch backend when overlap is enabled. " + "Either disable overlap (llm_args.disable_overlap_scheduler=True) or submit a generation request." + )
476-515: Max tokens deduction: minor robustness and naming
- Prefer
getattr(llm_args, "max_seq_len", None)overhasattrchecks.- Typo:
splited_prompt_len→split_prompt_len.Apply this diff:
- if llm_args is not None: + if llm_args is not None: # deduce max_tokens by llm args - assert executor_config is None, "An empty executor_config in _deduce_max_tokens is expected when LLM arguments are defined." - if hasattr(self, - "mapping") and self.mapping.cp_size is not None: + assert executor_config is None, "executor_config must be None when LLM arguments are defined." + if getattr(self, "mapping", None) is not None and self.mapping.cp_size is not None: cp_size = self.mapping.cp_size - if not hasattr(llm_args, "max_seq_len"): + max_seq_len = getattr(llm_args, "max_seq_len", None) + if max_seq_len is None: raise RuntimeError( "max_tokens for sampling is not set and cannot be deduced by llm args" ) - max_seq_len = llm_args.max_seq_len else: # deduce max_tokens by executor config if hasattr(executor_config, "mapping" ) and executor_config.mapping.cp_size is not None: cp_size = executor_config.mapping.cp_size if not hasattr(executor_config, "max_seq_len"): raise RuntimeError( "max_tokens for sampling is not set and cannot be deduced" ) max_seq_len = executor_config.max_seq_len - splited_prompt_len = int(len(prompt_token_ids) / cp_size) - default_max_tokens = max_seq_len - splited_prompt_len - query_token_len + split_prompt_len = int(len(prompt_token_ids) / cp_size) + default_max_tokens = max_seq_len - split_prompt_len - query_token_len if default_max_tokens < 0: raise ValueError( f"Deduced max_tokens {default_max_tokens} is less than 0, because" - f"prompt length {splited_prompt_len} plus query length {query_token_len} " + f"prompt length {split_prompt_len} plus query length {query_token_len} " f"is larger than max_seq_len {max_seq_len}")
488-488: Line length exceeds configured limit (Ruff E501)This line exceeds 120 chars. Wrap or split for readability and to satisfy linters.
648-648: Line length exceeds configured limit (Ruff E501)This line exceeds 120 chars. Wrap or split for readability and to satisfy linters.
1-1: Add NVIDIA copyright headerPer repository guidelines, prepend the current-year NVIDIA header.
Apply this diff at the top of the file:
+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
📜 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 (10)
tensorrt_llm/_torch/auto_deploy/shim/ad_executor.py(2 hunks)tensorrt_llm/_torch/pyexecutor/py_executor_creator.py(2 hunks)tensorrt_llm/executor/executor.py(7 hunks)tensorrt_llm/executor/proxy.py(1 hunks)tensorrt_llm/executor/worker.py(8 hunks)tensorrt_llm/llmapi/llm.py(3 hunks)tensorrt_llm/llmapi/llm_args.py(5 hunks)tensorrt_llm/llmapi/mm_encoder.py(2 hunks)tests/unittest/api_stability/references/llm.yaml(1 hunks)tests/unittest/llmapi/test_llm_args.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else
Files:
tensorrt_llm/_torch/auto_deploy/shim/ad_executor.pytensorrt_llm/executor/proxy.pytensorrt_llm/llmapi/mm_encoder.pytests/unittest/llmapi/test_llm_args.pytensorrt_llm/_torch/pyexecutor/py_executor_creator.pytensorrt_llm/llmapi/llm_args.pytensorrt_llm/executor/executor.pytensorrt_llm/executor/worker.pytensorrt_llm/llmapi/llm.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend NVIDIA copyright header (current year) to all source files
Files:
tensorrt_llm/_torch/auto_deploy/shim/ad_executor.pytensorrt_llm/executor/proxy.pytensorrt_llm/llmapi/mm_encoder.pytests/unittest/llmapi/test_llm_args.pytensorrt_llm/_torch/pyexecutor/py_executor_creator.pytensorrt_llm/llmapi/llm_args.pytensorrt_llm/executor/executor.pytensorrt_llm/executor/worker.pytensorrt_llm/llmapi/llm.py
🧠 Learnings (1)
📚 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/llmapi/mm_encoder.pytensorrt_llm/llmapi/llm.py
🧬 Code graph analysis (7)
tensorrt_llm/_torch/auto_deploy/shim/ad_executor.py (1)
tensorrt_llm/_torch/auto_deploy/llm_args.py (1)
LlmArgs(226-340)
tensorrt_llm/llmapi/mm_encoder.py (4)
tensorrt_llm/llmapi/llm_args.py (4)
TorchLlmArgs(2122-2536)parallel_config(1356-1357)world_size(248-260)world_size(269-276)tensorrt_llm/executor/executor.py (1)
create(347-442)tensorrt_llm/llmapi/mpi_session.py (1)
external_mpi_comm_available(57-66)tensorrt_llm/llmapi/llm.py (2)
tokenizer(691-695)tokenizer(698-699)
tests/unittest/llmapi/test_llm_args.py (2)
tensorrt_llm/llmapi/llm_args.py (2)
get_executor_config(1840-1913)get_executor_config(2461-2468)tensorrt_llm/llmapi/llm.py (2)
tokenizer(691-695)tokenizer(698-699)
tensorrt_llm/llmapi/llm_args.py (2)
tensorrt_llm/llmapi/tokenizer.py (4)
TokenizerBase(24-25)_llguidance_tokenizer_info(329-333)_xgrammar_tokenizer_info(293-326)tokenizer_factory(270-290)tensorrt_llm/_torch/pyexecutor/config.py (1)
update_executor_config(129-172)
tensorrt_llm/executor/executor.py (3)
tensorrt_llm/llmapi/llm_args.py (1)
BaseLlmArgs(1136-1913)tensorrt_llm/llmapi/llm.py (2)
tokenizer(691-695)tokenizer(698-699)tensorrt_llm/llmapi/tokenizer.py (1)
TokenizerBase(24-25)
tensorrt_llm/executor/worker.py (7)
tensorrt_llm/llmapi/llm_args.py (7)
BaseLlmArgs(1136-1913)PybindMirror(579-723)TorchLlmArgs(2122-2536)get_pytorch_backend_config(2471-2536)parallel_config(1356-1357)to_dict(334-340)to_dict(1385-1394)tensorrt_llm/llmapi/llm.py (2)
tokenizer(691-695)tokenizer(698-699)tensorrt_llm/llmapi/tokenizer.py (1)
TokenizerBase(24-25)tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)
create_py_executor(210-491)tensorrt_llm/_torch/auto_deploy/llm_args.py (1)
LlmArgs(226-340)tensorrt_llm/_torch/auto_deploy/shim/ad_executor.py (1)
create_autodeploy_executor(261-344)tensorrt_llm/_torch/pyexecutor/config.py (1)
_construct_checkpoint_loader(175-197)
tensorrt_llm/llmapi/llm.py (2)
tensorrt_llm/_torch/auto_deploy/models/factory.py (1)
tokenizer(48-50)tensorrt_llm/llmapi/tokenizer.py (2)
TokenizerBase(24-25)_xgrammar_tokenizer_info(293-326)
🪛 Ruff (0.12.2)
tensorrt_llm/executor/worker.py
488-488: Line too long (140 > 120)
(E501)
648-648: Line too long (136 > 120)
(E501)
⏰ 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 (12)
tensorrt_llm/llmapi/llm_args.py (2)
47-49: Guided decoding imports look correct and scoped; LGTM.The imports for GuidedDecodingConfig and tokenizer helpers are consistent with their usage in get_executor_config.
Also applies to: 60-62
2263-2269: mm_encoder_only field wiring is correct and matches API reference.The field name, type, default, and prototype status align with the API YAML and downstream usage in mm_encoder and executor config.
tensorrt_llm/llmapi/mm_encoder.py (2)
58-60: Explicitly marking Torch args and enabling encoder-only mode: LGTM.The isinstance check and setting mm_encoder_only=True makes the intent clear and aligns with the new API.
61-72: ExecutorConfig None is safely handled via llm_args pathGenerationExecutorWorker’s constructor ignores the passed-in
executor_configwhenllm_argsis provided and instead calls its internal_create_py_executor, which builds the PyTorch executor (and itsExecutorConfig) entirely fromllm_args. This covers the MM encoder case:
- In
tensorrt_llm/executor/worker.py(lines 65–73), the__init__sets
self.engine = _create_py_executor() if self.llm_args is not None else _create_engine(executor_config),
ensuringexecutor_config=Noneis never used whenllm_argsis present._create_py_executorpopulates all required configuration (checkpoint directory, tokenizer, parallel settings, post-processor config, etc.) fromllm_argsbefore instantiating the executor.No changes needed.
tensorrt_llm/executor/proxy.py (1)
96-96: Ensureis_llm_executoroverride is intentionalForcing
is_llm_executor=Falsein the proxy will always disable LLM-executor logic in the worker—regardless of what was passed into the proxy’s constructor. This impacts behaviors such as:
- Queue selection in
tensorrt_llm/executor/worker.py:298–300(choosing betweenresult_singleton.queuevs.it_result_queue.queue) and the subsequent result-enqueue loop underself._is_llm_executor- Conditional result-putting logic in
tensorrt_llm/executor/worker.py:302–305whenself._is_llm_executorisTrue- Initialization of iteration statistics in
tensorrt_llm/executor/executor.py:233–236, which only runs when_is_llm_executorisTruePlease verify that the override at
tensorrt_llm/executor/proxy.py:96- is_llm_executor=is_llm_executor, + is_llm_executor=Falseis intended for both MM-encoder and general LLM paths. If not, consider propagating the original
is_llm_executorflag or adjusting worker logic accordingly.tensorrt_llm/_torch/auto_deploy/shim/ad_executor.py (1)
321-328: Confirm LlmArgs exposes enable_mixed_sampler
TorchSampler.Args(..., enable_mixed_sampler=ad_config.enable_mixed_sampler)assumesenable_mixed_samplerexists on AutoDeploy LlmArgs. Verify the field is present (with a default) or guard access; otherwise this will raiseAttributeError.If needed, gate it:
- sampler_args = TorchSampler.Args( + sampler_args = TorchSampler.Args( max_seq_len=ad_config.max_seq_len, max_draft_len=max_draft_len, max_num_sequences=max_num_sequences, max_beam_width=ad_config.max_beam_width, - enable_mixed_sampler=ad_config.enable_mixed_sampler, + enable_mixed_sampler=getattr(ad_config, "enable_mixed_sampler", False), )tensorrt_llm/executor/executor.py (1)
384-391: Forward llm_args/hf_model_dir/tokenizer into worker kwargs looks correctThe wiring aligns with the new llm_args-driven flow; downstream Worker/Proxy must accept these keys. LGTM pending integration test.
Please run API-stability/unit tests that exercise both:
- PyTorch backend path (llm_args.backend == "pytorch")
- TensorRT backend path (llm_args is None, executor_config provided)
to ensureGenerationExecutorProxyandGenerationExecutorWorkerconstructors accept the new kwargs.tensorrt_llm/llmapi/llm.py (2)
969-989: Switch to llm_args-driven executor creation for torch backendPassing
executor_config=Noneand threadinghf_model_dir,tokenizer, andllm_argsintoGenerationExecutor.create()is consistent with the new design. Ensure worker/proxy paths are updated to consume these parameters; otherwise torch backend will fail at runtime.
- Verify that
GenerationExecutorWorker.__init__andworker_main()accept and propagatehf_model_dir,tokenizer, andllm_args(they do in this PR).- Run a smoke test: small HF model on PyTorch backend with and without LoRA to exercise tokenizer and checkpoint loading.
40-41: TokenizerBase import retained for protocol consistencyKeeping
TokenizerBasein the public docstrings and types is good; it also aligns with_xgrammar_tokenizer_info. No action needed.tensorrt_llm/executor/worker.py (3)
96-105: Good: derive device_id from global rank and broadcast ranks/device_idsThis fixes common multi-node device selection pitfalls and ensures
ParallelConfighas consistent participant and device ids. Nice.
631-660: Cleanup checkpoint loaders on shutdown: good; handle both pathsNice attention to resource cleanup for both llm_args and legacy executor_config paths. LGTM.
193-205: LoRA manager hookup for PyTorch backend looks correctIntegrating
PEFT_CACHE_MANAGERand readinglora_model_configfrom the model engine is the right flow. LGTM.
|
PR_Github #16407 [ run ] triggered by Bot |
|
PR_Github #16407 [ run ] completed with state |
Signed-off-by: leslie-fang25 <[email protected]>
|
/bot run |
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: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
tensorrt_llm/executor/worker.py (1)
156-176: TRT path sets executor_config.parallel_config but deduce path still reads mapping.cp_sizeIn the TRT path you now populate executor_config.parallel_config; however, _deduce_max_tokens() still reads executor_config.mapping.cp_size. This can silently fall back to cp_size=1 and under-estimate prompt splitting, producing an overly large default max_tokens.
- if hasattr(executor_config, "mapping" - ) and executor_config.mapping.cp_size is not None: - cp_size = executor_config.mapping.cp_size + # Prefer parallel_config; fall back to legacy mapping for compatibility. + if hasattr(executor_config, "parallel_config") and getattr(executor_config.parallel_config, "cp_size", None): + cp_size = executor_config.parallel_config.cp_size + elif hasattr(executor_config, "mapping") and getattr(executor_config.mapping, "cp_size", None): + cp_size = executor_config.mapping.cp_sizetensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)
247-247: Fix logger.info call: use formatting or f-string instead of extra argPassing an extra positional arg without a %s placeholder can throw during logging formatting. Use a placeholder or f-string.
- logger.info("ATTENTION RUNTIME FEATURES: ", attn_runtime_features) + logger.info("ATTENTION RUNTIME FEATURES: %s", attn_runtime_features) + # or + # logger.info(f"ATTENTION RUNTIME FEATURES: {attn_runtime_features}")
🧹 Nitpick comments (7)
tensorrt_llm/executor/worker.py (5)
96-104: Guard device selection for environments with zero CUDA devicesDirectly indexing modulo torch.cuda.device_count() will raise on systems (or CI) without CUDA or with CUDA not initialized. Add a quick guard to fail fast with a clear error or to skip device set in unsupported environments.
def _get_comm_ranks_device_id(): - device_id = self.global_rank % torch.cuda.device_count() - torch.cuda.set_device(device_id) + if not torch.cuda.is_available() or torch.cuda.device_count() == 0: + raise RuntimeError("CUDA is not available; GenerationExecutorWorker requires at least one CUDA device.") + device_id = self.global_rank % torch.cuda.device_count() + torch.cuda.set_device(device_id)
471-481: Context-only requests with overlap scheduler on PyTorch backend — clarify error and testThe restriction looks correct. Please tighten the error to include which flag caused it and add a targeted unit/integration test to prevent regressions.
- raise ValueError( - "Context only requests are not supported in pytorch backend when overlap is enabled." - ) + raise ValueError( + "Context-only requests are not supported on the PyTorch backend when disable_overlap_scheduler=False " + "(overlap scheduler enabled) and disaggregated serving is active (kv_cache_transceiver configured)." + )I can add a minimal test that enqueues a context-only request under these conditions and asserts the ValueError.
496-496: Wrap long assertion message (Ruff E501)This line exceeds the 120-char limit. Wrap it across lines with parentheses.
- assert executor_config is None, "An empty executor_config in _deduce_max_tokens is expected when LLM arguments are defined." + assert executor_config is None, ( + "An empty executor_config in _deduce_max_tokens is expected " + "when LLM arguments are defined." + )
655-662: Wrap long assertion message in shutdown (Ruff E501)Also exceeds 120 chars.
- assert self._executor_config is None, "An empty executor_config is expected in shutdown when LLM arguments are defined." + assert self._executor_config is None, ( + "An empty executor_config is expected in shutdown " + "when LLM arguments are defined." + )
64-67: Constructor parameters hf_model_dir/tokenizer/llm_args are wired correctly
- We ran ripgrep over all call sites and found no remaining invocations that pass both
executor_configandllm_args(avoiding “double-driving”) and no legacy calls still usingcheckpoint_dirin place ofhf_model_dir.worker_main’s signature now includes the new parameters:and these are forwarded intohf_model_dir: Optional[Path] = None, tokenizer: Optional[TokenizerBase] = None, llm_args: Optional[BaseLlmArgs] = None,GenerationExecutorWorkerexactly as intended.- Inside
GenerationExecutorWorker, the llm_args-driven branch callscreate_py_executorwithconfirming that the new parameters flow into the PyExecutor path.args["llm_args"] = self.llm_args args["checkpoint_dir"] = hf_model_dir args["tokenizer"] = tokenizerOptional refactoring: standardize checkpoint_dir types
- In
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py, update the signatureso that passing a- def create_py_executor( - llm_args: TorchLlmArgs, - checkpoint_dir: str = None, + def create_py_executor( + llm_args: TorchLlmArgs, + checkpoint_dir: Union[str, Path] = None, tokenizer: Optional[TokenizerBase] = None, lora_config: Optional[LoraConfig] = None, ) -> PyExecutor:Pathdoesn’t rely on implicit conversion.- Likewise, adjust any
get_executor_config(checkpoint_dir, ...)definitions on yourTorchLlmArgs/TrtLlmArgsclasses to acceptUnion[str, Path].tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (2)
13-20: Duplicate import of is_mla; remove one to avoid shadowingis_mla is imported from both ._util and .config_utils. Keep one canonical import to prevent confusion.
-from ._util import (KvCacheCreator, _adjust_torch_mem_fraction, - create_py_executor_instance, instantiate_sampler, is_mla) +from ._util import (KvCacheCreator, _adjust_torch_mem_fraction, + create_py_executor_instance, instantiate_sampler) from .config import LoadFormat, PyTorchConfig -from .config_utils import is_mla +from .config_utils import is_mlaAlso applies to: 31-33
210-218: API signature: broaden checkpoint_dir typing to Path | strDownstream users (e.g., worker) pass a Path. The implementation forwards it to model_engine; accept Union[str, Path] to match usage and reduce mypy noise.
-from typing import Optional +from typing import Optional, Union @@ -def create_py_executor( - llm_args: TorchLlmArgs, - checkpoint_dir: str = None, +def create_py_executor( + llm_args: TorchLlmArgs, + checkpoint_dir: Optional[Union[str, "Path"]] = None,(If you prefer not to import Path here, accept Any or str | os.PathLike.)
📜 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 (2)
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py(4 hunks)tensorrt_llm/executor/worker.py(9 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
tensorrt_llm/executor/worker.py (6)
tensorrt_llm/llmapi/llm_args.py (5)
BaseLlmArgs(1136-1913)TorchLlmArgs(2122-2536)get_pytorch_backend_config(2471-2536)parallel_config(1356-1357)to_mapping(282-294)tensorrt_llm/llmapi/tokenizer.py (1)
TokenizerBase(24-25)tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)
create_py_executor(210-497)tensorrt_llm/auto_parallel/parallelization.py (1)
ParallelConfig(51-77)tensorrt_llm/_torch/auto_deploy/shim/ad_executor.py (1)
create_autodeploy_executor(261-344)tensorrt_llm/_torch/pyexecutor/config.py (1)
_construct_checkpoint_loader(175-197)
🪛 Ruff (0.12.2)
tensorrt_llm/executor/worker.py
496-496: Line too long (140 > 120)
(E501)
656-656: Line too long (136 > 120)
(E501)
⏰ 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 (4)
tensorrt_llm/executor/worker.py (2)
524-562: Pass-through of computed max_tokens looks goodThe request construction correctly uses the deduced max_tokens and adapts logits post-processor handling per-backend. No issues spotted here.
833-843: Confirm forwarding of hf_model_dir, tokenizer, and llm_args across executor entry pointsI ran a regex search for
create_py_executor(andworker_main(and only located their definitions; no other literal invocation sites were found. Please manually verify that:
- The
create_py_executorAPI (defined in_torch/pyexecutor/py_executor_creator.pyat lines ~210–213) is actually called by any higher-level code and that those call sites pass through the newllm_argsandtokenizerparameters.- The
worker_mainentry point (inexecutor/worker.pyat lines 697–699) is invoked by all IPC or CLI layers, and that they forwardhf_model_dir,tokenizer, andllm_argsthrough to theGenerationExecutorWorkerconstructor.Without concrete call sites, the absence of evidence isn’t evidence of absence—please double-check the dynamic or indirect invocation paths in your codebase.
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (2)
220-223: Executor config assembly from llm_args — LGTMCreating executor_config via llm_args.get_executor_config and wiring in logits and parallel_config centralizes config nicely.
312-315: Propagating updated max_seq_len back to kwargs — LGTMUpdating kwargs_py_executor["max_seq_len"] when model adjusts it is correct and matches how the worker reads it afterwards.
|
PR_Github #16438 [ run ] triggered by Bot |
Signed-off-by: leslie-fang25 <[email protected]>
|
/bot run |
|
PR_Github #16440 [ run ] triggered by Bot |
|
PR_Github #16438 [ run ] completed with state |
|
PR_Github #16440 [ run ] completed with state |
|
/bot run |
|
PR_Github #16487 [ run ] triggered by Bot |
|
PR_Github #16487 [ run ] completed with state |
Summary by CodeRabbit
New Features
Breaking Changes
Tests/Documentation
Description
Test Coverage
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.
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.