Skip to content

GQA without kv repeats - #2259

Merged
tianyu-l merged 17 commits into
pytorch:mainfrom
francesco-bertolotti:f14-norepeat-gqa
Jan 27, 2026
Merged

tianyu-l merged 17 commits into
pytorch:mainfrom
francesco-bertolotti:f14-norepeat-gqa

Conversation

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator

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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jan 20, 2026
Comment thread torchtitan/models/attention.py Outdated
head_dim: torch.Tensor,
attention_masks: VarlenMetadata,
scale: float | None = None,
return_lse: bool = False,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

No particular reason; it felt like it could become useful in the future.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If no immediate use cases, can we revert this change and keep this PR focus on GQA?

@liangel-02 liangel-02 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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?

@tianyu-l tianyu-l linked an issue Jan 20, 2026 that may be closed by this pull request
Comment thread torchtitan/models/attention.py Outdated
head_dim: torch.Tensor,
attention_masks: VarlenMetadata,
scale: float | None = None,
return_lse: bool = False,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If no immediate use cases, can we revert this change and keep this PR focus on GQA?

Comment thread torchtitan/models/qwen3/model/model.py Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@drisspg Do all SDPA kernels support this feature? Just want to confirm.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Then I propose that we remove Efficient attention from TorchTitan and keep math for any hardware that doesn't have the right fuse kernel.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I remember @XilunWu mentioning something around this, but we didn't sync up more about the issues. I can check with him offline

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator Author

@fegin, I have remove return_lse
@liangel-02 , I have updated llama3 consistently with wath I did with qwen3.
Here's the plots comparing varlen/flex+llama3/qwen3

Screenshot 2026-01-21 at 19 49 57

).transpose(1,2).contiguous() # (bs, seqlen, n_local_heads, head_dim)
case "varlen":
assert isinstance(attention_masks, VarlenMetadata), attention_masks
output = self.inner_attention(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

cc @liangel-02 yeah we this was a kwarg that needs to be added to varlen for consistency

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator Author

As suggested by @tianyu-l , I moved the enable_gqa flag computation in the __init__ function of the attention layer.

@voidbag voidbag left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

  1. 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.
  2. 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. :)

Comment thread torchtitan/models/llama3/model/model.py Resolved
Comment thread torchtitan/models/qwen3/model/model.py Resolved
Comment thread torchtitan/models/llama3/model/model.py Resolved
Comment thread torchtitan/models/llama3/model/model.py Resolved
Comment on lines -65 to -77
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread torchtitan/models/qwen3/model/model.py Resolved
Comment thread torchtitan/models/qwen3/model/model.py Resolved
Comment thread torchtitan/models/llama3/model/model.py Resolved
Comment thread torchtitan/models/attention.py Resolved
@francesco-bertolotti

francesco-bertolotti commented Jan 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

@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

@voidbag

voidbag commented Jan 24, 2026

Copy link
Copy Markdown
Contributor

@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.

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:
Co-authored-by: Taeksang Kim [email protected]

Looking forward to the results of your local tests!

@voidbag

voidbag commented Jan 24, 2026 •

Copy link
Copy Markdown
Contributor

@francesco-bertolotti
I’ve been working on the zero-copy GQA for llama4 and gpt-oss on top of your branch!

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

@voidbag

voidbag commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor

@francesco-bertolotti

  1. lint error
    The command CI executed in https://github.com/pytorch/torchtitan/actions/runs/21314690407/job/61372598725?pr=2259#step:7:2 is here

    pre-commit run --files torchtitan/models/attention.py torchtitan/models/llama3/model/model.py torchtitan/models/qwen3/model/model.py

    You can install pre-commit via pip and execute the same command the CI did.

    pip install pre-commit && pre-commit run --files torchtitan/models/attention.py torchtitan/models/llama3/model/model.py torchtitan/models/qwen3/model/model.py
    # add other files you want

    Or, you can pre-commit check between main branch and your current branch HEAD

    #pip install pre-commit
    pre-commit run --from-ref main --to-ref HEAD

    To pass lint check, you can run this command and fix it!, I think my added suggestion format and comments lead to lint failure. It would be better for you to run pre-commit, instead of my re-suggestion. Sorry for the inconvenience.

  2. deepseek v3 error
    By the way, I don't still understand the deepseek_v3 error which we didn't touch.
    [updated]
    I think other PRs seem to have same issue. It might be an CI issue.

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator Author

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.

gptoss-llama4-nogqarepeats

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@voidbag

voidbag commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor

@tianyu-l
What do you think about implementing a wrapper like below codes, instead of discarding enable_gqa in sdpa totally.
If enable_gqa isn't required, the wrapper just doesn't use it.
But enable_gqa param seems only used in math, even if the api signature like this and some attention op support gqa handling the discrepancy btw n_kv_heads and n_q_heads automatically.

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.
https://github.com/pytorch/pytorch/blob/b731ffe3467840e1b6da911487310944be4f1687/aten/src/ATen/native/transformers/attention.cpp#L718-L848

  ...
  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));
    }
    ...
  }

@wwwjn wwwjn mentioned this pull request Jan 27, 2026
@fegin

fegin commented Jan 27, 2026

Copy link
Copy Markdown
Contributor

We can just remove efficient kernel. It doesn't support GQA, it doesn't work well with CP (numerical issue).

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator Author

Hi @fegin ,

Sorry for the delay, I have removed the efficient kernel.

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

sgtm, thank you!

@tianyu-l
tianyu-l merged commit ff0829c into pytorch:main Jan 27, 2026
wwwjn added a commit that referenced this pull request Jan 29, 2026
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
wwwjn added a commit that referenced this pull request Jan 30, 2026
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]
wwwjn added a commit that referenced this pull request Feb 2, 2026
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
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
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]>
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
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
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
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]>
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Efficiency Issue with Qwen3 attention module

8 participants