Skip to content

Conversation

@Liu-congo
Copy link
Contributor

@Liu-congo Liu-congo commented Oct 1, 2025

Purpose

FIX #25705

Method

  • the shape of key/value is: num_tokens * num_heads * head_size
  • the shape of key_cache is: num_blocks * num_heads * (head_size // x) * block_size * x
  • the shape of value_cache is: num_blocks * num_heads * head_size * block_size

then i viewed them in shape as:

  • the shape of key/value is: num_tokens * num_heads * (head_size // x) * x
  • the shape of key_cache is: num_blocks * num_heads * (head_size // x) * block_size * x
  • the shape of value_cache is: num_blocks * num_heads * (head_size// x) * x * block_size

that is to say that if we start the kernel in config as grid(num_tokens), block(num_heads * head_size // x)
we process each token's kv_cache in a block
the block size is num_heads * head_size // x
so by the threadIdx we could read a contiguous x elements in key/value
then apply vectorize op in key_cache and use naive loop method for value_cache
that's how it worked

I doubt whether there are efficient scatter kernel in cuda that can speed up the value_cache's op, cause value_cache need's to
fill in the data in a stride of block_size for every element, maybe there still potential for speeding up?

Test Plan

for time cost test, i add a benchmark_reshape_and_cache.py into benchmark/kernels, which almost copy the benchmark/kernels/benchmark_reshape_and_cache_flash.py

for accuary test, it has been implemented in tests/kernels/attention/test_cache.py::test_reshape_and_cache
the kernel implemented can passed it fully

Test Result

python benchmark/kernels/benckmark_reshape_and_cache.py --num-heads 64 --head-size 64

num_tokens latency_old (µs) latency_new (µs) Change (%)
2 10.548 11.796 +11.83%
4 10.297 11.178 +8.56%
8 10.355 11.196 +8.12%
16 10.087 12.026 +19.22%
32 10.934 12.105 +10.71%
64 12.617 15.353 +21.68%
128 19.795 23.331 +17.86%
256 49.896 52.235 +4.69%
512 134.205 124.531 -7.21%
1024 280.939 250.043 -11.00%
2048 596.014 529.813 -11.11%
4096 1196.63 1057.45 -11.63%
8192 2375.14 2096.88 -11.72%
16384 4730.87 4178.63 -11.67%
32768 9476.05 8334.58 -12.05%
65536 18945 16653 -12.10%

Essential Elements of an Effective PR Description Checklist
  • [ x ] The purpose of the PR, such as "Fix some issue (link existing issues this PR will resolve)".
  • [ x ] The test plan, such as providing test command.
  • [ x ] The test results, such as pasting the results comparison before and after, or e2e results
  • (Optional) The necessary documentation update, such as updating supported_models.md and examples for a new model.
  • (Optional) Release notes update. If your change is user facing, please update the release notes draft in the Google Doc.

@github-actions
Copy link

github-actions bot commented Oct 1, 2025

👋 Hi! Thank you for contributing to the vLLM project.

💬 Join our developer Slack at https://slack.vllm.ai to discuss your PR in #pr-reviews, coordinate on features in #feat- channels, or join special interest groups in #sig- channels.

Just a reminder: PRs would not trigger full CI run by default. Instead, it would only run fastcheck CI which starts running only a small and essential subset of CI tests to quickly catch errors.

You ask your reviewers to trigger select CI tests on top of fastcheck CI.

Once the PR is approved and ready to go, your PR reviewer(s) can run CI to test the changes comprehensively before merging.

To run CI, PR reviewers can either: Add ready label to the PR or enable auto-merge.

If you have any questions, please reach out to us on Slack at https://slack.vllm.ai.

🚀

@mergify mergify bot added the performance Performance-related issues label Oct 1, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request optimizes the reshape_and_cache CUDA kernel by altering the parallelization strategy, which results in significant performance gains for large token counts as demonstrated by the provided benchmarks. The new approach vectorizes key_cache updates. My review identified a critical issue where the complex index calculations for key_cache and value_cache could lead to integer overflow with large tensor dimensions, potentially causing memory corruption. I have provided a code suggestion to resolve this by pre-calculating strides using int64_t, which also enhances code readability.

Comment on lines 257 to 264
cache_t* __restrict__ key_dst = key_cache + block_idx * num_heads * h_block_count * block_size * x
+ head_idx * h_block_count * block_size * x
+ h_block * block_size * x
+ block_offset * x;
const int64_t tgt_value_start = block_idx * num_heads * h_block_count * x * block_size
+ head_idx * h_block_count * x * block_size
+ h_block * x * block_size
+ block_offset;
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The index calculations for key_dst and tgt_value_start are susceptible to integer overflow. The intermediate products like num_heads * h_block_count * block_size * x are computed using int types. With large tensor dimensions, this could overflow, leading to incorrect memory addressing and potential data corruption.

To prevent this and improve readability, I suggest pre-calculating the strides for each dimension using int64_t before computing the final offsets.

  const int64_t key_h_block_stride = (int64_t)block_size * x;
  const int64_t key_head_stride = (int64_t)h_block_count * key_h_block_stride;
  const int64_t key_block_stride = (int64_t)num_heads * key_head_stride;
  cache_t* __restrict__ key_dst = key_cache + block_idx * key_block_stride
                              + head_idx * key_head_stride
                              + h_block * key_h_block_stride
                              + block_offset * x;

  const int64_t val_h_block_stride = (int64_t)x * block_size;
  const int64_t val_head_stride = (int64_t)h_block_count * val_h_block_stride;
  const int64_t val_block_stride = (int64_t)num_heads * val_head_stride;
  const int64_t tgt_value_start = block_idx * val_block_stride
                                + head_idx * val_head_stride
                                + h_block * val_h_block_stride
                                + block_offset;

Signed-off-by: Liu-congo <1502632128@qq.com>
@Liu-congo Liu-congo closed this Oct 2, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Performance-related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: [Perf] Optimize reshape_and_cache CUDA Kernel

1 participant