Skip to content

Conversation

@leslie-fang25
Copy link
Collaborator

@leslie-fang25 leslie-fang25 commented Aug 25, 2025

Summary by CodeRabbit

  • New Features

    • Unified llm_args-based configuration: pass model directory and tokenizer directly; new mm_encoder_only option for encoder-only multimodal use.
    • Wider runtime configurability via dedicated LLM args (logits post-processing, parallel settings, guided-decoding backends).
  • Breaking Changes

    • Executor/worker creation APIs now accept llm_args; garbage_collection_gen0_threshold removed and several signatures changed.
    • Some guided-decoding/tokenizer wiring moved into llm_args-driven flow; return_logits is no longer forwarded to executor creation.
  • Tests/Documentation

    • Public API reference and tests updated to use llm_args.get_executor_config and reflect mm_encoder_only.

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 the stage-list parameter 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.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip 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-pipeline

Reuse 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.

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]>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 25, 2025

📝 Walkthrough

Walkthrough

Refactors executor configuration to be driven by llm_args across the codebase. Public APIs now pass llm_args, tokenizer, and hf_model_dir into executor creation; garbage_collection_gen0_threshold and checkpoint_dir parameters are removed from public signatures. Adds BaseLlmArgs.get_executor_config and TorchLlmArgs.mm_encoder_only.

Changes

Cohort / File(s) Summary
Core executor/proxy/worker refactor
tensorrt_llm/executor/executor.py, tensorrt_llm/executor/proxy.py, tensorrt_llm/executor/worker.py
Thread hf_model_dir, tokenizer, and llm_args through create → proxy → worker; remove garbage_collection_gen0_threshold API parameter; proxy derives GC threshold from llm_args; worker now selects backend via llm_args, supports PyTorch and autodeploy creation paths, adds rank/device helpers, refactors executor/engine creation, updates LoRA/resource handling, max_tokens deduction, and shutdown/cleanup logic.
Config plumbing via llm_args
tensorrt_llm/llmapi/llm_args.py, tensorrt_llm/_torch/pyexecutor/py_executor_creator.py, tensorrt_llm/_torch/auto_deploy/shim/ad_executor.py
Add BaseLlmArgs.get_executor_config(...) to construct _ExecutorConfig; thread KV/PEFT/guided-decoding, deterministic KV, chunked context, beam, parallel/speculative, and checkpoint settings into executor config; add TorchLlmArgs.mm_encoder_only; change create_py_executor signature to accept TorchLlmArgs (and tokenizer/logits/parallel configs); change autodeploy shim to accept LlmArgs directly and remove checkpoint_dir parameter.
LLM API runtime changes
tensorrt_llm/llmapi/llm.py, tensorrt_llm/llmapi/mm_encoder.py
Remove manual construction of internal ExecutorConfig; create executor with executor_config=None and pass hf_model_dir, tokenizer, and llm_args; set mm_encoder_only for multimodal encoder path; remove guided-decoding assembly wiring from TRT path; update Torch path similarly.
Tests and API references
tests/unittest/llmapi/test_llm_args.py, tests/unittest/api_stability/references/llm.yaml
Tests updated to call llm.args.get_executor_config(...) instead of inspecting private executor state; API reference adds mm_encoder_only: bool parameter to LLM.__init__.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • Superjomn
  • shaharmor98
  • pcastonguay
  • litaotju
  • nv-guomingz

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 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 620f139 and 1f2f762.

📒 Files selected for processing (1)
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
⏰ 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
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@leslie-fang25
Copy link
Collaborator Author

/bot run

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 %s placeholder. 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 setups

Setting torch.cuda.set_device(rank) assumes rank < device_count on 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_prefill

Optional follow-up (API polish): consider renaming parameter _hf_model_dir to hf_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_config
tests/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 True
tensorrt_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 check

The assertion message mentions pytorch_backend_config, but the parameter is ad_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 seed

Hardcoding torch.manual_seed(1234) makes results deterministic but can be surprising in production. Consider making this configurable on ad_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] = None to LlmArgs if not already present.


1-1: Add NVIDIA copyright header

Per 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_mla is 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 API

Add a concise docstring to clarify behavior and parameters, especially the relation between llm_args and derived executor_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_dir often comes as a Path. 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

LoadFormat is already imported from .config. Re-importing with the same name from llm_args is 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_ONLY

If 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 header

Per 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 parameters

The public factory signature now includes hf_model_dir, tokenizer, and llm_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 header

Per 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 header

Per 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 guard

When computing device_id = self.global_rank % torch.cuda.device_count(), add a guard for device_count == 0 to emit a clearer error. Also, when backend is "pytorch", consider validating hf_model_dir exists 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_cnt

And 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 default

Constructing tllm.ExecutorConfig(1) is a bit magical. If this code path can be hit by users, consider documenting why 1 is used or copying minimal fields from engine config to avoid surprising defaults.

Proposed improvement:

  • Read max_batch_size, max_seq_len from EngineConfig when available and set them on the default ExecutorConfig.

463-473: Overlap + disaggregated context-only rejection: good guard; improve error

The 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) over hasattr checks.
  • Typo: splited_prompt_lensplit_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 header

Per 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.

📥 Commits

Reviewing files that changed from the base of the PR and between be6d92f and 7968543.

