⚡️ Speed up function _shared_object_disabled by 120%
#206
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.
📄 120% (1.20x) speedup for
_shared_object_disabledinkeras/src/legacy/saving/serialization.py⏱️ Runtime :
1.32 milliseconds→602 microseconds(best of174runs)📝 Explanation and details
The optimization replaces
getattr(SHARED_OBJECT_DISABLED, "disabled", False)withSHARED_OBJECT_DISABLED.__dict__.get("disabled", False), achieving a 119% speedup by bypassing Python's built-in attribute lookup mechanism.Key Performance Improvements:
__dict__.get()directly accesses the underlying dictionary storage of the threading.local object, avoiding the overhead of Python's attribute resolution protocolgetattr()involves additional C-level checks and method dispatch, while dictionary.get()is a more direct operationgetattr()triggers the full descriptor protocol chain, whereas direct dictionary access skips these checksHot Path Impact:
Based on the function references,
_shared_object_disabled()is called in context manager__enter__methods for both loading and saving scopes. These are likely executed frequently during model serialization/deserialization operations, making this a high-impact optimization for Keras workflows involving model saving/loading.Test Case Performance:
The optimization shows consistent 90-150% speedups across all test scenarios:
The optimization maintains identical behavior and thread-safety guarantees while providing substantial performance gains for this frequently-called utility function in Keras's serialization pipeline.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_shared_object_disabled-mjacyxigand push.