Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f615de9383 | ||
|
|
1093f9b914 | ||
|
|
67ab1d6667 | ||
|
|
04e796d21b | ||
|
|
9f29e5388e | ||
|
|
822db2902c | ||
|
|
adfbc6003d | ||
|
|
94a93203cf | ||
|
|
f0d27513a4 | ||
|
|
684f0d0afe | ||
|
|
559b44772e | ||
|
|
1e756307ae | ||
|
|
2441fd5142 | ||
|
|
967fbf25ef |
Symlink
+1
@@ -0,0 +1 @@
|
||||
../skills
|
||||
@@ -34,20 +34,12 @@ max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -21,17 +21,11 @@ seq_len = 8192
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-env"
|
||||
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
dataset_subset = "default"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "math-env"
|
||||
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
env.taskset.dataset_subset = "default"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
@@ -24,15 +24,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -29,14 +29,8 @@ max_completion_tokens = 1024
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -42,15 +42,9 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -23,15 +23,9 @@ group_size = 8
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.player.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -27,23 +27,15 @@ max_completion_tokens = 384
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 2
|
||||
max_turns = 2
|
||||
min_names_per_turn = 1
|
||||
max_names_per_turn = 3
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
similarity_power = 4
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 2
|
||||
env.taskset.max_turns = 2
|
||||
env.taskset.min_names_per_turn = 1
|
||||
env.taskset.max_names_per_turn = 3
|
||||
env.taskset.task.similarity_power = 4
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -30,15 +30,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -27,15 +27,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -30,15 +30,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -42,15 +42,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -61,15 +55,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -48,15 +48,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -67,15 +61,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -30,15 +30,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -27,15 +27,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -23,20 +23,12 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
@@ -23,17 +23,11 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-env"
|
||||
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
dataset_subset = "default"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "math-env"
|
||||
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
env.taskset.dataset_subset = "default"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
@@ -41,15 +35,9 @@ interval = 50
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2024"
|
||||
group_size = 32
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime24"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime24"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -23,15 +23,9 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -24,15 +24,9 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -23,15 +23,9 @@ max_inflight = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.player.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -25,16 +25,10 @@ max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "color-codeword"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "color-codeword"
|
||||
images_per_turn = 1
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "color-codeword"
|
||||
env.taskset.images_per_turn = 1
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -26,20 +26,12 @@ alpha = 0.1
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -23,15 +23,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -42,15 +36,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -23,15 +23,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -42,15 +36,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -33,34 +33,18 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-grpo"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-opd"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.algo]
|
||||
type = "opd"
|
||||
|
||||
[orchestrator.train.source.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = "http://localhost:8001/v1"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
algo.type = "opd"
|
||||
algo.teacher.name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
algo.teacher.base_url = "http://localhost:8001/v1"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
@@ -71,15 +55,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -35,15 +35,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -54,15 +48,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -35,15 +35,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -54,15 +48,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
+10
-30
@@ -23,21 +23,11 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "kuhn-poker"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "kuhn-poker"
|
||||
|
||||
[orchestrator.train.source.env.player0.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player0.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.env.player1.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player1.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "kuhn-poker"
|
||||
env.player0.harness.id = "null"
|
||||
env.player0.runtime.type = "subprocess"
|
||||
env.player1.harness.id = "null"
|
||||
env.player1.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -48,21 +38,11 @@ max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "kuhn-poker"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "kuhn-poker"
|
||||
|
||||
[orchestrator.eval.source.env.player0.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.player0.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval.source.env.player1.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.player1.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "kuhn-poker"
|
||||
env.player0.harness.id = "null"
|
||||
env.player0.runtime.type = "subprocess"
|
||||
env.player1.harness.id = "null"
|
||||
env.player1.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -31,15 +31,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -50,15 +44,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -40,15 +40,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -59,15 +53,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -40,15 +40,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -59,15 +53,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
@@ -41,6 +41,8 @@ num_infer_replicas = 1
|
||||
project = "swe-ablations"
|
||||
name = "debug-concurrency"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -104,17 +106,9 @@ thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["debug-concurrency"]
|
||||
|
||||
[monitors.prime]
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
|
||||
@@ -124,18 +118,10 @@ interval = 20
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
num_examples = 100
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["debug-concurrency"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
|
||||
@@ -19,27 +19,15 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-a"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-b"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
@@ -50,15 +38,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
Vendored
+1
-1
Submodule deps/verifiers updated: 4bcb48e55a...d4f3d5a8c6
+17
-51
@@ -124,31 +124,17 @@ type = "grpo"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "math" # inherits the top-level grpo
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "math"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "terminal"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "terminal"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
env.taskset.id = "terminal"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
# this env runs its own algorithm
|
||||
[orchestrator.train.source.algo]
|
||||
type = "echo"
|
||||
algo.type = "echo"
|
||||
```
|
||||
|
||||
### The Algorithm Classes
|
||||
@@ -365,21 +351,11 @@ episode_agents = ["solver"]
|
||||
name = "proposer-solver"
|
||||
group_size = 4 # proposed problems per source task
|
||||
env.n = 4 # solver attempts per proposed problem
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "proposer-solver"
|
||||
|
||||
[orchestrator.train.source.env.proposer.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.proposer.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.env.solver.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.solver.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "proposer-solver"
|
||||
env.proposer.harness.id = "null"
|
||||
env.proposer.runtime.type = "subprocess"
|
||||
env.solver.harness.id = "null"
|
||||
env.solver.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero.
|
||||
@@ -399,21 +375,11 @@ decay = 0.95
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "kuhn-poker"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "kuhn-poker"
|
||||
|
||||
[orchestrator.train.source.env.player0.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player0.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.train.source.env.player1.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player1.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "kuhn-poker"
|
||||
env.player0.harness.id = "null"
|
||||
env.player0.runtime.type = "subprocess"
|
||||
env.player1.harness.id = "null"
|
||||
env.player1.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
Both of `kuhn-poker`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
|
||||
|
||||
+13
-33
@@ -106,10 +106,8 @@ uv run rl @ rl.toml --orchestrator.train.source.0.args \
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.source]]
|
||||
|
||||
[orchestrator.train.source.args]
|
||||
dataset_name = "openai/gsm8k"
|
||||
dataset_subset = "main"
|
||||
args.dataset_name = "openai/gsm8k"
|
||||
args.dataset_subset = "main"
|
||||
```
|
||||
|
||||
### Optional Sub-Configs
|
||||
@@ -153,42 +151,24 @@ Training and evaluation sources are arrays of tables. Set one source per environ
|
||||
[[orchestrator.train.source]]
|
||||
name = "gsm8k"
|
||||
ratio = 3 # 75% of batches
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "gsm8k"
|
||||
split = "train"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "gsm8k"
|
||||
env.taskset.split = "train"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
ratio = 1 # default — 25% of batches
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "gsm8k-eval"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "gsm8k"
|
||||
split = "test"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "gsm8k"
|
||||
env.taskset.split = "test"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
|
||||
|
||||
+4
-10
@@ -59,7 +59,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|
||||
|---|---|
|
||||
| `orchestrator.batch_size` | Tasks per trainer step. |
|
||||
| `orchestrator.group_size` | Rollouts generated per task. |
|
||||
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
|
||||
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
|
||||
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
|
||||
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
|
||||
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
|
||||
@@ -187,15 +187,9 @@ num_examples = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ num_infer_replicas = 4
|
||||
project = "search-ablations"
|
||||
name = "glm45air-search"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -88,8 +90,6 @@ num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.0
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
|
||||
|
||||
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
|
||||
@@ -97,18 +97,12 @@ num_turns_weight = 0.0
|
||||
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
|
||||
[[orchestrator.train.source]]
|
||||
name = "openseeker"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "openseeker"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.taskset.id = "openseeker"
|
||||
|
||||
[[orchestrator.train.source.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
@@ -127,18 +121,12 @@ choices = ["A", "B"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "redsearcher"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
|
||||
|
||||
[[orchestrator.train.source.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
@@ -163,24 +151,14 @@ interval = 20
|
||||
[[orchestrator.eval.source]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm45air-search"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "browsecomp"
|
||||
|
||||
[orchestrator.eval.source.env.taskset.task.judge]
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-search"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "browsecomp"
|
||||
env.taskset.task.judge.model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.eval.source.env.taskset.task.judges]]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, rlm harness on a prime sandbox
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
@@ -7,9 +7,8 @@
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# 1 train + 3 infer nodes. Inference serves FP8 via online per-tensor quantization of the bf16
|
||||
# checkpoint; weight broadcasts re-quantize through the same path on every update. The trainer fits on one
|
||||
# node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
|
||||
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
|
||||
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
|
||||
# skip-gather / skip-optimizer checkpointing.
|
||||
@@ -40,6 +39,8 @@ num_infer_replicas = 3
|
||||
project = "swe-ablations"
|
||||
name = "glm45air-scaleswe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -103,39 +104,21 @@ thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm45air-swe"]
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm45air-swe"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
@@ -149,5 +132,4 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
quantization = "fp8"
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -26,6 +26,8 @@ num_infer_replicas = 4
|
||||
project = "terminal-ablations"
|
||||
name = "glm45air-terminal"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -89,22 +91,14 @@ num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "tmax"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "tmax"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.taskset.id = "tmax"
|
||||
|
||||
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
|
||||
# [[orchestrator.train.source.env.taskset.judges]]
|
||||
@@ -128,27 +122,17 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/prime-envs/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
@@ -159,19 +143,11 @@ id = "swebench-verified"
|
||||
[[orchestrator.eval.source]]
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm45air-terminal"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "terminal-bench-2"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["glm45air-terminal"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
|
||||
@@ -134,15 +134,9 @@ clear_thinking = false
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "r2e"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["glm5-llmd"]
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.runtime.labels = ["glm5-llmd"]
|
||||
|
||||
[inference]
|
||||
# <0.80 because glm5 layers are too large for 0.85
|
||||
|
||||
@@ -78,15 +78,9 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["glm5-pd-disag", "swe-bench-verified"]
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
|
||||
|
||||
[inference]
|
||||
# we need <0.85 bc glm5 layers are too large for 0.85
|
||||
|
||||
@@ -54,103 +54,59 @@ max_inflight = 4096
|
||||
name = "swe"
|
||||
ratio = 0.3
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["intellect-3.1", "swe"]
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["intellect-3.1", "swe"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "deepdive"
|
||||
ratio = 0.2
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "deepdive"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
skills = ["search"]
|
||||
forward_env = ["SERPER_API_KEY"]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["intellect-3.1", "deepdive"]
|
||||
env.taskset.id = "deepdive"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
env.agent.runtime.labels = ["intellect-3.1", "deepdive"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
ratio = 0.3
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_math"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "i3_math"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "logic"
|
||||
ratio = 0.2
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_logic"
|
||||
|
||||
[orchestrator.train.source.env.taskset.filter]
|
||||
max = 0.874
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "i3_logic"
|
||||
env.taskset.filter.max = 0.874
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "code"
|
||||
ratio = 0.2
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_code"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "i3_code"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["intellect-3.1", "swe-bench-verified"]
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["intellect-3.1", "swe-bench-verified"]
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2025"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime25"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -53,30 +53,18 @@ max_inflight = 4096
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["minimax-swe", "swe"]
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["minimax-swe", "swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["minimax-swe", "swe-bench-verified"]
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["minimax-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -22,6 +22,8 @@ num_infer_replicas = 4
|
||||
project = "nemotron-3-super"
|
||||
name = "nemotron-3-super-swe"
|
||||
|
||||
[monitors.prime]
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
@@ -85,37 +87,21 @@ truncate_history_thinking = false
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "scaleswe"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = [65536, 131072]
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[monitors.prime]
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = [65536, 131072]
|
||||
env.agent.runtime.labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "rlm"
|
||||
summarize_at_tokens = 98304
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["nemotron-3-super-swe"]
|
||||
|
||||
[orchestrator.eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.summarize_at_tokens = 98304
|
||||
env.agent.runtime.labels = ["nemotron-3-super-swe"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
[inference]
|
||||
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
|
||||
|
||||
@@ -52,30 +52,18 @@ max_completion_tokens = 32768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "i3_math"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "i3_math"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2025"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime25"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -50,30 +50,18 @@ initial_inflight = 1024
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "r2e-gym"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
labels = ["qwen30b-swe", "swe"]
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["qwen30b-swe", "swe"]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
labels = ["qwen30b-swe", "swe-bench-verified"]
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["qwen30b-swe", "swe-bench-verified"]
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
|
||||
@@ -36,19 +36,11 @@ group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "general-agent"
|
||||
min_tier = 1
|
||||
|
||||
[orchestrator.train.source.env.taskset.task.tools]
|
||||
colocated = true
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "modal"
|
||||
env.taskset.id = "general-agent"
|
||||
env.taskset.min_tier = 1
|
||||
env.taskset.task.tools.colocated = true
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "modal"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -33,19 +33,11 @@ max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "alphabet-sort"
|
||||
min_turns = 3
|
||||
max_turns = 5
|
||||
|
||||
[orchestrator.train.source.env.taskset.task]
|
||||
power_per_turn = false
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference] # Default inference config
|
||||
|
||||
@@ -18,17 +18,11 @@ seq_len = 8192
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "math-env"
|
||||
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
dataset_subset = "default"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "math-env"
|
||||
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
|
||||
env.taskset.dataset_subset = "default"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
@@ -36,15 +30,9 @@ interval = 50
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2024"
|
||||
group_size = 32
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "aime24"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime24"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
@@ -17,15 +17,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -22,15 +22,9 @@ max_completion_tokens = 1024
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -45,15 +45,9 @@ max_completion_tokens = 512
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wiki-search"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -20,15 +20,9 @@ group_size = 16
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "wordle"
|
||||
|
||||
[orchestrator.train.source.env.player.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.player.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
+6
-18
@@ -21,24 +21,12 @@ max_inflight = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "swebench-verified"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "swebench-verified"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
[[eval.source]]
|
||||
name = "terminal-bench-2"
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "terminal-bench-2"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "bash"
|
||||
|
||||
[eval.source.env.agent.timeout]
|
||||
rollout = 3600
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
@@ -15,15 +15,9 @@ max_completion_tokens = 128
|
||||
|
||||
[[train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -530,7 +530,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Maximum training steps. If None, runs indefinitely."""
|
||||
|
||||
max_off_policy_steps: int = Field(8, ge=0)
|
||||
"""Maximum policies allowed to generate a single rollout. Rollouts generated more than ``max_off_policy_steps`` ahead of training are discarded. Higher values yield better throughput at the cost of off-policy noise."""
|
||||
"""Maximum staleness of a trained rollout: the version a batch trains on (v{step-1}) minus the oldest version that generated the rollout (a rollout can span several weight updates), queue time included. Episodes past the bound are dropped, in-flight and queued; a group shares one dispatch version, so its episodes age out together. Higher values yield better throughput at the cost of off-policy noise."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
@@ -543,12 +543,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
self.tokenizer.trust_remote_code = self.model.trust_remote_code
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_session_headers(self):
|
||||
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
|
||||
self.model.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_prime_monitor_name(self):
|
||||
"""Default ``monitors.prime.name`` to the W&B run name when monitoring
|
||||
|
||||
@@ -46,8 +46,8 @@ class BaseDataConfig(BaseConfig):
|
||||
micro_batch_size: int = Field(1, ge=1)
|
||||
"""Per-step micro batch size. ``batch_size`` must be divisible by this."""
|
||||
|
||||
num_workers: int = Field(1, ge=0)
|
||||
"""Number of dataloader worker processes. With ``>= 1``, batches are prepared and pinned in the background so tokenization/packing overlaps with training. ``0`` loads inline on the main process."""
|
||||
num_workers: int = Field(1, ge=1)
|
||||
"""Number of dataloader worker processes. Batches are prepared and pinned in the background so tokenization/packing overlaps with training."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_batch_size(self):
|
||||
|
||||
@@ -169,9 +169,6 @@ class ClientConfig(BaseConfig):
|
||||
headers_from_env: dict[str, str] = {}
|
||||
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
|
||||
|
||||
extra_headers_from_state: dict[str, str] = {}
|
||||
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "trajectory_id"}`` enables sticky routing at the inference router."""
|
||||
|
||||
skip_model_check: bool = False
|
||||
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
|
||||
|
||||
|
||||
+10
-20
@@ -34,7 +34,9 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
|
||||
|
||||
## Special syntax
|
||||
|
||||
**No inline tables** — checked-in configs use `[section]` headers, never `key = { ... }`. Expand `env.taskset = { id = "..." }` to a full-path header (`[orchestrator.train.source.env.taskset]` — subtable headers after a `[[...]]` entry attach to that entry).
|
||||
**No inline tables** — checked-in configs use `[section]` headers or dotted keys, never `key = { ... }`.
|
||||
|
||||
**Sources are one block** — inside a `[[...source]]` entry, write nested sub-configs as dotted keys in the same block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`), not one subsection header per nested config. Nested arrays of tables (e.g. `[[orchestrator.train.source.env.taskset.task.judges]]`) keep full-path headers — they attach to the preceding `[[...source]]` entry.
|
||||
|
||||
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
|
||||
|
||||
@@ -45,28 +47,16 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
|
||||
```toml
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text-eval"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text"
|
||||
split = "test"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.taskset.split = "test"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
|
||||
|
||||
@@ -130,7 +130,8 @@ All metrics print to the console log (and W&B when configured).
|
||||
| trainer | `perf/throughput`, `perf/mfu` | tokens/s and MFU % |
|
||||
| orchestrator | `time/step`, `time/save_ckpt` | phase timings |
|
||||
| orchestrator | `time/wait_for_policy` | **high → trainer is bottleneck** |
|
||||
| orchestrator | `dispatcher/off_policy_level/{mean,max}`, `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
|
||||
| orchestrator | `dispatcher/off_policy/{mean,max}`, `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
|
||||
| orchestrator | `off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`, `off_policy/dropped` | per-step staleness of trained rollouts |
|
||||
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
|
||||
|
||||
For live vLLM stats, query Prometheus directly:
|
||||
|
||||
@@ -114,15 +114,9 @@ max_inflight = 128
|
||||
[[eval.source]]
|
||||
num_examples = 32 # always cap eval size for smokes
|
||||
group_size = 4
|
||||
|
||||
[eval.source.env.taskset]
|
||||
id = "aime25"
|
||||
|
||||
[eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
|
||||
|
||||
@@ -252,7 +252,7 @@ def rl_local(config: RLConfig):
|
||||
for split, source, address in env_servers(config):
|
||||
name = source.resolved_name
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
|
||||
logger.info(f"Starting {split} env server {name} at {address}")
|
||||
logger.info(f"Starting {name} server")
|
||||
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
|
||||
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
|
||||
env_server_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -282,7 +282,7 @@ def rl_local(config: RLConfig):
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_CONFIG).as_posix()]
|
||||
logger.info("Starting orchestrator process")
|
||||
logger.info("Starting orchestrator")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
with open(log_dir / "orchestrator.log", "w") as log_file:
|
||||
orchestrator_process = Popen(
|
||||
|
||||
@@ -446,7 +446,7 @@ def sft_local(config: SFTConfig):
|
||||
# deterministic address, polling until the server is up.
|
||||
for source, address in eval_env_servers(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting eval env server {name} at {address}")
|
||||
logger.info(f"Starting {name} server")
|
||||
start_process(
|
||||
f"env/eval/{name}",
|
||||
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
|
||||
@@ -455,7 +455,7 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting evals process")
|
||||
logger.info("Starting evals")
|
||||
start_process(
|
||||
"evals",
|
||||
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
|
||||
|
||||
+18
-14
@@ -30,6 +30,7 @@ from subprocess import Popen
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.orchestrator.clients import AdminClients, InferenceClient, init_nccl_broadcast, update_weights
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
@@ -43,7 +44,6 @@ from prime_rl.orchestrator.patches import (
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import EvalBatch, Policy
|
||||
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
|
||||
from prime_rl.utils.client import InferencePool, init_nccl_broadcast
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir, get_step_path
|
||||
@@ -95,7 +95,8 @@ class Evals:
|
||||
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
|
||||
|
||||
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
|
||||
self.pool = InferencePool(config.eval.client, model_name=config.model)
|
||||
self.clients = InferenceClient(config.eval.client, model_name=config.model)
|
||||
self.admin_clients = AdminClients(config.eval.client)
|
||||
|
||||
self.spawn_env_servers()
|
||||
|
||||
@@ -105,14 +106,14 @@ class Evals:
|
||||
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
|
||||
|
||||
get_logger().info("Waiting for inference pool to be ready")
|
||||
await self.pool.wait_for_ready(config.model)
|
||||
await self.admin_clients.wait_for_ready(config.model)
|
||||
get_logger().success("Inference pool ready")
|
||||
|
||||
weight_broadcast = config.weight_broadcast
|
||||
if weight_broadcast is not None and weight_broadcast.type == "nccl":
|
||||
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
|
||||
await init_nccl_broadcast(
|
||||
self.pool.admin_clients,
|
||||
self.admin_clients.clients,
|
||||
weight_broadcast.host,
|
||||
weight_broadcast.port,
|
||||
weight_broadcast.timeout,
|
||||
@@ -134,7 +135,7 @@ class Evals:
|
||||
eval_envs=self.eval_envs,
|
||||
train_source=None,
|
||||
eval_source=self.eval_source,
|
||||
policy_pool=self.pool,
|
||||
policy_clients=self.clients,
|
||||
policy=self.policy,
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
@@ -154,7 +155,7 @@ class Evals:
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# W&B mirroring is gated on the registered monitor.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.pool.admin_clients,
|
||||
self.admin_clients.clients,
|
||||
on_load=self.concurrency.observe,
|
||||
log_to_wandb=wandb_enabled,
|
||||
)
|
||||
@@ -166,7 +167,7 @@ class Evals:
|
||||
if not await self.inference_metrics.probe():
|
||||
concurrency = config.eval.concurrency
|
||||
if concurrency.min_inflight != concurrency.max_inflight:
|
||||
urls = ", ".join(str(client.base_url) for client in self.pool.admin_clients)
|
||||
urls = ", ".join(str(client.base_url) for client in self.admin_clients.clients)
|
||||
raise ValueError(
|
||||
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
|
||||
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
|
||||
@@ -354,16 +355,16 @@ class Evals:
|
||||
# and serve the evals against that name (mirrors WeightWatcher).
|
||||
lora_name = LORA_NAME if (broadcast_dir / "adapter_config.json").exists() else None
|
||||
try:
|
||||
await self.pool.update_weights(broadcast_dir, lora_name=lora_name, step=step)
|
||||
await update_weights(self.admin_clients.clients, broadcast_dir, lora_name=lora_name, step=step)
|
||||
except Exception as exc:
|
||||
# Skip this step instead of killing the run; drain the queued examples
|
||||
# so they don't leak into a later epoch with the wrong eval_step.
|
||||
while self.eval_source.next_example() is not None:
|
||||
# so they don't leak into a later epoch with the wrong step.
|
||||
while self.eval_source.next_task() is not None:
|
||||
pass
|
||||
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
|
||||
return
|
||||
if lora_name is not None:
|
||||
self.pool.update_model_name(lora_name)
|
||||
self.clients.update_model_name(lora_name)
|
||||
self.policy.model_name = lora_name
|
||||
|
||||
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
|
||||
@@ -447,9 +448,12 @@ class Evals:
|
||||
dispatcher: Dispatcher | None = getattr(self, "dispatcher", None)
|
||||
if dispatcher is not None:
|
||||
await dispatcher.stop()
|
||||
pool: InferencePool | None = getattr(self, "pool", None)
|
||||
if pool is not None:
|
||||
await pool.stop()
|
||||
clients: InferenceClient | None = getattr(self, "clients", None)
|
||||
if clients is not None:
|
||||
await clients.aclose()
|
||||
admin_clients: AdminClients | None = getattr(self, "admin_clients", None)
|
||||
if admin_clients is not None:
|
||||
await admin_clients.aclose()
|
||||
cleanup_processes(self.env_server_procs)
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ down training.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Literal, overload
|
||||
|
||||
@@ -18,7 +19,7 @@ from prime_rl.monitors.file import FileMonitor
|
||||
from prime_rl.monitors.prime import PrimeMonitor
|
||||
from prime_rl.monitors.wandb import WandbMonitor
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
@@ -60,12 +61,13 @@ async def setup(
|
||||
if rank != 0:
|
||||
return
|
||||
|
||||
monitors: list[tuple[Monitor, dict[str, Any]]] = []
|
||||
monitors: list[tuple[str, Monitor, dict[str, Any]]] = []
|
||||
if prime is not None:
|
||||
monitors.append((PrimeMonitor(prime), dict(config=run_config)))
|
||||
monitors.append(("prime", PrimeMonitor(prime), dict(config=run_config)))
|
||||
if wandb is not None:
|
||||
monitors.append(
|
||||
(
|
||||
"wandb",
|
||||
WandbMonitor(wandb),
|
||||
dict(
|
||||
output_dir=output_dir,
|
||||
@@ -77,11 +79,17 @@ async def setup(
|
||||
)
|
||||
)
|
||||
if file is not None:
|
||||
monitors.append((FileMonitor(file), dict(output_dir=output_dir)))
|
||||
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir)))
|
||||
if not monitors:
|
||||
return
|
||||
|
||||
for monitor, init_kwargs in monitors:
|
||||
get_logger().info(f"Initializing monitors ({', '.join(name for name, _, _ in monitors)})")
|
||||
t0 = time.perf_counter()
|
||||
for name, monitor, init_kwargs in monitors:
|
||||
get_logger().info(f"Initializing {name} monitor ({monitor.config})")
|
||||
await monitor.init(**init_kwargs)
|
||||
MONITORS.append(monitor)
|
||||
get_logger().debug(f"Initialized monitors in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
|
||||
def get(monitor_cls: type[Monitor]) -> Monitor | None:
|
||||
|
||||
@@ -28,7 +28,7 @@ class FileMonitor(Monitor):
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Line-buffered append so a concurrently-running dashboard can tail the file.
|
||||
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
|
||||
self.logger.info(f"Logging metrics to {self.path} and episodes to {output_dir / 'rollouts'}")
|
||||
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
sanitized, dropped = sanitize(metrics)
|
||||
|
||||
@@ -16,6 +16,7 @@ from prime_rl.configs.monitors import WandbMonitorConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.monitors.wandb.overview import ensure_overview_view
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import format_time
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
@@ -63,7 +64,7 @@ class WandbMonitor(Monitor):
|
||||
x_primary=primary,
|
||||
x_update_finish_state=finisher,
|
||||
)
|
||||
self.logger.info(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
|
||||
self.logger.debug(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
|
||||
is_online = True
|
||||
else:
|
||||
run_id = None
|
||||
@@ -130,7 +131,7 @@ class WandbMonitor(Monitor):
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to create W&B overview view - {e}")
|
||||
|
||||
self.logger.info(f"Logging metrics to W&B run {self.wandb.id} ({self.wandb.url})")
|
||||
self.logger.info(f"Logging metrics to W&B ({self.wandb.url})")
|
||||
|
||||
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
|
||||
wandb.log({**metrics, "step": step})
|
||||
@@ -140,6 +141,8 @@ class WandbMonitor(Monitor):
|
||||
|
||||
async def finalize(self) -> None:
|
||||
self.logger.info(f"Finalizing W&B run {self.wandb.id}")
|
||||
t0 = time.perf_counter()
|
||||
# Explicit finish: in (experimental) shared mode the SDK's atexit finish does
|
||||
# not land the run state - without this, even clean runs decay to "crashed".
|
||||
await asyncio.to_thread(wandb.finish, exit_code=0)
|
||||
self.logger.debug(f"Finalized W&B run in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
@@ -22,7 +22,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_pool
|
||||
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
|
||||
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
|
||||
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
from prime_rl.orchestrator.algo.hierarchical_grpo import HierarchicalGRPOAlgorithm
|
||||
@@ -35,7 +35,7 @@ from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.configs.algorithm import AlgoConfig
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
# Runtime dispatch is keyed on ``algo.type`` — it names the algorithm, and
|
||||
# each config class's defaults are its vetted parameterization.
|
||||
@@ -51,7 +51,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
|
||||
}
|
||||
|
||||
|
||||
def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm:
|
||||
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
|
||||
cls = ALGORITHM_CLASSES[config.type]
|
||||
assert cls.action_loss_type == config.action_loss_type # config and runtime declare in two places
|
||||
# The Algorithm is the runtime of the algorithm config's training signal
|
||||
@@ -59,7 +59,7 @@ def build_algorithm(config: AlgoConfig, policy_pool: InferencePool) -> Algorithm
|
||||
# handed the live policy pool — opsd self-distills against it, others may
|
||||
# judge against it or ignore it. Other models (a frozen teacher, a hint
|
||||
# renderer) are built from the algorithm's own config in setup().
|
||||
return cls(config, policy_pool)
|
||||
return cls(config, clients)
|
||||
|
||||
|
||||
__all__ = [
|
||||
@@ -73,7 +73,7 @@ __all__ = [
|
||||
"RAEAlgorithm",
|
||||
"SFTDistillAlgorithm",
|
||||
"build_algorithm",
|
||||
"connect_frozen_pool",
|
||||
"connect_frozen_client",
|
||||
"assign_advantages",
|
||||
"stamp_loss_routing",
|
||||
]
|
||||
|
||||
@@ -12,24 +12,24 @@ from prime_rl.utils.logger import get_logger
|
||||
if TYPE_CHECKING:
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
async def connect_frozen_pool(
|
||||
async def connect_frozen_client(
|
||||
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
|
||||
) -> InferencePool:
|
||||
) -> InferenceClient:
|
||||
"""Connect to an externally hosted frozen model and wait for it."""
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
|
||||
|
||||
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
|
||||
if renderer_config is not None:
|
||||
pool = InferencePool(
|
||||
clients = InferenceClient(
|
||||
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
|
||||
)
|
||||
else:
|
||||
pool = InferencePool(config, model_name=config.name)
|
||||
await pool.wait_for_ready(config.name)
|
||||
return pool
|
||||
clients = InferenceClient(config, model_name=config.name)
|
||||
await check_inference_ready(config, config.name)
|
||||
return clients
|
||||
|
||||
|
||||
def iter_trainable_traces(episodes: list[vf.Episode]):
|
||||
@@ -52,18 +52,17 @@ class Algorithm:
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
def __init__(self, config: AlgoConfig, policy_pool: InferencePool):
|
||||
self.policy_pool = policy_pool
|
||||
self.connected_pools: list[InferencePool] = []
|
||||
def __init__(self, config: AlgoConfig, clients: InferenceClient):
|
||||
self.clients = clients
|
||||
self.connected: InferenceClient | None = None
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Connect resources owned by the algorithm."""
|
||||
|
||||
async def connect(self, reference: FrozenModelConfig) -> InferencePool:
|
||||
"""Connect and track a frozen model pool owned by this algorithm."""
|
||||
pool = await connect_frozen_pool(reference)
|
||||
self.connected_pools.append(pool)
|
||||
return pool
|
||||
async def connect(self, reference: FrozenModelConfig) -> InferenceClient:
|
||||
"""Connect and track the frozen model pool owned by this algorithm."""
|
||||
self.connected = await connect_frozen_client(reference)
|
||||
return self.connected
|
||||
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
"""Assign rollout-local annotations to one finalized episode."""
|
||||
|
||||
@@ -11,7 +11,7 @@ from prime_rl.utils.utils import import_object
|
||||
if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class EchoAlgorithm(GRPOAlgorithm):
|
||||
@@ -22,8 +22,8 @@ class EchoAlgorithm(GRPOAlgorithm):
|
||||
mask and its denominator. An optional user filter narrows the selection
|
||||
per rollout (e.g. dropping tool-output warnings)."""
|
||||
|
||||
def __init__(self, config: EchoAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: EchoAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.role_weights = {
|
||||
role: role_config.alpha
|
||||
for role in ("system", "user", "assistant", "tool")
|
||||
|
||||
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class GRPOAlgorithm(Algorithm):
|
||||
@@ -18,8 +18,8 @@ class GRPOAlgorithm(Algorithm):
|
||||
policy per example; credit = reward minus the group mean (optionally
|
||||
length-shaped); action tokens feed the ``rl`` loss."""
|
||||
|
||||
def __init__(self, config: GRPOAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: GRPOAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.length_penalty = config.length_penalty
|
||||
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
|
||||
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class HierarchicalGRPOAlgorithm(Algorithm):
|
||||
@@ -26,8 +26,8 @@ class HierarchicalGRPOAlgorithm(Algorithm):
|
||||
within one episode. Other roles are compared across the full rollout group.
|
||||
A comparison group with one trace produces zero advantage."""
|
||||
|
||||
def __init__(self, config: HierarchicalGRPOAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: HierarchicalGRPOAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.episode_agents = set(config.episode_agents)
|
||||
|
||||
async def score_group(self, episodes: list[vf.Episode]) -> None:
|
||||
|
||||
@@ -11,7 +11,7 @@ from prime_rl.orchestrator.algo.routing import assign_reference_logprobs
|
||||
from prime_rl.orchestrator.trajectories import iter_trainable_branches
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class OPDAlgorithm(Algorithm):
|
||||
@@ -26,20 +26,20 @@ class OPDAlgorithm(Algorithm):
|
||||
|
||||
action_loss_type = "ref_kl"
|
||||
|
||||
def __init__(self, config: OPDAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: OPDAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.teacher = config.teacher
|
||||
self.teacher_pool: InferencePool | None = None # frozen teacher endpoint, connected in setup()
|
||||
self.teacher_clients: InferenceClient | None = None # frozen teacher endpoint, connected in setup()
|
||||
|
||||
async def setup(self) -> None:
|
||||
self.teacher_pool = await self.connect(self.teacher)
|
||||
self.teacher_clients = await self.connect(self.teacher)
|
||||
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
pool = self.teacher_pool
|
||||
assert pool is not None, "teacher pool not connected — Algorithm.setup() must run first"
|
||||
teacher = self.teacher_clients
|
||||
assert teacher is not None, "teacher not connected — Algorithm.setup() must run first"
|
||||
branches = [
|
||||
branch for _, trace in iter_trainable_traces([episode]) for branch, _ in iter_trainable_branches(trace)
|
||||
]
|
||||
scores = await asyncio.gather(*(pool.score(branch.token_ids) for branch in branches))
|
||||
scores = await asyncio.gather(*(teacher.score(branch.token_ids) for branch in branches))
|
||||
for branch, logprobs in zip(branches, scores, strict=True):
|
||||
assign_reference_logprobs(branch, logprobs)
|
||||
|
||||
@@ -14,7 +14,7 @@ from prime_rl.orchestrator.utils import episode_env_name
|
||||
if TYPE_CHECKING:
|
||||
from renderers.base import Renderer
|
||||
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class OPSDAlgorithm(Algorithm):
|
||||
@@ -33,8 +33,8 @@ class OPSDAlgorithm(Algorithm):
|
||||
|
||||
action_loss_type = "ref_kl"
|
||||
|
||||
def __init__(self, config: OPSDAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: OPSDAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.demo_key = config.demo_key
|
||||
self.template = config.template
|
||||
self.renderer_config = config.renderer
|
||||
@@ -42,7 +42,7 @@ class OPSDAlgorithm(Algorithm):
|
||||
# Self-distillation: the teacher *is* the live policy. Scoring against
|
||||
# the shared policy pool tracks its current weights, model name, and
|
||||
# endpoint churn for free.
|
||||
self.teacher_pool = self.policy_pool
|
||||
self.teacher_clients = self.clients
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Build opsd's own hint-block renderer from config — it is not handed
|
||||
@@ -51,7 +51,7 @@ class OPSDAlgorithm(Algorithm):
|
||||
identically to the policy's own prompts."""
|
||||
from renderers.base import create_renderer, load_tokenizer
|
||||
|
||||
self.renderer = create_renderer(load_tokenizer(self.policy_pool.model_name), self.renderer_config)
|
||||
self.renderer = create_renderer(load_tokenizer(self.clients.model_name), self.renderer_config)
|
||||
|
||||
def _demonstration(self, episode: vf.Episode, trace: vf.Trace) -> str:
|
||||
demonstration = trace.info.get(self.demo_key)
|
||||
@@ -66,13 +66,13 @@ class OPSDAlgorithm(Algorithm):
|
||||
return demonstration
|
||||
|
||||
async def score_episode(self, episode: vf.Episode) -> None:
|
||||
pool = self.teacher_pool
|
||||
teacher = self.teacher_clients
|
||||
renderer = self.renderer
|
||||
assert renderer is not None, "renderer not built — Algorithm.setup() must run first"
|
||||
for _, trace in iter_trainable_traces([episode]):
|
||||
hint = self.template.format(demonstration=self._demonstration(episode, trace))
|
||||
hint_block = renderer.render_ids([{"role": "system", "content": hint}], add_generation_prompt=False)
|
||||
branches = [branch for branch, _ in iter_trainable_branches(trace)]
|
||||
scores = await asyncio.gather(*(pool.score(hint_block + branch.token_ids) for branch in branches))
|
||||
scores = await asyncio.gather(*(teacher.score(hint_block + branch.token_ids) for branch in branches))
|
||||
for branch, full_logprobs in zip(branches, scores, strict=True):
|
||||
assign_reference_logprobs(branch, full_logprobs[len(hint_block) :])
|
||||
|
||||
@@ -10,7 +10,7 @@ from prime_rl.orchestrator.algo.base import Algorithm, iter_trainable_traces
|
||||
from prime_rl.orchestrator.algo.routing import assign_advantages
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class RAEAlgorithm(Algorithm):
|
||||
@@ -31,8 +31,8 @@ class RAEAlgorithm(Algorithm):
|
||||
live in orchestrator memory: a restart re-warms them over ~1/(1 − decay)
|
||||
traces per agent."""
|
||||
|
||||
def __init__(self, config: RAEAlgoConfig, policy_pool: InferencePool):
|
||||
super().__init__(config, policy_pool)
|
||||
def __init__(self, config: RAEAlgoConfig, clients: InferenceClient):
|
||||
super().__init__(config, clients)
|
||||
self.decay = config.decay
|
||||
self.baselines: dict[str, float] = defaultdict(float)
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.algorithm import ActionLossType
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
|
||||
|
||||
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
|
||||
|
||||
@@ -40,8 +40,9 @@ class PrefillScorer:
|
||||
await self._client.close()
|
||||
|
||||
|
||||
class InferencePool:
|
||||
"""Inference pool with a single data-plane endpoint and one admin client per server."""
|
||||
class InferenceClient:
|
||||
"""Data-plane clients for one inference endpoint (the router of the policy
|
||||
deployment, or an external API for frozen models)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -59,7 +60,34 @@ class InferencePool:
|
||||
renderer_model_name=renderer_model_name,
|
||||
)
|
||||
self.eval_client = setup_client(client_config, client_type=eval_client_type)
|
||||
self._admin_clients = setup_admin_clients(client_config)
|
||||
self._scorer = PrefillScorer()
|
||||
self.model_name = model_name
|
||||
|
||||
def update_model_name(self, model_name: str) -> None:
|
||||
self.model_name = model_name
|
||||
|
||||
async def score(self, token_ids: list[int]) -> list[float]:
|
||||
"""Prefill-score ``token_ids`` under this endpoint's model (one logprob
|
||||
per token, 0.0 for the leading token)."""
|
||||
return await self._scorer.score(self.train_client, self.model_name, token_ids)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
await self._scorer.aclose()
|
||||
|
||||
|
||||
class AdminClients:
|
||||
"""Admin plane of the policy inference deployment: one httpx client per
|
||||
engine process. The router serves no admin routes (pause/resume,
|
||||
update_weights, init_broadcaster, load_lora_adapter live on the engines),
|
||||
so these clients bypass it via ``admin_base_url``.
|
||||
|
||||
The client order is load-bearing: ``admin_base_url`` order must match the
|
||||
GPU rank order — the ``rank_offset`` math in ``init_nccl_broadcast`` /
|
||||
``init_nixl_broadcast`` and the metrics collector's role list index into
|
||||
it."""
|
||||
|
||||
def __init__(self, client_config: ClientConfig):
|
||||
self.clients = setup_admin_clients(client_config)
|
||||
# When admin URLs bypass a router, also health-check the client-facing
|
||||
# (router) endpoint - it only starts serving once its workers are healthy.
|
||||
self._router_clients = (
|
||||
@@ -69,33 +97,25 @@ class InferencePool:
|
||||
)
|
||||
self._skip_model_check = client_config.skip_model_check
|
||||
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
|
||||
self._scorer = PrefillScorer()
|
||||
self.model_name = model_name
|
||||
|
||||
@property
|
||||
def admin_clients(self) -> list[AsyncClient]:
|
||||
return self._admin_clients
|
||||
async def wait_for_ready(self, model_name: str) -> None:
|
||||
await check_health(self.clients + self._router_clients, timeout=self._wait_for_ready_timeout)
|
||||
await maybe_check_has_model(self.clients, model_name, skip_model_check=self._skip_model_check)
|
||||
|
||||
def update_model_name(self, model_name: str) -> None:
|
||||
self.model_name = model_name
|
||||
async def aclose(self) -> None:
|
||||
for client in self.clients + self._router_clients:
|
||||
await client.aclose()
|
||||
|
||||
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
|
||||
await check_health(
|
||||
self._admin_clients + self._router_clients,
|
||||
timeout=timeout if timeout is not None else self._wait_for_ready_timeout,
|
||||
)
|
||||
await maybe_check_has_model(self._admin_clients, model_name, skip_model_check=self._skip_model_check)
|
||||
|
||||
async def update_weights(self, weight_dir: Path | None, lora_name: str | None = None, step: int = 0) -> None:
|
||||
await update_weights(self._admin_clients, weight_dir, lora_name=lora_name, step=step)
|
||||
|
||||
async def score(self, token_ids: list[int]) -> list[float]:
|
||||
"""Prefill-score ``token_ids`` under this pool's model (one logprob per
|
||||
token, 0.0 for the leading token). Delegates to the shared scorer."""
|
||||
return await self._scorer.score(self.train_client, self.model_name, token_ids)
|
||||
|
||||
async def stop(self) -> None:
|
||||
await self._scorer.aclose()
|
||||
async def check_inference_ready(client_config: ClientConfig, model_name: str) -> None:
|
||||
"""One-shot readiness check of an inference endpoint (health + model
|
||||
listing) with transient clients — for frozen endpoints that never need a
|
||||
persistent admin plane."""
|
||||
admin = AdminClients(client_config)
|
||||
try:
|
||||
await admin.wait_for_ready(model_name)
|
||||
finally:
|
||||
await admin.aclose()
|
||||
|
||||
|
||||
def setup_client(
|
||||
@@ -172,13 +192,13 @@ async def maybe_check_has_model(
|
||||
|
||||
|
||||
async def check_health(
|
||||
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 10, timeout: int = 1800
|
||||
admin_clients: list[AsyncClient], interval: int = 1, log_interval: int = 30, timeout: int = 1800
|
||||
) -> None:
|
||||
logger = get_logger()
|
||||
|
||||
async def _check_health(admin_client: AsyncClient) -> None:
|
||||
wait_time = 0
|
||||
logger.debug("Starting pinging /health to check health")
|
||||
logger.debug("Pinging /health until the inference server is ready")
|
||||
while wait_time < timeout:
|
||||
try:
|
||||
response = await admin_client.get("/health")
|
||||
@@ -190,9 +210,10 @@ async def check_health(
|
||||
return
|
||||
except Exception as e:
|
||||
if wait_time % log_interval == 0 and wait_time > 0:
|
||||
logger.warning(
|
||||
f"Inference server was not reached after {wait_time} seconds (Error: {e}) on {admin_client.base_url}"
|
||||
logger.info(
|
||||
f"Waiting for inference server at {admin_client.base_url} to start up ({wait_time}s elapsed)"
|
||||
)
|
||||
logger.debug(f"Inference server at {admin_client.base_url} not reachable: {e!r}")
|
||||
await asyncio.sleep(interval)
|
||||
wait_time += interval
|
||||
msg = f"Inference server is not ready after {wait_time} (>{timeout}) seconds. Aborting..."
|
||||
@@ -202,9 +223,6 @@ async def check_health(
|
||||
await asyncio.gather(*[_check_health(admin_client) for admin_client in admin_clients])
|
||||
|
||||
|
||||
NCCL_READY_MARKER = "NCCL_READY"
|
||||
|
||||
|
||||
def _is_retryable_admin_error(exception: BaseException) -> bool:
|
||||
"""Check if an exception should trigger a retry for an admin op (pause/resume/update_weights)."""
|
||||
if isinstance(exception, httpx.HTTPStatusError):
|
||||
@@ -219,6 +237,8 @@ def _is_retryable_admin_error(exception: BaseException) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
NCCL_READY_MARKER = "NCCL_READY"
|
||||
|
||||
# Per-attempt read timeout for admin ops, overridable per call. The admin
|
||||
# AsyncClient uses `timeout=None`, so without this a stuck server would hang the
|
||||
# weight update forever: the read timeout converts a hang into a TimeoutException
|
||||
@@ -253,7 +273,7 @@ async def _admin_post(client: AsyncClient, path: str, *, timeout_s: float = ADMI
|
||||
async def _pause_engines(admin_clients: list[AsyncClient], *, step: int) -> None:
|
||||
"""Pause all inference engines, waiting for in-flight requests to drain."""
|
||||
logger = get_logger()
|
||||
logger.info(f"Updating policy in-flight to v{step}")
|
||||
logger.debug(f"Pausing inference engines to update weights to policy v{step}")
|
||||
await asyncio.gather(
|
||||
*[_admin_post(client, "/pause", params={"mode": "keep", "clear_cache": "false"}) for client in admin_clients]
|
||||
)
|
||||
@@ -393,7 +413,7 @@ async def init_nccl_broadcast(
|
||||
host: str,
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int | None = None,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
"""Initialize NCCL broadcast on all inference servers.
|
||||
@@ -404,12 +424,6 @@ async def init_nccl_broadcast(
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
if inference_world_size is None:
|
||||
inference_world_size = len(admin_clients)
|
||||
logger.warning(
|
||||
f"inference_world_size not provided, defaulting to {inference_world_size} (one GPU per admin client)"
|
||||
)
|
||||
|
||||
gpus_per_server = inference_world_size // len(admin_clients)
|
||||
|
||||
logger.info(
|
||||
@@ -7,21 +7,20 @@
|
||||
once.
|
||||
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
|
||||
- Emit-everything invariant: every dispatched episode eventually reaches
|
||||
``out_q`` exactly once. Failures remain episode errors;
|
||||
sinks decide drop / partial-train policy.
|
||||
``out_q`` exactly once — as a native episode, or covered by its group's
|
||||
single ``GroupCancellation`` message when the group is dropped. Failures
|
||||
remain episode errors; sinks decide drop / partial-train policy.
|
||||
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight episodes of the opposite kind drain
|
||||
naturally on either side of an eval boundary.
|
||||
- ``on_version_pending`` (called by the watcher before the engines pause for
|
||||
the weight update) bumps ``off_policy_steps`` on in-flight train episodes and
|
||||
drops groups past ``max_off_policy_steps``.
|
||||
Eval rollouts are measurements for the policy version they started with,
|
||||
so they are allowed to finish even if training advances. Train rollouts
|
||||
sampled from a frozen model never age — their sampler doesn't change
|
||||
with policy updates.
|
||||
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
|
||||
count-to-``group_size`` finalization still fires.
|
||||
the weight update) drops train groups already past ``max_off_policy_steps`` — a
|
||||
compute-saving early cancel; the sink's queue sweep is what guarantees the
|
||||
bound. Eval episodes are measurements for the policy version they started
|
||||
with, so they are allowed to finish even if training advances. Train
|
||||
episodes sampled from a frozen model never go stale — their generation
|
||||
source doesn't change with policy updates.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,23 +33,27 @@ from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum, auto
|
||||
from typing import Any, Literal
|
||||
from typing import Literal
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from aiolimiter import AsyncLimiter
|
||||
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
CancelReason,
|
||||
DispatchResult,
|
||||
GroupCancellation,
|
||||
GroupState,
|
||||
InflightEpisode,
|
||||
Policy,
|
||||
Progress,
|
||||
WorkKind,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import min_fresh_version
|
||||
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -127,7 +130,7 @@ def _trace_task(task: vf.Task) -> vf.TraceTask:
|
||||
)
|
||||
|
||||
|
||||
def _validate_episode_task(episode: vf.Episode[Any, Any, Any], task: vf.Task) -> None:
|
||||
def _validate_episode_task(episode: vf.WireEpisode, task: vf.Task) -> None:
|
||||
expected = (task.key, task.hash)
|
||||
actual = (episode.task.key, episode.task.hash)
|
||||
if actual != expected:
|
||||
@@ -138,7 +141,7 @@ class Dispatcher:
|
||||
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
|
||||
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules episodes
|
||||
under shared capacity, and emits native verifier episodes to ``out_q``.
|
||||
The watcher drives ``on_version_pending`` for off-policy
|
||||
The watcher drives ``on_version_pending`` for staleness
|
||||
cancellation; the orchestrator triggers eval epochs."""
|
||||
|
||||
def __init__(
|
||||
@@ -148,7 +151,7 @@ class Dispatcher:
|
||||
eval_envs: EvalEnvs | None,
|
||||
train_source: TrainSource | None,
|
||||
eval_source: EvalSource | None,
|
||||
policy_pool: InferencePool,
|
||||
policy_clients: InferenceClient,
|
||||
policy: Policy,
|
||||
progress: Progress | None,
|
||||
initial_max_inflight: int,
|
||||
@@ -165,7 +168,7 @@ class Dispatcher:
|
||||
self.eval_envs = eval_envs
|
||||
# Train rollouts go to the env's generation source; eval always
|
||||
# evaluates the policy.
|
||||
self.policy_pool = policy_pool
|
||||
self.policy_clients = policy_clients
|
||||
self.train_source = train_source
|
||||
self.eval_source = eval_source
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
@@ -199,9 +202,9 @@ class Dispatcher:
|
||||
# Bounded so the dispatcher backpressures on a slow sink (unbounded
|
||||
# when no hard ceiling is configured — the dynamic cap still bounds
|
||||
# in-flight work). One entry per episode — the sinks count episodes,
|
||||
# never loose traces.
|
||||
# never loose traces — plus one ``GroupCancellation`` per dropped group.
|
||||
maxsize = max(8, max_inflight_ceiling) if max_inflight_ceiling is not None else 0
|
||||
self.out_q: asyncio.Queue[vf.Episode[Any, Any, Any]] = asyncio.Queue(maxsize=maxsize)
|
||||
self.out_q: asyncio.Queue[DispatchResult] = asyncio.Queue(maxsize=maxsize)
|
||||
|
||||
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
|
||||
# Set by the orchestrator after the final train step; pipeline then
|
||||
@@ -218,14 +221,14 @@ class Dispatcher:
|
||||
self.stopped = asyncio.Event()
|
||||
self.task: asyncio.Task | None = None
|
||||
|
||||
def _train_generation_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
|
||||
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
|
||||
def _train_generation_for(self, env_name: str) -> tuple[InferenceClient, str, bool]:
|
||||
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
|
||||
eval always uses the policy."""
|
||||
assert self.train_envs is not None # train groups only exist when train is configured
|
||||
source = self.train_envs.get(env_name).generation_source
|
||||
if source.uses_live_policy:
|
||||
return source.pool, self.policy.model_name, True
|
||||
return source.pool, source.pool.model_name, False
|
||||
return source.clients, self.policy.model_name, True
|
||||
return source.clients, source.clients.model_name, False
|
||||
|
||||
@property
|
||||
def inflight_train_count(self) -> int:
|
||||
@@ -267,9 +270,9 @@ class Dispatcher:
|
||||
if shed >= n:
|
||||
break
|
||||
# Count only live cancellations toward the excess: drop_group's
|
||||
# return includes never-dispatched markers, which free no permits
|
||||
# return includes never-dispatched episodes, which free no permits
|
||||
live = sum(1 for meta in self.inflight.values() if meta.group_id == group_id)
|
||||
await self.drop_group(group_id)
|
||||
await self.drop_group(group_id, reason="overload")
|
||||
shed += live
|
||||
if shed:
|
||||
get_logger().warning(f"Cancelled {shed} youngest in-flight episodes after overload cut")
|
||||
@@ -315,15 +318,17 @@ class Dispatcher:
|
||||
triggered eval drain naturally."""
|
||||
self.train_scheduling_disabled = True
|
||||
|
||||
@property
|
||||
def max_off_policy_level(self) -> int:
|
||||
steps = [m.off_policy_steps for m in self.inflight.values() if m.kind == "train"]
|
||||
return max(steps) if steps else 0
|
||||
|
||||
@property
|
||||
def mean_off_policy_level(self) -> float:
|
||||
steps = [m.off_policy_steps for m in self.inflight.values() if m.kind == "train"]
|
||||
return sum(steps) / len(steps) if steps else 0.0
|
||||
def inflight_staleness(self) -> list[int]:
|
||||
"""Current staleness of each in-flight live-sourced train episode: the
|
||||
version the batch being collected trains on (v{step-1}) minus the
|
||||
episode's dispatch version."""
|
||||
if self.train_envs is None or self.progress is None:
|
||||
return []
|
||||
return [
|
||||
(self.progress.step - 1) - meta.policy_version
|
||||
for meta in self.inflight.values()
|
||||
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
|
||||
]
|
||||
|
||||
# ── lifecycle ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -360,32 +365,32 @@ class Dispatcher:
|
||||
self.task = None
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""Bump off-policy counters and drop groups past
|
||||
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
|
||||
the sink still finalizes the partial group). Eval rollouts are not
|
||||
aged because they are tied to their start-time policy version.
|
||||
"""Drop train groups past ``max_off_policy_steps``: a group dispatched at
|
||||
v{k} ships at earliest in the batch currently collecting, at staleness
|
||||
``(progress.step - 1) - k`` — beyond the bound it can never train, so
|
||||
cut it before more inference sinks in. This is a compute saver; the
|
||||
sink's queue sweep is what guarantees no stale episode ships. Eval
|
||||
groups never go stale (they are tied to their start-time policy
|
||||
version), nor do frozen-sourced train groups (their generation source
|
||||
doesn't change with policy updates).
|
||||
|
||||
Runs *before* the inference engines are paused for the weight update so
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
stale_groups: set[uuid.UUID] = set()
|
||||
if self.train_envs is None or self.progress is None:
|
||||
return
|
||||
min_version = min_fresh_version(self.progress.step, self.max_off_policy_steps)
|
||||
stale_groups = [
|
||||
gid
|
||||
for gid, group in self.groups.items()
|
||||
if group.kind == "train"
|
||||
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
|
||||
and group.policy_version_at_start < min_version
|
||||
]
|
||||
cancelled = 0
|
||||
for meta in self.inflight.values():
|
||||
if meta.kind != "train":
|
||||
continue
|
||||
# Frozen-sourced rollouts never go stale — their generation source doesn't
|
||||
# change with policy updates.
|
||||
assert self.train_envs is not None
|
||||
if not self.train_envs.get(meta.env_name).generation_source.uses_live_policy:
|
||||
continue
|
||||
meta.off_policy_steps += 1
|
||||
if meta.off_policy_steps > self.max_off_policy_steps:
|
||||
stale_groups.add(meta.group_id)
|
||||
|
||||
for gid in stale_groups:
|
||||
removed = await self.drop_group(gid)
|
||||
cancelled += removed
|
||||
cancelled += await self.drop_group(gid, reason="stale")
|
||||
|
||||
if cancelled:
|
||||
get_logger().warning(
|
||||
@@ -457,29 +462,29 @@ class Dispatcher:
|
||||
return await self.schedule_group_episode(gid, fresh)
|
||||
|
||||
def next_fresh_group(self, kind: WorkKind, envs) -> GroupState | None:
|
||||
"""Pop the next example from the corresponding source and wrap it in
|
||||
"""Pop the next task from the corresponding source and wrap it in
|
||||
a ``GroupState``. Returns ``None`` if the source is empty."""
|
||||
if kind == "train":
|
||||
assert self.train_source is not None
|
||||
source = self.train_source
|
||||
if self.progress is None:
|
||||
raise RuntimeError("Train dispatch requires progress state")
|
||||
request = self.train_source.next_task(step=self.progress.step)
|
||||
else:
|
||||
assert self.eval_source is not None
|
||||
source = self.eval_source
|
||||
example = source.next_example()
|
||||
if example is None:
|
||||
request = self.eval_source.next_task()
|
||||
if request is None:
|
||||
return None
|
||||
|
||||
env_name = example["env_name"]
|
||||
env_name = request.env_name
|
||||
group_size = envs.get(env_name).config.group_size
|
||||
eval_step: int | None = example.get("eval_step") if kind == "eval" else None
|
||||
|
||||
return GroupState(
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
task=example["task"],
|
||||
task=request.task,
|
||||
step=request.step,
|
||||
episodes_to_schedule=group_size,
|
||||
target_episodes=group_size,
|
||||
eval_step=eval_step,
|
||||
policy_version_at_start=self.policy.version,
|
||||
)
|
||||
|
||||
@@ -495,14 +500,12 @@ class Dispatcher:
|
||||
# goes through the eval client (chat-completions) so eval scores stay
|
||||
# comparable.
|
||||
if group.kind == "eval":
|
||||
pool, model_name = self.policy_pool, self.policy.model_name
|
||||
clients, model_name = self.policy_clients, self.policy.model_name
|
||||
live_sourced = True
|
||||
else:
|
||||
pool, model_name, live_sourced = self._train_generation_for(group.env_name)
|
||||
clients, model_name, live_sourced = self._train_generation_for(group.env_name)
|
||||
|
||||
if group.pinned_client is None:
|
||||
group.pinned_client = pool.eval_client if group.kind == "eval" else pool.train_client
|
||||
client = group.pinned_client
|
||||
client = clients.eval_client if group.kind == "eval" else clients.train_client
|
||||
|
||||
env_collection = self.train_envs if group.kind == "train" else self.eval_envs
|
||||
if env_collection is None:
|
||||
@@ -534,21 +537,12 @@ class Dispatcher:
|
||||
group_id=group_id,
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start,
|
||||
step=self._work_step(group.kind, group.eval_step),
|
||||
step=group.step,
|
||||
client_config=client,
|
||||
eval_step=group.eval_step,
|
||||
started_at=time.monotonic(),
|
||||
)
|
||||
return True
|
||||
|
||||
def _work_step(self, kind: WorkKind, eval_step: int | None) -> int:
|
||||
if kind == "eval":
|
||||
assert eval_step is not None
|
||||
return eval_step
|
||||
if self.progress is None:
|
||||
raise RuntimeError("Train dispatch requires progress state")
|
||||
return self.progress.step
|
||||
|
||||
async def acquire(self) -> None:
|
||||
"""Reserve one permit + rate-limit it. Caller must precheck
|
||||
``available_permits >= 1``; this is not a blocking acquire."""
|
||||
@@ -574,7 +568,7 @@ class Dispatcher:
|
||||
|
||||
is_synth_exception = False
|
||||
try:
|
||||
episode: vf.Episode[Any, Any, Any] = task.result()
|
||||
episode: vf.WireEpisode = task.result()
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except Exception as exc:
|
||||
@@ -624,21 +618,17 @@ class Dispatcher:
|
||||
self,
|
||||
meta: InflightEpisode,
|
||||
group: GroupState | None,
|
||||
episode: vf.Episode[Any, Any, Any],
|
||||
episode: vf.WireEpisode,
|
||||
) -> None:
|
||||
"""Stamp one completed episode with its dispatch provenance and emit it."""
|
||||
_validate_episode_task(episode, meta.task)
|
||||
eval_step = meta.eval_step
|
||||
policy_version = meta.policy_version
|
||||
if group is not None:
|
||||
eval_step = group.eval_step
|
||||
policy_version = group.policy_version_at_start
|
||||
group.emitted += 1
|
||||
if group.emitted >= group.target_episodes:
|
||||
self.groups.pop(meta.group_id, None)
|
||||
|
||||
if meta.kind == "eval":
|
||||
assert eval_step is not None, "eval episode missing eval_step"
|
||||
episode.env.name = meta.env_name
|
||||
episode.group = vf.GroupInfo(id=str(meta.group_id))
|
||||
live_policy = meta.kind == "eval"
|
||||
@@ -655,11 +645,11 @@ class Dispatcher:
|
||||
episode.record_run(run)
|
||||
await self.out_q.put(episode)
|
||||
|
||||
async def drop_group(self, group_id: uuid.UUID) -> int:
|
||||
"""Cancel remaining in-flight tasks for this group and emit a
|
||||
``Cancelled`` marker for every rollout it still owes the sink
|
||||
(both in-flight and not-yet-scheduled). Returns the count for
|
||||
off-policy metrics."""
|
||||
async def drop_group(self, group_id: uuid.UUID, *, reason: CancelReason) -> int:
|
||||
"""Cancel this group's remaining in-flight tasks and emit one
|
||||
``GroupCancellation`` covering every episode it still owes the sink (both
|
||||
in-flight and never-dispatched), so count-to-``group_size``
|
||||
finalization still fires. Returns the owed count for metrics."""
|
||||
group = self.groups.pop(group_id, None)
|
||||
# Sync claim phase: pop matching tasks from ``self.inflight`` and
|
||||
# release their permits in one non-yielding sweep. After this loop
|
||||
@@ -674,69 +664,33 @@ class Dispatcher:
|
||||
self.release()
|
||||
claimed.append((task, meta))
|
||||
|
||||
tasks_to_cancel = [task for task, _ in claimed]
|
||||
inflight_cancelled = len(claimed)
|
||||
last_meta: InflightEpisode | None = claimed[-1][1] if claimed else None
|
||||
for _, meta in claimed:
|
||||
episode = vf.WireEpisode(
|
||||
env=vf.EnvInfo(id=meta.env_name),
|
||||
task=_trace_task(meta.task),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
)
|
||||
await self.emit_episode(meta, group, episode)
|
||||
|
||||
# The group may have episodes that were never dispatched. Emit markers
|
||||
# for those too so the sink reaches ``target_episodes``.
|
||||
#
|
||||
# ``last_meta`` can be ``None`` if the only inflight task for this
|
||||
# group completed naturally between ``on_version_pending``'s snapshot
|
||||
# and us reaching it — synthesize a stand-in from the group state
|
||||
unscheduled_cancelled = 0
|
||||
if group is not None and group.episodes_to_schedule > 0:
|
||||
fallback_meta = last_meta or InflightEpisode(
|
||||
kind=group.kind,
|
||||
env_name=group.env_name,
|
||||
group_id=group_id,
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start,
|
||||
step=self._work_step(group.kind, group.eval_step),
|
||||
eval_step=group.eval_step,
|
||||
)
|
||||
unscheduled_cancelled = group.episodes_to_schedule
|
||||
for _ in range(unscheduled_cancelled):
|
||||
episode = vf.WireEpisode(
|
||||
env=vf.EnvInfo(id=group.env_name),
|
||||
task=_trace_task(group.task),
|
||||
ok=False,
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
)
|
||||
await self.emit_episode(fallback_meta, group, episode)
|
||||
|
||||
unscheduled_cancelled = group.episodes_to_schedule if group is not None else 0
|
||||
cancelled = inflight_cancelled + unscheduled_cancelled
|
||||
if cancelled > 0:
|
||||
meta_for_log = last_meta or (
|
||||
InflightEpisode(
|
||||
kind=group.kind,
|
||||
env_name=group.env_name,
|
||||
group_id=group_id,
|
||||
task=group.task,
|
||||
policy_version=group.policy_version_at_start if group else 0,
|
||||
step=self._work_step(group.kind, group.eval_step),
|
||||
eval_step=group.eval_step,
|
||||
)
|
||||
if group is not None
|
||||
else None
|
||||
)
|
||||
if meta_for_log is not None:
|
||||
self.metrics.record_cancellation(kind=meta_for_log.kind, env_name=meta_for_log.env_name, n=cancelled)
|
||||
get_logger().debug(
|
||||
f"drain {meta_for_log.kind} | group={str(group_id)[:8]} env={meta_for_log.env_name} | "
|
||||
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
|
||||
)
|
||||
|
||||
if tasks_to_cancel:
|
||||
await safe_cancel_all(tasks_to_cancel)
|
||||
if cancelled > 0:
|
||||
# ``group`` can be ``None`` only if every episode was already
|
||||
# emitted — then nothing is in flight or unscheduled, so kind/env
|
||||
# always resolve from the group or a claimed meta.
|
||||
kind = group.kind if group is not None else claimed[-1][1].kind
|
||||
env_name = group.env_name if group is not None else claimed[-1][1].env_name
|
||||
self.metrics.record_cancellation(kind=kind, env_name=env_name, n=cancelled)
|
||||
get_logger().debug(
|
||||
f"Dropped {kind} group | group={str(group_id)[:8]} env={env_name} reason={reason} | "
|
||||
f"cancelled={cancelled} (inflight={inflight_cancelled} unscheduled={unscheduled_cancelled})"
|
||||
)
|
||||
await self.out_q.put(
|
||||
GroupCancellation(
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
group_id=str(group_id),
|
||||
count=cancelled,
|
||||
reason=reason,
|
||||
)
|
||||
)
|
||||
|
||||
if claimed:
|
||||
await safe_cancel_all([task for task, _ in claimed])
|
||||
return cancelled
|
||||
|
||||
async def cancel_inflight_episodes(self) -> None:
|
||||
@@ -777,11 +731,12 @@ class Dispatcher:
|
||||
|
||||
def gauges(self) -> dict[str, float]:
|
||||
"""Instantaneous, read-only gauges sampled by the periodic logger."""
|
||||
staleness = self.inflight_staleness()
|
||||
return {
|
||||
"dispatcher/inflight/train": float(self.inflight_train_count),
|
||||
"dispatcher/inflight/eval": float(self.inflight_eval_count),
|
||||
"dispatcher/queued/eval": float(self.queued_eval_examples),
|
||||
"dispatcher/mode": float(self.mode == DispatcherMode.PREFER_EVAL),
|
||||
"dispatcher/off_policy_level/max": float(self.max_off_policy_level),
|
||||
"dispatcher/off_policy_level/mean": self.mean_off_policy_level,
|
||||
"dispatcher/off_policy/max": float(max(staleness, default=0)),
|
||||
"dispatcher/off_policy/mean": sum(staleness) / len(staleness) if staleness else 0.0,
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from collections.abc import Iterator, Sequence
|
||||
from itertools import islice
|
||||
from typing import Generic, TypeVar
|
||||
@@ -30,7 +31,7 @@ from verifiers.v1.serve import EnvClient
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
from prime_rl.orchestrator.generation_source import GenerationSource
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
|
||||
# Max wait for the env server to answer health. Generous because the launcher spawns
|
||||
# servers concurrently with the orchestrator, and a server imports its env package
|
||||
@@ -68,6 +69,7 @@ class Env:
|
||||
async def start(self) -> None:
|
||||
"""Connect to the env server and load the taskset client-side."""
|
||||
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
|
||||
t0 = time.perf_counter()
|
||||
self._env_client = EnvClient(address=self.address)
|
||||
# The server may still be coming up (the launcher spawns it concurrently with
|
||||
# the orchestrator), so poll until it answers.
|
||||
@@ -82,7 +84,7 @@ class Env:
|
||||
self.tasks = iter(materialized)
|
||||
self.num_tasks = len(materialized)
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks}")
|
||||
get_logger().info(f"Env {self.name} ready in {format_time(time.perf_counter() - t0)} (num_tasks={num_tasks})")
|
||||
|
||||
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
|
||||
sampling = {**self.sampling_args}
|
||||
@@ -137,7 +139,7 @@ class EvalEnv(Env):
|
||||
def __init__(self, config: EvalSourceConfig, address: str):
|
||||
super().__init__(config, address)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.examples: list[dict] = []
|
||||
self.examples: list[vf.Task] = []
|
||||
|
||||
async def start(self) -> None:
|
||||
await super().start()
|
||||
@@ -146,7 +148,7 @@ class EvalEnv(Env):
|
||||
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
|
||||
# A fixed eval set, pulled off the tasks once and reused every epoch.
|
||||
tasks = list(self.tasks) if n < 0 else list(islice(self.tasks, n))
|
||||
self.examples = [{"task": task} for task in tasks]
|
||||
self.examples = tasks
|
||||
|
||||
|
||||
EnvT = TypeVar("EnvT", bound=Env)
|
||||
@@ -190,17 +192,18 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
configs: Sequence[TrainSourceConfig],
|
||||
addresses: dict[tuple[str, str], str],
|
||||
*,
|
||||
policy_pool,
|
||||
clients,
|
||||
renderer_config=None,
|
||||
):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
|
||||
get_logger().info(f"Initializing {config.algo.type} algorithm for {config.resolved_name}")
|
||||
env = TrainEnv(
|
||||
config,
|
||||
addresses[("train", config.resolved_name)],
|
||||
GenerationSource(config.algo.sampling, policy_pool, renderer_config),
|
||||
build_algorithm(config.algo, policy_pool),
|
||||
GenerationSource(config.algo.sampling, clients, renderer_config),
|
||||
build_algorithm(config.algo, clients),
|
||||
)
|
||||
self._envs[env.name] = env
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""EvalSource: trigger-driven, finite-per-epoch pull of eval examples.
|
||||
|
||||
The orchestrator pokes ``trigger(step)`` after each ship + once at
|
||||
startup; the dispatcher pulls via ``next_example()`` until
|
||||
startup; the dispatcher pulls via ``next_task()`` until
|
||||
``bool(source) == False``. Constructed only when eval is configured."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -9,8 +9,11 @@ from __future__ import annotations
|
||||
from collections import deque
|
||||
from itertools import zip_longest
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import EvalConfig
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.types import TaskRequest
|
||||
|
||||
|
||||
class EvalSource:
|
||||
@@ -26,18 +29,13 @@ class EvalSource:
|
||||
self.eval_envs = eval_envs
|
||||
self.eval_config = eval_config
|
||||
|
||||
self.examples_by_env: dict[str, list[dict]] = {}
|
||||
self.tasks_by_env: dict[str, list[vf.Task]] = {}
|
||||
self.intervals: dict[str, int] = {}
|
||||
for env in eval_envs:
|
||||
rows: list[dict] = []
|
||||
for ex in env.examples:
|
||||
row = dict(ex)
|
||||
row["env_name"] = env.name
|
||||
rows.append(row)
|
||||
self.examples_by_env[env.name] = rows
|
||||
self.tasks_by_env[env.name] = list(env.examples)
|
||||
self.intervals[env.name] = env.config.interval
|
||||
|
||||
self.queue: deque[dict] = deque()
|
||||
self.queue: deque[TaskRequest] = deque()
|
||||
|
||||
# On resume we skip the startup eval; on fresh start the first
|
||||
# trigger fires every env (subject to ``skip_first_step``)
|
||||
@@ -59,18 +57,16 @@ class EvalSource:
|
||||
# dispatcher rotates at example granularity. ``try_schedule``'s
|
||||
# continue-group branch still keeps each example's group_size
|
||||
# rollouts back-to-back, so per-example prefix-cache locality holds
|
||||
iters = [iter(self.examples_by_env[name]) for name in fired]
|
||||
for round_examples in zip_longest(*iters):
|
||||
for example in round_examples:
|
||||
if example is None:
|
||||
iters = [iter(self.tasks_by_env[name]) for name in fired]
|
||||
for round_tasks in zip_longest(*iters):
|
||||
for env_name, task in zip(fired, round_tasks, strict=True):
|
||||
if task is None:
|
||||
continue
|
||||
row = dict(example)
|
||||
row["eval_step"] = step
|
||||
self.queue.append(row)
|
||||
self.queue.append(TaskRequest(env_name=env_name, task=task, step=step))
|
||||
return fired
|
||||
|
||||
def next_example(self) -> dict | None:
|
||||
"""Pop the next eval example, or ``None`` when the queue is empty."""
|
||||
def next_task(self) -> TaskRequest | None:
|
||||
"""Pop the next eval task, or ``None`` when the queue is empty."""
|
||||
if not self.queue:
|
||||
return None
|
||||
return self.queue.popleft()
|
||||
|
||||
@@ -5,38 +5,36 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
|
||||
from prime_rl.orchestrator.algo import connect_frozen_pool
|
||||
from prime_rl.orchestrator.algo import connect_frozen_client
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers import RendererConfig
|
||||
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.orchestrator.clients import InferenceClient
|
||||
|
||||
|
||||
class GenerationSource:
|
||||
"""One env's generation model and inference pool.
|
||||
"""One env's generation model and inference clients.
|
||||
|
||||
``pool`` is the pool train rollouts are generated from: the policy pool,
|
||||
swapped for a connected frozen pool in :meth:`setup` when the source is an
|
||||
inline frozen model. A frozen source *generates* rollouts, so its pool uses
|
||||
``clients`` is what train rollouts are generated from: the policy clients,
|
||||
swapped for a connected frozen endpoint in :meth:`setup` when the source is
|
||||
an inline frozen model. A frozen source *generates* rollouts, so it uses
|
||||
the renderer (token-in/out) client (built from ``renderer_config``) — the
|
||||
rollout must carry tokens for training."""
|
||||
|
||||
def __init__(
|
||||
self, config: SamplingConfig, policy_pool: InferencePool, renderer_config: RendererConfig | None = None
|
||||
):
|
||||
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
|
||||
assert config.source is not None, "sampling.source must be resolved by config validation"
|
||||
self.config = config
|
||||
self.pool: InferencePool = policy_pool
|
||||
self.clients: InferenceClient = clients
|
||||
self.renderer_config = renderer_config
|
||||
self.connected_pools: list[InferencePool] = [] # client pools connected in setup(); closed at shutdown
|
||||
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
|
||||
|
||||
async def setup(self) -> None:
|
||||
"""Connect a client pool to a frozen generation source and wait for
|
||||
"""Connect clients to a frozen generation source and wait for
|
||||
readiness. Must run before dispatching."""
|
||||
if isinstance(self.config.source, FrozenModelConfig):
|
||||
self.pool = await connect_frozen_pool(self.config.source, renderer_config=self.renderer_config)
|
||||
self.connected_pools.append(self.pool)
|
||||
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
|
||||
self.connected = self.clients
|
||||
|
||||
@property
|
||||
def uses_live_policy(self) -> bool:
|
||||
|
||||
@@ -16,18 +16,22 @@ Subset = Literal["all", "effective"]
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TraceRecord:
|
||||
"""A trace joined with its episode and training selection state."""
|
||||
"""A trace joined with its episode and training selection state.
|
||||
``cancelled`` marks episodes the pipeline voided (stale drop) — a
|
||||
selection verdict disjoint from trace errors."""
|
||||
|
||||
episode: vf.Episode
|
||||
trace: vf.Trace
|
||||
sampled: bool
|
||||
admitted: bool
|
||||
cancelled: bool
|
||||
|
||||
|
||||
def _records(
|
||||
episodes: list[vf.Episode],
|
||||
sampled_trace_ids: set[str],
|
||||
admitted: set[str],
|
||||
cancelled: set[str],
|
||||
) -> list[TraceRecord]:
|
||||
return [
|
||||
TraceRecord(
|
||||
@@ -35,6 +39,7 @@ def _records(
|
||||
trace=trace,
|
||||
sampled=trace.id in sampled_trace_ids,
|
||||
admitted=episode.id in admitted,
|
||||
cancelled=episode.id in cancelled,
|
||||
)
|
||||
for episode in episodes
|
||||
for trace in episode.traces
|
||||
@@ -202,6 +207,11 @@ class TraceMetrics(StatGroup):
|
||||
def has_error(self) -> Stat:
|
||||
return Stat([float(trace.has_error) for trace in self.traces])
|
||||
|
||||
@property
|
||||
def cancelled(self) -> Stat:
|
||||
"""Pipeline cancellations (stale drop) — disjoint from errors."""
|
||||
return Stat([float(record.cancelled) for record in self.records])
|
||||
|
||||
def stop_conditions(self) -> dict[str, float]:
|
||||
out = {
|
||||
"generation_truncated": sum(
|
||||
@@ -243,6 +253,7 @@ class TraceMetrics(StatGroup):
|
||||
out |= self.rewards.to_dict(f"{prefix}/rewards")
|
||||
if subset == "all":
|
||||
out[f"{prefix}/has_error/mean"] = self.has_error.mean()
|
||||
out[f"{prefix}/cancelled/mean"] = self.cancelled.mean()
|
||||
out |= {f"{prefix}/error/{key}": float(value) for key, value in self.error_types().items()}
|
||||
out |= {f"{prefix}/{key}": value for key, value in self.solve_rates().items()}
|
||||
out |= {f"{prefix}/stop_condition/{key}": value for key, value in self.stop_conditions().items()}
|
||||
@@ -250,9 +261,15 @@ class TraceMetrics(StatGroup):
|
||||
|
||||
|
||||
class EpisodeMetrics:
|
||||
def __init__(self, episodes: list[vf.Episode], records: list[TraceRecord]) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
episodes: list[vf.Episode],
|
||||
records: list[TraceRecord],
|
||||
cancelled: set[str] | None = None,
|
||||
) -> None:
|
||||
self.episodes = episodes
|
||||
self.records = records
|
||||
self.cancelled_ids = cancelled if cancelled is not None else set()
|
||||
|
||||
def by_agent(self) -> dict[str, TraceMetrics]:
|
||||
per_agent: dict[str, list[TraceRecord]] = {}
|
||||
@@ -296,6 +313,14 @@ class EpisodeMetrics:
|
||||
[float(not episode.ok or any(trace.has_error for trace in episode.traces)) for episode in self.episodes]
|
||||
)
|
||||
|
||||
@property
|
||||
def cancelled(self) -> Stat:
|
||||
"""Per-episode pipeline-cancellation rate — same denominator as
|
||||
``has_error``. Read from the id-set, not the trace records, so
|
||||
trace-less episodes (synthetic error episodes inside a voided group)
|
||||
still count."""
|
||||
return Stat([float(episode.id in self.cancelled_ids) for episode in self.episodes])
|
||||
|
||||
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
|
||||
if not self.episodes:
|
||||
return {}
|
||||
@@ -305,6 +330,7 @@ class EpisodeMetrics:
|
||||
out |= getattr(self, name).to_dict(f"{metric_prefix}/{name}")
|
||||
if subset == "all":
|
||||
out[f"{metric_prefix}/has_error/mean"] = self.has_error.mean()
|
||||
out[f"{metric_prefix}/cancelled/mean"] = self.cancelled.mean()
|
||||
for agent, metrics in self.by_agent().items():
|
||||
out |= metrics.to_dict(f"{metric_prefix}/{agent}", subset=subset)
|
||||
return out
|
||||
@@ -368,16 +394,18 @@ class EpisodeCollection:
|
||||
episodes: list[vf.Episode] | None = None,
|
||||
sampled_trace_ids: set[str] | None = None,
|
||||
admitted: set[str] | None = None,
|
||||
cancelled: set[str] | None = None,
|
||||
predicate: Callable[[TraceRecord], bool] | None = None,
|
||||
) -> None:
|
||||
self.episodes = episodes if episodes is not None else []
|
||||
self.sampled_trace_ids = sampled_trace_ids if sampled_trace_ids is not None else set()
|
||||
self.admitted = admitted if admitted is not None else {episode.id for episode in self.episodes}
|
||||
self.cancelled = cancelled if cancelled is not None else set()
|
||||
self._predicate = predicate
|
||||
|
||||
@property
|
||||
def records(self) -> list[TraceRecord]:
|
||||
records = _records(self.episodes, self.sampled_trace_ids, self.admitted)
|
||||
records = _records(self.episodes, self.sampled_trace_ids, self.admitted, self.cancelled)
|
||||
if self._predicate is None:
|
||||
return records
|
||||
return [record for record in records if self._predicate(record)]
|
||||
@@ -420,11 +448,14 @@ class EpisodeCollection:
|
||||
*,
|
||||
sampled_trace_ids: set[str] | None = None,
|
||||
admitted: bool = True,
|
||||
cancelled: bool = False,
|
||||
) -> None:
|
||||
self.episodes.append(episode)
|
||||
self.sampled_trace_ids.update(sampled_trace_ids or set())
|
||||
if admitted:
|
||||
self.admitted.add(episode.id)
|
||||
if cancelled:
|
||||
self.cancelled.add(episode.id)
|
||||
|
||||
def extend(
|
||||
self,
|
||||
@@ -432,11 +463,14 @@ class EpisodeCollection:
|
||||
*,
|
||||
sampled_trace_ids: set[str] | None = None,
|
||||
admitted: bool = True,
|
||||
cancelled: bool = False,
|
||||
) -> None:
|
||||
self.episodes.extend(episodes)
|
||||
self.sampled_trace_ids.update(sampled_trace_ids or set())
|
||||
if admitted:
|
||||
self.admitted.update(episode.id for episode in episodes)
|
||||
if cancelled:
|
||||
self.cancelled.update(episode.id for episode in episodes)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self.selected_episodes)
|
||||
@@ -452,8 +486,13 @@ class TrainEpisodes(EpisodeCollection):
|
||||
self.episodes,
|
||||
self.sampled_trace_ids,
|
||||
self.admitted,
|
||||
self.cancelled,
|
||||
predicate=lambda record: (
|
||||
record.admitted and record.sampled and not record.trace.has_error and record.trace.agent.trainable
|
||||
record.admitted
|
||||
and record.sampled
|
||||
and not record.cancelled
|
||||
and not record.trace.has_error
|
||||
and record.trace.agent.trainable
|
||||
),
|
||||
)
|
||||
|
||||
@@ -462,13 +501,13 @@ class TrainEpisodes(EpisodeCollection):
|
||||
for episode in self.selected_episodes:
|
||||
grouped.setdefault(episode_env_name(episode), []).append(episode)
|
||||
return {
|
||||
env_name: TrainEpisodes(episodes, self.sampled_trace_ids, self.admitted, self._predicate)
|
||||
env_name: TrainEpisodes(episodes, self.sampled_trace_ids, self.admitted, self.cancelled, self._predicate)
|
||||
for env_name, episodes in grouped.items()
|
||||
}
|
||||
|
||||
@property
|
||||
def metrics(self) -> TrainMetrics:
|
||||
return TrainMetrics(self.selected_episodes, self.records)
|
||||
return TrainMetrics(self.selected_episodes, self.records, self.cancelled)
|
||||
|
||||
|
||||
class EvalEpisodes(EpisodeCollection):
|
||||
|
||||
@@ -31,17 +31,22 @@ from modelexpress.client import MxClient
|
||||
from verifiers.v1.runtimes import set_base_sandbox_labels
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from renderers.base import Renderer
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.orchestrator.ckpt import CheckpointManager
|
||||
from prime_rl.transports.rollouts.base import MicroBatchSender
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.transports.batch.base import BatchSender
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.algo.routing import is_trainable
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
from prime_rl.orchestrator.clients import (
|
||||
AdminClients,
|
||||
InferenceClient,
|
||||
init_nccl_broadcast,
|
||||
init_nixl_broadcast,
|
||||
update_weights,
|
||||
)
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
@@ -59,26 +64,25 @@ from prime_rl.orchestrator.train_sink import TrainSink
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
EvalBatch,
|
||||
GroupCancellation,
|
||||
Policy,
|
||||
Progress,
|
||||
TrainBatch,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import (
|
||||
episode_group_id,
|
||||
episode_staleness,
|
||||
eval_work,
|
||||
get_weight_dir,
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
setup_policy_inference_pool,
|
||||
train_work,
|
||||
trim_process_memory,
|
||||
)
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.transports.rollouts import setup_micro_batch_sender
|
||||
from prime_rl.transports.batch import setup_batch_sender
|
||||
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.utils import (
|
||||
@@ -123,8 +127,9 @@ class Orchestrator:
|
||||
|
||||
# Always set by ``setup()``
|
||||
tokenizer: PreTrainedTokenizer
|
||||
policy_inference: InferencePool
|
||||
sender: MicroBatchSender | None
|
||||
clients: InferenceClient
|
||||
admin_clients: AdminClients
|
||||
sender: BatchSender | None
|
||||
packer: BatchPacker
|
||||
train_envs: TrainEnvs
|
||||
train_source: TrainSource
|
||||
@@ -136,8 +141,6 @@ class Orchestrator:
|
||||
periodic_logger: PeriodicLogger
|
||||
|
||||
# Set by ``setup()`` only when relevant config is present
|
||||
renderer: Renderer | None
|
||||
mm_token_type_ids_mapping: dict[int, int] | None
|
||||
heart: Heartbeat | None
|
||||
inference_metrics: InferenceMetricsCollector | None
|
||||
eval_envs: EvalEnvs | None
|
||||
@@ -153,8 +156,7 @@ class Orchestrator:
|
||||
# Route the in-process v1 library logging through our handler. The
|
||||
# env server runs in a child process, so its logging is separate.
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
algorithms = sorted({env.algo.type for env in config.train.source if env.algo is not None})
|
||||
get_logger().info(f"Starting orchestrator (algorithm: {', '.join(algorithms)})")
|
||||
get_logger().info("Starting orchestrator")
|
||||
|
||||
self.progress = Progress()
|
||||
self.ckpt_manager = setup_ckpt_manager(config.output_dir, config.ckpt)
|
||||
@@ -177,8 +179,6 @@ class Orchestrator:
|
||||
|
||||
# Optional attributes — ``setup()`` populates them when the relevant
|
||||
# config is present
|
||||
self.renderer = None
|
||||
self.mm_token_type_ids_mapping = None
|
||||
self.heart = None
|
||||
self.inference_metrics = None
|
||||
self.eval_envs = None
|
||||
@@ -198,24 +198,23 @@ class Orchestrator:
|
||||
set_default_executor()
|
||||
|
||||
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
t0 = time.perf_counter()
|
||||
self.tokenizer = setup_tokenizer(config.tokenizer)
|
||||
get_logger().debug(f"Initialized tokenizer in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
# The one model prime-rl hosts: the live policy. Frozen model
|
||||
# references are external endpoints — each env's Algorithm builds its
|
||||
# own pools in ``setup()`` below.
|
||||
get_logger().info(
|
||||
f"Initializing policy inference pool (base_url={config.model.client.base_url}, model={config.model.name})"
|
||||
get_logger().info(f"Initializing policy inference pool ({config.model})")
|
||||
self.clients = InferenceClient(
|
||||
config.model.client,
|
||||
model_name=config.model.name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
self.renderer, self.policy_inference = await setup_policy_inference_pool(
|
||||
config=config, tokenizer=self.tokenizer
|
||||
)
|
||||
self.mm_token_type_ids_mapping = (
|
||||
getattr(self.renderer, "mm_token_type_id_map", None) if self.renderer is not None else None
|
||||
)
|
||||
if self.mm_token_type_ids_mapping == {}:
|
||||
self.mm_token_type_ids_mapping = None
|
||||
self.admin_clients = AdminClients(config.model.client)
|
||||
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
wandb=config.monitors.wandb,
|
||||
prime=config.monitors.prime,
|
||||
@@ -236,25 +235,14 @@ class Orchestrator:
|
||||
if config.heartbeat is not None:
|
||||
self.heart = Heartbeat(config.heartbeat.url)
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(
|
||||
config.train.source,
|
||||
config.env_addresses,
|
||||
policy_pool=self.policy_inference,
|
||||
clients=self.clients,
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
get_logger().debug(
|
||||
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
|
||||
)
|
||||
await self.train_envs.start()
|
||||
get_logger().success("Train environment(s) ready")
|
||||
|
||||
if config.eval is not None:
|
||||
get_logger().info("Loading eval environment(s)")
|
||||
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses)
|
||||
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
|
||||
await self.eval_envs.start()
|
||||
get_logger().success("Eval environment(s) ready")
|
||||
|
||||
if config.resume is not None:
|
||||
if config.resume.dir is not None:
|
||||
@@ -265,11 +253,53 @@ class Orchestrator:
|
||||
self.resume_step = resolve_latest_ckpt_step(self.ckpt_manager.ckpt_dir)
|
||||
|
||||
# Resume below may bump ``policy.version`` and the LoRA model name
|
||||
self.policy.model_name = self.policy_inference.model_name
|
||||
self.policy.model_name = self.clients.model_name
|
||||
self.lora_name = config.model.lora.name if config.model.lora else None
|
||||
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
|
||||
# themselves are restored below, once the envs are loaded.
|
||||
if self.resume_step is not None:
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming from step {self.resume_step}")
|
||||
else:
|
||||
get_logger().info("Starting from scratch")
|
||||
|
||||
# Transports are local setup — initialize them before the env and inference waits.
|
||||
self.packer = BatchPacker(config)
|
||||
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_batch_sender(
|
||||
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
|
||||
)
|
||||
if config.weight_broadcast.type == "filesystem":
|
||||
# Nothing to set up client-side — the watcher polls the broadcast dir.
|
||||
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
|
||||
# Wait phase: envs, then inference, then the trainer's startup broadcast —
|
||||
# the last things before the main loop starts.
|
||||
get_logger().info(f"Loading train environments ({', '.join(self.train_envs.names)})")
|
||||
t0 = time.perf_counter()
|
||||
await self.train_envs.start()
|
||||
get_logger().success(f"Train environments ready in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
if self.eval_envs is not None:
|
||||
get_logger().info(f"Loading eval environments ({', '.join(self.eval_envs.names)})")
|
||||
t0 = time.perf_counter()
|
||||
await self.eval_envs.start()
|
||||
get_logger().success(f"Eval environments ready in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
self.train_source = TrainSource(self.train_envs)
|
||||
if self.resume_step is not None:
|
||||
resume = self.config.resume
|
||||
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
|
||||
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
|
||||
self.progress.step = self.resume_step + 1
|
||||
|
||||
get_logger().info("Waiting for policy inference pool to be ready")
|
||||
await self.policy_inference.wait_for_ready(config.model.name)
|
||||
get_logger().success("Policy inference pool ready")
|
||||
t0 = time.perf_counter()
|
||||
await self.admin_clients.wait_for_ready(config.model.name)
|
||||
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
|
||||
# Build + ready pools for each env's frozen generation source and the
|
||||
# algorithm's frozen reference model
|
||||
await asyncio.gather(
|
||||
@@ -277,61 +307,46 @@ class Orchestrator:
|
||||
*(env.algorithm.setup() for env in self.train_envs),
|
||||
)
|
||||
|
||||
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
if config.weight_broadcast.type == "nccl":
|
||||
await init_nccl_broadcast(
|
||||
self.policy_inference.admin_clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
inference_world_size=config.weight_broadcast.inference_world_size,
|
||||
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
elif config.weight_broadcast.type == "nixl":
|
||||
await init_nixl_broadcast(
|
||||
self.policy_inference.admin_clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
config.weight_broadcast.inference_world_size,
|
||||
config.weight_broadcast.session_id,
|
||||
)
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
|
||||
role="orchestrator",
|
||||
rank=0,
|
||||
session_id=config.weight_broadcast.session_id,
|
||||
worker_id="orchestrator",
|
||||
)
|
||||
self.model_express.publish()
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
|
||||
self.lora_name = config.model.lora.name if config.model.lora else None
|
||||
|
||||
self.train_source = TrainSource(self.train_envs)
|
||||
|
||||
if self.resume_step is not None:
|
||||
resume = self.config.resume
|
||||
resume_path = resume.dir / "orchestrator" if resume is not None and resume.dir is not None else None
|
||||
self.ckpt_manager.load(self.progress, self.train_source, step=self.resume_step, path=resume_path)
|
||||
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
|
||||
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
|
||||
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
|
||||
self.progress.step = self.resume_step + 1
|
||||
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
|
||||
else:
|
||||
get_logger().info("Training from scratch")
|
||||
|
||||
self.packer = BatchPacker(config)
|
||||
get_logger().info(f"Initializing micro batch sender ({config.rollout_transport})")
|
||||
self.sender = setup_micro_batch_sender(
|
||||
config.output_dir, config.num_train_workers, self.progress.step, config.rollout_transport
|
||||
)
|
||||
# The in-memory broadcast transports rendezvous with live inference
|
||||
# engines, so their setup must follow pool readiness.
|
||||
if config.weight_broadcast.type in ("nccl", "nixl"):
|
||||
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
t0 = time.perf_counter()
|
||||
if config.weight_broadcast.type == "nccl":
|
||||
await init_nccl_broadcast(
|
||||
self.admin_clients.clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
inference_world_size=config.weight_broadcast.inference_world_size,
|
||||
quantize_in_weight_transfer=config.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
else:
|
||||
await init_nixl_broadcast(
|
||||
self.admin_clients.clients,
|
||||
config.weight_broadcast.host,
|
||||
config.weight_broadcast.port,
|
||||
config.weight_broadcast.timeout,
|
||||
config.weight_broadcast.inference_world_size,
|
||||
config.weight_broadcast.session_id,
|
||||
)
|
||||
self.model_express = ModelExpressSession(
|
||||
client=MxClient(server_url=f"{config.weight_broadcast.host}:{config.weight_broadcast.port}"),
|
||||
role="orchestrator",
|
||||
rank=0,
|
||||
session_id=config.weight_broadcast.session_id,
|
||||
worker_id="orchestrator",
|
||||
)
|
||||
self.model_express.publish()
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
get_logger().debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
# Sync inference to the incoming policy before the first step, rendezvousing
|
||||
# with the trainer's startup broadcast (v{resume_step} on resume, v0 from
|
||||
# scratch).
|
||||
sync_version = self.resume_step if self.resume_step is not None else 0
|
||||
get_logger().info(f"Syncing inference to the trainer's startup broadcast (v{sync_version})")
|
||||
t0 = time.perf_counter()
|
||||
if config.weight_broadcast.type == "nixl":
|
||||
weights_path = None
|
||||
else:
|
||||
@@ -346,7 +361,7 @@ class Orchestrator:
|
||||
)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
|
||||
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
await update_weights(self.admin_clients.clients, weights_path, lora_name=self.lora_name, step=sync_version)
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
# Complete the startup rendezvous before the watcher begins its next cycle.
|
||||
@@ -358,9 +373,10 @@ class Orchestrator:
|
||||
timeout=config.weight_broadcast.timeout,
|
||||
)
|
||||
if self.lora_name is not None:
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.clients.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
get_logger().debug(f"Synced inference to policy v{sync_version} in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -381,7 +397,7 @@ class Orchestrator:
|
||||
eval_envs=self.eval_envs,
|
||||
train_source=self.train_source,
|
||||
eval_source=self.eval_source,
|
||||
policy_pool=self.policy_inference,
|
||||
policy_clients=self.clients,
|
||||
policy=self.policy,
|
||||
progress=self.progress,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
@@ -401,17 +417,20 @@ class Orchestrator:
|
||||
# W&B mirroring is gated on the registered monitor (the collector logs
|
||||
# to the global W&B session, which only exists when init succeeded).
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.policy_inference.admin_clients,
|
||||
self.admin_clients.clients,
|
||||
roles=config.inference_metrics_roles,
|
||||
on_load=self.concurrency.observe,
|
||||
log_to_wandb=wandb_enabled and config.collect_inference_metrics,
|
||||
)
|
||||
await self.inference_metrics.start()
|
||||
# One awaited scrape so the concurrency controller derives (and logs) its
|
||||
# initial limit before the loop-start line; failures are tolerated.
|
||||
await self.inference_metrics.probe()
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
train_envs=self.train_envs,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
progress=self.progress,
|
||||
batch_size=config.batch_size,
|
||||
token_batch_size=config.token_batch_size,
|
||||
on_result=self.train_source.on_result,
|
||||
@@ -421,7 +440,8 @@ class Orchestrator:
|
||||
self.watcher = WeightWatcher(
|
||||
config,
|
||||
policy=self.policy,
|
||||
inference=self.policy_inference,
|
||||
clients=self.clients,
|
||||
admin_clients=self.admin_clients,
|
||||
observers=[self.dispatcher, self],
|
||||
lora_name=self.lora_name,
|
||||
ckpt_step=self.policy.version,
|
||||
@@ -453,13 +473,6 @@ class Orchestrator:
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
def off_policy_steps(self, episode: vf.Episode, training_step: int) -> int:
|
||||
"""Policy updates between generation and the batch that trains on it."""
|
||||
work = train_work(episode)
|
||||
if work.policy is None:
|
||||
return 0
|
||||
return max(0, (training_step - 1) - work.policy.start)
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Run the orchestrator until shutdown. Drives setup, spawns the
|
||||
background tasks, runs the main loop in this task, then cleans up."""
|
||||
@@ -496,6 +509,7 @@ class Orchestrator:
|
||||
clean_exit = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
await self.wait_for_final_broadcast()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
@@ -515,19 +529,53 @@ class Orchestrator:
|
||||
# first ship).
|
||||
if self.config.ckpt is not None and self.progress.step > 1:
|
||||
self.progress.step -= 1
|
||||
get_logger().info("Writing final checkpoint")
|
||||
get_logger().info(f"Saving final checkpoint at step {self.progress.step}")
|
||||
self.ckpt_manager.save(self.progress, self.train_source, step=self.progress.step)
|
||||
await self.stop()
|
||||
if clean_exit:
|
||||
get_logger().success("Orchestrator finished.")
|
||||
get_logger().success("Orchestrator finished")
|
||||
else:
|
||||
get_logger().warning("Orchestrator cleanup complete (forced).")
|
||||
get_logger().warning("Orchestrator cleanup complete (forced)")
|
||||
trim_process_memory()
|
||||
|
||||
async def wait_for_final_broadcast(self) -> None:
|
||||
"""Stay alive for the trainer's last in-memory broadcast (v{max_steps-1};
|
||||
nothing samples from v{max_steps}, so it is never sent). An in-memory
|
||||
broadcast is a blocking collective — tearing down the watcher before
|
||||
the rendezvous would strand the trainer inside it."""
|
||||
config = self.config
|
||||
if config.weight_broadcast.type not in ("nccl", "nixl") or config.max_steps is None:
|
||||
return
|
||||
final_version = config.max_steps - 1
|
||||
if self.policy.version >= final_version:
|
||||
return
|
||||
get_logger().info(f"Waiting for the trainer's final broadcast (v{final_version}) before shutdown")
|
||||
|
||||
async def wait() -> None:
|
||||
while self.policy.version < final_version:
|
||||
self.version_advanced.clear()
|
||||
if self.policy.version >= final_version:
|
||||
return
|
||||
# A dead watcher can never deliver the broadcast — fail out
|
||||
# instead of idling until the timeout.
|
||||
self._raise_if_component_stopped()
|
||||
try:
|
||||
await asyncio.wait_for(self.version_advanced.wait(), timeout=5)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(wait(), timeout=config.weight_broadcast.timeout)
|
||||
except asyncio.TimeoutError:
|
||||
get_logger().warning(
|
||||
f"Trainer did not broadcast v{final_version} within {config.weight_broadcast.timeout}s — "
|
||||
"shutting down anyway"
|
||||
)
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume completed episodes from the dispatcher and route them
|
||||
to the train / eval sink. Both sinks return a finalized batch (or
|
||||
``None``) from ``add()``; we just dispatch on the result."""
|
||||
"""Consume completed episodes and ``GroupCancellation`` events from the
|
||||
dispatcher and route them to the train / eval sink. The sinks return a
|
||||
finalized batch (or ``None``); we just dispatch on the result."""
|
||||
while not self.stopped.is_set():
|
||||
self._raise_if_component_stopped()
|
||||
if self.draining and self.dispatcher.is_idle:
|
||||
@@ -536,11 +584,19 @@ class Orchestrator:
|
||||
break
|
||||
|
||||
try:
|
||||
episode = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
except asyncio.TimeoutError:
|
||||
self._raise_if_component_stopped()
|
||||
continue
|
||||
|
||||
if isinstance(item, GroupCancellation):
|
||||
assert item.kind == "train" # eval groups are never dropped
|
||||
train_batch = await self.train_sink.cancel(item)
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
continue
|
||||
episode = item
|
||||
|
||||
# Every completed rollout — errored, rejected, or never batched — lands in the
|
||||
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
|
||||
# Train rollouts belong to the batch window currently collecting (``progress.step``),
|
||||
@@ -593,14 +649,10 @@ class Orchestrator:
|
||||
step_time = (now - self.last_batch_at) if self.last_batch_at is not None else 0.0
|
||||
self.last_batch_at = now
|
||||
|
||||
# A resume can start past the end (checkpoint written at the final
|
||||
# step, or a lowered ``max_steps``): never ship beyond the budget.
|
||||
if config.max_steps is not None and step > config.max_steps:
|
||||
self.draining = True
|
||||
self.dispatcher.disable_train_scheduling()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_episodes()
|
||||
get_logger().info(
|
||||
f"Draining pipeline (cancelled {n_cancelled} in-flight train rollout(s); "
|
||||
f"any in-flight evals will complete)"
|
||||
)
|
||||
await self.start_draining(f"Step {step} exceeds max_steps={config.max_steps}")
|
||||
return
|
||||
|
||||
if not batch.samples:
|
||||
@@ -626,11 +678,11 @@ class Orchestrator:
|
||||
)
|
||||
|
||||
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
|
||||
# Without this, fast envs fill batches from buffered rollouts, the
|
||||
# orchestrator finishes early, and its teardown strands the trainer inside
|
||||
# an in-memory broadcast handshake that needs the live weight watcher.
|
||||
# Always satisfiable: the trainer skips only the final TARGET_LAG+1
|
||||
# in-memory broadcasts.
|
||||
# Without this, fast envs fill batches from buffered rollouts and the
|
||||
# orchestrator races arbitrarily far ahead of the trainer. Always
|
||||
# satisfiable: the trainer broadcasts every version except v{max_steps},
|
||||
# and ``wait_for_final_broadcast`` keeps the watcher alive through the
|
||||
# last rendezvous after the pipeline drains.
|
||||
required_version = step - 1 - TARGET_LAG
|
||||
if self.policy.version < required_version:
|
||||
get_logger().info(
|
||||
@@ -691,6 +743,22 @@ class Orchestrator:
|
||||
"time/wait_for_policy": self.wait_for_policy_time,
|
||||
"step": step,
|
||||
}
|
||||
# Staleness of the shipped cohort, decomposed into its in-flight and
|
||||
# in-queue shares; ``dropped`` counts queued traces the sink voided
|
||||
# since the last ship.
|
||||
staleness = [episode_staleness(episode, step) for episode in effective]
|
||||
if staleness:
|
||||
totals, in_flight, in_queue = (list(values) for values in zip(*staleness))
|
||||
metrics |= {
|
||||
"off_policy/mean": sum(totals) / len(totals),
|
||||
"off_policy/max": float(max(totals)),
|
||||
"off_policy/in_flight/mean": sum(in_flight) / len(in_flight),
|
||||
"off_policy/in_flight/max": float(max(in_flight)),
|
||||
"off_policy/in_queue/mean": sum(in_queue) / len(in_queue),
|
||||
"off_policy/in_queue/max": float(max(in_queue)),
|
||||
}
|
||||
metrics["off_policy/dropped"] = float(self.train_sink.stale_drops)
|
||||
self.train_sink.stale_drops = 0
|
||||
for env_name, env_pool in batch.episodes.by_env().items():
|
||||
metrics[f"batch/{env_name}"] = env_pool.num_traces / batch.episodes.num_traces
|
||||
metrics |= self.train_source.metrics()
|
||||
@@ -707,8 +775,25 @@ class Orchestrator:
|
||||
self.log_train_batch(batch, step=step, step_time=step_time)
|
||||
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
# Drain right after shipping the final batch. Waiting for a further
|
||||
# batch to fill would burn inference on data that can never train —
|
||||
# and with a tight ``max_off_policy_steps`` it never fills at all (the
|
||||
# versions it would need are never broadcast).
|
||||
if config.max_steps is not None and step >= config.max_steps:
|
||||
await self.start_draining("Shipped the final batch")
|
||||
trim_process_memory()
|
||||
|
||||
async def start_draining(self, reason: str) -> None:
|
||||
"""Stop scheduling train work and let the pipeline empty; triggered
|
||||
eval epochs still run to completion."""
|
||||
self.draining = True
|
||||
self.dispatcher.disable_train_scheduling()
|
||||
n_cancelled = await self.dispatcher.cancel_inflight_train_episodes()
|
||||
get_logger().info(
|
||||
f"{reason} — draining pipeline (cancelled {n_cancelled} in-flight "
|
||||
f"train episode(s); any in-flight evals will complete)"
|
||||
)
|
||||
|
||||
def maybe_trigger_eval(self, step: int) -> None:
|
||||
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
|
||||
fires. No-op when eval is not configured."""
|
||||
@@ -794,8 +879,12 @@ class Orchestrator:
|
||||
|
||||
def log_train_batch(self, batch: TrainBatch, *, step: int, step_time: float) -> None:
|
||||
"""Per-step ``Step …`` success line. Multi-env runs append an indented ``╰─`` line per env.
|
||||
``Error`` is the sink-level rate (errored arrivals / total arrivals, over the full window);
|
||||
the quality metrics are over the effective (clean, trained-on) subset, as is ``Trainable``."""
|
||||
Every quality metric (Reward, Trainable, Turns, Branches, Max Off-Policy, Truncation) is
|
||||
computed over exactly the traces shipped to the trainer this step (``batch.cohort``).
|
||||
``Error``, ``Cancelled``, and ``Ratio`` are rates over the step's full arrival window —
|
||||
over the shipped set they are 0/0/share-of-shipped by construction, so the window is the
|
||||
only scope where they carry signal (and they stay disjoint: a cancellation is a pipeline
|
||||
decision, not a rollout failure)."""
|
||||
episodes = batch.episodes
|
||||
effective = batch.cohort.effective
|
||||
eff = effective.metrics
|
||||
@@ -803,14 +892,15 @@ class Orchestrator:
|
||||
n_effective = effective.num_traces
|
||||
n_trainable = sum(is_trainable(record.trace) for record in effective.records)
|
||||
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
|
||||
max_off_policy = max((self.off_policy_steps(episode, step) for episode in effective), default=0)
|
||||
max_off_policy_steps = max((episode_staleness(episode, step)[0] for episode in effective), default=0)
|
||||
|
||||
head = (
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Trainable {n_trainable}/{n_effective} ({trainable_rate:.1%}) | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max_off_policy} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
f"Max Off-Policy {max_off_policy_steps} | "
|
||||
f"Error {episodes.metrics.has_error.mean():.1%} | Cancelled {episodes.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
get_logger().success(head)
|
||||
@@ -829,8 +919,9 @@ class Orchestrator:
|
||||
lines.append(
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_eff.reward.mean():.4f} | "
|
||||
f"Turns {env_eff.num_turns.mean():.1f} | Branches {env_eff.num_branches.mean():.1f} | "
|
||||
f"Max Off-Policy {max((self.off_policy_steps(episode, step) for episode in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
f"Max Off-Policy {max((episode_staleness(episode, step)[0] for episode in env_eff_pool), default=0)} | "
|
||||
f"Error {pool.metrics.has_error.mean():.1%} | Cancelled {pool.metrics.cancelled.mean():.1%} | "
|
||||
f"Truncation {env_eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
|
||||
@@ -902,25 +993,19 @@ class Orchestrator:
|
||||
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
|
||||
count is ``progress.step - 1``."""
|
||||
lead = (self.progress.step - 1) - self.policy.version
|
||||
# The trainer skips the final in-memory weight broadcasts, so policy.version never
|
||||
# reaches the last step. Let the final batch through instead of waiting for it.
|
||||
building_final_batch_without_update = (
|
||||
self.config.weight_broadcast.type in ("nccl", "nixl")
|
||||
and self.config.max_steps is not None
|
||||
and self.progress.step >= self.config.max_steps - 1
|
||||
)
|
||||
gate = self.dispatcher.dispatch_allowed
|
||||
was_set = gate.is_set()
|
||||
if lead > TARGET_LAG and not building_final_batch_without_update:
|
||||
if lead > TARGET_LAG:
|
||||
if was_set:
|
||||
get_logger().info(
|
||||
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
|
||||
f"Pausing dispatcher until the trainer publishes policy v{self.progress.step - 1 - TARGET_LAG} "
|
||||
f"(currently v{self.policy.version})"
|
||||
)
|
||||
self.gate_closed_at = time.perf_counter()
|
||||
gate.clear()
|
||||
else:
|
||||
if not was_set:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
get_logger().info(f"Resuming dispatcher (policy v{self.policy.version})")
|
||||
if self.gate_closed_at is not None:
|
||||
self.wait_for_policy_time += time.perf_counter() - self.gate_closed_at
|
||||
self.gate_closed_at = None
|
||||
@@ -946,10 +1031,13 @@ class Orchestrator:
|
||||
training artifacts are already persisted before this is reached."""
|
||||
|
||||
async def teardown() -> None:
|
||||
get_logger().debug("Closing micro batch sender")
|
||||
self.sender.close()
|
||||
if self.dispatcher is not None:
|
||||
get_logger().debug("Stopping dispatcher")
|
||||
await self.dispatcher.stop()
|
||||
if self.watcher is not None:
|
||||
get_logger().debug("Stopping weight watcher")
|
||||
await self.watcher.stop()
|
||||
if self.periodic_logger is not None:
|
||||
await self.periodic_logger.stop()
|
||||
@@ -960,14 +1048,21 @@ class Orchestrator:
|
||||
await safe_cancel(task)
|
||||
self.component_tasks.clear()
|
||||
if self.inference_metrics is not None:
|
||||
get_logger().debug("Stopping inference metrics collector")
|
||||
await self.inference_metrics.stop()
|
||||
if getattr(self, "policy_inference", None) is not None:
|
||||
await self.policy_inference.stop()
|
||||
if getattr(self, "clients", None) is not None:
|
||||
await self.clients.aclose()
|
||||
if getattr(self, "admin_clients", None) is not None:
|
||||
await self.admin_clients.aclose()
|
||||
if self.train_envs is not None:
|
||||
get_logger().debug("Stopping generation source and algorithm clients")
|
||||
for env in self.train_envs:
|
||||
for pool in (*env.generation_source.connected_pools, *env.algorithm.connected_pools):
|
||||
await pool.stop()
|
||||
for clients in (env.generation_source.connected, env.algorithm.connected):
|
||||
if clients is not None:
|
||||
await clients.aclose()
|
||||
|
||||
get_logger().info("Stopping orchestrator components")
|
||||
t0 = time.perf_counter()
|
||||
task = asyncio.create_task(teardown())
|
||||
_, pending = await asyncio.wait({task}, timeout=SHUTDOWN_TIMEOUT_S)
|
||||
if pending:
|
||||
@@ -977,6 +1072,7 @@ class Orchestrator:
|
||||
)
|
||||
os._exit(0)
|
||||
await task
|
||||
get_logger().debug(f"Stopped orchestrator components in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
|
||||
@clean_exit
|
||||
|
||||
@@ -2,7 +2,7 @@ from transformers import AutoConfig
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
|
||||
from prime_rl.transports.rollouts.types import MicroBatch, TrainingSample
|
||||
from prime_rl.transports.batch.types import MicroBatch, TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
"""Training-side episode, group, and batch assembly."""
|
||||
"""Training-side episode, group, and batch assembly.
|
||||
|
||||
``add()`` takes one completed episode and ``cancel()`` a dropped group's
|
||||
``GroupCancellation``; both return ``TrainBatch | None``. Before every readiness
|
||||
check the sink sweeps ``pending_batch`` for traces past ``max_off_policy_steps`` —
|
||||
this sweep, not the dispatcher's in-flight cancel, is what guarantees nothing
|
||||
stale ships."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import defaultdict
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
@@ -14,9 +20,9 @@ from prime_rl.orchestrator.algo.routing import stamp_loss_routing
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.metrics import TrainEpisodes
|
||||
from prime_rl.orchestrator.trajectories import trace_to_samples
|
||||
from prime_rl.orchestrator.types import TrainBatch
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.orchestrator.types import GroupCancellation, Progress, TrainBatch
|
||||
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, min_fresh_version, train_work
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS = 10
|
||||
@@ -64,7 +70,7 @@ class TrainSink:
|
||||
*,
|
||||
tokenizer,
|
||||
train_envs: TrainEnvs,
|
||||
mm_token_type_ids_mapping: dict[int, int] | None,
|
||||
progress: Progress,
|
||||
batch_size: int | None,
|
||||
token_batch_size: int | None,
|
||||
on_result: Callable[[list[vf.Episode]], bool] | None = None,
|
||||
@@ -75,16 +81,25 @@ class TrainSink:
|
||||
self.config = config
|
||||
self.tokenizer = tokenizer
|
||||
self.train_envs = train_envs
|
||||
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
|
||||
self.progress = progress
|
||||
self.batch_size = batch_size
|
||||
self.token_batch_size = token_batch_size
|
||||
self.on_result = on_result
|
||||
|
||||
self.pending_episodes = TrainEpisodes()
|
||||
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
|
||||
# A dropped group's terminal marker; its ``count`` fills in for the
|
||||
# episodes the group will never deliver.
|
||||
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
|
||||
self.pending_batch: dict[str, list[TrainingSample]] = {}
|
||||
self.episode_by_trace: dict[str, vf.Episode] = {}
|
||||
self.pending_tokens = 0
|
||||
# Queued traces voided by the staleness sweep since the last ship;
|
||||
# read and reset by the orchestrator's per-step metrics.
|
||||
self.stale_drops = 0
|
||||
# Step of the last full staleness sweep — queued traces only age when
|
||||
# ``progress.step`` advances, so one full sweep per step suffices.
|
||||
self._swept_step = 0
|
||||
self.zero_output_units = 0
|
||||
self.reported_zero_output_windows = 0
|
||||
|
||||
@@ -112,12 +127,33 @@ class TrainSink:
|
||||
await self.process_episode(episode)
|
||||
group_id = episode_group_id(episode)
|
||||
env_name = episode_env_name(episode)
|
||||
group = self.pending_groups[group_id]
|
||||
group.append(episode)
|
||||
if len(group) < self.group_size_for(env_name):
|
||||
self.pending_groups[group_id].append(episode)
|
||||
if not self._group_complete(group_id, env_name):
|
||||
return None
|
||||
|
||||
await self.process_group(group_id)
|
||||
return self._maybe_batch()
|
||||
|
||||
async def cancel(self, cancellation: GroupCancellation) -> TrainBatch | None:
|
||||
"""Process a dropped group's terminal marker: its ``count`` completes
|
||||
the group's episode accounting so finalization still fires. A
|
||||
``stale`` drop also voids the group's already-arrived episodes in
|
||||
``process_group`` — they share the group's dispatch version, so they
|
||||
are equally stale."""
|
||||
self.pending_group_cancellations[cancellation.group_id] = cancellation
|
||||
if not self._group_complete(cancellation.group_id, cancellation.env_name):
|
||||
return None
|
||||
await self.process_group(cancellation.group_id)
|
||||
return self._maybe_batch()
|
||||
|
||||
def _group_complete(self, group_id: str, env_name: str) -> bool:
|
||||
cancellation = self.pending_group_cancellations.get(group_id)
|
||||
cancelled = cancellation.count if cancellation is not None else 0
|
||||
return len(self.pending_groups[group_id]) + cancelled >= self.group_size_for(env_name)
|
||||
|
||||
def _maybe_batch(self) -> TrainBatch | None:
|
||||
"""Sweep stale queued traces, then cut a batch if the survivors still
|
||||
meet the threshold."""
|
||||
self._drop_stale()
|
||||
ready = (
|
||||
len(self.pending_batch) >= self.batch_size
|
||||
if self.batch_size is not None
|
||||
@@ -125,6 +161,47 @@ class TrainSink:
|
||||
)
|
||||
return self.process_batch() if ready else None
|
||||
|
||||
def _drop_stale(self, trace_ids: Iterable[str] | None = None) -> None:
|
||||
"""Void queued traces past ``max_off_policy_steps``. The batch being
|
||||
collected is ``progress.step`` and trains policy v{step-1}, so a
|
||||
queued trace generated from v{k} would ship at staleness
|
||||
``(step-1) - k``. This sweep is the hard guarantee on trained
|
||||
staleness; the dispatcher's in-flight cancel only saves compute.
|
||||
Queued traces only age when ``progress.step`` advances, so the full
|
||||
sweep runs once per step; ``trace_ids`` scopes the check to a freshly
|
||||
inserted group, whose traces may already be stale on arrival.
|
||||
Frozen-sourced episodes (no policy span) never go stale.
|
||||
|
||||
A swept trace whose window already shipped is visible only in
|
||||
``stale_drops`` — its episode was reported with that window, and
|
||||
re-observing it would double-count its stats."""
|
||||
if trace_ids is None:
|
||||
if self._swept_step == self.progress.step:
|
||||
return
|
||||
self._swept_step = self.progress.step
|
||||
trace_ids = list(self.pending_batch)
|
||||
min_version = min_fresh_version(self.progress.step, self.config.max_off_policy_steps)
|
||||
if min_version <= 0:
|
||||
return
|
||||
dropped = 0
|
||||
for trace_id in trace_ids:
|
||||
episode = self.episode_by_trace[trace_id]
|
||||
policy = train_work(episode).policy
|
||||
if policy is None or policy.start >= min_version:
|
||||
continue
|
||||
samples = self.pending_batch.pop(trace_id)
|
||||
if self.token_batch_size is not None:
|
||||
self.pending_tokens -= payload_tokens(samples, self._trace(trace_id))
|
||||
del self.episode_by_trace[trace_id]
|
||||
self.pending_episodes.cancelled.add(episode.id)
|
||||
dropped += 1
|
||||
if dropped:
|
||||
self.stale_drops += dropped
|
||||
get_logger().warning(
|
||||
f"Dropped {dropped} queued traces past max_off_policy_steps={self.config.max_off_policy_steps}. "
|
||||
"Consider increasing it to avoid this."
|
||||
)
|
||||
|
||||
async def process_episode(self, episode: vf.Episode) -> None:
|
||||
"""Run rollout-local algorithm work on one native episode."""
|
||||
env_name = episode_env_name(episode)
|
||||
@@ -132,40 +209,50 @@ class TrainSink:
|
||||
|
||||
async def process_group(self, group_id: str) -> None:
|
||||
group = self.pending_groups.pop(group_id, [])
|
||||
if not group:
|
||||
cancellation = self.pending_group_cancellations.pop(group_id, None)
|
||||
if not group and cancellation is None:
|
||||
return
|
||||
|
||||
env_name = episode_env_name(group[0])
|
||||
env_name = episode_env_name(group[0]) if group else cancellation.env_name
|
||||
env = self.train_envs.get(env_name)
|
||||
traces = [trace for episode in group for trace in episode.traces]
|
||||
survivors = [trace for _, trace in iter_trainable_traces(group)]
|
||||
task_idx = next((trace.task.data.idx for trace in traces), None)
|
||||
num_errored = sum(trace.has_error for trace in traces) + sum(
|
||||
not episode.ok for episode in group if not episode.traces
|
||||
)
|
||||
n_owed = len(group) + (cancellation.count if cancellation is not None else 0)
|
||||
|
||||
# A stale drop voids the whole group: every member shares the dispatch
|
||||
# version, so the arrived episodes are exactly as stale as the
|
||||
# cancelled tail. Stale groups bypass the curriculum — a pipeline
|
||||
# decision is not a task result.
|
||||
if cancellation is not None and cancellation.reason == "stale":
|
||||
self.pending_episodes.extend(group, admitted=False, cancelled=True)
|
||||
self._record_zero_output(group, [], n_owed)
|
||||
get_logger().debug(
|
||||
f"Dropped group | env={env_name} task_idx={task_idx} | "
|
||||
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reason=cancelled (stale)"
|
||||
)
|
||||
return
|
||||
|
||||
survivors = [trace for _, trace in iter_trainable_traces(group)]
|
||||
if survivors:
|
||||
await env.algorithm.finalize_group(group)
|
||||
admitted = self._admit(group)
|
||||
admitted = self._admit(group) if group else False
|
||||
if not survivors or not admitted:
|
||||
self.pending_episodes.extend(group, admitted=admitted)
|
||||
self._record_zero_output(group, survivors)
|
||||
self._record_zero_output(group, survivors, n_owed)
|
||||
reason = "no trainable survivors" if not survivors else "rejected by curriculum"
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | dropped: {reason}"
|
||||
f"Dropped group | env={env_name} task_idx={task_idx} | "
|
||||
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reason={reason}"
|
||||
)
|
||||
return
|
||||
|
||||
samples_by_trace: dict[str, list[TrainingSample]] = {}
|
||||
temperature = env.sampling_args["temperature"]
|
||||
for trace in survivors:
|
||||
samples = await asyncio.to_thread(
|
||||
trace_to_samples,
|
||||
trace,
|
||||
env_name=env_name,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
)
|
||||
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
|
||||
for sample in samples:
|
||||
sample.temperatures = [temperature] * len(sample.token_ids)
|
||||
stamp_loss_routing(sample, env.algorithm.action_loss_type)
|
||||
@@ -174,7 +261,7 @@ class TrainSink:
|
||||
|
||||
self.pending_episodes.extend(group, sampled_trace_ids=set(samples_by_trace), admitted=True)
|
||||
if not samples_by_trace:
|
||||
self._record_zero_output(group, survivors)
|
||||
self._record_zero_output(group, survivors, n_owed)
|
||||
return
|
||||
|
||||
self.pending_batch.update(samples_by_trace)
|
||||
@@ -186,16 +273,18 @@ class TrainSink:
|
||||
self.pending_tokens += sum(
|
||||
payload_tokens(samples, self._trace(trace_id)) for trace_id, samples in samples_by_trace.items()
|
||||
)
|
||||
self._drop_stale(samples_by_trace)
|
||||
# A group's traces share one dispatch version, so the insertion sweep
|
||||
# voids all or none of them. A fully-voided group shipped nothing —
|
||||
# advance the zero-output budget instead of resetting it, or a stalled
|
||||
# trainer plus a tight bound could void groups forever without ever
|
||||
# tripping the abort.
|
||||
if not any(trace_id in self.pending_batch for trace_id in samples_by_trace):
|
||||
self._record_zero_output(group, [], n_owed)
|
||||
return
|
||||
self.zero_output_units = 0
|
||||
self.reported_zero_output_windows = 0
|
||||
|
||||
rewards = [trace.reward for trace in survivors if trace.id in samples_by_trace]
|
||||
avg_reward = sum(rewards) / len(rewards)
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"episodes={len(group)} traces={len(traces)} (errored={num_errored}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
def _trace(self, trace_id: str) -> vf.Trace:
|
||||
episode = self.episode_by_trace[trace_id]
|
||||
return next(trace for trace in episode.traces if trace.id == trace_id)
|
||||
@@ -203,14 +292,17 @@ class TrainSink:
|
||||
def _admit(self, group: list[vf.Episode]) -> bool:
|
||||
return self.on_result(group) if self.on_result is not None else True
|
||||
|
||||
def _record_zero_output(self, group: list[vf.Episode], survivors: list[vf.Trace]) -> None:
|
||||
def _record_zero_output(self, group: list[vf.Episode], survivors: list[vf.Trace], n_owed: int) -> None:
|
||||
"""``n_owed`` counts the group's full episode budget (arrived +
|
||||
cancelled), so dropped groups advance the zero-output budget at the
|
||||
same rate as fully-delivered ones."""
|
||||
if self.batch_size is not None:
|
||||
returned_traces = sum(len(episode.traces) for episode in group)
|
||||
self.zero_output_units += len(survivors) or returned_traces or len(group)
|
||||
self.zero_output_units += len(survivors) or returned_traces or n_owed
|
||||
else:
|
||||
survivor_tokens = sum(trace.num_total_tokens for trace in survivors)
|
||||
episode_tokens = sum(episode.num_total_tokens for episode in group)
|
||||
self.zero_output_units += survivor_tokens or episode_tokens or self.config.seq_len * len(group)
|
||||
self.zero_output_units += survivor_tokens or episode_tokens or self.config.seq_len * n_owed
|
||||
self._check_zero_output_budget()
|
||||
|
||||
def _check_zero_output_budget(self) -> None:
|
||||
@@ -228,7 +320,7 @@ class TrainSink:
|
||||
if windows >= MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS:
|
||||
raise RuntimeError(
|
||||
f"{windows} consecutive zero-output batch equivalents — "
|
||||
"check the curriculum admission policy and task difficulty."
|
||||
"check the curriculum admission policy, task difficulty, and staleness drops."
|
||||
)
|
||||
|
||||
def process_batch(self) -> TrainBatch:
|
||||
|
||||
@@ -10,6 +10,7 @@ import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.curriculum import Curriculum
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.types import TaskRequest
|
||||
from prime_rl.orchestrator.utils import episode_env_name
|
||||
|
||||
|
||||
@@ -34,12 +35,9 @@ class TrainSource:
|
||||
self._admitted: dict[str, int] = defaultdict(int)
|
||||
self._rejected: dict[str, int] = defaultdict(int)
|
||||
|
||||
def next_example(self) -> dict[str, Any]:
|
||||
def next_task(self, *, step: int) -> TaskRequest:
|
||||
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
|
||||
return {
|
||||
"env_name": env_name,
|
||||
"task": next(self.curricula[env_name].sampler),
|
||||
}
|
||||
return TaskRequest(env_name=env_name, task=next(self.curricula[env_name].sampler), step=step)
|
||||
|
||||
def on_result(self, group: list[vf.Episode]) -> bool:
|
||||
"""Report a finalized group and return whether it should train."""
|
||||
|
||||
@@ -20,8 +20,8 @@ from collections.abc import Iterator
|
||||
import numpy as np
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.transports.rollouts.types import EncodedTensor, RoutedExperts
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -108,12 +108,7 @@ def _loss_weights(branch: vf.Branch, name: str, trained_nodes: set[int]) -> list
|
||||
return weights if any(weights) else None
|
||||
|
||||
|
||||
def trace_to_samples(
|
||||
trace: vf.Trace,
|
||||
*,
|
||||
env_name: str = "",
|
||||
mm_token_type_ids_mapping: dict[int, int] | None = None,
|
||||
) -> list[TrainingSample]:
|
||||
def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSample]:
|
||||
"""Convert a v1 `Trace` into `TrainingSample`s — one per branch.
|
||||
|
||||
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
|
||||
@@ -121,21 +116,18 @@ def trace_to_samples(
|
||||
the trainable (model-sampled) tokens, the context tokens between completions stay masked
|
||||
out. Errored traces are dropped upstream (`TrainSink.process_episode`), so no error
|
||||
handling happens here. A branch carrying images also gets `mm_kwargs` (the concatenated
|
||||
pixel tensors) and `mm_token_type_ids` (the renderer's `mm_token_type_id_map` applied to
|
||||
the branch tokens). Branches with no sampled tokens (e.g. an openai client carrying none)
|
||||
yield nothing.
|
||||
pixel tensors) and `mm_token_type_ids` (`branch.mm_token_type_ids`, computed from the
|
||||
trace's renderer-stamped `mm_token_type_id_map`). Branches with no sampled tokens
|
||||
(e.g. an openai client carrying none) yield nothing.
|
||||
"""
|
||||
samples: list[TrainingSample] = []
|
||||
trained_loss_nodes: dict[str, set[int]] = {"rl": set(), "ce": set(), "ref_kl": set()}
|
||||
for branch, mask in iter_trainable_branches(trace):
|
||||
token_ids = branch.token_ids
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
mmd = branch.multi_modal_data
|
||||
if mmd is not None:
|
||||
mm_kwargs = _encode_mm_kwargs(mmd.mm_items)
|
||||
mapping = mm_token_type_ids_mapping or {}
|
||||
mm_token_type_ids = [mapping.get(t, 0) for t in token_ids]
|
||||
samples.append(
|
||||
TrainingSample(
|
||||
token_ids=token_ids,
|
||||
@@ -145,7 +137,7 @@ def trace_to_samples(
|
||||
env_name=env_name,
|
||||
ref_logprobs=branch.reference_logprobs,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
mm_token_type_ids=branch.mm_token_type_ids,
|
||||
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
|
||||
rl_weights=_loss_weights(branch, "rl", trained_loss_nodes["rl"]),
|
||||
ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]),
|
||||
|
||||
@@ -4,11 +4,11 @@ from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Literal, Protocol
|
||||
from typing import TYPE_CHECKING, Literal, Protocol, TypeAlias
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.transports.rollouts import TrainingSample
|
||||
from prime_rl.transports.batch import TrainingSample
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.metrics import EvalEpisodes, TrainEpisodes
|
||||
@@ -35,6 +35,34 @@ class Progress:
|
||||
|
||||
WorkKind = Literal["train", "eval"]
|
||||
|
||||
CancelReason = Literal["stale", "overload"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class GroupCancellation:
|
||||
"""Terminal marker for a dropped group: one message covering every episode
|
||||
the group still owed the sink (in-flight and never-dispatched), so
|
||||
count-to-``group_size`` finalization still fires. ``reason`` distinguishes
|
||||
pipeline decisions (staleness, overload cut) from episode errors."""
|
||||
|
||||
kind: WorkKind
|
||||
env_name: str
|
||||
group_id: str
|
||||
count: int
|
||||
reason: CancelReason
|
||||
|
||||
|
||||
DispatchResult: TypeAlias = vf.WireEpisode | GroupCancellation
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TaskRequest:
|
||||
"""A task selected by a train or eval source with its pinned run step."""
|
||||
|
||||
env_name: str
|
||||
task: vf.Task
|
||||
step: int
|
||||
|
||||
|
||||
@dataclass
|
||||
class InflightEpisode:
|
||||
@@ -47,26 +75,22 @@ class InflightEpisode:
|
||||
policy_version: int
|
||||
step: int
|
||||
client_config: vf.ClientConfig | None = None
|
||||
off_policy_steps: int = 0
|
||||
eval_step: int | None = None
|
||||
started_at: float = 0.0
|
||||
"""``time.monotonic()`` at dispatch; feeds episode-duration estimates."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class GroupState:
|
||||
"""Per-group dispatcher state: what's left to schedule + the pinned
|
||||
client (for prefix-cache hits)."""
|
||||
"""Per-group dispatcher state with its pinned run step."""
|
||||
|
||||
kind: WorkKind
|
||||
env_name: str
|
||||
task: vf.Task
|
||||
"""The group's task — its data is shipped on every dispatch."""
|
||||
step: int
|
||||
episodes_to_schedule: int
|
||||
target_episodes: int
|
||||
emitted: int = 0
|
||||
eval_step: int | None = None
|
||||
pinned_client: vf.ClientConfig | None = None
|
||||
policy_version_at_start: int = 0
|
||||
|
||||
|
||||
|
||||
@@ -10,8 +10,6 @@ from typing import Any
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
|
||||
from prime_rl.utils.utils import (
|
||||
get_broadcast_dir,
|
||||
@@ -48,34 +46,26 @@ def eval_work(episode: vf.Episode[Any, Any, Any]) -> vf.EvalWorkInfo:
|
||||
return run.work
|
||||
|
||||
|
||||
async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
"""Build the live policy inference pool + matching renderer. Returns
|
||||
``(renderer, inference_pool)``.
|
||||
def min_fresh_version(step: int, max_off_policy_steps: int) -> int:
|
||||
"""Oldest dispatch version whose episodes may still train in batch
|
||||
``step`` — anything older would ship past ``max_off_policy_steps``."""
|
||||
return (step - 1) - max_off_policy_steps
|
||||
|
||||
Training is renderer-only: the renderer object is the canonical
|
||||
messages → token ids path (sft backfill, opsd scoring prefixes, echo role
|
||||
attribution) and is always built. The renderer-client sampling path is
|
||||
wired onto the pool; when no train env samples from the live policy the
|
||||
renderer is still kept for client-side tokenization and the pool's evals
|
||||
use plain chat-completions."""
|
||||
from renderers.base import create_renderer
|
||||
|
||||
client_config = config.model.client
|
||||
model_name = config.model.name
|
||||
renderer = create_renderer(tokenizer, config.renderer)
|
||||
get_logger().info(f"Initialized {type(renderer).__name__} for {model_name}")
|
||||
if config.any_policy_sourced:
|
||||
get_logger().info("Using direct renderer rollout client")
|
||||
else:
|
||||
get_logger().info("No policy-sourced train env — renderer kept for client-side tokenization only")
|
||||
inference_pool = InferencePool(
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
return renderer, inference_pool
|
||||
def episode_staleness(episode: vf.Episode[Any, Any, Any], training_step: int) -> tuple[int, int, int]:
|
||||
"""``(total, in_flight, in_queue)`` staleness of one train episode when
|
||||
consumed by batch ``training_step``: the version the batch trains on
|
||||
(v{step-1}) minus the version that generated the episode. ``in_flight``
|
||||
is the span's share (weight updates during generation); ``in_queue`` is
|
||||
time spent buffered between completion and ship. Frozen-sourced episodes
|
||||
(no policy span) are never stale."""
|
||||
policy = train_work(episode).policy
|
||||
if policy is None:
|
||||
return 0, 0, 0
|
||||
total = max(0, (training_step - 1) - policy.start)
|
||||
in_flight = min(total, max(0, policy.end - policy.start))
|
||||
in_queue = total - in_flight
|
||||
return total, in_flight, in_queue
|
||||
|
||||
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
@@ -98,7 +88,7 @@ def setup_env_server_logging(log_level: str, json_logging: bool = False) -> None
|
||||
|
||||
def set_default_executor(max_workers: int = 64) -> None:
|
||||
"""Scale the default asyncio thread pool so asyncio.to_thread has enough capacity."""
|
||||
get_logger().info(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
|
||||
get_logger().debug(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
|
||||
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""WeightWatcher: polls the broadcast dir, advances ``Policy``, notifies
|
||||
observers (dispatcher → off-policy cancel). Standalone async task; the
|
||||
observers (dispatcher → staleness cancel). Standalone async task; the
|
||||
orchestrator's barrier bounds the in-flight lead."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -10,10 +10,10 @@ import time
|
||||
from modelexpress import p2p_pb2
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.clients import AdminClients, InferenceClient, update_weights
|
||||
from prime_rl.orchestrator.types import Policy, VersionObserver
|
||||
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.utils.async_utils import safe_cancel
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_broadcast_dir, get_step_path, wait_for_path
|
||||
from prime_rl.utils.utils import get_latest_ckpt_step
|
||||
@@ -27,7 +27,8 @@ class WeightWatcher:
|
||||
config: OrchestratorConfig,
|
||||
*,
|
||||
policy: Policy,
|
||||
inference: InferencePool,
|
||||
clients: InferenceClient,
|
||||
admin_clients: AdminClients,
|
||||
observers: list[VersionObserver],
|
||||
lora_name: str | None,
|
||||
ckpt_step: int = 0,
|
||||
@@ -36,7 +37,8 @@ class WeightWatcher:
|
||||
) -> None:
|
||||
self.config = config
|
||||
self.policy = policy
|
||||
self.inference = inference
|
||||
self.clients = clients
|
||||
self.admin_clients = admin_clients
|
||||
self.observers = observers
|
||||
self.lora_name = lora_name
|
||||
self.ckpt_step = ckpt_step
|
||||
@@ -77,7 +79,8 @@ class WeightWatcher:
|
||||
def compute_next_ckpt_step(self) -> int:
|
||||
"""Return the next policy version exposed by the configured transport."""
|
||||
if self.model_express is not None:
|
||||
if self.config.max_steps is not None and self.ckpt_step >= self.config.max_steps - 2:
|
||||
# The trainer broadcasts every version except v{max_steps}.
|
||||
if self.config.max_steps is not None and self.ckpt_step >= self.config.max_steps - 1:
|
||||
return self.ckpt_step
|
||||
# ModelExpress status changes are unversioned, so its rendezvous advances
|
||||
# exactly one policy version per READY/INITIALIZING cycle.
|
||||
@@ -102,10 +105,7 @@ class WeightWatcher:
|
||||
weights_path = get_step_path(broadcast_dir, next_step)
|
||||
stable_marker = weights_path / "STABLE"
|
||||
if not stable_marker.exists():
|
||||
get_logger().info(
|
||||
f"Orchestrator paused: waiting for trainer to broadcast checkpoint {next_step}. "
|
||||
"Training is progressing normally."
|
||||
)
|
||||
get_logger().info(f"Waiting for the trainer to broadcast policy v{next_step}")
|
||||
await wait_for_path(stable_marker)
|
||||
self.last_wait_for_ckpt_time = time.perf_counter() - t0
|
||||
|
||||
@@ -116,7 +116,7 @@ class WeightWatcher:
|
||||
self.ckpt_step = next_step
|
||||
self.policy.version = next_step
|
||||
|
||||
# Drain off-policy rollouts BEFORE pausing the inference engines.
|
||||
# Drain stale rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
# ``_reqs_not_processed``), which is only propagated to the workers
|
||||
# while the engine is stepping. If we drain after resume instead,
|
||||
@@ -134,15 +134,17 @@ class WeightWatcher:
|
||||
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
|
||||
)
|
||||
|
||||
get_logger().debug(f"Updating weights to step {next_step}")
|
||||
get_logger().debug(f"Updating inference weights to policy v{next_step}")
|
||||
t1 = time.perf_counter()
|
||||
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
|
||||
await update_weights(self.admin_clients.clients, weights_path, lora_name=self.lora_name, step=next_step)
|
||||
self.last_update_weights_time = time.perf_counter() - t1
|
||||
self.update_count += 1
|
||||
get_logger().debug(f"Updated weights to step {next_step} in {format_time(self.last_update_weights_time)}")
|
||||
get_logger().debug(
|
||||
f"Updated inference weights to policy v{next_step} in {format_time(self.last_update_weights_time)}"
|
||||
)
|
||||
|
||||
if self.lora_name is not None:
|
||||
self.inference.update_model_name(self.lora_name)
|
||||
self.clients.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
|
||||
for observer in self.observers:
|
||||
|
||||
@@ -6,7 +6,7 @@ from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from prime_rl.transports.rollouts.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
|
||||
from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
# Backfill value per component weight stream when a packed sample doesn't
|
||||
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
|
||||
|
||||
@@ -21,7 +21,7 @@ from prime_rl.configs.shared import ResumeConfig
|
||||
from prime_rl.configs.trainer import CheckpointConfig
|
||||
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.utils import get_all_ckpt_steps, get_ckpt_dir, get_step_path
|
||||
|
||||
|
||||
@@ -194,7 +194,7 @@ class CheckpointManager:
|
||||
# Save sharded state
|
||||
dcp_save(state_dict, checkpoint_id=path)
|
||||
|
||||
self.logger.debug(f"Training checkpoint saved in {time.perf_counter() - start_time:.2f} seconds")
|
||||
self.logger.debug(f"Saved training checkpoint in {format_time(time.perf_counter() - start_time)}")
|
||||
|
||||
def load_from_path(
|
||||
self,
|
||||
@@ -232,7 +232,7 @@ class CheckpointManager:
|
||||
)
|
||||
dataloader.load_state_dict(torch.load(dataloader_path, weights_only=False))
|
||||
|
||||
self.logger.debug(f"Training checkpoint loaded in {time.perf_counter() - start_time:.2f} seconds")
|
||||
self.logger.debug(f"Loaded training checkpoint in {format_time(time.perf_counter() - start_time)}")
|
||||
|
||||
def load(
|
||||
self,
|
||||
|
||||
@@ -241,7 +241,7 @@ def apply_lora_to_model(model: nn.Module, config: LoRAConfig) -> None:
|
||||
)
|
||||
raise RuntimeError("Cannot apply LoRA to FSDP-wrapped model. Apply LoRA before setup_fsdp().")
|
||||
|
||||
logger.debug(f"Applying LoRA to model: {model} for {config.target_modules}")
|
||||
logger.debug(f"Applying LoRA to {type(model).__name__} (target_modules={config.target_modules})")
|
||||
target_modules = _find_target_modules(model, config.target_modules)
|
||||
logger.debug(
|
||||
f"Found {len(target_modules)} target modules for LoRA: {target_modules[:10]} ... {target_modules[-10:]}"
|
||||
|
||||
@@ -595,7 +595,7 @@ def get_model(
|
||||
config: ModelConfig, device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.bfloat16
|
||||
) -> nn.Module:
|
||||
logger = get_logger()
|
||||
logger.info(
|
||||
logger.debug(
|
||||
f"Loading model config (name={config.name}, attn={config.attn}, trust_remote_code={config.trust_remote_code})"
|
||||
)
|
||||
|
||||
@@ -778,7 +778,7 @@ def get_model(
|
||||
trust_remote_code=config.trust_remote_code,
|
||||
**dtype_kwarg,
|
||||
)
|
||||
logger.debug(f"Loaded model {config.name} in {time.perf_counter() - load_model_start_time:.2f} seconds")
|
||||
logger.debug(f"Loaded model {config.name} in {format_time(time.perf_counter() - load_model_start_time)}")
|
||||
|
||||
assert model.lm_head.weight.dtype == dtype, (
|
||||
f"LM head dtype wasnt loaded correctly {model.lm_head.weight.dtype} != {dtype}"
|
||||
@@ -1057,7 +1057,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
generator = torch.Generator(device="cuda").manual_seed(seed_tensor.item())
|
||||
for module in lora_modules:
|
||||
module._init_lora_parameters(generator)
|
||||
logger.debug(f"Loaded weights using HF DCP in {time.perf_counter() - load_dcp_start_time:.2f} seconds")
|
||||
logger.debug(f"Loaded weights using HF DCP in {format_time(time.perf_counter() - load_dcp_start_time)}")
|
||||
|
||||
|
||||
def can_reinit_empty_buffers(model: nn.Module):
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from functools import cached_property
|
||||
|
||||
@@ -25,7 +26,7 @@ from torch._utils import _get_available_device_type
|
||||
from torch.distributed.device_mesh import DeviceMesh, init_device_mesh
|
||||
|
||||
from prime_rl.configs.trainer import ModelConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
|
||||
device_type = _get_available_device_type() or "cuda"
|
||||
|
||||
@@ -105,7 +106,9 @@ class ParallelDims:
|
||||
names.append(name)
|
||||
|
||||
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
|
||||
t0 = time.perf_counter()
|
||||
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
|
||||
self.logger.debug(f"Built device mesh in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
# Create all the submesh here to ensure all required process groups are
|
||||
# initialized:
|
||||
@@ -163,7 +166,9 @@ class ParallelDims:
|
||||
names.append(name)
|
||||
|
||||
self.logger.info(f"Building {len(dims)}-D device mesh with {names}, {dims}")
|
||||
t0 = time.perf_counter()
|
||||
mesh = init_device_mesh(device_type, dims, mesh_dim_names=names)
|
||||
self.logger.debug(f"Built device mesh in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
# Create all the submesh here to ensure all required process groups are
|
||||
# initialized:
|
||||
|
||||
@@ -7,11 +7,11 @@ from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import FakeDataLoaderConfig
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.transports.rollouts import (
|
||||
from prime_rl.transports.batch import (
|
||||
BatchReceiver,
|
||||
MicroBatch,
|
||||
MicroBatchReceiver,
|
||||
TransportConfig,
|
||||
setup_micro_batch_receiver,
|
||||
setup_batch_receiver,
|
||||
)
|
||||
|
||||
|
||||
@@ -174,7 +174,7 @@ class DataLoader:
|
||||
non_dp_world_size = self.world.world_size // dp_world_size
|
||||
dp_rank = self.world.rank // non_dp_world_size
|
||||
|
||||
self.receiver: MicroBatchReceiver = setup_micro_batch_receiver(output_dir, dp_rank, start_step, config)
|
||||
self.receiver: BatchReceiver = setup_batch_receiver(output_dir, dp_rank, start_step, config)
|
||||
|
||||
def wait_for_batch(self) -> None:
|
||||
self.receiver.wait()
|
||||
|
||||
@@ -79,10 +79,9 @@ def train(config: TrainerConfig):
|
||||
config.log.level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
logger.info(f"Starting RL trainer in {world} in {config.output_dir}")
|
||||
logger.info(f"Starting RL trainer in {world} (output_dir={config.output_dir})")
|
||||
|
||||
# Setup the monitors
|
||||
logger.info(f"Initializing monitors ({config.monitors})")
|
||||
asyncio.run(
|
||||
monitors.setup(
|
||||
wandb=config.monitors.wandb, file=config.monitors.file, output_dir=config.output_dir, run_config=config
|
||||
@@ -140,19 +139,21 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Initialize the model and tokenizer
|
||||
logger.info(f"Initializing model ({config.model})")
|
||||
t0 = time.perf_counter()
|
||||
loading_from_ckpt_later = checkpoint_step is not None
|
||||
model = setup_model(config.model, parallel_dims, loading_from_ckpt_later)
|
||||
logger.debug(f"Initialized model in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
|
||||
raise ValueError("Packed multimodal training requires model support")
|
||||
|
||||
# Set up the loss function for the RL loss type (ce / ref_kl are fixed)
|
||||
logger.info(f"Setting up loss function ({config.loss})")
|
||||
logger.info(f"Initializing loss function ({config.loss})")
|
||||
rl_loss_fn = setup_rl_loss_fn(config.loss)
|
||||
|
||||
# Set up the optimizer
|
||||
logger.info(f"Initializing optimizer ({config.optim})")
|
||||
|
||||
t0 = time.perf_counter()
|
||||
optimizer, gradient_manager = setup_optimizer(
|
||||
config.optim,
|
||||
list(model.named_parameters()),
|
||||
@@ -164,9 +165,10 @@ def train(config: TrainerConfig):
|
||||
get_full_offload_dtype_policy(model, config.model) if config.model.full_offload is not None else None
|
||||
),
|
||||
)
|
||||
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
|
||||
logger.debug(f"Initialized optimizer in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
logger.info(f"Using `{config.scheduler.type}` scheduler ({config.scheduler})")
|
||||
logger.info(f"Initializing scheduler ({config.scheduler})")
|
||||
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
|
||||
|
||||
# Set up weight broadcast (skip when using fake data since there's no inference server)
|
||||
if config.data.fake:
|
||||
@@ -174,12 +176,14 @@ def train(config: TrainerConfig):
|
||||
logger.info("Skipping weight broadcast setup (fake data mode)")
|
||||
else:
|
||||
logger.info(f"Initializing weight broadcast ({config.weight_broadcast})")
|
||||
t0 = time.perf_counter()
|
||||
weight_broadcast = setup_weight_broadcast(
|
||||
config.output_dir,
|
||||
config.weight_broadcast,
|
||||
parallel_dims,
|
||||
config.model.lora,
|
||||
)
|
||||
logger.debug(f"Initialized weight broadcast in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
if parallel_dims.cp_enabled:
|
||||
cp_group = parallel_dims.world_mesh["cp"].get_group()
|
||||
@@ -228,14 +232,16 @@ def train(config: TrainerConfig):
|
||||
)
|
||||
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
|
||||
progress.step += 1
|
||||
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
|
||||
|
||||
logger.info(
|
||||
f"Starting from step {progress.step} (total_tokens={progress.total_tokens}, total_samples={progress.total_samples})"
|
||||
)
|
||||
logger.info(
|
||||
f"Resuming from step {checkpoint_step} "
|
||||
f"(total_tokens={progress.total_tokens}, total_samples={progress.total_samples})"
|
||||
)
|
||||
else:
|
||||
logger.info("Starting from scratch")
|
||||
|
||||
# Set up the data loader (Optionally, use a fake data loader for debugging)
|
||||
logger.info(f"Initializing data loader ({config.data})")
|
||||
t0 = time.perf_counter()
|
||||
if config.data.fake:
|
||||
dataloader = FakeDataLoader(config.data.fake, config.model.seq_len, parallel_dims.get_mesh("dp").size())
|
||||
else:
|
||||
@@ -245,6 +251,7 @@ def train(config: TrainerConfig):
|
||||
parallel_dims.get_mesh("dp").size(),
|
||||
config.rollout_transport,
|
||||
)
|
||||
logger.debug(f"Initialized data loader in {format_time(time.perf_counter() - t0)}")
|
||||
|
||||
token_exporter = setup_token_exporter(config, parallel_dims, world, logger)
|
||||
|
||||
@@ -263,7 +270,7 @@ def train(config: TrainerConfig):
|
||||
torch.cuda.reset_peak_memory_stats()
|
||||
if gc_handler is not None:
|
||||
gc_handler.run(progress.step)
|
||||
is_last_step = config.max_steps is not None and progress.step == config.max_steps
|
||||
is_last_step = config.max_steps is not None and progress.step >= config.max_steps
|
||||
|
||||
logger.debug(f"Starting training step {progress.step}")
|
||||
step_start_time = time.perf_counter()
|
||||
@@ -273,22 +280,26 @@ def train(config: TrainerConfig):
|
||||
# and so a broken broadcast path fails at startup instead of after the first
|
||||
# optimizer step.
|
||||
if progress.step == start_step and weight_broadcast is not None:
|
||||
logger.info(f"Broadcasting startup policy weights (v{progress.step - 1}) to inference engines")
|
||||
logger.info(f"Broadcasting base policy weights (v{progress.step - 1}) to inference engines")
|
||||
t0 = time.perf_counter()
|
||||
weight_broadcast.broadcast_weights(model, step=progress.step - 1)
|
||||
logger.debug(
|
||||
f"Broadcast base policy weights (v{progress.step - 1}) in {format_time(time.perf_counter() - t0)}"
|
||||
)
|
||||
|
||||
# Wait for the batch to be available
|
||||
logger.debug("Waiting for training batch to arrive")
|
||||
wait_for_batch_start_time = time.perf_counter()
|
||||
dataloader.wait_for_batch()
|
||||
wait_for_batch_time = time.perf_counter() - wait_for_batch_start_time
|
||||
logger.debug(f"Waited for batch to arrive for {wait_for_batch_time:.2f} seconds")
|
||||
logger.debug(f"Waited for batch for {format_time(wait_for_batch_time)}")
|
||||
|
||||
# Load the training batch
|
||||
logger.debug("Loading batch")
|
||||
load_data_start_time = time.perf_counter()
|
||||
micro_batches = dataloader.get_batch()
|
||||
load_data_time = time.perf_counter() - load_data_start_time
|
||||
logger.debug(f"Loaded batch in {load_data_time:.2f} seconds")
|
||||
logger.debug(f"Loaded batch in {format_time(load_data_time)}")
|
||||
|
||||
batch_size = len(micro_batches)
|
||||
memory_profiler = None
|
||||
@@ -539,7 +550,7 @@ def train(config: TrainerConfig):
|
||||
tensors[key].append(loss_tensor.detach().to("cpu"))
|
||||
|
||||
# Debug log with *local, micro step* stats
|
||||
micro_step_message = f"Micro Step {micro_step}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
|
||||
micro_step_message = f"Micro Step {micro_step + 1}/{len(micro_batches)} | Loss {tensors['loss'][-1].mean().item():.4f} | Entropy {tensors['entropy/all'][-1].mean().item():.4f}"
|
||||
if has_mismatch_tokens:
|
||||
micro_step_message += f" | Mismatch KL {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
|
||||
if "max_vio" in tensors:
|
||||
@@ -573,15 +584,16 @@ def train(config: TrainerConfig):
|
||||
forward_backward_time = time.perf_counter() - forward_backward_start_time
|
||||
|
||||
# Broadcast the model just produced (policy v{progress.step}) so the orchestrator can
|
||||
# sample its next step from it. In-memory transports retain their two-step shutdown
|
||||
# window; filesystem broadcast still writes every version for resume.
|
||||
# sample its next step from it. Only the final version is unused (nothing samples from
|
||||
# v{max_steps}) — the orchestrator stays alive for every other in-memory rendezvous;
|
||||
# filesystem broadcast still writes every version for resume.
|
||||
if weight_broadcast is None:
|
||||
broadcast_weights_time = 0
|
||||
else:
|
||||
broadcast_unused = (
|
||||
config.weight_broadcast.type in ("nccl", "nixl")
|
||||
and config.max_steps is not None
|
||||
and progress.step >= config.max_steps - 1
|
||||
and progress.step >= config.max_steps
|
||||
)
|
||||
if not broadcast_unused:
|
||||
broadcast_weights_start_time = time.perf_counter()
|
||||
@@ -725,7 +737,7 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Write final checkpoint
|
||||
if config.ckpt is not None:
|
||||
logger.info("Writing final checkpoint")
|
||||
logger.info(f"Saving final checkpoint at step {progress.step}")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress)
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
@@ -733,7 +745,7 @@ def train(config: TrainerConfig):
|
||||
gradient_manager.close()
|
||||
|
||||
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
|
||||
logger.success("RL trainer finished!")
|
||||
logger.success("RL trainer finished")
|
||||
|
||||
# Stop metrics/health server if configured
|
||||
if metrics_server is not None:
|
||||
|
||||
@@ -683,14 +683,17 @@ def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig) -> St
|
||||
batch_size=1,
|
||||
collate_fn=cat_collate,
|
||||
num_workers=config.num_workers,
|
||||
pin_memory=config.num_workers > 0,
|
||||
pin_memory=True,
|
||||
)
|
||||
|
||||
|
||||
def get_dataset_state(dataloader: StatefulDataLoader) -> dict:
|
||||
state = dataloader.state_dict()
|
||||
if "dataset_state" in state:
|
||||
return state["dataset_state"]
|
||||
worker_snapshots = (state.get("_snapshot") or {}).get("_worker_snapshots") or {}
|
||||
(worker_state,) = worker_snapshots.values()
|
||||
return worker_state["dataset_state"]
|
||||
"""Dataset position per worker for the startup log, parsed from ``StatefulDataLoader.state_dict()``.
|
||||
|
||||
The loader is the only source that is correct in every case: after a resume's
|
||||
``load_state_dict`` the restored position exists solely in the loader's stashed
|
||||
state (it reaches the dataset copies inside workers when the iterator forks them;
|
||||
the main-process dataset object stays at position zero). The keys are torchdata's
|
||||
private worker-snapshot layout."""
|
||||
snapshots = dataloader.state_dict()["_snapshot"]["_worker_snapshots"]
|
||||
return {wid: snap["dataset_state"]["dataset"] for wid, snap in sorted(snapshots.items())}
|
||||
|
||||
@@ -72,10 +72,9 @@ def train(config: SFTConfig):
|
||||
config.log.level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
logger.info(f"Starting SFT trainer in {world}")
|
||||
logger.info(f"Starting SFT trainer in {world} (output_dir={config.run_dir})")
|
||||
|
||||
# Setup the monitors
|
||||
logger.info(f"Initializing monitors ({config.monitors})")
|
||||
asyncio.run(
|
||||
monitors.setup(
|
||||
wandb=config.monitors.wandb,
|
||||
@@ -184,7 +183,7 @@ def train(config: SFTConfig):
|
||||
renderer = create_renderer(tokenizer, config.renderer)
|
||||
if processor is not None and hasattr(renderer, "_processor"):
|
||||
renderer._processor = processor
|
||||
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
|
||||
logger.debug(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
|
||||
|
||||
# Set up the optimizer
|
||||
logger.info(f"Initializing optimizer ({config.optim})")
|
||||
@@ -208,7 +207,7 @@ def train(config: SFTConfig):
|
||||
if config.max_steps is not None and (config.ckpt and config.ckpt.skip_scheduler and checkpoint_step is not None)
|
||||
else config.max_steps
|
||||
)
|
||||
logger.info(f"Setting up {config.scheduler.type} scheduler with {scheduler_steps} steps ({config.scheduler})")
|
||||
logger.info(f"Initializing scheduler with {scheduler_steps} steps ({config.scheduler})")
|
||||
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
|
||||
|
||||
# Set up the dataset and dataloader
|
||||
@@ -216,7 +215,6 @@ def train(config: SFTConfig):
|
||||
multimodal = config.model.vlm is not None
|
||||
dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer, multimodal=multimodal)
|
||||
dataloader = setup_dataloader(dataset, config.data)
|
||||
dataiter = iter(dataloader)
|
||||
|
||||
val_raw_dataset = None
|
||||
if config.val is not None:
|
||||
@@ -238,16 +236,24 @@ def train(config: SFTConfig):
|
||||
dataloader=dataloader if not skip.skip_dataloader else None,
|
||||
path=resume_dir / "trainer" if resume_dir is not None else None,
|
||||
)
|
||||
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
|
||||
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
|
||||
if not skip.skip_progress:
|
||||
progress.step += 1
|
||||
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
|
||||
if skip.skip_scheduler:
|
||||
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
|
||||
logger.info(
|
||||
f"Starting from step {progress.step} (total_tokens={progress.total_tokens}, total_samples={progress.total_samples}, dataset_state={get_dataset_state(dataloader)})"
|
||||
)
|
||||
logger.info(
|
||||
f"Resuming from step {checkpoint_step} (total_tokens={progress.total_tokens}, "
|
||||
f"total_samples={progress.total_samples}, dataset_state={get_dataset_state(dataloader)})"
|
||||
)
|
||||
else:
|
||||
logger.info("Starting from scratch")
|
||||
|
||||
# Create the iterator only after a potential resume: iter() forks workers with a
|
||||
# copy of the dataset's *current* state, so a later load_state_dict never reaches
|
||||
# an already-running worker (the run silently restarts the data from the beginning
|
||||
# and re-saves the stale position).
|
||||
dataiter = iter(dataloader)
|
||||
|
||||
cp_enabled = parallel_dims.cp_enabled
|
||||
cp_rank = parallel_dims.world_mesh["cp"].get_local_rank() if cp_enabled else 0
|
||||
@@ -700,7 +706,7 @@ def train(config: SFTConfig):
|
||||
|
||||
# Write final checkpoint
|
||||
if config.ckpt is not None:
|
||||
logger.info("Writing final checkpoint")
|
||||
logger.info(f"Saving final checkpoint at step {progress.step}")
|
||||
ckpt_manager.save(progress.step, model, [optimizer], scheduler, progress, dataloader=dataloader)
|
||||
ckpt_manager.maybe_clean()
|
||||
|
||||
@@ -715,7 +721,7 @@ def train(config: SFTConfig):
|
||||
gradient_manager.close()
|
||||
|
||||
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
|
||||
logger.success("SFT trainer finished!")
|
||||
logger.success("SFT trainer finished")
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user