Skip to content

[#20460][perf] Skip unused history for single-token beam stop words - #20462

Draft
yifanQi98 wants to merge 1 commit into
NVIDIA:mainfrom
yifanQi98:perf/single-token-stop-history
Draft

yifanQi98 wants to merge 1 commit into
NVIDIA:mainfrom
yifanQi98:perf/single-token-stop-history

Conversation

@yifanQi98

@yifanQi98 yifanQi98 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Beam-search request admission currently materializes all token histories and constructs one CPU tensor per beam even when every stop word is a single token. This PR skips that unused work and initializes the history tensor directly on CUDA for those requests. The shared tensor shape is preserved, including when another request needs multi-token history or triggers buffer growth. Multi-token stops, single-beam requests, and EOS/length handling retain their existing paths. No public setting or API change is introduced.

Fixes #20460

Validation

  • 36 new GPU tests pass: history materialization is skipped, the shared shape is preserved, fallback prompt suffixes are correct, stop hits/misses work in homogeneous and mixed batches, EOS/length precedence and first-finish reasons are preserved, and buffer growth/slot reuse work. Streaming and non-streaming request flags are covered at the handler level.
  • The unchanged baseline passes the 27 behavior/fallback cases and fails the 9 checks that require avoiding history reads. The candidate passes all 36.
  • 16 existing finish-reason/fused-finish tests pass with the candidate method.
  • The new test file is covered by the existing sampler-directory entries in l0_h100.yml and l0_b200.yml.
  • pre-commit run --files ... and git diff --check pass. The repository's lightweight mypy mode was used because this checkout has no compiled bindings.

The final in-tree method also passed an exact-output A/B comparison on Qwen3-0.6B at beam capacity 500: 560 measured calls, two independent LLM startups with AB/BA order, seven cases, 20 measured calls per case/side after five warmups (a separate diagnostic call is not timed). Cases cover a real single-token stop hit, a hit on the second of multiple single-token stops, a non-hit, a multi-token stop hit, mixed requests, ignore_eos=True, and eight-token VBWS. Every case had one stable full-output hash per side and matching hashes between baseline and candidate. Stop hits were independently verified from the handler's STOP_WORDS result and early output termination. Output comparison includes the API finish-reason labels as returned, including existing rc0 beam-finalization labeling behavior.

Runtime scope: changes are based on main at 9e8e5a270ecd03919f914680581f8c1cc4e5bf25. I cannot build current-main binaries in this environment. GPU validation used TensorRT-LLM 1.4.0rc0, PyTorch 2.14.0+cu132, and an RTX PRO 5000 72GB Blackwell. Before this change, the complete affected finish_reasons.py file on that main revision and in the installed wheel was byte-identical (SHA-256 d3c2323c32d877e04ce51e8c3aed7ff372cd291dc3638ce50e76418156246d50). The candidate method was loaded directly from this PR's source into the test process; installed files were not modified. These results are not a claim that a complete current-main build was tested.

Independent performance measurement

Qwen3-0.6B, BF16, public weights revision c1899de289a04d12100db370d81485cdf75e47ca, beam capacity 500, no other local optimizations. These measurements preceded the in-tree patch and used an isolated prototype of this same early return against the byte-identical rc0 baseline.

Workload Baseline ms Candidate ms Latency reduction Exploratory 95% interval
3 generated tokens, submitted batch 1 43.364 42.112 2.89% [2.11%, 3.66%]
3 generated tokens, submitted batch 2 69.480 66.584 4.17% [3.24%, 5.09%]
8 generated tokens, submitted batch 2 161.390 158.750 1.64% [1.16%, 2.11%]
Multi-token-stop fallback, 3 tokens, batch 2 70.268 70.252 0.02% [-1.13%, 1.16%]

Six independent pairs of fresh processes, alternating AB/BA; 10 warmups and 60 measured calls per case/condition. CUDA synchronization surrounds the complete LLM.generate call. Model initialization, warmup, instrumentation, and output hashing are excluded. Table latencies are means of six per-process medians. The reduction is calculated from the geometric mean of paired ratios, with a paired t interval on six log ratios; repeated calls within a process are not treated as independent replicates. No samples were removed.

The 2,880 measured public-model calls had identical output hashes across both conditions for each case; hashes include all returned beam token IDs, beam order, finish reasons, and the cumulative-score field (None with the benchmark's logprobs=None; numeric score parity is not measured). These fixed prompts are performance cases, so stop-hit correctness is separately covered above.

This is single-client, closed-loop latency measurement, with no fixed QPS or saturated-throughput claim. Submitted batch 2 means two requests per generate, not guaranteed co-scheduling at every executor step. The savings occur at admission/history reprocessing, not on every decode step, so the percentage benefit decreases as generation work grows. With current request conversion, ignore_eos=True clears stop words and does not enter this path; it receives no benefit.

Additional validation limitation: fixed-width-4 trials, including 32-token generation, were not internally deterministic even in the unchanged baseline. This also occurred in the ignore_eos=True control where this history path is never called, and persisted with overlap disabled. Those runs are retained but are not used as an exact-output equivalence result or a performance claim. Their cause has not been established. Small-beam stop semantics are covered by the deterministic handler tests; model-level exact parity for that regime remains inconclusive. The performance claim above is restricted to the measured wide-beam workloads.

Configuration and reproduction
  • Three-token VBWS: [20, 300, 500]; eight-token VBWS: [20, 20, 20, 20, 20, 20, 300, 500].
  • ignore_eos=False, explicit stop_token_ids=[151643]; the fallback case also supplies stop="UNLIKELY STOP SEQUENCE 8675309" (13 tokens).
  • Prompts: The capital of France is and A good way to learn mathematics is (5 and 7 input tokens).
  • max_batch_size=32, max_seq_len=1024, max_num_tokens=1024, KV token budget 128000, block reuse disabled, CUDA Graph batch sizes [1, 2], overlap enabled.
  • Run the following script in fresh baseline and candidate runtime processes, keeping the model path/settings identical. Repeat six pairs in alternating order and summarize each run by its median before computing paired ratios. The final patch requires no runtime flag. To reproduce with the installed rc0 wheel, run A without --candidate-source, and B with --candidate-source /path/to/this/PR/tensorrt_llm/_torch/pyexecutor/sampler/finish_reasons.py. This optional benchmark-only overlay verifies the baseline source checksum and changes only the test process; it is not part of the runtime patch.
"""Run once per fresh process on the baseline or candidate runtime."""
import argparse
import hashlib
import importlib.util
import json
import os
import sys
from pathlib import Path
import time

os.environ['TLLM_WORKER_USE_SINGLE_PROCESS'] = '1'
import torch
from tensorrt_llm import LLM, SamplingParams
from tensorrt_llm.llmapi import CudaGraphConfig, KvCacheConfig

p = argparse.ArgumentParser()
p.add_argument('--model', default='Qwen/Qwen3-0.6B')
p.add_argument('--output', required=True)
p.add_argument('--candidate-source', help='PR finish_reasons.py; optional rc0 process-only overlay')
a = p.parse_args()
if a.candidate_source:
    import tensorrt_llm._torch.pyexecutor.sampler.finish_reasons as original
    baseline_sha = hashlib.sha256(Path(original.__file__).read_bytes()).hexdigest()
    assert baseline_sha == 'd3c2323c32d877e04ce51e8c3aed7ff372cd291dc3638ce50e76418156246d50'
    name = 'tensorrt_llm._torch.pyexecutor.sampler.finish_reasons_benchmark'
    spec = importlib.util.spec_from_file_location(name, a.candidate_source)
    candidate = importlib.util.module_from_spec(spec)
    sys.modules[name] = candidate
    spec.loader.exec_module(candidate)
    original.FinishReasonsHandler._get_past_tokens = candidate.FinishReasonsHandler._get_past_tokens
torch.manual_seed(1234)
llm = LLM(model=a.model, backend='pytorch', dtype='bfloat16',
          max_batch_size=32, max_beam_width=500, max_seq_len=1024,
          max_num_tokens=1024, disable_overlap_scheduler=False,
          kv_cache_config=KvCacheConfig(max_tokens=128000, enable_block_reuse=False),
          cuda_graph_config=CudaGraphConfig(batch_sizes=[1, 2]))
prompts = ['The capital of France is', 'A good way to learn mathematics is']
base = dict(n=500, best_of=500, use_beam_search=True,
            beam_width_array=[20, 300, 500], max_tokens=3,
            ignore_eos=False, detokenize=False, logprobs=None,
            stop_token_ids=[151643])
cases = [
    ('3t_b1', prompts[:1], base),
    ('3t_b2', prompts, base),
    ('8t_b2', prompts, {**base, 'max_tokens': 8,
                        'beam_width_array': [20] * 6 + [300, 500]}),
    ('multi_stop_b2', prompts, {**base, 'stop': 'UNLIKELY STOP SEQUENCE 8675309'}),
]
report = {}
try:
    for name, inputs, settings in cases:
        params = SamplingParams(**settings)
        for _ in range(10):
            llm.generate(inputs, params, use_tqdm=False)
        times, hashes = [], []
        for _ in range(60):
            torch.cuda.synchronize()
            start = time.perf_counter_ns()
            outputs = llm.generate(inputs, params, use_tqdm=False)
            torch.cuda.synchronize()
            times.append((time.perf_counter_ns() - start) / 1e6)
            value = [[[o.token_ids, str(o.finish_reason), o.cumulative_logprob]
                      for o in result.outputs] for result in outputs]
            hashes.append(hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest())
        report[name] = {'latency_ms': times, 'output_hashes': hashes}
        with open(a.output, 'w') as f:
            json.dump(report, f)
finally:
    llm.shutdown()
Per-process paired medians (ms)
Workload Pair Order Baseline median ms Candidate median ms
single_batch1 1 AB 43.669568 41.945679
single_batch1 2 BA 43.264079 42.330029
single_batch1 3 AB 43.345725 42.105567
single_batch1 4 BA 43.287445 42.112152
single_batch1 5 AB 43.372570 41.844578
single_batch1 6 BA 43.245877 42.333922
single_batch2 1 AB 69.734417 66.357064
single_batch2 2 BA 69.637762 67.128939
single_batch2 3 AB 69.170102 66.864975
single_batch2 4 BA 69.100170 66.877846
single_batch2 5 AB 69.688872 66.045386
single_batch2 6 BA 69.549829 66.228448
single_8token_batch2 1 AB 161.576045 158.524376
single_8token_batch2 2 BA 161.789603 158.433670
single_8token_batch2 3 AB 161.538431 159.078268
single_8token_batch2 4 BA 160.789385 159.526502
single_8token_batch2 5 AB 161.273032 158.270457
single_8token_batch2 6 BA 161.376266 158.669446
multi_fallback_batch2 1 AB 70.780574 70.395220
multi_fallback_batch2 2 BA 70.072967 70.105431
multi_fallback_batch2 3 AB 69.900814 70.846660
multi_fallback_batch2 4 BA 69.782383 70.517662
multi_fallback_batch2 5 AB 70.675277 69.558240
multi_fallback_batch2 6 BA 70.395630 70.089370

Dev Engineer Review

_get_past_tokens now returns zero-filled CUDA history for requests with beam width greater than one and a nonempty list of single-token stop words. The returned tensor keeps the handler-wide shape and int32 dtype. Other requests retain the existing history path. No public API changes.

The optimization is limited to history preparation. QA should verify it with mixed batches and when the handler grows its stop-word buffer. The supplied results report 36 new GPU tests and 16 existing finish-reason tests passing, plus pre-commit and git diff --check; they also report exact-output parity and latency improvements in the tested variable-beam-width cases. Fixed-width-4 model parity remains inconclusive. These results used TensorRT-LLM 1.4.0rc0, not a build of current main. Current review severity counts were not supplied.

QA Engineer Review

Added tests/unittest/_torch/sampler/test_stop_word_history.py. Its tests cover history-read avoidance, tensor shape and dtype, fallback prompt suffixes, single-beam behavior, stop matching, finish-reason precedence, streaming, buffer growth, and slot reuse. The tests require CUDA. No matching entry was found in tests/integration/test_lists; this is a unit-test file, not an integration test. Coverage verdict: sufficient for the described behavior and fallback paths.

Per-File QA Perspective

  • tensorrt_llm/_torch/pyexecutor/sampler/finish_reasons.py — Verify that multi-beam requests with only single-token stops use zero history, while multi-token and single-beam requests retain history materialization. Confirm shape preservation when requests share a handler.
  • tests/unittest/_torch/sampler/test_stop_word_history.py — CUDA-gated regression tests cover the new path, fallback paths, matching, precedence, buffer growth, and slot reuse. No integration test-list entry applies to this unit-test file.

@coderabbitai

coderabbitai Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: NVIDIA/TensorRT-LLM/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: 5891496e-13d1-4f83-a244-576317ee979c
📥 Commits

Reviewing files that changed from the base of the PR and between e95cdbd and 2b64c66.

📒 Files selected for processing: 2
  • tensorrt_llm/_torch/pyexecutor/sampler/finish_reasons.py
  • tests/unittest/_torch/sampler/test_stop_word_history.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.

Walkthrough

For multi-beam requests with nonempty stop-word lists containing only single-token words, _get_past_tokens now returns zero-filled CUDA history instead of reading request tokens. Tests cover history selection, stop-word matching, finish-reason precedence, buffer growth, and slot reuse.

Changes

Stop-word history

Layer / File(s) Summary
Skip unused history and validate finish reasons
tensorrt_llm/_torch/pyexecutor/sampler/finish_reasons.py, tests/unittest/_torch/sampler/test_stop_word_history.py
For qualifying multi-beam requests, _get_past_tokens returns zero-filled CUDA history. CUDA-gated tests cover history selection, matching and finish-reason precedence, buffer growth, and slot reuse.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Suggested reviewers: bowenfu

Merge Risk: ⚪ Minimal · up to 2b64c

No merge-blocking issue is identified; the change is ready for normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 8.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the performance change: skipping unused history for single-token beam stop words. It uses the required issue and type format.
Description check Passed The description clearly explains the problem, solution, scope, validation, performance results, and limitations. It provides detailed test coverage, although it does not use the template's exact Descr…
Linked Issues check Passed Issue #20460 is the active direct linked issue. The change adds an early return in FinishReasonsHandler._get_past_tokens for beam width greater than one and a nonempty list of single-token stop word…
Out of Scope Changes check Passed The pull request changes only finish_reasons.py and adds focused tests for the behavior in issue #20460. The source change is a local optimization and does not change a public API or setting. The te…
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

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.

[Feature]: Skip unused history for single-token beam stop words

2 participants