Skip to content

Commit 96acfc7

Browse files
committed
per module ranking
1 parent 70cecaf commit 96acfc7

File tree

3 files changed

+27
-27
lines changed

3 files changed

+27
-27
lines changed

codeflash/benchmarking/function_ranker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def get_function_ttx_score(self, function_to_optimize: FunctionToOptimize) -> fl
9898

9999
def rank_functions(self, functions_to_optimize: list[FunctionToOptimize]) -> list[FunctionToOptimize]:
100100
ranked = sorted(functions_to_optimize, key=self.get_function_ttx_score, reverse=True)
101-
logger.info(
101+
logger.debug(
102102
f"Function ranking order: {[f'{func.function_name} (ttX={self.get_function_ttx_score(func):.2f})' for func in ranked]}"
103103
)
104104
return ranked

codeflash/discovery/functions_to_optimize.py

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def get_functions_to_optimize(
158158
project_root: Path,
159159
module_root: Path,
160160
previous_checkpoint_functions: dict[str, dict[str, str]] | None = None,
161-
) -> tuple[dict[Path, list[FunctionToOptimize]], int]:
161+
) -> tuple[dict[Path, list[FunctionToOptimize]], int, Path | None]:
162162
assert sum([bool(optimize_all), bool(replay_test), bool(file)]) <= 1, (
163163
"Only one of optimize_all, replay_test, or file should be provided"
164164
)
@@ -208,27 +208,6 @@ def get_functions_to_optimize(
208208
functions, test_cfg.tests_root, ignore_paths, project_root, module_root, previous_checkpoint_functions
209209
)
210210

211-
if trace_file_path and trace_file_path.exists():
212-
from codeflash.benchmarking.function_ranker import FunctionRanker
213-
214-
ranker = FunctionRanker(trace_file_path)
215-
216-
all_functions = []
217-
for file_functions in filtered_modified_functions.values():
218-
all_functions.extend(file_functions)
219-
220-
if all_functions:
221-
ranked_functions = ranker.rank_functions(all_functions)
222-
functions_count = len(ranked_functions)
223-
224-
ranked_dict = {}
225-
for func in ranked_functions:
226-
if func.file_path not in ranked_dict:
227-
ranked_dict[func.file_path] = []
228-
ranked_dict[func.file_path].append(func)
229-
230-
filtered_modified_functions = ranked_dict
231-
232211
logger.info(f"Found {functions_count} function{'s' if functions_count > 1 else ''} to optimize")
233212
if optimize_all:
234213
three_min_in_ns = int(1.8e11)
@@ -237,7 +216,7 @@ def get_functions_to_optimize(
237216
f"It might take about {humanize_runtime(functions_count * three_min_in_ns)} to fully optimize this project. Codeflash "
238217
f"will keep opening pull requests as it finds optimizations."
239218
)
240-
return filtered_modified_functions, functions_count
219+
return filtered_modified_functions, functions_count, trace_file_path
241220

242221

243222
def get_functions_within_git_diff() -> dict[str, list[FunctionToOptimize]]:

codeflash/optimization/optimizer.py

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def run_benchmarks(
109109

110110
return function_benchmark_timings, total_benchmark_timings
111111

112-
def get_optimizable_functions(self) -> tuple[dict[Path, list[FunctionToOptimize]], int]:
112+
def get_optimizable_functions(self) -> tuple[dict[Path, list[FunctionToOptimize]], int, Path | None]:
113113
"""Discover functions to optimize."""
114114
from codeflash.discovery.functions_to_optimize import get_functions_to_optimize
115115

@@ -255,7 +255,7 @@ def run(self) -> None:
255255
cleanup_paths(Optimizer.find_leftover_instrumented_test_files(self.test_cfg.tests_root))
256256

257257
function_optimizer = None
258-
file_to_funcs_to_optimize, num_optimizable_functions = self.get_optimizable_functions()
258+
file_to_funcs_to_optimize, num_optimizable_functions, trace_file_path = self.get_optimizable_functions()
259259
function_benchmark_timings, total_benchmark_timings = self.run_benchmarks(
260260
file_to_funcs_to_optimize, num_optimizable_functions
261261
)
@@ -282,7 +282,21 @@ def run(self) -> None:
282282

283283
validated_original_code, original_module_ast = module_prep_result
284284

285-
for function_to_optimize in file_to_funcs_to_optimize[original_module_path]:
285+
functions_to_optimize = file_to_funcs_to_optimize[original_module_path]
286+
if trace_file_path and trace_file_path.exists() and len(functions_to_optimize) > 1:
287+
try:
288+
from codeflash.benchmarking.function_ranker import FunctionRanker
289+
290+
ranker = FunctionRanker(trace_file_path)
291+
functions_to_optimize = ranker.rank_functions(functions_to_optimize)
292+
logger.info(
293+
f"Ranked {len(functions_to_optimize)} functions by performance impact in {original_module_path}"
294+
)
295+
console.rule()
296+
except Exception as e:
297+
logger.debug(f"Could not rank functions in {original_module_path}: {e}")
298+
299+
for function_to_optimize in functions_to_optimize:
286300
function_iterator_count += 1
287301
logger.info(
288302
f"Optimizing function {function_iterator_count} of {num_optimizable_functions}: "
@@ -322,6 +336,8 @@ def run(self) -> None:
322336
ph("cli-optimize-run-finished", {"optimizations_found": optimizations_found})
323337
if self.functions_checkpoint:
324338
self.functions_checkpoint.cleanup()
339+
if hasattr(self.args, "command") and self.args.command == "optimize":
340+
self.cleanup_replay_tests()
325341
if optimizations_found == 0:
326342
logger.info("❌ No optimizations found.")
327343
elif self.args.all:
@@ -352,6 +368,11 @@ def find_leftover_instrumented_test_files(test_root: Path) -> list[Path]:
352368
file_path for file_path in test_root.rglob("*") if file_path.is_file() and pattern.match(file_path.name)
353369
]
354370

371+
def cleanup_replay_tests(self) -> None:
372+
if self.replay_tests_dir and self.replay_tests_dir.exists():
373+
logger.debug(f"Cleaning up replay tests directory: {self.replay_tests_dir}")
374+
cleanup_paths([self.replay_tests_dir])
375+
355376
def cleanup_temporary_paths(self) -> None:
356377
if self.current_function_optimizer:
357378
self.current_function_optimizer.cleanup_generated_files()

0 commit comments

Comments
 (0)