Compare commits
79
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9eacd477f1 | ||
|
|
40d130d8f1 | ||
|
|
7027f65e5f | ||
|
|
d51d0bb84c | ||
|
|
1b929ec184 | ||
|
|
d72e7e8b1e | ||
|
|
2662c9ace1 | ||
|
|
cde3bcd546 | ||
|
|
f962e9c104 | ||
|
|
771953ee01 | ||
|
|
e3dd67633d | ||
|
|
0a437ae340 | ||
|
|
9a55a0899c | ||
|
|
666297d09c | ||
|
|
202f108f33 | ||
|
|
96fa737c35 | ||
|
|
35aa06fbfa | ||
|
|
718635b2ca | ||
|
|
f557d7593f | ||
|
|
f87fd0eb33 | ||
|
|
12001f3167 | ||
|
|
1cf683267d | ||
|
|
b944873248 | ||
|
|
c28afbbae2 | ||
|
|
b963ceda3c | ||
|
|
3cc565eecb | ||
|
|
f52f6a69df | ||
|
|
9cc215df69 | ||
|
|
13c82f0551 | ||
|
|
7d25aaa0d2 | ||
|
|
5a0c80e54a | ||
|
|
e48c943c48 | ||
|
|
e521297df6 | ||
|
|
1556db6ca7 | ||
|
|
f984dee559 | ||
|
|
c1c1fe7e14 | ||
|
|
bdaafc35ab | ||
|
|
48aa99fbb5 | ||
|
|
94dff2ca54 | ||
|
|
4723b0ee5a | ||
|
|
b695a0aeda | ||
|
|
753cfb5a42 | ||
|
|
33e02a7a18 | ||
|
|
94f359e8d6 | ||
|
|
cf400e7db9 | ||
|
|
8da21f16b8 | ||
|
|
ae37b35a34 | ||
|
|
77788ba020 | ||
|
|
ab85b3b369 | ||
|
|
de5cdb8bae | ||
|
|
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 |
@@ -43,7 +43,7 @@ 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).
|
||||
Skills live in `skills/` and are symlinked to `.claude/skills/` (Claude Code) and `.agents/skills/` (Codex). They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs).
|
||||
|
||||
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.
|
||||
|
||||
|
||||
+29
-12
@@ -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 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,26 +133,42 @@ 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 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")]'
|
||||
|
||||
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
|
||||
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
|
||||
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
|
||||
# the disaggregated P/D path — default off so training-only / single-node
|
||||
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
|
||||
ARG INCLUDE_NIXL_FROM_SOURCE=0
|
||||
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
|
||||
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
|
||||
# rebuilding against our UCX is the documented fix. The rename is required: an
|
||||
# unrenamed source build is `nixl_cu12`, and the `nixl` shim imports nixl_cu13
|
||||
# (the PyPI wheel) first, so the fix would silently not apply. Libraries carry
|
||||
# RUNPATH=/opt/ucx/lib, so no LD_LIBRARY_PATH is needed at runtime.
|
||||
# Opt out via `--build-arg INCLUDE_NIXL_FROM_SOURCE=0`.
|
||||
#
|
||||
# NIXL's [build-system] requires are unpinned, so pip's build isolation picks up
|
||||
# new backends as they are released. meson-python 0.22.0 stopped keeping Meson's
|
||||
# build RPATH in wheel libraries, which dropped RUNPATH=/opt/ucx/lib and failed
|
||||
# the linkage check below on every build. Pin the validated backend.
|
||||
ARG INCLUDE_NIXL_FROM_SOURCE=1
|
||||
ARG NIXL_VERSION=0.10.1
|
||||
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
|
||||
VIRTUAL_ENV=/app/.venv uv pip install pip \
|
||||
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
|
||||
&& cd /tmp/nixl \
|
||||
&& uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml \
|
||||
&& printf 'meson-python==0.21.1\n' > /tmp/nixl-build-constraints.txt \
|
||||
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
|
||||
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
|
||||
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu13-*.whl \
|
||||
&& rm -rf /tmp/nixl /app/deps/nixl_cu13-*.whl; \
|
||||
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/tmp/nixl-whl \
|
||||
--build-constraint /tmp/nixl-build-constraints.txt \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /tmp/nixl-whl/nixl_cu13-*.whl \
|
||||
&& PLUGIN=/app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so \
|
||||
&& if ! ldd "$PLUGIN" | grep -q /opt/ucx/lib/libucp.so; then \
|
||||
echo "ERROR: $PLUGIN does not link /opt/ucx/lib. RUNPATH and ldd output:" >&2; \
|
||||
readelf -d "$PLUGIN" | grep -E 'RUNPATH|RPATH' >&2 || true; \
|
||||
ldd "$PLUGIN" >&2; \
|
||||
exit 1; \
|
||||
fi \
|
||||
&& rm -rf /tmp/nixl /tmp/nixl-whl /tmp/nixl-build-constraints.txt; \
|
||||
fi
|
||||
|
||||
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
|
||||
|
||||
@@ -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
|
||||
@@ -113,15 +113,6 @@ uv sync --all-extras
|
||||
|
||||
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
|
||||
|
||||
3.1. Optional: Install Flash Attention 3 (on Hopper GPUs only, for flash_attention_3 attention backend)
|
||||
|
||||
> *NOTE*: This step will take a while, as it builds the Flash Attention 3 extension from source, as it has no wheels prebuilt.
|
||||
> *NOTE*: After this step, you can't run `uv sync --all-extras` or `uv run` as it will uninstall the package, you can avoid it by running `uv sync --inexact` or `uv run --no-sync`
|
||||
|
||||
```bash
|
||||
uv pip install "flash-attn-3 @ git+https://github.com/Dao-AILab/flash-attention.git@main#subdirectory=hopper" --no-build-isolation
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
@@ -148,19 +139,13 @@ uv run python -c "import flash_attn"
|
||||
uv run sft @ configs/debug/fake/sft.toml
|
||||
```
|
||||
|
||||
4. Check that you can run the RL trainer (*this requires 1 GPU*)
|
||||
|
||||
```bash
|
||||
uv run trainer @ configs/debug/fake/rl.toml
|
||||
```
|
||||
|
||||
5. Check that you can run the inference server (*this requires 1 GPU*)
|
||||
4. Check that you can run the inference server (*this requires 1 GPU*)
|
||||
|
||||
```bash
|
||||
uv run inference --vllm.model Qwen/Qwen3-0.6B
|
||||
```
|
||||
|
||||
6. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
|
||||
5. Check that the full RL stack (inference + orchestrator + trainer) runs end-to-end (*this requires 2 GPUs*)
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/reverse-text/rl.toml
|
||||
@@ -204,7 +189,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. [**GLM-5**](examples/advanced/glm-5.2/): Large-scale `GLM-5`/`GLM-5.2` training 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
|
||||
|
||||
|
||||
@@ -22,7 +22,9 @@ lr = 2e-5
|
||||
|
||||
[eval]
|
||||
interval = 25
|
||||
num_examples = 32
|
||||
|
||||
[eval.select]
|
||||
limit = 32
|
||||
|
||||
[eval.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
# 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
|
||||
|
||||
[select]
|
||||
limit = 4
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
|
||||
@@ -48,7 +48,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 16
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -54,7 +54,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 16
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -29,7 +29,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -29,7 +29,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -48,7 +48,9 @@ algo.teacher.base_url = "http://localhost:8001/v1"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -41,7 +41,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -41,7 +41,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -31,7 +31,9 @@ env.player1.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 16
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 16
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
@@ -37,7 +37,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -46,7 +46,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -46,7 +46,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 1
|
||||
num_examples = 128
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
@@ -117,7 +117,7 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "swebench-verified"
|
||||
num_examples = 100
|
||||
select.limit = 100
|
||||
env.taskset.id = "swebench-verified"
|
||||
env.agent.harness.id = "bash"
|
||||
env.agent.runtime.labels = ["debug-concurrency"]
|
||||
@@ -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
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/multi-env.toml
|
||||
|
||||
num_examples = 16
|
||||
[select]
|
||||
limit = 16
|
||||
|
||||
[[source]]
|
||||
name = "tb2-bash"
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/multi-turn.toml
|
||||
|
||||
num_examples = 16
|
||||
[select]
|
||||
limit = 16
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "terminal-bench-2"
|
||||
|
||||
@@ -7,9 +7,11 @@
|
||||
# <Ctrl-C partway>
|
||||
# uv run eval @ configs/debug/eval/resume.toml --run.name resume-debug --resume
|
||||
|
||||
num_examples = 8
|
||||
group_size = 2
|
||||
|
||||
[select]
|
||||
limit = 8
|
||||
|
||||
[concurrency]
|
||||
min_inflight = 2
|
||||
max_inflight = 2
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
#
|
||||
# uv run eval @ configs/debug/eval/single-turn.toml
|
||||
|
||||
num_examples = 8
|
||||
group_size = 2
|
||||
|
||||
[select]
|
||||
limit = 8
|
||||
|
||||
[sampling]
|
||||
max_completion_tokens = 8192
|
||||
|
||||
|
||||
@@ -31,7 +31,9 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
num_examples = 64
|
||||
|
||||
[orchestrator.eval.select]
|
||||
limit = 64
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: 1f1e050ab0...565e8a74c0
Vendored
+1
-1
Submodule deps/renderers updated: f91c3e7061...cde869941c
Vendored
+1
-1
Submodule deps/verifiers updated: 28f0893974...e5a9e17a8c
+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]`.
|
||||
|
||||
|
||||
+18
-2
@@ -171,6 +171,22 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
Each source group — `[orchestrator.train]`, `[orchestrator.eval]`, the `[eval]` block of `sft` and the top level of `eval` — takes an `env` block that each of its sources inherits. A source's own `env` values win. The block holds only the knobs that every env and taskset has: `retries`, `timeout`, `max_concurrent_agents`, `interception`, and `taskset.task` and `taskset.system_prompt`. Ids and agents stay on each source:
|
||||
|
||||
```toml
|
||||
[orchestrator.eval.env]
|
||||
retries.max_retries = 3
|
||||
retries.include = ["ProviderError", "SandboxError"]
|
||||
timeout.episode = 7200
|
||||
```
|
||||
|
||||
Each source also takes a `select` block that picks which tasks of its taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit`, in that order. A group's `select` block works like its `env` block: every source inherits it field by field, and a source's own fields win. A source's `include` or `exclude` replaces the group's whole block. To evaluate 128 tasks of each taskset:
|
||||
|
||||
```toml
|
||||
[orchestrator.eval.select]
|
||||
limit = 128
|
||||
```
|
||||
|
||||
`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 +241,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.
|
||||
- [**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
|
||||
|
||||
|
||||
+18
-6
@@ -32,19 +32,21 @@ 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.
|
||||
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`/`-s`/`-r` set `select.limit`/`select.shuffle`/`group_size`, `-m` the model, and `-c N` pins the concurrency band (`concurrency.min_inflight = max_inflight = N`). `<taskset-id>` cannot be combined with a TOML that defines `[[source]]` blocks; next to one, `--env.<field>` sets the shared [env block](#configuration) instead. `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]]`:
|
||||
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]`, `[select]`, `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
|
||||
|
||||
[select] # every source inherits these
|
||||
limit = 32
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
@@ -55,6 +57,10 @@ max_inflight = 256
|
||||
[sampling]
|
||||
max_completion_tokens = 2048
|
||||
|
||||
[env] # every source inherits these
|
||||
timeout.episode = 7200
|
||||
retries.max_retries = 3
|
||||
|
||||
[[source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
env.agent.harness.id = "bash"
|
||||
@@ -63,9 +69,14 @@ env.agent.harness.id = "bash"
|
||||
env.taskset.id = "aime25"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
select.include.idx = ["0:30"]
|
||||
```
|
||||
|
||||
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.
|
||||
Per-source `group_size` and `sampling` override the top-level defaults. The top-level `[env]` block holds the env knobs that every source inherits (see [Environments](configuration.md#environments)); a source's own `env` values win.
|
||||
|
||||
Each field a source sets in its `select` overrides the same field of the top-level `[select]`. `select` picks which tasks of the taskset run: `include`/`exclude` by task `idx`/`ids`/`keys`/`names`, then `shuffle`, `skip` and `limit` (see verifiers' [Selecting tasks](../deps/verifiers/docs/v1/tasksets.md#selecting-tasks)). Train sources take the same `select`.
|
||||
|
||||
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
|
||||
|
||||
@@ -79,7 +90,7 @@ 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.
|
||||
A landed episode counts toward the task with its `task.key`, so `select` and `group_size` may change between the two launches: kept episodes are matched to the new selection and the rest is owed. The resumed config is not checked against the interrupted one: any of it may be overridden, so keep the model, the sampling and each source's env the same when the landed episodes must stay comparable. 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
|
||||
|
||||
@@ -89,7 +100,7 @@ Monitors receive the run's metrics and episodes through one abstraction. The fil
|
||||
|
||||
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 metrics 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 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
|
||||
|
||||
@@ -109,6 +120,7 @@ Eval metrics mirror the training rollout hierarchy under the `eval/<env>` scope:
|
||||
|---|---|
|
||||
| `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>/is_timeout/mean` | share of rollouts stopped by a stage deadline (`<stage>_timeout`) |
|
||||
| `eval/<env>/all/<agent>/has_error/mean` | share of rollouts that raised |
|
||||
| `eval/<env>/all/seq_len/mean` | mean episode length in tokens |
|
||||
|
||||
|
||||
+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`. Standard deployments use the V2 model runner. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.
|
||||
|
||||
```toml
|
||||
[trainer]
|
||||
|
||||
+6
-5
@@ -94,7 +94,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
|
||||
|
||||
EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP communication volume per layer and improving the training throughput. EP is only available with the custom model implementation (`model.impl = "custom"` or `"auto"` for supported families).
|
||||
|
||||
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is <= 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
|
||||
`ep` defaults to `"auto"`, which resolves at startup to the largest valid EP degree up to 8. It loads the model config to read `num_experts`, then picks the biggest divisor of `num_experts` that also divides the FSDP island size (`world_size // dp_replicate`), is a multiple of `cp`, and is at most 8. For non-MoE models, resolves to 1 (no-op). Set `ep` to an explicit integer to override:
|
||||
|
||||
```toml
|
||||
[trainer.model]
|
||||
@@ -117,7 +117,7 @@ CP shards a single sequence across multiple GPUs along the token dimension — f
|
||||
```toml
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "auto" # auto = FA3 on Hopper, FA4 on Blackwell; or flash_attention_2/3/4
|
||||
attn = "auto" # auto = FA3 on Hopper, FA4 on datacenter Blackwell, FA2 otherwise; or flash_attention_2/3/4
|
||||
cp = 2 # CP degree
|
||||
cp_style = "ulysses" # "ring"
|
||||
```
|
||||
@@ -233,7 +233,8 @@ 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/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.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.
|
||||
- [`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.
|
||||
|
||||
@@ -273,8 +274,8 @@ To benchmark a parallelism config before committing a multi-day run, run a short
|
||||
# SFT trainer alone
|
||||
uv run sft @ sft.toml --data.type fake --max-steps 4
|
||||
|
||||
# RL trainer alone (no inference involved)
|
||||
uv run trainer @ train.toml --data.fake --max-steps 4
|
||||
# RL trainer alone (no inference involved) -- launch it under torchrun, like the `rl` launcher does
|
||||
uv run torchrun --nproc-per-node=8 src/prime_rl/trainer/rl/train.py @ train.toml --data.fake --max-steps 4
|
||||
```
|
||||
|
||||
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `monitors/file/metrics.jsonl` under the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
|
||||
|
||||
+16
-7
@@ -35,8 +35,7 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
| `uv run rl` | Wraps the trainer, orchestrator, and inference server in one launch from a merged TOML. | The default for any RL run. Runs locally for single-node experiments; submits to SLURM for single- or multi-node when `[slurm]` is set (see [Scaling § SLURM](scaling.md#slurm)). |
|
||||
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
|
||||
| `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 orchestrator` | Standalone orchestrator process. | Pair with a separately-launched inference server and one `env-server` per source. |
|
||||
| `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. |
|
||||
|
||||
@@ -119,6 +118,7 @@ Pulled from the console logs and mirrored to W&B.
|
||||
|
||||
- `reward/{all,env}/mean` — main signal. Should trend upward over hundreds of steps.
|
||||
- `seq_len/{all,env}/mean` and `is_truncated/{all,env}/mean` — rollout length and truncation rate.
|
||||
- `is_timeout/{all,env}/mean` — share of rollouts stopped by a stage deadline (`setup`/`agent`/`finalize`/`scoring` `_timeout`). Training counts a timed-out rollout as an error, so it stays out of the batch; eval scores it.
|
||||
- `num_turns/{all,env}/mean` — for multi-turn envs.
|
||||
- `empty_rollouts/{all,env}`, `errored_rollouts/{all,env}` — non-zero is fine in small numbers; sustained > 5% is a smell.
|
||||
- `eval/{env}/{avg@k,pass@k}` — eval scores when `[orchestrator.eval]` is set.
|
||||
@@ -162,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.
|
||||
@@ -180,14 +182,18 @@ uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
|
||||
|
||||
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
|
||||
|
||||
`--monitors.prime` streams the run to the Prime Intellect platform — see [Platform Monitoring](#platform-monitoring).
|
||||
|
||||
### Online Evals
|
||||
|
||||
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `num_examples` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
|
||||
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `select` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
|
||||
|
||||
```toml
|
||||
[eval]
|
||||
interval = 25
|
||||
num_examples = 32
|
||||
|
||||
[eval.select]
|
||||
limit = 32
|
||||
|
||||
[[eval.source]]
|
||||
name = "reverse-text"
|
||||
@@ -250,7 +256,7 @@ Pulled from the console log and mirrored to W&B.
|
||||
|
||||
- `optim/grad_norm` — spikes precede divergence.
|
||||
- `optim/lr` — LR schedule.
|
||||
- For MoE: `max_vio/mean` (load-balancing violation), `routing_confidence/mean` — both are logged when non-zero.
|
||||
- For MoE: `max_vio/mean`, `max_vio/max` — mean and max over the step's microsteps of the largest load-balancing violation across layers and EP groups, computed from expert token counts summed across each EP group. `routing_confidence/mean` — mean routing confidence.
|
||||
|
||||
**Performance:**
|
||||
|
||||
@@ -355,7 +361,7 @@ 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.
|
||||
|
||||
@@ -379,6 +385,7 @@ Register a run on the Prime Intellect platform (Prime Lab) and stream training m
|
||||
|
||||
```bash
|
||||
uv run rl @ rl.toml --monitors.prime
|
||||
uv run sft @ sft.toml --monitors.prime # same flag on the SFT trainer
|
||||
```
|
||||
|
||||
Or set it in TOML:
|
||||
@@ -388,7 +395,9 @@ Or set it in TOML:
|
||||
name = "my-experiment"
|
||||
```
|
||||
|
||||
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. A process that exits without finishing is reported as crashed. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
|
||||
The monitor is a thin layer over the [`prime-runs`](https://github.com/PrimeIntellect-ai/prime/tree/main/packages/prime-runs) SDK (installed as `prime-runs[train]`): it registers the run, streams per-step metrics, uploads every 10th step's episodes (full conversations with rewards and advantages) to the run's sample viewer, and closes the run out. Finalization is best-effort SDK delivery: a process that exits without finishing is reported crashed when the SDK's atexit hook runs, but an abrupt kill (SIGKILL, OOM, node loss) skips the report and a lost finalize is not retried — the platform owns the terminal state of attached (`RUN_ID`) and managed runs. Uploaded episodes are keyed to the platform run by the SDK; the orchestrator's own run id (the launcher's `PRL_RUN_ID`) stays on W&B and in the local records.
|
||||
|
||||
On `sft` the monitor registers the run with the dataset-batched training fields (`max_steps`, `batch_size`, `seq_len`) and streams the trainer's per-step metrics and validation losses; SFT has no rollouts, so no episodes are uploaded.
|
||||
|
||||
Requires `PRIME_API_KEY` (`prime login` or the env var) and a team (`PRIME_TEAM_ID`, or the team selected with `prime login`) enabled for external runs. A configured monitor must work: a missing key or a team outside the allowlist fails the launch. `PRIME_RUNS_MODE=disabled` keeps the monitor configured but opens no platform run; `RUN_ID=<id>` attaches to an external run a launcher already created instead of registering a new one. Currently internal-only.
|
||||
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ Larger runs on frontier models, one folder per model, each with a launch README
|
||||
|
||||
- [`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.2/`](advanced/glm-5.2/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.
|
||||
- [`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.
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
# 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).
|
||||
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` | 1 train + 3 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`. `search.toml` and `terminal.toml` train with Muon on 2 nodes; `swe.toml` fits the trainer on a single node with full optimizer offload and the stateless sign-SGD optimizer. Search answers are scored by a reference judge (`Qwen/Qwen3-235B-A22B-Instruct-2507`).
|
||||
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 — if you use those, log the `prime` CLI in (it ships with prime-rl's dependencies), and each config's `slurm.pre_run_command` will clean up the run's orphaned sandboxes by label before launching:
|
||||
- **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 run prime login # or: uv run prime config set-api-key <your-key>
|
||||
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.
|
||||
@@ -54,7 +57,7 @@ uv run rl @ examples/advanced/glm-4.5-air/swe.toml \
|
||||
--run.name glm45air-swe
|
||||
```
|
||||
|
||||
Swap `swe.toml` for `search.toml` or `terminal.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>`).
|
||||
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
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ interval = 20
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "browsecomp"
|
||||
num_examples = 500 # full set is 1266; cap eval at 500
|
||||
select.limit = 500 # full set is 1266; cap eval at 500
|
||||
env.agent.harness.id = "rlm"
|
||||
env.agent.harness.skills = ["search"]
|
||||
env.agent.harness.forward_env = ["SERPER_API_KEY"]
|
||||
|
||||
@@ -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,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
|
||||
@@ -1,22 +1,23 @@
|
||||
# GLM-5 family at scale
|
||||
|
||||
Large-scale RL and serving for the GLM-5 family — `zai-org/GLM-5`, `GLM-5.1`, and `GLM-5.2-FP8` — at 131k context: 16 trainer nodes on the custom MoE implementation (expert parallelism; the llm-d variant adds context parallelism) and P/D-disaggregated FP8 inference. The `-llmd` variants front the 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. They also offload KV to a Mooncake distributed CPU pool (1TB per node by default).
|
||||
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) | GLM-5 RL plane: 16 train nodes, eval on `swebench-verified` every 20 steps, default vLLM router over 2 P/D replicas (4 prefill + 4 decode nodes each). Declares **no train source** — compose yours on top with an `[[orchestrator.train.source]]` overlay. | 16 train + 16 infer nodes |
|
||||
| [`swe-llmd.toml`](swe-llmd.toml) | Full-stack GLM-5.1 RL: trains on `r2e-gym` (`rlm` harness), FP8-quantized trainer (`deepgemm_fp8` MoE compute), llm-d router + Mooncake KV offload. | 16 train + 16 infer nodes |
|
||||
| [`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` (llm-d variant) accordingly.
|
||||
- InfiniBand/RDMA NICs for the Mooncake KV pool (llm-d variants).
|
||||
- **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, log the `prime` CLI in — it ships with prime-rl's dependencies:
|
||||
- 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 run prime login # or: uv run prime config set-api-key <your-key>
|
||||
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).
|
||||
@@ -24,9 +25,9 @@ uv run prime login # or: uv run prime config set-api-key <your-key>
|
||||
- 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 configs log to W&B (`[monitors.wandb]`).
|
||||
- `WANDB_API_KEY` — both RL variants log to W&B (`[monitors.wandb]`).
|
||||
|
||||
### Install llm-d (llmd variants only)
|
||||
### 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`:
|
||||
|
||||
@@ -47,28 +48,27 @@ uv sync --all-extras --all-packages
|
||||
|
||||
## Tweak before launching
|
||||
|
||||
- `swe-llmd.toml` marks two `# FILL IN` values: `output_dir` (point it at your shared filesystem) and `[slurm] partition`. `swe.toml` needs `--slurm.partition <your-partition>` or `--output-dir` overrides on the command line.
|
||||
- `[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.
|
||||
- `[inference.kv_cache_offload.cpu] num_bytes` — 1TB per node by default; lower it if your nodes have less RAM.
|
||||
- `swe-llmd.toml` ships without `[ckpt]` — add a checkpoint overlay if you want resume support.
|
||||
- `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.1 RL with llm-d + Mooncake (recommended)
|
||||
uv run rl @ examples/advanced/glm-5.2/swe-llmd.toml
|
||||
# GLM-5.3 RL behind the default vllm-router
|
||||
uv run rl @ examples/advanced/glm-5.3/swe.toml
|
||||
|
||||
# GLM-5 base plane — compose your train source onto it
|
||||
uv run rl @ examples/advanced/glm-5.2/swe.toml @ my-train-source.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.2/infer/pd.toml
|
||||
uv run inference @ examples/advanced/glm-5.2/infer/pd-llmd.toml
|
||||
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
|
||||
@@ -97,6 +97,21 @@ Pass several output directories to track parallel experiments side by side (`uv
|
||||
|
||||
## Checkpoint and resume
|
||||
|
||||
`swe.toml` checkpoints every 100 steps (`[ckpt] interval = 100`). 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.
|
||||
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.
|
||||
|
||||
## SFT
|
||||
|
||||
The SFT configs live under [`sft/h200/`](sft/h200) — they are tuned for 8-GPU H200 nodes. Compose the base config with a data overlay:
|
||||
|
||||
```bash
|
||||
uv run sft @ examples/advanced/glm-5.3/sft/h200/base.toml @ examples/advanced/glm-5.3/sft/h200/math-10k.toml
|
||||
```
|
||||
|
||||
This will start a SFT run with the following configuration:
|
||||
|
||||
- The model is `zai-org/GLM-5.3-BF16`
|
||||
- The data is `PrimeIntellect/INTELLECT-3-SFT-10K` (math split)
|
||||
|
||||
For a fake-data dry run, append [`fake.toml`](sft/h200/fake.toml) instead. You can use the same dashboard to monitor the SFT run.
|
||||
+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,40 @@
|
||||
clean = true
|
||||
|
||||
[env_vars]
|
||||
HF_HOME = "/home/huggingface"
|
||||
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
|
||||
|
||||
[model]
|
||||
name = "zai-org/GLM-5.3-BF16"
|
||||
impl = "custom"
|
||||
attn = "flash_attention_2"
|
||||
cp = 8
|
||||
ep = 8
|
||||
optim_cpu_offload = true
|
||||
|
||||
[model.ac]
|
||||
freq = 1
|
||||
|
||||
[model.ac_offloading]
|
||||
max_inflight_activations = 5
|
||||
|
||||
[optim]
|
||||
type = "sign_sgd"
|
||||
lr = 5e-5
|
||||
weight_decay = 0.01
|
||||
|
||||
[scheduler]
|
||||
type = "linear"
|
||||
warmup_steps = 50
|
||||
decay_steps = 0
|
||||
|
||||
[renderer]
|
||||
name = "glm-5.3"
|
||||
|
||||
[deployment]
|
||||
type = "multi_node"
|
||||
num_train_nodes = 8
|
||||
|
||||
[slurm]
|
||||
job_name = "glm53-sft"
|
||||
partition = "all"
|
||||
@@ -0,0 +1,8 @@
|
||||
[model.debug]
|
||||
force_balanced_routing = true
|
||||
|
||||
[data]
|
||||
type = "fake"
|
||||
batch_size = 8
|
||||
micro_batch_size = 1
|
||||
seq_len = 131072
|
||||
@@ -0,0 +1,7 @@
|
||||
[data]
|
||||
type = "sft"
|
||||
name = "PrimeIntellect/INTELLECT-3-SFT-10K"
|
||||
splits = ["math"]
|
||||
batch_size = 8
|
||||
micro_batch_size = 1
|
||||
seq_len = 131072
|
||||
@@ -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
|
||||
@@ -45,6 +45,7 @@ weight_decay = 0.01
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 2048
|
||||
group_size = 8
|
||||
|
||||
[orchestrator.concurrency]
|
||||
initial_inflight = 4096
|
||||
|
||||
@@ -13,10 +13,11 @@ RL on the 30B-A3B MoE across three domains: math, SWE, and agentic tool use. The
|
||||
## 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, log the `prime` CLI in (it ships with prime-rl's dependencies):
|
||||
- **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 run prime login # or: uv run prime config set-api-key <your-key>
|
||||
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).
|
||||
|
||||
@@ -42,6 +42,7 @@ lr = 1e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 8
|
||||
max_off_policy_steps = 8
|
||||
|
||||
[orchestrator.concurrency]
|
||||
|
||||
@@ -43,6 +43,7 @@ lr = 1e-6
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 8
|
||||
max_off_policy_steps = 16
|
||||
|
||||
[orchestrator.concurrency]
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
# uv run eval @ examples/basic/alphabet-sort/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[select]
|
||||
limit = 20
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
# uv run eval @ examples/basic/reverse-text/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-0.6B"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[select]
|
||||
limit = 20
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text-eval"
|
||||
num_examples = 256
|
||||
select.limit = 256
|
||||
env.taskset.id = "reverse-text"
|
||||
env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
|
||||
@@ -15,7 +15,9 @@ lr = 2e-5
|
||||
|
||||
[eval]
|
||||
interval = 25
|
||||
num_examples = 32
|
||||
|
||||
[eval.select]
|
||||
limit = 32
|
||||
|
||||
[eval.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
# uv run eval @ examples/basic/wiki-search/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[select]
|
||||
limit = 20
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
|
||||
@@ -5,9 +5,11 @@
|
||||
# uv run eval @ examples/basic/wordle/eval.toml
|
||||
|
||||
model = "Qwen/Qwen3-1.7B"
|
||||
num_examples = 20
|
||||
group_size = 3
|
||||
|
||||
[select]
|
||||
limit = 20
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ dependencies = [
|
||||
"renderers>=0.1.11",
|
||||
"tomli>=2.2.1",
|
||||
"tomli-w>=1.2.0",
|
||||
"verifiers>=0.3.0",
|
||||
"verifiers>=0.3.2.dev152",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import AliasChoices, Field, model_validator
|
||||
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, MonitorsConfig
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig
|
||||
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalSourcesConfig, ScheduledEvalConfig
|
||||
from prime_rl.configs.shared import ClientConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.shared import ClientConfig, HeartbeatConfig, LogConfig, RunConfig
|
||||
from prime_rl.configs.trainer import WeightBroadcastConfig
|
||||
from prime_rl.utils.config import default_output_dir
|
||||
|
||||
@@ -21,6 +22,18 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Adaptive in-flight episode concurrency, sized by the same controller as
|
||||
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
|
||||
sandbox-backed environments to pace provisioning during autoscaling. None disables
|
||||
rate limiting."""
|
||||
|
||||
heartbeat: HeartbeatConfig | None = None
|
||||
"""BetterStack heartbeat for the run: one ping per landed episode — the first
|
||||
landed episode is the first beat, so the run's boot never shows up as a
|
||||
stale-prone silence. When episodes stop landing, the pings stop and the heartbeat
|
||||
goes stale on Better Stack after its grace period. Size that period + grace above
|
||||
the longest legitimate gap between episodes."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
@@ -45,14 +58,15 @@ class EvalConfig(ServedEvalConfig):
|
||||
client: ClientConfig = ClientConfig(base_url=PRIME_INFERENCE_URL, api_key_var="PRIME_API_KEY")
|
||||
"""Client of the inference server. Defaults to Prime Inference."""
|
||||
|
||||
select: vf.SelectCLIConfig = vf.SelectCLIConfig()
|
||||
"""Task selection that every source inherits (``-n`` sets ``limit``, ``-s`` sets
|
||||
``shuffle``). Each field a source sets on its own ``select`` wins over this one."""
|
||||
|
||||
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."""
|
||||
|
||||
@@ -75,9 +89,7 @@ class EvalConfig(ServedEvalConfig):
|
||||
|
||||
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."""
|
||||
landed episodes rejoin the epoch and only the rollouts still owed run."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
@@ -145,8 +157,14 @@ class SFTOnlineEvalConfig(ScheduledEvalConfig, ServedEvalConfig):
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
monitors: EvalMonitorsConfig = EvalMonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``).
|
||||
|
||||
``EvalMonitorsConfig``, not the base ``MonitorsConfig``: the launcher
|
||||
converts the trainer's ``[monitors.prime]`` into a
|
||||
``PrimeEvalMonitorConfig`` for the online-eval process, and the base
|
||||
type would drop (or forbid) the prime block at the eval.json
|
||||
dump/re-parse boundary."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_broadcasts_dir(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)."""
|
||||
|
||||
@@ -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(14400, 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)."""
|
||||
@@ -629,6 +640,11 @@ class InferenceConfig(BaseConfig):
|
||||
if "enable_prompt_tokens_details" not in extra_fields:
|
||||
namespace.enable_prompt_tokens_details = True
|
||||
|
||||
# The orchestrator generates through /inference/v1/generate, a scale-out
|
||||
# endpoint that vLLM registers only with `--enable-scale-out`.
|
||||
if "enable_scale_out" not in extra_fields:
|
||||
namespace.enable_scale_out = True
|
||||
|
||||
# vLLM's DeepseekV2-family (and transformers-backend MoE) gates read
|
||||
# `moe_router_dtype` off the HF config to pick the router logits dtype.
|
||||
if self.enable_fp32_router_logits:
|
||||
@@ -636,6 +652,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 +666,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
|
||||
|
||||
@@ -3,7 +3,7 @@ from pathlib import Path
|
||||
from typing import Annotated, Any, Literal, TypeAlias
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
from pydantic import Field, SerializeAsAny, ValidationError, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
|
||||
from prime_rl.configs.algorithm import (
|
||||
@@ -166,6 +166,9 @@ class EnvConfig(BaseConfig):
|
||||
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."""
|
||||
|
||||
select: vf.SelectConfig = vf.SelectConfig()
|
||||
"""Which of the taskset's tasks this source uses: ``include``/``exclude`` by ``idx``, ``ids``, ``keys`` or ``names``, then ``shuffle``, ``skip`` and ``limit``, applied in that order."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _resolve_env(cls, data):
|
||||
@@ -191,6 +194,51 @@ class EnvConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
def merge_group_defaults(data: Any) -> Any:
|
||||
"""Shared ``mode="before"`` body for source groups: layer the group's ``env`` and
|
||||
``select`` blocks under those of each raw source. A source's own values win; a
|
||||
source's ``include`` or ``exclude`` replaces the group's whole block."""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
sources = data.get("source") or []
|
||||
if data.get("env") is not None:
|
||||
try:
|
||||
shared = vf.SharedEnvConfig.model_validate(data["env"])
|
||||
except ValidationError:
|
||||
shared = None # the ``env`` field reports the errors once, not once per source
|
||||
if shared is not None:
|
||||
sources = [
|
||||
{**source, "env": vf.merge_env_defaults(shared, source.get("env"))}
|
||||
if isinstance(source, dict)
|
||||
else source
|
||||
for source in sources
|
||||
]
|
||||
if data.get("select") is not None:
|
||||
group = select_fields(data["select"], vf.SelectCLIConfig)
|
||||
if group is not None:
|
||||
sources = [
|
||||
{**source, "select": group | own}
|
||||
if isinstance(source, dict)
|
||||
and (own := select_fields(source.get("select"), vf.SelectConfig)) is not None
|
||||
else source
|
||||
for source in sources
|
||||
]
|
||||
if sources:
|
||||
data["source"] = sources
|
||||
return data
|
||||
|
||||
|
||||
def select_fields(raw: Any, select_type: type[vf.SelectConfig]) -> dict | None:
|
||||
"""The fields a raw ``select`` block sets, under their canonical names; None when
|
||||
the block is invalid, which leaves it to report its own errors."""
|
||||
if raw is None:
|
||||
return {}
|
||||
try:
|
||||
return select_type.model_validate(raw).model_dump(exclude_unset=True)
|
||||
except ValidationError:
|
||||
return None
|
||||
|
||||
|
||||
class StandardSamplerConfig(BaseConfig):
|
||||
type: Literal["standard"] = "standard"
|
||||
|
||||
@@ -287,9 +335,6 @@ class EvalSourceConfig(EnvConfig):
|
||||
sampling: EvalSamplingConfig = EvalSamplingConfig()
|
||||
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
|
||||
|
||||
num_examples: int = -1
|
||||
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
|
||||
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``group_size=8`` enables pass@1 through pass@8)."""
|
||||
|
||||
@@ -305,9 +350,22 @@ class TrainConfig(BaseConfig):
|
||||
source: list[TrainSourceConfig] = Field(default_factory=list)
|
||||
"""Training sources."""
|
||||
|
||||
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
|
||||
"""Env knobs that every training source inherits: the fields every env and taskset
|
||||
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
|
||||
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
"""Shared training sampling configuration."""
|
||||
|
||||
select: vf.SelectConfig = vf.SelectConfig()
|
||||
"""Task selection that every training source inherits. Each field a source sets on
|
||||
its own ``select`` wins over this one."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def resolve_group_defaults(cls, data):
|
||||
return merge_group_defaults(data)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
|
||||
@@ -338,19 +396,30 @@ class EvalSourcesConfig(BaseConfig):
|
||||
source: list[EvalSourceConfig] = Field(default_factory=list)
|
||||
"""Evaluation sources."""
|
||||
|
||||
env: vf.SharedEnvConfig = vf.SharedEnvConfig()
|
||||
"""Env knobs that every eval source inherits: the fields every env and taskset
|
||||
has, such as ``retries`` and ``timeout``. A source's own ``env`` values win."""
|
||||
|
||||
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
|
||||
"""Shared eval sampling configuration; can differ from training sampling."""
|
||||
|
||||
num_examples: int = -1
|
||||
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
|
||||
select: vf.SelectConfig = vf.SelectConfig()
|
||||
"""Task selection that every eval source inherits, e.g. ``limit = 128`` to evaluate
|
||||
128 tasks of each taskset. Each field a source sets on its own ``select`` wins over
|
||||
this one."""
|
||||
|
||||
group_size: int = Field(1, ge=1)
|
||||
"""Default rollouts per example. Can be overridden per env."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def resolve_group_defaults(cls, data):
|
||||
return merge_group_defaults(data)
|
||||
|
||||
@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)."""
|
||||
"""Resolve per-env overrides: inherit group-level sampling 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:
|
||||
@@ -358,8 +427,6 @@ class EvalSourcesConfig(BaseConfig):
|
||||
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
|
||||
@@ -459,9 +526,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"
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -10,7 +10,7 @@ from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
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.monitors import TrainMonitorsConfig
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
HeartbeatConfig,
|
||||
@@ -91,6 +91,9 @@ class SFTDataConfig(BaseDataConfig):
|
||||
name: str = "PrimeIntellect/Reverse-Text-SFT"
|
||||
"""HF dataset name or path."""
|
||||
|
||||
revision: str | None = None
|
||||
"""HF dataset revision to load. Ignored for a local path."""
|
||||
|
||||
subsets: list[str] | None = None
|
||||
"""Subsets to load from the HF dataset."""
|
||||
|
||||
@@ -226,8 +229,8 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
log: TrainerLogConfig = TrainerLogConfig()
|
||||
|
||||
monitors: MonitorsConfig = MonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
|
||||
monitors: TrainMonitorsConfig = TrainMonitorsConfig()
|
||||
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
|
||||
|
||||
run: RunConfig = Field(default_factory=RunConfig)
|
||||
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
|
||||
@@ -246,7 +249,8 @@ class SFTConfig(BaseConfig):
|
||||
@model_validator(mode="after")
|
||||
def auto_setup_run_identity(self):
|
||||
"""Auto-generate the run name (``<dataset>--<model>--<short-id>``) when unset and
|
||||
default the run directory and W&B run name to it when not set explicitly."""
|
||||
default the run directory, W&B run name and platform run name to it when not
|
||||
set explicitly."""
|
||||
if self.run.name is None:
|
||||
dataset = str(getattr(self.data, "name", "")).split("/")[-1]
|
||||
model = self.model.name.split("/")[-1]
|
||||
@@ -256,6 +260,8 @@ class SFTConfig(BaseConfig):
|
||||
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
|
||||
|
||||
matmul_precision: Literal["highest", "high", "medium"] = "high"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -85,6 +85,9 @@ class CompileConfig(BaseConfig):
|
||||
fullgraph: bool = False
|
||||
"""Compile transformer blocks with ``fullgraph=True``."""
|
||||
|
||||
mode: Literal["reduce-overhead", "max-autotune", "max-autotune-no-cudagraphs", "lite"] | None = None
|
||||
"""``torch.compile`` mode. ``reduce-overhead`` records CUDA graphs to cut kernel launch overhead; ``max-autotune`` modes trade longer compile times for tuned kernels (``max-autotune`` also records CUDA graphs, ``max-autotune-no-cudagraphs`` does not). CUDA-graphed layers re-record on new input shapes. ``None`` uses PyTorch's default mode."""
|
||||
|
||||
|
||||
class FusionsConfig(BaseConfig):
|
||||
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
|
||||
@@ -342,7 +345,7 @@ class ModelConfig(BaseModelConfig):
|
||||
"""Debugging knobs for the model and distributed training."""
|
||||
|
||||
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
|
||||
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
|
||||
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. In SFT the fused head computes the summed cross-entropy and its gradients chunk by chunk, holding one chunk's full-vocab logits at a time."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def trust_remote_code_only_with_hf(self):
|
||||
@@ -568,13 +571,16 @@ 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."""
|
||||
|
||||
max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False)
|
||||
"""Cap the importance weight of accepted tokens while preserving its policy gradient."""
|
||||
|
||||
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."""
|
||||
|
||||
|
||||
@@ -597,6 +603,41 @@ class IcePopLossConfig(BaseConfig):
|
||||
return self
|
||||
|
||||
|
||||
class PPOLossConfig(BaseConfig):
|
||||
type: Literal["ppo"] = "ppo"
|
||||
|
||||
ratio_low: float = Field(0.8, gt=0, le=1, allow_inf_nan=False)
|
||||
"""Lower ratio bound for the clipped surrogate."""
|
||||
|
||||
ratio_high: float = Field(1.2, ge=1, allow_inf_nan=False)
|
||||
"""Upper ratio bound for the clipped surrogate."""
|
||||
|
||||
max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False)
|
||||
"""Cap the unbounded side of the surrogate while preserving its gradient."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_max_importance_ratio(self):
|
||||
if self.max_importance_ratio < self.ratio_high:
|
||||
raise ValueError("max_importance_ratio must be at least ratio_high")
|
||||
return self
|
||||
|
||||
|
||||
class CISPOLossConfig(BaseConfig):
|
||||
type: Literal["cispo"] = "cispo"
|
||||
|
||||
ratio_low: float = Field(0.0, ge=0, le=1, allow_inf_nan=False)
|
||||
"""Lower bound for the detached importance weight; zero disables lower clipping."""
|
||||
|
||||
ratio_high: float = Field(5.0, ge=1, allow_inf_nan=False)
|
||||
"""Upper bound for the detached importance weight."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
|
||||
class CustomLossConfig(BaseConfig):
|
||||
type: Literal["custom"] = "custom"
|
||||
|
||||
@@ -607,7 +648,9 @@ class CustomLossConfig(BaseConfig):
|
||||
"""Kwargs forwarded to the loss function."""
|
||||
|
||||
|
||||
LossConfig: TypeAlias = Annotated[IPOLossConfig | IcePopLossConfig | CustomLossConfig, Field(discriminator="type")]
|
||||
LossConfig: TypeAlias = Annotated[
|
||||
IPOLossConfig | IcePopLossConfig | PPOLossConfig | CISPOLossConfig | CustomLossConfig, Field(discriminator="type")
|
||||
]
|
||||
|
||||
|
||||
class FakeDataLoaderConfig(BaseConfig):
|
||||
@@ -645,9 +688,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"
|
||||
|
||||
@@ -107,7 +107,8 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# [monitors.file] leaf. (Bare empty ``[monitors.file]`` block enablement is at the end.)
|
||||
propagate("monitors.file.path", "trainer.monitors.file.path", "orchestrator.monitors.file.path")
|
||||
|
||||
# [monitors.prime] leaf → orchestrator only (the trainer has no platform integration).
|
||||
# [monitors.prime] leaf → orchestrator only (the RL trainer has no platform
|
||||
# integration; the SFT trainer does, but it parses SFTConfig directly).
|
||||
propagate("monitors.prime.name", "orchestrator.monitors.prime.name")
|
||||
|
||||
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
|
||||
|
||||
+27
-18
@@ -16,8 +16,8 @@ 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>=0.8.0",
|
||||
"prime-runs[train]>=0.1.3",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
"tenacity>=8.2.0",
|
||||
@@ -29,7 +29,7 @@ dependencies = [
|
||||
"rich>=14.0.0",
|
||||
"setproctitle>=1.3.0",
|
||||
"uvloop>=0.21.0",
|
||||
"verifiers[harbor]>=0.3.1",
|
||||
"verifiers[harbor]>=0.3.2.dev152",
|
||||
"renderers[multimodal]>=0.1.12.dev2",
|
||||
"pybase64>=1.4.2",
|
||||
"orjson>=3.10",
|
||||
@@ -56,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.30.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'",
|
||||
@@ -146,9 +146,9 @@ 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.30.0 requires this exact CUTLASS DSL version and quack-kernels 0.6.5.
|
||||
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
|
||||
"nvidia-cutlass-dsl==4.6.2",
|
||||
"nvidia-cutlass-dsl==4.7.1",
|
||||
"transformers==5.6.2",
|
||||
"torch>=2.13.0",
|
||||
"openenv-core",
|
||||
@@ -171,11 +171,14 @@ members = [
|
||||
"deps/verifiers/environments/wiki_search",
|
||||
"deps/verifiers/environments/wordle",
|
||||
]
|
||||
# tau2-synth and tau3-bench pin `tau2` forks/revs that conflict with the
|
||||
# canonical tau2-bench; a workspace shares one lock, so these can't coexist.
|
||||
# Tau tasksets require litellm<1.82.7, while Harbor requires litellm>=1.92.0.
|
||||
# Apex pins a verifiers git revision instead of the editable workspace member.
|
||||
# A workspace shares one lock, so these packages need separate environments.
|
||||
exclude = [
|
||||
"deps/prime-envs/environments/tool_use/tau2_bench",
|
||||
"deps/prime-envs/environments/tool_use/tau2_synth",
|
||||
"deps/prime-envs/environments/tool_use/tau3_bench",
|
||||
"deps/prime-envs/environments/tool_use/apex_agents",
|
||||
]
|
||||
|
||||
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
|
||||
@@ -214,18 +217,16 @@ requires-dist = ["nixl-cu13==0.10.1"]
|
||||
# so resolve that variant without installing both runtime packages.
|
||||
[[tool.uv.dependency-metadata]]
|
||||
name = "nvidia-cutlass-dsl"
|
||||
version = "4.6.2"
|
||||
version = "4.7.1"
|
||||
requires-dist = [
|
||||
"nvidia-cutlass-dsl-libs-base==4.6.2",
|
||||
"nvidia-cutlass-dsl-libs-cu13==4.6.2",
|
||||
"nvidia-cutlass-dsl-libs-base==4.7.1",
|
||||
"nvidia-cutlass-dsl-libs-cu13==4.7.1",
|
||||
]
|
||||
|
||||
[tool.uv.exclude-newer-package]
|
||||
# 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
|
||||
@@ -266,15 +267,15 @@ torchao = [
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/torchao-0.18.0+git5f2baf9d5-cp310-abi3-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
|
||||
]
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "99e5f7e" }
|
||||
dion = { git = "https://github.com/samsja/dion.git", rev = "6f9242d" }
|
||||
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.30.0/vllm-0.30.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
|
||||
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.30.0/vllm-0.30.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'" },
|
||||
@@ -310,6 +311,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"]
|
||||
|
||||
|
||||
+104
-45
@@ -5,67 +5,126 @@ set -e
|
||||
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
|
||||
|
||||
# Allow runtime override of the prime-rl source itself.
|
||||
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
|
||||
# PRIME_RL_REF can be a git tag, branch, or full commit hash. PRIME_RL_REPO
|
||||
# optionally points at a fork; defaults to the upstream repo.
|
||||
#
|
||||
# We clone into a per-ref dir under /tmp, seed the venv from the baked
|
||||
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
|
||||
# `uv sync --inexact` re-installs prime_rl from the override source.
|
||||
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
|
||||
# resolves the entrypoints from the override venv.
|
||||
# The ref is fetched shallowly under /tmp and synced INTO the baked
|
||||
# /app/.venv: uv re-points the first-party editables (prime_rl, verifiers,
|
||||
# renderers, ...) at the checkout and reinstalls only third-party pins
|
||||
# that differ from the image's lockfile, so the heavy prebuilt wheels
|
||||
# (flash-attn, deep-ep, mamba-ssm, ...) are never rebuilt. A container
|
||||
# starts from a fresh filesystem, so mutating /app/.venv in place is safe.
|
||||
# The pods of the prime-rl-fft chart run this with a sha pinned by the
|
||||
# dispatcher; the exported PRIME_RL_SOURCE_COMMIT records what ran.
|
||||
if [ -n "$PRIME_RL_REF" ]; then
|
||||
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
|
||||
# Slug + content hash for the cache dir name. Slug keeps the path
|
||||
# Slug + content hash for the checkout dir name. Slug keeps the path
|
||||
# human-readable; the hash (over repo + ref) prevents collisions
|
||||
# between distinct refs that slugify the same way (e.g. `feat/foo`
|
||||
# vs `feat-foo`) and between the same ref on different forks.
|
||||
REF_SLUG="${PRIME_RL_REF//\//-}"
|
||||
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
|
||||
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
|
||||
# Rewrite ssh://git@github.com URLs to https so submodules listed
|
||||
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
|
||||
# can be cloned from the pod without ssh keys.
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
if [ ! -d "$DEST/.git" ]; then
|
||||
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
|
||||
rm -rf "$DEST"
|
||||
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
|
||||
# Rewrite git@github.com URLs to https so submodules listed with SSH
|
||||
# URLs (deps/verifiers, deps/renderers, deps/prime-envs) clone from the
|
||||
# pod without ssh keys. Via GIT_CONFIG_* rather than `git config
|
||||
# --global`: the pod's HOME may not be writable by its uid.
|
||||
export GIT_CONFIG_COUNT=1
|
||||
export GIT_CONFIG_KEY_0="url.https://github.com/.insteadOf"
|
||||
export GIT_CONFIG_VALUE_0="git@github.com:"
|
||||
rm -rf "$DEST"
|
||||
git init --quiet "$DEST"
|
||||
git -C "$DEST" remote add origin "$PRIME_RL_REPO"
|
||||
# Depth-1 fetch of the ref itself: GitHub serves branches, tags and
|
||||
# full commit shas alike (abbreviated shas are not fetchable), and
|
||||
# prime-rl's history (~700 MB of .git) is not needed to run it.
|
||||
echo "[prime-rl] fetching ${PRIME_RL_REF} from ${PRIME_RL_REPO}"
|
||||
git -C "$DEST" fetch --quiet --depth 1 origin "$PRIME_RL_REF"
|
||||
git -C "$DEST" checkout --quiet --force --detach FETCH_HEAD
|
||||
# Same public submodules the image build inits (build_image.yaml);
|
||||
# a pinned commit that isn't the submodule's branch tip is fetched by
|
||||
# sha, which GitHub allows.
|
||||
git -C "$DEST" submodule sync --quiet --recursive
|
||||
git -C "$DEST" submodule update --quiet --init --recursive --depth 1 -- \
|
||||
deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
|
||||
PRIME_RL_SOURCE_COMMIT=$(git -C "$DEST" rev-parse HEAD)
|
||||
export PRIME_RL_SOURCE_COMMIT
|
||||
echo "[prime-rl] source overlay at ${PRIME_RL_SOURCE_COMMIT}"
|
||||
|
||||
# Give the verifiers/renderers editables the same versions the image
|
||||
# build does (Dockerfile.cuda): resolve them with the repo's script
|
||||
# (git describe, else the highest `>=` floor any pyproject declares),
|
||||
# then bake them into hatch-vcs's fallback-version and drop the
|
||||
# submodules' git metadata so the fallback is what gets used. The
|
||||
# shallow clones carry no tags, so hatch-vcs would otherwise stamp
|
||||
# them 0.0.1.dev1 and every `verifiers>=…` floor in the tree would be
|
||||
# unmet.
|
||||
if [ -f "$DEST/scripts/docker-editable-pretend-versions.sh" ]; then
|
||||
eval "$(bash "$DEST/scripts/docker-editable-pretend-versions.sh" --shell "$DEST")"
|
||||
rm -f "$DEST/deps/verifiers/.git" "$DEST/deps/renderers/.git"
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" "$DEST/deps/verifiers/pyproject.toml"
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" "$DEST/deps/renderers/pyproject.toml"
|
||||
fi
|
||||
# Always fetch + checkout so mutable refs (branches/tags) pick up new
|
||||
# commits between pod restarts. No-op for immutable SHAs.
|
||||
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
|
||||
git -C "$DEST" fetch --quiet --tags --force origin
|
||||
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
|
||||
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
|
||||
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
|
||||
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
|
||||
# Refresh submodules to whatever the parent commit pins. `sync`
|
||||
# picks up URL changes in .gitmodules between checkouts on cache
|
||||
# hit; `update --init --recursive` applies the pinned SHAs.
|
||||
git -C "$DEST" submodule sync --recursive
|
||||
git -C "$DEST" submodule update --init --recursive
|
||||
if [ ! -d "$DEST/.venv" ]; then
|
||||
# Seed from the baked venv so the heavy wheels (flash-attn,
|
||||
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
|
||||
# hardlinks): a subsequent `uv sync` writes into this tree, and
|
||||
# hardlinks would leak those writes back into /app/.venv when
|
||||
# /tmp and /app share a filesystem.
|
||||
cp -a /app/.venv "$DEST/.venv"
|
||||
fi
|
||||
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
|
||||
# --inexact keeps the seeded venv's pre-built wheels (flash-attn-3,
|
||||
# deep-ep, mamba-ssm) in place; uv only rebuilds them if the override's
|
||||
# lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages --all-extras --group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
|
||||
# Wheels the in-place sync cannot rebuild: a lockfile that pins any of
|
||||
# these differently from the image needs a real image build. Fail here
|
||||
# rather than minutes later inside a half-installed torch. Stdlib only;
|
||||
# --project /app pins the interpreter to the baked venv whatever the cwd.
|
||||
uv run --no-sync --project /app python - "$DEST/uv.lock" /app/uv.lock <<'HEAVY_PINS_PY'
|
||||
import sys
|
||||
import tomllib
|
||||
|
||||
HEAVY = {
|
||||
"torch", "torchvision", "torchaudio", "triton", "vllm", "vllm-router",
|
||||
"flash-attn", "flash-attn-3", "flashinfer-python", "tilelang",
|
||||
"deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels",
|
||||
}
|
||||
|
||||
|
||||
def pins(path):
|
||||
with open(path, "rb") as f:
|
||||
lock = tomllib.load(f)
|
||||
out = {}
|
||||
for pkg in lock.get("package", []):
|
||||
if pkg.get("name") in HEAVY:
|
||||
source = repr(sorted((pkg.get("source") or {}).items()))
|
||||
out.setdefault(pkg["name"], set()).add((pkg.get("version"), source))
|
||||
return out
|
||||
|
||||
|
||||
ref_pins, image_pins = pins(sys.argv[1]), pins(sys.argv[2])
|
||||
drift = sorted(name for name in HEAVY if ref_pins.get(name) != image_pins.get(name))
|
||||
if drift:
|
||||
print(
|
||||
f"[prime-rl] {sys.argv[1]} pins {', '.join(drift)} differently from the image; "
|
||||
"the runtime source overlay cannot rebuild these. Build an image for this ref "
|
||||
"(build_image.yaml) or run it on an image whose lockfile matches.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
HEAVY_PINS_PY
|
||||
|
||||
# Sync the checkout into the baked venv. Same extras as Dockerfile.cuda
|
||||
# so an unchanged lockfile is a no-op for third-party packages (keep
|
||||
# the two lists in sync). --inexact leaves packages the checkout
|
||||
# doesn't declare in place instead of uninstalling them.
|
||||
export UV_PROJECT_ENVIRONMENT=/app/.venv
|
||||
export VIRTUAL_ENV=/app/.venv
|
||||
echo "[prime-rl] syncing ${DEST} into /app/.venv"
|
||||
( cd "$DEST" && uv sync --inexact --locked --no-dev --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 )
|
||||
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
|
||||
# project from the cwd; the venv itself stays /app/.venv via
|
||||
# UV_PROJECT_ENVIRONMENT above.
|
||||
cd "$DEST"
|
||||
fi
|
||||
|
||||
# Allow runtime override of the verifiers package version.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
|
||||
# PRIME_RL_REF swap so when both are set the install lands in the override
|
||||
# venv (uv pip install targets $VIRTUAL_ENV when exported).
|
||||
# PRIME_RL_REF overlay so when both are set verifiers is installed last
|
||||
# (uv pip install targets $VIRTUAL_ENV, which is /app/.venv either way).
|
||||
if [ -n "$VERIFIERS_VERSION" ]; then
|
||||
echo "Installing verifiers version: $VERIFIERS_VERSION"
|
||||
uv pip install --reinstall-package verifiers \
|
||||
|
||||
@@ -134,9 +134,6 @@ main() {
|
||||
source $HOME/.local/bin/env
|
||||
fi
|
||||
|
||||
log_info "Installing prime..."
|
||||
uv tool install prime
|
||||
|
||||
log_info "Syncing virtual environment..."
|
||||
uv sync --all-extras
|
||||
|
||||
|
||||
@@ -82,6 +82,10 @@ else
|
||||
fi
|
||||
cd "$NIXL_SRC"
|
||||
git checkout "$NIXL_VERSION"
|
||||
# Name the wheel nixl-cu13 (pyproject says nixl-cu12): the `nixl` shim imports
|
||||
# nixl_cu13 first, so a nixl_cu12 build would sit unused next to the PyPI wheel.
|
||||
git checkout -- pyproject.toml
|
||||
uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml
|
||||
|
||||
export PKG_CONFIG_PATH="$UCX_INSTALL/lib/pkgconfig"
|
||||
export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
@@ -90,7 +94,13 @@ export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:
|
||||
WHEEL_DIR="$PROJECT_DIR/deps"
|
||||
mkdir -p "$WHEEL_DIR"
|
||||
uv pip install pip 2>/dev/null
|
||||
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR"
|
||||
# NIXL's [build-system] requires are unpinned; meson-python 0.22.0 stopped
|
||||
# keeping Meson's build RPATH in wheel libraries, which drops the link to the
|
||||
# UCX built above. Constrain the backend to the version these wheels were
|
||||
# validated with (same pin as Dockerfile.cuda).
|
||||
printf 'meson-python==0.21.1\n' > "$WORKSPACE/nixl-build-constraints.txt"
|
||||
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR" \
|
||||
--build-constraint "$WORKSPACE/nixl-build-constraints.txt"
|
||||
|
||||
WHEEL=$(ls "$WHEEL_DIR"/nixl*.whl | head -1)
|
||||
WHEEL=$(ls "$WHEEL_DIR"/nixl_cu13-"$NIXL_VERSION"-*.whl | head -1)
|
||||
echo "=== NIXL wheel built at: $WHEEL ==="
|
||||
|
||||
@@ -65,7 +65,7 @@ env.agent.runtime.type = "subprocess"
|
||||
|
||||
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). 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).
|
||||
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]`, `[select]`, `group_size` at the top level, plus the single-source shorthands `uv run eval <taskset-id> --env.<field> <value> -n N -s -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.
|
||||
|
||||
|
||||
@@ -9,10 +9,11 @@ description: Find, start, use, and stop the local run dashboard for metrics, con
|
||||
|
||||
What is not obvious from the UI:
|
||||
|
||||
- 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 metrics 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).
|
||||
- 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.
|
||||
|
||||
|
||||
+38
-4
@@ -23,18 +23,20 @@ uv run eval @ eval.toml --monitors.prime # stream eac
|
||||
|
||||
- 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.
|
||||
- Shorthands (single-source runs): `<taskset-id>`, `--env.<field> <value>`, `-n` `select.limit`, `-s` `select.shuffle`, `-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):
|
||||
Minimal multi-source TOML (the eval block is flattened to the top level; per-source `select`, `group_size`, `sampling` override the top level):
|
||||
|
||||
```toml
|
||||
model = "Qwen/Qwen3-4B"
|
||||
num_examples = 32
|
||||
group_size = 4
|
||||
|
||||
[select]
|
||||
limit = 32
|
||||
|
||||
[client]
|
||||
base_url = "http://localhost:8000/v1"
|
||||
|
||||
@@ -48,6 +50,38 @@ env.agent.harness.id = "null"
|
||||
env.agent.runtime.type = "subprocess"
|
||||
```
|
||||
|
||||
## Select tasks
|
||||
|
||||
`select` picks which tasks of a source's taskset run. The steps apply in a fixed order: `include` and `exclude` (by `idx` position, `ids`, `keys` or `names`), then `shuffle` (under `seed`, default 0), `skip`, `limit`. Set it once for every source of a group (`[select]` in an eval TOML, `[orchestrator.eval.select]`, `[orchestrator.train.select]`), or per source (`select.limit = 50` in a `[[source]]`); a source's own fields win.
|
||||
|
||||
```bash
|
||||
uv run eval gsm8k -n 50 # the first 50 tasks
|
||||
uv run eval gsm8k -n 50 -s # a random subset of 50 (same tasks every run)
|
||||
uv run eval gsm8k -n 50 -s --select.seed 1 # another random subset
|
||||
uv run eval gsm8k --select.include.idx 0:10,42 # tasks by position (ints and Python slices)
|
||||
uv run eval terminal-bench-2 --select.include.names '["fix-git"]' # tasks by name; `ids` and `keys` work the same
|
||||
uv run eval terminal-bench-2 --select.exclude.keys '["<task.key>"]' # drop known-broken tasks (keys are on every trace)
|
||||
```
|
||||
|
||||
Disjoint train/test splits from one taskset:
|
||||
|
||||
```toml
|
||||
# contiguous: eval on the first 100 tasks, train on the rest
|
||||
[[orchestrator.eval.source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
select.include.idx = [":100"]
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
env.taskset.id = "gsm8k"
|
||||
select.exclude.idx = [":100"]
|
||||
|
||||
# random: the same shuffle on both sides; eval takes 100, train skips them
|
||||
# eval: select.shuffle = true, select.limit = 100
|
||||
# train: select.shuffle = true, select.skip = 100
|
||||
```
|
||||
|
||||
The shuffle comes before `skip` and `limit`, so a larger `limit` extends the same selection: resuming a `-n 50 -s` run with `-n 100` keeps the 50 landed tasks and adds 50 more.
|
||||
|
||||
## 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).
|
||||
@@ -72,4 +106,4 @@ The progress line in `eval.log` counts live rollouts by phase (`- boot 1 · runn
|
||||
|
||||
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.
|
||||
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. Any config may be overridden on resume (`select`/`group_size` change what is owed); keep the model, sampling and env config the same to keep the landed episodes comparable. Env servers are children of the eval process and exit with it.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -37,6 +37,7 @@ 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
|
||||
@@ -47,6 +48,7 @@ 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,
|
||||
@@ -270,13 +272,14 @@ def eval_env(config: dict) -> str | None:
|
||||
|
||||
|
||||
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:
|
||||
"""What one ``[[source]]`` will produce, from its config alone: without a
|
||||
``select.limit`` the count is unknown up front unless the source names its tasks."""
|
||||
taskset = (source.get("env") or {}).get("taskset") or {}
|
||||
limit = (source.get("select") or {}).get("limit")
|
||||
tasks = taskset.get("tasks")
|
||||
if limit is None and not tasks:
|
||||
return None
|
||||
return (count if count >= 0 else len(tasks)) * (source.get("group_size") or 1)
|
||||
return (limit if limit is not None else len(tasks)) * (source.get("group_size") or 1)
|
||||
|
||||
|
||||
def eval_totals(config: dict) -> dict[str, int | None]:
|
||||
@@ -292,7 +295,7 @@ def eval_total_episodes(config: dict) -> int | None:
|
||||
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
|
||||
return ((config.get("select") or {}).get("limit") or 0) * (config.get("num_rollouts") or 0) or None
|
||||
|
||||
|
||||
def run_meta(run_dir: Path) -> dict:
|
||||
@@ -550,7 +553,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."""
|
||||
|
||||
@@ -566,7 +569,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
|
||||
@@ -819,6 +824,8 @@ def message_text(message: dict) -> str:
|
||||
def timeline_status(trace: dict) -> str:
|
||||
if not trace.get("is_completed"):
|
||||
return "running"
|
||||
if trace.get("is_timeout"):
|
||||
return "timeout"
|
||||
if not trace.get("ok") and (trace.get("errors") or trace.get("stop_condition") == "error"):
|
||||
return "failed"
|
||||
return "completed"
|
||||
@@ -1532,7 +1539,7 @@ def row_filter(
|
||||
return False
|
||||
if episode is not None and row.get("id") != episode:
|
||||
return False
|
||||
if errors_only and not (row.get("num_errors") or not row.get("ok")):
|
||||
if errors_only and row.get("ok"):
|
||||
return False
|
||||
arrival = row.get("arrival") or 0
|
||||
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
|
||||
@@ -1818,6 +1825,7 @@ def episode_series(run: str, kind: str | None = None, etag: str | None = None, a
|
||||
"ok",
|
||||
"num_errors",
|
||||
"truncated",
|
||||
"timeout",
|
||||
"stop_condition",
|
||||
"duration",
|
||||
"reward",
|
||||
|
||||
@@ -26,13 +26,13 @@ const state = {
|
||||
runs: [],
|
||||
run: null,
|
||||
meta: null,
|
||||
tab: "metrics",
|
||||
tab: "overview",
|
||||
live: true,
|
||||
metrics: {
|
||||
loaded: false, offset: 0, byKey: new Map(),
|
||||
charts: [], renderedKeys: -1, timeKeys: new Set(), timeZero: null, maxStep: null,
|
||||
collapsedSections: new Set(prefs.collapsedSections ?? []),
|
||||
mode: prefs.metricsMode ?? "overview", search: prefs.metricsSearch ?? "",
|
||||
searches: { overview: prefs.overviewSearch ?? "", metrics: prefs.metricsSearch ?? "" },
|
||||
smooth: prefs.smooth ?? 1, paneMin: prefs.paneMin ?? 260, paneH: prefs.paneH ?? 150, includeErrors: prefs.includeErrors ?? false,
|
||||
allLayout: prefs.allLayout ?? "flat",
|
||||
paneOrder: prefs.paneOrder ?? {},
|
||||
@@ -177,16 +177,15 @@ async function toggleCompare(name, on) {
|
||||
renderMetricsBody();
|
||||
}
|
||||
|
||||
/* eval runs have one env and no steps: the step bar, kind/subset toggles, chart
|
||||
mode, and smoothing make no sense there */
|
||||
/* eval runs have one env and no steps: the step bar, kind/subset toggles and
|
||||
smoothing make no sense there, and the overview is the episode pane */
|
||||
function applyRunTypeControls() {
|
||||
const isEval = state.meta?.type === "eval";
|
||||
$("#metrics-mode").hidden = isEval;
|
||||
$("#metrics-filter-wrap").hidden = !isEval;
|
||||
$("#metrics-search").hidden = isEval;
|
||||
$("#metrics-collapse").hidden = isEval;
|
||||
$("#metrics-expand").hidden = isEval;
|
||||
$("#smooth-range").closest(".ctl").hidden = isEval;
|
||||
$("#overview-filter-wrap").hidden = !isEval;
|
||||
$("#overview-search").hidden = isEval;
|
||||
$("#overview-collapse").hidden = isEval;
|
||||
$("#overview-expand").hidden = isEval;
|
||||
$("#overview-smooth").closest(".ctl").hidden = isEval;
|
||||
$("#step-bar").hidden = isEval;
|
||||
// an eval run has no steps to switch between, so it is stream-only
|
||||
$("#trace-mode").hidden = isEval;
|
||||
@@ -332,7 +331,7 @@ function renderOverview() {
|
||||
["status", `<span class="badge st-${status}">${status}</span>`],
|
||||
["type", `<span class="val">${esc((meta.type ?? "n/a").toUpperCase())}</span>`],
|
||||
meta.type === "eval"
|
||||
? ["episodes", `<span class="val">${step != null ? step.toLocaleString() : "n/a"}</span>`]
|
||||
? ["episodes", `<span class="val">${state.metrics.evalCount.toLocaleString()}</span>`]
|
||||
: ["step", `<span class="val">${stepText}</span>`],
|
||||
["model", `<span class="val" title="${esc(meta.model ?? "")}">${esc(meta.model ?? "n/a")}</span>`],
|
||||
...(meta.type === "eval"
|
||||
@@ -372,9 +371,12 @@ async function activateTab(tab, force = false) {
|
||||
setActive("#tabs", "tab", tab);
|
||||
document.querySelectorAll("main > section").forEach((s) => (s.hidden = s.id !== `tab-${tab}`));
|
||||
updateHash();
|
||||
if (tab === "metrics") {
|
||||
if (isChartTab(tab)) {
|
||||
if (!state.metrics.loaded) await initMetrics();
|
||||
else if (state.live) await fetchMetrics();
|
||||
else {
|
||||
renderMetricsBody();
|
||||
if (state.live) await fetchMetrics();
|
||||
}
|
||||
}
|
||||
if (tab === "config" && !state.config.loaded) await initConfig();
|
||||
if (tab === "logs" && !state.logs.loaded) await initLogs();
|
||||
@@ -390,8 +392,38 @@ async function activateTab(tab, force = false) {
|
||||
|
||||
/* ---------------------------------------------------------------- metrics */
|
||||
|
||||
/* the overview and metrics tabs read one metric store and share one chart
|
||||
registry: the open tab owns the charts, so switching re-renders into its body.
|
||||
The overview is the curated view (for an eval run, the episode pane); metrics
|
||||
is every key in the file, sectioned by family */
|
||||
const CHART_VIEWS = {
|
||||
overview: { body: "#overview-body", status: "#overview-status", search: "#overview-search", mode: "overview" },
|
||||
metrics: { body: "#metrics-body", status: "#metrics-status", search: "#metrics-search", mode: "all" },
|
||||
};
|
||||
|
||||
function isChartTab(tab = state.tab) {
|
||||
return tab in CHART_VIEWS;
|
||||
}
|
||||
|
||||
function chartBodies() {
|
||||
return Object.values(CHART_VIEWS).map((view) => $(view.body));
|
||||
}
|
||||
|
||||
function chartView() {
|
||||
return CHART_VIEWS[state.tab] ?? CHART_VIEWS.overview;
|
||||
}
|
||||
|
||||
function metricsMode() {
|
||||
return chartView().mode;
|
||||
}
|
||||
|
||||
/* the eval overview is built from the episode series, not the metric rows */
|
||||
function rowsChartHere() {
|
||||
return isChartTab() && !(state.tab === "overview" && state.meta?.type === "eval");
|
||||
}
|
||||
|
||||
const COMMON_METRICS = ["effective/num_turns/mean", "effective/num_total_tokens/mean", "effective/num_branches/mean"];
|
||||
const COMMON_REGEXES = ["effective/[^/]+/is_truncated/mean", "all/[^/]+/has_error/mean"];
|
||||
const COMMON_REGEXES = ["effective/[^/]+/is_truncated/mean", "all/[^/]+/is_timeout/mean", "all/[^/]+/has_error/mean"];
|
||||
const STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"];
|
||||
const PERFORMANCE_METRICS = ["perf/mfu", "time/step", "time/wait_for_batch", "time/wait_for_policy"];
|
||||
const SFT_TRAIN_METRICS = ["loss/mean", "loss/perplexity", "val/loss", "val/perplexity", "progress/epoch"];
|
||||
@@ -462,46 +494,52 @@ function ingestInto(store, rows, meta) {
|
||||
first charts paint immediately and a progress readout ticks up while the rest
|
||||
loads, with the main thread yielding between chunks */
|
||||
async function fetchMetrics() {
|
||||
if (state.meta?.type === "eval") return fetchEvalSeries();
|
||||
const m = state.metrics;
|
||||
if (m.fetching) return 0;
|
||||
m.fetching = true;
|
||||
let total = 0;
|
||||
let showedProgress = false;
|
||||
try {
|
||||
for (let first = true; ; first = false) {
|
||||
const requestedOffset = m.offset;
|
||||
const [data, compared] = await Promise.all([
|
||||
api(`/api/runs/${encodeURIComponent(state.run)}/metrics?offset=${m.offset}`),
|
||||
first ? fetchCompares() : false,
|
||||
]);
|
||||
if (state.metrics !== m) return total; // the run changed mid-load
|
||||
m.offset = data.offset;
|
||||
total += data.rows.length;
|
||||
let touched = null;
|
||||
if (data.rows.length) {
|
||||
touched = ingestInto(m, data.rows, state.meta);
|
||||
renderOverview();
|
||||
}
|
||||
if (data.rows.length || compared) {
|
||||
if (m.byKey.size !== m.renderedKeys) renderMetricsBody();
|
||||
else updateCharts(compared ? null : touched); // compares may touch any panel
|
||||
}
|
||||
// A writer can leave one incomplete JSONL record at EOF. Wait for the
|
||||
// next poll instead of repeatedly requesting the same partial record.
|
||||
if (data.offset >= (data.size ?? data.offset) || data.offset === requestedOffset) break;
|
||||
showedProgress = true;
|
||||
$("#metrics-status").textContent = `loading metrics · ${Math.round((data.offset / data.size) * 100)}%`;
|
||||
}
|
||||
if (showedProgress && m.mode === "overview") $("#metrics-status").textContent = "";
|
||||
if (state.meta?.type === "eval") await fetchEvalSeries();
|
||||
if (state.metrics !== m) return 0;
|
||||
return await fetchMetricRows(m);
|
||||
} finally {
|
||||
m.fetching = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchMetricRows(m) {
|
||||
let total = 0;
|
||||
let showedProgress = false;
|
||||
for (let first = true; ; first = false) {
|
||||
const requestedOffset = m.offset;
|
||||
const [data, compared] = await Promise.all([
|
||||
api(`/api/runs/${encodeURIComponent(state.run)}/metrics?offset=${m.offset}`),
|
||||
first ? fetchCompares() : false,
|
||||
]);
|
||||
if (state.metrics !== m) return total; // the run changed mid-load
|
||||
m.offset = data.offset;
|
||||
total += data.rows.length;
|
||||
let touched = null;
|
||||
if (data.rows.length) {
|
||||
touched = ingestInto(m, data.rows, state.meta);
|
||||
renderOverview();
|
||||
}
|
||||
if ((data.rows.length || compared) && rowsChartHere()) {
|
||||
if (m.byKey.size !== m.renderedKeys) renderMetricsBody();
|
||||
else updateCharts(compared ? null : touched); // compares may touch any panel
|
||||
}
|
||||
// A writer can leave one incomplete JSONL record at EOF. Wait for the
|
||||
// next poll instead of repeatedly requesting the same partial record.
|
||||
if (data.offset >= (data.size ?? data.offset) || data.offset === requestedOffset) break;
|
||||
if (!rowsChartHere()) continue;
|
||||
showedProgress = true;
|
||||
$(chartView().status).textContent = `loading metrics · ${Math.round((data.offset / data.size) * 100)}%`;
|
||||
}
|
||||
if (showedProgress && metricsMode() === "overview") $(chartView().status).textContent = "";
|
||||
return total;
|
||||
}
|
||||
|
||||
/* eval runs have no metrics.jsonl and no step axis — their metrics view is a
|
||||
grid of stat cards showing the running average over the episodes so far */
|
||||
/* an eval run's overview reads the episode series: the running distributions
|
||||
over the episodes so far */
|
||||
async function fetchEvalSeries() {
|
||||
const m = state.metrics;
|
||||
const liveChanged = await loadLive({ render: state.tab === "traces" });
|
||||
@@ -515,7 +553,7 @@ async function fetchEvalSeries() {
|
||||
data = { unchanged: true };
|
||||
}
|
||||
if (data.unchanged) {
|
||||
if (liveChanged && m.loaded && state.tab === "metrics") renderMetricsBody();
|
||||
if (liveChanged && m.loaded && state.tab === "overview") renderMetricsBody();
|
||||
return 0;
|
||||
}
|
||||
m.evalEtag = data.etag;
|
||||
@@ -528,11 +566,10 @@ async function fetchEvalSeries() {
|
||||
m.evalSeries[key] = existing;
|
||||
}
|
||||
m.evalCount = data.count;
|
||||
m.maxStep = data.count; // the overview's episode count
|
||||
const costs = (m.evalSeries.cost || []).filter((v) => v != null); // merged, not just the increment
|
||||
m.evalCost = costs.length ? costs.reduce((a, b) => a + b, 0) : null;
|
||||
renderOverview();
|
||||
if (m.loaded) renderMetricsBody();
|
||||
if (m.loaded && state.tab === "overview") renderMetricsBody();
|
||||
return data.count;
|
||||
}
|
||||
|
||||
@@ -557,8 +594,8 @@ function evalEnv() {
|
||||
function renderEvalEnvs() {
|
||||
const envs = evalEnvs();
|
||||
const current = evalEnv();
|
||||
$("#metrics-env-row").hidden = !envs.length;
|
||||
$("#metrics-env").innerHTML = envs.map((env) => `<option value="${esc(env)}" ${env === current ? "selected" : ""}>${esc(env)}</option>`).join("");
|
||||
$("#overview-env-row").hidden = !envs.length;
|
||||
$("#overview-env").innerHTML = envs.map((env) => `<option value="${esc(env)}" ${env === current ? "selected" : ""}>${esc(env)}</option>`).join("");
|
||||
syncDressedSelects();
|
||||
}
|
||||
|
||||
@@ -591,11 +628,11 @@ function evalProgressHtml(env, idx, live) {
|
||||
cells =
|
||||
idx
|
||||
.map((i) => {
|
||||
const err = series.ok?.[i] === false;
|
||||
const mark = outcomeClass(series, i);
|
||||
const reward = series.reward?.[i];
|
||||
return (
|
||||
`<span class="ep-cell done${err ? " err" : ""}" data-line="${series.line?.[i]}" ` +
|
||||
`title="#${series.line?.[i]} · reward ${reward != null ? fmtReward(reward) : "n/a"}${err ? " · error" : ""}"></span>`
|
||||
`<span class="ep-cell done ${mark}" data-line="${series.line?.[i]}" ` +
|
||||
`title="#${series.line?.[i]} · reward ${reward != null ? fmtReward(reward) : "n/a"}${mark === "err" ? " · error" : mark === "timeout" ? " · timeout" : ""}"></span>`
|
||||
);
|
||||
})
|
||||
.join("") +
|
||||
@@ -616,7 +653,7 @@ function evalProgressHtml(env, idx, live) {
|
||||
`<span class="ep-cell"></span>`.repeat(Math.max(0, EP_CELL_CAP - doneCells - liveCells));
|
||||
}
|
||||
// the toolbar line reads like the traces tab's
|
||||
$("#metrics-status").textContent = [...(live.length ? [`${live.length} live`] : []), `${fmtCompact(done)} completed episode${done === 1 ? "" : "s"}`].join(" · ");
|
||||
$("#overview-status").textContent = [...(live.length ? [`${live.length} live`] : []), `${fmtCompact(done)} completed episode${done === 1 ? "" : "s"}`].join(" · ");
|
||||
return (
|
||||
`<div class="eval-progress"><div class="ep-head"><span class="name">${esc(env)}</span></div>` +
|
||||
`<div class="ep-row"><div class="ep-blocks">${cells || `<span class="ep-cell"></span>`}</div>` +
|
||||
@@ -708,7 +745,7 @@ function dotPlotSvg(entry, W, H) {
|
||||
const col = Math.floor(j / perCol), rowN = j % perCol;
|
||||
const cx = x0 + col * (2 * r + 1);
|
||||
const cy = top + plotH - r - rowN * (2 * r + 1);
|
||||
return `<circle data-i="${i}" class="${p.err ? "err" : ""}" cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${r}"></circle>`;
|
||||
return `<circle data-i="${i}" class="${markClass(p)}" cx="${cx.toFixed(1)}" cy="${cy.toFixed(1)}" r="${r}"></circle>`;
|
||||
})
|
||||
.join("");
|
||||
const n = counts.get(v);
|
||||
@@ -792,7 +829,7 @@ function swarmSvg(entry, W, H) {
|
||||
stacks.set(column, k + 1);
|
||||
const offset = Math.ceil(k / 2) * d * (k % 2 ? -1 : 1);
|
||||
const y = Math.max(r, Math.min(plotH - r, mid + offset));
|
||||
return `<circle data-i="${i}" class="${points[i].err ? "err" : ""}" cx="${px.toFixed(1)}" cy="${y.toFixed(1)}" r="${r}"></circle>`;
|
||||
return `<circle data-i="${i}" class="${markClass(points[i])}" cx="${px.toFixed(1)}" cy="${y.toFixed(1)}" r="${r}"></circle>`;
|
||||
});
|
||||
// the x axis: a baseline under the plot, round-valued ticks with grid lines
|
||||
const label = (v) => tickLabel(v, entry.fmt);
|
||||
@@ -821,7 +858,7 @@ function swarmSvg(entry, W, H) {
|
||||
|
||||
/* swarms are drawn to their host's pixel size, so they redraw with the panes */
|
||||
function drawSwarms() {
|
||||
for (const card of document.querySelectorAll("#metrics-body .swarm-card")) {
|
||||
for (const card of document.querySelectorAll("#overview-body .swarm-card")) {
|
||||
const entry = swarmRegistry.get(card.dataset.key);
|
||||
const host = card.querySelector(".swarm-host");
|
||||
if (!entry || !host?.clientWidth) continue;
|
||||
@@ -831,6 +868,16 @@ function drawSwarms() {
|
||||
|
||||
const SWARM_STAT_ROWS = ["min", "p10", "median", "p90", "max"];
|
||||
|
||||
/* an episode's outcome mark: a timeout reads yellow, an error red, a clean one unmarked */
|
||||
function outcomeClass(series, i) {
|
||||
if (series.timeout?.[i] === true) return "timeout";
|
||||
return series.ok?.[i] === false ? "err" : "";
|
||||
}
|
||||
|
||||
function markClass(point) {
|
||||
return point.timeout ? "timeout" : point.err ? "err" : "";
|
||||
}
|
||||
|
||||
function swarmTipHtml(entry, point) {
|
||||
const row = (k, v) => `<div class="tip-row"><span>${esc(k)}</span><span>${v}</span></div>`;
|
||||
if (point) {
|
||||
@@ -838,6 +885,7 @@ function swarmTipHtml(entry, point) {
|
||||
? [row("rollouts", point.n), row(entry.label, entry.fmt(point.v))]
|
||||
: [row(entry.label, entry.fmt(point.v)), ...(point.reward != null ? [row("reward", fmtReward(point.reward))] : [])];
|
||||
if (point.err) rows.push(row("errors", point.group ? "in a rollout" : "yes"));
|
||||
if (point.timeout) rows.push(row("timeout", point.group ? "in a rollout" : "yes"));
|
||||
rows.push(row("", point.group ? "click opens its first rollout" : "click opens the trace"));
|
||||
return `<div class="tip-head">${point.group ? `task ${esc(point.group.slice(0, 8))}` : `episode #${point.line}`}</div>${rows.join("")}`;
|
||||
}
|
||||
@@ -870,15 +918,16 @@ function evalScoreEntries(idx, filter) {
|
||||
const reward = series.reward?.[i] ?? (series.ok?.[i] === false ? 0 : null);
|
||||
if (reward == null) continue;
|
||||
const task = series.group?.[i] ?? String(i);
|
||||
if (!byTask.has(task)) byTask.set(task, { group: task, line: series.line?.[i], rewards: [], err: false });
|
||||
if (!byTask.has(task)) byTask.set(task, { group: task, line: series.line?.[i], rewards: [], err: false, timeout: false });
|
||||
const t = byTask.get(task);
|
||||
t.rewards.push(reward);
|
||||
if (series.ok?.[i] === false) t.err = true;
|
||||
if (series.timeout?.[i] === true) t.timeout = true;
|
||||
}
|
||||
const tasks = [...byTask.values()];
|
||||
if (!tasks.length) return entries;
|
||||
const k = Math.max(...tasks.map((t) => t.rewards.length));
|
||||
const taskPoint = (t, v) => ({ v, group: t.group, line: t.line, n: t.rewards.length, err: t.err });
|
||||
const taskPoint = (t, v) => ({ v, group: t.group, line: t.line, n: t.rewards.length, err: t.err, timeout: t.timeout });
|
||||
if (!filter || filter.test("avg@k"))
|
||||
entries.push(swarmEntry("avg@k", `avg@${k}`, tasks.map((t) => taskPoint(t, t.rewards.reduce((a, b) => a + b, 0) / t.rewards.length)), fmtReward));
|
||||
if ((!filter || filter.test("pass@k")) && tasks.every((t) => t.rewards.every((r) => r === 0 || r === 1))) {
|
||||
@@ -978,7 +1027,7 @@ function timingPaneHtml(idx) {
|
||||
if (total == null) return null;
|
||||
const parts = leaves.map((p) => ({ name: p.split("/").pop(), v: series[`timing/${p}`]?.[i] ?? 0 }));
|
||||
parts.push({ name: "other", v: Math.max(0, total - parts.reduce((a, p) => a + p.v, 0)) });
|
||||
return { i, line: series.line?.[i], err: series.ok?.[i] === false, total, parts };
|
||||
return { i, line: series.line?.[i], err: series.ok?.[i] === false, timeout: series.timeout?.[i] === true, total, parts };
|
||||
})
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => b.total - a.total);
|
||||
@@ -1000,7 +1049,7 @@ function tokensPaneHtml(idx) {
|
||||
.map((i) => {
|
||||
const input = series.input_tokens?.[i] ?? 0, output = series.output_tokens?.[i] ?? 0;
|
||||
if (!input && !output) return null;
|
||||
return { i, line: series.line?.[i], err: series.ok?.[i] === false, total: input + output, parts: [{ name: "input", v: input }, { name: "output", v: output }] };
|
||||
return { i, line: series.line?.[i], err: series.ok?.[i] === false, timeout: series.timeout?.[i] === true, total: input + output, parts: [{ name: "input", v: input }, { name: "output", v: output }] };
|
||||
})
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => b.total - a.total);
|
||||
@@ -1017,8 +1066,8 @@ function tokensPaneHtml(idx) {
|
||||
const TM_MAX_STRIPS = 40;
|
||||
|
||||
function drawTiming() {
|
||||
drawComposition(document.querySelector("#metrics-body .timing-pane"), timingModel, { kind: "timing", fmt: fmtDuration, time: true, color: phaseColor });
|
||||
drawComposition(document.querySelector("#metrics-body .tokens-pane"), tokensModel, { kind: "tokens", fmt: (v) => fmtCompact(Math.round(v)), time: false, color: (n) => TOKEN_COLORS[n] || "#3a3a3a" });
|
||||
drawComposition(document.querySelector("#overview-body .timing-pane"), timingModel, { kind: "timing", fmt: fmtDuration, time: true, color: phaseColor });
|
||||
drawComposition(document.querySelector("#overview-body .tokens-pane"), tokensModel, { kind: "tokens", fmt: (v) => fmtCompact(Math.round(v)), time: false, color: (n) => TOKEN_COLORS[n] || "#3a3a3a" });
|
||||
}
|
||||
|
||||
/* an icicle of the mean composition above one strip per episode; every segment
|
||||
@@ -1076,7 +1125,7 @@ function drawComposition(pane, model, { kind, fmt, time, color }) {
|
||||
const t = tip(
|
||||
`<div class="tip-head">episode #${r.line} · ${fmt(r.total)}</div>` +
|
||||
parts.map((p) => rowTip(p.name, `${fmt(p.v)} · ${Math.round((p.v / (r.total || 1)) * 100)}%`)).join("") +
|
||||
`${r.err ? rowTip("errors", "yes") : ""}${rowTip("", "click opens the trace")}`
|
||||
`${r.err ? rowTip("errors", "yes") : ""}${r.timeout ? rowTip("timeout", "yes") : ""}${rowTip("", "click opens the trace")}`
|
||||
);
|
||||
const segs = parts
|
||||
.map((p) => {
|
||||
@@ -1089,7 +1138,7 @@ function drawComposition(pane, model, { kind, fmt, time, color }) {
|
||||
.join("");
|
||||
return (
|
||||
`<rect class="tm-row-hit" data-tip="${t}" data-row="${n}" data-line="${r.line}" x="0" y="${y - GAP / 2}" width="${W}" height="${SH + GAP}"></rect>` +
|
||||
`<text class="hax tm-line${r.err ? " err" : ""}" data-row="${n}" x="${PAD_L - 6}" y="${y + SH - 1}" style="text-anchor:end">#${r.line}</text>${segs}`
|
||||
`<text class="hax tm-line ${markClass(r)}" data-row="${n}" x="${PAD_L - 6}" y="${y + SH - 1}" style="text-anchor:end">#${r.line}</text>${segs}`
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
@@ -1137,13 +1186,19 @@ function summaryTilesHtml(idx, all, scoreEntries) {
|
||||
const rows = entry.rows ?? SWARM_STAT_ROWS.map((k) => [k, entry.fmt(entry.stats[k])]);
|
||||
tile(entry.label, entry.headline, `<div class="tip-head">${esc(entry.label)} · ${fmtCompact(entry.stats.n)} tasks</div>${rows.map(([k, v]) => rowTip(k, v)).join("")}`, { cls: " score" });
|
||||
}
|
||||
// failure rates count every landed episode, the errors filter notwithstanding
|
||||
// failure rates count every landed episode, the errors filter notwithstanding;
|
||||
// the timeout rate reads yellow as soon as any episode timed out
|
||||
if (all.length) {
|
||||
const errored = all.filter((i) => series.ok?.[i] === false || (series.num_errors?.[i] ?? 0) > 0).length;
|
||||
const errored = all.filter((i) => series.ok?.[i] === false).length;
|
||||
const truncated = all.filter((i) => (series.truncated?.[i] ?? TRUNCATING_STOPS.has(series.stop_condition?.[i])) === true).length;
|
||||
for (const [label, n, what] of [["error rate", errored, "errored"], ["truncation rate", truncated, "truncated"]]) {
|
||||
const timedOut = all.filter((i) => series.timeout?.[i] === true).length;
|
||||
for (const [label, n, what, cls] of [
|
||||
["error rate", errored, "errored", rateClass],
|
||||
["truncation rate", truncated, "truncated", rateClass],
|
||||
["timeout rate", timedOut, "timed out", (rate) => (rate > 0 ? " rate-timeout" : "")],
|
||||
]) {
|
||||
const rate = n / all.length;
|
||||
tile(label, `${Math.round(rate * 100)}%`, `<div class="tip-head">${esc(label)}</div>${rowTip(what, `${n} of ${all.length} episodes`)}`, { cls: rateClass(rate) });
|
||||
tile(label, `${Math.round(rate * 100)}%`, `<div class="tip-head">${esc(label)}</div>${rowTip(what, `${n} of ${all.length} episodes`)}`, { cls: cls(rate) });
|
||||
}
|
||||
}
|
||||
const turns = distStats(idx.map((i) => series.turns?.[i]));
|
||||
@@ -1174,12 +1229,12 @@ function summaryTilesHtml(idx, all, scoreEntries) {
|
||||
function renderEvalPane(body) {
|
||||
const m = state.metrics;
|
||||
const series = m.evalSeries || {};
|
||||
const filter = makeFilter(m.search.trim());
|
||||
const filter = makeFilter(m.searches.overview.trim());
|
||||
renderEvalEnvs();
|
||||
const env = evalEnv();
|
||||
$("#metrics-status").textContent = "";
|
||||
$("#metrics-errors").checked = !!m.includeErrors;
|
||||
$("#metrics-filter-btn").classList.toggle("active", !!m.includeErrors);
|
||||
$("#overview-status").textContent = "";
|
||||
$("#overview-errors").checked = !!m.includeErrors;
|
||||
$("#overview-filter-btn").classList.toggle("active", !!m.includeErrors);
|
||||
swarmRegistry.clear();
|
||||
if (!env) {
|
||||
body.innerHTML = emptyState("no episodes yet", "metrics appear as episodes land");
|
||||
@@ -1199,6 +1254,7 @@ function renderEvalPane(body) {
|
||||
line: series.line?.[i],
|
||||
reward: series.reward?.[i],
|
||||
err: series.ok?.[i] === false,
|
||||
timeout: series.timeout?.[i] === true,
|
||||
})),
|
||||
fmt,
|
||||
opts
|
||||
@@ -1251,19 +1307,19 @@ function renderEvalPane(body) {
|
||||
drawTiming();
|
||||
}
|
||||
|
||||
$("#metrics-errors").addEventListener("change", (e) => {
|
||||
$("#overview-errors").addEventListener("change", (e) => {
|
||||
state.metrics.includeErrors = e.target.checked;
|
||||
savePrefs();
|
||||
renderMetricsBody();
|
||||
});
|
||||
|
||||
$("#metrics-body").addEventListener("mousemove", (e) => {
|
||||
$("#overview-body").addEventListener("mousemove", (e) => {
|
||||
const tip = $("#swarm-tip");
|
||||
const timed = e.target.closest("[data-tip]");
|
||||
const pane = e.target.closest(".comp-pane");
|
||||
const rowEl = e.target.closest("[data-row]");
|
||||
const part = rowEl ? null : e.target.closest("[data-part]");
|
||||
document.querySelectorAll("#metrics-body .comp-pane").forEach((p) => {
|
||||
document.querySelectorAll("#overview-body .comp-pane").forEach((p) => {
|
||||
if (p === pane && rowEl) highlightRow(p, rowEl.dataset.row);
|
||||
else highlightPart(p, p === pane && part ? part.dataset.part : null);
|
||||
});
|
||||
@@ -1279,22 +1335,22 @@ $("#metrics-body").addEventListener("mousemove", (e) => {
|
||||
tip.innerHTML = swarmTipHtml(entry, dot ? entry.points[+dot.dataset.i] : null);
|
||||
}
|
||||
tip.hidden = false;
|
||||
const host = $("#tab-metrics").getBoundingClientRect();
|
||||
const host = $("#tab-overview").getBoundingClientRect();
|
||||
const left = Math.min(e.clientX - host.left + 12, host.width - tip.offsetWidth - 8);
|
||||
tip.style.left = `${Math.max(4, left)}px`;
|
||||
tip.style.top = `${e.clientY - host.top + 14}px`;
|
||||
});
|
||||
$("#metrics-body").addEventListener("mouseleave", () => {
|
||||
$("#overview-body").addEventListener("mouseleave", () => {
|
||||
$("#swarm-tip").hidden = true;
|
||||
document.querySelectorAll("#metrics-body .comp-pane").forEach((p) => highlightPart(p, null));
|
||||
document.querySelectorAll("#overview-body .comp-pane").forEach((p) => highlightPart(p, null));
|
||||
});
|
||||
|
||||
$("#metrics-env").addEventListener("change", (e) => {
|
||||
$("#overview-env").addEventListener("change", (e) => {
|
||||
state.metrics.evalEnv = e.target.value;
|
||||
renderMetricsBody();
|
||||
});
|
||||
|
||||
$("#metrics-body").addEventListener("click", (e) => {
|
||||
$("#overview-body").addEventListener("click", (e) => {
|
||||
const strip = e.target.closest(".tm-strip-seg[data-line], .tm-row-hit[data-line]");
|
||||
if (strip) {
|
||||
openEpisode(+strip.dataset.line);
|
||||
@@ -1805,7 +1861,7 @@ function panelTitle(panel, series, sectionName) {
|
||||
}
|
||||
if (sectionName && title.startsWith(`${sectionName}/`)) title = title.slice(sectionName.length + 1);
|
||||
// overview: a lone mean is implied - all mode keeps the stat next to its /min//p10 siblings
|
||||
if (state.metrics.mode === "overview" && title.endsWith("/mean")) title = title.slice(0, -"/mean".length);
|
||||
if (metricsMode() === "overview" && title.endsWith("/mean")) title = title.slice(0, -"/mean".length);
|
||||
return title;
|
||||
}
|
||||
|
||||
@@ -1851,7 +1907,7 @@ function renderPanelCard(grid, panel, lazy = false) {
|
||||
}
|
||||
|
||||
function paneOrderKey(sectionName) {
|
||||
return `${state.metrics.mode}:${sectionName ?? ""}`;
|
||||
return `${metricsMode()}:${sectionName ?? ""}`;
|
||||
}
|
||||
|
||||
function persistPaneOrder(grid) {
|
||||
@@ -1911,33 +1967,39 @@ function addSection(body, name, count, display = name) {
|
||||
/* all-mode: fully recursive sections along family path segments (train → agg →
|
||||
all → agent → …). Every logged key gets its own pane — stats are never
|
||||
overlaid, so min/p10/median/... show as raw separate plots. */
|
||||
function renderKeyTree(parent, name, families, depth) {
|
||||
/* one section per path prefix: the keys right under it are its panes, the deeper
|
||||
ones nest as sections of their own */
|
||||
function renderKeyTree(parent, name, keys, depth) {
|
||||
const display = depth === 1 ? name : name.split("/").pop();
|
||||
const { div, grid } = addSection(parent, name, families.length, display);
|
||||
const { div, grid } = addSection(parent, name, keys.length, display);
|
||||
const children = new Map();
|
||||
const leaves = [];
|
||||
for (const f of families) {
|
||||
const segments = f.family.split("/");
|
||||
if (segments.length <= depth + 1) leaves.push(f);
|
||||
for (const key of keys) {
|
||||
const segments = key.split("/");
|
||||
// a bare key (no path) is a pane of its own top-level section
|
||||
if (segments.length <= depth + 1) renderPanelCard(grid, { metric: key }, true);
|
||||
else {
|
||||
const segment = segments[depth];
|
||||
if (!children.has(segment)) children.set(segment, []);
|
||||
children.get(segment).push(f);
|
||||
children.get(segment).push(key);
|
||||
}
|
||||
}
|
||||
for (const f of leaves) for (const key of f.keys) renderPanelCard(grid, { metric: key }, true);
|
||||
if (grid.children.length) applyPaneOrder(grid);
|
||||
else grid.remove();
|
||||
for (const [segment, childFamilies] of children) renderKeyTree(div, `${name}/${segment}`, childFamilies, depth + 1);
|
||||
for (const [segment, childKeys] of children) renderKeyTree(div, `${name}/${segment}`, childKeys, depth + 1);
|
||||
}
|
||||
|
||||
function renderMetricsBody() {
|
||||
const m = state.metrics;
|
||||
for (const entry of m.charts) entry.u?.destroy();
|
||||
m.charts = [];
|
||||
if (!isChartTab()) {
|
||||
m.renderedKeys = -1; // nothing on screen: the next chart tab renders afresh
|
||||
return;
|
||||
}
|
||||
m.renderedKeys = m.byKey.size;
|
||||
const body = $("#metrics-body");
|
||||
body.innerHTML = "";
|
||||
const view = chartView();
|
||||
const body = $(view.body);
|
||||
for (const other of chartBodies()) other.innerHTML = ""; // the other tab's panes lost their charts above
|
||||
lazyObserver?.disconnect();
|
||||
lazyObserver = new IntersectionObserver(
|
||||
(entries) => {
|
||||
@@ -1949,15 +2011,15 @@ function renderMetricsBody() {
|
||||
},
|
||||
{ root: body, rootMargin: "400px" }
|
||||
);
|
||||
if (state.meta?.type === "eval") return renderEvalPane(body);
|
||||
activeFilter = makeFilter(state.metrics.search.trim());
|
||||
if (state.tab === "overview" && state.meta?.type === "eval") return renderEvalPane(body);
|
||||
activeFilter = makeFilter(m.searches[state.tab].trim());
|
||||
if (!state.meta?.has_metrics && !m.byKey.size) {
|
||||
body.innerHTML = emptyState("no metrics yet");
|
||||
$("#metrics-status").textContent = "";
|
||||
$(view.status).textContent = "";
|
||||
return;
|
||||
}
|
||||
if (m.mode === "overview") {
|
||||
$("#metrics-status").textContent = "";
|
||||
if (view.mode === "overview") {
|
||||
$(view.status).textContent = "";
|
||||
for (const section of buildSections(state.meta)) {
|
||||
const { div, grid } = addSection(body, section.name);
|
||||
for (const panel of section.panels) {
|
||||
@@ -1974,38 +2036,36 @@ function renderMetricsBody() {
|
||||
body.innerHTML = emptyState("no keys match", "no overview panels match the filter");
|
||||
return;
|
||||
}
|
||||
// all: one card per metric family - flat lists a section per family with a
|
||||
// pane per stat, nested groups families recursively along path segments
|
||||
const familyKeys = new Map();
|
||||
let shown = 0;
|
||||
for (const key of [...m.byKey.keys()].sort()) {
|
||||
if (activeFilter && !activeFilter.test(key)) continue;
|
||||
shown++;
|
||||
const family = familyOf(key);
|
||||
if (!familyKeys.has(family)) familyKeys.set(family, []);
|
||||
familyKeys.get(family).push(key);
|
||||
}
|
||||
$("#metrics-status").textContent = activeFilter ? `${shown} / ${m.byKey.size} keys` : "";
|
||||
if (!familyKeys.size) {
|
||||
// all: one pane per key - flat lists a section per parent path, nested walks
|
||||
// the path segments as a tree of sections
|
||||
const keys = [...m.byKey.keys()].filter((key) => !activeFilter || activeFilter.test(key)).sort();
|
||||
$(view.status).textContent = activeFilter ? `${keys.length} / ${m.byKey.size} keys` : "";
|
||||
if (!keys.length) {
|
||||
body.innerHTML = emptyState("no keys match", `0 of ${m.byKey.size} keys match the filter`);
|
||||
return;
|
||||
}
|
||||
const bySegment = (keys, at) => {
|
||||
const groups = new Map();
|
||||
for (const key of keys) {
|
||||
const segments = key.split("/");
|
||||
const group = at(segments);
|
||||
if (!groups.has(group)) groups.set(group, []);
|
||||
groups.get(group).push(key);
|
||||
}
|
||||
return groups;
|
||||
};
|
||||
if (m.allLayout === "flat") {
|
||||
for (const [family, keys] of familyKeys) {
|
||||
const { div, grid } = addSection(body, family, keys.length);
|
||||
for (const key of keys) renderPanelCard(grid, { metric: key }, true);
|
||||
// a bare key with no path is its own section
|
||||
const sections = [...bySegment(keys, (segments) => segments.slice(0, -1).join("/") || segments[0])].sort(([a], [b]) => a.localeCompare(b));
|
||||
for (const [parent, group] of sections) {
|
||||
const { div, grid } = addSection(body, parent, group.length);
|
||||
for (const key of group) renderPanelCard(grid, { metric: key }, true);
|
||||
if (!grid.children.length) div.remove();
|
||||
else applyPaneOrder(grid);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const groups = new Map();
|
||||
for (const [family, keys] of familyKeys) {
|
||||
const group = family.split("/")[0];
|
||||
if (!groups.has(group)) groups.set(group, []);
|
||||
groups.get(group).push({ family, keys });
|
||||
}
|
||||
for (const [group, families] of groups) renderKeyTree(body, group, families, 1);
|
||||
for (const [group, groupKeys] of bySegment(keys, (segments) => segments[0])) renderKeyTree(body, group, groupKeys, 1);
|
||||
}
|
||||
|
||||
async function initMetrics() {
|
||||
@@ -2981,10 +3041,12 @@ function fmtSpan(dispatched, arrived, elapsed) {
|
||||
}
|
||||
|
||||
function episodeRowHtml(ep) {
|
||||
const failed = !ep.ok || !!ep.num_errors;
|
||||
// an ok episode keeps the errors of the attempts it recovered from; they mark the
|
||||
// row as retried, not as failed
|
||||
const failed = !ep.ok;
|
||||
const phase = failed ? "error" : "done";
|
||||
const dispatched = ep.dispatch ?? (ep.arrival != null && ep.duration != null ? ep.arrival - ep.duration : null);
|
||||
return `<tr data-line="${ep.line}" class="${failed ? "err" : ""}"${failed ? ` title="${ep.num_errors || 1} error${ep.num_errors === 1 ? "" : "s"}"` : ""}>
|
||||
return `<tr data-line="${ep.line}" class="${episodeRowClass(ep)}" title="${esc(episodeRowTitle(ep))}">
|
||||
<td class="muted">${ep.line}</td>
|
||||
<td><span class="badge stage stage-${phase}">${phase}</span></td>
|
||||
<td class="muted nowrap">${fmtSpan(dispatched, ep.arrival, ep.duration)}</td>
|
||||
@@ -3168,7 +3230,7 @@ async function openLiveTrace(traceId, { refresh = false } = {}) {
|
||||
semanticExpandedRuns.clear();
|
||||
clearSemanticTranscriptOrigin();
|
||||
$("#sg-inspector").hidden = true;
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading live trace…</div>`;
|
||||
resetTranscript(`<div class="chart-empty">loading live trace…</div>`);
|
||||
$("#tm-timeline").innerHTML = "";
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
@@ -3284,7 +3346,7 @@ function tmItemHtml(item) {
|
||||
}
|
||||
const e = item;
|
||||
return (
|
||||
`<div class="tm-item ${rolloutActive(item) ? "active" : ""}${e.num_errors || !e.ok ? " err" : ""}" data-line="${e.line}">` +
|
||||
`<div class="tm-item ${rolloutActive(item) ? "active" : ""} ${episodeRowClass(e)}" data-line="${e.line}" title="${esc(episodeRowTitle(e))}">` +
|
||||
`<span class="tm-num">#${e.line}</span><span class="tm-env muted" title="${esc(e.env ?? "")}">${esc(e.env ?? "")}</span>` +
|
||||
`<span class="tm-reward ${rewardClass(e.reward)}">${fmtReward(e.reward)}</span></div>`
|
||||
);
|
||||
@@ -3385,7 +3447,7 @@ async function modalStep(delta) {
|
||||
currentLine = null;
|
||||
currentEpisode = null;
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = emptyState("no episodes", "this step has no rollouts for the current filters");
|
||||
resetTranscript(emptyState("no episodes", "this step has no rollouts for the current filters"));
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
}
|
||||
@@ -3433,6 +3495,15 @@ async function ensureTokens() {
|
||||
currentEpisode = episode;
|
||||
}
|
||||
|
||||
/* Every path that replaces the transcript with a placeholder goes through here, so the
|
||||
previous episode's error strip never outlives its episode. */
|
||||
function resetTranscript(html) {
|
||||
const episodeErrors = $("#tm-episode-errors");
|
||||
episodeErrors.hidden = true;
|
||||
episodeErrors.innerHTML = "";
|
||||
$("#tm-messages").innerHTML = html;
|
||||
}
|
||||
|
||||
async function openEpisode(line, target = {}) {
|
||||
currentLive = null;
|
||||
$("#tm-live-label").textContent = "";
|
||||
@@ -3445,7 +3516,7 @@ async function openEpisode(line, target = {}) {
|
||||
currentEpisode = null;
|
||||
renderModalStep();
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
|
||||
resetTranscript(`<div class="chart-empty">loading episode…</div>`);
|
||||
const timelineTarget = $("#tm-timeline");
|
||||
timelineTarget.classList.remove("semantic-canvas");
|
||||
delete timelineTarget.dataset.semanticEpisode;
|
||||
@@ -3899,7 +3970,7 @@ function judgeEvidenceHtml(trace) {
|
||||
|
||||
function renderedTokensHtml(trace, branches) {
|
||||
const rendered = trace.rendered_tokens;
|
||||
const errors = errorBannersHtml(episodeErrors(currentEpisode, trace));
|
||||
const errors = scopedErrorsHtml("trace", scopedErrors(currentEpisode, trace).trace);
|
||||
if (!rendered) return errors + emptyState("rendered text not loaded", "select this view again to load recorded token IDs");
|
||||
const path = currentPath(trace, branches);
|
||||
const tokenCount = path.reduce((count, index) => count + (trace.nodes[index]?.token_ids?.length || 0), 0);
|
||||
@@ -3939,43 +4010,70 @@ function renderedBoxHtml(tokenCount, body, canCopyText) {
|
||||
|
||||
let entriesObserver = null;
|
||||
|
||||
function episodeErrors(ep, trace) {
|
||||
// one failure is often recorded twice, on the episode and on its trace; show it
|
||||
// once, keeping whichever copy carries the traceback
|
||||
const byMessage = new Map();
|
||||
for (const error of [...(ep.errors || []), ...(trace?.errors || [])]) {
|
||||
const record = error && typeof error === "object" ? error : { message: String(error) };
|
||||
const key = `${record.type ?? "Error"}|${record.message ?? ""}`;
|
||||
const kept = byMessage.get(key);
|
||||
if (!kept || (!kept.traceback && record.traceback)) byMessage.set(key, record);
|
||||
/* Errors carried by the episode and by the open trace, each split by what they mean.
|
||||
Verifiers keeps every attempt's errors on the final record and stamps success as `ok`,
|
||||
so the errors of an ok episode or trace are history it recovered from, while a failed
|
||||
one's errors describe its outcome. A failure recorded on both the episode and its
|
||||
trace shows once, as the trace's, keeping whichever copy carries the traceback. */
|
||||
function scopedErrors(ep, trace) {
|
||||
const record = (error) => (error && typeof error === "object" ? error : { message: String(error) });
|
||||
const key = (r) => `${r.type ?? "Error"}|${r.message ?? ""}`;
|
||||
const keep = (map, r) => {
|
||||
const kept = map.get(key(r));
|
||||
if (!kept || (!kept.traceback && r.traceback)) map.set(key(r), r);
|
||||
};
|
||||
const onTrace = new Map();
|
||||
for (const error of trace?.errors || []) keep(onTrace, record(error));
|
||||
const onEpisode = new Map();
|
||||
for (const error of ep.errors || []) {
|
||||
const r = record(error);
|
||||
if (onTrace.has(key(r))) keep(onTrace, r);
|
||||
else keep(onEpisode, r);
|
||||
}
|
||||
return [...byMessage.values()];
|
||||
const split = (records, ok) => ({ failed: ok ? [] : records, recovered: ok ? records : [] });
|
||||
return { episode: split([...onEpisode.values()], ep.ok), trace: split([...onTrace.values()], trace?.ok) };
|
||||
}
|
||||
|
||||
function errorBannersHtml(errors) {
|
||||
if (!errors.length) return "";
|
||||
function errorEntryHtml(scope, record) {
|
||||
const type = record.type ?? "Error";
|
||||
const message = record.message ?? "No error message";
|
||||
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
|
||||
return (
|
||||
`<div class="trace-errors">` +
|
||||
errors
|
||||
.map((error) => {
|
||||
const record = error && typeof error === "object" ? error : { message: String(error) };
|
||||
const type = record.type ?? "Error";
|
||||
const message = record.message ?? "No error message";
|
||||
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
|
||||
return (
|
||||
`<section class="trace-error-banner">` +
|
||||
`<div class="trace-error-message"><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
|
||||
(traceback
|
||||
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
|
||||
: "") +
|
||||
`</section>`
|
||||
);
|
||||
})
|
||||
.join("") +
|
||||
`</div>`
|
||||
`<div class="trace-error-message"><span class="trace-error-scope">${scope} error</span><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
|
||||
(traceback
|
||||
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
|
||||
: "")
|
||||
);
|
||||
}
|
||||
|
||||
function scopedErrorsHtml(scope, { failed, recovered }) {
|
||||
const banners = failed.length
|
||||
? `<div class="trace-errors">${failed.map((record) => `<section class="trace-error-banner">${errorEntryHtml(scope, record)}</section>`).join("")}</div>`
|
||||
: "";
|
||||
const history = recovered.length
|
||||
? `<details class="trace-recovered"><summary><span>recovered from ${recovered.length} ${scope} error${recovered.length === 1 ? "" : "s"} in earlier attempts</span><span class="entry-chev">›</span></summary>` +
|
||||
recovered.map((record) => `<section class="trace-recovered-item">${errorEntryHtml(scope, record)}</section>`).join("") +
|
||||
`</details>`
|
||||
: "";
|
||||
return banners + history;
|
||||
}
|
||||
|
||||
function episodeRowClass(ep) {
|
||||
if (ep.timeout) return "timeout";
|
||||
if (!ep.ok) return "err";
|
||||
return ep.num_errors ? "retried" : "";
|
||||
}
|
||||
|
||||
function episodeRowTitle(ep) {
|
||||
const n = ep.num_errors || 0;
|
||||
const errors = `${n || 1} error${n === 1 ? "" : "s"}`;
|
||||
const timeout = ep.timeout ? `timed out (${ep.stop_condition ?? "timeout"})` : "";
|
||||
if (!ep.ok) return [timeout, errors].filter(Boolean).join(" · ");
|
||||
if (timeout) return timeout;
|
||||
return n ? `recovered from ${errors} in earlier attempts` : "";
|
||||
}
|
||||
|
||||
|
||||
function normalizedCallUsage(usage = {}) {
|
||||
let input = usage.prompt_tokens;
|
||||
let cached = usage.cached_input_tokens;
|
||||
@@ -3995,7 +4093,7 @@ function normalizedCallUsage(usage = {}) {
|
||||
function renderMessages(ep, trace, branches) {
|
||||
const container = $("#tm-messages");
|
||||
entriesObserver?.disconnect();
|
||||
const errorsHtml = errorBannersHtml(episodeErrors(ep, trace));
|
||||
const errorsHtml = scopedErrorsHtml("trace", scopedErrors(ep, trace).trace);
|
||||
if (!trace) {
|
||||
container.innerHTML = errorsHtml + emptyState("no traces", "this episode carries no trace data");
|
||||
return;
|
||||
@@ -4264,6 +4362,7 @@ function renderMeta(ep, trace, branches) {
|
||||
parts.push(metaRow("stop_condition", trace.stop_condition));
|
||||
parts.push(metaRow("is_completed", trace.is_completed));
|
||||
parts.push(metaRow("is_truncated", traceTruncated(trace)));
|
||||
parts.push(metaRow("is_timeout", !!trace.is_timeout));
|
||||
parts.push(metaRow("ok", trace.ok));
|
||||
|
||||
const durations = [];
|
||||
@@ -5446,12 +5545,17 @@ function renderEpisode() {
|
||||
const trace = traces[currentTraceIdx];
|
||||
const branches = trace ? traceBranches(trace) : [];
|
||||
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
|
||||
// the episode's own errors sit above the agent and branch selectors: they belong to
|
||||
// the whole episode, not to whichever trace is open
|
||||
const episodeErrors = $("#tm-episode-errors");
|
||||
episodeErrors.innerHTML = scopedErrorsHtml("episode", scopedErrors(ep, trace).episode);
|
||||
episodeErrors.hidden = !episodeErrors.innerHTML;
|
||||
const traceTabs = $("#tm-trace-tabs");
|
||||
traceTabs.hidden = traces.length <= 1;
|
||||
traceTabs.innerHTML =
|
||||
traces.length > 1
|
||||
? traces
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.is_timeout ? " timeout" : trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.join("")
|
||||
: "";
|
||||
const branchTabs = $("#tm-branch-tabs");
|
||||
@@ -6254,15 +6358,6 @@ function syncTraceFilterControls() {
|
||||
|
||||
document.querySelectorAll("#tabs button").forEach((b) => b.addEventListener("click", () => activateTab(b.dataset.tab)));
|
||||
|
||||
document.querySelectorAll("#metrics-mode button").forEach((b) =>
|
||||
b.addEventListener("click", () => {
|
||||
state.metrics.mode = b.dataset.mode;
|
||||
setActive("#metrics-mode", "mode", b.dataset.mode);
|
||||
$("#all-layout").hidden = b.dataset.mode !== "all";
|
||||
renderMetricsBody();
|
||||
savePrefs();
|
||||
})
|
||||
);
|
||||
$("#config-format").addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("button[data-fmt]");
|
||||
if (!btn || btn.disabled || btn.dataset.fmt === state.config.fmt) return;
|
||||
@@ -6282,49 +6377,57 @@ $("#config-search").addEventListener(
|
||||
savePrefs();
|
||||
})
|
||||
);
|
||||
document.querySelectorAll("#all-layout button").forEach((b) =>
|
||||
document.querySelectorAll("#metrics-layout button").forEach((b) =>
|
||||
b.addEventListener("click", () => {
|
||||
state.metrics.allLayout = b.dataset.layout;
|
||||
setActive("#all-layout", "layout", b.dataset.layout);
|
||||
setActive("#metrics-layout", "layout", b.dataset.layout);
|
||||
renderMetricsBody();
|
||||
savePrefs();
|
||||
})
|
||||
);
|
||||
$("#metrics-search").addEventListener(
|
||||
"input",
|
||||
debounce(() => {
|
||||
state.metrics.search = $("#metrics-search").value;
|
||||
renderMetricsBody();
|
||||
for (const [tab, view] of Object.entries(CHART_VIEWS)) {
|
||||
$(view.search).addEventListener(
|
||||
"input",
|
||||
debounce(() => {
|
||||
state.metrics.searches[tab] = $(view.search).value;
|
||||
renderMetricsBody();
|
||||
savePrefs();
|
||||
}, 250)
|
||||
);
|
||||
$(`#${tab}-collapse`).addEventListener("click", () =>
|
||||
document.querySelectorAll(`${view.body} details.section`).forEach((s) => (s.open = false))
|
||||
);
|
||||
$(`#${tab}-expand`).addEventListener("click", () =>
|
||||
document.querySelectorAll(`${view.body} details.section`).forEach((s) => (s.open = true))
|
||||
);
|
||||
$(`#${tab}-smooth`).addEventListener("input", (e) => {
|
||||
state.metrics.smooth = +e.target.value;
|
||||
syncSmoothControls();
|
||||
updateCharts();
|
||||
savePrefs();
|
||||
}, 250)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// remember collapsed sections across re-renders; charts created while hidden
|
||||
// have zero width, so resize on expand ("toggle" doesn't bubble → capture)
|
||||
$("#metrics-body").addEventListener(
|
||||
"toggle",
|
||||
(e) => {
|
||||
const section = e.target;
|
||||
if (!section.matches?.("details.section")) return;
|
||||
if (section.open) resizeCharts();
|
||||
// a search force-opens sections - don't let that overwrite the saved state
|
||||
if (activeFilter) return;
|
||||
if (section.open) state.metrics.collapsedSections.delete(section.dataset.name);
|
||||
else state.metrics.collapsedSections.add(section.dataset.name);
|
||||
savePrefs();
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
$("#metrics-collapse").addEventListener("click", () =>
|
||||
document.querySelectorAll("#metrics-body details.section").forEach((s) => (s.open = false))
|
||||
);
|
||||
$("#metrics-expand").addEventListener("click", () =>
|
||||
document.querySelectorAll("#metrics-body details.section").forEach((s) => (s.open = true))
|
||||
);
|
||||
for (const body of chartBodies())
|
||||
body.addEventListener(
|
||||
"toggle",
|
||||
(e) => {
|
||||
const section = e.target;
|
||||
if (!section.matches?.("details.section")) return;
|
||||
if (section.open) resizeCharts();
|
||||
// a search force-opens sections - don't let that overwrite the saved state
|
||||
if (activeFilter) return;
|
||||
if (section.open) state.metrics.collapsedSections.delete(section.dataset.name);
|
||||
else state.metrics.collapsedSections.add(section.dataset.name);
|
||||
savePrefs();
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
// drag a pane header to reorder within its section (order persisted by title)
|
||||
$("#metrics-body").addEventListener("dragover", (e) => {
|
||||
for (const body of chartBodies()) body.addEventListener("dragover", (e) => {
|
||||
if (!dragCard) return;
|
||||
const grid = e.target.closest(".chart-grid");
|
||||
if (!grid || grid !== dragCard.parentElement) return;
|
||||
@@ -6337,7 +6440,7 @@ $("#metrics-body").addEventListener("dragover", (e) => {
|
||||
});
|
||||
|
||||
/* wandb-style resize handles: resizing one pane resizes all of them */
|
||||
$("#metrics-body").addEventListener("pointerdown", (e) => {
|
||||
for (const body of chartBodies()) body.addEventListener("pointerdown", (e) => {
|
||||
const grip = e.target.closest("[data-rz]");
|
||||
if (!grip) return;
|
||||
e.preventDefault();
|
||||
@@ -6498,7 +6601,7 @@ async function reopenFirstEpisode() {
|
||||
currentLine = null;
|
||||
currentEpisode = null;
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = emptyState("no episodes", "nothing here for the current filters");
|
||||
resetTranscript(emptyState("no episodes", "nothing here for the current filters"));
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
|
||||
@@ -6983,7 +7086,7 @@ $("#tm-meta").addEventListener("click", (e) => {
|
||||
});
|
||||
|
||||
function resizeCharts() {
|
||||
$("#metrics-body").style.setProperty("--pane-h", `${chartHeight()}px`);
|
||||
for (const body of chartBodies()) body.style.setProperty("--pane-h", `${chartHeight()}px`);
|
||||
drawSwarms();
|
||||
drawTiming();
|
||||
for (const entry of state.metrics.charts) {
|
||||
@@ -7012,8 +7115,8 @@ function savePrefs() {
|
||||
paneH: state.metrics.paneH,
|
||||
includeErrors: state.metrics.includeErrors,
|
||||
paneOrder: state.metrics.paneOrder,
|
||||
metricsMode: state.metrics.mode,
|
||||
metricsSearch: state.metrics.search,
|
||||
overviewSearch: state.metrics.searches.overview,
|
||||
metricsSearch: state.metrics.searches.metrics,
|
||||
collapsedSections: [...state.metrics.collapsedSections],
|
||||
traceErrorsOnly: state.traces.errorsOnly,
|
||||
traceStatus: state.traces.status,
|
||||
@@ -7034,16 +7137,17 @@ function savePrefs() {
|
||||
}
|
||||
|
||||
function applyPaneSize() {
|
||||
$("#metrics-body").style.setProperty("--pane-min", `${state.metrics.paneMin}px`);
|
||||
for (const body of chartBodies()) body.style.setProperty("--pane-min", `${state.metrics.paneMin}px`);
|
||||
resizeCharts();
|
||||
}
|
||||
|
||||
$("#smooth-range").addEventListener("input", (e) => {
|
||||
state.metrics.smooth = +e.target.value;
|
||||
$("#smooth-val").textContent = state.metrics.smooth > 1 ? String(state.metrics.smooth) : "off";
|
||||
updateCharts();
|
||||
savePrefs();
|
||||
});
|
||||
/* one smoothing window, shown on both chart tabs */
|
||||
function syncSmoothControls() {
|
||||
for (const tab of Object.keys(CHART_VIEWS)) {
|
||||
$(`#${tab}-smooth`).value = state.metrics.smooth;
|
||||
$(`#${tab}-smooth-val`).textContent = state.metrics.smooth > 1 ? String(state.metrics.smooth) : "off";
|
||||
}
|
||||
}
|
||||
|
||||
let ticking = false;
|
||||
async function pollDashboard() {
|
||||
@@ -7061,7 +7165,7 @@ async function pollDashboard() {
|
||||
}
|
||||
renderOverview(); // keeps the duration field ticking
|
||||
syncDressedSelects();
|
||||
if (state.tab === "metrics" && state.metrics.loaded) await fetchMetrics();
|
||||
if (isChartTab() && state.metrics.loaded) await fetchMetrics();
|
||||
else if (state.tab === "logs" && state.logs.loaded) await pollLogs();
|
||||
else if (state.tab === "traces" && state.traces.loaded) await refreshTraces();
|
||||
else if (state.tab === "report" && state.report.loaded) await refreshReport();
|
||||
@@ -7089,9 +7193,8 @@ document.addEventListener("visibilitychange", () => {
|
||||
});
|
||||
|
||||
(async function init() {
|
||||
$("#smooth-range").value = state.metrics.smooth;
|
||||
$("#smooth-val").textContent = state.metrics.smooth > 1 ? String(state.metrics.smooth) : "off";
|
||||
$("#metrics-search").value = state.metrics.search;
|
||||
syncSmoothControls();
|
||||
for (const [tab, view] of Object.entries(CHART_VIEWS)) $(view.search).value = state.metrics.searches[tab];
|
||||
state.logs.level = LOG_LEVELS.some(([level]) => level === prefs.logLevel) ? prefs.logLevel : "DEBUG";
|
||||
renderLogLevel();
|
||||
$("#log-search").value = prefs.logSearch ?? "";
|
||||
@@ -7099,16 +7202,14 @@ document.addEventListener("visibilitychange", () => {
|
||||
const signal = prefs.tokenSignal ?? "";
|
||||
$("#token-signal").value = $(`#token-signal option[value="${CSS.escape(signal)}"]`) ? signal : "";
|
||||
$("#follow-toggle").checked = state.follow;
|
||||
for (const sel of ["#run-select", "#trace-env", "#metrics-env", "#trace-sort", "#tm-env", "#tm-sort", "#config-attempt-select", "#attempt-select", "#token-signal", "#report-select"])
|
||||
for (const sel of ["#run-select", "#trace-env", "#overview-env", "#trace-sort", "#tm-env", "#tm-sort", "#config-attempt-select", "#attempt-select", "#token-signal", "#report-select"])
|
||||
dressSelect($(sel));
|
||||
syncTraceFilterControls();
|
||||
setActive("#metrics-mode", "mode", state.metrics.mode);
|
||||
setActive("#all-layout", "layout", state.metrics.allLayout);
|
||||
$("#all-layout").hidden = state.metrics.mode !== "all";
|
||||
setActive("#metrics-layout", "layout", state.metrics.allLayout);
|
||||
setActive("#log-view", "view", state.logs.view);
|
||||
applyPaneSize();
|
||||
const params = new URLSearchParams(location.hash.slice(1));
|
||||
state.tab = params.get("tab") || "metrics";
|
||||
state.tab = params.get("tab") || "overview";
|
||||
state.report.wanted = params.get("report");
|
||||
hadHashRun = !!params.get("run");
|
||||
setActive("#tabs", "tab", state.tab);
|
||||
@@ -7117,6 +7218,6 @@ document.addEventListener("visibilitychange", () => {
|
||||
const wanted = params.get("run");
|
||||
const run = state.runs.find((r) => r.name === wanted)?.name ?? state.runs[0]?.name;
|
||||
if (run) await selectRun(run);
|
||||
else $("#metrics-body").innerHTML = emptyState("no runs found", `nothing to show in ${state.outputDir ?? "the output directory"}`);
|
||||
else $("#overview-body").innerHTML = emptyState("no runs found", `nothing to show in ${state.outputDir ?? "the output directory"}`);
|
||||
connectViewEvents();
|
||||
})();
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
</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>
|
||||
@@ -38,30 +39,39 @@
|
||||
<div id="run-overview"></div>
|
||||
|
||||
<main>
|
||||
<section id="tab-metrics">
|
||||
<section id="tab-overview">
|
||||
<div class="controls">
|
||||
<div id="metrics-filter-wrap" class="dd-wrap" hidden>
|
||||
<button id="metrics-filter-btn" class="btn dd-btn" title="filter">
|
||||
<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="metrics-filter-menu" hidden>
|
||||
<div class="dd-menu dd-filters" id="overview-filter-menu" hidden>
|
||||
<div class="dd-sec">filter</div>
|
||||
<label class="dd-row" id="metrics-env-row"><span class="t-label">env</span>
|
||||
<select id="metrics-env"></select>
|
||||
<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="metrics-errors"><span class="dot"></span>include errors</label>
|
||||
<label class="toggle dd-row"><input type="checkbox" id="overview-errors"><span class="dot"></span>include errors</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="seg" id="metrics-mode">
|
||||
<button data-mode="overview" class="active">Overview</button>
|
||||
<button data-mode="all">All</button>
|
||||
</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>
|
||||
@@ -69,7 +79,6 @@
|
||||
<button id="metrics-expand" class="btn">expand</button>
|
||||
</div>
|
||||
<div id="metrics-body"></div>
|
||||
<div id="swarm-tip" hidden></div>
|
||||
</section>
|
||||
|
||||
<section id="tab-config" hidden>
|
||||
@@ -293,6 +302,7 @@
|
||||
<button id="tm-expand" class="btn">expand</button>
|
||||
<button id="drawer-close" class="btn">✕</button>
|
||||
</div>
|
||||
<div id="tm-episode-errors" hidden></div>
|
||||
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
|
||||
<div id="tm-trace-tabs" class="seg" hidden></div>
|
||||
<div id="tm-branch-tabs" class="seg" hidden></div>
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
--accent: #b6ff3c;
|
||||
--negative: #ff4539;
|
||||
--timeout: #ffd166;
|
||||
--positive: #b6ff3c;
|
||||
--infra: #4a9eff;
|
||||
--risk: #ff6b4a;
|
||||
@@ -306,12 +307,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 {
|
||||
@@ -356,17 +359,19 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
.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.timeout { background: var(--timeout); border-color: var(--timeout); }
|
||||
.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-metrics { position: relative; }
|
||||
#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.timeout { fill: var(--timeout); }
|
||||
.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; }
|
||||
@@ -390,6 +395,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
.tm-strip-seg.dim { opacity: 0.2; }
|
||||
.tm-strip-seg:hover { filter: brightness(1.25); }
|
||||
.tm-line.err { fill: var(--negative); }
|
||||
.tm-line.timeout { fill: var(--timeout); }
|
||||
.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 */
|
||||
@@ -399,6 +405,7 @@ details.section[open] .sec-chev { transform: rotate(90deg); }
|
||||
.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); }
|
||||
.sum-tile.rate-timeout .stat-value { color: var(--timeout); }
|
||||
.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); }
|
||||
@@ -528,7 +535,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. */
|
||||
@@ -832,6 +839,9 @@ mark.hit {
|
||||
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
|
||||
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
|
||||
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
|
||||
.tm-item.timeout { background: rgba(255, 209, 102, 0.08); border-color: var(--timeout); }
|
||||
.tm-item.timeout:hover, .tm-item.timeout.active { background: rgba(255, 209, 102, 0.16); }
|
||||
.tm-item.retried { border-left: 2px dotted var(--grey-4); }
|
||||
.tm-item .tm-reward { margin-left: auto; }
|
||||
.tm-nav { padding: 0 8px; height: 24px; }
|
||||
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
|
||||
@@ -933,6 +943,7 @@ mark.hit {
|
||||
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
|
||||
.tl-state.completed { color: var(--positive); }
|
||||
.tl-state.failed { color: var(--negative); }
|
||||
.tl-state.timeout { color: var(--timeout); }
|
||||
.tl-state.running { color: var(--infra); }
|
||||
.tl-tooltip {
|
||||
position: fixed;
|
||||
@@ -1167,7 +1178,7 @@ mark.hit {
|
||||
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
|
||||
|
||||
/* the banners lead the transcript, so they stand off the first entry */
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
|
||||
.trace-errors { margin-top: auto; margin-bottom: 14px; }
|
||||
.trace-error-banner {
|
||||
border: 1px solid var(--negative);
|
||||
background: rgba(255, 69, 57, 0.08);
|
||||
@@ -1176,6 +1187,40 @@ mark.hit {
|
||||
.trace-error-banner + .trace-error-banner { margin-top: 8px; }
|
||||
.trace-error-message { padding: 10px 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
|
||||
.trace-error-type { font-weight: 500; color: var(--negative); }
|
||||
.trace-error-scope {
|
||||
display: inline-block;
|
||||
margin-right: 8px;
|
||||
padding: 1px 6px;
|
||||
border: 1px solid currentColor;
|
||||
font-size: 9px;
|
||||
line-height: 11px;
|
||||
letter-spacing: var(--track-mono);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.trace-error-banner .trace-error-scope { color: var(--negative); }
|
||||
#tm-episode-errors { padding: 12px 16px 0; border-bottom: 1px solid var(--hairline); }
|
||||
#tm-episode-errors .trace-errors { margin-top: 0; margin-bottom: 12px; }
|
||||
#tm-episode-errors .trace-recovered { margin-bottom: 12px; }
|
||||
.trace-recovered { margin-bottom: 14px; border: 1px solid var(--grey-3); color: var(--grey-6); }
|
||||
.trace-recovered > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 12px;
|
||||
font-size: 11px;
|
||||
color: var(--grey-4);
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
}
|
||||
.trace-recovered > summary::-webkit-details-marker { display: none; }
|
||||
.trace-recovered[open] > summary .entry-chev { transform: rotate(90deg); }
|
||||
.trace-recovered-item { border-top: 1px solid var(--grey-3); }
|
||||
.trace-recovered-item .trace-error-type { color: var(--grey-4); }
|
||||
.trace-recovered-item .trace-error-tb > summary { border-top-color: var(--grey-3); }
|
||||
.seg button.err, .seg button.err.active { color: var(--negative); }
|
||||
.seg button.timeout, .seg button.timeout.active { color: var(--timeout); }
|
||||
.trace-error-tb > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1695,6 +1740,8 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
|
||||
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.timeout td:first-child { border-left: 2px solid var(--timeout); }
|
||||
#episode-table tr.retried td:first-child { border-left: 2px dotted var(--grey-4); }
|
||||
#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; }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
import uuid
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
|
||||
@@ -53,6 +54,10 @@ def run_server(config: EnvServerConfig):
|
||||
def main():
|
||||
"""Main entry-point for the env server. Run using `uv run env-server`"""
|
||||
set_proc_title("EnvServer")
|
||||
# verifiers keys run-scoped state (creation limiters) by $VF_RUN_ID. Every launcher,
|
||||
# the Python entrypoints and the SLURM templates alike, hands env servers $PRL_RUN_ID;
|
||||
# a standalone server is a run of its own.
|
||||
os.environ.setdefault("VF_RUN_ID", os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex)
|
||||
run_server(cli(EnvServerConfig))
|
||||
|
||||
|
||||
|
||||
@@ -21,13 +21,14 @@ 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]
|
||||
usage: uv run eval [<taskset-id>] [--env.<field> <value> ...] [-n N] [-s] [-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:
|
||||
Shorthands:
|
||||
<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)
|
||||
--env.<field> <value> a field of that source's env block (e.g. --env.agent.harness.id bash); next to a
|
||||
TOML with [[source]] blocks, a field of the shared env block (e.g. --env.retries.max-retries 3)
|
||||
-c N pin the concurrency band (concurrency.min_inflight = max_inflight = N)
|
||||
"""
|
||||
|
||||
@@ -46,17 +47,21 @@ def parse_value(raw: str) -> Any:
|
||||
|
||||
|
||||
def expand_shorthands(argv: list[str]) -> list[str]:
|
||||
"""Rewrite the single-source shorthands into flags ``EvalConfig`` parses.
|
||||
"""Rewrite the 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.
|
||||
``--source.0.env...`` cannot address it). Next to a config file that defines
|
||||
``[[source]]`` blocks, ``--env.*`` flags pass through to the shared ``env`` block.
|
||||
``-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(("-", "@")):
|
||||
positional = bool(rest) and not rest[0].startswith(("-", "@"))
|
||||
sources_in_toml = any(toml_defines_source(path) for path in root_config_files(argv))
|
||||
shared_env = sources_in_toml and not positional
|
||||
if positional:
|
||||
set_nested(source, ["env", "taskset", "id"], rest.pop(0))
|
||||
i = 0
|
||||
while i < len(rest):
|
||||
@@ -67,7 +72,9 @@ def expand_shorthands(argv: list[str]) -> list[str]:
|
||||
raise SystemExit(f"{flag} needs a value")
|
||||
i += 1
|
||||
value = rest[i]
|
||||
if flag.startswith("--env."):
|
||||
if flag.startswith("--env.") and shared_env:
|
||||
out += [flag, value]
|
||||
elif 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]
|
||||
@@ -75,9 +82,9 @@ def expand_shorthands(argv: list[str]) -> list[str]:
|
||||
out.append(arg)
|
||||
i += 1
|
||||
if source:
|
||||
if any(toml_defines_source(path) for path in root_config_files(argv)):
|
||||
if sources_in_toml:
|
||||
raise SystemExit(
|
||||
"The <taskset-id> / --env.* shorthands describe a single source and cannot be combined "
|
||||
"The <taskset-id> shorthand describes 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])]
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -9,6 +9,7 @@ from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
|
||||
from prime_rl.configs.eval import SFTOnlineEvalConfig
|
||||
from prime_rl.configs.monitors import EvalMonitorsConfig, PrimeEvalMonitorConfig, TrainMonitorsConfig
|
||||
from prime_rl.configs.orchestrator import OnlineEvalSourceConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
@@ -72,6 +73,16 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
|
||||
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
|
||||
|
||||
|
||||
def build_online_eval_monitors(monitors: TrainMonitorsConfig) -> EvalMonitorsConfig:
|
||||
"""The online-eval process's monitors: same W&B and file config as the trainer's,
|
||||
with the platform monitor switched to the evaluation flavor under the same name."""
|
||||
return EvalMonitorsConfig(
|
||||
wandb=monitors.wandb,
|
||||
file=monitors.file,
|
||||
prime=PrimeEvalMonitorConfig(name=monitors.prime.name) if monitors.prime is not None else None,
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
@@ -85,9 +96,14 @@ def build_online_eval_config(config: SFTConfig) -> SFTOnlineEvalConfig:
|
||||
broadcasts_dir=get_broadcast_dir(config.run_dir),
|
||||
max_steps=config.max_steps,
|
||||
resume_step=resolve_resume_step(config),
|
||||
# Same run dir as the trainer: the dashboard reads the eval's
|
||||
# file-monitor artifacts from the run directory, so a separate
|
||||
# output dir would hide them. The train-vs-eval record collision
|
||||
# is resolved by record merging in prime_rl.monitors.prime, not
|
||||
# by directory separation.
|
||||
output_dir=config.run_dir,
|
||||
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
|
||||
monitors=config.monitors,
|
||||
monitors=build_online_eval_monitors(config.monitors),
|
||||
)
|
||||
return SFTOnlineEvalConfig(**{**eval_config.model_dump(exclude=set(run_fields)), **run_fields})
|
||||
|
||||
@@ -137,7 +153,7 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
|
||||
|
||||
|
||||
def write_slurm_script(
|
||||
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
|
||||
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str, wandb_shared: bool
|
||||
) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
@@ -210,6 +226,7 @@ def write_slurm_script(
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
wandb_shared=wandb_shared,
|
||||
run_name=config.run.name,
|
||||
online_eval=online_eval,
|
||||
use_nccl_broadcast=(
|
||||
@@ -249,16 +266,14 @@ def sft_slurm(config: SFTConfig):
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
|
||||
# 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"]
|
||||
wandb_shared = online_eval and config.monitors.wandb is not None
|
||||
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
if online_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
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)
|
||||
write_slurm_script(config, config_path, log_dir, script_path, os.environ["PRL_RUN_ID"], wandb_shared)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
|
||||
@@ -544,8 +559,12 @@ def sft(config: SFTConfig):
|
||||
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
from prime_rl.trainer.sft.data import pre_download_data
|
||||
|
||||
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init)
|
||||
pre_download_data(config.data, config.env_vars)
|
||||
if config.val is not None:
|
||||
pre_download_data(config.val.data, config.env_vars)
|
||||
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
|
||||
@@ -27,7 +27,6 @@ class Eval:
|
||||
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(
|
||||
|
||||
@@ -47,6 +47,7 @@ class OnlineEval:
|
||||
await monitors.setup(
|
||||
producer="online-eval",
|
||||
wandb=config.monitors.wandb,
|
||||
prime=config.monitors.prime,
|
||||
file=config.monitors.file,
|
||||
output_dir=config.output_dir,
|
||||
run_config=config,
|
||||
|
||||
@@ -8,16 +8,14 @@ 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``).
|
||||
kept episodes are matched to the new selection and the rest is owed. The resumed
|
||||
config is not checked against the interrupted one: any of it may be overridden.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter, defaultdict
|
||||
from collections.abc import Iterator
|
||||
from fnmatch import fnmatch
|
||||
from pathlib import Path
|
||||
|
||||
import orjson
|
||||
@@ -28,29 +26,10 @@ 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.*.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."""
|
||||
running, beside the episodes it produces, recording the config those episodes were
|
||||
measured with."""
|
||||
|
||||
|
||||
def stamp_config(run_dir: Path, config: dict) -> None:
|
||||
@@ -59,45 +38,6 @@ def stamp_config(run_dir: Path, config: dict) -> None:
|
||||
(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."""
|
||||
|
||||
@@ -45,6 +45,7 @@ from prime_rl.orchestrator.utils import (
|
||||
intercept_vf_logging,
|
||||
set_default_executor,
|
||||
)
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger
|
||||
from prime_rl.utils.pathing import get_config_dir
|
||||
|
||||
@@ -71,11 +72,20 @@ class EvalRunner:
|
||||
self.dispatcher: Dispatcher | None = None
|
||||
self.inference_metrics: InferenceMetricsCollector | None = None
|
||||
self.periodic_logger: PeriodicLogger | None = None
|
||||
self.heart: Heartbeat | None = None
|
||||
|
||||
async def setup(self, *, skip_first_step: bool = False, is_resumed: bool = False) -> None:
|
||||
config = self.config
|
||||
set_default_executor()
|
||||
|
||||
# The heartbeat is beaten only by landed episodes — the first episode is its
|
||||
# first beat. No startup ping on purpose: the run-start to first-episode gap
|
||||
# (pool boot, env servers, the first episode's full duration) would otherwise
|
||||
# sit inside the ping stream as an abnormally long silence and flip a healthy
|
||||
# run stale. Until then the heartbeat has simply never been pinged.
|
||||
if config.heartbeat is not None:
|
||||
self.heart = Heartbeat(config.heartbeat.url)
|
||||
|
||||
# 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")
|
||||
@@ -114,7 +124,7 @@ class EvalRunner:
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.concurrency.max_inflight,
|
||||
tasks_per_minute=None,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
max_off_policy_steps=0,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
@@ -224,6 +234,8 @@ class EvalRunner:
|
||||
eval_batch = self.eval_sink.fail(item)
|
||||
else:
|
||||
stamp_arrival([item], "eval", eval_work(item).step)
|
||||
if self.heart is not None:
|
||||
self.heart.beat()
|
||||
await self.land(item, pending)
|
||||
continue
|
||||
if eval_batch is not None:
|
||||
@@ -291,7 +303,8 @@ class EvalRunner:
|
||||
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%}"
|
||||
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%} | "
|
||||
f"Timeout {full.is_timeout.mean():.1%}"
|
||||
)
|
||||
|
||||
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
|
||||
|
||||
@@ -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,14 +15,12 @@ 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()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
monkey_patch_deepseek_v4_allowed_layer_types()
|
||||
monkey_patch_deepseek_v4_per_layer_rope()
|
||||
monkey_patch_deepseek_v4_bf16_o_proj()
|
||||
monkey_patch_deepseek_v4_request_tools_placement()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
@@ -42,6 +40,64 @@ def monkey_patch_deepseek_v4_allowed_layer_types():
|
||||
allow_deepseek_v4_layer_types()
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_request_tools_placement():
|
||||
"""Attach request-level tools to the first existing DSV4 system message.
|
||||
|
||||
vLLM 0.29.0's Python DeepSeek-V4 tokenizer always prepends a synthetic
|
||||
system message for request-level tools. That puts the tool schema before
|
||||
an existing system prompt, unlike DeepSeek's reference encoder, vLLM's
|
||||
Rust renderer, and prime-rl's training renderer. Upstream fixed this in
|
||||
https://github.com/vllm-project/vllm/pull/51856 (commit 2909ad8f).
|
||||
The fix is expected to ship in vLLM 0.31.
|
||||
|
||||
Wrap the tokenizer factory so existing-system requests take the corrected
|
||||
path through the stock implementation: shallow-copy the conversation,
|
||||
attach tools to its first system message, and suppress the stock synthetic
|
||||
insertion. Requests without a system message retain the stock behavior.
|
||||
Remove this patch once the vLLM pin includes the upstream fix (likely 0.31).
|
||||
"""
|
||||
import copy
|
||||
|
||||
from vllm.tokenizers import deepseek_v4 as dsv4_tokenizer
|
||||
|
||||
original_get_tokenizer = dsv4_tokenizer.get_deepseek_v4_tokenizer
|
||||
if getattr(original_get_tokenizer, "_prime_rl_places_request_tools", False):
|
||||
return
|
||||
|
||||
def _get_deepseek_v4_tokenizer(tokenizer):
|
||||
wrapped = original_get_tokenizer(tokenizer)
|
||||
tokenizer_cls = wrapped.__class__
|
||||
original_apply_chat_template = tokenizer_cls.apply_chat_template
|
||||
|
||||
# Each factory call creates a fresh dynamic tokenizer subclass, but be
|
||||
# defensive if vLLM starts caching that class in a future release.
|
||||
if getattr(original_apply_chat_template, "_prime_rl_places_request_tools", False):
|
||||
return wrapped
|
||||
|
||||
def _apply_chat_template(self, messages, tools=None, **kwargs):
|
||||
if tools:
|
||||
conversation = kwargs.get("conversation", messages)
|
||||
system_idx = next(
|
||||
(i for i, message in enumerate(conversation) if message.get("role") == "system"),
|
||||
None,
|
||||
)
|
||||
if system_idx is not None:
|
||||
conversation = conversation.copy()
|
||||
conversation[system_idx] = copy.copy(conversation[system_idx])
|
||||
conversation[system_idx]["tools"] = tools
|
||||
kwargs["conversation"] = conversation
|
||||
tools = None
|
||||
|
||||
return original_apply_chat_template(self, messages, tools=tools, **kwargs)
|
||||
|
||||
_apply_chat_template._prime_rl_places_request_tools = True
|
||||
tokenizer_cls.apply_chat_template = _apply_chat_template
|
||||
return wrapped
|
||||
|
||||
_get_deepseek_v4_tokenizer._prime_rl_places_request_tools = True
|
||||
dsv4_tokenizer.get_deepseek_v4_tokenizer = _get_deepseek_v4_tokenizer
|
||||
|
||||
|
||||
def monkey_patch_online_fp8_parameter_cast():
|
||||
"""Pass plain tensors to vLLM's compiled block-FP8 caster.
|
||||
|
||||
@@ -127,110 +183,6 @@ def monkey_patch_kv_xfer_finished_tolerate_freed():
|
||||
logger.warning("Patched Scheduler._update_from_kv_xfer_finished to tolerate freed (aborted) KV-transfer reqs.")
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_bf16_o_proj():
|
||||
"""Run DeepSeek V4's output projection in bf16 when the weights are not FP8.
|
||||
|
||||
vLLM's DeepSeek V4 output projection is FP8-only. All three CUDA attention
|
||||
classes (``DeepseekV4FlashMLAAttention``,
|
||||
``DeepseekV4FlashInferMLAAttention``, ``DeepseekV4FlashInferSM120Attention``)
|
||||
implement ``_o_proj`` by calling ``deep_gemm_fp8_o_proj``
|
||||
(``vllm/models/deepseek_v4/nvidia/ops/o_proj.py``), which dereferences
|
||||
``wo_a.weight_scale``, falling back to ``wo_a.weight_scale_inv``, and hands
|
||||
the result to DeepGEMM's ``fp8_einsum``. There is no branch on quant config
|
||||
or weight dtype, and ``_o_proj`` is an ``@abstractmethod`` dispatched purely
|
||||
by platform subclass, so no attention backend routes around it. A bf16
|
||||
checkpoint has neither attribute and therefore fails with
|
||||
``AttributeError: 'ColumnParallelLinear' object has no attribute
|
||||
'weight_scale_inv'``.
|
||||
|
||||
Quantizing is not an answer, because nothing quantizes by default:
|
||||
``[inference.vllm] quantization`` is unset, which leaves vLLM to infer the
|
||||
scheme from the checkpoint. bf16 DeepSeek V4 checkpoints are a first-class
|
||||
artifact here, written by ``tools/convert_fp8_to_bf16.py``,
|
||||
``tools/convert_dcp_to_bf16.py``, and trainer exports, and they carry no
|
||||
scales for the op to find. Passing ``--quantization fp8_per_block`` does
|
||||
produce a correct ``weight_scale_inv`` and is a genuine alternative on
|
||||
hardware whose DeepGEMM build has block-scaled FP8 kernels, but it changes
|
||||
the served numerics, so it is a deployment decision rather than a fix for
|
||||
serving the bf16 weights as given.
|
||||
|
||||
Only the unquantized case is redirected: an FP8 weight keeps using vLLM's own
|
||||
kernel, so a real FP8-serialized checkpoint behaves exactly as before. The
|
||||
condition is the weight dtype rather than the presence of
|
||||
``weight_scale_inv``, so a checkpoint that *is* quantized but whose scales
|
||||
ended up in the wrong layout still fails loudly instead of being silently
|
||||
rerouted.
|
||||
|
||||
The replacement mirrors the Triton kernel's arithmetic
|
||||
(``vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py:95-105``)
|
||||
without the quantization step. The trailing ``rope_dim`` channels of each head
|
||||
carry an inverse RoPE over interleaved pairs, with ``cos_sin_cache`` holding
|
||||
``rope_dim // 2`` cosines followed by the matching sines:
|
||||
|
||||
y[even] = x[even] * cos + x[odd] * sin
|
||||
y[odd] = x[odd] * cos - x[even] * sin
|
||||
|
||||
The remaining ``nope_dim`` channels pass through. The projection is the same
|
||||
grouped contraction ``fp8_einsum`` performs, with the group axis recovered by
|
||||
reshaping: head ``g * heads_per_group + i`` belongs to group ``g`` at offset
|
||||
``i * head_dim``, matching the kernel's own
|
||||
``g = pid_gh // heads_per_group`` indexing.
|
||||
|
||||
Rotation is computed in fp32 and the contraction runs in bf16, whose CUDA
|
||||
matmuls accumulate in fp32. That is strictly more accurate than the FP8 path
|
||||
it replaces, and it avoids materializing an fp32 copy of the attention output.
|
||||
"""
|
||||
from vllm.models.deepseek_v4.nvidia import flashinfer_sparse, flashmla
|
||||
from vllm.models.deepseek_v4.nvidia.ops import o_proj as o_proj_module
|
||||
|
||||
original_o_proj = o_proj_module.deep_gemm_fp8_o_proj
|
||||
if getattr(original_o_proj, "_prime_rl_has_bf16_fallback", False):
|
||||
return
|
||||
|
||||
def _inverse_rope(o, positions, cos_sin_cache, rope_dim):
|
||||
num_tokens, num_heads, head_dim = o.shape
|
||||
half_rope = rope_dim // 2
|
||||
cos_sin = cos_sin_cache[positions].float()
|
||||
cos = cos_sin[:, :half_rope].view(num_tokens, 1, half_rope)
|
||||
sin = cos_sin[:, half_rope:].view(num_tokens, 1, half_rope)
|
||||
|
||||
rotated = o[:, :, head_dim - rope_dim :].float().reshape(num_tokens, num_heads, half_rope, 2)
|
||||
even, odd = rotated[..., 0], rotated[..., 1]
|
||||
pairs = torch.stack((even * cos + odd * sin, odd * cos - even * sin), dim=-1)
|
||||
|
||||
out = o.clone()
|
||||
out[:, :, head_dim - rope_dim :] = pairs.reshape(num_tokens, num_heads, rope_dim).to(o.dtype)
|
||||
return out
|
||||
|
||||
def _patched_o_proj(o, positions, cos_sin_cache, wo_a, wo_b, *, n_groups, heads_per_group, **kwargs):
|
||||
if wo_a.weight.dtype == torch.float8_e4m3fn:
|
||||
return original_o_proj(
|
||||
o,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
wo_a,
|
||||
wo_b,
|
||||
n_groups=n_groups,
|
||||
heads_per_group=heads_per_group,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
x = _inverse_rope(o, positions, cos_sin_cache, kwargs["rope_dim"])
|
||||
x = x.reshape(o.shape[0], n_groups, heads_per_group * o.shape[-1])
|
||||
weight = wo_a.weight.view(n_groups, kwargs["o_lora_rank"], -1)
|
||||
z = torch.einsum("tgr,gdr->tgd", x, weight)
|
||||
return wo_b(z.flatten(1))
|
||||
|
||||
_patched_o_proj._prime_rl_has_bf16_fallback = True
|
||||
o_proj_module.deep_gemm_fp8_o_proj = _patched_o_proj
|
||||
|
||||
# Both attention modules did `from ...ops.o_proj import deep_gemm_fp8_o_proj` at
|
||||
# import time, so patching the defining module alone would not reach the names
|
||||
# their `_o_proj` methods actually call.
|
||||
flashmla.deep_gemm_fp8_o_proj = _patched_o_proj
|
||||
flashinfer_sparse.deep_gemm_fp8_o_proj = _patched_o_proj
|
||||
|
||||
|
||||
def monkey_patch_nano_v3_reasoning_parser():
|
||||
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
|
||||
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
|
||||
@@ -248,57 +200,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 +658,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.
|
||||
|
||||
@@ -850,124 +689,3 @@ def monkey_patch_dp_coordinator_startup_timeout():
|
||||
zmq_addr_pipe.close()
|
||||
|
||||
DPCoordinator._wait_for_zmq_addrs = _patched_wait_for_zmq_addrs
|
||||
|
||||
|
||||
_DEEPSEEK_V4_YARN_ROPE_TYPES = frozenset({"yarn", "deepseek_yarn", "deepseek_llama_scaling"})
|
||||
|
||||
|
||||
def _deepseek_v4_rope_parameters(rope_parameters, *, compress_ratio, max_position_embeddings):
|
||||
"""Flat, single-layer rope parameters for `build_deepseek_v4_rope`.
|
||||
|
||||
Handles both on-disk schemas. The real checkpoint ships a flat legacy `rope_scaling`, which
|
||||
vLLM's config shim normalizes in place. HF's own `DeepseekV4Config` nests the parameters
|
||||
under `main`/`compress` rope-type labels instead, and so does this repo's port. vLLM's shim
|
||||
cannot read that: `is_rope_parameters_nested` only recognizes nesting by *attention* layer
|
||||
type, so transformers leaves the sub-dicts alone and injects a top-level
|
||||
`rope_type="default"` beside them. Upstream then builds unscaled RoPE for every layer and
|
||||
hands `get_rope` a cache key containing a dict, which is unhashable. Selecting the branch
|
||||
this layer wants resolves both. Upstream picks the base from `config.rope_theta` /
|
||||
`config.compress_rope_theta` on its own either way.
|
||||
"""
|
||||
rope_parameters = rope_parameters if isinstance(rope_parameters, dict) else {}
|
||||
# `compress_ratio` is already clamped to >= 1 by the caller, so <= 1 is "no compressor",
|
||||
# i.e. the reference's `else` branch. vLLM lumps the MTP layers in here too.
|
||||
is_sliding = compress_ratio <= 1
|
||||
|
||||
if any(isinstance(value, dict) for value in rope_parameters.values()):
|
||||
label = "main" if is_sliding else "compress"
|
||||
branch = rope_parameters.get(label)
|
||||
if not isinstance(branch, dict):
|
||||
raise ValueError(
|
||||
f"DeepSeek V4 rope_parameters is nested by rope type but has no {label!r} "
|
||||
f"sub-dict; found {sorted(rope_parameters)}."
|
||||
)
|
||||
parameters = dict(branch)
|
||||
else:
|
||||
parameters = dict(rope_parameters)
|
||||
|
||||
rope_type = parameters.get("rope_type", parameters.get("type", "default"))
|
||||
if is_sliding or rope_type not in _DEEPSEEK_V4_YARN_ROPE_TYPES:
|
||||
# Plain RoPE, written as YaRN with `factor=1` rather than as `rope_type="default"`.
|
||||
# The table is the same either way, since `_compute_inv_freq`'s interpolated and
|
||||
# extrapolated frequencies coincide at `factor=1` and `yarn_get_mscale` returns 1.0,
|
||||
# but `"default"` would route `get_rope` to a plain `RotaryEmbedding`, whose cache
|
||||
# follows the ambient dtype and so fails the fp32 assertion in
|
||||
# `vllm/models/deepseek_v4/common/ops/fused_inv_rope_fp8_quant.py`.
|
||||
# `original_max_position_embeddings` is widened because the cache is
|
||||
# `original_max * factor` rows and must still span the context.
|
||||
rope_type = "yarn"
|
||||
parameters["factor"] = 1
|
||||
parameters["original_max_position_embeddings"] = max_position_embeddings
|
||||
parameters["rope_type"] = rope_type
|
||||
return parameters
|
||||
|
||||
|
||||
def monkey_patch_deepseek_v4_per_layer_rope():
|
||||
"""Give each DeepSeek V4 layer the RoPE its reference implementation uses.
|
||||
|
||||
DeepSeek ships the reference inside the checkpoint we serve, at
|
||||
https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731/tree/main/inference. Its
|
||||
`model.py:481-485` picks the frequencies per layer:
|
||||
|
||||
if self.compress_ratio:
|
||||
original_seq_len, rope_theta = args.original_seq_len, args.compress_rope_theta
|
||||
else:
|
||||
# disable YaRN and use base rope_theta in pure sliding-window attention
|
||||
original_seq_len, rope_theta = 0, args.rope_theta
|
||||
|
||||
and `precompute_freqs_cis` (`model.py:206-235`) applies the NTK-by-parts ramp only when
|
||||
`original_seq_len > 0`. So a pure sliding-window layer gets plain RoPE at `rope_theta` and
|
||||
every compressed layer gets YaRN at `compress_rope_theta`. HF's `DeepseekV4Config` splits its
|
||||
`rope_parameters` into `main`/`compress` for the same reason, and so does this repo's trainer.
|
||||
|
||||
`vllm/models/deepseek_v4/common/rope.py`'s `build_deepseek_v4_rope` branches the base on
|
||||
`compress_ratio` but never the scaling, so on the real checkpoint it hands YaRN to layers 0
|
||||
and 1 as well. No config value can correct that: `rope_type` is one global field there.
|
||||
So this patch resolves `rope_parameters` per layer instead, which also gives upstream a
|
||||
schema and a dtype it can handle; see `_deepseek_v4_rope_parameters` above.
|
||||
|
||||
Measured against the reference's own frequencies, at the test's `factor=16`,
|
||||
`original_max_position_embeddings=4096` geometry, this takes the sliding layers from 5.1e-03
|
||||
max absolute error to 6e-08, the float32 residual the compressed layers already have. The
|
||||
rope tests in `tests/unit/train/models/test_deepseek_v4.py` are that comparison, over both
|
||||
on-disk schemas and both scaled and unscaled configs.
|
||||
|
||||
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.
|
||||
"""
|
||||
from vllm.models.deepseek_v4.common import rope as dsv4_rope
|
||||
|
||||
original_build = dsv4_rope.build_deepseek_v4_rope
|
||||
|
||||
if getattr(original_build, "_prime_rl_matches_deepseek_reference", False):
|
||||
return
|
||||
|
||||
def _patched_build(config, *, head_dim, rope_head_dim, max_position_embeddings, compress_ratio):
|
||||
# Swapping a copy in also spares `config.rope_parameters` upstream's in-place mutation,
|
||||
# which otherwise leaves the last-built layer's `rope_theta` on the shared config.
|
||||
original_parameters = config.rope_parameters
|
||||
config.rope_parameters = _deepseek_v4_rope_parameters(
|
||||
original_parameters,
|
||||
compress_ratio=compress_ratio,
|
||||
max_position_embeddings=max_position_embeddings,
|
||||
)
|
||||
try:
|
||||
return original_build(
|
||||
config,
|
||||
head_dim=head_dim,
|
||||
rope_head_dim=rope_head_dim,
|
||||
max_position_embeddings=max_position_embeddings,
|
||||
compress_ratio=compress_ratio,
|
||||
)
|
||||
finally:
|
||||
config.rope_parameters = original_parameters
|
||||
|
||||
_patched_build._prime_rl_matches_deepseek_reference = True
|
||||
dsv4_rope.build_deepseek_v4_rope = _patched_build
|
||||
|
||||
# `attention.py` imports the builder into its own namespace, so the defining module alone
|
||||
# would not reach the already-bound reference.
|
||||
from vllm.models.deepseek_v4 import attention as dsv4_attention
|
||||
|
||||
dsv4_attention.build_deepseek_v4_rope = _patched_build
|
||||
|
||||
@@ -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.30 — 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
|
||||
|
||||
@@ -2,24 +2,16 @@
|
||||
|
||||
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:
|
||||
prefix-cache salting, lora dispatch, multimodal content parts and features,
|
||||
prompt logprobs, priority, ``data_parallel_rank`` header routing, server-side
|
||||
``max_tokens`` defaulting, ``usage`` reporting, and expanded prompt metadata.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Everything else (request/response schema, sampling params, error handling)
|
||||
delegates to upstream so we track future vLLM changes for free.
|
||||
Everything else delegates to upstream so we track future vLLM changes for free.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,26 +19,22 @@ 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
|
||||
|
||||
|
||||
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
|
||||
# Overrides upstream's base64 ``.npy`` string form with the compact
|
||||
# ``{data, shape, start, dtype}`` object the PD router merges and the
|
||||
# renderers parse.
|
||||
# Overrides upstream's base64 ``.npy`` string form with the compact object
|
||||
# the PD router merges and the renderers parse.
|
||||
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
@@ -63,29 +51,11 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
|
||||
)
|
||||
for choice in response.choices
|
||||
]
|
||||
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
|
||||
return PrimeRlGenerateResponse(**{**response.model_dump(exclude={"choices"}), "choices": choices})
|
||||
|
||||
|
||||
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 with compact routed experts."""
|
||||
|
||||
async def serve_tokens_full_generator( # type: ignore[override]
|
||||
self,
|
||||
@@ -95,22 +65,23 @@ class PrimeRlServingTokens(ServingTokens):
|
||||
model_name: str,
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> ErrorResponse | GenerateResponse:
|
||||
# Capture routed_experts as vLLM streams request outputs, then post-process
|
||||
# the final response into our GenerateResponse subclass so the encoded
|
||||
# experts surface in the JSON.
|
||||
capture: _GenerateRoutedExpertsCapture | None = None
|
||||
routed_experts: _GenerateRoutedExpertsCapture | None = None
|
||||
if self.model_config.enable_return_routed_experts:
|
||||
capture = _GenerateRoutedExpertsCapture(
|
||||
routed_experts = _GenerateRoutedExpertsCapture(
|
||||
result_generator,
|
||||
start=request.sampling_params.routed_experts_prompt_start,
|
||||
)
|
||||
result_generator = capture
|
||||
result_generator = routed_experts
|
||||
|
||||
response = await super().serve_tokens_full_generator(
|
||||
request, result_generator, request_id, model_name, request_metadata
|
||||
request,
|
||||
result_generator,
|
||||
request_id,
|
||||
model_name,
|
||||
request_metadata,
|
||||
)
|
||||
|
||||
if capture is not None and isinstance(response, GenerateResponse):
|
||||
response = capture.post_process(response)
|
||||
if routed_experts is not None and isinstance(response, GenerateResponse):
|
||||
response = routed_experts.post_process(response)
|
||||
|
||||
return response
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -50,9 +50,12 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
``line`` numbers the episode within the stream from 1, so the last of n reads as
|
||||
n — it is what a reader sees and what addresses the episode."""
|
||||
rewards, advantages = [], []
|
||||
input_tokens = output_tokens = turns = branches = 0
|
||||
input_tokens = rec.get("num_input_tokens")
|
||||
output_tokens = rec.get("num_output_tokens")
|
||||
turns = branches = 0
|
||||
stop_condition = None
|
||||
truncated = False
|
||||
timeout = bool(rec.get("is_timeout"))
|
||||
reward_parts: dict[str, list[float]] = {}
|
||||
metric_parts: dict[str, list[float]] = {}
|
||||
timing: dict[str, float] = {}
|
||||
@@ -86,20 +89,11 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
if advantage is not None:
|
||||
advantages.append(advantage)
|
||||
for node in nodes:
|
||||
n_tokens = len(node.get("token_ids") or [])
|
||||
if node.get("sampled"):
|
||||
output_tokens += n_tokens
|
||||
else:
|
||||
input_tokens += n_tokens
|
||||
if (node.get("message") or {}).get("role") == "assistant":
|
||||
turns += 1
|
||||
stop_condition = trace.get("stop_condition", stop_condition)
|
||||
truncated = truncated or trace_truncated(trace)
|
||||
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
|
||||
for call in trace.get("calls") or []:
|
||||
usage = call.get("usage") or {}
|
||||
input_tokens += usage.get("prompt_tokens") or 0
|
||||
output_tokens += usage.get("completion_tokens") or 0
|
||||
timeout = timeout or bool(trace.get("is_timeout"))
|
||||
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
|
||||
return {
|
||||
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
|
||||
@@ -125,6 +119,7 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
"branches": branches,
|
||||
"stop_condition": stop_condition,
|
||||
"truncated": truncated,
|
||||
"timeout": timeout,
|
||||
# when the episode landed and how long it was alive: the stream's x axis,
|
||||
# and the one duration worth sorting a stream by
|
||||
"dispatch": (first_info.get("dispatch") or {}).get("time"),
|
||||
|
||||
@@ -176,31 +176,31 @@ def message_text(message: dict[str, Any]) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def trace_row(trace: dict[str, Any]) -> dict[str, Any]:
|
||||
def trace_row(record: dict[str, Any]) -> dict[str, Any]:
|
||||
"""The live table's view of one trace: phase, turns, tokens, cost, last message."""
|
||||
calls = trace.get("calls") or []
|
||||
calls = record.get("calls") or []
|
||||
usage = [call.get("usage") or {} for call in calls]
|
||||
# The newest node is usually a tool result; the assistant's latest words say more.
|
||||
last = ""
|
||||
for node in reversed(trace.get("nodes") or []):
|
||||
for node in reversed(record.get("nodes") or []):
|
||||
message = node.get("message") or {}
|
||||
if message.get("role") == "assistant" and (last := " ".join(message_text(message).split())):
|
||||
break
|
||||
costs = [u["cost"] for u in usage if u.get("cost") is not None]
|
||||
nodes = trace.get("nodes") or []
|
||||
nodes = record.get("nodes") or []
|
||||
parents = {node.get("parent") for node in nodes if node.get("parent") is not None}
|
||||
return {
|
||||
"trace": trace.get("id"),
|
||||
"agent": (trace.get("agent") or {}).get("name", "agent"),
|
||||
"stage": stage(trace),
|
||||
"trace": record.get("id"),
|
||||
"agent": (record.get("agent") or {}).get("name", "agent"),
|
||||
"stage": stage(record),
|
||||
"turns": len(calls),
|
||||
"branches": sum(1 for index in range(len(nodes)) if index not in parents),
|
||||
"input_tokens": sum(u.get("prompt_tokens") or 0 for u in usage),
|
||||
"output_tokens": sum(u.get("completion_tokens") or 0 for u in usage),
|
||||
"input_tokens": record.get("num_input_tokens"),
|
||||
"output_tokens": record.get("num_output_tokens"),
|
||||
"cost": sum(costs) if costs else None,
|
||||
"stop_condition": trace.get("stop_condition"),
|
||||
"errors": len(trace.get("errors") or []),
|
||||
"pending": len(trace.get("pending") or []),
|
||||
"stop_condition": record.get("stop_condition"),
|
||||
"errors": len(record.get("errors") or []),
|
||||
"pending": len(record.get("pending") or []),
|
||||
"last": last[:SNIPPET_CHARS],
|
||||
}
|
||||
|
||||
|
||||
+165
-20
@@ -1,17 +1,22 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import fcntl
|
||||
import os
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, Callable, Iterator
|
||||
|
||||
import orjson
|
||||
import prime_runs as pr
|
||||
from prime_cli.core.config import Config as PrimeConfig
|
||||
from prime_sandboxes import Config as PrimeConfig
|
||||
|
||||
from prime_rl.configs.monitors import PrimeEvalMonitorConfig, PrimeTrainMonitorConfig
|
||||
from prime_rl.configs.sft import SFTConfig
|
||||
from prime_rl.monitors.base import Kind, Monitor, Subset
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.pathing import get_platform_run_path
|
||||
from prime_rl.utils.utils import sanitize
|
||||
|
||||
@@ -19,6 +24,7 @@ if TYPE_CHECKING:
|
||||
import verifiers.v1 as vf
|
||||
|
||||
BASE_URL_VAR = "PRIME_API_BASE"
|
||||
EVAL_ID_VAR = "PRIME_RUNS_EVAL_ID"
|
||||
# How long finish() and the SDK's atexit crash hook let queued uploads drain. The SDK
|
||||
# default (300 s) is sized for eval sample batches; a crashed training process should
|
||||
# not linger that long, and a clean finish rarely has more than the last step queued.
|
||||
@@ -27,12 +33,18 @@ FINISH_TIMEOUT = 60.0
|
||||
|
||||
def write_platform_record(output_dir: Path, record: dict[str, Any]) -> None:
|
||||
"""Leave the run's platform identity in the run directory for the dashboard's
|
||||
"view on platform" link (atomic replace: a reader never sees a torn file)."""
|
||||
"view on platform" link (atomic replace: a reader never sees a torn file).
|
||||
The tmp file is pid-suffixed: the trainer and the online-eval process
|
||||
share the run directory, and two writers sharing one tmp path can tear
|
||||
each other's staged file mid-write."""
|
||||
path = get_platform_run_path(output_dir)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".json.tmp")
|
||||
tmp.write_bytes(orjson.dumps(record, option=orjson.OPT_INDENT_2))
|
||||
tmp.replace(path)
|
||||
tmp = path.with_suffix(f".json.tmp.{os.getpid()}")
|
||||
try:
|
||||
tmp.write_bytes(orjson.dumps(record, option=orjson.OPT_INDENT_2))
|
||||
tmp.replace(path)
|
||||
finally:
|
||||
tmp.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
|
||||
@@ -40,6 +52,73 @@ def read_platform_record(output_dir: Path) -> dict[str, Any] | None:
|
||||
return orjson.loads(path.read_bytes()) if path.is_file() else None
|
||||
|
||||
|
||||
# Bounded wait for the record lock: a blocking flock(LOCK_EX) would stall the
|
||||
# async event-loop thread for as long as the other writer holds the lock.
|
||||
RECORD_LOCK_TIMEOUT = 10.0
|
||||
RECORD_LOCK_POLL = 0.05
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _platform_record_lock(output_dir: Path) -> Iterator[None]:
|
||||
"""Cross-process read-modify-write lock for the platform record: the
|
||||
trainer and the online-eval process merge into the SAME run.json, and an
|
||||
unlocked read-modify-write lets one clobber the other's snapshot. POSIX
|
||||
flock on a sibling .lock file. The lock file is NEVER unlinked: a waiting
|
||||
writer can still hold the unlinked inode's lock while a new writer
|
||||
creates and locks a fresh file — two simultaneous "exclusive" locks and
|
||||
a lost merge; a stable lock inode is the whole guarantee. Acquisition is
|
||||
BOUNDED (`RECORD_LOCK_TIMEOUT`), retried with non-blocking flock so the
|
||||
async event-loop thread never blocks; `TimeoutError` past the bound.
|
||||
Storage errors that make locking impossible (e.g. ENOLCK) raise
|
||||
immediately instead of retrying."""
|
||||
path = get_platform_run_path(output_dir)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
lock_path = path.with_suffix(path.suffix + ".lock")
|
||||
with open(lock_path, "a+b") as lock_file:
|
||||
deadline = time.monotonic() + RECORD_LOCK_TIMEOUT
|
||||
while True:
|
||||
try:
|
||||
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
break
|
||||
except BlockingIOError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError(f"platform record lock at {lock_path} still held after {RECORD_LOCK_TIMEOUT}s")
|
||||
time.sleep(RECORD_LOCK_POLL)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def _merge_platform_record(
|
||||
output_dir: Path,
|
||||
merge: Callable[[dict[str, Any]], dict[str, Any]],
|
||||
) -> None:
|
||||
"""Best-effort locked read-modify-write of the platform record: run
|
||||
`merge` on the current record under the record lock and atomically
|
||||
replace the file. The record only backs the dashboard's "view on
|
||||
platform" link, so a lock or storage failure (TimeoutError, ENOLCK, ...)
|
||||
is logged and SKIPPED, never fatal to training; the dashboard just misses
|
||||
the link for that run."""
|
||||
try:
|
||||
with _platform_record_lock(output_dir):
|
||||
write_platform_record(output_dir, merge(read_platform_record(output_dir) or {}))
|
||||
except OSError:
|
||||
get_logger().warning(
|
||||
f"Failed to persist the platform record at {get_platform_run_path(output_dir)} "
|
||||
f"(lock or storage error); the dashboard's platform link may be missing. "
|
||||
f"Training continues."
|
||||
)
|
||||
|
||||
|
||||
def update_platform_record(output_dir: Path, update: dict[str, Any]) -> None:
|
||||
"""Best-effort locked read-modify-write of the platform record: `update`
|
||||
overlays the current record (preserving keys it doesn't set). Use for
|
||||
every writer that shares the file — a naive overwrite drops concurrent
|
||||
writers' keys."""
|
||||
_merge_platform_record(output_dir, lambda record: {**record, **update})
|
||||
|
||||
|
||||
def _base_url() -> str | None:
|
||||
"""$PRIME_API_BASE historically points at the RFT API root (``.../api/v1/rft``);
|
||||
the SDK takes the platform base URL. Unset means the SDK resolves it."""
|
||||
@@ -53,8 +132,12 @@ class PrimeTrainMonitor(Monitor):
|
||||
The run handle owns what ``TrainRun`` used to do by hand: the RFT
|
||||
lifecycle (register or attach, finalize), the per-step metrics POSTs, the
|
||||
every-10th-step Parquet sample uploads (presign -> PUT -> confirm), and
|
||||
the terminal status — a process that exits without finalizing is reported
|
||||
crashed by the SDK's atexit hook, replacing the old ``_mark_failed`` one.
|
||||
the terminal status. Delivery is BEST-EFFORT: the SDK's atexit hook
|
||||
reports a process that exits without finalizing, but an abrupt kill
|
||||
(SIGKILL, OOM, node loss) skips the hook and a lost finalize is not
|
||||
retried here — the platform owns the terminal state of attached
|
||||
($RUN_ID) and managed runs. `FINISH_TIMEOUT` bounds the queued-upload
|
||||
drain, not the SDK's finalize HTTP retries.
|
||||
|
||||
``init``/``finish`` do network I/O and run in worker threads; the log
|
||||
calls are queue puts onto the SDK's uploader thread, which owns retries
|
||||
@@ -68,9 +151,25 @@ class PrimeTrainMonitor(Monitor):
|
||||
init_kwargs: dict[str, Any]
|
||||
if run_id := os.getenv("RUN_ID"):
|
||||
# A managed launch pre-created the platform run and injected its id -
|
||||
# attach instead of registering a duplicate. The backend owns the run's
|
||||
# failure marking then; a clean finish() still marks it completed.
|
||||
# attach instead of registering a duplicate. The platform owns the
|
||||
# attached run's failure/completion marking; a clean finish() is
|
||||
# delivered best-effort and does not by itself mark it completed.
|
||||
init_kwargs = {"id": run_id}
|
||||
elif isinstance(config, SFTConfig):
|
||||
# SFT trains on a dataset, not on environments, and has no rollouts - the
|
||||
# platform run is registered without both.
|
||||
init_kwargs = dict(
|
||||
name=self.config.name,
|
||||
model=config.model.name,
|
||||
environments=[],
|
||||
training=pr.TrainingSpec(
|
||||
max_steps=config.max_steps or 0,
|
||||
batch_size=config.data.batch_size,
|
||||
seq_len=config.data.seq_len,
|
||||
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
|
||||
),
|
||||
config=config.model_dump(exclude_none=True, mode="json"),
|
||||
)
|
||||
elif config is not None:
|
||||
init_kwargs = dict(
|
||||
name=self.config.name,
|
||||
@@ -106,7 +205,15 @@ class PrimeTrainMonitor(Monitor):
|
||||
attached = " (attached via $RUN_ID)" if self.run.attached else ""
|
||||
self.logger.info(f"Logging metrics and episodes to platform run {self.run.id} ({self.run.url}){attached}")
|
||||
if output_dir is not None:
|
||||
write_platform_record(output_dir, {"kind": "train", "id": self.run.id, "url": self.run.url})
|
||||
# Merge, not overwrite: a concurrent eval process (SFT
|
||||
# online evals share the trainer's run dir) may already
|
||||
# have written its evaluations record. Off the event
|
||||
# loop: the flock retry must not stall it.
|
||||
await asyncio.to_thread(
|
||||
update_platform_record,
|
||||
output_dir,
|
||||
{"kind": "train", "id": self.run.id, "url": self.run.url},
|
||||
)
|
||||
else:
|
||||
self.logger.info(f"Platform run disabled ({pr.MODE_ENV}=disabled)")
|
||||
|
||||
@@ -160,10 +267,28 @@ class PrimeEvalMonitor(Monitor):
|
||||
# episodes do not retry the platform on every arrival
|
||||
self.runs: dict[tuple[str, int], pr.Run | None] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
self.evaluation_id = os.getenv(EVAL_ID_VAR)
|
||||
if self.evaluation_id and len(self.sources) != 1:
|
||||
raise ValueError(
|
||||
f"${EVAL_ID_VAR} names one platform evaluation, so the run needs "
|
||||
f"exactly one eval source (got {len(self.sources)})"
|
||||
)
|
||||
if self.mode == "online":
|
||||
self.logger.info("Streaming eval epochs to the Prime platform")
|
||||
if output_dir is not None:
|
||||
write_platform_record(output_dir, {"kind": "eval", "run_id": self.run_id, "evaluations": {}})
|
||||
# Merge, not overwrite: when the eval process shares the
|
||||
# trainer's run dir (SFT online evals), the train record's
|
||||
# platform link (kind/id/url) must survive; a standalone
|
||||
# eval keeps the plain eval-shaped record. Locked RMW.
|
||||
def _eval_init_update(record: dict[str, Any]) -> dict[str, Any]:
|
||||
if record.get("kind") == "train":
|
||||
record.setdefault("evaluations", {})
|
||||
record["run_id"] = self.run_id
|
||||
return record
|
||||
return {"kind": "eval", "run_id": self.run_id, "evaluations": {}}
|
||||
|
||||
# Off the event loop: the flock retry must not stall it.
|
||||
await asyncio.to_thread(_merge_platform_record, output_dir, _eval_init_update)
|
||||
else:
|
||||
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
|
||||
|
||||
@@ -172,6 +297,19 @@ class PrimeEvalMonitor(Monitor):
|
||||
|
||||
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
|
||||
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
|
||||
if self.evaluation_id:
|
||||
# A hosted launch pre-created the platform evaluation and injected its id -
|
||||
# attach instead of registering a duplicate. The backend owns its failure
|
||||
# marking then; a clean finish still completes it.
|
||||
if self.runs:
|
||||
raise RuntimeError(f"${EVAL_ID_VAR} holds one epoch, and it already took one")
|
||||
return pr.init(
|
||||
kind="eval",
|
||||
mode=self.mode,
|
||||
base_url=_base_url(),
|
||||
id=self.evaluation_id,
|
||||
finish_timeout=FINISH_TIMEOUT,
|
||||
)
|
||||
source = self.sources[env_name]
|
||||
name = self.config.name if len(self.sources) == 1 else f"{self.config.name}--{env_name}"
|
||||
return pr.init(
|
||||
@@ -206,15 +344,22 @@ class PrimeEvalMonitor(Monitor):
|
||||
return None
|
||||
self.runs[key] = run
|
||||
if run.url:
|
||||
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}")
|
||||
attached = f" (attached via ${EVAL_ID_VAR})" if run.attached else ""
|
||||
self.logger.info(f"Streaming {env_name} (Step {step}) evaluation - {run.url}{attached}")
|
||||
if self.output_dir is not None:
|
||||
record = read_platform_record(self.output_dir) or {
|
||||
"kind": "eval",
|
||||
"run_id": self.run_id,
|
||||
"evaluations": {},
|
||||
}
|
||||
record["evaluations"][env_name] = {"step": step, "id": run.id, "url": run.url}
|
||||
write_platform_record(self.output_dir, record)
|
||||
|
||||
def _eval_epoch_update(record: dict[str, Any]) -> dict[str, Any]:
|
||||
record.setdefault("kind", "eval")
|
||||
record.setdefault("run_id", self.run_id)
|
||||
record.setdefault("evaluations", {})[env_name] = {
|
||||
"step": step,
|
||||
"id": run.id,
|
||||
"url": run.url,
|
||||
}
|
||||
return record
|
||||
|
||||
# Off the event loop: the flock retry must not stall it.
|
||||
await asyncio.to_thread(_merge_platform_record, self.output_dir, _eval_epoch_update)
|
||||
return run
|
||||
|
||||
async def log_eval_plan(self, env_name: str, step: int, expected: int) -> None:
|
||||
|
||||
@@ -40,6 +40,7 @@ COMMON_METRICS = [
|
||||
COMMON_REGEXES = [
|
||||
"all/[^/]+/has_error/mean",
|
||||
"effective/[^/]+/is_truncated/mean",
|
||||
"all/[^/]+/is_timeout/mean",
|
||||
]
|
||||
|
||||
STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"]
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user