-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathfunction_optimizer.py
More file actions
2275 lines (2052 loc) · 103 KB
/
function_optimizer.py
File metadata and controls
2275 lines (2052 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import ast
import concurrent.futures
import os
import queue
import random
import subprocess
import uuid
from collections import defaultdict
from pathlib import Path
from typing import TYPE_CHECKING
import libcst as cst
from rich.console import Group
from rich.panel import Panel
from rich.syntax import Syntax
from rich.tree import Tree
from codeflash.api.aiservice import AiServiceClient, AIServiceRefinerRequest, LocalAiServiceClient
from codeflash.api.cfapi import add_code_context_hash, create_staging, get_cfapi_base_urls, mark_optimization_success
from codeflash.benchmarking.utils import process_benchmark_data
from codeflash.cli_cmds.console import code_print, console, logger, lsp_log, progress_bar
from codeflash.code_utils import env_utils
from codeflash.code_utils.code_extractor import get_opt_review_metrics
from codeflash.code_utils.code_replacer import (
add_custom_marker_to_all_tests,
modify_autouse_fixture,
replace_function_definitions_in_module,
)
from codeflash.code_utils.code_utils import (
choose_weights,
cleanup_paths,
create_rank_dictionary_compact,
create_score_dictionary_from_metrics,
diff_length,
extract_unique_errors,
file_name_from_test_module_name,
get_run_tmp_file,
module_name_from_file_path,
normalize_by_max,
restore_conftest,
unified_diff_strings,
)
from codeflash.code_utils.config_consts import (
COVERAGE_THRESHOLD,
INDIVIDUAL_TESTCASE_TIMEOUT,
MAX_REPAIRS_PER_TRACE,
N_CANDIDATES_EFFECTIVE,
N_CANDIDATES_LP_EFFECTIVE,
N_TESTS_TO_GENERATE_EFFECTIVE,
REFINE_ALL_THRESHOLD,
REFINED_CANDIDATE_RANKING_WEIGHTS,
REPAIR_UNMATCHED_PERCENTAGE_LIMIT,
REPEAT_OPTIMIZATION_PROBABILITY,
TOP_N_REFINEMENTS,
TOTAL_LOOPING_TIME_EFFECTIVE,
)
from codeflash.code_utils.deduplicate_code import normalize_code
from codeflash.code_utils.edit_generated_tests import (
add_runtime_comments_to_generated_tests,
remove_functions_from_generated_tests,
)
from codeflash.code_utils.env_utils import get_pr_number
from codeflash.code_utils.formatter import format_code, format_generated_code, sort_imports
from codeflash.code_utils.git_utils import git_root_dir
from codeflash.code_utils.instrument_existing_tests import inject_profiling_into_existing_test
from codeflash.code_utils.line_profile_utils import add_decorator_imports
from codeflash.code_utils.static_analysis import get_first_top_level_function_or_method_ast
from codeflash.code_utils.time_utils import humanize_runtime
from codeflash.context import code_context_extractor
from codeflash.context.unused_definition_remover import detect_unused_helper_functions, revert_unused_helper_functions
from codeflash.discovery.functions_to_optimize import was_function_previously_optimized
from codeflash.either import Failure, Success, is_successful
from codeflash.lsp.helpers import is_LSP_enabled, report_to_markdown_table, tree_to_markdown
from codeflash.lsp.lsp_message import LspCodeMessage, LspMarkdownMessage, LSPMessageId
from codeflash.models.ExperimentMetadata import ExperimentMetadata
from codeflash.models.models import (
AIServiceCodeRepairRequest,
BestOptimization,
CandidateEvaluationContext,
CodeOptimizationContext,
GeneratedTests,
GeneratedTestsList,
OptimizationSet,
OptimizedCandidate,
OptimizedCandidateResult,
OptimizedCandidateSource,
OriginalCodeBaseline,
TestFile,
TestFiles,
TestingMode,
TestResults,
TestType,
)
from codeflash.result.create_pr import check_create_pr, existing_tests_source_for
from codeflash.result.critic import (
coverage_critic,
performance_gain,
quantity_of_tests_critic,
speedup_critic,
throughput_gain,
)
from codeflash.result.explanation import Explanation
from codeflash.telemetry.posthog_cf import ph
from codeflash.verification.concolic_testing import generate_concolic_tests
from codeflash.verification.equivalence import compare_test_results
from codeflash.verification.instrument_codeflash_capture import instrument_codeflash_capture
from codeflash.verification.parse_line_profile_test_output import parse_line_profile_results
from codeflash.verification.parse_test_output import calculate_function_throughput_from_test_results, parse_test_results
from codeflash.verification.test_runner import run_behavioral_tests, run_benchmarking_tests, run_line_profile_tests
from codeflash.verification.verification_utils import get_test_file_path
from codeflash.verification.verifier import generate_tests
if TYPE_CHECKING:
from argparse import Namespace
from codeflash.discovery.functions_to_optimize import FunctionToOptimize
from codeflash.either import Result
from codeflash.models.models import (
BenchmarkKey,
CodeStringsMarkdown,
CoverageData,
FunctionCalledInTest,
FunctionSource,
TestDiff,
)
from codeflash.verification.verification_utils import TestConfig
class CandidateProcessor:
"""Handles candidate processing using a queue-based approach."""
def __init__(
self,
initial_candidates: list,
future_line_profile_results: concurrent.futures.Future,
all_refinements_data: list[AIServiceRefinerRequest],
ai_service_client: AiServiceClient,
executor: concurrent.futures.ThreadPoolExecutor,
future_all_code_repair: list[concurrent.futures.Future],
) -> None:
self.candidate_queue = queue.Queue()
self.line_profiler_done = False
self.refinement_done = False
self.candidate_len = len(initial_candidates)
self.ai_service_client = ai_service_client
self.executor = executor
# Initialize queue with initial candidates
for candidate in initial_candidates:
self.candidate_queue.put(candidate)
self.future_line_profile_results = future_line_profile_results
self.all_refinements_data = all_refinements_data
self.future_all_code_repair = future_all_code_repair
def get_next_candidate(self) -> OptimizedCandidate | None:
"""Get the next candidate from the queue, handling async results as needed."""
try:
return self.candidate_queue.get_nowait()
except queue.Empty:
return self._handle_empty_queue()
def _handle_empty_queue(self) -> OptimizedCandidate | None:
"""Handle empty queue by checking for pending async results."""
if not self.line_profiler_done:
return self._process_line_profiler_results()
if len(self.future_all_code_repair) > 0:
return self._process_code_repair()
if self.line_profiler_done and not self.refinement_done:
return self._process_refinement_results()
return None # All done
def _process_line_profiler_results(self) -> OptimizedCandidate | None:
"""Process line profiler results and add to queue."""
logger.debug("all candidates processed, await candidates from line profiler")
concurrent.futures.wait([self.future_line_profile_results])
line_profile_results = self.future_line_profile_results.result()
for candidate in line_profile_results:
self.candidate_queue.put(candidate)
self.candidate_len += len(line_profile_results)
logger.info(f"Added results from line profiler to candidates, total candidates now: {self.candidate_len}")
self.line_profiler_done = True
return self.get_next_candidate()
def refine_optimizations(self, request: list[AIServiceRefinerRequest]) -> concurrent.futures.Future:
return self.executor.submit(self.ai_service_client.optimize_python_code_refinement, request=request)
def _process_refinement_results(self) -> OptimizedCandidate | None:
"""Process refinement results and add to queue. We generate a weighted ranking based on the runtime and diff lines and select the best (round of 45%) of valid optimizations to be refined."""
future_refinements: list[concurrent.futures.Future] = []
if len(self.all_refinements_data) <= REFINE_ALL_THRESHOLD:
for data in self.all_refinements_data:
future_refinements.append(self.refine_optimizations([data])) # noqa: PERF401
else:
diff_lens_list = []
runtimes_list = []
for c in self.all_refinements_data:
diff_lens_list.append(diff_length(c.original_source_code, c.optimized_source_code))
runtimes_list.append(c.optimized_code_runtime)
runtime_w, diff_w = REFINED_CANDIDATE_RANKING_WEIGHTS
weights = choose_weights(runtime=runtime_w, diff=diff_w)
runtime_norm = normalize_by_max(runtimes_list)
diffs_norm = normalize_by_max(diff_lens_list)
# the lower the better
score_dict = create_score_dictionary_from_metrics(weights, runtime_norm, diffs_norm)
top_n_candidates = int((TOP_N_REFINEMENTS * len(runtimes_list)) + 0.5)
top_indecies = sorted(score_dict, key=score_dict.get)[:top_n_candidates]
for idx in top_indecies:
data = self.all_refinements_data[idx]
future_refinements.append(self.refine_optimizations([data]))
if future_refinements:
logger.info("loading|Refining generated code for improved quality and performance...")
concurrent.futures.wait(future_refinements)
refinement_response = []
for f in future_refinements:
possible_refinement = f.result()
if len(possible_refinement) > 0:
refinement_response.append(possible_refinement[0])
for candidate in refinement_response:
self.candidate_queue.put(candidate)
self.candidate_len += len(refinement_response)
if len(refinement_response) > 0:
logger.info(
f"Added {len(refinement_response)} candidates from refinement, total candidates now: {self.candidate_len}"
)
self.refinement_done = True
return self.get_next_candidate()
def _process_code_repair(self) -> OptimizedCandidate | None:
logger.info(f"loading|Repairing {len(self.future_all_code_repair)} candidates")
concurrent.futures.wait(self.future_all_code_repair)
candidates_added = 0
for future_code_repair in self.future_all_code_repair:
possible_code_repair = future_code_repair.result()
if possible_code_repair:
self.candidate_queue.put(possible_code_repair)
self.candidate_len += 1
candidates_added += 1
if candidates_added > 0:
logger.info(
f"Added {candidates_added} candidates from code repair, total candidates now: {self.candidate_len}"
)
self.future_all_code_repair = []
return self.get_next_candidate()
def is_done(self) -> bool:
"""Check if processing is complete."""
return (
self.line_profiler_done
and self.refinement_done
and len(self.future_all_code_repair) == 0
and self.candidate_queue.empty()
)
class FunctionOptimizer:
def __init__(
self,
function_to_optimize: FunctionToOptimize,
test_cfg: TestConfig,
function_to_optimize_source_code: str = "",
function_to_tests: dict[str, set[FunctionCalledInTest]] | None = None,
function_to_optimize_ast: ast.FunctionDef | ast.AsyncFunctionDef | None = None,
aiservice_client: AiServiceClient | None = None,
function_benchmark_timings: dict[BenchmarkKey, int] | None = None,
total_benchmark_timings: dict[BenchmarkKey, int] | None = None,
args: Namespace | None = None,
replay_tests_dir: Path | None = None,
) -> None:
self.project_root = test_cfg.project_root_path
self.test_cfg = test_cfg
self.aiservice_client = aiservice_client if aiservice_client else AiServiceClient()
self.function_to_optimize = function_to_optimize
self.function_to_optimize_source_code = (
function_to_optimize_source_code
if function_to_optimize_source_code
else function_to_optimize.file_path.read_text(encoding="utf8")
)
if not function_to_optimize_ast:
original_module_ast = ast.parse(function_to_optimize_source_code)
self.function_to_optimize_ast = get_first_top_level_function_or_method_ast(
function_to_optimize.function_name, function_to_optimize.parents, original_module_ast
)
else:
self.function_to_optimize_ast = function_to_optimize_ast
self.function_to_tests = function_to_tests if function_to_tests else {}
self.experiment_id = os.getenv("CODEFLASH_EXPERIMENT_ID", None)
self.local_aiservice_client = LocalAiServiceClient() if self.experiment_id else None
self.test_files = TestFiles(test_files=[])
self.args = args # Check defaults for these
self.function_trace_id: str = str(uuid.uuid4())
self.original_module_path = module_name_from_file_path(self.function_to_optimize.file_path, self.project_root)
self.function_benchmark_timings = function_benchmark_timings if function_benchmark_timings else {}
self.total_benchmark_timings = total_benchmark_timings if total_benchmark_timings else {}
self.replay_tests_dir = replay_tests_dir if replay_tests_dir else None
n_tests = N_TESTS_TO_GENERATE_EFFECTIVE
self.executor = concurrent.futures.ThreadPoolExecutor(
max_workers=n_tests + 3 if self.experiment_id is None else n_tests + 4
)
self.optimization_review = ""
self.future_all_code_repair: list[concurrent.futures.Future] = []
self.repair_counter = 0 # track how many repairs we did for each function
def can_be_optimized(self) -> Result[tuple[bool, CodeOptimizationContext, dict[Path, str]], str]:
should_run_experiment = self.experiment_id is not None
logger.debug(f"Function Trace ID: {self.function_trace_id}")
ph("cli-optimize-function-start", {"function_trace_id": self.function_trace_id})
self.cleanup_leftover_test_return_values()
file_name_from_test_module_name.cache_clear()
ctx_result = self.get_code_optimization_context()
if not is_successful(ctx_result):
return Failure(ctx_result.failure())
code_context: CodeOptimizationContext = ctx_result.unwrap()
original_helper_code: dict[Path, str] = {}
helper_function_paths = {hf.file_path for hf in code_context.helper_functions}
for helper_function_path in helper_function_paths:
with helper_function_path.open(encoding="utf8") as f:
helper_code = f.read()
original_helper_code[helper_function_path] = helper_code
# Random here means that we still attempt optimization with a fractional chance to see if
# last time we could not find an optimization, maybe this time we do.
# Random is before as a performance optimization, swapping the two 'and' statements has the same effect
if random.random() > REPEAT_OPTIMIZATION_PROBABILITY and was_function_previously_optimized( # noqa: S311
self.function_to_optimize, code_context, self.args
):
return Failure("Function optimization previously attempted, skipping.")
return Success((should_run_experiment, code_context, original_helper_code))
def generate_and_instrument_tests(
self, code_context: CodeOptimizationContext
) -> Result[
tuple[
GeneratedTestsList,
dict[str, set[FunctionCalledInTest]],
str,
list[Path],
list[Path],
set[Path],
dict | None,
],
str,
]:
"""Generate and instrument tests for the function."""
n_tests = N_TESTS_TO_GENERATE_EFFECTIVE
generated_test_paths = [
get_test_file_path(
self.test_cfg.tests_root, self.function_to_optimize.function_name, test_index, test_type="unit"
)
for test_index in range(n_tests)
]
generated_perf_test_paths = [
get_test_file_path(
self.test_cfg.tests_root, self.function_to_optimize.function_name, test_index, test_type="perf"
)
for test_index in range(n_tests)
]
test_results = self.generate_tests(
testgen_context=code_context.testgen_context,
helper_functions=code_context.helper_functions,
generated_test_paths=generated_test_paths,
generated_perf_test_paths=generated_perf_test_paths,
)
if not is_successful(test_results):
return Failure(test_results.failure())
count_tests, generated_tests, function_to_concolic_tests, concolic_test_str = test_results.unwrap()
for i, generated_test in enumerate(generated_tests.generated_tests):
with generated_test.behavior_file_path.open("w", encoding="utf8") as f:
f.write(generated_test.instrumented_behavior_test_source)
with generated_test.perf_file_path.open("w", encoding="utf8") as f:
f.write(generated_test.instrumented_perf_test_source)
self.test_files.add(
TestFile(
instrumented_behavior_file_path=generated_test.behavior_file_path,
benchmarking_file_path=generated_test.perf_file_path,
original_file_path=None,
original_source=generated_test.generated_original_test_source,
test_type=TestType.GENERATED_REGRESSION,
tests_in_file=None, # This is currently unused. We can discover the tests in the file if needed.
)
)
logger.info(f"Generated test {i + 1}/{count_tests}:")
code_print(generated_test.generated_original_test_source, file_name=f"test_{i + 1}.py")
if concolic_test_str:
logger.info(f"Generated test {count_tests}/{count_tests}:")
code_print(concolic_test_str)
function_to_all_tests = {
key: self.function_to_tests.get(key, set()) | function_to_concolic_tests.get(key, set())
for key in set(self.function_to_tests) | set(function_to_concolic_tests)
}
instrumented_unittests_created_for_function = self.instrument_existing_tests(function_to_all_tests)
original_conftest_content = None
if self.args.override_fixtures:
logger.info("Disabling all autouse fixtures associated with the generated test files")
original_conftest_content = modify_autouse_fixture(generated_test_paths + generated_perf_test_paths)
logger.info("Add custom marker to generated test files")
add_custom_marker_to_all_tests(generated_test_paths + generated_perf_test_paths)
return Success(
(
generated_tests,
function_to_concolic_tests,
concolic_test_str,
generated_test_paths,
generated_perf_test_paths,
instrumented_unittests_created_for_function,
original_conftest_content,
)
)
# note: this isn't called by the lsp, only called by cli
def optimize_function(self) -> Result[BestOptimization, str]:
initialization_result = self.can_be_optimized()
if not is_successful(initialization_result):
return Failure(initialization_result.failure())
should_run_experiment, code_context, original_helper_code = initialization_result.unwrap()
code_print(
code_context.read_writable_code.flat,
file_name=self.function_to_optimize.file_path,
function_name=self.function_to_optimize.function_name,
)
with progress_bar(
f"Generating new tests and optimizations for function '{self.function_to_optimize.function_name}'",
transient=True,
revert_to_print=bool(get_pr_number()),
):
console.rule()
# Generate tests and optimizations in parallel
future_tests = self.executor.submit(self.generate_and_instrument_tests, code_context)
future_optimizations = self.executor.submit(
self.generate_optimizations,
read_writable_code=code_context.read_writable_code,
read_only_context_code=code_context.read_only_context_code,
run_experiment=should_run_experiment,
)
concurrent.futures.wait([future_tests, future_optimizations])
test_setup_result = future_tests.result()
optimization_result = future_optimizations.result()
console.rule()
if not is_successful(test_setup_result):
return Failure(test_setup_result.failure())
if not is_successful(optimization_result):
return Failure(optimization_result.failure())
(
generated_tests,
function_to_concolic_tests,
concolic_test_str,
generated_test_paths,
generated_perf_test_paths,
instrumented_unittests_created_for_function,
original_conftest_content,
) = test_setup_result.unwrap()
optimizations_set, function_references = optimization_result.unwrap()
baseline_setup_result = self.setup_and_establish_baseline(
code_context=code_context,
original_helper_code=original_helper_code,
function_to_concolic_tests=function_to_concolic_tests,
generated_test_paths=generated_test_paths,
generated_perf_test_paths=generated_perf_test_paths,
instrumented_unittests_created_for_function=instrumented_unittests_created_for_function,
original_conftest_content=original_conftest_content,
)
if not is_successful(baseline_setup_result):
return Failure(baseline_setup_result.failure())
(
function_to_optimize_qualified_name,
function_to_all_tests,
original_code_baseline,
test_functions_to_remove,
file_path_to_helper_classes,
) = baseline_setup_result.unwrap()
best_optimization = self.find_and_process_best_optimization(
optimizations_set=optimizations_set,
code_context=code_context,
original_code_baseline=original_code_baseline,
original_helper_code=original_helper_code,
file_path_to_helper_classes=file_path_to_helper_classes,
function_to_optimize_qualified_name=function_to_optimize_qualified_name,
function_to_all_tests=function_to_all_tests,
generated_tests=generated_tests,
test_functions_to_remove=test_functions_to_remove,
concolic_test_str=concolic_test_str,
function_references=function_references,
)
# Add function to code context hash if in gh actions
add_code_context_hash(code_context.hashing_code_context_hash)
if self.args.override_fixtures:
restore_conftest(original_conftest_content)
if not best_optimization:
return Failure(f"No best optimizations found for function {self.function_to_optimize.qualified_name}")
return Success(best_optimization)
def get_trace_id(self, exp_type: str) -> str:
"""Get the trace ID for the current experiment type."""
if self.experiment_id:
return self.function_trace_id[:-4] + exp_type
return self.function_trace_id
def build_runtime_info_tree(
self,
candidate_index: int,
candidate_result: OptimizedCandidateResult,
original_code_baseline: OriginalCodeBaseline,
perf_gain: float,
*,
is_successful_candidate: bool,
) -> Tree:
"""Build a Tree display for runtime information of a candidate."""
tree = Tree(f"Candidate #{candidate_index} - Runtime Information ⌛")
is_async = original_code_baseline.async_throughput is not None and candidate_result.async_throughput is not None
if is_successful_candidate:
if is_async:
throughput_gain_value = throughput_gain(
original_throughput=original_code_baseline.async_throughput,
optimized_throughput=candidate_result.async_throughput,
)
tree.add("This candidate has better async throughput than the original code. 🚀")
tree.add(f"Original async throughput: {original_code_baseline.async_throughput} executions")
tree.add(f"Optimized async throughput: {candidate_result.async_throughput} executions")
tree.add(f"Throughput improvement: {throughput_gain_value * 100:.1f}%")
tree.add(f"Throughput ratio: {throughput_gain_value + 1:.3f}X")
else:
tree.add("This candidate is faster than the original code. 🚀")
tree.add(f"Original summed runtime: {humanize_runtime(original_code_baseline.runtime)}")
tree.add(
f"Best summed runtime: {humanize_runtime(candidate_result.best_test_runtime)} "
f"(measured over {candidate_result.max_loop_count} "
f"loop{'s' if candidate_result.max_loop_count > 1 else ''})"
)
tree.add(f"Speedup percentage: {perf_gain * 100:.1f}%")
tree.add(f"Speedup ratio: {perf_gain + 1:.3f}X")
# Not a successful optimization candidate
elif is_async:
throughput_gain_value = throughput_gain(
original_throughput=original_code_baseline.async_throughput,
optimized_throughput=candidate_result.async_throughput,
)
tree.add(f"Async throughput: {candidate_result.async_throughput} executions")
tree.add(f"Throughput change: {throughput_gain_value * 100:.1f}%")
tree.add(
f"(Runtime for reference: {humanize_runtime(candidate_result.best_test_runtime)} over "
f"{candidate_result.max_loop_count} loop{'s' if candidate_result.max_loop_count > 1 else ''})"
)
else:
tree.add(
f"Summed runtime: {humanize_runtime(candidate_result.best_test_runtime)} "
f"(measured over {candidate_result.max_loop_count} "
f"loop{'s' if candidate_result.max_loop_count > 1 else ''})"
)
tree.add(f"Speedup percentage: {perf_gain * 100:.1f}%")
tree.add(f"Speedup ratio: {perf_gain + 1:.3f}X")
return tree
def handle_successful_candidate(
self,
candidate: OptimizedCandidate,
candidate_result: OptimizedCandidateResult,
code_context: CodeOptimizationContext,
original_code_baseline: OriginalCodeBaseline,
original_helper_code: dict[Path, str],
candidate_index: int,
eval_ctx: CandidateEvaluationContext,
) -> tuple[BestOptimization, Tree | None]:
"""Handle a successful optimization candidate.
Returns the BestOptimization and optional benchmark tree.
"""
with progress_bar("Running line-by-line profiling"):
line_profile_test_results = self.line_profiler_step(
code_context=code_context, original_helper_code=original_helper_code, candidate_index=candidate_index
)
eval_ctx.record_line_profiler_result(candidate.optimization_id, line_profile_test_results["str_out"])
replay_perf_gain = {}
benchmark_tree = None
if self.args.benchmark:
test_results_by_benchmark = candidate_result.benchmarking_test_results.group_by_benchmarks(
self.total_benchmark_timings.keys(), self.replay_tests_dir, self.project_root
)
if len(test_results_by_benchmark) > 0:
benchmark_tree = Tree("Speedup percentage on benchmarks:")
for benchmark_key, candidate_test_results in test_results_by_benchmark.items():
original_code_replay_runtime = original_code_baseline.replay_benchmarking_test_results[
benchmark_key
].total_passed_runtime()
candidate_replay_runtime = candidate_test_results.total_passed_runtime()
replay_perf_gain[benchmark_key] = performance_gain(
original_runtime_ns=original_code_replay_runtime, optimized_runtime_ns=candidate_replay_runtime
)
benchmark_tree.add(f"{benchmark_key}: {replay_perf_gain[benchmark_key] * 100:.1f}%")
best_optimization = BestOptimization(
candidate=candidate,
helper_functions=code_context.helper_functions,
code_context=code_context,
runtime=candidate_result.best_test_runtime,
line_profiler_test_results=line_profile_test_results,
winning_behavior_test_results=candidate_result.behavior_test_results,
replay_performance_gain=replay_perf_gain if self.args.benchmark else None,
winning_benchmarking_test_results=candidate_result.benchmarking_test_results,
winning_replay_benchmarking_test_results=candidate_result.benchmarking_test_results,
async_throughput=candidate_result.async_throughput,
)
return best_optimization, benchmark_tree
def select_best_optimization(
self,
eval_ctx: CandidateEvaluationContext,
code_context: CodeOptimizationContext,
original_code_baseline: OriginalCodeBaseline,
ai_service_client: AiServiceClient,
exp_type: str,
function_references: str,
) -> BestOptimization | None:
"""Select the best optimization from valid candidates."""
if not eval_ctx.valid_optimizations:
return None
valid_candidates_with_shorter_code = []
diff_lens_list = [] # character level diff
speedups_list = []
optimization_ids = []
diff_strs = []
runtimes_list = []
for valid_opt in eval_ctx.valid_optimizations:
valid_opt_normalized_code = normalize_code(valid_opt.candidate.source_code.flat.strip())
new_candidate_with_shorter_code = OptimizedCandidate(
source_code=eval_ctx.ast_code_to_id[valid_opt_normalized_code]["shorter_source_code"],
optimization_id=valid_opt.candidate.optimization_id,
explanation=valid_opt.candidate.explanation,
source=valid_opt.candidate.source,
parent_id=valid_opt.candidate.parent_id,
)
new_best_opt = BestOptimization(
candidate=new_candidate_with_shorter_code,
helper_functions=valid_opt.helper_functions,
code_context=valid_opt.code_context,
runtime=valid_opt.runtime,
line_profiler_test_results=valid_opt.line_profiler_test_results,
winning_behavior_test_results=valid_opt.winning_behavior_test_results,
replay_performance_gain=valid_opt.replay_performance_gain,
winning_benchmarking_test_results=valid_opt.winning_benchmarking_test_results,
winning_replay_benchmarking_test_results=valid_opt.winning_replay_benchmarking_test_results,
async_throughput=valid_opt.async_throughput,
)
valid_candidates_with_shorter_code.append(new_best_opt)
diff_lens_list.append(
diff_length(new_best_opt.candidate.source_code.flat, code_context.read_writable_code.flat)
)
diff_strs.append(
unified_diff_strings(code_context.read_writable_code.flat, new_best_opt.candidate.source_code.flat)
)
speedups_list.append(
1
+ performance_gain(
original_runtime_ns=original_code_baseline.runtime, optimized_runtime_ns=new_best_opt.runtime
)
)
optimization_ids.append(new_best_opt.candidate.optimization_id)
runtimes_list.append(new_best_opt.runtime)
if len(optimization_ids) > 1:
future_ranking = self.executor.submit(
ai_service_client.generate_ranking,
diffs=diff_strs,
optimization_ids=optimization_ids,
speedups=speedups_list,
trace_id=self.get_trace_id(exp_type),
function_references=function_references,
)
concurrent.futures.wait([future_ranking])
ranking = future_ranking.result()
if ranking:
min_key = ranking[0]
else:
diff_lens_ranking = create_rank_dictionary_compact(diff_lens_list)
runtimes_ranking = create_rank_dictionary_compact(runtimes_list)
overall_ranking = {key: diff_lens_ranking[key] + runtimes_ranking[key] for key in diff_lens_ranking}
min_key = min(overall_ranking, key=overall_ranking.get)
elif len(optimization_ids) == 1:
min_key = 0
else:
return None
return valid_candidates_with_shorter_code[min_key]
def log_evaluation_results(
self,
eval_ctx: CandidateEvaluationContext,
best_optimization: BestOptimization,
original_code_baseline: OriginalCodeBaseline,
ai_service_client: AiServiceClient,
exp_type: str,
) -> None:
"""Log evaluation results to the AI service."""
ai_service_client.log_results(
function_trace_id=self.get_trace_id(exp_type),
speedup_ratio=eval_ctx.speedup_ratios,
original_runtime=original_code_baseline.runtime,
optimized_runtime=eval_ctx.optimized_runtimes,
is_correct=eval_ctx.is_correct,
optimized_line_profiler_results=eval_ctx.optimized_line_profiler_results,
optimizations_post=eval_ctx.optimizations_post,
metadata={"best_optimization_id": best_optimization.candidate.optimization_id},
)
def process_single_candidate(
self,
candidate: OptimizedCandidate,
candidate_index: int,
total_candidates: int,
code_context: CodeOptimizationContext,
original_code_baseline: OriginalCodeBaseline,
original_helper_code: dict[Path, str],
file_path_to_helper_classes: dict[Path, set[str]],
eval_ctx: CandidateEvaluationContext,
all_refinements_data: list[AIServiceRefinerRequest],
exp_type: str,
function_references: str,
) -> BestOptimization | None:
"""Process a single optimization candidate.
Returns the BestOptimization if the candidate is successful, None otherwise.
Updates eval_ctx with results and may append to all_refinements_data.
"""
# Cleanup temp files
get_run_tmp_file(Path(f"test_return_values_{candidate_index}.bin")).unlink(missing_ok=True)
get_run_tmp_file(Path(f"test_return_values_{candidate_index}.sqlite")).unlink(missing_ok=True)
logger.info(f"h3|Optimization candidate {candidate_index}/{total_candidates}:")
code_print(
candidate.source_code.flat,
file_name=f"candidate_{candidate_index}.py",
lsp_message_id=LSPMessageId.CANDIDATE.value,
)
# Try to replace function with optimized code
try:
did_update = self.replace_function_and_helpers_with_optimized_code(
code_context=code_context,
optimized_code=candidate.source_code,
original_helper_code=original_helper_code,
)
if not did_update:
logger.warning(
"force_lsp|No functions were replaced in the optimized code. Skipping optimization candidate."
)
console.rule()
return None
except (ValueError, SyntaxError, cst.ParserSyntaxError, AttributeError) as e:
logger.error(e)
self.write_code_and_helpers(
self.function_to_optimize_source_code, original_helper_code, self.function_to_optimize.file_path
)
return None
# Check for duplicate candidates
normalized_code = normalize_code(candidate.source_code.flat.strip())
if normalized_code in eval_ctx.ast_code_to_id:
logger.info("Current candidate has been encountered before in testing, Skipping optimization candidate.")
eval_ctx.handle_duplicate_candidate(candidate, normalized_code, code_context)
return None
eval_ctx.register_new_candidate(normalized_code, candidate, code_context)
# Run the optimized candidate
run_results = self.run_optimized_candidate(
optimization_candidate_index=candidate_index,
baseline_results=original_code_baseline,
original_helper_code=original_helper_code,
file_path_to_helper_classes=file_path_to_helper_classes,
code_context=code_context,
candidate=candidate,
exp_type=exp_type,
)
console.rule()
if not is_successful(run_results):
eval_ctx.record_failed_candidate(candidate.optimization_id)
return None
candidate_result: OptimizedCandidateResult = run_results.unwrap()
perf_gain = performance_gain(
original_runtime_ns=original_code_baseline.runtime, optimized_runtime_ns=candidate_result.best_test_runtime
)
eval_ctx.record_successful_candidate(candidate.optimization_id, candidate_result.best_test_runtime, perf_gain)
# Check if this is a successful optimization
is_successful_opt = speedup_critic(
candidate_result,
original_code_baseline.runtime,
best_runtime_until_now=None,
original_async_throughput=original_code_baseline.async_throughput,
best_throughput_until_now=None,
) and quantity_of_tests_critic(candidate_result)
tree = self.build_runtime_info_tree(
candidate_index=candidate_index,
candidate_result=candidate_result,
original_code_baseline=original_code_baseline,
perf_gain=perf_gain,
is_successful_candidate=is_successful_opt,
)
best_optimization = None
benchmark_tree = None
if is_successful_opt:
best_optimization, benchmark_tree = self.handle_successful_candidate(
candidate=candidate,
candidate_result=candidate_result,
code_context=code_context,
original_code_baseline=original_code_baseline,
original_helper_code=original_helper_code,
candidate_index=candidate_index,
eval_ctx=eval_ctx,
)
eval_ctx.valid_optimizations.append(best_optimization)
# Queue refinement for non-refined candidates
if candidate.source != OptimizedCandidateSource.REFINE:
all_refinements_data.append(
AIServiceRefinerRequest(
optimization_id=best_optimization.candidate.optimization_id,
original_source_code=code_context.read_writable_code.markdown,
read_only_dependency_code=code_context.read_only_context_code,
original_code_runtime=original_code_baseline.runtime,
optimized_source_code=best_optimization.candidate.source_code.markdown,
optimized_explanation=best_optimization.candidate.explanation,
optimized_code_runtime=best_optimization.runtime,
speedup=f"{int(performance_gain(original_runtime_ns=original_code_baseline.runtime, optimized_runtime_ns=best_optimization.runtime) * 100)}%",
trace_id=self.get_trace_id(exp_type),
original_line_profiler_results=original_code_baseline.line_profile_results["str_out"],
optimized_line_profiler_results=best_optimization.line_profiler_test_results["str_out"],
function_references=function_references,
)
)
# Display runtime information
if is_LSP_enabled():
lsp_log(LspMarkdownMessage(markdown=tree_to_markdown(tree)))
else:
console.print(tree)
if self.args.benchmark and benchmark_tree:
console.print(benchmark_tree)
console.rule()
return best_optimization
def determine_best_candidate(
self,
*,
candidates: list[OptimizedCandidate],
code_context: CodeOptimizationContext,
original_code_baseline: OriginalCodeBaseline,
original_helper_code: dict[Path, str],
file_path_to_helper_classes: dict[Path, set[str]],
exp_type: str,
function_references: str,
) -> BestOptimization | None:
"""Determine the best optimization candidate from a list of candidates."""
logger.info(
f"Determining best optimization candidate (out of {len(candidates)}) for "
f"{self.function_to_optimize.qualified_name}…"
)
console.rule()
# Initialize evaluation context and async tasks
eval_ctx = CandidateEvaluationContext()
all_refinements_data: list[AIServiceRefinerRequest] = []
self.future_all_code_repair.clear()
self.repair_counter = 0
ai_service_client = self.aiservice_client if exp_type == "EXP0" else self.local_aiservice_client
assert ai_service_client is not None, "AI service client must be set for optimization"
future_line_profile_results = self.executor.submit(
ai_service_client.optimize_python_code_line_profiler,
source_code=code_context.read_writable_code.markdown,
dependency_code=code_context.read_only_context_code,
trace_id=self.get_trace_id(exp_type),
line_profiler_results=original_code_baseline.line_profile_results["str_out"],
num_candidates=N_CANDIDATES_LP_EFFECTIVE,
experiment_metadata=ExperimentMetadata(
id=self.experiment_id, group="control" if exp_type == "EXP0" else "experiment"
)
if self.experiment_id
else None,
)
processor = CandidateProcessor(
candidates,
future_line_profile_results,
all_refinements_data,
self.aiservice_client,
self.executor,
self.future_all_code_repair,
)
candidate_index = 0
# Process candidates using queue-based approach
while not processor.is_done():
candidate = processor.get_next_candidate()
if candidate is None:
logger.debug("everything done, exiting")
break
try:
candidate_index += 1
self.process_single_candidate(
candidate=candidate,
candidate_index=candidate_index,
total_candidates=processor.candidate_len,
code_context=code_context,
original_code_baseline=original_code_baseline,
original_helper_code=original_helper_code,
file_path_to_helper_classes=file_path_to_helper_classes,
eval_ctx=eval_ctx,
all_refinements_data=all_refinements_data,
exp_type=exp_type,
function_references=function_references,
)
except KeyboardInterrupt as e:
logger.exception(f"Optimization interrupted: {e}")
raise
finally:
self.write_code_and_helpers(
self.function_to_optimize_source_code, original_helper_code, self.function_to_optimize.file_path
)
# Select and return the best optimization
best_optimization = self.select_best_optimization(
eval_ctx=eval_ctx,
code_context=code_context,
original_code_baseline=original_code_baseline,
ai_service_client=ai_service_client,
exp_type=exp_type,
function_references=function_references,
)
if best_optimization:
self.log_evaluation_results(
eval_ctx=eval_ctx,
best_optimization=best_optimization,
original_code_baseline=original_code_baseline,
ai_service_client=ai_service_client,
exp_type=exp_type,
)
return best_optimization
def repair_optimization(
self,