flax icon indicating copy to clipboard operation
flax copied to clipboard

feat(nnx): Expose GQA support (num_key_value_heads) in MultiHeadAttention

Open ayushkumrdev opened this issue 10 months ago • 6 comments

Problem

PR #5180 adds GQA support to the functional nnx.dot_product_attention. However, the nnx.MultiHeadAttention module currently enforces symmetry, hardcoding Key/Value projections to num_heads:

https://github.com/google/flax/blob/main/flax/nnx/nn/attention.py#L380

This makes it impossible to define GQA layers (e.g., Llama 3 with 32 query heads and 8 KV heads) using the standard Module API.

Note: This implementation depends on the functional changes in PR #5180 and should be addressed after that PR is merged.

Proposed Solution

Update MultiHeadAttention to accept num_key_value_heads.

1. API Changes (__init__)

Add num_key_value_heads (defaulting to None for backward compatibility).

class MultiHeadAttention(Module):
  def __init__(
    self,
    num_heads: int,
    in_features: int,
    qkv_features: int | None = None,
    num_key_value_heads: int | None = None,  # New Arg
    # ... existing args
  ):
    self.num_heads = num_heads
    self.num_key_value_heads = num_key_value_heads if num_key_value_heads is not None else num_heads

    # ... feature validation ...
    
    # GQA Validation
    if self.num_heads % self.num_key_value_heads != 0:
        raise ValueError(f"num_heads ({self.num_heads}) must be divisible by num_key_value_heads ({self.num_key_value_heads})")

    head_dim = self.qkv_features 

    # Projections
    self.query = Linear(in_features, self.num_heads * head_dim, ...)
    # Key/Value utilize the reduced head count
    self.key = Linear(in_features, self.num_key_value_heads * head_dim, ...) 
    self.value = Linear(in_features, self.num_key_value_heads * head_dim, ...)
    
    # Output projection aggregates all Query heads (unchanged)
    self.out = Linear(self.num_heads * head_dim, out_features, ...)

ayushkumrdev avatar Jan 22 '26 20:01 ayushkumrdev

I can pick this up. This depends on the functional GQA support in PR #5180, so I will start on this once that merges.

ayushkumrdev avatar Jan 22 '26 20:01 ayushkumrdev

This makes sense to me. I'll ask @cgarciae to make sure, but I think this would be a good addition.

samanklesaria avatar Jan 23 '26 13:01 samanklesaria

Thanks @samanklesaria!

I also caught a logic error in my proposal snippet above regarding head_dim. In Flax, qkv_features typically represents the total dimension, not the per-head dimension.

I will ensure the PR implementation uses the standard calculation: head_dim = self.qkv_features // self.num_heads

This ensures the projection sizes remain consistent with the standard MultiHeadAttention behavior. I'll open the PR as soon as #5180 is merged.

ayushkumrdev avatar Jan 24 '26 04:01 ayushkumrdev

@samanklesaria updates on this should i feel free to open a PR

ayushkumrdev avatar Feb 17 '26 18:02 ayushkumrdev

@ayulockedin yes, open a PR!

samanklesaria avatar Feb 17 '26 20:02 samanklesaria

@samanklesaria so i have been researching in MHLA( Multi-Head Latent Attention) would this addition be feasible for upgrading flax framework just want your views after GQA just an idea wanted your opinion

ayushkumrdev avatar Apr 12 '26 19:04 ayushkumrdev