⚡️ Speed up function _topk_ids_logical_to_physical_dynamic by 12%
#322
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.
📄 12% (0.12x) speedup for
_topk_ids_logical_to_physical_dynamicinpython/sglang/srt/eplb/expert_location_dispatch.py⏱️ Runtime :
1.71 milliseconds→1.52 milliseconds(best of247runs)📝 Explanation and details
The optimized code achieves a 12% speedup through several key tensor operation optimizations:
Key Optimizations:
Smart reshape handling: Replaces unconditional
.flatten()with conditional.reshape(-1)only when needed (multi-dimensional tensors), avoiding unnecessary memory copies for already 1D tensors.Efficient random generation: Uses
torch.empty(...).random_(65536)instead oftorch.randint(0, 65536, ...), which generates random numbers in-place rather than creating intermediate tensors, reducing memory allocation overhead.Variable caching: Stores the flattened indices in
topk_idxto avoid recomputation during indexing operations.Conditional view operation: Only calls
.view()to restore original shape when the shape actually changed, eliminating unnecessary tensor operations.Performance Impact:
The function is called from
topk_ids_logical_to_physical()for "dynamic" and "fake" expert dispatch algorithms, suggesting it's in a hot path for expert routing in distributed inference scenarios. The optimizations are particularly effective for:The optimizations preserve exact functionality while reducing memory allocations and tensor operations, making expert routing more efficient in distributed model serving workloads where this function may be called frequently during request processing.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_topk_ids_logical_to_physical_dynamic-mhospliqand push.