Skip to content

Conversation

@ixlmar
Copy link
Collaborator

@ixlmar ixlmar commented Nov 18, 2025

Description

Adds --custom_module_dirs option (from trtllm-bench) to trtllm-serve.

Test Coverage

Refactored existing out-of-tree model tests to use pytest and updated them to cover trtllm-serve.

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • Update tava architecture diagram if there is a significant design change in PR.

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

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

Summary by CodeRabbit

  • New Features

    • Added --custom_module_dirs CLI option to the serve command to support importing custom Python modules from specified directories.
  • Documentation

    • Updated Serving documentation to reflect custom module directory import capabilities.
  • Improvements

    • Enhanced type annotations in the LLM API for improved type safety.

@ixlmar ixlmar force-pushed the feat/serve-out-of-tree branch from e477f07 to 7b0ac34 Compare November 18, 2025 16:09
@ixlmar
Copy link
Collaborator Author

ixlmar commented Nov 18, 2025

/bot run

@ixlmar ixlmar marked this pull request as ready for review November 18, 2025 16:10
@ixlmar ixlmar requested review from a team as code owners November 18, 2025 16:10
@ixlmar ixlmar requested a review from Shixiaowei02 November 18, 2025 16:10
@tensorrt-cicd
Copy link
Collaborator

PR_Github #24926 [ run ] triggered by Bot. Commit: 7b0ac34

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 18, 2025

📝 Walkthrough

Walkthrough

This pull request adds support for importing custom Python modules from user-specified directories in the serve command via a new --custom_module_dirs CLI option. Updates include serving documentation, refactored pytest-based tests with fixture parameterization, and corrected type annotations in the LLM API context manager.

Changes

Cohort / File(s) Summary
Out-of-tree example updates
examples/llm-api/out_of_tree_example/__init__.py, examples/llm-api/out_of_tree_example/readme.md
Added public re-export of modeling_opt submodule in package initializer; extended documentation to indicate serve command supports --custom_module_dirs option
Serve command enhancement
tensorrt_llm/commands/serve.py
Added --custom_module_dirs CLI option (Path type, multiple=True) and runtime custom module loading logic via import_custom_module_from_dir for each provided directory
LLM API type annotation
tensorrt_llm/llmapi/llm.py
Updated __exit__ method signature to return Literal[False] with multiline formatting and Pyright issue reference comment; runtime behavior unchanged
Test migration and expansion
tests/unittest/_torch/modeling/test_modeling_out_of_tree.py
Migrated from unittest class-based to pytest-style fixtures and parameterization; introduced conditional custom module import via monkeypatch; added new serve path test using RemoteOpenAIServer; refactored assertions to pytest patterns

Sequence Diagram(s)

sequenceDiagram
    participant CLI as Serve CLI
    participant Serve as serve()
    participant ImportUtil as import_custom_module_from_dir
    participant Module as Custom Module
    
    CLI->>Serve: --custom_module_dirs=[path1, path2, ...]
    activate Serve
    Serve->>Serve: Iterate over custom_module_dirs
    loop Each directory
        Serve->>ImportUtil: import_custom_module_from_dir(dir)
        activate ImportUtil
        ImportUtil->>Module: Dynamic module import
        alt Success
            Module-->>ImportUtil: Module loaded
            ImportUtil-->>Serve: Import complete
        else Failure
            ImportUtil-->>Serve: RuntimeError + log
            Serve->>Serve: Re-raise exception
        end
        deactivate ImportUtil
    end
    Serve->>Serve: Initialize server with loaded modules
    deactivate Serve
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • tensorrt_llm/commands/serve.py: Verify custom module import logic handles errors correctly and integrates properly with the CLI option plumbing
  • tests/unittest/_torch/modeling/test_modeling_out_of_tree.py: Review fixture setup, conditional import monkeypatch mechanics, and parallel test paths (LLM API vs. serve) for correctness
  • tensorrt_llm/llmapi/llm.py: Confirm Literal[False] type annotation is semantically correct and Pyright-compliant
  • Import chain: Validate Path and import_custom_module_from_dir imports are properly sourced

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding support for out-of-tree models to trtllm-serve, with appropriate ticket reference and feature type.
Description check ✅ Passed The description covers the key requirement: explaining what was added (--custom_module_dirs option) and test coverage (refactored to pytest for trtllm-serve). The PR checklist is completed.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

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: 0

