Skip to content

Conversation

@samuellees
Copy link
Collaborator

@samuellees samuellees commented Aug 18, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Generated benchmark prompts now strictly match expected token lengths, preventing mismatches between configuration and tokenized input.
  • Refactor

    • Adopted an encode/decode loop that iteratively adjusts content until the target token length is met, improving input consistency and adding slight content variation.
    • No public API changes.

Description

Fix bug of prompt and output token length of the RandomDataset under --random-token-ids option.
See more details in PR4971

Test Coverage

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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 18, 2025

📝 Walkthrough

Walkthrough

Reworks RandomDataset.sample (non-ShareGPT path) to generate inner token sequences via a helper, then decode/re-encode iteratively adding random tokens until a target combined token length, truncates to that length, and returns either text or token IDs. No public API changes.

Changes

Cohort / File(s) Summary
RandomDataset sampling logic
tensorrt_llm/serve/scripts/benchmark_dataset.py
Adds gen_inner_sequence for inner token offsets; computes total_input_len_expected; decodes composed tokens to text and re-encodes in a loop appending random sequences until reaching expected length; truncates final sequence; uses resulting token IDs (or decoded text) as SampleRequest.prompt and sets prompt_len = total_input_len_expected. No signature/API changes.

Sequence Diagram(s)

sequenceDiagram
  actor Caller
  participant Dataset as RandomDataset.sample
  participant Tok as Tokenizer

  Caller->>Dataset: sample(...)
  Dataset->>Dataset: gen_inner_sequence(input_len, idx_offset, random_offset, vocab_size)
  Dataset->>Tok: decode(prefix + inner_seq)
  Tok-->>Dataset: prompt_text
  loop until re-encoded length >= total_input_len_expected
    Dataset->>Tok: encode(prompt_text)
    Tok-->>Dataset: token_ids
    alt length < expected
      Dataset->>Dataset: append new_random_offset + gen_inner_sequence(...)
      Dataset->>Tok: decode(updated token_ids)
      Tok-->>Dataset: prompt_text
    end
  end
  Dataset->>Dataset: truncate to total_input_len_expected
  alt return_text
    Dataset->>Tok: decode(final_token_ids)
    Tok-->>Dataset: final_text
    Dataset-->>Caller: SampleRequest(prompt=final_text, prompt_len)
  else
    Dataset-->>Caller: SampleRequest(prompt=final_token_ids, prompt_len)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • qiaoxj07

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ 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 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: 1

🧹 Nitpick comments (4)
tensorrt_llm/serve/scripts/benchmark_dataset.py (4)

562-562: Ensure reproducibility: avoid mixing RNGs (torch vs numpy) in the loop

This path currently uses numpy’s global RNG (np.random.randint) and is not seeded alongside self.rng, breaking determinism across runs.

Apply this diff to use the already-seeded torch.Generator:

-                    new_random_offset = np.random.randint(0, vocab_size)
+                    new_random_offset = int(
+                        torch.randint(0, vocab_size, (1,), generator=self.rng).item()
+                    )

560-566: Reduce re-tokenization work by appending only the needed token count

Appending a full input_lens[i] each iteration can overshoot and cause unnecessary decode/encode work.

Apply this diff to minimize iterations and work:

-                while len(re_encoded_token_ids) < total_input_len_expected:
+                while len(re_encoded_token_ids) < total_input_len_expected:
                     # Append a new random sequence to the existing sequence
-                    new_random_offset = np.random.randint(0, vocab_size)
-                    new_inner_seq = gen_inner_sequence(input_lens[i], i, new_random_offset, vocab_size)
+                    new_random_offset = int(
+                        torch.randint(0, vocab_size, (1,), generator=self.rng).item()
+                    )
+                    needed = max(1, total_input_len_expected - len(re_encoded_token_ids))
+                    new_inner_seq = gen_inner_sequence(
+                        needed, i, new_random_offset, vocab_size
+                    )
                     re_encoded_token_ids += new_inner_seq
                     # Re-encode the prompt
-                    new_prompt = tokenizer.decode(re_encoded_token_ids)
-                    re_encoded_token_ids = tokenizer.encode(new_prompt)
+                    new_prompt = tokenizer.decode(
+                        re_encoded_token_ids, skip_special_tokens=True
+                    )
+                    re_encoded_token_ids = tokenizer.encode(
+                        new_prompt, add_special_tokens=False
+                    )