📒 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.py
  • tensorrt_llm/executor/proxy.py
  • tensorrt_llm/llmapi/mm_encoder.py
  • tests/unittest/llmapi/test_llm_args.py
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
  • tensorrt_llm/llmapi/llm_args.py
  • tensorrt_llm/executor/executor.py
  • tensorrt_llm/executor/worker.py
  • tensorrt_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.py
  • tensorrt_llm/executor/proxy.py
  • tensorrt_llm/llmapi/mm_encoder.py
  • tests/unittest/llmapi/test_llm_args.py
  • tensorrt_llm/_torch/pyexecutor/py_executor_creator.py
  • tensorrt_llm/llmapi/llm_args.py
  • tensorrt_llm/executor/executor.py
  • tensorrt_llm/executor/worker.py
  • tensorrt_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.py
  • tensorrt_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 path

GenerationExecutorWorker’s constructor ignores the passed-in executor_config when llm_args is provided and instead calls its internal _create_py_executor, which builds the PyTorch executor (and its ExecutorConfig) entirely from llm_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),
    ensuring executor_config=None is never used when llm_args is present.
  • _create_py_executor populates all required configuration (checkpoint directory, tokenizer, parallel settings, post-processor config, etc.) from llm_args before instantiating the executor.

No changes needed.

tensorrt_llm/executor/proxy.py (1)

96-96: Ensure is_llm_executor override is intentional

Forcing is_llm_executor=False in 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:298300 (choosing between result_singleton.queue vs. it_result_queue.queue) and the subsequent result-enqueue loop under self._is_llm_executor
  • Conditional result-putting logic in tensorrt_llm/executor/worker.py:302305 when self._is_llm_executor is True
  • Initialization of iteration statistics in tensorrt_llm/executor/executor.py:233236, which only runs when _is_llm_executor is True

Please verify that the override at tensorrt_llm/executor/proxy.py:96

-    is_llm_executor=is_llm_executor,
+    is_llm_executor=False

is intended for both MM-encoder and general LLM paths. If not, consider propagating the original is_llm_executor flag 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) assumes enable_mixed_sampler exists on AutoDeploy LlmArgs. Verify the field is present (with a default) or guard access; otherwise this will raise AttributeError.

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 correct

The 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 ensure GenerationExecutorProxy and GenerationExecutorWorker constructors accept the new kwargs.
tensorrt_llm/llmapi/llm.py (2)

969-989: Switch to llm_args-driven executor creation for torch backend

Passing executor_config=None and threading hf_model_dir, tokenizer, and llm_args into GenerationExecutor.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__ and worker_main() accept and propagate hf_model_dir, tokenizer, and llm_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 consistency

Keeping TokenizerBase in 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_ids

This fixes common multi-node device selection pitfalls and ensures ParallelConfig has consistent participant and device ids. Nice.


631-660: Cleanup checkpoint loaders on shutdown: good; handle both paths

Nice attention to resource cleanup for both llm_args and legacy executor_config paths. LGTM.


193-205: LoRA manager hookup for PyTorch backend looks correct

Integrating PEFT_CACHE_MANAGER and reading lora_model_config from the model engine is the right flow. LGTM.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16407 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16407 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12332 completed with status: 'FAILURE'

@leslie-fang25
Copy link
Collaborator Author

/bot run

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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_size

In 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_size
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (1)

247-247: Fix logger.info call: use formatting or f-string instead of extra arg

Passing 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 devices

Directly 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 test

The 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_config and llm_args (avoiding “double-driving”) and no legacy calls still using checkpoint_dir in place of hf_model_dir.
  • worker_main’s signature now includes the new parameters:
    hf_model_dir: Optional[Path] = None,
    tokenizer: Optional[TokenizerBase] = None,
    llm_args: Optional[BaseLlmArgs] = None,
    and these are forwarded into GenerationExecutorWorker exactly as intended.
  • Inside GenerationExecutorWorker, the llm_args-driven branch calls create_py_executor with
    args["llm_args"]       = self.llm_args
    args["checkpoint_dir"] = hf_model_dir
    args["tokenizer"]      = tokenizer
    confirming that the new parameters flow into the PyExecutor path.

Optional refactoring: standardize checkpoint_dir types

  • In tensorrt_llm/_torch/pyexecutor/py_executor_creator.py, update the signature
    - 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:
    so that passing a Path doesn’t rely on implicit conversion.
  • Likewise, adjust any get_executor_config(checkpoint_dir, ...) definitions on your TorchLlmArgs/TrtLlmArgs classes to accept Union[str, Path].
tensorrt_llm/_torch/pyexecutor/py_executor_creator.py (2)

13-20: Duplicate import of is_mla; remove one to avoid shadowing

is_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_mla

Also applies to: 31-33


210-218: API signature: broaden checkpoint_dir typing to Path | str

Downstream 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 7968543 and 620f139.

📒 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 good

The 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 points

I ran a regex search for create_py_executor( and worker_main( and only located their definitions; no other literal invocation sites were found. Please manually verify that:

  • The create_py_executor API (defined in _torch/pyexecutor/py_executor_creator.py at lines ~210–213) is actually called by any higher-level code and that those call sites pass through the new llm_args and tokenizer parameters.
  • The worker_main entry point (in executor/worker.py at lines 697–699) is invoked by all IPC or CLI layers, and that they forward hf_model_dir, tokenizer, and llm_args through to the GenerationExecutorWorker constructor.

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 — LGTM

Creating 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 — LGTM

Updating kwargs_py_executor["max_seq_len"] when model adjusts it is correct and matches how the worker reads it afterwards.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16438 [ run ] triggered by Bot

Signed-off-by: leslie-fang25 <[email protected]>
@leslie-fang25
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16440 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16438 [ run ] completed with state ABORTED

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16440 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12352 completed with status: 'FAILURE'

@leslie-fang25
Copy link
Collaborator Author

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16487 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16487 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #12383 completed with status: 'FAILURE'

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.

2 participants