-
Notifications
You must be signed in to change notification settings - Fork 1.9k
[TRTLLM-9191][feat] support out-of-tree models in trtllm-serve #9269
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
base: main
Are you sure you want to change the base?
Conversation
Signed-off-by: ixlmar <[email protected]>
e477f07 to
7b0ac34
Compare
|
/bot run |
|
PR_Github #24926 [ run ] triggered by Bot. Commit: |
📝 WalkthroughWalkthroughThis pull request adds support for importing custom Python modules from user-specified directories in the serve command via a new Changes
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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.
Example instruction:
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. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 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 exampleThe note correctly states that
trtllm-servesupports--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 intest_llm_apiThe 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
# noqaand 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
noqawarning.
- 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=Trueto the zip so the test fails early ifoutputsandreferencesever 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: Usezip(..., strict=True)intest_servefor safer assertionsFor 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 modulesThe
--custom_module_dirswiring and import loop are functionally correct and match the intended behavior. To improve debuggability:
- When re-raising after logging, prefer a bare
raiseto preserve the original traceback instead ofraise 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}") + raiseIf you want full traceback information in logs as well, you could use
logger.exception(...)instead oflogger.error(...).After this change, please exercise a failing
--custom_module_dirspath 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
📒 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.mdtests/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 ofmodeling_optlooks goodExposing
modeling_optat the package level aligns with howimport_custom_module_from_dirimports the package and keeps the example easy to use fromout_of_tree_example.tensorrt_llm/llmapi/llm.py (1)
779-785:__exit__typing / formatting change is safeAnnotating
__exit__as returningLiteral[False]and reformatting the signature keeps the existing behavior (always propagating exceptions) while satisfying static type checking; no runtime behavior change here.
|
PR_Github #24926 [ run ] completed with state |
LinPoly
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM
|
/bot run --disable-fail-fast |
|
PR_Github #25003 [ run ] triggered by Bot. Commit: |
|
/bot run --disable-fail-fast |
|
PR_Github #25012 [ run ] triggered by Bot. Commit: |
|
PR_Github #25012 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #25032 [ run ] triggered by Bot. Commit: |
Description
Adds
--custom_module_dirsoption (fromtrtllm-bench) totrtllm-serve.Test Coverage
Refactored existing out-of-tree model tests to use
pytestand updated them to covertrtllm-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 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.
Summary by CodeRabbit
New Features
--custom_module_dirsCLI option to the serve command to support importing custom Python modules from specified directories.Documentation
Improvements