⚡️ Speed up function shift_tokens_right by 28%
#392
+5
−4
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.
📄 28% (0.28x) speedup for
shift_tokens_rightinsrc/transformers/models/mvp/modeling_mvp.py⏱️ Runtime :
2.63 milliseconds→2.06 milliseconds(best of86runs)📝 Explanation and details
The optimized code achieves a 27% speedup through two key performance improvements:
1. Early validation check: Moving the
pad_token_id is Nonecheck to the beginning eliminates wasted computation when inputs are invalid, providing dramatic speedups (up to 4581% in error cases).2. More efficient tensor allocation: Replacing
input_ids.new_zeros()withtorch.empty_like()eliminates unnecessary zero-initialization since the tensor gets completely overwritten anyway. This reduces memory bandwidth overhead.3. Removing unnecessary
.clone(): The original code used.clone()when copyinginput_ids[:, :-1], which creates an extra tensor copy. The optimized version removes this since we're already writing to a new tensor.Performance impact by workload:
Hot path significance: Based on the function references,
shift_tokens_rightis called during model forward passes in both base model and conditional generation scenarios. It's used to prepare decoder inputs from eitherinput_idsorlabels, making it a critical path during training and inference where these optimizations will have meaningful impact on overall model performance.The optimizations are particularly effective for transformer workloads that process large batches with long sequences, which is typical in modern NLP applications.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-shift_tokens_right-miabqwqjand push.