560-566: Add a safety cap to prevent pathological infinite growth loops

On unusual tokenizers/text, re-encode length could stagnate or oscillate. Add a bounded number of iterations to avoid hangs.

Suggested guard:

-                while len(re_encoded_token_ids) < total_input_len_expected:
+                max_iters = 16  # guardrail against pathological cases
+                iters = 0
+                while len(re_encoded_token_ids) < total_input_len_expected:
+                    iters += 1
+                    if iters > max_iters:
+                        logger.warning(
+                            "Exceeded max token growth iterations for sample %d; truncating to %d.",
+                            i, total_input_len_expected
+                        )
+                        break
                     # Append a new random sequence to the existing sequence

541-544: Minor: add type hints to helper for clarity and consistency

Local helper is great. Add type hints to match codebase style and improve readability.

-            def gen_inner_sequence(input_len, idx_offset, random_offset, vocab_size):
+            def gen_inner_sequence(
+                input_len: int,
+                idx_offset: int,
+                random_offset: int,
+                vocab_size: int,
+            ) -> list[int]:
                 return ((random_offset + idx_offset + np.arange(input_len)) %
                              vocab_size).tolist()
📜 Review details

Configuration used: .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 ce0b13e and 99d9cc8.

📒 Files selected for processing (1)
  • tensorrt_llm/serve/scripts/benchmark_dataset.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/serve/scripts/benchmark_dataset.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tensorrt_llm/serve/scripts/benchmark_dataset.py
⏰ 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 (1)
tensorrt_llm/serve/scripts/benchmark_dataset.py (1)

548-570: LGTM on the length-targeting strategy and final truncation

Introducing total_input_len_expected and truncating after re-tokenization aligns prompt_len with the actual tokenized length. This directly addresses the random-token-ids length bug.

Also applies to: 572-579

@svc-trtllm-gh-bot svc-trtllm-gh-bot added the Community want to contribute PRs initiated from Community label Aug 18, 2025
Add explicit flags to make length behavior predictable

Signed-off-by: li-kesen <[email protected]>
@samuellees samuellees changed the title Fix bug of prompt and output token length of the RandomDataset under --random-token-ids option [None][fix] Fix bug of prompt and output token length of the RandomDataset under --random-token-ids option Aug 18, 2025
Signed-off-by: li-kesen <[email protected]>
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: 1

♻️ Duplicate comments (1)
tensorrt_llm/serve/scripts/benchmark_dataset.py (1)

582-584: Decode final prompt with skip_special_tokens=True (consistency with loop)

Final decode should also skip special tokens for consistency and to avoid surfacing them as text. This mirrors the encode/decode contract used in the loop and prevents accidental textual artifacts.

Apply this diff:

-                if self.return_text:
-                    result_prompt = tokenizer.decode(result_prompt)
+                if self.return_text:
+                    result_prompt = tokenizer.decode(
+                        result_prompt, skip_special_tokens=True
+                    )
🧹 Nitpick comments (4)
tensorrt_llm/serve/scripts/benchmark_dataset.py (4)

1-5: Add NVIDIA copyright header per coding guidelines

Per the provided guidelines, prepend the NVIDIA copyright header to all source files.

Apply this diff at the top of the file:

+# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
 # Adopted from
 # https://github.com/vllm-project/vllm/blob/200bbf92e8861e2458a6f90bca73f40cc3b1ad1f/benchmarks/benchmark_dataset.py
 # https://github.com/sgl-project/sglang/blob/8321f8e45e07a8539935145d1c76373e457ddc89/python/sglang/bench_serving.py
 # SPDX-License-Identifier: Apache-2.0
 """

541-546: Helper function is fine; consider adding type hints for readability

Optional: add annotations to make intent explicit and ease static analysis.

Example:

-            def gen_inner_sequence(input_len, idx_offset, random_offset,
-                                   vocab_size):
+            def gen_inner_sequence(input_len: int,
+                                   idx_offset: int,
+                                   random_offset: int,
+                                   vocab_size: int) -> list[int]:
                 return ((random_offset + idx_offset + np.arange(input_len)) %
                         vocab_size).tolist()

553-576: Optional: guard against pathological non-termination

Highly unlikely, but adding a max-iterations safety guard around the while can prevent pathological tokenizer behaviors from causing long loops on exotic tokenizers.

Sketch:

-                while len(re_encoded_token_ids) < total_input_len_expected:
+                max_iters = 8  # small cap; we add large chunks each time
+                iters = 0
+                while len(re_encoded_token_ids) < total_input_len_expected and iters < max_iters:
                     # Append a new random sequence to the existing sequence
                     ...
                     re_encoded_token_ids = tokenizer.encode(
                         new_prompt, add_special_tokens=False)
+                    iters += 1

Also applies to: 577-580


426-436: Consider unit tests covering exact-length guarantees with --random-token-ids

No tests are included. Recommend adding tests that assert:

  • When return_text=False, len(prompt_ids) == prefix_len + input_len.
  • When return_text=True, len(tokenizer.encode(prompt, add_special_tokens=False)) == prefix_len + input_len.
  • Works across at least two tokenizers (e.g., LLaMA/LlamaTokenizerFast and Qwen2TokenizerFast).

I can provide a minimal pytest to exercise RandomDataset.sample() on both paths.

📜 Review details

Configuration used: .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 383735b and aa0088a.

📒 Files selected for processing (1)
  • tensorrt_llm/serve/scripts/benchmark_dataset.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/serve/scripts/benchmark_dataset.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tensorrt_llm/serve/scripts/benchmark_dataset.py
🧠 Learnings (2)
📓 Common learnings
Learnt from: samuellees
PR: NVIDIA/TensorRT-LLM#6974
File: tensorrt_llm/serve/scripts/benchmark_dataset.py:558-566
Timestamp: 2025-08-18T08:42:02.615Z
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.
📚 Learning: 2025-08-18T08:42:02.615Z
Learnt from: samuellees
PR: NVIDIA/TensorRT-LLM#6974
File: tensorrt_llm/serve/scripts/benchmark_dataset.py:558-566
Timestamp: 2025-08-18T08:42:02.615Z
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:

  • tensorrt_llm/serve/scripts/benchmark_dataset.py
⏰ 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)
tensorrt_llm/serve/scripts/benchmark_dataset.py (2)

548-552: Good: deterministic inner-seq and explicit target length computation

The construction of token_ids and total_input_len_expected is straightforward and aligns with the PR goal of exact-length prompts.


561-576: Correct control of special tokens during re-tokenization loop

Using skip_special_tokens=True and add_special_tokens=False eliminates BOS/EOS drift and makes the length control deterministic. This matches the stated benchmarking priority on exact sequence lengths.

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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tensorrt_llm/serve/scripts/benchmark_dataset.py (2)

1-5: Add NVIDIA copyright header and future annotations import (Py3.8 compatibility).

  • Coding guidelines require the NVIDIA copyright header at the top of every source file.
  • The file uses PEP 585 style generics (list[str], list[SampleRequest]) which are Python 3.9+; for Python 3.8+ targets, add from __future__ import annotations as the first non-docstring statement.

Apply:

+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
 # Adopted from
 # https://github.com/vllm-project/vllm/blob/200bbf92e8861e2458a6f90bca73f40cc3b1ad1f/benchmarks/benchmark_dataset.py
 # https://github.com/sgl-project/sglang/blob/8321f8e45e07a8539935145d1c76373e457ddc89/python/sglang/bench_serving.py
 # SPDX-License-Identifier: Apache-2.0
 """
@@
- 
+from __future__ import annotations
+
 import base64

Also applies to: 19-21


1167-1189: Fix: sampled_requests used before assignment in VisionArenaDataset.sample.

This method appends to sampled_requests without initializing it; it will raise UnboundLocalError.

