Conversation
Added checks for invalid inputs
Added tests to check invalid inputs
Fix for model not loading when using numpy behaviour with tensorflow
This reverts commit 3fdc7fd.
Casts indices to int32 before using them in ops.take_along_axis to prevent type mismatch issues in non-TensorFlow backends. This improves compatibility and avoids potential runtime errors.
Replaces direct access to the _keras_mask attribute with the get_keras_mask utility in TokenAndPositionEmbeddingTest. This improves compatibility with changes in Keras mask handling.
This reverts commit d39d485.
- Added SDPA override for self-attention in CachedMultiHeadAttention - Fast path for position embedding single-token decoding - New call_cached() method in TransformerDecoder for decoder-only inference - Optimized causal mask computation for autoregressive decoding - Direct tensor indexing in GPT-2 call_with_cache - Temperature division skip in sampler when temp=1.0 - Fast path for single stop token in any_equal - Added torch.inference_mode() for better PyTorch performance Benchmark: PyTorch 1.58s vs JAX 0.98s (1.61x gap)
Summary of ChangesHello @pctablet505, I'm Gemini Code Assist1! 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 focuses on significant performance optimizations for cached autoregressive decoding in GPT-2 and similar transformer models, primarily targeting the PyTorch backend. The changes aim to enhance generation speed by reducing computational overheads associated with mask calculations, minimizing tensor slicing operations, and integrating highly optimized PyTorch functionalities like Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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 👍 and 👎 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. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a set of significant performance optimizations for autoregressive decoding, mainly for the PyTorch backend. The changes are well-thought-out, leveraging backend-specific features like PyTorch's scaled_dot_product_attention (SDPA) and in-place updates to improve generation speed. The introduction of a call_cached fast path and pre-computation of causal masks are excellent strategies for reducing overhead.
I've found one critical issue in the implementation of the SDPA fast path where the attention mask logic is inverted, which would lead to incorrect attention results. I've provided a suggestion for the fix.
Overall, this is a high-quality contribution that will substantially improve model performance. Great work!
|
|
||
| # Convert attention mask to SDPA format. | ||
| if attention_mask is not None: | ||
| attention_mask = attention_mask.to(dtype=torch.bool) |
There was a problem hiding this comment.
The conversion of the attention mask for PyTorch's scaled_dot_product_attention appears to be incorrect. The Keras convention for attention masks is that 1 or True indicates a position should be attended to. However, PyTorch's SDPA attn_mask expects True for positions that should be ignored (masked out).
The current implementation attention_mask.to(dtype=torch.bool) will convert attending positions (1/True) to True, which causes SDPA to ignore them, effectively inverting the attention logic.
To fix this, the boolean mask should be inverted before being passed to scaled_dot_product_attention. This is a critical issue as it will lead to incorrect model outputs during cached inference on the PyTorch backend.
| attention_mask = attention_mask.to(dtype=torch.bool) | |
| attention_mask = ~attention_mask.to(dtype=torch.bool) |
Keras convention: 1/True = attend, 0/False = don't attend PyTorch SDPA convention: True = mask out, False = attend The mask needs to be inverted when passed to scaled_dot_product_attention.
Introduce an ultra-fast cached decoding path and centralize generation logic. - Add CachedMultiHeadAttention.call_cached to bypass Layer.__call__ and directly invoke sublayer .call() for query/key/value/output dense ops, reducing overhead during cached autoregressive decoding. Also adjust boolean attention-mask handling to pass through without inversion. - Update TransformerDecoder to use .call() on layer-norms/denses and to call the new attention.call_cached path, avoiding repeated Layer.__call__ overhead in inference. - Move the per-model generate_step implementations into a single default implementation on CausalLM (with backend-specific optimizations such as direct tensor indexing for torch). Add abstract call_with_cache and _build_cache stubs that subclasses must implement. Remove now-duplicate generate_step code and related any_equal imports from many model files. These changes reduce runtime overhead during cached inference and consolidate generation behavior across models.
This pull request introduces several optimizations for cached autoregressive decoding in GPT-2 and related transformer models, primarily targeting the PyTorch backend. The changes improve generation speed by reducing redundant mask computations, minimizing tensor slicing overhead, and leveraging PyTorch's
scaled_dot_product_attention(SDPA) when available. There are also minor improvements to sampler logic and tensor utilities for efficiency.Transformer and Attention Layer Optimizations
CachedMultiHeadAttentionto use PyTorch's SDPA for cached inference, including a runtime check for SDPA availability and an override mechanism for self-attention. [1] [2]call_cachedmethod inTransformerDecoderto bypass validation, skip redundant mask computations, and enable SDPA override during autoregressive decoding.compute_causal_maskto use a fast path for single-token generation, avoiding unnecessary tensor operations when output length is 1.GPT-2 Model Generation Improvements
GPT2CausalLM.call_with_cacheto precompute and share the causal mask across all decoder layers, reducing repeated mask creation and leveraging in-place cache updates on PyTorch.generate_stepto use direct tensor indexing for single-token extraction on PyTorch, avoiding ops.slice overhead.torch.no_grad()andtorch.inference_mode()in the generation wrapper.Sampler and Utility Enhancements
Sampler.compute_probabilitiesfor clarity and efficiency, applying division only when temperature is not 1.0.Sampler.stateless_body, noting optimized while loop support for PyTorch.any_equalto avoid unnecessary logical operations.Position Embedding Optimization
PositionEmbedding.callfor single-token decoding on PyTorch, using direct indexing to avoid slicing overhead.## Description of the changeReference
Colab Notebook
Checklist