🧹 Nitpick comments (4)
examples/llm-api/out_of_tree_example/readme.md (1)

52-55: Serving section is accurate; consider adding a concrete CLI example

The note correctly states that trtllm-serve supports --custom_module_dirs. To match the Quickstart/Benchmarking sections, you might add a short example command (e.g., trtllm-serve ... --custom_module_dirs ../modeling_custom_phi) so users can immediately see how to wire it into serving.

tests/unittest/_torch/modeling/test_modeling_out_of_tree.py (2)

68-104: Tighten side-effect import, regex pattern, and zip usage in test_llm_api

The overall test logic looks solid. A few small cleanups will make it more robust and lint-friendly:

  • For the side-effect-only import, avoid the blanket # noqa and rely on an explicit import call instead. For example:
+import importlib
@@
-            # Import out-of-tree modeling code for OPTForCausalLM
-            monkeypatch.syspath_prepend(oot_path)
-            import modeling_opt  # noqa
+            # Import out-of-tree modeling code for OPTForCausalLM
+            monkeypatch.syspath_prepend(oot_path)
+            importlib.import_module("modeling_opt")

This keeps the intent clear and removes the unused blanket noqa warning.

  • Make the regex pattern for match= a raw string to satisfy linters and emphasize that it’s a regex:
-              pytest.raises(RuntimeError,
-                            match=".*Executor worker returned error.*")) as ctx:
+              pytest.raises(RuntimeError,
+                            match=r".*Executor worker returned error.*")) as ctx:
@@
-            assert re.match(
-                ".*Unknown architecture for AutoModelForCausalLM: OPTForCausalLM.*",
-                str(exc_val.__cause__),
-            ) is not None
+            assert re.match(
+                r".*Unknown architecture for AutoModelForCausalLM: OPTForCausalLM.*",
+                str(exc_val.__cause__),
+            ) is not None
  • Add strict=True to the zip so the test fails early if outputs and references ever diverge in length:
-            for output, ref in zip(outputs, references):
+            for output, ref in zip(outputs, references, strict=True):
                 assert similar(output.outputs[0].text, ref)

Please re-run the test suite after these changes to confirm no behavioral differences and that your lint configuration is happy with the updated patterns.


105-134: Use zip(..., strict=True) in test_serve for safer assertions

For the serving path, you can mirror the stricter zip behavior from test_llm_api:

-            for choice, ref in zip(result.choices, references):
+            for choice, ref in zip(result.choices, references, strict=True):
                 assert similar(choice.text, ref)

This ensures the test will fail loudly if the number of returned choices ever diverges from the number of reference strings.

After updating, run the tests to ensure the environment’s Python version supports zip(strict=...) (Python ≥ 3.10) and everything passes.

tensorrt_llm/commands/serve.py (1)

249-258: Improve error re-raise behavior when importing custom modules

The --custom_module_dirs wiring and import loop are functionally correct and match the intended behavior. To improve debuggability:

  • When re-raising after logging, prefer a bare raise to preserve the original traceback instead of raise e:
-    for custom_module_dir in custom_module_dirs:
-        try:
-            import_custom_module_from_dir(custom_module_dir)
-        except Exception as e:
-            logger.error(
-                f"Failed to import custom module from {custom_module_dir}: {e}")
-            raise e
+    for custom_module_dir in custom_module_dirs:
+        try:
+            import_custom_module_from_dir(custom_module_dir)
+        except Exception as e:
+            logger.error(
+                f"Failed to import custom module from {custom_module_dir}: {e}")
+            raise

If you want full traceback information in logs as well, you could use logger.exception(...) instead of logger.error(...).

