Skip to content

[#22016][perf] Convert only the batch's slots in SpecSampler.update_requests - #22017

Open
Hang-get wants to merge 2 commits into
NVIDIA:mainfrom
Hang-get:perf/spec-sampler-active-slot-rows
Open

Hang-get wants to merge 2 commits into
NVIDIA:mainfrom
Hang-get:perf/spec-sampler-active-slot-rows

Conversation

@Hang-get

@Hang-get Hang-get commented Nov 10, 2026 •

Copy link
Copy Markdown

Dev Engineer Review

  • SpecSampler.update_requests builds active_requests from requests not in GENERATION_COMPLETE. It converts only those slots' rows from new_tokens, new_tokens_lens, and next_draft_tokens. The diff confirms this.
  • token_windows[request_index] and draft_lens[req_idx] keep request-position indexing. The loops read compact rows by row.
  • The assert seq_slot is not None check is removed. The diff does not show an equivalent check. Confirm that py_seq_slot cannot be None for active requests.
  • add_token removal and the _request_common_handling signature change, stated in the earlier summary, do not appear in this diff. Treat those claims as unverified and do not rely on them.
  • No public API or config changes appear in the diff.

QA Engineer Review

Test files changed:

  • Added: tests/unittest/_torch/speculative/hw_agnostic/test_spec_sampler_update_requests.py (+110 lines). It has one parameterized test with verify_lens set to None or [3, 2, 1, 2]. It is marked cpu_only.

The test covers:

  • Non-contiguous sequence slots, with a completed request between active requests.
  • Accepted tokens, accepted and verified draft counts, rewind length, next draft tokens, and decoding iteration.
  • Unchanged state for the completed request.

Test-list membership: not established. The grep result did not return in the evidence. The test is a CPU unit test, so test-db/ and qa/ listing may not apply.

Coverage verdict: needs follow-up. The test does not cover GPU execution, end-to-end serving, or real stop-criteria paths, because handle_stop_criteria is stubbed. Current-head CI results are not available.

Per-File QA Perspective

  • tensorrt_llm/_torch/speculative/spec_sampler_base.py: Verify updates for active requests with scattered slots and batches that include completed requests. Verify verification-window bounds and stop handling.
  • tests/unittest/_torch/speculative/hw_agnostic/test_spec_sampler_update_requests.py: Adds a CPU-only unit test for row selection and request updates. Its list membership is not established.

Description

SpecSampler.update_requests runs once per step for every one-model speculative decoding mode. After sampler_event.synchronize() it converted the host copies of the whole sampler store to nested Python lists: new_tokens ([max_draft_len + 1, max_num_sequences, 1]), new_tokens_lens and next_draft_tokens. The store has one row per preallocated sequence slot, but the loop only reads the rows of the batch's requests, so the conversion cost depended on max_num_sequences rather than on the batch.

This change indexes the three host tensors with the slots of the batch's unfinished requests, converts only those rows, and reads them by row position in the validation and update loops. token_windows and draft_lens are still indexed by request position. _request_common_handling now receives the request's own draft row. Device work, the D2H copies and the request updates are unchanged.

Closes #22016.

Benchmark

CPU only, main 37e6e677 against this change (spec_sampler_base.py is identical on the current base 70fe2b2a6). Both versions of update_requests ran on identical host tensors, with request stubs implementing add_new_token, get_num_tokens, get_tokens and finish_by, and the real handle_stop_criteria; native bindings were stubbed for the import. Intel Xeon Platinum 8352Y, CPython 3.12.3, PyTorch 2.15.0+cpu, one pinned core; 20 warmups, then nine rounds of 15-50 timed calls, median of the round medians.

Slots Active requests Draft tokens main This PR Speedup
256 1 3 129.6 us 27.1 us 4.8x
256 256 3 651.4 us 584.1 us 1.1x
512 1 3 256.1 us 27.1 us 9.5x
512 16 3 289.1 us 60.8 us 4.8x
2048 1 3 1086.3 us 27.7 us 39.2x
2048 8 3 1108.4 us 45.0 us 24.6x
2048 64 3 1249.0 us 159.0 us 7.9x
2048 2048 3 5748.5 us 4994.5 us 1.2x
2048 8 7 2223.6 us 52.2 us 42.6x

2048 is the default max_batch_size; most DeepSeek-R1-0528 MTP configs under examples/configs/database use 512, including all concurrency-1 configs. A full store is not slower, because each request's tokens become one flat list instead of one single-element list per token.

Test Coverage

  • New tests/unittest/_torch/speculative/hw_agnostic/test_spec_sampler_update_requests.py (cpu_only): requests on scattered slots of a 16-slot store, with a finished request between them so that row positions differ from request positions, for uniform and ragged verification windows. It checks the appended tokens, the accepted/verified/rewind counts and the next draft tokens against each request's slot row. 2 passed, on this branch and on main.
  • Existing tests/unittest/_torch/speculative/hw_agnostic/test_ragged_spec_sampler.py, which drives update_requests through sample_async (verify windows, pending steps, slot reuse): 85 passed.
  • Randomized differential check against main, not included in the PR: 20,000 random states (finished requests, ragged and uniform windows, runtime_draft_len above and below the store width, end-id, length and stop-word finishes, invalid windows) gave identical request updates and identical exceptions.
  • pre-commit run --files on both files: all hooks passed, including Ruff, ruff-format, codespell, the test-list AST check and Pyrefly (no diagnostics).

Local test runs used --noconftest with an in-process stub for the native bindings; this machine has no usable GPU or TensorRT-LLM build. The l0_cpu list already includes unittest/_torch/speculative/hw_agnostic. Not run: GPU tests and end-to-end serving benchmarks.

PR Checklist

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

AI assistance (Cursor) was used for this change.

@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

SpecSampler.update_requests now selects host token data for active requests by sequence slot. It appends accepted tokens and assigns each request’s selected next-draft row. A CPU-only test checks non-contiguous slots, an interleaved completed request, and both verification-length modes.

Changes

Speculative sampler request updates

Layer / File(s) Summary
Select rows and update active requests
tensorrt_llm/_torch/speculative/spec_sampler_base.py, tests/unittest/_torch/speculative/hw_agnostic/test_spec_sampler_update_requests.py
update_requests gathers host data for active requests by sequence slot and uses the selected rows to validate verification windows and update request state. The CPU-only test checks active and completed requests, request state updates, and both verification-length modes.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor · Severity of issue fixed: Medium

Suggested reviewers: zhaoyuanh-nvidia

Merge Risk: Minimal · up to e4190

This change reduces CPU conversion work in speculative sampler request updates without altering request-state updates. A CPU-only test covers scattered slots, completed requests, and both verification-length modes. No merge-blocking risk is evident.

Security architecture risk: Minimal · up to e4190

The change reduces unnecessary work without changing how results are assigned to requests. The review found no material increase in security or failure-containment risk.

Pre-merge checks: Passed 2 · Inconclusive 2

Failed Failed checks: 2 inconclusive

Check name Status Explanation Resolution
Linked Issues check Inconclusive [#22016] requires SpecSampler.update_requests to convert only the rows of the batch's unfinished request slots, read those rows by position, and keep device work, D2H copies, and request updates uncha… Confirm the intended scope of the changes to the D2H copy path, the Store layout, and the device scatter path. Either narrow the PR to the row-selection change described in #22016, or update the linked issue and PR description to cover the …
Out of Scope Changes check Inconclusive Changes that serve #22016 include the row selection, the row-based reads in the validation and update loops, and the _request_common_handling signature change. The whole-PR diff also contains changes … Explain how items 1 to 5 serve #22016, or move them to a separate PR. If they stay, update the PR description to list each change and its benchmark or test evidence. Remove the is_generation_model removal if it does not belong to this chang…
Passed Passed checks: 2 passed

Check name Status Explanation
Title check Passed The title follows the repository template: it has a GitHub issue ID tag [#22016], a type tag [perf], and a summary. It names the main change, which limits the host-side conversion in SpecSampler.updat…
Description check Passed The description covers the problem, the solution, the benchmark method and results, and the test coverage. It explains that only the batch's slots are converted and which tensors are affected. It also…
Full details: Title check

Explanation

The title follows the repository template: it has a GitHub issue ID tag [#22016], a type tag [perf], and a summary. It names the main change, which limits the host-side conversion in SpecSampler.update_requests to the batch's slots. The changeset matches this scope.

Full details: Description check

Explanation

The description covers the problem, the solution, the benchmark method and results, and the test coverage. It explains that only the batch's slots are converted and which tensors are affected. It also lists the tests run and the checklist. It does not fill the template's separate PR Checklist items as checked, and the template's '@coderabbitai summary' header is left as is. These gaps are minor, so the description is mostly complete.

Full details: Linked Issues check

Explanation

[#22016] requires SpecSampler.update_requests to convert only the rows of the batch's unfinished request slots, read those rows by position, and keep device work, D2H copies, and request updates unchanged. The whole-PR diff (merge base 13aae0e to head e41908f) implements the row selection in spec_sampler_base.py. active_requests skips GENERATION_COMPLETE. new_tokens, new_tokens_lens, and next_draft_tokens are indexed by active_slots before .tolist(). The loops read these by row. token_windows and draft_lens stay indexed by request position. _request_common_handling now receives the request's own draft row. The diff also changes parts the issue says must stay the same. The Store now uses one host_read buffer with views, so one D2H copy replaces three copies (_copy_to_host / stage_copy_to_host). The device scatter path now uses spec_store_scatter and _slot_index. handle_stop_criteria is inlined. The change set has grown beyond the PR description, which says D2H copies and device work are unchanged. The diff output was truncated at 16000 bytes, so the device scatter changes are only partly visible. Whether the 'unchanged' constraint is met cannot be confirmed from the reviewed evidence. The row-selection objective itself appears implemented. The new CPU-only test file was not re-read at this head, so its current content is not verified here.

Resolution

Confirm the intended scope of the changes to the D2H copy path, the Store layout, and the device scatter path. Either narrow the PR to the row-selection change described in #22016, or update the linked issue and PR description to cover the additional changes and their measured effect. Re-run the CPU-only tests in test_spec_sampler_update_requests.py and test_ragged_spec_sampler.py against this head.

Full details: Out of Scope Changes check

Explanation

Changes that serve #22016 include the row selection, the row-based reads in the validation and update loops, and the _request_common_handling signature change. The whole-PR diff also contains changes that the PR description does not mention. These are: (1) Store.host_read with views and Store.allocate, which merge the host-read tensors into one D2H copy; (2) spec_step_copies.slot_scatter_supported() and spec_store_scatter in the device write path, with a new row and slot validation that raises ValueError; (3) _slot_index and a cached device slot tensor; (4) removal of is_generation_model; (5) inlining of stop handling with FinishReason and meet_stop_token_criteria in update_requests. Items 1 to 3 touch device and D2H work that #22016 says must stay unchanged. Item 4 has no connection to the issue in the reviewed evidence. A reason may exist for these changes, such as a shared branch base or an overlapping perf change, but the reviewed evidence does not show it. The diff output was truncated, so the full extent of items 2 and 3 is not visible. Related PR references in the history do not establish their scope.

Resolution

Explain how items 1 to 5 serve #22016, or move them to a separate PR. If they stay, update the PR description to list each change and its benchmark or test evidence. Remove the is_generation_model removal if it does not belong to this change, or state its reason.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between da82467 and e41908f.

Files selected for processing: 2

  • tensorrt_llm/_torch/speculative/spec_sampler_base.py
  • tests/unittest/_torch/speculative/hw_agnostic/test_spec_sampler_update_requests.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@JunyiXu-nv JunyiXu-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Runtime part LGTM. The compact rows match the per-slot reads (new_tokens[step][slot][beam], new_tokens_lens and next_draft_tokens by slot) on random shapes and slot subsets, add_token did only the read plus add_new_token, and _request_common_handling has no other caller. The new cpu_only test runs via l0_cpu.yml's speculative/hw_agnostic entry.

@svc-trtllm-gh-bot svc-trtllm-gh-bot added the Community want to contribute PRs initiated from Community label Nov 10, 2026
@hanjingtian

Copy link
Copy Markdown
Collaborator

Could you please rebase this branch onto the latest upstream main to include the CI hang fix in #22101 (6edbe383497a)? The current branch still contains the regression that can cause pipelines to hang for an extended period and worsen CI queueing

…date_requests

Index the host copies of the one-model speculative sampler store with the slots of the batch's unfinished requests before converting them to Python lists. The store holds one row per preallocated sequence slot, so converting all of it made the per-step cost grow with max_num_sequences instead of the batch.

AI assistance (Cursor) was used for this change.

Co-authored-by: Cursor <[email protected]>
Signed-off-by: YangHaoooooo <[email protected]>
@Hang-get
Hang-get force-pushed the perf/spec-sampler-active-slot-rows branch from afb753f to da82467 Compare November 12, 2026 06:35
@Hang-get

Copy link
Copy Markdown
Author

Rebased onto current main (efec60ea5), which includes the CI hang fix from #22101 (6edbe383). This branch is now da82467ca. The patch is unchanged.

@Hang-get

Copy link
Copy Markdown
Author

Thanks @JunyiXu-nv for the review. When someone has a moment, could you trigger CI for this PR and for #21981 and #22093, which are also approved? I can't start it as an external contributor.

Preserve the inlined upstream stop criteria while reading only active slot rows.

AI assistance (OpenAI Codex) was used for this change.

Signed-off-by: YangHaoooooo <[email protected]>

This branch has not been deployed

No deployments
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Performance]: SpecSampler.update_requests converts every preallocated slot to Python lists each step

4 participants