|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import ast |
| 4 | +from pathlib import Path |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +from codeflash.cli_cmds.console import console, logger |
| 8 | +from codeflash.code_utils.config_consts import TOTAL_LOOPING_TIME_EFFECTIVE |
| 9 | +from codeflash.languages.python.context.unused_definition_remover import ( |
| 10 | + detect_unused_helper_functions, |
| 11 | + revert_unused_helper_functions, |
| 12 | +) |
| 13 | +from codeflash.languages.python.optimizer import resolve_python_function_ast |
| 14 | +from codeflash.languages.python.static_analysis.code_extractor import get_opt_review_metrics, is_numerical_code |
| 15 | +from codeflash.languages.python.static_analysis.code_replacer import ( |
| 16 | + add_custom_marker_to_all_tests, |
| 17 | + modify_autouse_fixture, |
| 18 | +) |
| 19 | +from codeflash.languages.python.static_analysis.line_profile_utils import add_decorator_imports, contains_jit_decorator |
| 20 | +from codeflash.models.models import TestingMode, TestResults |
| 21 | +from codeflash.optimization.function_optimizer import FunctionOptimizer |
| 22 | +from codeflash.verification.parse_test_output import calculate_function_throughput_from_test_results |
| 23 | + |
| 24 | +if TYPE_CHECKING: |
| 25 | + from typing import Any |
| 26 | + |
| 27 | + from codeflash.languages.base import Language |
| 28 | + from codeflash.models.function_types import FunctionParent |
| 29 | + from codeflash.models.models import ( |
| 30 | + CodeOptimizationContext, |
| 31 | + CodeStringsMarkdown, |
| 32 | + ConcurrencyMetrics, |
| 33 | + CoverageData, |
| 34 | + OriginalCodeBaseline, |
| 35 | + TestDiff, |
| 36 | + ) |
| 37 | + |
| 38 | + |
| 39 | +class PythonFunctionOptimizer(FunctionOptimizer): |
| 40 | + def _resolve_function_ast( |
| 41 | + self, source_code: str, function_name: str, parents: list[FunctionParent] |
| 42 | + ) -> ast.FunctionDef | ast.AsyncFunctionDef | None: |
| 43 | + original_module_ast = ast.parse(source_code) |
| 44 | + return resolve_python_function_ast(function_name, parents, original_module_ast) |
| 45 | + |
| 46 | + def analyze_code_characteristics(self, code_context: CodeOptimizationContext) -> None: |
| 47 | + self.is_numerical_code = is_numerical_code(code_string=code_context.read_writable_code.flat) |
| 48 | + |
| 49 | + def get_optimization_review_metrics( |
| 50 | + self, |
| 51 | + source_code: str, |
| 52 | + file_path: Path, |
| 53 | + qualified_name: str, |
| 54 | + project_root: Path, |
| 55 | + tests_root: Path, |
| 56 | + language: Language, |
| 57 | + ) -> str: |
| 58 | + return get_opt_review_metrics(source_code, file_path, qualified_name, project_root, tests_root, language) |
| 59 | + |
| 60 | + def instrument_test_fixtures(self, test_paths: list[Path]) -> dict[Path, list[str]] | None: |
| 61 | + logger.info("Disabling all autouse fixtures associated with the generated test files") |
| 62 | + original_conftest_content = modify_autouse_fixture(test_paths) |
| 63 | + logger.info("Add custom marker to generated test files") |
| 64 | + add_custom_marker_to_all_tests(test_paths) |
| 65 | + return original_conftest_content |
| 66 | + |
| 67 | + def instrument_capture(self, file_path_to_helper_classes: dict[Path, set[str]]) -> None: |
| 68 | + from codeflash.verification.instrument_codeflash_capture import instrument_codeflash_capture |
| 69 | + |
| 70 | + instrument_codeflash_capture(self.function_to_optimize, file_path_to_helper_classes, self.test_cfg.tests_root) |
| 71 | + |
| 72 | + def should_check_coverage(self) -> bool: |
| 73 | + return True |
| 74 | + |
| 75 | + def collect_async_metrics( |
| 76 | + self, |
| 77 | + benchmarking_results: TestResults, |
| 78 | + code_context: CodeOptimizationContext, |
| 79 | + helper_code: dict[Path, str], |
| 80 | + test_env: dict[str, str], |
| 81 | + ) -> tuple[int | None, ConcurrencyMetrics | None]: |
| 82 | + if not self.function_to_optimize.is_async: |
| 83 | + return None, None |
| 84 | + |
| 85 | + async_throughput = calculate_function_throughput_from_test_results( |
| 86 | + benchmarking_results, self.function_to_optimize.function_name |
| 87 | + ) |
| 88 | + logger.debug(f"Async function throughput: {async_throughput} calls/second") |
| 89 | + |
| 90 | + concurrency_metrics = self.run_concurrency_benchmark( |
| 91 | + code_context=code_context, original_helper_code=helper_code, test_env=test_env |
| 92 | + ) |
| 93 | + if concurrency_metrics: |
| 94 | + logger.debug( |
| 95 | + f"Concurrency metrics: ratio={concurrency_metrics.concurrency_ratio:.2f}, " |
| 96 | + f"seq={concurrency_metrics.sequential_time_ns}ns, conc={concurrency_metrics.concurrent_time_ns}ns" |
| 97 | + ) |
| 98 | + return async_throughput, concurrency_metrics |
| 99 | + |
| 100 | + def instrument_async_for_mode(self, mode: TestingMode) -> None: |
| 101 | + from codeflash.code_utils.instrument_existing_tests import add_async_decorator_to_function |
| 102 | + |
| 103 | + add_async_decorator_to_function( |
| 104 | + self.function_to_optimize.file_path, self.function_to_optimize, mode, project_root=self.project_root |
| 105 | + ) |
| 106 | + |
| 107 | + def should_skip_sqlite_cleanup(self, testing_type: TestingMode, optimization_iteration: int) -> bool: |
| 108 | + return False |
| 109 | + |
| 110 | + def parse_line_profile_test_results( |
| 111 | + self, line_profiler_output_file: Path | None |
| 112 | + ) -> tuple[TestResults | dict, CoverageData | None]: |
| 113 | + from codeflash.verification.parse_line_profile_test_output import parse_line_profile_results |
| 114 | + |
| 115 | + return parse_line_profile_results(line_profiler_output_file=line_profiler_output_file) |
| 116 | + |
| 117 | + def compare_candidate_results( |
| 118 | + self, |
| 119 | + baseline_results: OriginalCodeBaseline, |
| 120 | + candidate_behavior_results: TestResults, |
| 121 | + optimization_candidate_index: int, |
| 122 | + ) -> tuple[bool, list[TestDiff]]: |
| 123 | + from codeflash.verification.equivalence import compare_test_results |
| 124 | + |
| 125 | + return compare_test_results(baseline_results.behavior_test_results, candidate_behavior_results) |
| 126 | + |
| 127 | + def replace_function_and_helpers_with_optimized_code( |
| 128 | + self, |
| 129 | + code_context: CodeOptimizationContext, |
| 130 | + optimized_code: CodeStringsMarkdown, |
| 131 | + original_helper_code: dict[Path, str], |
| 132 | + ) -> bool: |
| 133 | + did_update = super().replace_function_and_helpers_with_optimized_code( |
| 134 | + code_context, optimized_code, original_helper_code |
| 135 | + ) |
| 136 | + unused_helpers = detect_unused_helper_functions(self.function_to_optimize, code_context, optimized_code) |
| 137 | + if unused_helpers: |
| 138 | + revert_unused_helper_functions(self.project_root, unused_helpers, original_helper_code) |
| 139 | + return did_update |
| 140 | + |
| 141 | + def line_profiler_step( |
| 142 | + self, code_context: CodeOptimizationContext, original_helper_code: dict[Path, str], candidate_index: int |
| 143 | + ) -> dict[str, Any]: |
| 144 | + candidate_fto_code = Path(self.function_to_optimize.file_path).read_text("utf-8") |
| 145 | + if contains_jit_decorator(candidate_fto_code): |
| 146 | + logger.info( |
| 147 | + f"Skipping line profiler for {self.function_to_optimize.function_name} - code contains JIT decorator" |
| 148 | + ) |
| 149 | + return {"timings": {}, "unit": 0, "str_out": ""} |
| 150 | + |
| 151 | + for module_abspath in original_helper_code: |
| 152 | + candidate_helper_code = Path(module_abspath).read_text("utf-8") |
| 153 | + if contains_jit_decorator(candidate_helper_code): |
| 154 | + logger.info( |
| 155 | + f"Skipping line profiler for {self.function_to_optimize.function_name} - helper code contains JIT decorator" |
| 156 | + ) |
| 157 | + return {"timings": {}, "unit": 0, "str_out": ""} |
| 158 | + |
| 159 | + try: |
| 160 | + console.rule() |
| 161 | + |
| 162 | + test_env = self.get_test_env( |
| 163 | + codeflash_loop_index=0, codeflash_test_iteration=candidate_index, codeflash_tracer_disable=1 |
| 164 | + ) |
| 165 | + line_profiler_output_file = add_decorator_imports(self.function_to_optimize, code_context) |
| 166 | + line_profile_results, _ = self.run_and_parse_tests( |
| 167 | + testing_type=TestingMode.LINE_PROFILE, |
| 168 | + test_env=test_env, |
| 169 | + test_files=self.test_files, |
| 170 | + optimization_iteration=0, |
| 171 | + testing_time=TOTAL_LOOPING_TIME_EFFECTIVE, |
| 172 | + enable_coverage=False, |
| 173 | + code_context=code_context, |
| 174 | + line_profiler_output_file=line_profiler_output_file, |
| 175 | + ) |
| 176 | + finally: |
| 177 | + self.write_code_and_helpers( |
| 178 | + self.function_to_optimize_source_code, original_helper_code, self.function_to_optimize.file_path |
| 179 | + ) |
| 180 | + if isinstance(line_profile_results, TestResults) and not line_profile_results.test_results: |
| 181 | + logger.warning( |
| 182 | + f"Timeout occurred while running line profiler for original function {self.function_to_optimize.function_name}" |
| 183 | + ) |
| 184 | + return {"timings": {}, "unit": 0, "str_out": ""} |
| 185 | + if line_profile_results["str_out"] == "": |
| 186 | + logger.warning( |
| 187 | + f"Couldn't run line profiler for original function {self.function_to_optimize.function_name}" |
| 188 | + ) |
| 189 | + return line_profile_results |
0 commit comments