-        # Collect prompts for batch processing
-        prompts = []
+        # Collect prompts for batch processing
+        prompts = []
+        sampled_requests = []
@@
-            sampled_requests.append(
+            sampled_requests.append(
♻️ Duplicate comments (2)
tensorrt_llm/serve/scripts/benchmark_dataset.py (2)

566-569: Reproducibility fix acknowledged: RNG now uses self.rng.

Replacing np.random.randint with torch.randint(..., generator=self.rng) restores seeded determinism.


584-586: Decode final prompt with skip_special_tokens=True to preserve exact token-length when return_text=True.

Without this, special tokens can surface in text and re-tokenization downstream can drift from prompt_len=total_input_len_expected, defeating the exact-length goal.

-                if self.return_text:
-                    result_prompt = tokenizer.decode(result_prompt)
+                if self.return_text:
+                    result_prompt = tokenizer.decode(
+                        result_prompt, skip_special_tokens=True
+                    )
🧹 Nitpick comments (4)
tensorrt_llm/serve/scripts/benchmark_dataset.py (4)

542-546: Prefer torch.arange over numpy here; add minimal typing.

Keeps everything in torch, avoids per-call numpy array allocation, and makes intent crisper.

-            def gen_inner_sequence(input_len, idx_offset, random_offset,
-                                   vocab_size):
-                return ((random_offset + idx_offset + np.arange(input_len)) %
-                        vocab_size).tolist()
+            def gen_inner_sequence(input_len: int, idx_offset: int, random_offset: int,
+                                   vocab_size: int) -> list[int]:
+                # Use torch.arange to avoid numpy allocation; returns Python ints via .tolist()
+                return ((random_offset + idx_offset +
+                         torch.arange(input_len, dtype=torch.long)) % vocab_size).tolist()

569-573: Generate only the remaining tokens to reduce re-encode passes and memory churn.

Currently each loop appends a full input_lens[i] chunk, which often overshoots and forces extra decode/encode work. Appending only the deficit typically converges faster.

-                    new_inner_seq = gen_inner_sequence(input_lens[i], i,
-                                                       new_random_offset,
-                                                       vocab_size)
+                    remaining = total_input_len_expected - len(re_encoded_token_ids)
+                    new_inner_seq = gen_inner_sequence(
+                        remaining, i, new_random_offset, vocab_size
+                    )
                     re_encoded_token_ids += new_inner_seq

541-593: Add targeted tests for --random-token-ids to prevent regressions across tokenizers.

Minimal tests should assert that for various vocab sizes and tokenizers (e.g., Qwen2TokenizerFast, LLaMA-based), the produced prompt re-tokenizes to exactly prefix_len + input_len when return_text is both True and False.

I can open a small test PR adding parameterized pytest cases that:

  • seed the dataset,
  • run sample() with/without return_text,
  • re-tokenize returned prompts,
  • assert exact token counts and no infinite loops for edge cases (small vocab, high ratio).

691-693: Optional: decode random token prompts with skip_special_tokens=True for consistency.

Random IDs may include special tokens; decoding them verbatim can introduce artifacts when return_text=True. Using skip_special_tokens=True aligns with the exact-length philosophy elsewhere.

-            if self.return_text:
-                prompt = tokenizer.decode(prompt)
+            if self.return_text:
+                prompt = tokenizer.decode(prompt, skip_special_tokens=True)
📜 Review details

Configuration used: .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 aa0088a and b09be0b.

📒 Files selected for processing (1)
  • tensorrt_llm/serve/scripts/benchmark_dataset.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/serve/scripts/benchmark_dataset.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tensorrt_llm/serve/scripts/benchmark_dataset.py
🧠 Learnings (2)
📓 Common learnings
Learnt from: samuellees
PR: NVIDIA/TensorRT-LLM#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.
📚 Learning: 2025-08-18T08:42:02.640Z
Learnt from: samuellees
PR: NVIDIA/TensorRT-LLM#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:

  • tensorrt_llm/serve/scripts/benchmark_dataset.py
⏰ 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 (1)
tensorrt_llm/serve/scripts/benchmark_dataset.py (1)

561-563: Good: controlling special tokens during decode/encode ensures exact-length behavior.

Using skip_special_tokens=True for decode and add_special_tokens=False for encode aligns with the exact token-length guarantee required under --random-token-ids. Nicely done.

Also applies to: 574-577

@samuellees
Copy link
Collaborator Author

/bot run

1 similar comment
@samuellees
Copy link
Collaborator Author

/bot run

@samuellees
Copy link
Collaborator Author

/bot run

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.

3 participants