⚡️ Speed up function get by 17%
#217
Open
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.
📄 17% (0.17x) speedup for
getinkeras/src/dtype_policies/__init__.py⏱️ Runtime :
9.81 milliseconds→8.41 milliseconds(best of23runs)📝 Explanation and details
The optimization achieves a 16% speedup through two key changes that eliminate repeated overhead in hot code paths:
1. Import Hoisting in
get()FunctionThe most significant optimization moves the import of
_get_quantized_dtype_policy_by_strfrom inside theget()function to the module level. The profiler shows this import consumed 3.5% of total time (2.1M ns out of 60.1M ns) on every function call. Even though Python caches imports, the lookup and execution overhead adds up whenget()is called frequently. Moving it to module scope eliminates this per-call cost entirely.2. Optimized String Handling in
standardize_dtype()The function now stores
str(dtype)in a variable only when needed, avoiding duplicate string conversions. The original code calledstr(dtype)twice when checking for "torch" or "jax.numpy" patterns. This reduces string creation overhead and improves cache locality.3. Exception Handling Improvement
Changed the bare
except:toexcept Exception:, which is both more specific and slightly more performant.Impact Analysis
Based on the function references,
dtype_policies.get()is called inDTypePolicyMapconstructors and setters, suggesting it's in hot paths during model initialization and dtype policy management. The test results show consistent improvements across all scenarios:The optimization is particularly effective for workloads with frequent dtype policy lookups, which are common in Keras model construction and mixed-precision training scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-get-mjaig9zhand push.