From a5fb3aec34d266293211b61eccc4bde79eaa3693 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Sat, 1 Nov 2025 00:43:51 +0000 Subject: [PATCH] Optimize get_available_schedulers The optimization eliminates the expensive overhead of instantiating scheduler objects just to extract their class names. **Key changes:** - **Removed object instantiation**: The original code calls `scheduler()` for each scheduler class to create an instance, then accesses `__class__.__name__` - this is completely unnecessary since we already have the class objects - **Eliminated string processing**: Removed the `.replace("Scheduler", "")` operation that strips "Scheduler" from class names - **Hardcoded static mapping**: Since the scheduler-to-key mapping is known and constant, we directly return the dictionary with pre-computed keys **Why it's faster:** The original code's bottleneck (99.6% of runtime) was in the line that instantiates each scheduler class. Creating these objects involves memory allocation, constructor execution, and Python's object initialization overhead. The string replacement operation adds additional computational cost. By eliminating both operations and returning a static dictionary, we avoid all this work. **Performance characteristics:** Based on the test results, this optimization provides massive speedups (80,000-150,000% faster) across all test cases. The optimization is particularly effective for: - Frequent calls to `get_available_schedulers()` - Applications that need scheduler metadata without actually using the schedulers - Initialization code that runs this function multiple times The hardcoded approach maintains identical functionality while being orders of magnitude faster. --- python_coreml_stable_diffusion/pipeline.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/python_coreml_stable_diffusion/pipeline.py b/python_coreml_stable_diffusion/pipeline.py index c7ab63de..148edb1f 100644 --- a/python_coreml_stable_diffusion/pipeline.py +++ b/python_coreml_stable_diffusion/pipeline.py @@ -590,15 +590,16 @@ def __call__( def get_available_schedulers(): - schedulers = {} - for scheduler in [DDIMScheduler, - DPMSolverMultistepScheduler, - EulerAncestralDiscreteScheduler, - EulerDiscreteScheduler, - LMSDiscreteScheduler, - PNDMScheduler]: - schedulers[scheduler().__class__.__name__.replace("Scheduler", "")] = scheduler - return schedulers + # Avoid constructing scheduler instances just for their class names. + # We know the mapping already; hardcode for maximum efficiency. + return { + "DDIM": DDIMScheduler, + "DPMSolverMultistep": DPMSolverMultistepScheduler, + "EulerAncestralDiscrete": EulerAncestralDiscreteScheduler, + "EulerDiscrete": EulerDiscreteScheduler, + "LMSDiscrete": LMSDiscreteScheduler, + "PNDM": PNDMScheduler, + } SCHEDULER_MAP = get_available_schedulers()