-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[#3325][feat] Add MCTS and TOT tree-based inference controllers to Scaffolding #7490
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
[#3325][feat] Add MCTS and TOT tree-based inference controllers to Scaffolding #7490
Conversation
|
cc @WeiHaocheng |
📝 WalkthroughWalkthroughAdds tree-based scaffolding to the LLM system: a new tree_controllers module implementing MCTSController and TOTController with supporting node classes; exposes these via scaffolding init; introduces two runnable examples (MCTS and TOT) wiring generation and reward workers; and adds documentation describing usage and parameters. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant User as User
participant Scaf as ScaffoldingLlm
participant MCTS as MCTSController
participant Gen as GenerationController
participant Rwd as PRMController
User->>Scaf: submit task(prompt)
Scaf->>MCTS: process(tasks)
rect rgba(200,230,255,0.3)
note right of MCTS: Selection/Expansion/Simulation/Backprop (iterate)
loop max_iterations
MCTS->>MCTS: select node (UCB1)
MCTS->>Gen: expand: generate thoughts
Gen-->>MCTS: candidate thoughts
alt reward enabled
MCTS->>Rwd: score thoughts
Rwd-->>MCTS: rewards
else
MCTS->>MCTS: heuristic score
end
MCTS->>MCTS: backpropagate rewards
end
end
MCTS->>Gen: final-answer prompt (best trajectory)
Gen-->>MCTS: final text
MCTS-->>Scaf: result
Scaf-->>User: output
sequenceDiagram
autonumber
participant User as User
participant Scaf as ScaffoldingLlm
participant TOT as TOTController
participant Gen as GenerationController
participant Rwd as PRMController
User->>Scaf: submit task(prompt)
Scaf->>TOT: process(tasks)
rect rgba(220,255,220,0.3)
note right of TOT: Level-wise thought expansion and pruning
loop depth = 1..max_depth
TOT->>Gen: generate thoughts per frontier node
Gen-->>TOT: thoughts
alt reward enabled
TOT->>Rwd: evaluate thoughts
Rwd-->>TOT: scores
else
TOT->>TOT: simple heuristic
end
TOT->>TOT: select/prune per strategy
end
end
TOT->>Gen: final-answer prompt (best path)
Gen-->>TOT: final text
TOT-->>Scaf: result
Scaf-->>User: output
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
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: 9
🧹 Nitpick comments (19)
tensorrt_llm/scaffolding/README_TREE_METHODS.md (1)
41-43: Nit: tighten wording and quote the stop token.Apply:
-For long outputs, raise generation `max_tokens` and consider adding a stop sequence (e.g., `</think>`). +For long outputs, increase generation `max_tokens` and consider adding a stop sequence (e.g., '</think>').examples/scaffolding/run_tot_example.py (5)
11-25: CLI polish: remove unused arg and expose branch_factor.
jsonl_fileis unused. Expose--branch_factorto match controller/documentation.Apply:
- parser.add_argument('--jsonl_file', type=str, default='./test.jsonl') + # Optional: dataset input can be added later @@ parser.add_argument('--selection_strategy', type=str, default="best", choices=["best", "vote", "random"]) + parser.add_argument('--branch_factor', type=int, default=2)
42-52: Make reward model optional.Docs say PRM is optional; gate reward worker initialization.
Apply:
- # Initialize reward worker if provided - reward_controller = None - reward_worker = TRTLLMWorker.init_with_new_llm( - args.reward_model_dir, - backend="pytorch", - max_batch_size=4, - max_num_tokens=8192, - kv_cache_free_gpu_memory_fraction=0.2, - disable_overlap_scheduler=True) - workers[PRMController.WorkerTag.REWARD] = reward_worker + # Initialize reward worker if provided + reward_controller = None + reward_worker = None + if args.reward_model_dir: + reward_worker = TRTLLMWorker.init_with_new_llm( + args.reward_model_dir, + backend="pytorch", + max_batch_size=4, + max_num_tokens=8192, + kv_cache_free_gpu_memory_fraction=0.2, + disable_overlap_scheduler=True) + workers[PRMController.WorkerTag.REWARD] = reward_worker
54-59: Construct PRMController only when reward_worker exists.Apply:
- reward_controller = PRMController(tokenizer=reward_worker.tokenizer) + if reward_worker: + reward_controller = PRMController(tokenizer=reward_worker.tokenizer)
61-67: Pass branch_factor from CLI.Aligns example with documented parameter.
Apply:
- selection_strategy=args.selection_strategy, - branch_factor=2) + selection_strategy=args.selection_strategy, + branch_factor=args.branch_factor)
74-77: Ensure worker shutdown on errors; print robustly.Wrap run in try/finally and handle single vs batched returns.
Apply:
- results = llm.generate(prompts) - print(results[0].outputs[0].text) - llm.shutdown(shutdown_workers=True) - print(f'main shut down done') + try: + results = llm.generate(prompts) + res = results if isinstance(results, list) else [results] + print(res[0].outputs[0].text) + finally: + llm.shutdown(shutdown_workers=True) + print("Main shutdown done")examples/scaffolding/run_mcts_example.py (4)
18-24: Remove unused argument.
jsonl_fileisn’t used.Apply:
- parser.add_argument('--jsonl_file', type=str, default='./test.jsonl')
39-48: Make reward model optional (mirrors TOT example).Apply:
- # Initialize reward worker if provided - reward_controller = None - reward_worker = TRTLLMWorker.init_with_new_llm( - args.reward_model_dir, - backend="pytorch", - max_batch_size=4, - max_num_tokens=8192, - kv_cache_free_gpu_memory_fraction=0.2, - disable_overlap_scheduler=True) - workers[PRMController.WorkerTag.REWARD] = reward_worker + # Initialize reward worker if provided + reward_controller = None + reward_worker = None + if args.reward_model_dir: + reward_worker = TRTLLMWorker.init_with_new_llm( + args.reward_model_dir, + backend="pytorch", + max_batch_size=4, + max_num_tokens=8192, + kv_cache_free_gpu_memory_fraction=0.2, + disable_overlap_scheduler=True) + workers[PRMController.WorkerTag.REWARD] = reward_worker
54-55: Construct PRMController only when reward_worker exists.Apply:
- reward_controller = PRMController(tokenizer=reward_worker.tokenizer) + if reward_worker: + reward_controller = PRMController(tokenizer=reward_worker.tokenizer)
70-73: Ensure worker shutdown on errors; print robustly.Apply:
- results = llm.generate(prompts) - print(results[0].outputs[0].text) - llm.shutdown(shutdown_workers=True) - print(f'main shut down done') + try: + results = llm.generate(prompts) + res = results if isinstance(results, list) else [results] + print(res[0].outputs[0].text) + finally: + llm.shutdown(shutdown_workers=True) + print("Main shutdown done")tensorrt_llm/scaffolding/tree_controllers.py (9)
23-30: Polish method docstrings (punctuation, clarity).Keeps D415 happy and improves readability.
def is_leaf(self) -> bool: - """node has no children""" + """Return True if the node has no children.""" ... def is_root(self) -> bool: - """node has no parent?""" + """Return True if the node has no parent."""
50-52: Remove or useuntried_actions.It’s declared but never referenced. Either wire it into expansion or drop it to avoid confusion.
110-117: Prefer explicit exception overassertfor runtime validation.
assertcan be stripped with optimization; raiseValueErrorinstead.- assert len( - tasks) == 1, "MCTS Controller only supports single task processing" + if len(tasks) != 1: + raise ValueError("MCTSController only supports single task processing.")
118-121: Seed randomness for reproducibility (optional).Honor
task.seed/seedkwarg to make runs deterministic.initial_state = getattr(task, 'input_str', str(task)) or "" + # Optional reproducibility + seed = kwargs.get('seed', getattr(task, 'seed', None)) + if seed is not None: + random.seed(seed)
253-276: Document and validate constructor params.Add docstrings and basic validation (e.g., positive depths/iterations, branch_factor ≥ 1).
279-281: Prefer explicit exception overassertfor runtime validation.Same as MCTS: raise
ValueError.- assert len( - tasks) == 1, "TOT Controller only supports single task processing" + if len(tasks) != 1: + raise ValueError("TOTController only supports single task processing.")
414-423: Narrow overly broad exception.Catch specific types to avoid masking issues.
- except Exception: + except (TypeError, AttributeError): final_task.stop = ['</think>']
449-456: Fix docstring style (D205, D415).Add punctuation and a blank line after the summary.
- def is_new_item(line: str) -> Optional[str]: - """Return the content of a new item header if the line starts a new approach/step item. - Supports: + def is_new_item(line: str) -> Optional[str]: + """Return the content of a new item header if the line starts a new approach/step item. + + Supports: - 'Approach N: ...' or 'Step N: ...' - 'N. ...' - '- ...' or '* ...' """
150-166: Avoid brittle GenerationResult instantiation
Bypassing__init__and poking_outputsis fragile—provide a small constructor/helper (or extend PRMController) to build a validGenerationResultfrom raw text (or accept plain strings directly), instead of usingGenerationResult.__new__and private fields.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
examples/scaffolding/run_mcts_example.py(1 hunks)examples/scaffolding/run_tot_example.py(1 hunks)tensorrt_llm/scaffolding/README_TREE_METHODS.md(1 hunks)tensorrt_llm/scaffolding/__init__.py(2 hunks)tensorrt_llm/scaffolding/tree_controllers.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Filenames compiled into a target must be case-insensitively unique
Files:
tensorrt_llm/scaffolding/README_TREE_METHODS.mdexamples/scaffolding/run_mcts_example.pyexamples/scaffolding/run_tot_example.pytensorrt_llm/scaffolding/__init__.pytensorrt_llm/scaffolding/tree_controllers.py
**/*.{h,hpp,hh,hxx,cc,cpp,cxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use spaces, not tabs; indent 4 spaces
Files:
examples/scaffolding/run_mcts_example.pyexamples/scaffolding/run_tot_example.pytensorrt_llm/scaffolding/__init__.pytensorrt_llm/scaffolding/tree_controllers.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Code must target Python 3.8+
Indent with 4 spaces; do not use tabs (Python)
Maintain module namespace on import: prefer from package.subpackage import foo; use foo.Symbol()
Python filenames use snake_case
Python class names use PascalCase
Python functions and methods use snake_case
Python local variables use snake_case; if starting with a number concept, prefix with k (e.g., k_99th_percentile)
Python global variables use G_ prefix with UPPER_SNAKE_CASE
Python constants use UPPER_SNAKE_CASE
Avoid shadowing variables from outer scopes
Initialize all externally visible class members in init
For public interfaces, prefer docstrings over comments; comments should be for in-function or file-local interfaces
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes and variables inline with docstrings immediately after assignment
Avoid reflection when a non-reflective approach suffices
Limit except clauses to specific exceptions where possible
When using try/except for duck-typing, keep try body minimal and move logic to else
Files:
examples/scaffolding/run_mcts_example.pyexamples/scaffolding/run_tot_example.pytensorrt_llm/scaffolding/__init__.pytensorrt_llm/scaffolding/tree_controllers.py
**/*.{cpp,cc,cxx,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend NVIDIA copyright header (current year) to all source files
Files:
examples/scaffolding/run_mcts_example.pyexamples/scaffolding/run_tot_example.pytensorrt_llm/scaffolding/__init__.pytensorrt_llm/scaffolding/tree_controllers.py
🧬 Code graph analysis (4)
examples/scaffolding/run_mcts_example.py (5)
tensorrt_llm/scaffolding/tree_controllers.py (3)
MCTSController(88-250)WorkerTag(91-93)WorkerTag(256-258)tensorrt_llm/scaffolding/controller.py (2)
NativeGenerationController(47-72)PRMController(91-196)tensorrt_llm/scaffolding/scaffolding_llm.py (2)
ScaffoldingLlm(22-231)shutdown_workers(211-213)tensorrt_llm/scaffolding/worker.py (2)
TRTLLMWorker(133-208)init_with_new_llm(145-176)examples/scaffolding/run_tot_example.py (2)
parse_arguments(9-26)main(29-77)
examples/scaffolding/run_tot_example.py (4)
tensorrt_llm/scaffolding/controller.py (2)
NativeGenerationController(47-72)PRMController(91-196)tensorrt_llm/scaffolding/tree_controllers.py (3)
TOTController(253-645)WorkerTag(91-93)WorkerTag(256-258)tensorrt_llm/scaffolding/scaffolding_llm.py (2)
ScaffoldingLlm(22-231)shutdown_workers(211-213)tensorrt_llm/scaffolding/worker.py (2)
TRTLLMWorker(133-208)init_with_new_llm(145-176)
tensorrt_llm/scaffolding/__init__.py (2)
tensorrt_llm/scaffolding/controller.py (1)
PRMController(91-196)tensorrt_llm/scaffolding/tree_controllers.py (2)
MCTSController(88-250)TOTController(253-645)
tensorrt_llm/scaffolding/tree_controllers.py (2)
tensorrt_llm/executor/result.py (2)
CompletionOutput(86-145)GenerationResult(485-634)tensorrt_llm/scaffolding/task.py (2)
GenerationTask(29-115)Task(11-19)
🪛 LanguageTool
tensorrt_llm/scaffolding/README_TREE_METHODS.md
[grammar] ~15-~15: There might be a mistake here.
Context: ...Expansion → Simulation → Backpropagation - Parameters: max_depth, `max_iterations...
(QB_NEW_EN)
[grammar] ~41-~41: There might be a mistake here.
Context: ...step, max_depth, or max_iterations` for broader/deeper search. - For long outpu...
(QB_NEW_EN)
[grammar] ~41-~41: There might be a mistake here.
Context: ...x_iterationsfor broader/deeper search. - For long outputs, raise generationmax_...
(QB_NEW_EN)
🪛 Ruff (0.12.2)
tensorrt_llm/scaffolding/tree_controllers.py
24-24: First line should end with a period, question mark, or exclamation point
Add closing punctuation
(D415)
450-455: 1 blank line required between summary line and description
(D205)
450-455: First line should end with a period, question mark, or exclamation point
Add closing punctuation
(D415)
🔇 Additional comments (4)
tensorrt_llm/scaffolding/README_TREE_METHODS.md (2)
21-22: Clarify or implement TOT max_iterations (currently not enforced).Docs state TOT supports
max_iterationsas a guard, but the controller loops only onmax_depth. Either document it as unused, or implement an iteration cap.Optional fix (controller, not this file):
- for depth in range(self.max_depth): + iterations = 0 + for depth in range(self.max_depth): next_level: List[TOTNode] = [] for node in current_level: + if iterations >= self.max_iterations: + break if node.is_terminal: continue # Generate thoughts... ... - for thought_data in selected_thoughts: + for thought_data in selected_thoughts: child_state = self._combine_state_and_thought( node.state, thought_data['thought']) ... next_level.append(child) + iterations += 1 if not next_level or iterations >= self.max_iterations: break
41-43: Ensure stop sequences are actually honored in the current worker.TRTLLMWorker.convert_task_params doesn’t forward
stop, so advising a stop sequence may mislead users. Forwardstopto SamplingParams.Suggested change (worker.py):
sampling_params = SamplingParams( max_tokens=task.max_tokens, temperature=task.temperature, top_p=task.top_p, top_k=task.top_k, - return_context_logits=task.return_context_logits) + stop=task.stop, + return_context_logits=task.return_context_logits)tensorrt_llm/scaffolding/__init__.py (1)
11-11: Public exports look good.Also applies to: 20-25
tensorrt_llm/scaffolding/tree_controllers.py (1)
414-422: Overall: solid orchestration and parsing.Thought parsing, evaluation parsing, and selection strategies are well factored and readable.
Also applies to: 521-591, 593-619
|
@therealnaveenkamal It is very cool! |
|
/bot run |
|
PR_Github #17517 [ run ] triggered by Bot |
|
PR_Github #17517 [ run ] completed with state |
|
@WeiHaocheng i've made the changes. please review and let me know |
|
Good jobs~ Code is allright for me, just left two comments for README and directory naming. |
|
@WeiHaocheng I've made the changes. Thank you very much for your support. Please feel free to assign me to interesting issues/features. would love to contribute more! |
Thank you! You can see our issues on : https://github.com/NVIDIA/TensorRT-LLM/issues?q=state%3Aopen%20label%3AScaffolding From my side, I think "Scaffolding support A2A protocal" is a interesting topic but I don't have time to think more deeply for the time being. I'm going to develop some agentic examples on scaffolding. If we can conveniently run these examples as services, it will greatly increase the appeal of using them. The first step of implementation of A2A is developing a wrapper which is similar to trtllm-serve to run the scaffolding as a server. In addition, feel free to tell me any issues you are interested in. Issues without comments have not yet started. |
|
@WeiHaocheng made the changes. thanks! |
Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
0a5f4b9 to
071e947
Compare
|
/bot reuse-pipeline |
|
PR_Github #17693 [ reuse-pipeline ] triggered by Bot |
|
PR_Github #17693 [ reuse-pipeline ] completed with state |
Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Head branch was pushed to by a user without write access
|
@WeiHaocheng there was a small lint error my side, fixed it. thanks. |
|
/bot reuse-pipeline |
|
PR_Github #17728 [ reuse-pipeline ] triggered by Bot |
|
PR_Github #17728 [ reuse-pipeline ] completed with state |
… to Scaffolding (NVIDIA#7490) Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Summary by CodeRabbit
New Features
Documentation
Description
This PR implements tree-based inference methods in Scaffolding to address this issue #3325 by adding:
Examples:
examples/scaffolding/run_mcts_example.pyandexamples/scaffolding/run_tot_example.py.Docs: concise
tensorrt_llm/scaffolding/README_TREE_METHODS.md.PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...Provide a user friendly way for developers to interact with a Jenkins server.
Run
/bot [-h|--help]to print this help message.See details below for each supported subcommand.
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.