⚡️ Speed up method ApertusAttention.forward by 27%
#357
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 27% (0.27x) speedup for
ApertusAttention.forwardinsrc/transformers/models/apertus/modeling_apertus.py⏱️ Runtime :
25.9 milliseconds→20.4 milliseconds(best of76runs)📝 Explanation and details
The optimized code achieves a 27% speedup through several targeted micro-optimizations that reduce computational overhead and memory operations:
Key Optimizations Applied
1. In-place Operations in
apply_rotary_pos_emb:(q * cos) + (rotate_half(q) * sin)with separate computation and in-place addition usingadd_()rot_half = rotate_halfto avoid repeated global lookups2. Optimized Matrix Operations in
eager_attention_forward:torch.matmul(query, key_states.transpose(2, 3)) * scalingwith separate transpose assignment and in-place multiplication usingmul_()add_()for attention mask addition instead of creating new tensors.to(query.dtype)when types already match3. Reduced Attribute Lookups in
ApertusAttention.forward:head_dim,num_attention_heads,_attn_implementation) as local variables.contiguous()call on final output since.reshape()handles contiguity requirements4. Batch Operations in Cache Management:
extend()using generator expressionPerformance Impact
The optimizations are particularly effective for larger tensor operations, as shown by the test results where the
test_forward_maximum_tensor_sizecase improved by 81.6%. Smaller operations see modest improvements of 1-4%, which is expected since the overhead reduction becomes more significant as computational workload increases.These optimizations maintain full functional correctness while reducing memory allocations and computational overhead, making the attention mechanism more efficient across various input sizes.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-ApertusAttention.forward-mi9p16yfand push.