After this change, please exercise a failing --custom_module_dirs path to confirm that the logged error message and traceback still contain all the information you need for debugging.

Also applies to: 381-395

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 160b361 and 7b0ac34.

📒 Files selected for processing (5)
  • examples/llm-api/out_of_tree_example/__init__.py (1 hunks)
  • examples/llm-api/out_of_tree_example/readme.md (1 hunks)
  • tensorrt_llm/commands/serve.py (4 hunks)
  • tensorrt_llm/llmapi/llm.py (1 hunks)
  • tests/unittest/_torch/modeling/test_modeling_out_of_tree.py (1 hunks)
🧰 Additional context used
🧠 Learnings (7)
📚 Learning: 2025-08-21T00:16:56.457Z
Learnt from: farshadghodsian
Repo: NVIDIA/TensorRT-LLM PR: 7101
File: docs/source/blogs/tech_blog/blog9_Deploying_GPT_OSS_on_TRTLLM.md:36-36
Timestamp: 2025-08-21T00:16:56.457Z
Learning: TensorRT-LLM container release tags in documentation should only reference published NGC container images. The README badge version may be ahead of the actual published container versions.

Applied to files:

  • examples/llm-api/out_of_tree_example/readme.md
📚 Learning: 2025-08-01T15:14:45.673Z
Learnt from: yibinl-nvidia
Repo: NVIDIA/TensorRT-LLM PR: 6506
File: examples/models/core/mixtral/requirements.txt:3-3
Timestamp: 2025-08-01T15:14:45.673Z
Learning: In TensorRT-LLM, examples directory can have different dependency versions than the root requirements.txt file. Version conflicts between root and examples dependencies are acceptable because examples are designed to be standalone and self-contained.

Applied to files:

  • examples/llm-api/out_of_tree_example/readme.md
📚 Learning: 2025-07-28T17:06:08.621Z
Learnt from: moraxu
Repo: NVIDIA/TensorRT-LLM PR: 6303
File: tests/integration/test_lists/qa/examples_test_list.txt:494-494
Timestamp: 2025-07-28T17:06:08.621Z
Learning: In TensorRT-LLM testing, it's common to have both CLI flow tests (test_cli_flow.py) and PyTorch API tests (test_llm_api_pytorch.py) for the same model. These serve different purposes: CLI flow tests validate the traditional command-line workflow, while PyTorch API tests validate the newer LLM API backend. Both are legitimate and should coexist.

Applied to files:

  • examples/llm-api/out_of_tree_example/readme.md
  • tests/unittest/_torch/modeling/test_modeling_out_of_tree.py
📚 Learning: 2025-08-18T08:42:02.640Z
Learnt from: samuellees
Repo: NVIDIA/TensorRT-LLM PR: 6974
File: tensorrt_llm/serve/scripts/benchmark_dataset.py:558-566
Timestamp: 2025-08-18T08:42:02.640Z
Learning: In TensorRT-LLM's RandomDataset (tensorrt_llm/serve/scripts/benchmark_dataset.py), when using --random-token-ids option, sequence length accuracy is prioritized over semantic correctness for benchmarking purposes. The encode/decode operations should use skip_special_tokens=True and add_special_tokens=False to ensure exact target token lengths.

Applied to files:

  • examples/llm-api/out_of_tree_example/readme.md
📚 Learning: 2025-09-09T09:40:45.658Z
Learnt from: fredricz-20070104
Repo: NVIDIA/TensorRT-LLM PR: 7645
File: tests/integration/test_lists/qa/llm_function_core.txt:648-648
Timestamp: 2025-09-09T09:40:45.658Z
Learning: In TensorRT-LLM test lists, it's common and intentional for the same test to appear in multiple test list files when they serve different purposes (e.g., llm_function_core.txt for comprehensive core functionality testing and llm_function_core_sanity.txt for quick sanity checks). This duplication allows tests to be run in different testing contexts.

Applied to files:

  • examples/llm-api/out_of_tree_example/readme.md
📚 Learning: 2025-08-06T13:58:07.506Z
Learnt from: galagam
Repo: NVIDIA/TensorRT-LLM PR: 6487
File: tests/unittest/_torch/auto_deploy/unit/singlegpu/test_ad_trtllm_bench.py:1-12
Timestamp: 2025-08-06T13:58:07.506Z
Learning: In TensorRT-LLM, test files (files under tests/ directories) do not require NVIDIA copyright headers, unlike production source code files. Test files typically start directly with imports, docstrings, or code.

Applied to files:

  • examples/llm-api/out_of_tree_example/readme.md
📚 Learning: 2025-08-29T14:07:45.863Z
Learnt from: EmmaQiaoCh
Repo: NVIDIA/TensorRT-LLM PR: 7370
File: tests/unittest/trt/model_api/test_model_quantization.py:24-27
Timestamp: 2025-08-29T14:07:45.863Z
Learning: In TensorRT-LLM's CI infrastructure, pytest skip markers (pytest.mark.skip) are properly honored even when test files have __main__ blocks that call test functions directly. The testing system correctly skips tests without requiring modifications to the __main__ block execution pattern.

Applied to files:

  • tests/unittest/_torch/modeling/test_modeling_out_of_tree.py
🧬 Code graph analysis (2)
tensorrt_llm/commands/serve.py (2)
tensorrt_llm/tools/importlib_utils.py (1)
  • import_custom_module_from_dir (59-99)
tensorrt_llm/logger.py (1)
  • error (126-127)
tests/unittest/_torch/modeling/test_modeling_out_of_tree.py (2)
tensorrt_llm/llmapi/llm.py (3)
  • LLM (1104-1120)
  • generate (259-341)
  • prompt (86-87)
tests/unittest/llmapi/apps/openai_server.py (1)
  • get_client (110-114)
🪛 Ruff (0.14.5)
tensorrt_llm/commands/serve.py

395-395: Use raise without specifying exception name

Remove exception name

(TRY201)

tests/unittest/_torch/modeling/test_modeling_out_of_tree.py

83-83: Unused blanket noqa directive

Remove unused noqa directive

(RUF100)


87-87: Pattern passed to match= contains metacharacters but is neither escaped nor raw

(RUF043)


95-95: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)


133-133: zip() without an explicit strict= parameter

Add explicit value for parameter strict=

(B905)

⏰ 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 (2)
examples/llm-api/out_of_tree_example/__init__.py (1)

1-1: Re-export of modeling_opt looks good

Exposing modeling_opt at the package level aligns with how import_custom_module_from_dir imports the package and keeps the example easy to use from out_of_tree_example.

tensorrt_llm/llmapi/llm.py (1)

779-785: __exit__ typing / formatting change is safe

Annotating __exit__ as returning Literal[False] and reformatting the signature keeps the existing behavior (always propagating exceptions) while satisfying static type checking; no runtime behavior change here.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #24926 [ run ] completed with state SUCCESS. Commit: 7b0ac34
/LLM/main/L0_MergeRequest_PR pipeline #18826 completed with status: 'FAILURE'

@syuoni syuoni requested a review from LinPoly November 19, 2025 02:02
Copy link
Collaborator

@LinPoly LinPoly left a comment

Choose a reason for hiding this comment

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

LGTM

@ixlmar
Copy link
Collaborator Author

ixlmar commented Nov 19, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25003 [ run ] triggered by Bot. Commit: 7b0ac34

@ixlmar
Copy link
Collaborator Author

ixlmar commented Nov 19, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25012 [ run ] triggered by Bot. Commit: 7b0ac34

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25012 [ run ] completed with state FAILURE. Commit: 7b0ac34
/LLM/main/L0_MergeRequest_PR pipeline #18894 completed with status: 'FAILURE'

@ixlmar
Copy link
Collaborator Author

ixlmar commented Nov 19, 2025

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #25032 [ run ] triggered by Bot. Commit: 7b0ac34

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants