Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7089ba1e4d | ||
|
|
38494ccb41 | ||
|
|
375d8596d8 | ||
|
|
e035135126 | ||
|
|
533e992ad2 | ||
|
|
858207d340 | ||
|
|
570463cca2 | ||
|
|
31e81e5b18 | ||
|
|
137f8f49c8 | ||
|
|
f04c8d988c | ||
|
|
4d361adacc | ||
|
|
7f77713886 | ||
|
|
efeddae6bb |
@@ -77,8 +77,11 @@ jobs:
|
||||
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
|
||||
from prime_rl.utils.validation import validate_shared_ckpt_config
|
||||
|
||||
# `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types
|
||||
# (EnvConfig, Task, ...) extend verifiers.v1, which is pure-pydantic and pulls no
|
||||
# GPU/ML deps. We still forbid the actual heavy training deps below.
|
||||
forbidden = ["torch", "transformers", "vllm", "wandb", "ring_flash_attn",
|
||||
"verifiers", "prime", "datasets", "liger_kernel", "loguru"]
|
||||
"prime", "liger_kernel", "loguru"]
|
||||
leaked = [m for m in forbidden if m in sys.modules]
|
||||
if leaked:
|
||||
raise SystemExit(f"slim install leaked heavy deps into sys.modules: {leaked}")
|
||||
|
||||
@@ -2,6 +2,13 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **verifiers v1 training integration** (collection of removals/renames). The orchestrator now trains against a v1 env server returning `vf.Trace` rollouts, renderer-only, with a unified token schema.
|
||||
- **`[[orchestrator.train.env]]` is now a v1 `vf.EnvServerConfig`**: a v1 env is `taskset = { id = "<id>" }` + `harness = { id = "default", runtime = { type = "subprocess" } }`. A bare `id = "<id>"` (optionally with `args`) runs the v0 env through the verifiers legacy bridge — old flat `id`/`args`-only configs keep working as legacy envs; v1 envs must use the `taskset`/`harness` shape.
|
||||
- **`orchestrator.train.env` no longer defaults to a `reverse-text` env**: the default is now empty (`[]`), so configs must declare `[[orchestrator.train.env]]` explicitly.
|
||||
- **`...env[].num_workers` → `pool`**: per-env worker sizing moves to a `pool` config (`static`/`elastic`). Back-compat: `num_workers = N` maps to `pool = { type = "static", num_workers = N }` and `"auto"` to the default elastic pool; the group-level `orchestrator.train.num_workers` / `orchestrator.eval.num_workers` are removed.
|
||||
- **`orchestrator.renderer` is now required (MITO removed)**: it was `RendererConfig | None`, where `renderer = None` selected the MITO path; training is now renderer-only, so `renderer` is non-optional. Drop `renderer = None` / `renderer = "None"`.
|
||||
- **`...client.timeout` / `...client.connect_timeout` removed**: the v1 rollout client manages its own timeouts. Drop these from `[orchestrator.student.client]` and `[orchestrator.teacher.client]`. (2026-06-23)
|
||||
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
|
||||
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
|
||||
@@ -97,6 +97,7 @@ RUN apt-get update && apt-get install -y \
|
||||
tmux \
|
||||
iperf \
|
||||
openssh-server \
|
||||
git \
|
||||
git-lfs \
|
||||
gpg \
|
||||
sudo \
|
||||
|
||||
@@ -38,6 +38,7 @@ PRIME-RL is a framework for large-scale reinforcement learning. It is designed t
|
||||
5. Multi-node deployment with Slurm and Kubernetes support.
|
||||
6. Multimodal support for VLMs such as Qwen3-VL.
|
||||
7. Hackable, modular, and extensible by design.
|
||||
8. One-line SLURM deployment for frontier models — e.g. [`GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload](examples/glm5_llmd/README.md).
|
||||
|
||||
|
||||
## Models support
|
||||
@@ -221,6 +222,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
|
||||
3. [**Intellect-3.1**](examples/Intellect-3.1/README.md): Reproduce our `INTELLECT-3.1` training run.
|
||||
4. [**MiniMax-M2.5 SWE**](examples/minimax_m2.5_swe/README.md): Train `MiniMax-M2.5` on agentic SWE tasks.
|
||||
5. [**High-throughput GLM-5**](examples/glm5_pd_disag/README.md): Train `GLM-5` with PD disaggregation and FP8 inference on SWE.
|
||||
6. [**High-throughput GLM-5 (llm-d)**](examples/glm5_llmd/README.md): One-line SLURM deployment for `GLM-5` FP8 with P/D disaggregation, the `llm-d` router, and Mooncake KV offload — the faster way to run `GLM-5`.
|
||||
|
||||
## Docs
|
||||
|
||||
|
||||
@@ -19,6 +19,10 @@ training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text-v1"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
args = { v1 = true }
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[inference]
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
@@ -9,9 +9,8 @@ Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) a
|
||||
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
|
||||
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
|
||||
| `sft_external.toml` | `sft` | PI inference (`openai/gpt-5-mini`) | external OAI endpoint; no local teacher |
|
||||
|
||||
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml` and `sft_external.toml`) is **not** auto-launched — start it manually on GPU 1.
|
||||
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml`) is **not** auto-launched — start it manually on GPU 1.
|
||||
|
||||
## Start the local teacher
|
||||
|
||||
@@ -38,10 +37,6 @@ uv run rl @ configs/debug/training_modes/opd_lora.toml
|
||||
# SFT hard distill (needs teacher on port 8001)
|
||||
uv run rl @ configs/debug/training_modes/sft.toml
|
||||
uv run rl @ configs/debug/training_modes/sft_lora.toml
|
||||
|
||||
# SFT hard distill from openai/gpt-5-mini via PI inference
|
||||
# (requires PRIME_API_KEY + PRIME_TEAM_ID in env; no local teacher needed)
|
||||
uv run rl @ configs/debug/training_modes/sft_external.toml
|
||||
```
|
||||
|
||||
See [docs/training.md](../../docs/training.md#training-modes-rl--opd--sft-via-orchestrator) for what each mode does.
|
||||
|
||||
@@ -20,6 +20,10 @@ training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 4
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
# SFT from openai/gpt-5-mini via PI inference.
|
||||
# Requires PRIME_API_KEY + PRIME_TEAM_ID in the environment.
|
||||
#
|
||||
# Run with:
|
||||
# uv run rl @ configs/debug/training_modes/sft_external.toml
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text-debug"
|
||||
name = "debug-sft-external"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 4
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
extra_body = { reasoning_effort = "minimal" }
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "reverse-text"
|
||||
|
||||
[orchestrator.teacher.model]
|
||||
name = "openai/gpt-5-mini"
|
||||
|
||||
[orchestrator.teacher.client]
|
||||
base_url = ["https://api.pinference.ai/api/v1"]
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[orchestrator.teacher.client.headers_from_env]
|
||||
X-Prime-Team-ID = "PRIME_TEAM_ID"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -20,6 +20,10 @@ training_mode = "sft"
|
||||
batch_size = 128
|
||||
group_size = 4
|
||||
|
||||
# Teacher rolls out over plain chat-completions (no tokens); the renderer backfills them.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# v1 port of examples/alphabet_sort/rl.toml — identical except the env block, which loads
|
||||
# the v1 `alphabet-sort-v1` taskset (multi-turn via a colocated vf.User) instead of the v0
|
||||
# `primeintellect/alphabet-sort` env. Harness runs on the subprocess runtime.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 2048
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[wandb]
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
[trainer.model]
|
||||
impl = "auto"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.lora]
|
||||
rank = 32
|
||||
alpha = 64
|
||||
|
||||
[trainer.optim]
|
||||
lr = 1e-5
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "alphabet-sort"
|
||||
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, power_per_turn = false }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
[inference] # Default inference config
|
||||
@@ -0,0 +1,55 @@
|
||||
# Debug v1 RL run: the v1 `general-agent-v1` taskset (GeneralAgentSolverTaskset) driven by the
|
||||
# default harness, with the agent and its tool server colocated in a modal sandbox. Copied from
|
||||
# configs/general_agent/rl_qwen3_4b.toml and rewired for v1 (taskset + harness + renderer; the
|
||||
# v0 `id = "general-agent-solver-rlm"` env becomes the v1 taskset + a separate harness).
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 32768
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
project = "general-agent-debug"
|
||||
name = "qwen3-4b-v1"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
keep_last = 1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
cp = 2
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "rl"
|
||||
batch_size = 256
|
||||
rollouts_per_example = 8
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
# v1 general-agent solver taskset; the tool server is colocated in the harness's modal sandbox.
|
||||
taskset = { id = "general-agent-v1", tools = { colocated = true } }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 32768
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
@@ -0,0 +1,42 @@
|
||||
# GSM8K (v1) — the v1 port of configs/gsm8k/rl.toml. Trains Qwen3-0.6B on GSM8K through the
|
||||
# v1 env server: the orchestrator spawns a v1 EnvServer for the gsm8k-v1 taskset and trains on
|
||||
# the returned Traces. Runs on 2 GPUs (1 inference, 1 training):
|
||||
# uv run inference --model.name PrimeIntellect/Qwen3-0.6B # Inference pane (GPU 0)
|
||||
# uv run rl @ configs/debug/v1/gsm8k.toml --ckpt # Trainer pane (GPU 1)
|
||||
|
||||
max_steps = 100
|
||||
seq_len = 2048
|
||||
|
||||
[wandb]
|
||||
project = "gsm8k-debug"
|
||||
name = "gsm8k-v1"
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-0.6B"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "rl"
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
taskset = { id = "gsm8k-v1", split = "train" }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
num_examples = 256
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
taskset = { id = "gsm8k-v1", split = "test" }
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference] # Default inference config
|
||||
@@ -0,0 +1,55 @@
|
||||
# v1 analog of examples/hendrycks_sanity/rl.toml — identical config with only
|
||||
# the env sections swapped to v1 taskset/harness syntax (math-env taskset,
|
||||
# default harness, modal runtime). Submits to slurm by default; pass --no-slurm
|
||||
# to run locally.
|
||||
|
||||
output_dir = "/beegfs/mika/hendrycks-sanity-v1"
|
||||
max_steps = 200
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-sanity"
|
||||
name = "v1"
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[slurm]
|
||||
job_name = "hendrycks-modal"
|
||||
partition = "all"
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 8
|
||||
seq_len = 8192
|
||||
max_inflight_rollouts = 256
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "hendrycks-math"
|
||||
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
timeout = { scoring = 300 }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "aime2024"
|
||||
taskset = { id = "aime24-v1" }
|
||||
harness = { id = "default", runtime = { type = "modal" } }
|
||||
timeout = { scoring = 300 }
|
||||
group_size = 32
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 8192
|
||||
|
||||
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -0,0 +1,86 @@
|
||||
# v1 port of configs/rlm_swe/qwen35_4b.toml — identical except the env blocks, which load
|
||||
# the v1 `r2e-gym-v1` taskset through the rlm harness on the prime runtime instead of the
|
||||
# v0 `rlm_swe` composable env. Same model / trainer / inference / orchestrator knobs.
|
||||
|
||||
output_dir = "/beegfs/mika/rlm-swe-qwen35-4b"
|
||||
max_steps = 400
|
||||
seq_len = 65536
|
||||
|
||||
[slurm]
|
||||
job_name = "rlm-swe-qwen35-4b"
|
||||
project_dir = "."
|
||||
pre_run_command = "prime sandbox delete --label rlm-swe-qwen35-4b -y --plain || true"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 2
|
||||
|
||||
[wandb]
|
||||
project = "rlm-swe-debug"
|
||||
name = "qwen35-4b"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.5-4B"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 8
|
||||
max_inflight_rollouts = 512
|
||||
max_off_policy_steps = 16
|
||||
|
||||
# Thinking enabled for the Qwen3.5 renderer.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3.5"
|
||||
enable_thinking = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "rlm-swe-r2e"
|
||||
taskset = { id = "r2e-gym-v1" }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["rlm-swe-qwen35-4b"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
|
||||
[inference.parallel]
|
||||
dp = 8
|
||||
|
||||
# Qwen3.5-4B is a VL model; skip the vision tower for text-only SWE.
|
||||
# `language_model_only` is a vLLM MultiModalConfig arg (no prime-rl field) → pass via vllm_extra.
|
||||
[inference.vllm_extra]
|
||||
language_model_only = true
|
||||
@@ -0,0 +1,42 @@
|
||||
# Debug RL run on the v1 env server (reverse-text starter).
|
||||
# The orchestrator spawns a v1 EnvServer per env (it never loads the env
|
||||
# itself), dispatches rollouts by task index, and trains on the returned Traces
|
||||
# (renderer-tokenized). Light settings for a quick end-to-end smoke.
|
||||
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text"
|
||||
name = "v1"
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[orchestrator]
|
||||
training_mode = "rl"
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
taskset = { id = "reverse-text-v1" }
|
||||
# reverse-text is a pure-text single-turn env: disable the bash tool (the model answers
|
||||
# directly) and use the subprocess runtime (no docker).
|
||||
harness = { id = "default", runtime = { type = "subprocess" } }
|
||||
|
||||
# No eval block, mirroring examples/reverse_text/rl.toml — this is a train-only
|
||||
# smoke. Add an [orchestrator.eval] block (with an interval) to exercise eval.
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[ckpt]
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
@@ -0,0 +1,118 @@
|
||||
# v1 RL run: Qwen3.6-35B-A3B (MoE) on the v1 `scaleswe-v1` SWE taskset, rlm harness on a prime
|
||||
# sandbox runtime. Each scaleswe row ships its own Docker image (NEEDS_CONTAINER) which the
|
||||
# Environment injects into the prime sandbox; the agent edits the repo + runs tests there (no MCP
|
||||
# toolset). Router replay is enabled: trainer.enable_router_replay replays the routed-expert
|
||||
# decisions returned by inference (enable_return_routed_experts).
|
||||
#
|
||||
# Built from configs/debug/v1/r2e_gym.toml (the v1 SWE structure) + the MoE parallelism from
|
||||
# configs/general_agent/rl_qwen3_30b_a3b.toml. The deployment/parallelism is a starting point off
|
||||
# the 30B-A3B reference — confirm/adjust for your cluster and the 35B / 65k-context footprint.
|
||||
|
||||
max_steps = 400
|
||||
seq_len = 65536
|
||||
|
||||
[slurm]
|
||||
job_name = "scaleswe-qwen36-35b-a3b-rlm"
|
||||
project_dir = "."
|
||||
partition = "all"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 2
|
||||
|
||||
[wandb]
|
||||
project = "scaleswe-debug"
|
||||
name = "qwen36-35b-a3b-rlm"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
resume_step = -1
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3.6-35B-A3B"
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
# NCCL collective watchdog timeout — raised from default 600s: scaleswe's slow
|
||||
# multi-node startup (step-0 swebench eval + slow first SWE batch) was tripping the
|
||||
# 600s _ALLGATHER_BASE watchdog → SIGABRT trainer crash.
|
||||
dist_timeout_seconds = 3600
|
||||
# Replay the routed-expert decisions returned by inference (enable_return_routed_experts)
|
||||
# so the trainer's MoE routing matches the rollout's — cuts trainer/inference mismatch on A3B.
|
||||
enable_router_replay = true
|
||||
|
||||
[trainer.model]
|
||||
cp = 2
|
||||
# Qwen3.6 is a hybrid/linear-attention model — ring CP is unsupported; ulysses
|
||||
# all-to-all on Q/K/V works with the non-softmax kernels.
|
||||
cp_style = "ulysses"
|
||||
# Chunk the LM head over tokens to avoid materializing the full [seq, vocab] logits
|
||||
# (65k seq × large vocab) — big activation-memory saver. 1024 matches the SWE configs.
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
group_size = 16
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3.6"
|
||||
enable_thinking = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "scaleswe"
|
||||
# v1 scaleswe SWE taskset; rlm harness in a prime sandbox using the row's injected Docker image.
|
||||
taskset = { id = "scaleswe-v1" }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["scaleswe-qwen36-35b-a3b-rlm"] } }
|
||||
|
||||
[orchestrator.prime_monitor]
|
||||
|
||||
# --- Eval: SWE-Bench Verified (first 100 tasks) every 20 steps, rlm harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "swebench-verified"
|
||||
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
|
||||
harness = { id = "rlm", runtime = { type = "prime", labels = ["scaleswe-qwen36-35b-a3b-rlm"] } }
|
||||
num_examples = 100
|
||||
group_size = 1
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.85
|
||||
enable_prefix_caching = true
|
||||
# Return per-token routed-expert decisions to the trainer for router replay
|
||||
# (pairs with trainer.enable_router_replay).
|
||||
enable_return_routed_experts = true
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 65536
|
||||
# Qwen3.6 is not matched by the auto tool-parser resolver; set explicitly so vLLM
|
||||
# enables auto tool choice (the scaleswe SWE agent sends tool_choice="auto").
|
||||
tool_call_parser = "qwen3_coder"
|
||||
|
||||
[inference.parallel]
|
||||
dp = 2
|
||||
tp = 4
|
||||
@@ -60,7 +60,6 @@ temperature = 1.0
|
||||
[[orchestrator.train.env]]
|
||||
id = "rlm_swe"
|
||||
name = "rlm-swe-r2e"
|
||||
num_workers = 4
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
labels = ["rlm-swe-qwen35-4b"]
|
||||
@@ -73,8 +72,7 @@ interval = 20
|
||||
[[orchestrator.eval.env]]
|
||||
id = "rlm_swe"
|
||||
name = "rlm-swe-swebench-verified-quick"
|
||||
num_workers = 4
|
||||
timeout = 3600
|
||||
timeout = { rollout = 3600 }
|
||||
|
||||
[orchestrator.eval.env.args]
|
||||
task_type = "swebench"
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Wordle (classic v0 TextArena env) on 2 GPUs (1 trainer + 1 inference), run via the
|
||||
# legacy bridge. The Wordle-SFT model plays a full ~6-turn game per rollout; the bridge
|
||||
# serves each multi-turn rollout to the orchestrator as a vf.Trace.
|
||||
|
||||
max_steps = 200
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[wandb]
|
||||
project = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
[ckpt] # Checkpoint at the end of training
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 8
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "primeintellect/wordle"
|
||||
name = "wordle"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[trainer] # Default trainer config
|
||||
|
||||
[inference] # single inference GPU (no data parallelism)
|
||||
|
||||
# Qwen3 finetune with the standard PI template patch (byte-identical to
|
||||
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
|
||||
# Match that with the qwen3 renderer's preserve_all_thinking.
|
||||
[orchestrator.renderer]
|
||||
name = "qwen3"
|
||||
preserve_all_thinking = true
|
||||
Vendored
+1
-1
Submodule deps/pydantic-config updated: 896ade4e69...99f47c6cc0
Vendored
+1
-1
Submodule deps/renderers updated: e6dba5ad6c...1933293372
Vendored
+1
-1
Submodule deps/verifiers updated: 78c1b3c545...7c347f6110
+3
-1
@@ -25,7 +25,7 @@ impl = "custom" # or "hf" to force the HF path
|
||||
|
||||
| Family | HF config types | EP | CP |
|
||||
|---|---|---|---|
|
||||
| GLM-5 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8` | ✅ | ✅ |
|
||||
| GLM-5 / GLM-5.2 (`glm_moe_dsa`) | `zai-org/GLM-5`, `zai-org/GLM-5-FP8`, `zai-org/GLM-5.2`, `zai-org/GLM-5.2-FP8` | ✅ | ✅ |
|
||||
| Qwen3 MoE | `Qwen/Qwen3-30B-A3B`, … | ✅ | ✅ |
|
||||
| Qwen3.5 MoE | `Qwen/Qwen3.5-35B-A3B`, … | ✅ | ✅ |
|
||||
| Qwen3 / Qwen3.5 VLMs | see [Multimodal training](#multimodal-training) | MoE only | ✅ |
|
||||
@@ -38,6 +38,8 @@ impl = "custom" # or "hf" to force the HF path
|
||||
|
||||
The custom path enables you to set EP, CP, selective activation checkpointing, FP8 training (`model.fp8 = true`, requires SM90+), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
|
||||
|
||||
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
|
||||
|
||||
### Expert Parallelism Backends
|
||||
|
||||
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
|
||||
|
||||
+13
-3
@@ -136,10 +136,20 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
|
||||
|
||||
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
|
||||
|
||||
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
|
||||
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
|
||||
|
||||
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
|
||||
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
|
||||
```toml
|
||||
[orchestrator.advantage.length_penalty]
|
||||
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
|
||||
gate_by_correctness = false # when true, only penalize rollouts with reward == 1
|
||||
```
|
||||
|
||||
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
length_weighted_baseline = true
|
||||
```
|
||||
|
||||
|
||||
### Custom Advantage
|
||||
|
||||
+17
-4
@@ -30,7 +30,7 @@ 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`, `router_port`, `backend_port`, etc.
|
||||
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.
|
||||
|
||||
```toml
|
||||
[inference.deployment]
|
||||
@@ -102,7 +102,7 @@ tp = 2
|
||||
dp = 4
|
||||
```
|
||||
|
||||
This configuration will run 2 independent vLLM replicas, each with `tp=2` and `dp=4`. Routing will be handled by the `vllm-router` instance running on the same node as the 1st replica. We aim to support more advanced routing options, such as `llm-d` or `dynamo` in the future. 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 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.
|
||||
|
||||
### Wide-EP
|
||||
|
||||
@@ -167,9 +167,22 @@ This will run 3 inference replicas, each running on 6 nodes. Each replica will r
|
||||
|
||||
## Router
|
||||
|
||||
We use our own fork of [vllm-router](https://github.com/PrimeIntellect-ai/router) as the request handler. We plan to support more advanced proxy options in the future.
|
||||
Multi-node and disaggregated deployments front their vLLM backends with a router, configured via a discriminated `[...deployment.router]` block (`type = "vllm-router" | "llm-d"`):
|
||||
|
||||
Right now, router handles 2 most important things:
|
||||
```toml
|
||||
[inference.deployment.router] # or [deployment.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
|
||||
prefill_scorer_overrides = { "queue-scorer" = 2.0, "kv-cache-utilization-scorer" = 2.0 } # merged onto the P/D prefill profile
|
||||
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).
|
||||
|
||||
Both backends support the 2 most important things:
|
||||
- Request routing - KV cache re-use and balanced routing
|
||||
- P/D disaggregation - handling the prefill and decode stages separately
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# High-throughput GLM-5 with llm-d
|
||||
|
||||
This example trains `GLM-5.1` with RL on agentic SWE tasks using P/D disaggregation, FP8 inference, and a Mooncake distributed CPU KV store — fronted by the upstream [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy).
|
||||
|
||||
**llm-d is the faster way to run GLM-5.** It is the recommended router backend for large GLM-5 runs: its `active-request-scorer` is an in-flight load balancer that spreads requests across ranks immediately, instead of relying on metrics that are scraped on a delay (as the default `vllm-router` does). Combined with prefix-cache affinity for grouped rollouts, this keeps prefill and decode ranks evenly loaded under the bursty request pattern of RL. If you want the simpler default router instead, see the [GLM-5 PD disaggregation example](../glm5_pd_disag/README.md).
|
||||
|
||||
## Requirements
|
||||
|
||||
You need access to a Slurm cluster with at least **32 nodes** (16 trainer + 16 inference, 8 GPUs each) and a shared filesystem. In this guide we assume the NFS is mounted at `/shared`; you can change it to your own path.
|
||||
|
||||
You also need prime-rl cloned on your cluster into the shared filesystem.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
uv sync --all-extras
|
||||
```
|
||||
|
||||
### Install llm-d
|
||||
|
||||
The llm-d router ships as vendored binaries (`epp`, `envoy`, `pd-sidecar`). Build them once into `third_party/llmd/bin`:
|
||||
|
||||
```bash
|
||||
bash scripts/install_llmd.sh
|
||||
```
|
||||
|
||||
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
|
||||
|
||||
```bash
|
||||
touch .env
|
||||
echo "WANDB_API_KEY=your_wandb_api_key" >> .env
|
||||
echo "HUGGINGFACE_TOKEN=your_huggingface_token" >> .env
|
||||
```
|
||||
|
||||
### sandbox
|
||||
|
||||
The SWE environment is configured to use Prime Intellect Sandboxes. You can find more information about the sandboxes [here](https://docs.primeintellect.ai/sandboxes/overview). You will need to create a sandbox account and add the credentials to the `.env` file. Alternatively, you can adapt the code of the environment to use your own sandbox implementation.
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
This config is tuned for our cluster — a few values **must** be adapted to yours before you run. Search the config for these markers:
|
||||
|
||||
- **`output_dir`** (`# FILL IN`) — point it at your shared filesystem.
|
||||
- **`[slurm] partition`** (`# FILL IN`) — set it to your cluster's Slurm partition.
|
||||
- **`[inference.kv_cache_offload] device_name`** (`# do it yourself`) — the list of RDMA NICs for Mooncake. Auto-detection is unreliable, so set it by hand from `nvidia-smi topo -m` on your nodes.
|
||||
|
||||
A few more knobs you may want to tune for your hardware:
|
||||
|
||||
- **Trainer parallelism** — this config assumes **16 trainer nodes** at **131K** sequence length with `cp = 4` (context parallel) and the `adamw` optimizer. If you have fewer trainer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
|
||||
- **Scorer weights** (`[inference.deployment.router]`) — the `scorers` / `prefill_scorer_overrides` / `decode_scorer_overrides` weights follow the upstream llm-d P/D guide and are a good starting point; tune them if your prefill/decode balance drifts.
|
||||
- **Mooncake CPU pool** (`[inference.kv_cache_offload.cpu] num_bytes`) — defaults to 1TB/node; lower it if your nodes have less RAM.
|
||||
|
||||
## Tmux session
|
||||
|
||||
We recommend using the tmux helper to start the run and look at the logs.
|
||||
|
||||
From your Slurm head node:
|
||||
|
||||
```bash
|
||||
bash scripts/tmux.sh glm5-llmd /shared/outputs/glm5-llmd
|
||||
```
|
||||
|
||||
You can then attach to it by doing `tmux attach -t glm5-llmd`.
|
||||
|
||||
## Start the run
|
||||
|
||||
Run the following command to start the RL training:
|
||||
|
||||
PS: If using the tmux helper, you can run the command in the `Terminal` (window 0) pane and look at the logs in the `Logs` (window 1) pane.
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/glm5_llmd/rl.toml --output-dir /shared/outputs/glm5-llmd
|
||||
```
|
||||
|
||||
Output of the command:
|
||||
```
|
||||
XXX:XX:XX INFO Wrote subconfigs to /shared/outputs/glm5-llmd/configs [rl.py::515]
|
||||
XXX:XX:XX INFO Wrote SLURM script to /shared/outputs/glm5-llmd/rl.sbatch [rl.py::534]
|
||||
XXX:XX:XX INFO Submitting: sbatch /shared/outputs/glm5-llmd/rl.sbatch [rl.py::540]
|
||||
XXX:XX:XX SUCCESS Submitted batch job YYYY
|
||||
|
||||
Logs:
|
||||
Trainer: tail -F /shared/outputs/glm5-llmd/logs/trainer.log
|
||||
Orchestrator: tail -F /shared/outputs/glm5-llmd/logs/orchestrator.log
|
||||
Inference: tail -F /shared/outputs/glm5-llmd/logs/inference.log
|
||||
Envs: tail -F /shared/outputs/glm5-llmd/logs/envs/*/*/*.log
|
||||
```
|
||||
@@ -0,0 +1,140 @@
|
||||
max_steps = 10000000
|
||||
seq_len = 131072
|
||||
output_dir = "/shared/outputs/glm5-llmd" # FILL IN: point at your shared filesystem
|
||||
clean_output_dir = true
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[wandb]
|
||||
project = "glm5-llmd"
|
||||
name = "base"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
port = 29502
|
||||
timeout = 12000
|
||||
quantize_in_weight_transfer = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
num_infer_nodes = 16
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 1
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
num_prefill_nodes = 8
|
||||
num_prefill_replicas = 4
|
||||
num_decode_nodes = 8
|
||||
num_decode_replicas = 1
|
||||
# skip warmup for faster start in cost of some jit overhead early
|
||||
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
|
||||
prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
decode_env_overrides = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
|
||||
|
||||
# gives the most KV cache while keeping decent throughput, KV cache increase comes in from lower deep-ep LL static buffers
|
||||
prefill_vllm_overrides = {"enable_dbo"=true}
|
||||
decode_vllm_overrides = {"max_num_batched_tokens"=96, "max_num_seqs"=96}
|
||||
|
||||
[inference.deployment.router]
|
||||
type = "llm-d"
|
||||
scorers = { "prefix-cache-scorer" = 3.0 } # need some prefix-cache routing, however due to shared mooncake pool do low prio
|
||||
|
||||
prefill_scorer_overrides = { "queue-scorer" = 4.0, "active-request-scorer" = 5.0 } # prefill creates queues quite heavily, queue scorer to 4.0, active request at 5.0 is needed due to burstiness of early pipeline RL fill
|
||||
decode_scorer_overrides = { "active-request-scorer" = 5.0, "kv-cache-utilization-scorer" = 4.0, "queue-scorer" = 3.0 } # decode doesn't really create queue, it fills in KV cache fast, give 4.0
|
||||
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
|
||||
|
||||
[slurm]
|
||||
job_name = "glm5-llmd"
|
||||
partition = "all" # FILL IN: set to your cluster's partition
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 1800
|
||||
enable_token_export = true
|
||||
|
||||
[trainer.model]
|
||||
name = "zai-org/GLM-5.1"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # ignored with GLM5
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
cp = 4 # context parallel for the 131K seq len
|
||||
ep = 8
|
||||
optim_cpu_offload = true
|
||||
fp8 = true
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
lr = 1e-6
|
||||
weight_decay = 0.0
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
rollouts_per_example = 16
|
||||
max_inflight_rollouts = 2048
|
||||
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5.1-FP8"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-5.1"
|
||||
preserve_all_thinking = true
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
temperature = 1.0
|
||||
extra_body = {chat_template_kwargs = {clear_thinking = false}}
|
||||
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "rlm_swe"
|
||||
name = "r2e"
|
||||
num_workers = 16
|
||||
|
||||
[orchestrator.train.env.args]
|
||||
max_turns = 300
|
||||
timeout_seconds = 21600
|
||||
summarize_at_tokens = [35000, 80000]
|
||||
poll_interval = 5
|
||||
rlm_ref = "907115a79b2a50d193863e7ea1f3550acb4386f0"
|
||||
labels = ["glm5-llmd"]
|
||||
|
||||
[orchestrator.advantage]
|
||||
type = "default"
|
||||
|
||||
[inference]
|
||||
enable_expert_parallel = true
|
||||
# <0.80 because glm5 layers are too large for 0.85
|
||||
gpu_memory_utilization = 0.75
|
||||
enable_eplb = false
|
||||
use_deep_gemm = true
|
||||
enable_fp32_lm_head = true
|
||||
|
||||
[inference.model]
|
||||
name = "zai-org/GLM-5.1-FP8"
|
||||
max_model_len = 131072
|
||||
tool_call_parser = "glm47"
|
||||
reasoning_parser = "glm45"
|
||||
|
||||
# Speed up GLM-5.1 weight load: EP weight filtering + safetensors prefetch.
|
||||
[inference.vllm_extra]
|
||||
enable_ep_weight_filter = true
|
||||
safetensors_load_strategy = "prefetch"
|
||||
|
||||
# Mooncake distributed CPU KV store: 1TB/node shared pool across all inference nodes.
|
||||
[inference.kv_cache_offload]
|
||||
type = "mooncake"
|
||||
# Auto Detection is funky, do it yourself from nvidia-smi topo -m
|
||||
device_name = "mlx5_0,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_9,mlx5_10,mlx5_11"
|
||||
|
||||
[inference.kv_cache_offload.cpu]
|
||||
num_bytes = 1_000_000_000_000 # 1TB per node - 16TB total CPU pool
|
||||
@@ -10,6 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.8.dev28",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.1.15.dev357",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -1,25 +1,14 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import model_validator
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
env: EnvConfig = EnvConfig()
|
||||
env: EnvConfig
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
env_install_prerelease: bool = False
|
||||
"""Allow pre-release versions when installing environments. Passes ``--prerelease`` to ``prime env install``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_num_workers(self):
|
||||
if self.env.num_workers == "auto":
|
||||
self.env.num_workers = 1
|
||||
return self
|
||||
|
||||
@@ -167,8 +167,26 @@ All2AllBackend = Literal[
|
||||
]
|
||||
|
||||
|
||||
# Known llm-d EPP scorer plugins (used to guard the ``scorers`` map against typos).
|
||||
KNOWN_SCORERS = frozenset(
|
||||
{
|
||||
"prefix-cache-scorer",
|
||||
"precise-prefix-cache-scorer",
|
||||
"queue-scorer",
|
||||
"kv-cache-utilization-scorer",
|
||||
"active-request-scorer",
|
||||
"load-aware-scorer",
|
||||
"running-requests-size-scorer",
|
||||
"token-load-scorer",
|
||||
"latency-scorer",
|
||||
"session-affinity-scorer",
|
||||
"lora-affinity-scorer",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class VllmRouterConfig(BaseConfig):
|
||||
"""PrimeIntellect vllm-router fronting the per-rank (external-LB) endpoints."""
|
||||
"""PrimeIntellect vllm-router."""
|
||||
|
||||
type: Literal["vllm-router"] = "vllm-router"
|
||||
|
||||
@@ -179,9 +197,57 @@ class VllmRouterConfig(BaseConfig):
|
||||
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
|
||||
|
||||
|
||||
# Discriminated on ``type`` so additional router backends can be added to the
|
||||
# union (a single member needs no discriminator yet).
|
||||
RouterConfig: TypeAlias = VllmRouterConfig
|
||||
class LlmdRouterConfig(BaseConfig):
|
||||
"""llm-d router backend (EPP + Envoy)."""
|
||||
|
||||
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,
|
||||
}
|
||||
"""EPP scorer name → weight, applied to every routing profile (before the per-profile P/D overrides). Defaults to prefix-cache affinity plus in-flight (active-request) load balancing. Unknown scorer names are rejected."""
|
||||
|
||||
prefill_scorer_overrides: dict[str, float] = {
|
||||
"queue-scorer": 2.0,
|
||||
"kv-cache-utilization-scorer": 2.0,
|
||||
}
|
||||
"""P/D only: scorer → weight merged onto ``scorers`` for the prefill profile (a per-profile weight overrides the base)."""
|
||||
|
||||
decode_scorer_overrides: dict[str, float] = {}
|
||||
"""P/D only: scorer → weight merged onto ``scorers`` for the decode profile (a per-profile weight overrides the base); empty by default."""
|
||||
|
||||
non_cached_tokens: int = 16
|
||||
"""P/D only: requests with fewer than this many non-cached prompt tokens skip remote prefill and run decode-only."""
|
||||
|
||||
decode_sidecar_port: int = 8300
|
||||
"""P/D only: port the decode-side llm-d sidecar listens on."""
|
||||
|
||||
@property
|
||||
def prefill_scorers(self) -> dict[str, float]:
|
||||
"""Effective prefill-profile scorers: ``scorers`` merged with ``prefill_scorer_overrides``."""
|
||||
return {**self.scorers, **self.prefill_scorer_overrides}
|
||||
|
||||
@property
|
||||
def decode_scorers(self) -> dict[str, float]:
|
||||
"""Effective decode-profile scorers: ``scorers`` merged with ``decode_scorer_overrides``."""
|
||||
return {**self.scorers, **self.decode_scorer_overrides}
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_scorers(self):
|
||||
unknown = (
|
||||
set(self.scorers) | set(self.prefill_scorer_overrides) | set(self.decode_scorer_overrides)
|
||||
) - KNOWN_SCORERS
|
||||
if unknown:
|
||||
raise ValueError(f"Unknown llm-d scorer(s): {sorted(unknown)}. Known scorers: {sorted(KNOWN_SCORERS)}.")
|
||||
return self
|
||||
|
||||
|
||||
# Discriminated on ``type`` so the launch path can pick the router backend.
|
||||
RouterConfig: TypeAlias = Annotated[VllmRouterConfig | LlmdRouterConfig, Field(discriminator="type")]
|
||||
|
||||
|
||||
class BaseInferenceDeploymentConfig(BaseConfig):
|
||||
@@ -240,6 +306,12 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
|
||||
decode_env_overrides: dict[str, str] = {}
|
||||
"""Extra environment variables exported only on decode nodes."""
|
||||
|
||||
prefill_vllm_overrides: dict[str, Any] = {}
|
||||
"""Extra vLLM config options merged into --vllm-extra only for prefill ranks (SLURM only)."""
|
||||
|
||||
decode_vllm_overrides: dict[str, Any] = {}
|
||||
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
|
||||
|
||||
@property
|
||||
def num_nodes(self) -> int:
|
||||
return self.num_prefill_nodes + self.num_decode_nodes
|
||||
@@ -369,6 +441,18 @@ class InferenceConfig(BaseConfig):
|
||||
raise ValueError("Must use SLURM for multi-node / disaggregated deployment.")
|
||||
return self
|
||||
|
||||
@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:
|
||||
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. "
|
||||
"Use router type 'vllm-router' for routed-expert runs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_kv_cache_offload(self):
|
||||
if self.kv_cache_offload is not None:
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import math
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
from pydantic import AliasChoices, Field, model_serializer, model_validator
|
||||
from pydantic_core.core_schema import SerializerFunctionWrapHandler
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
@@ -143,31 +142,85 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return data
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
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."""
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
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."""
|
||||
|
||||
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
|
||||
ratio: float | None = Field(None, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Times the env server retries a failed rollout before returning an error."""
|
||||
|
||||
@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
|
||||
|
||||
@property
|
||||
def is_legacy(self) -> bool:
|
||||
"""A v0/legacy env (run via the bridge): an ``id`` is set and no v1 ``taskset`` is."""
|
||||
return not self.taskset.id
|
||||
|
||||
@property
|
||||
def env_id(self) -> str:
|
||||
"""The env identifier — the v1 taskset id (v1) or the legacy env id (v0)."""
|
||||
return self.taskset.id or self.id or ""
|
||||
|
||||
@property
|
||||
def resolved_name(self) -> str:
|
||||
return self.name or self.env_id
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env(self):
|
||||
if not self.taskset.id and not self.id:
|
||||
raise ValueError('no env configured — set taskset = { id = "<id>" } (v1) or id = "<id>" (v0/legacy)')
|
||||
if self.resolved_name == "all":
|
||||
raise ValueError(
|
||||
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
|
||||
)
|
||||
return self
|
||||
|
||||
@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. (``max_seq_len`` is added per train run in
|
||||
``OrchestratorConfig.resolve_env_config``, which knows ``seq_len``.)"""
|
||||
if self.is_legacy:
|
||||
if self.timeout.rollout is not None:
|
||||
self.extra_env_kwargs["timeout_seconds"] = self.timeout.rollout
|
||||
if self.max_output_tokens is not None:
|
||||
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_output_tokens
|
||||
return self
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
class LinearLengthPenaltyConfig(BaseConfig):
|
||||
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
gate_by_correctness: bool = False
|
||||
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None
|
||||
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
|
||||
|
||||
length_weighted_baseline: bool = False
|
||||
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseConfig):
|
||||
@@ -186,69 +239,6 @@ AdvantageConfig: TypeAlias = Annotated[
|
||||
]
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
id: str = "reverse-text"
|
||||
"""Registered verifiers environment ID (e.g. ``math-env``, ``primeintellect/math-env``). May include an ``@version`` suffix for installation."""
|
||||
|
||||
name: str | None = None
|
||||
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the ``id`` without ``@version``. Must be unique across all envs in the same group."""
|
||||
|
||||
args: dict = {}
|
||||
"""Keyword arguments forwarded to ``vf.load_environment``. See the environment's docstring for accepted args."""
|
||||
|
||||
extra_env_kwargs: dict[str, Any] = {}
|
||||
"""Extra kwargs passed to the env (e.g. ``seq_len``, ``max_total_completion_tokens``). Auto-populated by the orchestrator; user overrides are generally discouraged. The main use case is matching ``extra_env_kwargs`` when running an env in an isolated environment server."""
|
||||
|
||||
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."""
|
||||
|
||||
num_workers: int | Literal["auto"] = "auto"
|
||||
"""Worker processes for the spawned env server. ``auto`` scales to 1 worker per 256 concurrent rollouts. Ignored when ``address`` is set."""
|
||||
|
||||
ratio: float | None = Field(None, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Times the env server retries a failed rollout before returning an error."""
|
||||
|
||||
max_total_completion_tokens: int = -1
|
||||
"""Maximum total completion tokens across all turns in a multi-turn rollout. ``-1`` disables. Auto-populated into ``extra_env_kwargs``."""
|
||||
|
||||
timeout: float | None = Field(None, validation_alias=AliasChoices("timeout", "timeout_seconds"))
|
||||
"""Per-rollout wall-clock timeout in seconds. None disables."""
|
||||
|
||||
state_columns: list[str] = []
|
||||
"""Extra ``State`` fields to persist into the saved rollout records (in addition to the always-saved ``trajectory`` and ``sampling_args``). Values must be JSON-serializable."""
|
||||
|
||||
@property
|
||||
def stripped_id(self) -> str:
|
||||
"""Environment ID without the @version suffix."""
|
||||
return self.id.split("@")[0]
|
||||
|
||||
@property
|
||||
def resolved_name(self) -> str:
|
||||
return self.name or self.stripped_id
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env_name(self):
|
||||
if self.resolved_name == "all":
|
||||
raise ValueError(
|
||||
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_max_total_completion_tokens(self):
|
||||
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_total_completion_tokens
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_timeout(self):
|
||||
if self.timeout is not None:
|
||||
self.extra_env_kwargs["timeout_seconds"] = self.timeout
|
||||
return self
|
||||
|
||||
|
||||
class TrainEnvConfig(EnvConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
|
||||
@@ -278,21 +268,19 @@ class EvalEnvConfig(EnvConfig):
|
||||
|
||||
|
||||
class TrainConfig(BaseConfig):
|
||||
env: list[TrainEnvConfig] = [TrainEnvConfig()]
|
||||
env: list[TrainEnvConfig] = Field(default_factory=list)
|
||||
"""Training environments."""
|
||||
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
num_workers: int | Literal["auto"] = "auto"
|
||||
"""Default worker processes for env servers. Can be overridden per env."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, and max_retries."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling and max_retries (the
|
||||
worker ``pool`` is configured per env, defaulting to elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
@@ -300,8 +288,6 @@ class TrainConfig(BaseConfig):
|
||||
else:
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = TrainSamplingConfig(**merged)
|
||||
if "num_workers" not in env.model_fields_set:
|
||||
env.num_workers = self.num_workers
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
@@ -327,7 +313,7 @@ class TrainConfig(BaseConfig):
|
||||
|
||||
|
||||
class EvalConfig(BaseConfig):
|
||||
env: list[EvalEnvConfig] = [EvalEnvConfig()]
|
||||
env: list[EvalEnvConfig] = Field(default_factory=list)
|
||||
"""Evaluation environments."""
|
||||
|
||||
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
|
||||
@@ -339,9 +325,6 @@ class EvalConfig(BaseConfig):
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "rollouts_per_example"))
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
num_workers: int | Literal["auto"] = "auto"
|
||||
"""Default worker processes for env servers. Can be overridden per env."""
|
||||
|
||||
max_retries: int = Field(3, ge=0)
|
||||
"""Default retries for failed rollouts. Can be overridden per env."""
|
||||
|
||||
@@ -354,7 +337,8 @@ class EvalConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, group_size, and interval. Then resolve auto num_workers."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling, max_retries, 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:
|
||||
@@ -368,17 +352,8 @@ class EvalConfig(BaseConfig):
|
||||
env.group_size = self.group_size
|
||||
if "interval" not in env.model_fields_set:
|
||||
env.interval = self.interval
|
||||
if "num_workers" not in env.model_fields_set:
|
||||
env.num_workers = self.num_workers
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
# Resolve auto num_workers now that num_examples and group_size are set
|
||||
if env.num_workers == "auto":
|
||||
if env.num_examples == -1:
|
||||
env.num_workers = 4
|
||||
else:
|
||||
max_concurrent = env.num_examples * env.group_size
|
||||
env.num_workers = max(1, math.ceil(max_concurrent / 256))
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -518,30 +493,16 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
tokenizer: TokenizerConfig = TokenizerConfig()
|
||||
|
||||
renderer: RendererConfig | None = AutoRendererConfig()
|
||||
"""Typed renderer config (``renderers.RendererConfig`` discriminated
|
||||
union). Defaults to ``"auto"``, which resolves from
|
||||
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. ``None``
|
||||
opts into MITO (``openai_chat_completions``)."""
|
||||
renderer: RendererConfig = AutoRendererConfig()
|
||||
"""Typed renderer config (``renderers.RendererConfig`` discriminated union), required —
|
||||
training is renderer-only. Defaults to ``"auto"``, which resolves from
|
||||
``tokenizer.name_or_path`` via ``MODEL_RENDERER_MAP``. RL/OPD roll out through the renderer
|
||||
client; SFT uses it to backfill tokens for its chat-completions teacher."""
|
||||
|
||||
pool_size: int | None = Field(None, ge=1)
|
||||
"""Number of renderer slots shared across concurrent rollouts. Bump
|
||||
for long multi-turn prompts where client-side jinja tokenization
|
||||
serializes. Only meaningful when ``renderer`` is not ``None``."""
|
||||
|
||||
@model_serializer(mode="wrap")
|
||||
def _preserve_mito_renderer(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
|
||||
"""Emit ``renderer = "None"`` (string) when MITO so
|
||||
``model_dump(exclude_none=True)`` round-trips: dumped TOML has
|
||||
``renderer = "None"``, and on reload
|
||||
``BaseConfig._none_str_to_none`` coerces it back to ``None``.
|
||||
Without this, a MITO orchestrator config saved to
|
||||
``control/orch.toml`` would lose the renderer key entirely and
|
||||
reload as the default ``AutoRendererConfig()`` (TITO)."""
|
||||
result = handler(self)
|
||||
if self.renderer is None:
|
||||
result["renderer"] = "None"
|
||||
return result
|
||||
serializes."""
|
||||
|
||||
optim: OptimizerConfig = OptimizerConfig()
|
||||
"""Per-run optimizer configuration for multi-run training."""
|
||||
@@ -630,9 +591,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat configuration for monitoring training progress."""
|
||||
|
||||
env_install_prerelease: bool = False
|
||||
"""Allow pre-release versions when installing environments (e.g. ``verifiers>=0.1.12.dev5``). Passes ``--prerelease`` to ``prime env install``."""
|
||||
|
||||
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
|
||||
|
||||
@model_validator(mode="before")
|
||||
@@ -757,51 +715,14 @@ class OrchestratorConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _force_no_renderer_for_sft(self):
|
||||
"""Teacher-backed SFT rolls out via the teacher's plain chat-completions
|
||||
endpoint; the renderer client doesn't apply. When no teacher is
|
||||
configured, SFT uses the student rollout path and keeps the renderer."""
|
||||
if self.training_mode == "sft" and self.teacher is not None:
|
||||
self.renderer = None
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_training_mode(self):
|
||||
"""Enforce training mode invariants that involve only orchestrator fields."""
|
||||
has_teacher = self.teacher is not None
|
||||
if self.training_mode == "rl" and has_teacher:
|
||||
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
|
||||
if self.training_mode == "opd" and not has_teacher:
|
||||
raise ValueError("orchestrator.teacher must be configured when training_mode = 'opd'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_pool_size(self):
|
||||
"""``pool_size`` is only meaningful when the renderer is enabled
|
||||
(``renderer is not None``). Reject otherwise so callers don't
|
||||
silently pass it and wonder why it's ignored."""
|
||||
if self.renderer is None and self.pool_size is not None:
|
||||
raise ValueError(
|
||||
f"orchestrator.pool_size={self.pool_size!r} is set but "
|
||||
"orchestrator.renderer is None (MITO mode). Either configure a renderer "
|
||||
"or remove pool_size."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlm_requires_renderer(self):
|
||||
"""VLMs (``[model.vlm]`` block set) must go through the renderer.
|
||||
|
||||
The renderer owns the processor per-slot, produces byte-identical
|
||||
tokens, and ships generic ``mm_kwargs`` keyed by whatever the
|
||||
model's forward signature expects.
|
||||
"""
|
||||
if self.student.model.vlm is not None and self.renderer is None:
|
||||
raise ValueError(
|
||||
"orchestrator.renderer must be set when model.vlm is set. "
|
||||
"VLMs must go through a renderer (e.g. Qwen3VLRenderer) that owns the processor."
|
||||
)
|
||||
if self.training_mode in ("opd", "sft") and not has_teacher:
|
||||
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -817,7 +738,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
``DefaultRendererConfig.tool_parser`` is configured. Surface at
|
||||
config time so ``--dry-run`` reports the error.
|
||||
"""
|
||||
if self.renderer is None or self.renderer.name != "auto":
|
||||
if self.renderer.name != "auto":
|
||||
return self
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
@@ -835,9 +756,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
f"(b) [orchestrator.renderer] name=<model-specific renderer> — "
|
||||
f"if {model_id!r} is template-identical to a mapped family "
|
||||
f"(and ideally also add it upstream to "
|
||||
f"renderers.base.MODEL_RENDERER_MAP). "
|
||||
f"(c) orchestrator.renderer='none' — opt out of the renderer "
|
||||
f"client entirely (MITO)."
|
||||
f"renderers.base.MODEL_RENDERER_MAP)."
|
||||
)
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -885,12 +804,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
if "advantage" not in env_cfg.model_fields_set:
|
||||
env_cfg.advantage = self.advantage
|
||||
|
||||
# Resolve train env num_workers from max_inflight_rollouts
|
||||
for env_cfg in self.train.env:
|
||||
if env_cfg.num_workers == "auto":
|
||||
assert self.max_inflight_rollouts is not None
|
||||
env_cfg.num_workers = max(1, math.ceil(self.max_inflight_rollouts / 256))
|
||||
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -909,12 +822,15 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_config(self):
|
||||
"""Populate extra_env_kwargs and vLLM sampling defaults from top-level fields."""
|
||||
is_vllm = self.training_mode != "sft"
|
||||
"""Set vLLM sampling defaults on each train env from top-level fields."""
|
||||
if self.training_mode == "sft":
|
||||
return self
|
||||
for env in self.train.env:
|
||||
env.extra_env_kwargs.update(max_seq_len=self.seq_len)
|
||||
if is_vllm:
|
||||
env.sampling.extra_body.setdefault("top_k", -1)
|
||||
env.sampling.extra_body.setdefault("min_p", 0.0)
|
||||
env.sampling.extra_body.setdefault("return_token_ids", True)
|
||||
env.sampling.extra_body.setdefault("top_k", -1)
|
||||
env.sampling.extra_body.setdefault("min_p", 0.0)
|
||||
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
|
||||
return self
|
||||
|
||||
@@ -438,6 +438,25 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@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).
|
||||
|
||||
Runs after ``auto_setup_router_replay`` so it also catches the
|
||||
``trainer.enable_router_replay`` path, which sets the inference flag here
|
||||
(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)
|
||||
if router is not None and router.type == "llm-d":
|
||||
raise ValueError(
|
||||
"The llm-d router backend does not support routed-expert return "
|
||||
"(inference.enable_return_routed_experts / trainer.enable_router_replay): it "
|
||||
"breaks P/D and is unverified for multi-node. Use router type 'vllm-router' "
|
||||
"for router-replay runs."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_router_replay_without_kv_offload(self):
|
||||
if (
|
||||
|
||||
@@ -100,12 +100,6 @@ class ElasticConfig(BaseConfig):
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
timeout: int = 1200
|
||||
"""Request timeout in seconds."""
|
||||
|
||||
connect_timeout: float = 30.0
|
||||
"""TCP connect timeout in seconds for inference API requests."""
|
||||
|
||||
wait_for_ready_timeout: int = 1800
|
||||
"""Seconds to wait at startup for the inference pool to become ready. Applies to both the static health check and elastic DNS-based discovery."""
|
||||
|
||||
|
||||
+48
-7
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.5.0"
|
||||
version = "0.6.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
@@ -33,13 +33,16 @@ dependencies = [
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"torchtitan",
|
||||
"verifiers",
|
||||
"verifiers>=0.1.15.dev357",
|
||||
"renderers",
|
||||
"dion",
|
||||
"tilelang>=0.1.8",
|
||||
"flash-linear-attention",
|
||||
"nvidia-ml-py>=12.575.51",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
"pandas>=2.0",
|
||||
"msgspec>=0.18",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
@@ -88,11 +91,30 @@ envs = [
|
||||
"reverse-text",
|
||||
"rlm-swe",
|
||||
"rlm-search",
|
||||
"rlm-uuid-ctf",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
"wiki-search",
|
||||
"wordle",
|
||||
"reverse-text-v1",
|
||||
"gsm8k-v1",
|
||||
"math-env-v1",
|
||||
"aime24-v1",
|
||||
"alphabet-sort-v1",
|
||||
"scaleswe-v1",
|
||||
"color-codeword-v1",
|
||||
"r2e-gym-v1",
|
||||
"terminal-bench-2-v1",
|
||||
"code-golf-v1",
|
||||
"deepwiki-v1",
|
||||
"glossary-v1",
|
||||
"swelego-v1",
|
||||
"wiki-search-v1",
|
||||
"wikispeedia-v1",
|
||||
"wordle-v1",
|
||||
"general-agent-v1",
|
||||
"swebench-verified-v1",
|
||||
]
|
||||
disagg = [
|
||||
"deep-ep ; platform_machine == 'x86_64'",
|
||||
@@ -152,7 +174,7 @@ override-dependencies = [
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.9.0",
|
||||
"openenv-core",
|
||||
"verifiers[packages]>=0.1.15.dev150",
|
||||
"verifiers>=0.1.15.dev357",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
@@ -187,8 +209,6 @@ prime-tunnel = false
|
||||
prime-evals = false
|
||||
verifiers = false
|
||||
renderers = false
|
||||
tasksets = false
|
||||
harnesses = false
|
||||
prime-pydantic-config = false
|
||||
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
|
||||
vllm-router = false
|
||||
@@ -199,6 +219,10 @@ nixl-cu12 = false
|
||||
|
||||
[tool.uv.sources]
|
||||
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
|
||||
# prime-rl depends on the one `verifiers` package (v0 + v1 + the legacy bridge + the built-in v1
|
||||
# harnesses/tasksets, now bundled in verifiers.v1). v0 envs resolve from
|
||||
# deps/{verifiers,research-environments}/environments; v1 tasksets (`-v1`) and the `compact`
|
||||
# example live under deps/verifiers/environments.
|
||||
verifiers = { path = "deps/verifiers", editable = true }
|
||||
renderers = { path = "deps/renderers", editable = true }
|
||||
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
|
||||
@@ -210,7 +234,6 @@ color-codeword = { path = "deps/research-environments/environments/color_codewor
|
||||
deepdive = { path = "deps/research-environments/environments/deepdive", editable = true }
|
||||
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
|
||||
gpqa = { path = "deps/research-environments/environments/gpqa", editable = true }
|
||||
harnesses = { path = "deps/verifiers/packages/harnesses", editable = true }
|
||||
hle = { path = "deps/research-environments/environments/hle", editable = true }
|
||||
ifeval = { path = "deps/research-environments/environments/ifeval", editable = true }
|
||||
livecodebench = { path = "deps/research-environments/environments/livecodebench", editable = true }
|
||||
@@ -228,12 +251,30 @@ opencode-swe = { path = "deps/research-environments/environments/opencode_swe",
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf", editable = true }
|
||||
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
|
||||
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
|
||||
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
|
||||
tasksets = { path = "deps/verifiers/packages/tasksets", editable = true }
|
||||
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
|
||||
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
|
||||
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
|
||||
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
|
||||
math-env-v1 = { path = "deps/verifiers/environments/math_env_v1", editable = true }
|
||||
aime24-v1 = { path = "deps/verifiers/environments/aime24_v1", editable = true }
|
||||
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
|
||||
scaleswe-v1 = { path = "deps/verifiers/environments/scaleswe_v1", editable = true }
|
||||
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
|
||||
r2e-gym-v1 = { path = "deps/verifiers/environments/r2e_gym_v1", editable = true }
|
||||
terminal-bench-2-v1 = { path = "deps/verifiers/environments/terminal_bench_2_v1", editable = true }
|
||||
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
|
||||
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
|
||||
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
|
||||
swelego-v1 = { path = "deps/verifiers/environments/swelego_v1", editable = true }
|
||||
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
|
||||
wikispeedia-v1 = { path = "deps/verifiers/environments/wikispeedia_v1", editable = true }
|
||||
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
|
||||
general-agent-v1 = { path = "deps/verifiers/environments/general_agent_v1", editable = true }
|
||||
swebench-verified-v1 = { path = "deps/verifiers/environments/swebench_verified_v1", editable = true }
|
||||
torch = { index = "pytorch-cu128" }
|
||||
torchvision = { index = "pytorch-cu128" }
|
||||
torchaudio = { index = "pytorch-cu128" }
|
||||
|
||||
@@ -4,8 +4,74 @@ set -e
|
||||
# Set higher ulimit for file descriptors to prevent API timeout issues
|
||||
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
|
||||
|
||||
# Allow runtime override of the prime-rl source itself.
|
||||
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
|
||||
# optionally points at a fork; defaults to the upstream repo.
|
||||
#
|
||||
# We clone into a per-ref dir under /tmp, seed the venv from the baked
|
||||
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
|
||||
# `uv sync --inexact` re-installs prime_rl from the override source.
|
||||
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
|
||||
# resolves the entrypoints from the override venv.
|
||||
if [ -n "$PRIME_RL_REF" ]; then
|
||||
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
|
||||
# Slug + content hash for the cache dir name. Slug keeps the path
|
||||
# human-readable; the hash (over repo + ref) prevents collisions
|
||||
# between distinct refs that slugify the same way (e.g. `feat/foo`
|
||||
# vs `feat-foo`) and between the same ref on different forks.
|
||||
REF_SLUG="${PRIME_RL_REF//\//-}"
|
||||
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
|
||||
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
|
||||
# Rewrite ssh://git@github.com URLs to https so submodules listed
|
||||
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
|
||||
# can be cloned from the pod without ssh keys.
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
if [ ! -d "$DEST/.git" ]; then
|
||||
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
|
||||
rm -rf "$DEST"
|
||||
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
|
||||
fi
|
||||
# Always fetch + checkout so mutable refs (branches/tags) pick up new
|
||||
# commits between pod restarts. No-op for immutable SHAs.
|
||||
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
|
||||
git -C "$DEST" fetch --quiet --tags --force origin
|
||||
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
|
||||
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
|
||||
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
|
||||
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
|
||||
# Refresh submodules to whatever the parent commit pins. `sync`
|
||||
# picks up URL changes in .gitmodules between checkouts on cache
|
||||
# hit; `update --init --recursive` applies the pinned SHAs.
|
||||
git -C "$DEST" submodule sync --recursive
|
||||
git -C "$DEST" submodule update --init --recursive
|
||||
if [ ! -d "$DEST/.venv" ]; then
|
||||
# Seed from the baked venv so the heavy wheels (flash-attn,
|
||||
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
|
||||
# hardlinks): a subsequent `uv sync` writes into this tree, and
|
||||
# hardlinks would leak those writes back into /app/.venv when
|
||||
# /tmp and /app share a filesystem.
|
||||
cp -a /app/.venv "$DEST/.venv"
|
||||
fi
|
||||
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
|
||||
# Mirror the image's extras (Dockerfile.cuda:82) — explicit instead
|
||||
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
|
||||
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
|
||||
# startup. --inexact keeps the seeded venv's pre-built wheels
|
||||
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
|
||||
# override's lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev \
|
||||
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
|
||||
--extra envs --extra gpt-oss --extra modelexpress \
|
||||
--group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
cd "$DEST"
|
||||
fi
|
||||
|
||||
# Allow runtime override of the verifiers package version.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
|
||||
# PRIME_RL_REF swap so when both are set the install lands in the override
|
||||
# venv (uv pip install targets $VIRTUAL_ENV when exported).
|
||||
if [ -n "$VERIFIERS_VERSION" ]; then
|
||||
echo "Installing verifiers version: $VERIFIERS_VERSION"
|
||||
uv pip install --reinstall-package verifiers \
|
||||
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install the llm-d standalone (no-Kubernetes) routing binaries into
|
||||
# third_party/llmd/bin:
|
||||
# - epp : llm-d-router Endpoint Picker (the routing brain)
|
||||
# - pd-sidecar : decode-side proxy for P/D disaggregation
|
||||
# - envoy : the data-plane proxy that calls the EPP via ext_proc
|
||||
#
|
||||
# epp/pd-sidecar are built from a pinned llm-d-router commit. We currently build
|
||||
# from a small fork that adds P/D disaggregation for vLLM's token-in
|
||||
# /inference/v1/generate endpoint (prime-rl's renderer / TITO rollout path) —
|
||||
# upstream's pd-sidecar only disaggregates the OpenAI endpoints, so token-in P/D
|
||||
# silently runs decode-only. The fork is pending upstream PR
|
||||
# llm-d/llm-d-router#1458; switch LLMD_ROUTER_REPO back to the upstream repo and
|
||||
# bump LLMD_ROUTER_REF once it merges. The fork is branched off the upstream
|
||||
# commit that added the EPP vllmhttp parser (PR #1248), which the renderer path
|
||||
# also needs.
|
||||
#
|
||||
# System Go is not required: a Go toolchain is vendored under third_party/llmd/go
|
||||
# and used to bootstrap; GOTOOLCHAIN=auto fetches the exact version the module
|
||||
# pins. Envoy is extracted as a static binary from its release container image
|
||||
# WITHOUT docker: we build `crane` (pure-Go, talks straight to the OCI registry)
|
||||
# with the same vendored toolchain and use it to export the image filesystem.
|
||||
# This is the only step that previously required a docker daemon, which cluster
|
||||
# compute nodes don't have.
|
||||
set -euo pipefail
|
||||
|
||||
LLMD_ROUTER_REPO="${LLMD_ROUTER_REPO:-https://github.com/S1ro1/llm-d-router.git}"
|
||||
LLMD_ROUTER_REF="${LLMD_ROUTER_REF:-1ca4243ec84c657b4a5f507a1776d6c15a618d5b}"
|
||||
GO_BOOTSTRAP_VERSION="${GO_BOOTSTRAP_VERSION:-1.23.4}"
|
||||
ENVOY_VERSION="${ENVOY_VERSION:-1.36.0}"
|
||||
ENVOY_IMAGE="${ENVOY_IMAGE:-envoyproxy/envoy:v${ENVOY_VERSION}}"
|
||||
|
||||
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
PROJECT_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
|
||||
LLMD_DIR="$PROJECT_DIR/third_party/llmd"
|
||||
BIN_DIR="$LLMD_DIR/bin"
|
||||
GO_ROOT="$LLMD_DIR/go"
|
||||
SRC_DIR="$LLMD_DIR/src"
|
||||
GO_TOOLS_BIN="$LLMD_DIR/gotools/bin"
|
||||
mkdir -p "$BIN_DIR" "$GO_TOOLS_BIN"
|
||||
|
||||
# --- Go toolchain (vendored bootstrap; auto-upgrades to the module's version) ---
|
||||
if [ ! -x "$GO_ROOT/bin/go" ]; then
|
||||
echo "[install_llmd] downloading bootstrap Go $GO_BOOTSTRAP_VERSION"
|
||||
rm -rf "$GO_ROOT"
|
||||
curl -fsSL "https://go.dev/dl/go${GO_BOOTSTRAP_VERSION}.linux-amd64.tar.gz" | tar -xz -C "$LLMD_DIR"
|
||||
fi
|
||||
export GOROOT="$GO_ROOT"
|
||||
export PATH="$GO_ROOT/bin:$PATH"
|
||||
export GOTOOLCHAIN=auto
|
||||
echo "[install_llmd] bootstrap $(go version)"
|
||||
|
||||
# --- Fetch llm-d-router source at the pinned ref ---
|
||||
echo "[install_llmd] fetching ${LLMD_ROUTER_REPO}@${LLMD_ROUTER_REF}"
|
||||
if [ ! -d "$SRC_DIR/.git" ]; then
|
||||
rm -rf "$SRC_DIR"
|
||||
git clone --quiet "$LLMD_ROUTER_REPO" "$SRC_DIR"
|
||||
fi
|
||||
git -C "$SRC_DIR" remote set-url origin "$LLMD_ROUTER_REPO"
|
||||
git -C "$SRC_DIR" fetch --quiet origin
|
||||
git -C "$SRC_DIR" checkout --quiet "$LLMD_ROUTER_REF"
|
||||
|
||||
# --- Build epp + pd-sidecar ---
|
||||
echo "[install_llmd] building epp + pd-sidecar"
|
||||
( cd "$SRC_DIR" && go build -o "$BIN_DIR/epp" ./cmd/epp && go build -o "$BIN_DIR/pd-sidecar" ./cmd/pd-sidecar )
|
||||
|
||||
# --- Envoy static binary (extract from the release image; keep if present) ---
|
||||
# No docker: build crane with the vendored toolchain and export the image's
|
||||
# filesystem straight from the registry, then pull out the static envoy binary.
|
||||
if [ ! -x "$BIN_DIR/envoy" ]; then
|
||||
if [ ! -x "$GO_TOOLS_BIN/crane" ]; then
|
||||
echo "[install_llmd] building crane (OCI registry client, no docker needed)"
|
||||
GOBIN="$GO_TOOLS_BIN" GOFLAGS=-mod=mod \
|
||||
go install github.com/google/go-containerregistry/cmd/crane@latest
|
||||
fi
|
||||
echo "[install_llmd] extracting Envoy ${ENVOY_VERSION} from ${ENVOY_IMAGE}"
|
||||
"$GO_TOOLS_BIN/crane" export "$ENVOY_IMAGE" - \
|
||||
| tar -xf - -O usr/local/bin/envoy > "$BIN_DIR/envoy"
|
||||
chmod +x "$BIN_DIR/envoy"
|
||||
fi
|
||||
|
||||
echo "[install_llmd] installed binaries in $BIN_DIR:"
|
||||
"$BIN_DIR/epp" --version 2>&1 | head -1 || true
|
||||
"$BIN_DIR/envoy" --version 2>&1 | head -1 || true
|
||||
"$BIN_DIR/pd-sidecar" --help >/dev/null 2>&1 && echo " pd-sidecar OK" || true
|
||||
echo "[install_llmd] done"
|
||||
+3
-3
@@ -81,7 +81,7 @@ tmux send-keys -t "$SESSION_NAME:Logs.1" \
|
||||
"tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.2" \
|
||||
"tail -F ${LOG_DIR}/envs/*/*/*.log 2>/dev/null" C-m
|
||||
"tail -F ${LOG_DIR}/envs/*/*.log 2>/dev/null" C-m
|
||||
|
||||
tmux send-keys -t "$SESSION_NAME:Logs.3" \
|
||||
"tail -F ${LOG_DIR}/inference.log 2>/dev/null" C-m
|
||||
@@ -95,8 +95,8 @@ tmux send-keys -t "$SESSION_NAME:Claude" \
|
||||
All ranks: ${LOG_DIR}/trainer/torchrun/*/*/*/*.log
|
||||
Orchestrator: ${LOG_DIR}/orchestrator.log
|
||||
Inference: ${LOG_DIR}/inference.log
|
||||
Envs: ${LOG_DIR}/envs/*/*/*.log
|
||||
Train envs: ${LOG_DIR}/envs/train/*/*.log
|
||||
Envs: ${LOG_DIR}/envs/*/*.log
|
||||
Train envs: ${LOG_DIR}/envs/train/*.log
|
||||
You are running inside tmux session \"${SESSION_NAME}\". The Launcher window (window 0) is where the user runs launch commands. You can read its contents with: tmux capture-pane -t ${SESSION_NAME}:Launcher -p
|
||||
Help the user monitor and debug this run.'" C-m
|
||||
|
||||
|
||||
+11
-1
@@ -27,7 +27,7 @@ uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
|
||||
```
|
||||
|
||||
The `envs` extra installs every env workspace listed in `[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and `[tool.uv.sources]`.
|
||||
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
@@ -59,6 +59,16 @@ Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
bash scripts/install_llmd.sh # builds epp + pd-sidecar from a pinned llm-d-router commit (vendored Go), fetches envoy
|
||||
```
|
||||
|
||||
Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, so SLURM nodes see them). `epp` is pinned to the commit that includes the `vllmhttp-parser` (PR #1248) so prime-rl's renderer/TITO `/inference/v1/generate` path routes correctly. Override the pin with `LLMD_ROUTER_REF=<sha>`. The EPP + Envoy + endpoints configs are rendered from `templates/llmd/*.yaml.j2` (included into the SLURM script); only the per-node IPv4 addresses are filled in inline at launch time.
|
||||
|
||||
## Key files
|
||||
|
||||
- `pyproject.toml` — dependencies, extras, dependency groups
|
||||
|
||||
@@ -71,9 +71,7 @@ After a restart, verify all processes are back up and progress resumed before th
|
||||
├── inference/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
│ └── router_0.log # vllm-router per replica (multi-node only)
|
||||
└── envs/{train,eval}/{env_name}/
|
||||
├── env_server.log
|
||||
└── env_worker_*.log
|
||||
└── envs/{train,eval}/{env_name}.log # one log file per env
|
||||
```
|
||||
|
||||
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
|
||||
@@ -82,7 +80,7 @@ Scan for problems:
|
||||
|
||||
```bash
|
||||
grep -E "WARNING|ERROR" {output_dir}/logs/{trainer,orchestrator,inference}.log
|
||||
grep -E "WARNING|ERROR" {output_dir}/logs/envs/train/*/env_{server,worker_*}.log
|
||||
grep -E "WARNING|ERROR" {output_dir}/logs/envs/{train,eval}/*.log
|
||||
```
|
||||
|
||||
### Metrics
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import tomli_w
|
||||
|
||||
@@ -14,6 +16,17 @@ INFERENCE_TOML = "inference.toml"
|
||||
INFERENCE_SBATCH = "inference.sbatch"
|
||||
|
||||
|
||||
def vllm_overrides_fragment(overrides: dict[str, Any]) -> str:
|
||||
"""Render per-role vLLM overrides as a JSON fragment for the ROLE_EXTRA bash string.
|
||||
|
||||
Returns a leading-comma fragment with quotes escaped for the double-quoted assignment
|
||||
(e.g. `, \\"max_num_seqs\\": 256`), or an empty string when there are no overrides.
|
||||
"""
|
||||
if not overrides:
|
||||
return ""
|
||||
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."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -47,7 +60,7 @@ 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,
|
||||
disaggregated=is_disaggregated,
|
||||
is_disaggregated=is_disaggregated,
|
||||
kv_offload=offload is not None,
|
||||
kv_offload_mooncake=is_mooncake,
|
||||
kv_offload_cpu_bytes=int(offload.cpu.num_bytes) if is_mooncake else 0,
|
||||
@@ -65,20 +78,21 @@ 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_port=config.deployment.router.port,
|
||||
router_policy=config.deployment.router.policy,
|
||||
router=config.deployment.router,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
use_deep_gemm=config.use_deep_gemm,
|
||||
prefill_env_overrides=config.deployment.prefill_env_overrides,
|
||||
decode_env_overrides=config.deployment.decode_env_overrides,
|
||||
prefill_vllm_extra_json=vllm_overrides_fragment(config.deployment.prefill_vllm_overrides),
|
||||
decode_vllm_extra_json=vllm_overrides_fragment(config.deployment.decode_vllm_overrides),
|
||||
)
|
||||
elif is_multi_node:
|
||||
template_vars.update(
|
||||
router_port=config.deployment.router.port,
|
||||
router=config.deployment.router,
|
||||
backend_port=config.deployment.backend_port,
|
||||
router_policy=config.deployment.router.policy,
|
||||
data_parallel_rpc_port=config.data_parallel_rpc_port,
|
||||
enable_expert_parallel=config.enable_expert_parallel,
|
||||
infer_nodes_per_replica=config.deployment.num_nodes,
|
||||
)
|
||||
|
||||
script = template.render(**template_vars)
|
||||
|
||||
@@ -12,7 +12,9 @@ from threading import Event, Thread
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.inference import VllmRouterConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.entrypoints.inference import vllm_overrides_fragment
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
@@ -371,7 +373,7 @@ 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_port=infer_deploy.router.port,
|
||||
router=infer_deploy.router,
|
||||
prefill_port=infer_deploy.prefill_port,
|
||||
decode_port=infer_deploy.decode_port,
|
||||
inference_tp=config.inference.parallel.tp,
|
||||
@@ -379,6 +381,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
use_deep_gemm=config.inference.use_deep_gemm,
|
||||
prefill_env_overrides=infer_deploy.prefill_env_overrides,
|
||||
decode_env_overrides=infer_deploy.decode_env_overrides,
|
||||
prefill_vllm_extra_json=vllm_overrides_fragment(infer_deploy.prefill_vllm_overrides),
|
||||
decode_vllm_extra_json=vllm_overrides_fragment(infer_deploy.decode_vllm_overrides),
|
||||
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",
|
||||
@@ -397,7 +401,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
nodes_per_infer_replica=config.deployment.num_infer_nodes,
|
||||
num_infer_replicas=config.deployment.num_infer_replicas,
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
router_port=config.inference.deployment.router.port if config.inference else 8000,
|
||||
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
|
||||
infer_nodes_per_replica=config.deployment.num_infer_nodes,
|
||||
backend_port=config.inference.deployment.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,
|
||||
|
||||
@@ -21,6 +21,68 @@ def transformers_v5_compat():
|
||||
monkey_patch_deep_gemm_silu_mul_quant_int64()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
|
||||
|
||||
def monkey_patch_kv_xfer_finished_tolerate_freed():
|
||||
"""Tolerate KV-transfer finish notifications for already-freed requests.
|
||||
|
||||
In disaggregated P/D (NIXL, optionally + a KV store connector) a request can
|
||||
be finished — most often ``FINISHED_ABORTED`` from an off-policy cancel, a
|
||||
client disconnect, or a request timeout — while it still has in-flight KV
|
||||
transfers. When such a request's ``finished_recving`` and ``finished_sending``
|
||||
both land in the same ``Scheduler.update_from_output`` step, the stock
|
||||
``_update_from_kv_xfer_finished`` frees it in the recving branch
|
||||
(``_free_blocks`` -> ``del self.requests[req_id]``) and then the sending
|
||||
branch hits ``assert req_id in self.requests`` and kills the EngineCore. On a
|
||||
DP deployment that one death cascades to every rank via the gloo finish-state
|
||||
all-reduce, taking down the whole inference pool.
|
||||
|
||||
The trigger is the abort itself, not weight-update pause/resume: it reproduces
|
||||
during normal stepping whenever an aborted request's recv and send complete in
|
||||
the same step (observed with zero off-policy cancellations, driven only by
|
||||
incidental client-side aborts). Skip already-freed request ids instead of
|
||||
asserting — their blocks are freed either way, so dropping the stale
|
||||
notification is safe.
|
||||
|
||||
Upstream issue: https://github.com/vllm-project/vllm/issues/46240
|
||||
"""
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.core.sched.scheduler import Scheduler
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
logger = init_logger("vllm.v1.core.sched.scheduler")
|
||||
|
||||
if getattr(Scheduler._update_from_kv_xfer_finished, "_prime_rl_tolerates_freed", False):
|
||||
return
|
||||
|
||||
def _update_from_kv_xfer_finished(self, kv_connector_output):
|
||||
if self.connector is not None:
|
||||
self.connector.update_connector_output(kv_connector_output)
|
||||
|
||||
for req_id in kv_connector_output.finished_recving or ():
|
||||
logger.debug("Finished recving KV transfer for request %s", req_id)
|
||||
# Stale notification for a request freed earlier this step (e.g. an
|
||||
# aborted request whose send completion freed it). Nothing to do.
|
||||
if req_id not in self.requests:
|
||||
continue
|
||||
req = self.requests[req_id]
|
||||
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
|
||||
self.finished_recving_kv_req_ids.add(req_id)
|
||||
else:
|
||||
assert RequestStatus.is_finished(req.status)
|
||||
self._free_blocks(self.requests[req_id])
|
||||
for req_id in kv_connector_output.finished_sending or ():
|
||||
logger.debug("Finished sending KV transfer for request %s", req_id)
|
||||
# See above: the recving branch may have already freed an aborted
|
||||
# request whose send also completed this step.
|
||||
if req_id not in self.requests:
|
||||
continue
|
||||
self._free_blocks(self.requests[req_id])
|
||||
|
||||
_update_from_kv_xfer_finished._prime_rl_tolerates_freed = True
|
||||
Scheduler._update_from_kv_xfer_finished = _update_from_kv_xfer_finished
|
||||
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
|
||||
|
||||
|
||||
def monkey_patch_nano_v3_reasoning_parser():
|
||||
|
||||
@@ -4,21 +4,17 @@ from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Callable
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from jaxtyping import Float
|
||||
from torch import Tensor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
from prime_rl.configs.orchestrator import (
|
||||
AdvantageConfig,
|
||||
CustomAdvantageConfig,
|
||||
LengthPenaltyConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -26,7 +22,7 @@ from prime_rl.utils.utils import import_object
|
||||
class AdvantageInputs:
|
||||
"""Inputs for advantage computation of a single group (one example × N rollouts)."""
|
||||
|
||||
rollouts: list[vf.RolloutOutput]
|
||||
rollouts: list[vf.Trace]
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -50,68 +46,36 @@ entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_penalty: LengthPenaltyConfig | None = None,
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None,
|
||||
max_seq_len: int | None = None,
|
||||
length_weighted_baseline: bool = False,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage for a single group: reward minus per-group baseline.
|
||||
|
||||
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
|
||||
cost: tokens (weighted completion + tool-response) or trajectory turn count.
|
||||
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
|
||||
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
|
||||
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
|
||||
mean reward as the baseline instead of the plain mean.
|
||||
"""
|
||||
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
|
||||
rewards = torch.tensor([r.reward for r in inputs.rollouts], dtype=torch.float32)
|
||||
lengths = torch.tensor([r.completion_len for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
|
||||
if isinstance(length_penalty, TokensLengthPenaltyConfig):
|
||||
w_c = length_penalty.completion_weight
|
||||
w_t = length_penalty.tool_response_weight
|
||||
costs = torch.tensor(
|
||||
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
|
||||
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if length_penalty is not None:
|
||||
if max_seq_len is None:
|
||||
raise ValueError("max_seq_len is required when length_penalty is enabled")
|
||||
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
|
||||
if length_penalty.gate_by_correctness:
|
||||
penalty = penalty * rewards
|
||||
rewards = rewards - penalty
|
||||
|
||||
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
|
||||
if length_weighted_baseline:
|
||||
baseline = (lengths * rewards).sum() / lengths.sum()
|
||||
else:
|
||||
baseline = rewards.mean()
|
||||
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
|
||||
|
||||
|
||||
def _efficiency_shaping(
|
||||
rewards: Float[Tensor, "group_size"],
|
||||
costs: Float[Tensor, "group_size"],
|
||||
) -> Float[Tensor, "group_size"]:
|
||||
"""Correctness-gated efficiency shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
|
||||
(e.g., completion length in tokens or number of turns).
|
||||
|
||||
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
|
||||
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max()
|
||||
correct_mask = rewards >= max_reward
|
||||
num_correct = correct_mask.sum()
|
||||
|
||||
# No shaping when max reward is 0 — no correct rollouts to differentiate
|
||||
if max_reward <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
# Mean cost of correct rollouts
|
||||
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
|
||||
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
|
||||
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
|
||||
if mean_correct_cost <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
return shaped_rewards - shaped_rewards.mean()
|
||||
|
||||
|
||||
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
|
||||
"""Setup advantage function from config."""
|
||||
if isinstance(config, CustomAdvantageConfig):
|
||||
custom_fn = import_object(config.import_path)
|
||||
@@ -123,25 +87,29 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
return advantage_fn
|
||||
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_penalty=config.length_penalty,
|
||||
max_seq_len=max_seq_len,
|
||||
length_weighted_baseline=config.length_weighted_baseline,
|
||||
)
|
||||
|
||||
return advantage_fn
|
||||
|
||||
|
||||
def assign_advantages(
|
||||
rollouts: list["TrainRollout"], # noqa: F821 (forward ref)
|
||||
rollouts: list[Rollout],
|
||||
advantage_fn: AdvantageFn | None,
|
||||
) -> None:
|
||||
"""Compute and assign advantages for one finished group of rollouts
|
||||
(``TrainSink.process_group`` hands in a single group's surviving rollouts).
|
||||
``advantage_fn=None`` is the trivial case (advantage = reward); a custom
|
||||
``advantage_fn`` receives the raw ``vf.RolloutOutput``\\ s via
|
||||
``AdvantageInputs.rollouts``.
|
||||
``advantage_fn`` receives the ``vf.Trace``\\ s via ``AdvantageInputs.rollouts``.
|
||||
"""
|
||||
if advantage_fn is None:
|
||||
for rollout in rollouts:
|
||||
rollout.advantage = rollout.reward
|
||||
return
|
||||
result = advantage_fn(AdvantageInputs(rollouts=[r.raw for r in rollouts]))
|
||||
result = advantage_fn(AdvantageInputs(rollouts=[r for r in rollouts]))
|
||||
for rollout, advantage in zip(rollouts, result.advantages):
|
||||
rollout.advantage = advantage
|
||||
|
||||
@@ -6,13 +6,14 @@
|
||||
- Emit-everything invariant: every dispatched rollout eventually reaches
|
||||
``out_q`` exactly once as a ``TrainRollout`` / ``EvalRollout``. Failures
|
||||
(env error, empty trajectory, task exception, off-policy cancel) carry
|
||||
``raw["error"]`` set; sinks decide drop / partial-train policy.
|
||||
``trace.error`` set; sinks decide drop / partial-train policy.
|
||||
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight rollouts of the opposite kind drain
|
||||
naturally on either side of an eval boundary.
|
||||
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
|
||||
in-flight train rollouts and drops groups past ``max_off_policy_steps``.
|
||||
- ``on_version_pending`` (called by the watcher before the engines pause for
|
||||
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
|
||||
drops groups past ``max_off_policy_steps``.
|
||||
Eval rollouts are measurements for the policy version they started with,
|
||||
so they are allowed to finish even if training advances.
|
||||
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
|
||||
@@ -28,20 +29,18 @@ from dataclasses import dataclass, field
|
||||
from enum import Enum, auto
|
||||
from typing import Literal
|
||||
|
||||
import verifiers as vf
|
||||
import verifiers.v1 as vf
|
||||
from aiolimiter import AsyncLimiter
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
EvalRollout,
|
||||
FinishedRollout,
|
||||
GroupState,
|
||||
InflightRollout,
|
||||
Policy,
|
||||
Rollout,
|
||||
RolloutKind,
|
||||
TrainRollout,
|
||||
)
|
||||
from prime_rl.utils.async_utils import safe_cancel, safe_cancel_all
|
||||
from prime_rl.utils.client import InferencePool, client_identity
|
||||
@@ -116,7 +115,7 @@ class RolloutDispatcher:
|
||||
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
|
||||
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
|
||||
rollouts under shared capacity, and emits ``FinishedRollout``\\ s to
|
||||
``out_q``. The watcher drives ``on_new_version`` for off-policy
|
||||
``out_q``. The watcher drives ``on_version_pending`` for off-policy
|
||||
cancellation; the orchestrator triggers eval epochs."""
|
||||
|
||||
def __init__(
|
||||
@@ -158,7 +157,7 @@ class RolloutDispatcher:
|
||||
self.groups: dict[uuid.UUID, GroupState] = {}
|
||||
|
||||
# Bounded so the dispatcher backpressures on a slow sink
|
||||
self.out_q: asyncio.Queue[FinishedRollout] = asyncio.Queue(maxsize=max(8, self.max_inflight))
|
||||
self.out_q: asyncio.Queue[Rollout] = asyncio.Queue(maxsize=max(8, self.max_inflight))
|
||||
|
||||
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
|
||||
# Set by the orchestrator after the final train step; pipeline then
|
||||
@@ -263,11 +262,16 @@ class RolloutDispatcher:
|
||||
await safe_cancel(self.task)
|
||||
self.task = None
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""Bump off-policy counters and drop groups past
|
||||
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
|
||||
the sink still finalizes the partial group). Eval rollouts are not
|
||||
aged because they are tied to their start-time policy version."""
|
||||
aged because they are tied to their start-time policy version.
|
||||
|
||||
Runs *before* the inference engines are paused for the weight update so
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
stale_groups: set[uuid.UUID] = set()
|
||||
cancelled = 0
|
||||
for meta in self.inflight.values():
|
||||
@@ -287,6 +291,9 @@ class RolloutDispatcher:
|
||||
"Consider increasing it to avoid this."
|
||||
)
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
|
||||
|
||||
async def fill_inflight(self) -> None:
|
||||
"""Schedule new rollouts up to ``max_inflight``, honoring
|
||||
``self.mode``. Eval scheduling ignores the orchestrator's dispatch
|
||||
@@ -373,7 +380,7 @@ class RolloutDispatcher:
|
||||
return GroupState(
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
example=example,
|
||||
task_idx=example["task_idx"],
|
||||
rollouts_to_schedule=group_size,
|
||||
target_rollouts=group_size,
|
||||
eval_step=eval_step,
|
||||
@@ -427,7 +434,7 @@ class RolloutDispatcher:
|
||||
task: asyncio.Task = asyncio.create_task(
|
||||
env.run_group(
|
||||
client=client,
|
||||
example=group.example,
|
||||
task_idx=group.task_idx,
|
||||
model_name=model_name,
|
||||
group_size=permits,
|
||||
cache_salt=cache_salt,
|
||||
@@ -440,7 +447,7 @@ class RolloutDispatcher:
|
||||
task = asyncio.create_task(
|
||||
env.run_rollout(
|
||||
client=client,
|
||||
example=group.example,
|
||||
task_idx=group.task_idx,
|
||||
model_name=model_name,
|
||||
cache_salt=cache_salt,
|
||||
)
|
||||
@@ -484,97 +491,60 @@ class RolloutDispatcher:
|
||||
is_synth_exception = False
|
||||
try:
|
||||
result = task.result()
|
||||
rollouts: list[vf.RolloutOutput] = result if isinstance(result, list) else [result]
|
||||
rollouts: list[Rollout] = result if isinstance(result, list) else [result]
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except Exception as exc:
|
||||
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
|
||||
rollouts = [
|
||||
self.error_rollout_output(error_type=type(exc).__name__, error_repr=repr(exc))
|
||||
for _ in range(meta.rollout_count)
|
||||
]
|
||||
task_idx = group.task_idx if group is not None else -1
|
||||
rollouts = [Rollout(task=vf.Task(idx=task_idx, prompt=None)) for _ in range(meta.rollout_count)]
|
||||
for r in rollouts:
|
||||
r.capture_error(exc)
|
||||
is_synth_exception = True
|
||||
|
||||
for r in rollouts:
|
||||
if r.get("error") is None and len(r.get("trajectory") or []) == 0:
|
||||
if not r.has_error and r.num_turns == 0:
|
||||
# Empty trajectory: promote to an explicit error so the sink
|
||||
# treats it like any other failure
|
||||
r["error"] = {
|
||||
"error": "EmptyTrajectory",
|
||||
"error_chain_repr": "Rollout returned with no trajectory steps",
|
||||
"error_chain_str": "",
|
||||
}
|
||||
r.errors.append(vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps"))
|
||||
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
|
||||
if r.get("error") is not None:
|
||||
err_type = r["error"].get("error", "Unknown")
|
||||
if r.has_error:
|
||||
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
|
||||
if not is_synth_exception:
|
||||
get_logger().warning(
|
||||
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — "
|
||||
f"{r['error'].get('error_chain_repr', err_type)}"
|
||||
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.error.type}: {r.error.message}"
|
||||
)
|
||||
await self.emit_rollout(meta, group, r)
|
||||
|
||||
async def emit_rollout(self, meta: InflightRollout, group: GroupState | None, raw: vf.RolloutOutput) -> None:
|
||||
"""Build a ``TrainRollout`` / ``EvalRollout`` and put it on ``out_q``.
|
||||
async def emit_rollout(self, meta: InflightRollout, group: GroupState | None, rollout: Rollout) -> None:
|
||||
"""Stamp prime-rl metadata onto the completed rollout and put it on ``out_q``.
|
||||
Pops the group from ``self.groups`` once every member has been emitted."""
|
||||
eval_step = meta.eval_step
|
||||
policy_version = meta.policy_version
|
||||
example_id = raw.get("example_id")
|
||||
if group is not None:
|
||||
eval_step = group.eval_step
|
||||
policy_version = group.policy_version_at_start
|
||||
example_id = group.example["example_id"]
|
||||
group.emitted += 1
|
||||
if group.emitted >= group.target_rollouts:
|
||||
self.groups.pop(meta.group_id, None)
|
||||
|
||||
common = dict(
|
||||
raw=raw,
|
||||
env_name=meta.env_name,
|
||||
example_id=example_id if example_id is not None else -1,
|
||||
group_id=meta.group_id,
|
||||
policy_version=policy_version,
|
||||
off_policy_steps=meta.off_policy_steps,
|
||||
)
|
||||
rollout: FinishedRollout
|
||||
if meta.kind == "train":
|
||||
rollout = TrainRollout(**common)
|
||||
else:
|
||||
rollout.kind = meta.kind
|
||||
rollout.env_name = meta.env_name
|
||||
rollout.group_id = meta.group_id
|
||||
rollout.policy_version = policy_version
|
||||
rollout.off_policy_steps = meta.off_policy_steps
|
||||
if meta.kind == "eval":
|
||||
assert eval_step is not None, "eval rollout missing eval_step"
|
||||
rollout = EvalRollout(**common, eval_step=eval_step)
|
||||
rollout.eval_step = eval_step
|
||||
await self.out_q.put(rollout)
|
||||
|
||||
@staticmethod
|
||||
def error_rollout_output(*, error_type: str, error_repr: str) -> vf.RolloutOutput:
|
||||
"""Minimal ``vf.RolloutOutput`` for rollouts that never produced
|
||||
real output (task exception, off-policy cancel)."""
|
||||
out: vf.RolloutOutput = vf.RolloutOutput()
|
||||
out["error"] = {
|
||||
"error": error_type,
|
||||
"error_chain_repr": error_repr,
|
||||
"error_chain_str": error_repr,
|
||||
}
|
||||
out["trajectory"] = []
|
||||
out["completion"] = None
|
||||
out["reward"] = 0.0
|
||||
out["is_truncated"] = False
|
||||
out["metrics"] = {}
|
||||
out["stop_condition"] = None
|
||||
out["token_usage"] = {
|
||||
"input_tokens": 0.0,
|
||||
"output_tokens": 0.0,
|
||||
"final_input_tokens": 0.0,
|
||||
"final_output_tokens": 0.0,
|
||||
}
|
||||
return out
|
||||
|
||||
async def drop_group(self, group_id: uuid.UUID) -> int:
|
||||
"""Cancel remaining in-flight tasks for this group and emit a
|
||||
``Cancelled`` marker for every rollout it still owes the sink
|
||||
(both in-flight and not-yet-scheduled). Returns the count for
|
||||
off-policy metrics."""
|
||||
group = self.groups.pop(group_id, None)
|
||||
task_idx = group.task_idx if group is not None else -1
|
||||
|
||||
# Sync claim phase: pop matching tasks from ``self.inflight`` and
|
||||
# release their permits in one non-yielding sweep. After this loop
|
||||
@@ -594,15 +564,19 @@ class RolloutDispatcher:
|
||||
last_meta: InflightRollout | None = claimed[-1][1] if claimed else None
|
||||
for _, meta in claimed:
|
||||
for _ in range(meta.rollout_count):
|
||||
raw = self.error_rollout_output(error_type="Cancelled", error_repr="Off-policy cancel")
|
||||
await self.emit_rollout(meta, group, raw)
|
||||
trace = Rollout(
|
||||
task=vf.Task(idx=task_idx, prompt=None),
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
await self.emit_rollout(meta, group, trace)
|
||||
|
||||
# For non-group-scoring envs, the group may have rollouts that
|
||||
# were never dispatched (``rollouts_to_schedule > 0``). Emit
|
||||
# markers for those too so the sink hits ``target_rollouts``
|
||||
#
|
||||
# ``last_meta`` can be ``None`` if the only inflight task for this
|
||||
# group completed naturally between ``on_new_version``'s snapshot
|
||||
# group completed naturally between ``on_version_pending``'s snapshot
|
||||
# and us reaching it — synthesize a stand-in from the group state
|
||||
unscheduled_cancelled = 0
|
||||
if group is not None and group.rollouts_to_schedule > 0:
|
||||
@@ -616,8 +590,12 @@ class RolloutDispatcher:
|
||||
)
|
||||
unscheduled_cancelled = group.rollouts_to_schedule
|
||||
for _ in range(unscheduled_cancelled):
|
||||
raw = self.error_rollout_output(error_type="Cancelled", error_repr="Off-policy cancel")
|
||||
await self.emit_rollout(fallback_meta, group, raw)
|
||||
trace = Rollout(
|
||||
task=vf.Task(idx=task_idx, prompt=None),
|
||||
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
|
||||
stop_condition="error",
|
||||
)
|
||||
await self.emit_rollout(fallback_meta, group, trace)
|
||||
|
||||
cancelled = inflight_cancelled + unscheduled_cancelled
|
||||
if cancelled > 0:
|
||||
|
||||
@@ -1,38 +1,35 @@
|
||||
import asyncio
|
||||
from functools import partial
|
||||
|
||||
from verifiers.serve import ZMQEnvServer
|
||||
from verifiers.v1 import pool_serve_kwargs
|
||||
from verifiers.v1.serve import serve_env
|
||||
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.orchestrator.utils import setup_env_server_logging
|
||||
from prime_rl.utils.config import cli
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import get_log_dir
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit, get_env_ids_to_install, install_env
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
|
||||
@clean_exit
|
||||
def run_server(config: EnvServerConfig):
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
|
||||
# install environment if not already installed
|
||||
env_ids_to_install = set()
|
||||
env_ids_to_install.update(get_env_ids_to_install([config.env]))
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id, prerelease=config.env_install_prerelease)
|
||||
|
||||
log_dir = (get_log_dir(config.output_dir) / config.env.resolved_name).as_posix()
|
||||
|
||||
server = ZMQEnvServer(
|
||||
env_id=config.env.stripped_id,
|
||||
env_args=config.env.args,
|
||||
extra_env_kwargs=config.env.extra_env_kwargs,
|
||||
log_level=config.log.level,
|
||||
log_dir=log_dir,
|
||||
json_logging=config.log.json_logging,
|
||||
num_workers=config.env.num_workers,
|
||||
**{"address": config.env.address} if config.env.address is not None else {},
|
||||
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
|
||||
# the bridge, a v1 env is a native taskset — both serve vf.Trace over the same 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}
|
||||
if env.is_legacy
|
||||
else {"config": env}
|
||||
)
|
||||
serve_env(
|
||||
**pool_serve_kwargs(env.pool),
|
||||
legacy=env.is_legacy,
|
||||
address=address,
|
||||
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
|
||||
**server_kwargs,
|
||||
)
|
||||
asyncio.run(server.run())
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
+157
-124
@@ -1,33 +1,90 @@
|
||||
"""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
|
||||
orchestrator never *runs* an environment: it asks the server for ``info``
|
||||
(``num_tasks`` + whether group scoring is needed), then runs rollouts purely by
|
||||
**task index**. The server returns a ``Trace`` (a plain ``model_dump`` — derived values are
|
||||
properties, not serialized) which we validate into a ``Trace[WireTask]`` — a real ``vf.Trace``
|
||||
(never a loose dict) whose task keeps the env's
|
||||
task-specific fields as extras (``WireTask`` allows them). The orchestrator never imports the
|
||||
env package: the env's *type* and *runtime* both live only in the server, and the orchestrator
|
||||
drives it purely by task index. (Nothing here reads typed env task fields — only ``task.idx``
|
||||
and a full ``task.model_dump``, both of which ``WireTask`` preserves.)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
from collections.abc import Iterator, Sequence
|
||||
from multiprocessing.process import BaseProcess
|
||||
from pathlib import Path
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
import verifiers as vf
|
||||
from verifiers.serve import ZMQEnvClient, ZMQEnvServer
|
||||
from verifiers.utils.serve_utils import get_free_port
|
||||
import verifiers.v1 as vf
|
||||
from verifiers.v1.serve import EnvClient
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig, TrainEnvConfig
|
||||
from prime_rl.orchestrator.advantage import AdvantageFn, setup_advantage_fn
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
REQUIRED_STATE_COLUMNS = ["trajectory"]
|
||||
# Every wire trace validates into this type. WireTask (extra="allow") keeps the env's task
|
||||
# fields without importing the env package — the orchestrator never reads them typed (only
|
||||
# task.idx + task.model_dump).
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTask]
|
||||
|
||||
# Max wait for a spawned env server to bind and report its address. The child
|
||||
# loads the taskset (possibly downloading a dataset) before reporting, so this
|
||||
# is generous.
|
||||
ENV_SERVER_SPAWN_TIMEOUT = 600.0
|
||||
|
||||
|
||||
def _run_env_server(
|
||||
*,
|
||||
log_file: str,
|
||||
log_level: str,
|
||||
json_logging: bool,
|
||||
legacy: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Spawned-process entry point: redirect this process's output to ``log_file`` (the
|
||||
server's logging + any subprocess-runtime output), then serve via ``serve_env``. The
|
||||
worker-pool sizing arrives in ``kwargs`` (``max_workers`` / ``multiplex`` / ``elastic``
|
||||
from the env's ``pool``). ``serve_env`` applies ``log_setup`` here and in every spawned
|
||||
worker; a worker inherits this process's redirected stdout/stderr, so its per-rollout
|
||||
logs reach ``log_file`` too. Top-level so it stays picklable for the ``spawn`` start
|
||||
method. ``legacy`` picks the v0 bridge."""
|
||||
from functools import partial
|
||||
|
||||
from verifiers.v1.serve import serve_env
|
||||
|
||||
from prime_rl.orchestrator.utils import setup_env_server_logging
|
||||
|
||||
fh = open(log_file, "w", buffering=1)
|
||||
os.dup2(fh.fileno(), sys.stdout.fileno())
|
||||
os.dup2(fh.fileno(), sys.stderr.fileno())
|
||||
serve_env(
|
||||
legacy=legacy,
|
||||
log_setup=partial(setup_env_server_logging, log_level, json_logging),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
class Env:
|
||||
"""Wraps a vf.Environment - only exposes features used in PRIME-RL."""
|
||||
"""Wraps a v1 env server + client. The orchestrator never loads the env."""
|
||||
|
||||
def __init__(self, config: EnvConfig):
|
||||
self.config = config
|
||||
self.sampling_args: dict = {}
|
||||
|
||||
get_logger().debug(f"Initializing {config.resolved_name} ({config})")
|
||||
self._env: vf.Environment = vf.load_environment(config.stripped_id, **config.args)
|
||||
self._env_client: ZMQEnvClient | None = None
|
||||
self.num_tasks: int = 0
|
||||
self.requires_group_scoring: bool = False
|
||||
self._env_client: EnvClient | None = None
|
||||
self._env_server_process: BaseProcess | None = None
|
||||
|
||||
@property
|
||||
@@ -35,122 +92,105 @@ class Env:
|
||||
return self.config.resolved_name
|
||||
|
||||
@property
|
||||
def env(self) -> vf.Environment:
|
||||
return self._env
|
||||
|
||||
@property
|
||||
def env_client(self) -> ZMQEnvClient:
|
||||
if not self._env_client:
|
||||
raise RuntimeError(
|
||||
f"Env {self.name} has no env client connected. Call connect() first to connect to an env server."
|
||||
)
|
||||
def env_client(self) -> EnvClient:
|
||||
if self._env_client is None:
|
||||
raise RuntimeError(f"Env {self.name} not started — call start() first.")
|
||||
return self._env_client
|
||||
|
||||
@property
|
||||
def requires_group_scoring(self) -> bool:
|
||||
return any(self.env.rubric._is_group_func(func) for func in self.env.rubric._get_reward_funcs())
|
||||
|
||||
async def start(
|
||||
self,
|
||||
log_dir: Path,
|
||||
log_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
) -> None:
|
||||
"""Spawn an env server (if needed) and connect to it."""
|
||||
if self.config.address is None:
|
||||
address = self._spawn(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
else:
|
||||
address = self.config.address
|
||||
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 cache its ``info``."""
|
||||
external = self.config.address is not None
|
||||
address = self.config.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 = ZMQEnvClient(address=address, name=self.name)
|
||||
await self.env_client.wait_for_server_startup()
|
||||
|
||||
def _spawn(
|
||||
self,
|
||||
log_dir: Path,
|
||||
log_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
) -> str:
|
||||
assert isinstance(self.config.num_workers, int), (
|
||||
f"num_workers must be resolved before spawn, got {self.config.num_workers!r}"
|
||||
self._env_client = EnvClient(address=address)
|
||||
# A spawned server already reported its address *after* binding + loading,
|
||||
# so it's up — the untimed ``info`` below is enough. An external server has
|
||||
# no such handshake, so poll until it answers before we block on ``info``.
|
||||
if external:
|
||||
await self.env_client.wait_for_server_startup()
|
||||
info = await self.env_client.info()
|
||||
self.num_tasks = info.num_tasks
|
||||
self.requires_group_scoring = info.requires_group_scoring
|
||||
get_logger().info(
|
||||
f"Env {self.name} ready: num_tasks={self.num_tasks} group_scoring={self.requires_group_scoring}"
|
||||
)
|
||||
num_workers = self.config.num_workers
|
||||
address = f"tcp://127.0.0.1:{get_free_port()}"
|
||||
get_logger().debug(f"Spawning env server {self.name} ({address=}, {num_workers=})")
|
||||
process = mp.get_context("spawn").Process(
|
||||
target=ZMQEnvServer.run_server,
|
||||
args=(
|
||||
self.config.stripped_id,
|
||||
self.config.args,
|
||||
self.config.extra_env_kwargs,
|
||||
log_level,
|
||||
(log_dir / self.name).as_posix(),
|
||||
),
|
||||
|
||||
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
|
||||
"""Spawn a v1 EnvServer child process (it loads the env; we never do).
|
||||
The server binds an OS-assigned port (``:0``) and reports the concrete
|
||||
address back over a queue — no free-port guess, no TOCTOU race. Its output
|
||||
goes to ``<log_dir>/<name>.log`` (``log_dir`` is already the train/eval-split
|
||||
``.../logs/envs/{train,eval}`` the orchestrator passes in)."""
|
||||
ctx = mp.get_context("spawn")
|
||||
address_queue: mp.Queue = ctx.Queue()
|
||||
log_file = log_dir / f"{self.name}.log"
|
||||
log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_logger().debug(f"Spawning env server {self.name} (id={self.config.env_id}, log={log_file})")
|
||||
server_kwargs = (
|
||||
dict(
|
||||
legacy=True,
|
||||
env_id=self.config.env_id,
|
||||
env_args=self.config.args,
|
||||
extra_env_kwargs=self.config.extra_env_kwargs,
|
||||
)
|
||||
if self.config.is_legacy
|
||||
else dict(legacy=False, config=self.config)
|
||||
)
|
||||
process = ctx.Process(
|
||||
target=_run_env_server,
|
||||
kwargs=dict(
|
||||
address=address,
|
||||
log_file=str(log_file),
|
||||
log_level=log_level,
|
||||
json_logging=json_logging,
|
||||
console_logging=False,
|
||||
num_workers=num_workers,
|
||||
**vf.pool_serve_kwargs(self.config.pool),
|
||||
address="tcp://127.0.0.1:0",
|
||||
address_queue=address_queue,
|
||||
**server_kwargs,
|
||||
),
|
||||
daemon=False,
|
||||
)
|
||||
process.start()
|
||||
self._env_server_process = process
|
||||
try:
|
||||
address = await asyncio.to_thread(address_queue.get, timeout=ENV_SERVER_SPAWN_TIMEOUT)
|
||||
except queue.Empty:
|
||||
raise RuntimeError(f"Env server {self.name} did not report its address within {ENV_SERVER_SPAWN_TIMEOUT}s")
|
||||
finally:
|
||||
address_queue.close()
|
||||
address_queue.join_thread()
|
||||
get_logger().debug(f"Env server {self.name} bound at {address}")
|
||||
return address
|
||||
|
||||
def _sampling_args_with_salt(self, cache_salt: str | None) -> dict:
|
||||
sampling_args = {**self.sampling_args}
|
||||
if cache_salt is None:
|
||||
return sampling_args
|
||||
extra_body = {**sampling_args.get("extra_body", {}), "cache_salt": cache_salt}
|
||||
sampling_args["extra_body"] = extra_body
|
||||
return sampling_args
|
||||
|
||||
@property
|
||||
def state_columns(self) -> list[str]:
|
||||
"""Required columns plus any extras configured on the env, deduped (required first)."""
|
||||
merged: list[str] = []
|
||||
for col in (*REQUIRED_STATE_COLUMNS, *self.config.state_columns):
|
||||
if col not in merged:
|
||||
merged.append(col)
|
||||
return merged
|
||||
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
|
||||
sampling = {**self.sampling_args}
|
||||
if cache_salt is not None:
|
||||
sampling["extra_body"] = {**sampling.get("extra_body", {}), "cache_salt": cache_salt}
|
||||
return vf.SamplingConfig(**sampling)
|
||||
|
||||
async def run_rollout(
|
||||
self,
|
||||
client: vf.ClientConfig,
|
||||
example: dict,
|
||||
model_name: str,
|
||||
cache_salt: str | None,
|
||||
) -> vf.RolloutOutput:
|
||||
"""Run a single rollout for an example."""
|
||||
return await self.env.run_rollout(
|
||||
vf.RolloutInput(**example),
|
||||
self, client: vf.ClientConfig, task_idx: int, model_name: str, cache_salt: str | None
|
||||
) -> Rollout:
|
||||
"""Run a single rollout for ``task_idx``; return a typed Trace."""
|
||||
wire = await self.env_client.run_rollout(
|
||||
task_idx=task_idx,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=self._sampling_args_with_salt(cache_salt),
|
||||
max_retries=self.config.max_retries,
|
||||
state_columns=self.state_columns,
|
||||
env_client=self.env_client,
|
||||
sampling=self._sampling(cache_salt),
|
||||
)
|
||||
return ROLLOUT_TYPE.model_construct(**dict(wire))
|
||||
|
||||
async def run_group(
|
||||
self,
|
||||
client: vf.ClientConfig,
|
||||
example: dict,
|
||||
model_name: str,
|
||||
group_size: int,
|
||||
cache_salt: str | None,
|
||||
) -> list[vf.RolloutOutput]:
|
||||
"""Run a group of rollouts for an example. Required for group-scoring envs."""
|
||||
return await self.env.run_group(
|
||||
[vf.RolloutInput(**example) for _ in range(group_size)],
|
||||
self, client: vf.ClientConfig, task_idx: int, model_name: str, group_size: int, cache_salt: str | None
|
||||
) -> list[Rollout]:
|
||||
"""Run a group of rollouts for ``task_idx`` (group-scoring envs); return typed Traces."""
|
||||
wires = await self.env_client.run_group(
|
||||
task_idx=task_idx,
|
||||
n=group_size,
|
||||
client=client,
|
||||
model=model_name,
|
||||
sampling_args=self._sampling_args_with_salt(cache_salt),
|
||||
max_retries=self.config.max_retries,
|
||||
state_columns=self.state_columns,
|
||||
env_client=self.env_client,
|
||||
sampling=self._sampling(cache_salt),
|
||||
)
|
||||
return [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in wires]
|
||||
|
||||
def shutdown(self) -> None:
|
||||
if self._env_server_process is None:
|
||||
@@ -162,18 +202,14 @@ class Env:
|
||||
class TrainEnv(Env):
|
||||
config: TrainEnvConfig
|
||||
|
||||
def __init__(self, config: TrainEnvConfig):
|
||||
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
|
||||
super().__init__(config)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
# Built once — custom advantage funcs do an ``import_object`` we don't
|
||||
# want to pay per group. ``None`` = reward-only path.
|
||||
# Built once — custom advantage funcs do an ``import_object`` we don't want to pay per group.
|
||||
self.advantage_fn: AdvantageFn | None = (
|
||||
setup_advantage_fn(config.advantage) if config.advantage is not None else None
|
||||
setup_advantage_fn(config.advantage, max_seq_len=max_seq_len) if config.advantage is not None else None
|
||||
)
|
||||
|
||||
def get_dataset(self, seed: int | None = None):
|
||||
return self.env.get_dataset(seed=seed)
|
||||
|
||||
|
||||
class EvalEnv(Env):
|
||||
config: EvalEnvConfig
|
||||
@@ -181,7 +217,12 @@ class EvalEnv(Env):
|
||||
def __init__(self, config: EvalEnvConfig):
|
||||
super().__init__(config)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.examples = self.env.get_eval_dataset(n=config.num_examples).to_list()
|
||||
self.examples: list[dict] = []
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
|
||||
self.examples = [{"task_idx": i} for i in range(n)]
|
||||
|
||||
|
||||
EnvT = TypeVar("EnvT", bound=Env)
|
||||
@@ -209,23 +250,15 @@ class Envs(Generic[EnvT]):
|
||||
def __len__(self) -> int:
|
||||
return len(self._envs)
|
||||
|
||||
async def start(
|
||||
self,
|
||||
log_dir: Path,
|
||||
log_level: str | None = None,
|
||||
json_logging: bool = False,
|
||||
) -> None:
|
||||
"""Spawn env servers (where needed) and connect env clients one at a time.
|
||||
|
||||
Serialized to avoid a TOCTOU port race: get_free_port() only holds the port
|
||||
until it returns, so parallel spawns can hand the same port to two children.
|
||||
"""
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
"""Spawn env servers (where needed) and connect, one at a time. Each server
|
||||
binds an OS-assigned port and reports it back, so there's no port race."""
|
||||
for env in self:
|
||||
await env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
atexit.register(self.shutdown)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Terminate all spawned env server processes in parallel."""
|
||||
"""Terminate all spawned env server processes."""
|
||||
processes = [env._env_server_process for env in self if env._env_server_process is not None]
|
||||
if not processes:
|
||||
return
|
||||
@@ -246,10 +279,10 @@ class Envs(Generic[EnvT]):
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
"""Collection of training environments."""
|
||||
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig]):
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
env = TrainEnv(config)
|
||||
env = TrainEnv(config, max_seq_len=max_seq_len)
|
||||
self._envs[env.name] = env
|
||||
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ from collections import defaultdict
|
||||
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_utils import compute_pass_at_k
|
||||
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, EvalRollout
|
||||
from prime_rl.orchestrator.types import EvalBatch, EvalBatchMetrics, Rollout
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -27,12 +27,12 @@ class EvalSink:
|
||||
|
||||
def __init__(self, *, eval_envs: EvalEnvs) -> None:
|
||||
self.eval_envs = eval_envs
|
||||
self.pending_groups: dict[uuid.UUID, list[EvalRollout]] = defaultdict(list)
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
# Bucket size IS the arrival count — ``process_group`` flushes
|
||||
# everything in without filtering
|
||||
self.pending_batches: dict[tuple[str, int], list[EvalRollout]] = defaultdict(list)
|
||||
self.pending_batches: dict[tuple[str, int], list[Rollout]] = defaultdict(list)
|
||||
|
||||
def add(self, rollout: EvalRollout) -> EvalBatch | None:
|
||||
def add(self, rollout: Rollout) -> EvalBatch | None:
|
||||
"""Process one arrival; finalize the group on the ``group_size``-th
|
||||
arrival and the per-env epoch on the ``num_examples × group_size``-th."""
|
||||
env_name = rollout.env_name
|
||||
@@ -82,7 +82,7 @@ class EvalSink:
|
||||
|
||||
# ── level 1: per-rollout (no-op for eval) ─────────────────────────────
|
||||
|
||||
def process_rollout(self, rollout: EvalRollout) -> None:
|
||||
def process_rollout(self, rollout: Rollout) -> None:
|
||||
"""No-op. Eval rollouts don't need trainer-bound tokenization; the
|
||||
method exists to keep the three-level structure uniform with
|
||||
``TrainSink``.
|
||||
@@ -96,17 +96,17 @@ class EvalSink:
|
||||
if not group:
|
||||
return
|
||||
env_name = group[0].env_name
|
||||
example_id = group[0].example_id
|
||||
task_idx = group[0].task.idx
|
||||
eval_step = group[0].eval_step
|
||||
bucket = self.pending_batches[(env_name, eval_step)]
|
||||
bucket.extend(group)
|
||||
|
||||
survivors = [r for r in group if r.error is None]
|
||||
survivors = [r for r in group if not r.has_error]
|
||||
num_errored = len(group) - len(survivors)
|
||||
rewards = [r.reward for r in survivors]
|
||||
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} example_id={example_id} eval_step={eval_step} | "
|
||||
f"Finished group | env={env_name} task_idx={task_idx} eval_step={eval_step} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
|
||||
)
|
||||
|
||||
@@ -120,9 +120,9 @@ class EvalSink:
|
||||
rollouts = self.pending_batches.pop(key, [])
|
||||
|
||||
n_total = len(rollouts)
|
||||
n_cancelled = sum(1 for r in rollouts if (r.error or {}).get("error") == "Cancelled")
|
||||
n_errored = sum(1 for r in rollouts if r.error is not None) - n_cancelled
|
||||
valid = [r for r in rollouts if r.error is None]
|
||||
n_cancelled = sum(1 for r in rollouts if r.has_error and r.error.type == "Cancelled")
|
||||
n_errored = sum(1 for r in rollouts if r.has_error) - n_cancelled
|
||||
valid = [r for r in rollouts if not r.has_error]
|
||||
metrics = EvalBatchMetrics(
|
||||
n_rollouts=n_total,
|
||||
n_cancelled=n_cancelled,
|
||||
@@ -131,23 +131,23 @@ class EvalSink:
|
||||
|
||||
if valid:
|
||||
rewards = [r.reward for r in valid]
|
||||
lens = [r.raw["token_usage"]["final_output_tokens"] for r in valid]
|
||||
lens = [r.completion_len for r in valid]
|
||||
metrics.group_size = self.group_size_for(env_name)
|
||||
metrics.reward_mean = float(sum(rewards) / len(rewards))
|
||||
metrics.completion_len_mean = float(sum(lens) / len(lens))
|
||||
metrics.completion_len_max = float(max(lens))
|
||||
metrics.completion_len_min = float(min(lens))
|
||||
metrics.truncation_rate = float(sum(1 for r in valid if r.is_truncated) / len(valid))
|
||||
metrics.no_response_rate = float(sum(1 for r in valid if not r.raw.get("completion")) / len(valid))
|
||||
num_turns = [len(r.raw.get("trajectory") or []) for r in valid]
|
||||
metrics.no_response_rate = float(sum(1 for r in valid if not r.has_response) / len(valid))
|
||||
num_turns = [r.num_turns for r in valid]
|
||||
metrics.num_turns_mean = float(sum(num_turns) / len(num_turns))
|
||||
metrics.num_turns_min = float(min(num_turns))
|
||||
metrics.num_turns_max = float(max(num_turns))
|
||||
|
||||
# pass@k: errored attempts don't count toward k tries
|
||||
by_example: dict[int | str, list[float]] = {}
|
||||
by_example: dict[int, list[float]] = {}
|
||||
for r in valid:
|
||||
by_example.setdefault(r.example_id, []).append(r.reward)
|
||||
by_example.setdefault(r.task.idx, []).append(r.reward)
|
||||
metrics.n_examples = len(by_example)
|
||||
unique_rewards = {float(r) for r in rewards}
|
||||
if unique_rewards.issubset({0.0, 1.0}) and by_example:
|
||||
|
||||
@@ -16,7 +16,7 @@ from prime_rl.configs.orchestrator import FilterConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -29,7 +29,7 @@ class RolloutFilter(Protocol):
|
||||
name: str
|
||||
enforce: bool
|
||||
|
||||
def check(self, rollout: "TrainRollout") -> FilterResult: ...
|
||||
def check(self, rollout: Rollout) -> FilterResult: ...
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -49,13 +49,14 @@ class GibberishFilter:
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: "TrainRollout") -> FilterResult:
|
||||
def check(self, rollout: Rollout) -> FilterResult:
|
||||
global_idx = 0
|
||||
for step in rollout.raw["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is None:
|
||||
continue
|
||||
for token_id, logprob in zip(tokens["completion_ids"], tokens["completion_logprobs"]):
|
||||
for node in rollout.nodes:
|
||||
# token_ids / logprobs / mask are per-token aligned; check only the
|
||||
# sampled completion tokens, pairing each with its own logprob.
|
||||
for token_id, logprob, sampled in zip(node.token_ids, node.logprobs, node.mask):
|
||||
if not sampled:
|
||||
continue
|
||||
if token_id > self.token_id_threshold and logprob < self.logprob_threshold:
|
||||
return FilterResult(detected=True, detection_index=global_idx)
|
||||
global_idx += 1
|
||||
@@ -79,14 +80,15 @@ class RepetitionFilter:
|
||||
logprob_threshold: float
|
||||
enforce: bool = False
|
||||
|
||||
def check(self, rollout: "TrainRollout") -> FilterResult:
|
||||
def check(self, rollout: Rollout) -> FilterResult:
|
||||
consecutive = 0
|
||||
global_idx = 0
|
||||
for step in rollout.raw["trajectory"]:
|
||||
tokens = step["tokens"]
|
||||
if tokens is None:
|
||||
continue
|
||||
for logprob in tokens["completion_logprobs"]:
|
||||
for node in rollout.nodes:
|
||||
# Streak only over sampled completion tokens — context/prompt tokens
|
||||
# (mask=False) are not model-generated and must not feed the loop count.
|
||||
for logprob, sampled in zip(node.logprobs, node.mask):
|
||||
if not sampled:
|
||||
continue
|
||||
if logprob > self.logprob_threshold:
|
||||
consecutive += 1
|
||||
else:
|
||||
@@ -105,7 +107,7 @@ class ZeroAdvantageFilter:
|
||||
name: str
|
||||
enforce: bool = True
|
||||
|
||||
def check(self, rollout: "TrainRollout") -> FilterResult:
|
||||
def check(self, rollout: Rollout) -> FilterResult:
|
||||
if rollout.advantage is not None and rollout.advantage == 0.0:
|
||||
return FilterResult(detected=True)
|
||||
return FilterResult(detected=False)
|
||||
@@ -147,8 +149,8 @@ def setup_filters(configs: list[FilterConfig], vocab_size: int, *, kind: str) ->
|
||||
return filters
|
||||
|
||||
|
||||
def apply_filters(filters: list[RolloutFilter], rollouts: list["TrainRollout"]) -> None: # noqa: F821 (forward ref)
|
||||
"""Flag ``TrainRollout``\\ s in place with per-filter detection + drop decision.
|
||||
def apply_filters(filters: list[RolloutFilter], rollouts: list[Rollout]) -> None:
|
||||
"""Flag ``Rollout``\\ s in place with per-filter detection + drop decision.
|
||||
|
||||
Each rollout's ``filter_results`` dict records per-filter detection bools;
|
||||
``is_filtered`` is True iff an enforcing filter detected it. First matching
|
||||
|
||||
@@ -1,9 +1,4 @@
|
||||
"""MetricsBuilder: assembles the per-step W&B dict.
|
||||
|
||||
The only I/O / state is the trainer's token-export metrics, which lag the
|
||||
orchestrator: ``build`` folds in the oldest unlogged stable step it finds on
|
||||
disk and tracks the last step logged so it never re-logs one.
|
||||
"""
|
||||
"""MetricsBuilder: assembles the per-step W&B dict. No I/O, no side effects."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,22 +7,18 @@ from typing import Any
|
||||
import pandas as pd
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.token_export_metrics import collect_next_token_export_metrics
|
||||
from prime_rl.orchestrator.types import Progress, TrainBatchMetrics, TrainRollout
|
||||
from prime_rl.orchestrator.types import Progress, Rollout, TrainBatchMetrics
|
||||
|
||||
|
||||
class MetricsBuilder:
|
||||
def __init__(self, config: OrchestratorConfig, start_step: int = 0) -> None:
|
||||
def __init__(self, config: OrchestratorConfig) -> None:
|
||||
self.config = config
|
||||
# Token exports are read back one step behind the orchestrator; track the
|
||||
# last run step whose metrics we've folded in so we never re-log a step.
|
||||
self._last_token_export_step_logged = start_step - 1
|
||||
|
||||
def build(
|
||||
self,
|
||||
*,
|
||||
step: int,
|
||||
rollouts: list[TrainRollout],
|
||||
rollouts: list[Rollout],
|
||||
metrics: TrainBatchMetrics,
|
||||
progress: Progress,
|
||||
step_time: float,
|
||||
@@ -41,30 +32,25 @@ class MetricsBuilder:
|
||||
existing dashboards / alerts keep working."""
|
||||
num_rollouts = len(rollouts)
|
||||
num_unique_examples = len({r.group_id for r in rollouts})
|
||||
num_tokens = sum(
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"] for r in rollouts
|
||||
)
|
||||
num_tokens = sum(r.total_tokens for r in rollouts)
|
||||
|
||||
results_df = pd.DataFrame(
|
||||
{
|
||||
"group_id": [r.group_id for r in rollouts],
|
||||
"example_id": [r.example_id for r in rollouts],
|
||||
"task_idx": [r.task.idx for r in rollouts],
|
||||
"env_name": [r.env_name for r in rollouts],
|
||||
"reward": [r.reward for r in rollouts],
|
||||
"is_truncated": [r.is_truncated for r in rollouts],
|
||||
"is_filtered": [r.is_filtered for r in rollouts],
|
||||
"stop_condition": [r.raw.get("stop_condition") for r in rollouts],
|
||||
"seq_len": [
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
for r in rollouts
|
||||
],
|
||||
"stop_condition": [r.stop_condition for r in rollouts],
|
||||
"seq_len": [r.total_tokens for r in rollouts],
|
||||
"prefill_len": metrics.rollout_prefill_lens,
|
||||
"decode_len": metrics.rollout_decode_lens,
|
||||
"samples_per_rollout": metrics.samples_per_rollout,
|
||||
"num_turns": [len(r.raw["trajectory"]) for r in rollouts],
|
||||
"num_turns": [r.num_turns for r in rollouts],
|
||||
}
|
||||
)
|
||||
metrics_df = pd.DataFrame([(r.raw.get("metrics") or {}) for r in rollouts])
|
||||
metrics_df = pd.DataFrame([r.metrics for r in rollouts])
|
||||
filter_df = pd.DataFrame([r.filter_results for r in rollouts])
|
||||
timing_df = self.timing_df(rollouts)
|
||||
|
||||
@@ -188,42 +174,14 @@ class MetricsBuilder:
|
||||
for name, count in pre_filter_dropped_by_name.items():
|
||||
to_log[f"pre_filters/all/{name}/rate"] = count / pre_filter_seen
|
||||
|
||||
# Fold in the trainer's token-export metrics for the oldest unlogged stable
|
||||
# step (exports always lag the orchestrator, so this is a past step).
|
||||
to_log.update(self.next_token_export_metrics())
|
||||
|
||||
return to_log
|
||||
|
||||
@property
|
||||
def last_token_export_step_logged(self) -> int:
|
||||
return self._last_token_export_step_logged
|
||||
|
||||
def next_token_export_metrics(self) -> dict[str, float | int]:
|
||||
"""Log-ready token-export metrics for the next unlogged stable step (empty if
|
||||
none), advancing the cursor. They arrive under trainer/, including trainer/step
|
||||
(the run step they belong to) for plotting against a lag-corrected axis. Shared
|
||||
by build() and the orchestrator's end-of-run drain."""
|
||||
token_export = collect_next_token_export_metrics(
|
||||
self.config.output_dir,
|
||||
last_logged_step=self._last_token_export_step_logged,
|
||||
)
|
||||
if token_export:
|
||||
self._last_token_export_step_logged = token_export["trainer/step"]
|
||||
return token_export
|
||||
|
||||
@staticmethod
|
||||
def timing_df(rollouts: list[TrainRollout]) -> pd.DataFrame:
|
||||
return pd.DataFrame(
|
||||
[
|
||||
{
|
||||
"total": r.raw["timing"]["total"],
|
||||
"setup": r.raw["timing"]["setup"]["duration"],
|
||||
"generation": r.raw["timing"]["generation"]["duration"],
|
||||
"model": r.raw["timing"]["model"]["duration"],
|
||||
"env": r.raw["timing"]["env"]["duration"],
|
||||
"scoring": r.raw["timing"]["scoring"]["duration"],
|
||||
"overhead": r.raw["timing"]["overhead"],
|
||||
}
|
||||
for r in rollouts
|
||||
]
|
||||
)
|
||||
def timing_df(rollouts: list[Rollout]) -> pd.DataFrame:
|
||||
"""Per-rollout timing from the v1 Trace (`generation`/`scoring` spans)."""
|
||||
rows = []
|
||||
for r in rollouts:
|
||||
timing = r.timing
|
||||
generation, scoring = timing.generation.duration, timing.scoring.duration
|
||||
rows.append({"total": generation + scoring, "generation": generation, "scoring": scoring})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
@@ -21,8 +21,6 @@ in ``setup()`` and drives them from ``main_loop()``.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import ctypes
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from typing import TYPE_CHECKING
|
||||
@@ -37,8 +35,6 @@ if TYPE_CHECKING:
|
||||
from prime_rl.transport.base import TrainingBatchSender
|
||||
from prime_rl.utils.client import InferencePool
|
||||
from prime_rl.utils.monitor.base import Monitor
|
||||
from verifiers.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats
|
||||
|
||||
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
|
||||
@@ -58,12 +54,10 @@ from prime_rl.orchestrator.train_sink import TrainSink
|
||||
from prime_rl.orchestrator.train_source import TrainSource
|
||||
from prime_rl.orchestrator.types import (
|
||||
EvalBatch,
|
||||
EvalRollout,
|
||||
FinishedRollout,
|
||||
Policy,
|
||||
Progress,
|
||||
Rollout,
|
||||
TrainBatch,
|
||||
TrainRollout,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import (
|
||||
compute_teacher_logprobs,
|
||||
@@ -72,11 +66,12 @@ from prime_rl.orchestrator.utils import (
|
||||
save_rollouts,
|
||||
set_default_executor,
|
||||
setup_student_inference_pool,
|
||||
trim_process_memory,
|
||||
)
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
|
||||
from prime_rl.utils.async_utils import safe_cancel
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast, setup_inference_pool
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
@@ -85,8 +80,6 @@ from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
get_env_ids_to_install,
|
||||
install_env,
|
||||
resolve_latest_ckpt_step,
|
||||
)
|
||||
|
||||
@@ -108,10 +101,12 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
|
||||
# resumed when the watcher advances ``policy.version``.
|
||||
TARGET_LAG = 1
|
||||
|
||||
# After max_steps, how long to wait for the trainer to finalize the trailing
|
||||
# token-export steps it hadn't flushed yet, and how often to poll for them.
|
||||
TOKEN_EXPORT_DRAIN_TIMEOUT_S = 300.0
|
||||
TOKEN_EXPORT_DRAIN_POLL_S = 2.0
|
||||
# Drop the per-node training tensors when dumping a Trace to disk (rollout jsonl / wandb
|
||||
# tables): the multimodal `mm_kwargs` carrier and the router-replay `routed_experts` array are
|
||||
# training inputs, not part of the rollout record, and would bloat every line. They also can't
|
||||
# round-trip the json dump — their `__nd__` carriers hold raw bytes. `__all__` applies the
|
||||
# exclude to every node in the list.
|
||||
ROLLOUT_DUMP_EXCLUDE = {"nodes": {"__all__": {"multi_modal_data", "routed_experts"}}}
|
||||
|
||||
|
||||
class Orchestrator:
|
||||
@@ -158,10 +153,9 @@ class Orchestrator:
|
||||
def __init__(self, config: OrchestratorConfig) -> None:
|
||||
self.config = config
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
# Silence in-process ``verifiers.*`` library noise but keep
|
||||
# ``verifiers.serve`` (env-server lifecycle) through our handler
|
||||
logging.getLogger("verifiers").setLevel(logging.CRITICAL + 1)
|
||||
intercept_vf_logging(logger="verifiers.serve", level="WARN")
|
||||
# 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")
|
||||
get_logger().info(f"Starting orchestrator ({config.training_mode})")
|
||||
|
||||
if config.bench:
|
||||
@@ -211,12 +205,6 @@ class Orchestrator:
|
||||
with open(config_dir / "orch.toml", "wb") as f:
|
||||
tomli_w.dump(config.model_dump(exclude_none=True, mode="json"), f)
|
||||
|
||||
env_ids_to_install = set(get_env_ids_to_install(config.train.env))
|
||||
if config.eval is not None:
|
||||
env_ids_to_install.update(get_env_ids_to_install(config.eval.env))
|
||||
for env_id in env_ids_to_install:
|
||||
install_env(env_id, prerelease=config.env_install_prerelease)
|
||||
|
||||
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
self.tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
@@ -242,7 +230,11 @@ class Orchestrator:
|
||||
self.teacher_inference = await setup_inference_pool(
|
||||
config.teacher.client,
|
||||
model_name=config.teacher.model.name,
|
||||
train_client_type="openai_chat_completions",
|
||||
# SFT rolls the teacher out through the renderer client (token-in/out) so its
|
||||
# rollouts carry tokens directly — training is renderer-only. (OPD reads teacher
|
||||
# logprobs via prefill, so its pool client type is moot.)
|
||||
train_client_type="renderer",
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
|
||||
get_logger().info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
|
||||
@@ -268,7 +260,7 @@ class Orchestrator:
|
||||
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(config.train.env)
|
||||
self.train_envs = TrainEnvs(config.train.env, max_seq_len=config.seq_len)
|
||||
if config.training_mode == "sft":
|
||||
for env in self.train_envs:
|
||||
env.sampling_args.pop("logprobs", None)
|
||||
@@ -387,11 +379,10 @@ class Orchestrator:
|
||||
training_mode=config.training_mode,
|
||||
use_cache_salt=use_cache_salt,
|
||||
)
|
||||
self.metrics = MetricsBuilder(config, start_step=self.progress.step)
|
||||
self.metrics = MetricsBuilder(config)
|
||||
self.train_sink = TrainSink(
|
||||
config,
|
||||
tokenizer=self.tokenizer,
|
||||
renderer=self.renderer,
|
||||
train_envs=self.train_envs,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
batch_size=config.batch_size,
|
||||
@@ -465,7 +456,6 @@ class Orchestrator:
|
||||
clean_exit = False
|
||||
try:
|
||||
await self.main_loop()
|
||||
await self._drain_token_export_metrics()
|
||||
clean_exit = True
|
||||
finally:
|
||||
elapsed = format_time(time.perf_counter() - start_time)
|
||||
@@ -482,10 +472,7 @@ class Orchestrator:
|
||||
get_logger().success("Orchestrator finished.")
|
||||
else:
|
||||
get_logger().warning("Orchestrator cleanup complete (forced).")
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except Exception as e:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {e}")
|
||||
trim_process_memory()
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume ``FinishedRollout``\\ s from the dispatcher and route them
|
||||
@@ -498,53 +485,23 @@ class Orchestrator:
|
||||
break
|
||||
|
||||
try:
|
||||
rollout: FinishedRollout = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
rollout: Rollout = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=0.5)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
|
||||
if isinstance(rollout, EvalRollout):
|
||||
if rollout.kind == "eval":
|
||||
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
|
||||
eval_batch = self.eval_sink.add(rollout)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
continue
|
||||
|
||||
assert isinstance(rollout, TrainRollout)
|
||||
train_batch = await self.train_sink.add(rollout)
|
||||
# In drain mode any late-arriving train batch is dropped — we
|
||||
# don't want to ship past ``max_steps``
|
||||
if train_batch is not None and not self.draining and not self.stopped.is_set():
|
||||
await self.finalize_train_batch(train_batch)
|
||||
|
||||
async def _drain_token_export_metrics(self) -> None:
|
||||
"""Token exports lag the orchestrator, so once the loop ends the trainer is
|
||||
still finalizing the last shipped steps and ``build`` no longer runs to pick
|
||||
them up. Poll for the remaining stable steps up to ``max_steps - 1`` and log
|
||||
each under its own ``trainer/step`` (a local W&B step axis, so the final
|
||||
checkpoint's ``progress.step`` is untouched)."""
|
||||
if self.config.max_steps is None:
|
||||
return
|
||||
if not (self.config.output_dir / "token_exports").exists():
|
||||
return # token export not enabled for this run — don't block shutdown
|
||||
target = self.config.max_steps - 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return # build() already kept up — nothing trailing to flush
|
||||
wandb_step = self.progress.step
|
||||
deadline = time.perf_counter() + TOKEN_EXPORT_DRAIN_TIMEOUT_S
|
||||
while time.perf_counter() < deadline:
|
||||
token_export = self.metrics.next_token_export_metrics()
|
||||
if not token_export:
|
||||
await asyncio.sleep(TOKEN_EXPORT_DRAIN_POLL_S)
|
||||
continue
|
||||
self.monitor.log(token_export, step=wandb_step)
|
||||
wandb_step += 1
|
||||
if self.metrics.last_token_export_step_logged >= target:
|
||||
return
|
||||
get_logger().warning(
|
||||
f"Token-export drain timed out before step {target} "
|
||||
f"(last logged {self.metrics.last_token_export_step_logged})"
|
||||
)
|
||||
|
||||
async def finalize_train_batch(self, batch: TrainBatch) -> None:
|
||||
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
|
||||
side-effects (ckpt, save_rollouts, teacher logprobs, sender.send,
|
||||
@@ -591,13 +548,11 @@ class Orchestrator:
|
||||
f"({batch.metrics.n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
)
|
||||
|
||||
# Materialize at the I/O boundary so prime-rl metadata travels with
|
||||
# the raw vf payload on disk + in wandb sample tables
|
||||
rollout_dicts = [r.to_dict() for r in batch.rollouts]
|
||||
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); drop the
|
||||
# per-node multimodal tensors — they're for training, not the rollout record, and bloat it.
|
||||
rollout_dicts = [r.model_dump(mode="json", exclude=ROLLOUT_DUMP_EXCLUDE) for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(config.output_dir), step)
|
||||
await asyncio.to_thread(
|
||||
save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl", exclude_keys={"trajectory"}
|
||||
)
|
||||
await asyncio.to_thread(save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl")
|
||||
|
||||
teacher_logprobs_time = 0.0 # opd only
|
||||
if config.training_mode == "opd" and self.teacher_inference is not None:
|
||||
@@ -614,6 +569,7 @@ class Orchestrator:
|
||||
|
||||
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
|
||||
self.update_dispatch_gate()
|
||||
trim_process_memory()
|
||||
|
||||
metrics = self.metrics.build(
|
||||
step=step,
|
||||
@@ -628,7 +584,7 @@ class Orchestrator:
|
||||
pre_filter_dropped_by_name=dict(self.train_sink.pre_filter_dropped_by_name),
|
||||
)
|
||||
self.monitor.log(metrics, step=step)
|
||||
self.monitor.log_samples(rollout_dicts, step=step)
|
||||
self.monitor.log_samples(batch.rollouts, step=step)
|
||||
self.monitor.log_distributions(
|
||||
distributions={
|
||||
"rewards": [r.reward for r in batch.rollouts],
|
||||
@@ -650,10 +606,7 @@ class Orchestrator:
|
||||
|
||||
num_rollouts = len(batch.rollouts)
|
||||
num_unique_examples = len({r.group_id for r in batch.rollouts})
|
||||
num_tokens = sum(
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
for r in batch.rollouts
|
||||
)
|
||||
num_tokens = sum(r.total_tokens for r in batch.rollouts)
|
||||
self.progress.total_tokens += num_tokens
|
||||
self.progress.total_samples += num_rollouts
|
||||
self.progress.total_problems += num_unique_examples
|
||||
@@ -663,6 +616,7 @@ class Orchestrator:
|
||||
self.train_sink.reset_pre_filter_stats()
|
||||
self.progress.step += 1
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
trim_process_memory()
|
||||
|
||||
def maybe_trigger_eval(self, step: int) -> None:
|
||||
"""Fire eligible eval epochs and flip to ``PREFER_EVAL`` if anything
|
||||
@@ -760,13 +714,14 @@ class Orchestrator:
|
||||
trainable_rate = (n_trainable / n_survivors) if n_survivors else 0.0
|
||||
reward_mean = sum(r.reward for r in batch.rollouts) / max(n_survivors, 1)
|
||||
max_off_policy = max((r.off_policy_steps for r in batch.rollouts), default=0)
|
||||
turns_mean = sum(len(r.raw.get("trajectory") or []) for r in batch.rollouts) / max(n_survivors, 1)
|
||||
turns_mean = sum(r.num_turns for r in batch.rollouts) / max(n_survivors, 1)
|
||||
branches_mean = sum(r.num_branches for r in batch.rollouts) / max(n_survivors, 1)
|
||||
truncation_rate = sum(1 for r in batch.rollouts if r.is_truncated) / max(n_survivors, 1)
|
||||
|
||||
head = (
|
||||
f"Step {step} | {format_time(step_time):>7} | Reward {reward_mean:.4f} | "
|
||||
f"Trainable {n_trainable}/{n_survivors} ({trainable_rate:.1%}) | "
|
||||
f"Turns {turns_mean:.1f} | Max Off-Policy {max_off_policy} | "
|
||||
f"Turns {turns_mean:.1f} | Branches {branches_mean:.1f} | Max Off-Policy {max_off_policy} | "
|
||||
f"Error {error_rate:.1%} | Truncation {truncation_rate:.1%}"
|
||||
)
|
||||
if len(self.train_envs) <= 1:
|
||||
@@ -784,15 +739,12 @@ class Orchestrator:
|
||||
env_error_rate = (n_env_errors / n_env_arrivals) if n_env_arrivals else 0.0
|
||||
env_reward = (sum(r.reward for r in env_rollouts) / len(env_rollouts)) if env_rollouts else 0.0
|
||||
env_max_off_policy = max((r.off_policy_steps for r in env_rollouts), default=0)
|
||||
env_turns = (
|
||||
sum(len(r.raw.get("trajectory") or []) for r in env_rollouts) / len(env_rollouts)
|
||||
if env_rollouts
|
||||
else 0.0
|
||||
)
|
||||
env_turns = sum(r.num_turns for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
|
||||
env_branches = sum(r.num_branches for r in env_rollouts) / len(env_rollouts) if env_rollouts else 0.0
|
||||
env_truncation = sum(1 for r in env_rollouts if r.is_truncated) / len(env_rollouts) if env_rollouts else 0.0
|
||||
lines.append(
|
||||
f"╰─ {env_name:<{name_width}} | Ratio {ratio:.1%} | Reward {env_reward:.4f} | "
|
||||
f"Turns {env_turns:.1f} | Max Off-Policy {env_max_off_policy} | "
|
||||
f"Turns {env_turns:.1f} | Branches {env_branches:.1f} | Max Off-Policy {env_max_off_policy} | "
|
||||
f"Error {env_error_rate:.1%} | Truncation {env_truncation:.1%}"
|
||||
)
|
||||
get_logger().success("\n\t\t ".join(lines))
|
||||
@@ -804,15 +756,14 @@ class Orchestrator:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no surviving rollouts, skipping log")
|
||||
return
|
||||
|
||||
rollout_dicts = [r.to_dict() for r in batch.rollouts]
|
||||
rollout_dicts = [r.model_dump(mode="json", exclude=ROLLOUT_DUMP_EXCLUDE) for r in batch.rollouts]
|
||||
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
|
||||
await asyncio.to_thread(
|
||||
save_rollouts,
|
||||
rollout_dicts,
|
||||
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
|
||||
exclude_keys={"trajectory"},
|
||||
)
|
||||
self.monitor.log_eval_samples(rollout_dicts, env_name=batch.env_name, step=batch.step)
|
||||
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
|
||||
policy_versions = {r.policy_version for r in batch.rollouts}
|
||||
policy_version = min(policy_versions)
|
||||
if len(policy_versions) > 1:
|
||||
@@ -827,11 +778,12 @@ class Orchestrator:
|
||||
error_rate = ((batch.metrics.n_cancelled + batch.metrics.n_errored) / n_total) if n_total else 0.0
|
||||
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
|
||||
branches_mean = sum(r.num_branches for r in batch.rollouts) / len(batch.rollouts)
|
||||
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"Policy v{policy_version} | {format_time(elapsed):>7} | Reward {batch.metrics.reward_mean:.4f} | "
|
||||
f"Turns {batch.metrics.num_turns_mean:.1f} | "
|
||||
f"Turns {batch.metrics.num_turns_mean:.1f} | Branches {branches_mean:.1f} | "
|
||||
f"Error {error_rate:.1%} | Truncation {batch.metrics.truncation_rate:.1%}"
|
||||
)
|
||||
|
||||
@@ -876,6 +828,10 @@ class Orchestrator:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
|
||||
the new policy version is live."""
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
TOKEN_EXPORT_METRIC_FIELDS = ("mismatch_kl", "entropy")
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Stats:
|
||||
total: float = 0.0
|
||||
count: int = 0
|
||||
maximum: float = -math.inf
|
||||
|
||||
def add(self, value: Any) -> None:
|
||||
if not isinstance(value, int | float):
|
||||
return
|
||||
value = float(value)
|
||||
if not math.isfinite(value):
|
||||
return
|
||||
self.total += value
|
||||
self.count += 1
|
||||
self.maximum = max(self.maximum, value)
|
||||
|
||||
def as_metrics(self, prefix: str) -> dict[str, float]:
|
||||
if self.count == 0:
|
||||
return {}
|
||||
return {
|
||||
f"{prefix}/mean": self.total / self.count,
|
||||
f"{prefix}/max": self.maximum,
|
||||
}
|
||||
|
||||
|
||||
def collect_next_token_export_metrics(output_dir: Path, *, last_logged_step: int) -> dict[str, float | int]:
|
||||
"""Log-ready metrics for the oldest unlogged stable step, namespaced under
|
||||
``trainer/`` and stamped with ``trainer/step`` (the run step they belong to).
|
||||
Empty when there is no new stable step."""
|
||||
stable_steps = [step for step in _stable_token_export_steps(output_dir) if step > last_logged_step]
|
||||
if not stable_steps:
|
||||
return {}
|
||||
|
||||
step = min(stable_steps)
|
||||
metrics: dict[str, float | int] = {
|
||||
f"trainer/{key}": value for key, value in collect_token_export_metrics(output_dir, step).items()
|
||||
}
|
||||
metrics["trainer/step"] = step
|
||||
return metrics
|
||||
|
||||
|
||||
def collect_token_export_metrics(output_dir: Path, step: int) -> dict[str, float | int]:
|
||||
step_dir = output_dir / "token_exports" / f"step_{step}"
|
||||
if not (step_dir / "STABLE").exists():
|
||||
return {}
|
||||
|
||||
stats_by_key: dict[str, _Stats] = {}
|
||||
sequence_count = 0
|
||||
skipped_count = 0
|
||||
|
||||
for export_file in sorted(step_dir.glob("rank_*.jsonl")):
|
||||
with export_file.open(encoding="utf-8") as file:
|
||||
for line in file:
|
||||
if not line.strip():
|
||||
continue
|
||||
# Token exports are best-effort monitoring; a malformed line or a
|
||||
# length-mismatched record shouldn't abort the orchestrator step.
|
||||
try:
|
||||
record = json.loads(line)
|
||||
values_by_field = {field: _loss_token_values(record, field) for field in TOKEN_EXPORT_METRIC_FIELDS}
|
||||
except ValueError:
|
||||
skipped_count += 1
|
||||
continue
|
||||
sequence_count += 1
|
||||
for field, values in values_by_field.items():
|
||||
for value in values:
|
||||
stats_by_key.setdefault(field, _Stats()).add(value)
|
||||
|
||||
if skipped_count:
|
||||
get_logger().warning(f"Skipped {skipped_count} malformed token-export record(s) in {step_dir}")
|
||||
|
||||
metrics: dict[str, float | int] = {}
|
||||
if sequence_count == 0:
|
||||
return metrics
|
||||
for key, stats in sorted(stats_by_key.items()):
|
||||
metrics.update(stats.as_metrics(key))
|
||||
return metrics
|
||||
|
||||
|
||||
def _stable_token_export_steps(output_dir: Path) -> list[int]:
|
||||
token_exports_dir = output_dir / "token_exports"
|
||||
if not token_exports_dir.exists():
|
||||
return []
|
||||
|
||||
steps = []
|
||||
for step_dir in token_exports_dir.glob("step_*"):
|
||||
if not (step_dir / "STABLE").exists():
|
||||
continue
|
||||
try:
|
||||
steps.append(int(step_dir.name.removeprefix("step_")))
|
||||
except ValueError:
|
||||
continue
|
||||
return sorted(steps)
|
||||
|
||||
|
||||
def _loss_token_values(record: dict[str, Any], field: str) -> list[Any]:
|
||||
loss_mask = record.get("loss_mask", [])
|
||||
values = record.get(field, [])
|
||||
if len(loss_mask) != len(values):
|
||||
raise ValueError(
|
||||
f"Token export record has mismatched loss_mask and {field} lengths: {len(loss_mask)} != {len(values)}"
|
||||
)
|
||||
return [value for value, keep in zip(values, loss_mask) if keep]
|
||||
@@ -21,12 +21,8 @@ from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.advantage import assign_advantages
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
from prime_rl.orchestrator.filters import RolloutFilter, apply_filters
|
||||
from prime_rl.orchestrator.trajectories import (
|
||||
backfill_rollout_tokens,
|
||||
interleave_rollout,
|
||||
offload_images_to_disk,
|
||||
)
|
||||
from prime_rl.orchestrator.types import TrainBatch, TrainBatchMetrics, TrainRollout
|
||||
from prime_rl.orchestrator.trajectories import trace_to_samples
|
||||
from prime_rl.orchestrator.types import Rollout, TrainBatch, TrainBatchMetrics
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -39,7 +35,6 @@ class TrainSink:
|
||||
config: OrchestratorConfig,
|
||||
*,
|
||||
tokenizer,
|
||||
renderer,
|
||||
train_envs: TrainEnvs,
|
||||
mm_token_type_ids_mapping: dict[int, int] | None,
|
||||
batch_size: int | None,
|
||||
@@ -52,7 +47,6 @@ class TrainSink:
|
||||
)
|
||||
self.config = config
|
||||
self.tokenizer = tokenizer
|
||||
self.renderer = renderer
|
||||
self.train_envs = train_envs
|
||||
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
|
||||
self.batch_size = batch_size
|
||||
@@ -60,11 +54,15 @@ class TrainSink:
|
||||
self.pre_filters = pre_filters
|
||||
self.post_filters = post_filters
|
||||
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, example_id)``
|
||||
# isn't unique — the same example can be re-sampled while an
|
||||
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
|
||||
# isn't unique — the same task can be re-sampled while an
|
||||
# earlier group is still in flight
|
||||
self.pending_groups: dict[uuid.UUID, list[TrainRollout]] = defaultdict(list)
|
||||
self.pending_batch: list[TrainRollout] = []
|
||||
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
|
||||
self.pending_batch: list[Rollout] = []
|
||||
# Running token total of ``pending_batch`` (token-batched runs), kept in
|
||||
# sync on append/pop so the readiness check never re-walks the uncached
|
||||
# ``Trace.total_tokens`` graph property per arrival.
|
||||
self.pending_tokens: int = 0
|
||||
|
||||
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
|
||||
self.pre_filter_seen = 0
|
||||
@@ -79,13 +77,13 @@ class TrainSink:
|
||||
def group_size_for(self, env_name: str) -> int:
|
||||
return self.train_envs.get(env_name).config.group_size
|
||||
|
||||
def in_progress_groups(self) -> list[list[TrainRollout]]:
|
||||
def in_progress_groups(self) -> list[list[Rollout]]:
|
||||
"""Per-rollout groups currently accumulating in ``pending_groups`` —
|
||||
i.e. groups that haven't hit ``group_size`` yet, so the pipeline log
|
||||
can reflect partial-group progress. Skips group-scoring envs (whose
|
||||
rollouts only make sense as a unit — the user expects per-group
|
||||
fill, not per-rollout, for those)."""
|
||||
out: list[list[TrainRollout]] = []
|
||||
out: list[list[Rollout]] = []
|
||||
for rollouts in self.pending_groups.values():
|
||||
if not rollouts:
|
||||
continue
|
||||
@@ -103,11 +101,7 @@ class TrainSink:
|
||||
if self.batch_size is not None:
|
||||
return len(self.pending_batch), self.batch_size, "rollouts"
|
||||
assert self.token_batch_size is not None
|
||||
tokens = sum(
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
for r in self.pending_batch
|
||||
)
|
||||
return tokens, self.token_batch_size, "tokens"
|
||||
return self.pending_tokens, self.token_batch_size, "tokens"
|
||||
|
||||
def buffered_count(self) -> int:
|
||||
"""Rollouts that have arrived but sit in not-yet-complete groups
|
||||
@@ -122,13 +116,13 @@ class TrainSink:
|
||||
counts[r.env_name] += 1
|
||||
return dict(counts)
|
||||
|
||||
async def add(self, rollout: TrainRollout) -> TrainBatch | None:
|
||||
async def add(self, rollout: Rollout) -> TrainBatch | None:
|
||||
"""Process one arrival; finalize the group on the ``group_size``-th
|
||||
arrival; return a ``TrainBatch`` if the batch threshold is met."""
|
||||
await self.process_rollout(rollout)
|
||||
env_name = rollout.env_name
|
||||
self.arrivals_by_env[env_name] += 1
|
||||
if rollout.error is not None:
|
||||
if rollout.has_error:
|
||||
self.errors_by_env[env_name] += 1
|
||||
self.pending_groups[rollout.group_id].append(rollout)
|
||||
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
|
||||
@@ -136,37 +130,26 @@ class TrainSink:
|
||||
ready = (
|
||||
len(self.pending_batch) >= self.batch_size
|
||||
if self.batch_size is not None
|
||||
else sum(
|
||||
r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
for r in self.pending_batch
|
||||
)
|
||||
>= (self.token_batch_size or 0)
|
||||
else self.pending_tokens >= (self.token_batch_size or 0)
|
||||
)
|
||||
if ready:
|
||||
return self.process_batch()
|
||||
return None
|
||||
|
||||
async def process_rollout(self, rollout: TrainRollout) -> None:
|
||||
"""Tokenize the rollout eagerly. Backfills tokens if the env didn't
|
||||
return them (SFT against external teacher APIs); errored rollouts
|
||||
skip tokenization and get dropped at the group level."""
|
||||
if rollout.error is not None:
|
||||
async def process_rollout(self, rollout: Rollout) -> None:
|
||||
"""Build training samples from the rollout's Trace (one per branch), walking the
|
||||
message graph. Training is renderer-only across all modes (RL/OPD student, SFT teacher),
|
||||
so every node already carries its tokens. Errored rollouts are dropped at the group
|
||||
level, so skip them here."""
|
||||
if rollout.has_error:
|
||||
return
|
||||
raw = rollout.raw
|
||||
needs_backfill = any(s["tokens"] is None for s in raw.get("trajectory") or [])
|
||||
if needs_backfill:
|
||||
await asyncio.to_thread(backfill_rollout_tokens, raw, self.tokenizer, renderer=self.renderer)
|
||||
samples = await asyncio.to_thread(
|
||||
interleave_rollout,
|
||||
raw,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
trace_to_samples,
|
||||
rollout,
|
||||
env_name=rollout.env_name,
|
||||
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
|
||||
)
|
||||
rollout.samples = samples or []
|
||||
# Offload base64 image bytes to disk as soon as the rollout is
|
||||
# tokenized, so memory stays flat instead of holding every buffered
|
||||
# rollout's images until the batch ships (no-op for text-only).
|
||||
await asyncio.to_thread(offload_images_to_disk, [raw], self.config.output_dir)
|
||||
|
||||
def process_group(self, group_id: uuid.UUID) -> None:
|
||||
"""Finalize one GRPO group: drop errored rollouts (the whole group
|
||||
@@ -176,8 +159,8 @@ class TrainSink:
|
||||
if not group:
|
||||
return
|
||||
env_name = group[0].env_name
|
||||
example_id = group[0].example_id
|
||||
survivors = [r for r in group if r.error is None]
|
||||
task_idx = group[0].task.idx
|
||||
survivors = [r for r in group if not r.has_error]
|
||||
num_errored = len(group) - len(survivors)
|
||||
|
||||
# Group-scoring envs: any failure makes survivors' rewards unsafe
|
||||
@@ -185,23 +168,23 @@ class TrainSink:
|
||||
env = self.train_envs.get(env_name)
|
||||
if num_errored > 0 and env.requires_group_scoring:
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} example_id={example_id} | "
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | dropped: group-scored partial"
|
||||
)
|
||||
return
|
||||
if not survivors:
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} example_id={example_id} | "
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}) | dropped: all failed"
|
||||
)
|
||||
return
|
||||
|
||||
assign_advantages(survivors, self.train_envs.get(env_name).advantage_fn)
|
||||
assign_advantages(survivors, env.advantage_fn)
|
||||
|
||||
# Propagate to the pre-tokenized samples so the orchestrator can
|
||||
# collect samples at ship time without re-walking rollouts. The env
|
||||
# has a single sampling temperature; fan it out across each sample's
|
||||
# completion tokens here (interleave leaves it empty).
|
||||
# has a single sampling temperature; fan it out per token (context
|
||||
# tokens are masked out, so their temperature is don't-care).
|
||||
temperature = env.sampling_args["temperature"]
|
||||
for r in survivors:
|
||||
for sample in r.samples:
|
||||
@@ -209,7 +192,7 @@ class TrainSink:
|
||||
sample.reward = r.reward
|
||||
sample.env_name = r.env_name
|
||||
sample.training_mode = self.config.training_mode
|
||||
sample.completion_temperatures = [temperature] * len(sample.completion_ids)
|
||||
sample.temperatures = [temperature] * len(sample.token_ids)
|
||||
|
||||
if self.pre_filters:
|
||||
apply_filters(self.pre_filters, survivors)
|
||||
@@ -229,6 +212,8 @@ class TrainSink:
|
||||
r.filter_results = {}
|
||||
r.is_filtered = False
|
||||
self.pending_batch.append(r)
|
||||
if self.token_batch_size is not None:
|
||||
self.pending_tokens += r.total_tokens
|
||||
|
||||
# Per-group summary. One line per finalized group; per-filter
|
||||
# detection breakdown lives at debug level in ``apply_filters``
|
||||
@@ -236,7 +221,7 @@ class TrainSink:
|
||||
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
|
||||
filter_str = ", ".join(f"{n}={c}" for n, c in filtered_by_name.items()) if filtered_by_name else "—"
|
||||
get_logger().debug(
|
||||
f"Finished group | env={env_name} example_id={example_id} | "
|
||||
f"Finished group | env={env_name} task_idx={task_idx} | "
|
||||
f"rollouts={len(group)} (errored={num_errored}, filtered={num_filtered}) | "
|
||||
f"reward={avg_reward:.4f} | filters: {filter_str}"
|
||||
)
|
||||
@@ -255,12 +240,13 @@ class TrainSink:
|
||||
cut = 0
|
||||
running = 0
|
||||
for i, r in enumerate(self.pending_batch):
|
||||
running += r.raw["token_usage"]["final_input_tokens"] + r.raw["token_usage"]["final_output_tokens"]
|
||||
running += r.total_tokens
|
||||
cut = i + 1
|
||||
if running >= self.token_batch_size:
|
||||
break
|
||||
cohort = self.pending_batch[:cut]
|
||||
self.pending_batch = self.pending_batch[cut:]
|
||||
self.pending_tokens -= running
|
||||
|
||||
if self.post_filters:
|
||||
apply_filters(self.post_filters, cohort)
|
||||
@@ -278,8 +264,8 @@ class TrainSink:
|
||||
prefill = 0
|
||||
decode = 0
|
||||
for sample in r.samples:
|
||||
sample_decode = sum(sample.completion_mask)
|
||||
sample_prefill = len(sample.prompt_ids) + len(sample.completion_mask) - sample_decode
|
||||
sample_decode = sum(sample.mask)
|
||||
sample_prefill = len(sample.token_ids) - sample_decode
|
||||
decode += sample_decode
|
||||
prefill += sample_prefill
|
||||
if not r.is_filtered:
|
||||
|
||||
@@ -14,7 +14,7 @@ class TrainSource:
|
||||
"""``next_example(available_permits)`` picks a weighted-RR env and
|
||||
returns its next example (or ``None`` when the env's per-call permit
|
||||
cost doesn't fit — the dispatch loop retries when permits free up).
|
||||
Returned dicts carry ``env_name`` + ``example_id``."""
|
||||
Returned dicts carry ``env_name`` + ``task_idx``."""
|
||||
|
||||
def __init__(self, train_envs: TrainEnvs, *, seed: int | None) -> None:
|
||||
self.rng = random.Random(seed)
|
||||
@@ -28,11 +28,9 @@ class TrainSource:
|
||||
# per-rollout envs need 1
|
||||
self.env_costs: dict[str, int] = {}
|
||||
for env in self.envs:
|
||||
rows: list[dict] = []
|
||||
for row in env.get_dataset(seed=seed):
|
||||
ex = dict(row)
|
||||
ex["env_name"] = env.name
|
||||
rows.append(ex)
|
||||
# The orchestrator never loads the env: sample over the task-index
|
||||
# range the server reported via info() (num_tasks).
|
||||
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
|
||||
self.rng.shuffle(rows)
|
||||
self.examples[env.name] = rows
|
||||
self.cursors[env.name] = 0
|
||||
|
||||
@@ -1,652 +1,115 @@
|
||||
import base64
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
"""Turn a v1 `Trace` (the env server's native, typed output) into training data.
|
||||
|
||||
The orchestrator holds a real `vf.Trace` (validated in `envs.py`), so everything here is
|
||||
attribute access — no dicts. The trace is a message graph (`trace.nodes`); each `trace.branches`
|
||||
entry (a root→leaf path) is first-class and carries its own flat token sequence
|
||||
(`branch.token_ids` / `branch.sampled_mask` / `branch.logprobs`), so a branch yields one
|
||||
training sample directly. Token-length readers (`completion_len`, `total_tokens`, `num_turns`)
|
||||
live on `vf.Trace` itself.
|
||||
|
||||
Training is renderer-only across every mode (RL/OPD student, SFT teacher), so every node
|
||||
always carries its tokens — no backfill needed. For multimodal rollouts the branch also carries
|
||||
the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat `mm_kwargs` /
|
||||
`mm_token_type_ids` the trainer forwards.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pybase64
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.transport import RoutedExperts, TrainingSample
|
||||
from prime_rl.utils.chat_template import (
|
||||
common_prefix_len,
|
||||
deserialize_tool_calls,
|
||||
normalize_messages,
|
||||
render_messages,
|
||||
strip_message_content,
|
||||
)
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.transport.types import EncodedTensor, RoutedExperts
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# We use list() instead of deepcopy() for flat lists (token IDs, logprobs) - safe because
|
||||
# primitives are immutable. mm_kwargs payloads are not mutated after creation.
|
||||
|
||||
def _to_numpy(val) -> np.ndarray:
|
||||
"""A renderer mm item value (torch tensor or numpy array) -> a contiguous numpy array."""
|
||||
if hasattr(val, "detach"): # torch tensor
|
||||
val = val.detach().cpu().numpy()
|
||||
return np.ascontiguousarray(val)
|
||||
|
||||
|
||||
def align_routed_experts(
|
||||
routed_experts: np.ndarray | None,
|
||||
expected_len: int,
|
||||
) -> np.ndarray | None:
|
||||
"""Align routed_experts length with the expected token count.
|
||||
|
||||
VLLM's capturer uses `num_tokens - 1` slot mappings because the final
|
||||
generated token was never fed as input to a forward pass and has no
|
||||
routing decision. Append zero-filled entries for the missing positions.
|
||||
"""
|
||||
if routed_experts is None:
|
||||
return routed_experts
|
||||
assert routed_experts.ndim == 3
|
||||
if routed_experts.shape[0] > expected_len:
|
||||
return np.ascontiguousarray(routed_experts[:expected_len])
|
||||
deficit = expected_len - routed_experts.shape[0]
|
||||
if deficit <= 0:
|
||||
return routed_experts
|
||||
padding = np.zeros((deficit, routed_experts.shape[1], routed_experts.shape[2]), dtype=routed_experts.dtype)
|
||||
return np.concatenate((routed_experts, padding), axis=0)
|
||||
def _encode_mm_kwargs(mm_items: dict[str, list[dict]]) -> dict[str, EncodedTensor] | None:
|
||||
"""Concatenate the branch's per-image renderer items into the flat `mm_kwargs` the trainer
|
||||
forwards — one `EncodedTensor` per kwarg key (e.g. `pixel_values`, `image_grid_thw`), images
|
||||
cat'd along dim 0 in branch token order. Model-agnostic: the keys are whatever the processor
|
||||
emits. Returns None when there are no items."""
|
||||
bins: dict[str, list[np.ndarray]] = {}
|
||||
for items in mm_items.values(): # per modality
|
||||
for item in items: # per image
|
||||
for key, val in item.items():
|
||||
bins.setdefault(key, []).append(_to_numpy(val))
|
||||
encoded: dict[str, EncodedTensor] = {}
|
||||
for key, arrs in bins.items():
|
||||
arr = np.concatenate(arrs, axis=0)
|
||||
encoded[key] = EncodedTensor(dtype=str(arr.dtype), shape=list(arr.shape), data=arr.tobytes())
|
||||
return encoded or None
|
||||
|
||||
|
||||
def _common_prefix_len(a: list[int], b: list[int]) -> int:
|
||||
return common_prefix_len(a, b)
|
||||
|
||||
|
||||
def _normalize_messages(messages: Any, default_role: str) -> list[dict[str, Any]]:
|
||||
return normalize_messages(messages, default_role)
|
||||
|
||||
|
||||
def _deserialize_tool_calls(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return deserialize_tool_calls(messages)
|
||||
|
||||
|
||||
def _strip_message_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return strip_message_content(messages)
|
||||
|
||||
|
||||
def _render_messages(
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
messages: list[dict[str, Any]],
|
||||
add_generation_prompt: bool = False,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> list[int]:
|
||||
return render_messages(
|
||||
tokenizer,
|
||||
messages,
|
||||
add_generation_prompt=add_generation_prompt,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
|
||||
def _tokenize_step_from_messages(
|
||||
step: vf.TrajectoryStep,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
prompt = _normalize_messages(step.get("prompt"), default_role="user")
|
||||
completion = _normalize_messages(step.get("completion"), default_role="assistant")
|
||||
|
||||
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
|
||||
completion = _strip_message_content(_deserialize_tool_calls(completion))
|
||||
|
||||
assert all(m.get("role") == "assistant" for m in completion), (
|
||||
"Expected all completion messages to be assistant role for SFT distillation, "
|
||||
f"got roles: {[m.get('role') for m in completion]}"
|
||||
)
|
||||
|
||||
all_messages = prompt + completion
|
||||
prompt_has_assistant_completion = len(completion) > 0 and completion[0].get("role") == "assistant"
|
||||
prompt_ids = _render_messages(
|
||||
tokenizer,
|
||||
prompt,
|
||||
add_generation_prompt=prompt_has_assistant_completion,
|
||||
tools=tools,
|
||||
)
|
||||
full_ids = _render_messages(
|
||||
tokenizer,
|
||||
all_messages,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
split_idx = _common_prefix_len(prompt_ids, full_ids)
|
||||
original_prompt_len = len(prompt_ids)
|
||||
|
||||
prompt_ids = full_ids[:split_idx]
|
||||
completion_ids = full_ids[split_idx:]
|
||||
completion_mask = [True] * len(completion_ids)
|
||||
completion_logprobs = [0.0] * len(completion_ids)
|
||||
|
||||
return {
|
||||
"prompt_ids": prompt_ids,
|
||||
"prompt_mask": [False] * len(prompt_ids),
|
||||
"completion_ids": completion_ids,
|
||||
"completion_mask": completion_mask,
|
||||
"completion_logprobs": completion_logprobs,
|
||||
"routed_experts": None,
|
||||
"prompt_prefix_len": split_idx,
|
||||
"original_prompt_len": original_prompt_len,
|
||||
}
|
||||
|
||||
|
||||
def _convert_tools_to_oai_format(tool_defs: list) -> list[dict[str, Any]] | None:
|
||||
"""Convert verifiers Tool objects or dicts to OAI function-calling format."""
|
||||
if not tool_defs:
|
||||
def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExperts | None:
|
||||
"""The branch's router-replay array (`[tokens, layers, top_k]`) -> the transport
|
||||
`RoutedExperts` the trainer replays. Defensively realigns the token axis to `num_tokens`
|
||||
(the trainer asserts `routed_experts.shape[0] == len(token_ids)`): truncate if longer,
|
||||
zero-pad the tail if shorter. `Branch.routed_experts` already guarantees alignment, so this
|
||||
is a backstop."""
|
||||
if arr is None:
|
||||
return None
|
||||
|
||||
def _get(tool: Any, key: str) -> Any:
|
||||
if isinstance(tool, dict):
|
||||
return tool.get(key)
|
||||
return getattr(tool, key, None)
|
||||
|
||||
return [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": _get(tool, "name"),
|
||||
"description": _get(tool, "description"),
|
||||
"parameters": _get(tool, "parameters"),
|
||||
**({} if _get(tool, "strict") is None else {"strict": _get(tool, "strict")}),
|
||||
},
|
||||
}
|
||||
for tool in tool_defs
|
||||
]
|
||||
arr = np.ascontiguousarray(arr)
|
||||
if arr.shape[0] > num_tokens:
|
||||
arr = arr[:num_tokens]
|
||||
elif arr.shape[0] < num_tokens:
|
||||
pad = np.zeros((num_tokens - arr.shape[0], *arr.shape[1:]), dtype=arr.dtype)
|
||||
arr = np.concatenate([arr, pad], axis=0)
|
||||
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
|
||||
|
||||
|
||||
def _tokenize_step_with_renderer(
|
||||
step: vf.TrajectoryStep,
|
||||
renderer,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Tokenize a trajectory step using a Renderer."""
|
||||
from renderers.base import build_trajectory_step
|
||||
|
||||
prompt = _normalize_messages(step.get("prompt"), default_role="user")
|
||||
completion = _normalize_messages(step.get("completion"), default_role="assistant")
|
||||
prompt = _strip_message_content(_deserialize_tool_calls(prompt))
|
||||
completion = _strip_message_content(_deserialize_tool_calls(completion))
|
||||
return build_trajectory_step(renderer, prompt, completion, tools=tools)
|
||||
|
||||
|
||||
def backfill_rollout_tokens(
|
||||
output: vf.RolloutOutput,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
renderer=None,
|
||||
) -> bool:
|
||||
"""Populate missing step tokens from prompt/completion messages.
|
||||
|
||||
When a renderer is provided, uses it for tokenization (faster, deterministic).
|
||||
Otherwise falls back to the tokenizer + apply_chat_template path.
|
||||
"""
|
||||
if all(step["tokens"] is not None for step in output["trajectory"]):
|
||||
return True
|
||||
|
||||
logger = get_logger()
|
||||
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
|
||||
|
||||
for step_idx, step in enumerate(output["trajectory"]):
|
||||
if step["tokens"] is not None:
|
||||
continue
|
||||
|
||||
if renderer is not None:
|
||||
step["tokens"] = _tokenize_step_with_renderer(step, renderer, tools=tools)
|
||||
else:
|
||||
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools)
|
||||
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
|
||||
logger.debug(
|
||||
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
|
||||
f"Using longest common prefix length {reconstructed['prompt_prefix_len']} "
|
||||
f"(original prompt had {reconstructed['original_prompt_len']} tokens)."
|
||||
)
|
||||
reconstructed.pop("prompt_prefix_len")
|
||||
reconstructed.pop("original_prompt_len")
|
||||
step["tokens"] = reconstructed
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def interleave_rollout(
|
||||
output: vf.RolloutOutput,
|
||||
mm_token_type_ids_mapping: dict[int, int] | None = None,
|
||||
def trace_to_samples(
|
||||
trace: vf.Trace,
|
||||
*,
|
||||
env_name: str = "",
|
||||
) -> list[TrainingSample] | None:
|
||||
mm_token_type_ids_mapping: dict[int, int] | None = None,
|
||||
) -> list[TrainingSample]:
|
||||
"""Convert a v1 `Trace` into `TrainingSample`s — one per branch.
|
||||
|
||||
Each `trace.branches` entry is already a flat token sequence (`branch.token_ids` /
|
||||
`branch.sampled_mask` / `branch.logprobs`), so a sample carries it directly: `mask` marks
|
||||
the trainable (model-sampled) tokens, the context tokens between completions stay masked
|
||||
out. On a rollout error the whole completion is masked out. A branch carrying images also
|
||||
gets `mm_kwargs` (the concatenated pixel tensors) and `mm_token_type_ids` (the renderer's
|
||||
`mm_token_type_id_map` applied to the branch tokens). Branches with no sampled tokens
|
||||
(e.g. an openai client carrying none) yield nothing.
|
||||
"""
|
||||
Convert vf.RolloutOutput to trainable rollouts by interleaving trajectory steps
|
||||
where the extension property holds.
|
||||
|
||||
When consecutive steps share token prefixes (extension property), they are
|
||||
merged into a single sample. When extension breaks (e.g., due to context
|
||||
compaction or a change in control-flow), a new sample is started.
|
||||
|
||||
Supports multi-prefix matching to handle interleaved agents. For example,
|
||||
[agent1-step1, agent1-step2, agent2-step1, agent1-step3] produces two samples:
|
||||
agent1 steps merged together, agent2 step separate.
|
||||
|
||||
Returns a list of samples - could be 1 (extension always held) or up to T
|
||||
(extension never held).
|
||||
|
||||
For VLM models, each renderer-produced trajectory step carries its
|
||||
per-image processed tensors inline on ``multi_modal_data``; the last
|
||||
merged step's sidecar covers every image in the sample.
|
||||
"""
|
||||
logger = get_logger()
|
||||
|
||||
trajectory = output["trajectory"]
|
||||
if len(trajectory) == 0:
|
||||
error = output.get("error")
|
||||
stop = output.get("stop_condition")
|
||||
logger.warning(
|
||||
f"No trajectory steps for example {output['example_id']} (error={error}, stop={stop}). Skipping rollout."
|
||||
)
|
||||
return None
|
||||
|
||||
has_error = output["error"] is not None
|
||||
|
||||
def prepare_step_tokens(step: vf.TrajectoryStep, step_idx: int) -> dict[str, Any] | None:
|
||||
tokens = step["tokens"]
|
||||
if tokens is not None:
|
||||
routed_experts_payload = tokens.get("routed_experts")
|
||||
routed_experts = None
|
||||
routed_experts_start = None
|
||||
if routed_experts_payload is not None:
|
||||
decoded_routed_experts = pybase64.b64decode_as_bytearray(routed_experts_payload["data"])
|
||||
routed_experts = np.frombuffer(decoded_routed_experts, dtype=np.uint8).reshape(
|
||||
routed_experts_payload["shape"]
|
||||
)
|
||||
routed_experts_start = routed_experts_payload["start"]
|
||||
|
||||
return {
|
||||
"prompt_ids": list(tokens["prompt_ids"]),
|
||||
"prompt_mask": list(map(bool, tokens["prompt_mask"])),
|
||||
"completion_ids": list(tokens["completion_ids"]),
|
||||
"completion_mask": list(map(bool, tokens["completion_mask"])),
|
||||
"completion_logprobs": list(tokens["completion_logprobs"]),
|
||||
"routed_experts": routed_experts,
|
||||
"routed_experts_start": routed_experts_start,
|
||||
# Renderer-emitted multimodal sidecar (placeholders + per-item
|
||||
# processed tensors). Populated when the rollout went through
|
||||
# a multimodal-aware renderer (e.g. Qwen3VLRenderer); absent
|
||||
# for text-only rollouts.
|
||||
"multi_modal_data": tokens.get("multi_modal_data"),
|
||||
}
|
||||
|
||||
logger.warning(f"Missing rollout tokens for example {output['example_id']} step {step_idx}.")
|
||||
return None
|
||||
|
||||
prepared_steps: list[dict[str, Any]] = []
|
||||
for step_idx, step in enumerate(trajectory):
|
||||
prepared = prepare_step_tokens(step, step_idx)
|
||||
if prepared is None:
|
||||
return None
|
||||
prepared_steps.append(prepared)
|
||||
|
||||
# Deferred routed_experts state per sample: O(N) chunk list concatenated
|
||||
# once at finalize, replacing the prior O(N²) per-extension unpack/repack.
|
||||
sample_routed_state: dict[int, dict[str, Any]] = {}
|
||||
routed_prefix_states: dict[int, list[tuple[list[int], list[int], dict[str, Any]]]] = {}
|
||||
|
||||
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
|
||||
# is the explicit list of prepared_steps positions merged into this sample —
|
||||
# non-contiguous when other agents' steps interleave.
|
||||
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
|
||||
|
||||
def make_sample(tokens: dict[str, Any], step_idx: int) -> TrainingSample:
|
||||
"""Create a new TrainingSample from a trajectory step."""
|
||||
if has_error:
|
||||
completion_mask = [False] * len(tokens["completion_mask"])
|
||||
else:
|
||||
completion_mask = list(tokens["completion_mask"])
|
||||
completion_ids = list(tokens["completion_ids"])
|
||||
|
||||
prompt_ids = list(tokens["prompt_ids"])
|
||||
sample = TrainingSample(
|
||||
prompt_ids=prompt_ids,
|
||||
prompt_mask=list(tokens["prompt_mask"]),
|
||||
completion_ids=completion_ids,
|
||||
completion_mask=completion_mask,
|
||||
completion_logprobs=list(tokens["completion_logprobs"]),
|
||||
completion_temperatures=[],
|
||||
teacher_logprobs=None,
|
||||
advantage=None,
|
||||
env_name=env_name,
|
||||
mm_token_type_ids=None,
|
||||
routed_experts=None, # deferred — finalized at end of interleave_rollout
|
||||
)
|
||||
# Initialize routed-experts state for this sample. First chunk is the
|
||||
# raw step routed_experts (no pad, no copy). running_len is the
|
||||
# cumulative count across chunks; tracked so the boundary fix-up at
|
||||
# each extension is a no-op append rather than a destructive write.
|
||||
step_routed = tokens.get("routed_experts")
|
||||
if step_routed is not None:
|
||||
routed_start = tokens["routed_experts_start"]
|
||||
assert routed_start is not None, f"Missing routed_experts_start for step {step_idx}"
|
||||
chunks: list[np.ndarray] = []
|
||||
running_len = 0
|
||||
if routed_start > 0:
|
||||
source_len = routed_start + 1
|
||||
assert source_len in routed_prefix_states, (
|
||||
f"Missing routed prefix state for step {step_idx}: "
|
||||
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
|
||||
)
|
||||
source_state = None
|
||||
for prompt_ids, completion_ids, candidate_state in routed_prefix_states[source_len]:
|
||||
prompt_len = len(prompt_ids)
|
||||
if (
|
||||
tokens["prompt_ids"][:prompt_len] == prompt_ids
|
||||
and tokens["prompt_ids"][prompt_len:source_len] == completion_ids
|
||||
):
|
||||
source_state = candidate_state
|
||||
break
|
||||
assert source_state is not None, (
|
||||
f"No matching routed prefix for step {step_idx}: "
|
||||
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
|
||||
)
|
||||
assert source_state["running_len"] >= routed_start, (
|
||||
f"Routed prefix too short for step {step_idx}: "
|
||||
f"running_len={source_state['running_len']}, routed_start={routed_start}"
|
||||
)
|
||||
remaining = routed_start
|
||||
for chunk in source_state["chunks"]:
|
||||
if remaining == 0:
|
||||
break
|
||||
take = min(remaining, int(chunk.shape[0]))
|
||||
chunks.append(chunk[:take])
|
||||
remaining -= take
|
||||
assert remaining == 0, (
|
||||
f"Could not reconstruct routed prefix for step {step_idx}: "
|
||||
f"remaining={remaining}, routed_start={routed_start}"
|
||||
)
|
||||
running_len = routed_start
|
||||
chunks.append(step_routed)
|
||||
running_len += int(step_routed.shape[0])
|
||||
sample_routed_state[id(sample)] = {
|
||||
"chunks": chunks,
|
||||
"running_len": running_len,
|
||||
}
|
||||
return sample
|
||||
|
||||
def extend_sample(
|
||||
sample: TrainingSample,
|
||||
prefix_len: int,
|
||||
step_idx: int,
|
||||
) -> None:
|
||||
"""Extend an existing sample with a new trajectory step (extension property holds)."""
|
||||
tokens = prepared_steps[step_idx]
|
||||
|
||||
# Extend with new prompt tokens (mask=False, no gradient)
|
||||
new_prompt_ids = tokens["prompt_ids"][prefix_len:]
|
||||
sample.completion_ids.extend(new_prompt_ids)
|
||||
sample.completion_mask.extend([False] * len(new_prompt_ids))
|
||||
sample.completion_logprobs.extend([0.0] * len(new_prompt_ids))
|
||||
|
||||
# Extend with new completion tokens
|
||||
completion_ids = tokens["completion_ids"]
|
||||
sample.completion_ids.extend(completion_ids)
|
||||
if has_error:
|
||||
sample.completion_mask.extend([False] * len(tokens["completion_mask"]))
|
||||
else:
|
||||
sample.completion_mask.extend(tokens["completion_mask"])
|
||||
sample.completion_logprobs.extend(tokens["completion_logprobs"])
|
||||
|
||||
step_routed = tokens.get("routed_experts")
|
||||
state = sample_routed_state.get(id(sample))
|
||||
if state is not None:
|
||||
assert step_routed is not None, f"Missing routed experts for routed sample extension at step {step_idx}"
|
||||
if step_routed is not None:
|
||||
assert state is not None, f"Unexpected routed experts for unrouted sample at step {step_idx}"
|
||||
assert tokens["routed_experts_start"] == prefix_len - 1, (
|
||||
f"Routed experts delta start mismatch at step {step_idx}: "
|
||||
f"start={tokens['routed_experts_start']}, expected={prefix_len - 1}, prefix_len={prefix_len}"
|
||||
)
|
||||
# Delta payloads start at prefix_len - 1. Row 0 fills the boundary
|
||||
# token missing from the previous request; the rest is the new suffix.
|
||||
if prefix_len > 0:
|
||||
boundary_chunk = step_routed[:1]
|
||||
state["chunks"].append(boundary_chunk)
|
||||
state["running_len"] += 1
|
||||
step_routed = step_routed[1:]
|
||||
new_chunk = step_routed
|
||||
state["chunks"].append(new_chunk)
|
||||
state["running_len"] += int(new_chunk.shape[0])
|
||||
|
||||
first_tokens = prepared_steps[0]
|
||||
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
|
||||
first_sample = make_sample(first_tokens, step_idx=0)
|
||||
active_samples.append((first_prefix, first_sample, [0]))
|
||||
first_routed_state = sample_routed_state.get(id(first_sample))
|
||||
if first_routed_state is not None:
|
||||
routed_prefix_states.setdefault(len(first_prefix), []).append(
|
||||
(first_tokens["prompt_ids"], first_tokens["completion_ids"], first_routed_state)
|
||||
)
|
||||
|
||||
for step_idx, _step in enumerate(trajectory[1:], start=1):
|
||||
tokens = prepared_steps[step_idx]
|
||||
step_prompt_ids = tokens["prompt_ids"]
|
||||
|
||||
# Pick the *longest* matching active prefix. With compaction/rollback,
|
||||
# one active sample's prefix can be a strict prefix of another (e.g. a
|
||||
# later sample re-generated tokens that overlap an earlier sample's
|
||||
# prefix). Both would satisfy the slice check; the shorter would
|
||||
# silently absorb the longer sample's generated tokens as user input.
|
||||
matched_idx = None
|
||||
matched_len = -1
|
||||
matching_prefix_lens: list[int] = []
|
||||
for idx, (prefix_tokens, _, _) in enumerate(active_samples):
|
||||
pl = len(prefix_tokens)
|
||||
if step_prompt_ids[:pl] == prefix_tokens:
|
||||
matching_prefix_lens.append(pl)
|
||||
if pl > matched_len:
|
||||
matched_idx = idx
|
||||
matched_len = pl
|
||||
|
||||
if len(matching_prefix_lens) > 1:
|
||||
# Ambiguous extension: rare, but reachable via compaction/rollback
|
||||
# where a new sample's prefix happens to start with an older
|
||||
# sample's prefix. Longest-match is the correct choice; surface
|
||||
# the ambiguity so we can audit if it shows up in real rollouts.
|
||||
logger.warning(
|
||||
f"Ambiguous prefix match at step {step_idx} for example {output['example_id']}: "
|
||||
f"{len(matching_prefix_lens)} of {len(active_samples)} active prefixes match "
|
||||
f"(lens={sorted(matching_prefix_lens)}, step_prompt_len={len(step_prompt_ids)}). "
|
||||
f"Extending the longest (len={matched_len})."
|
||||
)
|
||||
|
||||
if matched_idx is not None:
|
||||
# Extension holds - merge into matched sample
|
||||
prefix_tokens, sample, step_indices = active_samples[matched_idx]
|
||||
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
active_samples[matched_idx] = (
|
||||
new_prefix,
|
||||
sample,
|
||||
step_indices + [step_idx],
|
||||
)
|
||||
routed_state = sample_routed_state.get(id(sample))
|
||||
if routed_state is not None:
|
||||
routed_prefix_states.setdefault(len(new_prefix), []).append(
|
||||
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
|
||||
)
|
||||
else:
|
||||
# No prefix matches - start a new sample
|
||||
logger.debug(
|
||||
f"Extension property broke at step {step_idx + 1} for example {output['example_id']}. "
|
||||
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
|
||||
)
|
||||
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
sample = make_sample(tokens, step_idx=step_idx)
|
||||
active_samples.append((new_prefix, sample, [step_idx]))
|
||||
routed_state = sample_routed_state.get(id(sample))
|
||||
if routed_state is not None:
|
||||
routed_prefix_states.setdefault(len(new_prefix), []).append(
|
||||
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
|
||||
)
|
||||
|
||||
# Finalize routed_experts for each sample. One concat per sample (O(N) byte
|
||||
# work) replaces the previous per-step unpack/concat/repack (O(N²)). The
|
||||
# boundary entries between steps were already inserted as one-entry chunks
|
||||
# during extend_sample, so a straight concat is correct.
|
||||
for _, sample, _ in active_samples:
|
||||
state = sample_routed_state.get(id(sample))
|
||||
if state is None:
|
||||
has_error = trace.has_error
|
||||
samples: list[TrainingSample] = []
|
||||
for branch in trace.branches:
|
||||
mask = branch.sampled_mask
|
||||
if not any(mask):
|
||||
continue
|
||||
chunks = state["chunks"]
|
||||
if not chunks:
|
||||
continue
|
||||
combined = np.concatenate(chunks, axis=0) if len(chunks) > 1 else np.ascontiguousarray(chunks[0])
|
||||
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
combined = align_routed_experts(combined, expected_len)
|
||||
combined = np.ascontiguousarray(combined)
|
||||
sample.routed_experts = RoutedExperts(
|
||||
data=combined.tobytes(),
|
||||
shape=list(combined.shape),
|
||||
dtype=str(combined.dtype),
|
||||
token_ids = branch.token_ids
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
mm_token_type_ids: list[int] | None = None
|
||||
mmd = branch.multi_modal_data
|
||||
if mmd is not None:
|
||||
mm_kwargs = _encode_mm_kwargs(mmd.mm_items)
|
||||
mapping = mm_token_type_ids_mapping or {}
|
||||
mm_token_type_ids = [mapping.get(t, 0) for t in token_ids]
|
||||
samples.append(
|
||||
TrainingSample(
|
||||
token_ids=token_ids,
|
||||
mask=[m and not has_error for m in mask],
|
||||
logprobs=branch.logprobs,
|
||||
temperatures=[], # filled by TrainSink.process_group
|
||||
teacher_logprobs=None,
|
||||
advantage=None,
|
||||
env_name=env_name,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
routed_experts=_encode_routed_experts(branch.routed_experts, len(token_ids)),
|
||||
)
|
||||
)
|
||||
|
||||
# Attach images by concatenating mm_items across every step the
|
||||
# sample covers. verifiers' ``state_to_output`` ships per-step
|
||||
# *delta* mm_data (each step contains only items not present in the
|
||||
# prior step's cumulative set, with multiset-aware dedup), so
|
||||
# reading the last step alone would miss every earlier-turn image.
|
||||
# Concat in step order recovers the per-sample cumulative set;
|
||||
# deduping again here would drop legitimate duplicate placeholders.
|
||||
for _, sample, step_indices in active_samples:
|
||||
renderer_mm = _union_step_mm_data(prepared_steps, step_indices)
|
||||
if renderer_mm is not None:
|
||||
mm_kwargs = _pack_mm_kwargs_from_renderer(renderer_mm)
|
||||
if mm_kwargs is not None:
|
||||
sample.mm_kwargs = mm_kwargs
|
||||
# ``mm_token_type_ids``: 1 for image-placeholder tokens, 2
|
||||
# for video, 0 otherwise. Renderer-supplied via
|
||||
# ``mm_token_type_id_map`` (single source of truth).
|
||||
if mm_token_type_ids_mapping is not None:
|
||||
sample.mm_token_type_ids = [
|
||||
mm_token_type_ids_mapping.get(token_id, 0)
|
||||
for token_id in sample.prompt_ids + sample.completion_ids
|
||||
]
|
||||
|
||||
return [sample for _, sample, _ in active_samples]
|
||||
|
||||
|
||||
def _union_step_mm_data(
|
||||
prepared_steps: list[dict[str, Any]],
|
||||
step_indices: list[int],
|
||||
) -> "dict[str, Any] | None":
|
||||
"""Concatenate renderer-emitted mm_items across this sample's owned steps.
|
||||
|
||||
``step_indices`` lists exactly the ``prepared_steps`` positions merged into
|
||||
the sample — explicit, not a range, so interleaved-agent trajectories skip
|
||||
steps owned by other agents.
|
||||
|
||||
Verifiers ≥ c7731bbb ships per-step *delta* mm_data instead of
|
||||
cumulative — see ``verifiers/utils/save_utils.py::_delta_intermediate_mm_data``.
|
||||
The cross-step dedup is already done there with multiset semantics
|
||||
(preserving multiplicity for an image that appears in multiple
|
||||
placeholder runs in the token stream). We just concatenate in step
|
||||
order to recover the per-sample cumulative; deduping again here
|
||||
would drop legitimate duplicate placeholders.
|
||||
"""
|
||||
union_items: dict[str, list] = {}
|
||||
union_hashes: dict[str, list] = {}
|
||||
has_any = False
|
||||
for i in step_indices:
|
||||
mm = prepared_steps[i].get("multi_modal_data")
|
||||
if mm is None:
|
||||
continue
|
||||
items = mm.mm_items if hasattr(mm, "mm_items") else (mm or {}).get("mm_items") or {}
|
||||
hashes = mm.mm_hashes if hasattr(mm, "mm_hashes") else (mm or {}).get("mm_hashes") or {}
|
||||
for modality, item_lst in items.items():
|
||||
hash_lst = hashes.get(modality, []) or []
|
||||
for j, item in enumerate(item_lst or []):
|
||||
h = hash_lst[j] if j < len(hash_lst) else None
|
||||
union_items.setdefault(modality, []).append(item)
|
||||
union_hashes.setdefault(modality, []).append(h)
|
||||
has_any = True
|
||||
if not has_any:
|
||||
return None
|
||||
return {"mm_items": union_items, "mm_hashes": union_hashes}
|
||||
|
||||
|
||||
def _pack_mm_kwargs_from_renderer(mm_data: Any) -> "dict[str, Any] | None":
|
||||
"""Batch the renderer's per-image ``mm_items`` into model-agnostic
|
||||
forward kwargs.
|
||||
|
||||
``mm_data`` may arrive as a ``MultiModalData`` instance (in-process
|
||||
for tests) or as a plain dict (after msgpack round-trip from the
|
||||
env-worker). Each item is a dict keyed by the names the model's
|
||||
``forward`` expects (``pixel_values`` + ``image_grid_thw`` for
|
||||
Qwen3-VL, just ``pixel_values`` for Gemma3-VL, etc.). We batch by
|
||||
``torch.cat(..., dim=0)`` per key — generic because every HF VLM
|
||||
processor emits a leading batch/patch dimension, and the renderer
|
||||
always processes one image per call.
|
||||
|
||||
Returns a dict of ``EncodedTensor`` payloads keyed by kwarg name,
|
||||
or ``None`` when no multimodal data is present.
|
||||
"""
|
||||
from verifiers.utils.serve_utils import decode_tensor_payload
|
||||
|
||||
from prime_rl.transport.types import EncodedTensor
|
||||
|
||||
mm_items = mm_data.mm_items if hasattr(mm_data, "mm_items") else (mm_data or {}).get("mm_items") or {}
|
||||
# Flatten across modalities into one kwarg dict — the model's
|
||||
# forward signature is the schema. ``mm_items`` is typically
|
||||
# ``{"image": [...], "video": [...]}`` but each modality's keys
|
||||
# don't collide for any HF VLM we ship today.
|
||||
per_kwarg: dict[str, list] = {}
|
||||
for _modality, items in mm_items.items():
|
||||
for item in items or []:
|
||||
for key, payload in item.items():
|
||||
per_kwarg.setdefault(key, []).append(decode_tensor_payload(payload))
|
||||
if not per_kwarg:
|
||||
return None
|
||||
out: dict[str, EncodedTensor] = {}
|
||||
for key, tensors in per_kwarg.items():
|
||||
cat = torch.cat(tensors, dim=0).contiguous()
|
||||
arr = cat.detach().cpu().numpy()
|
||||
out[key] = EncodedTensor(
|
||||
dtype=str(arr.dtype),
|
||||
shape=list(arr.shape),
|
||||
data=arr.tobytes(),
|
||||
if not samples:
|
||||
get_logger().warning(
|
||||
f"No trainable samples (error={has_error}, stop={trace.stop_condition}, num_turns={trace.num_turns})."
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
_FILE_URL_PREFIX = "file://"
|
||||
|
||||
|
||||
def offload_images_to_disk(rollouts: list[vf.RolloutOutput], output_dir: Path) -> int:
|
||||
"""Replace base64 image data in rollout trajectories with file paths on disk.
|
||||
|
||||
Scans all trajectory step prompts for data:image URLs, writes the decoded
|
||||
image bytes to ``{output_dir}/assets/images/{hash}.png``, and replaces the
|
||||
URL in-place with ``file://{path}``. Deduplicates by content hash so each
|
||||
unique image is written only once.
|
||||
|
||||
Returns the number of unique images written to disk.
|
||||
"""
|
||||
images_dir = output_dir / "assets" / "images"
|
||||
images_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
written: set[str] = set()
|
||||
|
||||
for output in rollouts:
|
||||
for step in output.get("trajectory", []):
|
||||
prompt = step.get("prompt")
|
||||
if not prompt or not isinstance(prompt, list):
|
||||
continue
|
||||
for msg in prompt:
|
||||
content = msg.get("content", [])
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for item in content:
|
||||
if item.get("type") != "image_url":
|
||||
continue
|
||||
url = item.get("image_url", {}).get("url", "")
|
||||
if not url.startswith("data:image"):
|
||||
continue
|
||||
b64_data = url.split(",", 1)[1]
|
||||
content_hash = hashlib.sha256(b64_data.encode()).hexdigest()[:16]
|
||||
path = images_dir / f"{content_hash}.png"
|
||||
if content_hash not in written:
|
||||
if not path.exists():
|
||||
path.write_bytes(base64.b64decode(b64_data))
|
||||
written.add(content_hash)
|
||||
item["image_url"]["url"] = f"{_FILE_URL_PREFIX}{path}"
|
||||
|
||||
return len(written)
|
||||
return samples
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import dataclass, field, fields
|
||||
from typing import Literal, Protocol
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Generic, Literal, Protocol
|
||||
|
||||
import verifiers as vf
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import ConfigDict, Field
|
||||
from verifiers.v1.task import TaskT
|
||||
|
||||
from prime_rl.transport import TrainingSample
|
||||
|
||||
@@ -55,7 +57,7 @@ class GroupState:
|
||||
|
||||
kind: RolloutKind
|
||||
env_name: str
|
||||
example: dict
|
||||
task_idx: int
|
||||
rollouts_to_schedule: int
|
||||
target_rollouts: int
|
||||
emitted: int = 0
|
||||
@@ -64,60 +66,25 @@ class GroupState:
|
||||
policy_version_at_start: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class FinishedRollout:
|
||||
"""A completed rollout the sink receives. ``raw`` is the env's untouched
|
||||
``vf.RolloutOutput``; prime-rl metadata lives on typed fields. Train vs
|
||||
eval is discriminated via ``isinstance``. ``rollout_id`` is the only
|
||||
safe key for tracing one rollout — ``(env_name, example_id)`` collides
|
||||
on re-sampling and ``group_id`` covers a whole group."""
|
||||
class Rollout(vf.Trace[TaskT], Generic[TaskT]):
|
||||
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
|
||||
orchestration metadata lives on it directly (set by the dispatcher once the rollout
|
||||
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
|
||||
fields are ``exclude=True``, so dumping a Rollout yields a plain trace — the on-disk
|
||||
``results.jsonl`` is unchanged."""
|
||||
|
||||
raw: vf.RolloutOutput
|
||||
env_name: str
|
||||
example_id: int | str
|
||||
group_id: uuid.UUID
|
||||
policy_version: int
|
||||
off_policy_steps: int
|
||||
rollout_id: uuid.UUID = field(default_factory=uuid.uuid4)
|
||||
model_config = ConfigDict(arbitrary_types_allowed=True) # ``samples`` holds msgspec structs
|
||||
|
||||
@property
|
||||
def error(self) -> dict | None:
|
||||
return self.raw.get("error")
|
||||
|
||||
@property
|
||||
def reward(self) -> float:
|
||||
return float(self.raw.get("reward", 0.0))
|
||||
|
||||
@property
|
||||
def is_truncated(self) -> bool:
|
||||
return bool(self.raw.get("is_truncated", False))
|
||||
|
||||
def to_dict(self) -> vf.RolloutOutput:
|
||||
"""``raw`` + metadata merged for I/O (``save_rollouts``,
|
||||
``monitor.log_samples``). Shallow copy; never mutates ``self.raw``."""
|
||||
out: vf.RolloutOutput = dict(self.raw) # type: ignore[assignment]
|
||||
for f in fields(self):
|
||||
if f.name in ("raw", "samples"):
|
||||
continue
|
||||
val = getattr(self, f.name)
|
||||
if f.name == "filter_results":
|
||||
out["filters"] = dict(val)
|
||||
continue
|
||||
out[f.name] = str(val) if isinstance(val, uuid.UUID) else val
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrainRollout(FinishedRollout):
|
||||
samples: list[TrainingSample] = field(default_factory=list)
|
||||
advantage: float | None = None
|
||||
is_filtered: bool = False
|
||||
filter_results: dict[str, bool] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class EvalRollout(FinishedRollout):
|
||||
eval_step: int = 0
|
||||
kind: RolloutKind = Field(default="train", exclude=True)
|
||||
env_name: str = Field(default="", exclude=True)
|
||||
group_id: uuid.UUID = Field(default_factory=uuid.uuid4, exclude=True)
|
||||
policy_version: int = Field(default=0, exclude=True)
|
||||
off_policy_steps: int = Field(default=0, exclude=True)
|
||||
samples: list[TrainingSample] = Field(default_factory=list, exclude=True)
|
||||
advantage: float | None = Field(default=None, exclude=True)
|
||||
is_filtered: bool = Field(default=False, exclude=True)
|
||||
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
|
||||
eval_step: int | None = Field(default=None, exclude=True)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -142,7 +109,7 @@ class TrainBatch:
|
||||
"""``samples`` is the trainer-bound payload (post-filter survivors);
|
||||
``rollouts`` is the full cohort kept for orchestrator-side I/O."""
|
||||
|
||||
rollouts: list[TrainRollout]
|
||||
rollouts: list[Rollout]
|
||||
samples: list[TrainingSample]
|
||||
metrics: TrainBatchMetrics
|
||||
|
||||
@@ -197,12 +164,17 @@ class EvalBatch:
|
||||
|
||||
env_name: str
|
||||
step: int
|
||||
rollouts: list[EvalRollout]
|
||||
rollouts: list[Rollout]
|
||||
metrics: EvalBatchMetrics
|
||||
|
||||
|
||||
class VersionObserver(Protocol):
|
||||
"""Notified after each policy update; walked by the watcher after it
|
||||
mutates ``Policy``."""
|
||||
"""Notified around each policy update; walked by the watcher.
|
||||
|
||||
``on_version_pending`` fires *before* the inference engines are paused for
|
||||
the weight update; ``on_new_version`` fires *after* the new weights are live
|
||||
and ``Policy`` has been mutated."""
|
||||
|
||||
async def on_version_pending(self, step: int) -> None: ...
|
||||
|
||||
async def on_new_version(self, step: int) -> None: ...
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
import asyncio
|
||||
import ctypes
|
||||
import gc
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from itertools import cycle
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
import verifiers as vf
|
||||
from verifiers.utils.client_utils import setup_openai_client
|
||||
from verifiers.utils.save_utils import make_serializable
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.transport import TrainingSample
|
||||
from prime_rl.utils.client import setup_inference_pool
|
||||
from prime_rl.utils.logger import InterceptHandler, get_logger
|
||||
from prime_rl.utils.logger import InterceptHandler, get_logger, setup_logger
|
||||
from prime_rl.utils.utils import (
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
@@ -22,63 +23,38 @@ from prime_rl.utils.utils import (
|
||||
|
||||
|
||||
async def setup_student_inference_pool(*, config: OrchestratorConfig, tokenizer):
|
||||
"""Build the student inference pool + matching renderer. Returns
|
||||
``(renderer | None, inference_pool)``; ``renderer`` is ``None`` on the
|
||||
MITO path (``config.renderer is None``)."""
|
||||
"""Build the student renderer and inference pool, returning ``(renderer, inference_pool)``.
|
||||
|
||||
Training is renderer-only: RL/OPD roll out through the env server's renderer client
|
||||
(token-in/out), and SFT — which rolls out against a chat-completions teacher that returns
|
||||
no tokens — re-renders the conversation with this renderer to backfill them. The renderer
|
||||
is built here from the (always-set) ``config.renderer`` and also supplies the multimodal
|
||||
token-type-id map. The eval client is plain chat-completions (eval traces aren't trained)."""
|
||||
from renderers.base import create_renderer
|
||||
|
||||
client_config = config.student.client
|
||||
model_name = config.student.model.name
|
||||
|
||||
if config.renderer is not None:
|
||||
renderer = create_renderer(tokenizer, config.renderer)
|
||||
get_logger().info(f"Initialized {type(renderer).__name__} for {model_name}")
|
||||
inference_pool = await setup_inference_pool(
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
pool_size=config.pool_size,
|
||||
)
|
||||
get_logger().info("Using direct renderer rollout client")
|
||||
return renderer, inference_pool
|
||||
|
||||
get_logger().info("Using MITO (openai_chat_completions) for rollouts")
|
||||
renderer = create_renderer(tokenizer, config.renderer)
|
||||
get_logger().info("Using renderer rollout client")
|
||||
inference_pool = await setup_inference_pool(
|
||||
client_config,
|
||||
model_name=model_name,
|
||||
train_client_type="openai_chat_completions",
|
||||
train_client_type="renderer",
|
||||
eval_client_type="openai_chat_completions",
|
||||
renderer_config=config.renderer,
|
||||
pool_size=config.pool_size,
|
||||
)
|
||||
return None, inference_pool
|
||||
return renderer, inference_pool
|
||||
|
||||
|
||||
def get_model_completion_len(output: vf.RolloutOutput) -> int:
|
||||
"""Sum of model-generated completion tokens across all turns (excludes
|
||||
environment-injected tokens between turns)."""
|
||||
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
|
||||
|
||||
|
||||
def get_tool_response_len(output: vf.RolloutOutput) -> int:
|
||||
"""Total tool-response tokens consumed across the whole rollout, read from a
|
||||
harness-emitted metric (e.g. RLM's `rlm_total_tool_response_tokens`, deduped
|
||||
across turns/branches/sub-RLMs). Returns 0 when no such metric is present."""
|
||||
metrics = output.get("metrics") or {}
|
||||
for key, value in metrics.items():
|
||||
if key.endswith("total_tool_response_tokens") and isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
return 0
|
||||
|
||||
|
||||
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts to a JSONL file using verifiers serialization."""
|
||||
def save_rollouts(rollouts: list[dict], path: Path, exclude_keys: set[str] | None = None) -> None:
|
||||
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
|
||||
with open(path, "wb") as f:
|
||||
for rollout in rollouts:
|
||||
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
|
||||
f.write(orjson.dumps(row, default=make_serializable, option=opts))
|
||||
f.write(orjson.dumps(row, default=str, option=opts))
|
||||
|
||||
|
||||
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
|
||||
@@ -90,12 +66,30 @@ def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix
|
||||
vf_logger.propagate = False
|
||||
|
||||
|
||||
def setup_env_server_logging(log_level: str, json_logging: bool = False) -> None:
|
||||
"""Configure logging for an env-server process: prime-rl's logger + routing v1's stdlib
|
||||
logs through it. Passed to verifiers' ``serve_env`` so it runs in the broker and in every
|
||||
spawned worker — fresh ``spawn`` processes that otherwise have no handlers and would drop
|
||||
their per-rollout logs."""
|
||||
setup_logger(log_level, json_logging=json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level=log_level)
|
||||
|
||||
|
||||
def set_default_executor(max_workers: int = 64) -> None:
|
||||
"""Scale the default asyncio thread pool so asyncio.to_thread has enough capacity."""
|
||||
get_logger().info(f"Setting default executor to ThreadPoolExecutor(max_workers={max_workers})")
|
||||
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
|
||||
|
||||
|
||||
def trim_process_memory() -> None:
|
||||
"""Return freed heap pages to the OS on glibc systems."""
|
||||
gc.collect()
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except Exception as exc:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
|
||||
|
||||
|
||||
async def compute_teacher_logprobs(
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
@@ -103,10 +97,15 @@ async def compute_teacher_logprobs(
|
||||
) -> list[list[float]]:
|
||||
"""Compute teacher model logprobs for a batch of training samples via prefill."""
|
||||
import httpx
|
||||
from openai import AsyncOpenAI
|
||||
from vllm.entrypoints.serve.disagg.protocol import GenerateResponse
|
||||
|
||||
async def _compute_single(client_config: vf.ClientConfig, sample: TrainingSample) -> list[float]:
|
||||
client = setup_openai_client(client_config)
|
||||
client = AsyncOpenAI(
|
||||
base_url=client_config.base_url,
|
||||
api_key=os.environ.get(client_config.api_key_var, "EMPTY"),
|
||||
default_headers=client_config.headers or None,
|
||||
)
|
||||
|
||||
# Two escape hatches from ``AsyncOpenAI.post``:
|
||||
# 1. URL — ``/inference/v1/generate`` is mounted at server root, not
|
||||
@@ -125,7 +124,7 @@ async def compute_teacher_logprobs(
|
||||
cast_to=httpx.Response,
|
||||
body={
|
||||
"model": model_name,
|
||||
"token_ids": list(sample.prompt_ids) + list(sample.completion_ids),
|
||||
"token_ids": list(sample.token_ids),
|
||||
"sampling_params": {
|
||||
"max_tokens": 1,
|
||||
"temperature": 1.0,
|
||||
|
||||
@@ -92,6 +92,24 @@ class WeightWatcher:
|
||||
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
|
||||
)
|
||||
|
||||
# Drain off-policy rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
# ``_reqs_not_processed``), which is only propagated to the workers
|
||||
# while the engine is stepping. If we drain after resume instead,
|
||||
# the aborts race with the flush of KV transfers that completed
|
||||
# during the pause and trip ``assert req_id in self.requests`` in
|
||||
# the decode scheduler's ``_update_from_kv_xfer_finished`` — killing
|
||||
# the engine and cascading to every DP rank. Draining first lets the
|
||||
# aborts settle under normal stepping. ``on_new_version`` (below)
|
||||
# still runs post-update for observers that need the live version.
|
||||
for observer in self.observers:
|
||||
try:
|
||||
await observer.on_version_pending(next_step)
|
||||
except Exception as exc:
|
||||
get_logger().warning(
|
||||
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
|
||||
)
|
||||
|
||||
get_logger().debug(f"Updating weights to step {next_step}")
|
||||
t1 = time.perf_counter()
|
||||
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
|
||||
|
||||
@@ -15,14 +15,20 @@ rank_log() {
|
||||
# launch_inference_rank <port> <cuda_visible_devices> <dp> <rpc_port> <vllm_extra_json|""> <nixl_side_channel_port|""> <log_file>
|
||||
launch_inference_rank() {
|
||||
local port="$1" gpus="$2" dp="$3" rpc="$4" extra="$5" nixl="$6" log="$7"
|
||||
# Per-rank dir for the mooncake-store lookup ipc socket. It must be unique per process:
|
||||
# external-LB runs one engine per process, all with data_parallel_rank_local 0, so the
|
||||
# lookup socket name collides on bind if the dir is shared node-wide. $port is unique per
|
||||
# rank on the node. Node-local /tmp also avoids inheriting an absent submit-node TMPDIR.
|
||||
local rpcbase="/tmp/vllm-rpc-$USER-$SLURM_JOB_ID-$port"
|
||||
mkdir -p "$rpcbase"
|
||||
local -a cmd=(uv run inference @ "$CONFIG_PATH"
|
||||
--server.host 0.0.0.0 --server.port "$port"
|
||||
--parallel.dp "$dp" --data-parallel-size-local 1 --api-server-count 1)
|
||||
[ -n "$rpc" ] && cmd+=(--data-parallel-rpc-port "$rpc")
|
||||
[ -n "$extra" ] && cmd+=(--vllm-extra "$extra")
|
||||
if [ -n "$nixl" ]; then
|
||||
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
CUDA_VISIBLE_DEVICES="$gpus" VLLM_NIXL_SIDE_CHANNEL_PORT="$nixl" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
else
|
||||
CUDA_VISIBLE_DEVICES="$gpus" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
CUDA_VISIBLE_DEVICES="$gpus" VLLM_RPC_BASE_PATH="$rpcbase" "${cmd[@]}" 2>&1 | tee -a "$log" &
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -1,12 +1,63 @@
|
||||
{# Shared router launch helper, included once per template and called by the
|
||||
replica-head rank. vllm-router today; an llm-d (EPP+Envoy) branch can slot in
|
||||
here so the call sites stay router-agnostic. #}
|
||||
# launch_router <mode:pd|regular> <worker_args> <port> <policy> <log_file> [replica_idx]
|
||||
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]
|
||||
launch_router() {
|
||||
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-}"
|
||||
local mode="$1" worker_args="$2" port="$3" policy="$4" log="$5" replica="${6:-0}" node_base="${7:-0}" node_count="${8:-0}"
|
||||
{%- if router.type == "llm-d" %}
|
||||
echo "Starting llm-d router (EPP+Envoy) on $LOCAL_IP:$port for replica $replica" | tee "$log"
|
||||
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
|
||||
local LLMD_DIR="$OUTPUT_DIR/logs/inference/llmd_${replica}"
|
||||
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_dp = dp_per_node %}
|
||||
{%- set ep_prefill_port = prefill_port %}
|
||||
{%- set ep_sidecar_port = router.decode_sidecar_port %}
|
||||
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
|
||||
{% include 'llmd/epp_pd.yaml.j2' %}
|
||||
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
|
||||
{%- else %}
|
||||
{%- set ep_disaggregated = false %}
|
||||
{%- set ep_num_nodes = infer_nodes_per_replica %}
|
||||
{%- set ep_dp = dp_per_node %}
|
||||
{%- set ep_backend_port = backend_port %}
|
||||
cat > "$LLMD_DIR/epp.yaml" <<LLMD_EOF
|
||||
{% include 'llmd/epp_estimate.yaml.j2' %}
|
||||
LLMD_EOF
|
||||
cat > "$LLMD_DIR/endpoints.yaml" <<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
|
||||
{%- 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.
|
||||
epp --pool-name prime-rl --pool-namespace slurm \
|
||||
--config-file "$LLMD_DIR/epp.yaml" \
|
||||
--grpc-port 9002 --grpc-health-port 9013 --metrics-port 9090 \
|
||||
--secure-serving=false --metrics-endpoint-auth=false --tracing=false \
|
||||
>> "$log" 2>&1 &
|
||||
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"
|
||||
local -a cmd=(vllm-router --policy "$policy" --host 0.0.0.0 --port "$port"
|
||||
--request-id-headers x-session-id
|
||||
--worker-startup-timeout-secs 4200 --log-level debug)
|
||||
if [ "$mode" = pd ]; then
|
||||
cmd+=(--vllm-pd-disaggregation $worker_args)
|
||||
@@ -14,4 +65,5 @@ launch_router() {
|
||||
cmd+=(--worker-urls $worker_args)
|
||||
fi
|
||||
"${cmd[@]}" >> "$log" 2>&1 &
|
||||
{%- endif %}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
SLURM templates inside the per-node `bash -c` body, so NO single quotes / apostrophes.
|
||||
Requires shell vars: LOCAL_IP, INFER_NODE_RANK, OUTPUT_DIR (and SLURM env).
|
||||
Requires jinja vars: kv_offload_cpu_bytes, kv_offload_disk_path, kv_offload_device_name.
|
||||
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process on this node. -#}
|
||||
Exports PYTHONHASHSEED + MOONCAKE_CONFIG_PATH for the vLLM process. (VLLM_RPC_BASE_PATH,
|
||||
used by the mooncake-store lookup ipc socket, is set per-rank in _launch_rank.sh.j2.) -#}
|
||||
# ---- Mooncake distributed store (shared pool across inference nodes) ----
|
||||
MC_DIR="$OUTPUT_DIR/mooncake/node_${INFER_NODE_RANK}"
|
||||
mkdir -p "$MC_DIR"
|
||||
@@ -23,9 +24,11 @@
|
||||
{%- endif %}
|
||||
if [ "$SLURMD_NODENAME" = "$MC_HEAD" ]; then
|
||||
{%- if kv_offload_disk_path %}
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 -enable_offload=true -root_fs_dir={{ kv_offload_disk_path }} > "$MC_DIR/master.log" 2>&1 &
|
||||
{%- else %}
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 > "$MC_DIR/master.log" 2>&1 &
|
||||
# default_kv_lease_ttl raised from 5s: KV blocks were expiring before the decode side
|
||||
# reused them ("invalid KV blocks ... may have expired"), the real non-NIC config issue.
|
||||
mooncake_master -rpc_port=50051 -enable_http_metadata_server -http_metadata_server_host=0.0.0.0 -http_metadata_server_port=8080 -default_kv_lease_ttl=3600000 > "$MC_DIR/master.log" 2>&1 &
|
||||
{%- endif %}
|
||||
fi
|
||||
# Every node waits for the shared master + metadata, then contributes its segment.
|
||||
|
||||
@@ -28,7 +28,7 @@ set -e
|
||||
# Configs
|
||||
export NUM_NODES={{ num_nodes }}
|
||||
export GPUS_PER_NODE={{ gpus_per_node }}
|
||||
{% if disaggregated -%}
|
||||
{% if is_disaggregated -%}
|
||||
export NUM_PREFILL_NODES={{ num_prefill_nodes }}
|
||||
export NUM_DECODE_NODES={{ num_decode_nodes }}
|
||||
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
|
||||
@@ -38,10 +38,13 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
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 %}
|
||||
@@ -70,7 +73,7 @@ uv sync --all-extras
|
||||
# Print inference URLs
|
||||
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
|
||||
export HOSTNAMES_STR="${HOSTNAMES[*]}"
|
||||
{% if disaggregated -%}
|
||||
{% if is_disaggregated -%}
|
||||
# Build per-replica router URLs
|
||||
INFER_URLS=""
|
||||
ALL_ROUTER_ARGS=""
|
||||
@@ -132,6 +135,10 @@ srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
|
||||
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
|
||||
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
|
||||
pkill -9 -f "[p]d-sidecar" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
@@ -144,7 +151,7 @@ srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -x mooncake_client 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
@@ -179,7 +186,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
{% include "_mooncake_store.sh.j2" %}
|
||||
{%- endif %}
|
||||
|
||||
{% if disaggregated -%}
|
||||
{% if is_disaggregated -%}
|
||||
# NVSHMEM libs for DeepEP — ensure the rpath target exists on all nodes
|
||||
if [ ! -d /tmp/deepep_build/nvshmem/lib ] && [ -d "$OUTPUT_DIR/nvshmem/lib" ]; then
|
||||
mkdir -p /tmp/deepep_build/nvshmem
|
||||
@@ -247,7 +254,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
{% for key, value in prefill_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
|
||||
else
|
||||
# ── Decode node ──
|
||||
export UCX_NET_DEVICES=mlx5_0:1
|
||||
@@ -262,7 +269,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
{% for key, value in decode_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
|
||||
fi
|
||||
|
||||
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" \
|
||||
@@ -271,8 +278,28 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
# 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"
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
|
||||
fi
|
||||
{%- if router.type == "llm-d" %}
|
||||
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
|
||||
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
|
||||
# Every decode node fronts its own local ranks, so launch on each (not just the
|
||||
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
|
||||
if [ "$ROLE" = "decode" ]; then
|
||||
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
|
||||
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
|
||||
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
|
||||
pd-sidecar \
|
||||
--port $DECODE_SIDECAR_PORT \
|
||||
--vllm-port $DECODE_PORT \
|
||||
--kv-connector nixlv2 \
|
||||
--secure-proxy=false \
|
||||
--enable-ssrf-protection=false \
|
||||
--inference-pool prime-rl \
|
||||
--data-parallel-size {{ dp_per_node }} \
|
||||
>> $SIDECAR_LOG 2>&1 &
|
||||
fi
|
||||
{%- endif %}
|
||||
|
||||
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
|
||||
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
|
||||
@@ -296,7 +323,7 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
|
||||
# Start the 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"
|
||||
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log" 0 0 "$NUM_NODES"
|
||||
fi
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
{# llm-d file-discovery endpoints: one entry per DP rank. Rendered (via include)
|
||||
into the sbatch; the per-node address is the __LLMD_ADDR_<node>__ placeholder,
|
||||
filled with each SLURM host's IPv4 inline in the sbatch (file-discovery rejects
|
||||
hostnames). Node ordering matches the sbatch's host loop: prefill then decode.
|
||||
The including sbatch sets ep_* via {% set %}. #}
|
||||
endpoints:
|
||||
{%- if ep_disaggregated %}
|
||||
{%- for node in range(ep_num_prefill) %}
|
||||
{%- for rank in range(ep_dp) %}
|
||||
- name: prefill-{{ node }}-rank-{{ rank }}
|
||||
address: __LLMD_ADDR_{{ node }}__
|
||||
port: "{{ ep_prefill_port + rank }}"
|
||||
namespace: default
|
||||
labels:
|
||||
llm-d.ai/pool: prime-rl
|
||||
llm-d.ai/role: prefill
|
||||
{%- endfor %}
|
||||
{%- endfor %}
|
||||
{%- for node in range(ep_num_decode) %}
|
||||
{%- for rank in range(ep_dp) %}
|
||||
- name: decode-{{ node }}-rank-{{ rank }}
|
||||
address: __LLMD_ADDR_{{ ep_num_prefill + node }}__
|
||||
port: "{{ ep_sidecar_port + rank }}"
|
||||
namespace: default
|
||||
labels:
|
||||
llm-d.ai/pool: prime-rl
|
||||
llm-d.ai/role: decode
|
||||
{%- endfor %}
|
||||
{%- endfor %}
|
||||
{%- else %}
|
||||
{%- for node in range(ep_num_nodes) %}
|
||||
{%- for rank in range(ep_dp) %}
|
||||
- name: backend-{{ node }}-rank-{{ rank }}
|
||||
address: __LLMD_ADDR_{{ node }}__
|
||||
port: "{{ ep_backend_port + rank }}"
|
||||
namespace: default
|
||||
labels:
|
||||
llm-d.ai/pool: prime-rl
|
||||
{%- endfor %}
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
@@ -0,0 +1,97 @@
|
||||
{# Envoy data plane: EPP picks the backend (ext_proc) and sets
|
||||
x-gateway-destination-endpoint; the ORIGINAL_DST cluster routes there. Both
|
||||
/v1/ (MITO) and /inference/v1/ (TITO) go through the picker. EPP gRPC is on
|
||||
loopback 9002; the gateway listens on the configured port. #}
|
||||
admin:
|
||||
address: { socket_address: { address: 127.0.0.1, port_value: 9901 } }
|
||||
static_resources:
|
||||
listeners:
|
||||
- name: prime_rl
|
||||
address: { socket_address: { address: 0.0.0.0, port_value: {{ router.port }} } }
|
||||
filter_chains:
|
||||
- filters:
|
||||
- name: envoy.filters.network.http_connection_manager
|
||||
typed_config:
|
||||
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
|
||||
stat_prefix: prime_rl
|
||||
codec_type: AUTO
|
||||
stream_idle_timeout: 0s
|
||||
request_timeout: 0s
|
||||
route_config:
|
||||
virtual_hosts:
|
||||
- name: prime_rl
|
||||
domains: ["*"]
|
||||
routes:
|
||||
- match: { prefix: "/v1/" }
|
||||
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
|
||||
- match: { prefix: "/inference/v1/" }
|
||||
route: { cluster: backend_cluster, timeout: 0s, idle_timeout: 86400s }
|
||||
http_filters:
|
||||
- name: envoy.filters.http.ext_proc
|
||||
typed_config:
|
||||
"@type": type.googleapis.com/envoy.extensions.filters.http.ext_proc.v3.ExternalProcessor
|
||||
grpc_service:
|
||||
envoy_grpc: { cluster_name: epp_cluster }
|
||||
timeout: 10s
|
||||
processing_mode:
|
||||
request_header_mode: SEND
|
||||
response_header_mode: SEND
|
||||
request_body_mode: FULL_DUPLEX_STREAMED
|
||||
response_body_mode: FULL_DUPLEX_STREAMED
|
||||
request_trailer_mode: SEND
|
||||
response_trailer_mode: SEND
|
||||
message_timeout: 1000s
|
||||
- name: envoy.filters.http.router
|
||||
typed_config:
|
||||
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
|
||||
suppress_envoy_headers: true
|
||||
clusters:
|
||||
- name: backend_cluster
|
||||
type: ORIGINAL_DST
|
||||
lb_policy: CLUSTER_PROVIDED
|
||||
original_dst_lb_config:
|
||||
use_http_header: true
|
||||
http_header_name: x-gateway-destination-endpoint
|
||||
connect_timeout: 5s
|
||||
# Default circuit breakers (~1024) overflow at high inflight concurrency (>=1536),
|
||||
# causing "reset reason: overflow" 500s. Raise far above the max concurrent rollouts.
|
||||
circuit_breakers:
|
||||
thresholds:
|
||||
- priority: DEFAULT
|
||||
max_connections: 100000
|
||||
max_pending_requests: 100000
|
||||
max_requests: 100000
|
||||
max_retries: 1000
|
||||
- priority: HIGH
|
||||
max_connections: 100000
|
||||
max_pending_requests: 100000
|
||||
max_requests: 100000
|
||||
max_retries: 1000
|
||||
- name: epp_cluster
|
||||
type: STRICT_DNS
|
||||
typed_extension_protocol_options:
|
||||
envoy.extensions.upstreams.http.v3.HttpProtocolOptions:
|
||||
"@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions
|
||||
explicit_http_config:
|
||||
http2_protocol_options: {}
|
||||
load_assignment:
|
||||
cluster_name: epp_cluster
|
||||
endpoints:
|
||||
- lb_endpoints:
|
||||
- endpoint:
|
||||
address: { socket_address: { address: 127.0.0.1, port_value: 9002 } }
|
||||
connect_timeout: 5s
|
||||
# ext_proc (EPP) connection pool overflows at high concurrency without this — the
|
||||
# gRPC ext_proc calls are 1:1 with inflight requests, so cap well above max rollouts.
|
||||
circuit_breakers:
|
||||
thresholds:
|
||||
- priority: DEFAULT
|
||||
max_connections: 100000
|
||||
max_pending_requests: 100000
|
||||
max_requests: 100000
|
||||
max_retries: 1000
|
||||
- priority: HIGH
|
||||
max_connections: 100000
|
||||
max_pending_requests: 100000
|
||||
max_requests: 100000
|
||||
max_retries: 1000
|
||||
@@ -0,0 +1,34 @@
|
||||
{# llm-d EPP config: single-pool (non-P/D) routing with approximate prefix-cache
|
||||
scoring. The vllmhttp parser embeds the OpenAI parser and also handles
|
||||
/inference/v1/generate (token_ids), so MITO + TITO both get prefix-cache
|
||||
scoring. Included into the sbatch as a heredoc; $LLMD_DIR is the per-replica
|
||||
config dir, expanded at launch time. #}
|
||||
apiVersion: inference.networking.x-k8s.io/v1alpha1
|
||||
kind: EndpointPickerConfig
|
||||
plugins:
|
||||
- name: file-disc
|
||||
type: file-discovery
|
||||
parameters:
|
||||
path: $LLMD_DIR/endpoints.yaml
|
||||
watchFile: true
|
||||
- name: vllmhttp-parser
|
||||
type: vllmhttp-parser
|
||||
{%- for scorer in router.scorers %}
|
||||
- type: {{ scorer }}
|
||||
{%- endfor %}
|
||||
- type: max-score-picker
|
||||
- type: single-profile-handler
|
||||
schedulingProfiles:
|
||||
- name: default
|
||||
plugins:
|
||||
{%- for scorer, weight in router.scorers.items() %}
|
||||
- pluginRef: {{ scorer }}
|
||||
weight: {{ weight }}
|
||||
{%- endfor %}
|
||||
- pluginRef: max-score-picker
|
||||
requestHandler:
|
||||
parser:
|
||||
pluginRef: vllmhttp-parser
|
||||
dataLayer:
|
||||
discovery:
|
||||
pluginRef: file-disc
|
||||
@@ -0,0 +1,56 @@
|
||||
{# llm-d EPP config: prefill/decode disaggregation. disagg-profile-handler runs
|
||||
the prefill profile when prefix-based-pd-decider sees >= nonCachedTokens
|
||||
non-cached prompt tokens, else decode-only. Mirrors the upstream llm-d PD
|
||||
guide: the prefill profile uses prefill_scorers (prefix + queue/kv) and the
|
||||
decode profile uses scorers (prefix + active-request); prefill-filter /
|
||||
decode-filter select endpoints by llm-d.ai/role label. Included into the
|
||||
sbatch as a heredoc; $LLMD_DIR is the per-replica config dir, expanded at
|
||||
launch time. #}
|
||||
apiVersion: inference.networking.x-k8s.io/v1alpha1
|
||||
kind: EndpointPickerConfig
|
||||
plugins:
|
||||
- name: file-disc
|
||||
type: file-discovery
|
||||
parameters:
|
||||
path: $LLMD_DIR/endpoints.yaml
|
||||
watchFile: true
|
||||
- name: vllmhttp-parser
|
||||
type: vllmhttp-parser
|
||||
- name: pd-decider
|
||||
type: prefix-based-pd-decider
|
||||
parameters:
|
||||
nonCachedTokens: {{ router.non_cached_tokens }}
|
||||
- name: profile-handler
|
||||
type: disagg-profile-handler
|
||||
parameters:
|
||||
deciders:
|
||||
prefill: pd-decider
|
||||
- type: prefill-filter
|
||||
- type: decode-filter
|
||||
{%- for scorer in ((router.prefill_scorers.keys() | list) + (router.decode_scorers.keys() | list)) | unique %}
|
||||
- type: {{ scorer }}
|
||||
{%- endfor %}
|
||||
- type: max-score-picker
|
||||
schedulingProfiles:
|
||||
- name: prefill
|
||||
plugins:
|
||||
- pluginRef: prefill-filter
|
||||
{%- for scorer, weight in router.prefill_scorers.items() %}
|
||||
- pluginRef: {{ scorer }}
|
||||
weight: {{ weight }}
|
||||
{%- endfor %}
|
||||
- pluginRef: max-score-picker
|
||||
- name: decode
|
||||
plugins:
|
||||
- pluginRef: decode-filter
|
||||
{%- for scorer, weight in router.decode_scorers.items() %}
|
||||
- pluginRef: {{ scorer }}
|
||||
weight: {{ weight }}
|
||||
{%- endfor %}
|
||||
- pluginRef: max-score-picker
|
||||
requestHandler:
|
||||
parser:
|
||||
pluginRef: vllmhttp-parser
|
||||
dataLayer:
|
||||
discovery:
|
||||
pluginRef: file-disc
|
||||
@@ -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 }}
|
||||
@@ -45,6 +45,9 @@ export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
|
||||
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
|
||||
export PREFILL_PORT={{ prefill_port }}
|
||||
export DECODE_PORT={{ decode_port }}
|
||||
{%- if router.type == "llm-d" %}
|
||||
export DECODE_SIDECAR_PORT={{ router.decode_sidecar_port }}
|
||||
{%- endif %}
|
||||
{%- else -%}
|
||||
export BACKEND_PORT={{ backend_port }}
|
||||
export INFERENCE_ENABLE_EXPERT_PARALLEL={{ "1" if inference_enable_expert_parallel else "0" }}
|
||||
@@ -166,6 +169,10 @@ srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
|
||||
pkill -9 -f "[t]orchrun" 2>/dev/null
|
||||
pkill -9 -f "[v]llm-router" 2>/dev/null
|
||||
# llm-d router procs (EPP + Envoy + decode pd-sidecar) left over from a prior run.
|
||||
pkill -9 -f "[e]pp.*pool-name" 2>/dev/null
|
||||
pkill -9 -f "[e]nvoy.*envoy.yaml" 2>/dev/null
|
||||
pkill -9 -f "[p]d-sidecar" 2>/dev/null
|
||||
pkill -9 -f "[v]llm" 2>/dev/null
|
||||
pkill -9 -f "[p]rime_rl" 2>/dev/null
|
||||
# Also match prctl-set process names (kernel comm) like "vllm::router"
|
||||
@@ -178,7 +185,7 @@ srun bash -s <<'CLEANUP_SH'
|
||||
pkill -9 -x mooncake_client 2>/dev/null
|
||||
sleep 2
|
||||
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* /tmp/torchelastic_* 2>/dev/null
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_" | grep -v grep | wc -l)
|
||||
procs=$(ps -eo comm,args | grep -E "python|torchrun|vllm|vllm::|mooncake_|[e]pp |envoy|pd-sidecar" | grep -v grep | wc -l)
|
||||
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
|
||||
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
|
||||
CLEANUP_SH
|
||||
@@ -284,7 +291,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
{% for key, value in prefill_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\""
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_high_throughput\"{{ prefill_vllm_extra_json }}"
|
||||
else
|
||||
export UCX_NET_DEVICES=mlx5_0:1
|
||||
ROLE="decode"
|
||||
@@ -298,7 +305,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
{% for key, value in decode_env_overrides.items() %}
|
||||
export {{ key }}="{{ value }}"
|
||||
{% endfor %}
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG"
|
||||
ROLE_EXTRA="\"all2all_backend\": \"deepep_low_latency\", \"compilation_config\": $DECODE_COMPILE_CFG{{ decode_vllm_extra_json }}"
|
||||
fi
|
||||
|
||||
echo "ROLE=$ROLE REPLICA=$REPLICA_IDX SUB_REPLICA=$SUB_REPLICA ROLE_RANK=$ROLE_RANK DP=$DP PORT=$PORT" \
|
||||
@@ -307,8 +314,28 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
# 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" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
|
||||
launch_router pd "$REPLICA_ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX" "$REPLICA_BASE"
|
||||
fi
|
||||
{%- if router.type == "llm-d" %}
|
||||
# pd-sidecar on each decode node: EPP routes decode -> sidecar (DECODE_SIDECAR_PORT
|
||||
# + rank) -> vLLM decode (DECODE_PORT + rank) after orchestrating remote prefill.
|
||||
# Every decode node fronts its own local ranks, so launch on each (not just the
|
||||
# replica head), or decode nodes beyond the head get advertised but unserved endpoints.
|
||||
if [ "$ROLE" = "decode" ]; then
|
||||
SIDECAR_LOG="$OUTPUT_DIR/logs/inference/sidecar_${INFER_NODE_RANK}.log"
|
||||
echo "Starting pd-sidecar on $LOCAL_IP:$DECODE_SIDECAR_PORT(+rank) -> vLLM $DECODE_PORT(+rank)" | tee $SIDECAR_LOG
|
||||
export PATH="$PROJECT_DIR/third_party/llmd/bin:$PATH"
|
||||
pd-sidecar \
|
||||
--port $DECODE_SIDECAR_PORT \
|
||||
--vllm-port $DECODE_PORT \
|
||||
--kv-connector nixlv2 \
|
||||
--secure-proxy=false \
|
||||
--enable-ssrf-protection=false \
|
||||
--inference-pool prime-rl \
|
||||
--data-parallel-size $INFERENCE_DP_LOCAL \
|
||||
>> $SIDECAR_LOG 2>&1 &
|
||||
fi
|
||||
{%- endif %}
|
||||
|
||||
# External-LB: one vLLM API server per local DP rank (PORT + k), each pinned to its TP
|
||||
# slice of GPUs with a unique NIXL side-channel port. Each role is its own external-LB DP
|
||||
@@ -325,7 +352,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
|
||||
# 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" consistent_hash "$OUTPUT_DIR/logs/inference/router_${REPLICA_IDX}.log" "$REPLICA_IDX"
|
||||
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"
|
||||
fi
|
||||
|
||||
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + d),
|
||||
|
||||
@@ -2,8 +2,10 @@ import copy
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from prime_rl.trainer.utils import balanced_partition
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
|
||||
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
ROUTED_EXPERTS_DTYPE_ITEMSIZE = {
|
||||
"uint8": 1,
|
||||
@@ -41,26 +43,77 @@ def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None:
|
||||
routed_experts.shape[0] += padding_size
|
||||
|
||||
|
||||
def _slice_encoded(tensor: EncodedTensor, n_rows: int) -> EncodedTensor:
|
||||
"""First `n_rows` rows of a dim-0-stacked encoded tensor (e.g. pixel_values, image_grid_thw)."""
|
||||
row = int(np.prod(tensor.shape[1:])) if len(tensor.shape) > 1 else 1
|
||||
itemsize = np.dtype(tensor.dtype).itemsize
|
||||
return EncodedTensor(
|
||||
dtype=tensor.dtype,
|
||||
shape=[n_rows, *tensor.shape[1:]],
|
||||
data=tensor.data[: n_rows * row * itemsize],
|
||||
)
|
||||
|
||||
|
||||
def _truncate_mm(
|
||||
mm_token_type_ids: list[int], mm_kwargs: dict[str, EncodedTensor], seq_len: int
|
||||
) -> tuple[int, dict[str, EncodedTensor] | None]:
|
||||
"""Truncating a sample must not split an image's placeholder block, else the surviving image
|
||||
token count no longer matches the image embeddings in `mm_kwargs`. Returns the cut point
|
||||
(<= seq_len, never inside an image block) and `mm_kwargs` sliced to the images whose
|
||||
placeholders fully survive (None if no image survives)."""
|
||||
grid = np.frombuffer(bytearray(mm_kwargs["image_grid_thw"].data), dtype=mm_kwargs["image_grid_thw"].dtype).reshape(
|
||||
mm_kwargs["image_grid_thw"].shape
|
||||
)
|
||||
patches_per_image = [int(g.prod()) for g in grid]
|
||||
total_patches = mm_kwargs["pixel_values"].shape[0]
|
||||
total_tokens = sum(1 for t in mm_token_type_ids if t)
|
||||
ppt = total_patches // total_tokens if total_tokens else 1 # patches per token (merge^2)
|
||||
tokens_per_image = [p // ppt for p in patches_per_image]
|
||||
|
||||
surviving = sum(1 for t in mm_token_type_ids[:seq_len] if t)
|
||||
kept = acc = 0
|
||||
for n in tokens_per_image:
|
||||
if acc + n > surviving:
|
||||
break
|
||||
acc += n
|
||||
kept += 1
|
||||
if acc == surviving:
|
||||
cut = seq_len # surviving image tokens are exactly `kept` whole images
|
||||
else:
|
||||
# `surviving` lands inside image `kept`; cut to its first placeholder, dropping it.
|
||||
seen, cut = 0, seq_len
|
||||
for i, t in enumerate(mm_token_type_ids):
|
||||
if t:
|
||||
seen += 1
|
||||
if seen == acc + 1:
|
||||
cut = i
|
||||
break
|
||||
if not kept:
|
||||
return cut, None
|
||||
kept_patches = sum(patches_per_image[:kept])
|
||||
sliced = {k: _slice_encoded(v, kept if k == "image_grid_thw" else kept_patches) for k, v in mm_kwargs.items()}
|
||||
return cut, sliced
|
||||
|
||||
|
||||
def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch:
|
||||
"""
|
||||
Prepare a problem for sequence packing training.
|
||||
Tokenize and prepare tensors.
|
||||
"""
|
||||
input_ids = training_example.prompt_ids + training_example.completion_ids
|
||||
loss_mask = training_example.prompt_mask + training_example.completion_mask
|
||||
inference_logprobs = [0.0] * len(training_example.prompt_ids) + training_example.completion_logprobs
|
||||
input_ids = training_example.token_ids
|
||||
loss_mask = training_example.mask
|
||||
inference_logprobs = training_example.logprobs
|
||||
advantages = [training_example.advantage] * len(input_ids)
|
||||
reward = training_example.reward if training_example.reward is not None else float("nan")
|
||||
rewards = [reward] * len(input_ids)
|
||||
position_ids = list(range(len(input_ids)))
|
||||
mm_token_type_ids = training_example.mm_token_type_ids
|
||||
mm_kwargs = training_example.mm_kwargs
|
||||
assert training_example.env_name != "all", "env_name='all' is reserved for aggregate metric keys"
|
||||
env_names = [training_example.env_name] * len(input_ids)
|
||||
|
||||
# Per-token temperatures: prompt tokens use first completion temp (masked out anyway)
|
||||
# Default to 1.0 if completion is empty (e.g., model generated only tool calls with no text)
|
||||
prompt_temp = training_example.completion_temperatures[0] if training_example.completion_temperatures else 1.0
|
||||
temperatures = [prompt_temp] * len(training_example.prompt_ids) + training_example.completion_temperatures
|
||||
# Per-token sampling temperatures (context tokens are masked out, so theirs are don't-care).
|
||||
temperatures = training_example.temperatures
|
||||
|
||||
# Teacher logprobs already cover the full sequence (prompt + completion),
|
||||
# computed via prefill in the orchestrator when a teacher model is configured
|
||||
@@ -70,20 +123,25 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
)
|
||||
|
||||
if len(input_ids) > seq_len:
|
||||
input_ids = input_ids[:seq_len]
|
||||
loss_mask = loss_mask[:seq_len]
|
||||
inference_logprobs = inference_logprobs[:seq_len]
|
||||
position_ids = position_ids[:seq_len]
|
||||
advantages = advantages[:seq_len]
|
||||
rewards = rewards[:seq_len]
|
||||
temperatures = temperatures[:seq_len]
|
||||
# Multimodal: never split an image's placeholder block — cut to a whole-image boundary
|
||||
# and slice mm_kwargs to match, so image-token count == image-embedding count.
|
||||
cut = seq_len
|
||||
if mm_token_type_ids is not None and mm_kwargs is not None:
|
||||
cut, mm_kwargs = _truncate_mm(mm_token_type_ids, mm_kwargs, seq_len)
|
||||
input_ids = input_ids[:cut]
|
||||
loss_mask = loss_mask[:cut]
|
||||
inference_logprobs = inference_logprobs[:cut]
|
||||
position_ids = position_ids[:cut]
|
||||
advantages = advantages[:cut]
|
||||
rewards = rewards[:cut]
|
||||
temperatures = temperatures[:cut]
|
||||
if teacher_logprobs is not None:
|
||||
teacher_logprobs = teacher_logprobs[:seq_len]
|
||||
teacher_logprobs = teacher_logprobs[:cut]
|
||||
if routed_experts is not None:
|
||||
routed_experts = _slice_routed_experts(routed_experts, seq_len)
|
||||
routed_experts = _slice_routed_experts(routed_experts, cut)
|
||||
if mm_token_type_ids is not None:
|
||||
mm_token_type_ids = mm_token_type_ids[:seq_len]
|
||||
env_names = env_names[:seq_len]
|
||||
mm_token_type_ids = mm_token_type_ids[:cut]
|
||||
env_names = env_names[:cut]
|
||||
|
||||
assert (
|
||||
len(input_ids)
|
||||
@@ -124,7 +182,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=training_example.mm_kwargs,
|
||||
mm_kwargs=mm_kwargs,
|
||||
training_mode=training_example.training_mode,
|
||||
)
|
||||
|
||||
|
||||
@@ -510,6 +510,18 @@ def get_model(
|
||||
model_config.use_index_cache = True
|
||||
model_config.index_topk_freq = config.index_cache.topk_freq
|
||||
model_config.index_topk_pattern = config.index_cache.topk_pattern
|
||||
# Explicit override supersedes the model's native IndexShare schedule.
|
||||
model_config.indexer_types = None
|
||||
else:
|
||||
# Auto-enable IndexShare from the model's own indexer schedule (e.g. GLM-5.2). The model
|
||||
# reads `indexer_types` directly: shared layers reuse cached indices and carry no indexer weights.
|
||||
indexer_types = getattr(model_config, "indexer_types", None)
|
||||
if indexer_types and any(t == "shared" for t in indexer_types):
|
||||
model_config.use_index_cache = True
|
||||
logger.info(
|
||||
f"Auto-enabled IndexShare from indexer_types schedule "
|
||||
f"({sum(t == 'full' for t in indexer_types)}/{len(indexer_types)} full layers)"
|
||||
)
|
||||
|
||||
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
|
||||
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
|
||||
|
||||
@@ -227,7 +227,11 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
|
||||
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
||||
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
|
||||
# .contiguous(): the per-layer slice is a strided view of [tokens, layers, topk]
|
||||
# (dim-1 stride = layers*topk); torch.compile's MoE kernel asserts a contiguous input.
|
||||
routed_experts_layer = (
|
||||
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
|
||||
)
|
||||
hidden_states = decoder_layer(
|
||||
hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
|
||||
@@ -11,6 +11,10 @@ def _index_cache_skip_topk(config, layer_idx: int) -> bool:
|
||||
if index_topk_pattern is not None:
|
||||
return layer_idx < len(index_topk_pattern) and index_topk_pattern[layer_idx] == "S"
|
||||
|
||||
indexer_types = getattr(config, "indexer_types", None)
|
||||
if indexer_types is not None:
|
||||
return layer_idx < len(indexer_types) and indexer_types[layer_idx] == "shared"
|
||||
|
||||
return layer_idx % getattr(config, "index_topk_freq", 1) != 0
|
||||
|
||||
|
||||
@@ -162,6 +166,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
use_index_cache=False,
|
||||
index_topk_freq=1,
|
||||
index_topk_pattern=None,
|
||||
indexer_types=None,
|
||||
scoring_func="sigmoid",
|
||||
topk_method="noaux_tc",
|
||||
use_grouped_mm=True,
|
||||
@@ -218,6 +223,7 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
self.use_index_cache = use_index_cache
|
||||
self.index_topk_freq = index_topk_freq
|
||||
self.index_topk_pattern = index_topk_pattern
|
||||
self.indexer_types = indexer_types
|
||||
self.scoring_func = scoring_func
|
||||
self.topk_method = topk_method
|
||||
self.use_grouped_mm = use_grouped_mm
|
||||
@@ -226,6 +232,10 @@ class GlmMoeDsaConfig(PretrainedConfig):
|
||||
if not self.use_grouped_mm:
|
||||
warnings.warn("not using grouped mm for moe is very slow, should only be used for debugging")
|
||||
|
||||
# head_dim is derived from qk_rope_head_dim (the RoPE slice). Some checkpoints (e.g. GLM-5.2)
|
||||
# set head_dim=qk_nope_head_dim in config.json; drop it so PretrainedConfig.__init__ can't
|
||||
# overwrite self.head_dim and break the rotary embedding dimension.
|
||||
kwargs.pop("head_dim", None)
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
|
||||
@@ -158,7 +158,8 @@ class GlmMoeDsaAttention(nn.Module):
|
||||
)
|
||||
|
||||
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, args.hidden_size, bias=args.attention_bias)
|
||||
self.indexer = Indexer(args)
|
||||
# IndexShare (GLM-5.2): layers that reuse cached indices carry no indexer weights.
|
||||
self.indexer = Indexer(args) if not args.skip_topk else None
|
||||
self.use_index_cache = args.use_index_cache
|
||||
self.skip_topk = args.skip_topk
|
||||
self.scaling = self.qk_head_dim ** (-0.5)
|
||||
|
||||
@@ -8,6 +8,7 @@ import torch.nn as nn
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.vlm import get_final_logit_softcapping
|
||||
|
||||
FUSED_CE_IGNORE_INDEX = -100
|
||||
|
||||
@@ -299,8 +300,8 @@ def inject_prime_lm_head(
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
# Check for Gemma-style softcapping - dispatch to specialized implementation
|
||||
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
|
||||
# Check for Gemma-style softcapping - dispatch to specialized implementation.
|
||||
final_logit_softcapping = get_final_logit_softcapping(model.config)
|
||||
if final_logit_softcapping:
|
||||
if fused_cross_entropy == "quack":
|
||||
raise ValueError(
|
||||
|
||||
@@ -160,27 +160,17 @@ class MultiPacker(BasePacker):
|
||||
|
||||
def _validate_sample(self, sample: TrainingSample) -> tuple[bool, str | None]:
|
||||
"""Validate a sample to ensure it won't crash the trainer."""
|
||||
sample_length = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
if len(sample.prompt_mask) != len(sample.prompt_ids):
|
||||
return (
|
||||
False,
|
||||
f"Run wrote a sample with prompt mask length != prompt ids length ({len(sample.prompt_mask)} != {len(sample.prompt_ids)})",
|
||||
)
|
||||
if len(sample.completion_mask) != len(sample.completion_ids):
|
||||
return (
|
||||
False,
|
||||
f"Run wrote a sample with completion mask length != completion ids length ({len(sample.completion_mask)} != {len(sample.completion_ids)})",
|
||||
)
|
||||
if len(sample.completion_logprobs) != len(sample.completion_ids):
|
||||
return (
|
||||
False,
|
||||
f"Run wrote a sample with completion logprobs length != completion ids length ({len(sample.completion_logprobs)} != {len(sample.completion_ids)})",
|
||||
)
|
||||
if len(sample.completion_temperatures) != len(sample.completion_ids):
|
||||
return (
|
||||
False,
|
||||
f"Run wrote a sample with completion temperatures length != completion ids length ({len(sample.completion_temperatures)} != {len(sample.completion_ids)})",
|
||||
)
|
||||
sample_length = len(sample.token_ids)
|
||||
for name, arr in (
|
||||
("mask", sample.mask),
|
||||
("logprobs", sample.logprobs),
|
||||
("temperatures", sample.temperatures),
|
||||
):
|
||||
if len(arr) != sample_length:
|
||||
return (
|
||||
False,
|
||||
f"Run wrote a sample with {name} length != token_ids length ({len(arr)} != {sample_length})",
|
||||
)
|
||||
if sample_length == 0:
|
||||
return False, "Run wrote a sample with no tokens"
|
||||
if sample_length > self.seq_len:
|
||||
@@ -228,7 +218,7 @@ class MultiPacker(BasePacker):
|
||||
for sample, step in buffer:
|
||||
if step > current_step:
|
||||
break
|
||||
tokens += len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
tokens += len(sample.token_ids)
|
||||
if threshold is not None and tokens >= threshold:
|
||||
return tokens
|
||||
return tokens
|
||||
@@ -265,10 +255,10 @@ class MultiPacker(BasePacker):
|
||||
if step > current_step:
|
||||
# Samples from different steps should be consumed later
|
||||
break
|
||||
tokens_collected += len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
tokens_collected += len(sample.token_ids)
|
||||
if tokens_collected > token_budget:
|
||||
if tokens_collected == (len(sample.prompt_ids) + len(sample.completion_ids)):
|
||||
tokens_collected -= len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
if tokens_collected == (len(sample.token_ids)):
|
||||
tokens_collected -= len(sample.token_ids)
|
||||
# This means we have a sample that has more tokens than max seqlen
|
||||
self.buffers[run_idx].popleft()
|
||||
continue
|
||||
@@ -322,7 +312,7 @@ class MultiPacker(BasePacker):
|
||||
assert steps_by_run[run_idx] == step, "Micro batches for a run must come from a single run step"
|
||||
samples_by_run[run_idx].append(sample)
|
||||
|
||||
num_tokens = len(sample.prompt_ids) + len(sample.completion_ids)
|
||||
num_tokens = len(sample.token_ids)
|
||||
if run_idx in per_run_stats:
|
||||
cur_samples, cur_tokens = per_run_stats[run_idx]
|
||||
per_run_stats[run_idx] = (cur_samples + 1, cur_tokens + num_tokens)
|
||||
|
||||
@@ -24,14 +24,17 @@ class RoutedExperts(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tru
|
||||
|
||||
# Orchestrator -> Packer
|
||||
class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
"""A single training example."""
|
||||
"""A single training example — one branch of a rollout as a flat token sequence.
|
||||
|
||||
prompt_ids: list[int]
|
||||
prompt_mask: list[bool]
|
||||
completion_ids: list[int]
|
||||
completion_mask: list[bool]
|
||||
completion_logprobs: list[float]
|
||||
completion_temperatures: list[float] # Per-token temperatures used during generation
|
||||
There is no prompt/completion split: an agentic, multi-turn branch interleaves context and
|
||||
model-sampled spans, so ``mask`` marks which tokens are trainable (model-sampled) and
|
||||
``logprobs`` / ``temperatures`` are aligned per token. All four arrays share the length of
|
||||
``token_ids``."""
|
||||
|
||||
token_ids: list[int]
|
||||
mask: list[bool]
|
||||
logprobs: list[float]
|
||||
temperatures: list[float]
|
||||
env_name: str
|
||||
teacher_logprobs: list[float] | None = None
|
||||
advantage: float | None = None
|
||||
@@ -74,9 +77,9 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
|
||||
advantages: list[float]
|
||||
inference_logprobs: list[float]
|
||||
position_ids: list[int]
|
||||
sequence_lengths: list[int]
|
||||
temperatures: list[float] # Per-token temperatures used during generation
|
||||
env_names: list[str]
|
||||
sequence_lengths: list[int]
|
||||
teacher_logprobs: list[float] | None = None
|
||||
lora_num_tokens: list[int] | None = None
|
||||
routed_experts: RoutedExperts | None = None
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import deque
|
||||
from time import perf_counter
|
||||
|
||||
import numpy as np
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
async def safe_cancel(task: asyncio.Task) -> None:
|
||||
@@ -13,3 +20,54 @@ async def safe_cancel(task: asyncio.Task) -> None:
|
||||
async def safe_cancel_all(tasks: list[asyncio.Task]) -> None:
|
||||
"""Safely cancels and awaits all asyncio.Tasks."""
|
||||
await asyncio.gather(*[safe_cancel(task) for task in tasks])
|
||||
|
||||
|
||||
class EventLoopLagMonitor:
|
||||
"""Monitors how busy the main event loop is by timing short sleeps.
|
||||
|
||||
Vendored from verifiers.utils.async_utils (the orchestrator now runs on
|
||||
v1 and no longer depends on v1 verifiers)."""
|
||||
|
||||
def __init__(self, measure_interval: float = 0.1, max_measurements: int = 1000):
|
||||
assert measure_interval > 0 and max_measurements > 0
|
||||
self.measure_interval = measure_interval
|
||||
self.max_measurements = max_measurements
|
||||
self.lags: deque[float] = deque(maxlen=max_measurements)
|
||||
|
||||
async def measure_lag(self) -> float:
|
||||
next_time = perf_counter() + self.measure_interval
|
||||
await asyncio.sleep(self.measure_interval)
|
||||
return perf_counter() - next_time
|
||||
|
||||
async def run(self) -> None:
|
||||
"""Loop measuring event-loop lag; run as a background task."""
|
||||
while True:
|
||||
self.lags.append(await self.measure_lag())
|
||||
|
||||
|
||||
class EventLoopLagStats(BaseModel):
|
||||
"""Snapshot of event-loop lag statistics."""
|
||||
|
||||
min: float = 0.0
|
||||
mean: float = 0.0
|
||||
median: float = 0.0
|
||||
p90: float = 0.0
|
||||
p99: float = 0.0
|
||||
max: float = 0.0
|
||||
n: int = 0
|
||||
|
||||
@classmethod
|
||||
def from_monitor(cls, monitor: EventLoopLagMonitor) -> EventLoopLagStats:
|
||||
n = len(monitor.lags)
|
||||
if n == 0:
|
||||
return cls(n=0)
|
||||
arr = np.array(monitor.lags)
|
||||
return cls(
|
||||
min=float(arr.min()),
|
||||
mean=float(arr.mean()),
|
||||
median=float(np.median(arr)),
|
||||
p90=float(np.percentile(arr, 90)),
|
||||
p99=float(np.percentile(arr, 99)),
|
||||
max=float(arr.max()),
|
||||
n=n,
|
||||
)
|
||||
|
||||
@@ -8,16 +8,17 @@ from pathlib import Path
|
||||
from typing import Protocol, runtime_checkable
|
||||
|
||||
import httpx
|
||||
import verifiers as vf
|
||||
import verifiers.v1 as vf
|
||||
from httpx import AsyncClient
|
||||
from openai import NotFoundError
|
||||
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
|
||||
|
||||
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. ``api_base_url``
|
||||
# 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]
|
||||
@@ -25,7 +26,7 @@ ClientIdentity = tuple[str, str | None]
|
||||
|
||||
def client_identity(client: vf.ClientConfig) -> ClientIdentity:
|
||||
"""Stable identity for load balancing across inference clients."""
|
||||
return (client.api_base_url, client.extra_headers.get("X-data-parallel-rank"))
|
||||
return (client.base_url, client.headers.get("X-data-parallel-rank"))
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
@@ -185,42 +186,31 @@ def setup_clients(
|
||||
renderer_model_name: str | None = None,
|
||||
pool_size: int | None = None,
|
||||
) -> list[vf.ClientConfig]:
|
||||
clients = []
|
||||
client_idx = 0
|
||||
# Only forward the renderer config when the client actually uses a
|
||||
# renderer — MITO/TITO clients ignore it.
|
||||
"""Build v1 client configs (one per base_url × DP rank). ``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``)."""
|
||||
is_renderer = client_type == "renderer"
|
||||
config_cls = TrainClientConfig if is_renderer else EvalClientConfig
|
||||
renderer_extra: dict = {}
|
||||
if client_type == "renderer":
|
||||
if is_renderer:
|
||||
renderer_extra = {
|
||||
"renderer_config": renderer_config,
|
||||
"renderer": renderer_config,
|
||||
"pool_size": pool_size or 1,
|
||||
"renderer_model_name": renderer_model_name,
|
||||
"renderer_pool_size": pool_size,
|
||||
}
|
||||
env_headers = {
|
||||
k: v for k, v in ((k, os.getenv(v)) for k, v in client_config.headers_from_env.items()) if v is not None
|
||||
}
|
||||
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(
|
||||
vf.ClientConfig(
|
||||
client_idx=client_idx,
|
||||
client_type=client_type,
|
||||
api_base_url=base_url,
|
||||
api_key_var=client_config.api_key_var,
|
||||
timeout=client_config.timeout,
|
||||
connect_timeout=client_config.connect_timeout,
|
||||
max_connections=8192,
|
||||
max_keepalive_connections=8192,
|
||||
max_retries=10,
|
||||
extra_headers=headers,
|
||||
extra_headers_from_state=client_config.extra_headers_from_state,
|
||||
**renderer_extra,
|
||||
)
|
||||
config_cls(base_url=base_url, api_key_var=client_config.api_key_var, headers=headers, **renderer_extra)
|
||||
)
|
||||
client_idx += 1
|
||||
return clients
|
||||
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
import verifiers as vf
|
||||
import verifiers.v1 as vf
|
||||
from httpx import AsyncClient
|
||||
from renderers import RendererConfig
|
||||
|
||||
@@ -191,8 +191,6 @@ class ElasticInferencePool:
|
||||
|
||||
self._eval_index = 0
|
||||
url_config = ClientConfig(
|
||||
timeout=self.client_config.timeout,
|
||||
connect_timeout=self.client_config.connect_timeout,
|
||||
base_url=urls,
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
@@ -251,7 +249,6 @@ class ElasticInferencePool:
|
||||
async def _create_admin_client(self, ip: str) -> AsyncClient:
|
||||
url = self._build_url(ip)
|
||||
config = ClientConfig(
|
||||
timeout=self.client_config.timeout,
|
||||
base_url=[f"{url}/v1"],
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import verifiers as vf
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
def sample_items_for_logging(items: list[Any], sample_ratio: float | None) -> list[Any]:
|
||||
@@ -39,11 +42,11 @@ class Monitor(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
|
||||
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -72,10 +75,10 @@ class NoOpMonitor(Monitor):
|
||||
else:
|
||||
self.history = [metrics]
|
||||
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
|
||||
pass
|
||||
|
||||
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
|
||||
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
|
||||
pass
|
||||
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
from typing import Any
|
||||
from __future__ import annotations
|
||||
|
||||
import verifiers as vf
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
class MultiMonitor(Monitor):
|
||||
"""Monitor that wraps multiple monitors and delegates calls to all of them."""
|
||||
@@ -26,14 +29,14 @@ class MultiMonitor(Monitor):
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to log metrics to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
monitor.log_samples(rollouts=rollouts, step=step)
|
||||
except Exception as e:
|
||||
self.logger.warning(f"Failed to log samples to {monitor.__class__.__name__}: {e}")
|
||||
|
||||
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
|
||||
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
|
||||
for monitor in self.monitors:
|
||||
try:
|
||||
monitor.log_eval_samples(rollouts=rollouts, env_name=env_name, step=step)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
@@ -7,12 +9,11 @@ import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from threading import Thread
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import httpx
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
import verifiers as vf
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
@@ -21,14 +22,8 @@ from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
|
||||
|
||||
|
||||
def _json(val: Any) -> str:
|
||||
"""JSON-serialize dicts/lists, pass strings through, default to empty string for None."""
|
||||
if isinstance(val, str):
|
||||
return val
|
||||
if val is None:
|
||||
return ""
|
||||
return json.dumps(val)
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
_SAMPLE_SCHEMA = pa.schema(
|
||||
@@ -286,7 +281,7 @@ class PrimeMonitor(Monitor):
|
||||
},
|
||||
)
|
||||
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
|
||||
"""Logs rollouts to Prime Intellect API using presigned URLs for direct R2 upload."""
|
||||
if not self.is_master:
|
||||
return
|
||||
@@ -329,35 +324,35 @@ class PrimeMonitor(Monitor):
|
||||
f"Initiated samples upload at step {step} to Prime Intellect API in {time.perf_counter() - start_time:.2f}s"
|
||||
)
|
||||
|
||||
def _rollouts_to_parquet_bytes(self, rollouts: list[vf.RolloutOutput], step: int) -> bytes | None:
|
||||
"""Convert rollouts directly to Parquet bytes for upload."""
|
||||
def _rollouts_to_parquet_bytes(self, rollouts: list[Rollout], step: int) -> bytes | None:
|
||||
"""Convert rollouts to Parquet bytes for upload. One row per rollout, built from the
|
||||
message graph: the conversation is the unit (no prompt/completion split — meaningless in
|
||||
a multi-turn branch), so `completion` carries the main (last) branch's full message list
|
||||
and `trajectory` carries one message list per branch (`trace.branches`)."""
|
||||
now = datetime.now(timezone.utc)
|
||||
rows = []
|
||||
|
||||
for sample_id, rollout in enumerate(rollouts):
|
||||
prompt = rollout.get("prompt")
|
||||
completion = rollout.get("completion")
|
||||
trajectory = rollout.get("trajectory") or []
|
||||
if prompt is None or completion is None or not trajectory:
|
||||
branches = rollout.branches
|
||||
if not branches:
|
||||
continue
|
||||
main_messages = [m.model_dump(mode="json") for m in branches[-1].messages]
|
||||
|
||||
example_id = rollout.get("example_id")
|
||||
task_idx = rollout.task.idx
|
||||
try:
|
||||
problem_id = int(example_id) if example_id is not None else sample_id
|
||||
problem_id = int(task_idx) if task_idx is not None else sample_id
|
||||
except (TypeError, ValueError):
|
||||
problem_id = sample_id
|
||||
|
||||
trajectory_data = [
|
||||
{
|
||||
"prompt": ts["prompt"],
|
||||
"completion": ts["completion"],
|
||||
"reward": ts.get("reward"),
|
||||
"advantage": ts.get("advantage"),
|
||||
"extras": ts.get("extras", {}),
|
||||
"num_input_tokens": len(ts["tokens"]["prompt_ids"]) if ts.get("tokens") else None,
|
||||
"num_output_tokens": len(ts["tokens"]["completion_ids"]) if ts.get("tokens") else None,
|
||||
"messages": [m.model_dump(mode="json") for m in branch.messages],
|
||||
"reward": rollout.reward,
|
||||
"advantage": rollout.advantage,
|
||||
"num_input_tokens": branch.prompt_len,
|
||||
"num_output_tokens": branch.completion_len,
|
||||
}
|
||||
for ts in trajectory
|
||||
for branch in branches
|
||||
]
|
||||
|
||||
rows.append(
|
||||
@@ -367,19 +362,19 @@ class PrimeMonitor(Monitor):
|
||||
"tag": "",
|
||||
"problem_id": problem_id,
|
||||
"sample_id": sample_id,
|
||||
"prompt": json.dumps(prompt),
|
||||
"completion": json.dumps(completion),
|
||||
"prompt": "",
|
||||
"completion": json.dumps(main_messages),
|
||||
"trajectory": json.dumps(trajectory_data),
|
||||
"answer": rollout.get("answer") or "",
|
||||
"env_name": rollout.get("env_name") or "",
|
||||
"task": rollout.get("task") or "",
|
||||
"info": _json(rollout.get("info")),
|
||||
"reward": rollout.get("reward"),
|
||||
"advantage": rollout.get("advantage"),
|
||||
"metrics": _json(rollout.get("metrics")),
|
||||
"timing": _json(rollout.get("timing")),
|
||||
"num_input_tokens": 0,
|
||||
"num_output_tokens": 0,
|
||||
"answer": "",
|
||||
"env_name": rollout.env_name,
|
||||
"task": rollout.task.model_dump_json(),
|
||||
"info": json.dumps(rollout.info),
|
||||
"reward": rollout.reward,
|
||||
"advantage": rollout.advantage,
|
||||
"metrics": json.dumps(rollout.metrics),
|
||||
"timing": rollout.timing.model_dump_json(),
|
||||
"num_input_tokens": branches[-1].prompt_len,
|
||||
"num_output_tokens": branches[-1].completion_len,
|
||||
"created_at": now,
|
||||
}
|
||||
)
|
||||
@@ -492,7 +487,7 @@ class PrimeMonitor(Monitor):
|
||||
await asyncio.sleep(delay)
|
||||
return False
|
||||
|
||||
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
|
||||
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
|
||||
pass
|
||||
|
||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||
|
||||
@@ -1,22 +1,42 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import verifiers as vf
|
||||
import wandb
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from wandb.errors import CommError
|
||||
from wandb.sdk.mailbox.mailbox_handle import ServerResponseError
|
||||
|
||||
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.chat_template import deserialize_tool_calls
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
def _loggable_task(task) -> str:
|
||||
"""A Table-safe JSON string of the task for sample logging. Image content parts are elided to
|
||||
a short placeholder — their base64 data bloats the table and breaks wandb Table's nested-type
|
||||
inference on the variable-length content list (a plain dict would otherwise crash on it)."""
|
||||
|
||||
def elide(obj):
|
||||
if isinstance(obj, dict):
|
||||
if obj.get("type") == "image_url":
|
||||
return {"type": "image_url", "image_url": "<image>"}
|
||||
return {k: elide(v) for k, v in obj.items()}
|
||||
if isinstance(obj, list):
|
||||
return [elide(v) for v in obj]
|
||||
return obj
|
||||
|
||||
return json.dumps(elide(task.model_dump(mode="json")))
|
||||
|
||||
|
||||
class WandbMonitor(Monitor):
|
||||
"""Logs to Weights and Biases."""
|
||||
@@ -113,13 +133,13 @@ class WandbMonitor(Monitor):
|
||||
if config is not None and isinstance(config, WandbWithExtrasConfig) and config.log_extras:
|
||||
if config.log_extras.samples:
|
||||
self.last_log_samples_step = -1
|
||||
self.samples_cols = ["step", "env_name", "task", "example_id", "messages", "input_ids", "reward"]
|
||||
self.samples_cols = ["step", "env_name", "task", "task_idx", "messages", "input_ids", "reward"]
|
||||
self.samples_table = wandb.Table(
|
||||
columns=self.samples_cols,
|
||||
log_mode="INCREMENTAL",
|
||||
)
|
||||
self.tokenizer = tokenizer
|
||||
self.eval_samples_cols = ["step", "env", "task", "example_id", "completion", "reward"]
|
||||
self.eval_samples_cols = ["step", "env", "task", "task_idx", "completion", "reward"]
|
||||
self.eval_samples_table = wandb.Table(
|
||||
columns=self.eval_samples_cols,
|
||||
log_mode="INCREMENTAL",
|
||||
@@ -143,7 +163,7 @@ class WandbMonitor(Monitor):
|
||||
return
|
||||
wandb.log({**metrics, "step": step})
|
||||
|
||||
def log_samples(self, rollouts: list[vf.RolloutOutput], step: int) -> None:
|
||||
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
|
||||
"""Logs rollouts to W&B table."""
|
||||
if not self.is_master:
|
||||
return
|
||||
@@ -172,32 +192,30 @@ class WandbMonitor(Monitor):
|
||||
start_time = time.perf_counter()
|
||||
|
||||
for rollout in rollouts:
|
||||
trajectory = rollout["trajectory"]
|
||||
if not trajectory:
|
||||
continue
|
||||
last_step = trajectory[-1]
|
||||
tokens = last_step["tokens"]
|
||||
full_ids = tokens["prompt_ids"] + tokens["completion_ids"]
|
||||
messages_text = self.tokenizer.decode(full_ids)
|
||||
sample = {
|
||||
"step": step,
|
||||
"env_name": rollout.get("env_name"),
|
||||
"task": rollout.get("task"),
|
||||
"example_id": rollout["example_id"],
|
||||
"messages": messages_text,
|
||||
"input_ids": str(full_ids),
|
||||
"reward": rollout["reward"],
|
||||
}
|
||||
assert list(sample.keys()) == self.samples_cols, (
|
||||
"Order of columns in the table must be the same as order of the keys here"
|
||||
)
|
||||
self.samples_table.add_data(*sample.values())
|
||||
trace = rollout
|
||||
for branch in trace.branches:
|
||||
token_ids = branch.token_ids
|
||||
if not token_ids:
|
||||
continue
|
||||
sample = {
|
||||
"step": step,
|
||||
"env_name": rollout.env_name,
|
||||
"task": _loggable_task(trace.task),
|
||||
"task_idx": trace.task.idx,
|
||||
"messages": self.tokenizer.decode(token_ids),
|
||||
"input_ids": str(token_ids),
|
||||
"reward": trace.reward,
|
||||
}
|
||||
assert list(sample.keys()) == self.samples_cols, (
|
||||
"Order of columns in the table must be the same as order of the keys here"
|
||||
)
|
||||
self.samples_table.add_data(*sample.values())
|
||||
|
||||
wandb.log({"samples": self.samples_table, "step": step})
|
||||
self.last_log_samples_step = step
|
||||
self.logger.debug(f"Logged samples at step {step} to W&B table in {time.perf_counter() - start_time:.2f}s")
|
||||
|
||||
def log_eval_samples(self, rollouts: list[vf.RolloutOutput], env_name: str, step: int) -> None:
|
||||
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
|
||||
"""Logs eval rollouts to a separate W&B table."""
|
||||
if not self.is_master:
|
||||
return
|
||||
@@ -210,23 +228,22 @@ class WandbMonitor(Monitor):
|
||||
return
|
||||
|
||||
for rollout in rollouts:
|
||||
completion = rollout.get("completion")
|
||||
if not completion:
|
||||
continue
|
||||
if isinstance(completion, list):
|
||||
try:
|
||||
completion = self.tokenizer.apply_chat_template(deserialize_tool_calls(completion), tokenize=False)
|
||||
except Exception:
|
||||
completion = str(completion)
|
||||
sample = {
|
||||
"step": step,
|
||||
"env": env_name,
|
||||
"task": rollout.get("task"),
|
||||
"example_id": rollout["example_id"],
|
||||
"completion": completion,
|
||||
"reward": rollout["reward"],
|
||||
}
|
||||
self.eval_samples_table.add_data(*sample.values())
|
||||
trace = rollout
|
||||
for branch in trace.branches:
|
||||
# Eval runs the openai client (no token ids), so show the assistant message
|
||||
# content rather than decoded tokens.
|
||||
completion = "".join(m.content or "" for m in branch.messages if m.role == "assistant")
|
||||
if not completion:
|
||||
continue
|
||||
sample = {
|
||||
"step": step,
|
||||
"env": env_name,
|
||||
"task": _loggable_task(trace.task),
|
||||
"task_idx": trace.task.idx,
|
||||
"completion": completion,
|
||||
"reward": trace.reward,
|
||||
}
|
||||
self.eval_samples_table.add_data(*sample.values())
|
||||
|
||||
wandb.log({"eval/samples": self.eval_samples_table, "step": step})
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import asyncio
|
||||
import functools
|
||||
import importlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from contextlib import contextmanager
|
||||
@@ -13,7 +12,6 @@ import torch
|
||||
import torch.distributed as dist
|
||||
import wandb
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalEnvConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
# TODO: Change all imports to use utils.pathing
|
||||
@@ -229,31 +227,3 @@ def default_dtype(dtype):
|
||||
yield
|
||||
finally:
|
||||
torch.set_default_dtype(prev)
|
||||
|
||||
|
||||
def install_env(env_id: str, prerelease: bool = False) -> None:
|
||||
"""Install an environment in subprocess."""
|
||||
logger = get_logger()
|
||||
logger.info(f"Installing environment {env_id}")
|
||||
install_cmd = ["uv", "run", "--no-sync", "prime", "env", "install", env_id]
|
||||
if prerelease:
|
||||
install_cmd.insert(-1, "--prerelease")
|
||||
result = subprocess.run(install_cmd, capture_output=True, text=True)
|
||||
for line in result.stdout.splitlines():
|
||||
if line.strip():
|
||||
logger.info(line)
|
||||
for line in result.stderr.splitlines():
|
||||
if line.strip():
|
||||
logger.warning(line)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(f"Failed to install environment {env_id} (exit code {result.returncode})")
|
||||
logger.info(f"Successfully installed environment {env_id}")
|
||||
|
||||
|
||||
def get_env_ids_to_install(env_configs: list[EnvConfig] | list[EvalEnvConfig]) -> set[str]:
|
||||
"""Get the list of environment IDs to install."""
|
||||
env_ids_to_install = set()
|
||||
for env_config in env_configs:
|
||||
if "/" in env_config.id:
|
||||
env_ids_to_install.add(env_config.id)
|
||||
return env_ids_to_install
|
||||
|
||||
@@ -29,6 +29,7 @@ VLM_REGISTRY: dict[str, VLMModelInfo] = {
|
||||
"qwen3_5": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_5_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_vl_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"gemma4": VLMModelInfo(vision_encoder_attr="model.vision_tower", language_model_attr="model.language_model"),
|
||||
}
|
||||
|
||||
# Text-only default
|
||||
@@ -86,6 +87,16 @@ def is_vlm_architecture(model_config: PretrainedConfig) -> bool:
|
||||
return _get_model_info_from_config(model_config) is not None
|
||||
|
||||
|
||||
def get_final_logit_softcapping(model_config: PretrainedConfig) -> float | None:
|
||||
"""Read ``final_logit_softcapping`` from the text config.
|
||||
|
||||
For composite VLM configs (e.g. Gemma) the value lives under ``text_config``;
|
||||
``get_text_config()`` returns that for VLMs and the config itself for text-only
|
||||
models, so a plain top-level ``getattr`` would miss it and silently drop softcapping.
|
||||
"""
|
||||
return getattr(model_config.get_text_config(), "final_logit_softcapping", None)
|
||||
|
||||
|
||||
def get_layer_prefix(model_config: PretrainedConfig, override: str | None = None) -> str:
|
||||
"""Return the weight key prefix for language model layers.
|
||||
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import math
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import (
|
||||
CustomAdvantageConfig,
|
||||
DefaultAdvantageConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.advantage import (
|
||||
AdvantageInputs,
|
||||
@@ -16,46 +14,37 @@ from prime_rl.orchestrator.advantage import (
|
||||
default_advantage_fn,
|
||||
setup_advantage_fn,
|
||||
)
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
from prime_rl.orchestrator.envs import Env, TrainEnv
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
def _make_rollout(
|
||||
reward: float,
|
||||
completion_len: int = 0,
|
||||
num_turns: int = 1,
|
||||
env_name: str = "test",
|
||||
example_id: int = 0,
|
||||
) -> dict:
|
||||
"""Create a minimal rollout dict for advantage testing.
|
||||
|
||||
`completion_len` tokens are split across `num_turns` trajectory steps.
|
||||
"""
|
||||
per_turn, rem = divmod(completion_len, max(num_turns, 1))
|
||||
trajectory = [
|
||||
{"tokens": {"prompt_ids": [0], "completion_ids": list(range(per_turn + (rem if i == 0 else 0)))}}
|
||||
for i in range(num_turns)
|
||||
]
|
||||
return {
|
||||
"reward": reward,
|
||||
"trajectory": trajectory,
|
||||
"env_name": env_name,
|
||||
"example_id": example_id,
|
||||
}
|
||||
def _make_rollout(reward: float, completion_len: int = 0, env_name: str = "test") -> Rollout:
|
||||
"""Build a ``Rollout`` (message-graph trace): ``reward`` via the reward dict and
|
||||
``completion_len`` model-sampled completion tokens (a single assistant node)."""
|
||||
node = vf.MessageNode(
|
||||
message=vf.AssistantMessage(content="x"),
|
||||
token_ids=list(range(completion_len)),
|
||||
mask=[True] * completion_len,
|
||||
logprobs=[0.0] * completion_len,
|
||||
sampled=True,
|
||||
)
|
||||
rollout = Rollout[vf.Task](task=vf.Task(idx=0, prompt=""), nodes=[node], rewards={"reward": reward})
|
||||
rollout.env_name = env_name
|
||||
return rollout
|
||||
|
||||
|
||||
def _make_group(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
|
||||
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths/turns."""
|
||||
def _make_group(rewards, completion_lengths=None) -> AdvantageInputs:
|
||||
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths."""
|
||||
rollouts = []
|
||||
for i, reward in enumerate(rewards):
|
||||
cl = int(completion_lengths[i]) if completion_lengths is not None else 0
|
||||
nt = int(num_turns[i]) if num_turns is not None else 1
|
||||
rollouts.append(_make_rollout(float(reward), cl, nt))
|
||||
rollouts.append(_make_rollout(float(reward), cl))
|
||||
return AdvantageInputs(rollouts=rollouts)
|
||||
|
||||
|
||||
# Helper aliases for readability — completion-only and tool-only token shaping.
|
||||
_TOKENS_COMPLETION = TokensLengthPenaltyConfig(completion_weight=1.0, tool_response_weight=0.0)
|
||||
_TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_response_weight=1.0)
|
||||
def _train_rollouts(rewards: list[float]) -> list[Rollout]:
|
||||
"""One group's worth of Rollouts for ``assign_advantages`` (operates on a single group)."""
|
||||
return [Rollout[vf.Task](task=vf.Task(idx=0, prompt=""), rewards={"reward": r}) for r in rewards]
|
||||
|
||||
|
||||
def test_default_advantage_fn_simple_mean():
|
||||
@@ -66,205 +55,144 @@ def test_default_advantage_fn_simple_mean():
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_mixed_group():
|
||||
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_linear_length_penalty_scales_by_pass_rate():
|
||||
"""Linear penalty subtracts coef * pass_rate * (completion tokens / max_seq_len), then mean-centers.
|
||||
|
||||
# mean_correct_len = (10+30+20)/3 = 20
|
||||
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
|
||||
# shaped_rewards = R * (1 + bonus * correct_mask) = [1.5, 1, 0, 1]
|
||||
# baseline = mean(shaped_rewards) = 0.875
|
||||
# A = shaped_rewards - baseline = [0.625, 0.125, -0.875, 0.125]
|
||||
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
``pass_rate`` is the group's mean reward, so a half-solved group scales the penalty by 0.5.
|
||||
"""
|
||||
rewards = [1.0, 1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
|
||||
result = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=2.0), max_seq_len=100)
|
||||
|
||||
# Zero-mean per group
|
||||
pass_rate = sum(rewards) / len(rewards) # 0.5
|
||||
penalized = [r - 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
# Zero-mean per group, and within each reward tier shorter output → higher advantage
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
# All correct rollouts have positive advantage
|
||||
for rollout, adv in zip(inputs.rollouts, result.advantages):
|
||||
if rollout["reward"] >= 1.0:
|
||||
assert adv > 0
|
||||
assert result.advantages[0] > result.advantages[1]
|
||||
assert result.advantages[2] > result.advantages[3]
|
||||
|
||||
|
||||
def test_efficiency_all_correct_group():
|
||||
"""All-correct group: zero-mean, shorter gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 1.0], completion_lengths=[10, 20, 40])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
|
||||
# mean_len = 70/3 ≈ 23.33
|
||||
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
|
||||
# shaped_rewards = [1+4/7, 1+1/7, 1] = [11/7, 8/7, 1]
|
||||
shaped = [11.0 / 7, 8.0 / 7, 1.0]
|
||||
mean_shaped = sum(shaped) / len(shaped)
|
||||
expected = [s - mean_shaped for s in shaped]
|
||||
assert result.advantages == pytest.approx(expected, abs=1e-6)
|
||||
|
||||
# Zero-mean
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
# Shortest has highest advantage
|
||||
assert result.advantages[0] > result.advantages[1] > result.advantages[2]
|
||||
def test_linear_length_penalty_zero_pass_rate_disables_penalty():
|
||||
"""A never-solved group (mean reward 0) gets no length pressure — falls back to plain GRPO."""
|
||||
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 50, 200])
|
||||
penalized = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=5.0), max_seq_len=100)
|
||||
plain = default_advantage_fn(inputs)
|
||||
assert penalized.advantages == pytest.approx(plain.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_all_zero_rewards():
|
||||
"""When all rewards are 0, no length shaping — falls back to standard GRPO."""
|
||||
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 20, 15])
|
||||
result_with = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
result_without = default_advantage_fn(inputs)
|
||||
def test_linear_length_penalty_gate_by_correctness():
|
||||
"""Gating scales each rollout's penalty by its reward, so reward-0 rollouts are untouched."""
|
||||
rewards = [1.0, 1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
|
||||
cfg = LinearLengthPenaltyConfig(coef=2.0, gate_by_correctness=True)
|
||||
result = default_advantage_fn(inputs, length_penalty=cfg, max_seq_len=100)
|
||||
|
||||
assert result_with.advantages == pytest.approx(result_without.advantages, abs=1e-6)
|
||||
pass_rate = sum(rewards) / len(rewards) # 0.5
|
||||
penalized = [r - r * 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_single_correct():
|
||||
"""Single correct rollout: bonus=0 (at its own mean), same as standard GRPO."""
|
||||
inputs = _make_group(rewards=[1.0, 0.0, 0.0, 0.0], completion_lengths=[100, 50, 200, 150])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_setup_advantage_fn_threads_max_seq_len():
|
||||
"""``setup_advantage_fn`` threads ``max_seq_len`` into the linear penalty denominator."""
|
||||
rewards = [1.0, 1.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30])
|
||||
fn = setup_advantage_fn(DefaultAdvantageConfig(length_penalty=LinearLengthPenaltyConfig(coef=1.0)), max_seq_len=100)
|
||||
result = fn(inputs)
|
||||
|
||||
assert result.advantages == pytest.approx([0.75, -0.25, -0.25, -0.25], abs=1e-6)
|
||||
pass_rate = sum(rewards) / len(rewards) # 1.0
|
||||
penalized = [1.0 - 1.0 * pass_rate * (length / 100) for length in (10, 30)]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_shorter_correct_higher_advantage():
|
||||
"""Among correct rollouts in a mixed group, shorter always gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 1.0, 0.0, 0.0], completion_lengths=[50, 100, 200, 80, 120])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_train_env_threads_max_seq_len_into_advantage_fn(monkeypatch):
|
||||
"""TrainEnv-built advantage funcs use orchestrator seq_len for length penalties."""
|
||||
|
||||
advs = result.advantages
|
||||
assert advs[0] > advs[1] > advs[2]
|
||||
assert all(a > 0 for a in advs[:3])
|
||||
assert all(a < 0 for a in advs[3:])
|
||||
def fake_env_init(self, config):
|
||||
self.config = config
|
||||
|
||||
|
||||
def test_efficiency_zero_mean_per_group():
|
||||
"""Reward shaping preserves zero-mean advantages within each group."""
|
||||
mixed = default_advantage_fn(
|
||||
_make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20]),
|
||||
length_penalty=_TOKENS_COMPLETION,
|
||||
)
|
||||
all_correct = default_advantage_fn(
|
||||
_make_group(rewards=[1.0, 1.0, 1.0, 1.0], completion_lengths=[10, 20, 40, 80]),
|
||||
length_penalty=_TOKENS_COMPLETION,
|
||||
monkeypatch.setattr(Env, "__init__", fake_env_init)
|
||||
config = OrchestratorConfig(
|
||||
seq_len=100,
|
||||
train={
|
||||
"env": [
|
||||
{
|
||||
"taskset": {"id": "reverse-text-v1"},
|
||||
"advantage": {"type": "default", "length_penalty": {"coef": 1.0}},
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
|
||||
assert sum(mixed.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
assert sum(all_correct.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
env = TrainEnv(config.train.env[0], max_seq_len=config.seq_len)
|
||||
assert env.advantage_fn is not None
|
||||
result = env.advantage_fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
|
||||
|
||||
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_amplification_bounded():
|
||||
"""Even with extreme length outliers, reward amplification is capped at 2x."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0], completion_lengths=[1, 10000, 5000])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
|
||||
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
|
||||
# Standard reward = 1, so amplification ≈ 2x
|
||||
# shaped_rewards ≈ [2, 1, 0], baseline ≈ 1, max advantage ≈ 1
|
||||
assert result.advantages[0] < 1.0 + 1e-3
|
||||
|
||||
|
||||
def test_efficiency_tokens_with_tool_response_weight():
|
||||
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
|
||||
rollouts = [
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 200},
|
||||
def test_per_env_linear_advantage_uses_runtime_schema():
|
||||
config = OrchestratorConfig(
|
||||
seq_len=100,
|
||||
train={
|
||||
"env": [
|
||||
{
|
||||
"taskset": {"id": "reverse-text-v1"},
|
||||
"advantage": {"type": "default", "length_penalty": {"coef": 1.0}},
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 0},
|
||||
},
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 100},
|
||||
},
|
||||
]
|
||||
inputs = AdvantageInputs(rollouts=rollouts)
|
||||
|
||||
# completion tokens identical (10 each) → completion-only shaping is a no-op
|
||||
result_completion_only = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
assert result_completion_only.advantages == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
|
||||
|
||||
# tool-response only: costs are [200, 0, 100], mean=100, bonus is one-sided
|
||||
# so only the below-mean rollout (idx 1) gets amplified; the at/above-mean tie.
|
||||
result_tool_only = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
|
||||
advs = result_tool_only.advantages
|
||||
assert advs[1] > advs[0]
|
||||
assert advs[1] > advs[2]
|
||||
assert advs[0] == pytest.approx(advs[2], abs=1e-6)
|
||||
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_fractional_weight_with_int_rewards():
|
||||
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
|
||||
rollouts_int = [
|
||||
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(7))}}]},
|
||||
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(11))}}]},
|
||||
{"reward": 0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(13))}}]},
|
||||
]
|
||||
rollouts_float = [{**r, "reward": float(r["reward"])} for r in rollouts_int]
|
||||
|
||||
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
|
||||
int_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_int), length_penalty=fractional)
|
||||
float_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_float), length_penalty=fractional)
|
||||
assert int_result.advantages == pytest.approx(float_result.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
|
||||
"""When all effective costs are zero, shaping is a no-op (no NaNs from div-by-zero)."""
|
||||
# tool-only weights but no harness metric → all costs == 0
|
||||
rollouts = [
|
||||
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
{"reward": 0.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
]
|
||||
inputs = AdvantageInputs(rollouts=rollouts)
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
|
||||
expected = default_advantage_fn(inputs) # plain GRPO
|
||||
assert not any(math.isnan(a) for a in result.advantages)
|
||||
assert result.advantages == pytest.approx(expected.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_tokens_default_weights_match_completion_when_no_metric():
|
||||
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
|
||||
result_default = default_advantage_fn(inputs, length_penalty=TokensLengthPenaltyConfig())
|
||||
result_completion = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
assert result_default.advantages == pytest.approx(result_completion.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_turns_penalty():
|
||||
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
|
||||
inputs = _make_group(
|
||||
rewards=[1.0, 1.0, 0.0, 1.0],
|
||||
# token counts identical, but turns differ — turns penalty should still differentiate
|
||||
completion_lengths=[100, 100, 100, 100],
|
||||
num_turns=[1, 3, 2, 2],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_penalty=TurnsLengthPenaltyConfig())
|
||||
|
||||
# mean_correct_turns = (1+3+2)/3 = 2
|
||||
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
|
||||
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
advantage = config.train.env[0].advantage
|
||||
assert isinstance(advantage, DefaultAdvantageConfig)
|
||||
assert isinstance(advantage.length_penalty, LinearLengthPenaltyConfig)
|
||||
|
||||
fn = setup_advantage_fn(advantage, max_seq_len=config.seq_len)
|
||||
result = fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
|
||||
|
||||
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
|
||||
|
||||
|
||||
def _train_rollouts(rewards: list[float]) -> list[TrainRollout]:
|
||||
"""Wrap a list of rewards into ``TrainRollout``\\ s sharing a single
|
||||
``group_id`` — ``assign_advantages`` works on one group at a time
|
||||
(the sink groups by ``group_id`` upstream)."""
|
||||
gid = uuid.uuid4()
|
||||
return [
|
||||
TrainRollout(
|
||||
raw={"reward": r, "trajectory": []},
|
||||
env_name="test",
|
||||
example_id=0,
|
||||
group_id=gid,
|
||||
policy_version=0,
|
||||
off_policy_steps=0,
|
||||
)
|
||||
for r in rewards
|
||||
]
|
||||
def test_per_env_custom_advantage_uses_runtime_schema():
|
||||
config = OrchestratorConfig(
|
||||
train={
|
||||
"env": [
|
||||
{
|
||||
"taskset": {"id": "reverse-text-v1"},
|
||||
"advantage": {
|
||||
"type": "custom",
|
||||
"import_path": "tests.unit.orchestrator.test_advantage._dummy_custom_advantage",
|
||||
"kwargs": {"scale": 3.0},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
advantage = config.train.env[0].advantage
|
||||
assert isinstance(advantage, CustomAdvantageConfig)
|
||||
|
||||
fn = setup_advantage_fn(advantage)
|
||||
result = fn(_make_group(rewards=[1.0, 0.5], completion_lengths=[10, 20]))
|
||||
|
||||
assert result.advantages == pytest.approx([3.0, 1.5], abs=1e-6)
|
||||
|
||||
|
||||
def test_length_weighted_baseline():
|
||||
"""Length-weighted baseline uses sum(len_i * reward_i) / sum(len_i) instead of the plain mean."""
|
||||
rewards = [1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30, 60])
|
||||
result = default_advantage_fn(inputs, length_weighted_baseline=True)
|
||||
|
||||
baseline = (10 * 1.0 + 30 * 0.0 + 60 * 0.0) / (10 + 30 + 60) # 0.1
|
||||
assert result.advantages == pytest.approx([r - baseline for r in rewards], abs=1e-6)
|
||||
# Token-weighted mean of advantages is zero
|
||||
assert sum(length * adv for length, adv in zip((10, 30, 60), result.advantages)) == pytest.approx(0.0, abs=1e-5)
|
||||
|
||||
|
||||
def test_assign_advantages_writes_field():
|
||||
@@ -306,4 +234,4 @@ def test_setup_advantage_fn_with_custom_config():
|
||||
|
||||
def _dummy_custom_advantage(inputs: AdvantageInputs, scale: float = 1.0) -> AdvantageOutputs:
|
||||
"""A simple custom advantage for testing."""
|
||||
return AdvantageOutputs(advantages=[r["reward"] * scale for r in inputs.rollouts])
|
||||
return AdvantageOutputs(advantages=[r.reward * scale for r in inputs.rollouts])
|
||||
|
||||
@@ -3,13 +3,9 @@ from types import SimpleNamespace
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from prime_rl.trainer.batch import (
|
||||
pad_micro_batch,
|
||||
prepare_batch,
|
||||
prepare_sample,
|
||||
)
|
||||
from prime_rl.trainer.batch import pad_micro_batch, prepare_batch, prepare_sample
|
||||
from prime_rl.trainer.utils import build_bin_cost
|
||||
from prime_rl.transport.types import MicroBatch, RoutedExperts, TrainingSample
|
||||
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
|
||||
|
||||
|
||||
def _routed_experts(data, dtype=np.uint8):
|
||||
@@ -29,12 +25,10 @@ def make_training_example():
|
||||
env_name: str = "test-env",
|
||||
) -> TrainingSample:
|
||||
return TrainingSample(
|
||||
prompt_ids=[1, 2],
|
||||
prompt_mask=[False, False],
|
||||
completion_ids=[3, 4],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[temperature, temperature], # Per-token temperatures
|
||||
token_ids=[1, 2, 3, 4],
|
||||
mask=[False, False, True, True],
|
||||
logprobs=[0.0, 0.0, -0.1, -0.2],
|
||||
temperatures=[temperature, temperature, temperature, temperature],
|
||||
teacher_logprobs=[0.0, 0.0, 0.0, 0.0],
|
||||
advantage=1.0,
|
||||
env_name=env_name,
|
||||
@@ -48,12 +42,10 @@ def make_sized_training_example(length: int, env_name: str = "test-env") -> Trai
|
||||
assert length >= 1
|
||||
prompt_len = length - 1
|
||||
return TrainingSample(
|
||||
prompt_ids=[1] * prompt_len,
|
||||
prompt_mask=[False] * prompt_len,
|
||||
completion_ids=[2],
|
||||
completion_mask=[True],
|
||||
completion_logprobs=[-0.1],
|
||||
completion_temperatures=[1.0],
|
||||
token_ids=[1] * prompt_len + [2],
|
||||
mask=[False] * prompt_len + [True],
|
||||
logprobs=[0.0] * prompt_len + [-0.1],
|
||||
temperatures=[1.0] * length,
|
||||
advantage=1.0,
|
||||
env_name=env_name,
|
||||
)
|
||||
@@ -120,35 +112,8 @@ def test_randomized_packing_invariants():
|
||||
assert not any(batch.advantages)
|
||||
|
||||
|
||||
def test_prepare_batch_packs_different_temperatures(make_training_example):
|
||||
"""With per-token temperatures, samples can be packed together regardless of their temperature values."""
|
||||
example1 = make_training_example(temperature=0.7, env_name="env-a")
|
||||
example2 = make_training_example(temperature=1.1, env_name="env-b")
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=[example1, example2],
|
||||
seq_len=16,
|
||||
num_train_workers=1,
|
||||
idxs=[0, 0],
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
flat_batches = _flatten_batches(batches_per_gpu)
|
||||
# With per-token temperatures, samples can now be packed together
|
||||
assert len(flat_batches) == 1
|
||||
# Each sample has 4 tokens (2 prompt + 2 completion), so 8 total tokens
|
||||
assert len(flat_batches[0].temperatures) == 8
|
||||
# First sample (4 tokens): all get temp 0.7
|
||||
assert flat_batches[0].temperatures[:4] == [0.7, 0.7, 0.7, 0.7]
|
||||
# Second sample (4 tokens): all get temp 1.1
|
||||
assert flat_batches[0].temperatures[4:8] == [1.1, 1.1, 1.1, 1.1]
|
||||
assert flat_batches[0].env_names == ["env-a"] * 4 + ["env-b"] * 4
|
||||
assert flat_batches[0].sequence_lengths == [4, 4]
|
||||
|
||||
|
||||
def test_pad_micro_batch_preserves_explicit_sequence_lengths(make_training_example):
|
||||
micro_batch = prepare_sample(make_training_example(), seq_len=16)
|
||||
def test_pad_micro_batch_preserves_explicit_sequence_lengths():
|
||||
micro_batch = prepare_sample(make_sized_training_example(4), seq_len=16)
|
||||
|
||||
padded = pad_micro_batch(micro_batch, pad_to_multiple_of=6)
|
||||
|
||||
@@ -158,25 +123,6 @@ def test_pad_micro_batch_preserves_explicit_sequence_lengths(make_training_examp
|
||||
assert padded.loss_mask[-2:] == [False, False]
|
||||
|
||||
|
||||
def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
|
||||
rl_example = make_training_example(training_mode="rl")
|
||||
sft_example = make_training_example(training_mode="sft")
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=[rl_example, sft_example],
|
||||
seq_len=16,
|
||||
num_train_workers=1,
|
||||
idxs=[0, 0],
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
flat_batches = _flatten_batches(batches_per_gpu)
|
||||
assert len(flat_batches) == 2
|
||||
assert {batch.training_mode for batch in flat_batches} == {"rl", "sft"}
|
||||
assert [batch.sequence_lengths for batch in flat_batches] == [[4], [4]]
|
||||
|
||||
|
||||
def test_split_to_align_avoids_dummy_micro_batches():
|
||||
examples = [make_sized_training_example(length) for length in [6, 6, 5, 5, 4, 4]]
|
||||
|
||||
@@ -244,18 +190,136 @@ def test_flop_aware_split_to_align_splits_heaviest_flop_bin():
|
||||
assert sum(len(batch.sequence_lengths) > 1 for batch in real_batches) == 3
|
||||
|
||||
|
||||
def test_training_sample_requires_env_name():
|
||||
with pytest.raises(TypeError, match="env_name"):
|
||||
TrainingSample(
|
||||
token_ids=[1, 2, 3, 4],
|
||||
mask=[False, False, True, True],
|
||||
logprobs=[0.0, 0.0, -0.1, -0.2],
|
||||
temperatures=[1.0, 1.0, 1.0, 1.0],
|
||||
advantage=1.0,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("rollout_count", "num_train_workers", "expected_batches_per_worker"), [(4, 2, 2), (5, 2, 3), (7, 1, 7), (11, 4, 3)]
|
||||
)
|
||||
def test_prepare_batch_balances_micro_batches_across_workers(
|
||||
make_training_example, rollout_count, num_train_workers, expected_batches_per_worker
|
||||
):
|
||||
examples = [make_training_example() for i in range(rollout_count)]
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=examples,
|
||||
seq_len=4,
|
||||
num_train_workers=num_train_workers,
|
||||
idxs=[0] * rollout_count,
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
assert all(len(worker_batches) == expected_batches_per_worker for worker_batches in batches_per_gpu)
|
||||
|
||||
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
assert len(examples) <= len(flat_batches) < len(examples) + num_train_workers
|
||||
print(flat_batches)
|
||||
|
||||
# Real rollouts and dummy padding can be interleaved across workers by the
|
||||
# FLOP-balanced partition, so classify by content rather than position.
|
||||
real_batches = [b for b in flat_batches if any(advantage != 0.0 for advantage in b.advantages)]
|
||||
assert len(real_batches) == len(examples)
|
||||
for batch in real_batches:
|
||||
assert sum(1 for advantage in batch.advantages if advantage != 0.0) == 4
|
||||
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 2
|
||||
|
||||
# Dummy padding batches have zero advantages and loss mask.
|
||||
for batch in flat_batches:
|
||||
if all(advantage == 0.0 for advantage in batch.advantages):
|
||||
assert sum(1 for loss_mask in batch.loss_mask if loss_mask) == 0
|
||||
|
||||
|
||||
def test_prepare_batch_packs_different_temperatures(make_training_example):
|
||||
"""With per-token temperatures, samples can be packed together regardless of their temperature values."""
|
||||
example1 = make_training_example(temperature=0.7, env_name="env-a")
|
||||
example2 = make_training_example(temperature=1.1, env_name="env-b")
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=[example1, example2],
|
||||
seq_len=16,
|
||||
num_train_workers=1,
|
||||
idxs=[0, 0],
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
# With per-token temperatures, samples can now be packed together
|
||||
assert len(flat_batches) == 1
|
||||
# Each sample has 4 tokens (2 prompt + 2 completion), so 8 total tokens
|
||||
assert len(flat_batches[0].temperatures) == 8
|
||||
# First sample (4 tokens): all get temp 0.7
|
||||
assert flat_batches[0].temperatures[:4] == [0.7, 0.7, 0.7, 0.7]
|
||||
# Second sample (4 tokens): all get temp 1.1
|
||||
assert flat_batches[0].temperatures[4:8] == [1.1, 1.1, 1.1, 1.1]
|
||||
assert flat_batches[0].env_names == ["env-a"] * 4 + ["env-b"] * 4
|
||||
|
||||
|
||||
def test_prepare_sample_propagates_training_mode(make_training_example):
|
||||
example = make_training_example(training_mode="sft")
|
||||
|
||||
micro_batch = prepare_sample(example, seq_len=16)
|
||||
|
||||
assert micro_batch.training_mode == "sft"
|
||||
|
||||
|
||||
def test_prepare_batch_does_not_pack_mixed_training_mode(make_training_example):
|
||||
rl_example = make_training_example(training_mode="rl")
|
||||
sft_example = make_training_example(training_mode="sft")
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=[rl_example, sft_example],
|
||||
seq_len=16,
|
||||
num_train_workers=1,
|
||||
idxs=[0, 0],
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
flat_batches = [batch for worker_batches in batches_per_gpu for batch in worker_batches]
|
||||
assert len(flat_batches) == 2
|
||||
assert {batch.training_mode for batch in flat_batches} == {"rl", "sft"}
|
||||
|
||||
|
||||
def test_prepare_sample_with_routed_experts():
|
||||
"""Routed experts are passed through prepare_sample and match input_ids length."""
|
||||
# 2 prompt + 2 completion = 4 tokens, 2 layers, topk=2
|
||||
routed_experts = [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[0, 2], [1, 3]], [[1, 0], [3, 2]]]
|
||||
routed_payload = _routed_experts(routed_experts)
|
||||
sample = TrainingSample(
|
||||
token_ids=[1, 2, 3, 4],
|
||||
mask=[False, False, True, True],
|
||||
logprobs=[0.0, 0.0, -0.1, -0.2],
|
||||
temperatures=[1.0, 1.0, 1.0, 1.0],
|
||||
advantage=1.0,
|
||||
env_name="test-env",
|
||||
routed_experts=routed_payload,
|
||||
)
|
||||
|
||||
micro_batch = prepare_sample(sample, seq_len=8)
|
||||
assert micro_batch.routed_experts is not None
|
||||
assert micro_batch.routed_experts == routed_payload
|
||||
|
||||
|
||||
def test_prepare_sample_truncates_routed_experts():
|
||||
"""Routed experts are truncated to seq_len when input exceeds it."""
|
||||
routed_experts = [[[0, 1]], [[2, 3]], [[4, 5]], [[6, 7]]]
|
||||
routed_payload = _routed_experts(routed_experts)
|
||||
expected_payload = _routed_experts(routed_experts[:3])
|
||||
sample = TrainingSample(
|
||||
prompt_ids=[1, 2],
|
||||
prompt_mask=[False, False],
|
||||
completion_ids=[3, 4],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[1.0, 1.0],
|
||||
token_ids=[1, 2, 3, 4],
|
||||
mask=[False, False, True, True],
|
||||
logprobs=[0.0, 0.0, -0.1, -0.2],
|
||||
temperatures=[1.0, 1.0, 1.0, 1.0],
|
||||
advantage=1.0,
|
||||
env_name="test-env",
|
||||
routed_experts=routed_payload,
|
||||
@@ -265,3 +329,55 @@ def test_prepare_sample_truncates_routed_experts():
|
||||
assert micro_batch.routed_experts is not None
|
||||
assert micro_batch.routed_experts == expected_payload
|
||||
assert micro_batch.env_names == ["test-env"] * 3
|
||||
|
||||
|
||||
def _encoded(arr) -> EncodedTensor:
|
||||
a = np.asarray(arr)
|
||||
return EncodedTensor(data=a.tobytes(), shape=list(a.shape), dtype=str(a.dtype))
|
||||
|
||||
|
||||
def test_prepare_sample_truncates_mm_at_image_boundary():
|
||||
"""Truncation never splits an image's placeholder block: it cuts to a whole-image boundary
|
||||
and slices mm_kwargs to match, so image-token count stays == image-embedding count."""
|
||||
# Two 2-token images (patches-per-token = 1): image-pad at indices 1,2 (img0) and 4,5 (img1).
|
||||
mm_token_type_ids = [0, 1, 1, 0, 1, 1, 0]
|
||||
pixel_values = np.array([[1.0], [1.0], [2.0], [2.0]], dtype=np.float32) # img0=1.0, img1=2.0
|
||||
grid = np.array([[1, 2, 1], [1, 2, 1]], dtype=np.int64)
|
||||
sample = TrainingSample(
|
||||
token_ids=[10, 11, 12, 13, 14, 15, 16],
|
||||
mask=[False, False, False, False, False, True, True],
|
||||
logprobs=[0.0] * 7,
|
||||
temperatures=[1.0] * 7,
|
||||
advantage=1.0,
|
||||
env_name="test-env",
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
mm_kwargs={"pixel_values": _encoded(pixel_values), "image_grid_thw": _encoded(grid)},
|
||||
)
|
||||
|
||||
# seq_len=5 falls inside img1 (one of its two placeholders survives) -> drop img1 entirely.
|
||||
mb = prepare_sample(sample, seq_len=5)
|
||||
assert len(mb.input_ids) == 4 # cut back to img1's first placeholder (index 4)
|
||||
assert len(mb.mm_token_type_ids) == len(mb.input_ids)
|
||||
n_placeholders = sum(1 for t in mb.mm_token_type_ids if t)
|
||||
assert n_placeholders == 2 # only img0's two placeholders remain
|
||||
# No mismatch: placeholders == image embeddings, and only img0's pixels are kept.
|
||||
assert mb.mm_kwargs["pixel_values"].shape == [2, 1]
|
||||
assert mb.mm_kwargs["image_grid_thw"].shape == [1, 3]
|
||||
kept = np.frombuffer(bytearray(mb.mm_kwargs["pixel_values"].data), dtype=np.float32)
|
||||
assert kept.tolist() == [1.0, 1.0]
|
||||
assert n_placeholders == mb.mm_kwargs["pixel_values"].shape[0] # ppt == 1 here
|
||||
|
||||
|
||||
def test_prepare_sample_none_routed_experts():
|
||||
"""When routed_experts is None, micro_batch.routed_experts is None."""
|
||||
sample = TrainingSample(
|
||||
token_ids=[1, 2, 3, 4],
|
||||
mask=[False, False, True, True],
|
||||
logprobs=[0.0, 0.0, -0.1, -0.2],
|
||||
temperatures=[1.0, 1.0, 1.0, 1.0],
|
||||
advantage=1.0,
|
||||
env_name="test-env",
|
||||
)
|
||||
|
||||
micro_batch = prepare_sample(sample, seq_len=8)
|
||||
assert micro_batch.routed_experts is None
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import math
|
||||
import uuid
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.configs.orchestrator import GibberishFilterConfig, RepetitionFilterConfig
|
||||
from prime_rl.orchestrator.filters import (
|
||||
GibberishFilter,
|
||||
@@ -9,7 +11,18 @@ from prime_rl.orchestrator.filters import (
|
||||
setup_filter,
|
||||
setup_filters,
|
||||
)
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
def _assistant_node(token_ids: list[int], logprobs: list[float]) -> vf.MessageNode:
|
||||
"""An assistant node whose tokens are all model-sampled (the filters read each node's
|
||||
masked-True tokens + logprobs)."""
|
||||
return vf.MessageNode(
|
||||
message=vf.AssistantMessage(content="x"),
|
||||
token_ids=token_ids,
|
||||
mask=[True] * len(token_ids),
|
||||
logprobs=logprobs,
|
||||
)
|
||||
|
||||
|
||||
def _make_rollout(
|
||||
@@ -18,52 +31,21 @@ def _make_rollout(
|
||||
*,
|
||||
reward: float = 1.0,
|
||||
multi_step: bool = False,
|
||||
) -> TrainRollout:
|
||||
"""Build a ``TrainRollout`` with a minimal ``vf.RolloutOutput``-shaped
|
||||
raw payload — enough for the filters to inspect ``trajectory`` /
|
||||
``stop_condition`` / etc."""
|
||||
) -> Rollout:
|
||||
"""Build a ``Rollout`` (a message-graph trace) carrying the completion tokens — enough for
|
||||
the filters to inspect each node's sampled tokens / logprobs."""
|
||||
if multi_step:
|
||||
mid = len(completion_ids) // 2
|
||||
trajectory = [
|
||||
{
|
||||
"tokens": {
|
||||
"completion_ids": completion_ids[:mid],
|
||||
"completion_logprobs": completion_logprobs[:mid],
|
||||
"completion_mask": [1] * mid,
|
||||
}
|
||||
},
|
||||
{
|
||||
"tokens": {
|
||||
"completion_ids": completion_ids[mid:],
|
||||
"completion_logprobs": completion_logprobs[mid:],
|
||||
"completion_mask": [1] * (len(completion_ids) - mid),
|
||||
}
|
||||
},
|
||||
nodes = [
|
||||
_assistant_node(completion_ids[:mid], completion_logprobs[:mid]),
|
||||
_assistant_node(completion_ids[mid:], completion_logprobs[mid:]),
|
||||
]
|
||||
else:
|
||||
trajectory = [
|
||||
{
|
||||
"tokens": {
|
||||
"completion_ids": completion_ids,
|
||||
"completion_logprobs": completion_logprobs,
|
||||
"completion_mask": [1] * len(completion_ids),
|
||||
}
|
||||
}
|
||||
]
|
||||
raw = {
|
||||
"trajectory": trajectory,
|
||||
"reward": reward,
|
||||
"stop_condition": None,
|
||||
"metrics": {},
|
||||
}
|
||||
return TrainRollout(
|
||||
raw=raw,
|
||||
env_name="test",
|
||||
example_id=0,
|
||||
group_id=uuid.uuid4(),
|
||||
policy_version=0,
|
||||
off_policy_steps=0,
|
||||
)
|
||||
nodes = [_assistant_node(completion_ids, completion_logprobs)]
|
||||
rollout = Rollout[vf.Task](task=vf.Task(idx=0, prompt=""), nodes=nodes, rewards={"reward": reward})
|
||||
rollout.env_name = "test"
|
||||
rollout.group_id = uuid.uuid4()
|
||||
return rollout
|
||||
|
||||
|
||||
def _make_gibberish_filter(vocab_size=128_000, token_id_threshold=100_000, logprob_offset=2.0, enforce=False):
|
||||
@@ -248,9 +230,9 @@ def test_apply_filters_enforced_flags_rollout():
|
||||
apply_filters([gibberish_filter], [rollout])
|
||||
|
||||
assert rollout.reward == 1.0
|
||||
assert rollout.raw["trajectory"][0]["tokens"]["completion_ids"] == [120_000]
|
||||
assert rollout.raw["trajectory"][0]["tokens"]["completion_mask"] == [1]
|
||||
assert rollout.raw["stop_condition"] is None
|
||||
assert rollout.nodes[0].token_ids == [120_000]
|
||||
assert rollout.nodes[0].mask == [True]
|
||||
assert rollout.stop_condition is None
|
||||
assert rollout.filter_results == {"gibberish": True}
|
||||
assert rollout.is_filtered is True
|
||||
|
||||
@@ -267,9 +249,9 @@ def test_apply_filters_preserves_clean_rollouts():
|
||||
apply_filters([gibberish_filter], [rollout])
|
||||
|
||||
assert rollout.reward == 1.0
|
||||
assert rollout.raw["trajectory"][0]["tokens"]["completion_ids"] == [50, 60, 70]
|
||||
assert all(m == 1 for m in rollout.raw["trajectory"][0]["tokens"]["completion_mask"])
|
||||
assert rollout.raw["stop_condition"] is None
|
||||
assert rollout.nodes[0].token_ids == [50, 60, 70]
|
||||
assert all(rollout.nodes[0].mask)
|
||||
assert rollout.stop_condition is None
|
||||
assert rollout.filter_results == {"gibberish": False}
|
||||
assert rollout.is_filtered is False
|
||||
|
||||
@@ -286,7 +268,7 @@ def test_apply_filters_first_filter_wins():
|
||||
|
||||
apply_filters([gibberish_filter, repetition_filter], [rollout])
|
||||
|
||||
assert rollout.raw["stop_condition"] is None
|
||||
assert rollout.stop_condition is None
|
||||
assert rollout.filter_results == {"gibberish": True, "repetition": False}
|
||||
assert rollout.is_filtered is True
|
||||
|
||||
@@ -329,13 +311,13 @@ def test_apply_filters_enforced_preserves_rollout_tokens():
|
||||
|
||||
apply_filters([gibberish_filter], [rollout])
|
||||
|
||||
assert rollout.raw["trajectory"][0]["tokens"]["completion_ids"] == [10, 120_000, 30]
|
||||
assert rollout.raw["trajectory"][0]["tokens"]["completion_logprobs"] == [
|
||||
assert rollout.nodes[0].token_ids == [10, 120_000, 30]
|
||||
assert rollout.nodes[0].logprobs == [
|
||||
-1.0,
|
||||
gibberish_filter.logprob_threshold - 1.0,
|
||||
-0.5,
|
||||
]
|
||||
assert rollout.raw["trajectory"][0]["tokens"]["completion_mask"] == [1, 1, 1]
|
||||
assert rollout.nodes[0].mask == [True, True, True]
|
||||
assert rollout.is_filtered is True
|
||||
|
||||
|
||||
@@ -347,11 +329,11 @@ def test_apply_filters_preserves_existing_stop_condition():
|
||||
completion_logprobs=[gibberish_filter.logprob_threshold - 1.0],
|
||||
reward=1.0,
|
||||
)
|
||||
rollout.raw["stop_condition"] = "generation_truncated"
|
||||
rollout.stop_condition = "generation_truncated"
|
||||
|
||||
apply_filters([gibberish_filter], [rollout])
|
||||
|
||||
assert rollout.raw["stop_condition"] == "generation_truncated"
|
||||
assert rollout.stop_condition == "generation_truncated"
|
||||
assert rollout.is_filtered is True
|
||||
|
||||
|
||||
@@ -370,8 +352,8 @@ def test_apply_filters_monitor_only_tracks_detection():
|
||||
apply_filters([gibberish_filter], [rollout])
|
||||
|
||||
assert rollout.reward == 1.0
|
||||
assert all(m == 1 for m in rollout.raw["trajectory"][0]["tokens"]["completion_mask"])
|
||||
assert rollout.raw["stop_condition"] is None
|
||||
assert all(rollout.nodes[0].mask)
|
||||
assert rollout.stop_condition is None
|
||||
assert rollout.filter_results == {"gibberish": True}
|
||||
assert rollout.is_filtered is False
|
||||
|
||||
|
||||
@@ -48,44 +48,3 @@ def test_setup_student_inference_pool_uses_renderer_when_enabled():
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_setup_student_inference_pool_defaults_to_mito():
|
||||
"""No renderer -> plain MITO chat completions."""
|
||||
|
||||
async def run() -> None:
|
||||
tokenizer = object()
|
||||
config = SimpleNamespace(
|
||||
training_mode="rl",
|
||||
renderer=None,
|
||||
pool_size=None,
|
||||
student=SimpleNamespace(
|
||||
client=SimpleNamespace(base_url=["http://localhost:8000/v1"]),
|
||||
model=SimpleNamespace(name="student-model"),
|
||||
),
|
||||
)
|
||||
inference_pool = object()
|
||||
|
||||
with (
|
||||
patch("renderers.base.create_renderer") as create_renderer_mock,
|
||||
patch(
|
||||
"prime_rl.orchestrator.utils.setup_inference_pool",
|
||||
new=AsyncMock(return_value=inference_pool),
|
||||
) as setup_pool_mock,
|
||||
):
|
||||
renderer, returned_pool = await setup_student_inference_pool(
|
||||
config=config,
|
||||
tokenizer=tokenizer,
|
||||
)
|
||||
|
||||
assert renderer is None
|
||||
assert returned_pool is inference_pool
|
||||
create_renderer_mock.assert_not_called()
|
||||
setup_pool_mock.assert_awaited_once_with(
|
||||
config.student.client,
|
||||
model_name="student-model",
|
||||
train_client_type="openai_chat_completions",
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
@@ -1,141 +0,0 @@
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import verifiers as vf
|
||||
|
||||
from prime_rl.orchestrator.trajectories import backfill_rollout_tokens, interleave_rollout
|
||||
|
||||
|
||||
class SimpleChatTokenizer:
|
||||
def __init__(self):
|
||||
self._tok2id: dict[str, int] = {}
|
||||
self._next_id = 1
|
||||
|
||||
def _id(self, token: str) -> int:
|
||||
if token not in self._tok2id:
|
||||
self._tok2id[token] = self._next_id
|
||||
self._next_id += 1
|
||||
return self._tok2id[token]
|
||||
|
||||
def apply_chat_template(self, messages, add_generation_prompt=False, return_dict=False):
|
||||
del return_dict
|
||||
ids = []
|
||||
for message in messages:
|
||||
role = message.get("role", "unknown")
|
||||
ids.append(self._id(f"<|{role}|>"))
|
||||
content = message.get("content", "")
|
||||
if isinstance(content, str):
|
||||
if content:
|
||||
ids.append(self._id(content))
|
||||
else:
|
||||
ids.append(self._id(str(content)))
|
||||
if add_generation_prompt:
|
||||
ids.append(self._id("<|assistant|>"))
|
||||
return ids
|
||||
|
||||
|
||||
def test_interleave_rollout_missing_tokens_returns_none():
|
||||
output = vf.RolloutOutput(
|
||||
example_id=1,
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "U1"}],
|
||||
completion=[{"role": "assistant", "content": "A1"}],
|
||||
response=MagicMock(),
|
||||
tokens=None,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
)
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
assert interleave_rollout(output) is None
|
||||
|
||||
|
||||
def test_backfill_rollout_tokens_for_sft():
|
||||
tokenizer = SimpleChatTokenizer()
|
||||
output = vf.RolloutOutput(
|
||||
example_id=42,
|
||||
env_name="test-env",
|
||||
trajectory=[
|
||||
vf.TrajectoryStep(
|
||||
prompt=[{"role": "user", "content": "U1"}],
|
||||
completion=[{"role": "assistant", "content": "A1"}],
|
||||
response=MagicMock(),
|
||||
tokens=None,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
vf.TrajectoryStep(
|
||||
prompt=[
|
||||
{"role": "user", "content": "U1"},
|
||||
{"role": "assistant", "content": "A1"},
|
||||
{"role": "user", "content": "U2"},
|
||||
],
|
||||
completion=[{"role": "assistant", "content": "A2"}],
|
||||
response=MagicMock(),
|
||||
tokens=None,
|
||||
reward=None,
|
||||
advantage=None,
|
||||
is_truncated=False,
|
||||
trajectory_id="1",
|
||||
extras={},
|
||||
),
|
||||
],
|
||||
sampling_args={"temperature": 1.0},
|
||||
error=None,
|
||||
)
|
||||
|
||||
backfill_rollout_tokens(output, tokenizer)
|
||||
|
||||
rollouts = interleave_rollout(output)
|
||||
assert rollouts is not None
|
||||
assert len(rollouts) == 1
|
||||
|
||||
rollout = rollouts[0]
|
||||
step1_prompt_ids = tokenizer.apply_chat_template(
|
||||
[{"role": "user", "content": "U1"}],
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
step1_full_ids = tokenizer.apply_chat_template(
|
||||
[{"role": "user", "content": "U1"}, {"role": "assistant", "content": "A1"}],
|
||||
add_generation_prompt=False,
|
||||
)
|
||||
step2_prompt_ids = tokenizer.apply_chat_template(
|
||||
[
|
||||
{"role": "user", "content": "U1"},
|
||||
{"role": "assistant", "content": "A1"},
|
||||
{"role": "user", "content": "U2"},
|
||||
],
|
||||
add_generation_prompt=True,
|
||||
)
|
||||
step2_full_ids = tokenizer.apply_chat_template(
|
||||
[
|
||||
{"role": "user", "content": "U1"},
|
||||
{"role": "assistant", "content": "A1"},
|
||||
{"role": "user", "content": "U2"},
|
||||
{"role": "assistant", "content": "A2"},
|
||||
],
|
||||
add_generation_prompt=False,
|
||||
)
|
||||
|
||||
prefix_len_1 = len(step1_prompt_ids)
|
||||
prefix_len_2 = len(step2_prompt_ids)
|
||||
step1_completion_ids = step1_full_ids[prefix_len_1:]
|
||||
step2_completion_ids = step2_full_ids[prefix_len_2:]
|
||||
step1_prefix = step1_prompt_ids + step1_completion_ids
|
||||
step2_new_prompt_ids = step2_prompt_ids[len(step1_prefix) :]
|
||||
|
||||
assert rollout.prompt_ids == step1_prompt_ids
|
||||
assert rollout.completion_ids == step1_completion_ids + step2_new_prompt_ids + step2_completion_ids
|
||||
assert rollout.completion_mask == (
|
||||
[True] * len(step1_completion_ids) + [False] * len(step2_new_prompt_ids) + [True] * len(step2_completion_ids)
|
||||
)
|
||||
assert rollout.completion_logprobs == [0.0] * len(rollout.completion_ids)
|
||||
@@ -2,7 +2,8 @@ import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import verifiers as vf
|
||||
import openai
|
||||
from verifiers.v1.clients.config import EvalClientConfig
|
||||
|
||||
from prime_rl.orchestrator import utils as orchestrator_utils
|
||||
from prime_rl.transport import TrainingSample
|
||||
@@ -41,20 +42,19 @@ def test_compute_teacher_logprobs_uses_inference_generate(monkeypatch):
|
||||
"kv_transfer_params": None,
|
||||
}
|
||||
)
|
||||
monkeypatch.setattr(orchestrator_utils, "setup_openai_client", lambda _: fake_client)
|
||||
# compute_teacher_logprobs constructs AsyncOpenAI directly; hand back the fake.
|
||||
monkeypatch.setattr(openai, "AsyncOpenAI", lambda **kwargs: fake_client)
|
||||
|
||||
sample = TrainingSample(
|
||||
prompt_ids=[1],
|
||||
prompt_mask=[True],
|
||||
completion_ids=[2, 3],
|
||||
completion_mask=[True, True],
|
||||
completion_logprobs=[-0.1, -0.2],
|
||||
completion_temperatures=[1.0, 1.0],
|
||||
token_ids=[1, 2, 3],
|
||||
mask=[False, True, True],
|
||||
logprobs=[0.0, -0.1, -0.2],
|
||||
temperatures=[1.0, 1.0, 1.0],
|
||||
env_name="test-env",
|
||||
)
|
||||
|
||||
result = await orchestrator_utils.compute_teacher_logprobs(
|
||||
clients=[vf.ClientConfig()],
|
||||
clients=[EvalClientConfig(base_url="http://fake-host:8000/v1")],
|
||||
model_name="teacher-model",
|
||||
samples=[sample],
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+26
-26
@@ -215,7 +215,7 @@ def test_multi_node_auto_inference_client_dp_rank_count_uses_router_url():
|
||||
|
||||
|
||||
def test_orchestrator_vlm_requires_renderer():
|
||||
with pytest.raises(ValidationError, match="orchestrator.renderer must be set when model.vlm is set"):
|
||||
with pytest.raises(ValidationError, match="renderer"):
|
||||
OrchestratorConfig.model_validate(
|
||||
{
|
||||
"student": {
|
||||
@@ -259,7 +259,7 @@ def test_shared_model_name_propagates_to_subconfigs():
|
||||
{
|
||||
"model": {"name": model_name},
|
||||
"trainer": {},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
"inference": {},
|
||||
}
|
||||
)
|
||||
@@ -276,7 +276,7 @@ def test_shared_tokenizer_propagates_when_subconfigs_unset():
|
||||
"model": {"name": "my-model"},
|
||||
"tokenizer": {"name": "my-tokenizer"},
|
||||
"trainer": {},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
}
|
||||
)
|
||||
assert config.trainer.tokenizer.name == "my-tokenizer"
|
||||
@@ -293,7 +293,7 @@ def test_shared_and_sub_tokenizer_name_conflict_raises():
|
||||
"model": {"name": "my-model"},
|
||||
"tokenizer": {"name": "shared-tok"},
|
||||
"trainer": {"tokenizer": {"name": "trainer-tok"}},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -304,7 +304,7 @@ def test_tokenizer_name_falls_back_to_model_name_when_unset():
|
||||
"model": {"name": "my-model"},
|
||||
"tokenizer": {"trust_remote_code": True},
|
||||
"trainer": {},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
}
|
||||
)
|
||||
assert config.trainer.tokenizer.name == "my-model"
|
||||
@@ -332,7 +332,7 @@ def test_explicit_subconfig_tokenizer_name_survives_shared_model_propagation():
|
||||
"model": {"name": "M"},
|
||||
"trainer": {},
|
||||
"orchestrator": {
|
||||
"renderer": None,
|
||||
"renderer": {"name": "default"},
|
||||
"tokenizer": {"name": "explicit-orch-tok"},
|
||||
},
|
||||
}
|
||||
@@ -351,7 +351,7 @@ def test_tokenizer_chat_template_mismatch_raises():
|
||||
RLConfig.model_validate(
|
||||
{
|
||||
"trainer": {"tokenizer": {"chat_template": "A"}},
|
||||
"orchestrator": {"renderer": None, "tokenizer": {"chat_template": "B"}},
|
||||
"orchestrator": {"renderer": {"name": "default"}, "tokenizer": {"chat_template": "B"}},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -361,7 +361,7 @@ def test_shared_seq_len_propagates_to_subconfigs():
|
||||
{
|
||||
"seq_len": 4096,
|
||||
"trainer": {},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
}
|
||||
)
|
||||
assert config.trainer.model.seq_len == 4096
|
||||
@@ -377,7 +377,7 @@ def test_shared_and_sub_seq_len_conflict_raises():
|
||||
{
|
||||
"seq_len": 4096,
|
||||
"trainer": {"model": {"seq_len": 8192}},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -389,7 +389,7 @@ def test_shared_and_sub_model_name_conflict_raises():
|
||||
{
|
||||
"model": {"name": "X"},
|
||||
"trainer": {"model": {"name": "Y"}},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -401,7 +401,7 @@ def test_shared_and_sub_max_steps_conflict_raises():
|
||||
{
|
||||
"max_steps": 100,
|
||||
"trainer": {},
|
||||
"orchestrator": {"renderer": None, "max_steps": 200},
|
||||
"orchestrator": {"renderer": {"name": "default"}, "max_steps": 200},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -416,7 +416,7 @@ def test_trainer_chat_template_cascades_to_inference():
|
||||
{
|
||||
"model": {"name": "Qwen/Qwen3-0.6B"},
|
||||
"trainer": {"tokenizer": {"chat_template": "TPL"}},
|
||||
"orchestrator": {"renderer": None, "tokenizer": {"chat_template": "TPL"}},
|
||||
"orchestrator": {"renderer": {"name": "default"}, "tokenizer": {"chat_template": "TPL"}},
|
||||
"inference": {},
|
||||
}
|
||||
)
|
||||
@@ -442,7 +442,7 @@ def test_shared_wandb_fields_propagate_to_subconfigs():
|
||||
"offline": False,
|
||||
},
|
||||
"trainer": {},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
}
|
||||
)
|
||||
for component in (config.trainer.wandb, config.orchestrator.wandb):
|
||||
@@ -462,7 +462,7 @@ def test_empty_shared_ckpt_block_does_not_conflict_with_subconfig_ckpt():
|
||||
{
|
||||
"ckpt": {}, # empty block, no field set
|
||||
"trainer": {"ckpt": {"interval": 50}},
|
||||
"orchestrator": {"renderer": None, "ckpt": {"interval": 50}},
|
||||
"orchestrator": {"renderer": {"name": "default"}, "ckpt": {"interval": 50}},
|
||||
}
|
||||
)
|
||||
assert config.trainer.ckpt is not None
|
||||
@@ -476,7 +476,7 @@ def test_shared_and_subconfig_disjoint_fields_coexist():
|
||||
{
|
||||
"model": {"name": "Qwen/Qwen3-0.6B"},
|
||||
"trainer": {"model": {"impl": "custom"}},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
}
|
||||
)
|
||||
assert config.trainer.model.name == "Qwen/Qwen3-0.6B"
|
||||
@@ -528,15 +528,15 @@ def test_orchestrator_explicit_renderer_skips_unmapped_check():
|
||||
assert config.renderer.name == "qwen3"
|
||||
|
||||
|
||||
def test_orchestrator_renderer_none_skips_unmapped_check():
|
||||
"""renderer=None (MITO mode) means the renderer client isn't used, so MODEL_RENDERER_MAP doesn't apply."""
|
||||
config = OrchestratorConfig.model_validate(
|
||||
{
|
||||
"model": {"name": "not-a-real-org/not-a-real-model"},
|
||||
"renderer": None,
|
||||
}
|
||||
)
|
||||
assert config.renderer is None
|
||||
def test_orchestrator_renderer_none_rejected():
|
||||
"""A renderer is required (training is renderer-only): the non-optional type rejects None."""
|
||||
with pytest.raises(ValidationError, match="renderer"):
|
||||
OrchestratorConfig.model_validate(
|
||||
{
|
||||
"model": {"name": "not-a-real-org/not-a-real-model"},
|
||||
"renderer": None,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_orchestrator_explicit_default_renderer_with_unmapped_model():
|
||||
@@ -561,7 +561,7 @@ def test_shared_model_name_resolves_inference_parsers():
|
||||
{
|
||||
"model": {"name": "Qwen/Qwen3-Coder-30B-A3B-Instruct"},
|
||||
"trainer": {},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
"inference": {},
|
||||
}
|
||||
)
|
||||
@@ -577,7 +577,7 @@ def test_explicit_inference_parser_wins_over_auto():
|
||||
{
|
||||
"model": {"name": "Qwen/Qwen3-Coder-30B-A3B-Instruct"},
|
||||
"trainer": {},
|
||||
"orchestrator": {"renderer": None},
|
||||
"orchestrator": {"renderer": {"name": "default"}},
|
||||
"inference": {"model": {"tool_call_parser": "hermes"}},
|
||||
}
|
||||
)
|
||||
|
||||
@@ -33,8 +33,8 @@ def create_run_with_config(output_dir: Path, run_name: str) -> Path:
|
||||
"group_size": 1,
|
||||
"env": [{"id": "test-env"}],
|
||||
"sampling": {"temperature": 1.0},
|
||||
# test-model isn't in MODEL_RENDERER_MAP; bypass the renderer-resolution validator.
|
||||
"renderer": "None",
|
||||
# test-model isn't in MODEL_RENDERER_MAP; use the explicit default renderer.
|
||||
"renderer": {"name": "default"},
|
||||
}
|
||||
with open(control_dir / "orch.toml", "wb") as f:
|
||||
tomli_w.dump(config, f)
|
||||
@@ -43,12 +43,10 @@ def create_run_with_config(output_dir: Path, run_name: str) -> Path:
|
||||
|
||||
def make_training_sample() -> TrainingSample:
|
||||
return TrainingSample(
|
||||
prompt_ids=[1],
|
||||
prompt_mask=[False],
|
||||
completion_ids=[2],
|
||||
completion_mask=[True],
|
||||
completion_logprobs=[-0.1],
|
||||
completion_temperatures=[1.0],
|
||||
token_ids=[1, 2],
|
||||
mask=[False, True],
|
||||
logprobs=[0.0, -0.1],
|
||||
temperatures=[1.0, 1.0],
|
||||
env_name="test-env",
|
||||
)
|
||||
|
||||
|
||||
@@ -42,8 +42,8 @@ def create_run_with_config(
|
||||
"batch_size": 32,
|
||||
"group_size": 4,
|
||||
"env": [{"id": "test-env"}],
|
||||
# test-model isn't in MODEL_RENDERER_MAP; bypass the renderer-resolution validator.
|
||||
"renderer": "None",
|
||||
# test-model isn't in MODEL_RENDERER_MAP; use the explicit default renderer.
|
||||
"renderer": {"name": "default"},
|
||||
}
|
||||
|
||||
with open(config_dir / "orch.toml", "wb") as f:
|
||||
@@ -203,7 +203,7 @@ def test_config_loading(tmp_path: Path) -> None:
|
||||
"max_steps": 1000,
|
||||
"group_size": 4,
|
||||
"env": [{"id": "test-env"}],
|
||||
"renderer": "None",
|
||||
"renderer": {"name": "default"},
|
||||
}
|
||||
create_run_with_config(tmp_path, "run_test123", config=test_config)
|
||||
|
||||
@@ -248,7 +248,7 @@ def test_config_cleanup_on_deletion(tmp_path: Path) -> None:
|
||||
"batch_size": 16,
|
||||
"group_size": 4,
|
||||
"env": [{"id": "test-env"}],
|
||||
"renderer": "None",
|
||||
"renderer": {"name": "default"},
|
||||
}
|
||||
run_dir = create_run_with_config(tmp_path, "run_delete_me", config=test_config)
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import httpx
|
||||
import verifiers as vf
|
||||
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
|
||||
@@ -67,13 +67,12 @@ def test_setup_clients_assigns_renderer_and_dp_rank_headers():
|
||||
renderer_config=renderer_settings,
|
||||
)
|
||||
|
||||
assert [client.client_type for client in clients] == ["renderer", "renderer"]
|
||||
assert [client.renderer_config for client in clients] == [renderer_settings, renderer_settings]
|
||||
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.api_base_url for client in clients] == ["http://worker-a:8000/v1"] * 2
|
||||
assert [client.extra_headers["X-data-parallel-rank"] for client in clients] == ["0", "1"]
|
||||
assert clients[0].extra_headers["X-Test"] == "test"
|
||||
assert clients[0].extra_headers_from_state == {"X-Session-ID": "session_id"}
|
||||
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 clients[0].headers["X-Test"] == "test"
|
||||
|
||||
|
||||
def test_setup_clients_assigns_renderer_model_name():
|
||||
@@ -103,17 +102,9 @@ def test_setup_clients_preserves_chat_client_defaults():
|
||||
clients = setup_clients(client_config)
|
||||
|
||||
assert clients == [
|
||||
vf.ClientConfig(
|
||||
client_idx=0,
|
||||
client_type="openai_chat_completions",
|
||||
EvalClientConfig(
|
||||
api_key_var="PRIME_API_KEY",
|
||||
api_base_url="http://worker-a:8000/v1",
|
||||
timeout=client_config.timeout,
|
||||
connect_timeout=client_config.connect_timeout,
|
||||
max_connections=8192,
|
||||
max_keepalive_connections=8192,
|
||||
max_retries=10,
|
||||
extra_headers={},
|
||||
extra_headers_from_state={},
|
||||
base_url="http://worker-a:8000/v1",
|
||||
headers={},
|
||||
)
|
||||
]
|
||||
|
||||
@@ -4,7 +4,7 @@ from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
import verifiers as vf
|
||||
from verifiers.v1.clients.config import TrainClientConfig
|
||||
|
||||
from prime_rl.utils.elastic import (
|
||||
AdapterState,
|
||||
@@ -411,8 +411,6 @@ def test_elastic_clients_preserve_renderer_model_name_when_model_name_updates():
|
||||
client_config.elastic.port = 8000
|
||||
client_config.elastic.sync_interval = 5.0
|
||||
client_config.router_url = None
|
||||
client_config.timeout = 1200
|
||||
client_config.connect_timeout = 30.0
|
||||
client_config.api_key_var = "PRIME_API_KEY"
|
||||
client_config.headers = {}
|
||||
client_config.headers_from_env = {}
|
||||
@@ -435,20 +433,14 @@ def test_elastic_clients_preserve_renderer_model_name_when_model_name_updates():
|
||||
pool.update_model_name("r8-smoke")
|
||||
clients = pool.train_clients
|
||||
|
||||
# `renderer_model_name` stays pinned to the original base model even after the
|
||||
# served model name flips to the LoRA adapter (`r8-smoke`).
|
||||
assert clients == [
|
||||
vf.ClientConfig(
|
||||
client_idx=0,
|
||||
client_type="renderer",
|
||||
renderer_config=renderer_settings,
|
||||
TrainClientConfig(
|
||||
renderer=renderer_settings,
|
||||
renderer_model_name="Qwen/Qwen3-VL-4B-Instruct",
|
||||
api_key_var="PRIME_API_KEY",
|
||||
api_base_url="http://10.0.0.1:8000/v1",
|
||||
timeout=1200,
|
||||
connect_timeout=30.0,
|
||||
max_connections=8192,
|
||||
max_keepalive_connections=8192,
|
||||
max_retries=10,
|
||||
extra_headers={},
|
||||
extra_headers_from_state={},
|
||||
base_url="http://10.0.0.1:8000/v1",
|
||||
headers={},
|
||||
)
|
||||
]
|
||||
|
||||
@@ -3,7 +3,9 @@ import json
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pyarrow.parquet as pq
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
from prime_rl.utils.monitor.prime import PrimeMonitor
|
||||
|
||||
|
||||
@@ -13,32 +15,34 @@ def _new_monitor() -> PrimeMonitor:
|
||||
return monitor
|
||||
|
||||
|
||||
def _build_rollout(*, example_id: int, reward: float, task: str) -> dict:
|
||||
return {
|
||||
"example_id": example_id,
|
||||
"prompt": [{"role": "user", "content": f"prompt-{example_id}"}],
|
||||
"completion": [{"role": "assistant", "content": f"completion-{example_id}"}],
|
||||
"trajectory": [
|
||||
{
|
||||
"prompt": [{"role": "user", "content": f"prompt-{example_id}"}],
|
||||
"completion": [{"role": "assistant", "content": f"completion-{example_id}"}],
|
||||
"reward": reward,
|
||||
"advantage": reward / 2,
|
||||
"extras": {"source": "test"},
|
||||
"tokens": {
|
||||
"prompt_ids": [1, 2, 3],
|
||||
"completion_ids": [4, 5],
|
||||
},
|
||||
}
|
||||
],
|
||||
"answer": f"answer-{example_id}",
|
||||
"task": task,
|
||||
"info": {"difficulty": "easy"},
|
||||
"reward": reward,
|
||||
"advantage": reward / 2,
|
||||
"metrics": {"accuracy": reward},
|
||||
"timing": {"generation": {"start": 0.0, "end": 12.5, "duration": 12.5}},
|
||||
}
|
||||
def _build_rollout(*, example_id: int, reward: float, task: str) -> Rollout:
|
||||
"""Build a v1 ``Rollout`` (message-graph trace). The user node carries the prompt and the
|
||||
assistant node the completion; ``_rollouts_to_parquet_bytes`` reads the conversation off the
|
||||
branches (its ``completion`` column is the last branch's messages, ``trajectory`` is one
|
||||
message list per branch)."""
|
||||
nodes = [
|
||||
vf.MessageNode(
|
||||
message=vf.UserMessage(content=f"prompt-{example_id}"),
|
||||
token_ids=[1, 2, 3],
|
||||
mask=[False, False, False],
|
||||
logprobs=[0.0, 0.0, 0.0],
|
||||
),
|
||||
vf.MessageNode(
|
||||
message=vf.AssistantMessage(content=f"completion-{example_id}"),
|
||||
token_ids=[4, 5],
|
||||
mask=[True, True],
|
||||
logprobs=[-0.1, -0.2],
|
||||
sampled=True,
|
||||
),
|
||||
]
|
||||
rollout = Rollout[vf.Task](
|
||||
task=vf.Task(idx=example_id, prompt=f"prompt-{example_id}"),
|
||||
nodes=nodes,
|
||||
rewards={"reward": reward},
|
||||
)
|
||||
rollout.env_name = task
|
||||
rollout.advantage = reward / 2
|
||||
return rollout
|
||||
|
||||
|
||||
def test_rollouts_to_parquet_bytes_preserves_all_rollouts_and_ids():
|
||||
@@ -63,24 +67,22 @@ def test_rollouts_to_parquet_bytes_preserves_all_rollouts_and_ids():
|
||||
assert [row["sample_id"] for row in rows] == [0, 1]
|
||||
assert all(row["run_id"] == "run-123" for row in rows)
|
||||
assert all(row["step"] == 7 for row in rows)
|
||||
assert json.loads(rows[0]["prompt"])[0]["content"] == "prompt-101"
|
||||
# `completion` is the last branch's messages; the prompt user message lives in `trajectory`.
|
||||
assert json.loads(rows[1]["completion"])[0]["content"] == "completion-202"
|
||||
trajectory = json.loads(rows[0]["trajectory"])
|
||||
assert trajectory[0]["messages"][0]["content"] == "prompt-101"
|
||||
|
||||
|
||||
def test_rollouts_to_parquet_bytes_skips_rollouts_without_trajectory():
|
||||
monitor = _new_monitor()
|
||||
monitor.run_id = "run-456"
|
||||
|
||||
rollout_with_branches = _build_rollout(example_id=1, reward=1.0, task="task-a")
|
||||
rollout_without_branches = Rollout[vf.Task](task=vf.Task(idx=2, prompt="missing-trajectory"))
|
||||
assert rollout_without_branches.branches == []
|
||||
|
||||
parquet_bytes = monitor._rollouts_to_parquet_bytes(
|
||||
[
|
||||
_build_rollout(example_id=1, reward=1.0, task="task-a"),
|
||||
{
|
||||
"example_id": 2,
|
||||
"prompt": [{"role": "user", "content": "missing-trajectory"}],
|
||||
"completion": [{"role": "assistant", "content": "ignored"}],
|
||||
"trajectory": [],
|
||||
},
|
||||
],
|
||||
[rollout_with_branches, rollout_without_branches],
|
||||
step=3,
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user