⚡️ Speed up method GraphormerGraphNodeFeature.forward by 8%
#92
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.
📄 8% (0.08x) speedup for
GraphormerGraphNodeFeature.forwardinsrc/transformers/models/deprecated/graphormer/modeling_graphormer.py⏱️ Runtime :
1.46 milliseconds→1.36 milliseconds(best of45runs)📝 Explanation and details
The optimization replaces
repeat()withexpand()when creating the graph token feature tensor. This is a memory optimization that provides a 7% speedup.Key Change:
self.graph_token.weight.unsqueeze(0).repeat(n_graph, 1, 1)self.graph_token.weight.unsqueeze(0).expand(n_graph, -1, -1)Why This Is Faster:
repeat()allocates new memory and physically copies datan_graphtimes, creating a fully materialized tensorexpand()creates a memory-efficient view that shares the underlying data, avoiding memory allocation and copyingexpand()is semantically equivalent but computationally cheaperPerformance Impact:
The line profiler shows the graph token creation time improved from 389,196 ns to 224,186 ns (42% faster on that line), contributing to the overall 7% speedup. This optimization is particularly effective for:
The test results confirm consistent 6-15% improvements across various scenarios, with the largest gains seen in cases with empty graphs (15.2% faster) and single nodes (12-14% faster), where the relative cost of tensor operations is highest.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-GraphormerGraphNodeFeature.forward-mhha9fyjand push.