⚡️ Speed up function _sample_negative_indices by 40%
#887
+21
−11
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.
📄 40% (0.40x) speedup for
_sample_negative_indicesinsrc/transformers/models/wav2vec2/modeling_wav2vec2.py⏱️ Runtime :
3.32 milliseconds→2.37 milliseconds(best of90runs)📝 Explanation and details
The optimization achieves a 39% speedup through several key improvements that reduce computational overhead and redundant operations:
Key Optimizations:
Conditional restructuring: The original code uses a ternary expression for mask handling that gets evaluated on every call. The optimized version uses explicit if/else branching, which is more efficient and clearer.
Early exit optimization: Added a
masked_count == 0check that skips the expensive sampling logic when no positions are masked. This provides dramatic speedups (167-282% faster) for edge cases with empty masks, as shown in the test results.Local variable caching: Stores
mask_time_indices[batch_idx]inmask_rowandmask_row.sum()inmasked_countto avoid repeated array indexing and sum computations within the loop.Vectorized arithmetic: Replaces
sampled_indices[sampled_indices >= feature_indices] += 1withnp.add(sampled_indices, sampled_indices >= feature_indices, out=sampled_indices). This uses NumPy's optimized in-place addition with broadcasting, avoiding temporary boolean array allocations and reducing memory pressure.Removed unnecessary broadcasting: Eliminates
np.broadcast_to()call by usingnp.arange(high + 1)[:, None]directly, which is more memory-efficient.Performance Impact:
np.random.randint()calls and vectorized array operations, which remain the dominant cost but are now more efficiently managedThe optimizations are particularly effective because they target the hot path of negative sampling in contrastive learning, where this function is called repeatedly during model training.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_sample_negative_indices-misl46beand push.