⚡️ Speed up function serialize_keras_class_and_config by 55%
#210
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.
📄 55% (0.55x) speedup for
serialize_keras_class_and_configinkeras/src/legacy/saving/serialization.py⏱️ Runtime :
2.68 milliseconds→1.72 milliseconds(best of167runs)📝 Explanation and details
The optimization achieves a 55% speedup by eliminating redundant function calls to
_shared_object_saving_scope().Key optimizations:
Reduced function calls: The original code calls
_shared_object_saving_scope()twice when both conditions are met - once in the compoundifstatement and again when callingscope.get_config(). The optimized version calls it at most once by storing the result in a local variablescope.Short-circuit evaluation: By checking
obj is not Nonefirst, the optimization avoids calling_shared_object_saving_scope()entirely when no object is provided (which happens in many test cases), saving expensivegetattr()operations on the threading.local object.Performance impact from profiling:
_shared_object_saving_scope()calls dropped from 4,242 to 1,715 (59% reduction)Test case benefits:
obj is not NonecheckReal-world impact:
Based on the function reference,
serialize_keras_class_and_configis called fromserialize_keras_object, which is likely in the hot path during model serialization. The optimization is particularly effective when serializing models without shared object scopes (the common case), where it eliminates unnecessary threading.local lookups entirely.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-serialize_keras_class_and_config-mjaew037and push.