⚡️ Speed up function rotate_half by 43%
#95
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.
📄 43% (0.43x) speedup for
rotate_halfinsrc/transformers/models/hunyuan_v1_dense/modeling_hunyuan_v1_dense.py⏱️ Runtime :
3.00 milliseconds→2.09 milliseconds(best of104runs)📝 Explanation and details
The optimization eliminates redundant computation of
x.shape[-1] // 2by calculating it once and storing it in a variablehalf.Key changes:
x[..., : x.shape[-1] // 2]withhalf = x.shape[-1] // 2followed byx[..., :half]x[..., x.shape[-1] // 2 :]withx[..., half:]Why it's faster:
In the original code,
x.shape[-1] // 2was computed twice - once for each slice operation. The optimized version computes this value only once and reuses it. While tensor shape access is relatively fast, eliminating the redundant integer division and the second shape lookup provides measurable performance gains.Performance characteristics:
The optimization shows consistent improvements across different test scenarios:
This optimization is particularly effective for transformer models where rotary position embeddings (which use
rotate_half) are applied repeatedly during attention computation.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-rotate_half-mhjpn92aand push.