⚡️ Speed up function in_stateless_scope by 72%
#170
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.
📄 72% (0.72x) speedup for
in_stateless_scopeinkeras/src/backend/common/stateless_scope.py⏱️ Runtime :
828 microseconds→480 microseconds(best of169runs)📝 Explanation and details
The optimization replaces
getattr(GLOBAL_STATE_TRACKER, name, None)withGLOBAL_STATE_TRACKER.__dict__.get(name, None)in theget_global_attributefunction, providing a 72% speedup.Key optimization:
getattr)dict.get()method which is optimized at the C levelWhy this is faster:
getattr()involves multiple layers of Python's attribute resolution machinery, including descriptor protocol checks and special method lookups. In contrast,threading.local()objects store their per-thread data in a simple__dict__, so direct dictionary access via.get()is much more efficient.Impact on workloads:
The function references show
in_stateless_scope()is called frequently in Keras variable operations - during variable initialization, value access, and assignment operations. Since these are core operations that can occur thousands of times during model training/inference, this micro-optimization has significant cumulative impact.Test case performance:
The annotated tests show consistent 50-88% speedups across all scenarios, with the optimization being particularly effective for:
This optimization is safe because
threading.local().__dict__is the documented way to access thread-local storage and maintains identical behavior while being substantially faster.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
⏪ Replay Tests and Runtime
test_pytest_integration_testsdataset_testsfashion_mnist_test_py_integration_testsdataset_testscifar10_tes__replay_test_0.py::test_keras_src_backend_common_stateless_scope_in_stateless_scopetest_pytest_integration_teststorch_workflow_test_py_integration_testsdataset_testscalifornia_housing_test__replay_test_0.py::test_keras_src_backend_common_stateless_scope_in_stateless_scopeTo edit these changes
git checkout codeflash/optimize-in_stateless_scope-mirm1t39and push.