Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b636a8b7ec | ||
|
|
9aa8563eae | ||
|
|
a44dc3572c | ||
|
|
32f4f40f9e | ||
|
|
ef07764841 | ||
|
|
7745c669d1 | ||
|
|
87c5456806 | ||
|
|
12b4d4b050 | ||
|
|
64a0decfaa | ||
|
|
a1822f7a0a | ||
|
|
8c2847721a | ||
|
|
9dbe8b5fa0 | ||
|
|
819993faac | ||
|
|
d57c59f16a | ||
|
|
c4a78d1134 | ||
|
|
cacae615e6 | ||
|
|
a9005aba8e | ||
|
|
788b9fdd1a | ||
|
|
abcf7c0acc | ||
|
|
26c967c6e3 | ||
|
|
7760531310 | ||
|
|
ce65f38fc0 | ||
|
|
1c45dc4572 | ||
|
|
4a80d747db | ||
|
|
8df2329a70 | ||
|
|
487d8a76d1 | ||
|
|
d05fe6de95 | ||
|
|
a563a03d61 | ||
|
|
de08c72769 | ||
|
|
7f811c01a8 | ||
|
|
2d6dc64efd | ||
|
|
07ebe34570 | ||
|
|
c1ac451e39 | ||
|
|
d5ed9fb7e4 | ||
|
|
b4a41d3f2c | ||
|
|
d7339fcf25 | ||
|
|
c394c2e1bd | ||
|
|
0d372c1fd6 | ||
|
|
9f4eef81a3 | ||
|
|
1d9ab255eb | ||
|
|
eff12f2483 | ||
|
|
e0886c152d | ||
|
|
9ef21a64f1 |
@@ -87,6 +87,9 @@ jobs:
|
||||
- test: benchmark_regression
|
||||
runner: 4xa6000
|
||||
pytest_args: "tests/integration/test_benchmark_regression.py"
|
||||
- test: gsm8k_eval
|
||||
runner: vm
|
||||
pytest_args: "tests/integration/test_gsm8k_eval.py"
|
||||
steps:
|
||||
- name: Install Git
|
||||
run: |
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
|
||||
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
|
||||
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
|
||||
- **Context parallelism**: a module that needs CP state holds a `CPContext` (`models/base.py`) as `self.cp_context`, defaulting to `CPContext()`, which is the non-CP case; `PreTrainedModelPrimeRL` supplies that default. `setup_context_parallel` in `utils/cp.py` builds one `CPContext` and assigns it to every module that has the field, so each module holds the same frozen object.
|
||||
- **Zen of Python**: remember the Zen of Python when writing code.
|
||||
```
|
||||
Beautiful is better than ugly.
|
||||
@@ -42,9 +43,9 @@ Namespaces are one honking great idea -- let's do more of those!
|
||||
|
||||
## Skills
|
||||
|
||||
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
|
||||
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
|
||||
|
||||
You are responsible for maintaining the skills folder. When a workflow fails and you fix it – whether with help from the user or through trial and error – you must update the skills to make implicit knowledge explicit. You are also responsible for keeping the skills up to date whenever you or anyone else modifies the code.
|
||||
If a repository skill could benefit from an update, suggest the specific change, explain why it would help, and ask the user for approval before making it. Wait for approval before creating, modifying, renaming, or deleting skills, including their supporting files and symlinks. If the user has already explicitly requested or approved the skill change, proceed without asking again. Requests to change code, fix workflows, update documentation, or open a PR do not implicitly authorize skill changes. You may read and follow skills without changing them.
|
||||
|
||||
## Testing
|
||||
|
||||
|
||||
+3
-2
@@ -94,9 +94,10 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
|
||||
# Third-party deps only — source edits don't bust this layer. First-party
|
||||
# editables install in the source-layer sync below. No build-context bind
|
||||
# mount here: .git would bust the cache every commit.
|
||||
# `--extra dashboard` (fastapi/uvicorn) is baked in so the fft chart's dashboard pod needs no runtime uv sync (see PR body).
|
||||
COPY --from=manifests /manifests /app
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
--no-install-workspace \
|
||||
--no-install-package prime-rl-configs \
|
||||
--no-install-package verifiers \
|
||||
@@ -132,7 +133,7 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& \
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" /app/deps/renderers/pyproject.toml \
|
||||
&& \
|
||||
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
uv sync --all-packages --extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
|
||||
@@ -38,7 +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/advanced/glm-5.2/).
|
||||
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/advanced/glm-5.3/).
|
||||
|
||||
|
||||
## Models support
|
||||
@@ -204,10 +204,7 @@ These guides are designed to be run from a Slurm cluster but can also be adapted
|
||||
|
||||
1. [**Qwen3-30B-A3B**](examples/advanced/qwen3-30b-a3b/): Train `Qwen3-30B-A3B` on math, SWE, and agentic tool use.
|
||||
2. [**GLM-4.5-Air**](examples/advanced/glm-4.5-air/): Train `GLM-4.5-Air` on search, SWE, and terminal tasks.
|
||||
3. [**Nemotron-3-Super**](examples/advanced/nemotron-3-super/): Train the `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
4. [**MiniMax-M2.5 SWE**](examples/advanced/minimax-m2.5/): Train `MiniMax-M2.5` on agentic SWE tasks.
|
||||
5. [**INTELLECT-3.1**](examples/advanced/intellect-3.1/): Reproduce our `INTELLECT-3.1` training run.
|
||||
6. [**High-throughput GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
3. [**GLM-5**](examples/advanced/glm-5.3/): Large-scale `GLM-5`/`GLM-5.3` training with P/D disaggregation, the `llm-d` router, and FP8.
|
||||
|
||||
## Docs
|
||||
|
||||
@@ -215,7 +212,8 @@ Check out the [docs](docs) directory for in-depth guides on how to use prime-rl.
|
||||
|
||||
- [**Overview**](docs/overview.md) - Architecture, install, and a copy-pasteable end-to-end RL run
|
||||
- [**Configuration**](docs/configuration.md) - TOML composition, CLI overrides, env vars, validation
|
||||
- [**Training**](docs/training.md) - RL, SFT, evals, checkpointing, observability, rules of thumb
|
||||
- [**Training**](docs/training.md) - RL, SFT, checkpointing, observability, rules of thumb
|
||||
- [**Eval**](docs/eval.md) - Standalone evals against any inference server, online evals, resume, platform upload
|
||||
- [**Scaling**](docs/scaling.md) - Single-GPU through multi-node, FSDP/EP/CP, SLURM, benchmarking
|
||||
- [**Algorithms**](docs/algorithms.md) - Async/off-policy training, the AIPO loss, advantage and filter plugins, trajectory merging
|
||||
- [**Advanced**](docs/advanced.md) - Custom modeling, multimodal training, LoRA
|
||||
|
||||
+12
-5
@@ -6,13 +6,20 @@ Configurations for running prime-rl.
|
||||
environments, sized to run on a single dev machine. Each mirrors the matching
|
||||
[`examples/basic/`](../examples/basic) tutorial and is smoke-tested for one step.
|
||||
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
|
||||
- **[`advanced/`](advanced)** — frontier-model training configs without launch walkthroughs:
|
||||
`minimax-m2.5` (swe), `nemotron-3-super` (swe), `deepseek-v4-flash` (sft + a standalone
|
||||
vLLM serving pre-flight). For the tutorialized equivalents, see
|
||||
[`examples/advanced/`](../examples/advanced).
|
||||
- **`ci/`** — integration and nightly configs used by CI.
|
||||
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
|
||||
(two reverse-text train sources + one eval source, one env server per source). Not
|
||||
guaranteed functional or up to date.
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), `multi-env/`
|
||||
(two reverse-text train sources + one eval source, one env server per source), and
|
||||
`eval/` (`uv run eval` smokes against Prime Inference, one per shape: `single-turn`
|
||||
(gsm8k), `multi-turn` (terminal-bench-2 fix-git in sandboxes against a local vLLM deployment with the adaptive band), `resume`, `multi-env`).
|
||||
Not guaranteed functional or up to date.
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/<env>/rl.toml
|
||||
uv run sft @ configs/basic/<env>/sft.toml # where present
|
||||
uv run rl @ configs/basic/<env>/rl.toml
|
||||
uv run sft @ configs/basic/<env>/sft.toml # where present
|
||||
uv run eval @ configs/debug/eval/<shape>.toml
|
||||
```
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# CI eval smoke: gsm8k with the null harness in a local subprocess runtime against
|
||||
# Prime Inference — the eval path end to end without a GPU or sandbox.
|
||||
num_examples = 4
|
||||
dashboard = false
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -135,5 +135,5 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
quantization = "fp8"
|
||||
quantization = "fp8_per_block"
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# AIME 2026 at avg@16: every problem 16 times with the null harness (one chat
|
||||
# completion per rollout) against Prime Inference. The math tasksets forbid the
|
||||
# agent any network, and only the sandboxed runtimes enforce that policy, so the
|
||||
# rollouts run in prime sandboxes (PRIME_API_KEY) rather than as subprocesses.
|
||||
# Competition math needs room to reason, so the completion budget is generous.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/aime2026.toml
|
||||
|
||||
group_size = 16
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 32768
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "aime26"
|
||||
env.agent.harness.id = "null"
|
||||
@@ -0,0 +1,20 @@
|
||||
# Multi env: 16 terminal-bench-2 tasks under two harnesses, bash and rlm, in prime
|
||||
# sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout each with
|
||||
# a ten-minute budget, against Prime Inference on the default model. One env server
|
||||
# per source; the sources share the taskset, so each carries its own name.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/multi-env.toml
|
||||
|
||||
num_examples = 16
|
||||
|
||||
[[source]]
|
||||
name = "tb2-bash"
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 600
|
||||
|
||||
[[source]]
|
||||
name = "tb2-rlm"
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.timeout.rollout = 600
|
||||
@@ -0,0 +1,12 @@
|
||||
# Single env, multi turn: 16 terminal-bench-2 tasks with the bash harness in
|
||||
# prime sandboxes (PRIME_API_KEY authenticates sandbox creation), one rollout
|
||||
# each, against Prime Inference on the default model.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/multi-turn.toml
|
||||
|
||||
num_examples = 16
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
@@ -0,0 +1,23 @@
|
||||
# Single env, resume: gsm8k with a low pinned concurrency so the run can be
|
||||
# interrupted partway. Relaunch with the same --run.name and --resume: the landed
|
||||
# episodes are restored from the trace stream and only the owed rollouts run.
|
||||
# Resuming a finished run restores everything and exits.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug
|
||||
# <Ctrl-C partway>
|
||||
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
|
||||
|
||||
num_examples = 8
|
||||
group_size = 2
|
||||
|
||||
[concurrency]
|
||||
min_inflight = 2
|
||||
max_inflight = 2
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -0,0 +1,15 @@
|
||||
# Single env, single turn: gsm8k with the null harness (one chat completion per
|
||||
# task, no sandbox) against Prime Inference.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/single-turn.toml
|
||||
|
||||
num_examples = 8
|
||||
group_size = 2
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -0,0 +1,13 @@
|
||||
# Terminal-Bench 2 at avg@4: every task 4 times with the bash harness in prime
|
||||
# sandboxes (PRIME_API_KEY authenticates sandbox creation) against Prime Inference.
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/tb2.toml
|
||||
|
||||
group_size = 4
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
env.agent.retries.max_retries = 2
|
||||
env.agent.retries.include = ["ProviderError", "SandboxError"]
|
||||
@@ -1,6 +1,6 @@
|
||||
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
|
||||
# The launcher spawns one env server per source at its derived address
|
||||
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
|
||||
# (each on an OS-assigned loopback port it publishes); the orchestrator connects to each.
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: 1f1e050ab0...1213b7336d
Vendored
+1
-1
Submodule deps/renderers updated: f91c3e7061...6b8da3f7b1
Vendored
+1
-1
Submodule deps/verifiers updated: 392d596de8...ceecc4d422
+1
-1
@@ -188,7 +188,7 @@ For large MoE serving, splitting prefill and decode onto separate vLLM groups ca
|
||||
| Agentic (SWE, Lean) | 3:1 | Long growing contexts → prefill-heavy |
|
||||
| Non-agentic (math, chat) | 1:2 | Short prompts, long generations → decode-heavy |
|
||||
|
||||
Example config: [`examples/advanced/glm-5.2/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.2/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.2/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2/infer).
|
||||
Example config: [`examples/advanced/glm-5.3/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-5.3/swe.toml) — full RL run on `GLM-5` with P/D disaggregation behind a `vllm-router`, FP8 inference, and NCCL weight broadcast, paired with an inference config from [`examples/advanced/glm-5.3/infer/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3/infer).
|
||||
|
||||
Monitor live queue depths to detect imbalance:
|
||||
|
||||
|
||||
+3
-3
@@ -112,7 +112,7 @@ patterns = ["WARNING"]
|
||||
def drop_warnings(rollout, *, patterns: list[str]) -> list[list[bool]]: ...
|
||||
```
|
||||
|
||||
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and aborts after repeated zero-trainable batches), not at config time.
|
||||
Component compatibility is validated at config time: frozen-model sampling can only feed the `ce` loss component — the `rl` and `ref_kl` components need the live policy's own sampling logprobs for importance ratios — `opd` pointed at `"policy"` is rejected as degenerate (zero KL), `sft` without a frozen source is rejected (CE on the policy's own tokens is not a distillation target). A group-relative algorithm with `group_size = 1` produces all-zero advantages; the resulting empty batch is caught at runtime (the orchestrator warns and skips it), not at config time.
|
||||
|
||||
### Per-Env Algorithms
|
||||
|
||||
@@ -209,9 +209,9 @@ The knobs under `[trainer.loss]` are:
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `eps` | 0.1 | Maximum absolute probability change before a token is masked. |
|
||||
| `eps` | 0.3 | Maximum absolute probability change before a token is masked. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
|
||||
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
| `kl_tau` | 0.0 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
|
||||
Omit `[trainer.loss]` to use these defaults. Set `type = "ipo"` when you specify the section. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
|
||||
|
||||
|
||||
@@ -171,7 +171,7 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
|
||||
`ratio` is a training-source field: it defaults to `1` (equal weight per env), and values are relative weights normalized to probabilities across envs. Eval sources of a training run carry `interval` instead, the step interval at which they fire (inherited from the group-level `interval` when unset); a standalone eval has neither.
|
||||
|
||||
Everything environment lives under the `env` block (verifiers' `[env]` shape): `env.taskset` configures the v1 taskset, and each agent is a field on the env — `env.agent.harness` selects how the single-agent env's tasks are run, and per-run caps are per-agent (`env.agent.max_turns`, `env.agent.timeout`, `env.agent.max_output_tokens`). A multi-agent env declares its own seats (`env.<role>.*`).
|
||||
|
||||
@@ -225,11 +225,11 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
|
||||
**Advanced** (32–2048 GPUs, SLURM):
|
||||
|
||||
- [**Qwen3-30B-A3B**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/qwen3-30b-a3b) — `Qwen3-30B-A3B` on math, SWE, and tool use.
|
||||
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal.
|
||||
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**GLM-4.5-Air**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-4.5-air) — `GLM-4.5-Air` on search, SWE, and terminal; includes a variant that trains the 100B+ MoE on only two nodes.
|
||||
- [**Nemotron-3-Super**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/nemotron-3-super) — `Nemotron-3-Super-120B` hybrid-Mamba MoE on SWE at 131k context.
|
||||
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/configs/advanced/minimax-m2.5) — `MiniMax-M2.5` on agentic SWE.
|
||||
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale `GLM-5`/`GLM-5.2` inference with P/D disaggregation and FP8.
|
||||
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale `GLM-5`/`GLM-5.3` inference with P/D disaggregation and FP8.
|
||||
|
||||
### Worked Example: Compose, Override, Dry-Run
|
||||
|
||||
|
||||
+1
-1
@@ -148,5 +148,5 @@ VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementatio
|
||||
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
|
||||
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
|
||||
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
|
||||
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
6. **Context parallelism (optional).** CP-capable VLMs hold a `CPContext` on all modules which need to be CP-aware and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
# Eval
|
||||
|
||||
This page covers `uv run eval` — evaluating a model in one or more environments. For the online evals of a training run, see [Training](training.md#online-evals).
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbook is at [`skills/eval/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/eval/SKILL.md).
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Launch](#launch)
|
||||
- [Configuration](#configuration)
|
||||
- [Resume](#resume)
|
||||
- [Monitors](#monitors)
|
||||
- [File](#file)
|
||||
- [Prime](#prime)
|
||||
- [Metrics](#metrics)
|
||||
|
||||
`uv run eval` runs one epoch of every configured source and exits. It reuses the orchestrator's eval pipeline: env servers are spawned per source, episodes are admitted under the concurrency controller, and every episode streams into the run's trace stream and metrics.
|
||||
|
||||
## Launch
|
||||
|
||||
By default the model is served by Prime Inference; authenticate with `PRIME_API_KEY` or `prime login`:
|
||||
|
||||
```bash
|
||||
uv run eval gsm8k -n 32 -r 4 -c 8 # Prime Inference
|
||||
uv run eval @ configs/debug/eval/single-turn.toml # the same shape as a TOML
|
||||
```
|
||||
|
||||
To evaluate a model you serve yourself, start a `uv run inference` vLLM server (or any OpenAI-compatible API) and point the client at it:
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-4B
|
||||
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1
|
||||
```
|
||||
|
||||
Single-source shorthands: `<taskset-id>` names the run's only source, `--env.<field> <value>` sets a field of that source's env block (`--env.agent.harness.id bash`, `--env.taskset.tasks '["fix-git"]'`), `-n`/`-r` set `num_examples`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). The shorthands cannot be combined with a TOML that defines `[[source]]` blocks. `uv run eval -h` lists them.
|
||||
|
||||
Against a local vLLM deployment, set `min_inflight < max_inflight` in `[concurrency]` to dynamically adjust the number of concurrent episodes for maximum throughput. An external API exposes no vLLM `/metrics` to adapt to, so pin the concurrency there (`-c N`, i.e. `min_inflight = max_inflight`).
|
||||
|
||||
## Configuration
|
||||
|
||||
Multi-source runs use a TOML (`EvalConfig` in `packages/prime-rl-configs/src/prime_rl/configs/eval.py`). The eval block is flattened to the top level — `[[source]]`, `[client]`, `[concurrency]`, `[sampling]`, `num_examples`, `group_size` — and each source takes the same `env` block as `[[orchestrator.eval.source]]`:
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
num_examples = 32
|
||||
group_size = 4
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[concurrency] # adaptive against a local vLLM deployment
|
||||
min_inflight = 8
|
||||
max_inflight = 256
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "bash"
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
Per-source `num_examples`, `group_size` and `sampling` override the top-level defaults. Every source's env server is spawned by the eval process unless the source sets `serve.address`, in which case the server is externally managed. A spawned server binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/eval/<name>.address`, which the eval process reads, so concurrent runs on one host never collide on a port.
|
||||
|
||||
## Resume
|
||||
|
||||
An interrupted run resumes from its trace stream. Relaunch with the same `--run.name` and `--resume`: the episodes that landed rejoin the epoch as if they had just arrived (stream, metrics and platform upload cover the whole epoch) and only the rollouts still owed run. Errored episodes and the ones the interruption cut off run again.
|
||||
|
||||
```bash
|
||||
uv run eval @ eval.toml --run.name my-eval
|
||||
# <interrupted>
|
||||
uv run eval @ eval.toml --run.name my-eval --resume
|
||||
```
|
||||
|
||||
The previous attempt's `monitors/file` is kept as `monitors/file.attempt_N`; the resumed attempt writes a fresh one. Nothing is deleted, and a resume reads every attempt's stream.
|
||||
|
||||
A landed episode counts toward the task with its `task.key`, so `num_examples` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The model, the sampling and each source's env must match the config the landed episodes were measured with (kept beside them in `monitors/file/eval.json`); a resume that changes them stops with the differing config paths. Rollouts that complete a task's landed group join that group, so pass@k and the dashboard see one group per task. Use `--clean` to start over instead.
|
||||
|
||||
## Monitors
|
||||
|
||||
Monitors receive the run's metrics and episodes through one abstraction. The file monitor is on by default; `--monitors.wandb` logs the run to Weights & Biases; `--monitors.prime` streams it to the Prime platform.
|
||||
|
||||
### File
|
||||
|
||||
The file monitor writes the run's metrics and trace stream under `output_dir / run.name / monitors/file/` and feeds the local [dashboard](training.md#dashboard). Env servers stream every rollout to the eval process as it happens: the trace's header when it is minted, then one delta per committed turn (the new messages and the model call behind them), per phase change (boot, setup, agent, finalize, scoring), and a preview of each model request's uncommitted messages, so a tool result shows the moment the model is asked about it rather than with the reply. The file monitor appends those deltas to `monitors/file/traces/live/<trace_id>.jsonl` and deletes the file when the episode lands in the finished trace stream, so that directory is exactly the live set and finished traces stay where they always were. The dashboard's traces tab shows live rollouts in the episode table itself: a pulsing dot in the `#` cell marks the row, a phase badge says where the rollout is (boot, setup, running, finalize, scoring), the `dispatched → arrived` column shows the dispatch time with the elapsed time in brackets, and the turn, token and branch counts grow as deltas land. The status filter toggles live and completed rows, and a live row opens in the trace viewer, which follows the rollout turn by turn (the transcript stays pinned to the newest turn until you scroll up; folded entries stay folded; the pending messages of the request in flight render dimmed with an `awaiting model` chip). The table and an open live trace poll once a second and transfer nothing while the rollout is unchanged. The progress line in `eval.log` counts the live rollouts by phase (`2 inflight episodes ... - boot 1 · running 1`). Read a live trace from a shell with `uv run python -m prime_rl.monitors.file.traces <run_dir> [<trace_id>]`. The same stream exists for RL runs, covering train and online-eval rollouts alike.
|
||||
|
||||
The dashboard's overview tab reads the trace stream directly. It shows one env at a time; the filter menu picks the env and whether errored episodes join the distributions. A block bar has one cell per expected episode: landed episodes (errored ones in red; click one to open it), live rollouts as pulsing outlines (click one to follow it), and the rest empty, with the percentage beside it. The expected count is what the eval runner wrote to `monitors/file/plan.json` when it counted the epoch's tasks. Below the bar, a summary row gives the headline numbers: avg@k and pass@k, the error and truncation rates (yellow past 10%, red past 50%), mean turns and branches in one tile, mean episode time and tokens, and the total cost when the run has costs; hover a tile for its distribution. The env's own rewards and metrics follow, a beeswarm pane each, resizable like the training charts. The usage section is one pane splitting each episode's tokens into input and output, and the timing section is the same pane over the phases of a rollout (boot, setup, model, harness, finalize, scoring, and `other` for wall time no phase accounts for): an icicle bar shows the mean split, one strip per episode below shows the split per rollout, and a legend sits above. Hovering a phase highlights it across the pane; the strips show 40 episodes by default and all of them on `show all`. A metric every episode shares appears as a chip instead of a pane, and a metric with only a few distinct values, such as a binary reward, as a counted dot plot with the count and share of each value. Every dot is an episode (or a task): hover it for its value and click it to open the trace; hover the pane's background for the summary (min, p10, median, p90, max), with a faint boxplot behind the dots. Errored episodes stay out of the distributions until the filter includes them, where they read red. The metrics tab charts every key of the run's `metrics.jsonl`: the epoch's `eval/<env>/…` summaries and the time-keyed `inference/` and `concurrency/` rows the runner samples while the epoch is in flight.
|
||||
|
||||
### Prime
|
||||
|
||||
`--monitors.prime` streams each source's epoch as an evaluation on the Prime platform:
|
||||
|
||||
```bash
|
||||
uv run eval gsm8k -n 32 -r 4 -c 8 --monitors.prime
|
||||
```
|
||||
|
||||
The monitor opens one platform evaluation per env when its epoch starts, streams every episode to it as it lands, and closes it with the epoch's aggregates. The run leaves its platform identity in `monitors/prime/run.json` (the training run's id and URL, or one entry per eval epoch), and the dashboard's top bar shows a `view on platform` link from the moment the evaluation opens: a direct link for a training run or a single evaluation, a menu when a run has several.
|
||||
|
||||
## Metrics
|
||||
|
||||
Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
|
||||
|
||||
| Metric | Reading |
|
||||
|---|---|
|
||||
| `eval/<env>/all/<agent>/reward/mean` | mean reward over the epoch |
|
||||
| `eval/<env>/all/<agent>/is_truncated/mean` | share of rollouts cut by the length limit |
|
||||
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
|
||||
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
|
||||
|
||||
Task-specific env metrics (e.g. `correct_answer`, `format`) appear under the same prefix. The console summary line per source (`Evaluated <env> ... Reward 0.8125`) reports the epoch mean.
|
||||
+5
-3
@@ -190,8 +190,10 @@ Both backends support the 2 most important things:
|
||||
- P/D disaggregation - handling the prefill and decode stages separately
|
||||
|
||||
### Routing policies
|
||||
The 2 policies you might want to configure are:
|
||||
- `consistent_hash` - this is the default policy that optimizes for KV cache re-use across turns - it hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica.
|
||||
The policies you might want to configure are:
|
||||
- `sticky_least_loaded` - the default policy. A new `X-Session-ID` is assigned to the least-loaded replica, then every later turn in that rollout remains on the same replica for KV cache reuse. The orchestrator releases sessions when rollouts complete, fail, or are cancelled, including traces discarded during retries. Failed release requests are logged without disabling future cleanup.
|
||||
|
||||
- `consistent_hash` - hashes the `X-Session-ID` request header (sent per rollout by the verifiers clients) to pick a replica, preserving KV cache reuse without considering current load.
|
||||
|
||||
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
|
||||
|
||||
@@ -285,7 +287,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o
|
||||
|
||||
Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.
|
||||
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.28 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.29 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"overview",
|
||||
"configuration",
|
||||
"training",
|
||||
"eval",
|
||||
"inference",
|
||||
"scaling",
|
||||
"algorithms",
|
||||
|
||||
+3
-2
@@ -232,8 +232,9 @@ gpus_per_node = 8
|
||||
|
||||
Full multi-node configs ship under [`examples/advanced/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced):
|
||||
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`glm-5.2/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.2) — large-scale and P/D-disaggregated inference across the GLM-5 family.
|
||||
- [`nemotron-3-super/swe.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/configs/advanced/nemotron-3-super/swe.toml) — 4 trainer + 1 inference node RL on a 120B hybrid-Mamba MoE with NCCL weight broadcast.
|
||||
- [`glm-5.3/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/advanced/glm-5.3) — large-scale and P/D-disaggregated inference across the GLM-5 family.
|
||||
- [`glm-4.5-air/swe-2-node.toml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/examples/advanced/glm-4.5-air/swe-2-node.toml) — train a 100B+ MoE on only two nodes: a single-node sign-SGD trainer (full optimizer offload) paired with one inference replica at batch size 64. An overlay on the shared `swe-budget.toml` base — launch with `uv run rl @ swe-budget.toml @ swe-2-node.toml`.
|
||||
|
||||
For inference-only multi-node, set `[deployment] type = "multi_node"` on an inference TOML — each node runs an independent vLLM replica (TP and DP must fit within one node), fronted by a single global router on node 0. Point clients at the router URL the launcher prints.
|
||||
|
||||
|
||||
+12
-9
@@ -1,6 +1,6 @@
|
||||
# Training
|
||||
|
||||
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md).
|
||||
This page covers everything you need to launch, observe, checkpoint, and recover a `prime-rl` training run — the RL trainer (and the distillation algorithms that run through it) and the SFT trainer. For multi-node and cluster layouts, see [Scaling](scaling.md). For the loss math and algorithm knobs, see [Algorithms](algorithms.md). For standalone evals, see [Eval](eval.md).
|
||||
|
||||
> **AI agents working in this repo:** the equivalent runbooks are at [`skills/training/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/skills/training) — top-level routing in [`skills/training/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/SKILL.md), launch details in [`skills/training/start-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/start-run/SKILL.md), and check-in / restart procedures in [`skills/training/monitor-run/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/training/monitor-run/SKILL.md).
|
||||
|
||||
@@ -37,7 +37,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
|
||||
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at a derived loopback address); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
|
||||
| `uv run eval` | Multi-env evals against a live inference server. | One epoch per source, pinned (or adaptive) concurrency, cursor checkpoints + `--resume`, dashboard + optional platform upload; see [Eval](eval.md). |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source; each binds an OS-assigned loopback port and publishes it to `configs/attempt_N/resolved/envs/<split>/<name>.address` for the orchestrator); only needed when running the orchestrator standalone, or for sources with an explicit `serve.address` — those are externally managed (e.g. their own k8s pod) and the launcher expects the server to already run there. |
|
||||
|
||||
## RL Trainer
|
||||
|
||||
@@ -161,6 +162,8 @@ name = "qwen3"
|
||||
enable_thinking = false
|
||||
```
|
||||
|
||||
A `reasoning_effort` column in the dataset sets the renderer's `reasoning_effort` field per row, on top of the `[renderer]` config. The column requires a typed renderer that has that field (for example `gpt-oss`, `qwen3.8`, `deepseek-v4`); rows with a null value use the configured renderer unchanged. This lets one run mix reasoning efforts, with the `[renderer]` value as the default for rows that do not set one.
|
||||
|
||||
If a model needs another template control, add it to that model's renderer config in `renderers` (for example a new field on the relevant `*RendererConfig`) and consume it in the renderer implementation.
|
||||
|
||||
**Renderer-backed tokenization.** SFT tokenization is renderer-only. The [`renderers`](algorithms.md#renderers) package owns message-to-token conversion and loss attribution end-to-end, so position-dependent chat templates (for example templates that strip past `<think>` blocks across user turns) do not corrupt the loss mask. `[renderer]` defaults to `name = "auto"`; set a typed renderer config only when you need model-specific template controls. Hand-coded renderers ship for Qwen3, Qwen3.5, GLM-5, GLM-4.5, Kimi K2/K2.5, MiniMax M2, DeepSeek V3, Nemotron 3, GPT-OSS, and VLM families such as Qwen3-VL/Qwen3.5.
|
||||
@@ -201,17 +204,17 @@ num_train_gpus = 1 # trainer
|
||||
num_infer_gpus = 1 # inference
|
||||
```
|
||||
|
||||
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
The launcher starts the inference server, one env server per eval source, and an online-eval process next to the trainer (it logs to `logs/attempt_<n>/eval.log`). NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the online-eval process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
|
||||
|
||||
#### Multi-Node Trainer and Inference Pool
|
||||
|
||||
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and evals process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
|
||||
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and online-eval process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
|
||||
|
||||
```toml
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 2 # trainer nodes
|
||||
num_infer_nodes = 1 # inference pool + evals
|
||||
num_infer_nodes = 1 # inference pool + online evals
|
||||
|
||||
[inference.vllm]
|
||||
tensor_parallel_size = 8
|
||||
@@ -220,7 +223,7 @@ tensor_parallel_size = 8
|
||||
job_name = "my-run"
|
||||
```
|
||||
|
||||
The shared script passes the trainer rank-0 hostname directly to the evals process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
|
||||
The shared script passes the trainer rank-0 hostname directly to the online-eval process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, online-eval never sees a final broadcast, so the job remains active until walltime. Trainer and online-eval log to one shared W&B run. The trainer creates it, and online-eval finalizes it.
|
||||
|
||||
### SFT-Specific Knobs
|
||||
|
||||
@@ -331,7 +334,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
|
||||
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
|
||||
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
|
||||
├── orchestrator.log # single instance, single file
|
||||
├── evals.log # SFT online-eval process
|
||||
├── eval.log # `uv run eval` process, or the SFT online-eval process
|
||||
├── inference.log # symlink → inference/node_0.log on multi-node
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node trainer stdout (multi-node only)
|
||||
@@ -347,14 +350,14 @@ Env logs are the first place to look for env-side errors (most user code lives t
|
||||
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
|
||||
|
||||
```bash
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,evals,inference}.log
|
||||
tail -F <run_dir>/logs/latest/{trainer,orchestrator,eval,inference}.log
|
||||
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
|
||||
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
|
||||
```
|
||||
|
||||
### Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with six views per run: an overview (the W&B overview sections, read from the file monitor's `metrics.jsonl`), metrics (every key in that file, one pane each, with a regex filter), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
|
||||
|
||||
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
|
||||
|
||||
|
||||
+33
-13
@@ -2,17 +2,37 @@
|
||||
|
||||
End-to-end usage examples for prime-rl, referenced from the top-level [README](../README.md).
|
||||
|
||||
- **[`basic/`](basic)** — walk-throughs for the core environments on 1–8 GPUs (baseline eval →
|
||||
optional SFT warmup → RL → eval), each with its own README:
|
||||
- `reverse-text` — smallest end-to-end loop (single-turn, 0.6B)
|
||||
- `alphabet-sort` — multi-turn, user simulator, LoRA
|
||||
- `wiki-search` — multi-turn tool calling, LoRA
|
||||
- `wordle` — multi-turn (~6-turn games)
|
||||
- `hendrycks-sanity` — single-turn math, long-running
|
||||
- `dynamo` — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
|
||||
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
|
||||
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
|
||||
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
|
||||
`intellect-3.1` (swe), `deepseek-v4-flash` (sft + a standalone vLLM serving pre-flight).
|
||||
New here? Follow [`basic/reverse-text/`](basic/reverse-text/README.md) first — it trains a small model end-to-end on 2 GPUs and introduces the launch → dashboard → checkpoint flow the advanced examples reuse.
|
||||
|
||||
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
## advanced/ — frontier models, multi-node
|
||||
|
||||
Larger runs on frontier models, one folder per model, each with a launch README covering requirements, credentials, launch, monitoring, and resume:
|
||||
|
||||
- [`qwen3-30b-a3b/`](advanced/qwen3-30b-a3b/README.md) — `Qwen3-30B-A3B` RL on math (`i3_math`), SWE (`r2e-gym`), and agentic tool use (general-agent on Modal). 2 train + 2 infer nodes; the SWE config runs at 131k context with `ep = 8` + `cp = 2`.
|
||||
- [`glm-4.5-air/`](advanced/glm-4.5-air/README.md) — `GLM-4.5-Air` (100B MoE) RL across search, SWE, and terminal domains at 131k context, with agents in sandboxes. 2 train + 4 infer nodes (SWE: 1 + 3).
|
||||
- [`glm-5.3/`](advanced/glm-5.3/README.md) — the GLM-5 family at scale: 16 trainer nodes, P/D-disaggregated FP8 inference, and an llm-d router + Mooncake KV-offload variant. Also ships standalone `infer/` pre-flights.
|
||||
- `intellect-3.1/` — reproduce the `INTELLECT-3.1` run: 4 train + 12 infer nodes on SWE.
|
||||
|
||||
All advanced configs submit through SLURM (the `rl` entrypoint writes the sbatch job when the config has a `[slurm]` table) and are monitored with `uv run dashboard`. See the per-model README for the full walkthrough.
|
||||
|
||||
## basic/ — 1 to 8 GPUs
|
||||
|
||||
Walk-throughs for the core environments (baseline eval → optional SFT warmup → RL → eval), each with its own README:
|
||||
|
||||
- [`reverse-text/`](basic/reverse-text/README.md) — smallest end-to-end loop (single-turn, 0.6B): `eval.toml` → `sft.toml` → `rl.toml`
|
||||
- [`alphabet-sort/`](basic/alphabet-sort/README.md) — multi-turn, user simulator, LoRA
|
||||
- [`wiki-search/`](basic/wiki-search/README.md) — multi-turn tool calling, LoRA
|
||||
- [`wordle/`](basic/wordle/README.md) — multi-turn (~6-turn games)
|
||||
- [`hendrycks-sanity/`](basic/hendrycks-sanity/README.md) — single-turn math, long-running
|
||||
|
||||
## extra/ — beyond the core loop
|
||||
|
||||
Examples that don't follow the basic eval → SFT → RL walk-through pattern:
|
||||
|
||||
- [`dynamo/`](extra/dynamo/README.md) — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
|
||||
- [`vlm/`](extra/vlm/README.md) — multimodal (VLM) SFT, dense + MoE LoRA configs
|
||||
|
||||
## Related config folders
|
||||
|
||||
- Frontier-model configs without launch walkthroughs (`minimax-m2.5`, `nemotron-3-super`, `deepseek-v4-flash`) live in [`configs/advanced/`](../configs/advanced).
|
||||
- Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# GLM-4.5-Air
|
||||
|
||||
RL on [`zai-org/GLM-4.5-Air`](https://huggingface.co/zai-org/GLM-4.5-Air) — a 100B MoE — at 131k context, across three agentic domains: web search, SWE, and terminal. Rollouts run in sandboxes ([Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default — see [Requirements](#requirements) for using your own), driven either by the `rlm` agent harness (with its `search` skill, or ipython-only) or a plain `bash` harness. All three configs share the same recipe: GRPO with a linear length penalty on input tokens (and turns, for SWE/terminal), the custom MoE trainer implementation with `cp = 4` (ulysses) context parallelism, router replay, NCCL weight broadcast, checkpoints every 50 steps (`keep_last = 1`), and evals every 20 steps (including step 0). The SWE configs also ship budget variants: `swe-4-node.toml` (1 train + 3 infer) and `swe-2-node.toml` — train a 100B+ MoE on only two nodes. Both are thin overlays on a shared `swe-budget.toml` base: the base holds the recipe, the overlay the topology, batch size, and per-run identity.
|
||||
|
||||
| Config | Trains on | Evals on | Topology |
|
||||
|---|---|---|---|
|
||||
| [`search.toml`](search.toml) | `openseeker` + `redsearcher` (search QA, `rlm` harness + `search` skill) | `browsecomp` (500 examples) | 2 train + 4 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 2 train + 4 infer nodes |
|
||||
| [`swe-budget.toml`](swe-budget.toml) + [`swe-4-node.toml`](swe-4-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 3 infer nodes |
|
||||
| [`swe-budget.toml`](swe-budget.toml) + [`swe-2-node.toml`](swe-2-node.toml) | `scaleswe` (`bash` harness) | `swebench-verified` | 1 train + 1 infer node |
|
||||
| [`terminal.toml`](terminal.toml) | `tmax` (per-task Docker image, `rlm` ipython harness) | `swebench-verified` + `terminal-bench-2` (avg@4) | 2 train + 4 infer nodes |
|
||||
|
||||
Inference serves the bf16 checkpoint as-is (no quantization), with `tensor_parallel_size = 8` (plus expert parallelism on `swe.toml`). `search.toml`, `swe.toml`, and `terminal.toml` train with Muon on 2 trainer nodes. The budget variants instead fit the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer; `swe-2-node.toml` cuts the batch size to 64 (4 groups of 16) to match the throughput of its single inference replica. They don't parse standalone: compose them left-to-right over `swe-budget.toml` (`uv run rl @ swe-budget.toml @ swe-2-node.toml`). Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes. These configs are wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. Install the `prime` CLI separately and log in. Each config's `slurm.pre_run_command` then cleans up the run's orphaned sandboxes by label before launch:
|
||||
|
||||
```bash
|
||||
uv tool install prime
|
||||
prime login # or: prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend) and drop the `slurm.pre_run_command` cleanup line.
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `HF_TOKEN` — `zai-org/GLM-4.5-Air` is a gated model.
|
||||
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
|
||||
- `SERPER_API_KEY` — search envs only; forwarded into the agent sandbox for the `search` skill (`harness.forward_env`).
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- `[slurm] partition` is set to `all` — override with `--slurm.partition <your-partition>`, or edit the config.
|
||||
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
|
||||
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--output-dir /shared/outputs/glm45air \
|
||||
--run.name glm45air-swe
|
||||
```
|
||||
|
||||
Swap `swe.toml` for `search.toml` or `terminal.toml` to run the other domains. For SWE on a smaller budget, compose a budget variant over its base: `uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml` trains the 100B+ MoE on only two nodes. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs/glm45air # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run (`<run_name>` from the launch) and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint, resume, export
|
||||
|
||||
Checkpoints land in `<run_dir>/checkpoints/step_<N>` every 50 steps (`keep_last = 1`). To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--output-dir /shared/outputs/glm45air \
|
||||
--run.name glm45air-swe \
|
||||
--resume --max-steps 1000
|
||||
```
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export HF-format weights with:
|
||||
|
||||
```bash
|
||||
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/glm45air/glm45air-swe/checkpoints/step_100
|
||||
```
|
||||
|
||||
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Budget variant of swe.toml: train a 100B+ MoE on only two nodes (1 train + 1 infer replica) with
|
||||
# the single-node sign-SGD trainer. Overlay for swe-budget.toml — this file only carries the
|
||||
# deltas, so compose the two (left-to-right merge, see docs/configuration.md "TOML Composition"):
|
||||
#
|
||||
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-2-node.toml
|
||||
#
|
||||
# The batch size is 64 (4 groups of 16), matching the rollout throughput of the single inference
|
||||
# replica. The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the
|
||||
# budget variants can run side by side.
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe-2-node"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-2-node" -y || true'
|
||||
|
||||
[deployment]
|
||||
num_infer_replicas = 1
|
||||
|
||||
[monitors.wandb]
|
||||
name = "glm45air-scaleswe-2-node"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 64
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe-2-node"]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe-2-node"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
@@ -0,0 +1,42 @@
|
||||
# Budget variant of swe.toml: the same recipe on four nodes (1 train + 3 infer replicas, the
|
||||
# topology swe.toml used before the Muon switch) with the single-node sign-SGD trainer. Overlay for
|
||||
# swe-budget.toml — this file only carries the deltas, so compose the two (left-to-right merge, see
|
||||
# docs/configuration.md "TOML Composition"):
|
||||
#
|
||||
# uv run rl @ examples/advanced/glm-4.5-air/swe-budget.toml @ examples/advanced/glm-4.5-air/swe-4-node.toml
|
||||
#
|
||||
# Batch size 256 (16 groups of 16) matches the rollout throughput of the three inference replicas.
|
||||
# The SLURM job name, sandbox cleanup label, and W&B run name are per-variant so the budget
|
||||
# variants can run side by side.
|
||||
|
||||
[slurm]
|
||||
job_name = "glm45air-swe-4-node"
|
||||
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
|
||||
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe-4-node" -y || true'
|
||||
|
||||
[deployment]
|
||||
num_infer_replicas = 3
|
||||
|
||||
[monitors.wandb]
|
||||
name = "glm45air-scaleswe-4-node"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 256
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "scaleswe"
|
||||
env.taskset.id = "scaleswe"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe-4-node"]
|
||||
|
||||
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm45air-swe-4-node"]
|
||||
env.agent.timeout.rollout = 3600
|
||||
@@ -0,0 +1,114 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Shared base of the budget variants of swe.toml
|
||||
# (`swe-4-node.toml`, `swe-2-node.toml`): the pre-Muon recipe with the single-node sign-SGD
|
||||
# trainer, composed as `uv run rl @ swe-budget.toml @ <variant>.toml`. Router replay is enabled
|
||||
# (trainer.enable_router_replay replays the routed-expert decisions returned by inference via
|
||||
# enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe model, which supports routed_experts.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# Inference serves the bf16 checkpoint as-is (no quantization). The trainer fits on one node via
|
||||
# cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus the
|
||||
# memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
|
||||
# skip-gather / skip-optimizer checkpointing. Concurrency is fully default: the controller derives
|
||||
# its start from the measured KV budget and adapts from there.
|
||||
#
|
||||
# The variant overlays on top of this base set the inference replica count and batch size, the
|
||||
# per-variant SLURM job name / sandbox cleanup label / W&B run name, and the train/eval sources
|
||||
# with their matching runtime labels.
|
||||
|
||||
max_steps = 1000
|
||||
seq_len = 131072
|
||||
|
||||
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
|
||||
# slow/contended shared-FS caches and FS lock deadlocks.
|
||||
[env_vars]
|
||||
TRITON_CACHE_DIR = "/tmp/.triton-cache"
|
||||
|
||||
[slurm]
|
||||
partition = "all"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_infer_nodes = 1
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
timeout = 3600
|
||||
|
||||
[ckpt]
|
||||
interval = 50
|
||||
keep_last = 1
|
||||
|
||||
[resume]
|
||||
|
||||
# --- Trainer ---
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 3600
|
||||
enable_router_replay = true
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-4.5-Air"
|
||||
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
[orchestrator]
|
||||
group_size = 16
|
||||
max_off_policy_steps = 32
|
||||
|
||||
[orchestrator.algo]
|
||||
type = "grpo"
|
||||
|
||||
[orchestrator.algo.length_penalty]
|
||||
type = "linear"
|
||||
num_output_tokens_weight = 0.0
|
||||
num_input_tokens_weight = 0.1
|
||||
num_turns_weight = 0.1
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-4.5"
|
||||
thinking_retention = "all"
|
||||
|
||||
# --- Inference ---
|
||||
|
||||
[inference]
|
||||
|
||||
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
|
||||
[inference.env_vars]
|
||||
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_return_routed_experts = true
|
||||
@@ -1,17 +1,18 @@
|
||||
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
|
||||
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
|
||||
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
|
||||
# a glm4_moe model, which supports routed_experts.
|
||||
# runtime; eval on SWE-Bench Verified. Follows the research-prod air ablation base config
|
||||
# (research-prod PR #198): 2 trainer nodes with the Muon optimizer (instead of the single-node
|
||||
# sign-SGD setup), 4 one-node inference replicas serving the bf16 checkpoint with TP=8 + expert
|
||||
# parallelism, batch size 256 / group size 16, and the linear length penalty with the input-token
|
||||
# and turns coefficients set to 0.1. Router replay stays enabled (trainer.enable_router_replay replays the routed-expert
|
||||
# decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is a glm4_moe
|
||||
# model, which supports routed_experts. Optimizer state is checkpointed so runs can resume.
|
||||
#
|
||||
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
# GRPO uses the linear length penalty. Each term is pass_rate-scaled and normalized by the
|
||||
# group's own max before the GRPO baseline subtraction.
|
||||
#
|
||||
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
|
||||
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
|
||||
# skip-gather / skip-optimizer checkpointing.
|
||||
# Two trainer nodes fit GLM-4.5-Air with Muon plus the memory improvements from the GLM-5.1 prod
|
||||
# run (research-prod rlm5/prod.toml): activation checkpointing (freq=1) + activation offloading
|
||||
# (max_inflight=1). LM-head token chunking (8192) and optimizer CPU offload run at their defaults.
|
||||
# Concurrency is fully default: the controller derives its start from the measured KV budget and
|
||||
# adapts from there.
|
||||
|
||||
@@ -31,9 +32,9 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 1
|
||||
num_train_nodes = 2
|
||||
num_infer_nodes = 1
|
||||
num_infer_replicas = 3
|
||||
num_infer_replicas = 4
|
||||
|
||||
[monitors.wandb]
|
||||
project = "swe-ablations"
|
||||
@@ -63,9 +64,6 @@ impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
optim_cpu_offload = false
|
||||
full_offload = true
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
|
||||
[trainer.model.ac]
|
||||
|
||||
@@ -74,11 +72,8 @@ max_inflight_activations = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "sign_sgd"
|
||||
type = "muon"
|
||||
|
||||
# --- Orchestrator ---
|
||||
|
||||
@@ -128,6 +123,8 @@ VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
|
||||
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
|
||||
|
||||
[inference.vllm]
|
||||
gpu_memory_utilization = 0.85
|
||||
max_model_len = 131072
|
||||
tensor_parallel_size = 8
|
||||
enable_expert_parallel = true
|
||||
enable_return_routed_experts = true
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
seq_len = 131072
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "glm5-pd-disag"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
port = 29502
|
||||
timeout = 12000
|
||||
quantize_in_weight_transfer = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 16
|
||||
gpus_per_node = 8
|
||||
num_infer_replicas = 2
|
||||
|
||||
[inference.deployment]
|
||||
type = "disaggregated"
|
||||
prefill_nodes_per_replica = 4
|
||||
decode_nodes_per_replica = 4
|
||||
|
||||
[inference.vllm]
|
||||
model = "zai-org/GLM-5-FP8"
|
||||
tool_call_parser = "glm47"
|
||||
gpu_memory_utilization = 0.80
|
||||
enable_expert_parallel = true
|
||||
enable_eplb = false
|
||||
[slurm]
|
||||
job_name = "glm5-pd-disag"
|
||||
|
||||
[ckpt]
|
||||
interval = 100
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 7200
|
||||
|
||||
[trainer.model]
|
||||
name = "zai-org/GLM-5"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # dsa is skipping flash attn anyway
|
||||
fused_lm_head_token_chunk_size = 2048
|
||||
ep = 8
|
||||
|
||||
[trainer.model.ac]
|
||||
freq = 1
|
||||
|
||||
[trainer.model.compile]
|
||||
|
||||
[trainer.model.ac_offloading]
|
||||
max_inflight_activations = 1
|
||||
|
||||
[trainer.ckpt]
|
||||
skip_optimizer = true
|
||||
|
||||
[trainer.optim]
|
||||
type = "adamw"
|
||||
lr = 1e-6
|
||||
weight_decay = 0.1
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 4096
|
||||
group_size = 16
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 4096
|
||||
max_inflight = 8192
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5-FP8"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swe-bench-verified"
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
|
||||
|
||||
[inference]
|
||||
# we need <0.85 bc glm5 layers are too large for 0.85
|
||||
use_deep_gemm = true
|
||||
@@ -0,0 +1,102 @@
|
||||
# GLM-5 family at scale
|
||||
|
||||
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5.3-BF16` for training and serving alike, quantized to per-block FP8 online on the vLLM side — at 131k context: 16 trainer nodes on the custom MoE implementation (expert + context parallelism) and P/D-disaggregated FP8 inference. The [`swe-llmd.toml`](swe-llmd.toml) append fronts the same inference plane with the [**llm-d**](https://llm-d.ai) router (Endpoint Picker + Envoy): its `active-request-scorer` load-balances in flight — instead of reacting to delayed metrics like the default `vllm-router` — which, combined with prefix-cache affinity for grouped rollouts, keeps prefill and decode ranks evenly loaded under RL's bursty request pattern. It also offloads KV to a Mooncake distributed CPU pool (1TB per node by default).
|
||||
|
||||
| Config | What it runs | Topology |
|
||||
|---|---|---|
|
||||
| [`swe.toml`](swe.toml) | Base GLM-5.3 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), serves `GLM-5.3-BF16` with online per-block FP8 quantization behind the default `vllm-router`. | 16 train + 16 infer nodes |
|
||||
| [`swe-llmd.toml`](swe-llmd.toml) | Append for `swe.toml`: swaps in the llm-d router (EPP scorer tuning) + Mooncake KV offload — launch as `rl @ swe.toml @ swe-llmd.toml`. | same |
|
||||
| [`infer/pd.toml`](infer/pd.toml) | Inference-only pre-flight: P/D-disaggregated `GLM-5-FP8`. | 6 infer nodes |
|
||||
| [`infer/pd-llmd.toml`](infer/pd-llmd.toml) | Inference-only pre-flight: `GLM-5.2-FP8` with llm-d + Mooncake. | 16 infer nodes |
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes, a shared filesystem, and at least **32 nodes** (16 trainer + 16 inference) for the RL configs. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path. If you have fewer nodes, drop `seq_len`, lower `num_train_nodes`, and reduce `cp` accordingly.
|
||||
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d append).
|
||||
- **Sandboxes.** Rollout and eval agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
|
||||
|
||||
```bash
|
||||
uv tool install prime
|
||||
prime login # or: prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on each source for a runtime your environments support (e.g. a local Docker backend).
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `HF_TOKEN` — the GLM-5 family checkpoints are gated models.
|
||||
- `WANDB_API_KEY` — both RL variants log to W&B (`[monitors.wandb]`).
|
||||
|
||||
### Install llm-d (llm-d append only)
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- `swe.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`.
|
||||
- `swe-llmd.toml` `[inference.kv_cache_offload] device_name` — the RDMA NIC list for Mooncake. Auto-detection is unreliable; set it by hand from `nvidia-smi topo -m` on your nodes.
|
||||
- `swe-llmd.toml` `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
# GLM-5.3 RL behind the default vllm-router
|
||||
uv run rl @ examples/advanced/glm-5.3/swe.toml
|
||||
|
||||
# with the llm-d router + Mooncake KV offload appended
|
||||
uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
|
||||
```
|
||||
|
||||
The inference configs are standalone pre-flights: they serve the FP8 checkpoint through the same entrypoint the trainer uses (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster` included — never call `vllm serve` directly), and are a fast way to check that this cluster can serve the model at all before committing it to a run:
|
||||
|
||||
```bash
|
||||
uv run inference @ examples/advanced/glm-5.3/infer/pd.toml
|
||||
uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
|
||||
```
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint and resume
|
||||
|
||||
Both RL configs ship without `[ckpt]` — add a `[ckpt]` overlay (e.g. `interval = 100`) for periodic checkpoints. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, a stable `--run.name`, and a `--max-steps` at least the target final step. Trainer checkpoints are DCP-sharded; export HF-format weights with `tools/convert_dcp_to_bf16.py`. See [Training](../../../docs/training.md) for the full resume and export reference.
|
||||
|
||||
See [Scaling](../../../docs/scaling.md) for SLURM details and [Inference](../../../docs/inference.md) for the disaggregated-inference and router reference.
|
||||
+1
-2
@@ -2,7 +2,7 @@
|
||||
# Step 3 / goal target. Topology mirrors the proven original glm5.1_llmd_inference
|
||||
# (job 348 succeeded): 8 prefill nodes (4 replicas x 2) + 8 decode nodes (1 replica).
|
||||
#
|
||||
# Launch: uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
|
||||
# Launch: uv run inference @ examples/advanced/glm-5.3/infer/pd-llmd.toml
|
||||
|
||||
output_dir = "/shared/outputs/glm5.2-16node-llmd"
|
||||
|
||||
@@ -60,5 +60,4 @@ reasoning_parser = "glm45"
|
||||
gpu_memory_utilization = 0.75
|
||||
enable_expert_parallel = true
|
||||
enable_eplb = false
|
||||
enable_ep_weight_filter = true
|
||||
safetensors_load_strategy = "prefetch"
|
||||
@@ -0,0 +1,47 @@
|
||||
# llm-d append for swe.toml: fronts the P/D-disaggregated inference plane with
|
||||
# the llm-d router (Endpoint Picker + Envoy) and offloads KV to a Mooncake
|
||||
# distributed CPU pool. Everything else is inherited from the base config:
|
||||
#
|
||||
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
|
||||
|
||||
[run]
|
||||
name = "glm5-llmd"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "glm5-llmd"
|
||||
|
||||
[slurm]
|
||||
job_name = "glm5-llmd"
|
||||
|
||||
# Overlays replace arrays of tables wholesale, so the train source is spelled
|
||||
# out again just to swap the sandbox runtime label.
|
||||
[[orchestrator.train.source]]
|
||||
name = "r2e"
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.runtime.labels = ["glm5-llmd"]
|
||||
|
||||
[inference.router]
|
||||
type = "llm-d"
|
||||
|
||||
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
|
||||
|
||||
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
|
||||
"prefix-cache-scorer" = 3.0
|
||||
|
||||
[inference.router.prefill_scorer_overrides] # 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
|
||||
"queue-scorer" = 4.0
|
||||
"active-request-scorer" = 5.0
|
||||
|
||||
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
|
||||
"active-request-scorer" = 5.0
|
||||
"kv-cache-utilization-scorer" = 4.0
|
||||
"queue-scorer" = 3.0
|
||||
|
||||
[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
|
||||
@@ -1,23 +1,29 @@
|
||||
# Base GLM-5.3 RL config: P/D-disaggregated FP8 inference behind the default
|
||||
# vllm-router. Serves the same GLM-5.3-BF16 checkpoint the trainer broadcasts,
|
||||
# quantized to per-block FP8 online on the vLLM side. Append swe-llmd.toml to
|
||||
# front the same plane with the llm-d router + Mooncake KV offload:
|
||||
#
|
||||
# uv run rl @ examples/advanced/glm-5.3/swe.toml @ examples/advanced/glm-5.3/swe-llmd.toml
|
||||
|
||||
max_steps = 10000000
|
||||
seq_len = 131072
|
||||
output_dir = "/shared/outputs" # FILL IN: point at your shared filesystem
|
||||
clean = true
|
||||
|
||||
[run]
|
||||
name = "glm5-llmd"
|
||||
name = "glm5"
|
||||
|
||||
[log]
|
||||
level = "debug"
|
||||
|
||||
[monitors.wandb]
|
||||
project = "glm5-llmd"
|
||||
project = "glm5"
|
||||
name = "base"
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
port = 29502
|
||||
timeout = 12000
|
||||
quantize_in_weight_transfer = true
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
@@ -52,41 +58,30 @@ num_decode_replicas = 1
|
||||
"max_num_seqs" = 96
|
||||
|
||||
[inference.router]
|
||||
type = "llm-d"
|
||||
|
||||
non_cached_tokens = 128 # if <128 tokens, skip prefill go to decode immediately
|
||||
|
||||
[inference.router.scorers] # need some prefix-cache routing, however due to shared mooncake pool do low prio
|
||||
"prefix-cache-scorer" = 3.0
|
||||
|
||||
[inference.router.prefill_scorer_overrides] # 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
|
||||
"queue-scorer" = 4.0
|
||||
"active-request-scorer" = 5.0
|
||||
|
||||
[inference.router.decode_scorer_overrides] # decode doesn't really create queue, it fills in KV cache fast, give 4.0
|
||||
"active-request-scorer" = 5.0
|
||||
"kv-cache-utilization-scorer" = 4.0
|
||||
"queue-scorer" = 3.0
|
||||
type = "vllm-router"
|
||||
|
||||
[inference.vllm]
|
||||
model = "zai-org/GLM-5.1-FP8"
|
||||
# Serve the same GLM-5.3-BF16 checkpoint the trainer broadcasts; vLLM quantizes
|
||||
# it to per-block FP8 online.
|
||||
model = "zai-org/GLM-5.3-BF16"
|
||||
dtype = "bfloat16"
|
||||
quantization = "fp8_per_block"
|
||||
max_model_len = 131072
|
||||
tool_call_parser = "glm47"
|
||||
reasoning_parser = "glm45"
|
||||
gpu_memory_utilization = 0.75
|
||||
enable_expert_parallel = true
|
||||
enable_eplb = false
|
||||
enable_ep_weight_filter = true
|
||||
safetensors_load_strategy = "prefetch"
|
||||
[slurm]
|
||||
job_name = "glm5-llmd"
|
||||
job_name = "glm5"
|
||||
partition = "all" # FILL IN: set to your cluster's partition
|
||||
|
||||
[trainer]
|
||||
dist_timeout_seconds = 1800
|
||||
|
||||
[trainer.model]
|
||||
name = "zai-org/GLM-5.1"
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2" # ignored with GLM5
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
@@ -122,10 +117,10 @@ initial_inflight = 256
|
||||
max_inflight = 512
|
||||
|
||||
[orchestrator.model]
|
||||
name = "zai-org/GLM-5.1-FP8"
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "glm-5.1"
|
||||
name = "glm-5.3"
|
||||
clear_thinking = false
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
@@ -138,17 +133,9 @@ clear_thinking = false
|
||||
name = "r2e"
|
||||
env.taskset.id = "r2e-gym"
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.runtime.labels = ["glm5-llmd"]
|
||||
env.agent.runtime.labels = ["glm5"]
|
||||
|
||||
[inference]
|
||||
# <0.80 because glm5 layers are too large for 0.85
|
||||
use_deep_gemm = true
|
||||
enable_fp32_lm_head = true
|
||||
|
||||
[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
|
||||
@@ -0,0 +1,107 @@
|
||||
# Qwen3-30B-A3B
|
||||
|
||||
RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The Thinking checkpoint trains math and SWE; the tool config trains the Instruct checkpoint with colocated tools on [Modal](https://modal.com). All configs use the custom MoE trainer implementation with expert parallelism (`ep = 8`), the AdamW optimizer, NCCL weight broadcast, and W&B logging. `swe.toml` adds `cp = 2` context parallelism for its 131k context; the other two run at 32k.
|
||||
|
||||
| Config | Trains on | Evals on | Runtime | Topology |
|
||||
|---|---|---|---|---|
|
||||
| [`math.toml`](math.toml) | `i3_math` | `aime2025` (every 25 steps) | `subprocess` — runs locally, no sandbox | 2 train + 2 infer nodes |
|
||||
| [`swe.toml`](swe.toml) | `r2e-gym` (`bash` harness) | `swebench-verified` (every 25 steps) | sandbox (Prime Intellect by default) | 2 train + 2 infer nodes |
|
||||
| [`tool.toml`](tool.toml) | `general-agent` (colocated tools) | — | `modal` | 1 train + 1 infer node |
|
||||
|
||||
`tool.toml` is the odd one out: 400 steps, `group_size = 16`, checkpoints every 50 steps with `keep_last = 1`, and inference at `dp = 2` / `tp = 4`. `math.toml` and `swe.toml` run 512-task batches with checkpoints every 100 steps.
|
||||
|
||||
## Requirements
|
||||
|
||||
- A Slurm cluster with 8-GPU nodes and a shared filesystem. This guide assumes the shared filesystem is mounted at `/shared` — adjust to your own path.
|
||||
- **Sandboxes** (`swe.toml` only) — the SWE agents run in sandboxes, wired for [Prime Intellect Sandboxes](https://docs.primeintellect.ai/sandboxes/overview) by default. If you use those, install the `prime` CLI separately and log in:
|
||||
|
||||
```bash
|
||||
uv tool install prime
|
||||
prime login # or: prime config set-api-key <your-key>
|
||||
```
|
||||
|
||||
To run on your own infrastructure instead, swap `env.agent.runtime` on the source for a runtime your environments support (e.g. a local Docker backend).
|
||||
- **Modal** (`tool.toml` only) — the tool agents run on Modal (`env.agent.runtime.type = "modal"`). Authenticate once:
|
||||
|
||||
```bash
|
||||
uv run modal setup # or export MODAL_TOKEN_ID / MODAL_TOKEN_SECRET
|
||||
```
|
||||
|
||||
- Environment variables, exported in the shell you launch from — the launcher passes its environment to every component:
|
||||
|
||||
- `WANDB_API_KEY` — every config logs to W&B (`[monitors.wandb]`).
|
||||
- `HF_TOKEN` — optional; the Qwen checkpoints are public, but a token avoids rate limits.
|
||||
|
||||
`math.toml` needs none of the above beyond W&B: its agents run as local subprocesses on the env server.
|
||||
|
||||
## Setup
|
||||
|
||||
Clone prime-rl onto the shared filesystem and install everything, including the environments — they are opt-in uv workspace members, so `--all-packages` is required:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
|
||||
cd /shared/prime-rl
|
||||
git submodule update --init -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
|
||||
uv sync --all-extras --all-packages
|
||||
```
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- None of the configs set a `[slurm] partition` — sbatch picks your cluster default. Override with `--slurm.partition <your-partition>`.
|
||||
- `--output-dir` defaults to `outputs/` next to the checkout; on a cluster, point it at the shared filesystem.
|
||||
- Validate the full config without submitting a job by appending `--dry-run`: it writes `<run_dir>/launcher/rl.sbatch` plus the resolved per-process configs, and exits.
|
||||
|
||||
## Start the run
|
||||
|
||||
The `rl` entrypoint submits an sbatch job whenever the config has a `[slurm]` table — there is no separate launcher. From the shared checkout:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
|
||||
--output-dir /shared/outputs/qwen30b \
|
||||
--run.name qwen30b-math
|
||||
```
|
||||
|
||||
Swap `math.toml` for `swe.toml` or `tool.toml` to run the other domains. Pass `--run.name`: the run directory is `<output_dir>/<run_name>` and you need a stable name to resume later (unset, it auto-generates as `<envs>--<model>--<short-id>`).
|
||||
|
||||
## Monitor with the dashboard
|
||||
|
||||
Start the local run dashboard on the head node — it only reads the run directories, so it is safe to point at a live run while the job is training:
|
||||
|
||||
```bash
|
||||
uv run dashboard /shared/outputs/qwen30b # serves http://localhost:7788
|
||||
```
|
||||
|
||||
If the head node is remote, forward the port from your laptop and open `http://localhost:7788` in a browser:
|
||||
|
||||
```bash
|
||||
ssh -L 7788:localhost:7788 <head-node>
|
||||
```
|
||||
|
||||
Pick the run and you get five views:
|
||||
|
||||
- **Metrics** — the W&B-style overview, read from the run's `metrics.jsonl`. Watch `reward/{all,env}/mean` trend upward over steps, and `seq_len/*` + `is_truncated/*` for rollout health.
|
||||
- **Configs** — the launch TOML next to the merged, resolved per-process configs the run actually started with.
|
||||
- **Trace** — a per-episode rollout viewer with per-token overlays (advantage, entropy, sampling mismatch, loss/content masks), showing the transcript, a wall-clock timeline of the rollout, a terminal replay of model and tool activity, and a semantic graph of the model-call chain.
|
||||
- **Logs** — the merged component logs (trainer, orchestrator, inference), also on disk under `<run_dir>/logs/`.
|
||||
- **Reports** — markdown reports written to `<run_dir>/reports/`, if any tooling produces them.
|
||||
|
||||
Pass several output directories to track parallel experiments side by side (`uv run dashboard /shared/outputs/a /shared/outputs/b`); a taken port automatically bumps to the next free one. SLURM stdout/stderr and the generated sbatch script land in `<run_dir>/launcher/`.
|
||||
|
||||
## Checkpoint, resume, export
|
||||
|
||||
Checkpoints land in `<run_dir>/checkpoints/step_<N>` — every 100 steps for `math.toml`/`swe.toml`, every 50 steps (`keep_last = 1`) for `tool.toml`. To resume, re-run the same command with `--resume` (latest checkpoint) or `--resume.step <N>`, the same `--run.name` / `--output-dir`, and a `--max-steps` at least the target final step:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/advanced/qwen3-30b-a3b/math.toml \
|
||||
--output-dir /shared/outputs/qwen30b \
|
||||
--run.name qwen30b-math \
|
||||
--resume --max-steps 1000
|
||||
```
|
||||
|
||||
Trainer checkpoints are DCP-sharded; export HF-format weights with:
|
||||
|
||||
```bash
|
||||
uv run python tools/convert_dcp_to_bf16.py /shared/outputs/qwen30b/qwen30b-math/checkpoints/step_100
|
||||
```
|
||||
|
||||
See [Training](../../../docs/training.md) for the full knobs and metrics reference, and [Scaling](../../../docs/scaling.md) for SLURM and multi-node details.
|
||||
@@ -39,14 +39,7 @@ uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
|
||||
Evaluate the base model:
|
||||
```bash
|
||||
# Run this in the other terminal
|
||||
uv run eval alphabet-sort --harness.id null \
|
||||
-m Qwen/Qwen3-4B-Instruct-2507 \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
-n 20 \
|
||||
-r 3 \
|
||||
--sampling.max-tokens 768 \
|
||||
--args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}' \
|
||||
--no-push
|
||||
uv run eval @ examples/basic/alphabet-sort/eval.toml
|
||||
```
|
||||
|
||||
We got an **average reward of ~0.26** across 20×3 rollouts. The model achieves **0% perfect attempts** (no rollouts score 1.0) and **0% perfect examples** (no examples have all 3 rollouts at 1.0). The model shows high variance and struggles on most examples, with the high similarity power (8) heavily penalizing even small errors, and the scores aren't different for most attempts.
|
||||
@@ -113,14 +106,7 @@ uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruc
|
||||
|
||||
```bash
|
||||
# Run this in the other terminal
|
||||
uv run eval alphabet-sort --harness.id null \
|
||||
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
-n 20 \
|
||||
-r 3 \
|
||||
--sampling.max-tokens 768 \
|
||||
--args '{"min_turns": 3, "max_turns": 3, "min_names_per_turn": 1, "max_names_per_turn": 4, "task": {"similarity_power": 8, "power_per_turn": false}}' \
|
||||
--no-push
|
||||
uv run eval @ examples/basic/alphabet-sort/eval.toml -m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
|
||||
```
|
||||
|
||||
Way better! Our model now gets an **average reward of ~0.81** with **73% perfect attempts** (44/60 rollouts score 1.0) and **65% perfect examples** (13/20 examples have all 3 rollouts at 1.0).
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Evaluate a model on alphabet-sort against a local inference server
|
||||
# (`uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507`).
|
||||
# Override the model with `-m` to evaluate a trained checkpoint.
|
||||
#
|
||||
# uv run eval @ examples/basic/alphabet-sort/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[[source]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset.id = "alphabet-sort"
|
||||
env.taskset.min_turns = 3
|
||||
env.taskset.max_turns = 5
|
||||
env.taskset.task.power_per_turn = false
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -27,7 +27,7 @@ uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
|
||||
```bash
|
||||
# Run this in the other terminal
|
||||
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
uv run eval @ examples/basic/reverse-text/eval.toml
|
||||
```
|
||||
|
||||
This is of course just a quick vibe check and no full-fledged evaluation, but we can see that the model struggles with this task. In this specific instance, we got an **average reward of ~0.05** across the 20x3 rollouts. Let's do some training!
|
||||
@@ -94,7 +94,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
|
||||
|
||||
```bash
|
||||
# Run this in the other terminal
|
||||
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
uv run eval @ examples/basic/reverse-text/eval.toml -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
|
||||
```
|
||||
|
||||
Way better! Now we get an **average reward of ~0.8**.
|
||||
@@ -197,10 +197,9 @@ kubectl exec -it my-exp-inference-0 -- bash
|
||||
uv run inference --vllm.model /data/outputs/weights_hf/step_20
|
||||
|
||||
# Back in trainer pod, run evaluation
|
||||
uv run eval reverse-text --harness.id null \
|
||||
uv run eval @ examples/basic/reverse-text/eval.toml \
|
||||
-m /data/outputs/weights_hf/step_20 \
|
||||
--client.base-url $INFERENCE_URL \
|
||||
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
--client.base-url $INFERENCE_URL
|
||||
```
|
||||
|
||||
### Clean Up
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Evaluate a model on reverse-text against a local inference server
|
||||
# (`uv run inference --vllm.model Qwen/Qwen3-0.6B`). Override the model
|
||||
# with `-m` to evaluate a trained checkpoint.
|
||||
#
|
||||
# uv run eval @ examples/basic/reverse-text/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-0.6B"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[source]]
|
||||
name = "reverse-text"
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -77,13 +77,7 @@ Evaluate the base model:
|
||||
|
||||
```bash
|
||||
# Run this in the other terminal
|
||||
uv run eval wiki-search --harness.id null \
|
||||
-m Qwen/Qwen3-4B-Instruct-2507 \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
-n 20 \
|
||||
-r 3 \
|
||||
--sampling.max-tokens 512 \
|
||||
--no-push
|
||||
uv run eval @ examples/basic/wiki-search/eval.toml
|
||||
```
|
||||
|
||||
## RL Training
|
||||
@@ -116,13 +110,7 @@ uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSe
|
||||
|
||||
```bash
|
||||
# Run this in the other terminal
|
||||
uv run eval wiki-search --harness.id null \
|
||||
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
|
||||
--client.base-url http://localhost:8000/v1 \
|
||||
-n 20 \
|
||||
-r 3 \
|
||||
--sampling.max-tokens 512 \
|
||||
--no-push
|
||||
uv run eval @ examples/basic/wiki-search/eval.toml -m <user>/Qwen3-4B-Instruct-WikiSearch-RL
|
||||
```
|
||||
|
||||
## Taskset Configuration
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Evaluate a model on wiki-search against a local inference server
|
||||
# (`uv run inference --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes`).
|
||||
# Override the model with `-m` to evaluate a trained checkpoint.
|
||||
#
|
||||
# uv run eval @ examples/basic/wiki-search/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[[source]]
|
||||
name = "wiki-search"
|
||||
env.taskset.id = "wiki-search"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
@@ -29,7 +29,7 @@ Then, use the `eval` entrypoint to evaluate the model in the `wordle` environmen
|
||||
|
||||
```bash
|
||||
# Run this in the other terminal
|
||||
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
uv run eval @ examples/basic/wordle/eval.toml
|
||||
```
|
||||
|
||||
We got an **average reward of ~0.2** across the 20x3 rollouts. From the summary, we can see that the most of the reward is coming from format and partial rewards. In fact, the model does not guess the correct word within any game, leading to a win rate of **0%**. Looking at some samples, it is evident repeatedly submitting guesses in the wrong format and is not able to revise its strategy from the environment feedback. Let's do some SFT warmup to get the model to learn the format of the environment.
|
||||
@@ -97,7 +97,7 @@ uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
|
||||
|
||||
```bash
|
||||
# Run this in the other terminal
|
||||
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
|
||||
uv run eval @ examples/basic/wordle/eval.toml -m PrimeIntellect/Qwen3-1.7B-Wordle-RL
|
||||
```
|
||||
|
||||
Way better! Our model now wins **~60%** and gets an average reward of **~1.5**.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Evaluate a model on wordle against a local inference server
|
||||
# (`uv run inference --vllm.model Qwen/Qwen3-1.7B`). Override the model
|
||||
# with `-m` to evaluate a trained checkpoint.
|
||||
#
|
||||
# uv run eval @ examples/basic/wordle/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-1.7B"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[[source]]
|
||||
name = "wordle"
|
||||
env.taskset.id = "wordle"
|
||||
env.player.harness.id = "null"
|
||||
env.player.runtime.type = "subprocess"
|
||||
@@ -1,32 +0,0 @@
|
||||
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
|
||||
# against DeepSeek V4 Flash on Prime Inference.
|
||||
#
|
||||
# export PRIME_API_KEY=<your Prime Inference key>
|
||||
# uv run evals @ examples/evals/swe.toml
|
||||
#
|
||||
# The tasksets run in prime sandboxes (the default runtime), so the key also
|
||||
# authenticates sandbox creation. External API endpoints expose no vLLM
|
||||
# /metrics, so adaptive concurrency has no load signal - the band must be
|
||||
# pinned (min_inflight = max_inflight) or the evals process refuses to start.
|
||||
|
||||
model = "deepseek/deepseek-v4-flash"
|
||||
|
||||
[eval.client]
|
||||
base_url = "https://api.pinference.ai/api/v1"
|
||||
api_key_var = "PRIME_API_KEY"
|
||||
|
||||
[eval.concurrency]
|
||||
min_inflight = 32
|
||||
max_inflight = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "swebench-verified"
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
|
||||
[[eval.source]]
|
||||
name = "terminal-bench-2"
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.timeout.rollout = 3600
|
||||
@@ -67,7 +67,7 @@ discovery_url = "http://dynamo.example:9000"
|
||||
After both endpoint checks pass, run Prime-RL from the repository in a third terminal. With no managed `[inference]` section, Prime-RL assigns GPU 0 to its single trainer process and leaves the external Dynamo worker on GPU 1:
|
||||
|
||||
```bash
|
||||
uv run rl @ examples/basic/dynamo/rl.toml
|
||||
uv run rl @ examples/extra/dynamo/rl.toml
|
||||
```
|
||||
|
||||
The example stops after five optimizer steps. Outputs are written under `outputs/` unless `output_dir` is overridden.
|
||||
@@ -0,0 +1,22 @@
|
||||
# VLM SFT
|
||||
|
||||
Multimodal (VLM) supervised fine-tuning configs, dense and MoE. VLM training requires a custom PrimeRL implementation (`impl = "custom"`, `[model.vlm]` set — see [Advanced § Multimodal Training](../../../docs/advanced.md#multimodal-training)); these configs use the Qwen3.5 dense and Qwen3.6 MoE VLM implementations. Both LoRA-finetune with a frozen vision encoder and assistant-only loss masking.
|
||||
|
||||
| Config | Model | Hardware |
|
||||
|---|---|---|
|
||||
| [`sft.toml`](sft.toml) | `Qwen/Qwen3.5-0.8B` (dense, LoRA rank 16) | tiny — sanity-scale (20 steps) |
|
||||
| [`sft-moe.toml`](sft-moe.toml) | `Qwen/Qwen3.6-35B-A3B` (MoE, LoRA rank 32, `ep = 8`) | one 8-GPU node (`num_train_gpus = 8`) |
|
||||
|
||||
## Run it
|
||||
|
||||
Point `data.name` at your multimodal chat dataset (HF dataset with a `messages` column — see [Training § Dataset Format](../../../docs/training.md#dataset-format)), then:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/extra/vlm/sft.toml
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- The MoE config declares `[deployment]` with `num_train_gpus = 8`; keep its `ep` in sync with the GPU count.
|
||||
- `micro_batch_size = 1` is required for VLM SFT — do not raise it.
|
||||
- Checkpoints land in `<run_dir>/checkpoints/step_<N>`; export HF-format weights with `tools/convert_dcp_to_bf16.py` (see [Training](../../../docs/training.md)).
|
||||
@@ -34,10 +34,7 @@ micro_batch_size = 1 # required for VLM SFT
|
||||
seq_len = 16384
|
||||
|
||||
[data.loss_mask]
|
||||
system = false
|
||||
user = false
|
||||
assistant = true
|
||||
tool = false
|
||||
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -29,5 +29,8 @@ batch_size = 1
|
||||
micro_batch_size = 1
|
||||
seq_len = 16384
|
||||
|
||||
[data.loss_mask]
|
||||
assistant = true # only assistant turns contribute to the loss; system/user/tool default to false
|
||||
|
||||
[optim]
|
||||
lr = 1e-5
|
||||
@@ -9,8 +9,8 @@ from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
"""``uv run env-server``: what to serve (``[env]``) and how it's hosted (``[serve]``).
|
||||
The ``rl`` launcher writes one of these per train/eval source, with ``serve.address``
|
||||
set to the source's derived address."""
|
||||
The launchers write one of these per train/eval source they manage, with
|
||||
``address_file`` set: the server binds an OS-assigned port and publishes it there."""
|
||||
|
||||
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
|
||||
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
@@ -18,6 +18,11 @@ class EnvServerConfig(BaseConfig):
|
||||
serve: vf.ServeConfig = vf.ServeConfig()
|
||||
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
|
||||
|
||||
address_file: Path | None = None
|
||||
"""Publish the bound address to this file once serving. Set by the launchers for the
|
||||
servers they spawn, so the address never has to be agreed on up front (``serve.address``
|
||||
unset binds an OS-assigned port)."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
|
||||
class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Eval sources run against a live inference server: the server's client and the
|
||||
adaptive concurrency band."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
"""Client of the inference server evals run against."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
"""Adaptive in-flight episode concurrency, sized by the same controller as
|
||||
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
Same contract as ``OrchestratorConfig.env_addresses``: an explicit ``serve.address``
|
||||
is an externally managed server; None means the launcher spawns the server and the
|
||||
eval learns its address from the file it publishes."""
|
||||
return {("eval", source.resolved_name): source.serve.address for source in self.source}
|
||||
|
||||
|
||||
PRIME_INFERENCE_URL = "https://api.pinference.ai/api/v1"
|
||||
|
||||
|
||||
class EvalConfig(ServedEvalConfig):
|
||||
"""``uv run eval``: evaluate the configured sources once against a live inference
|
||||
server, then exit. Every source's env server is spawned by the eval process unless
|
||||
the source sets ``serve.address``. Defaults to Prime Inference (``PRIME_API_KEY`` or
|
||||
``prime login``) with the concurrency pinned at 128."""
|
||||
|
||||
model: str = Field("deepseek/deepseek-v4.1-flash", validation_alias=AliasChoices("model", "m"))
|
||||
"""Model id — the ``model`` field of every eval request and the startup model check."""
|
||||
|
||||
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
|
||||
"""Client of the inference server. Defaults to Prime Inference."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig(min_inflight=128, max_inflight=128)
|
||||
"""In-flight episodes, pinned at 128 (``-c N`` repins). External APIs expose no vLLM
|
||||
``/metrics`` to adapt to; against a vLLM server set ``min_inflight < max_inflight`` to
|
||||
let the band adapt to KV usage like the orchestrator's."""
|
||||
|
||||
num_examples: int = Field(-1, validation_alias=AliasChoices("num_examples", "n"))
|
||||
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
|
||||
|
||||
group_size: int = Field(1, ge=1, validation_alias=AliasChoices("group_size", "r"))
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory that groups related runs. Each run writes its artifacts (traces, logs,
|
||||
checkpoints) to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
clean: bool = False
|
||||
"""Delete the run directory (``output_dir / run.name``) before starting. Required to
|
||||
overwrite a run directory that contains artifacts from a previous run when not resuming."""
|
||||
|
||||
dry_run: bool = False
|
||||
"""Resolve and write the config, then exit without evaluating."""
|
||||
|
||||
dashboard: bool = True
|
||||
"""Start (or reuse) the local dashboard daemon and print its URL."""
|
||||
|
||||
resume: bool = False
|
||||
"""Continue the interrupted run named by ``run.name`` from its trace stream: the
|
||||
landed episodes rejoin the epoch and only the rollouts still owed run. The model,
|
||||
sampling and env config must match the interrupted run; ``num_examples`` and
|
||||
``group_size`` may change."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
@property
|
||||
def run_dir(self) -> Path:
|
||||
assert self.run.dir is not None # resolved at construction
|
||||
return self.output_dir / self.run.dir
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<envs>--<model>--<short-id>``) when unset and
|
||||
default the run directory, W&B run name and platform evaluation name to it."""
|
||||
if self.run.name is None:
|
||||
envs = "+".join(dict.fromkeys(source.resolved_name for source in self.source))
|
||||
model = self.model.split("/")[-1]
|
||||
self.run.name = f"{envs}--{model}--{uuid.uuid4().hex[:8]}".lower()
|
||||
if self.run.dir is None:
|
||||
self.run.dir = self.run.name
|
||||
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
|
||||
self.monitors.wandb.name = self.run.name
|
||||
if self.monitors.prime is not None and self.monitors.prime.name is None:
|
||||
self.monitors.prime.name = self.run.name
|
||||
return self
|
||||
|
||||
|
||||
class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig):
|
||||
"""The ``[eval]`` block of the ``sft`` entrypoint, and the config of the online-eval
|
||||
process the launcher spawns from it: interval-driven eval sources against the inference
|
||||
server that receives the trainer's weight broadcasts. The process watches the
|
||||
broadcasts directory, moves the inference server onto each broadcast, and runs the
|
||||
due sources against the updated weights. The launcher fills the run-level fields
|
||||
(``model``, ``weight_broadcast``, ``broadcasts_dir``, ``max_steps``, ``resume_step``,
|
||||
``output_dir``, ``log``, ``monitors``) from the resolved SFT config."""
|
||||
|
||||
cancel_on_new_checkpoint: bool = True
|
||||
"""Cancel unfinished episodes when a newer trainer checkpoint is ready. Disable to
|
||||
finish every triggered eval epoch before loading later weights. The trainer can idle
|
||||
while it waits for slow evals."""
|
||||
|
||||
model: str | None = None
|
||||
"""Name the inference server serves the model under. The name stays fixed across
|
||||
weight updates (weights are swapped in place), so per-step results are told apart by
|
||||
``eval/{env}/policy_version``."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Weight transport. None reloads weights from the filesystem broadcasts."""
|
||||
|
||||
broadcasts_dir: Path | None = None
|
||||
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
|
||||
``<output_dir>/broadcasts``."""
|
||||
|
||||
max_steps: int | None = None
|
||||
"""Trainer step at which the run ends. The final checkpoint always fires every eval
|
||||
env, and the process exits after processing it. If None, runs until terminated."""
|
||||
|
||||
resume_step: int | None = None
|
||||
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
|
||||
skipped; set ``retrigger_on_resume`` to re-fire interval-aligned evals at this step."""
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""The run directory, shared with the trainer. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_broadcasts_dir(self):
|
||||
if self.broadcasts_dir is None:
|
||||
self.broadcasts_dir = self.output_dir / "broadcasts"
|
||||
return self
|
||||
@@ -1,141 +0,0 @@
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig, ResumeConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import BaseConfig, default_output_dir
|
||||
|
||||
|
||||
class EvalsEvalConfig(EvalConfig):
|
||||
"""Evals against a live inference server. Extends the orchestrator ``EvalConfig``
|
||||
(sources, sampling, intervals) with the client of the inference deployment and
|
||||
evals-side knobs."""
|
||||
|
||||
client: ClientConfig = ClientConfig()
|
||||
"""Client of the inference server evals run against. Auto-wired from the
|
||||
``[inference]`` block when the launcher manages the server."""
|
||||
|
||||
env_server_base_port: int = Field(5000, ge=1, le=65535)
|
||||
"""First port of the env-server port range: the eval source at position ``i`` is
|
||||
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
|
||||
keep it instead, without shifting the other sources' ports."""
|
||||
|
||||
concurrency: ConcurrencyConfig = ConcurrencyConfig()
|
||||
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
|
||||
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
|
||||
|
||||
cancel_on_new_checkpoint: bool = True
|
||||
"""For online evals, cancel unfinished episodes when a newer trainer checkpoint is ready.
|
||||
Disable to finish every triggered eval epoch before loading later weights. The trainer can
|
||||
idle while it waits for slow evals."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
Same contract as ``OrchestratorConfig.env_addresses``: sources with an explicit
|
||||
``serve.address`` are externally managed; the evals process spawns an env server at
|
||||
the derived address for every other source."""
|
||||
return {
|
||||
("eval", source.resolved_name): source.serve.address
|
||||
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
|
||||
for index, source in enumerate(self.source)
|
||||
}
|
||||
|
||||
|
||||
class OnlineConfig(BaseConfig):
|
||||
"""Broadcast-driven online evals: watch a broadcasts directory for new weight
|
||||
broadcasts and evaluate each eligible one. Without this block the evals process runs
|
||||
every eval source once against the weights the inference server currently serves,
|
||||
then exits."""
|
||||
|
||||
broadcasts_dir: Path | None = None
|
||||
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
|
||||
``<output_dir>/broadcasts``."""
|
||||
|
||||
max_steps: int | None = None
|
||||
"""Trainer step at which the run ends. The final checkpoint always fires every
|
||||
eval env, and the evals process exits after processing it. If None, the evals process
|
||||
runs until terminated."""
|
||||
|
||||
resume_step: int | None = None
|
||||
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
|
||||
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
|
||||
this step."""
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
"""Checkpoint progress for an interruptible standalone eval run."""
|
||||
|
||||
interval: int = Field(1, ge=1)
|
||||
"""Save after the task cursor advances by N completed groups."""
|
||||
|
||||
|
||||
class EvalsConfig(BaseConfig):
|
||||
"""``uv run evals``: run the configured evals against a live inference server.
|
||||
Standalone (no ``[online]``), one epoch of every eval source runs against the
|
||||
served weights and the evals process exits. With ``[online]``, the evals process watches a
|
||||
broadcasts directory for new weight broadcasts, updates the inference server through
|
||||
the configured transport, and runs the configured evals against the updated weights.
|
||||
The ``sft`` launcher writes this config; filesystem mode also works standalone against
|
||||
any trainer that writes ``broadcasts/step_{n}`` directories with ``STABLE`` markers."""
|
||||
|
||||
model: str = "Qwen/Qwen3-0.6B"
|
||||
"""Name the inference server serves the model under — the ``model`` field of every
|
||||
eval request and the startup model check. Auto-filled from ``model.name`` by the
|
||||
``sft`` launcher; the name stays fixed across weight updates (weights are
|
||||
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
|
||||
|
||||
eval: EvalsEvalConfig
|
||||
"""Eval sources, sampling, intervals, concurrency, and the inference client."""
|
||||
|
||||
online: OnlineConfig | None = None
|
||||
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
|
||||
|
||||
weight_broadcast: WeightBroadcastConfig | None = None
|
||||
"""Weight transport for online evals. The ``sft`` launcher fills this from its
|
||||
resolved trainer transport. None uses filesystem reloads."""
|
||||
|
||||
output_dir: Path = Field(default_factory=default_output_dir)
|
||||
"""Directory to write outputs to — rollout traces and logs are written as
|
||||
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
|
||||
|
||||
ckpt: CheckpointConfig | None = None
|
||||
"""Checkpoint standalone eval progress. Checkpoint steps are task cursor positions."""
|
||||
|
||||
resume: ResumeConfig | None = None
|
||||
"""Resume a standalone eval run from a cursor checkpoint. A bare block loads the latest checkpoint."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_broadcasts_dir(self):
|
||||
if self.online is not None and self.online.broadcasts_dir is None:
|
||||
self.online.broadcasts_dir = self.output_dir / "broadcasts"
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_skip_first_step_is_online_only(self):
|
||||
"""``skip_first_step`` gates the base-model eval between checkpoints; a
|
||||
standalone run has only that one epoch, so skipping it would exit
|
||||
successfully without evaluating anything."""
|
||||
if self.online is None and self.eval.skip_first_step:
|
||||
raise ValueError(
|
||||
"eval.skip_first_step only applies to online evals - a standalone run "
|
||||
"would skip its only eval epoch. Remove it or add an [online] block."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_checkpointing_is_standalone_only(self):
|
||||
if self.online is not None and (self.ckpt is not None or self.resume is not None):
|
||||
raise ValueError(
|
||||
"evals ckpt/resume only supports standalone evals - online evals are coordinated "
|
||||
"with the trainer's live weight-broadcast lifecycle"
|
||||
)
|
||||
return self
|
||||
@@ -38,6 +38,8 @@ All2AllBackend = Literal[
|
||||
"flashinfer_nvlink_two_sided",
|
||||
]
|
||||
|
||||
QuantizationType = Literal["fp8_per_block"]
|
||||
|
||||
|
||||
class VllmConfig(BaseConfig):
|
||||
"""Arguments forwarded to the vLLM server, under vLLM's own argument names
|
||||
@@ -105,7 +107,7 @@ class VllmConfig(BaseConfig):
|
||||
enable_prefix_caching: bool | None = None
|
||||
"""Enable prefix caching."""
|
||||
|
||||
quantization: str | None = None
|
||||
quantization: QuantizationType | None = None
|
||||
"""Online inference quantization method. If None, vLLM infers it from the checkpoint."""
|
||||
|
||||
enable_lora: bool = False
|
||||
@@ -130,6 +132,12 @@ class VllmConfig(BaseConfig):
|
||||
enable_eplb: bool = False
|
||||
"""Enable expert parallel load balancer (EPLB)."""
|
||||
|
||||
enable_ep_weight_filter: bool = True
|
||||
"""Skip non-local expert weights at load time under expert parallelism, so each
|
||||
rank reads only its own expert shard from disk. No-op for non-MoE models, when
|
||||
expert parallelism is disabled, or under EPLB (redundant expert slots need all
|
||||
logical expert weights)."""
|
||||
|
||||
enable_dbo: bool = False
|
||||
"""Enable dual batch overlap (DBO)."""
|
||||
|
||||
@@ -220,7 +228,7 @@ class CPUOffloadTier(BaseConfig):
|
||||
|
||||
class DiskOffloadTier(BaseConfig):
|
||||
path: Path
|
||||
"""Filesystem root for the disk tier. For ``native`` this is the ``fs_python`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
|
||||
"""Filesystem root for the disk tier. For ``native`` this is the ``fs`` secondary tier's ``root_dir``; for ``mooncake`` it is the store client's ``MOONCAKE_OFFLOAD_FILE_STORAGE_PATH``. Capacity is bounded by the filesystem at ``path`` (neither backend enforces a byte quota)."""
|
||||
|
||||
|
||||
class BaseKVCacheOffloadConfig(BaseConfig):
|
||||
@@ -242,14 +250,14 @@ class BaseKVCacheOffloadConfig(BaseConfig):
|
||||
|
||||
class NativeKVCacheOffloadConfig(BaseKVCacheOffloadConfig):
|
||||
type: Literal["native"] = "native"
|
||||
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs_python`` disk secondary). Fully self-contained — no external processes."""
|
||||
"""vLLM-native offloading. cpu-only uses ``OffloadingConnector`` + ``CPUOffloadingSpec``; cpu+disk uses ``TieringOffloadingSpec`` (CPU primary tier + ``fs`` disk secondary). Fully self-contained — no external processes."""
|
||||
|
||||
def to_connector_dict(self) -> dict[str, Any]:
|
||||
assert self.cpu is not None
|
||||
extra: dict[str, Any] = {"cpu_bytes_to_use": int(self.cpu.num_bytes)}
|
||||
if self.disk is not None:
|
||||
extra["spec_name"] = "TieringOffloadingSpec"
|
||||
extra["secondary_tiers"] = [{"type": "fs_python", "root_dir": str(self.disk.path)}]
|
||||
extra["secondary_tiers"] = [{"type": "fs", "root_dir": str(self.disk.path)}]
|
||||
return {
|
||||
"kv_connector": "OffloadingConnector",
|
||||
"kv_role": "kv_both",
|
||||
@@ -303,8 +311,11 @@ class VllmRouterConfig(BaseConfig):
|
||||
|
||||
type: Literal["vllm-router"] = "vllm-router"
|
||||
|
||||
policy: str = "consistent_hash"
|
||||
"""Routing policy, e.g. ``consistent_hash`` or ``round_robin``."""
|
||||
request_timeout_secs: int = Field(1800, ge=1)
|
||||
"""Maximum lifetime of a routed request, including streamed completions."""
|
||||
|
||||
policy: str = "sticky_least_loaded"
|
||||
"""Routing policy. Defaults to session-affine least-loaded routing; alternatives include ``consistent_hash`` and ``round_robin``."""
|
||||
|
||||
|
||||
class LlmdRouterConfig(BaseConfig):
|
||||
@@ -462,7 +473,7 @@ class InferenceConfig(BaseConfig):
|
||||
"""Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs and selects the V2 model runner before vLLM starts. Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on."""
|
||||
|
||||
enable_fp32_lm_head: bool = True
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
|
||||
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented natively by vLLM's LogitsProcessor, which reads ``head_dtype`` off the HF config, so this flag injects ``hf_overrides = {"head_dtype": "float32"}``."""
|
||||
|
||||
enable_fp32_router_logits: bool = True
|
||||
"""Emit fp32 MoE router logits: the bf16×bf16 gate GEMM writes its fp32 accumulator out unrounded instead of truncating logits to bf16 before expert scoring. Matches fp32-routed checkpoints (e.g. GLM-5.x, trained with Megatron ``--moe-router-dtype fp32``); pairs with ``trainer.model.moe_router_dtype = "float32"``. Implemented natively by vLLM, which reads ``moe_router_dtype`` off the HF config — this flag injects ``hf_overrides = {"moe_router_dtype": "float32"}`` (GLM-5.x gets fp32 routing regardless)."""
|
||||
@@ -636,6 +647,13 @@ class InferenceConfig(BaseConfig):
|
||||
hf_overrides.setdefault("moe_router_dtype", "float32")
|
||||
namespace.hf_overrides = hf_overrides
|
||||
|
||||
# vLLM's LogitsProcessor reads `head_dtype` off the HF config to pick the
|
||||
# lm_head projection dtype (fp32 runs as a native bf16xbf16 -> fp32 GEMM).
|
||||
if self.enable_fp32_lm_head:
|
||||
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
|
||||
hf_overrides.setdefault("head_dtype", "float32")
|
||||
namespace.hf_overrides = hf_overrides
|
||||
|
||||
if self.enable_return_sampling_mask:
|
||||
namespace.return_sampling_mask = True
|
||||
|
||||
@@ -643,12 +661,4 @@ class InferenceConfig(BaseConfig):
|
||||
if kv_transfer_config is not None:
|
||||
namespace.kv_transfer_config = kv_transfer_config
|
||||
|
||||
# Pass prime-rl-specific flags through vLLM's additional_config dict;
|
||||
# workers read these via get_current_vllm_config().additional_config.
|
||||
additional_config = getattr(namespace, "additional_config", None) or {}
|
||||
if self.enable_fp32_lm_head:
|
||||
additional_config["fp32_lm_head"] = True
|
||||
if additional_config:
|
||||
namespace.additional_config = additional_config
|
||||
|
||||
return namespace
|
||||
|
||||
@@ -43,11 +43,16 @@ class FileMonitorConfig(BaseConfig):
|
||||
not the records, so this only trades record size against overlay precision."""
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
class PrimeTrainMonitorConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Run name shown on the platform. Inherits ``run.name`` when unset."""
|
||||
|
||||
|
||||
class PrimeEvalMonitorConfig(BaseConfig):
|
||||
name: str | None = None
|
||||
"""Evaluation name shown on the platform. Inherits ``run.name`` when unset."""
|
||||
|
||||
|
||||
class MonitorsConfig(BaseConfig):
|
||||
wandb: WandbMonitorConfig | None = None
|
||||
"""Log metrics to Weights & Biases. Off by default; enable with ``--monitors.wandb``."""
|
||||
@@ -56,6 +61,11 @@ class MonitorsConfig(BaseConfig):
|
||||
"""Log metrics and episode traces to the run's output directory. On by default; disable with ``--no-monitors.file``."""
|
||||
|
||||
|
||||
class OrchestratorMonitorsConfig(MonitorsConfig):
|
||||
prime: PrimeMonitorConfig | None = None
|
||||
class TrainMonitorsConfig(MonitorsConfig):
|
||||
prime: PrimeTrainMonitorConfig | None = None
|
||||
"""Log metrics and episodes to the Prime Intellect platform. If None, disabled."""
|
||||
|
||||
|
||||
class EvalMonitorsConfig(MonitorsConfig):
|
||||
prime: PrimeEvalMonitorConfig | None = None
|
||||
"""Upload every eval source's finished epoch as an evaluation on the Prime Intellect platform. If None, disabled."""
|
||||
|
||||
@@ -10,7 +10,7 @@ from prime_rl.configs.algorithm import (
|
||||
AlgoConfig,
|
||||
GRPOAlgoConfig,
|
||||
)
|
||||
from prime_rl.configs.monitors import OrchestratorMonitorsConfig
|
||||
from prime_rl.configs.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
BaseWeightBroadcastConfig,
|
||||
@@ -161,13 +161,13 @@ class EnvConfig(BaseConfig):
|
||||
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
|
||||
serve: vf.ServeConfig = vf.ServeConfig()
|
||||
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config with an unset ``address`` filled in as the derived ``tcp://127.0.0.1:<env_server_base_port + index>``. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
|
||||
"""How this source's env server is hosted. The sizing knobs are consumed by the launcher, which writes each source's env-server config; an unset ``address`` means the spawned server binds an OS-assigned port and publishes it for the orchestrator. Setting ``address`` marks the server externally managed: the launchers neither write its env-server TOML nor spawn a server for it, and the orchestrator connects to the given address — e.g. a k8s deployment running env servers in their own pods."""
|
||||
|
||||
name: str | None = None
|
||||
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the taskset id. Must be unique across all envs in the same group."""
|
||||
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
shuffle: bool = False
|
||||
"""Shuffle the source's finite taskset once with a fixed seed. The shuffled order is fixed for the whole run; infinite tasksets cannot be shuffled."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
@@ -269,6 +269,9 @@ class TrainSourceConfig(EnvConfig):
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
|
||||
|
||||
ratio: float = Field(1.0, gt=0)
|
||||
"""Sampling weight for this environment in the buffer. Relative weights are normalized to probabilities across envs (e.g. [1, 1] and [0.5, 0.5] are equivalent). Defaults to 1, i.e. equal weight per env."""
|
||||
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Rollouts generated per example for GRPO group-relative advantages.
|
||||
Inherits from ``orchestrator.group_size`` when unset."""
|
||||
@@ -293,6 +296,10 @@ class EvalSourceConfig(EnvConfig):
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
|
||||
|
||||
|
||||
class OnlineEvalSourceConfig(EvalSourceConfig):
|
||||
"""An eval source of a training run: evaluated on a step interval."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
"""Per-env eval interval. If unset, inherits from the group-level eval interval."""
|
||||
|
||||
@@ -328,7 +335,9 @@ class TrainConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
class EvalConfig(BaseConfig):
|
||||
class EvalSourcesConfig(BaseConfig):
|
||||
"""Eval sources and the group-level defaults they inherit."""
|
||||
|
||||
source: list[EvalSourceConfig] = Field(default_factory=list)
|
||||
"""Evaluation sources."""
|
||||
|
||||
@@ -341,6 +350,49 @@ class EvalConfig(BaseConfig):
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples and
|
||||
group_size (the worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for source in self.source:
|
||||
if "sampling" not in source.model_fields_set:
|
||||
source.sampling = EvalSamplingConfig(**group_sampling)
|
||||
else:
|
||||
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
|
||||
source.sampling = EvalSamplingConfig(**merged)
|
||||
if "num_examples" not in source.model_fields_set:
|
||||
source.num_examples = self.num_examples
|
||||
if "group_size" not in source.model_fields_set:
|
||||
source.group_size = self.group_size
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_non_empty_sources(self):
|
||||
if not self.source:
|
||||
raise ValueError(
|
||||
"At least one eval source is required. Add a source block "
|
||||
"(e.g. [[source]] or [[orchestrator.eval.source]]) or drop the eval block entirely to disable eval."
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [source.resolved_name for source in self.source]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(
|
||||
f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name."
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class ScheduledEvalConfig(EvalSourcesConfig):
|
||||
"""Eval sources evaluated on a step interval next to training."""
|
||||
|
||||
source: list[OnlineEvalSourceConfig] = Field(default_factory=list)
|
||||
"""Evaluation sources, each with its own step interval."""
|
||||
|
||||
interval: int = Field(100, ge=1)
|
||||
"""Step interval at which to evaluate the model."""
|
||||
|
||||
@@ -354,43 +406,22 @@ class EvalConfig(BaseConfig):
|
||||
exit where all evals already completed."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
|
||||
group_size, and interval (the worker ``pool`` is configured per env, default elastic)."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
def resolve_env_intervals(self):
|
||||
"""Per-env intervals inherit the group-level interval."""
|
||||
for source in self.source:
|
||||
if "sampling" not in source.model_fields_set:
|
||||
source.sampling = EvalSamplingConfig(**group_sampling)
|
||||
else:
|
||||
merged = group_sampling | source.sampling.model_dump(exclude_unset=True)
|
||||
source.sampling = EvalSamplingConfig(**merged)
|
||||
if "num_examples" not in source.model_fields_set:
|
||||
source.num_examples = self.num_examples
|
||||
if "group_size" not in source.model_fields_set:
|
||||
source.group_size = self.group_size
|
||||
if "interval" not in source.model_fields_set:
|
||||
source.interval = self.interval
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_non_empty_sources(self):
|
||||
if not self.source:
|
||||
raise ValueError(
|
||||
"EvalConfig must define at least one source. Either drop the "
|
||||
"[orchestrator.eval] block entirely (to disable eval) or "
|
||||
"add a [[orchestrator.eval.source]] block."
|
||||
)
|
||||
return self
|
||||
@property
|
||||
def intervals(self) -> dict[str, int]:
|
||||
"""Step interval per eval env, by resolved name."""
|
||||
return {source.resolved_name: source.interval for source in self.source}
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_unique_env_names(self):
|
||||
env_names = [source.resolved_name for source in self.source]
|
||||
duplicates = [n for n in env_names if env_names.count(n) > 1]
|
||||
if duplicates:
|
||||
raise ValueError(
|
||||
f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name."
|
||||
)
|
||||
return self
|
||||
|
||||
class RLOnlineEvalConfig(ScheduledEvalConfig):
|
||||
"""The ``[orchestrator.eval]`` block: online evals against the orchestrator's
|
||||
inference pool, on the policy the train rollouts see."""
|
||||
|
||||
|
||||
class CheckpointConfig(BaseConfig):
|
||||
@@ -431,9 +462,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
@@ -510,7 +538,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
``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."""
|
||||
|
||||
eval: EvalConfig | None = None
|
||||
eval: RLOnlineEvalConfig | None = None
|
||||
"""Evaluation configuration."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
@@ -518,7 +546,7 @@ class OrchestratorConfig(BaseConfig):
|
||||
env_vars: EnvVars = {}
|
||||
"""Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults."""
|
||||
|
||||
monitors: OrchestratorMonitorsConfig = OrchestratorMonitorsConfig()
|
||||
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
collect_inference_metrics: bool = True
|
||||
@@ -545,9 +573,6 @@ class OrchestratorConfig(BaseConfig):
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
|
||||
|
||||
env_server_base_port: int = Field(5000, ge=1, le=65535)
|
||||
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address`` keep it instead, without shifting the other sources' ports (indices stay positional). Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
|
||||
|
||||
batch_size: int | None = Field(None, ge=1)
|
||||
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
|
||||
|
||||
@@ -770,15 +795,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
return sources
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
|
||||
the source's own ``serve.address`` when set (an externally managed server), else
|
||||
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
|
||||
``env_sources`` order. The launcher binds env servers at exactly these addresses
|
||||
and the orchestrator connects to them, so both sides agree from the config
|
||||
alone."""
|
||||
return {
|
||||
(split, source.resolved_name): source.serve.address
|
||||
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
|
||||
for index, (split, source) in enumerate(self.env_sources)
|
||||
}
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each source's env server lives, keyed by ``(split, resolved_name)``: the
|
||||
source's own ``serve.address`` when set (an externally managed server), else None —
|
||||
the launcher spawns the server, which binds an OS-assigned port and publishes it
|
||||
to the source's address file for the orchestrator to pick up."""
|
||||
return {(split, source.resolved_name): source.serve.address for split, source in self.env_sources}
|
||||
|
||||
@@ -7,7 +7,7 @@ from pydantic import Field, model_validator
|
||||
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig
|
||||
from prime_rl.configs.monitors import FileMonitorConfig, PrimeTrainMonitorConfig
|
||||
from prime_rl.configs.orchestrator import (
|
||||
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
|
||||
)
|
||||
@@ -102,7 +102,7 @@ class SharedMonitorsConfig(BaseConfig):
|
||||
file: FileMonitorConfig | None = None
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/monitors/file/metrics.jsonl`` on both trainer and orchestrator."""
|
||||
|
||||
prime: PrimeMonitorConfig | None = None
|
||||
prime: PrimeTrainMonitorConfig | None = None
|
||||
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
|
||||
|
||||
|
||||
@@ -145,9 +145,6 @@ class SharedNCCLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
port: int = 29501
|
||||
"""Port for NCCL weight broadcast."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
|
||||
|
||||
|
||||
class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
@@ -368,22 +365,6 @@ class RLConfig(BaseConfig):
|
||||
)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_quantize_in_weight_transfer(self):
|
||||
if not isinstance(self.weight_broadcast, SharedNCCLWeightBroadcastConfig):
|
||||
return self
|
||||
|
||||
if not self.weight_broadcast.quantize_in_weight_transfer:
|
||||
return self
|
||||
|
||||
if self.inference is None:
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
|
||||
|
||||
if self.trainer.model.impl != "custom":
|
||||
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
|
||||
|
||||
return self
|
||||
|
||||
### Auto-setup shared configs (before sub-config construction)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@@ -487,9 +468,7 @@ class RLConfig(BaseConfig):
|
||||
inference_world_size=inference_world_size,
|
||||
)
|
||||
if self.weight_broadcast.type == "nccl":
|
||||
transport_config = dict(
|
||||
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
|
||||
)
|
||||
transport_config = {}
|
||||
trainer_config_type = TrainerNCCLWeightBroadcastConfig
|
||||
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
|
||||
else:
|
||||
@@ -538,18 +517,9 @@ class RLConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_eplb_requires_quantized_weight_transfer(self):
|
||||
if self.inference is None or not self.inference.vllm.enable_eplb:
|
||||
return self
|
||||
|
||||
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
|
||||
trainer_weight_broadcast = self.trainer.weight_broadcast
|
||||
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
|
||||
raise ValueError(
|
||||
"inference.vllm.enable_eplb requires weight_broadcast.type = 'nccl' and "
|
||||
"weight_broadcast.quantize_in_weight_transfer = true."
|
||||
)
|
||||
|
||||
def validate_eplb(self):
|
||||
if self.inference is not None and self.inference.vllm.enable_eplb:
|
||||
raise ValueError("inference.vllm.enable_eplb is not supported with RL weight updates.")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
|
||||
@@ -8,7 +8,7 @@ from pydantic import AliasChoices, Field, model_validator
|
||||
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
|
||||
from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.evals import EvalsEvalConfig
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.monitors import MonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
@@ -203,7 +203,7 @@ class SFTConfig(BaseConfig):
|
||||
val: SFTValConfig | None = None
|
||||
"""Validation configuration. If None, no validation runs."""
|
||||
|
||||
eval: EvalsEvalConfig | None = None
|
||||
eval: SFTOnlineEvalConfig | None = None
|
||||
"""Online evaluation configuration: rollout-based evals against a live inference
|
||||
server that receives the trainer's weight broadcasts. If None, no online evals run."""
|
||||
|
||||
@@ -437,7 +437,7 @@ class SFTConfig(BaseConfig):
|
||||
"Online evals are configured without an [inference] block - the launcher will not "
|
||||
f"start an inference server. Make sure one is running at eval.client.base_url "
|
||||
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
|
||||
"otherwise the evals process will hang waiting for it. If a router fronts the "
|
||||
"otherwise the online-eval process will hang waiting for it. If a router fronts the "
|
||||
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
|
||||
"(pause/update_weights/resume) must bypass the router.",
|
||||
stacklevel=2,
|
||||
|
||||
@@ -171,7 +171,7 @@ class DynamoConfig(BaseConfig):
|
||||
|
||||
|
||||
class ClientConfig(BaseConfig):
|
||||
wait_for_ready_timeout: int = 1800
|
||||
wait_for_ready_timeout: int = 3600
|
||||
"""Seconds to wait at startup for the inference pool to become ready."""
|
||||
|
||||
base_url: str = "http://localhost:8000/v1"
|
||||
|
||||
@@ -568,13 +568,13 @@ class CheckpointConfig(BaseConfig):
|
||||
|
||||
class IPOLossConfig(BaseConfig):
|
||||
type: Literal["ipo"] = "ipo"
|
||||
eps: float = Field(0.1, ge=0)
|
||||
eps: float = Field(0.3, ge=0)
|
||||
"""Maximum absolute probability change before a token is masked."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
kl_tau: float = Field(1e-3, ge=0)
|
||||
kl_tau: float = Field(0.0, ge=0)
|
||||
"""Temperature for the KL term."""
|
||||
|
||||
|
||||
@@ -645,9 +645,6 @@ class NCCLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
port: int = 29501
|
||||
"""Port for the NCCL broadcast rendezvous."""
|
||||
|
||||
quantize_in_weight_transfer: bool = False
|
||||
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
|
||||
|
||||
|
||||
class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
|
||||
type: Literal["nixl"] = "nixl"
|
||||
|
||||
+18
-11
@@ -16,14 +16,15 @@ dependencies = [
|
||||
"transformers==5.6.2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime>=0.6.19",
|
||||
"prime-runs[train]>=0.1.1",
|
||||
"prime-sandboxes>=0.3.0",
|
||||
"prime-runs[train]>=0.1.3",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
"openai>=1.106.1",
|
||||
"orjson>=3.11.0",
|
||||
"psutil>=7.0.0",
|
||||
"prometheus-client>=0.20.0",
|
||||
"pyzstd>=0.16.2",
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
@@ -42,7 +43,7 @@ sft = "prime_rl.entrypoints.sft:main"
|
||||
inference = "prime_rl.entrypoints.inference:main"
|
||||
trainer = "prime_rl.entrypoints.trainer:main"
|
||||
orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
evals = "prime_rl.entrypoints.evals:main"
|
||||
eval = "prime_rl.entrypoints.eval:main"
|
||||
env-server = "prime_rl.entrypoints.env_server:main"
|
||||
dashboard = "prime_rl.entrypoints.dashboard:main"
|
||||
|
||||
@@ -55,7 +56,7 @@ gpu = [
|
||||
"torchvision ; sys_platform == 'linux'",
|
||||
"torchaudio ; sys_platform == 'linux'",
|
||||
"torchdata>=0.11.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.28.0 ; sys_platform == 'linux'",
|
||||
"vllm>=0.29.0 ; sys_platform == 'linux'",
|
||||
"mooncake-transfer-engine>=0.3.10.post2 ; sys_platform == 'linux'",
|
||||
"ring-flash-attn>=0.1.8 ; sys_platform == 'linux'",
|
||||
"torchtitan ; sys_platform == 'linux'",
|
||||
@@ -145,7 +146,7 @@ override-dependencies = [
|
||||
# Shared by vLLM, TileLang, and the pinned FlashAttention 4 runtime.
|
||||
"apache-tvm-ffi==0.1.11",
|
||||
"nvidia-cudnn-cu13>=9.15 ; sys_platform == 'linux'",
|
||||
# vLLM 0.28.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
|
||||
# vLLM 0.29.0 requires quack-kernels 0.6.4. It requires this exact CUTLASS version.
|
||||
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
|
||||
"nvidia-cutlass-dsl==4.6.2",
|
||||
"transformers==5.6.2",
|
||||
@@ -223,8 +224,6 @@ requires-dist = [
|
||||
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
|
||||
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
|
||||
harbor = "2026-08-11T00:00:00Z"
|
||||
# we want latest vllm, remove next patch
|
||||
vllm = false
|
||||
tokenspeed-mla = false
|
||||
fastokens = false
|
||||
flash_attn_3 = false
|
||||
@@ -268,12 +267,12 @@ torchao = [
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
|
||||
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "0251105" }
|
||||
vllm-router = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.1/vllm_router-0.2.1-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
vllm = [
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.28.0/vllm-0.28.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.29.0/vllm-0.29.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
deep-ep = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
@@ -309,6 +308,14 @@ name = "pytorch-cu130-test"
|
||||
url = "https://download.pytorch.org/whl/test/cu130"
|
||||
explicit = true
|
||||
|
||||
# Environments Hub wheels carry no upload time, so the exclude-newer cooldown
|
||||
# would reject every one of them. The Hub is first-party: skip the cutoff there.
|
||||
[[tool.uv.index]]
|
||||
name = "prime-hub"
|
||||
url = "https://hub.primeintellect.ai/primeintellect/simple/"
|
||||
explicit = true
|
||||
exclude-newer = false
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["F", "I"]
|
||||
|
||||
|
||||
@@ -63,9 +63,9 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
|
||||
Source lists are set in TOML. The CLI has no list-index paths (`--orchestrator.eval.source.0.env.taskset.id` does not parse); a whole list can be passed as JSON (`--orchestrator.eval.source '[{"env": {"taskset": {"id": "reverse-text"}}}]'`), which replaces the list wholesale.
|
||||
|
||||
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server), e.g. `--eval.source.0.env.taskset.id reverse-text`.
|
||||
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server). The `eval` entrypoint flattens it further: `[[source]]`, `[client]`, `[concurrency]`, `num_examples`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -r N -c N -m MODEL` (see the `eval` skill).
|
||||
|
||||
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
|
||||
|
||||
|
||||
+21
-136
@@ -5,164 +5,49 @@ description: Find, start, use, and stop the local run dashboard for metrics, con
|
||||
|
||||
# Run dashboard
|
||||
|
||||
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default
|
||||
`outputs/`, or `$PRL_OUTPUT_DIR` if set) serves a web UI at `http://localhost:7788`. It only reads run
|
||||
dirs — safe against live runs — and installs anywhere (cluster head node,
|
||||
laptop against a mounted outputs dir): GPU dependencies live behind the
|
||||
`gpu` extra.
|
||||
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR`) serves a web UI at `http://localhost:7788`. It only reads run dirs, so it is safe against live runs and installs anywhere: GPU dependencies live behind the `gpu` extra.
|
||||
|
||||
The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
|
||||
to inspect the immutable config or log files from an earlier launch. The Config
|
||||
view shows a copyable launch command above the launch TOML or resolved JSON.
|
||||
What is not obvious from the UI:
|
||||
|
||||
The trace viewer has separate **Transcript**, **Timeline**, **Replay**, and
|
||||
**Semantic** views. Timeline is a wall-clock Gantt of physical prefix branches.
|
||||
Replay renders the selected agent branch as a terminal session with play/pause,
|
||||
seek, restart, and speed controls. It preserves recorded model-call and
|
||||
tool-result delays. Since the trace schema records a complete model-call span
|
||||
but no per-token timestamps, response text is paced evenly across that measured
|
||||
span and labeled as inferred; events without timestamps remain ordered and are
|
||||
labeled untimed. Semantic projects Verifiers `MessageNode.semantic_parents` as a
|
||||
top-to-bottom causal graph of model calls, including subagent calls, returns,
|
||||
compactions, and custom edge types. Calls occupy compact causal ranks within
|
||||
bounded agent lanes: the root stays centered, concurrent children fan out
|
||||
symmetrically, and child slots are reused after return, so graph width reflects
|
||||
peak agent concurrency rather than total subagents. Compaction starts a visibly
|
||||
separate context segment. For display only, a missing continuation is recovered
|
||||
when the physical parent chain proves a completed tool round-trip; fragments
|
||||
that still cannot be placed are shown explicitly as unlinked instead of being
|
||||
presented as contexts. Hover or click an agent or context label to see its
|
||||
latest and peak prompt lengths first, followed by cumulative token processing
|
||||
and cost. Exact timing remains available on model-call hover and in Timeline.
|
||||
Traces without semantic parents keep the other views and disable Semantic.
|
||||
- Overview and Metrics read the same `monitors/file/metrics.jsonl`. **Overview** is the curated view (the sections of the W&B overview: train, eval, stability, inference, performance). **Metrics** is every key in the file, one pane per key, sectioned by parent path (`Flat`) or as a tree of sections along the key path (`Nested`), with a regex filter; time-keyed rows (`inference/`, `concurrency/`, `dispatcher/`) chart against wall time.
|
||||
- Config and Logs default to `latest (attempt <n>)`; select an attempt to inspect an earlier launch. The Config view shows a copyable launch command.
|
||||
- Trace viewer views: **Transcript**, **Timeline** (wall-clock Gantt of prefix branches), **Replay** (the branch as a terminal session; response text is paced evenly across the recorded model-call span and labelled inferred; default 8×; **Skip inference** collapses model calls but keeps tool delays; **T** toggles thinking, never advertise Ctrl+T) and **Semantic** (`semantic_parents` as a causal graph of model calls; width reflects peak agent concurrency; unplaceable fragments show as unlinked). Traces without semantic parents disable Semantic.
|
||||
- Live rollouts appear in the traces table with a pulsing dot and a phase badge, and open in the viewer, which follows them (pinned to the newest turn until you scroll up; the request in flight's uncommitted messages render dimmed as `awaiting model`). They come from `monitors/file/traces/live/*.jsonl`, polled once a second.
|
||||
- For an eval run the overview tab shows one env at a time (filter → env, `include errors`): a block progress bar (one cell per expected episode, from `monitors/file/plan.json`), summary tiles (avg@k, pass@k, error and truncation rate coloured >10% yellow / >50% red, turns / branches, episode time, tokens, cost), env metrics as dot plots or beeswarms (hover a dot for its episode, click to open it; hover the background for the quantiles), and usage / timing composition panes (icicle of the mean split over per-episode strips; `other` is wall time no phase accounts for; hover a part to dim the rest; 40 strips by default, `show all` for every one).
|
||||
- `view on platform` in the top bar links to the run on the Prime platform when `--monitors.prime` was on (`monitors/prime/run.json`); an eval's evaluation opens at epoch start, so the link is live from the first episode.
|
||||
- An eval reads `completed` once its stream is sealed by a clean exit; a crashed or interrupted one reads `stopped` after its files go quiet.
|
||||
|
||||
Replay defaults to 8× so long coding-agent model waits remain watchable; select
|
||||
1× for exact wall time or up to 32× for faster review. In-flight calls display
|
||||
their measured progress and recorded output-token usage even when they produce
|
||||
only tool calls. Enable **Skip inference** to collapse model calls to immediate
|
||||
responses while preserving the recorded command-to-tool-output delays. This is
|
||||
distinct from the speed control, which scales every delay uniformly. Recorded
|
||||
model thinking is shown by default. Toggle **Thinking** in the replay controls
|
||||
or press **T** while Replay is open to hide or show it without changing playback
|
||||
timing. Do not advertise Ctrl+T: browsers reserve it for a new tab before the
|
||||
page can handle the keypress. Use **Top** or the **Home** key to scroll to the
|
||||
beginning without pausing the replay. Use **Live** or **End** to resume
|
||||
following newly rendered output. Prompt-context nodes that were committed at
|
||||
response time are placed at the linked call's start so their serialization
|
||||
timestamp does not create a false blank wait before the replay.
|
||||
Every dashboard instance serves the dirs it was started with plus every dir in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`). Launchers register their output dir on every start and, in interactive sessions, auto-start a dashboard only when none is live; `--no-dashboard` opts a run out, non-interactive launches never spawn one. `--isolated` serves only the given dirs and ignores the registry.
|
||||
|
||||
Every dashboard instance serves the dirs it was started with **plus** every dir
|
||||
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
|
||||
live). Launchers (`rl`, `sft`) register their output dir on every
|
||||
start and, in interactive sessions, auto-start a dashboard only when none is
|
||||
live — an already-running one absorbs the new dir automatically, whatever port
|
||||
it is on. `--no-dashboard` opts a run out; non-interactive launches (CI, nohup)
|
||||
register their dir but never spawn.
|
||||
## Finding, stopping, restarting
|
||||
|
||||
## Isolated mode
|
||||
|
||||
`--isolated` serves only the given dirs: no registry read or write, no
|
||||
discovery claim, and launchers ignore the instance. Use it for focused views
|
||||
(demos, debugging one run dir) or to keep a scratch dir out of the registry.
|
||||
|
||||
## Finding the live dashboard
|
||||
|
||||
The live port can differ from 7788 (a taken port bumps to the next free one),
|
||||
so read the discovery file:
|
||||
The port can differ from 7788 (a taken port bumps to the next free one), so read the discovery file and hand the researcher its `url`; launcher logs also end with a `Dashboard · <url>` banner.
|
||||
|
||||
```bash
|
||||
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
|
||||
curl -sf $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/runs > /dev/null && echo live
|
||||
ps aux | grep PRL::Dashboard # process title
|
||||
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<port>"}
|
||||
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # stop; the next launch (or `uv run dashboard`) restarts it
|
||||
```
|
||||
|
||||
Hand the researcher the `url` from `daemon.json`. Launcher logs also print it:
|
||||
startup ends with a `Dashboard · <url>` banner. The auto-started instance logs
|
||||
to `~/.cache/prime-rl/dashboard/daemon.log`.
|
||||
|
||||
## Stopping / restarting
|
||||
|
||||
```bash
|
||||
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # the discovered instance
|
||||
pkill -f PRL::Dashboard # every dashboard on the host
|
||||
```
|
||||
|
||||
A clean exit releases `daemon.json`; a stale file from a dead process is taken
|
||||
over by the next start. Killing a dashboard never affects runs (it only reads),
|
||||
and killing a run never takes the dashboard down (it runs in its own session).
|
||||
Restart by launching any run, or directly: `uv run dashboard`.
|
||||
Killing a dashboard never affects runs and killing a run never takes the dashboard down. The daemon serves the code of the checkout that started it (`readlink /proc/<pid>/cwd`): after switching branches or worktrees, kill it so the next launch restarts it on the current code. Its log is `~/.cache/prime-rl/dashboard/daemon.log`.
|
||||
|
||||
## Point the open dashboard
|
||||
|
||||
Use `POST /api/view` to show relevant run data in every connected dashboard
|
||||
tab:
|
||||
`POST /api/view` shows run data in every connected tab. `run` is required; the other fields leave unspecified state alone. For trace evidence pass `step`, `kind` and `subset` together and address the episode by its stable `id` (`subset: "effective"` narrows the traces tab to the cohort shipped at that step); `highlight` entries are `{node, quote, reason, field?}`. On `409`, tell the user to open the returned `url`.
|
||||
|
||||
```bash
|
||||
curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view \
|
||||
-H 'content-type: application/json' -d '{
|
||||
"run": "demo-rl", "tab": "traces",
|
||||
"step": 0, "kind": "train", "subset": "effective",
|
||||
"episode": "ep-s00-reverse-text-0",
|
||||
"highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "tool result the policy conditioned on"}]
|
||||
}'
|
||||
-H 'content-type: application/json' -d '{"run": "demo-rl", "tab": "traces", "step": 0, "kind": "train", "subset": "effective",
|
||||
"episode": "ep-s00-reverse-text-0", "highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "the tool result the policy conditioned on"}]}'
|
||||
```
|
||||
|
||||
`run` is required; other fields are optional and leave unspecified UI state
|
||||
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
|
||||
address the episode by stable `id`. The traces tab opens on the whole stream;
|
||||
`subset: "effective"` switches it to the cohort that shipped at one step. Use
|
||||
optional `trace` and `branch` indices
|
||||
for multi-agent traces and `highlight` entries shaped as `{node, quote,
|
||||
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
|
||||
command applies when the tab connects.
|
||||
## Reports, only when asked
|
||||
|
||||
## Write a report only when asked
|
||||
|
||||
Create a report only when the user explicitly asks for one. Otherwise answer
|
||||
normally; use `/api/view` when showing trace evidence would help.
|
||||
|
||||
Write requested reports to `<run>/reports/<slug>.md`, then POST `{"run": ...,
|
||||
"tab": "report", "report": "<slug>"}`. Use Markdown with a frontmatter
|
||||
`title` and one-line JSON citation definitions:
|
||||
Write a requested report to `<run>/reports/<slug>.md`, then POST `{"run": ..., "tab": "report", "report": "<slug>"}`. Markdown with a frontmatter `title` (rendered as the H1, do not repeat it) and one-line JSON citations:
|
||||
|
||||
```markdown
|
||||
---
|
||||
title: Why does reward dip at step 4?
|
||||
---
|
||||
|
||||
The dip is provider errors, not policy regression [^err].
|
||||
|
||||
[^err]: {"step": 4, "kind": "train", "subset": "all", "episode": "ep-...", "node": 0, "quote": "engine overloaded", "note": "The failed call that emptied this step's batch."}
|
||||
```
|
||||
|
||||
The frontmatter `title` is rendered as the report H1; do not repeat it with a
|
||||
Markdown `#` heading. The inline renderer supports only HTTP(S) and anchor
|
||||
links. Relative Markdown links render as literal text, so identify local source
|
||||
files with inline code paths or link to a supported HTTP endpoint.
|
||||
|
||||
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
|
||||
Use the top-level rollout record `id` returned by the dashboard episode-list
|
||||
API—not a nested `traces[*].id`, and never `line`. Copy a short, distinctive
|
||||
quote exactly; matching is case-sensitive and whitespace-insensitive. Keep
|
||||
`note` to 1–2 sentences explaining why the quote supports the claim.
|
||||
|
||||
Cite major empirical, comparative, and diagnostic conclusions, but not routine
|
||||
explanation. Use exact trace citations for trajectory-level claims. For
|
||||
aggregate statistics, identify the run and source file; do not imply that one
|
||||
example trajectory proves the aggregate.
|
||||
|
||||
Use adjacent markers (`[^a] [^b]`) only when one claim genuinely depends on
|
||||
distinct passages, such as a comparison or corroboration. Use one citation
|
||||
when one passage is sufficient.
|
||||
|
||||
Optional fields are `run`, `trace`, `branch`, `node`, `field`, `prefix`, and
|
||||
`suffix`. Use `field: "content"` or `"reasoning"` only to disambiguate message
|
||||
parts. Use verbatim adjacent `prefix`/`suffix` only when a quote repeats.
|
||||
Ambiguous or mismatched citations remain broken and do not navigate.
|
||||
|
||||
Use Markdown; raw HTML is escaped.
|
||||
|
||||
Before handoff, reload the report and verify through the dashboard API that
|
||||
every referenced citation resolves uniquely to its episode, node, and quote.
|
||||
Confirm zero broken citations, one rendered title, and no unsupported relative
|
||||
links.
|
||||
A citation needs `step`, `kind`, `subset`, `episode` (the top-level record `id`, never `line` or a `traces[*].id`), an exact short `quote` (case-sensitive, whitespace-insensitive) and a one-sentence `note`; optional `trace`, `branch`, `node`, `field`, `prefix`, `suffix` disambiguate. Cite empirical and diagnostic claims, not routine explanation; one citation per passage. Only HTTP(S) and anchor links render. Before handing over, verify through the API that every citation resolves.
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
name: eval
|
||||
description: Launch and monitor prime-rl evals — the `uv run eval` entrypoint, its config and CLI shorthands, run directory, resume, logs and metrics. Use when asked to evaluate a model or checkpoint on an environment, smoke-test an environment, or check on an eval run.
|
||||
---
|
||||
|
||||
# Eval
|
||||
|
||||
`uv run eval` evaluates a model in one or more environments and exits after one epoch per source. It reuses the orchestrator's eval pipeline: one env server per source, a concurrency band, every episode through the monitors, and a trace stream that `--resume` continues from. Online evals of training runs are the `training` skill.
|
||||
|
||||
## Start an eval
|
||||
|
||||
The user launches runs; hand over the command unless told otherwise. Always cap smokes (`-n`, `-r`).
|
||||
|
||||
```bash
|
||||
uv run eval gsm8k -n 32 -r 4 # Prime Inference
|
||||
uv run eval gsm8k -n 32 -r 4 -c 8 --env.agent.harness.id bash # pin concurrency; set a field of the env block
|
||||
uv run eval gsm8k -n 32 -r 4 -m Qwen/Qwen3-4B --client.base_url http://localhost:8000/v1 # a local `uv run inference` server
|
||||
uv run eval @ eval.toml --run.name my-eval # multi-source TOML
|
||||
uv run eval @ eval.toml --run.name my-eval --resume # continue an interrupted run
|
||||
uv run eval @ eval.toml --dry-run # resolve and write the config, exit
|
||||
uv run eval @ eval.toml --monitors.prime # stream each source's epoch to the platform
|
||||
```
|
||||
|
||||
- Config: `EvalConfig` (`packages/prime-rl-configs/src/prime_rl/configs/eval.py`); `uv run eval -h` lists the fields.
|
||||
- Entrypoint: `src/prime_rl/entrypoints/eval.py`; implementation `src/prime_rl/eval/eval.py`, shared engine `src/prime_rl/eval/runner.py`.
|
||||
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `num_examples`, `-r` `group_size`, `-m` `model`, `-c N` pins `concurrency.min_inflight = max_inflight = N`. They cannot be combined with a TOML that defines `[[source]]` blocks.
|
||||
- Concurrency: an API exposes no vLLM `/metrics`, so run pinned there; against `uv run inference` set `min_inflight < max_inflight` in `[concurrency]` to adapt to KV usage.
|
||||
- Env servers: spawned per source on OS-assigned ports (published to `configs/attempt_N/resolved/envs/eval/<name>.address`) unless the source sets `serve.address`.
|
||||
- Ready-made configs: `configs/debug/eval/*.toml`, one per shape (single turn, multi turn, resume, multi env, aime2026, tb2).
|
||||
|
||||
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `num_examples`, `group_size`, `sampling` override the top level):
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
num_examples = 32
|
||||
group_size = 4
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "bash"
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
## Monitor an eval
|
||||
|
||||
Run dir: `output_dir / run.name` (auto `<envs>--<model>--<short-id>`; `ls -t outputs | head -1` finds the latest). The console stays quiet while the eval runs; everything is in the files and the dashboard (`dashboard` skill).
|
||||
|
||||
```
|
||||
{run_dir}/
|
||||
├── configs/latest/ # command.txt, the launch TOML, resolved/eval.json
|
||||
├── logs/latest/
|
||||
│ ├── eval.log # the eval process
|
||||
│ └── envs/eval/{name}.log # one log per env server
|
||||
└── monitors/file/ # metrics.jsonl, the trace stream, traces/live/ (one file per live trace), plan.json
|
||||
```
|
||||
|
||||
```bash
|
||||
tail -F {run_dir}/logs/latest/eval.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/eval.log {run_dir}/logs/latest/envs/eval/*.log
|
||||
grep SUCCESS {run_dir}/logs/latest/eval.log # one "Evaluated <env> ... Reward 0.xxxx" line per source
|
||||
uv run python -m prime_rl.monitors.file.traces {run_dir} [<trace_id>] # live rollouts by phase, or one assembled live trace
|
||||
```
|
||||
|
||||
The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · running 3`). A rollout stuck in `boot` for minutes is waiting on its sandbox; one in `running` with a frozen turn count is waiting on a model call or tool.
|
||||
|
||||
Metrics live under `eval/<env>/all/<agent>/…` (`reward/mean`, `is_truncated/mean` — raise `sampling.max_completion_tokens` when high, `has_error/mean`, the taskset's own metrics). Validate a result by reading a few traces in the dashboard rather than trusting the mean alone.
|
||||
|
||||
Stop a run with SIGINT/SIGTERM to the eval PID (`ps aux | grep PRL::Eval`); `--resume` restores the landed episodes from the trace stream and runs only the rollouts still owed (`num_examples`/`group_size` may change, the model, sampling and env config may not). Env servers are children of the eval process and exit with it.
|
||||
@@ -10,4 +10,4 @@ Two phases — start the run, then watch it.
|
||||
- **Start a run** — see `start-run/SKILL.md` for the `rl`, `sft`, and `inference` entrypoints and how to launch them (single-node, SLURM, dry-run).
|
||||
- **Monitor a run** — see `monitor-run/SKILL.md` for the runbook: how to find the output dir, what to tail, which metrics to watch, and how to restart safely.
|
||||
|
||||
Both subskills assume the `configs` skill for config-loading mechanics.
|
||||
Both subskills assume the `configs` skill for config-loading mechanics. Standalone evals (`uv run eval`) are the `eval` skill; online evals of a training run are configured in `start-run` and read in `monitor-run`.
|
||||
|
||||
@@ -82,7 +82,7 @@ Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`
|
||||
{run_dir}/logs/latest/
|
||||
├── trainer.log # rank 0 stdout
|
||||
├── orchestrator.log # orchestrator stdout
|
||||
├── evals.log # SFT online-eval evals stdout
|
||||
├── eval.log # SFT online-eval process (also the `uv run eval` process — see the `eval` skill)
|
||||
├── inference.log # vLLM stdout
|
||||
├── trainer/
|
||||
│ ├── node_*.log # per-node (multi-node only)
|
||||
@@ -100,10 +100,14 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
|
||||
Scan for problems:
|
||||
|
||||
```bash
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evals,inference}.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,eval,inference}.log
|
||||
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
|
||||
```
|
||||
|
||||
### Live rollouts
|
||||
|
||||
`{run_dir}/monitors/file/traces/live/<trace_id>.jsonl` holds the env server's streamed deltas of one live rollout (train or eval) and disappears when its episode lands in the stream, so the directory is the live set. `uv run python -m prime_rl.monitors.file.traces {run_dir}` prints one row per live trace with `stage` (pending/boot/setup/running/finalize/scoring/done/error), turns, tokens, elapsed and the latest message; with a trace id it prints the assembled trace. The dashboard's traces tab shows them in the episode table (tinted, phase badge, growing counts; filter status → in flight) and opens them in the viewer.
|
||||
|
||||
### Metrics
|
||||
|
||||
All metrics print to the console log (and W&B when configured).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: start-run
|
||||
description: How to launch prime-rl training runs — the `rl`, `sft`, `inference`, and `evals` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
|
||||
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint. Standalone evals are the `eval` skill.
|
||||
---
|
||||
|
||||
# Start a run
|
||||
@@ -74,7 +74,9 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
|
||||
|
||||
## `inference` — vLLM server
|
||||
|
||||
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly.
|
||||
Router session cleanup runs on successful, failed, and cancelled episodes, including discarded retry traces. Cleanup failures are logged per session and do not disable subsequent releases.
|
||||
|
||||
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly. It starts a `vllm-router` on `server.port` (default 8000, the client-facing URL) fronting the engine on `backend_port` (default 8100); admin endpoints must target the engine port directly. The default `sticky_least_loaded` policy keeps each rollout on one replica while assigning new sessions to the least-loaded replica; RL and SFT online eval automatically release completed sessions.
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
@@ -95,43 +97,6 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
|
||||
- SLURM: single-node, multi-node, and disaggregated deployments
|
||||
|
||||
## `evals` — multi-env evals
|
||||
|
||||
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. Add `[ckpt]` (`interval` counts completed task groups in the eval-source order) to make the run interruptible, then use `--resume`, `--resume.step N`, or `--resume.dir path/to/checkpoints/step_N`; for standalone evals, checkpoint step N means resume from task cursor N. Checkpoints store only the cursor, not generated episode records; partially completed groups and groups beyond the durable cursor are retried. Resume loads without `[ckpt]` but does not save new checkpoints. Checkpoint/resume is rejected with `[online]` because that process is coupled to the trainer's live broadcast handshake. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
|
||||
uv run evals @ eval.toml
|
||||
```
|
||||
|
||||
Minimal standalone `eval.toml`:
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
|
||||
[eval.client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
[eval.concurrency] # adaptive; same controller as [orchestrator.concurrency]
|
||||
min_inflight = 8
|
||||
max_inflight = 128
|
||||
|
||||
[[eval.source]]
|
||||
num_examples = 32 # always cap eval size for smokes
|
||||
group_size = 4
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
[ckpt] # optional: make a standalone eval resumable
|
||||
interval = 10 # completed task groups between cursor saves
|
||||
```
|
||||
|
||||
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
|
||||
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
|
||||
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
|
||||
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
|
||||
|
||||
## Exporting checkpoints
|
||||
|
||||
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/latest/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
|
||||
@@ -143,7 +108,8 @@ Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`).
|
||||
| `rl` | Full RL pipeline | Production RL training |
|
||||
| `sft` | Supervised fine-tuning | SFT and hard-distill |
|
||||
| `inference` | vLLM server | Standalone serving / debugging |
|
||||
| `evals` | Multi-env evals | Standalone evals / SFT online evals |
|
||||
|
||||
Standalone evals (`uv run eval`) are covered by the `eval` skill.
|
||||
|
||||
## Key paths
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# Dashboard
|
||||
|
||||
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
|
||||
directories (metrics, resolved configs, rollout traces, cited reports,
|
||||
component logs) at
|
||||
directories (a curated overview, every logged metric, resolved configs,
|
||||
rollout traces, cited reports, component logs) at
|
||||
http://localhost:7788. The trace viewer includes transcript, synchronized
|
||||
agent timeline, and terminal replay views; timeline activities open the
|
||||
corresponding transcript call. Needs the `dashboard` extra. Every instance also serves
|
||||
|
||||
@@ -28,24 +28,27 @@ from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, re
|
||||
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
|
||||
from prime_rl.monitors.file.traces.chunks import open_chunk
|
||||
from prime_rl.monitors.file.traces.index import summarize_episode
|
||||
from prime_rl.monitors.file.traces.live import LiveFolds, live_etag, live_path, live_rows, stage
|
||||
from prime_rl.monitors.file.traces.update import branch_node_paths, fold_trace_updates
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
from prime_rl.utils.pathing import get_eval_plan_path, get_file_monitor_dir, get_platform_run_path
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
try:
|
||||
import uvicorn
|
||||
from fastapi import FastAPI, HTTPException, Query
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
except ModuleNotFoundError as error: # the dashboard ships as an extra
|
||||
raise SystemExit("the dashboard needs the 'dashboard' extra - install with `uv sync --extra dashboard`") from error
|
||||
|
||||
STATIC_DIR = Path(__file__).parent / "static"
|
||||
MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "evals.log"}
|
||||
MASTER_LOGS = {"trainer.log", "orchestrator.log", "inference.log", "eval.log"}
|
||||
MAX_LOG_CHUNK = 2_000_000
|
||||
|
||||
app = FastAPI()
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=1)
|
||||
output_dirs: list[Path] = [default_output_dir()]
|
||||
|
||||
# run id -> run dir, rebuilt on every /api/runs poll; ids are the run name,
|
||||
@@ -75,6 +78,8 @@ def _lru_put(cache: OrderedDict, key, value) -> None:
|
||||
# Append-only file caches keyed by absolute path: line-start offsets and per-episode summaries.
|
||||
_offsets_cache: OrderedDict[Path, tuple[int, bytes, list[int]]] = OrderedDict()
|
||||
_summaries_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
|
||||
_series_keys: dict[tuple[Path, str | None], tuple[int, set[str]]] = {}
|
||||
"""Per stream and kind filter: how many summaries were scanned for series keys, and the keys."""
|
||||
_annotations_cache: OrderedDict[Path, tuple[tuple, dict[str, dict], dict[Path, int]]] = OrderedDict()
|
||||
_index_cache: OrderedDict[Path, tuple[int, list[dict]]] = OrderedDict()
|
||||
_rows_cache: OrderedDict[Path, tuple] = OrderedDict() # key, rows, entered, by_trace, consumed, last row
|
||||
@@ -239,7 +244,7 @@ def main_config(run_dir: Path) -> tuple[str, dict]:
|
||||
return "sft", read_json(configs / "sft.json")
|
||||
if (configs / "orchestrator.json").exists() or (configs / "trainer.json").exists():
|
||||
return "rl", read_json(configs / "orchestrator.json") or read_json(configs / "trainer.json")
|
||||
if (configs / "eval.json").exists(): # verifiers `uv run eval` run dir
|
||||
if (configs / "eval.json").exists():
|
||||
return "eval", read_json(configs / "eval.json")
|
||||
return "other", {}
|
||||
|
||||
@@ -258,6 +263,40 @@ def step_numbers(run_dir: Path) -> list[int]:
|
||||
return sorted({step for _, step in effective_steps(run_dir)})
|
||||
|
||||
|
||||
def eval_env(config: dict) -> str | None:
|
||||
"""The taskset(s) of an eval run: the ``[[source]]`` list, else a single ``[env]``."""
|
||||
sources = config.get("source") or []
|
||||
if sources:
|
||||
return "+".join(((s.get("env") or {}).get("taskset") or {}).get("id") or "?" for s in sources)
|
||||
return ((config.get("env") or {}).get("taskset") or {}).get("id")
|
||||
|
||||
|
||||
def source_total_episodes(source: dict) -> int | None:
|
||||
"""What one ``[[source]]`` will produce, from its config alone: ``num_examples = -1``
|
||||
means the whole taskset, unknown up front unless the source names its tasks."""
|
||||
tasks = ((source.get("env") or {}).get("taskset") or {}).get("tasks")
|
||||
count = source.get("num_examples") or -1
|
||||
if count < 0 and not tasks:
|
||||
return None
|
||||
return (count if count >= 0 else len(tasks)) * (source.get("group_size") or 1)
|
||||
|
||||
|
||||
def eval_totals(config: dict) -> dict[str, int | None]:
|
||||
"""Expected episodes per eval env (a source's name, else its taskset id)."""
|
||||
return {
|
||||
s.get("name") or ((s.get("env") or {}).get("taskset") or {}).get("id") or "?": source_total_episodes(s)
|
||||
for s in config.get("source") or []
|
||||
}
|
||||
|
||||
|
||||
def eval_total_episodes(config: dict) -> int | None:
|
||||
sources = config.get("source") or []
|
||||
if sources:
|
||||
totals = [source_total_episodes(s) for s in sources]
|
||||
return None if any(t is None for t in totals) else sum(totals) or None
|
||||
return (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None
|
||||
|
||||
|
||||
def run_meta(run_dir: Path) -> dict:
|
||||
configs = run_dir / "configs"
|
||||
run_type, config = main_config(run_dir)
|
||||
@@ -278,18 +317,43 @@ def run_meta(run_dir: Path) -> dict:
|
||||
started = orjson.loads(f.readline()).get("time")
|
||||
except orjson.JSONDecodeError:
|
||||
started = None
|
||||
# Liveness reads every artifact the processes touch: an eval ships its metrics at
|
||||
# epoch end and its first episode can take minutes, but its log ticks every few
|
||||
# seconds. The launch itself is the start until a metrics row says otherwise.
|
||||
stream = traces_file(run_dir)
|
||||
if updated is None and stream is not None: # eval runs have no metrics
|
||||
updated = stream.stat().st_mtime
|
||||
started = configs.stat().st_mtime if configs.is_dir() else None
|
||||
touched = []
|
||||
for path in (run_dir / "logs" / "latest").glob("*.log"):
|
||||
try:
|
||||
touched.append(path.stat().st_mtime)
|
||||
except FileNotFoundError:
|
||||
continue # rotated away between the listing and the stat
|
||||
if stream is not None:
|
||||
touched.append(stream.stat().st_mtime)
|
||||
if touched:
|
||||
updated = max(touched + ([updated] if updated is not None else []))
|
||||
# An eval writes its only metrics row at the end of the epoch, so its start is the
|
||||
# launch, not that row; a training run's first row follows its launch closely.
|
||||
if (started is None or run_type == "eval") and resolved.is_dir():
|
||||
started = resolved.stat().st_mtime
|
||||
# An eval has no step horizon; it is complete when its file monitor finalized, which
|
||||
# only a clean exit does: the stream's live chunk is sealed and nothing plain is left.
|
||||
finished = run_type == "eval" and stream is not None and stream.is_dir() and not any(stream.glob("*.jsonl"))
|
||||
plan_path = get_eval_plan_path(run_dir)
|
||||
eval_plan = orjson.loads(plan_path.read_bytes()) if plan_path.is_file() else {}
|
||||
platform_path = get_platform_run_path(run_dir)
|
||||
platform = orjson.loads(platform_path.read_bytes()) if platform_path.is_file() else None
|
||||
return {
|
||||
"name": run_dir.name,
|
||||
"type": run_type,
|
||||
"finished": finished,
|
||||
"eval_plan": eval_plan,
|
||||
"platform": platform,
|
||||
"model": model_name(config),
|
||||
"dataset": (config.get("data") or {}).get("name"),
|
||||
"has_validation": run_type == "sft" and config.get("val") is not None,
|
||||
"env": ((config.get("env") or {}).get("taskset") or {}).get("id"),
|
||||
"total_episodes": (config.get("num_tasks") or 0) * (config.get("num_rollouts") or 0) or None,
|
||||
"env": eval_env(config),
|
||||
"total_episodes": eval_total_episodes(config),
|
||||
"eval_totals": eval_totals(config),
|
||||
"max_steps": config.get("max_steps"),
|
||||
"train_envs": envs("train"),
|
||||
"eval_envs": envs("eval"),
|
||||
@@ -329,8 +393,7 @@ def log_component(rel: Path) -> tuple[str, str]:
|
||||
"trainer.log": ("trainer", "trainer"),
|
||||
"orchestrator.log": ("orch", "orchestrator"),
|
||||
"inference.log": ("infer", "inference"),
|
||||
"evals.log": ("evals", "evals"),
|
||||
"eval.log": ("evals", "eval"),
|
||||
"eval.log": ("eval", "eval"),
|
||||
}.get(parts[0], ("other", parts[0]))
|
||||
if parts[0] == "trainer":
|
||||
if parts[1] == "torchrun": # trainer/torchrun/<rdzv>/attempt_0/<rank>/std{out,err}.log
|
||||
@@ -377,7 +440,7 @@ def list_logfiles(run: str, attempt: str = "latest") -> dict:
|
||||
add(path, component, label)
|
||||
# Include unscoped env logs from runs created before attempt-scoped eval logging.
|
||||
for path in sorted((run_dir / "logs" / "envs").rglob("*.log")):
|
||||
add(path, f"env:{path.stem}", f"{path.stem} (evals)")
|
||||
add(path, f"env:{path.stem}", f"{path.stem} (eval)")
|
||||
return {"attempt": attempt_num, "attempts": attempts, "files": files}
|
||||
|
||||
|
||||
@@ -408,7 +471,7 @@ def read_log(run: str, file: str, start: int | None = None, end: int | None = No
|
||||
|
||||
# ------------------------------------------------------------------------- configs
|
||||
|
||||
CONFIG_ORDER = ["rl", "sft", "eval", "evals", "orchestrator", "trainer", "inference"]
|
||||
CONFIG_ORDER = ["rl", "sft", "eval", "orchestrator", "trainer", "inference"]
|
||||
|
||||
|
||||
def config_rank(name: str) -> tuple[int, str]:
|
||||
@@ -489,7 +552,7 @@ def read_report(run: str, file: str) -> dict:
|
||||
# ------------------------------------------------------------------------- metrics
|
||||
|
||||
|
||||
MAX_METRICS_CHUNK = 4 * 1024 * 1024
|
||||
MAX_METRICS_CHUNK = 16 * 1024 * 1024
|
||||
"""Per-response cap on /metrics: huge runs stream in chunks the client loops over,
|
||||
so the first charts paint long before a 100MB metrics.jsonl finishes loading."""
|
||||
|
||||
@@ -505,7 +568,9 @@ def read_metrics(run: str, offset: int = 0) -> dict:
|
||||
rows = []
|
||||
with path.open("rb") as f:
|
||||
f.seek(offset)
|
||||
data = f.read(MAX_METRICS_CHUNK)
|
||||
# Keep the first response small for quick initial chart rendering.
|
||||
chunk_size = 4 * 1024 * 1024 if offset == 0 else MAX_METRICS_CHUNK
|
||||
data = f.read(chunk_size)
|
||||
if data and b"\n" not in data: # a single line larger than the chunk
|
||||
data += f.readline()
|
||||
consumed = data.rfind(b"\n") + 1 # leave a partially-written last line for the next poll
|
||||
@@ -529,8 +594,7 @@ def _file_size(path: Path) -> int:
|
||||
|
||||
def traces_file(run_dir: Path) -> Path | None:
|
||||
"""The run's episode stream: the chunk directory the file monitor writes, browsed
|
||||
through its index, or the single ``traces.jsonl`` a verifiers ``uv run eval`` run
|
||||
writes at the run root."""
|
||||
through its index, or a bare ``traces.jsonl`` at the run root."""
|
||||
stream = get_trace_stream(run_dir)
|
||||
if _file_size(get_index_path(stream)) > 0:
|
||||
return stream
|
||||
@@ -1687,6 +1751,51 @@ def rendered_token_text(trace: dict, model: str | None) -> dict:
|
||||
}
|
||||
|
||||
|
||||
_live_folds = LiveFolds()
|
||||
"""The dashboard's incremental folds of every run's live files."""
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/live")
|
||||
def live_traces(run: str, etag: str | None = None) -> dict:
|
||||
"""The run's in-flight traces, folded from the env servers' streamed deltas
|
||||
(``monitors/file/traces/live/<trace_id>.jsonl``): one row per live trace with its
|
||||
phase, turns, tokens, cost, elapsed time and last message. A trace whose file is
|
||||
gone has finished and sits in the stream. ``etag`` is the fingerprint the client
|
||||
last saw: an unchanged live set answers a poll with ``{unchanged}``."""
|
||||
run_dir = get_run_dir(run)
|
||||
current = live_etag(run_dir)
|
||||
if etag is not None and etag == current:
|
||||
return {"unchanged": True}
|
||||
return {"time": time.time(), "etag": current, "rows": live_rows(run_dir, _live_folds)}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/live/{trace_id}")
|
||||
def live_trace(run: str, trace_id: str, etag: str | None = None) -> dict:
|
||||
"""One in-flight trace assembled from its deltas, shaped like a stream record (an
|
||||
episode with this one trace) so the trace viewer renders it as it grows. ``etag``
|
||||
is the file size the client last folded: nothing appended means ``{unchanged}``."""
|
||||
path = live_path(get_run_dir(run), trace_id)
|
||||
try:
|
||||
size = path.stat().st_size # before the read: a delta landing in between shows up next poll
|
||||
except FileNotFoundError:
|
||||
raise HTTPException(404, "live trace not found - its episode finished or never streamed")
|
||||
if etag is not None and etag == str(size):
|
||||
return {"unchanged": True}
|
||||
folded = _live_folds.read(path)
|
||||
if folded is None:
|
||||
raise HTTPException(404, "live trace not found - its episode finished or never streamed")
|
||||
dispatch, trace = folded
|
||||
return {
|
||||
"id": None,
|
||||
"etag": str(size),
|
||||
"kind": dispatch.get("kind"),
|
||||
"env": {"name": dispatch.get("env")},
|
||||
"group": {"id": dispatch.get("group")},
|
||||
"live": {**dispatch, "stage": stage(trace)},
|
||||
"traces": [trace],
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run}/episodes/series")
|
||||
def episode_series(run: str, kind: str | None = None, etag: str | None = None, after: int = 0) -> dict:
|
||||
"""Per-episode series over the stream (x = arrival order): reward, shape, and the
|
||||
@@ -1698,15 +1807,37 @@ def episode_series(run: str, kind: str | None = None, etag: str | None = None, a
|
||||
if etag is not None and etag == current_etag:
|
||||
return {"unchanged": True, "etag": current_etag}
|
||||
summaries = [s for s in episode_summaries(path) if not kind or s.get("kind") == kind]
|
||||
keys: set[str] = set()
|
||||
for s in summaries:
|
||||
# the key set only grows: rescan the summaries past the ones already scanned
|
||||
with _lock:
|
||||
scanned, keys = _series_keys.get((path, kind)) or (0, set())
|
||||
if scanned > len(summaries):
|
||||
scanned, keys = 0, set()
|
||||
for s in summaries[scanned:]:
|
||||
keys.update(
|
||||
k
|
||||
for k in ("reward", "advantage", "cost", "turns", "branches", "input_tokens", "output_tokens")
|
||||
for k in (
|
||||
"env",
|
||||
"group",
|
||||
"line",
|
||||
"ok",
|
||||
"num_errors",
|
||||
"truncated",
|
||||
"stop_condition",
|
||||
"duration",
|
||||
"reward",
|
||||
"advantage",
|
||||
"cost",
|
||||
"turns",
|
||||
"branches",
|
||||
"input_tokens",
|
||||
"output_tokens",
|
||||
)
|
||||
if s.get(k) is not None
|
||||
)
|
||||
for group in ("rewards", "metrics", "timing"):
|
||||
keys.update(f"{group}/{name}" for name in s.get(group) or {})
|
||||
with _lock:
|
||||
_series_keys[(path, kind)] = (len(summaries), keys)
|
||||
|
||||
def value(s: dict, key: str):
|
||||
group, _, name = key.partition("/")
|
||||
@@ -1982,6 +2113,17 @@ def get_episode_timeline(run: str, line: int) -> dict:
|
||||
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def revalidate_static(request, call_next):
|
||||
"""The page and its assets change with the checkout the daemon runs; a reload must
|
||||
revalidate them (an ETag answers 304 when unchanged) instead of trusting a heuristic
|
||||
freshness from ``Last-Modified``."""
|
||||
response = await call_next(request)
|
||||
if request.url.path == "/" or request.url.path.startswith("/static/"):
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index() -> FileResponse:
|
||||
return FileResponse(STATIC_DIR / "index.html")
|
||||
|
||||
+1402
-253
File diff suppressed because it is too large
Load Diff
@@ -21,29 +21,57 @@
|
||||
</div>
|
||||
<nav id="tabs">
|
||||
<button data-tab="config">Config</button>
|
||||
<button data-tab="metrics" class="active">Metrics</button>
|
||||
<button data-tab="overview" class="active">Overview</button>
|
||||
<button data-tab="metrics">Metrics</button>
|
||||
<button data-tab="traces">Traces</button>
|
||||
<button data-tab="report">Report</button>
|
||||
<button data-tab="logs">Logs</button>
|
||||
</nav>
|
||||
<label class="toggle" title="apply agent view commands as they arrive"><input type="checkbox" id="follow-toggle" checked><span class="dot"></span>follow</label>
|
||||
<label class="toggle" title="poll for updates"><input type="checkbox" id="live-toggle" checked><span class="dot"></span>live</label>
|
||||
<div id="platform-wrap" class="dd-wrap" hidden>
|
||||
<a id="platform-link" class="btn platform" target="_blank" rel="noopener">view on platform<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 17L17 7M9 7h8v8"></path></svg></a>
|
||||
<button id="platform-btn" class="btn dd-btn platform" hidden>view on platform</button>
|
||||
<div class="dd-menu" id="platform-menu" hidden></div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="run-overview"></div>
|
||||
|
||||
<main>
|
||||
<section id="tab-metrics">
|
||||
<section id="tab-overview">
|
||||
<div class="controls">
|
||||
<div class="seg" id="metrics-mode">
|
||||
<button data-mode="overview" class="active">Overview</button>
|
||||
<button data-mode="all">All</button>
|
||||
<div id="overview-filter-wrap" class="dd-wrap" hidden>
|
||||
<button id="overview-filter-btn" class="btn dd-btn" title="filter">
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
|
||||
filter
|
||||
</button>
|
||||
<div class="dd-menu dd-filters" id="overview-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<label class="dd-row" id="overview-env-row"><span class="t-label">env</span>
|
||||
<select id="overview-env"></select>
|
||||
</label>
|
||||
<label class="toggle dd-row"><input type="checkbox" id="overview-errors"><span class="dot"></span>include errors</label>
|
||||
</div>
|
||||
</div>
|
||||
<input id="overview-search" class="search" type="search" placeholder="regex filter, e.g. reward or ^inference/">
|
||||
<label class="ctl">smooth <input id="overview-smooth" type="range" min="1" max="50" value="1"><span id="overview-smooth-val">off</span></label>
|
||||
<span id="overview-status" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<button id="overview-collapse" class="btn">collapse</button>
|
||||
<button id="overview-expand" class="btn">expand</button>
|
||||
</div>
|
||||
<div id="overview-body"></div>
|
||||
<div id="swarm-tip" hidden></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-metrics" hidden>
|
||||
<div class="controls">
|
||||
<input id="metrics-search" class="search" type="search" placeholder="regex filter, e.g. ^entropy/ or reward">
|
||||
<label class="ctl">smooth <input id="smooth-range" type="range" min="1" max="50" value="1"><span id="smooth-val">off</span></label>
|
||||
<label class="ctl">smooth <input id="metrics-smooth" type="range" min="1" max="50" value="1"><span id="metrics-smooth-val">off</span></label>
|
||||
<span id="metrics-status" class="muted"></span>
|
||||
<div class="spacer"></div>
|
||||
<div class="seg" id="all-layout" hidden>
|
||||
<div class="seg" id="metrics-layout">
|
||||
<button data-layout="flat">Flat</button>
|
||||
<button data-layout="nested">Nested</button>
|
||||
</div>
|
||||
@@ -91,6 +119,12 @@
|
||||
</button>
|
||||
<div class="dd-menu dd-filters" id="trace-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<div class="dd-row"><span class="t-label">status</span>
|
||||
<div class="seg toggle-seg" id="trace-status-filter">
|
||||
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
|
||||
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dd-row"><span class="t-label">kind</span>
|
||||
<div class="seg toggle-seg" id="trace-kinds">
|
||||
<button data-kind="train" class="on">train</button>
|
||||
@@ -130,9 +164,13 @@
|
||||
</div>
|
||||
<div id="episode-table-wrap">
|
||||
<table id="episode-table">
|
||||
<colgroup>
|
||||
<col class="c-line"><col class="c-phase"><col class="c-span"><col class="c-kind"><col class="c-env"><col class="c-group">
|
||||
<col class="c-tok"><col class="c-turns"><col class="c-branches"><col class="c-stop"><col class="c-reward">
|
||||
</colgroup>
|
||||
<thead><tr>
|
||||
<th>#</th><th>arrived</th><th>took</th><th>kind</th><th>env</th><th>group</th><th>reward</th>
|
||||
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
|
||||
<th>#</th><th>phase</th><th title="when the rollout was dispatched, when its episode arrived, and how long that took (or has taken so far)">dispatched → arrived</th><th>kind</th><th>env</th><th>group</th>
|
||||
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>reward</th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
@@ -179,7 +217,7 @@
|
||||
<aside id="tm-left">
|
||||
<div class="tm-head tm-stephead" id="tm-stephead">
|
||||
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
|
||||
<span id="tm-step-label"></span>
|
||||
<span id="tm-step-label"></span><span id="tm-live-label" class="muted"></span>
|
||||
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
|
||||
</div>
|
||||
<div class="tm-head tm-ctlrow">
|
||||
@@ -190,6 +228,12 @@
|
||||
</button>
|
||||
<div class="dd-menu dd-filters" id="tm-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<div class="dd-row"><span class="t-label">status</span>
|
||||
<div class="seg toggle-seg" id="tm-status-filter">
|
||||
<button data-status="live" class="on" title="live rollouts, streamed by their env servers">live</button>
|
||||
<button data-status="done" class="on" title="episodes in the finished stream">completed</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dd-row"><span class="t-label">kind</span>
|
||||
<div class="seg toggle-seg" id="tm-kinds">
|
||||
<button data-kind="train" class="on">train</button>
|
||||
|
||||
@@ -90,6 +90,15 @@ body {
|
||||
#tabs button:hover { color: var(--grey-6); }
|
||||
#tabs button.active { color: var(--accent); border-bottom-color: var(--accent); }
|
||||
#topbar .toggle { margin-left: auto; }
|
||||
#topbar .toggle + .toggle { margin-left: 0; }
|
||||
#platform-wrap { margin-left: 14px; }
|
||||
/* looks like the run and compare pickers; the arrow says it leaves the page */
|
||||
#platform-wrap .platform { display: inline-flex; align-items: center; gap: 8px; text-decoration: none; cursor: pointer; }
|
||||
#platform-wrap .platform:hover { color: var(--accent); border-color: var(--accent); }
|
||||
#platform-wrap .platform.disabled { color: var(--grey-4); border-color: var(--grey-3); cursor: default; }
|
||||
#platform-menu { left: auto; right: 0; min-width: 180px; }
|
||||
#platform-menu .dd-opt { display: block; color: var(--grey-5); text-decoration: none; }
|
||||
#platform-menu .dd-opt:hover { color: var(--grey-6); }
|
||||
|
||||
select, .search, .btn {
|
||||
background: transparent;
|
||||
@@ -297,12 +306,14 @@ main > section { flex: 1; min-height: 0; display: flex; flex-direction: column;
|
||||
|
||||
/* --------------------------------------------------------------- metrics */
|
||||
/* stable gutter: no layout shift when collapsing sections hides the scrollbar */
|
||||
#metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
|
||||
#overview-body, #metrics-body { flex: 1; overflow-y: auto; scrollbar-gutter: stable; min-height: 0; padding-right: 10px; }
|
||||
.chart-card.dragging { opacity: 0.45; }
|
||||
/* one 12px rhythm everywhere: section-to-section, header-to-panes, pane-to-pane */
|
||||
details.section { margin-bottom: 12px; }
|
||||
/* nested sections (all-mode key tree) indent one step */
|
||||
details.section details.section { margin-left: 14px; }
|
||||
/* a section's own panes keep the rhythm before the sections nested under them */
|
||||
details.section > .chart-grid:not(:last-child) { margin-bottom: 12px; }
|
||||
details.section:not([open]) > summary { margin-bottom: 0; }
|
||||
/* section headers are full-width bars so the clickable region is obvious */
|
||||
details.section > summary {
|
||||
@@ -336,9 +347,85 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.stat-value { font-size: 20px; color: var(--grey-6); margin: 6px 0 0; }
|
||||
.eval-progress { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
|
||||
.ep-bar { flex: 1; height: 6px; background: var(--grey-2); border: 1px solid var(--hairline); }
|
||||
.ep-fill { height: 100%; background: var(--accent); }
|
||||
/* eval progress: one cell per expected episode */
|
||||
.eval-progress { display: flex; flex-direction: column; gap: 8px; margin-bottom: 16px; }
|
||||
.ep-head { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
|
||||
.ep-row { display: flex; align-items: center; gap: 12px; }
|
||||
.ep-row .ep-blocks { flex: 1; }
|
||||
.ep-pct { font-size: 13px; color: var(--grey-6); min-width: 4ch; text-align: right; }
|
||||
.ep-head .name { font-size: 14px; color: var(--grey-6); }
|
||||
.ep-blocks { display: flex; gap: 2px; height: 28px; }
|
||||
.ep-cell { flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); }
|
||||
.ep-cell.done { background: var(--accent); border-color: var(--accent); cursor: pointer; }
|
||||
.ep-cell.done.err { background: var(--negative); border-color: var(--negative); }
|
||||
.ep-cell.done:hover { filter: brightness(1.2); }
|
||||
.ep-cell.live { border-color: var(--accent); background: rgba(182, 255, 60, 0.18); animation: live-pulse 1.6s ease-in-out infinite; cursor: pointer; }
|
||||
|
||||
/* distributions: a beeswarm per metric, a faint boxplot behind it, stats on hover */
|
||||
#tab-overview { position: relative; }
|
||||
.swarm-card .chart-head { cursor: default; }
|
||||
.swarm-host { height: var(--pane-h, 150px); margin-top: 6px; }
|
||||
.swarm { display: block; }
|
||||
.swarm .sw-bg { fill: transparent; }
|
||||
.swarm circle { fill: var(--accent); fill-opacity: 0.7; cursor: pointer; }
|
||||
.swarm circle.err { fill: var(--negative); }
|
||||
.swarm circle:hover { fill-opacity: 1; stroke: var(--grey-6); stroke-width: 1; }
|
||||
.sw-axis { stroke: var(--grey-3); stroke-width: 1; }
|
||||
.sw-grid { stroke: var(--hairline-faint); stroke-width: 1; }
|
||||
.sw-box rect { fill: var(--hairline-faint); stroke: var(--grey-3); stroke-width: 1; }
|
||||
.sw-box line { stroke: var(--grey-3); stroke-width: 1; }
|
||||
.sw-box .median { stroke: var(--grey-4); stroke-width: 1.5; }
|
||||
/* timing pane: breadcrumb, icicle of the zoomed node, per-episode strips, tree legend */
|
||||
/* eval metrics sections: flat, a muted heading each */
|
||||
.eval-sec { margin-bottom: 18px; }
|
||||
.eval-sec-title { text-transform: uppercase; font-size: 10px; letter-spacing: 0.08em; color: var(--grey-4); border-bottom: 1px solid var(--hairline); padding-bottom: 4px; margin-bottom: 10px; }
|
||||
.phase-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; margin-right: 6px; vertical-align: middle; }
|
||||
.timing-pane .chart-head { cursor: default; }
|
||||
.tm-crumbs { font-size: 12px; color: var(--grey-5); }
|
||||
.tm-crumb.current { color: var(--grey-6); }
|
||||
.tm-legend { display: flex; flex-wrap: wrap; gap: 4px 18px; margin: 4px 0 14px; font-size: 11px; color: var(--grey-5); }
|
||||
.tm-icicle svg { display: block; margin-bottom: 14px; }
|
||||
.tm-seg text { fill: #111; font-size: 10px; pointer-events: none; }
|
||||
.tm-strip-seg { cursor: pointer; }
|
||||
.tm-row-hit { fill: transparent; cursor: pointer; }
|
||||
.tm-line.dim { opacity: 0.3; }
|
||||
.tm-strip-seg.dim { opacity: 0.2; }
|
||||
.tm-strip-seg:hover { filter: brightness(1.25); }
|
||||
.tm-line.err { fill: var(--negative); }
|
||||
.comp-pane [data-part].dim { opacity: 0.2; }
|
||||
.comp-pane .tm-node.dim { opacity: 0.35; }
|
||||
/* the summary is one row whatever the count: the tiles share the width equally */
|
||||
.sum-grid { margin-bottom: 4px; display: grid; grid-template-columns: none; grid-auto-flow: column; grid-auto-columns: minmax(0, 1fr); gap: 12px; }
|
||||
.sum-tile { cursor: default; padding: 14px 16px; min-height: 96px; display: flex; flex-direction: column; justify-content: center; }
|
||||
.sum-tile .stat-label, .sum-tile .stat-value { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.sum-tile .stat-value { font-size: clamp(16px, 1.7vw, 24px); margin-top: 8px; }
|
||||
.sum-tile.rate-warn .stat-value { color: #ffd166; }
|
||||
.sum-tile.rate-bad .stat-value { color: var(--negative); }
|
||||
.tm-note { font-size: 10px; margin-top: 4px; }
|
||||
.tm-more { color: var(--grey-5); cursor: pointer; text-decoration: underline dotted; text-underline-offset: 3px; }
|
||||
.tm-more:hover { color: var(--grey-6); }
|
||||
.tm-strips.scroll { max-height: 560px; overflow-y: auto; }
|
||||
.tm-node { white-space: nowrap; cursor: default; }
|
||||
.tm-node:hover { color: var(--grey-6); }
|
||||
/* constants as chips; counted dot plots for few-valued metrics */
|
||||
.const-row { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
|
||||
.const-chip { font-size: 12px; color: var(--grey-6); background: var(--grey-2); border: 1px solid var(--hairline); padding: 4px 10px; }
|
||||
.const-chip .k { color: var(--grey-4); font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em; margin-right: 8px; }
|
||||
.dp-count { fill: var(--grey-5); font-size: 10px; }
|
||||
#swarm-tip {
|
||||
position: absolute;
|
||||
z-index: 50;
|
||||
pointer-events: none;
|
||||
background: var(--grey-1);
|
||||
border: 1px solid var(--grey-3);
|
||||
padding: 6px 8px;
|
||||
min-width: 160px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
|
||||
font-size: 11px;
|
||||
}
|
||||
#swarm-tip .tip-head { color: var(--accent); margin-bottom: 4px; }
|
||||
#swarm-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
|
||||
#swarm-tip .tip-row span:first-child { color: var(--grey-4); }
|
||||
.ep-label {
|
||||
font-size: 10px;
|
||||
letter-spacing: var(--track-caps);
|
||||
@@ -443,7 +530,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
|
||||
|
||||
/* metrics regex filter (overview + all) */
|
||||
#metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
|
||||
#overview-search, #metrics-search, #config-search, #log-search { flex: 1; max-width: 460px; }
|
||||
|
||||
/* wandb-style resize handles on every chart card: right edge = width, bottom
|
||||
edge = height, corner = both. Resizing one pane resizes all of them. */
|
||||
@@ -633,7 +720,7 @@ mark.hit {
|
||||
.sb-cell.eval:hover::after { background: var(--grey-6); }
|
||||
#trace-filter-menu {
|
||||
right: 0;
|
||||
min-width: 240px;
|
||||
min-width: 320px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
@@ -643,7 +730,21 @@ mark.hit {
|
||||
|
||||
#episode-table-wrap { flex: 1; overflow: auto; border: 1px solid var(--hairline); background: var(--grey-1); min-height: 0; }
|
||||
#episode-table .vpad td { padding: 0; border: 0; }
|
||||
#episode-table { width: 100%; border-collapse: collapse; font-size: 11.5px; }
|
||||
/* fixed columns: a poll that swaps rows in or out never reflows the table. The sized
|
||||
columns hold mono text whose width follows the font, not the window, so they are
|
||||
measured in characters; env and stop take what is left, and below the minimum the
|
||||
wrap scrolls sideways instead of crushing them. */
|
||||
#episode-table { width: 100%; min-width: 190ch; border-collapse: collapse; font-size: 11.5px; table-layout: fixed; }
|
||||
#episode-table col.c-line { width: 7.5ch; }
|
||||
#episode-table col.c-phase { width: 11.5ch; }
|
||||
#episode-table col.c-span { width: 50ch; }
|
||||
#episode-table col.c-kind { width: 8.5ch; }
|
||||
#episode-table col.c-group { width: 13.5ch; }
|
||||
#episode-table col.c-tok { width: 25ch; }
|
||||
#episode-table col.c-turns { width: 9ch; }
|
||||
#episode-table col.c-branches { width: 12.5ch; }
|
||||
#episode-table col.c-reward { width: 10.5ch; }
|
||||
#episode-table td, #episode-table th { overflow: hidden; text-overflow: ellipsis; }
|
||||
#episode-table th {
|
||||
text-align: left;
|
||||
font: 400 10px var(--font-mono);
|
||||
@@ -1102,6 +1203,7 @@ mark.hit {
|
||||
|
||||
/* numbered collapsible message entries */
|
||||
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
|
||||
details.entry.pending { opacity: 0.55; border-style: dashed; }
|
||||
details.entry.semantic-origin {
|
||||
border-color: var(--accent);
|
||||
outline: 1px solid rgba(182, 255, 60, 0.55);
|
||||
@@ -1523,7 +1625,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
|
||||
|
||||
|
||||
/* filter & sort popover */
|
||||
.dd-filters { min-width: 210px; display: flex; flex-direction: column; gap: 6px; }
|
||||
.dd-filters { min-width: 320px; display: flex; flex-direction: column; gap: 6px; }
|
||||
.dd-sec {
|
||||
text-transform: uppercase;
|
||||
font-size: 10px;
|
||||
@@ -1534,6 +1636,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
|
||||
margin-top: 2px;
|
||||
}
|
||||
.dd-filters .dd-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin: 0; }
|
||||
.dd-filters .seg button { padding: 0 9px; }
|
||||
/* controls sit right, sized to their content, so the label reads as the row's subject */
|
||||
.dd-filters .dd-row select, .dd-filters .dd-row .dd-select, .dd-filters .dd-row .seg { margin-left: auto; }
|
||||
.dd-filters .dd-row .dd-btn { justify-content: space-between; gap: 8px; }
|
||||
@@ -1589,3 +1692,13 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
|
||||
background: var(--grey-2);
|
||||
border-bottom: 1px solid var(--hairline);
|
||||
}
|
||||
|
||||
/* in-flight rollouts share the episode table; the phase badge and a pulsing dot in
|
||||
place of their number set them apart */
|
||||
.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: live-pulse 2s ease-out infinite; }
|
||||
#episode-table tr.err td:first-child { border-left: 2px solid var(--negative); }
|
||||
#episode-table tr.live.landing .live-dot { animation: none; opacity: 0.45; }
|
||||
.badge.stage { font-size: 9px; padding: 2px 5px; line-height: 12px; border-radius: 3px; background: var(--hairline); border-color: transparent; color: var(--accent); }
|
||||
#tm-live-label { margin-left: 8px; }
|
||||
#log-comp-menu .file-item.sub { padding-left: 22px; }
|
||||
#episode-table .day { margin-right: 8px; }
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
|
||||
from verifiers.v1 import pool_serve_kwargs
|
||||
from verifiers.v1.runtimes import set_base_sandbox_labels
|
||||
@@ -17,15 +20,30 @@ def setup_worker(log_level: str | None, json_logging: bool, sandbox_labels: list
|
||||
set_base_sandbox_labels(sandbox_labels)
|
||||
|
||||
|
||||
def publish_address(addresses: queue.SimpleQueue, path: Path) -> None:
|
||||
"""Write the bound address once serve_env reports it (it blocks in the server loop
|
||||
afterwards). Atomic, so a waiting client never reads a partial line."""
|
||||
address = addresses.get()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".address.tmp")
|
||||
tmp.write_text(address)
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
@clean_exit
|
||||
def run_server(config: EnvServerConfig):
|
||||
run_name = os.environ.get("PRL_RUN_NAME")
|
||||
sandbox_labels = [run_name] if run_name else []
|
||||
addresses: queue.SimpleQueue | None = None
|
||||
if config.address_file is not None:
|
||||
addresses = queue.SimpleQueue()
|
||||
threading.Thread(target=publish_address, args=(addresses, config.address_file), daemon=True).start()
|
||||
# ``serve.pool`` (static or elastic) sizes the server. serve_env applies the worker
|
||||
# setup in this process and in every spawned worker.
|
||||
serve_env(
|
||||
**pool_serve_kwargs(config.serve.pool),
|
||||
address=config.serve.address,
|
||||
address=config.serve.address or "tcp://127.0.0.1:0",
|
||||
address_queue=addresses,
|
||||
log_setup=partial(setup_worker, config.log.level, config.log.json_logging, sandbox_labels),
|
||||
config_data=env_config_data(config.env),
|
||||
max_concurrent=config.serve.max_concurrent,
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Launcher for ``uv run eval``: one epoch of every configured eval source.
|
||||
|
||||
Defers heavy ML imports until after the config is parsed, so ``eval --help``
|
||||
short-circuits. The implementation lives in ``prime_rl.eval.eval``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import sys
|
||||
import tomllib
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from typing import Any
|
||||
|
||||
from prime_rl.configs.eval import EvalConfig
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes, set_proc_title
|
||||
|
||||
USAGE = """\
|
||||
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-r N] [-c N] [-m MODEL] [options]
|
||||
uv run eval @ eval.toml [options] multi-source runs ([[source]] blocks)
|
||||
uv run eval @ eval.toml --run.name <name> --resume resume an interrupted run
|
||||
|
||||
Shorthands for a single-source run:
|
||||
<taskset-id> the taskset of the run's only source
|
||||
--env.<field> <value> a field of that source's env block (e.g. --env.agent.harness.id bash)
|
||||
-c N pin the concurrency band (concurrency.min_inflight = max_inflight = N)
|
||||
"""
|
||||
|
||||
NUMBER = re.compile(r"-?\d+(\.\d+)?")
|
||||
|
||||
|
||||
def set_nested(target: dict[str, Any], keys: list[str], value: Any) -> None:
|
||||
for key in keys[:-1]:
|
||||
target = target.setdefault(key, {})
|
||||
target[keys[-1]] = value
|
||||
|
||||
|
||||
def parse_value(raw: str) -> Any:
|
||||
"""A JSON list/object stays structured; every other value is left to pydantic."""
|
||||
return json.loads(raw) if raw.startswith(("[", "{")) else raw
|
||||
|
||||
|
||||
def expand_shorthands(argv: list[str]) -> list[str]:
|
||||
"""Rewrite the single-source shorthands into flags ``EvalConfig`` parses.
|
||||
|
||||
``<taskset-id>`` and ``--env.<path> <value>`` describe the run's only source and fold
|
||||
into one JSON ``--source`` flag (pydantic-config has no list-index paths, so
|
||||
``--source.0.env...`` cannot address it). ``-c N`` pins the concurrency band.
|
||||
Everything else passes through untouched.
|
||||
"""
|
||||
out: list[str] = []
|
||||
source: dict[str, Any] = {}
|
||||
rest = list(argv)
|
||||
if rest and not rest[0].startswith(("-", "@")):
|
||||
set_nested(source, ["env", "taskset", "id"], rest.pop(0))
|
||||
i = 0
|
||||
while i < len(rest):
|
||||
arg = rest[i]
|
||||
flag, has_value, value = arg.partition("=")
|
||||
if not has_value and (flag.startswith("--env.") or flag == "-c"):
|
||||
if i + 1 >= len(rest) or (rest[i + 1].startswith("-") and not NUMBER.fullmatch(rest[i + 1])):
|
||||
raise SystemExit(f"{flag} needs a value")
|
||||
i += 1
|
||||
value = rest[i]
|
||||
if flag.startswith("--env."):
|
||||
set_nested(source, [key.replace("-", "_") for key in flag[2:].split(".")], parse_value(value))
|
||||
elif flag == "-c":
|
||||
out += ["--concurrency.min_inflight", value, "--concurrency.max_inflight", value]
|
||||
else:
|
||||
out.append(arg)
|
||||
i += 1
|
||||
if source:
|
||||
if any(toml_defines_source(path) for path in root_config_files(argv)):
|
||||
raise SystemExit(
|
||||
"The <taskset-id> / --env.* shorthands describe a single source and cannot be combined "
|
||||
"with a config file that defines [[source]] blocks - use one or the other"
|
||||
)
|
||||
out += ["--source", json.dumps([source])]
|
||||
return out
|
||||
|
||||
|
||||
def root_config_files(argv: list[str]) -> list[Path]:
|
||||
"""Root ``@ file`` references (a ``--flag @ file`` is a nested reference)."""
|
||||
return [
|
||||
Path(argv[i + 1])
|
||||
for i, arg in enumerate(argv[:-1])
|
||||
if arg == "@" and (i == 0 or not argv[i - 1].startswith("--"))
|
||||
]
|
||||
|
||||
|
||||
def toml_defines_source(path: Path) -> bool:
|
||||
if path.suffix != ".toml" or not path.is_file():
|
||||
return False
|
||||
with path.open("rb") as f:
|
||||
return "source" in tomllib.load(f)
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Eval")
|
||||
argv = sys.argv[1:]
|
||||
if not argv or any(arg in ("-h", "--help") for arg in argv):
|
||||
print(USAGE)
|
||||
sys.argv = [sys.argv[0], "--help"]
|
||||
cli(EvalConfig)
|
||||
return
|
||||
# The typed parse sees the expanded flags; the launch artifacts keep the command as typed.
|
||||
sys.argv = [sys.argv[0], *expand_shorthands(argv)]
|
||||
config = cli(EvalConfig)
|
||||
sys.argv = [sys.argv[0], *argv]
|
||||
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
format_config_message,
|
||||
format_log_message,
|
||||
prepare_attempt_dirs,
|
||||
validate_run_dir,
|
||||
write_env_server_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
|
||||
# The run identity is runtime-only: $PRL_RUN_ID / $PRL_RUN_NAME are stamped on
|
||||
# every episode and inherited by the env servers.
|
||||
os.environ.setdefault("PRL_RUN_ID", uuid.uuid4().hex)
|
||||
assert config.run.name is not None # resolved at construction
|
||||
os.environ["PRL_RUN_NAME"] = config.run.name
|
||||
|
||||
clean = config.clean and not os.environ.get("NEVER_CLEAN")
|
||||
validate_run_dir(config.run_dir, output_dir=config.output_dir, resuming=config.resume, clean=clean)
|
||||
config.run_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
|
||||
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
|
||||
log_file = log_dir / "eval.log"
|
||||
logger = setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file)
|
||||
logger.info("Starting eval")
|
||||
|
||||
write_launch_artifacts(config_dir, "eval")
|
||||
(config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
|
||||
components: list[tuple[str, Path | str]] = [("Eval", config_dir / "eval.json")]
|
||||
# One env server per source without an explicit `serve.address`, like the rl launcher's:
|
||||
# `env-server @ <path>` binds an OS-assigned port and publishes it to the source's
|
||||
# address file, where the eval picks it up.
|
||||
env_servers = [source for source in config.source if source.serve.address is None]
|
||||
env_names = [source.resolved_name for source in env_servers]
|
||||
if env_servers:
|
||||
components.append(("Envs", f"{config_dir}/envs/eval/*.json"))
|
||||
for source in env_servers:
|
||||
components.append(
|
||||
(f" {source.resolved_name}", write_env_server_config(config_dir, "eval", source, config.log))
|
||||
)
|
||||
if config.dry_run:
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
|
||||
logger.success("Dry run complete. To start the eval, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
from prime_rl.eval.eval import run_eval
|
||||
|
||||
processes: list[Popen] = []
|
||||
for source in env_servers:
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
env_server_log = log_dir / "envs" / "eval" / f"{name}.log"
|
||||
env_server_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(env_server_log, "w") as log_file_handle:
|
||||
processes.append(
|
||||
Popen(
|
||||
["env-server", "@", (config_dir / "envs" / "eval" / f"{name}.json").as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
|
||||
stdout=log_file_handle,
|
||||
stderr=log_file_handle,
|
||||
)
|
||||
)
|
||||
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'eval', components)}")
|
||||
logger.info(format_log_message(log_dir, eval=True, env_names={"eval": env_names}))
|
||||
|
||||
def sigterm_handler(signum, frame):
|
||||
logger.warning("Received SIGTERM, terminating all processes...")
|
||||
cleanup_processes(processes)
|
||||
sys.exit(1)
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Like the rl/sft launchers, the console stays quiet while the eval runs: results
|
||||
# live in the dashboard and the log file, only errors surface here.
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file, console_level="ERROR")
|
||||
try:
|
||||
asyncio.run(run_eval(config))
|
||||
finally:
|
||||
cleanup_processes(processes)
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging, log_file=log_file).success("Eval finished!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,34 +0,0 @@
|
||||
"""Lightweight launcher for the online evals.
|
||||
|
||||
Defers heavy ML imports until after ``cli()`` parses CLI args, so
|
||||
``evals --help`` short-circuits in ``cli()``. The actual implementation
|
||||
lives in ``prime_rl.evals.evals``.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("Evals")
|
||||
config = cli(EvalsConfig)
|
||||
from prime_rl.utils.pathing import prepare_attempt_dirs, write_launch_artifacts
|
||||
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
|
||||
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
|
||||
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
|
||||
os.environ["PRL_LOG_DIR"] = str(log_dir)
|
||||
write_launch_artifacts(config_dir, "evals")
|
||||
(config_dir / "evals.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
|
||||
from prime_rl.evals.evals import run_evals
|
||||
|
||||
asyncio.run(run_evals(config))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -181,6 +181,8 @@ def start_router(config: InferenceConfig) -> subprocess.Popen:
|
||||
str(config.vllm.data_parallel_size_local or config.vllm.data_parallel_size),
|
||||
"--request-id-headers",
|
||||
"x-session-id",
|
||||
"--request-timeout-secs",
|
||||
str(config.router.request_timeout_secs),
|
||||
"--worker-startup-timeout-secs",
|
||||
"4200",
|
||||
"--prometheus-port",
|
||||
|
||||
@@ -20,6 +20,7 @@ from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
format_config_message,
|
||||
format_log_message,
|
||||
get_ckpt_dir,
|
||||
get_launcher_dir,
|
||||
@@ -27,6 +28,7 @@ from prime_rl.utils.pathing import (
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_env_server_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
@@ -50,23 +52,18 @@ INFERENCE_CONFIG = "inference.json"
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
|
||||
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig, str]]:
|
||||
"""``(split, source, address)`` for every launcher-managed train/eval source. The
|
||||
launcher runs one env server per source at its deterministic address; the
|
||||
orchestrator connects there. A source with ``serve.address`` set is externally
|
||||
managed — its server runs elsewhere and only the orchestrator connects to it — so
|
||||
the launcher neither writes its TOML nor spawns a server for it."""
|
||||
addresses = config.orchestrator.env_addresses
|
||||
return [
|
||||
(split, source, addresses[(split, source.resolved_name)])
|
||||
for split, source in config.orchestrator.env_sources
|
||||
if source.serve.address is None
|
||||
]
|
||||
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig]]:
|
||||
"""``(split, source)`` for every launcher-managed train/eval source. The launcher
|
||||
runs one env server per source; each binds an OS-assigned port and publishes it to
|
||||
its address file, where the orchestrator picks it up. A source with ``serve.address``
|
||||
set is externally managed — its server runs elsewhere and only the orchestrator
|
||||
connects to it — so the launcher neither writes its TOML nor spawns a server for it."""
|
||||
return [(split, source) for split, source in config.orchestrator.env_sources if source.serve.address is None]
|
||||
|
||||
|
||||
def env_server_names(config: RLConfig, split: str) -> list[str]:
|
||||
"""Names of the launcher-managed env servers for one split."""
|
||||
return [source.resolved_name for source_split, source, _ in env_servers(config) if source_split == split]
|
||||
return [source.resolved_name for source_split, source in env_servers(config) if source_split == split]
|
||||
|
||||
|
||||
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
|
||||
@@ -76,6 +73,19 @@ def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None =
|
||||
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
|
||||
|
||||
|
||||
def rl_config_components(config: RLConfig, config_dir: Path) -> list[tuple[str, Path | str]]:
|
||||
"""The resolved per-component configs ``write_subconfigs`` leaves in ``config_dir``."""
|
||||
components: list[tuple[str, Path | str]] = [
|
||||
("Orchestrator", config_dir / ORCHESTRATOR_CONFIG),
|
||||
("Trainer", config_dir / TRAINER_CONFIG),
|
||||
]
|
||||
if config.inference is not None:
|
||||
components.append(("Inference", config_dir / INFERENCE_CONFIG))
|
||||
if env_servers(config):
|
||||
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/*/*.json"))
|
||||
return components
|
||||
|
||||
|
||||
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
"""Write resolved subconfigs to disk as TOML files."""
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -96,21 +106,11 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
with open(output_dir / INFERENCE_CONFIG, "w") as f:
|
||||
json.dump(inference_dict, f, indent=2)
|
||||
|
||||
# One EnvServerConfig TOML per launcher-managed source: `env-server @ <path>` binds
|
||||
# at the source's deterministic address, where the orchestrator connects. The source's
|
||||
# env/serve blocks carry over; its other knobs (sampling, algo, name, ...) are
|
||||
# orchestrator-side.
|
||||
for split, source, address in env_servers(config):
|
||||
env_dir = output_dir / ENVS_DIR / split
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_dict = dump_resolved_config(source)
|
||||
env_server_dict = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**source_dict.get("serve", {}), "address": address},
|
||||
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
|
||||
}
|
||||
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
# One EnvServerConfig per launcher-managed source: `env-server @ <path>` binds an
|
||||
# OS-assigned port and publishes it to the source's address file, where the
|
||||
# orchestrator picks it up.
|
||||
for split, source in env_servers(config):
|
||||
write_env_server_config(output_dir, split, source, config.orchestrator.log)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
@@ -124,12 +124,21 @@ def rl_local(config: RLConfig):
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "rl")
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
logger.info(
|
||||
format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
orchestrator=True,
|
||||
inference=config.inference is not None,
|
||||
env_names={split: env_server_names(config, split) for split in ("train", "eval")},
|
||||
)
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs from deployment config
|
||||
@@ -153,7 +162,6 @@ def rl_local(config: RLConfig):
|
||||
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
|
||||
|
||||
start_command = sys.argv
|
||||
logger.info("Starting RL run")
|
||||
logger.debug(f"RL start command: {' '.join(start_command)}")
|
||||
|
||||
# Build shared W&B env vars for subprocesses. Shared mode is always on for
|
||||
@@ -248,10 +256,10 @@ def rl_local(config: RLConfig):
|
||||
"otherwise rollouts will hang."
|
||||
)
|
||||
|
||||
# Start one env server per source. The orchestrator connects to each source's
|
||||
# deterministic address, polling until the server is up, so the servers and the
|
||||
# Start one env server per source. The orchestrator waits for each server's
|
||||
# published address and polls until it answers, so the servers and the
|
||||
# orchestrator start in parallel.
|
||||
for split, source, address in env_servers(config):
|
||||
for split, source in env_servers(config):
|
||||
name = source.resolved_name
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.json").as_posix()]
|
||||
logger.info(f"Starting {name} server")
|
||||
@@ -586,7 +594,7 @@ def rl_slurm(config: RLConfig):
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
|
||||
logger.info(f"Wrote config to {config_dir / RL_CONFIG}")
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', [('RL', config_dir / RL_CONFIG)])}")
|
||||
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
@@ -596,12 +604,11 @@ def rl_slurm(config: RLConfig):
|
||||
trainer=True,
|
||||
orchestrator=True,
|
||||
inference=True,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
env_names={"train": train_env_names, "eval": eval_env_names},
|
||||
)
|
||||
else:
|
||||
write_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote subconfigs to {config_dir}")
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'rl', rl_config_components(config, config_dir))}")
|
||||
|
||||
train_env_names = env_server_names(config, "train")
|
||||
eval_env_names = env_server_names(config, "eval")
|
||||
@@ -612,8 +619,7 @@ def rl_slurm(config: RLConfig):
|
||||
trainer=True,
|
||||
orchestrator=has_infer,
|
||||
inference=has_infer,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
env_names={"train": train_env_names, "eval": eval_env_names},
|
||||
num_train_nodes=config.deployment.num_train_nodes,
|
||||
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
|
||||
)
|
||||
@@ -661,6 +667,7 @@ def rl(config: RLConfig):
|
||||
# step is stale. When training from scratch, every existing step directory is
|
||||
# stale — without this, a fresh run in a dirty run dir would pick up rollouts
|
||||
# from a previous run and the orchestrator would see a negative async level.
|
||||
get_logger().info("Starting RL run")
|
||||
resume_step: int | None = None
|
||||
if resuming:
|
||||
if config.resume.dir is not None:
|
||||
|
||||
@@ -8,8 +8,8 @@ from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
from prime_rl.configs.evals import EvalsConfig, OnlineConfig
|
||||
from prime_rl.configs.orchestrator import EvalSourceConfig
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
|
||||
@@ -17,6 +17,7 @@ from prime_rl.utils.config import cli, dump_resolved_config, find_package_resour
|
||||
from prime_rl.utils.logger import setup_logger
|
||||
from prime_rl.utils.pathing import (
|
||||
clean_future_steps,
|
||||
format_config_message,
|
||||
format_log_message,
|
||||
get_broadcast_dir,
|
||||
get_ckpt_dir,
|
||||
@@ -25,6 +26,7 @@ from prime_rl.utils.pathing import (
|
||||
prepare_attempt_dirs,
|
||||
resolve_latest_ckpt_step,
|
||||
validate_run_dir,
|
||||
write_env_server_config,
|
||||
write_launch_artifacts,
|
||||
)
|
||||
from prime_rl.utils.process import (
|
||||
@@ -42,23 +44,17 @@ SFT_CONFIG = "sft.json"
|
||||
SFT_SBATCH = "sft.sbatch"
|
||||
|
||||
INFERENCE_CONFIG = "inference.json"
|
||||
EVALS_CONFIG = "evals.json"
|
||||
ONLINE_EVAL_CONFIG = "eval.json"
|
||||
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
|
||||
def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
|
||||
"""``(source, address)`` for every launcher-managed eval source. A source with
|
||||
``serve.address`` set is externally managed — the launcher neither writes its
|
||||
config nor spawns a server for it."""
|
||||
def eval_env_servers(config: SFTConfig) -> list[OnlineEvalSourceConfig]:
|
||||
"""Every launcher-managed eval source. A source with ``serve.address`` set is
|
||||
externally managed — the launcher neither writes its config nor spawns a server for it."""
|
||||
if config.eval is None:
|
||||
return []
|
||||
addresses = config.eval.env_addresses
|
||||
return [
|
||||
(source, addresses[("eval", source.resolved_name)])
|
||||
for source in config.eval.source
|
||||
if source.serve.address is None
|
||||
]
|
||||
return [source for source in config.eval.source if source.serve.address is None]
|
||||
|
||||
|
||||
def get_ckpt_base(config: SFTConfig) -> Path:
|
||||
@@ -76,28 +72,37 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
|
||||
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
|
||||
|
||||
|
||||
def build_evals_config(config: SFTConfig) -> EvalsConfig:
|
||||
"""Derive the evals subconfig from the resolved SFT config. The launcher
|
||||
spawns the env servers itself, so each source's derived address is stamped in,
|
||||
marking it externally managed for the evals process."""
|
||||
def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
|
||||
"""The online-eval process's config: the resolved ``[eval]`` block with the run-level
|
||||
fields filled from the SFT config. The launcher spawns the env servers itself; the
|
||||
online-eval process finds each one through the address it publishes in the shared
|
||||
config attempt."""
|
||||
assert config.eval is not None
|
||||
eval_config = config.eval.model_copy(deep=True)
|
||||
addresses = config.eval.env_addresses
|
||||
for source in eval_config.source:
|
||||
source.serve.address = addresses[("eval", source.resolved_name)]
|
||||
return EvalsConfig(
|
||||
run_fields = dict(
|
||||
model=config.model.name,
|
||||
eval=eval_config,
|
||||
weight_broadcast=config.weight_broadcast,
|
||||
online=OnlineConfig(
|
||||
broadcasts_dir=get_broadcast_dir(config.run_dir),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
),
|
||||
broadcasts_dir=get_broadcast_dir(config.run_dir),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
output_dir=config.run_dir,
|
||||
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
|
||||
monitors=config.monitors,
|
||||
)
|
||||
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
|
||||
|
||||
|
||||
def sft_config_components(config: SFTConfig, config_dir: Path) -> list[tuple[str, Path | str]]:
|
||||
"""The resolved configs a launch leaves in ``config_dir``: the SFT config and, with
|
||||
online evals, the inference, online-eval and env-server configs."""
|
||||
components: list[tuple[str, Path | str]] = [("SFT", config_dir / SFT_CONFIG)]
|
||||
if config.eval is not None:
|
||||
if config.inference is not None:
|
||||
components.append(("Inference", config_dir / INFERENCE_CONFIG))
|
||||
components.append(("Eval", config_dir / ONLINE_EVAL_CONFIG))
|
||||
if eval_env_servers(config):
|
||||
components.append(("Envs", f"{config_dir}/{ENVS_DIR}/eval/*.json"))
|
||||
return components
|
||||
|
||||
|
||||
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
|
||||
@@ -108,7 +113,7 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
|
||||
|
||||
|
||||
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
|
||||
"""Write the inference, evals, and env-server configs for online evals."""
|
||||
"""Write the inference, online-eval, and env-server configs for online evals."""
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if config.inference is not None:
|
||||
@@ -121,22 +126,14 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
|
||||
with open(config_dir / INFERENCE_CONFIG, "w") as f:
|
||||
json.dump(inference_dict, f, indent=2)
|
||||
|
||||
with open(config_dir / EVALS_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(build_evals_config(config)), f, indent=2)
|
||||
with open(config_dir / ONLINE_EVAL_CONFIG, "w") as f:
|
||||
json.dump(dump_resolved_config(build_online_eval_config(config)), f, indent=2)
|
||||
|
||||
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
|
||||
# binds at the source's deterministic address, where the evals process connects.
|
||||
for source, address in eval_env_servers(config):
|
||||
env_dir = config_dir / ENVS_DIR / "eval"
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_dict = dump_resolved_config(source)
|
||||
env_server_dict = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**(source_dict.get("serve") or {}), "address": address},
|
||||
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
|
||||
}
|
||||
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
|
||||
json.dump(env_server_dict, f, indent=2)
|
||||
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>` binds an
|
||||
# OS-assigned port and publishes it to the source's address file, where the
|
||||
# online-eval process picks it up.
|
||||
for source in eval_env_servers(config):
|
||||
write_env_server_config(config_dir, "eval", source, config.log)
|
||||
|
||||
|
||||
def write_slurm_script(
|
||||
@@ -191,12 +188,12 @@ def write_slurm_script(
|
||||
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
|
||||
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
|
||||
"inference_env_vars": inference_env_vars,
|
||||
"evals_env_vars": {
|
||||
"online_eval_env_vars": {
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
"LOGURU_FORCE_COLORS": "1",
|
||||
**config.env_vars,
|
||||
},
|
||||
"eval_env_names": [source.resolved_name for source, _ in eval_env_servers(config)],
|
||||
"eval_env_names": [source.resolved_name for source in eval_env_servers(config)],
|
||||
}
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -236,6 +233,7 @@ def sft_slurm(config: SFTConfig):
|
||||
|
||||
online_eval = config.deployment.type == "multi_node" and config.eval is not None
|
||||
|
||||
logger.info("Starting SFT run")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
@@ -249,9 +247,8 @@ def sft_slurm(config: SFTConfig):
|
||||
# inference pool runs on its dedicated nodes in the same allocation.
|
||||
exclude = exclude | {"inference"}
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
# Trainer and evals processes log to a single shared W&B run.
|
||||
# Trainer and online-eval processes log to a single shared W&B run.
|
||||
prl_run_id: str | None = None
|
||||
if online_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
@@ -259,7 +256,7 @@ def sft_slurm(config: SFTConfig):
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
if online_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
@@ -269,9 +266,9 @@ def sft_slurm(config: SFTConfig):
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
num_train_nodes=num_nodes,
|
||||
evals=online_eval,
|
||||
eval=online_eval,
|
||||
inference=online_eval,
|
||||
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)] if online_eval else None,
|
||||
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]} if online_eval else None,
|
||||
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
|
||||
)
|
||||
|
||||
@@ -297,20 +294,28 @@ def sft_local(config: SFTConfig):
|
||||
|
||||
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
|
||||
|
||||
logger.info("Starting SFT run")
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
|
||||
write_launch_artifacts(config_dir, "sft")
|
||||
config_path = config_dir / SFT_CONFIG
|
||||
write_config(config, config_path)
|
||||
logger.info(f"Wrote config to {config_path}")
|
||||
|
||||
if config.eval is not None:
|
||||
write_eval_subconfigs(config, config_dir)
|
||||
logger.info(f"Wrote eval subconfigs to {config_dir}")
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
|
||||
|
||||
if config.dry_run:
|
||||
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
|
||||
return
|
||||
|
||||
logger.info(
|
||||
format_log_message(
|
||||
log_dir=log_dir,
|
||||
trainer=True,
|
||||
eval=config.eval is not None,
|
||||
inference=config.inference is not None,
|
||||
env_names={"eval": [source.resolved_name for source in eval_env_servers(config)]},
|
||||
)
|
||||
)
|
||||
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
|
||||
|
||||
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
|
||||
@@ -329,17 +334,17 @@ def sft_local(config: SFTConfig):
|
||||
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
|
||||
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
|
||||
|
||||
# Trainer and evals log to a single shared W&B run whose id ($WANDB_RUN_ID)
|
||||
# Trainer and online-eval log to a single shared W&B run whose id ($WANDB_RUN_ID)
|
||||
# equals $PRL_RUN_ID, one label per process.
|
||||
wandb_shared_env: dict[str, str] = {}
|
||||
if config.eval is not None:
|
||||
# The trainer creates the run; the evals process (which drains its final evals
|
||||
# after the trainer exits) finalizes it.
|
||||
# The trainer creates the run; the online-eval process (which drains its final
|
||||
# evals after the trainer exits) finalizes it.
|
||||
wandb_shared_env = {
|
||||
"WANDB_SHARED_MODE": "1",
|
||||
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
|
||||
"WANDB_SHARED_PRIMARY": "trainer",
|
||||
"WANDB_SHARED_FINISHER": "evals",
|
||||
"WANDB_SHARED_FINISHER": "online-eval",
|
||||
"WANDB_PROGRAM": "uv run sft",
|
||||
"WANDB_ARGS": json.dumps(sys.argv),
|
||||
}
|
||||
@@ -388,9 +393,9 @@ def sft_local(config: SFTConfig):
|
||||
log_path=log_dir / "inference.log",
|
||||
)
|
||||
|
||||
# Start one env server per eval source. The evals process connects to each source's
|
||||
# deterministic address, polling until the server is up.
|
||||
for source, address in eval_env_servers(config):
|
||||
# Start one env server per eval source. The online-eval process waits for each
|
||||
# server's published address and polls until it answers.
|
||||
for source in eval_env_servers(config):
|
||||
name = source.resolved_name
|
||||
logger.info(f"Starting {name} server")
|
||||
start_process(
|
||||
@@ -401,10 +406,10 @@ def sft_local(config: SFTConfig):
|
||||
)
|
||||
|
||||
if config.eval is not None:
|
||||
logger.info("Starting evals")
|
||||
logger.info("Starting online evals")
|
||||
start_process(
|
||||
"evals",
|
||||
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
|
||||
"online-eval",
|
||||
[sys.executable, "-m", "prime_rl.eval.online", "@", (config_dir / ONLINE_EVAL_CONFIG).as_posix()],
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
@@ -414,9 +419,9 @@ def sft_local(config: SFTConfig):
|
||||
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
|
||||
"PRL_LOG_DIR": str(log_dir),
|
||||
**wandb_shared_env,
|
||||
"WANDB_SHARED_LABEL": "evals",
|
||||
"WANDB_SHARED_LABEL": "online-eval",
|
||||
},
|
||||
log_path=log_dir / "evals.log",
|
||||
log_path=log_dir / "eval.log",
|
||||
)
|
||||
|
||||
from prime_rl.utils.utils import get_free_port
|
||||
@@ -455,11 +460,11 @@ def sft_local(config: SFTConfig):
|
||||
logger.success("Launcher complete")
|
||||
log_dashboard_url(logger, dashboard_url)
|
||||
|
||||
# Wait for the trainer (and the evals process, which drains its final evals after
|
||||
# the trainer's last checkpoint) while surfacing any process failure.
|
||||
# Wait for the trainer (and the online-eval process, which drains its final evals
|
||||
# after the trainer's last checkpoint) while surfacing any process failure.
|
||||
terminal_events = [stop_events["trainer"]]
|
||||
if "evals" in stop_events:
|
||||
terminal_events.append(stop_events["evals"])
|
||||
if "online-eval" in stop_events:
|
||||
terminal_events.append(stop_events["online-eval"])
|
||||
while True:
|
||||
pending = [event for event in terminal_events if not event.is_set()]
|
||||
if error_queue:
|
||||
@@ -497,12 +502,12 @@ def sft_local(config: SFTConfig):
|
||||
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
|
||||
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
|
||||
trace dirs — everything on a fresh start, steps past the resume step on resume.
|
||||
Without this the evals process would replay stale broadcasts (and then skip the
|
||||
Without this the online-eval process would replay stale broadcasts (and then skip the
|
||||
re-trained ones at the same steps), and the append-only trace files would mix two
|
||||
policies' rollouts under one step."""
|
||||
logger = setup_logger(config.log.level or "info")
|
||||
if os.environ.get("NEVER_CLEAN"):
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the evals process may replay them")
|
||||
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the online-eval process may replay them")
|
||||
return
|
||||
resume_step = resolve_resume_step(config)
|
||||
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Evals: one epoch of every configured eval source against the weights the inference
|
||||
server currently serves.
|
||||
|
||||
Every episode streams through the monitors as it arrives; a finished epoch also goes to
|
||||
the platform when ``monitors.prime`` is set. An interrupted run resumes with
|
||||
``--resume`` from its trace stream: the landed episodes rejoin the epoch and only the
|
||||
rollouts still owed run (``prime_rl.eval.resume``)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.eval import EvalConfig
|
||||
from prime_rl.eval import resume
|
||||
from prime_rl.eval.runner import EvalRunner
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
|
||||
class Eval:
|
||||
def __init__(self, config: EvalConfig) -> None:
|
||||
self.config = config
|
||||
self.runner = EvalRunner(config, run_dir=config.run_dir)
|
||||
|
||||
async def run(self) -> None:
|
||||
config = self.config
|
||||
landed: list[dict] = []
|
||||
if config.resume:
|
||||
# read and set aside before the monitors start: the resumed attempt writes a fresh stream
|
||||
resume.check_config(resume.previous_config(config.run_dir), dump_resolved_config(config))
|
||||
landed = resume.take_landed(config.run_dir)
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
producer="eval",
|
||||
wandb=config.monitors.wandb,
|
||||
prime=config.monitors.prime,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.run_dir,
|
||||
run_config=config,
|
||||
eval_env_names=[source.resolved_name for source in config.source],
|
||||
overview_flavor="eval",
|
||||
)
|
||||
resume.stamp_config(config.run_dir, dump_resolved_config(config))
|
||||
await self.runner.setup()
|
||||
restored: list = []
|
||||
if config.resume:
|
||||
restored, owed, groups = resume.plan(landed, self.runner.eval_envs)
|
||||
self.runner.eval_source.restore(owed, groups)
|
||||
get_logger().info(
|
||||
f"Resuming from the trace stream: {len(restored)} episodes restored, "
|
||||
f"{sum(sum(counts.values()) for counts in owed.values())} rollouts owed"
|
||||
)
|
||||
|
||||
await self.runner.start()
|
||||
fired = self.runner.eval_source.trigger(0)
|
||||
await self.runner.run_epoch(fired, 0, restored=restored)
|
||||
await self.runner.drain()
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_eval(config: EvalConfig) -> None:
|
||||
evaluation = Eval(config)
|
||||
try:
|
||||
await evaluation.run()
|
||||
# Finalize only on a clean exit — a crashed run must not mark itself completed.
|
||||
await monitors.finalize()
|
||||
finally:
|
||||
await evaluation.runner.stop()
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Online evals: evaluate the trainer's weight broadcasts as they appear.
|
||||
|
||||
Spawned by the ``sft`` launcher (``python -m prime_rl.eval.online @ eval.json``)
|
||||
next to the trainer. The process watches a broadcasts directory for offered weight broadcasts through a
|
||||
``WeightReceiver`` (announced by their ``.sender_ready`` marker), moves the inference
|
||||
server onto each of them, and runs the due eval sources against the updated weights,
|
||||
sequentially per broadcast so every epoch measures exactly one policy version. Every
|
||||
offered broadcast must be received, even when no eval is due — the trainer blocks inside
|
||||
the handshake until the receiver acknowledges. By default, a newer checkpoint cancels
|
||||
unfinished episodes from the prior version; ``cancel_on_new_checkpoint = false`` drains
|
||||
every epoch instead."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.eval.runner import POLL_INTERVAL_S, EvalRunner
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.config import cli, dump_resolved_config
|
||||
from prime_rl.utils.logger import get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, prepare_attempt_dirs
|
||||
from prime_rl.utils.process import set_proc_title
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
# Budget for the trainer's startup broadcast: it is always coming, but only
|
||||
# after the trainer has finished loading the model.
|
||||
STARTUP_BROADCAST_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class OnlineEval:
|
||||
def __init__(self, config: SFTOnlineEvalConfig) -> None:
|
||||
assert config.model is not None, "the sft launcher fills eval.model"
|
||||
self.config = config
|
||||
self.runner = EvalRunner(config, run_dir=config.output_dir)
|
||||
# The last weight-broadcast step already handled (evaluated or skipped).
|
||||
self.last_step = config.resume_step or 0
|
||||
self.receiver: WeightReceiver | None = None
|
||||
|
||||
async def run(self) -> None:
|
||||
config = self.config
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
producer="online-eval",
|
||||
wandb=config.monitors.wandb,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.output_dir,
|
||||
run_config=config,
|
||||
eval_env_names=[source.resolved_name for source in config.source],
|
||||
overview_flavor="sft",
|
||||
)
|
||||
await self.runner.setup(skip_first_step=config.skip_first_step, is_resumed=config.resume_step is not None)
|
||||
|
||||
assert config.broadcasts_dir is not None # resolved by the config validator
|
||||
# A hand-written config may omit the transport; broadcasts are then plain
|
||||
# filesystem checkpoints.
|
||||
weight_broadcast = config.weight_broadcast or FileSystemWeightBroadcastConfig()
|
||||
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
|
||||
self.receiver = setup_weight_receiver(
|
||||
config.broadcasts_dir,
|
||||
weight_broadcast,
|
||||
admin_plane=self.runner.admin_plane,
|
||||
model_name=config.model,
|
||||
)
|
||||
await self.receiver.initialize()
|
||||
|
||||
await self.runner.start()
|
||||
await self.watch()
|
||||
await self.runner.drain()
|
||||
get_logger().success("Online evals finished!")
|
||||
|
||||
async def watch(self) -> None:
|
||||
"""Evaluate each eligible weight broadcast as it appears."""
|
||||
config = self.config
|
||||
assert self.receiver is not None
|
||||
assert config.broadcasts_dir is not None
|
||||
|
||||
# Rendezvous with the trainer's startup broadcast (v0 fresh, the checkpoint step
|
||||
# on resume) — always, for every transport: an in-memory trainer blocks inside
|
||||
# its startup broadcast until this receive, and for filesystem it guarantees the
|
||||
# served weights match the trainer's incoming policy.
|
||||
startup_step = config.resume_step or 0
|
||||
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
|
||||
self.runner.policy.version = startup_step
|
||||
|
||||
if config.resume_step is None:
|
||||
# The first trigger fires every env (policy v0) unless ``skip_first_step``.
|
||||
await self.maybe_run_eval(step=0)
|
||||
elif config.retrigger_on_resume:
|
||||
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
|
||||
# evals); the startup rendezvous above already loaded its weights. The
|
||||
# final broadcast force-fires every env, exactly like the watch loop below.
|
||||
is_final = config.max_steps is not None and config.resume_step >= config.max_steps
|
||||
await self.maybe_run_eval(step=config.resume_step, force=is_final)
|
||||
|
||||
get_logger().info(f"Watching {config.broadcasts_dir} for new weight broadcasts (max_steps={config.max_steps})")
|
||||
while True:
|
||||
steps = get_all_ckpt_steps(config.broadcasts_dir)
|
||||
published = {step: self.receiver.is_published(step) for step in steps}
|
||||
newest_published = max((step for step in steps if published[step]), default=None)
|
||||
# Also walk eval-due steps that are no longer on disk: broadcast cleaning
|
||||
# (the trainer keeps only the newest broadcast) can delete a step before
|
||||
# this scan sees it, and a vanished step would otherwise be skipped
|
||||
# without a trace.
|
||||
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_published)):
|
||||
if step <= self.last_step:
|
||||
continue
|
||||
if step not in published:
|
||||
get_logger().warning(
|
||||
f"Weight broadcast for eval step {step} was deleted before it could be "
|
||||
"evaluated (broadcast cleaning outpaced the evals process) - skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
if not published[step]:
|
||||
# The trainer writes broadcasts in ascending order, so a marker-less
|
||||
# step below a published one is an abandoned partial write (e.g. a
|
||||
# crash mid-save), not one in progress — skip it instead of wedging.
|
||||
if newest_published is None or newest_published < step:
|
||||
break # still being written — later steps can't be ready either
|
||||
get_logger().warning(
|
||||
f"Weight broadcast step {step} is not marked published but newer "
|
||||
"broadcasts are - treating it as abandoned and skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
is_final = config.max_steps is not None and step >= config.max_steps
|
||||
await self.maybe_run_eval(step=step, reload_weights=True, force=is_final)
|
||||
if config.max_steps is not None and self.last_step >= config.max_steps:
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
def next_published_step(self, step: int) -> int | None:
|
||||
"""Return the first newer checkpoint offered by the trainer."""
|
||||
assert self.config.broadcasts_dir is not None
|
||||
assert self.receiver is not None
|
||||
return next(
|
||||
(
|
||||
candidate
|
||||
for candidate in get_all_ckpt_steps(self.config.broadcasts_dir)
|
||||
if candidate > step and self.receiver.is_published(candidate)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
|
||||
"""Eval-due steps up to the newest published broadcast that are missing from
|
||||
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
|
||||
so their absence means broadcast cleaning removed them before they were
|
||||
evaluated."""
|
||||
if newest_published is None:
|
||||
return set()
|
||||
due = {
|
||||
step
|
||||
for interval in self.runner.eval_source.intervals.values()
|
||||
for step in range(interval, newest_published + 1, interval)
|
||||
}
|
||||
return due - set(steps)
|
||||
|
||||
async def maybe_run_eval(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
|
||||
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
|
||||
reloading the inference weights first. No-op when no env is due — except
|
||||
that a live transport's broadcast must always be received (the trainer
|
||||
is blocked inside it), eval or no eval."""
|
||||
runner = self.runner
|
||||
if reload_weights:
|
||||
assert self.receiver is not None
|
||||
broadcast_dir = self.receiver.step_dir(step)
|
||||
if not self.receiver.is_published(step):
|
||||
get_logger().warning(f"No published weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
|
||||
self.last_step = max(self.last_step, step)
|
||||
return
|
||||
|
||||
# Trigger before the reload: the dispatcher only schedules eval in PREFER_EVAL,
|
||||
# so nothing dispatches until ``run_epoch`` switches modes below.
|
||||
fired = runner.eval_source.trigger(step, force=force)
|
||||
self.last_step = max(self.last_step, step)
|
||||
|
||||
if reload_weights:
|
||||
# Every offered version must be received: the trainer blocks inside
|
||||
# the handshake, so a failed receive fails the run loudly.
|
||||
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
|
||||
await runner.dispatcher.on_version_pending(step)
|
||||
await self.receiver.receive(step)
|
||||
runner.policy.version = step
|
||||
await runner.dispatcher.on_new_version(step)
|
||||
else:
|
||||
runner.policy.version = step
|
||||
|
||||
if not fired:
|
||||
return
|
||||
superseding_step = (lambda: self.next_published_step(step)) if self.config.cancel_on_new_checkpoint else None
|
||||
await runner.run_epoch(fired, step, superseding_step=superseding_step)
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_online_eval(config: SFTOnlineEvalConfig) -> None:
|
||||
evaluation = OnlineEval(config)
|
||||
try:
|
||||
await evaluation.run()
|
||||
# Finalize only on a clean exit — a crashed run must not mark the run completed.
|
||||
await monitors.finalize()
|
||||
finally:
|
||||
await evaluation.runner.stop()
|
||||
|
||||
|
||||
def main():
|
||||
set_proc_title("OnlineEvals")
|
||||
config = cli(SFTOnlineEvalConfig)
|
||||
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
|
||||
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
|
||||
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
|
||||
(config_dir / "eval.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
asyncio.run(run_online_eval(config))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,169 @@
|
||||
"""Resume an interrupted eval from its trace stream.
|
||||
|
||||
The stream records what landed, so it is what a resume continues from. The run's ok
|
||||
episodes are read back and rejoin the epoch as if they had just arrived - through the
|
||||
monitors, so the rebuilt stream, the epoch's metrics and the platform upload cover the
|
||||
whole epoch - and only the rollouts still owed run. Errored episodes and the in-flight
|
||||
ones the interruption cut off are owed again.
|
||||
|
||||
A landed episode counts toward the task with its ``task.key``, so a resumed run may
|
||||
select more or fewer examples or rollouts per example than the interrupted one: the
|
||||
kept episodes are matched to the new selection and the rest is owed. What defines the
|
||||
measurement itself - the model, the sampling, each source's env - must not change
|
||||
(``check_config``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter, defaultdict
|
||||
from collections.abc import Iterator
|
||||
from fnmatch import fnmatch
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.monitors.file.traces import get_trace_stream
|
||||
from prime_rl.monitors.file.traces.chunks import chunk_numbers, open_chunk
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.utils.pathing import get_file_monitor_dir
|
||||
|
||||
RESUMABLE = (
|
||||
"resume",
|
||||
"clean",
|
||||
"dry_run",
|
||||
"dashboard",
|
||||
"num_examples",
|
||||
"group_size",
|
||||
"concurrency",
|
||||
"client",
|
||||
"log",
|
||||
"monitors",
|
||||
"source.*.num_examples",
|
||||
"source.*.shuffle",
|
||||
"source.*.group_size",
|
||||
"source.*.serve",
|
||||
)
|
||||
"""Config paths a resumed run may change: how many rollouts to run and how to run them,
|
||||
never what is measured."""
|
||||
|
||||
|
||||
CONFIG_NAME = "eval.json"
|
||||
"""The resolved config an attempt stamps into its file monitor directory once it is
|
||||
running, beside the episodes it produces: a resume validates against the config those
|
||||
episodes were measured with, never against an attempt that was rejected or dry."""
|
||||
|
||||
|
||||
def stamp_config(run_dir: Path, config: dict) -> None:
|
||||
directory = get_file_monitor_dir(run_dir)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / CONFIG_NAME).write_bytes(orjson.dumps(config, option=orjson.OPT_INDENT_2))
|
||||
|
||||
|
||||
def previous_config(run_dir: Path) -> dict:
|
||||
"""The config stamped beside the run's landed episodes: the current file monitor
|
||||
directory's, else the newest archive's."""
|
||||
for directory in [get_file_monitor_dir(run_dir), *reversed(archives(run_dir))]:
|
||||
if (directory / CONFIG_NAME).is_file():
|
||||
return orjson.loads((directory / CONFIG_NAME).read_bytes())
|
||||
raise FileNotFoundError(f"Nothing to resume: {run_dir} holds no attempt that ran")
|
||||
|
||||
|
||||
def config_diff(previous, current, prefix: str = "") -> list[str]:
|
||||
"""Dotted paths at which two resolved configs differ (list items by index)."""
|
||||
if isinstance(previous, dict) and isinstance(current, dict):
|
||||
return [
|
||||
path
|
||||
for key in sorted(set(previous) | set(current))
|
||||
for path in config_diff(previous.get(key), current.get(key), f"{prefix}.{key}" if prefix else key)
|
||||
]
|
||||
if isinstance(previous, list) and isinstance(current, list) and len(previous) == len(current):
|
||||
return [
|
||||
path
|
||||
for index, (before, after) in enumerate(zip(previous, current, strict=True))
|
||||
for path in config_diff(before, after, f"{prefix}.{index}")
|
||||
]
|
||||
return [] if previous == current else [prefix]
|
||||
|
||||
|
||||
def check_config(previous: dict, current: dict) -> None:
|
||||
changed = [
|
||||
path
|
||||
for path in config_diff(previous, current)
|
||||
if not any(fnmatch(path, pattern) or fnmatch(path, f"{pattern}.*") for pattern in RESUMABLE)
|
||||
]
|
||||
if changed:
|
||||
raise ValueError(
|
||||
f"The run cannot resume with a different {', '.join(changed)} - the landed episodes would not "
|
||||
"measure the same thing. Relaunch with --clean to start over."
|
||||
)
|
||||
|
||||
|
||||
def read_records(stream: Path) -> Iterator[dict]:
|
||||
"""Every record of a trace stream, in order. A torn last line (the interrupted
|
||||
process died mid-append) ends the stream."""
|
||||
for number in sorted(chunk_numbers(stream)):
|
||||
with open_chunk(stream, number) as chunk:
|
||||
for line in chunk:
|
||||
try:
|
||||
yield orjson.loads(line)
|
||||
except orjson.JSONDecodeError:
|
||||
return
|
||||
|
||||
|
||||
def archives(run_dir: Path) -> list[Path]:
|
||||
"""The file monitor directories of the run's earlier attempts, oldest first: a resume
|
||||
renames the one it finds to ``monitors/file.attempt_N`` and starts a fresh one."""
|
||||
monitors = get_file_monitor_dir(run_dir).parent
|
||||
return sorted(monitors.glob("file.attempt_*"), key=lambda path: int(path.name.rsplit("_", 1)[1]))
|
||||
|
||||
|
||||
def take_landed(run_dir: Path) -> list[dict]:
|
||||
"""The ok eval episodes the run has landed, each once, from every attempt's stream.
|
||||
The current file monitor directory joins the archives so the resumed attempt writes a
|
||||
fresh stream, plan and metrics; nothing is deleted."""
|
||||
current = get_file_monitor_dir(run_dir)
|
||||
stream = get_trace_stream(run_dir).relative_to(current)
|
||||
landed: dict[str, dict] = {}
|
||||
for directory in [*archives(run_dir), current]:
|
||||
if (directory / stream).is_dir():
|
||||
for record in read_records(directory / stream):
|
||||
if record.get("ok"):
|
||||
landed.setdefault(record["id"], record)
|
||||
if current.is_dir():
|
||||
current.rename(current.with_name(f"file.attempt_{len(archives(run_dir)) + 1}"))
|
||||
return list(landed.values())
|
||||
|
||||
|
||||
def plan(
|
||||
landed: list[dict], eval_envs: EvalEnvs
|
||||
) -> tuple[list[vf.WireEpisode], dict[str, dict[str, int]], dict[str, dict[str, str]]]:
|
||||
"""Match the landed episodes to the run's tasks: the episodes to keep, in stream
|
||||
order, the rollouts still owed per env and task key, and the group id a task's kept
|
||||
episodes carry, so the owed ones complete that group rather than open another."""
|
||||
targets: dict[str, Counter[str]] = {}
|
||||
for env in eval_envs:
|
||||
targets[env.name] = Counter(task.key for task in env.examples)
|
||||
for key in targets[env.name]:
|
||||
targets[env.name][key] *= env.config.group_size
|
||||
kept: list[vf.WireEpisode] = []
|
||||
counts: dict[str, Counter[str]] = defaultdict(Counter)
|
||||
groups: dict[str, dict[str, str]] = defaultdict(dict)
|
||||
for record in landed:
|
||||
env_name = record["env"].get("name") or record["env"]["id"]
|
||||
key = record["task"]["key"]
|
||||
if counts[env_name][key] >= targets.get(env_name, Counter())[key]:
|
||||
continue
|
||||
kept.append(vf.WireEpisode.model_validate(record))
|
||||
counts[env_name][key] += 1
|
||||
if (group := record.get("group") or {}).get("id"):
|
||||
groups[env_name].setdefault(key, group["id"])
|
||||
owed = {
|
||||
env_name: {
|
||||
key: target - counts[env_name][key]
|
||||
for key, target in target_counts.items()
|
||||
if target > counts[env_name][key]
|
||||
}
|
||||
for env_name, target_counts in targets.items()
|
||||
}
|
||||
return kept, owed, dict(groups)
|
||||
@@ -0,0 +1,333 @@
|
||||
"""EvalRunner: the eval engine shared by ``eval`` (one epoch against the served weights)
|
||||
and ``online-eval`` (an epoch per weight broadcast).
|
||||
|
||||
Scheduling reuses the orchestrator pipeline unchanged: an eval-only ``Dispatcher``
|
||||
admits episodes under the adaptive ``ConcurrencyController``, fed by the
|
||||
``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes are version-pinned
|
||||
measurements and are never cancelled on load - a controller cut only blocks admission
|
||||
until the pool drains.
|
||||
|
||||
Env servers belong to the launcher (``eval``, ``sft``), like the orchestrator's belong to
|
||||
``rl``: a source without an explicit ``serve.address`` is found through the address file
|
||||
its server publishes; one with an address is reached directly."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Callable, Sequence
|
||||
from pathlib import Path
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.eval import EvalConfig, SFTOnlineEvalConfig
|
||||
from prime_rl.orchestrator import live
|
||||
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
|
||||
from prime_rl.orchestrator.utils import (
|
||||
eval_work,
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
)
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_config_dir
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
|
||||
# How often ``run_epoch`` re-checks for a superseding checkpoint while it waits for episodes.
|
||||
POLL_INTERVAL_S = 2.0
|
||||
|
||||
|
||||
class EvalRunner:
|
||||
def __init__(self, config: EvalConfig | SFTOnlineEvalConfig, *, run_dir: Path) -> None:
|
||||
self.config = config
|
||||
self.run_dir = run_dir
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
|
||||
self.eval_triggered_at: dict[tuple[str, int], float] = {}
|
||||
self.dispatcher_task: asyncio.Task | None = None
|
||||
|
||||
# Assigned in setup(); None-initialized so stop() can tear down a
|
||||
# partially completed setup with plain attribute checks.
|
||||
self.clients: InferenceClient | None = None
|
||||
self.admin_plane: AdminPlane | None = None
|
||||
self.dispatcher: Dispatcher | None = None
|
||||
self.inference_metrics: InferenceMetricsCollector | None = None
|
||||
self.periodic_logger: PeriodicLogger | None = None
|
||||
|
||||
async def setup(self, *, skip_first_step: bool = False, is_resumed: bool = False) -> None:
|
||||
config = self.config
|
||||
set_default_executor()
|
||||
|
||||
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
|
||||
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
|
||||
self.run_name = os.environ.get("PRL_RUN_NAME")
|
||||
|
||||
get_logger().info(f"Initializing inference pool (base_url={config.client.base_url}, model={config.model})")
|
||||
self.clients = InferenceClient(config.client, model_name=config.model)
|
||||
self.admin_plane = AdminPlane(config.client)
|
||||
|
||||
get_logger().info("Loading eval environment(s)")
|
||||
self.eval_envs = EvalEnvs(config.source, config.env_addresses, get_config_dir(self.run_dir))
|
||||
await self.eval_envs.start()
|
||||
get_logger().info(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
|
||||
|
||||
get_logger().info("Waiting for inference pool to be ready")
|
||||
await self.admin_plane.wait_for_ready(config.model)
|
||||
get_logger().info("Inference pool ready")
|
||||
|
||||
intervals = config.intervals if isinstance(config, SFTOnlineEvalConfig) else None
|
||||
self.eval_source = EvalSource(
|
||||
self.eval_envs, intervals=intervals, skip_first_step=skip_first_step, is_resumed=is_resumed
|
||||
)
|
||||
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
|
||||
self.policy = Policy(version=0, model_name=config.model)
|
||||
|
||||
# Pessimistic per-episode token cost for the controller's starting cap,
|
||||
# only used when the engine doesn't report its max context length.
|
||||
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.source) or 8192
|
||||
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=fallback_cost)
|
||||
self.dispatcher = Dispatcher(
|
||||
train_envs=None,
|
||||
eval_envs=self.eval_envs,
|
||||
train_source=None,
|
||||
eval_source=self.eval_source,
|
||||
policy_clients=self.clients,
|
||||
policy=self.policy,
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.concurrency.max_inflight,
|
||||
tasks_per_minute=None,
|
||||
max_off_policy_steps=0,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
on_episode_complete=self.concurrency.record_episode,
|
||||
)
|
||||
# No ``on_overload``: eval episodes are measurements and are never
|
||||
# cancelled — a cut only blocks admission until the pool drains.
|
||||
self.concurrency.bind(
|
||||
set_limit=self.dispatcher.set_limit,
|
||||
get_inflight=lambda: self.dispatcher.current_inflight,
|
||||
)
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# metrics fan out to every registered monitor.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.admin_plane.clients,
|
||||
on_load=self.concurrency.observe,
|
||||
)
|
||||
# Fail fast when adaptivity has no signal: external API endpoints
|
||||
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
|
||||
# hit the cap would silently sit at min_inflight forever. A pinned
|
||||
# band (min_inflight = max_inflight) makes the controller inert and
|
||||
# is the supported way to run against such endpoints.
|
||||
if not await self.inference_metrics.probe():
|
||||
concurrency = config.concurrency
|
||||
if concurrency.min_inflight != concurrency.max_inflight:
|
||||
urls = ", ".join(str(client.base_url) for client in self.admin_plane.clients)
|
||||
raise ValueError(
|
||||
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
|
||||
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
|
||||
"pin the concurrency with `-c N` (concurrency.min_inflight = max_inflight = N)."
|
||||
)
|
||||
get_logger().info(f"No engine metrics - running with concurrency pinned at {concurrency.min_inflight}")
|
||||
await self.inference_metrics.start()
|
||||
|
||||
self.periodic_logger = PeriodicLogger(
|
||||
name="Eval",
|
||||
collect=self.collect_pipeline_view,
|
||||
interval=config.log.interval,
|
||||
)
|
||||
|
||||
async def start(self) -> None:
|
||||
self.dispatcher_task = asyncio.create_task(self.dispatcher.start(), name="dispatcher")
|
||||
await self.periodic_logger.start()
|
||||
|
||||
async def run_epoch(
|
||||
self,
|
||||
fired: list[str],
|
||||
step: int,
|
||||
*,
|
||||
restored: Sequence[vf.Episode] = (),
|
||||
superseding_step: Callable[[], int | None] | None = None,
|
||||
) -> None:
|
||||
"""Run the epoch ``EvalSource.trigger`` queued for ``step`` in the fired envs and
|
||||
finalize each env's batch as it completes. ``restored`` episodes of this epoch
|
||||
landed before a resume and rejoin it first; when ``superseding_step`` returns a
|
||||
newer checkpoint, the unfinished episodes of this epoch are cancelled so the
|
||||
caller can move on to it."""
|
||||
for env_name in fired:
|
||||
await monitors.log_eval_plan(env_name, step, self.eval_sink.batch_size_for(env_name))
|
||||
|
||||
now = time.perf_counter()
|
||||
for env_name in fired:
|
||||
self.eval_triggered_at[(env_name, step)] = now
|
||||
total_rollouts = sum(
|
||||
request.rollouts or 0
|
||||
for request in self.eval_source.queue
|
||||
if request.step == step and request.env_name in fired
|
||||
)
|
||||
restored_part = f", {len(restored)} restored" if restored else ""
|
||||
get_logger().info(
|
||||
f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts{restored_part})"
|
||||
)
|
||||
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
|
||||
|
||||
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
|
||||
for episode in restored:
|
||||
await self.land(episode, pending)
|
||||
cancellation_task: asyncio.Task[int] | None = None
|
||||
newer_step: int | None = None
|
||||
|
||||
while pending:
|
||||
if (
|
||||
cancellation_task is None
|
||||
and superseding_step is not None
|
||||
and (newer_step := superseding_step()) is not None
|
||||
):
|
||||
get_logger().warning(
|
||||
f"Checkpoint {newer_step} is ready - cancelling unfinished eval episodes for step {step}"
|
||||
)
|
||||
cancellation_task = asyncio.create_task(
|
||||
self.dispatcher.cancel_eval_step(step), name=f"cancel-eval-step-{step}"
|
||||
)
|
||||
|
||||
try:
|
||||
if superseding_step is not None:
|
||||
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=POLL_INTERVAL_S)
|
||||
else:
|
||||
item = await self.dispatcher.out_q.get()
|
||||
except asyncio.TimeoutError:
|
||||
if cancellation_task is not None and cancellation_task.done():
|
||||
cancellation_task.result()
|
||||
continue
|
||||
|
||||
if isinstance(item, GroupCancellation):
|
||||
eval_batch = self.eval_sink.cancel(item)
|
||||
elif isinstance(item, DispatchFailure):
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
else:
|
||||
stamp_arrival([item], "eval", eval_work(item).step)
|
||||
await self.land(item, pending)
|
||||
continue
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
pending.discard(eval_batch.env_name)
|
||||
|
||||
if cancellation_task is not None:
|
||||
cancelled = await cancellation_task
|
||||
get_logger().warning(
|
||||
f"Cancelled {cancelled} unfinished eval episodes for step {step}; advancing to checkpoint {newer_step}"
|
||||
)
|
||||
|
||||
async def land(self, episode: vf.Episode, pending: set[str]) -> None:
|
||||
"""One episode of the epoch, arrived or restored: through the monitors and into
|
||||
its env's batch, which is finalized once the epoch is complete."""
|
||||
step = eval_work(episode).step
|
||||
await monitors.log([episode], step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(episode)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
pending.discard(eval_batch.env_name)
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors, mirroring the
|
||||
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
|
||||
if not batch.episodes and not batch.failures and not batch.cancelled:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
|
||||
return
|
||||
|
||||
if batch.episodes.effective:
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
|
||||
await monitors.log_eval_epoch(batch.env_name, batch.step, batch.episodes.vf_episodes)
|
||||
|
||||
episodes = batch.episodes
|
||||
effective = episodes.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", episodes), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
|
||||
metrics |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
if batch.cancelled:
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
|
||||
eff, full = effective.metrics, episodes.metrics
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
if batch.cancelled:
|
||||
get_logger().warning(
|
||||
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Error {full.has_error.mean():.1%} | "
|
||||
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
|
||||
)
|
||||
return
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
|
||||
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
|
||||
"""Pipeline view for the ``PeriodicLogger``: per-env epoch progress plus the
|
||||
in-flight pool against the controller's current cap."""
|
||||
disp_gauges = self.dispatcher.gauges()
|
||||
disp_drain = self.dispatcher.metrics.drained(train_envs=set(), eval_envs={env.name for env in self.eval_envs})
|
||||
|
||||
parts = []
|
||||
for env_name, _step, arrived, expected in sorted(self.eval_sink.batch_progress()):
|
||||
parts.append(f"{env_name} {arrived}/{expected} ({arrived / expected:.1%})" if expected else env_name)
|
||||
progress_part = " | ".join(parts) if parts else "Idle"
|
||||
|
||||
stages = live.stage_counts(list(self.dispatcher.inflight.values()))
|
||||
body = (
|
||||
f"{progress_part}; {self.dispatcher.inflight_eval_count} inflight episodes "
|
||||
f"(cap {self.dispatcher.max_inflight}, signal {self.concurrency.signal})"
|
||||
+ (f" - {stages}" if stages else "")
|
||||
)
|
||||
payload = {**disp_gauges, **disp_drain, **self.concurrency.gauges()}
|
||||
return body, payload
|
||||
|
||||
async def drain(self) -> None:
|
||||
"""Stop the background loggers so nothing logs after the monitors finalize."""
|
||||
await self.periodic_logger.stop()
|
||||
await self.inference_metrics.stop()
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
|
||||
if self.periodic_logger is not None:
|
||||
await self.periodic_logger.stop()
|
||||
if self.inference_metrics is not None:
|
||||
await self.inference_metrics.stop()
|
||||
if self.dispatcher is not None:
|
||||
await self.dispatcher.stop()
|
||||
if self.clients is not None:
|
||||
await self.clients.aclose()
|
||||
if self.admin_plane is not None:
|
||||
await self.admin_plane.aclose()
|
||||
@@ -1,66 +0,0 @@
|
||||
"""Checkpoint standalone eval progress cursor."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import pickle
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
|
||||
|
||||
|
||||
class CheckpointManager:
|
||||
def __init__(self, output_dir: Path) -> None:
|
||||
self.ckpt_dir = get_ckpt_dir(output_dir)
|
||||
|
||||
def get_ckpt_path(self, step: int) -> Path:
|
||||
return get_step_path(self.ckpt_dir, step) / "evals"
|
||||
|
||||
def latest_step(self) -> int:
|
||||
steps = [
|
||||
step for step in get_all_ckpt_steps(self.ckpt_dir) if (self.get_ckpt_path(step) / "progress.pt").is_file()
|
||||
]
|
||||
if not steps:
|
||||
raise FileNotFoundError(f"No evals checkpoints found in {self.ckpt_dir}")
|
||||
return steps[-1]
|
||||
|
||||
def save(self, eval_source: EvalSource) -> None:
|
||||
cursor = eval_source.cursor
|
||||
ckpt_path = self.get_ckpt_path(cursor)
|
||||
ckpt_path.mkdir(parents=True, exist_ok=True)
|
||||
start = time.perf_counter()
|
||||
# Replace atomically so resume never observes a partially written pickle.
|
||||
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as f:
|
||||
pickle.dump(eval_source.state_dict(), f)
|
||||
os.replace(tmp_name, ckpt_path / "progress.pt")
|
||||
except BaseException:
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(tmp_name)
|
||||
raise
|
||||
get_logger().debug(
|
||||
f"Evals checkpoint saved to {ckpt_path} (cursor={cursor}) in {format_time(time.perf_counter() - start)}"
|
||||
)
|
||||
|
||||
def load(
|
||||
self,
|
||||
step: int,
|
||||
eval_source: EvalSource,
|
||||
path: Path | None = None,
|
||||
) -> None:
|
||||
ckpt_path = path if path is not None else self.get_ckpt_path(step)
|
||||
state_file = ckpt_path / "progress.pt"
|
||||
if not state_file.is_file():
|
||||
raise FileNotFoundError(f"Evals checkpoint not found at {state_file}")
|
||||
get_logger().info(f"Loading evals checkpoint from {state_file}")
|
||||
with open(state_file, "rb") as f:
|
||||
state = pickle.load(f)
|
||||
if state["cursor"] != step:
|
||||
raise ValueError(f"Evals checkpoint contains cursor {state['cursor']}, expected step {step}")
|
||||
eval_source.load_state_dict(state)
|
||||
@@ -1,605 +0,0 @@
|
||||
"""Evals: multi-env evals against a live inference server.
|
||||
|
||||
Standalone (no ``[online]``), it runs one epoch of every configured eval
|
||||
source against the weights the inference server currently serves, then exits.
|
||||
With ``[online]``, it watches a broadcasts directory for offered weight
|
||||
broadcasts through a ``WeightReceiver`` (announced by their
|
||||
``.sender_ready`` marker), moves the inference server onto each of them, and
|
||||
runs the configured evals against the updated weights, sequentially per
|
||||
broadcast so every epoch measures exactly one policy version. Every offered
|
||||
broadcast must be received, even when no eval is due — the trainer blocks
|
||||
inside the handshake until the receiver acknowledges.
|
||||
|
||||
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
|
||||
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
|
||||
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
|
||||
are version-pinned measurements. By default, a newer online checkpoint cancels
|
||||
unfinished episodes from the prior version; callers can disable this when they need
|
||||
every epoch to drain.
|
||||
|
||||
Env servers: sources without an explicit ``serve.address`` get an env server
|
||||
spawned by the evals process at their derived address; sources with one are
|
||||
externally managed (e.g. spawned by the ``sft`` launcher, which stamps the
|
||||
derived addresses into this config)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
|
||||
from prime_rl import monitors
|
||||
from prime_rl.configs.evals import EvalsConfig
|
||||
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
|
||||
from prime_rl.evals.ckpt import CheckpointManager
|
||||
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
|
||||
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
|
||||
from prime_rl.orchestrator.concurrency import ConcurrencyController
|
||||
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
|
||||
from prime_rl.orchestrator.envs import EvalEnvs
|
||||
from prime_rl.orchestrator.eval_sink import EvalSink
|
||||
from prime_rl.orchestrator.eval_source import EvalSource
|
||||
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
|
||||
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
|
||||
from prime_rl.orchestrator.patches import (
|
||||
monkey_patch_chat_completion_logprobs,
|
||||
monkey_patch_oai_iterable_types,
|
||||
)
|
||||
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
|
||||
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
|
||||
from prime_rl.orchestrator.utils import (
|
||||
episode_group_id,
|
||||
eval_work,
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
)
|
||||
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
|
||||
from prime_rl.utils.config import dump_resolved_config
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.pathing import create_attempt_log_dir, get_all_ckpt_steps, get_config_dir
|
||||
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
|
||||
from prime_rl.utils.utils import clean_exit
|
||||
|
||||
monkey_patch_oai_iterable_types()
|
||||
monkey_patch_chat_completion_logprobs()
|
||||
|
||||
# How often to re-scan the broadcasts directory for new weight broadcasts.
|
||||
POLL_INTERVAL_S = 2.0
|
||||
|
||||
# Budget for the trainer's startup broadcast: it is always coming, but only
|
||||
# after the trainer has finished loading the model.
|
||||
STARTUP_BROADCAST_TIMEOUT_S = 1200
|
||||
|
||||
|
||||
class Evals:
|
||||
def __init__(self, config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
self.config = config
|
||||
self.log_dir = log_dir or (
|
||||
Path(os.environ["PRL_LOG_DIR"])
|
||||
if "PRL_LOG_DIR" in os.environ
|
||||
else create_attempt_log_dir(config.output_dir)
|
||||
)
|
||||
setup_logger(config.log.level, json_logging=config.log.json_logging)
|
||||
intercept_vf_logging(logger="verifiers.v1", level="WARN")
|
||||
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
|
||||
get_logger().info(f"Starting evals ({mode})")
|
||||
|
||||
# The last weight-checkpoint step already handled (evaluated or skipped).
|
||||
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
|
||||
self.eval_triggered_at: dict[tuple[str, int], float] = {}
|
||||
self.ckpt_manager = CheckpointManager(config.output_dir)
|
||||
self.last_saved_cursor = 0
|
||||
self.env_server_procs: list[Popen] = []
|
||||
self.dispatcher_task: asyncio.Task | None = None
|
||||
|
||||
# Assigned in setup(); None-initialized so stop() can tear down a
|
||||
# partially completed setup with plain attribute checks.
|
||||
self.clients: InferenceClient | None = None
|
||||
self.admin_plane: AdminPlane | None = None
|
||||
self.dispatcher: Dispatcher | None = None
|
||||
self.inference_metrics: InferenceMetricsCollector | None = None
|
||||
self.periodic_logger: PeriodicLogger | None = None
|
||||
|
||||
async def setup(self) -> None:
|
||||
config = self.config
|
||||
set_default_executor()
|
||||
|
||||
get_logger().info(f"Initializing monitors ({config.monitors})")
|
||||
await monitors.setup(
|
||||
producer="evals",
|
||||
wandb=config.monitors.wandb,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.output_dir,
|
||||
run_config=config,
|
||||
eval_env_names=[source.resolved_name for source in config.eval.source],
|
||||
overview_flavor="sft",
|
||||
)
|
||||
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
|
||||
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
|
||||
self.run_name = os.environ.get("PRL_RUN_NAME")
|
||||
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
|
||||
|
||||
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
|
||||
self.clients = InferenceClient(config.eval.client, model_name=config.model)
|
||||
self.admin_plane = AdminPlane(config.eval.client)
|
||||
|
||||
self.spawn_env_servers()
|
||||
|
||||
get_logger().info("Loading eval environment(s)")
|
||||
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
|
||||
await self.eval_envs.start()
|
||||
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
|
||||
|
||||
get_logger().info("Waiting for inference pool to be ready")
|
||||
await self.admin_plane.wait_for_ready(config.model)
|
||||
get_logger().success("Inference pool ready")
|
||||
|
||||
self.receiver: WeightReceiver | None = None
|
||||
if config.online is not None:
|
||||
assert config.online.broadcasts_dir is not None
|
||||
# A hand-written online config may omit the transport; broadcasts
|
||||
# are then plain filesystem checkpoints.
|
||||
weight_broadcast = config.weight_broadcast or FileSystemWeightBroadcastConfig()
|
||||
get_logger().info(f"Initializing weight broadcast ({weight_broadcast})")
|
||||
self.receiver = setup_weight_receiver(
|
||||
config.online.broadcasts_dir,
|
||||
weight_broadcast,
|
||||
admin_plane=self.admin_plane,
|
||||
model_name=config.model,
|
||||
)
|
||||
await self.receiver.initialize()
|
||||
|
||||
is_resumed = config.online is not None and config.online.resume_step is not None
|
||||
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
|
||||
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
|
||||
if config.resume is not None:
|
||||
if config.resume.dir is not None:
|
||||
resume_step = config.resume.dir_step
|
||||
resume_path = config.resume.dir / "evals"
|
||||
else:
|
||||
resume_step = config.resume.step or self.ckpt_manager.latest_step()
|
||||
resume_path = None
|
||||
self.ckpt_manager.load(
|
||||
resume_step,
|
||||
self.eval_source,
|
||||
path=resume_path,
|
||||
)
|
||||
self.last_saved_cursor = self.eval_source.cursor
|
||||
get_logger().info(f"Resuming evals from task cursor {self.eval_source.cursor}")
|
||||
self.policy = Policy(version=0, model_name=config.model)
|
||||
|
||||
# Pessimistic per-episode token cost for the controller's starting cap,
|
||||
# only used when the engine doesn't report its max context length.
|
||||
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.eval.source) or 8192
|
||||
self.concurrency = ConcurrencyController(config.eval.concurrency, fallback_cost=fallback_cost)
|
||||
self.dispatcher = Dispatcher(
|
||||
train_envs=None,
|
||||
eval_envs=self.eval_envs,
|
||||
train_source=None,
|
||||
eval_source=self.eval_source,
|
||||
policy_clients=self.clients,
|
||||
policy=self.policy,
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.eval.concurrency.max_inflight,
|
||||
tasks_per_minute=None,
|
||||
max_off_policy_steps=0,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
on_episode_complete=self.concurrency.record_episode,
|
||||
)
|
||||
# No ``on_overload``: eval episodes are measurements and are never
|
||||
# cancelled — a cut only blocks admission until the pool drains.
|
||||
self.concurrency.bind(
|
||||
set_limit=self.dispatcher.set_limit,
|
||||
get_inflight=lambda: self.dispatcher.current_inflight,
|
||||
)
|
||||
# The collector always polls — it feeds the concurrency controller;
|
||||
# metrics fan out to every registered monitor.
|
||||
self.inference_metrics = InferenceMetricsCollector(
|
||||
self.admin_plane.clients,
|
||||
on_load=self.concurrency.observe,
|
||||
)
|
||||
# Fail fast when adaptivity has no signal: external API endpoints
|
||||
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
|
||||
# hit the cap would silently sit at min_inflight forever. A pinned
|
||||
# band (min_inflight = max_inflight) makes the controller inert and
|
||||
# is the supported way to run against such endpoints.
|
||||
if not await self.inference_metrics.probe():
|
||||
concurrency = config.eval.concurrency
|
||||
if concurrency.min_inflight != concurrency.max_inflight:
|
||||
urls = ", ".join(str(client.base_url) for client in self.admin_plane.clients)
|
||||
raise ValueError(
|
||||
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
|
||||
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
|
||||
"pin the concurrency by setting eval.concurrency.min_inflight = max_inflight."
|
||||
)
|
||||
get_logger().warning(f"No engine metrics - running with concurrency pinned at {concurrency.min_inflight}")
|
||||
await self.inference_metrics.start()
|
||||
|
||||
self.periodic_logger = PeriodicLogger(
|
||||
name="Evals",
|
||||
collect=self.collect_pipeline_view,
|
||||
metric_keys=[
|
||||
*list(self.dispatcher.gauges().keys()),
|
||||
*list(self.concurrency.gauges().keys()),
|
||||
*DispatcherMetrics.drain_keys(train_envs=set(), eval_envs={env.name for env in self.eval_envs}),
|
||||
],
|
||||
interval=config.log.interval,
|
||||
wandb_enabled=wandb_enabled,
|
||||
)
|
||||
|
||||
def spawn_env_servers(self) -> None:
|
||||
"""Spawn one env server per source without an explicit ``serve.address``,
|
||||
at the source's derived address."""
|
||||
config = self.config
|
||||
addresses = config.eval.env_addresses
|
||||
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
|
||||
log_dir = self.log_dir / "envs" / "eval"
|
||||
for source in config.eval.source:
|
||||
if source.serve.address is not None:
|
||||
continue
|
||||
name = source.resolved_name
|
||||
address = addresses[("eval", name)]
|
||||
source_dict = dump_resolved_config(source)
|
||||
server_config = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**(source_dict.get("serve") or {}), "address": address},
|
||||
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
|
||||
}
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
config_path = config_dir / f"{name}.json"
|
||||
config_path.write_text(json.dumps(server_config, indent=2))
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
log_path = log_dir / f"{name}.log"
|
||||
get_logger().info(f"Starting env server {name} at {address} (logs: {log_path})")
|
||||
with open(log_path, "w") as log_file:
|
||||
process = Popen(
|
||||
["env-server", "@", config_path.as_posix()],
|
||||
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
self.env_server_procs.append(process)
|
||||
|
||||
async def run(self) -> None:
|
||||
await self.setup()
|
||||
self.dispatcher_task = asyncio.create_task(self.dispatcher.start(), name="dispatcher")
|
||||
await self.periodic_logger.start()
|
||||
|
||||
if self.config.online is None:
|
||||
await self.maybe_run_evals(step=0)
|
||||
else:
|
||||
await self.watch()
|
||||
|
||||
self.maybe_save_checkpoint(force=True)
|
||||
|
||||
# The periodic logger and the collector log to the W&B run, so they
|
||||
# must stop before finalize marks the run finished.
|
||||
await self.periodic_logger.stop()
|
||||
await self.inference_metrics.stop()
|
||||
get_logger().success("Evals finished!")
|
||||
|
||||
async def watch(self) -> None:
|
||||
"""Online mode: evaluate each eligible weight broadcast as it appears."""
|
||||
config = self.config
|
||||
assert config.online is not None
|
||||
online = config.online
|
||||
|
||||
# Rendezvous with the trainer's startup broadcast (v0 fresh, the
|
||||
# checkpoint step on resume) — always, for every transport: an
|
||||
# in-memory trainer blocks inside its startup broadcast until this
|
||||
# receive, and for filesystem it guarantees the served weights match
|
||||
# the trainer's incoming policy.
|
||||
assert self.receiver is not None
|
||||
startup_step = online.resume_step or 0
|
||||
await self.receiver.sync_startup(startup_step, timeout=STARTUP_BROADCAST_TIMEOUT_S)
|
||||
self.policy.version = startup_step
|
||||
|
||||
if online.resume_step is None:
|
||||
# The first trigger fires every env (policy v0) unless ``skip_first_step``.
|
||||
await self.maybe_run_evals(step=0)
|
||||
elif config.eval.retrigger_on_resume:
|
||||
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
|
||||
# evals); the startup rendezvous above already loaded its weights. The
|
||||
# final broadcast force-fires every env, exactly like the watch loop below.
|
||||
is_final = online.max_steps is not None and online.resume_step >= online.max_steps
|
||||
await self.maybe_run_evals(step=online.resume_step, force=is_final)
|
||||
|
||||
get_logger().info(f"Watching {online.broadcasts_dir} for new weight broadcasts (max_steps={online.max_steps})")
|
||||
while True:
|
||||
assert online.broadcasts_dir is not None # resolved by the config validator
|
||||
steps = get_all_ckpt_steps(online.broadcasts_dir)
|
||||
published = {step: self.receiver.is_published(step) for step in steps}
|
||||
newest_published = max((step for step in steps if published[step]), default=None)
|
||||
# Also walk eval-due steps that are no longer on disk: broadcast cleaning
|
||||
# (the trainer keeps only the newest broadcast) can delete a step before
|
||||
# this scan sees it, and a vanished step would otherwise be skipped
|
||||
# without a trace.
|
||||
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_published)):
|
||||
if step <= self.last_step:
|
||||
continue
|
||||
if step not in published:
|
||||
get_logger().warning(
|
||||
f"Weight broadcast for eval step {step} was deleted before it could be "
|
||||
"evaluated (broadcast cleaning outpaced the evals process) - skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
if not published[step]:
|
||||
# The trainer writes broadcasts in ascending order, so a marker-less
|
||||
# step below a published one is an abandoned partial write (e.g. a
|
||||
# crash mid-save), not one in progress — skip it instead of wedging.
|
||||
if newest_published is None or newest_published < step:
|
||||
break # still being written — later steps can't be ready either
|
||||
get_logger().warning(
|
||||
f"Weight broadcast step {step} is not marked published but newer "
|
||||
"broadcasts are - treating it as abandoned and skipping its evals"
|
||||
)
|
||||
self.last_step = max(self.last_step, step)
|
||||
continue
|
||||
is_final = online.max_steps is not None and step >= online.max_steps
|
||||
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
|
||||
if online.max_steps is not None and self.last_step >= online.max_steps:
|
||||
break
|
||||
await asyncio.sleep(POLL_INTERVAL_S)
|
||||
|
||||
def next_published_step(self, step: int) -> int | None:
|
||||
"""Return the first newer checkpoint offered by the trainer."""
|
||||
assert self.config.online is not None
|
||||
assert self.config.online.broadcasts_dir is not None
|
||||
assert self.receiver is not None
|
||||
return next(
|
||||
(
|
||||
candidate
|
||||
for candidate in get_all_ckpt_steps(self.config.online.broadcasts_dir)
|
||||
if candidate > step and self.receiver.is_published(candidate)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
|
||||
"""Eval-due steps up to the newest published broadcast that are missing from
|
||||
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
|
||||
so their absence means broadcast cleaning removed them before they were
|
||||
evaluated."""
|
||||
if newest_published is None:
|
||||
return set()
|
||||
due = {
|
||||
step
|
||||
for interval in self.eval_source.intervals.values()
|
||||
for step in range(interval, newest_published + 1, interval)
|
||||
}
|
||||
return due - set(steps)
|
||||
|
||||
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
|
||||
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
|
||||
reloading the inference weights first. No-op when no env is due — except
|
||||
that a live transport's broadcast must always be received (the trainer
|
||||
is blocked inside it), eval or no eval."""
|
||||
if reload_weights:
|
||||
assert self.receiver is not None
|
||||
broadcast_dir = self.receiver.step_dir(step)
|
||||
if not self.receiver.is_published(step):
|
||||
get_logger().warning(f"No published weight broadcast for step {step} ({broadcast_dir}) - skipping eval")
|
||||
self.last_step = max(self.last_step, step)
|
||||
return
|
||||
|
||||
fired = self.eval_source.trigger(step, force=force)
|
||||
self.last_step = max(self.last_step, step)
|
||||
|
||||
if reload_weights:
|
||||
# Every offered version must be received: the trainer blocks inside
|
||||
# the handshake, so a failed receive fails the run loudly.
|
||||
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
|
||||
await self.dispatcher.on_version_pending(step)
|
||||
await self.receiver.receive(step)
|
||||
self.policy.version = step
|
||||
await self.dispatcher.on_new_version(step)
|
||||
|
||||
if not fired:
|
||||
return
|
||||
|
||||
for env_name in fired:
|
||||
task_count = self.eval_source.triggered_task_count(env_name, step)
|
||||
self.eval_sink.set_batch_size(env_name, step, task_count * self.eval_sink.group_size_for(env_name))
|
||||
|
||||
now = time.perf_counter()
|
||||
for env_name in fired:
|
||||
self.eval_triggered_at[(env_name, step)] = now
|
||||
total_rollouts = sum(
|
||||
self.eval_envs.get(request.env_name).config.group_size
|
||||
for request in self.eval_source.queue
|
||||
if request.step == step and request.env_name in fired
|
||||
)
|
||||
|
||||
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
|
||||
# between the trigger above and the weight reload completing.
|
||||
if not reload_weights:
|
||||
self.policy.version = step
|
||||
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
|
||||
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
|
||||
await self.consume_epoch(fired, step)
|
||||
|
||||
async def consume_epoch(self, fired: list[str], step: int) -> None:
|
||||
"""Consume one epoch, preempting it when a newer checkpoint is ready."""
|
||||
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name, step) > 0}
|
||||
cancellation_task: asyncio.Task[int] | None = None
|
||||
superseding_step: int | None = None
|
||||
online = self.config.online
|
||||
|
||||
while pending:
|
||||
if (
|
||||
cancellation_task is None
|
||||
and online is not None
|
||||
and self.config.eval.cancel_on_new_checkpoint
|
||||
and (superseding_step := self.next_published_step(step)) is not None
|
||||
):
|
||||
get_logger().warning(
|
||||
f"Checkpoint {superseding_step} is ready - cancelling unfinished eval episodes for step {step}"
|
||||
)
|
||||
cancellation_task = asyncio.create_task(
|
||||
self.dispatcher.cancel_eval_step(step), name=f"cancel-eval-step-{step}"
|
||||
)
|
||||
|
||||
try:
|
||||
if online is not None and self.config.eval.cancel_on_new_checkpoint:
|
||||
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=POLL_INTERVAL_S)
|
||||
else:
|
||||
item = await self.dispatcher.out_q.get()
|
||||
except asyncio.TimeoutError:
|
||||
if cancellation_task is not None and cancellation_task.done():
|
||||
cancellation_task.result()
|
||||
continue
|
||||
|
||||
if isinstance(item, GroupCancellation):
|
||||
eval_batch = self.eval_sink.cancel(item)
|
||||
group_completed = False
|
||||
group_id = item.group_id
|
||||
elif isinstance(item, DispatchFailure):
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
group_completed = not self.eval_sink.has_pending_group(item.group_id)
|
||||
group_id = item.group_id
|
||||
else:
|
||||
item_step = eval_work(item).step
|
||||
stamp_arrival([item], "eval", item_step)
|
||||
await monitors.log([item], item_step, "eval", "all")
|
||||
eval_batch = self.eval_sink.add(item)
|
||||
group_id = episode_group_id(item)
|
||||
group_completed = not self.eval_sink.has_pending_group(group_id)
|
||||
if eval_batch is not None:
|
||||
await self.finalize_eval_batch(eval_batch)
|
||||
pending.discard(eval_batch.env_name)
|
||||
if group_completed:
|
||||
source_index = self.dispatcher.pop_source_index(group_id)
|
||||
if self.config.online is not None:
|
||||
continue
|
||||
if source_index is None:
|
||||
raise RuntimeError(f"Eval group {group_id} is missing its source cursor")
|
||||
if self.eval_source.mark_completed(source_index):
|
||||
self.maybe_save_checkpoint()
|
||||
|
||||
if cancellation_task is not None:
|
||||
cancelled = await cancellation_task
|
||||
get_logger().warning(
|
||||
f"Cancelled {cancelled} unfinished eval episodes for step {step}; "
|
||||
f"advancing to checkpoint {superseding_step}"
|
||||
)
|
||||
|
||||
def maybe_save_checkpoint(self, *, force: bool = False) -> None:
|
||||
if self.config.ckpt is None:
|
||||
return
|
||||
cursor = self.eval_source.cursor
|
||||
if cursor <= 0 or cursor == self.last_saved_cursor:
|
||||
return
|
||||
if not force and cursor - self.last_saved_cursor < self.config.ckpt.interval:
|
||||
return
|
||||
self.ckpt_manager.save(self.eval_source)
|
||||
self.last_saved_cursor = cursor
|
||||
|
||||
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
|
||||
"""Persist + log one completed eval epoch through the monitors, mirroring the
|
||||
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
|
||||
if not batch.episodes and not batch.failures and not batch.cancelled:
|
||||
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
|
||||
return
|
||||
|
||||
if batch.episodes.effective:
|
||||
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
|
||||
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
|
||||
|
||||
episodes = batch.episodes
|
||||
effective = episodes.effective
|
||||
metrics: dict[str, float] = {}
|
||||
for subset, pool in (("all", episodes), ("effective", effective)):
|
||||
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
|
||||
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
|
||||
metrics |= dispatch_failure_metrics(
|
||||
batch.failures,
|
||||
prefix=f"eval/{batch.env_name}/all",
|
||||
total_attempts=total_attempts,
|
||||
)
|
||||
if batch.cancelled:
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
|
||||
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
|
||||
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
|
||||
metrics["step"] = float(batch.step)
|
||||
await monitors.log(metrics, step=batch.step)
|
||||
|
||||
eff, full = effective.metrics, episodes.metrics
|
||||
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
|
||||
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
|
||||
if batch.cancelled:
|
||||
get_logger().warning(
|
||||
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Error {full.has_error.mean():.1%} | "
|
||||
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
|
||||
)
|
||||
return
|
||||
get_logger().success(
|
||||
f"Evaluated {batch.env_name} (Step {batch.step}) | "
|
||||
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
|
||||
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
|
||||
)
|
||||
|
||||
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
|
||||
"""Pipeline view for the ``PeriodicLogger``: per-env epoch progress plus the
|
||||
in-flight pool against the controller's current cap."""
|
||||
disp_gauges = self.dispatcher.gauges()
|
||||
disp_drain = self.dispatcher.metrics.drained(train_envs=set(), eval_envs={env.name for env in self.eval_envs})
|
||||
|
||||
parts = []
|
||||
for env_name, _step, arrived, expected, buffered in sorted(self.eval_sink.batch_progress()):
|
||||
part = f"{env_name} {arrived}/{expected} ({arrived / expected:.1%})" if expected else env_name
|
||||
if buffered:
|
||||
part += f" (+{buffered} buffered)"
|
||||
parts.append(part)
|
||||
progress_part = " | ".join(parts) if parts else "Idle"
|
||||
|
||||
body = (
|
||||
f"{progress_part}; {self.dispatcher.inflight_eval_count} inflight episodes "
|
||||
f"(cap {self.dispatcher.max_inflight}, signal {self.concurrency.signal})"
|
||||
)
|
||||
payload = {**disp_gauges, **disp_drain, **self.concurrency.gauges()}
|
||||
return body, payload
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
|
||||
if self.periodic_logger is not None:
|
||||
await self.periodic_logger.stop()
|
||||
if self.inference_metrics is not None:
|
||||
await self.inference_metrics.stop()
|
||||
if self.dispatcher is not None:
|
||||
await self.dispatcher.stop()
|
||||
if self.clients is not None:
|
||||
await self.clients.aclose()
|
||||
if self.admin_plane is not None:
|
||||
await self.admin_plane.aclose()
|
||||
cleanup_processes(self.env_server_procs)
|
||||
|
||||
|
||||
@clean_exit
|
||||
async def run_evals(config: EvalsConfig, log_dir: Path | None = None) -> None:
|
||||
evals = Evals(config, log_dir)
|
||||
try:
|
||||
await evals.run()
|
||||
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
|
||||
await monitors.finalize()
|
||||
finally:
|
||||
await evals.stop()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from prime_rl.entrypoints.evals import main as entrypoint_main
|
||||
|
||||
entrypoint_main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -391,7 +391,6 @@ class DynamoAdminPlane(AdminPlane):
|
||||
port: int,
|
||||
timeout: int,
|
||||
inference_world_size: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
) -> None:
|
||||
async with self._mutation_lock:
|
||||
self._require_uninitialized_nccl()
|
||||
@@ -411,7 +410,6 @@ class DynamoAdminPlane(AdminPlane):
|
||||
0,
|
||||
1,
|
||||
timeout,
|
||||
quantize_in_weight_transfer,
|
||||
"default",
|
||||
],
|
||||
)
|
||||
|
||||
@@ -15,7 +15,6 @@ def apply_shared_vllm_patches():
|
||||
_patch_lora_key_prefix()
|
||||
_patch_qwen35_moe_lora_format()
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_qwen3_coder_param_newline_trim()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
@@ -248,57 +247,6 @@ def monkey_patch_nano_v3_reasoning_parser():
|
||||
ReasoningParserManager.register_module("nano_v3", module=NanoV3ReasoningParser)
|
||||
|
||||
|
||||
def monkey_patch_qwen3_coder_param_newline_trim():
|
||||
"""Restore vLLM 0.23's single-newline trim for qwen3_coder tool parameters.
|
||||
|
||||
vLLM 0.24's parser engine applies a full ``.strip()`` to every parameter
|
||||
value in ``_qwen3_arg_converter``; 0.23's ``Qwen3CoderToolParser`` trimmed
|
||||
exactly one leading and one trailing newline. A full strip corrupts
|
||||
whitespace-significant string parameters (str_replace-style
|
||||
``old_str``/``new_str``, file content with an indented first line, values
|
||||
with intentional trailing newlines), silently changing tool execution and
|
||||
rewards for agentic runs. Copy of ``_qwen3_arg_converter`` with only the
|
||||
trim changed. Also covers ``nemotron_v3``, which reuses ``qwen3_config``.
|
||||
"""
|
||||
import json
|
||||
|
||||
from vllm.parser import qwen3
|
||||
|
||||
def _trim_one_newline(value: str) -> str:
|
||||
if value.startswith("\n"):
|
||||
value = value[1:]
|
||||
if value.endswith("\n"):
|
||||
value = value[:-1]
|
||||
return value
|
||||
|
||||
def _patched_arg_converter(raw_args: str, partial: bool) -> str:
|
||||
params: dict[str, object] = {}
|
||||
|
||||
for match in qwen3._PARAM_RE.finditer(raw_args):
|
||||
name = match.group(1)
|
||||
value = match.group(2)
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
if partial:
|
||||
remaining = qwen3._PARAM_RE.sub("", raw_args)
|
||||
m = qwen3._PARTIAL_PARAM_RE.search(remaining)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
value = m.group(2)
|
||||
if name:
|
||||
## START PATCHED CODE (upstream: value.strip())
|
||||
params[name] = _trim_one_newline(value)
|
||||
## END PATCHED CODE
|
||||
|
||||
return json.dumps(params, ensure_ascii=False)
|
||||
|
||||
qwen3._qwen3_arg_converter = _patched_arg_converter
|
||||
# qwen3_config captures the converter when first built; drop any cached configs.
|
||||
qwen3.qwen3_config.cache_clear()
|
||||
|
||||
|
||||
def monkey_patch_minimax_m2_think_end_passthrough():
|
||||
"""Keep the literal ``</think>`` in MiniMax-M2 content on tool-calling turns.
|
||||
|
||||
@@ -757,68 +705,6 @@ def monkey_patch_no_moe_lora():
|
||||
FusedMoEConfig.__post_init__ = _patched__post_init__
|
||||
|
||||
|
||||
def monkey_patch_fp32_lm_head():
|
||||
"""Run the lm_head projection in fp32, via a native bf16xbf16 -> fp32 GEMM.
|
||||
|
||||
Uses ``torch.mm(..., out_dtype=torch.float32)`` (PyTorch >= 2.10) so the
|
||||
matmul accumulates and emits fp32 directly without zero-padding the bf16
|
||||
operands or maintaining a separate fp32 weight copy. This avoids the
|
||||
epilogue truncation to bf16 that `F.linear(bf16, bf16)` does, which is
|
||||
where lm_head precision actually leaks before the sampler's softmax.
|
||||
|
||||
Activated by setting ``additional_config["fp32_lm_head"] = True`` on the
|
||||
vLLM namespace; the launcher does this when ``inference.enable_fp32_lm_head``
|
||||
is set. The flag is captured once on ``LogitsProcessor.__init__`` (where
|
||||
vLLM guarantees a ``set_current_vllm_config()`` context) and stored on the
|
||||
instance — reading it from ``_get_logits`` during serving doesn't work
|
||||
because vLLM doesn't keep the context set during forwards.
|
||||
|
||||
Tracks vllm-project/vllm#24567 (which uses the operand-upcast approach).
|
||||
Per @Jackmin801 on PR #2438, native ``out_dtype=fp32`` mm is more efficient
|
||||
and just as correct.
|
||||
"""
|
||||
import torch
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_original_init = LogitsProcessor.__init__
|
||||
_original_get_logits = LogitsProcessor._get_logits
|
||||
|
||||
def _patched_init(self, *args, **kwargs):
|
||||
_original_init(self, *args, **kwargs)
|
||||
vllm_config = get_current_vllm_config()
|
||||
additional_config = vllm_config.additional_config or {}
|
||||
self._fp32_lm_head_enabled = additional_config.get("fp32_lm_head", False)
|
||||
if self._fp32_lm_head_enabled:
|
||||
logger.warning("fp32 lm_head ENABLED for this LogitsProcessor instance.")
|
||||
|
||||
def _patched_get_logits(self, hidden_states, lm_head, embedding_bias):
|
||||
if not getattr(self, "_fp32_lm_head_enabled", False):
|
||||
return _original_get_logits(self, hidden_states, lm_head, embedding_bias)
|
||||
|
||||
# Native bf16xbf16 -> fp32 GEMM. torch.mm requires 2D inputs; vLLM v1's
|
||||
# generative path passes 2D [num_tokens, hidden_size] hidden_states, but
|
||||
# flatten defensively in case some future caller passes 3D.
|
||||
flat = hidden_states.reshape(-1, hidden_states.shape[-1])
|
||||
logits = torch.mm(flat, lm_head.weight.t(), out_dtype=torch.float32)
|
||||
if embedding_bias is not None:
|
||||
logits = logits + embedding_bias.to(torch.float32)
|
||||
if hidden_states.dim() > 2:
|
||||
logits = logits.reshape(*hidden_states.shape[:-1], -1)
|
||||
|
||||
logits = self._gather_logits(logits)
|
||||
if logits is not None:
|
||||
logits = logits[..., : self.org_vocab_size]
|
||||
return logits
|
||||
|
||||
LogitsProcessor.__init__ = _patched_init
|
||||
LogitsProcessor._get_logits = _patched_get_logits
|
||||
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
|
||||
|
||||
|
||||
def monkey_patch_dp_coordinator_startup_timeout():
|
||||
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
|
||||
|
||||
@@ -935,6 +821,8 @@ def monkey_patch_deepseek_v4_per_layer_rope():
|
||||
Note that nothing in vLLM's DeepSeek V4 calls the module's `forward`; every consumer reads
|
||||
`cos_sin_cache` and hands it to a fused kernel. The class choice is therefore about the
|
||||
cache's dtype and row count, not about which channels the module would rotate.
|
||||
|
||||
Remove this patch once the pin includes vllm-project/vllm#54815, which ships in 0.29.1.
|
||||
"""
|
||||
from vllm.models.deepseek_v4.common import rope as dsv4_rope
|
||||
|
||||
|
||||
@@ -6,10 +6,10 @@ from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.datastructures import State
|
||||
from vllm.engine.protocol import EngineClient
|
||||
from vllm.entrypoints.openai.api_server import init_app_state
|
||||
from vllm.entrypoints.openai.cli_args import make_arg_parser, validate_parsed_serve_args
|
||||
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.launchers.api_server.app_state import init_app_state
|
||||
from vllm.entrypoints.launchers.cli_args import make_arg_parser, validate_parsed_serve_args
|
||||
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.serve.lora.protocol import LoadLoRAAdapterRequest
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.argparse_utils import FlexibleArgumentParser
|
||||
@@ -26,7 +26,7 @@ from prime_rl.inference.patches import (
|
||||
)
|
||||
|
||||
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
|
||||
# Still needed in vLLM 0.28 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
# Still needed in vLLM 0.29 — upstream rejects prompt_len > max_model_len - max_tokens
|
||||
monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
@@ -42,7 +42,7 @@ monkey_patch_strip_routed_experts_from_chat()
|
||||
# weights concurrently (multi-node disaggregated deployments).
|
||||
monkey_patch_dp_coordinator_startup_timeout()
|
||||
|
||||
logger = init_logger("vllm.entrypoints.openai.api_server")
|
||||
logger = init_logger("vllm.entrypoints.launchers.api_server.entry")
|
||||
|
||||
# Create our own router for custom endpoints
|
||||
router = APIRouter()
|
||||
@@ -138,11 +138,10 @@ async def init_broadcaster(request: Request):
|
||||
timeout = data.get("timeout")
|
||||
rank_offset = data.get("rank_offset")
|
||||
inference_world_size = data.get("inference_world_size")
|
||||
quantize_in_weight_transfer = data.get("quantize_in_weight_transfer", False)
|
||||
session_id = data.get("session_id", "default")
|
||||
await engine_client(request).collective_rpc(
|
||||
"init_broadcaster",
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, quantize_in_weight_transfer, session_id),
|
||||
args=(host, port, rank_offset, inference_world_size, timeout, session_id),
|
||||
)
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -177,9 +176,9 @@ async def custom_init_app_state(
|
||||
state.serving_tokens = prime_serving
|
||||
|
||||
|
||||
import vllm.entrypoints.openai.api_server
|
||||
import vllm.entrypoints.launchers.api_server.entry
|
||||
import vllm.v1.utils
|
||||
from vllm.entrypoints.openai.api_server import build_app as _original_build_app
|
||||
from vllm.entrypoints.launchers.app import build_app as _original_build_app
|
||||
from vllm.v1.utils import run_api_server_worker_proc as _original_run_api_server_worker_proc
|
||||
|
||||
|
||||
@@ -202,8 +201,8 @@ def custom_run_api_server_worker_proc(listen_address, sock, args, client_config=
|
||||
_original_run_api_server_worker_proc(listen_address, sock, args, client_config, **uvicorn_kwargs)
|
||||
|
||||
|
||||
vllm.entrypoints.openai.api_server.init_app_state = custom_init_app_state
|
||||
vllm.entrypoints.openai.api_server.build_app = custom_build_app
|
||||
vllm.entrypoints.launchers.api_server.entry.init_app_state = custom_init_app_state
|
||||
vllm.entrypoints.launchers.api_server.entry.build_app = custom_build_app
|
||||
vllm.v1.utils.run_api_server_worker_proc = custom_run_api_server_worker_proc
|
||||
|
||||
|
||||
@@ -214,7 +213,7 @@ def server(config: InferenceConfig):
|
||||
import os
|
||||
|
||||
from vllm.entrypoints.cli.serve import run_headless, run_multi_api_server
|
||||
from vllm.entrypoints.openai.api_server import run_server
|
||||
from vllm.entrypoints.launchers.api_server.entry import run_server
|
||||
|
||||
# Signal worker processes to disable LoRA on MoE layers when LoRA targets don't include experts
|
||||
lora_target_modules = config.vllm.lora_target_modules
|
||||
|
||||
@@ -4,19 +4,11 @@ vLLM ships a generic tokens-in / tokens-out handler at
|
||||
``vllm.entrypoints.scale_out.token_in_token_out.serving.ServingTokens`` that covers
|
||||
prefix-cache salting, lora dispatch, multimodal features, prompt logprobs,
|
||||
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
|
||||
defaulting and ``usage`` reporting. We subclass it for the bits still missing
|
||||
from the upstream handler:
|
||||
|
||||
1. Compact ``routed_experts`` export — when the engine emits routing
|
||||
decisions, surface them as ``{data, shape, start, dtype}`` base64 raw-byte
|
||||
objects (the form the PD router can merge and the renderers parse) instead
|
||||
of upstream's single ``.npy`` base64 string.
|
||||
|
||||
2. ``kv_transfer_params`` bridging — upstream ``ServingTokens.serve_tokens``
|
||||
parses ``request.kv_transfer_params`` but never threads it into the engine,
|
||||
so PD disagg never fires on ``/inference/v1/generate``. Fixed upstream by
|
||||
https://github.com/vllm-project/vllm/pull/42644, which missed the 0.28.0
|
||||
cut — drop the bridge once we pin a release that includes it.
|
||||
defaulting and ``usage`` reporting. We subclass it for the one bit still
|
||||
missing from the upstream handler: compact ``routed_experts`` export — when the
|
||||
engine emits routing decisions, surface them as ``{data, shape, start, dtype}``
|
||||
base64 raw-byte objects (the form the PD router can merge and the renderers
|
||||
parse) instead of upstream's single ``.npy`` base64 string.
|
||||
|
||||
Everything else (request/response schema, sampling params, error handling)
|
||||
delegates to upstream so we track future vLLM changes for free.
|
||||
@@ -27,17 +19,14 @@ from __future__ import annotations
|
||||
from collections.abc import AsyncGenerator
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from vllm.entrypoints.openai.engine.protocol import (
|
||||
ErrorResponse,
|
||||
RequestResponseMetadata,
|
||||
)
|
||||
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateRequest,
|
||||
GenerateResponse,
|
||||
GenerateResponseChoice,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
from vllm.outputs import RequestOutput
|
||||
|
||||
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
|
||||
@@ -67,25 +56,7 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
|
||||
|
||||
class PrimeRlServingTokens(ServingTokens):
|
||||
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
|
||||
|
||||
async def serve_tokens(
|
||||
self,
|
||||
request: GenerateRequest,
|
||||
raw_request: Request | None = None,
|
||||
) -> GenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
|
||||
# Upstream parses ``request.kv_transfer_params`` but never threads it
|
||||
# into the engine, so decode receives an empty NIXL handshake and
|
||||
# re-prefills the prompt locally (~100x slower under concurrency).
|
||||
# Bridge it through ``sampling_params.extra_args`` so the engine's KV
|
||||
# connector picks the params up. Fixed upstream by vllm#42644 (merged
|
||||
# after 0.28.0) — drop once we pin a release that includes it.
|
||||
if request.kv_transfer_params is not None:
|
||||
extra = request.sampling_params.extra_args or {}
|
||||
extra["kv_transfer_params"] = request.kv_transfer_params
|
||||
request.sampling_params.extra_args = extra
|
||||
|
||||
return await super().serve_tokens(request, raw_request)
|
||||
"""ServingTokens + compact routed experts."""
|
||||
|
||||
async def serve_tokens_full_generator( # type: ignore[override]
|
||||
self,
|
||||
|
||||
@@ -2,7 +2,6 @@ import logging
|
||||
import os
|
||||
|
||||
from prime_rl.inference.patches import (
|
||||
monkey_patch_fp32_lm_head,
|
||||
monkey_patch_minimax_m2_for_lora,
|
||||
monkey_patch_no_moe_lora,
|
||||
)
|
||||
@@ -17,6 +16,3 @@ if os.environ.get("PRIME_NO_MOE_LORA") == "1":
|
||||
monkey_patch_no_moe_lora()
|
||||
else:
|
||||
logger.info("PRIME_NO_MOE_LORA=0: no patch applied")
|
||||
|
||||
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
|
||||
monkey_patch_fp32_lm_head()
|
||||
|
||||
@@ -7,11 +7,7 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.utils import StatelessProcessGroup
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import (
|
||||
load_weights_checkpoint_layerwise,
|
||||
load_weights_kernel,
|
||||
update_mla_absorbed_weights,
|
||||
)
|
||||
from prime_rl.inference.vllm.worker.weight_transfer import load_weights_checkpoint_layerwise
|
||||
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
|
||||
|
||||
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
|
||||
@@ -99,7 +95,6 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
rank_offset: int,
|
||||
inference_world_size: int,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
session_id: str = "default",
|
||||
) -> None:
|
||||
"""Initialize the NCCL broadcast receiver.
|
||||
@@ -109,7 +104,6 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
inference_world_size: Total number of inference GPUs across all servers.
|
||||
"""
|
||||
del session_id
|
||||
self.quantize_in_weight_transfer = quantize_in_weight_transfer
|
||||
# Use the worker's device index directly as the local rank.
|
||||
# The previous dp_group-based computation broke in vLLM v1 multiprocess
|
||||
# DP mode where each worker is a separate process with a singleton
|
||||
@@ -145,11 +139,6 @@ class NCCLWeightUpdateWorker(Worker):
|
||||
assert isinstance(model, Module)
|
||||
|
||||
state_iter = self.nccl_broadcast_receiver.receive_state_dict()
|
||||
if self.quantize_in_weight_transfer:
|
||||
load_weights_kernel(model, state_iter)
|
||||
update_mla_absorbed_weights(model)
|
||||
return
|
||||
|
||||
load_weights_checkpoint_layerwise(
|
||||
model,
|
||||
state_iter,
|
||||
|
||||
@@ -98,10 +98,9 @@ class NIXLWeightUpdateWorker(Worker):
|
||||
rank_offset: int,
|
||||
inference_world_size: int,
|
||||
timeout: int,
|
||||
quantize_in_weight_transfer: bool = False,
|
||||
session_id: str = "default",
|
||||
) -> None:
|
||||
del inference_world_size, quantize_in_weight_transfer
|
||||
del inference_world_size
|
||||
global_rank = rank_offset + self.device.index
|
||||
server_url = f"{host}:{port}"
|
||||
set_ucx_env_defaults(self.device.index)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
from typing import Generator, Iterable
|
||||
from typing import Iterable
|
||||
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader.reload import finalize_layerwise_reload, initialize_layerwise_reload
|
||||
from vllm.model_executor.model_loader.weight_utils import remap_moe_expert_weights
|
||||
|
||||
logger = init_logger("vllm.inference.vllm.worker_weight_transfer")
|
||||
|
||||
@@ -24,116 +23,6 @@ def load_weights_checkpoint_layerwise(
|
||||
finalize_layerwise_reload(model, model_config)
|
||||
|
||||
|
||||
def _invert_logical_to_physical_map(logical_to_physical_map: torch.Tensor, num_physical_experts: int) -> torch.Tensor:
|
||||
"""Build a physical expert -> logical expert map from vLLM EPLB state."""
|
||||
physical_to_logical = torch.full(
|
||||
(num_physical_experts,),
|
||||
-1,
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)
|
||||
logical_indices = torch.arange(
|
||||
logical_to_physical_map.shape[0],
|
||||
dtype=torch.long,
|
||||
device=logical_to_physical_map.device,
|
||||
)[:, None].expand_as(logical_to_physical_map)
|
||||
physical_indices = logical_to_physical_map.to(torch.long)
|
||||
invalid = (physical_indices < -1) | (physical_indices >= num_physical_experts)
|
||||
if invalid.any():
|
||||
invalid_indices = physical_indices[invalid].unique().tolist()
|
||||
raise ValueError(f"EPLB maps to invalid physical experts: {invalid_indices}")
|
||||
|
||||
valid = physical_indices >= 0
|
||||
physical_to_logical[physical_indices[valid]] = logical_indices[valid]
|
||||
return physical_to_logical
|
||||
|
||||
|
||||
def _build_expert_source_indices(routed_experts, router) -> torch.Tensor | None:
|
||||
if routed_experts._expert_map is None:
|
||||
return None
|
||||
|
||||
physical_indices = torch.where(routed_experts._expert_map >= 0)[0]
|
||||
local_indices = routed_experts._expert_map[physical_indices]
|
||||
physical_indices = physical_indices[local_indices.argsort()]
|
||||
|
||||
eplb_layer_state = getattr(router, "eplb_state", None)
|
||||
logical_to_physical_map = getattr(eplb_layer_state, "logical_to_physical_map", None)
|
||||
if logical_to_physical_map is None:
|
||||
return physical_indices
|
||||
|
||||
physical_to_logical = _invert_logical_to_physical_map(logical_to_physical_map, routed_experts.global_num_experts)
|
||||
logical_indices = physical_to_logical[physical_indices.to(physical_to_logical.device)]
|
||||
if (logical_indices < 0).any():
|
||||
missing = physical_indices[(logical_indices < 0).to(physical_indices.device)].tolist()
|
||||
raise ValueError(f"EPLB has no logical mapping for local physical experts: {missing}")
|
||||
|
||||
return logical_indices.to(physical_indices.device)
|
||||
|
||||
|
||||
def build_expert_map(model: Module) -> dict[str, torch.Tensor]:
|
||||
"""Map MoE module names to source expert indices local to this worker.
|
||||
|
||||
vLLM 0.24 turned ``FusedMoE`` into a factory returning a ``MoERunner`` and
|
||||
split the state that used to live on the ``FusedMoE`` module: the expert map
|
||||
(``_expert_map`` / ``global_num_experts``) now lives on
|
||||
``MoERunner.routed_experts`` (a ``RoutedExperts``), and the EPLB state on
|
||||
``MoERunner.router``. Keying by the ``MoERunner`` name prefix-matches the
|
||||
nested ``routed_experts.*`` weight params after ``load_weights_kernel``
|
||||
remaps incoming flat names via ``remap_moe_expert_weights``.
|
||||
"""
|
||||
from vllm.model_executor.layers.fused_moe import MoERunner
|
||||
|
||||
source_indices_by_module: dict[str, torch.Tensor] = {}
|
||||
for module_name, module in model.named_modules():
|
||||
if not isinstance(module, MoERunner):
|
||||
continue
|
||||
source_indices = _build_expert_source_indices(module.routed_experts, module.router)
|
||||
if source_indices is None:
|
||||
continue
|
||||
source_indices_by_module[module_name] = source_indices
|
||||
return source_indices_by_module
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def load_weights_kernel(model: Module, state_iter: Generator[tuple[str, torch.Tensor], None, None]) -> None:
|
||||
"""Load vLLM kernel-format tensors using in-place copy_ updates."""
|
||||
params = dict(model.named_parameters())
|
||||
expert_source_indices = build_expert_map(model)
|
||||
|
||||
loaded = 0
|
||||
skipped: list[str] = []
|
||||
shape_mismatches: list[str] = []
|
||||
|
||||
# The trainer emits pre-0.24 flat kernel names (``...experts.w13_weight``); since
|
||||
# vLLM 0.24 the expert params are nested (``...experts.routed_experts.w13_weight``).
|
||||
# ``remap_moe_expert_weights`` is upstream's compat shim for exactly this transition.
|
||||
for name, tensor in remap_moe_expert_weights(state_iter, params):
|
||||
if name not in params:
|
||||
skipped.append(name)
|
||||
continue
|
||||
|
||||
param = params[name]
|
||||
if param.shape != tensor.shape:
|
||||
for module_name, source_indices in expert_source_indices.items():
|
||||
if not name.startswith(f"{module_name}."):
|
||||
continue
|
||||
tensor = tensor[source_indices.to(tensor.device)]
|
||||
break
|
||||
|
||||
if param.shape != tensor.shape:
|
||||
shape_mismatches.append(f"{name}: param={list(param.shape)} != received={list(tensor.shape)}")
|
||||
continue
|
||||
|
||||
param.copy_(tensor)
|
||||
loaded += 1
|
||||
|
||||
if shape_mismatches:
|
||||
raise ValueError(f"Kernel weight transfer had {len(shape_mismatches)} shape mismatches: {shape_mismatches}")
|
||||
if skipped:
|
||||
raise ValueError(f"Kernel weight transfer skipped {len(skipped)} weights not found in model: {skipped}")
|
||||
logger.debug(f"Kernel weight transfer copied {loaded} weights in-place")
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def update_mla_absorbed_weights(model: Module) -> None:
|
||||
"""Recompute MLA absorbed KV weights after in-place kv_b_proj updates."""
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user