KEMBAR78
[TRTLLM-8348][feat] Speed up concat k and copy k_nope in context phase using torch.compile by yuantailing · Pull Request #8044 · NVIDIA/TensorRT-LLM · GitHub
Skip to content

Conversation

@yuantailing
Copy link
Member

@yuantailing yuantailing commented Sep 28, 2025

Benchmark for DeepSeek-R1 with 8K-1K random dataset on context servers:

Each layer Copy kernel name Copy time
Original 7829us direct_copy_kernel_cuda 306us
Use torch.compile 7656us (-2.2%) triton_poi_fused_copy_0 107us

Please be aware that I have checked that although the time for Copy is reduced for 199us, the time for MLA.forward_impl as well as the time for each layer are not reduced for so much.

Summary by CodeRabbit

  • Refactor
    • Optimized attention operations to reduce overhead during context processing and chunked prefill, improving throughput and latency on supported runtimes.
    • Streamlined internal data movement and tensor concatenation for more consistent performance on large inputs.
    • No changes to user-facing APIs or model outputs; gains are performance-focused only.

Description

Test Coverage

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.

Signed-off-by: Tailing Yuan <yuantailing@gmail.com>
@yuantailing yuantailing requested a review from a team as a code owner September 28, 2025 10:38
@yuantailing
Copy link
Member Author

/bot run

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 28, 2025

📝 Walkthrough

Walkthrough

Adds two torch.compile-wrapped helper functions for copy and concatenation, and updates attention forward paths to use these helpers instead of direct in-place copy_ and torch.cat calls.

Changes

Cohort / File(s) Summary
Compiled helper utilities
tensorrt_llm/_torch/modules/attention.py
Added compiled_copy_(dst, src) and compiled_cat(tensors, dim) using torch.compile to wrap copy_ and torch.cat.
Attention forward path updates
tensorrt_llm/_torch/modules/attention.py
Replaced direct k copy with compiled_copy_ in forward_context_default. Replaced multiple torch.cat usages with compiled_cat in forward_context_with_cached_kv and forward_context_with_chunked_prefill (including chunked_k concatenations).

Sequence Diagram(s)

sequenceDiagram
  participant Attn as Attention
  participant CC as compiled_copy_
  participant CAT as compiled_cat

  rect rgb(245,248,255)
    note over Attn: forward_context_default
    Attn->>CC: copy_(k_nope → k)
    CC-->>Attn: k updated
  end

  rect rgb(245,255,245)
    note over Attn: forward_context_with_cached_kv
    Attn->>CAT: cat([k_nope, k_pe.expand(...)], dim)
    CAT-->>Attn: concatenated k
  end

  rect rgb(255,248,245)
    note over Attn: forward_context_with_chunked_prefill
    Attn->>CAT: cat([full_k_nope, full_k_pe.expand(...)], dim)
    CAT-->>Attn: full_k concatenated
    Attn->>CAT: cat(chunked_k parts, dim)
    CAT-->>Attn: chunked_k concatenated
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The pull request description does not follow the repository’s template because it lacks the required formatted title with the “[JIRA ticket/...][type] Summary” pattern, leaves the “## Description” and “## Test Coverage” sections empty, and presents benchmark results outside the designated sections, reducing clarity and consistency. Please add a properly formatted title at the top following the template guidelines, complete the “## Description” section with a concise explanation of the issue and the implemented solution, populate the “## Test Coverage” section with details of the relevant tests, and relocate the benchmark table into the Description or a dedicated Results subsection for coherence, then review and adjust the PR Checklist to accurately reflect the changes made.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly identifies the JIRA ticket, specifies the feature type, and clearly describes the primary change of using torch.compile to speed up concat and copy operations in the context phase, making it both concise and aligned with the repository’s title conventions.
✨ 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

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

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20169 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20169 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15208 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@kaiyux kaiyux requested a review from yuxianq September 29, 2025 03:16
@yuxianq
Copy link
Collaborator

yuxianq commented Sep 29, 2025

@yuantailing I am curious about in which case compiled cat/copy can improve perf? strided layout?

@yuantailing
Copy link
Member Author

Yes, compiled cat/copy improves perf when layout is strided.

For cat(a, b), if both a and b are contiguous, torch calls CatArrayBatchedCopy_alignedK_contig which is fast; if a or b is strided, torch calls CatArrayBatchedCopy which is slower than the compiled kernel.

For a.copy_(b), direct_copy_kernel_cuda is always strided or torch will call cudaMemcpy.

@yuxianq yuxianq merged commit 985b79c into NVIDIA:main Sep 29, 2025
12 of 13 checks passed
@yuantailing yuantailing deleted the compile_concat_k branch September 29, 2025 05:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants