Compare commits
15
Commits
trinity
...
v0.7.1.dev78
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d612e23c1d | ||
|
|
d135ed4c90 | ||
|
|
1fd2d732c2 | ||
|
|
6a9969e61a | ||
|
|
1385e0722c | ||
|
|
e2ad3beaaa | ||
|
|
9551e20fa8 | ||
|
|
6df90dc0aa | ||
|
|
8372c37a15 | ||
|
|
15f5355f5f | ||
|
|
d1bfcbc636 | ||
|
|
f50ec5c4c8 | ||
|
|
9b944591c4 | ||
|
|
3b22dd951c | ||
|
|
13770289ef |
@@ -13,9 +13,9 @@ on:
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
# Scheduled run at 3AM PST (11AM UTC) — disabled for now, enable once dry-run passes
|
||||
# schedule:
|
||||
# - cron: "0 11 * * *"
|
||||
# Scheduled run at 3AM PST (11AM UTC)
|
||||
schedule:
|
||||
- cron: "0 11 * * *"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -113,16 +113,24 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# The GHCR versions API can list a tag before its manifest is
|
||||
# actually pullable (build in-flight, or manifest step didn't
|
||||
# finish). So: pull the top N candidate tags, then verify each
|
||||
# with a manifest HEAD via the anonymous registry token flow;
|
||||
# take the newest one that resolves.
|
||||
# No dispatch input: auto-resolve the newest v*.dev* tag on
|
||||
# GHCR (the point of a nightly is to catch regressions on
|
||||
# tip-of-main). The GHCR versions API can list a tag before
|
||||
# its manifest is actually pullable (build in-flight, or
|
||||
# manifest step didn't finish), so pull the top N candidates
|
||||
# and verify each with a manifest HEAD via the anonymous
|
||||
# registry token flow; take the newest one that resolves.
|
||||
# Disable pipefail locally: `grep` may exit 1 on no matches
|
||||
# (empty tag list) and `head` may SIGPIPE `sort` after
|
||||
# reading its 10 lines. Both would abort the step before the
|
||||
# explicit no-candidates guard below runs.
|
||||
set +o pipefail
|
||||
candidates=$(gh api --paginate \
|
||||
"/orgs/primeintellect-ai/packages/container/prime-rl/versions" \
|
||||
--jq '.[].metadata.container.tags[]' \
|
||||
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+$' \
|
||||
| sort -Vru | head -n 10)
|
||||
set -o pipefail
|
||||
if [ -z "$candidates" ]; then
|
||||
echo "No v*.dev* tag listed on GHCR." >&2
|
||||
exit 1
|
||||
|
||||
@@ -32,10 +32,11 @@ group_size = 8
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -19,10 +19,11 @@ batch_size = 128
|
||||
group_size = 8
|
||||
seq_len = 8192
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
@@ -22,10 +22,11 @@ group_size = 16
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -40,10 +40,11 @@ group_size = 16
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
env.taskset = { id = "wiki-search-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -21,10 +21,11 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
batch_size = 128
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
env.taskset = { id = "wordle-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.player.harness = { id = "null" }
|
||||
env.player.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -22,10 +22,11 @@ group_size = 8
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 384
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, task = { similarity_power = 4, power_per_turn = false } }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -26,10 +26,11 @@ name = "r8-1e-4"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
|
||||
@@ -25,10 +25,11 @@ name = "r8-1e-4"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference]
|
||||
enable_lora = true
|
||||
|
||||
@@ -25,10 +25,11 @@ group_size = 16
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.7
|
||||
|
||||
@@ -14,10 +14,11 @@ lr = 3e-5
|
||||
[train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[train.env]]
|
||||
[[train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[ckpt]
|
||||
interval = 10
|
||||
|
||||
@@ -37,10 +37,11 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -49,10 +50,11 @@ num_examples = 16
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -43,10 +43,11 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -55,10 +56,11 @@ num_examples = 16
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -23,10 +23,11 @@ group_size = 16
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -22,10 +22,11 @@ group_size = 16
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference]
|
||||
|
||||
|
||||
@@ -18,10 +18,11 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
@@ -18,18 +18,20 @@ batch_size = 512
|
||||
group_size = 8
|
||||
seq_len = 8192
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2024"
|
||||
env.taskset = { id = "aime24-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
group_size = 32
|
||||
|
||||
[trainer]
|
||||
|
||||
@@ -18,10 +18,11 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -23,10 +23,11 @@ oversampling_factor = 2.0
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
env.taskset = { id = "wiki-search-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -18,10 +18,11 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
env.taskset = { id = "wordle-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.player.harness = { id = "null" }
|
||||
env.player.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -20,10 +20,11 @@ group_size = 16
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 64
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "color-codeword"
|
||||
env.taskset = { id = "color-codeword-v1", images_per_turn = 1 }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer]
|
||||
|
||||
|
||||
@@ -24,10 +24,11 @@ type = "echo"
|
||||
[orchestrator.algo.roles.user]
|
||||
alpha = 0.1
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -21,10 +21,11 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -33,10 +34,11 @@ num_examples = 128
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -21,10 +21,11 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -33,10 +34,11 @@ num_examples = 128
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -31,20 +31,22 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-grpo"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-opd"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.env.algo]
|
||||
[orchestrator.train.source.algo]
|
||||
type = "opd"
|
||||
|
||||
[orchestrator.train.env.algo.teacher]
|
||||
[orchestrator.train.source.algo.teacher]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
|
||||
base_url = ["http://localhost:8001/v1"]
|
||||
|
||||
@@ -55,10 +57,11 @@ num_examples = 128
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -33,10 +33,11 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -45,10 +46,11 @@ num_examples = 128
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -33,10 +33,11 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -45,10 +46,11 @@ num_examples = 128
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
max_steps = 20
|
||||
seq_len = 4096
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[wandb]
|
||||
project = "algorithms-debug"
|
||||
name = "debug-rae"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 32
|
||||
group_size = 1
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "rae"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "kuhn-poker"
|
||||
env.taskset = { id = "kuhn-poker-v1" }
|
||||
env.player0.harness = { id = "null" }
|
||||
env.player0.runtime = { type = "subprocess" }
|
||||
env.player1.harness = { id = "null" }
|
||||
env.player1.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "kuhn-poker"
|
||||
env.taskset = { id = "kuhn-poker-v1" }
|
||||
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
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -29,10 +29,11 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -41,10 +42,11 @@ num_examples = 128
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -38,10 +38,11 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -50,10 +51,11 @@ num_examples = 128
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -38,10 +38,11 @@ name = "prime-qwen3"
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
@@ -50,10 +51,11 @@ num_examples = 128
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-4
|
||||
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: bdb96b0c84...5fdf78c30e
Vendored
+1
-1
Submodule deps/research-environments updated: f5d423c321...6a2dee6fcd
Vendored
+1
-1
Submodule deps/verifiers updated: b13ba60da6...fcb48822ea
+34
-7
@@ -17,6 +17,7 @@ This page covers the math and the configurable algorithmic components: the algor
|
||||
- [Custom Loss](#custom-loss)
|
||||
- [Advantage](#advantage)
|
||||
- [Default Advantage](#default-advantage)
|
||||
- [Self-Play Advantage (RAE)](#self-play-advantage-rae)
|
||||
- [Authoring an Algorithm](#authoring-an-algorithm)
|
||||
- [Reference Scoring](#reference-scoring)
|
||||
- [Filters](#filters)
|
||||
@@ -67,6 +68,7 @@ type = "grpo" # the default
|
||||
|---|---|---|---|
|
||||
| `grpo` | policy | `rl` on actions | Standard group-relative RL. |
|
||||
| `max_rl` | policy | `rl` on actions | MaxRL ([arXiv:2602.02710](https://arxiv.org/abs/2602.02710)): GRPO's centered reward normalized by the group **mean** instead of the standard deviation — the gradient is unbiased for the order-`group_size` truncation of the maximum-likelihood objective, upweighting hard examples like `1/p`. |
|
||||
| `rae` | policy | `rl` on actions | RAE (SPIRAL, [arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): reward minus a per-agent EMA baseline of that agent's own rewards — the estimator for multi-agent self-play envs, where the group mean would mix the agents' opposite reward scales. See [Self-Play Advantage](#self-play-advantage-rae). |
|
||||
| `opd` | policy | `ref_kl` on actions | On-policy distillation ([Thinking Machines](https://thinkingmachines.ai/blog/on-policy-distillation/)): the policy samples, per-token reverse KL against a reference model as the gradient signal. Needs a `teacher`. |
|
||||
| `sft` | *(the teacher)* | `ce` on actions | Hard distillation: a frozen model generates rollouts, the policy trains with CE on its tokens. Needs a frozen `sampling.source` (the teacher it samples from). |
|
||||
| `opsd` | policy | `ref_kl` on actions | SDFT ([arXiv:2601.19897](https://arxiv.org/abs/2601.19897)): the model is its own reference, conditioned on an expert demonstration. The teacher *is* the live policy (the paper's setting, no extra deployment) — no model to configure. |
|
||||
@@ -116,16 +118,18 @@ Both components resolve per environment. Each env inherits `[orchestrator.algo]`
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
taskset = { id = "math-v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.taskset = { id = "math-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
# inherits the top-level grpo
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "terminal"
|
||||
taskset = { id = "terminal-v1" }
|
||||
harness = { id = "bash", runtime = { type = "subprocess" } }
|
||||
env.taskset = { id = "terminal-v1" }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
algo = { type = "echo" } # this env runs its own algorithm
|
||||
```
|
||||
|
||||
@@ -138,6 +142,7 @@ At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_r
|
||||
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
|
||||
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
|
||||
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
|
||||
| `rae` | `RAEAlgorithm` | `score_group`: per-agent EMA-baseline credit |
|
||||
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
|
||||
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
|
||||
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
|
||||
@@ -174,7 +179,7 @@ $$
|
||||
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
|
||||
$$
|
||||
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the group-relative algorithms (`grpo`, `max_rl`, and `echo`'s action tokens).
|
||||
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, and `echo`'s action tokens).
|
||||
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
|
||||
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
|
||||
|
||||
@@ -276,6 +281,7 @@ The per-token training signal is set by `algo.type` and the [algorithm](#the-alg
|
||||
|---|---|---|
|
||||
| `grpo` | `rl` | Group-norm: reward minus per-group baseline, optional length penalty. |
|
||||
| `max_rl` | `rl` | Mean-normalized group credit (maximum-likelihood RL). |
|
||||
| `rae` | `rl` | Reward minus a per-agent EMA baseline (SPIRAL's role-conditioned advantage estimation) — for multi-agent self-play envs. |
|
||||
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
|
||||
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
|
||||
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
|
||||
@@ -297,6 +303,27 @@ type = "grpo"
|
||||
type = "linear"
|
||||
```
|
||||
|
||||
### Self-Play Advantage (RAE)
|
||||
|
||||
Group-relative baselines assume the group is exchangeable attempts by one agent. A multi-agent self-play env breaks that: one episode yields one trace per agent, all trainable, and in a zero-sum game the rewards sum to ~0 whatever the policy does — the group mean carries no information, and centering against it converts any structural asymmetry (a first-mover edge) into permanent credit for one agent.
|
||||
|
||||
`rae` implements SPIRAL's role-conditioned advantage estimation ([arXiv:2506.24119](https://arxiv.org/abs/2506.24119)): each agent keeps an exponential-moving-average baseline of its own rewards, and every trace's advantage is its reward minus its agent's baseline — measured against the *pre-update* baseline (the unbiased order), then folded in at `decay` (SPIRAL's α, default 0.95). The algorithm instance is per-env, so baselines are keyed per (env, agent) — the paper's per (game, role). Advantages are not normalized, and `group_size` is free (RAE needs no sibling rollouts; `group_size = 1` is fine). Baselines live in orchestrator memory and re-warm from 0 over ~`1/(1 − decay)` traces per agent after a restart.
|
||||
|
||||
```toml
|
||||
[orchestrator.algo]
|
||||
type = "rae"
|
||||
decay = 0.95
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "kuhn-poker"
|
||||
env.taskset = { id = "kuhn-poker-v1" }
|
||||
env.player0.harness = { id = "null" }
|
||||
env.player0.runtime = { type = "subprocess" }
|
||||
env.player1.harness = { id = "null" }
|
||||
env.player1.runtime = { type = "subprocess" }
|
||||
```
|
||||
|
||||
Both of `kuhn-poker-v1`'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.
|
||||
|
||||
### Authoring an Algorithm
|
||||
|
||||
|
||||
+16
-13
@@ -17,7 +17,7 @@ Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeInt
|
||||
- [Optional Sub-Configs](#optional-sub-configs)
|
||||
- [None](#none)
|
||||
- [Discriminated Unions](#discriminated-unions)
|
||||
- [Environments](#environments-orchestratortrainenv)
|
||||
- [Environments](#environments)
|
||||
- [Environment Variables](#environment-variables)
|
||||
- [Examples](#examples)
|
||||
|
||||
@@ -55,7 +55,7 @@ CLI flags mirror the TOML tree using dots:
|
||||
|
||||
> Field names are snake_case in TOML (`max_model_len`) and kebab-case on the CLI (`--max-model-len`).
|
||||
|
||||
> Renamed fields keep their old name as a validation alias — e.g. `rollouts_per_example` is still accepted in TOML and CLI after being renamed to `group_size`. Mixing the two names across sources is safe.
|
||||
> A renamed field keeps no alias for its old name: the old spelling fails as an unknown key rather than being silently translated.
|
||||
|
||||
## Inspecting and Validating
|
||||
|
||||
@@ -93,19 +93,19 @@ uv run rl @ rl.toml --trainer.model.lora.target-modules '["q_proj", "k_proj", "v
|
||||
target_modules = ["q_proj", "k_proj", "v_proj"]
|
||||
```
|
||||
|
||||
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables (e.g. environments), see [Environments](#environments-orchestratortrainenv).
|
||||
Overlay TOMLs **replace** lists wholesale — an overlay that wants to add one item must still spell out the full list. For arrays of tables, see [Environments](#environments).
|
||||
|
||||
### Dicts
|
||||
|
||||
CLI takes a JSON literal. TOML uses a table or inline-table. CLI dicts deep-merge with TOML dicts — CLI keys win on conflict but don't wipe the file's keys:
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --orchestrator.train.env.0.args \
|
||||
uv run rl @ rl.toml --orchestrator.train.source.0.args \
|
||||
'{"dataset_name": "openai/gsm8k", "dataset_subset": "main"}'
|
||||
```
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
args = { dataset_name = "openai/gsm8k", dataset_subset = "main" }
|
||||
```
|
||||
|
||||
@@ -142,27 +142,30 @@ mu = 0.95
|
||||
|
||||
Omit `type` to keep the default variant.
|
||||
|
||||
### Environments (`[[orchestrator.train.env]]`)
|
||||
### Environments
|
||||
|
||||
Training environments are an array of tables — set one per env, optionally with sampling weights:
|
||||
Training and evaluation sources are arrays of tables. Set one source per environment; training sources can optionally carry sampling weights:
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "gsm8k"
|
||||
env.taskset = { id = "gsm8k-v1", split = "train" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
ratio = 3 # 75% of batches
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
ratio = 1 # default — 25% of batches
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "gsm8k-eval"
|
||||
env.taskset = { id = "gsm8k-v1", split = "test" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
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.
|
||||
|
||||
+12
-8
@@ -30,7 +30,9 @@ We support 3 distinct deployment shapes:
|
||||
|
||||
Most of the features are supported for all deployment shapes, with few exceptions. These exceptions are rejected on validation.
|
||||
|
||||
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape, deployment-specific knobs such as `num_nodes`, `num_replicas`, `backend_port`, and a `[...deployment.router]` block, etc.
|
||||
Every deployment shape has the same client-facing layout: a single global router listens on `inference.server.port` and fronts all vLLM engines, which listen on `inference.backend_port` (+ rank offset). Clients always talk to one URL, regardless of how many engines run behind it.
|
||||
|
||||
You can select the deployment shape with `InferenceDeploymentConfig` in your config file. This is a config-field that allows you to set the deployment shape and topology knobs such as `num_nodes` and `num_replicas`.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
@@ -56,6 +58,8 @@ The single-node deployment is the default deployment shape. It runs the inferenc
|
||||
type = "single_node"
|
||||
```
|
||||
|
||||
The launcher starts a `vllm-router` on `inference.server.port` (default `8000`) fronting the vLLM engine on `inference.backend_port` (default `8100`). Clients connect to the router URL; admin operations (weight updates, health checks) bypass the router and hit the engine port directly — the RL entrypoint wires `orchestrator.model.client.admin_base_url` accordingly.
|
||||
|
||||
This deployment shape runs the inference server on a single node, if configured with NVLink enabled, it allows you more freedom in terms of parallelism configurations.
|
||||
|
||||
```toml
|
||||
@@ -102,7 +106,7 @@ tp = 2
|
||||
dp = 4
|
||||
```
|
||||
|
||||
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a router instance running on the same node as the 1st replica — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[...deployment.router]` block. You can read more about the supported routing options in the [router](#router) section.
|
||||
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing is handled by a single global router running on the first inference node, fronting the per-rank endpoints of all replicas — either `vllm-router` (default) or the upstream `llm-d` EPP+Envoy, selected via the `[inference.router]` block. You can read more about the supported routing options in the [router](#router) section.
|
||||
|
||||
### Wide-EP
|
||||
|
||||
@@ -160,15 +164,15 @@ num_train_nodes = 4
|
||||
num_infer_replicas = 3
|
||||
```
|
||||
|
||||
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
|
||||
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes, fronted by the single global router.
|
||||
|
||||
|
||||
## Router
|
||||
|
||||
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
|
||||
Every deployment fronts its vLLM engines with a single global router — it listens on `inference.server.port` and is the one URL clients connect to. The backend is configured via a discriminated `[inference.router]` block (`type = "vllm-router" | "llm-d"`):
|
||||
|
||||
```toml
|
||||
[inference.deployment.router] # or [deployment.router] for the standalone inference entrypoint
|
||||
[inference.router] # or [router] for the standalone inference entrypoint
|
||||
type = "llm-d" # "vllm-router" (default) or "llm-d"
|
||||
# llm-d-only knobs (all optional):
|
||||
scorers = { "prefix-cache-scorer" = 3.0, "active-request-scorer" = 2.0 } # base, applied to every profile
|
||||
@@ -177,8 +181,8 @@ decode_scorer_overrides = {} # merged onto the P/D decode profile
|
||||
non_cached_tokens = 16 # below this many non-cached prompt tokens, skip remote prefill (P/D)
|
||||
```
|
||||
|
||||
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`.
|
||||
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy. Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
|
||||
- **`vllm-router`** (default) — our fork of [vllm-router](https://github.com/PrimeIntellect-ai/router). Knob: `policy`. The only backend supported for single-node (local) deployments.
|
||||
- **`llm-d`** — the upstream [llm-d](https://llm-d.ai) Endpoint Picker (EPP) + Envoy proxy (multi-node / disaggregated SLURM deployments only). Routing combines **prefix-cache affinity** (grouped rollouts reuse a cached prefix and skip prefill) with the **`active-request-scorer`** — an in-flight load balancer that spreads requests across ranks immediately, unlike the metrics-scraped `queue-scorer` / `kv-cache-utilization-scorer` / `load-aware-scorer` (which lag and concentrate bursts of same-prefix requests). The scorer weights follow the upstream llm-d P/D guide; tune via `scorers` (base) + `prefill_scorer_overrides` / `decode_scorer_overrides` (per-profile, P/D). Does not support `enable_return_routed_experts` (router replay).
|
||||
|
||||
Both backends support the 2 most important things:
|
||||
- Request routing - KV cache re-use and balanced routing
|
||||
@@ -279,6 +283,6 @@ enable_router_replay = true # this will also auto-set the inference.enable_retur
|
||||
enable_return_routed_experts = true
|
||||
```
|
||||
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend increasing `orchestrator.*.env.num_workers` to allow for more parallelization on the verifiers side.
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env-server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
|
||||
|
||||
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ A `prime-rl` RL run is three cooperating processes:
|
||||
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
|
||||
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
|
||||
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
|
||||
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses ZMQ, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap the rollout link to the local filesystem (`rollout_transport.type = "filesystem"`) if you want rollouts persisted to disk. See [Scaling](scaling.md) for the deployment options.
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
+1
-1
@@ -231,7 +231,7 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), and the launcher prints one URL per node. Front the URLs with a router or point clients at any of them.
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
### Custom Templates
|
||||
|
||||
|
||||
+7
-6
@@ -59,9 +59,9 @@ 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.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
|
||||
| `[[orchestrator.train.env]]` | Training environments. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Environments](configuration.md#environments-orchestratortrainenv). |
|
||||
| `[[orchestrator.eval.env]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
|
||||
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `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). |
|
||||
|
||||
**Monitoring:**
|
||||
|
||||
@@ -89,6 +89,7 @@ The RL entrypoint supports several training algorithms, switched via `[orchestra
|
||||
|---|---|---|
|
||||
| `grpo` (default) | None | Standard group-relative RL |
|
||||
| `max_rl` | None | [MaxRL](https://arxiv.org/abs/2602.02710): GRPO with mean-normalized advantages (maximum-likelihood RL) |
|
||||
| `rae` | None | [SPIRAL](https://arxiv.org/abs/2506.24119)'s role-conditioned advantage estimation: reward minus a per-agent EMA baseline, for multi-agent self-play envs (e.g. `kuhn-poker-v1`) |
|
||||
| `opd` | Required, must be vLLM (needs `prompt_logprobs`) | [On-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): the policy generates rollouts, the trainer minimizes per-token reverse KL to a reference model |
|
||||
| `sft` | Required, any OpenAI-compatible endpoint | Hard-distill: a frozen model generates rollouts, the policy trains on its tokens |
|
||||
| `opsd` | None — the live policy is its own reference (no deployment) | [SDFT](https://arxiv.org/abs/2601.19897): the model is its own reference conditioned on expert demonstrations |
|
||||
@@ -256,7 +257,7 @@ For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write t
|
||||
|
||||
### Log Files
|
||||
|
||||
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router_*.log` files):
|
||||
The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
|
||||
|
||||
```
|
||||
<output_dir>/logs/
|
||||
@@ -268,7 +269,7 @@ The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The f
|
||||
│ └── torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log # per-rank
|
||||
├── inference/
|
||||
│ ├── node_*.log # per-node inference stdout (multi-node only)
|
||||
│ └── router_*.log # vllm-router per replica (multi-node only)
|
||||
│ └── router.log # the single global router (multi-node only)
|
||||
└── envs/{train,eval}/<env_name>/
|
||||
├── env_server.log
|
||||
└── env_worker_<id>.log
|
||||
@@ -281,7 +282,7 @@ Live tailing from a single point (works on the head node for multi-node runs ove
|
||||
```bash
|
||||
tail -F <output_dir>/logs/{trainer,orchestrator,inference}.log
|
||||
tail -F <output_dir>/logs/trainer/node_*.log # multi-node only
|
||||
tail -F <output_dir>/logs/inference/router_*.log # multi-node only
|
||||
tail -F <output_dir>/logs/inference/router.log # multi-node only
|
||||
```
|
||||
|
||||
### Console Output
|
||||
|
||||
@@ -71,7 +71,7 @@ type = "muon"
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
max_inflight_episodes = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
@@ -93,14 +93,15 @@ num_turns_weight = 0.0
|
||||
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
|
||||
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
|
||||
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "openseeker"
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
|
||||
|
||||
[orchestrator.train.env.env.taskset]
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "openseeker-v1"
|
||||
|
||||
[[orchestrator.train.env.env.taskset.task.judges]]
|
||||
[[orchestrator.train.source.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
@@ -108,21 +109,22 @@ question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.env.taskset.task.judges]]
|
||||
# [[orchestrator.train.source.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "redsearcher"
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
|
||||
|
||||
[orchestrator.train.env.env.taskset]
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
|
||||
|
||||
[[orchestrator.train.env.env.taskset.task.judges]]
|
||||
[[orchestrator.train.source.env.taskset.task.judges]]
|
||||
id = "reference"
|
||||
name = "correct"
|
||||
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
|
||||
@@ -130,7 +132,7 @@ question_field = "question"
|
||||
choices = ["A", "B"]
|
||||
|
||||
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.env.taskset.task.judges]]
|
||||
# [[orchestrator.train.source.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
@@ -142,18 +144,19 @@ choices = ["A", "B"]
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.env.taskset]
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "browsecomp-v1"
|
||||
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.env.env.taskset.task.judges]]
|
||||
# [[orchestrator.eval.source.env.taskset.task.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
|
||||
@@ -82,7 +82,7 @@ type = "muon"
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
max_inflight_episodes = 512
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
@@ -97,10 +97,11 @@ num_turns_weight = 0.1
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset = { id = "scaleswe-v1" }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
@@ -109,10 +110,11 @@ env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
@@ -72,7 +72,7 @@ type = "muon"
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 512
|
||||
max_inflight_episodes = 512
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
@@ -91,22 +91,23 @@ num_turns_weight = 0.1
|
||||
|
||||
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "tmax"
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
|
||||
|
||||
[orchestrator.train.env.env.taskset]
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "tmax-v1"
|
||||
|
||||
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
|
||||
# [[orchestrator.train.env.env.taskset.judges]]
|
||||
# [[orchestrator.train.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.train.env.env.taskset.judges]]
|
||||
# [[orchestrator.train.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
@@ -118,45 +119,47 @@ id = "tmax-v1"
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.env.taskset]
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "swebench-verified-v1"
|
||||
|
||||
# [[orchestrator.eval.env.env.taskset.judges]]
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.env.taskset.judges]]
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "terminal-bench-2"
|
||||
group_size = 4 # avg@4
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.env.taskset]
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "terminal-bench-2-v1"
|
||||
|
||||
# [[orchestrator.eval.env.env.taskset.judges]]
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "rlm"
|
||||
# path = "deps/research-environments/rubrics/rlm.toml"
|
||||
# model = "zai-org/GLM-5.2"
|
||||
# weight = 0.0
|
||||
|
||||
# [[orchestrator.eval.env.env.taskset.judges]]
|
||||
# [[orchestrator.eval.source.env.taskset.judges]]
|
||||
# id = "rubric"
|
||||
# name = "swe"
|
||||
# path = "deps/research-environments/rubrics/swe.toml"
|
||||
|
||||
@@ -38,7 +38,7 @@ num_decode_replicas = 1
|
||||
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
|
||||
[deployment.router]
|
||||
[router]
|
||||
type = "llm-d"
|
||||
scorers = { "prefix-cache-scorer" = 3.0 }
|
||||
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 }
|
||||
|
||||
@@ -37,7 +37,7 @@ decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="
|
||||
prefill_vllm_overrides = {"enable_dbo"=true}
|
||||
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
|
||||
|
||||
[inference.deployment.router]
|
||||
[inference.router]
|
||||
type = "llm-d"
|
||||
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
|
||||
|
||||
@@ -81,7 +81,7 @@ weight_decay = 0.0
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_inflight_rollouts = 2048
|
||||
max_inflight_episodes = 2048
|
||||
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
|
||||
|
||||
[orchestrator.model]
|
||||
@@ -96,10 +96,11 @@ temperature = 1.0
|
||||
extra_body = {chat_template_kwargs = {clear_thinking = false}}
|
||||
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "r2e"
|
||||
env.taskset = { id = "r2e-gym-v1" }
|
||||
env.agent.harness = { id = "rlm", runtime = { type = "prime", labels = ["glm5-llmd"] } }
|
||||
env.agent.harness = { id = "rlm" }
|
||||
env.agent.runtime = { type = "prime", labels = ["glm5-llmd"] }
|
||||
|
||||
[inference]
|
||||
enable_expert_parallel = true
|
||||
|
||||
@@ -71,10 +71,11 @@ name = "zai-org/GLM-5-FP8"
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] }
|
||||
|
||||
[[orchestrator.post_batch_filters]]
|
||||
type = "gibberish"
|
||||
|
||||
@@ -47,35 +47,40 @@ weight_decay = 0.01
|
||||
batch_size = 2048
|
||||
oversampling_factor = 2
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
ratio = 0.3
|
||||
env.taskset = { id = "r2e-gym-v1" }
|
||||
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe"] }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "deepdive"
|
||||
ratio = 0.2
|
||||
env.taskset = { id = "deepdive-v1" }
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
|
||||
env.agent.harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"] }
|
||||
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
ratio = 0.3
|
||||
env.taskset = { id = "i3_math_v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "logic"
|
||||
ratio = 0.2
|
||||
env.taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "code"
|
||||
ratio = 0.2
|
||||
env.taskset = { id = "i3_code_v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
@@ -84,15 +89,17 @@ enforce = true
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] }
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2025"
|
||||
env.taskset = { id = "aime25-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
@@ -49,18 +49,20 @@ oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
env.taskset = { id = "r2e-gym-v1" }
|
||||
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe"] }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
|
||||
@@ -66,7 +66,7 @@ type = "adamw"
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
max_inflight_rollouts = 1536
|
||||
max_inflight_episodes = 1536
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
@@ -81,20 +81,22 @@ num_turns_weight = 0.1
|
||||
name = "nemotron-3"
|
||||
truncate_history_thinking = false
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset = { id = "scaleswe-v1" }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = [65536, 131072] }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] } }
|
||||
env.agent.harness = { id = "rlm", summarize_at_tokens = 98304 }
|
||||
env.agent.runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["nemotron-3-super-swe"] }
|
||||
env.agent.timeout = { rollout = 3600 }
|
||||
|
||||
[inference]
|
||||
|
||||
@@ -48,18 +48,20 @@ max_off_policy_steps = 8
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 32768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "math"
|
||||
env.taskset = { id = "i3_math_v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2025"
|
||||
env.taskset = { id = "aime25-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
tp = 8
|
||||
|
||||
@@ -46,18 +46,20 @@ batch_size = 512
|
||||
oversampling_factor = 2
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "swe"
|
||||
env.taskset = { id = "r2e-gym-v1" }
|
||||
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 25
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
env.taskset = { id = "swebench-verified-v1" }
|
||||
env.agent.harness = { id = "bash", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
|
||||
env.agent.harness = { id = "bash" }
|
||||
env.agent.runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] }
|
||||
|
||||
[inference.parallel]
|
||||
tp = 8
|
||||
tp = 8
|
||||
|
||||
@@ -35,9 +35,10 @@ batch_size = 512
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
env.taskset = { id = "general-agent-v1", task = { tools = { colocated = true } }, min_tier = 1 }
|
||||
env.agent.harness = { id = "null", runtime = { type = "modal" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "modal" }
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
@@ -31,9 +31,10 @@ group_size = 16
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[inference] # Default inference config
|
||||
|
||||
@@ -16,18 +16,20 @@ batch_size = 512
|
||||
group_size = 8
|
||||
seq_len = 8192
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
[[orchestrator.eval.source]]
|
||||
name = "aime2024"
|
||||
env.taskset = { id = "aime24-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
group_size = 32
|
||||
|
||||
[trainer.model]
|
||||
|
||||
@@ -15,10 +15,11 @@ group_size = 16
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
@@ -133,10 +133,11 @@ uv run eval wiki-search-v1 --harness.id null \
|
||||
The V1 taskset fixes the question bank and searchable corpus. You can replace its reference judge in `rl.toml`:
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
taskset = { id = "wiki-search-v1", task = { judges = [{ id = "reference", model = "openai/gpt-5.4-nano" }] } }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
harness = { id = "null" }
|
||||
runtime = { type = "subprocess" }
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
@@ -44,10 +44,11 @@ max_completion_tokens = 512
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "wiki-search"
|
||||
env.taskset = { id = "wiki-search-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
|
||||
@@ -18,10 +18,11 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "wordle"
|
||||
env.taskset = { id = "wordle-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.player.harness = { id = "null" }
|
||||
env.player.runtime = { type = "subprocess" }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -13,10 +13,11 @@ name = "reverse-text"
|
||||
[train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[train.env]]
|
||||
[[train.source]]
|
||||
name = "reverse-text"
|
||||
taskset = { id = "reverse-text-v1" }
|
||||
harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
@@ -10,7 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.8",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.2.1",
|
||||
"verifiers>=0.2.2.dev43",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -232,6 +232,27 @@ class MaxRLAlgoConfig(BaseAlgoConfig):
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
|
||||
class RAEAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["rae"] = "rae"
|
||||
"""RAE — role-conditioned advantage estimation (SPIRAL,
|
||||
https://arxiv.org/abs/2506.24119): scalar advantage = reward minus a
|
||||
per-agent EMA baseline of that agent's own rewards, consumed by the ``rl``
|
||||
loss component. The advantage estimator for multi-agent self-play envs
|
||||
(``kuhn-poker-v1`` and friends): in a zero-sum game the group mean is ~0
|
||||
whatever the policy does, so a group-relative baseline mixes the agents'
|
||||
opposite reward scales — a structural first-mover edge would read as
|
||||
permanent credit. Per-agent baselines measure each agent against its own
|
||||
expected reward instead. Works with any ``group_size`` (including 1)."""
|
||||
|
||||
action_loss_type: ClassVar[ActionLossType] = "rl"
|
||||
|
||||
decay: float = Field(0.95, ge=0.0, lt=1.0)
|
||||
"""EMA decay of the per-agent baselines (SPIRAL's α): after a trace is
|
||||
scored, its agent's baseline moves as ``baseline ← decay · baseline +
|
||||
(1 − decay) · reward``. Baselines start at 0 and live in orchestrator
|
||||
memory — a restart re-warms them over ~1/(1 − decay) traces per agent."""
|
||||
|
||||
|
||||
class OPDAlgoConfig(BaseAlgoConfig):
|
||||
type: Literal["opd"] = "opd"
|
||||
"""On-policy distillation: the per-token signal is the reverse KL to
|
||||
@@ -305,7 +326,7 @@ class SFTAlgoConfig(BaseAlgoConfig):
|
||||
|
||||
|
||||
AlgoConfig: TypeAlias = Annotated[
|
||||
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
|
||||
GRPOAlgoConfig | EchoAlgoConfig | MaxRLAlgoConfig | RAEAlgoConfig | OPDAlgoConfig | OPSDAlgoConfig | SFTAlgoConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
"""The training algorithm: sampling plus the per-token training signal (credit
|
||||
@@ -314,6 +335,7 @@ its class defaults are the vetted setting.
|
||||
|
||||
- ``grpo`` — policy group sampling, group-relative advantage, RL loss (the default).
|
||||
- ``max_rl`` — GRPO with mean-normalized advantages (maximum-likelihood RL).
|
||||
- ``rae`` — reward minus a per-agent EMA baseline (SPIRAL), for multi-agent self-play envs.
|
||||
- ``opd`` — on-policy distillation: policy samples, per-token reverse KL against a reference model. Needs ``teacher``.
|
||||
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
|
||||
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
|
||||
|
||||
@@ -190,9 +190,6 @@ class VllmRouterConfig(BaseConfig):
|
||||
|
||||
type: Literal["vllm-router"] = "vllm-router"
|
||||
|
||||
port: int = 8000
|
||||
"""Port the router listens on — becomes the client-facing router URL."""
|
||||
|
||||
policy: str = "consistent_hash"
|
||||
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
|
||||
|
||||
@@ -202,9 +199,6 @@ class LlmdRouterConfig(BaseConfig):
|
||||
|
||||
type: Literal["llm-d"] = "llm-d"
|
||||
|
||||
port: int = 8000
|
||||
"""Port the Envoy gateway listens on — becomes the client-facing router URL."""
|
||||
|
||||
scorers: dict[str, float] = {
|
||||
"prefix-cache-scorer": 3.0,
|
||||
"active-request-scorer": 2.0,
|
||||
@@ -254,12 +248,6 @@ class BaseInferenceDeploymentConfig(BaseConfig):
|
||||
gpus_per_node: int = 8
|
||||
"""GPUs per node."""
|
||||
|
||||
backend_port: int = 8100
|
||||
"""Port for the per-rank vLLM backend instances."""
|
||||
|
||||
router: RouterConfig = VllmRouterConfig()
|
||||
"""Router fronting the per-rank endpoints."""
|
||||
|
||||
|
||||
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
type: Literal["single_node"] = "single_node"
|
||||
@@ -331,6 +319,12 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
|
||||
class InferenceConfig(BaseConfig):
|
||||
server: ServerConfig = ServerConfig()
|
||||
|
||||
router: RouterConfig | None = Field(default_factory=VllmRouterConfig)
|
||||
"""Router fronting the engine(s). Every deployment runs a single global router as the client-facing endpoint on ``server.port``, with the engines listening on ``backend_port``. Set to ``None`` to run a bare engine on ``server.port`` without a router (the SLURM launchers do this for per-rank engine processes; the sbatch script starts the router)."""
|
||||
|
||||
backend_port: int = 8100
|
||||
"""Port for the vLLM engine(s) behind the router. Defaults to ``server.port + 100``. Multi-node deployments start one engine per local DP rank at ``backend_port + rank``."""
|
||||
|
||||
model: ModelConfig = Field(default_factory=ModelConfig)
|
||||
|
||||
parallel: ParallelConfig = ParallelConfig()
|
||||
@@ -438,8 +432,7 @@ class InferenceConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def validate_llmd_no_routed_experts(self):
|
||||
"""Reject routed-expert return with the llm-d router (breaks P/D, unverified for multi-node)."""
|
||||
router = getattr(self.deployment, "router", None)
|
||||
if router is not None and router.type == "llm-d" and self.enable_return_routed_experts:
|
||||
if self.router is not None and self.router.type == "llm-d" and self.enable_return_routed_experts:
|
||||
raise ValueError(
|
||||
"The llm-d router backend does not support routed-expert return "
|
||||
"(enable_return_routed_experts): it breaks P/D and is unverified for multi-node. "
|
||||
@@ -447,6 +440,21 @@ class InferenceConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_router_deployment(self):
|
||||
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
|
||||
if self.router is not None and self.router.type == "llm-d" and self.deployment.type == "single_node":
|
||||
raise ValueError("The llm-d router backend requires a multi-node or disaggregated SLURM deployment.")
|
||||
if self.router is None and self.deployment.type in ("multi_node", "disaggregated"):
|
||||
raise ValueError("Multi-node / disaggregated deployments require a router fronting the per-rank engines.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_backend_port(self):
|
||||
if self.router is not None and "backend_port" not in self.model_fields_set:
|
||||
self.backend_port = self.server.port + 100
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_kv_cache_offload(self):
|
||||
if self.kv_cache_offload is not None:
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.algorithm import (
|
||||
@@ -15,12 +14,12 @@ from prime_rl.configs.shared import (
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
PrimeMonitorConfig,
|
||||
TransportConfig,
|
||||
WandbWithExtrasConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import TokenizerConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
@@ -54,9 +53,7 @@ class TrainSamplingConfig(BaseConfig):
|
||||
temperature: float = Field(1.0, ge=0, le=2.0)
|
||||
"""Sampling temperature."""
|
||||
|
||||
max_completion_tokens: int | None = Field(
|
||||
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
|
||||
)
|
||||
max_completion_tokens: int | None = None
|
||||
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
|
||||
|
||||
# Strictly speaking, extra_body is not a sampling parameter, but it is the
|
||||
@@ -79,18 +76,6 @@ class TrainSamplingConfig(BaseConfig):
|
||||
|
||||
return args
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _deprecate_max_tokens(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
|
||||
warnings.warn(
|
||||
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
class EvalSamplingConfig(BaseConfig):
|
||||
temperature: float | None = Field(None, ge=0, le=2.0)
|
||||
@@ -105,9 +90,7 @@ class EvalSamplingConfig(BaseConfig):
|
||||
min_p: float | None = Field(None, ge=0)
|
||||
"""Min-p sampling threshold. None defers to the inference server default."""
|
||||
|
||||
max_completion_tokens: int | None = Field(
|
||||
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
|
||||
)
|
||||
max_completion_tokens: int | None = None
|
||||
"""Maximum output tokens per turn. None defers to the inference server default."""
|
||||
|
||||
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
|
||||
@@ -138,40 +121,53 @@ class EvalSamplingConfig(BaseConfig):
|
||||
|
||||
return args
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _deprecate_max_tokens(cls, data: Any) -> Any:
|
||||
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
|
||||
warnings.warn(
|
||||
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
class EnvConfig(vf.EnvServerConfig):
|
||||
name: str | None = None
|
||||
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
|
||||
class ServingConfig(vf.ServingConfig):
|
||||
"""Verifiers' serving block with ``address`` back to optional. Verifiers defaults it
|
||||
to the address its own ``serve`` CLI binds; here the question is whether to spawn a
|
||||
server or connect to one already running, and that answer has to survive the
|
||||
resolved config being written to a file and read back — so it must be a *value*
|
||||
(``None``), not field-set metadata, which a round-trip drops."""
|
||||
|
||||
address: str | None = None
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically. The ``pool`` sizes the spawned server."""
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to that server instead of spawning one; when None, it spawns a subprocess env server on a free port. ``pool`` sizes the spawned server."""
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
"""One environment a run pulls from: the verifiers blocks it composes (``env`` — what
|
||||
runs, ``serve`` — how it's hosted, ``legacy`` — a classic v0 env instead) plus this
|
||||
orchestrator's own per-env knobs."""
|
||||
|
||||
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
|
||||
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
|
||||
serve: ServingConfig = ServingConfig()
|
||||
"""How the env server is run: ``serve.pool`` sizes the spawned server, ``serve.address`` points at an external one instead, and ``serve.max_concurrent`` bounds one worker's episodes in flight (unset = unbounded; the dispatcher's ``max_inflight_episodes`` is the run's bound)."""
|
||||
|
||||
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
|
||||
"""A classic (v0) environment to run through the bridge instead of ``env``."""
|
||||
|
||||
name: str | None = None
|
||||
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
|
||||
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _migrate_num_workers(cls, data):
|
||||
"""Back-compat: the removed ``num_workers`` maps onto ``pool`` — an int becomes a
|
||||
fixed ``static`` pool, ``"auto"`` falls through to the default ``elastic`` pool. An
|
||||
explicit ``pool`` always wins."""
|
||||
if isinstance(data, dict) and "num_workers" in data:
|
||||
num_workers = data.pop("num_workers")
|
||||
if "pool" not in data and num_workers != "auto":
|
||||
data["pool"] = {"type": "static", "num_workers": num_workers}
|
||||
return data
|
||||
def _resolve_env(cls, data):
|
||||
"""Narrow ``env`` to the selected env's config class."""
|
||||
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
|
||||
|
||||
@property
|
||||
def is_legacy(self) -> bool:
|
||||
"""A classic (v0) env run through the bridge: a legacy id and no v1 taskset."""
|
||||
return self.legacy.id is not None and not self.env.taskset.id
|
||||
|
||||
@property
|
||||
def env_id(self) -> str:
|
||||
"""The env's identifier: the v1 env's, else the v0 env id."""
|
||||
return self.env.env_id or self.legacy.id or ""
|
||||
|
||||
@property
|
||||
def resolved_name(self) -> str:
|
||||
@@ -179,9 +175,24 @@ class EnvConfig(vf.EnvServerConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env(self):
|
||||
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
|
||||
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
|
||||
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
|
||||
if self.legacy.id is not None and self.env.env_id:
|
||||
if self.env.taskset.id:
|
||||
raise ValueError(
|
||||
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
|
||||
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
|
||||
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
|
||||
)
|
||||
raise ValueError(
|
||||
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
|
||||
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
|
||||
"env's name. Keep whichever one you meant to run."
|
||||
)
|
||||
if not self.env_id:
|
||||
raise ValueError(
|
||||
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or id = "<id>" (v0/legacy)'
|
||||
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
|
||||
)
|
||||
if self.resolved_name == "agg":
|
||||
raise ValueError(
|
||||
@@ -192,25 +203,25 @@ class EnvConfig(vf.EnvServerConfig):
|
||||
@model_validator(mode="after")
|
||||
def resolve_legacy_env_kwargs(self):
|
||||
"""For a v0/legacy env, surface the v1 knobs the legacy bridge applies via
|
||||
``extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock timeout and
|
||||
the multi-turn completion-token budget, read off ``env.agent``. (``max_seq_len`` is
|
||||
added per train run in ``OrchestratorConfig.resolve_env_config``, which knows
|
||||
``seq_len``.)"""
|
||||
``legacy.extra_env_kwargs`` (``env.set_kwargs(...)``): the per-rollout wall-clock
|
||||
timeout and the multi-turn completion-token budget, read off ``env.agent``.
|
||||
(``max_seq_len`` is added per train run in ``OrchestratorConfig.resolve_env_config``,
|
||||
which knows ``seq_len``.)"""
|
||||
if self.is_legacy:
|
||||
agent = getattr(self.env, "agent", None)
|
||||
if agent is not None:
|
||||
if agent.timeout.rollout is not None:
|
||||
self.extra_env_kwargs["timeout_seconds"] = agent.timeout.rollout
|
||||
self.legacy.extra_env_kwargs["timeout_seconds"] = agent.timeout.rollout
|
||||
if agent.max_output_tokens is not None:
|
||||
self.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
|
||||
self.legacy.extra_env_kwargs["max_total_completion_tokens"] = agent.max_output_tokens
|
||||
return self
|
||||
|
||||
|
||||
class TrainEnvConfig(EnvConfig):
|
||||
class TrainSourceConfig(EnvConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
|
||||
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Rollouts generated per example for GRPO group-relative advantages.
|
||||
Inherits from ``orchestrator.group_size`` when unset."""
|
||||
|
||||
@@ -220,14 +231,14 @@ class TrainEnvConfig(EnvConfig):
|
||||
this env its own algorithm."""
|
||||
|
||||
|
||||
class EvalEnvConfig(EnvConfig):
|
||||
class EvalSourceConfig(EnvConfig):
|
||||
sampling: EvalSamplingConfig = EvalSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
|
||||
|
||||
num_examples: int = -1
|
||||
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
|
||||
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
@@ -235,8 +246,8 @@ class EvalEnvConfig(EnvConfig):
|
||||
|
||||
|
||||
class TrainConfig(BaseConfig):
|
||||
env: list[TrainEnvConfig] = Field(default_factory=list)
|
||||
"""Training environments."""
|
||||
source: list[TrainSourceConfig] = Field(default_factory=list)
|
||||
"""Training sources."""
|
||||
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
@@ -246,7 +257,7 @@ class TrainConfig(BaseConfig):
|
||||
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
|
||||
is configured per env, defaulting to elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
for env in self.source:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
env.sampling = TrainSamplingConfig(**group_sampling)
|
||||
else:
|
||||
@@ -256,7 +267,7 @@ class TrainConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [env.resolved_name for env in self.env]
|
||||
env_names = [env.resolved_name for env in self.source]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(
|
||||
@@ -266,8 +277,8 @@ class TrainConfig(BaseConfig):
|
||||
|
||||
|
||||
class EvalConfig(BaseConfig):
|
||||
env: list[EvalEnvConfig] = Field(default_factory=list)
|
||||
"""Evaluation environments."""
|
||||
source: list[EvalSourceConfig] = Field(default_factory=list)
|
||||
"""Evaluation sources."""
|
||||
|
||||
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
|
||||
"""Shared eval sampling configuration; can differ from training sampling."""
|
||||
@@ -275,7 +286,7 @@ class EvalConfig(BaseConfig):
|
||||
num_examples: int = -1
|
||||
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
|
||||
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
@@ -290,33 +301,33 @@ class EvalConfig(BaseConfig):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
|
||||
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
env.sampling = EvalSamplingConfig(**group_sampling)
|
||||
for source in self.source:
|
||||
if "sampling" not in source.model_fields_set:
|
||||
source.sampling = EvalSamplingConfig(**group_sampling)
|
||||
else:
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = EvalSamplingConfig(**merged)
|
||||
if "num_examples" not in env.model_fields_set:
|
||||
env.num_examples = self.num_examples
|
||||
if "group_size" not in env.model_fields_set:
|
||||
env.group_size = self.group_size
|
||||
if "interval" not in env.model_fields_set:
|
||||
env.interval = self.interval
|
||||
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
|
||||
source.sampling = EvalSamplingConfig(**merged)
|
||||
if "num_examples" not in source.model_fields_set:
|
||||
source.num_examples = self.num_examples
|
||||
if "group_size" not in source.model_fields_set:
|
||||
source.group_size = self.group_size
|
||||
if "interval" not in source.model_fields_set:
|
||||
source.interval = self.interval
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_non_empty_envs(self):
|
||||
if not self.env:
|
||||
def validate_non_empty_sources(self):
|
||||
if not self.source:
|
||||
raise ValueError(
|
||||
"EvalConfig must define at least one env. Either drop the "
|
||||
"EvalConfig must define at least one source. Either drop the "
|
||||
"[orchestrator.eval] block entirely (to disable eval) or "
|
||||
"add a [[orchestrator.eval.env]] block."
|
||||
"add a [[orchestrator.eval.source]] block."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [env.resolved_name for env in self.env]
|
||||
env_names = [source.resolved_name for source in self.source]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(
|
||||
@@ -437,7 +448,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
algo: AlgoConfig = GRPOAlgoConfig()
|
||||
"""Training algorithm: sampling plus the per-token training signal (credit
|
||||
assignment and loss routing, fused — its ``type`` names the algorithm).
|
||||
Defaults to ``grpo``. Override per env via ``[[orchestrator.train.env]]``'s
|
||||
Defaults to ``grpo``. Override per source via ``[[orchestrator.train.source]]``'s
|
||||
``algo``."""
|
||||
|
||||
model: ModelConfig = ModelConfig()
|
||||
@@ -509,7 +520,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
"""Transport used to receive updated weights from the trainer."""
|
||||
|
||||
rollout_transport: TransportConfig = FileSystemTransportConfig()
|
||||
rollout_transport: TransportConfig = ZMQTransportConfig()
|
||||
"""Transport used to ship rollouts from orchestrator to trainer."""
|
||||
|
||||
output_dir: Path = Path("outputs/run_default")
|
||||
@@ -525,12 +536,12 @@ class OrchestratorConfig(BaseConfig):
|
||||
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
|
||||
|
||||
oversampling_factor: float | None = Field(None, gt=0)
|
||||
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_rollouts`` from ``batch_size`` when ``max_inflight_rollouts`` is unset. Values below 1.0 intentionally cap in-flight rollout capacity below ``batch_size``."""
|
||||
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_episodes`` from ``batch_size`` when ``max_inflight_episodes`` is unset. Values below 1.0 intentionally cap in-flight episode capacity below ``batch_size``."""
|
||||
|
||||
max_inflight_rollouts: int | None = Field(None, ge=1)
|
||||
"""Maximum number of rollouts kept in-flight. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
|
||||
max_inflight_episodes: int | None = Field(None, ge=1)
|
||||
"""Maximum number of episodes kept in-flight — one episode is one agent run at a time, whatever the env's agents are. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
|
||||
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Output sequences returned per example during training."""
|
||||
|
||||
seq_len: int = 2048
|
||||
@@ -552,33 +563,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _env_to_train(cls, data: Any) -> Any:
|
||||
"""Allow [[env]] and [sampling] as shorthand for [train] with [[train.env]] and [train.sampling]."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
if "env" in data or "sampling" in data:
|
||||
train = data.setdefault("train", {})
|
||||
if isinstance(train, dict):
|
||||
if "env" in data:
|
||||
warnings.warn(
|
||||
"'[[orchestrator.env]]' is deprecated, use '[[orchestrator.train.env]]' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
train.setdefault("env", data.pop("env"))
|
||||
if "sampling" in data:
|
||||
warnings.warn(
|
||||
"'[orchestrator.sampling]' is deprecated, use '[orchestrator.train.sampling]' instead. "
|
||||
"Auto-translating for now, but this will be removed in a future release.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
train.setdefault("sampling", data.pop("sampling"))
|
||||
return data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_tokenizer(self):
|
||||
if self.tokenizer.name is None:
|
||||
@@ -617,7 +601,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
def inherit_env_algorithms(self):
|
||||
"""Envs without their own algorithm inherit the top-level one.
|
||||
Declared before any validator that reads ``algo``."""
|
||||
for env_cfg in self.train.env:
|
||||
for env_cfg in self.train.source:
|
||||
if env_cfg.algo is None:
|
||||
env_cfg.algo = self.algo.model_copy(deep=True)
|
||||
return self
|
||||
@@ -625,7 +609,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
@property
|
||||
def any_policy_sourced(self) -> bool:
|
||||
"""True when at least one train env samples rollouts from the live policy."""
|
||||
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.env)
|
||||
return any(env.algo is not None and env.algo.sampling.source == "policy" for env in self.train.source)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_pool_size(self):
|
||||
@@ -691,29 +675,29 @@ class OrchestratorConfig(BaseConfig):
|
||||
if has_token_batch:
|
||||
if self.oversampling_factor is not None:
|
||||
raise ValueError("oversampling_factor can only be set when batch_size is set")
|
||||
if self.max_inflight_rollouts is None:
|
||||
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
|
||||
if self.max_inflight_episodes is None:
|
||||
raise ValueError("max_inflight_episodes must be set when token_batch_size is set")
|
||||
else:
|
||||
assert self.batch_size is not None
|
||||
if self.batch_size % self.group_size != 0:
|
||||
raise ValueError("Batch size must be divisible by the number of samples per problem")
|
||||
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
|
||||
resolved_max_inflight_rollouts = max(
|
||||
resolved_max_inflight_episodes = max(
|
||||
self.group_size,
|
||||
int(self.batch_size * oversampling_factor),
|
||||
)
|
||||
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
|
||||
expected_max_inflight_rollouts = resolved_max_inflight_rollouts
|
||||
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
|
||||
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
|
||||
if self.max_inflight_rollouts is None:
|
||||
self.max_inflight_rollouts = resolved_max_inflight_rollouts
|
||||
if self.max_inflight_episodes is not None and self.oversampling_factor is not None:
|
||||
expected_max_inflight_episodes = resolved_max_inflight_episodes
|
||||
if self.max_inflight_episodes != expected_max_inflight_episodes:
|
||||
raise ValueError("max_inflight_episodes conflicts with oversampling_factor * batch_size")
|
||||
if self.max_inflight_episodes is None:
|
||||
self.max_inflight_episodes = resolved_max_inflight_episodes
|
||||
|
||||
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.group_size:
|
||||
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
|
||||
if self.max_inflight_episodes is not None and self.max_inflight_episodes < self.group_size:
|
||||
raise ValueError("max_inflight_episodes must be at least the number of rollouts per example")
|
||||
|
||||
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
|
||||
for env_cfg in self.train.env:
|
||||
for env_cfg in self.train.source:
|
||||
if "group_size" not in env_cfg.model_fields_set:
|
||||
env_cfg.group_size = self.group_size
|
||||
|
||||
@@ -736,7 +720,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_config(self):
|
||||
"""Set vLLM sampling defaults + legacy env kwargs on each train env from top-level fields."""
|
||||
for env in self.train.env:
|
||||
for env in self.train.source:
|
||||
# Policy-sourced rollouts hit our vLLM server; frozen-sourced
|
||||
# rollouts may hit external OAI endpoints that reject these knobs.
|
||||
assert env.algo is not None
|
||||
@@ -746,6 +730,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
env.sampling.extra_body.setdefault("return_token_ids", True)
|
||||
if env.is_legacy:
|
||||
# v0 env: cap per-turn response tokens to the training budget (the legacy
|
||||
# bridge applies extra_env_kwargs via env.set_kwargs).
|
||||
env.extra_env_kwargs["max_seq_len"] = self.seq_len
|
||||
# bridge applies legacy.extra_env_kwargs via env.set_kwargs).
|
||||
env.legacy.extra_env_kwargs["max_seq_len"] = self.seq_len
|
||||
return self
|
||||
|
||||
@@ -22,6 +22,7 @@ from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
SlurmConfig,
|
||||
TransportConfig,
|
||||
VLMConfig,
|
||||
)
|
||||
from prime_rl.configs.trainer import (
|
||||
@@ -260,6 +261,8 @@ class RLConfig(BaseConfig):
|
||||
|
||||
weight_broadcast: SharedWeightBroadcastConfig | None = None
|
||||
|
||||
rollout_transport: TransportConfig | None = None
|
||||
|
||||
bench: bool = False
|
||||
"""Benchmark mode. Sets trainer and orchestrator to benchmark mode and, when set, suffixes the W&B project with ``-bench``."""
|
||||
|
||||
@@ -419,6 +422,28 @@ class RLConfig(BaseConfig):
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_rollout_transport(self):
|
||||
"""Resolve the shared ``rollout_transport`` from the sub-configs so the launcher can
|
||||
gate multi-node ZMQ host injection on it (mirrors ``auto_setup_weight_broadcast``).
|
||||
|
||||
``rollout_transport`` may be set either as the shared block (propagated down to both
|
||||
sub-configs by ``propagate_shared_fields``) or directly on
|
||||
``trainer.rollout_transport`` / ``orchestrator.rollout_transport`` (the documented
|
||||
fallback). Either way the shared field must reflect the resolved per-component
|
||||
transport, otherwise the launcher would leave ZMQ trainers connecting to localhost.
|
||||
"""
|
||||
if self.trainer.rollout_transport.type != self.orchestrator.rollout_transport.type:
|
||||
raise ValueError(
|
||||
"trainer.rollout_transport.type "
|
||||
f"({self.trainer.rollout_transport.type!r}) != orchestrator.rollout_transport.type "
|
||||
f"({self.orchestrator.rollout_transport.type!r}); set the shared [rollout_transport] "
|
||||
"block or make both sub-configs the same type."
|
||||
)
|
||||
if self.rollout_transport is None:
|
||||
self.rollout_transport = self.trainer.rollout_transport
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_eplb_requires_quantized_weight_transfer(self):
|
||||
if self.inference is None or not self.inference.enable_eplb:
|
||||
@@ -529,7 +554,7 @@ class RLConfig(BaseConfig):
|
||||
(after InferenceConfig's own validators, which therefore miss it).
|
||||
"""
|
||||
if self.inference is not None and self.inference.enable_return_routed_experts:
|
||||
router = getattr(self.inference.deployment, "router", None)
|
||||
router = self.inference.router
|
||||
if router is not None and router.type == "llm-d":
|
||||
raise ValueError(
|
||||
"The llm-d router backend does not support routed-expert return "
|
||||
@@ -539,6 +564,12 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_multi_node_requires_router(self):
|
||||
if self.deployment.type == "multi_node" and self.inference is not None and self.inference.router is None:
|
||||
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_router_replay_without_kv_offload(self):
|
||||
if (
|
||||
@@ -707,27 +738,27 @@ class RLConfig(BaseConfig):
|
||||
def auto_setup_inference_client(self):
|
||||
"""Auto-configure the orchestrator policy client from the inference server config.
|
||||
|
||||
Direct single-node runs expose all local DP ranks behind one base URL,
|
||||
so pin logical clients with ``X-data-parallel-rank``. Multi-node SLURM
|
||||
runs expose a vllm-router URL instead; the router balances across
|
||||
per-rank backend URLs and forwards request headers, so the orchestrator
|
||||
must not inject a DP-rank header there. When no train env samples from
|
||||
the policy (e.g. sft_distill), also set base_url — policy-sourced
|
||||
algorithms rely on the ClientConfig default (``["http://localhost:8000/v1"]``)
|
||||
which already matches the auto-launched policy vLLM at inference.server.port = 8000.
|
||||
When no train env samples from the policy (e.g. sft_distill), set
|
||||
base_url. Policy-sourced algorithms rely on the ClientConfig default
|
||||
(``["http://localhost:8000/v1"]``), which already matches the
|
||||
auto-launched policy router at inference.server.port = 8000.
|
||||
"""
|
||||
if self.inference is None:
|
||||
return self
|
||||
client = self.orchestrator.model.client
|
||||
if "dp_rank_count" not in client.model_fields_set:
|
||||
if self.deployment.type == "multi_node":
|
||||
client.dp_rank_count = 1
|
||||
else:
|
||||
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
|
||||
if not self.orchestrator.any_policy_sourced and "base_url" not in client.model_fields_set:
|
||||
host = self.inference.server.host or "localhost"
|
||||
port = self.inference.server.port
|
||||
client.base_url = [f"http://{host}:{port}/v1"]
|
||||
if (
|
||||
self.deployment.type == "single_node"
|
||||
and self.inference.router is not None
|
||||
and "admin_base_url" not in client.model_fields_set
|
||||
):
|
||||
# Admin ops (pause/update_weights/resume) must bypass the router and hit
|
||||
# the engine directly; multi-node runs get ADMIN_URLS from the sbatch.
|
||||
host = self.inference.server.host or "localhost"
|
||||
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -141,9 +141,6 @@ class ClientConfig(BaseConfig):
|
||||
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``."""
|
||||
|
||||
dp_rank_count: int = Field(1, ge=1)
|
||||
"""Number of data-parallel ranks behind each base URL. When > 1, each URL is expanded into ``dp_rank_count`` logical clients pinned via the ``X-data-parallel-rank`` header, so every request within a rollout hits the same DP engine and reuses KV cache. Auto-set from the inference config when using the RL entrypoint."""
|
||||
|
||||
admin_base_url: list[str] | None = None
|
||||
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in disaggregated P/D deployments where the router must not handle admin traffic."""
|
||||
|
||||
|
||||
@@ -8,12 +8,12 @@ from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
TrainerLogConfig,
|
||||
TransportConfig,
|
||||
WandbConfig,
|
||||
ZMQTransportConfig,
|
||||
)
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
@@ -582,7 +582,7 @@ class TrainerConfig(BaseConfig):
|
||||
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
|
||||
"""Transport used to broadcast updated weights from trainer to inference."""
|
||||
|
||||
rollout_transport: TransportConfig = FileSystemTransportConfig()
|
||||
rollout_transport: TransportConfig = ZMQTransportConfig()
|
||||
"""Transport used to ship rollouts from orchestrator to trainer."""
|
||||
|
||||
log: TrainerLogConfig = TrainerLogConfig()
|
||||
|
||||
@@ -126,6 +126,9 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
"inference.model.chat_template",
|
||||
)
|
||||
|
||||
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
|
||||
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
|
||||
|
||||
# Top-level scalars.
|
||||
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
|
||||
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers[harbor]>=0.2.1",
|
||||
"verifiers[harbor]>=0.2.2.dev43",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
|
||||
+12
-5
@@ -30,7 +30,7 @@ uv run rl @ rl.toml --dry-run --output-dir /tmp/x # write resolved TOML to /tmp/
|
||||
|
||||
## Validators
|
||||
|
||||
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, emit a deprecation warning with a migration hint — never silently drop.
|
||||
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, remove the old spelling: no `validation_alias`, no auto-translating `mode="before"` validator. The old key then fails as an unknown key, which is the signal. An alias that stays forever is worse than a break — it never gets retired, and a key whose *meaning* changed silently misconfigures the run.
|
||||
|
||||
## Special syntax
|
||||
|
||||
@@ -41,19 +41,26 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
|
||||
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
|
||||
|
||||
```toml
|
||||
[[orchestrator.train.env]]
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text-eval"
|
||||
env.taskset = { id = "reverse-text-v1", split = "test" }
|
||||
env.agent.harness = { id = "null" }
|
||||
env.agent.runtime = { type = "subprocess" }
|
||||
```
|
||||
|
||||
CLI: `--orchestrator.train.env.0.env.taskset.id reverse-text-v1`.
|
||||
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text-v1` or `--orchestrator.eval.source.0.env.taskset.id reverse-text-v1`.
|
||||
|
||||
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
|
||||
|
||||
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
|
||||
|
||||
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-env override: `[orchestrator.train.env.algo] type = "opd"` (the env assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
|
||||
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
|
||||
|
||||
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
|
||||
|
||||
### llm-d router backend
|
||||
|
||||
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[...deployment.router] type = "llm-d"`). It needs three native binaries — install once:
|
||||
Multi-node / disaggregated deployments can route through the upstream llm-d Endpoint Picker instead of `vllm-router` (set `[inference.router] type = "llm-d"`). It needs three native binaries — install once:
|
||||
|
||||
```bash
|
||||
bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy
|
||||
|
||||
@@ -72,7 +72,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
│ └── torchrun/ # per-rank stdout/stderr
|
||||
├── inference/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
│ └── router_0.log # vllm-router per replica (multi-node only)
|
||||
│ └── router.log # the single global router (multi-node only; single-node logs it in inference.log)
|
||||
└── envs/{train,eval}/{env_name}.log # one log file per env
|
||||
```
|
||||
|
||||
@@ -93,13 +93,13 @@ All metrics print to the console log (and W&B when configured).
|
||||
|
||||
| Metric | Description |
|
||||
|--------|-------------|
|
||||
| `train/agg/all/reward/mean` | mean training reward (per env: `train/<env>/all/reward/mean`) |
|
||||
| `train/agg/all/num_total_tokens/mean` | avg tokens per rollout (also `num_input_tokens`, `num_output_tokens`) |
|
||||
| `train/agg/all/num_turns/mean` | avg turns per rollout (multi-turn only) |
|
||||
| `train/agg/all/is_truncated/mean` | fraction truncated |
|
||||
| `train/agg/effective/reward/mean` | mean training reward (per env: `train/<env>/effective/reward/mean`) |
|
||||
| `train/agg/effective/num_total_tokens/mean` | avg tokens per rollout (also `num_input_tokens`, `num_output_tokens`) |
|
||||
| `train/agg/effective/num_turns/mean` | avg turns per rollout (multi-turn only) |
|
||||
| `train/agg/effective/is_truncated/mean` | fraction truncated |
|
||||
| `train/agg/all/has_error/mean` | fraction errored (per-type under `train/agg/all/error/<type>`; also `dispatcher/errored/{train,eval}`) |
|
||||
| `train/<env>/all/metrics/<name>/mean` | env-specific metrics (e.g. pass rate) |
|
||||
| `eval/<env>/all/{avg@k,pass@k}` | eval scores when configured |
|
||||
| `train/<env>/effective/metrics/<name>/mean` | env-specific metrics (e.g. pass rate) |
|
||||
| `eval/<env>/effective/{avg@k,pass@k}` | eval scores when configured |
|
||||
|
||||
**Stability** — trainer log:
|
||||
|
||||
@@ -126,7 +126,7 @@ All metrics print to the console log (and W&B when configured).
|
||||
For live vLLM stats, query Prometheus directly:
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
|
||||
curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage" # engine port (8000 is the router)
|
||||
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
|
||||
```
|
||||
|
||||
@@ -154,7 +154,7 @@ jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
|
||||
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
|
||||
```
|
||||
|
||||
The binary batches consumed by the trainer still live at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
|
||||
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
|
||||
|
||||
### Common failure modes
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
|
||||
|
||||
## `inference` — vLLM server
|
||||
|
||||
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly.
|
||||
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
|
||||
|
||||
```bash
|
||||
uv run inference --model.name Qwen/Qwen3-0.6B
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from threading import Event, Thread
|
||||
from typing import Any
|
||||
|
||||
import tomli_w
|
||||
@@ -11,7 +13,12 @@ from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, DEFAULT_INFERENCE_ENV_VARS, set_proc_title
|
||||
from prime_rl.utils.process import (
|
||||
DEFAULT_COMMON_ENV_VARS,
|
||||
DEFAULT_INFERENCE_ENV_VARS,
|
||||
cleanup_processes,
|
||||
set_proc_title,
|
||||
)
|
||||
|
||||
INFERENCE_TOML = "inference.toml"
|
||||
INFERENCE_SBATCH = "inference.sbatch"
|
||||
@@ -28,12 +35,21 @@ def vllm_overrides_fragment(overrides: dict[str, Any]) -> str:
|
||||
return ", " + json.dumps(overrides)[1:-1].replace('"', '\\"')
|
||||
|
||||
|
||||
def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None) -> Path:
|
||||
"""Write resolved config to disk."""
|
||||
def write_config(
|
||||
config: InferenceConfig, output_dir: Path, exclude: set[str] | None = None, engine_only: bool = False
|
||||
) -> Path:
|
||||
"""Write resolved config to disk.
|
||||
|
||||
With ``engine_only``, the router is nulled so per-rank processes run bare
|
||||
engines — the sbatch script starts the single global router.
|
||||
"""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_path = output_dir / INFERENCE_TOML
|
||||
toml_dict = to_toml_dict(config, exclude=exclude)
|
||||
if engine_only:
|
||||
toml_dict["router"] = "None"
|
||||
with open(config_path, "wb") as f:
|
||||
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
|
||||
tomli_w.dump(toml_dict, f)
|
||||
return config_path
|
||||
|
||||
|
||||
@@ -61,6 +77,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
dp_per_node=dp_per_node,
|
||||
num_nodes=getattr(config.deployment, "num_nodes", 1),
|
||||
port=config.server.port,
|
||||
router=config.router,
|
||||
router_port=config.server.port,
|
||||
is_disaggregated=is_disaggregated,
|
||||
kv_offload=offload is not None,
|
||||
kv_offload_mooncake=is_mooncake,
|
||||
@@ -82,7 +100,6 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
num_decode_replicas=config.deployment.num_decode_replicas,
|
||||
prefill_port=config.deployment.prefill_port,
|
||||
decode_port=config.deployment.decode_port,
|
||||
router=config.deployment.router,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
prefill_env_vars=config.deployment.prefill_env_vars,
|
||||
@@ -92,8 +109,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
|
||||
)
|
||||
elif is_multi_node:
|
||||
template_vars.update(
|
||||
router=config.deployment.router,
|
||||
backend_port=config.deployment.backend_port,
|
||||
backend_port=config.backend_port,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
enable_expert_parallel=config.enable_expert_parallel,
|
||||
infer_nodes_per_replica=config.deployment.num_nodes,
|
||||
@@ -112,12 +128,9 @@ def inference_slurm(config: InferenceConfig):
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
config_dir = get_config_dir(config.output_dir)
|
||||
exclude = (
|
||||
{"deployment", "slurm", "dry_run"}
|
||||
if config.deployment.type in ("multi_node", "disaggregated")
|
||||
else {"slurm", "dry_run"}
|
||||
)
|
||||
config_path = write_config(config, config_dir, exclude=exclude)
|
||||
is_multi_node = config.deployment.type in ("multi_node", "disaggregated")
|
||||
exclude = {"deployment", "slurm", "dry_run"} if is_multi_node else {"slurm", "dry_run"}
|
||||
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
script_path = config.output_dir / INFERENCE_SBATCH
|
||||
@@ -141,8 +154,35 @@ def inference_slurm(config: InferenceConfig):
|
||||
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
|
||||
|
||||
|
||||
def start_router(config: InferenceConfig) -> subprocess.Popen:
|
||||
"""Start the vllm-router on ``server.port``, fronting the local engine at ``backend_port``."""
|
||||
assert config.router is not None and config.router.type == "vllm-router"
|
||||
host = config.server.host
|
||||
worker_host = "localhost" if host in (None, "0.0.0.0") else host
|
||||
cmd = [
|
||||
"vllm-router",
|
||||
"--policy",
|
||||
config.router.policy,
|
||||
"--host",
|
||||
host or "0.0.0.0",
|
||||
"--port",
|
||||
str(config.server.port),
|
||||
"--worker-urls",
|
||||
f"http://{worker_host}:{config.backend_port}",
|
||||
"--intra-node-data-parallel-size",
|
||||
str(config.data_parallel_size_local or config.parallel.dp),
|
||||
"--request-id-headers",
|
||||
"x-session-id",
|
||||
"--worker-startup-timeout-secs",
|
||||
"4200",
|
||||
"--prometheus-port",
|
||||
str(config.server.port + 21000),
|
||||
]
|
||||
return subprocess.Popen(cmd)
|
||||
|
||||
|
||||
def inference_local(config: InferenceConfig):
|
||||
"""Run inference locally."""
|
||||
"""Run inference locally: a router on ``server.port`` fronting the engine on ``backend_port``."""
|
||||
from prime_rl.inference.server import setup_vllm_env
|
||||
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
@@ -153,7 +193,6 @@ def inference_local(config: InferenceConfig):
|
||||
|
||||
host = config.server.host or "0.0.0.0"
|
||||
port = config.server.port
|
||||
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
|
||||
|
||||
# Apply the inference env (defaults + [inference.env_vars]) in-process so a standalone
|
||||
# `uv run inference` gets the same environment the rl/SLURM launchers inject into the
|
||||
@@ -162,9 +201,32 @@ def inference_local(config: InferenceConfig):
|
||||
|
||||
setup_vllm_env(config)
|
||||
|
||||
router_process: subprocess.Popen | None = None
|
||||
router_stopping = Event()
|
||||
if config.router is not None:
|
||||
logger.info(f"Starting router on http://{host}:{port}/v1 (engine on port {config.backend_port})\n")
|
||||
router_process = start_router(config)
|
||||
# The router owns the client-facing port; the engine moves behind it.
|
||||
config.server.port = config.backend_port
|
||||
|
||||
def watch_router():
|
||||
router_process.wait()
|
||||
if not router_stopping.is_set():
|
||||
logger.error(f"Router exited with code {router_process.returncode} - shutting down")
|
||||
os.kill(os.getpid(), signal.SIGTERM)
|
||||
|
||||
Thread(target=watch_router, daemon=True).start()
|
||||
else:
|
||||
logger.info(f"Starting inference on http://{host}:{port}/v1\n")
|
||||
|
||||
from prime_rl.inference.vllm.server import server # pyright: ignore
|
||||
|
||||
server(config, vllm_extra=config.vllm_extra)
|
||||
try:
|
||||
server(config, vllm_extra=config.vllm_extra)
|
||||
finally:
|
||||
if router_process is not None:
|
||||
router_stopping.set()
|
||||
cleanup_processes([router_process])
|
||||
|
||||
|
||||
def inference(config: InferenceConfig):
|
||||
|
||||
@@ -73,8 +73,12 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
if config.inference is not None:
|
||||
# Exclude launcher-only fields that are not needed by the vLLM server
|
||||
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
|
||||
inference_dict = to_toml_dict(config.inference, exclude=exclude_inference)
|
||||
if config.deployment.type == "multi_node":
|
||||
# Per-rank processes run bare engines; the sbatch starts the single global router.
|
||||
inference_dict["router"] = "None"
|
||||
with open(output_dir / INFERENCE_TOML, "wb") as f:
|
||||
tomli_w.dump(to_toml_dict(config.inference, exclude=exclude_inference), f)
|
||||
tomli_w.dump(inference_dict, f)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
@@ -201,9 +205,9 @@ def rl_local(config: RLConfig):
|
||||
)
|
||||
|
||||
frozen_endpoints: list[str] = []
|
||||
for env in config.orchestrator.train.env:
|
||||
for env in config.orchestrator.train.source:
|
||||
algo = env.algo
|
||||
assert algo is not None, "TrainEnvConfig.algo must be resolved before launch (inherit_env_algorithms)"
|
||||
assert algo is not None, "TrainSourceConfig.algo must be resolved before launch (inherit_env_algorithms)"
|
||||
for ref in (algo.sampling.source, getattr(algo, "teacher", None)):
|
||||
if isinstance(ref, FrozenModelConfig):
|
||||
frozen_endpoints.append(f"{ref.name} ({', '.join(ref.base_url)})")
|
||||
@@ -414,7 +418,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
num_prefill_replicas=infer_deploy.num_prefill_replicas,
|
||||
num_decode_replicas=infer_deploy.num_decode_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=infer_deploy.router,
|
||||
router=config.inference.router,
|
||||
router_port=config.inference.server.port,
|
||||
prefill_port=infer_deploy.prefill_port,
|
||||
decode_port=infer_deploy.decode_port,
|
||||
inference_tp=config.inference.parallel.tp,
|
||||
@@ -430,6 +435,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
dp_per_node=config.deployment.gpus_per_node // config.inference.parallel.tp,
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
)
|
||||
@@ -445,15 +451,17 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
|
||||
router=config.inference.router if config.inference else VllmRouterConfig(),
|
||||
router_port=config.inference.server.port if config.inference else 8000,
|
||||
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
|
||||
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
|
||||
backend_port=config.inference.backend_port if config.inference else 8100,
|
||||
inference_tp=config.inference.parallel.tp if config.inference else 1,
|
||||
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
|
||||
inference_data_parallel_rpc_port=config.inference.data_parallel_rpc_port if config.inference else 29600,
|
||||
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
|
||||
**mooncake_vars,
|
||||
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
|
||||
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
@@ -479,8 +487,10 @@ def rl_slurm(config: RLConfig):
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean_output_dir"})
|
||||
logger.info(f"Wrote config to {config_dir / RL_TOML}")
|
||||
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
|
||||
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
|
||||
eval_env_names = (
|
||||
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
|
||||
)
|
||||
|
||||
log_message = format_log_message(
|
||||
log_dir=log_dir,
|
||||
@@ -494,8 +504,10 @@ def rl_slurm(config: RLConfig):
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
|
||||
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
|
||||
train_env_names = [env.resolved_name for env in config.orchestrator.train.source]
|
||||
eval_env_names = (
|
||||
[source.resolved_name for source in config.orchestrator.eval.source] if config.orchestrator.eval else []
|
||||
)
|
||||
|
||||
has_infer = config.deployment.infer_nodes_per_replica > 0
|
||||
log_message = format_log_message(
|
||||
|
||||
@@ -5,7 +5,7 @@ is — a bundle of sampling and the per-token training signal. This package
|
||||
turns the signal half into runtime objects (the sampling half is the env's
|
||||
:class:`~prime_rl.orchestrator.sampler.Sampler`):
|
||||
|
||||
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``opd``,
|
||||
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``, ``opd``,
|
||||
``opsd``, ``sft``) — each named class owns its scoring hooks
|
||||
(``score_rollout`` / ``score_group``) and declares what it needs (loss
|
||||
component, a "teacher", ...). One instance per env, built by
|
||||
@@ -34,6 +34,7 @@ from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
|
||||
from prime_rl.orchestrator.algo.max_rl import MaxRLAlgorithm
|
||||
from prime_rl.orchestrator.algo.opd import OPDAlgorithm
|
||||
from prime_rl.orchestrator.algo.opsd import OPSDAlgorithm
|
||||
from prime_rl.orchestrator.algo.rae import RAEAlgorithm
|
||||
from prime_rl.orchestrator.algo.routing import stamp_advantages, stamp_loss_routing
|
||||
from prime_rl.orchestrator.algo.sft import SFTDistillAlgorithm
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
@@ -48,6 +49,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
|
||||
"grpo": GRPOAlgorithm,
|
||||
"echo": EchoAlgorithm,
|
||||
"max_rl": MaxRLAlgorithm,
|
||||
"rae": RAEAlgorithm,
|
||||
"opd": OPDAlgorithm,
|
||||
"opsd": OPSDAlgorithm,
|
||||
"sft": SFTDistillAlgorithm,
|
||||
@@ -72,6 +74,7 @@ __all__ = [
|
||||
"MaxRLAlgorithm",
|
||||
"OPDAlgorithm",
|
||||
"OPSDAlgorithm",
|
||||
"RAEAlgorithm",
|
||||
"Rollout",
|
||||
"SFTDistillAlgorithm",
|
||||
"build_algorithm",
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from prime_rl.configs.algorithm import RAEAlgoConfig
|
||||
from prime_rl.orchestrator.algo.base import Algorithm
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.client import InferencePool
|
||||
|
||||
|
||||
class RAEAlgorithm(Algorithm):
|
||||
"""Role-conditioned advantage estimation (SPIRAL, arXiv:2506.24119):
|
||||
credit = reward minus a per-agent EMA baseline of that agent's rewards.
|
||||
|
||||
The advantage estimator for multi-agent self-play envs (kuhn-poker-v1 and
|
||||
friends): in a zero-sum game the group mean is ~0 whatever the policy does,
|
||||
and centering all agents against it mixes their opposite reward scales — a
|
||||
structural first-mover edge would read as permanent credit for one agent.
|
||||
A per-agent baseline tracks each agent's own expected reward instead, so
|
||||
credit measures improvement over that agent's usual result. The instance is
|
||||
per-env, so baselines are keyed per (env, agent) — the paper's per
|
||||
(game, role). A single-agent env degrades to REINFORCE with an EMA baseline.
|
||||
|
||||
Each trace is scored against the baseline *before* its reward updates it
|
||||
(the reference implementation's unbiased order). Baselines start at 0 and
|
||||
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)
|
||||
self.decay = config.decay
|
||||
self.baselines: dict[str | None, float] = defaultdict(float)
|
||||
|
||||
async def score_group(self, group: list[Rollout]) -> None:
|
||||
for rollout in group:
|
||||
baseline = self.baselines[rollout.agent_name]
|
||||
rollout.assign_advantages(rollout.reward - baseline)
|
||||
self.baselines[rollout.agent_name] = self.decay * baseline + (1.0 - self.decay) * rollout.reward
|
||||
@@ -1,7 +1,9 @@
|
||||
"""RolloutDispatcher: schedules rollouts under a shared permit counter.
|
||||
|
||||
- Capacity (``max_inflight_rollouts``) is shared across train + eval.
|
||||
A group-scoring task that runs N rollouts in one call reserves N permits.
|
||||
- Capacity (``max_inflight_episodes``) is shared across train + eval. One permit is
|
||||
one episode: for a v1 env one ``run`` request, and a group-scoring task that runs
|
||||
N rollouts in one call reserves N permits (each bridged v0 rollout is its own
|
||||
single-agent episode).
|
||||
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
|
||||
- Emit-everything invariant: every dispatched env-rollout eventually reaches
|
||||
``out_q`` exactly once, as one episode (a ``list[Rollout]``). Failures
|
||||
@@ -129,7 +131,7 @@ class RolloutDispatcher:
|
||||
eval_source: EvalSource | None,
|
||||
policy_pool: InferencePool,
|
||||
policy: Policy,
|
||||
max_inflight_rollouts: int,
|
||||
max_inflight_episodes: int,
|
||||
tasks_per_minute: float | None,
|
||||
max_off_policy_steps: int,
|
||||
) -> None:
|
||||
@@ -143,7 +145,7 @@ class RolloutDispatcher:
|
||||
self.eval_source = eval_source
|
||||
self.max_off_policy_steps = max_off_policy_steps
|
||||
|
||||
self.max_inflight = max_inflight_rollouts
|
||||
self.max_inflight = max_inflight_episodes
|
||||
self.inflight_permits = 0
|
||||
self.rate_limiter: AsyncLimiter | None = (
|
||||
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
|
||||
|
||||
@@ -13,18 +13,18 @@ from prime_rl.utils.utils import clean_exit
|
||||
@clean_exit
|
||||
def run_server(config: EnvServerConfig):
|
||||
env = config.env
|
||||
address = env.address or "tcp://127.0.0.1:5000"
|
||||
# The env's ``pool`` (static or elastic) sizes the server; a v0/legacy env runs through
|
||||
address = env.serve.address or "tcp://127.0.0.1:5000"
|
||||
# The env's ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
|
||||
# the bridge, a v1 env is a native env block — both speak the same serve protocol,
|
||||
# so the orchestrator is agnostic. serve_env applies the logging setup in this process
|
||||
# and in every spawned worker.
|
||||
server_kwargs = (
|
||||
{"env_id": env.env_id, "env_args": env.args, "extra_env_kwargs": env.extra_env_kwargs}
|
||||
{"env_id": env.env_id, "env_args": env.legacy.args, "extra_env_kwargs": env.legacy.extra_env_kwargs}
|
||||
if env.is_legacy
|
||||
else {"config_data": env_config_data(env.env)}
|
||||
else {"config_data": env_config_data(env.env), "max_concurrent": env.serve.max_concurrent}
|
||||
)
|
||||
serve_env(
|
||||
**pool_serve_kwargs(env.pool),
|
||||
**pool_serve_kwargs(env.serve.pool),
|
||||
legacy=env.is_legacy,
|
||||
address=address,
|
||||
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Env wrappers over a v1 env server.
|
||||
|
||||
Each ``Env`` owns a v1 ``EnvServer`` (spawned as a child process, or an
|
||||
external one given by ``config.address``) and an ``EnvClient`` to drive it. The
|
||||
external one pinned by ``config.serve.address``) and an ``EnvClient`` to drive it. The
|
||||
orchestrator never *runs* an environment — the agents and their runtimes live only
|
||||
in the server — but it does own the *taskset*: a v1 env's tasks are loaded here,
|
||||
once, and each dispatched env-rollout ships its task's data on the request
|
||||
@@ -34,7 +34,7 @@ from typing import Generic, TypeVar
|
||||
import verifiers.v1 as vf
|
||||
from verifiers.v1.serve import EnvClient, env_config_data
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
from prime_rl.orchestrator.sampler import Sampler
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
@@ -112,8 +112,8 @@ class Env:
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
"""Spawn the env server (if needed), connect, and load the taskset client-side
|
||||
(legacy instead asks the server for ``info`` — its dataset is server-side)."""
|
||||
external = self.config.address is not None
|
||||
address = self.config.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
|
||||
external = self.config.serve.address is not None
|
||||
address = self.config.serve.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
|
||||
get_logger().debug(f"Connecting {self.name} to env server {address}")
|
||||
self._env_client = EnvClient(address=address)
|
||||
# A spawned server already reported its address *after* binding, so it's up. An
|
||||
@@ -152,12 +152,18 @@ class Env:
|
||||
dict(
|
||||
legacy=True,
|
||||
env_id=self.config.env_id,
|
||||
env_args=self.config.args,
|
||||
extra_env_kwargs=self.config.extra_env_kwargs,
|
||||
env_args=self.config.legacy.args,
|
||||
extra_env_kwargs=self.config.legacy.extra_env_kwargs,
|
||||
)
|
||||
if self.config.is_legacy
|
||||
# Picklable dict — the narrowed config class doesn't survive the spawn.
|
||||
else dict(legacy=False, config_data=env_config_data(self.config.env))
|
||||
# ``max_concurrent`` bounds this worker's episodes in flight — usually unset,
|
||||
# since the dispatcher's ``max_inflight_episodes`` is the run's bound.
|
||||
else dict(
|
||||
legacy=False,
|
||||
config_data=env_config_data(self.config.env),
|
||||
max_concurrent=self.config.serve.max_concurrent,
|
||||
)
|
||||
)
|
||||
process = ctx.Process(
|
||||
target=_run_env_server,
|
||||
@@ -165,7 +171,7 @@ class Env:
|
||||
log_file=str(log_file),
|
||||
log_level=log_level,
|
||||
json_logging=json_logging,
|
||||
**vf.pool_serve_kwargs(self.config.pool),
|
||||
**vf.pool_serve_kwargs(self.config.serve.pool),
|
||||
address="tcp://127.0.0.1:0",
|
||||
address_queue=address_queue,
|
||||
**server_kwargs,
|
||||
@@ -246,9 +252,9 @@ class Env:
|
||||
|
||||
|
||||
class TrainEnv(Env):
|
||||
config: TrainEnvConfig
|
||||
config: TrainSourceConfig
|
||||
|
||||
def __init__(self, config: TrainEnvConfig, sampler: Sampler, algorithm: Algorithm):
|
||||
def __init__(self, config: TrainSourceConfig, sampler: Sampler, algorithm: Algorithm):
|
||||
super().__init__(config)
|
||||
self.sampler = sampler
|
||||
self.algorithm = algorithm
|
||||
@@ -256,9 +262,9 @@ class TrainEnv(Env):
|
||||
|
||||
|
||||
class EvalEnv(Env):
|
||||
config: EvalEnvConfig
|
||||
config: EvalSourceConfig
|
||||
|
||||
def __init__(self, config: EvalEnvConfig):
|
||||
def __init__(self, config: EvalSourceConfig):
|
||||
super().__init__(config)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.examples: list[dict] = []
|
||||
@@ -333,10 +339,10 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
|
||||
resolved algorithm config."""
|
||||
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig], *, policy_pool, renderer_config=None):
|
||||
def __init__(self, configs: Sequence[TrainSourceConfig], *, policy_pool, renderer_config=None):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
assert config.algo is not None, "TrainEnvConfig.algo must be resolved before env construction"
|
||||
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
|
||||
env = TrainEnv(
|
||||
config,
|
||||
Sampler(config.algo.sampling, policy_pool, renderer_config),
|
||||
@@ -348,7 +354,7 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
class EvalEnvs(Envs[EvalEnv]):
|
||||
"""Collection of evaluation environments."""
|
||||
|
||||
def __init__(self, configs: Sequence[EvalEnvConfig]):
|
||||
def __init__(self, configs: Sequence[EvalSourceConfig]):
|
||||
self._envs: dict[str, EvalEnv] = {}
|
||||
for config in configs:
|
||||
env = EvalEnv(config)
|
||||
|
||||
@@ -12,7 +12,7 @@ is flat over the rollout list except the solve rates, which group by ``group_id`
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Iterator, Literal
|
||||
from typing import TYPE_CHECKING, Any, Callable, Iterator, Literal
|
||||
|
||||
from prime_rl.orchestrator.utils import compute_pass_metrics
|
||||
|
||||
@@ -134,16 +134,20 @@ class TimingMetrics(StatGroup):
|
||||
|
||||
class CustomMetrics(StatGroup):
|
||||
"""Per-key ``Stat``s over a dynamic per-rollout dict attribute (env ``@metric``s or reward
|
||||
components), each averaged over the rollouts that report the key."""
|
||||
components), each averaged over the rollouts that report the key. ``value`` extracts the
|
||||
float from each entry (rewards are ``vf.Reward`` records; metrics are plain floats)."""
|
||||
|
||||
def __init__(self, rollouts: list[Rollout], attr: str) -> None:
|
||||
def __init__(self, rollouts: list[Rollout], attr: str, value: Callable[[Any], float] = float) -> None:
|
||||
super().__init__(rollouts)
|
||||
self.attr = attr
|
||||
self.value = value
|
||||
|
||||
def stats(self) -> dict[str, Stat]:
|
||||
names = sorted({name for r in self.rollouts for name in getattr(r, self.attr)})
|
||||
return {
|
||||
name: Stat([getattr(r, self.attr)[name] for r in self.rollouts if name in getattr(r, self.attr)])
|
||||
name: Stat(
|
||||
[self.value(getattr(r, self.attr)[name]) for r in self.rollouts if name in getattr(r, self.attr)]
|
||||
)
|
||||
for name in names
|
||||
}
|
||||
|
||||
@@ -188,8 +192,9 @@ class RolloutMetrics:
|
||||
|
||||
@property
|
||||
def rewards(self) -> CustomMetrics:
|
||||
"""Per-component reward breakdown, keyed by name (summed into the scalar ``reward``)."""
|
||||
return CustomMetrics(self.rollouts, "rewards")
|
||||
"""Per-component reward breakdown, keyed by name (each entry's weighted ``value``,
|
||||
summed into the scalar ``reward``)."""
|
||||
return CustomMetrics(self.rollouts, "rewards", value=lambda reward: reward.value)
|
||||
|
||||
# Boolean rate metrics (0/1 distributions — ``.mean()`` is the rate)
|
||||
@property
|
||||
|
||||
@@ -156,7 +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.env if env.algo is not None})
|
||||
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)})")
|
||||
|
||||
if config.bench:
|
||||
@@ -238,8 +238,8 @@ class Orchestrator:
|
||||
tokenizer=self.tokenizer,
|
||||
run_config=config,
|
||||
keep_full_history=config.bench,
|
||||
train_env_names=[env.resolved_name for env in config.train.env],
|
||||
eval_env_names=[env.resolved_name for env in config.eval.env] if config.eval is not None else [],
|
||||
train_env_names=[env.resolved_name for env in config.train.source],
|
||||
eval_env_names=[source.resolved_name for source in config.eval.source] if config.eval is not None else [],
|
||||
)
|
||||
|
||||
if config.heartbeat is not None:
|
||||
@@ -256,7 +256,7 @@ class Orchestrator:
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(
|
||||
config.train.env, policy_pool=self.policy_inference, renderer_config=config.renderer
|
||||
config.train.source, policy_pool=self.policy_inference, renderer_config=config.renderer
|
||||
)
|
||||
get_logger().debug(
|
||||
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
|
||||
@@ -270,7 +270,7 @@ class Orchestrator:
|
||||
|
||||
if config.eval is not None:
|
||||
get_logger().info("Loading eval environment(s)")
|
||||
self.eval_envs = EvalEnvs(config.eval.env)
|
||||
self.eval_envs = EvalEnvs(config.eval.source)
|
||||
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
|
||||
await self.eval_envs.start(
|
||||
log_dir=get_log_dir(config.output_dir.parent) / "envs" / "eval",
|
||||
@@ -391,7 +391,7 @@ class Orchestrator:
|
||||
else None
|
||||
)
|
||||
|
||||
assert config.max_inflight_rollouts is not None, "max_inflight_rollouts must be resolved before dispatcher init"
|
||||
assert config.max_inflight_episodes is not None, "max_inflight_episodes must be resolved before dispatcher init"
|
||||
log_interval = config.log.interval
|
||||
wandb_enabled = config.wandb is not None
|
||||
self.dispatcher = RolloutDispatcher(
|
||||
@@ -401,7 +401,7 @@ class Orchestrator:
|
||||
eval_source=self.eval_source,
|
||||
policy_pool=self.policy_inference,
|
||||
policy=self.policy,
|
||||
max_inflight_rollouts=config.max_inflight_rollouts,
|
||||
max_inflight_episodes=config.max_inflight_episodes,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
max_off_policy_steps=config.max_off_policy_steps,
|
||||
)
|
||||
@@ -597,11 +597,12 @@ class Orchestrator:
|
||||
)
|
||||
return
|
||||
self.consecutive_empty_batches = 0
|
||||
n_trainable = sum(1 for r in batch.rollouts if r.is_trainable)
|
||||
if n_trainable / len(batch.rollouts) <= 0.1:
|
||||
effective = batch.rollouts.effective
|
||||
n_trainable = sum(1 for r in effective if r.is_trainable)
|
||||
if effective and n_trainable / len(effective) <= 0.1:
|
||||
get_logger().warning(
|
||||
f"Only {n_trainable}/{len(batch.rollouts)} generated rollouts are trainable "
|
||||
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
f"Only {n_trainable}/{len(effective)} effective rollouts are trainable "
|
||||
f"({n_trainable / len(effective):.1%}) — consider reviewing task difficulty / filter config"
|
||||
)
|
||||
|
||||
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
|
||||
@@ -637,7 +638,6 @@ class Orchestrator:
|
||||
# at ship time; the full arrival window already streamed into ``all`` on arrival.
|
||||
# to_record drops the per-node training tensors — they're for training, not the rollout
|
||||
# record, and can't round-trip json (raw numpy bytes).
|
||||
effective = batch.rollouts.effective
|
||||
records = [r.to_record() for r in effective]
|
||||
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
|
||||
|
||||
@@ -805,19 +805,19 @@ 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; ``Trainable`` is
|
||||
relative to all generated rollouts."""
|
||||
the quality metrics are over the effective (clean, trained-on) subset, as is ``Trainable``."""
|
||||
rollouts = batch.rollouts
|
||||
effective = rollouts.effective
|
||||
eff = effective.metrics
|
||||
n_generated = len(rollouts)
|
||||
n_trainable = sum(1 for r in rollouts if r.is_trainable)
|
||||
trainable_rate = (n_trainable / n_generated) if n_generated else 0.0
|
||||
n_effective = len(effective)
|
||||
n_trainable = sum(1 for r in effective if r.is_trainable)
|
||||
trainable_rate = (n_trainable / n_effective) if n_effective else 0.0
|
||||
max_off_policy = max((r.off_policy_steps for r in effective), default=0)
|
||||
|
||||
head = (
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Trainable {n_trainable}/{n_generated} ({trainable_rate:.1%}) | "
|
||||
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 {rollouts.metrics.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
@@ -875,15 +875,15 @@ class Orchestrator:
|
||||
metrics["step"] = float(batch.step)
|
||||
self.monitor.log(metrics, step=batch.step)
|
||||
|
||||
# Success line — reward / turns / truncation over the effective set, error rate + branches
|
||||
# over the full returned cohort. ``Stat.mean()`` is 0.0 for an empty set.
|
||||
# Success line — quality metrics over the effective set, error rate over the full returned
|
||||
# cohort. ``Stat.mean()`` is 0.0 for an empty set.
|
||||
eff, full = effective.metrics, rollouts.metrics
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {full.num_branches.mean():.1f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
|
||||
|
||||
@@ -146,7 +146,7 @@ class TrainBatch:
|
||||
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
|
||||
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
|
||||
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
|
||||
ships, which would stall the trainer. Trainable counts derive from ``rollouts``
|
||||
ships, which would stall the trainer. Trainable counts derive from ``rollouts.effective``
|
||||
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
|
||||
|
||||
rollouts: TrainRollouts
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
{# Shared router launch helper, included once per template and called by the
|
||||
replica-head rank. The router backend (vllm-router vs llm-d EPP+Envoy) is
|
||||
chosen here via router.type, so the call sites stay router-agnostic.
|
||||
node_base/node_count locate this replica's nodes in HOSTNAMES for llm-d
|
||||
endpoint discovery (disagg uses NUM_PREFILL_NODES/NUM_DECODE_NODES). #}
|
||||
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log> <replica_idx> <node_base> [node_count]
|
||||
{# Shared launch helper for the single global router, included once per template
|
||||
and called by inference node 0. The router backend (vllm-router vs llm-d
|
||||
EPP+Envoy) is chosen here via router.type, so the call sites stay
|
||||
router-agnostic. llm-d endpoint discovery enumerates every inference node:
|
||||
all nodes for regular mode; for disaggregated mode all prefill nodes across
|
||||
replicas, then all decode nodes (matching the logical node order in
|
||||
endpoints.yaml). #}
|
||||
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log>
|
||||
launch_router() {
|
||||
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-0}" node_base="${7:-0}" node_count="${8:-0}"
|
||||
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5"
|
||||
{%- if router.type == "llm-d" %}
|
||||
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port for replica $replica" | tee "$log"
|
||||
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port" | tee "$log"
|
||||
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
|
||||
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd_${replica}"
|
||||
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd"
|
||||
mkdir -p "$LLMD_DIR"
|
||||
read -ra HOSTNAMES <<< "$HOSTNAMES_STR"
|
||||
{%- if is_disaggregated %}
|
||||
{%- set ep_disaggregated = true %}
|
||||
{%- set ep_num_prefill = num_prefill_nodes %}
|
||||
{%- set ep_num_decode = num_decode_nodes %}
|
||||
{%- set ep_num_prefill = num_prefill_nodes * (num_infer_replicas | default(1)) %}
|
||||
{%- set ep_num_decode = num_decode_nodes * (num_infer_replicas | default(1)) %}
|
||||
{%- set ep_dp = dp_per_node %}
|
||||
{%- set ep_prefill_port = prefill_port %}
|
||||
{%- set ep_sidecar_port = router.decode_sidecar_port %}
|
||||
@@ -25,12 +27,22 @@ LLMD_EOF
|
||||
cat > "$LLMD_DIR/endpoints.yaml" <<LLMD_EOF
|
||||
{% include 'llmd/endpoints.yaml.j2' %}
|
||||
LLMD_EOF
|
||||
local node=0 ip
|
||||
for ((p=0; p<NUM_PREFILL_NODES; p++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + p))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
|
||||
for ((d=0; d<NUM_DECODE_NODES; d++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1)); done
|
||||
local node=0 ip reps=${NUM_INFER_REPLICAS:-1} span=${NODES_PER_INFER_REPLICA:-$((NUM_PREFILL_NODES + NUM_DECODE_NODES))}
|
||||
for ((rr=0; rr<reps; rr++)); do
|
||||
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
|
||||
ip=$(getent hosts "${HOSTNAMES[$((rr * span + p))]}" | awk "{print \$1}")
|
||||
sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1))
|
||||
done
|
||||
done
|
||||
for ((rr=0; rr<reps; rr++)); do
|
||||
for ((d=0; d<NUM_DECODE_NODES; d++)); do
|
||||
ip=$(getent hosts "${HOSTNAMES[$((rr * span + NUM_PREFILL_NODES + d))]}" | awk "{print \$1}")
|
||||
sed -i "s|__LLMD_ADDR_${node}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; node=$((node + 1))
|
||||
done
|
||||
done
|
||||
{%- else %}
|
||||
{%- set ep_disaggregated = false %}
|
||||
{%- set ep_num_nodes = infer_nodes_per_replica %}
|
||||
{%- set ep_num_nodes = num_infer_nodes | default(num_nodes) %}
|
||||
{%- set ep_dp = dp_per_node %}
|
||||
{%- set ep_backend_port = backend_port %}
|
||||
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
|
||||
@@ -40,13 +52,16 @@ LLMD_EOF
|
||||
{% include 'llmd/endpoints.yaml.j2' %}
|
||||
LLMD_EOF
|
||||
local ip
|
||||
for ((n=0; n<node_count; n++)); do ip=$(getent hosts "${HOSTNAMES[$((node_base + n))]}" | awk "{print \$1}"); sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"; done
|
||||
for ((n=0; n<{{ ep_num_nodes }}; n++)); do
|
||||
ip=$(getent hosts "${HOSTNAMES[$n]}" | awk "{print \$1}")
|
||||
sed -i "s|__LLMD_ADDR_${n}__|${ip}|g" "$LLMD_DIR/endpoints.yaml"
|
||||
done
|
||||
{%- endif %}
|
||||
cat > "$LLMD_DIR/envoy.yaml" <<LLMD_EOF
|
||||
{% include 'llmd/envoy.yaml.j2' %}
|
||||
LLMD_EOF
|
||||
# grpc-health-port avoids 9003: mooncake_master runs its metrics server on 9003 and
|
||||
# shares the replica-head node with the EPP, so 9003 would fail to bind and kill the EPP.
|
||||
# shares node 0 with the EPP, so 9003 would fail to bind and kill the EPP.
|
||||
epp --pool-name prime-rl --pool-namespace slurm \
|
||||
--config-file "$LLMD_DIR/epp.yaml" \
|
||||
--grpc-port 9002 --grpc-health-port 9013 --metrics-port 9090 \
|
||||
@@ -55,9 +70,10 @@ LLMD_EOF
|
||||
envoy -c "$LLMD_DIR/envoy.yaml" >> "$log" 2>&1 &
|
||||
{%- else %}
|
||||
local tag="vllm-router"; [ "$mode" = pd ] && tag="vllm-router (PD)"
|
||||
echo "Starting $tag on $LOCAL_IP:$port${replica:+ for replica $replica}" | tee "$log"
|
||||
echo "Starting $tag on $LOCAL_IP:$port" | tee "$log"
|
||||
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
|
||||
--request-id-headers x-session-id
|
||||
--prometheus-port "$((port + 21000))"
|
||||
--worker-startup-timeout-secs 4200 --log-level debug)
|
||||
if [ "$mode" = pd ]; then
|
||||
cmd+=(--vllm-pd-disaggregation $worker_args)
|
||||
|
||||
@@ -38,13 +38,13 @@ export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
|
||||
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
{%- if router.type == "llm-d" %}
|
||||
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
|
||||
{%- endif %}
|
||||
{%- elif num_nodes > 1 %}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export RPC_PORT={{ data_parallel_rpc_port }}
|
||||
{%- endif %}
|
||||
@@ -77,32 +77,24 @@ uv sync --all-extras --all-packages
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if is_disaggregated -%}
|
||||
# Build per-replica router URLs
|
||||
INFER_URLS=""
|
||||
ALL_ROUTER_ARGS=""
|
||||
for ((r=0; r<NUM_NODES/NODES_PER_REPLICA; r++)); do
|
||||
replica_base=$((r * NODES_PER_REPLICA))
|
||||
router_host="${HOSTNAMES[$replica_base]}"
|
||||
INFER_URLS="${INFER_URLS:+$INFER_URLS,}http://${router_host}:${ROUTER_PORT}/v1"
|
||||
|
||||
REPLICA_ROUTER_ARGS=""
|
||||
# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node.
|
||||
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
|
||||
host="${HOSTNAMES[$((replica_base + p))]}"
|
||||
for ((k=0; k<{{ dp_per_node }}; k++)); do
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
|
||||
done
|
||||
# Single global router on node 0 fronts every per-rank endpoint.
|
||||
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
|
||||
ROUTER_ARGS=""
|
||||
# External-LB: one --prefill/--decode endpoint per DP rank (PORT + k) on each node.
|
||||
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
|
||||
host="${HOSTNAMES[$p]}"
|
||||
for ((k=0; k<{{ dp_per_node }}; k++)); do
|
||||
ROUTER_ARGS="$ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
|
||||
done
|
||||
for ((d=0; d<NUM_DECODE_NODES; d++)); do
|
||||
host="${HOSTNAMES[$((replica_base + NUM_PREFILL_NODES + d))]}"
|
||||
for ((k=0; k<{{ dp_per_node }}; k++)); do
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
|
||||
done
|
||||
done
|
||||
for ((d=0; d<NUM_DECODE_NODES; d++)); do
|
||||
host="${HOSTNAMES[$((NUM_PREFILL_NODES + d))]}"
|
||||
for ((k=0; k<{{ dp_per_node }}; k++)); do
|
||||
ROUTER_ARGS="$ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
|
||||
done
|
||||
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
|
||||
done
|
||||
export INFER_URLS
|
||||
export ALL_ROUTER_ARGS
|
||||
export ROUTER_ARGS
|
||||
{%- elif num_nodes > 1 %}
|
||||
# External LB: one router on node 0; one endpoint per DP rank (BACKEND_PORT + dp_local) on every node.
|
||||
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
|
||||
@@ -273,10 +265,9 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
echo "NODE_RANK=$INFER_NODE_RANK ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT LOCAL_IP=$LOCAL_IP" \
|
||||
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
# Start the router on the first prefill node of each replica (external LB across per-rank endpoints)
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
|
||||
# Start the single global router on node 0 (external LB across all per-rank endpoints)
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
fi
|
||||
{%- if router.type == "llm-d" %}
|
||||
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
|
||||
@@ -318,9 +309,9 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
TP=$((GPUS_PER_NODE / DP_PER_NODE))
|
||||
EP={{ "1" if enable_expert_parallel else "0" }}
|
||||
|
||||
# Start the router on node 0 (balances across per-rank endpoints — no intra-node DP header)
|
||||
# Start the single global router on node 0 (balances across per-rank endpoints — no intra-node DP header)
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log" 0 0 "$NUM_NODES"
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
fi
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
|
||||
|
||||
@@ -7,7 +7,7 @@ admin:
|
||||
static_resources:
|
||||
listeners:
|
||||
- name: prime_rl
|
||||
address: { socket_address: { address: 0.0.0.0, port_value: {{ router.port }} } }
|
||||
address: { socket_address: { address: 0.0.0.0, port_value: {{ router_port }} } }
|
||||
filter_chains:
|
||||
- filters:
|
||||
- name: envoy.filters.network.http_connection_manager
|
||||
|
||||
@@ -32,7 +32,7 @@ export NODES_PER_INFER_REPLICA={{ nodes_per_infer_replica }}
|
||||
export NUM_INFER_REPLICAS={{ num_infer_replicas }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
export ROUTER_PORT={{ router.port }}
|
||||
export ROUTER_PORT={{ router_port }}
|
||||
export INFERENCE_TP={{ inference_tp }}
|
||||
export INFERENCE_DP_LOCAL=$((GPUS_PER_NODE / INFERENCE_TP))
|
||||
export INFERENCE_DATA_PARALLEL_RPC_PORT={{ inference_data_parallel_rpc_port }}
|
||||
@@ -75,58 +75,43 @@ export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if num_infer_nodes > 0 -%}
|
||||
INFER_HOSTS=( ${HOSTNAMES[@]:0:$NUM_INFER_NODES} )
|
||||
|
||||
# Build per-replica router URLs, admin URLs, and backend args for the router
|
||||
INFER_URLS=""
|
||||
# Single global router on inference node 0 fronts every per-rank endpoint;
|
||||
# admin URLs bypass it and hit each rank directly.
|
||||
INFER_URLS="http://${INFER_HOSTS[0]}:${ROUTER_PORT}/v1"
|
||||
ADMIN_URLS=""
|
||||
ALL_ROUTER_ARGS=""
|
||||
ROUTER_ARGS=""
|
||||
{% if is_disaggregated -%}
|
||||
# External-LB: one prefill/decode endpoint per DP rank (PORT + k) on each node.
|
||||
for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
|
||||
replica_base=$((r * NODES_PER_INFER_REPLICA))
|
||||
router_host="${INFER_HOSTS[$replica_base]}"
|
||||
INFER_URLS="${INFER_URLS:+$INFER_URLS }http://${router_host}:${ROUTER_PORT}/v1"
|
||||
|
||||
REPLICA_ROUTER_ARGS=""
|
||||
# External-LB: one prefill/decode endpoint per DP rank (PORT + k) on each node.
|
||||
for ((p=0; p<NUM_PREFILL_NODES; p++)); do
|
||||
node_idx=$((replica_base + p))
|
||||
host="${INFER_HOSTS[$node_idx]}"
|
||||
host="${INFER_HOSTS[$((replica_base + p))]}"
|
||||
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((PREFILL_PORT + k))/v1"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
|
||||
ROUTER_ARGS="$ROUTER_ARGS --prefill http://${host}:$((PREFILL_PORT + k))"
|
||||
done
|
||||
done
|
||||
for ((d=0; d<NUM_DECODE_NODES; d++)); do
|
||||
node_idx=$((replica_base + NUM_PREFILL_NODES + d))
|
||||
host="${INFER_HOSTS[$node_idx]}"
|
||||
host="${INFER_HOSTS[$((replica_base + NUM_PREFILL_NODES + d))]}"
|
||||
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((DECODE_PORT + k))/v1"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
|
||||
ROUTER_ARGS="$ROUTER_ARGS --decode http://${host}:$((DECODE_PORT + k))"
|
||||
done
|
||||
done
|
||||
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
|
||||
done
|
||||
{%- else -%}
|
||||
for ((r=0; r<NUM_INFER_REPLICAS; r++)); do
|
||||
head_idx=$((r * NODES_PER_INFER_REPLICA))
|
||||
router_host="${INFER_HOSTS[$head_idx]}"
|
||||
INFER_URLS="${INFER_URLS:+$INFER_URLS }http://${router_host}:${ROUTER_PORT}/v1"
|
||||
|
||||
REPLICA_ROUTER_ARGS=""
|
||||
for ((n=0; n<NODES_PER_INFER_REPLICA; n++)); do
|
||||
node_idx=$((head_idx + n))
|
||||
host="${INFER_HOSTS[$node_idx]}"
|
||||
# External-LB: one endpoint per DP rank (BACKEND_PORT + dp_local) on each node.
|
||||
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + k))/v1"
|
||||
REPLICA_ROUTER_ARGS="$REPLICA_ROUTER_ARGS http://${host}:$((BACKEND_PORT + k))"
|
||||
done
|
||||
# External-LB: one endpoint per DP rank (BACKEND_PORT + dp_local) on each node.
|
||||
for ((n=0; n<NUM_INFER_NODES; n++)); do
|
||||
host="${INFER_HOSTS[$n]}"
|
||||
for ((k=0; k<INFERENCE_DP_LOCAL; k++)); do
|
||||
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + k))/v1"
|
||||
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + k))"
|
||||
done
|
||||
ALL_ROUTER_ARGS="${ALL_ROUTER_ARGS:+$ALL_ROUTER_ARGS|}$REPLICA_ROUTER_ARGS"
|
||||
done
|
||||
{%- endif %}
|
||||
export INFER_URLS
|
||||
export ADMIN_URLS
|
||||
export ALL_ROUTER_ARGS
|
||||
export ROUTER_ARGS
|
||||
echo "INFER_HOSTS=${INFER_HOSTS[*]}"
|
||||
echo "INFER_URLS=${INFER_URLS}"
|
||||
echo "ADMIN_URLS=${ADMIN_URLS}"
|
||||
@@ -310,10 +295,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
|
||||
| tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
|
||||
|
||||
# Start the router on the first node of each replica (PD mode, external LB across per-rank endpoints)
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
|
||||
# Start the single global router on inference node 0 (PD mode, external LB across all per-rank endpoints)
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router pd "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
fi
|
||||
{%- if router.type == "llm-d" %}
|
||||
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
|
||||
@@ -348,10 +332,9 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
launch_inference_rank "$((PORT + k))" "$RANK_GPUS" "$DP" "$INFERENCE_DATA_PARALLEL_RPC_PORT" "$RANK_EXTRA" "$((5600 + k))" "$(rank_log "$INFER_NODE_RANK" "$k")"
|
||||
done
|
||||
{%- else -%}
|
||||
# Start the router on the first node of each replica
|
||||
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
|
||||
REPLICA_ROUTER_ARGS=$(echo "$ALL_ROUTER_ARGS" | cut -d"|" -f$((REPLICA_IDX + 1)))
|
||||
launch_router regular "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$((REPLICA_IDX * NODES_PER_INFER_REPLICA))" "$NODES_PER_INFER_REPLICA"
|
||||
# Start the single global router on inference node 0 (external LB across all per-rank endpoints)
|
||||
if [ "$INFER_NODE_RANK" -eq 0 ]; then
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
|
||||
fi
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
|
||||
@@ -407,7 +390,8 @@ else
|
||||
--local-ranks-filter={{ ranks_filter }} \
|
||||
-m prime_rl.trainer.rl.train \
|
||||
@ $CONFIG_DIR/trainer.toml \
|
||||
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
{% if use_zmq_transport %}--rollout_transport.host $MASTER_ADDR \
|
||||
{% endif %}2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
|
||||
{% if num_infer_nodes > 0 %} fi{% endif %}
|
||||
{% if num_infer_nodes > 0 %}
|
||||
# Launch the orchestrator on one node. Default is trainer rank 0 (SLURM_PROCID ==
|
||||
@@ -426,6 +410,7 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $MASTER_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
|
||||
fi
|
||||
|
||||
@@ -10,7 +10,7 @@ from typing import Protocol, runtime_checkable
|
||||
import httpx
|
||||
import verifiers.v1 as vf
|
||||
from httpx import AsyncClient
|
||||
from openai import AsyncOpenAI, NotFoundError
|
||||
from openai import AsyncOpenAI
|
||||
from renderers import RendererConfig
|
||||
from tenacity import AsyncRetrying, retry, retry_if_exception, stop_after_attempt, stop_after_delay, wait_exponential
|
||||
from verifiers.v1.clients.config import EvalClientConfig, TrainClientConfig
|
||||
@@ -18,15 +18,12 @@ from verifiers.v1.clients.config import EvalClientConfig, TrainClientConfig
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# Identity tuple used by ``select_train_client`` to key load counts. ``base_url``
|
||||
# distinguishes servers; ``X-data-parallel-rank`` distinguishes DP shards within a
|
||||
# server, since the router uses that header to route to specific GPU ranks.
|
||||
ClientIdentity = tuple[str, str | None]
|
||||
ClientIdentity = str
|
||||
|
||||
|
||||
def client_identity(client: vf.ClientConfig) -> ClientIdentity:
|
||||
"""Stable identity for load balancing across inference clients."""
|
||||
return (client.base_url, client.headers.get("X-data-parallel-rank"))
|
||||
return client.base_url
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
@@ -137,6 +134,13 @@ class StaticInferencePool:
|
||||
)
|
||||
self._eval_clients = setup_clients(client_config, client_type=eval_client_type)
|
||||
self._admin_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 = (
|
||||
setup_admin_clients(client_config.model_copy(update={"admin_base_url": None}))
|
||||
if client_config.admin_base_url
|
||||
else []
|
||||
)
|
||||
self._skip_model_check = client_config.skip_model_check
|
||||
self._wait_for_ready_timeout = client_config.wait_for_ready_timeout
|
||||
self._eval_cycle = cycle(self._eval_clients)
|
||||
@@ -168,7 +172,8 @@ class StaticInferencePool:
|
||||
|
||||
async def wait_for_ready(self, model_name: str, timeout: int | None = None) -> None:
|
||||
await check_health(
|
||||
self._admin_clients, timeout=timeout if timeout is not None else self._wait_for_ready_timeout
|
||||
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)
|
||||
|
||||
@@ -222,7 +227,7 @@ def setup_clients(
|
||||
renderer_model_name: str | None = None,
|
||||
pool_size: int | None = None,
|
||||
) -> list[vf.ClientConfig]:
|
||||
"""Build v1 client configs (one per base_url × DP rank). ``client_type``
|
||||
"""Build one v1 client config per base URL. ``client_type``
|
||||
``renderer`` → token-in/out (``TrainClientConfig``, with the renderer the env
|
||||
server should use forwarded as a serialized config so it doesn't fall back to the
|
||||
default renderer); otherwise plain chat-completions (``EvalClientConfig``)."""
|
||||
@@ -240,13 +245,10 @@ def setup_clients(
|
||||
}
|
||||
clients: list[vf.ClientConfig] = []
|
||||
for base_url in client_config.base_url:
|
||||
for dp_rank in range(client_config.dp_rank_count):
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
if client_config.dp_rank_count > 1:
|
||||
headers["X-data-parallel-rank"] = str(dp_rank)
|
||||
clients.append(
|
||||
config_cls(base_url=base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra)
|
||||
)
|
||||
headers = {**client_config.headers, **env_headers}
|
||||
clients.append(
|
||||
config_cls(base_url=base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra)
|
||||
)
|
||||
return clients
|
||||
|
||||
|
||||
@@ -306,12 +308,13 @@ async def check_health(
|
||||
logger.debug("Starting pinging /health to check health")
|
||||
while wait_time < timeout:
|
||||
try:
|
||||
await admin_client.get("/health")
|
||||
response = await admin_client.get("/health")
|
||||
if response.status_code == 404:
|
||||
logger.warning("The route /health does not exist. Skipping health check.")
|
||||
return
|
||||
response.raise_for_status()
|
||||
logger.debug(f"Inference pool is ready after {wait_time} seconds")
|
||||
return
|
||||
except NotFoundError:
|
||||
logger.warning("The route /health does not exist. Skipping health check.")
|
||||
return
|
||||
except Exception as e:
|
||||
if wait_time % log_interval == 0 and wait_time > 0:
|
||||
logger.warning(
|
||||
|
||||
@@ -203,7 +203,6 @@ class ElasticInferencePool:
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
headers_from_env=self.client_config.headers_from_env,
|
||||
dp_rank_count=self.client_config.dp_rank_count,
|
||||
extra_headers_from_state=self.client_config.extra_headers_from_state,
|
||||
)
|
||||
self._train_clients = (
|
||||
|
||||
@@ -168,7 +168,7 @@ class PrimeMonitor(Monitor):
|
||||
payload["batch_size"] = run_config.batch_size
|
||||
payload["rollouts_per_example"] = run_config.group_size
|
||||
payload["seq_len"] = run_config.seq_len
|
||||
payload["environments"] = [{"id": env.id} for env in run_config.train.env]
|
||||
payload["environments"] = [{"id": env.env_id} for env in run_config.train.source]
|
||||
payload["run_config"] = run_config.model_dump(exclude_none=True, mode="json")
|
||||
if run_config.wandb:
|
||||
payload["wandb_project"] = run_config.wandb.project
|
||||
|
||||
@@ -298,14 +298,17 @@ class WandbMonitor(Monitor):
|
||||
|
||||
OVERVIEW_NAME = "overview"
|
||||
|
||||
# Per-rollout metrics (under "<scope>/all/") shown for BOTH train and eval. Only the reward metric
|
||||
# differs — train uses "reward/mean", eval uses "avg@k" — and each section builder prepends its own.
|
||||
# Per-rollout metrics (as "<subset>/<metric>" under "<scope>/") shown for BOTH train and eval.
|
||||
# Quality metrics read the effective subset — the all subset includes errored rollouts, whose
|
||||
# zero values skew the distributions. has_error only exists on all (effective drops errors by
|
||||
# construction). Only the reward metrics differ — train uses "reward/mean", eval uses "avg@k",
|
||||
# each shown for the all and effective subsets — and each section builder prepends its own.
|
||||
COMMON_METRICS = [
|
||||
"has_error/mean",
|
||||
"is_truncated/mean",
|
||||
"num_total_tokens/mean",
|
||||
"num_turns/mean",
|
||||
"num_branches/mean",
|
||||
"all/has_error/mean",
|
||||
"effective/is_truncated/mean",
|
||||
"effective/num_total_tokens/mean",
|
||||
"effective/num_turns/mean",
|
||||
"effective/num_branches/mean",
|
||||
]
|
||||
|
||||
STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"]
|
||||
@@ -328,10 +331,11 @@ ROWS = 6
|
||||
|
||||
|
||||
def line_panels(metrics: Sequence[str], regexes: Sequence[str]) -> list[wr.LinePlot]:
|
||||
# inference/* is logged against wall time (step_metric="_timestamp") → "WallTime" (== W&B's
|
||||
# "_timestamp"); everything else on "step" (prime-rl's logged training step, not internal "Step").
|
||||
# inference/* is logged against time (step_metric="_timestamp"), plotted on "RelativeTime(Wall)"
|
||||
# (== W&B's "_absolute_runtime", seconds since run start) so runs started at different times
|
||||
# overlay; everything else on "step" (prime-rl's logged training step, not internal "Step").
|
||||
# x is set per-panel because LinePlot defaults it to "Step", which overrides the workspace x_axis.
|
||||
return [wr.LinePlot(x="WallTime" if m.startswith("inference/") else "step", y=[m]) for m in metrics] + [
|
||||
return [wr.LinePlot(x="RelativeTime(Wall)" if m.startswith("inference/") else "step", y=[m]) for m in metrics] + [
|
||||
wr.LinePlot(x="step", metric_regex=r) for r in regexes
|
||||
]
|
||||
|
||||
@@ -346,15 +350,20 @@ def section(name: str, metrics: Sequence[str] = (), regexes: Sequence[str] = ())
|
||||
|
||||
|
||||
def train_section(name: str, scope: str) -> ws.Section:
|
||||
return section(name, metrics=[f"{scope}/all/reward/mean"] + [f"{scope}/all/{m}" for m in COMMON_METRICS])
|
||||
return section(
|
||||
name,
|
||||
metrics=[f"{scope}/all/reward/mean", f"{scope}/effective/reward/mean"]
|
||||
+ [f"{scope}/{m}" for m in COMMON_METRICS],
|
||||
)
|
||||
|
||||
|
||||
def eval_section(name: str, env_pattern: str) -> ws.Section:
|
||||
# Same metrics as train, but eval's reward is "avg@k" (dynamic k → regex). Everything is a regex so
|
||||
# one section can also serve any env (env_pattern=".*"). Only the "all" subset, like train.
|
||||
# one section can also serve any env (env_pattern=".*").
|
||||
return section(
|
||||
name,
|
||||
regexes=[f"eval/{env_pattern}/all/avg@.*"] + [f"eval/{env_pattern}/all/{m}" for m in COMMON_METRICS],
|
||||
regexes=[f"eval/{env_pattern}/all/avg@.*", f"eval/{env_pattern}/effective/avg@.*"]
|
||||
+ [f"eval/{env_pattern}/{m}" for m in COMMON_METRICS],
|
||||
)
|
||||
|
||||
|
||||
@@ -395,15 +404,16 @@ def list_views(entity: str, project: str) -> list[tuple[str, str]]:
|
||||
return [(e["node"]["displayName"], e["node"]["name"]) for e in edges if e.get("node")]
|
||||
|
||||
|
||||
def env_signature(train_envs: Sequence[str], eval_envs: Sequence[str]) -> tuple:
|
||||
return (tuple(sorted(train_envs)), tuple(sorted(eval_envs)))
|
||||
|
||||
|
||||
def view_env_signature(sections: Sequence[ws.Section]) -> tuple:
|
||||
"""Reconstruct the ``(train, eval)`` env set a view was built for from its section names."""
|
||||
def view_signature(sections: Sequence[ws.Section]) -> tuple:
|
||||
train = sorted(s.name[len("train/") :] for s in sections if s.name.startswith("train/") and s.name != "train/agg")
|
||||
evals = sorted(s.name[len("eval/") :] for s in sections if s.name.startswith("eval/"))
|
||||
return (tuple(train), tuple(evals))
|
||||
panels = {
|
||||
(getattr(p.x, "name", p.x), tuple(getattr(m, "name", m) for m in p.y or ()), p.metric_regex)
|
||||
for s in sections
|
||||
for p in s.panels
|
||||
if isinstance(p, wr.LinePlot)
|
||||
}
|
||||
return (tuple(train), tuple(evals), tuple(sorted(panels, key=str)))
|
||||
|
||||
|
||||
def next_overview_name(base: str, existing: Sequence[str]) -> str:
|
||||
@@ -424,13 +434,14 @@ def ensure_overview_view(
|
||||
"""Ensure an overview saved view exists for this run's env set. Reuses an existing overview built
|
||||
for the same envs; when the env set is new, creates a fresh versioned view (``overview`` →
|
||||
``overview-v2`` → …). Returns the URL of a newly created view, else None."""
|
||||
target = env_signature(train_envs, eval_envs)
|
||||
sections = build_sections(train_envs, eval_envs)
|
||||
target = view_signature(sections)
|
||||
overviews = [(dn, iname) for dn, iname in list_views(entity, project) if dn == name or dn.startswith(f"{name}-v")]
|
||||
for _, internal_name in overviews:
|
||||
slug = internal_name.removeprefix("nw-").removesuffix("-v")
|
||||
try:
|
||||
existing = ws.Workspace.from_url(f"https://wandb.ai/{entity}/{project}?nw={slug}")
|
||||
matches = view_env_signature(existing.sections) == target
|
||||
matches = view_signature(existing.sections) == target
|
||||
except Exception as e:
|
||||
# A single unreadable view must not abort reuse detection / versioning for the rest.
|
||||
get_logger().warning(f"Could not inspect overview view {internal_name} - {e}")
|
||||
@@ -441,7 +452,7 @@ def ensure_overview_view(
|
||||
entity=entity,
|
||||
project=project,
|
||||
name=next_overview_name(name, [dn for dn, _ in overviews]),
|
||||
sections=build_sections(train_envs, eval_envs),
|
||||
sections=sections,
|
||||
auto_generate_panels=False,
|
||||
settings=ws.WorkspaceSettings(x_axis="step"),
|
||||
)
|
||||
|
||||
@@ -101,7 +101,7 @@ def _build_rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=0, prompt=None)),
|
||||
nodes=nodes,
|
||||
calls=calls,
|
||||
rewards={"reward": reward},
|
||||
rewards={"reward": vf.Reward(score=reward)},
|
||||
metrics=metrics or {},
|
||||
)
|
||||
rollout.env_name = env_name
|
||||
|
||||
@@ -258,7 +258,7 @@ def _two_turn_rollout(observation_role: str = "tool") -> Rollout:
|
||||
rollout = Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=0, prompt=None)),
|
||||
nodes=nodes,
|
||||
rewards={"r": 1.0},
|
||||
rewards={"r": vf.Reward(score=1.0)},
|
||||
env_name="test-env",
|
||||
)
|
||||
rollout.samples = trace_to_samples(rollout, env_name="test-env")
|
||||
@@ -309,7 +309,7 @@ def test_echo_weights_only_content_tokens_when_is_content_present():
|
||||
rollout = Rollout(
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=0, prompt=None)),
|
||||
nodes=nodes,
|
||||
rewards={"r": 1.0},
|
||||
rewards={"r": vf.Reward(score=1.0)},
|
||||
env_name="test-env",
|
||||
)
|
||||
rollout.samples = trace_to_samples(rollout, env_name="test-env")
|
||||
|
||||
@@ -58,7 +58,9 @@ def _make_rollout(
|
||||
else:
|
||||
nodes = [_assistant_node(completion_ids, completion_logprobs)]
|
||||
rollout = Rollout[vf.TaskData](
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=0, prompt="")), nodes=nodes, rewards={"reward": reward}
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=0, prompt="")),
|
||||
nodes=nodes,
|
||||
rewards={"reward": vf.Reward(score=reward)},
|
||||
)
|
||||
rollout.env_name = "test"
|
||||
rollout.group_id = uuid.uuid4()
|
||||
@@ -140,7 +142,7 @@ def test_gibberish_aligns_logprobs_under_generation_prompt_scaffold():
|
||||
rollout = Rollout[vf.TaskData](
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=0, prompt="")),
|
||||
nodes=[_scaffold_assistant_node([50, 80, 120_000], [-1.0, -0.5, gibberish_filter.logprob_threshold - 1.0])],
|
||||
rewards={"reward": 1.0},
|
||||
rewards={"reward": vf.Reward(score=1.0)},
|
||||
)
|
||||
|
||||
result = gibberish_filter.check(rollout)
|
||||
|
||||
@@ -2,6 +2,7 @@ import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.metrics import EvalRollouts, Stat, TrainRollouts
|
||||
from prime_rl.orchestrator.utils import compute_pass_metrics
|
||||
@@ -141,8 +142,8 @@ def test_stop_condition_breakdown():
|
||||
|
||||
def test_nested_metrics_and_rewards():
|
||||
rollouts = [
|
||||
mk(metrics={"acc": 1.0}, rewards={"correct": 1.0, "format": 0.0}),
|
||||
mk(metrics={"acc": 3.0, "fmt": 5.0}, rewards={"correct": 0.0, "format": 1.0}),
|
||||
mk(metrics={"acc": 1.0}, rewards={"correct": vf.Reward(score=1.0), "format": vf.Reward(score=0.0)}),
|
||||
mk(metrics={"acc": 3.0, "fmt": 5.0}, rewards={"correct": vf.Reward(score=0.0), "format": vf.Reward(score=1.0)}),
|
||||
]
|
||||
m = TrainRollouts(rollouts).metrics
|
||||
assert m.metrics["acc"].mean() == 2.0 and m.rewards["correct"].mean() == 0.5 # nested group access
|
||||
|
||||
+29
-10
@@ -25,11 +25,14 @@ CONFIG_CLASSES = [
|
||||
|
||||
|
||||
def get_config_files() -> list[Path]:
|
||||
"""Any TOML file inside `configs/` or `examples/`."""
|
||||
"""Any TOML file inside `configs/`, `examples/` or `k8s/`."""
|
||||
config_files = list(Path("configs").rglob("*.toml"))
|
||||
example_files = list(Path("examples").rglob("*.toml"))
|
||||
# The k8s example configs are mounted into the chart's containers verbatim, so a
|
||||
# stale key there breaks a deploy with nothing else to catch it.
|
||||
k8s_files = list(Path("k8s").rglob("*.toml"))
|
||||
|
||||
return config_files + example_files
|
||||
return config_files + example_files + k8s_files
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_file", get_config_files(), ids=lambda x: x.as_posix())
|
||||
@@ -177,10 +180,10 @@ def test_env_algo_overrides_top_level():
|
||||
{
|
||||
"renderer": {"name": "qwen3"}, # echo needs the renderer's role attribution
|
||||
"algo": {"type": "echo"},
|
||||
"train": {"env": [{"id": "a", "algo": {"type": "grpo"}}, {"id": "b"}]},
|
||||
"train": {"source": [{"legacy": {"id": "a"}, "algo": {"type": "grpo"}}, {"legacy": {"id": "b"}}]},
|
||||
}
|
||||
)
|
||||
env_a, env_b = config.train.env
|
||||
env_a, env_b = config.train.source
|
||||
# Env a sets its own algorithm; only env b inherits the top-level echo algorithm.
|
||||
assert env_a.algo is not None and env_a.algo.type == "grpo"
|
||||
assert env_b.algo is not None and env_b.algo.type == "echo"
|
||||
@@ -188,7 +191,23 @@ def test_env_algo_overrides_top_level():
|
||||
# Resolved configs round-trip.
|
||||
dumped = config.model_dump(exclude_none=True)
|
||||
reloaded = OrchestratorConfig.model_validate(dumped)
|
||||
assert reloaded.train.env[0].algo is not None and reloaded.train.env[0].algo.type == "grpo"
|
||||
assert reloaded.train.source[0].algo is not None and reloaded.train.source[0].algo.type == "grpo"
|
||||
|
||||
with pytest.raises(ValidationError, match="env"):
|
||||
OrchestratorConfig.model_validate(
|
||||
{
|
||||
"renderer": {"name": "qwen3"},
|
||||
"train": {"env": [{"legacy": {"id": "removed"}}]},
|
||||
}
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError, match="env"):
|
||||
OrchestratorConfig.model_validate(
|
||||
{
|
||||
"renderer": {"name": "qwen3"},
|
||||
"eval": {"env": [{"legacy": {"id": "removed"}}]},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_trainer_enable_token_export_cli_flag():
|
||||
@@ -196,12 +215,12 @@ def test_trainer_enable_token_export_cli_flag():
|
||||
assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export
|
||||
|
||||
|
||||
def test_single_node_auto_inference_client_dp_rank_count_matches_local_dp():
|
||||
def test_single_node_auto_inference_ports_follow_server_port():
|
||||
config = RLConfig.model_validate(
|
||||
{
|
||||
"trainer": {},
|
||||
"orchestrator": {},
|
||||
"inference": {"parallel": {"tp": 1}},
|
||||
"inference": {"server": {"port": 8001}, "parallel": {"tp": 1}},
|
||||
"deployment": {
|
||||
"type": "single_node",
|
||||
"gpus_per_node": 4,
|
||||
@@ -213,10 +232,11 @@ def test_single_node_auto_inference_client_dp_rank_count_matches_local_dp():
|
||||
|
||||
assert config.inference is not None
|
||||
assert config.inference.parallel.dp == 2
|
||||
assert config.orchestrator.model.client.dp_rank_count == 2
|
||||
assert config.inference.backend_port == 8101
|
||||
assert config.orchestrator.model.client.admin_base_url == ["http://localhost:8101/v1"]
|
||||
|
||||
|
||||
def test_multi_node_auto_inference_client_dp_rank_count_uses_router_url():
|
||||
def test_multi_node_auto_inference_parallelism():
|
||||
config = RLConfig.model_validate(
|
||||
{
|
||||
"trainer": {},
|
||||
@@ -235,7 +255,6 @@ def test_multi_node_auto_inference_client_dp_rank_count_uses_router_url():
|
||||
assert config.inference is not None
|
||||
assert config.inference.data_parallel_size_local == 2
|
||||
assert config.inference.parallel.dp == 2
|
||||
assert config.orchestrator.model.client.dp_rank_count == 1
|
||||
|
||||
|
||||
def test_orchestrator_vlm_requires_renderer():
|
||||
|
||||
@@ -32,8 +32,7 @@ def create_run_with_config(output_dir: Path, run_name: str) -> Path:
|
||||
"model": {"name": "test-model"},
|
||||
"batch_size": 2,
|
||||
"group_size": 1,
|
||||
"env": [{"id": "test-env"}],
|
||||
"sampling": {"temperature": 1.0},
|
||||
"train": {"source": [{"legacy": {"id": "test-env"}}], "sampling": {"temperature": 1.0}},
|
||||
# test-model isn't in MODEL_RENDERER_MAP; use the explicit default renderer.
|
||||
"renderer": {"name": "default"},
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ def create_run_with_config(
|
||||
"model": {"name": "test-model"},
|
||||
"batch_size": 32,
|
||||
"group_size": 4,
|
||||
"env": [{"id": "test-env"}],
|
||||
"train": {"source": [{"legacy": {"id": "test-env"}}]},
|
||||
# test-model isn't in MODEL_RENDERER_MAP; use the explicit default renderer.
|
||||
"renderer": {"name": "default"},
|
||||
}
|
||||
@@ -202,7 +202,7 @@ def test_config_loading(tmp_path: Path) -> None:
|
||||
"batch_size": 32,
|
||||
"max_steps": 1000,
|
||||
"group_size": 4,
|
||||
"env": [{"id": "test-env"}],
|
||||
"train": {"source": [{"legacy": {"id": "test-env"}}]},
|
||||
"renderer": {"name": "default"},
|
||||
}
|
||||
create_run_with_config(tmp_path, "run_test123", config=test_config)
|
||||
@@ -247,7 +247,7 @@ def test_config_cleanup_on_deletion(tmp_path: Path) -> None:
|
||||
"model": {"name": "test-model"},
|
||||
"batch_size": 16,
|
||||
"group_size": 4,
|
||||
"env": [{"id": "test-env"}],
|
||||
"train": {"source": [{"legacy": {"id": "test-env"}}]},
|
||||
"renderer": {"name": "default"},
|
||||
}
|
||||
run_dir = create_run_with_config(tmp_path, "run_delete_me", config=test_config)
|
||||
@@ -278,7 +278,7 @@ def test_config_invalid(tmp_path: Path) -> None:
|
||||
"model": {"name": "test-model"},
|
||||
"batch_size": "not-a-number", # Invalid type
|
||||
"group_size": 4,
|
||||
"env": [{"id": "test-env"}],
|
||||
"train": {"source": [{"legacy": {"id": "test-env"}}]},
|
||||
}
|
||||
run_dir = create_run_with_config(tmp_path, "run_invalid", config=invalid_config)
|
||||
config_dir = run_dir / "control"
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
from verifiers.v1.clients.config import EvalClientConfig
|
||||
|
||||
from prime_rl.configs.shared import ClientConfig
|
||||
from prime_rl.utils.client import _is_retryable_lora_error, load_lora_adapter, setup_clients
|
||||
from prime_rl.utils.client import _is_retryable_lora_error, check_health, load_lora_adapter, setup_clients
|
||||
|
||||
|
||||
def test_is_retryable_lora_error_returns_true_for_404():
|
||||
@@ -49,14 +49,13 @@ def test_load_lora_adapter_succeeds_on_first_attempt():
|
||||
)
|
||||
|
||||
|
||||
def test_setup_clients_assigns_renderer_and_dp_rank_headers():
|
||||
def test_setup_clients_creates_one_renderer_client_per_url():
|
||||
from renderers import Qwen3VLRendererConfig
|
||||
|
||||
client_config = ClientConfig(
|
||||
base_url=["http://worker-a:8000/v1"],
|
||||
base_url=["http://worker-a:8000/v1", "http://worker-b:8000/v1"],
|
||||
api_key_var="PRIME_API_KEY",
|
||||
headers={"X-Test": "test"},
|
||||
dp_rank_count=2,
|
||||
extra_headers_from_state={"X-Session-ID": "session_id"},
|
||||
)
|
||||
|
||||
@@ -70,11 +69,27 @@ def test_setup_clients_assigns_renderer_and_dp_rank_headers():
|
||||
assert [client.type for client in clients] == ["train", "train"]
|
||||
assert [client.renderer for client in clients] == [renderer_settings, renderer_settings]
|
||||
assert [client.renderer_model_name for client in clients] == [None, None]
|
||||
assert [client.base_url for client in clients] == ["http://worker-a:8000/v1"] * 2
|
||||
assert [client.headers["X-data-parallel-rank"] for client in clients] == ["0", "1"]
|
||||
assert [client.base_url for client in clients] == [
|
||||
"http://worker-a:8000/v1",
|
||||
"http://worker-b:8000/v1",
|
||||
]
|
||||
assert all("X-data-parallel-rank" not in client.headers for client in clients)
|
||||
assert clients[0].headers["X-Test"] == "test"
|
||||
|
||||
|
||||
def test_check_health_retries_non_success_status():
|
||||
client = AsyncMock()
|
||||
unavailable = httpx.Response(503, request=httpx.Request("GET", "http://worker/health"))
|
||||
healthy = httpx.Response(200, request=httpx.Request("GET", "http://worker/health"))
|
||||
client.get.side_effect = [unavailable, healthy]
|
||||
client.base_url = httpx.URL("http://worker")
|
||||
|
||||
with patch("prime_rl.utils.client.asyncio.sleep", new=AsyncMock()):
|
||||
asyncio.run(check_health([client], interval=1, timeout=2))
|
||||
|
||||
assert client.get.await_count == 2
|
||||
|
||||
|
||||
def test_setup_clients_assigns_renderer_model_name():
|
||||
from renderers import Qwen3VLRendererConfig
|
||||
|
||||
|
||||
@@ -415,8 +415,6 @@ def test_elastic_clients_preserve_renderer_model_name_when_model_name_updates():
|
||||
client_config.headers = {}
|
||||
client_config.headers_from_env = {}
|
||||
client_config.extra_headers_from_state = {}
|
||||
client_config.dp_rank_count = 1
|
||||
|
||||
from renderers import Qwen3VLRendererConfig
|
||||
|
||||
renderer_settings = Qwen3VLRendererConfig()
|
||||
|
||||
@@ -38,7 +38,7 @@ def _build_rollout(*, example_id: int, reward: float, task: str) -> Rollout:
|
||||
rollout = Rollout[vf.TaskData](
|
||||
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=example_id, prompt=f"prompt-{example_id}")),
|
||||
nodes=nodes,
|
||||
rewards={"reward": reward},
|
||||
rewards={"reward": vf.Reward(score=reward)},
|
||||
)
|
||||
rollout.env_name = task
|
||||
# Per-token advantage stream (full-length-N): 0.0 on the 3 prompt tokens,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user