You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "grf53 (via GitHub)" <gi...@apache.org> on 2026/01/02 10:38:54 UTC
[PR] [KVCache] Enable sliding window for ragged prefill (`SelfAttention`) [tvm]
grf53 opened a new pull request, #18630:
URL: https://github.com/apache/tvm/pull/18630
## Description
This PR improves the sliding window, previously considered only in `_attention_prefil()` and `_attention_decode()`(`CrossAttention`), to also be applied in the `_attention_prefill_ragged()`(`SelfAttention`) function.
This allows us to calculate the attention value more properly for the requests with long prefill lengths.
## Background
(Note that in TVM, `CrossAttention` refers to the attention of Q in a new seq for K and V already stored in the KV Cache, while `SelfAttention` refers to the self-attention for Q, K, and V within a new seq.)
In layers applying a sliding window in models with SWA (e.g., Mistral) or per-layer SWA (e.g., Gemma 3), the `CrossAttention` uses a function with `sliding_window=True`.
However, `SelfAttention` is not affected by applying sliding window or not in the current implementation. Since the attention of a new seq is the result of merging `SelfAttention` and `CrossAttention`, if the newly input sequence is longer than the sliding window size, the resulting attention cannot be considered appropriate.
In past SWA-based models, their `sliding_window_size`s were often large enough, which may not have been a problem when each prefill input was not long. However, with the advent of per-layer SWA, models using shorter `sliding_window_sizes` (such as gpt-oss with `128`) emerged, and with the prevalence of agentic usage, a single prefill can become very long, which can lead to problems in performance or stability.
## Fixes
In those functions with `sliding_window=True` in `CrossAttention`, the length of the KV chunk to be referenced is adjusted with `sliding_window_offset` and `sink_size` additionally provided in `length_info`, thereby applying the sliding window.
However, `_attention_prefill_ragged()` in `SelfAttention` must apply a sliding window by applying an appropriate causal mask to the given tensors. Currently, `_causal_mask()` only uses the appropriate upper bound condition, forming a lower triangular matrix. To apply a sliding window, a lower bound condition must be added to form a diagonal band matrix.
#### AS-IS
`condition = col <= row`
#### TO-BE
`condition = (col <= row) and (col >= row - window_size)`
However, since the `sliding_window_size` value is not provided for the function, we needed to provide it additionally. (I confirmed that using the `sliding_window_offset` value directly is not appropriate.)
## Notes
There were some hard-coded values for gemma 3 models added in #17928, and I removed them in this PR.
There is a mention of introducing optional parameters for those values, so the way I chose could be not match to the existing plan or intention.
Or there could be a more preferred way to add lower bound condition in causal mask, I think.
Please kindly let me know if there is a comment.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] [KVCache] Enable sliding window for ragged prefill (`SelfAttention`) [tvm]
Posted by "grf53 (via GitHub)" <gi...@apache.org>.
grf53 commented on code in PR #18630:
URL: https://github.com/apache/tvm/pull/18630#discussion_r2661208456
##########
python/tvm/relax/frontend/nn/llm/kv_cache.py:
##########
@@ -860,10 +860,15 @@ def _var(dtype):
return T.alloc_buffer((1,), dtype, scope="local")
-def _causal_mask(causal, row, col, kv_len, qo_len):
+def _causal_mask(causal, row, col, kv_len, qo_len, sliding_window_size=-1):
+ lower_bound_condition = T.if_then_else(
+ sliding_window_size > 0,
+ col >= kv_len - qo_len + row - sliding_window_size,
Review Comment:
This makes a lot of sense, and decreases the errors quite a lot. So let me happily apply this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] [KVCache] Enable sliding window for ragged prefill (`SelfAttention`) [tvm]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #18630:
URL: https://github.com/apache/tvm/pull/18630#discussion_r2657496028
##########
src/runtime/vm/paged_kv_cache.cc:
##########
@@ -1408,8 +1417,8 @@ class PagedAttentionKVCacheObj : public AttentionKVCacheObj {
// The auxiliary data structure on device must have been synchronized.
ICHECK(!dirty_aux_data_device_);
- if (attn_kind == AttnKind::kMHA) {
- MHASelfAttnInternal(q_data, k_data, v_data, o_data, lse_data, sm_scale);
+ if (attn_kind == AttnKind::kMHA || attn_kind == AttnKind::kMHASliding) {
+ MHASelfAttnInternal(layer_id, q_data, k_data, v_data, o_data, lse_data, sm_scale);
Review Comment:

There appears to be a bug here. `MHASelfAttnInternal` expects a `local_layer_id`, but it's being called with the global `layer_id`. The `local_layer_id` is computed on line 1387 but is not used in this call. This will lead to incorrect indexing of `attn_kinds_` inside `MHASelfAttnInternal` and potentially other issues. You should pass `local_layer_id` instead.
```suggestion
MHASelfAttnInternal(local_layer_id, q_data, k_data, v_data, o_data, lse_data, sm_scale);
```
##########
src/runtime/vm/paged_kv_cache.cc:
##########
@@ -766,6 +769,8 @@ class PagedAttentionKVCacheObj : public AttentionKVCacheObj {
// introduce more sink. Therefore, we update the given attn sink size.
it->second.last_block_attn_sink_size = std::max(attn_sink_size - prefix_length, 0);
it->second.sliding_window_size = sliding_window_size;
+ if (sliding_window_size_ == -1)
+ sliding_window_size_ = sliding_window_size;
Review Comment:

This logic to set `sliding_window_size_` is a bit fragile. If `EnableSlidingWindowForSeq` is called for different sequences with different `sliding_window_size` values, only the first one will take effect, and subsequent calls with different sizes will be silently ignored. This could lead to unexpected behavior. To make this assumption explicit and prevent silent errors, I'd suggest adding a check to ensure that all calls use a consistent `sliding_window_size`.
```suggestion
if (sliding_window_size_ == -1) {
sliding_window_size_ = sliding_window_size;
} else {
ICHECK_EQ(sliding_window_size_, sliding_window_size)
<< "Inconsistent sliding window sizes are not supported. Previously got "
<< sliding_window_size_ << ", but now got " << sliding_window_size;
}
```
##########
python/tvm/relax/frontend/nn/llm/kv_cache.py:
##########
@@ -860,10 +860,15 @@ def _var(dtype):
return T.alloc_buffer((1,), dtype, scope="local")
-def _causal_mask(causal, row, col, kv_len, qo_len):
+def _causal_mask(causal, row, col, kv_len, qo_len, sliding_window_size=-1):
+ lower_bound_condition = T.if_then_else(
+ sliding_window_size > 0,
+ col >= kv_len - qo_len + row - sliding_window_size,
Review Comment:

There might be an off-by-one error in the lower bound condition for the sliding window. The condition `col >= kv_len - qo_len + row - sliding_window_size` defines a window of `sliding_window_size + 1` tokens. If the intention is to have a window of exactly `sliding_window_size` tokens, the condition should be `col >= kv_len - qo_len + row - sliding_window_size + 1`. Many models like Mistral define the window as inclusive, resulting in `sliding_window_size + 1` tokens, so this might be correct, but it's worth confirming to ensure it matches the intended behavior of the models this will be used with.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] [KVCache] Enable sliding window for ragged prefill (`SelfAttention`) [tvm]
Posted by "dotcom07 (via GitHub) via discuss-archive" <di...@tvm.apache.org>.
dotcom07 commented on PR #18630:
URL: https://github.com/apache/tvm/pull/18630#issuecomment-7009998409
Hi @grf53, thanks for this fix. The ragged prefill path still lacks the
sliding-window lower bound on main, and per-layer SWA models such as
gpt-oss and Gemma 3 hit it once a prefill chunk exceeds the window.
Are you still planning to continue this PR? The branch now conflicts with
several refactors on main. If you don't have time, would you be OK with me
picking it up in a new PR? I'd credit you as a co-author.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] [KVCache] Enable sliding window for ragged prefill (`SelfAttention`) [tvm]
Posted by "grf53 (via GitHub) via discuss-archive" <di...@tvm.apache.org>.
grf53 commented on PR #18630:
URL: https://github.com/apache/tvm/pull/18630#issuecomment-7029996113
> Hi @grf53, thanks for this fix. The ragged prefill path still lacks the sliding-window lower bound on main, and per-layer SWA models such as gpt-oss and Gemma 3 hit it once a prefill chunk exceeds the window.
>
> Are you still planning to continue this PR? The branch now conflicts with several refactors on main. If you don't have time, would you be OK with me picking it up in a new PR? I'd credit you as a co-author.
Hi, @dotcom07. I am totally fine with you to pick up this. Thank you for discovering this work and continuing it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] [KVCache] Enable sliding window for ragged prefill (`SelfAttention`) [tvm]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #18630:
URL: https://github.com/apache/tvm/pull/18630#issuecomment-3705058291
## Summary of Changes
Hello @grf53, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request significantly enhances the KVCache's ability to handle sliding window attention for large language models, particularly when processing long prefill sequences. By extending sliding window logic to self-attention operations within ragged prefill, it ensures more accurate attention calculations and improves compatibility with models utilizing per-layer sliding window attention, addressing potential performance and stability issues with shorter window sizes.
### Highlights
* **Sliding Window for Ragged Prefill**: Extended sliding window attention to the `_attention_prefill_ragged()` function, which handles self-attention for new sequences, ensuring proper attention calculation for requests with long prefill lengths.
* **Enhanced Causal Masking**: Modified the `_causal_mask` function to incorporate a lower bound condition based on `sliding_window_size`, transforming it into a diagonal band matrix for accurate sliding window application.
* **Dynamic Sliding Window Size**: Introduced `sliding_window_size` as a parameter to relevant attention functions and classes, allowing for dynamic configuration rather than hardcoded values.
* **Gemma 3 Hardcode Removal**: Eliminated specific hard-coded values related to Gemma 3 models, promoting a more generalized and flexible implementation.
🧠**New Feature in Public Preview:** You can now enable **Memory** to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
<details>
<summary><b>Using Gemini Code Assist</b></summary>
<br>
The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
<b>Invoking Gemini</b>
You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
Feature | Command | Description
--- | --- | ---
Code Review | `/gemini review` | Performs a code review for the current pull request in its current state.
Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state.
Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help | `/gemini help` | Displays a list of available commands.
<b>Customization</b>
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
<b>Limitations & Feedback</b>
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
<b>You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the [Gemini Code Assist IDE Extension](https://cloud.google.com/products/gemini/code-assist).</b>
</details>
[^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org