⚡️ Speed up function fused_recurrent_gated_delta_rule by 45%
#325
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.
📄 45% (0.45x) speedup for
fused_recurrent_gated_delta_ruleinpython/sglang/srt/layers/attention/fla/fused_recurrent.py⏱️ Runtime :
27.6 microseconds→19.0 microseconds(best of13runs)📝 Explanation and details
The optimization achieves a 44% speedup through two key changes:
1. Replaced
len(cu_seqlens)withcu_seqlens.numel()len()triggers Python's__len__protocol which adds overhead, whilenumel()directly accesses the tensor's element countcu_seqlensvalidation runs on every function call2. Changed beta default from
torch.ones_like(q[..., 0])toq.new_ones(q.shape[:-1])torch.ones_like(q[..., 0])creates an intermediate tensor slice before callingones_likeq.new_ones(q.shape[:-1])directly creates the tensor with the right shape, avoiding the slice operation and leveraging PyTorch's optimized tensor creation pathwayImpact Analysis:
cu_seqlenschecksbeta=Nonecases (default parameter usage) and variable-length sequence processingThese micro-optimizations compound effectively because both occur in the function's hot validation/setup phase before the expensive
FusedRecurrentFunction.apply()call.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-fused_recurrent_gated_delta_rule-mhouby4uand push.