⚡️ Speed up method AmazonStabilityConfig.get_config
by 278%
#8
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.
📄 278% (2.78x) speedup for
AmazonStabilityConfig.get_config
inlitellm/llms/bedrock/image/amazon_stability1_transformation.py
⏱️ Runtime :
3.85 milliseconds
→1.02 milliseconds
(best of345
runs)📝 Explanation and details
The optimization achieves a 277% speedup by eliminating expensive dictionary operations and type checking in the hot path:
Key optimizations:
Replaced
locals()
dictionary copying in__init__
: The original code created a copy of the entire locals dictionary and iterated through it. The optimized version uses direct conditional checks for each parameter, avoiding dictionary creation and iteration overhead.Eliminated
cls.__dict__.items()
iteration inget_config
: The original code iterated through the entire class dictionary and performed expensiveisinstance
checks against multiple function types for every attribute. The optimized version uses a predefined tuple of known attribute names and directly accesses only those attributes withgetattr
.Removed repeated type checking: The original performed
isinstance
checks againsttypes.FunctionType
,types.BuiltinFunctionType
,classmethod
, andstaticmethod
for every class attribute. The optimization leverages domain knowledge that this class only uses the five configuration attributes, eliminating all type checking.Why this works so well:
locals().copy()
,cls.__dict__.items()
) are expensive in Pythonisinstance
against multiple types has significant overhead when called repeatedlygetattr
is much faster than dictionary iterationTest case performance:
The optimization shows consistent 150-300% speedups across all test scenarios, with particularly strong performance in high-frequency calls (500+ iterations showing 285-308% speedups) and scenarios with multiple parameters set.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-AmazonStabilityConfig.get_config-mh2lilwz
and push.