KEMBAR78
[#3325][feat] Add MCTS and TOT tree-based inference controllers to Scaffolding by therealnaveenkamal · Pull Request #7490 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@therealnaveenkamal
Copy link
Contributor

@therealnaveenkamal therealnaveenkamal commented Sep 3, 2025

Summary by CodeRabbit

  • New Features

    • Added tree-based inference controllers: Monte Carlo Tree Search (MCTS) and Tree of Thoughts (ToT) for structured reasoning with configurable depth, iterations, and thoughts-per-step, with optional reward scoring.
    • Public API now exposes PRM, MCTS, and ToT controllers.
    • Introduced CLI examples to run MCTS/ToT workflows with adjustable parameters.
  • Documentation

    • New guide detailing MCTS and ToT methods, configuration options, and usage examples, including tips for tuning outputs.

Description

This PR implements tree-based inference methods in Scaffolding to address this issue #3325 by adding:

  • MCTSController: UCB1 selection, expansion via generation, simulation via PRM or heuristic, backpropagation; compact “Problem + Steps” final reasoning.
  • TOTController: level-wise thought expansion with evaluation; supports PRM-based scoring; robust parsing of “Approach/Step/numbered/bulleted” formats; selection strategies (best, vote, random) with configurable branch_factor; final synthesis from best path.

Examples: examples/scaffolding/run_mcts_example.py and examples/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 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.

@therealnaveenkamal therealnaveenkamal requested a review from a team as a code owner September 3, 2025 01:57
@therealnaveenkamal
Copy link
Contributor Author

cc @WeiHaocheng

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary of Changes
Tree controllers implementation
tensorrt_llm/scaffolding/tree_controllers.py
New module adding TreeNode, MCTSNode, TOTNode, and controllers MCTSController and TOTController with WorkerTag enums, constructor params, and process(...) orchestration for selection/expansion/evaluation/backprop and level-wise thought exploration.
Public API exports
tensorrt_llm/scaffolding/__init__.py
Re-exports PRMController, MCTSController, TOTController; updates imports and all without logic changes.
Examples: tree methods
examples/scaffolding/run_mcts_example.py, examples/scaffolding/run_tot_example.py
Adds CLI scripts demonstrating end-to-end scaffolding with MCTS and TOT. Define parse_arguments() and main(); initialize generation and reward workers, set controller params, run a sample prompt, print first result, and shutdown workers.
Documentation
tensorrt_llm/scaffolding/README_TREE_METHODS.md
New README detailing Tree-Based Inference (MCTS and TOT), parameters, flow phases, example invocations, and notes on reward model usage and output control.

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

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

✨ 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 or @coderabbit 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.

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: 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_file is unused. Expose --branch_factor to 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_file isn’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 use untried_actions.

It’s declared but never referenced. Either wire it into expansion or drop it to avoid confusion.


110-117: Prefer explicit exception over assert for runtime validation.

assert can be stripped with optimization; raise ValueError instead.

-        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/seed kwarg 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 over assert for 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 _outputs is fragile—provide a small constructor/helper (or extend PRMController) to build a valid GenerationResult from raw text (or accept plain strings directly), instead of using GenerationResult.__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.

📥 Commits

Reviewing files that changed from the base of the PR and between 109f272 and c9a3cbd.

📒 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.md
  • examples/scaffolding/run_mcts_example.py
  • examples/scaffolding/run_tot_example.py
  • tensorrt_llm/scaffolding/__init__.py
  • tensorrt_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.py
  • examples/scaffolding/run_tot_example.py
  • tensorrt_llm/scaffolding/__init__.py
  • tensorrt_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.py
  • examples/scaffolding/run_tot_example.py
  • tensorrt_llm/scaffolding/__init__.py
  • tensorrt_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.py
  • examples/scaffolding/run_tot_example.py
  • tensorrt_llm/scaffolding/__init__.py
  • tensorrt_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_iterations as a guard, but the controller loops only on max_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. Forward stop to 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

@svc-trtllm-gh-bot svc-trtllm-gh-bot added the Community want to contribute PRs initiated from Community label Sep 3, 2025
@juney-nvidia juney-nvidia requested review from WeiHaocheng and removed request for kaiyux September 3, 2025 03:50
@WeiHaocheng
Copy link
Collaborator

@therealnaveenkamal It is very cool!
I think there's no problem overall and left come comments.

@WeiHaocheng
Copy link
Collaborator

/bot run

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17517 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17517 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #13168 completed with status: 'SUCCESS'

@therealnaveenkamal
Copy link
Contributor Author

@WeiHaocheng i've made the changes. please review and let me know

@WeiHaocheng
Copy link
Collaborator

Good jobs~ Code is allright for me, just left two comments for README and directory naming.

@therealnaveenkamal
Copy link
Contributor Author

@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!

@WeiHaocheng
Copy link
Collaborator

WeiHaocheng commented Sep 4, 2025

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

@therealnaveenkamal
Copy link
Contributor Author

@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>
@WeiHaocheng WeiHaocheng force-pushed the feature/scaffolding_tree branch from 0a5f4b9 to 071e947 Compare September 4, 2025 14:15
@WeiHaocheng
Copy link
Collaborator

/bot reuse-pipeline

@WeiHaocheng WeiHaocheng enabled auto-merge (squash) September 4, 2025 14:15
@tensorrt-cicd
Copy link
Collaborator

PR_Github #17693 [ reuse-pipeline ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17693 [ reuse-pipeline ] completed with state SUCCESS
Release Check Pipeline #1899 failed
Reusing PR_Github #17517 for commit 071e947

Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
auto-merge was automatically disabled September 4, 2025 16:08

Head branch was pushed to by a user without write access

@therealnaveenkamal
Copy link
Contributor Author

@WeiHaocheng there was a small lint error my side, fixed it. thanks.

@WeiHaocheng WeiHaocheng enabled auto-merge (squash) September 5, 2025 01:49
@WeiHaocheng
Copy link
Collaborator

/bot reuse-pipeline

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17728 [ reuse-pipeline ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #17728 [ reuse-pipeline ] completed with state SUCCESS
Reusing PR_Github #17517 for commit e72112e

@WeiHaocheng WeiHaocheng merged commit 58d1036 into NVIDIA:main Sep 5, 2025
5 checks passed
@karljang karljang added the LLM API <NV>High-level LLM Python API & tools (e.g., trtllm-llmapi-launch) for TRTLLM inference/workflows. label Sep 9, 2025
Wong4j pushed a commit to Wong4j/TensorRT-LLM that referenced this pull request Sep 20, 2025
… to Scaffolding (NVIDIA#7490)

Signed-off-by: Naveenraj Kamalakannan <therealnaveenkamal@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Community want to contribute PRs initiated from Community LLM API <NV>High-level LLM Python API & tools (e.g., trtllm-llmapi-launch) for TRTLLM inference/workflows.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants