feat(nnx): add preferred_element_type to attention module
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: forwardspreferred_element_typetojnp.einsumdot_product_attention: forwards to bothjnp.einsumcalls and conditionally applies.astype()only whenpreferred_element_type is not NoneMultiHeadAttention.__init__: acceptspreferred_element_typeand passes it to allLinearGenerallayers (q/k/v/out)MultiHeadAttention.__call__: forwardspreferred_element_typetoself.attention_fn
tests:
- adds
test_preferred_element_typetoattention_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!)
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_typetodot_product_attention_weightsforjnp.einsumprecision control. - Precision Control in Dot Product Attention: Enhanced
dot_product_attentionto acceptpreferred_element_type, applying it tojnp.einsumoperations and conditionally casting the output. - MultiHeadAttention Integration: Updated
MultiHeadAttentionto propagatepreferred_element_typeto its internalLinearGenerallayers and the attention function. - New Test Coverage: Added a new test case
test_preferred_element_typeto validate the new functionality inattention_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_typeparameter todot_product_attention_weightsfunction signature and docstring. - Modified
jnp.einsumcalls indot_product_attention_weightsto acceptpreferred_element_type. - Added
preferred_element_typeparameter todot_product_attentionfunction signature and docstring. - Updated
dot_product_attentionto conditionally cast its output topreferred_element_typeif specified. - Modified
jnp.einsumcalls indot_product_attentionto acceptpreferred_element_type. - Added
preferred_element_typeparameter toMultiHeadAttention.__init__and stored it as an instance attribute. - Passed
preferred_element_typeto theLinearGenerallayers (query, key, value, output) withinMultiHeadAttention.__init__. - Forwarded
self.preferred_element_typeto theattention_fncall withinMultiHeadAttention.__call__.
- Added
- tests/nnx/nn/attention_test.py
- Added
test_preferred_element_typeto verify thatMultiHeadAttentioncorrectly utilizes thepreferred_element_typeparameter.
- Added
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.
We already have
precisionto control the op precision anddtypeto 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?
@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_typewas already added tonnx.Linear*,nnx.Conv*, andnnx.Einsumin PR #4920, included in the Flax 0.12.0 release. this PR meant to extend the same pattern toMultiHeadAttentionwhich 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_generalfor 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_generalfunction. Seejax.lax.dotfor details.
and strengthen the tests to cover the mixed-precision use case.