⚡️ Speed up function keras_model_summary by 6%
#204
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.
📄 6% (0.06x) speedup for
keras_model_summaryinkeras/src/callbacks/tensorboard.py⏱️ Runtime :
2.84 milliseconds→2.67 milliseconds(best of118runs)📝 Explanation and details
The optimization achieves a 6% speedup by eliminating redundant imports on every function call. The key change is moving expensive TensorFlow imports to module-level -
tensorflow.summaryandSummaryMetadataare now imported once at startup rather than repeatedly inside the function.What changed:
import tensorflow.summaryandfrom tensorflow.compat.v1 import SummaryMetadatato module-level with underscore prefixes_summary.experimental.summary_scopeand_summary.writebefore the context managerWhy it's faster:
The line profiler shows the original imports consumed 1.9% of total runtime (325,013 + 206,389 ns out of 27.69ms total). TensorFlow modules are notoriously expensive to import due to their complex initialization. By importing once at module load instead of on every call, we eliminate this repeated overhead entirely.
Impact on workloads:
Looking at the function reference,
keras_model_summaryis called from_write_keras_model_summary()in TensorBoard callbacks. While this appears to be called once per model (step=0), the optimization is particularly valuable because:The optimization is most effective for workloads that call this function multiple times or where import overhead is a concern, with minimal impact on single-use scenarios.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-keras_model_summary-mjaatxy7and push.