flax icon indicating copy to clipboard operation
flax copied to clipboard

feat(nnx): add preferred_element_type to attention module

Open aarushisingh04 opened this issue 9 months ago • 3 comments

What does this PR do?

adds preferred_element_type parameter to dot_product_attention_weights, dot_product_attention and MultiHeadAttention in flax/nnx/nn/attention.py.

split from #5179 for easier review.

changes:

  • dot_product_attention_weights: forwards preferred_element_type to jnp.einsum
  • dot_product_attention: forwards to both jnp.einsum calls and conditionally applies .astype() only when preferred_element_type is not None
  • MultiHeadAttention.__init__: accepts preferred_element_type and passes it to all LinearGeneral layers (q/k/v/out)
  • MultiHeadAttention.__call__: forwards preferred_element_type to self.attention_fn

tests:

  • adds test_preferred_element_type to attention_test.py

Checklist

  • [ ] This PR fixes a minor issue (e.g.: typo or small bug) or improves the docs (you can dismiss the other checks if that's the case).
  • [ ] This change is discussed in a Github issue/discussion (please add a link).
  • [x] The documentation and docstrings adhere to the documentation guidelines.
  • [x] This change includes necessary high-coverage tests. (No quality testing = no merge!)

aarushisingh04 avatar Feb 15 '26 14:02 aarushisingh04

Summary of Changes

Hello @aarushisingh04, 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 introduces the preferred_element_type parameter across key attention modules within Flax NNX, including dot_product_attention_weights, dot_product_attention, and MultiHeadAttention. This enhancement provides fine-grained control over the numerical precision of dot product computations, which is crucial for optimizing performance and memory usage, especially in mixed-precision training scenarios. The changes ensure that the specified element type is consistently applied throughout the attention mechanism, from weight calculation to output projection.

Highlights

  • Precision Control in Attention Weights: Introduced preferred_element_type to dot_product_attention_weights for jnp.einsum precision control.
  • Precision Control in Dot Product Attention: Enhanced dot_product_attention to accept preferred_element_type, applying it to jnp.einsum operations and conditionally casting the output.
  • MultiHeadAttention Integration: Updated MultiHeadAttention to propagate preferred_element_type to its internal LinearGeneral layers and the attention function.
  • New Test Coverage: Added a new test case test_preferred_element_type to validate the new functionality in attention_test.py.

🧠 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 to enable Memory in your admin console.

Changelog
  • flax/nnx/nn/attention.py
    • Added preferred_element_type parameter to dot_product_attention_weights function signature and docstring.
    • Modified jnp.einsum calls in dot_product_attention_weights to accept preferred_element_type.
    • Added preferred_element_type parameter to dot_product_attention function signature and docstring.
    • Updated dot_product_attention to conditionally cast its output to preferred_element_type if specified.
    • Modified jnp.einsum calls in dot_product_attention to accept preferred_element_type.
    • Added preferred_element_type parameter to MultiHeadAttention.__init__ and stored it as an instance attribute.
    • Passed preferred_element_type to the LinearGeneral layers (query, key, value, output) within MultiHeadAttention.__init__.
    • Forwarded self.preferred_element_type to the attention_fn call within MultiHeadAttention.__call__.
  • tests/nnx/nn/attention_test.py
    • Added test_preferred_element_type to verify that MultiHeadAttention correctly utilizes the preferred_element_type parameter.
Activity
  • No human activity (comments, reviews, or progress updates) was detected for this pull request.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

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.

Customization

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.

Limitations & Feedback

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.

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.

[^1]: Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

gemini-code-assist avatar Feb 15 '26 14:02 gemini-code-assist

We already have precision to control the op precision and dtype to control the param precision. What's a use case for this additional API?

Good point. It seems like these parameters cover the use case for a preferred_element_type parameter. @aarushisingh04 does that make sense to you?

samanklesaria avatar Apr 27 '26 19:04 samanklesaria

@IvyZX @samanklesaria

thank you for reviewing, i'll address the mentioned points below-

i believe precision and dtype don't cover this use case. precision controls how carefully the hardware computes (e.g. HIGHEST uses more precise accumulators) but does not change the output dtype, as with bfloat16 inputs and precision=Precision.HIGHEST, you still get bfloat16 attention weights back.

dtype promotes the inputs before the einsum but similarly doesn't let you accumulate in a higher dtype. so, preferred_element_type is the only way to get float32 attention logits when inputs are bfloat16, without manually inserting .astype() calls or casting the entire Q/K/V tensors to float32. this is the same design choice FlashAttention makes for numerical stability.

just as a note, the motivation behind this PR was that preferred_element_type was already added to nnx.Linear*, nnx.Conv*, and nnx.Einsum in PR #4920, included in the Flax 0.12.0 release. this PR meant to extend the same pattern to MultiHeadAttention which was not covered by #4920.

if the pr is green-lighted after this discussion i will fix the docstrings (which currently incorrectly describe it as "numerical precision")

  • preferred_element_type: numerical precision of the computation, see jax.lax.dot_general for details.

to a more accurate description

  • preferred_element_type: Optional parameter controls the data type output by the dot product. This argument is passed to dot_general function. See jax.lax.dot for details.

and strengthen the tests to cover the mixed-precision use case.

aarushisingh04 avatar Apr 28 '26 16:04 aarushisingh04