forked from Jiayi-Pan/TinyZero
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodal_tinyzero.py
More file actions
2223 lines (2016 loc) · 94.8 KB
/
Copy pathmodal_tinyzero.py
File metadata and controls
2223 lines (2016 loc) · 94.8 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
"""
Modal wrapper for running TinyZero remotely on Modal GPUs.
This wrapper keeps all heavy work off the local machine:
1. TinyZero is cloned and installed inside the Modal image.
2. Countdown data is prepared on Modal.
3. Training is launched on a remote GPU container.
Usage examples:
modal run modal_tinyzero.py
modal run --detach modal_tinyzero.py --base-model Qwen/Qwen2.5-3B --n-gpus 2
modal run modal_tinyzero.py --prepare-data False --extra-hydra-args "critic.model.enable_gradient_checkpointing=True"
modal run modal_tinyzero.py --dataset-name gsm8k --base-model Qwen/Qwen2.5-1.5B-Instruct --n-gpus 1
modal run modal_tinyzero.py --dataset-name gsm8k --prompt-conditioning-mode mixed --base-model Qwen/Qwen2.5-1.5B-Instruct --n-gpus 1
modal run modal_tinyzero.py --dataset-name math500 --total-training-steps 250 --base-model Qwen/Qwen2.5-1.5B-Instruct --n-gpus 1
modal run --detach modal_tinyzero.py --dataset-name countdown --base-model Qwen/Qwen2.5-1.5B-Instruct --n-gpus 1 --prompt-conditioning-mode adaptive --total-training-steps 350 --seed 1
modal run --detach modal_tinyzero.py --base-model Qwen/Qwen2.5-1.5B-Instruct --n-gpus 1 --gpu-type A100-40GB
Notes:
- This wrapper targets the archived TinyZero countdown setup from GitHub.
- The default path is the 2-GPU Qwen2.5-3B run described in the TinyZero README.
- prompt-conditioning-mode=off is the single-prompt baseline; mixed is uniform round-robin; adaptive is a softmax bandit over per-family success rate.
- gpu-type defaults to A100-80GB. Use list_available_gpu_types() to see supported Modal GPU strings.
"""
from __future__ import annotations
import json
import re
import shlex
import textwrap
import ast
from collections import Counter, defaultdict
from fractions import Fraction
from functools import lru_cache
from pathlib import Path
import modal
APP_NAME = "tinyzero-modal"
REPO_URL = "https://github.com/zefangzh/TinyZero.git"
REMOTE_REPO_DIR = "/root/TinyZero"
ARTIFACT_DIR = "/root/tinyzero-artifacts"
DATA_ROOT = f"{ARTIFACT_DIR}/data"
RUN_ROOT = f"{ARTIFACT_DIR}/runs"
HF_CACHE = f"{ARTIFACT_DIR}/hf"
app = modal.App(APP_NAME)
wandb_secret = modal.Secret.from_dict({"WANDB_API_KEY": "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"})
_shared_env = {
"HF_HOME": HF_CACHE,
"TOKENIZERS_PARALLELISM": "false",
"PYTHONUNBUFFERED": "1",
}
image = (
modal.Image.from_registry("nvidia/cuda:12.1.1-devel-ubuntu22.04", add_python="3.9")
.apt_install("git", "build-essential", "curl", "ninja-build")
.run_commands(
"python -m pip install --upgrade pip setuptools wheel",
f"git clone {REPO_URL} {REMOTE_REPO_DIR}",
"python -m pip install torch==2.4.0 --index-url https://download.pytorch.org/whl/cu121",
"python -m pip install vllm==0.6.3 ray",
f"cd {REMOTE_REPO_DIR} && python -m pip install -e .",
"python -m pip install flash-attn --no-build-isolation",
"python -m pip install wandb ipython matplotlib",
)
.env(
{
**_shared_env,
"VLLM_ATTENTION_BACKEND": "XFORMERS",
"HYDRA_FULL_ERROR": "1",
}
)
)
artifacts = modal.Volume.from_name("tinyzero-artifacts", create_if_missing=True)
DATASET_SOURCES = {
"gsm8k": "openai/gsm8k",
"math500": "HuggingFaceH4/MATH-500",
"aime24": "HuggingFaceH4/aime_2024",
}
DEFAULT_GPU_TYPE = "A100-80GB"
SUPPORTED_MODAL_GPU_TYPES = {
"T4": "T4",
"L4": "L4",
"A10": "A10",
"L40S": "L40S",
"A100": "A100",
"A100-40GB": "A100-40GB",
"A100-80GB": "A100-80GB",
"RTX-PRO-6000": "RTX-PRO-6000",
"H100": "H100",
"H100!": "H100!",
"H200": "H200",
"B200": "B200",
"B200+": "B200+",
}
MODAL_GPU_MAX_COUNTS = {
"A10": 4,
"T4": 8,
"L4": 8,
"L40S": 8,
"A100": 8,
"A100-40GB": 8,
"A100-80GB": 8,
"RTX-PRO-6000": 8,
"H100": 8,
"H100!": 8,
"H200": 8,
"B200": 8,
"B200+": 8,
}
def list_available_gpu_types() -> list[str]:
"""Return Modal GPU type strings accepted by --gpu-type."""
return list(SUPPORTED_MODAL_GPU_TYPES)
def _normalize_gpu_type(gpu_type: str) -> str:
normalized = gpu_type.strip().upper()
aliases = {
"A100-40G": "A100-40GB",
"A100:40G": "A100-40GB",
"A100-80G": "A100-80GB",
"A100:80G": "A100-80GB",
"A10G": "A10",
"RTXPRO6000": "RTX-PRO-6000",
"RTX-PRO6000": "RTX-PRO-6000",
}
normalized = aliases.get(normalized, normalized)
if normalized not in SUPPORTED_MODAL_GPU_TYPES:
supported = ", ".join(list_available_gpu_types())
raise ValueError(f"Unsupported gpu_type={gpu_type!r}. Supported Modal GPU types: {supported}")
return normalized
def _modal_gpu_spec(gpu_type: str, n_gpus: int) -> str:
if n_gpus < 1:
raise ValueError("n_gpus must be >= 1.")
gpu = SUPPORTED_MODAL_GPU_TYPES[_normalize_gpu_type(gpu_type)]
max_count = MODAL_GPU_MAX_COUNTS[gpu]
if n_gpus > max_count:
raise ValueError(f"Modal GPU type {gpu} supports at most {max_count} GPUs per container.")
return gpu if n_gpus == 1 else f"{gpu}:{n_gpus}"
def _repo_checkout(repo_ref: str) -> None:
import subprocess
subprocess.run(["git", "-C", REMOTE_REPO_DIR, "fetch", "--all", "--tags"], check=True)
subprocess.run(["git", "-C", REMOTE_REPO_DIR, "checkout", repo_ref], check=True)
def _countdown_family_instruction(prompt_family: str) -> str:
instructions = {
"default": "Show your work in <think> </think> tags. And return the final answer in <answer> </answer> tags, for example <answer> (1 + 2) / 3 </answer>.",
"target_first": "Work backward from the target before choosing an expression. Show your work in <think> </think> tags and return the final equation in <answer> </answer> tags.",
"build_up": "First build useful intermediate numbers from the inputs, then combine them. Show your work in <think> </think> tags and return the final equation in <answer> </answer> tags.",
"verify": "Check that each number is used at most once and verify the arithmetic before finalizing. Show your work in <think> </think> tags and return the final equation in <answer> </answer> tags.",
}
return instructions[prompt_family]
def _make_countdown_prefix(example: dict, template_type: str, prompt_family: str = "default") -> str:
target = example["target"]
numbers = example["nums"]
family_instruction = _countdown_family_instruction(prompt_family)
if template_type == "base":
return (
"A conversation between User and Assistant.\n"
"The user asks a question, and the Assistant solves it. "
"The assistant first thinks about the reasoning process in the mind "
"and then provides the user with the answer. "
f"User: Using the numbers {numbers}, create an equation that equals {target}. "
"You can use basic arithmetic operations (+, -, *, /). Use each provided "
"number exactly once, do not introduce any other numbers, and stop immediately "
f"after the closing </answer> tag. This problem is guaranteed to have a solution. {family_instruction} "
"Assistant: Let me solve this step by step.\n<think>"
)
if template_type == "qwen-instruct":
return (
"<|im_start|>system\n"
"You are a helpful assistant. You first thinks about the reasoning process "
"in the mind and then provides the user with the answer.<|im_end|>\n"
"<|im_start|>user\n"
f"Using the numbers {numbers}, create an equation that equals {target}. "
"You can use basic arithmetic operations (+, -, *, /). Use each provided "
"number exactly once, do not introduce any other numbers, and stop immediately "
f"after the closing </answer> tag. This problem is guaranteed to have a solution. {family_instruction}<|im_end|>\n"
"<|im_start|>assistant\n"
"Let me solve this step by step.\n<think>"
)
raise ValueError(f"Unsupported template_type: {template_type}")
def _normalize_countdown_numbers(numbers) -> tuple[int, ...]:
if isinstance(numbers, str):
return tuple(int(item) for item in re.findall(r"-?\d+", numbers))
return tuple(int(item) for item in list(numbers))
@lru_cache(maxsize=1_000_000)
def _countdown_solution_expression_cached(target: int, numbers_key: tuple[int, ...]) -> str | None:
target_value = Fraction(int(target), 1)
initial_items = tuple((Fraction(number, 1), str(number)) for number in numbers_key)
seen: set[tuple[tuple[int, int], ...]] = set()
def search(items: tuple[tuple[Fraction, str], ...]) -> str | None:
if len(items) == 1:
value, expr = items[0]
return expr if value == target_value else None
value_key = tuple(sorted((value.numerator, value.denominator) for value, _ in items))
if value_key in seen:
return None
seen.add(value_key)
item_count = len(items)
for i in range(item_count):
for j in range(i + 1, item_count):
a_value, a_expr = items[i]
b_value, b_expr = items[j]
rest = tuple(items[k] for k in range(item_count) if k not in {i, j})
candidates: list[tuple[Fraction, str]] = [
(a_value + b_value, f"({a_expr} + {b_expr})"),
(a_value * b_value, f"({a_expr} * {b_expr})"),
(a_value - b_value, f"({a_expr} - {b_expr})"),
(b_value - a_value, f"({b_expr} - {a_expr})"),
]
if b_value != 0:
candidates.append((a_value / b_value, f"({a_expr} / {b_expr})"))
if a_value != 0:
candidates.append((b_value / a_value, f"({b_expr} / {a_expr})"))
for candidate in candidates:
result = search(rest + (candidate,))
if result is not None:
return result
return None
return search(initial_items)
def _countdown_solution_expression(target, numbers) -> str | None:
numbers_key = tuple(sorted(_normalize_countdown_numbers(numbers)))
return _countdown_solution_expression_cached(int(target), numbers_key)
def _is_solvable_countdown_example(example: dict) -> bool:
return _countdown_solution_expression(example["target"], example["nums"]) is not None
def _extract_countdown_answer(output: str) -> str:
matches = re.findall(r"<answer>(.*?)</answer>", output, flags=re.IGNORECASE | re.DOTALL)
if not matches:
return ""
answer = matches[-1].strip()
answer = re.sub(r"<\|.*?\|>", " ", answer)
return re.sub(r"\s+", " ", answer).strip()
def _candidate_countdown_expressions(answer: str) -> list[str]:
answer = re.sub(r"\\boxed\s*\{(.*?)\}", r"\1", answer)
answer = answer.replace("^", "**")
if "=" in answer:
return [part.strip() for part in answer.split("=") if part.strip()]
return [answer.strip()] if answer.strip() else []
def _safe_eval_countdown_expr(expr: str) -> tuple[Fraction, list[Fraction]] | None:
try:
tree = ast.parse(expr, mode="eval")
except SyntaxError:
return None
used_numbers: list[Fraction] = []
def visit(node) -> Fraction | None:
if isinstance(node, ast.Expression):
return visit(node.body)
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
value = Fraction(str(node.value))
used_numbers.append(abs(value))
return value
if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
value = visit(node.operand)
if value is None:
return None
return value if isinstance(node.op, ast.UAdd) else -value
if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div)):
left = visit(node.left)
right = visit(node.right)
if left is None or right is None:
return None
if isinstance(node.op, ast.Add):
return left + right
if isinstance(node.op, ast.Sub):
return left - right
if isinstance(node.op, ast.Mult):
return left * right
if right == 0:
return None
return left / right
return None
value = visit(tree)
if value is None:
return None
return value, used_numbers
def _countdown_ground_truth_parts(gts) -> tuple[int, tuple[int, ...]] | None:
if not isinstance(gts, dict) or "target" not in gts or "numbers" not in gts:
return None
return int(gts["target"]), _normalize_countdown_numbers(gts["numbers"])
def _is_valid_countdown_ground_truth(gts) -> bool:
parts = _countdown_ground_truth_parts(gts)
if parts is None:
return True
target, numbers = parts
return _countdown_solution_expression(target, numbers) is not None
def _has_valid_countdown_equation(output: str, gts) -> bool:
parts = _countdown_ground_truth_parts(gts)
if parts is None:
return True
target, numbers = parts
answer = _extract_countdown_answer(output)
if not answer or answer.upper() == "NO_SOLUTION":
return False
expected_counts = Counter(Fraction(number, 1) for number in numbers)
target_value = Fraction(target, 1)
for expr in _candidate_countdown_expressions(answer):
evaluated = _safe_eval_countdown_expr(expr)
if evaluated is None:
continue
value, used_numbers = evaluated
if value == target_value and Counter(used_numbers) == expected_counts:
return True
return False
def _extract_gsm8k_answer(answer_text: str) -> str:
marker = "####"
if marker in answer_text:
return answer_text.split(marker, 1)[1].strip()
return answer_text.strip()
def _make_gsm8k_prompt(question: str, prompt_family: str = "default") -> str:
family_instructions = {
"default": 'Let\'s think step by step and output the final answer after "####".',
"verify": 'Reason step by step, verify each intermediate calculation, and output the final answer after "####".',
"decompose": 'Break the problem into smaller subproblems, solve them carefully, and output the final answer after "####".',
"equation_first": 'Translate the problem into equations before solving, then output the final answer after "####".',
}
instruction = family_instructions[prompt_family]
return f"{question.strip()} {instruction}"
def _make_competition_math_prompt(problem: str, prompt_family: str = "default") -> str:
family_instructions = {
"default": "Solve the following math problem step by step. Please put your final answer within \\boxed{}.",
"verify": "Solve the following math problem step by step. Verify each algebraic and arithmetic step, and put your final answer within \\boxed{}.",
"decompose": "Decompose the following math problem into smaller subproblems, solve carefully, and put your final answer within \\boxed{}.",
"equation_first": "Translate the following math problem into equations or cases before solving, and put your final answer within \\boxed{}.",
}
instruction = family_instructions[prompt_family]
return f"{instruction}\n\n{problem.strip()}\n\nRemember to put your final answer within \\boxed{{}}."
def _prompt_families_for_dataset(dataset_name: str) -> list[str]:
if dataset_name == "countdown":
return ["default", "target_first", "build_up", "verify"]
if dataset_name in {"gsm8k", "math500", "aime24"}:
return ["default", "verify", "decompose", "equation_first"]
return ["default"]
def _build_prompt_variants(dataset_name: str, example: dict, template_type: str) -> dict[str, str]:
families = _prompt_families_for_dataset(dataset_name)
if dataset_name == "countdown":
return {family: _make_countdown_prefix(example, template_type, family) for family in families}
if dataset_name == "gsm8k":
return {family: _make_gsm8k_prompt(example["question"], family) for family in families}
if dataset_name in {"math500", "aime24"}:
return {family: _make_competition_math_prompt(example["problem"], family) for family in families}
return {"default": str(example)}
def _select_prompt_family(*, dataset_name: str, split: str, idx: int, prompt_conditioning_mode: str) -> str:
if split != "train" or prompt_conditioning_mode == "off":
return "default"
if prompt_conditioning_mode not in {"mixed", "adaptive"}:
raise ValueError(f"Unsupported prompt_conditioning_mode: {prompt_conditioning_mode}")
families = _prompt_families_for_dataset(dataset_name)
return families[idx % len(families)]
def _split_single_split_dataset(dataset, *, train_size: int, test_size: int, default_train_size: int, default_test_size: int):
total = len(dataset)
if train_size == 0 and test_size == 0:
train_size = default_train_size
test_size = default_test_size
elif train_size == 0:
train_size = total - test_size
elif test_size == 0:
test_size = total - train_size
if train_size <= 0 or test_size <= 0:
raise ValueError("train_size and test_size must both be positive for single-split datasets.")
if train_size + test_size > total:
raise ValueError("Requested train_size + test_size exceeds the available dataset size.")
train_dataset = dataset.select(range(train_size))
test_dataset = dataset.select(range(train_size, train_size + test_size))
return train_dataset, test_dataset
def _parse_eval_ks(eval_ks: str, validation_rollouts: int) -> list[int]:
ks = []
for chunk in eval_ks.split(","):
chunk = chunk.strip()
if not chunk:
continue
value = int(chunk)
if value <= 0:
continue
if value <= validation_rollouts:
ks.append(value)
if not ks:
ks = [min(validation_rollouts, 1)]
if validation_rollouts >= 1:
ks.append(1)
return sorted(set(ks))
def _extract_reasoning_text(output: str) -> str:
text = output
think_match = re.search(r"<think>(.*?)</think>", text, flags=re.IGNORECASE | re.DOTALL)
if think_match:
text = think_match.group(1)
text = re.sub(r"<answer>.*?</answer>", " ", text, flags=re.IGNORECASE | re.DOTALL)
text = text.split("####", 1)[0]
text = re.sub(r"\\boxed\s*\{.*?\}", " ", text, flags=re.DOTALL)
return text
def _reasoning_signature(output: str) -> str:
text = _extract_reasoning_text(output).lower()
text = re.sub(r"\d+(?:\.\d+)?", "<num>", text)
text = re.sub(r"[^a-z<>\+\-\*\/=\(\)\[\]\{\}\s]", " ", text)
text = re.sub(r"\s+", " ", text).strip()
return " ".join(text.split()[:64])
def _compute_validation_passk_clusters(validation_data_dir: Path, ks: list[int]) -> dict[int, dict[str, float]]:
per_step_metrics: dict[int, dict[str, float]] = {}
for jsonl_path in sorted(validation_data_dir.glob("*.jsonl"), key=lambda p: int(p.stem)):
groups: dict[str, list[dict]] = defaultdict(list)
with open(jsonl_path, "r", encoding="utf-8") as infile:
for line in infile:
record = json.loads(line)
group_key = f"{record.get('input', '')}||{record.get('gts', '')}"
groups[group_key].append(record)
skipped_invalid_groups = 0
valid_groups: dict[str, list[dict]] = {}
for group_key, records in groups.items():
if records and not _is_valid_countdown_ground_truth(records[0].get("gts")):
skipped_invalid_groups += 1
continue
valid_groups[group_key] = records
groups = valid_groups
if not groups:
continue
step = int(jsonl_path.stem)
metrics: dict[str, float] = {
"val-data/custom/evaluable_problem_count": float(len(groups)),
"val-data/custom/skipped_invalid_problem_count": float(skipped_invalid_groups),
}
base_pass = 0.0
base_max = 0.0
for k in ks:
pass_hits = 0
max_scores = []
cluster_counts = []
correct_cluster_counts = []
valid_equation_rates = []
for records in groups.values():
subset = records[:k]
valid_subset = [
item for item in subset if _has_valid_countdown_equation(item.get("output", ""), item.get("gts"))
]
valid_ids = {id(item) for item in valid_subset}
scores = [
float(item.get("score", 0.0)) if id(item) in valid_ids else 0.0
for item in subset
]
max_score = max(scores) if scores else 0.0
max_scores.append(max_score)
if max_score > 0.5:
pass_hits += 1
signatures = {_reasoning_signature(item.get("output", "")) for item in valid_subset}
signatures.discard("")
cluster_counts.append(float(len(signatures)))
correct_signatures = {
_reasoning_signature(item.get("output", ""))
for item in valid_subset
if float(item.get("score", 0.0)) > 0.5
}
correct_signatures.discard("")
correct_cluster_counts.append(float(len(correct_signatures)))
valid_equation_rates.append(len(valid_subset) / len(subset) if subset else 0.0)
group_count = float(len(groups))
pass_at_k = pass_hits / group_count if group_count else 0.0
max_at_k = sum(max_scores) / len(max_scores) if max_scores else 0.0
if k == 1:
base_pass = pass_at_k
base_max = max_at_k
clusters_at_k = sum(cluster_counts) / len(cluster_counts) if cluster_counts else 0.0
correct_clusters_at_k = (
sum(correct_cluster_counts) / len(correct_cluster_counts) if correct_cluster_counts else 0.0
)
valid_equation_rate_at_k = (
sum(valid_equation_rates) / len(valid_equation_rates) if valid_equation_rates else 0.0
)
pass_gain_at_k = pass_at_k - base_pass
max_gain_at_k = max_at_k - base_max
metrics.update(
{
f"val-core/custom/pass@{k}": pass_at_k,
f"val-core/custom/max@{k}": max_at_k,
f"val-aux/custom/clusters@{k}": clusters_at_k,
f"val-aux/custom/correct_clusters@{k}": correct_clusters_at_k,
f"val-aux/custom/valid_equation_rate@{k}": valid_equation_rate_at_k,
f"val-gap/custom/pass_gain@{k}": pass_gain_at_k,
f"val-gap/custom/max_gain@{k}": max_gain_at_k,
f"custom/pass_at_{k}": pass_at_k,
f"custom/max_at_{k}": max_at_k,
f"custom/cluster_at_{k}": clusters_at_k,
f"custom/clusters_at_{k}": clusters_at_k,
f"custom/correct_cluster_at_{k}": correct_clusters_at_k,
f"custom/correct_clusters_at_{k}": correct_clusters_at_k,
f"custom/valid_equation_rate_at_{k}": valid_equation_rate_at_k,
f"custom/pass_gain_at_{k}": pass_gain_at_k,
f"custom/max_gain_at_{k}": max_gain_at_k,
}
)
per_step_metrics[step] = metrics
return per_step_metrics
def _log_validation_passk_clusters_to_wandb(
*,
validation_data_dir: Path,
wandb_project: str,
wandb_entity: str,
experiment_name: str,
run_id: str,
eval_ks: str,
validation_rollouts: int,
) -> None:
import wandb
ks = _parse_eval_ks(eval_ks, validation_rollouts)
validation_files = sorted(validation_data_dir.glob("*.jsonl"), key=lambda p: int(p.stem))
print(
"Custom validation metrics: "
f"dir={validation_data_dir}, files={len(validation_files)}, eval_ks={','.join(map(str, ks))}"
)
if not validation_files:
print(
"Custom validation metrics skipped: no validation JSONL files were written. "
"Check that trainer.test_freq is <= trainer.total_training_steps and that validation ran at least once."
)
return
per_step_metrics = _compute_validation_passk_clusters(validation_data_dir, ks)
if not per_step_metrics:
print(
"Custom validation metrics skipped: validation files existed, but no evaluable problem groups were found."
)
return
run = wandb.init(
project=wandb_project,
entity=wandb_entity or None,
name=experiment_name,
id=run_id,
resume="allow",
)
try:
for step, metrics in sorted(per_step_metrics.items()):
wandb.log(metrics, step=step)
logged_keys = sorted({key for metrics in per_step_metrics.values() for key in metrics})
print(
"Custom validation metrics logged to W&B: "
f"steps={sorted(per_step_metrics)}, metric_keys={len(logged_keys)}"
)
print("Custom validation metric examples: " + ", ".join(logged_keys[:12]))
finally:
wandb.finish()
def _flatten_wandb_summary(data: dict, prefix: str = "") -> dict[str, object]:
flattened: dict[str, object] = {}
for key, value in data.items():
metric_key = f"{prefix}.{key}" if prefix else str(key)
if isinstance(value, dict) and "_type" not in value:
flattened.update(_flatten_wandb_summary(value, metric_key))
else:
flattened[metric_key] = value
return flattened
def _format_summary_value(value: object) -> str:
if isinstance(value, float):
return f"{value:.12g}"
if isinstance(value, (int, bool)):
return str(value)
if isinstance(value, str):
return value
return json.dumps(value, sort_keys=True, default=str)
def _load_local_wandb_summary(run_dir: Path) -> dict[str, object]:
candidates: list[Path] = []
candidates.extend(run_dir.glob("wandb/latest-run/files/wandb-summary.json"))
candidates.extend(run_dir.glob("wandb/run-*/files/wandb-summary.json"))
candidates = sorted(
{path.resolve(): path for path in candidates if path.exists()}.values(),
key=lambda path: path.stat().st_mtime,
reverse=True,
)
for summary_path in candidates:
try:
with open(summary_path, "r", encoding="utf-8") as infile:
payload = json.load(infile)
if isinstance(payload, dict) and payload:
return _flatten_wandb_summary(payload)
except Exception as exc:
print(f"Could not read local W&B summary {summary_path}: {exc}")
return {}
def _load_api_wandb_summary(*, wandb_project: str, wandb_entity: str, run_id: str) -> dict[str, object]:
if not wandb_entity:
return {}
try:
import wandb
api = wandb.Api(timeout=30)
run = api.run(f"{wandb_entity}/{wandb_project}/{run_id}")
return _flatten_wandb_summary(dict(run.summary))
except Exception as exc:
print(f"Could not fetch W&B summary from API: {exc}")
return {}
def _print_full_wandb_summary(
*,
run_dir: Path,
wandb_project: str,
wandb_entity: str,
run_id: str,
) -> None:
metrics = _load_local_wandb_summary(run_dir)
if not metrics:
metrics = _load_api_wandb_summary(
wandb_project=wandb_project,
wandb_entity=wandb_entity,
run_id=run_id,
)
print("\nFull W&B run summary:")
if not metrics:
print("wandb-full: no local/API W&B summary metrics found")
return
for key in sorted(metrics):
print(f"wandb-full: {key} {_format_summary_value(metrics[key])}")
print(f"wandb-full: metric_count {len(metrics)}")
def _print_full_run_parameters(params: dict[str, object]) -> None:
print("\nFull run parameters:")
for key in sorted(params):
print(f"param: {key}={_format_summary_value(params[key])}")
def _run_and_tee(cmd: list[str], log_path: str, env: dict[str, str] | None = None) -> None:
import os
import subprocess
import sys
merged_env = os.environ.copy()
if env:
merged_env.update(env)
with open(log_path, "a", encoding="utf-8") as log_file:
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
env=merged_env,
)
assert process.stdout is not None
for line in process.stdout:
sys.stdout.write(line)
log_file.write(line)
return_code = process.wait()
if return_code != 0:
raise subprocess.CalledProcessError(return_code, cmd)
def _install_modal_tinyzero_extensions() -> None:
"""Patch the freshly cloned TinyZero checkout with Modal-only experiment hooks."""
repo_dir = Path(REMOTE_REPO_DIR)
countdown_reward_path = repo_dir / "verl" / "utils" / "reward_score" / "countdown.py"
countdown_reward_path.write_text(
textwrap.dedent(
r'''
import ast
import operator
import random
import re
from collections import Counter
_OPS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
def extract_solution(solution_str):
"""Extract the final equation from the whole assistant response."""
if "Assistant:" in solution_str:
solution_str = solution_str.split("Assistant:", 1)[1]
elif "<|im_start|>assistant" in solution_str:
solution_str = solution_str.split("<|im_start|>assistant", 1)[1]
answer_pattern = r"<answer>(.*?)</answer>"
matches = list(re.finditer(answer_pattern, solution_str, flags=re.IGNORECASE | re.DOTALL))
if not matches:
return None
final_answer = matches[-1].group(1).strip()
final_answer = re.sub(r"<\|.*?\|>", " ", final_answer)
final_answer = re.sub(r"\s+", " ", final_answer).strip()
if not final_answer or final_answer.upper() == "NO_SOLUTION":
return None
return final_answer
def validate_equation(equation_str, available_numbers):
"""Validate that the equation uses exactly the provided numbers once."""
try:
numbers_in_eq = [int(n) for n in re.findall(r"\d+", equation_str)]
return Counter(numbers_in_eq) == Counter(int(n) for n in list(available_numbers))
except Exception:
return False
def _eval_node(node):
if isinstance(node, ast.Expression):
return _eval_node(node.body)
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.UnaryOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_eval_node(node.operand))
if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
return _OPS[type(node.op)](_eval_node(node.left), _eval_node(node.right))
raise ValueError("Unsupported expression node.")
def evaluate_equation(equation_str):
"""Safely evaluate arithmetic equations without eval()."""
try:
allowed_pattern = r"^[\d+\-*/().\s]+$"
if not re.match(allowed_pattern, equation_str):
raise ValueError("Invalid characters in equation.")
return _eval_node(ast.parse(equation_str, mode="eval"))
except Exception:
return None
def compute_score(solution_str, ground_truth, method="strict", format_score=0.1, score=1.0):
target = ground_truth["target"]
numbers = ground_truth["numbers"]
equation = extract_solution(solution_str=solution_str)
do_print = random.randint(1, 64) == 1
if do_print:
solution_preview = str(solution_str)
if len(solution_preview) > 1200:
solution_preview = solution_preview[:1200] + "... <truncated>"
print("--------------------------------")
print(f"Target: {target} | Numbers: {numbers}")
print(f"Extracted equation: {equation}")
print(f"Solution string: {solution_preview}")
if equation is None:
if do_print:
print("No equation found")
return 0.0
if not validate_equation(equation, numbers):
if do_print:
print("Invalid equation")
return format_score
result = evaluate_equation(equation)
if result is None:
if do_print:
print("Could not evaluate equation")
return format_score
if abs(result - target) < 1e-5:
if do_print:
print(f"Correct equation: {equation} = {result}")
return score
if do_print:
print(f"Wrong result: equation = {result}, target = {target}")
return format_score
'''
).strip()
+ "\n",
encoding="utf-8",
)
controller_path = repo_dir / "verl" / "utils" / "adaptive_prompt_controller.py"
controller_path.write_text(
textwrap.dedent(
r'''
import json
import math
import os
from pathlib import Path
def _enabled():
return os.environ.get("TZ_PROMPT_CONTROLLER_MODE") == "adaptive"
def _state_path():
value = os.environ.get("TZ_PROMPT_CONTROLLER_STATE")
return Path(value) if value else None
def _env_families():
raw = os.environ.get("TZ_PROMPT_FAMILIES", "")
return [item.strip() for item in raw.split(",") if item.strip()]
def _initial_state(families=None):
families = list(families or _env_families())
return {
"step": 0,
"families": families,
"counts": {family: 0.0 for family in families},
"successes": {family: 0.0 for family in families},
"rates": {family: 0.0 for family in families},
"probs": {family: 1.0 / len(families) for family in families} if families else {},
}
def _read_state():
path = _state_path()
if path is None or not path.exists():
return _initial_state()
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return _initial_state()
def _write_state(state):
path = _state_path()
if path is None:
return
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_suffix(path.suffix + ".tmp")
tmp_path.write_text(json.dumps(state, sort_keys=True, indent=2), encoding="utf-8")
tmp_path.replace(path)
def _ensure_families(state, families):
existing = list(state.get("families") or [])
merged = []
for family in list(families or []) + existing:
if family and family not in merged:
merged.append(family)
state["families"] = merged
state.setdefault("counts", {})
state.setdefault("successes", {})
for family in merged:
state["counts"].setdefault(family, 0.0)
state["successes"].setdefault(family, 0.0)
return state
def _attach_probs(state):
families = list(state.get("families") or [])
if not families:
state["rates"] = {}
state["probs"] = {}
return state
temp = max(float(os.environ.get("TZ_PROMPT_BANDIT_TEMP", "0.25")), 1e-6)
prior_success = float(os.environ.get("TZ_PROMPT_BANDIT_PRIOR_SUCCESS", "0.25"))
prior_count = float(os.environ.get("TZ_PROMPT_BANDIT_PRIOR_COUNT", "1.0"))
counts = state.get("counts", {})
successes = state.get("successes", {})
rates = {}
logits = []
for family in families:
count = float(counts.get(family, 0.0))
success = float(successes.get(family, 0.0))
rate = (success + prior_success) / max(count + prior_count, 1e-9)
rates[family] = rate
logits.append(rate / temp)
max_logit = max(logits)
exp_values = [math.exp(logit - max_logit) for logit in logits]
denom = sum(exp_values) or 1.0
state["rates"] = rates
state["probs"] = {family: exp_values[i] / denom for i, family in enumerate(families)}
return state
def reset_state():
if not _enabled():
return
state = _attach_probs(_initial_state())
_write_state(state)
def choose_family(prompt_variants_json, rng):
if not _enabled() or not prompt_variants_json:
return None
variants = json.loads(prompt_variants_json) if isinstance(prompt_variants_json, str) else dict(prompt_variants_json)
families = [family for family in _env_families() if family in variants]
if not families:
families = sorted(variants.keys())
state = _attach_probs(_ensure_families(_read_state(), families))
probs = state.get("probs", {})
draw = rng.random()
cumulative = 0.0
selected = families[-1]
for family in families:
cumulative += float(probs.get(family, 0.0))
if draw <= cumulative:
selected = family
break
return selected, variants[selected]
def _as_extra_info_dict(value):
if isinstance(value, dict):
return value
if isinstance(value, str):
try:
parsed = json.loads(value)
if isinstance(parsed, dict):
return parsed
except Exception:
pass
return {}
def update_from_rewards(extra_infos, sequence_scores):
if not _enabled():
return {}
state = _ensure_families(_read_state(), _env_families())
threshold = float(os.environ.get("TZ_PROMPT_SUCCESS_THRESHOLD", "0.5"))
for extra_info, score in zip(extra_infos, sequence_scores):
info = _as_extra_info_dict(extra_info)
family = info.get("prompt_family")
if family not in state["families"]:
continue
state["counts"][family] = float(state["counts"].get(family, 0.0)) + 1.0
state["successes"][family] = float(state["successes"].get(family, 0.0)) + (1.0 if float(score) > threshold else 0.0)
state["step"] = int(state.get("step", 0)) + 1
state = _attach_probs(state)
_write_state(state)
metrics = {