Repository navigation
GQA without kv repeats - #2259
Conversation
| head_dim: torch.Tensor, | ||
| attention_masks: VarlenMetadata, | ||
| scale: float | None = None, | ||
| return_lse: bool = False, |
There was a problem hiding this comment.
Curious why we need this flag here? To align with FlexAttention APIs? From what I read, the return_lse flag is only used for gpt-oss attention sink for now, are you trying to apply attention sink?
There was a problem hiding this comment.
No particular reason; it felt like it could become useful in the future.
There was a problem hiding this comment.
If no immediate use cases, can we revert this change and keep this PR focus on GQA?
liangel-02
left a comment
There was a problem hiding this comment.
ty for these changes, do u mind updating the varlen logic for llama3 too and also providing the loss curves compared to flex for both models?
| head_dim: torch.Tensor, | ||
| attention_masks: VarlenMetadata, | ||
| scale: float | None = None, | ||
| return_lse: bool = False, |
There was a problem hiding this comment.
If no immediate use cases, can we revert this change and keep this PR focus on GQA?
| xk.transpose(1, 2), # (bs, n_kv_heads, seqlen, head_dim) | ||
| xv.transpose(1, 2), # (bs, n_kv_heads, seqlen, head_dim) | ||
| scale=self.scaling, | ||
| enable_gqa=self.n_heads > self.n_kv_heads |
There was a problem hiding this comment.
@drisspg Do all SDPA kernels support this feature? Just want to confirm.
There was a problem hiding this comment.
So all backends but Efficient Attention support this flag. This was in part the reason why we never just globally switched since users w/ attn_bias would not get gqa support. For torch titan I dont think this is still used and if so cudnn does not supprot bias + gqa setting
There was a problem hiding this comment.
TorchTitan still set efficient attention and math attention as the kernel options. Some users argue that we need to preserve these so that different hardwares can be used with TorchTitan. We should consider to remove the two kernels from TrochTitan.
cc., @tianyu-l
There was a problem hiding this comment.
As long as you dont force Efficient attention you can still use the GQA flag it will just fall back to the math impl. Im not sure though that is the behavior you want
There was a problem hiding this comment.
Then I propose that we remove Efficient attention from TorchTitan and keep math for any hardware that doesn't have the right fuse kernel.
There was a problem hiding this comment.
I used to remember that math attention doesn't play well with DTensor, because when you do is_causal in math attention, there will be a plain tensor for mask generated in the kernel, and we will get mixed DTensor and plain tensor issue. Is that fixed @bdhirsh ?
There was a problem hiding this comment.
I remember @XilunWu mentioning something around this, but we didn't sync up more about the issues. I can check with him offline
There was a problem hiding this comment.
Actually @tianyu-l is there a github issue or repro somewhere I can take a look at? I tried to get claude to generate a repro but I couldn't get SDPA + math backend with DTensor inputs to error.
There was a problem hiding this comment.
I could not reproduce any issue with MATH backend. But anyway, we should remove EFFICIENT backend, it doesn't support GQA, it doesn't work well with CP.
|
@fegin, I have remove
|
| ).transpose(1,2).contiguous() # (bs, seqlen, n_local_heads, head_dim) | ||
| case "varlen": | ||
| assert isinstance(attention_masks, VarlenMetadata), attention_masks | ||
| output = self.inner_attention( |
There was a problem hiding this comment.
Does varlen not need the enable_gqa flag?
nit comment: anyway I think we should set enable_gqa=self.n_heads > self.n_kv_heads outside the match case.
There was a problem hiding this comment.
Don't think so. To my understanding varlen under the hood calls flash-attn which does not have the enable_gqa flag. From the docs, it says that if the KV heads are fewer than Q heads then it uses GQA.
There was a problem hiding this comment.
cc @liangel-02 yeah we this was a kwarg that needs to be added to varlen for consistency
|
As suggested by @tianyu-l , I moved the |
There was a problem hiding this comment.
You've done great job! I was also handling it about this issue to implement zero-copy.
Before this PR is about to be merged, I have left some comments.
- I think keeping the parameter shape/size of q, k, v convention (bs, n_heads, seqlen, head_dim) for attention in the perspective of abstract function or virtual function of software design.
- I guess you have changed attention.py file, because you might think reshape incurs a copy. The reshape op about contiguous tensor doesn't trigger copy like view as far as I know. Even if there is no copy, I added the code using flatten which you used instead of reshape.
P.S Actually, I think flatten also triggers copy if a tensor isn't contiguous. :)
| cu_seq_q = attention_masks.cu_seq_q | ||
| cu_seq_k = attention_masks.cu_seq_k | ||
| max_q = attention_masks.max_q | ||
| max_k = attention_masks.max_k | ||
|
|
||
| n_local_heads = xq.shape[1] | ||
| # pyrefly: ignore [no-matching-overload] | ||
| xq_packed = xq.transpose(1, 2).reshape(-1, n_local_heads, head_dim) | ||
| # pyrefly: ignore [no-matching-overload] | ||
| xk_packed = xk.transpose(1, 2).reshape(-1, n_local_heads, head_dim) | ||
| # pyrefly: ignore [no-matching-overload] | ||
| xv_packed = xv.transpose(1, 2).reshape(-1, n_local_heads, head_dim) | ||
|
|
There was a problem hiding this comment.
| cu_seq_q = attention_masks.cu_seq_q | |
| cu_seq_k = attention_masks.cu_seq_k | |
| max_q = attention_masks.max_q | |
| max_k = attention_masks.max_k | |
| n_local_heads = xq.shape[1] | |
| # pyrefly: ignore [no-matching-overload] | |
| xq_packed = xq.transpose(1, 2).reshape(-1, n_local_heads, head_dim) | |
| # pyrefly: ignore [no-matching-overload] | |
| xk_packed = xk.transpose(1, 2).reshape(-1, n_local_heads, head_dim) | |
| # pyrefly: ignore [no-matching-overload] | |
| xv_packed = xv.transpose(1, 2).reshape(-1, n_local_heads, head_dim) | |
| cu_seq_q = attention_masks.cu_seq_q | |
| cu_seq_k = attention_masks.cu_seq_k | |
| max_q = attention_masks.max_q | |
| max_k = attention_masks.max_k | |
| # pyrefly: ignore [no-matching-overload] | |
| xq_packed = xq.transpose(1, 2).flatten(0, 1) # (bs * seqlen, n_heads, head_dim) | |
| # pyrefly: ignore [no-matching-overload] | |
| xk_packed = xk.transpose(1, 2).flatten(0, 1) # (bs * seqlen, n_kv_heads, head_dim) | |
| # pyrefly: ignore [no-matching-overload] | |
| xv_packed = xv.transpose(1, 2).flatten(0, 1) # (bs * seqlen, n_kv_heads, head_dim) | |
There was a problem hiding this comment.
tensor 'a' with the size (bs, seq_len, n_heads, head_dim) and contiguous stride.
a = a.transpose(1, 2) # (bs, n_heads, seq_len, head_dim): zero-copied "Non-Contitiguous" view with just updated metadata and shared storage.
a_packed = a.transpose(1, 2) # (bs, seq_len, n_heads, head_dim): zero-copied "Contiguous" view with just updated metadata and shared storage.
a_packed = a_packed.flatten(0, 1) # (bs * seq_len, n_heads, head_dim): zero-copied "Contiguous" view with just updated metadata and shared storage.
So there is no copy with this. I think it might be better to keep attention q, k, v shape/size convention like cpp virtual function.
|
@voidbag, thanks for the comments. They seems reasonable to me. I am committing your suggestions. I will test then locally in a few minutes. update Github is not letting me committing all your suggestion, so I will apply the last two myself. update Tests seems ok. SDPA/Flex/Varlen behaving the same |
Co-authored-by: Taeksang Kim <[email protected]>
Co-authored-by: Taeksang Kim <[email protected]>
Co-authored-by: Taeksang Kim <[email protected]>
Co-authored-by: Taeksang Kim <[email protected]>
Co-authored-by: Taeksang Kim <[email protected]>
Co-authored-by: Taeksang Kim <[email protected]>
Co-authored-by: Taeksang Kim <[email protected]>
Thanks for incorporating those suggestions! If you're adding me as a co-author on the commit, could you please use my professional email ([email protected]) instead of my personal Gmail? You can add this to the bottom of the commit message: Looking forward to the results of your local tests! |
Co-authored-by: Taeksang Kim <[email protected]>
3fc59a9 to
f00ad5a
Compare
|
@francesco-bertolotti I'm happy to either have these merged into this PR to keep the GQA changes unified, or I can hold them for a follow-up PR if you'd prefer to keep this one focused on Qwen3. If you want to include them now, you can find the commits here (starting from 73574a0): https://github.com/voidbag/torchtitan/tree/f14-norepeat-gqa Let me know what you prefer! The start commit is commit 73574a07a8982a8432aef949a735998a8425ce62
Author: Taeksang Kim <[email protected]>
Date: Sat Jan 24 21:12:59 2026 +0900
llama3: Modify comments n_heads -> n_local_heads
The repository link is here https://github.com/voidbag/torchtitan/tree/f14-norepeat-gqa |
|
Signed-off-by: Taeksang Kim <[email protected]>
Signed-off-by: Taeksang Kim <[email protected]>
|
I applied commits from @voidbag to remove repeated components in the LLaMA-4 and GPT-OSS architectures. The only issue encountered was a minor variable-naming mismatch. Below is a comparison plot showing the architectures before and after the commits.
|
tianyu-l
left a comment
There was a problem hiding this comment.
For sdpa, we need to remove this line, efficient attention backend, because it doesn't support enable_gqa=True.
https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/attention.py#L175
|
@tianyu-l Tensor scaled_dot_product_attention(
const Tensor& query_,
const Tensor& key,
const Tensor& value,
const std::optional<Tensor>& attn_mask_,
double dropout_p,
bool is_causal,
std::optional<double> scale,
bool enable_gqa)The reference code is here. ...
switch (backend) {
case SDPBackend::cudnn_attention: {
bool compute_logsumexp = should_compute_logsumexp(query_, key, value);
auto out_lse_softmax = at::_scaled_dot_product_cudnn_attention(
query_, key, value, attn_mask, compute_logsumexp, dropout_p, is_causal, false /*return_debug_mask*/, scale);
return std::get<0>(out_lse_softmax);
}
case SDPBackend::flash_attention: {
if(query_device_type == DeviceType::CUDA ||
query_device_type == DeviceType::XPU) {
c10::SymInt og_size = query_.sym_size(-1);
int alignment_size = (query_device_type == DeviceType::XPU) ? 64 : 8;
Tensor query_padded = pad_last_dim<false>(query_, alignment_size);
Tensor key_padded = pad_last_dim<false>(key, alignment_size);
Tensor value_padded = pad_last_dim<false>(value, alignment_size);
// We need to calculate the scale based off the OG head dim size
auto og_scale = sdp::calculate_scale(query_, scale);
auto out_lse_softmax = at::_scaled_dot_product_flash_attention(
query_padded, key_padded, value_padded, dropout_p, is_causal, false /*return_debug_mask*/, og_scale.guard_float("attention.cpp", 735));
return post_process_flash_output(std::get<0>(out_lse_softmax), og_size);
}
// For the CPU case we do not need to pad the last dim
return std::get<0>(at::_scaled_dot_product_flash_attention_for_cpu(
query_, key, value, dropout_p, is_causal, attn_mask, scale));
}
case SDPBackend::efficient_attention: {
bool compute_logsumexp = should_compute_logsumexp(query_, key, value);
if (attn_mask.has_value()) {
attn_mask.value() = preprocess_mask(attn_mask.value(), query_, key, value);;
}
auto out_and_lse = at::_scaled_dot_product_efficient_attention(
query_, key, value, attn_mask, compute_logsumexp, dropout_p, is_causal, scale);
return std::get<0>(out_and_lse);
}
...
case SDPBackend::math: {
return std::get<0>(at::_scaled_dot_product_attention_math(
query_,
key,
value,
attn_mask,
dropout_p,
is_causal,
std::nullopt, /*dropout_mask*/
scale,
enable_gqa));
}
...
} |
|
We can just remove efficient kernel. It doesn't support GQA, it doesn't work well with CP (numerical issue). |
|
Hi @fegin , Sorry for the delay, I have removed the efficient kernel. |
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at bottom): * #2292 * __->__ #2291 Following #2259 Context: Fix RL attention implementation, add numerics check scripts comparing torchtitan Qwen3 model (with vllm wrapper) and vllm native Qwen3 model NOTE: I tried enabling CI for this work, but need more efforts install vllm from source code (need to build vllm from scratch). Will enable CI in later PRs
Following #2259 Context: Fix RL attention implementation, add numerics check scripts comparing torchtitan Qwen3 model (with vllm wrapper) and vllm native Qwen3 model NOTE: I tried enabling CI for this work, but need more efforts install vllm from source code (need to build vllm from scratch). Will enable CI in later PRs [ghstack-poisoned]
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at bottom): * #2300 * __->__ #2299 Following #2259 Context: Fix RL attention implementation, add numerics check scripts comparing torchtitan Qwen3 model (with vllm wrapper) and vllm native Qwen3 model NOTE: I tried enabling CI for this work, but need more efforts install vllm from source code (need to build vllm from scratch). Will enable CI in later PRs
PR for pytorch#2224 This is a first tentative commit for the GQA attention without extra transpose and repeats. @tianyu-l, please let me know what you think. Since I changed the attention wrappers I can also check if other architecture are affected. --------- Signed-off-by: Taeksang Kim <[email protected]> Co-authored-by: Taeksang Kim <[email protected]> Co-authored-by: Taeksang Kim <[email protected]>
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at bottom): * pytorch#2300 * __->__ pytorch#2299 Following pytorch#2259 Context: Fix RL attention implementation, add numerics check scripts comparing torchtitan Qwen3 model (with vllm wrapper) and vllm native Qwen3 model NOTE: I tried enabling CI for this work, but need more efforts install vllm from source code (need to build vllm from scratch). Will enable CI in later PRs
PR for pytorch#2224 This is a first tentative commit for the GQA attention without extra transpose and repeats. @tianyu-l, please let me know what you think. Since I changed the attention wrappers I can also check if other architecture are affected. --------- Signed-off-by: Taeksang Kim <[email protected]> Co-authored-by: Taeksang Kim <[email protected]> Co-authored-by: Taeksang Kim <[email protected]>
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at bottom): * pytorch#2300 * __->__ pytorch#2299 Following pytorch#2259 Context: Fix RL attention implementation, add numerics check scripts comparing torchtitan Qwen3 model (with vllm wrapper) and vllm native Qwen3 model NOTE: I tried enabling CI for this work, but need more efforts install vllm from source code (need to build vllm from scratch). Will enable CI in later PRs


PR for #2224
This is a first tentative commit for the GQA attention without extra transpose and repeats. @tianyu-l, please let me know what you think. Since I changed the attention wrappers I can also check if other architecture are affected.