-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathgenerate_loop.py
More file actions
1189 lines (1103 loc) · 43.5 KB
/
generate_loop.py
File metadata and controls
1189 lines (1103 loc) · 43.5 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
# Copyright (c) Meta Platforms, Inc. and affiliates.
import argparse
import json
import os
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import docker
from analysis.plot_progress import plot_progress_single, plot_progress_together
from analysis.visualize_archive import (
visualize_archive_single,
visualize_archive_together,
)
from utils.common import file_exist_and_not_empty, load_json_file
from utils.constants import REPO_NAME
from utils.docker_utils import (
build_container,
cleanup_container,
copy_from_container,
copy_to_container,
log_container_output,
safe_log,
setup_logger,
)
from utils.domain_utils import (
can_domain_ensembled,
get_domain_eval_subset,
get_domain_splits,
get_domain_stagedeval_samples,
)
from utils.gl_utils import (
apply_diffs_container,
get_patch_files,
get_score,
load_archive_data,
run_commands_to_check_compilation,
select_parent,
setup_initial_gen,
update_and_save_archive,
update_node_metadata,
get_latest_can_select_parent,
is_starting_node,
process_meta_patch_files,
)
def run_harness_polyglot(root_dir, output_dir, genid, skip_staged_eval=False, num_samples=-1):
# NOTE: the harness for polyglot is different because each task instance needs a docker container
from domains.polyglot.harness import harness as harness_polyglot
from domains.polyglot.report import report as report_polyglot
eval_output_dir = os.path.join(output_dir, f"gen_{genid}", "polyglot_eval")
test_more_threshold = 0.4 # NOTE: same setting as that in DGM
model_name_or_path = "eval_run"
patch_files = get_patch_files(output_dir, genid)
run_next_eval = True
# Small sample size evaluation for staged eval
if not skip_staged_eval:
test_task_list = load_json_file("./domains/polyglot/subsets/small.json")
dnames = harness_polyglot(
test_task_list=test_task_list,
num_samples=-1,
max_workers=10,
model_name_or_path=model_name_or_path,
model_patch_paths=patch_files,
num_evals=1,
num_evals_parallel=1,
pred_dname=eval_output_dir,
output_dir=eval_output_dir,
root_dir=root_dir,
)
report_polyglot(output_dir=eval_output_dir, run_keyword=model_name_or_path, expected_num_tasks=len(test_task_list))
stagedeval_score = get_score("polyglot", output_dir, genid)
run_next_eval = stagedeval_score is not None and stagedeval_score >= test_more_threshold
# Check if additional evaluation should be run
if run_next_eval:
test_task_list_more = load_json_file("./domains/polyglot/subsets/medium.json")
dnames = harness_polyglot(
test_task_list=test_task_list + test_task_list_more,
num_samples=num_samples,
max_workers=10,
model_name_or_path=model_name_or_path,
model_patch_paths=patch_files,
num_evals=1,
num_evals_parallel=1,
pred_dname=eval_output_dir,
output_dir=eval_output_dir,
root_dir=root_dir,
)
report_polyglot(output_dir=eval_output_dir, run_keyword=model_name_or_path, expected_num_tasks=len(test_task_list + test_task_list_more))
# Update metadata
update_node_metadata(output_dir, genid, {"run_full_eval": run_next_eval})
def select_next_parent_container(
docker_client,
domains,
generate_output_dir,
archive,
root_dir="./",
root_commit="HEAD",
max_attempts=10,
):
# Setup logger
logger = setup_logger(os.path.join(generate_output_dir, "select_next_parent.log"))
# Get the latest node that can select parent
latest_node = get_latest_can_select_parent(archive, generate_output_dir)
safe_log(f"select_next_parent_container: latest_node={latest_node}")
prev_patch_files = get_patch_files(generate_output_dir, latest_node)
# Create and start the Docker container
image_name = f"{REPO_NAME}"
run_id = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
container_name = f"{REPO_NAME}-nextparent-container-{run_id}"
container = build_container(docker_client, root_dir, image_name, container_name, verbose=False)
container.start()
container_output_folder = "/tmp/"
try:
# Apply all lineage diffs
commit_hash = apply_diffs_container(container, prev_patch_files, verbose=False)
# Copy generate_output_dir to container
container_generate_output_dir = os.path.join(
container_output_folder, generate_output_dir.split(os.sep)[-1]
)
copy_to_container(
container,
source_path=generate_output_dir,
dest_path=container_generate_output_dir,
verbose=False,
)
# Get next parent in container
command = [
"timeout",
"3600", # 1h timeout
"python",
"-m",
"utils.run_select_next_parent",
"--domains",
*domains,
"--generate_output_dir",
container_generate_output_dir,
]
exec_result = container.exec_run(cmd=command, workdir=f"/{REPO_NAME}")
log_container_output(exec_result, verbose=True)
# Get next parent outputs
container_output_strings = exec_result.output.decode().strip().split("\n")
next_parent_genid = container_output_strings[-1]
next_parent_genid = int(next_parent_genid) if not is_starting_node(next_parent_genid) else next_parent_genid
except Exception as e:
safe_log(f"Error in select_next_parent_container: {e}")
update_node_metadata(generate_output_dir, latest_node, {"can_select_next_parent": False})
next_parent_genid = None
# Even on errors or KeyboardInterrupt
finally:
# Reset to the root commit
exec_result = container.exec_run(
cmd=["git", "reset", "--hard", root_commit], workdir=f"/{REPO_NAME}"
)
log_container_output(exec_result, verbose=False)
exec_result = container.exec_run(
cmd=["git", "clean", "-fd"], workdir=f"/{REPO_NAME}"
)
log_container_output(exec_result, verbose=False)
# Cleanup container
cleanup_container(container, verbose=False)
# Try again if no parent is selected
if next_parent_genid is None:
if max_attempts > 0:
next_parent_genid = select_next_parent_container(
docker_client,
domains,
generate_output_dir,
archive,
root_dir,
root_commit,
max_attempts=max_attempts - 1,
)
else:
# In case of infinite recursive, but it should not happen
raise Exception("Max attempts reached in select_next_parent_container")
return next_parent_genid
def get_ensemble_scores_container(
docker_client,
domain,
generate_output_dir,
gen_output_dir,
root_dir="./",
root_commit="HEAD",
prev_patch_files=[],
num_samples=-1,
max_workers=5,
subsets=[],
):
# Setup logger
logger = setup_logger(os.path.join(gen_output_dir, "ensemble.log"))
# Create and start the Docker container
image_name = f"{REPO_NAME}"
run_id = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
container_name = f"{REPO_NAME}-ens-container-{run_id}"
container = build_container(docker_client, root_dir, image_name, container_name)
container.start()
container_output_folder = "/tmp/"
try:
# Apply all lineage diffs
commit_hash = apply_diffs_container(container, prev_patch_files)
# Copy generate_output_dir to container
container_generate_output_dir = os.path.join(
container_output_folder, generate_output_dir.split(os.sep)[-1]
)
copy_to_container(
container,
source_path=generate_output_dir,
dest_path=container_generate_output_dir,
)
# Get ensemble scores in container
scores = []
for subset in subsets:
command = [
"timeout",
"10800", # 3h timeout
"python",
"-m",
"utils.run_ensemble",
"--domain",
domain,
"--generate_output_dir",
container_generate_output_dir,
"--num_samples",
str(num_samples),
"--max_workers",
str(max_workers),
"--subset",
subset,
]
exec_result = container.exec_run(cmd=command, workdir=f"/{REPO_NAME}")
log_container_output(exec_result)
# Get ensemble outputs
container_output_strings = exec_result.output.decode().strip().split("\n")
score = float(container_output_strings[-3])
scores.append(score)
container_predictions_path = container_output_strings[-2]
container_report_path = container_output_strings[-1]
# Copy container outputs to local
predictions_file = os.path.basename(container_predictions_path)
report_file = os.path.basename(container_report_path)
local_predictions_path = os.path.join(gen_output_dir, predictions_file)
local_report_path = os.path.join(gen_output_dir, report_file)
copy_from_container(
container,
source_path=container_predictions_path,
dest_path=local_predictions_path,
)
copy_from_container(
container,
source_path=container_report_path,
dest_path=local_report_path,
)
except Exception as e:
safe_log(f"Error in get_ensemble_scores_container: {e}")
scores = [None] * len(subsets)
# Even on errors or KeyboardInterrupt
finally:
# Reset to the root commit
exec_result = container.exec_run(
cmd=["git", "reset", "--hard", root_commit], workdir=f"/{REPO_NAME}"
)
log_container_output(exec_result)
exec_result = container.exec_run(
cmd=["git", "clean", "-fd"], workdir=f"/{REPO_NAME}"
)
log_container_output(exec_result)
# Cleanup container
cleanup_container(container)
return scores
def eval_produced_agent(
container,
container_output_folder,
gen_output_dir,
domain,
eval_samples=-1,
eval_workers=10,
eval_subset="_filtered_100_train",
eval_test=False,
):
# Evaluate the produced agent
splits = get_domain_splits(domain, eval_test=eval_test)
for split in splits: # pyright: ignore
safe_log(f"Evaluating the produced agent on {domain} {eval_samples} {split}...")
eval_run_id = f"{domain}_eval" if split == "train" else f"{domain}_eval_{split}"
container_evaloutput_folder = os.path.join(container_output_folder, eval_run_id)
command = [
"timeout",
"18000", # 5h timeout
"python",
"-m",
"domains.harness",
"--agent_path",
"./task_agent.py",
"--output_dir",
container_output_folder,
"--run_id",
eval_run_id,
"--domain",
domain,
"--num_samples",
str(eval_samples),
"--num_workers",
str(eval_workers),
"--subset",
eval_subset.replace("_train", f"_{split}"),
]
exec_result = container.exec_run(cmd=command, workdir=f"/{REPO_NAME}")
log_container_output(exec_result)
command = [
"timeout",
"10800", # 3h timeout
"python",
"-m",
"domains.report",
"--domain",
domain,
"--dname",
os.path.join(container_output_folder, eval_run_id),
]
exec_result = container.exec_run(cmd=command, workdir=f"/{REPO_NAME}")
log_container_output(exec_result)
# Copy container outputs to local, evaluation results
evaloutput_folder = os.path.join(gen_output_dir, eval_run_id)
copy_from_container(
container,
source_path=container_evaloutput_folder,
dest_path=evaloutput_folder,
)
def copy_prev_eval_to_container(
container,
prev_eval_path,
container_output_folder,
current_genid=None,
container_folder_name=None,
):
"""Copy the entire prev_eval_path into the container, then remove unwanted files/dirs in the container"""
if not os.path.exists(prev_eval_path):
raise FileNotFoundError(f"Previous eval path not found: {prev_eval_path}")
# Normalize and construct destination path in container
prev_eval_path = os.path.normpath(prev_eval_path)
tail = os.path.join(*prev_eval_path.split(os.sep)[-1:])
container_prev_eval_path = os.path.join(container_output_folder, tail)
# Ensure destination parent exists
container.exec_run(["mkdir", "-p", container_output_folder], workdir="/")
# Copy the whole tree into the container in one go
copy_to_container(
container, source_path=prev_eval_path, dest_path=container_prev_eval_path
)
# Now prune inside the container
prune_cmds = [
# Remove current genid folder
f"find '{container_prev_eval_path}' -type d -name 'gen_{current_genid}' -prune -exec rm -rf {{}} +",
# 1) Remove val/test eval directories
f"find '{container_prev_eval_path}' -type d -name '*_eval_val*' -prune -exec rm -rf {{}} +",
f"find '{container_prev_eval_path}' -type d -name '*_eval_test*' -prune -exec rm -rf {{}} +",
# 2) Remove any directories containing the repo name (copied worktrees, etc.)
f"find '{container_prev_eval_path}' -type d -name '*{REPO_NAME}*' -prune -exec rm -rf {{}} +",
# 3) Remove compiled Python files
f"find '{container_prev_eval_path}' -type f -name '*.pyc' -delete",
# 4) Remove files whose base name indicates val/test (with/without extensions)
# *_val, *_val.*, *_val_*, and same for _test
f"find '{container_prev_eval_path}' -type f \\( -name '*_val' -o -name '*_val.*' -o -name '*_val_*' \\) -delete",
f"find '{container_prev_eval_path}' -type f \\( -name '*_test' -o -name '*_test.*' -o -name '*_test_*' \\) -delete",
]
for cmd in prune_cmds:
exec_result = container.exec_run(["bash", "-lc", cmd], workdir="/")
# Confirm files remaining were copied
exec_result = container.exec_run(
["ls", "-l", container_prev_eval_path], workdir="/"
)
log_container_output(exec_result)
# Move the folder to a new name
if container_folder_name is not None:
new_container_prev_eval_path = os.path.join(
container_output_folder, container_folder_name
)
container.exec_run(
["mv", container_prev_eval_path, new_container_prev_eval_path], workdir="/"
)
log_container_output(exec_result)
container_prev_eval_path = new_container_prev_eval_path
return container_prev_eval_path
def generate(
docker_client,
domains,
output_dir,
run_id,
current_genid,
parent_genid,
root_dir,
root_commit="main",
eval_samples=-1,
eval_workers=10,
eval_subsets="_filtered_100",
meta_patch_files=None,
run_meta_agent=True,
run_baseline=None,
optimize_option="only_agent",
agent_archive_path=None,
eval_test=False,
skip_staged_eval=False,
edit_select_parent=False,
max_generation=None,
):
# Setup local output folder
prev_gen_dir = os.path.join(output_dir, f"gen_{parent_genid}")
gen_output_dir = os.path.join(output_dir, f"gen_{current_genid}")
os.makedirs(gen_output_dir, exist_ok=True)
logger = setup_logger(os.path.join(gen_output_dir, "generate.log")) # Set up logger
metadata = {
"gen_output_dir": gen_output_dir,
"current_genid": current_genid,
"parent_genid": parent_genid,
"run_baseline": run_baseline,
"prev_patch_files": [],
"curr_patch_files": [],
"parent_agent_success": not run_meta_agent, # meta agent success if not run
"optimize_option": optimize_option,
"agent_archive_path": agent_archive_path,
"can_select_next_parent": True,
}
run_eval = not run_meta_agent # always run eval if not running meta agent
metadata["run_eval"] = run_eval
print(metadata)
# Create and start the Docker container
image_name = f"{REPO_NAME}"
container_name = f"{REPO_NAME}-gl-container-{run_id}"
container = build_container(
docker_client,
root_dir,
image_name,
container_name,
domains=domains,
)
container.start()
container_output_folder = "/tmp/"
try:
# Make a copy of the repo
if run_baseline and "no_selfimprove" in run_baseline:
donottouch_reponame = f"/DONOTTOUCH_{REPO_NAME}"
exec_result = container.exec_run(
cmd=["cp", "-r", f"/{REPO_NAME}", donottouch_reponame],
workdir=f"/",
)
log_container_output(exec_result)
meta_patch_files = meta_patch_files or []
_ = apply_diffs_container(container, meta_patch_files, repo_name=donottouch_reponame)
# Apply meta patches (only for starting node, because subsequent generations will inherit the patches from the parent)
if is_starting_node(current_genid):
meta_patch_files = meta_patch_files or []
commit_hash = apply_diffs_container(container, meta_patch_files)
metadata["prev_patch_files"] += meta_patch_files
# Apply all lineage diffs
patch_files = get_patch_files(output_dir, parent_genid)
metadata["prev_patch_files"] += patch_files
commit_hash = apply_diffs_container(container, patch_files)
if run_meta_agent:
if run_baseline and "dgm" in run_baseline:
# Get problem statement (DGM specific)
from baselines.dgm.utils import get_problem_statement
problem_statement = get_problem_statement(
root_dir, output_dir, parent_genid, domains,
customized="custom" in run_baseline,
)
else:
# Copy another agent archive to container
if optimize_option == "only_ensemble":
container_agent_archive_path = copy_prev_eval_to_container(
container,
agent_archive_path,
container_output_folder,
current_genid=current_genid,
container_folder_name="agent_archive",
)
# Copy previous generations to container
if run_baseline == "no_archive":
container_prev_eval_path = os.path.join(
container_output_folder, *prev_gen_dir.split(os.sep)[-2:]
)
copy_to_container(
container,
source_path=prev_gen_dir,
dest_path=container_prev_eval_path,
)
else:
container_prev_eval_path = copy_prev_eval_to_container(
container, output_dir, container_output_folder, current_genid=current_genid,
)
# Run meta agent
safe_log("Running meta agent...")
container_agentoutput_folder = os.path.join(
container_output_folder, "agent_output"
)
container_chat_history_file = os.path.join(
container_agentoutput_folder, "meta_agent_chat_history.md"
)
if run_baseline and "dgm" in run_baseline:
command = [
"timeout",
"21600", # 6h timeout
"python",
"coding_agent.py",
"--problem_statement",
problem_statement,
"--chat_history_file",
container_chat_history_file,
"--git_dir",
f"/{REPO_NAME}",
"--base_commit",
commit_hash,
"--outdir",
container_agentoutput_folder,
]
else:
command = [
"timeout",
"21600", # 6h timeout
"python",
"run_meta_agent.py",
"--chat_history_file",
container_chat_history_file,
"--repo_path",
f"/{REPO_NAME}/",
"--evals_folder",
container_prev_eval_path,
"--git_dir",
f"/{REPO_NAME}",
"--base_commit",
commit_hash,
"--outdir",
container_agentoutput_folder,
"--iterations_left",
str(max_generation - current_genid),
*(
# If domain is polyglot, for a fair comparison with DGM
["--model", "claude-3-5-sonnet-20241022"] if domains == ["polyglot"] else []
),
]
run_workdir = (
f"/DONOTTOUCH_{REPO_NAME}"
if run_baseline and "no_selfimprove" in run_baseline
else f"/{REPO_NAME}"
)
exec_result = container.exec_run(cmd=command, workdir=run_workdir)
log_container_output(exec_result)
metadata["parent_agent_success"] = exec_result.exit_code == 0
# Copy container outputs to local
local_agentoutput_folder = os.path.join(gen_output_dir, "agent_output/")
copy_from_container(
container,
source_path=container_agentoutput_folder,
dest_path=local_agentoutput_folder,
)
# Check if agent produced a diff
local_patch_file = os.path.join(
local_agentoutput_folder, "model_patch.diff"
)
metadata["curr_patch_files"].append(local_patch_file)
run_eval = file_exist_and_not_empty(local_patch_file)
metadata["run_eval"] = run_eval
# Run commands to check if the agents are compilable
run_commands_to_check_compilation(container, run_baseline=run_baseline, edit_select_parent=edit_select_parent)
# Evaluate the produced agent
if run_eval and "agent" in optimize_option:
log_path = os.path.join(gen_output_dir, "generate.log")
def eval_agent_worker(domain, eval_subset, eval_n):
setup_logger(log_path) # Re-setup logger because of threading
eval_produced_agent(
container,
container_output_folder,
gen_output_dir,
domain=domain,
eval_samples=eval_n,
eval_workers=eval_workers,
eval_subset=eval_subset,
eval_test=eval_test,
)
# Small sample size evaluation for staged eval
if not skip_staged_eval:
stagedeval_samples = [
get_domain_stagedeval_samples(domain) for domain in domains
]
with ThreadPoolExecutor() as executor:
futures = [
executor.submit(eval_agent_worker, d, s, n)
for d, s, n in zip(domains, eval_subsets, stagedeval_samples)
]
try:
for f in futures:
f.result()
except Exception as e:
# Cancel all other futures if any job fails
for future in futures:
if not future.done():
future.cancel()
raise
stagedeval_scores = [
get_score(domain, output_dir, current_genid) for domain in domains
]
run_next_eval = all(
[x is not None and x > 0 for x in stagedeval_scores]
)
else:
run_next_eval = True
# Full evaluation
if run_next_eval:
_per_domain_eval_samples = eval_samples
with ThreadPoolExecutor() as executor:
futures = [
executor.submit(eval_agent_worker, d, s, n)
for d, s, n in zip(
domains, eval_subsets, _per_domain_eval_samples
)
]
try:
for f in futures:
f.result()
except Exception as e:
# Cancel all other futures if any job fails
for future in futures:
if not future.done():
future.cancel()
raise
metadata["run_full_eval"] = True
except Exception as e:
safe_log(f"Error in generate: {e}")
metadata["run_eval"] = False
# Even on errors or KeyboardInterrupt
finally:
# Reset to the root commit
exec_result = container.exec_run(
cmd=["git", "reset", "--hard", root_commit], workdir=f"/{REPO_NAME}"
)
log_container_output(exec_result)
exec_result = container.exec_run(
cmd=["git", "clean", "-fd"], workdir=f"/{REPO_NAME}"
)
log_container_output(exec_result)
# Cleanup container
cleanup_container(container)
# Save metadata
eval_successful = all(
[
get_score(domain, output_dir, current_genid) is not None
for domain in domains
]
)
metadata["valid_parent"] = metadata["run_eval"] and (eval_successful or meta_patch_files is not None)
with open(os.path.join(gen_output_dir, "metadata.json"), "w") as f:
json.dump(metadata, f, indent=4)
return metadata
def generate_loop(
domains,
run_id=None,
max_generation=3,
eval_samples=-1,
eval_workers=5,
eval_subsets=[],
parent_selection="score_prop",
resume_from=None,
output_dir_parent=None,
meta_patch_files=None,
reset_task_agent=False,
reset_meta_agent=False,
copy_root_dir=None, # To have the same initial repo
run_baseline=None,
optimize_option="only_agent",
agent_archive_path=None,
eval_test=False,
skip_staged_eval=False,
edit_select_parent=False,
):
# Initialization
docker_client = docker.DockerClient()
parent_selection = "latest" if run_baseline == "no_archive" else parent_selection
if resume_from:
output_dir = os.path.normpath(os.path.abspath(resume_from))
run_id = os.path.basename(output_dir).split("generate_")[-1]
root_dir, root_commit = setup_initial_gen(
output_dir,
domains,
copy_root_dir=copy_root_dir,
subsets=eval_subsets,
resume=True,
optimize_option=optimize_option,
run_baseline=run_baseline,
eval_test=eval_test,
edit_select_parent=edit_select_parent,
)
archive = load_archive_data(
os.path.join(output_dir, "archive.jsonl"), last_only=True
)[
"archive"
] # pyright: ignore
else:
run_id = (
datetime.now().strftime("%Y%m%d_%H%M%S_%f") if run_id is None else run_id
)
output_dir_parent = (
os.path.join(os.getcwd(), "outputs/")
if output_dir_parent is None
else output_dir_parent
)
output_dir = os.path.normpath(
os.path.join(output_dir_parent, f"generate_{run_id}/")
)
os.makedirs(output_dir, exist_ok=True)
root_dir, root_commit = setup_initial_gen(
output_dir,
domains,
copy_root_dir=copy_root_dir,
subsets=eval_subsets,
resume=False,
optimize_option=optimize_option,
run_baseline=run_baseline,
eval_test=eval_test,
edit_select_parent=edit_select_parent,
)
# Create initial node
if meta_patch_files is None or len(meta_patch_files) <= 0:
archive = update_and_save_archive(output_dir, [], new_node="initial")
metadata = {
"gen_output_dir": os.path.join(output_dir, f"gen_initial"),
"prev_patch_files": [],
"curr_patch_files": [],
"run_eval": True,
}
elif reset_task_agent:
# Task agent is the same as initial agent
meta_patch_files = process_meta_patch_files(meta_patch_files, output_dir, reset_task_agent=reset_task_agent, reset_meta_agent=reset_meta_agent)
archive = update_and_save_archive(output_dir, [], new_node="initial")
gen_output_dir = os.path.join(output_dir, f"gen_initial")
metadata = {
"gen_output_dir": gen_output_dir,
"current_genid": "initial",
"parent_genid": None,
"run_baseline": run_baseline,
"prev_patch_files": meta_patch_files,
"curr_patch_files": [],
"optimize_option": optimize_option,
"agent_archive_path": agent_archive_path,
"can_select_next_parent": True,
"run_eval": True,
"run_full_eval": False,
"valid_parent": True,
}
with open(os.path.join(gen_output_dir, "metadata.json"), "w") as f:
json.dump(metadata, f, indent=4)
else:
# Process meta patch files
meta_patch_files = process_meta_patch_files(meta_patch_files, output_dir, reset_task_agent=reset_task_agent, reset_meta_agent=reset_meta_agent)
# add node 0, which is the evaled version of the patches applied
archive = update_and_save_archive(output_dir, [], new_node=0)
metadata = generate(
docker_client,
[d for d in domains if d != "polyglot"],
output_dir,
run_id,
current_genid=0,
parent_genid=None,
root_dir=root_dir,
root_commit=root_commit,
eval_samples=eval_samples,
eval_workers=eval_workers,
eval_subsets=eval_subsets,
meta_patch_files=meta_patch_files,
run_meta_agent=False,
run_baseline=run_baseline,
optimize_option=optimize_option,
agent_archive_path=agent_archive_path,
eval_test=eval_test,
skip_staged_eval=skip_staged_eval,
edit_select_parent=edit_select_parent,
max_generation=max_generation,
)
print(f"generate_loop: generation 0 completed, parent None")
# Evaluate the agent on polyglot if needed
if "polyglot" in domains:
run_harness_polyglot(root_dir, output_dir, 0, skip_staged_eval=skip_staged_eval, num_samples=eval_samples[domains.index("polyglot")])
# Evaluate the entire archive as an ensemble
eval_ensemble = (
"ensemble" in optimize_option
and all(can_domain_ensembled(domain) for domain in domains)
and run_baseline != "no_archive"
)
if metadata["run_eval"] and eval_ensemble:
for domain, eval_subset, eval_n in zip(domains, eval_subsets, eval_samples):
_ = get_ensemble_scores_container(
docker_client,
domain,
(
output_dir
if optimize_option != "only_ensemble"
else agent_archive_path
),
gen_output_dir=metadata["gen_output_dir"],
root_dir=root_dir,
root_commit=root_commit,
prev_patch_files=metadata["prev_patch_files"]
+ metadata["curr_patch_files"],
num_samples=eval_n,
subsets=[
eval_subset,
eval_subset.replace("_train", "_val"),
*(
[eval_subset.replace("_train", "_test")]
if eval_test
else []
),
],
)
# Save args
with open(os.path.join(output_dir, "generate_loop.log"), "a") as f:
args_dict = locals()
args_str = ", ".join([f"{k}={v}" for k, v in args_dict.items()])
f.write(f"Args: {args_str}\n")
# Run generations
start_genid = len(archive)
if not edit_select_parent or run_baseline == "no_archive":
parent_genid = select_parent(archive, output_dir, domains, method=parent_selection)
else:
parent_genid = select_next_parent_container(
docker_client,
domains,
output_dir,
archive,
root_dir, root_commit,
)
for current_genid in range(start_genid, max_generation + 1):
metadata = generate(
docker_client,
[d for d in domains if d != "polyglot"],
output_dir,
run_id,
current_genid,
parent_genid=parent_genid,
root_dir=root_dir,
root_commit=root_commit,
eval_samples=eval_samples,
eval_workers=eval_workers,
eval_subsets=eval_subsets,
meta_patch_files=meta_patch_files,
run_meta_agent=True,
run_baseline=run_baseline,
optimize_option=optimize_option,
agent_archive_path=agent_archive_path,
eval_test=eval_test,
skip_staged_eval=skip_staged_eval,
edit_select_parent=edit_select_parent,
max_generation=max_generation,
)
# NOTE: need to update and save archive before running ensembling eval
archive = update_and_save_archive(output_dir, archive, new_node=current_genid)
# Parent agent failed, update the metadata in the parent node
if not metadata["parent_agent_success"]:
update_node_metadata(output_dir, parent_genid, {"valid_parent": False})
# Evaluate the agent on polyglot if needed
if "polyglot" in domains:
run_harness_polyglot(root_dir, output_dir, current_genid, skip_staged_eval=skip_staged_eval, num_samples=eval_samples[domains.index("polyglot")])
# Evaluate the entire archive as an ensemble
eval_ensemble = (
"ensemble" in optimize_option
and all(can_domain_ensembled(domain) for domain in domains)
and run_baseline != "no_archive"
)
if metadata["run_eval"] and eval_ensemble:
for domain, eval_subset, eval_n in zip(domains, eval_subsets, eval_samples):
_ = get_ensemble_scores_container(
docker_client,
domain,
(
output_dir
if optimize_option != "only_ensemble"
else agent_archive_path
),
gen_output_dir=metadata["gen_output_dir"],
root_dir=root_dir,
root_commit=root_commit,
prev_patch_files=metadata["prev_patch_files"]
+ metadata["curr_patch_files"],
num_samples=eval_n,
subsets=[
eval_subset,
eval_subset.replace("_train", "_val"),
*(
[eval_subset.replace("_train", "_test")]
if eval_test
else []
),
],
)
# Make analysis plots
# Per-domain plots
for domain in domains:
splits = get_domain_splits(domain)
if optimize_option == "only_ensemble":
score_types = ["ensemble"]
elif eval_ensemble:
score_types = ["agent", "ensemble", "max"]
else:
score_types = ["agent"]
for split in splits: # pyright: ignore
for stype in score_types:
plot_progress_single(domain, output_dir, split=split, type=stype)
visualize_archive_single(
domain, output_dir, split=split, type=stype
)
# Combined together plots across all domains (if there is more than one domain)
if len(domains) > 1:
domain_splits_sets = [set(get_domain_splits(d)) for d in domains]
common_splits = (
sorted(list(set.intersection(*domain_splits_sets)))
if domain_splits_sets
else []
)
if optimize_option == "only_ensemble":
together_score_types = ["ensemble"]
elif eval_ensemble:
together_score_types = ["agent", "ensemble", "max"]
else:
together_score_types = ["agent"]
for split in common_splits:
for stype in together_score_types: