Compare commits

...
Author SHA1 Message Date
Matej SirovatkaandGitHub bad80b1a30 feat(models): add native Nemotron-H implementation (#3426)
Nemotron-H now runs as a native PyTorch module through PrimeRL Mamba-2,
shared attention, and unified MoE layers. Both Nano (regular MoE) and
Super (latent MoE) layouts are retained. Packed convolution and SSD
reset at document boundaries, and Mamba owns the full-sequence/head
redistribution required by Ulysses context parallelism. Checkpoint
conversion maps official per-expert and latent-expert weights into the
canonical runtime layout.

Updated against main (`daa72a91d`), retaining current fusion,
normalization, and CP interfaces. Restored LoRA adapter `mixer` names
and installed Mamba SSD through the GPU extra. The pinned upstream
source uses Triton without requiring the optional selective-scan CUDA
extension. Configuration guards and HF execution comparisons were
removed; existing packed-boundary tests exercise real GPU kernels.
Router compute follows `trainer.model.moe_router_dtype` (`float32` by
default, optionally `bfloat16`); the model does not force an override.

`NemotronHModel` and `NemotronHForCausalLM` both inherit
`NemotronHPreTrainedModel`, following the existing pattern used by other
architectures. The shared Nemotron base retains the config type and
architecture-specific conversion/CP hooks. Unused TP/PP plans, no-split
metadata, checkpointing flags, redundant attributes, and obsolete
`use_mamba_kernels` handling are removed. Shared model construction,
LoRA, LM-head patching, and weight-transfer code remain unchanged.
Broader removal of the model abstractions is deferred to a follow-up PR.

Garrett's config-docstring and unused-HF-attribute comments are
addressed. The broader context-parallel setter refactor and additional
gradient tests remain deferred.

## Validation

All GPU validation used Slurm-allocated Hopper H200s. Current revision
`f6d7a4033` restores the shared Nemotron base while retaining the
attribute cleanup. Ruff lint/format checks, factory
construction/dtype/inherited-hook checks, and all **15 existing model
tests** passed (Slurm job 343).

- Full unit suite: **699 passed, 11 skipped**, rerun after the nn.Module
cleanup (Slurm job 336).
- Targeted Nemotron, packed-boundary, and KL tests: **15 passed**, rerun
after removing the router override.
- H200 checks verified gate GEMM and weight-gradient dtypes for both
BF16 and FP32 router settings.
- Compiled two-GPU Mamba Ulysses: output, input-gradient, and reduced
parameter-gradient checks passed.
- Fused QKV + compiled selective activation checkpointing:
forward/backward and meta-buffer initialization passed.
- Eight two-GPU checkpoint-resume combinations: exact weights,
CPU-offloaded AdamW state, and next update across fused/unfused QKV and
FSDP shard placements.
- Official Nano checkpoint: exact key/shape conversion round trip,
**6,243 → 401 → 6,243 tensors**.
- `uv sync --all-extras --all-packages`, Ruff lint, and format checks
passed.

The 20-step run below was completed at `a7f798048` (Slurm job 339),
before restoring the original shared base. The preceding revision
`00746d6d2` was also validated: direct inheritance and the original
factory passed construction checks; compiled two-GPU Mamba and fused-QKV
selective-AC checks passed again (job 341). All 15 targeted unit tests
passed (job 340). The two-step end-to-end Nano run completed (job 342),
with mismatch KL **0.00475226** and **0.00522814**, finite gradients,
and three successful NCCL weight updates including startup. Compiled
Mamba/selective-AC and eight checkpoint-resume probes also passed again
on this code (jobs 337–338). The end-to-end run used
`nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16` on eight Slurm-allocated
H200s: four trainer GPUs with EP=4 and four inference replicas. The
native trainer used FlashAttention 3, compilation, selective activation
checkpointing, and NCCL weight updates. Reverse-text used batch size 64,
group size 8, sequence length 1024, and maximum completion length 512.
Optimization and reduction dtypes retained their defaults.

Launched with `uv run rl @ rl-module-cleanup.toml`. The config sets
`trainer.env_vars.TRITON_CACHE_DIR` to node-local `/tmp` to avoid
shared-home artifact read failures; no diagnostic hooks are present in
this run.

The automated review requests a math-environment table. This run uses
reverse-text and does not satisfy that environment-specific requirement:
the current math task requires a policy-aware container runtime, which
is unavailable on the validation nodes.

**20/20 steps completed**, with **21 successful NCCL weight reloads**
(startup plus every update). Mismatch KL: mean **0.0059826873**, maximum
**0.0076148757**, final **0.0071559078**. All step KL values and
gradient norms were finite. Super latent behavior was exercised by small
model tests and distributed probes; no full-size Super run was
performed.

| Step | Mean mismatch KL |
| ---: | ---: |
| 1 | 0.0061262716 |
| 2 | 0.0044362689 |
| 3 | 0.0046579577 |
| 4 | 0.0057872585 |
| 5 | 0.0052399668 |
| 6 | 0.0067561148 |
| 7 | 0.0045683677 |
| 8 | 0.0047115656 |
| 9 | 0.0063753380 |
| 10 | 0.0065832101 |
| 11 | 0.0062584030 |
| 12 | 0.0072330278 |
| 13 | 0.0066353143 |
| 14 | 0.0060227909 |
| 15 | 0.0053012762 |
| 16 | 0.0066529727 |
| 17 | 0.0055223401 |
| 18 | 0.0060145170 |
| 19 | 0.0076148757 |
| 20 | 0.0071559078 |

CI at `a7f798048`: Ruff, slim install, and CodeQL passed; remaining jobs
were running or queued at the last check. On the previous commit
(`a60d27578`): all 15 Nemotron tests passed. The GPU unit job had five
failures in unchanged DeepSeek-V4 tests (packed-batch assertions and
unsupported FP8 kernels on that runner); CPU unit tests, Ruff, slim
install, and CodeQL passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large rewrite of a hybrid MoE/Mamba training path, checkpoint layout,
and distributed Mamba CP, with dependency pins that affect the whole GPU
stack.
> 
> **Overview**
> Replaces the Hugging Face–wrapped Nemotron-H stack with a **native
hybrid model**: one `NemotronHDecoderLayer` per block type (Mamba,
attention, MoE), a first-party **`NemotronHMamba2`** that uses FLA
packed causal conv plus **`mamba_ssm` Triton SSD**, and Ulysses CP via
**sequence↔head all-to-all inside the Mamba module** (the shared
`cp_mamba` helper is deleted).
> 
> **Checkpoint and config:** `NemotronHConfig` is realigned to current
HF field names and `layer_types`; conversion is **explicit per layer
type** instead of inferring from key presence (the old router-bias
`MapValue` shift is gone). Install/docs now pull **`mamba-ssm` from a
pinned git rev** through the **gpu** extra, with **`tilelang==0.1.12`**
pinned for vLLM compatibility; trainer init no longer disables
`use_mamba_kernels` or monkey-patches HF Mamba.
> 
> Tests drop HF parity checks and instead exercise native packed
boundaries, CP wiring on `NemotronHMamba2`, and existing KL/conversion
coverage.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f6d7a403332bd90d26efa3dcb4c8358a5e95f92e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-10 14:04:38 +02:00
samsjaandGitHub aa3a6522b4 feat(algo): add debug advantage algorithm (#3521)
## What

Adds a `debug` algorithm (`[orchestrator.algo] type = "debug"`) that
assigns the same constant advantage (default `advantage = 1.0`) to every
sampled token of every clean trainable trace, ignoring rewards entirely.

## Why

Purely a debugging feature for infra work: with constant advantages
every admitted rollout is trainable and every action token carries
gradient signal, so the full RL path — advantage transport, importance
ratios, trust region, trainer loss, optimizer, weight update — can be
exercised regardless of the reward function (e.g. to rule out "all-zero
advantages / nothing trainable" when smoke-testing a pipeline). The
config validator rejects `advantage = 0`, the exact failure this tool
exists to rule out.

## How

Follows the existing "a new credit-assignment scheme is a new named
class" pattern:

- `DebugAlgoConfig` in `prime_rl.configs.algorithm` (discriminated-union
member, `action_loss_type = "rl"`, nonzero-advantage validator)
- `DebugAlgorithm` (`score_episode` — the signal is rollout-local, no
group-relative work needed) registered in `ALGORITHM_CLASSES`

Intentionally not documented in `docs/` or the skills — it is a debug
tool, and the code docstrings are the reference.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Opt-in debug algorithm only; no changes to existing algo behavior or
production defaults.
> 
> **Overview**
> Adds a **`debug`** training algorithm for pipeline smoke tests: set
`[orchestrator.algo] type = "debug"` to assign the same constant
per-token advantage (default **1.0**) on every clean trainable trace,
**ignoring rewards**, so admitted rollouts always produce RL gradient
through the full stack (advantage transport, ratios, trust region,
trainer, optimizer).
> 
> **Config:** `DebugAlgoConfig` joins the `AlgoConfig` discriminated
union with `action_loss_type = "rl"` and a validator that rejects
`advantage = 0` (the “nothing trainable” case this mode is meant to rule
out). **Runtime:** `DebugAlgorithm` implements `score_episode` via
`iter_trainable_traces` + `assign_advantages`, registered in
`ALGORITHM_CLASSES` like other algorithms. Docstrings mark it as
infra-only—not a real training signal.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ce6ca60585b3f259780492b892157b356b0569cf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-10 00:19:14 +02:00
3f0c2e3b5a feat(trainer): select MoE compute by layer (#3518)
Select the model layers that use the configured MoE compute backend with
`model.moe.compute.apply_to`:

- `"all"` (default): all routed-expert groups.
- `"85%"`: the first 85% of model layers, rounded down; 48 layers
selects indices 0–39.
- `[0, 1, 2, 3]`: explicit zero-based model layer indices. `[]` selects
none.

Non-MoE blocks in hybrid models count toward indices and percentages.
Other expert groups use BF16 compute and transport while retaining the
configured dispatch backend and expert parallelism. Out-of-range indices
and invalid percentages fail early. Dense linear quantization is
unchanged.

```toml
[trainer.model.moe.compute]
type = "mxfp8"
apply_to = "85%"
```

BF16, DeepGEMM FP8 and MXFP8 configs inherit the common selector. NVFP4
inherits it in #3511. Inference precision remains configured separately.

First PR in the stack: main → #3518 → #3515 (filter flag) → #3513 (vLLM
upgrade) → #3511 (NVFP4).

Validation: 62 focused MoE/config tests passed on this main-based
branch, including all three forms through CLI/config round trips,
percentage rounding, hybrid-layer indexing, and invalid indices. Ruff
lint/format and whitespace checks passed. GB200 mixed DeepGEMM-FP8/BF16
forward/backward passed with an exact BF16 fallback output and unchanged
parameters/checkpoint keys. EP2 with layer-index selection verified
MXFP8 transport for the selected group, BF16 transport for the excluded
group, both forwards, and BF16 fallback backward. MXFP8 backward has a
separately reproduced CuTe TMA-alignment compiler failure in the
existing kernel; that kernel is unchanged here.

<sub>Stack created with <a
href="https://github.com/github/gh-stack">GitHub Stacks CLI</a> • <a
href="https://gh.io/stacks-feedback">Give Feedback 💬</a></sub>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Per-layer MoE precision and transport wiring affects forward/backward
numerics and expert-parallel paths; misaligned trainer vs inference
precision could skew RL logprobs if rollout config is not matched
manually.
> 
> **Overview**
> Adds **`model.moe.compute.apply_to`** so BF16, DeepGEMM FP8, and MXFP8
routed-expert backends can target **all layers**, a **leading
percentage** (e.g. `"85%"`, rounded down), or **explicit zero-based
layer indices** (including `[]` for none). Shared
**`MoEComputeConfigBase`** validates inputs and **`resolve_layers`**
maps selections to layer sets; out-of-range indices fail at resolve
time.
> 
> **`configure_moe_runtime`** maps selection onto language-model
**`layers`** (including VLM via **`get_language_model`**): selected MoE
modules get the configured grouped GEMM; others **fall back to BF16**
compute and matching token dispatch alignment. **MXFP8 torch transport**
is used only when that layer’s grouped GEMM is actually
**`MXFP8GroupedGemm`**, so excluded layers no longer take MXFP8
all-to-all when compute is partial. Startup logging reports selected vs
total MoE layers.
> 
> Docs describe hybrid-layer counting, dense-quant independence, and RL
rollout/inference precision alignment. Unit tests cover config/CLI
round-trips and BF16 fallback without loading MXFP8 backends when
nothing is selected.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f367d4866ddcc0debd53faebe8944f096eb3ba44. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: matejsirovatka <matejsirovatka@users.noreply.github.com>
2026-09-10 00:11:35 +02:00
6b0d9e504b fix(deepseek_v4): hardware guards for unrunnable gpu CI tests (#3512)
Custom deepseek v4 flash attention requires more SMEM than some gpus
(like the current CI runners) have. Skip the tests in those cases.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 11:06:46 -04:00
751a235af8 perf(deepseek_v4): score the Lightning Indexer with the fused FP8 kernel (#3504)
Second of three stacked PRs, builds on #3479.

Scores the DeepSeek V4 Lightning Indexer with `fp8_indexer`, the fused
Triton kernel GLM DSA already runs, dropping the eager float32 `(batch,
seq_len, heads, entries)` intermediate.

The indexer now rejects a batch larger than 1 instead of looping over
the batch axis: the entry ranges it hands the kernel are built from
sample 0's causal thresholds, so every other sample would have been
scored against the wrong range.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 10:51:22 -04:00
Matej SirovatkaandGitHub daa72a91d8 feat(models): add native GPT-OSS implementation (#3424)
## Summary

Replace the Transformers/hub-kernel GPT-OSS runtime with a Prime-owned
model, FA4 attention with learned sinks, and canonical grouped experts.
BF16 GPT-OSS checkpoints load through lossless expert-layout conversion;
inference policy updates route prepared expert and sink tensors through
vLLM's registered parameter loaders.

This branch targets `main` and supports runtime QKV and gate/up fusions,
canonical checkpointing, and the CP capability interface. Main's
dependency pins are retained; the obsolete `gpt-oss` hub-kernel extra is
removed.

## Supported configuration

- `model.impl = "auto"` selects native GPT-OSS. Validated checkpoint:
`unsloth/gpt-oss-20b-BF16`. Original MXFP4 checkpoint loading is outside
this change.
- Direct FA4 calls preserve learned sinks, sliding/full attention, and
packed-document boundaries. FA4 explicitly returns `(output, lse)`;
FA2/FA3 default calls return a tensor.
- Ring and Ulysses CP preserve sink gradients; common expert parallelism
and runtime fusions are supported.
- Hopper is the validation target. The vLLM loader patch handles
prepared expert and sink tensors with the pinned vLLM.

GPT-OSS and shared FA4 attention no longer use `torch._dynamo.disable`.
There is no forwarding wrapper around the native FA4 function. Native
configuration/input guards and HF GPT-OSS execution-comparison tests are
removed; checkpoint conversion and CP checks remain. There are no
example or skill changes relative to main.

## Context-parallel attention

Every CP helper replaces an attention compute method. GPT-OSS's ring
adapter is separate because the shared ring custom operators have no
learned-sink input or sink-gradient output. It uses differentiable K/V
gathers and FA4 to preserve those gradients. Its Ulysses adapter passes
the model's FA4 function, scale, and sinks into the shared sink-aware
Ulysses implementation. That thin adapter is an organizational choice;
directly assigning the existing generic closure would omit these
arguments.

## Validation

- H200 full unit suite after cleanup: **701 passed, 11 skipped**. After
the final direct-FA4 assignment, the targeted checkpoint roundtrip and
compiled attention/CP checks passed again.
- Cold `torch.compile(fullgraph=False)` forward/backward and
eager-output agreement passed for GPT-OSS and shared FA2/FA3/FA4
attention.
- Two-GPU eager and compiled GPT-OSS ring/Ulysses output and
Q/K/V/sink-gradient checks passed. Compiled shared FA4 Ulysses output
and Q/K/V gradients passed on both ranks.
- The CP tests reuse one process group across cases, avoiding
teardown/reinitialization reconnect failures.
- Earlier integration validation covered eight checkpoint/resume
combinations and a real 20B export matching all 411 checkpoint
keys/shapes and sampled tensor values.
- Ruff lint/format and git whitespace checks passed.

## Final 20-step H200 RL run

After all code changes, `uv run rl @ config.toml` completed through the
standard Slurm launcher on eight H200 GPUs: four trainer and four
inference GPUs, `unsloth/gpt-oss-20b-BF16`, reverse-text, batch 64,
group 8, sequence length 1024, completion budget 512, EP=4, QKV/gate-up
fusions, compilation, selective activation checkpointing, and NCCL
policy reloads. Rollout concurrency starts at 32 and is capped at 64.

Slurm job **326 completed with exit code 0**, in 24m42s. All **20
optimizer steps** completed and inference acknowledged **21 successful
reloads** (startup plus 20 updates). Rollout errors were 0%. The short
completion budget truncates most reasoning; this validates numerical
consistency and pipeline operation.

The table reports `mismatch_kl/all/mean` on commit `c3fe30c29`.

Completed steps: 20
Mean of step means: 0.0014423477
Min: 0.0007825278
Max: 0.0027635854

| Step | Mismatch KL |
| ---: | ---: |
| 1 | 0.0007825278 |
| 2 | 0.0008648058 |
| 3 | 0.0010610037 |
| 4 | 0.0015761884 |
| 5 | 0.0012348450 |
| 6 | 0.0023151361 |
| 7 | 0.0016181732 |
| 8 | 0.0012400812 |
| 9 | 0.0010534789 |
| 10 | 0.0017238446 |
| 11 | 0.0027635854 |
| 12 | 0.0023905332 |
| 13 | 0.0015134896 |
| 14 | 0.0014993388 |
| 15 | 0.0011815884 |
| 16 | 0.0012801469 |
| 17 | 0.0012795344 |
| 18 | 0.0012338012 |
| 19 | 0.0011749482 |
| 20 | 0.0010599031 |

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core training attention/MoE and vLLM weight loading for a new
architecture; mistakes could affect numerics or checkpoint load, though
conversion and CP tests mitigate this.
> 
> **Overview**
> Replaces the Transformers / hub-kernel GPT-OSS path with a
**Prime-owned** `gpt_oss` stack: custom config, packed-batch forward
(`seq_lens`), grouped MoE, and **FlashAttention 4** attention with
**learnable sink** parameters wired through ring and Ulysses context
parallelism (including sink gradients).
> 
> **Training/runtime:** Drops Hopper-only checks and explicit hub-kernel
enablement; hub kernels stay disabled globally. Shared FA4 call sites
now handle `(output, lse)` returns and drop `torch._dynamo.disable`
wrappers. Ulysses varlen attention gains optional `learnable_sink`
sharding.
> 
> **Inference:** Registers a vLLM startup patch to load prepared BF16
MoE expert and **`.sinks`** tensors via weight loaders until upstream
vLLM catches up.
> 
> **Packaging/docs:** Removes the `gpt-oss` optional extra (`kernels`
dependency); docs point at BF16 checkpoints (e.g.
`unsloth/gpt-oss-20b-BF16`) and SM90/SM100+ for FA4 sinks. Tests add
2-GPU ring/Ulysses CP checks and drop HF MoE parity.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c3fe30c2956c167563821a0542ec587069704b00. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-09 16:33:45 +02:00
dad79d1ce8 feat(inference): add Dynamo admin plane integration (#3491)
## Overview

Add a minimal Dynamo admin-plane integration for Prime-RL weight
synchronization. Prime-RL discovers and pins one Dynamo inference
worker, routes administrative operations directly to it, propagates
configured authentication to the worker client, and uses the existing
custom NCCL sender and receiver for policy updates.

This PR is intentionally limited to a singleton text-model RL training
loop. It excludes managed Dynamo process launch, multi-worker or
multi-rank topology, multimodal training, routed-expert transfer, and
LoRA. Managed process launch is the stacked follow-up #3493; the
unrelated `skip_gather` compatibility fix remains isolated in #3492.

## Changes

- Add optional Linux-only Dynamo dependency support and compatibility
metadata for the upstream Pydantic bound.
- Add `orchestrator.model.client.dynamo` with `enabled` and optional
`discovery_url`.
- Derive an omitted discovery URL from the OpenAI base URL by stripping
its path and incrementing its explicit non-default port.
- Discover exactly one model-matching worker and pin its instance
identity and private admin origin.
- Propagate static headers, environment-derived headers, and a non-empty
API-key bearer token to Dynamo discovery and worker administration.
- Initialize Prime-RL's existing NCCL communicator through Dynamo
collective RPC and transfer policy weights without adding another
transport protocol.
- Preserve existing filesystem and NIXL behavior outside the
Dynamo-specific NCCL path.
- Add `examples/basic/dynamo/rl.toml` and a runnable README with
loopback-safe commands, endpoint checks, GPU isolation, trusted-network
guidance, and the Prime-RL command.
- Keep the `uv.lock` conflict resolution isolated from upstream source
changes.

## Validation

### Local

- `uv lock --check` — passed at functional source head
`55d8f2f658b543aea08d13b4ce53bb6ec91ab82d`.
- `uv run --frozen pytest -q tests/unit/inference/test_dynamo.py` — 15
passed.
- Ruff lint and format checks — passed for all five changed Python
files.
- `git diff --check origin/main...HEAD` — passed.
- Signed conflict-resolution commit
`dc1e7910977e8a847d6081ceb204f779081ebe36` changes only `uv.lock` (39
additions, 2 deletions in that commit).
- `git merge-tree --write-tree HEAD origin/main` — passed without
conflicts at current head.
- The current `uv.lock` PR delta against main is 139 additions and 17
deletions.

### Kubernetes

- The exact functional source head
`1cdcaff56972aab55ed1456a2829555052285099`, with the separate #3492
`skip_gather` compatibility overlay required by the installed vLLM-RS
build, completed a five-step Qwen3-0.6B Math run in `bis-rl-3` over SSH.
- Trainer and orchestrator completed steps 1 through 5; vLLM received
startup policy `v0` and updates `v1` through `v5`; every step reported
0% rollout errors and 0% truncation; post-update generation succeeded;
the runner exited zero.
- The subsequent authentication change at
`dec4f82b66c3a231f56f8b759c1c4dcb20685a8b` was also exercised in the
stacked #3493 managed-Dynamo five-step run, which completed 1,001
generation requests and policy updates `v0` through `v5`.
- Current-head commits after that runtime validation modify only
`uv.lock` and one trailing blank line; no production behavior changed.

## Operational notes

- Keep Dynamo discovery and worker administration on a trusted loopback
or private network.
- The Dynamo frontend must expose the native generate route with
`DYN_VLLM_ENABLE_INFERENCE_V1_GENERATE=1`.
- The included vLLM-RS recipe uses `top_k = 0` because that backend
rejects Verifiers' default `top_k = -1`.

---------

Co-authored-by: sami jaghouar <sami@primeintellect.ai>
2026-09-08 21:03:02 -07:00
dd2dd5461b prime-runs (#3459)
Replaces `monitors/prime.py`'s`TrainRun` with `pr.init(kind="train",
...)`.

## What moved where

| was in prime-rl | now |
| --- | --- |
| `TrainRun.create` / `$RUN_ID` attach | `pr.init(kind="train", model=,
environments=, training=pr.TrainingSpec(...), config=, ...)` /
`pr.init(kind="train", id=$RUN_ID)` |
| `TrainRun.log_metrics` (fire-and-forget task per POST) |
`run.log_metrics(values, step=)` — a queue put; the SDK's uploader owns
retries, `Retry-After`, backpressure |
| `episodes_to_parquet_bytes` + `SAMPLE_SCHEMA` + presign→PUT→confirm |
`prime_runs.projection` + the SDK's training samples sink (same schema,
same flow) |
| the `step % 10` cadence in `log_episodes` | the sink
(`step_interval=10`), keyed on each episode's `run.work.step` — the
`TrainRunInfo` the dispatcher stamps |
| `finalize` → `POST /finalize`, fallback `set_status` | `run.finish()`
— drain, then an idempotent finalize; 409 on the failure path is treated
as already-closed |
| atexit `_mark_failed` | the SDK's atexit hook reports **crashed**
(with a message); an attached run's failure marking stays with the
launcher, as before |

The `kind == "train" and subset == "effective"` cohort filter stays
here. The monitor keeps `sanitize()` so dropped non-finite metric paths
are still named in the log (the SDK would drop them silently).
`$PRIME_API_BASE` still works — it historically points at
`…/api/v1/rft`, so the monitor strips what the SDK re-adds.

## Decisions

- **Step keying.** The samples sink keys each episode by the step it was
*dispatched* at (`run.work.step`), not the batch step; the platform
keeps one Parquet object per upload and the viewer unions every object
under a step, so an off-policy episode landing in a later batch adds an
object rather than replacing one, and each object numbers its
`sample_id`s in its own range (SDK side, `aba26790`). "Step N" in the
sample viewer therefore means dispatched at N, while the metrics at N
describe the batch trained at N.
- **Run identity.** The orchestrator keeps the launcher's `PRL_RUN_ID`
(or a local uuid) as the run identity for episodes, W&B and sandbox
labels, exactly as on `main`. The SDK keys every uploaded record to the
platform run (`run.id` / `run.type` on the uploaded copy, `work` kept),
so Prime Traces documents carry the id the dashboard shows without the
orchestrator learning it.

## Dependency

`prime-runs[train]>=0.1.1` from PyPI
([0.1.1](https://pypi.org/project/prime-runs/0.1.1/),
PrimeIntellect-ai/prime#896); the lock carries `prime-runs 0.1.1` +
`prime-traces 0.0.3` from the registry. The monitor's own unit tests run
in CI; there is no GPU-free end-to-end path for the training seam, so
the RFT contract was verified by reading the platform's `/api/v1/rft/*`
and `/api/internal/rft/*` routes against the SDK's calls.

## Hosted managed runs

Since PrimeIntellect-ai/platform#4885, hosted managed runs start the
orchestrator with `--monitors.prime.name`, `RUN_ID`, a per-run token in
`PRIME_API_KEY` and `PRIME_API_BASE=<platform>/api/internal/rft`.
prime-runs 0.1.1 (PrimeIntellect-ai/prime#895) addresses that internal
router and sends the run's token in `x-api-key`, the header it
authenticates on; 0.1.0 only spoke `/api/v1` with a Bearer header and
would have left those runs silently unmonitored. This monitor's
`_base_url()` passes `$PRIME_API_BASE` minus the trailing `/rft`, which
0.1.1 accepts, so the floor bump is the whole change. External runs
(prime-rl launched outside the platform) were never affected.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01Fk5fBAAaTiPfJ5UpNyqxXR


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how training runs register and upload to the Prime platform
(including hosted `$RUN_ID` / internal RFT paths); misconfiguration now
fails launch instead of silently skipping monitoring, but orchestrator
run identity for W&B stays unchanged.
> 
> **Overview**
> **Replaces** the in-repo `TrainRun` HTTP/Parquet implementation in
`PrimeMonitor` with **`prime-runs[train]>=0.1.1`**, so run registration
(or `$RUN_ID` attach), metrics streaming, episode sample uploads,
finalize, and crash reporting are owned by the SDK uploader instead of
custom `httpx` + fire-and-forget tasks.
> 
> The monitor layer is now a thin adapter: `pr.init(kind="train", …)` on
startup, `run.log_metrics` / `run.log_episodes` via `asyncio.to_thread`,
and `run.finish()` with a **60s** drain timeout. Local behavior kept
where it matters: non-finite metrics are still **sanitized with named
warnings**, only **train / effective** episodes are forwarded, and
**`$PRIME_API_BASE`** is normalized for the SDK. Episode
**every-10th-step** upload cadence moves into the SDK sink (keyed on
dispatch step on `run.work`).
> 
> **Docs** in `training.md` describe the SDK, team allowlisting,
**`PRIME_RUNS_MODE=disabled`**, and **`RUN_ID`** attach.
**Lock/pyproject** add `prime-runs` and transitive **`prime-traces`**,
with fast-track resolver entries.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
aed9bbfb509367d7cad1fb8cd869c2b835fa8860. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-08 20:06:21 -07:00
cea63f9ef3 feat(deepseek_v4): sparse attention kernels (#3479)
Adds a TileLang implementation of the flash-attention style kernel for
DS V4. Based on the similar kernel used for GLM. The kernel is wired
through the DS V4 model and the attention arguments are refactored to
naturally adapt to the shape expected by the efficient kernel (e.g. no
more `attention_mask` realization).

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 21:11:30 -04:00
6a360c3029 feat(trainer): add runtime gate/up and qkv fusions (#3451)
## Summary

Adds runtime parameter fusions, on by default: `model.fusions` packs
parameters that are always computed together into one tensor, turning
several GEMMs into one. Fusions are runtime-only — checkpoints keep the
canonical parameter names and shapes, so a run can enable or disable one
at any point and still load its own checkpoints.

```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"]   # default; [] disables
raise_on_fail = false          # default: a fusion no module supports logs a warning
shard_fused_on_dim1 = false    # default; experimental zero-copy checkpointing, see Notes
```

- **`gate_up`** — each gated MoE expert's `gate_proj` and `up_proj`
become one `[num_experts, 2 * intermediate_size, hidden_size]` weight.
The forward is a single grouped GEMM whose transpose and chunk are
views; there is no weight reshape.
- **`qkv`** — an attention layer's `q_proj`, `k_proj` and `v_proj` (and
their biases) become one `nn.Linear`. `FlashAttention.project_qkv` is
shared with `LagunaFlashAttention` so both support it.

## Review fixes and verification (2026-09-08)

Review found and fixed three previously unchecked checkpoint cases:

- **Exports and model-only resume:** DCP returns `{}` when no optimizers
are supplied. Both fusion optimizer-state translators now preserve that
empty dictionary instead of raising `KeyError: 'state'`.
- **AdamW resume with optimizer-state CPU offload:** packed parameters
restored their moments but lost scalar state, including AdamW's step
counter. The write-back now restores scalar tensors and non-tensor state
as well as packed moments.
- **Full CPU offload checkpoint save:** splitting packed CPU optimizer
tensors requires CPU collectives. Both training entrypoints now enable
Gloo alongside NCCL when full offload is enabled.

Verified on H200s through Slurm job **232**:

- The complete existing unit suite and Ruff checks passed.
- All **32 distributed checkpoint combinations** passed: AdamW/Muon,
fused/unfused save and load, default/dimension-1 sharding, and
optimizer-state CPU offload on/off. Canonical weights, optimizer state,
and the next update with identical gradients were bitwise exact.
- Full CPU offload completed model-only resume/save and optimizer
resume/save. All **311 model tensors** were exact after model-only
resume; **931 model/master/step tensors** were checked across optimizer
resume, with unchanged weights and correctly incremented counters.
- Expert outputs and matrix-weight gradients, and QKV projections
with/without bias, were exact. BF16 input-gradient relative differences
were about 0.29%; bias-reduction variation also occurred in repeated
unfused calculations.
- All **11 RL/SFT training, resume, and export checks** passed (6 SFT, 5
RL). BF16 and FP8 exports reload in HF, and direct DCP-to-FP8 matches
chained conversion byte-for-byte. RL completed 20 steps with final
reward **0.8362** and passed its mismatch-KL checks.

The dashboard browser checks cannot install OS dependencies on this
cluster because they require sudo. The prior A6000 benchmark CI job was
cancelled without executing any steps; its hardware-specific baseline
was not validated on H200. Blackwell-only MXFP8 was not exercised.

Verification artifacts: `/home/matej/prime-rl-verify/pr3451-20260908/`.
This review changes only the fusion helpers and RL/SFT distributed
initialization; it adds no tests or skill changes.

## Design

A fusion is a function that replaces some of a module's parameters with
one `PackedParameterSpec`, which owns the split sizes, the packing
dimension, and the canonical names it stands in for. Everything else
falls out of that description, so a new fusion adds no machinery:

- **Checkpoints** — state-dict hooks registered alongside the packing
swap the packed entry for its canonical entries on the way out and back
on the way in. The canonical entries are views of the packed storage
when the packing dimension is unsharded (`gate_up`: experts shard on dim
0, pack on dim 1); a DTensor sharded along the packing dimension (`qkv`:
FSDP shards dim 0) is unsharded by the split, so those entries are
replicated copies. Anything that loads into the state dict in place
therefore packs the loaded entries back explicitly
(`write_back_loaded_packed_parameters` after the HF weight load,
`write_back_loaded_packed_optimizer_state` /
`join_loaded_optimizer_state_for_runtime` on resume). DCP therefore
writes `gate_proj`/`up_proj` and `q_proj`/`k_proj`/`v_proj` and never
sees the packed layout. The optimizer has no equivalent hook (its
`state_dict()` hooks fire while state is still keyed by integer param
ids, before DCP maps them to FQNs), so the same translation is applied
explicitly around `get_state_dict` in `AppState`.
- **Muon** — `PackedParameterSpec.muon_matrix_partitions` yields the
split sizes when the packing is on the output dimension. Those go to
Dion's new `matrix_partitions` argument, which orthogonalizes each
logical matrix separately on the one physical parameter, with a
per-partition learning-rate adjustment. A packed parameter therefore
trains exactly as the parameters it replaces would — including
per-projection scaling for grouped-query attention — while keeping a
single momentum tensor. Uses the merged matrix-partition support in the
pinned `samsja/dion@99e5f7e` (samsja/dion#3).

Modules advertise fusions through `supported_fusions`; requesting one
that no module supports logs a warning, or fails at startup with
`raise_on_fail = true`. Fusions are skipped when LoRA is enabled, since
it targets the unfused projections.

## Performance

Qwen3-30B-A3B, 8×H200, EP=8, `seq_len=8192`, torch EP dispatch,
selective AC, compile, no offload. Mean throughput over steps 3–6:

| precision | unfused | fused | |
|---|---|---|---|
| BF16 | 37636 tok/s (MFU 13.3%) | 37352 tok/s (MFU 13.2%) | −0.8% |
| FP8 (`quantization.type=fp8` + `moe.compute.type=deepgemm_fp8`) |
30594 tok/s (MFU 10.8%) | 34062 tok/s (MFU 12.0%) | **+11.3%** |

BF16 is unchanged, as expected: the separate GEMMs already read the same
activation, so there is nothing to save. The gain is under FP8, where
each GEMM quantizes its activation independently — unfused casts the
same tensor 3× for q/k/v and 2× for gate/up, fused casts it once. Peak
memory is unchanged (101.8 → 102.0 GiB).

## Validation

Correctness, on GPU:

- Forward output and all weight gradients of the fused grouped experts
are **bitwise identical** to the unfused module; the packed q/k/v
projections are bitwise identical to the separate ones. Only the MoE
input gradient differs (max abs `1.5e-5` on a `2.4e-3` scale), by one
bf16 accumulation rounding from doing one `[T, 2I]` dgrad instead of two
`[T, I]`.
- Muon updates on a packed parameter are **bitwise identical** to
updating the parameters it replaces, over multiple steps, for both
fusions.
- All four fused/unfused optimizer checkpoint round trips are exact,
including the next optimizer update after each. For `gate_up` the
checkpoint entries alias the packed storage; for `qkv` under FSDP they
are replicated copies of the q/k/v weights and their optimizer state,
materialized transiently on every rank at load and checkpoint time (~1
GB bf16 weights + ~2 GB fp32 Muon momentum for Qwen3-30B-A3B).
`shard_fused_on_dim1 = true` (experimental, default off) shards fused
2-D parameters along dim 1 via FSDP2's `shard_placement_fn`, so the
split stays a local view: the q/k/v weight entries alias the packed
storage and `model.state_dict()` holds 0.1 MiB extra instead of 72 MiB
on the mini model (0 / 144 → 72 / 72 weight entries aliasing; biases
stay copies, having no second dimension). It is not a correctness fix on
its own — biases would still load as zero and the optimizer-offload
resume path replaces its state tensors after the template is built, so
the explicit write-back stays in place with the flag on or off.
Constraints: `hidden_size % dp_shard == 0` (FSDP2 raises otherwise) and
an extra chunk-cat per all-gather of dim-1 shards. #3486 measured the
placement alone and is closed in favour of this flag.
- DCP metadata for a fused EP=2 checkpoint contains 94 `gate_proj` and
94 `up_proj` entries and zero `gate_up_proj` entries.

End to end on SLURM (2 GPUs, EP=2, compiled, Muon, both fusions unless
noted):

| run | result |
|---|---|
| BF16 fake-data training + checkpoint save | ✅ |
| resume: fused ckpt → fused runtime | ✅ |
| resume: fused ckpt → **unfused** runtime | ✅ |
| resume: unfused ckpt → **fused** runtime | ✅ |
| optimizer-state CPU offload, save + resume | ✅ |
| DeepGEMM FP8 expert compute | ✅ |
| pretrained `mini-glm-moe` RL run with vLLM weight reload | ✅ mismatch
KL `0.0001` at both steps |

Plus `ruff format`/`ruff check`, and `pytest tests/unit/train/models
tests/unit/test_configs.py` (`215 passed, 3 skipped`), including a new
`tests/unit/train/models/test_fusions.py`.

## Notes

- `pyproject.toml` and `uv.lock` pin `samsja/dion@99e5f7e`, which
contains the merged matrix-partition support from samsja/dion#3.

## Verification on merged `main` (2026-09-04)

Branch merged with `main` (no conflicts) and re-verified on 8×H200 nodes
via SLURM. `ruff check`/`ruff format --check` clean; `pytest tests/unit
-m "not gpu"`: 536 passed, 1 skipped; `pytest tests/unit -m gpu`: 81
passed, 8 skipped.

**Numerics against an fp32 reference** (`samsja/mini-glm-moe`, single
GPU, no FSDP, 512 random tokens; reference is HF `Glm4MoeForCausalLM` in
fp32 eager). Whole-model outputs are not bitwise identical between fused
and unfused bf16 — the packed GEMMs take a different accumulation path —
but the fused model is exactly as close to fp32 as the unfused one:

| model (bf16) | logits mean abs diff vs fp32 | KL(fp32 ‖ model) | grad
rel. err vs fp32: q/k/v · experts gate/up · rest |
|---|---|---|---|
| unfused | 7.64e-3 | 3.97e-5 | 4.52e-2 · 4.96e-2 · 4.48e-2 |
| fused `qkv` | 7.64e-3 | 3.82e-5 | 4.14e-2 · 4.81e-2 · 4.12e-2 |
| fused `gate_up` | 7.22e-3 | 3.83e-5 | 4.52e-2 · 5.19e-2 · 4.51e-2 |
| fused both | 7.27e-3 | 3.88e-5 | 4.31e-2 · 4.87e-2 · 4.27e-2 |
| HF bf16 sdpa (noise floor) | 7.72e-3 | 4.48e-5 | 4.48e-2 · 5.19e-2 ·
4.46e-2 |

Fused vs unfused state dicts are bitwise identical after loading, and
each packed parameter equals the concatenation of the parameters it
replaces.

**Fake-data training matrix** (`mini-glm-moe`, 2 GPUs, EP=2, Muon,
compile + AC on, `ckpt.interval=5`, 10 steps), all runs complete without
errors:

| run | result |
|---|---|
| fused / unfused, optimizer offload on / off | ✅ losses agree to ≤ 5e-4
relative on every step |
| `shard_fused_on_dim1 = true`: load, resume (both offload paths), fused
↔ unfused resume, 10-step loss vs unfused | ✅ (verified with this code
before the flag existed; see #3486 for the measurements) |
| fused ckpt → fused resume, fused ckpt → unfused resume | ✅ post-resume
losses agree to ≤ 1e-3 relative |
| unfused ckpt → fused resume vs unfused ckpt → unfused resume | ✅ |
| the same three resumes with optimizer-state CPU offload | ✅ |
| DeepGEMM FP8 (`quantization.type=fp8`,
`moe.compute.type=deepgemm_fp8`), fused and unfused | ✅ |

(Resumed runs deliberately diverge from the un-interrupted run:
`FakeDataLoader` reseeds from a batch counter that restarts at 0, so a
resume replays the first batches. Fused and unfused resumes see
identical data and are compared against each other.)

**RL end to end** (`configs/ci/integration/reverse-text-moe/start.toml`,
custom impl, EP=2, 2 trainer GPUs + 1 vLLM GPU, 20 steps, filesystem
weight broadcast): fused `mismatch_kl/all/mean` 1.8e-4–2.2e-4 on every
step vs 1.9e-4–2.1e-4 unfused.

**Fix included in this branch.** Before `fix(trainer): load packed
parameters and their optimizer state explicitly`, the same runs showed
the `qkv` fusion training from zero attention weights: the HF weight
load wrote into the replicated q/k/v copies, every q/k/v tensor in a
fused checkpoint was exactly 0, the fused/unfused step-1 loss differed
by 20% reproducibly under both bf16 and FP8, and the RL run aborted with
no trainable rollouts. A fused resume also lost the Muon momentum of
every packed parameter (verified with lr=0: momentum after resume was
1.00× instead of 1.95× the saved value; both fusions with optimizer CPU
offload, `qkv` without). With the fix, loaded weights are bitwise
identical to the source and momentum is restored on both resume paths.
Full optimizer offload (`model.full_offload`) with fusions was not
exercised. MXFP8 expert compute needs Blackwell and could not be tested
on H200.

## Cluster verification with merged Dion (2026-09-05)

Pinned `samsja/dion@99e5f7e` (merged samsja/dion#3) and refreshed
`uv.lock`; its tree is identical to the prior fork pin. Synced with `uv
sync --all-extras --inexact`, then ran GPU verification through Slurm on
H200s:

- 10 prime-rl fusion/activation-checkpointing tests, 13 Dion single-GPU
tests, and 4 Dion distributed tests passed.
- All **16 distributed checkpoint combinations** passed: fused/unfused
save and load, default/dimension-1 sharding, and optimizer-state offload
on/off. Canonical weights, optimizer state, and the next Muon update
with identical supplied gradients were **bitwise exact**.
- **13 compiled EP=2 training/resume variants** completed on
`samsja/mini-glm-moe` (512-token fake batches): both fusion modes, all
four resume combinations, state offload, dimension-1 sharding, and
DeepGEMM FP8. Fused/unfused BF16 losses differed by at most **0.031%**
across the three initial steps.
- All **406 pretrained model tensors** were bitwise exact in the zero-LR
checkpoint and after its offloaded resume. All 13 variants saved
canonical model/optimizer projection names, with no packed `qkv_proj` or
`gate_up_proj` entries.
- The real **2-step RL run with vLLM weight reloads** completed with
mismatch KL **0.00019046 / 0.00019005**. Fake-data runs use random
inference logprobs, so their mismatch KL is not a trainer/inference
agreement metric.
- H200 module checks: gate/up outputs and matrix-weight gradients, plus
Q/K/V outputs with/without bias, were exact. BF16 MoE input-gradient
relative differences were ~0.29%. Bias reductions in an all-BF16 module
varied ~1.5%, also reproduced by repeating the unfused calculation
itself.

Slurm evidence: 147/148 (test suites), 149 (RL), 150/158 (checkpoint
equivalence), 153 (training matrix), 157 (saved checkpoint inspection).
Job 148's test suites passed before an overly strict ad-hoc BF16 bias
assertion stopped that script; the numerical diagnostic was resolved
separately. Full optimizer offload and Blackwell-only MXFP8 were not
exercised.

## CI collection fix (2026-09-05)

The `reverse_text` integration job failed before running any tests
because importing `prime_rl.utils.weights` first triggered a circular
import through the model registry and `fusions`. Import
`PreTrainedModelPrimeRL` inside `convert_state_dict_to_hf`, its only
use, so loading weight utilities no longer eagerly imports the model
registry.

Reproduced the failing import locally before the fix. After the fix,
standalone collection of `test_reverse_text.py` succeeds (6 tests), the
complete integration suite collects (38 tests), and all 6 fusion unit
tests pass. Ruff lint/format checks and `git diff --check` pass.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core training paths (FSDP sharding, weight load, DCP optimizer
state, Muon) and defaults fusions on; incorrect packing/load logic would
corrupt weights or momentum on resume, though extensive
checkpoint/resume testing is described in the PR.
> 
> **Overview**
> Adds **runtime parameter fusions** (on by default via
`[trainer.model.fusions]`) that pack related weights into single tensors
so MoE **gate/up** and attention **q/k/v** run as one GEMM each, while
**checkpoints and exports still use canonical names** (`gate_proj`,
`q_proj`, etc.).
> 
> A new **`fusions` module** implements packing (`PackedParameterSpec`),
state-dict hooks, HF/DCP load **write-back** for packed weights, and
explicit **optimizer-state split/join** around distributed checkpoint
save/load (including CPU-offload resume). Optional
**`shard_fused_on_dim1`** wires FSDP2 **`shard_placement_fn`** for
experimental zero-copy fused weight/optimizer I/O.
> 
> **Attention and MoE layers** advertise fusions through
`supported_fusions`; forwards use **`project_qkv`** / a single grouped
**`gate_up`** GEMM when fused. Fusions are **skipped with LoRA**.
**Muon** gets **`matrix_partitions`** from packed params via an updated
**dion** pin. Docs and unit tests cover config and canonical state-dict
behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
52e736c685485fdbca109c86721017ab8065f65d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 19:47:47 +02:00
samsjaandGitHub 04a61d3b75 fix: warm Muon all-to-all connections during optimizer initialization (#3490)
## Summary

Automatically establish the NCCL peer connections used by Dion's Muon
optimizer immediately after constructing Muon and before returning it to
the trainer.

The warm-up runs only for Muon. It covers the exact main optimizer
process group and, when expert parameters use expert parallelism, the
separate expert-shard process group. Single-rank and non-NCCL groups
remain no-ops; AdamW, SGD, and other optimizers are unchanged.

This is a required correctness workaround for a reproducible multi-node
GLM-4.5-Air first-step deadlock. The source now documents that optimizer
refactors must preserve the warm-up, its process groups, and its
placement between Muon construction and the first optimizer step.

## Failure signature

Pretrained GLM-4.5-Air training with Muon reproducibly stalled while
submitting the first optimizer all-to-all on two nodes. All 16 ranks
reached the collective, but only rank 0 enqueued it successfully; ranks
1–15 remained inside submission until the NCCL watchdog fired.

The clearest controlled failure was job 1182:

- Nodes `qpn01gpu009` and `qpn01gpu011`, 16 GPUs total.
- Pretrained eight-layer GLM-Air reproduction with CP4, EP8/automatic
expert mesh, BF16 compute, and optimizer-state offload.
- First Muon all-to-all was NCCL sequence 67 with 50,331,648 BF16
elements per rank.
- The watchdog fired after 182 seconds.
- Setting `NCCL_CUMEM_ENABLE=0` did not resolve it.

This was not a generic inability of the nodes to communicate: Adam
training and standalone all-reduce/all-to-all controls completed on the
same cluster. Fake-weight and reduced-model tests further isolated the
trigger to Muon's pretrained-model initialization state and first bulk
all-to-all.

## Implementation

`_warmup_muon_mesh` takes the `DeviceMesh`, resolves its single process
group, and performs a bulk BF16 list all-to-all matching Dion's
communication path, waits for completion, and synchronizes CUDA before
releasing its temporary buffers. A scalar collective is intentionally
not used because it may not initialize the same bulk-transfer peer
channels. Meshes with more than one dimension (the replicate-only world
mesh) have no single group and are skipped; Dion's Muon only accepts 1-D
meshes there anyway.

The ordering is part of the fix:

1. Construct the Dion Muon optimizer.
2. Warm Muon's main distributed NCCL group.
3. If expert parameters and EP are active, warm the independent
expert-shard NCCL group.
4. Return the optimizer only after both required warm-ups complete.

The temporary allocation is approximately 12 MiB per peer for send plus
receive buffers. No config flag is introduced because making this
optional would allow the known deadlock to recur.

Patch scope remains one optimizer source file. There are no
trainer-loop, dependency, precision, optimizer-offload, allocator, Dion,
or experiment-config changes.

## Validation

- Ruff lint/format and whitespace checks passed.
- Existing configuration tests passed: 70 passed, 67 deselected.
- Job 1183, reduced pretrained model with early connection warm-up: one
full step passed on all 16 ranks; 42.6 seconds, loss 15.4930, gradient
norm 49.0578, clean exit.
- Job 1184, full 46-layer pretrained GLM-4.5-Air with the earlier
pre-model-load placement: three fake-data steps passed with finite
losses and nonzero gradient norms.
- Job 1185, full 46-layer model with the final optimizer-construction
placement in this PR: three steps passed on all 16 ranks. Losses were
13.2325, 13.1564, and 13.3399; gradient norms were 27.9833, 27.8885, and
31.8815; clean exit.
- The research-prod Air ablations pin the backport of this
implementation. IPO-KL, IPO, DPPO, and IcePop have each subsequently
advanced beyond 400 Muon steps without recurrence of the initialization
deadlock.
- Review follow-up (`dfa07cd7e`): the warm-up now resolves the process
group from the mesh and no-ops on non-1-D meshes. Verified on 2 GPUs
with NCCL: the `dp_shard` path still completes the warm-up collectives,
and the 2-D replicate-only world mesh returns cleanly where the previous
no-arg `get_group()` call raised `RuntimeError`.

Both full-model validations used `qpn01gpu009/011`, 16 GPUs, CP4 + EP8,
optimizer-state offload, BF16 compute, and expandable CUDA allocator
segments. They used fake data with no evaluation or checkpoint overhead.

Job 1185 artifacts are retained at:

```text
/home/outputs/int4-debug/sft-air-full-muon-init-warmup-2n-009-011
```

## Confidence and limitations

Confidence is high that this initialization prevents the observed
first-all-to-all deadlock: the failure was reproducible without it, the
matching warm-up removed it in progressively more production-like tests,
and the final implementation has continued to work in four long-running
RL jobs.

The exact NCCL-native deadlock mechanism remains unproven. The warm-up
changes connection state, allocation history, and startup timing, so
this should be described as a targeted correctness workaround rather
than proof of a particular NCCL defect. Removing or moving it requires
reproducing the original multi-node pretrained GLM-Air Muon case, not
merely passing a standalone collective test.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed initialization for Muon only, but incorrect group
selection or removal could reintroduce multi-node deadlocks or add
startup memory/time on every Muon run.
> 
> **Overview**
> Adds a **correctness workaround** for multi-node Muon training: NCCL
peer channels for bulk all-to-all are established **right after** Dion
`Muon` is built and **before** the first optimizer step, so
GLM-Air-style jobs avoid deadlocking on the initial Muon collective.
> 
> New helper `_warmup_muon_process_group` no-ops for single-rank or
non-NCCL groups; otherwise it runs an async **list** `all_to_all` on ~3
MiB BF16 buffers per rank (matching Dion’s bulk path), waits, and
synchronizes CUDA. Warm-up runs on the main **`dp_shard_cp`** (or world)
process group and, when expert MLP params use EP, separately on
**`dp_shard_mod_ep`**. AdamW, SGD, and other optimizers are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d0b707438f77780e4b5e0ed69237c08435ba3a41. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-07 11:20:40 -07:00
26b3131d27 fix(transports): make NCCL respect keep_in_fp32_for_weight_transfer (#3480)
The NCCL weight-broadcast transport hardcoded every tensor to
`bfloat16`, ignoring `keep_in_fp32_for_weight_transfer`. This PR makes
NCCL transport respect the fp32 overrides. This makes NCCL honor the
same declaration the other two transports already respect. Note: NIXL
does its own thing and does not use this shared helper, yet.

- Extracted `resolve_wire_dtype()` so the filesystem and NCCL paths
share one implementation.
- Lifted `NCCLBroadcaster._resolve_dtensors` to a module-level
`resolve_dtensors()`, since a method reachable only through a live
`PyNcclCommunicator` can't be unit tested.
- Added `tests/unit/utils/test_weights.py`, the flag's first test
coverage, parametrized over all six models that declare it.

Ran various experiments with small models to see if this affected KL mismatch in any way, but results were inconclusive. See commit https://github.com/PrimeIntellect-ai/prime-rl/pull/3480/changes/4b152bf3fa551ff5a1fc1752036262d14520c343 for example experiment configs.


---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-04 16:57:19 -04:00
samsjaandGitHub ef9dea1781 chore(inference): introduce admin plane abstraction (#3472)
## Summary

- consolidate the inference control path into a single `AdminPlane`
abstraction over its worker HTTP clients
- make the static plane own readiness, NCCL setup, weight updates, and
lifecycle management
- expose one typed `update_weights` operation; each receiver identifies
its transport explicitly
- route filesystem, NCCL, and NIXL receivers through the admin plane
instead of passing raw HTTP client lists
- remove the separate admin-plane protocol, unused factory argument, and
pass-through weight-update wrapper

`InferenceClient` remains the data-plane client for generation and
scoring, while `AdminPlane` coordinates control operations against one
or more inference workers. Alternate backends can specialize a transport
operation without adding backend flags to weight receivers.

## Validation

- `uv run ruff check src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights tests/unit/orchestrator/test_clients.py`
- `uv run python -m compileall -q src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights`
- `uv run pytest -q tests/unit/orchestrator/test_clients.py` (10 passed)

The transport test module could not be collected on this host because
its optional CUDA import chain requires `flash_attn`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Refactors the weight-broadcast control path (pause/resume,
NCCL/NIXL/filesystem updates) used during training; behavior should be
equivalent but mistakes here can strand engines paused or desync policy
versions.
> 
> **Overview**
> Renames **`AdminClients`** to **`AdminPlane`** and makes it the single
control-plane entry point for inference workers (readiness, NCCL init,
weight updates, LoRA load, teardown).
> 
> **NCCL setup** and **weight updates** move from module-level helpers
into **`AdminPlane.initialize_nccl`** and
**`AdminPlane.update_weights`**, with callers passing an explicit
**`transport`** (`filesystem` | `nccl` | `nixl`). Orchestrator, evals,
and all **`WeightReceiver`** implementations now take an
**`AdminPlane`** instead of raw **`httpx`** client lists;
**`load_lora_adapter`** and **`init_nixl_broadcast`** follow the same
pattern.
> 
> Unit tests are updated and **`test_admin_plane_initializes_nccl`** is
added.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
65043370b7a9c857e6e3302f665b0b8c389043f1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-03 16:36:16 -07:00
Konstantin DunasandGitHub 6c7b1ef375 feat: visualize compaction attempts and exclude rejected branches (#3478) 2026-09-03 22:09:41 +02:00
samsjaandGitHub 608c75c0af feat(dashboard): add timed terminal trace replay (#3456)
## Summary


https://github.com/user-attachments/assets/cd2caaa1-d700-40e5-8465-911812313f15

- add a terminal-style Replay view for rollout traces using recorded
model-call and tool timing
- add play/pause, seek, restart, 0.5x-32x speed controls, and an
inference-skipping tool-timing mode
- expose recorded model thinking with a toggle and T shortcut
- support Top/Live transcript navigation with Home/End shortcuts
- document replay timing semantics and extend dashboard smoke coverage

## Rebase notes

Rebased onto main (past #3444 overlays, #3465 chunked trace streams,
#3470 task/judge evidence, and #3455 semantic traces). Resolutions:

- `app.js` view state: trace viewer now has four modes — transcript,
timeline, replay, semantic; `setTraceView` keeps main's `persist` option
(replay is never persisted as a preference) and stops replay playback on
view switches; control visibility unions both sides (token-signal /
view-mode / collapse / expand hidden in graph, evidence, and replay
modes)
- `app.js` keyboard handler: replay T/Home/End shortcuts run first, then
main's step-bar arrow-key walking
- `app.js` click handler: replay control handlers first, then the
copy-button selector (including main's task/judge copy buttons)
- `index.html`: Replay button sits alongside main's Semantic button and
its episode-nav row
- `docs/training.md` / `skills/dashboard/SKILL.md`: describe all four
trace views together

## Validation

- `node --check src/prime_rl/dashboard/static/app.js` (rebased)
- `uv run --frozen ruff check tests/integration/dashboard_smoke.py`
(rebased)
- focused Playwright checks were run on the original branch (timed
playback, inference skipping, thinking toggles, keyboard shortcuts,
Top/Live navigation)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Read-only dashboard frontend and documentation; no changes to
training, inference, or data persistence.
> 
> **Overview**
> Adds a **Replay** tab to the rollout trace viewer that plays the
selected branch as a terminal session, using recorded model-call and
message timestamps for wall-clock pacing.
> 
> Playback includes play/pause, seek, restart, **0.5×–32×** speed
(default **8×**), **Skip inference** (instant model replies while
keeping tool delays), optional **Thinking** display (**T**), and **Top**
/ **Live** scroll follow (**Home** / **End**). Response text is revealed
evenly across each model-call span and labeled as inferred when
per-token timestamps are absent; prompt nodes committed at response time
are aligned to call start to avoid false idle gaps. Transcript-only
controls are hidden in Replay mode, and integration smoke tests cover
the new UI.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fddf8349c2f99ec4ac658b6bbfacb2e8f24532c9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 16:50:33 -07:00
Konstantin DunasandGitHub b28714289a feat(dashboard): visualize semantic agent traces (#3455) 2026-09-03 01:33:18 +02:00
Konstantin DunasandGitHub 903baaaa01 fix(dashboard): hide repeated timeline rewards (#3473) 2026-09-03 00:51:31 +02:00
Konstantin DunasandGitHub ae170acda1 feat(dashboard): surface task and judge evidence (#3470) 2026-09-03 00:45:13 +02:00
samsjaandGitHub c84068cf9e fix(evals): show error rate on partially evaluated epochs (#3462)
## Summary

- the partially-evaluated (cancelled-epoch) warning line in the `uv run
evals` entrypoint log now shows the `Error` rate next to `Reward` —
previously it reported reward with no signal of how many completed
episodes errored

```
Partially evaluated swebench-pro (Step 240) |  1m 32s | Reward 0.4167 | Error 5.0% | Completed 92/100 | Cancelled 8/100
```

The completed-epoch success line already shows `Error` and is unchanged:

```
Evaluated swebench-pro (Step 240) |  1m 32s | Reward 0.4167 | Turns 3.2 | Branches 1.0 | Error 5.0% | Truncation 2.0%
```

## Verification

- `uv run ruff check src/prime_rl/evals/evals.py` — passed
- `uv run ruff format --check src/prime_rl/evals/evals.py` — passed

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Logging-only change in eval finalization; no behavior, scheduling, or
metric emission changes.
> 
> **Overview**
> When an eval epoch is **cancelled** (e.g. superseded by a newer
checkpoint), the warning log line now includes the **Error** rate from
completed episodes, using the same `full.has_error` formatting as the
full **Evaluated** success line.
> 
> Previously that partial-eval message only showed reward and
completion/cancel counts, so operators could not see how many finished
rollouts failed without digging into metrics.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
010a7eceb61c71fa105ffadf7b4dc4e6708fc188. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 13:26:03 -07:00
Mika SenghaasandGitHub 7ad1bb9123 feat: chunk and seal trace streams (#3465)
## Summary

- Each trace stream (`traces/stream`, `traces/annotations/<producer>`)
is now a directory of numbered chunks. `ChunkedJsonl`
(`monitors/file/traces/chunks.py`) rolls at `monitors.file.chunk_bytes`
(default 5 GiB; a line never spans chunks) and, with
`monitors.file.compress` (default on), seals each full chunk with zstd
in a background thread. The live chunk stays plain text; a finished run
seals its live chunk too. A relaunch resumes the live chunk it finds and
seals anything a crash left mid-seal.
- Sealed chunks use zstd's seekable format (`pyzstd`, 4 MiB frames), so
a seek costs one frame, not the chunk. `zstd -dcf stream/* | jq` reads a
whole stream, sealed and live alike.
- Index rows carry `chunk` beside `offset`; the dashboard resolves both
through `open_chunk` (plain or sealed) for episodes and annotation
records, keys its caches and etags on the index size, and parses chunked
streams for the series view through the index, one chunk open at a time.
Annotation readers rely on the producer's index (the file monitor always
writes one).
- `monitors.file.float_decimals` (default 4, `None` for every digit)
sets the precision of per-token float streams in both the episode
records (`to_record(float_decimals=...)`) and the trainer's annotation
streams. Trainer streams also hold `null` outside the loss mask - the
fold keeps sampled tokens only, so nothing a reader sees changes, and
runs of nulls seal to nothing. The trainer finalizes its monitors on
exit so its live chunk seals.
- Submodule bump to verifiers main `cfc7c474`
(PrimeIntellect-ai/verifiers#2495, merged): JSON records round per-token
floats to `to_record(float_decimals=...)`, 4 by default. The msgpack
wire keeps full precision, so the importance ratio is unaffected.

## Measurements

Replayed the 100-step, 33,342-episode scaleswe baseline
(`ipo-baseline-rollouts-steps1-100`, 15.17 GB as one `stream.jsonl`)
through the new writer with 5 GiB chunks:

| | raw | 4 dp | on disk (sealed) | total |
|---|---|---|---|---|
| 10 steps (5,696 episodes) | 1.06 GB | 0.89 GB | **0.10 GB** | 11.0x |
| 100 steps (33,342 episodes) | 15.17 GB | 12.66 GB | **1.38 GB** |
11.0x |
| 1000 steps (extrapolated from steps 11-100: 307 episodes, 157 MB raw
per step) | 156 GB | 130 GB | **14.2 GB** | 11.0x |

Rounding contributes 1.20x on the plain bytes and lifts zstd from 6.9x
to 9.2x, since mantissa digits were the incompressible part. Writing 33K
episodes took 81.8 s with sealing vs 80.4 s plain: sealing runs beside
the writer, not in front of it. The final 2.7 GB live chunk sealed in 4
s.

Dashboard against the sealed run (same box, 5 GiB chunks): open one
episode 5.8 ms cold / 4.0 ms warm vs 3.9 / 3.4 ms plain; table page 17
ms cold (index only, unchanged); series view full parse of all 33K
records 35.7 s sealed vs 39.7 s plain (orjson-bound, cached and
persisted after the first pass). Browser check: traces table renders,
episode viewer opens from a sealed chunk, no console errors. Unit suite:
571 passed.

## Breaking

- On-disk trace layout: `traces/stream.jsonl` →
`traces/stream/<NNNNN>.jsonl[.zst]`,
`traces/annotations/<producer>.jsonl` →
`traces/annotations/<producer>/<NNNNN>.jsonl[.zst]`; index rows gain
`chunk` and their `offset` is chunk-relative. Read a stream with `zstd
-dcf <stream dir>/* | jq`. The dashboard reads only the new layout.
- Per-token floats in records (`logprobs`, `reference_logprobs`,
`advantages`, trainer `trainer_logprobs`/`entropies`) are written with 4
decimals by default; set `monitors.file.float_decimals = None`
(orchestrator and trainer) to keep full precision.
- New dependency `pyzstd`.


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking on-disk trace layout and default float precision affect
observability and external readers; dashboard and monitor paths are
heavily touched but training wire precision is unchanged per PR notes.
> 
> **Overview**
> **Trace on-disk layout is now chunked directories** instead of single
`stream.jsonl` / `annotations/<producer>.jsonl` files. The file monitor
writes through `ChunkedJsonl`: rolls at `monitors.file.chunk_bytes`
(default 5 GiB), optionally seals full chunks with seekable zstd in
background threads (`monitors.file.compress`, default on), and seals the
live chunk on `finalize()` (trainer now calls
`asyncio.run(monitors.finalize())` at shutdown). Index rows add
**`chunk`** beside chunk-relative **`offset`**.
> 
> **`monitors.file.float_decimals`** (default 4) rounds per-token floats
in episode `to_record(...)` and trainer annotation streams; trainer
streams also emit **`null`** outside the loss mask for better
compression without changing what readers fold onto traces.
> 
> The **dashboard** detects chunked streams via the index, reads
episodes and annotations with `open_chunk` (plain or `.zst`), versions
caches/etags on index size, and builds series summaries by walking the
index one chunk at a time. **Breaking:** tools and scripts must use
`zstd -dcf <stream-dir>/*` and per-producer chunk dirs under
`annotations/`. New dependency **`pyzstd`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
62a6893f75cbc770cbad06fd65d640aec13f058b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 11:37:29 -07:00
5990b1b9ba feat: add deepseek v4 (step 0) (#3325)
Initial commit for adding deepseek v4 flash. 

This architecture brings in multiple new ingredients and will require
multiple commits for a fully mature implementation to be ready. The
present PR should be regarded as the very rough first draft, focused on
unblocking basic SFT runs.

Other notes:
* I am attempting to isolate most changes to live under
`trainer/models/deepseek_v4/` to keep the PR clean and easier to iterate
on later without entangling this code with other `prime-rl` changes.
E.g. the `deepseek_v4/attention.py` impls may eventually get hoisted to
`attn.py`
* Does not yet implement methods needed for RL weight broadcasting
(blocking evals as well)
* We will incrementally pull in kernels to replace the current
pure-eager torch impl

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-02 11:34:01 -04:00
ffb845c13c fix(trainer): zero-index position_ids fallback in LM-head wrapper (#3466)
Use the standard zero-indexing convention for `position_ids` in patched
LM head forward, (`_patch_model_forward`), rather than one-indexing.

A uniform shift is mathematically invisible to RoPE, which sees only
query-key angle differences, but it is wrong for attention that keys off
absolute token indices (as is important for deepseek v4 where
compression boundaries are tied to absolute positions).

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 10:05:32 -04:00
Mika SenghaasandGitHub 421198cb93 feat: constant trainer batch size (#3463) 2026-09-01 20:22:40 -07:00
e3fdadedc5 feat: trainer trace annotations + dashboard overlays (#3444)
## Summary

Every rollout episode is written to disk exactly once, as an
arrival-ordered stream, and everything learned about it afterwards is an
append-only annotation folded back on read. The trainer's recomputed
per-token streams ride that mechanism, and the trace viewer renders them
as overlays (entropy, the trainer↔sampling mismatch, the IPO stable
mask) next to the loss mask.

**Layout** (replaces
`rollouts/step_N/{train,eval}/{all,effective}/traces.jsonl`):

```
<run_dir>/monitors/file/metrics.jsonl                              # every metric row, tagged by producer
<run_dir>/monitors/file/traces/stream.jsonl                        # every episode, appended as it arrives
<run_dir>/monitors/file/traces/stream.index.jsonl                  # one compact row per episode, with its byte offset
<run_dir>/monitors/file/traces/annotations/<producer>.jsonl        # trace updates: orch ship-time facts, trainer per-token streams
<run_dir>/monitors/file/traces/annotations/<producer>.index.jsonl  # each update's scalars and where its record sits
```

Everything the file monitor dumps lives under its own directory, and
nothing is written there when the monitor is off. The traces and
everything written about them sit under `traces/`, and every index is
named for the stream it indexes and sits beside it. Each file is
append-only with exactly one writer, so there are no locks and live
tailing keeps working.

**Steps are events, not locations.** A trace is dispatched at one step,
arrives at another and is trained at a third, so a step directory could
only ever be honest about one of them — and picking arrival forced the
arrival step onto the batch wire just so the trainer could find the
right directory. Instead each step is stamped as its own event on the
record. `orchestrator/annotations.py` owns both events: `stamp_arrival`
puts `info.kind` plus `info.dispatch` / `info.arrival` (`{step, time}`)
on a trace as its episode lands, and `stamp_ship` produces the update
carrying `info.effective` and `info.ship` — the orchestrator step whose
batch shipped the cohort, or for eval the policy version the epoch
measured. Staleness is `ship.step - dispatch.step`; the trace viewer
shows all three for a train trace, and an eval trace shows the step it
measured instead (it never ships in a batch and never goes stale).

- **Annotations**: one record format and one fold, in
`prime_rl.monitors.trace_updates`, used by the file monitor, the trainer
writer and the dashboard. An update names a trace and carries an `info`
dict merged into the trace's own plus per-branch token streams,
full-length over the branch's token prefix (nulls mark unknown
positions) so folding never depends on the producer's loss mask.
- **Indexes**: the file monitor summarises each episode into
`stream.index.jsonl` as it writes it, and each update's scalars into the
producer's `.index.jsonl`, both with byte offsets. A reader browses the
indexes and seeks for the one episode it opens, so the cost of listing a
run stops scaling with the token streams — which outweigh the episodes
themselves.
- **Branch identity on the batch wire**: `TrainingSample` gains
`trace_id` / `branch_index`; `MicroBatch` carries them per sequence,
parallel to `sequence_lengths`, preserved through packing/padding and
nulled on dummy micro batches.
- **Trainer**: accumulates one update per trained sequence per forward
(packing-boundary first value and non-finite values are null), gathers
them to rank 0 at the end of each step, and logs them through its own
file monitor — the same monitor it already logs metrics through — rather
than writing to disk behind it. Always on; the token-export path is
gone.
- **Dashboard**: same HTTP API shape. The traces tab opens on the whole
stream — newest first, paged as you scroll, with a histogram of episodes
finished per interval you can click to narrow to a moment — and switches
to step mode for the cohort that shipped at one step (arrow keys walk
the step bar). Episode reads fold every annotation onto the record, so
the overlays work in both views. Token signals are Advantage, Entropy,
Mismatch (`r − log r − 1`, computed client-side from the trainer and
sampling logprobs), Stable mask (`|Δp|` vs the run's IPO `eps`), Loss
Mask and Content Mask; an overlay the open episode cannot colour is
disabled in the selector and names the input it is missing, rather than
silently painting nothing. In a token overlay the reasoning renders
inside the token spans that already cover it instead of in its own box.
- Verifiers gained only the two per-token node fields the records land
on (`MessageNode.trainer_logprobs` / `entropies`, with matching `Branch`
spread properties) —
[verifiers#2481](https://github.com/PrimeIntellect-ai/verifiers/pull/2481),
merged; `deps/verifiers` tracks verifiers main.

## Verification

Reverse-text, 4 steps: 645 episodes on one stream, 496 annotated by both
producers, 55,694 masked tokens folded with every node's compact arrays
equal to its masked-token count. Mean KL mismatch 0.0014, mean entropy
0.61. Staleness came out as 336 traces shipped at their dispatch step
and 160 a step later — the lag the old layout could not express. Re-run
end to end on a 20-step reverse-text run after the layout change.
SFT-online-eval and verifiers `uv run eval` run shapes checked through
the real API with a FastAPI test client; the dashboard's browser smoke
suite covers the stream/step views, the histogram, the step bar and
every token signal.

## Breaking

- The `rollouts/` trace tree is gone. Episodes now live in one
`monitors/file/traces/stream.jsonl` stream, written once at arrival,
with the effective cohort expressed as
`monitors/file/traces/annotations/<producer>.jsonl` records instead of
duplicate episode copies (per-token advantages and the scalar advantage
now arrive via annotations). The dashboard reads only the new layout;
runs recorded before this change need the old dashboard.
- `metrics.jsonl` moves from the run root to
`monitors/file/metrics.jsonl`.
- `trainer.enable_token_export` is removed and `token_exports/` is no
longer written; the trainer's per-token streams are always logged as
annotations.
- The filesystem batch transport writes packed micro batches to
`batches/step_<n>/rank_<r>.bin` (previously `rollouts/step_<n>/`).

## 20-step GLM-Air ScaleSWE comparison

- The baseline ran `main`; the comparison ran this PR. The code change
was the only behavioral difference. Run names, output directories, and
conversion cache paths were isolated.
- Trainer step 1: before 874.0 s; after 822.0 s (-5.9%).
- Trainer steps 1–20: before 3,179.2 s; after 2,995.2 s (-5.8%).
- Steady trainer steps 2–20: before 121.3 s mean / 120.0 s median; after
114.4 s mean / 99.0 s median. The after run was 5.7% faster by mean step
time.
- Trace data at each run's trainer step-20 cutoff: before 3.516 GB
across duplicated `all` and `effective` traces; after 3.476 GB across
the arrival stream plus orchestrator and trainer annotations. The after
layout was 1.1% smaller despite 864 MB of per-token trainer logprob and
entropy annotations.
- Dashboard on the after run at step 20: a 128-episode page took 15.7
ms, a 2.22 MB annotated episode took 42.7 ms, and its timeline took 9.7
ms.

The after job was cancelled after step 24 at the researcher's request.
The baseline completed trainer step 20.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large observability and on-disk contract change (breaking paths and
removed `trainer.enable_token_export`); training/orchestration logic is
mostly additive but any tool still expecting `rollouts/` or root
`metrics.jsonl` will break.
> 
> **Overview**
> Replaces the per-step `rollouts/.../traces.jsonl` tree with a **file
monitor layout** under `monitors/file/`: metrics at `metrics.jsonl`,
episodes in one append-only `traces/stream.jsonl` plus sidecar indexes,
and **append-only trace annotations** per producer (orchestrator
ship-time facts, trainer per-token streams).
> 
> **Orchestrator/evals** stamp arrival metadata on episodes at log time
and log **effective cohort** membership, advantages, and ship step via
`log_annotations` instead of duplicating episode files. **Trainer**
drops `enable_token_export` / `token_exports/`; per-token logprobs and
entropies always go through the same annotation path. **Dashboard**
reads the new layout: stream vs step cohort views, paged
`/api/runs/.../episodes`, arrival histogram, and token overlays
(entropy, mismatch KL, IPO stable mask, masks) folded from annotations.
> 
> Docs, skills, configs, and `run_single_benchmark.py` are updated for
the new paths and for skipping non-step metric rows. Filesystem batch
transport writes to `batches/step_*` instead of under `rollouts/`.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
16bf663b7805ecfe7d993ff6b6d34c8b7bc47308. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-01 17:17:54 -07:00
Mika SenghaasandGitHub 84e7312f33 feat: top-p/top-k train sampling with native sampling replay (#3431)
## Summary

- Add typed top-p and top-k settings for policy rollouts.
- Capture vLLM 0.28 sampling masks and replay the truncated distribution
in the trainer.
- Bound sampling masks with a default `top_k = 512` when truncation is
enabled.
- Use Model Runner V2 for router replay on standard deployments.
- Support router replay and sampling replay together on Model Runner V2.
- Keep NIXL P/D router replay on V1 and reject the unsupported combined
P/D mode.
- Use `SamplingMask` and `sampling_mask` across Renderers, Verifiers,
and prime-rl.
- Pin merged Renderers and require its published `0.1.12.dev2` build.
- Pin Verifiers to the latest `main` after its sampling-mask merge.
- Document standalone capture, the NIXL replay matrix, and sampling-mask
layout examples.
- Shard sampling masks with labels for multimodal context-parallel
training.
- Reject mixed enabled and disabled top-k settings across live-policy
train sources.

This builds on vLLM 0.28.0 from #3430. It supersedes #3235. The capture
side uses vLLM's native sampling-mask support from
[vllm#49577](https://github.com/vllm-project/vllm/pull/49577).

## Usage

```toml
[orchestrator.train.sampling]
top_p = 0.95
top_k = 20
```

There are no replay flags for sampling replay. Truncated policy sampling
enables mask capture and trainer replay automatically.

Set `trainer.enable_router_replay = true` to combine router replay with
sampling replay. Standard deployments use Model Runner V2 for both
captures. Disaggregated NIXL deployments keep router replay on V1 and
cannot combine both replay modes.

## Behavior

- Policy sampling with `top_p < 1` or `top_k` gets a bounded sampling
mask.
- Truncation without an explicit `top_k` defaults to 512.
- Different truncating sources can use different top-p values; each gets
a positive top-k.
- Mixed top-k capture modes across live-policy sources are rejected.
- Values above 512 are rejected to bound trainer memory.
- The trainer renormalizes each sampled token over the same mask as
inference.
- Frozen-source environments do not require masks.
- `opd` and `opsd` reject truncated policy sampling because their
reference scores use the full vocabulary.
- vLLM rejects sampling-mask requests with `temperature <= 0` or without
an effective `top_k > 0`.

## Runs

GLM-4.5-Air on `scaleswe` on 4 nodes

| Run | Runner | Router replay | Top-p | Effective top-k | Nodes |
| --- | --- | --- | --- | --- | --- |
| `glm-air-v1-baseline` | V1 | Off | 1.0 | Off | 6 |
| `glm-air-v2-baseline` | V2 | Off | 1.0 | Off | 6 |
| `glm-air-v2-router-replay` | V2 | On | 1.0 | Off | 6 |
| `glm-air-v2-top-p-0.95` | V2 | Off | 0.95 | 512 | 6 |
| `glm-air-v2-router-replay-top-p-0.95` | V2 | On | 0.95 | 512 | 6 |

<img width="279" height="238" alt="Screenshot 2026-09-01 at 3 45 20 PM"
src="https://github.com/user-attachments/assets/bbbf5334-4b06-4573-9232-80d9207a97e6"
/>

<img width="286" height="226" alt="Screenshot 2026-09-01 at 3 46 03 PM"
src="https://github.com/user-attachments/assets/8d048fb1-3e2a-4484-a437-8084d845d47e"
/>

<img width="285" height="238" alt="Screenshot 2026-09-01 at 3 45 39 PM"
src="https://github.com/user-attachments/assets/ca5c21c7-6355-497f-a553-adade238dc1a"
/>

Sampling replay leads to
- no reduction in step 0 KL mismatch
- more stable KL mismatch in conjunction with router replay
- more stable entropy (not rising)
- slower step time (follow-up perf investigation TBD)

## Verification

- `uv run pytest -q tests/unit/test_configs.py -k 'policy_sources'`: 2
passed.
- `uv run pytest -q tests/unit/test_configs.py -k 'not
test_load_configs'`: 69 passed and 67 deselected.
- Pre-commit checks passed for the changed config and test files.

- `uv run pytest tests/unit/train/rl/test_fused_lm_head.py
tests/unit/train/rl/test_loss.py -q`: 19 passed and 1 skipped after the
context-parallel fix.

- `uv run pytest
tests/unit/test_configs.py::test_combined_replay_uses_v2_runner -q`:
passed after the documentation review.

- `uv sync --all-extras`: passed with merged Renderers and Verifiers
dependencies.
- `uv run pytest tests/unit/orchestrator tests/unit/inference
tests/unit/train/rl/test_loss.py
tests/unit/train/rl/test_fused_lm_head.py
--ignore=tests/unit/orchestrator/test_qwen3_vl_e2e.py -q`: 108 passed
and 1 skipped.
- The excluded Qwen3-VL test has an existing fake-response fixture
mismatch.
- `uv run rl @ examples/basic/reverse-text/rl.toml --max-steps 5
--orchestrator.train.sampling.top-p 0.95`: completed five trainer and
orchestrator steps on the final dependency chain.
- The end-to-end run used Model Runner V2, effective `top_k = 512`, and
sampling-mask capture. Final mismatch KL was 0.0035 with no rollout
errors.
- Renderers: `uv run pytest tests/test_client.py -q`: 21 passed and 5
skipped. Ruff and format checks pass.
- Latest Verifiers main: `uv run pytest
deps/verifiers/tests/v1/test_graph.py
deps/verifiers/tests/v1/test_trace.py -q`: 21 passed. Ruff, format,
type, and pre-commit checks pass.
- Reverse-text baseline, top-p 0.95, and top-p 0.95 plus top-k 20 runs
completed with 100% sampling-mask coverage.

W&B:
`reverse-text/reverse-text-native-replay-{baseline,topp095,topp095-topk20}`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)





<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes core RL logprob/importance-ratio math and vLLM runner
selection; misconfiguration or missing masks can bias training or fail
at runtime, though validation and runtime checks aim to catch
incompatible modes.
> 
> **Overview**
> Adds **sampling replay** so policy rollouts with `top_p < 1` or
`top_k` stay aligned with trainer importance ratios: vLLM 0.28 returns
per-token sampling masks (`enable_return_sampling_mask` /
`--return-sampling-mask`), and the trainer renormalizes logprobs over
the same mask instead of the full vocabulary.
> 
> **Config & orchestration:** `TrainSamplingConfig` gains typed `top_p`
and `top_k` (truncation via `extra_body` is rejected). The `rl`
entrypoint auto-enables mask capture when policy sampling truncates;
unbounded truncation defaults `top_k = 512`, values above 512 are
rejected, `temperature = 0` and `opd`/`opsd` are blocked. Policy train
sources must agree on top-k capture mode (engine-wide). **Inference:**
new `enable_return_sampling_mask`; vLLM env setup prefers **V2** for
sampling capture and for router replay on standard deployments, while
**disaggregated NIXL P/D** keeps routed-expert capture on V1 and
**rejects** router + sampling replay together.
> 
> **Data path:** `SamplingMask` on `TrainingSample` / `MicroBatch`,
encoding in trajectories, packing/padding in the trainer batch builder,
and a hard error in `TrainSink` if truncated rollouts lack masks.
**Trainer:** masks flow through CP sharding; fused `lm_head` and
vanilla-path `selective_log_softmax_with_sampling_mask` compute
mask-renormalized logprobs (Gemma softcap heads explicitly unsupported).
Docs cover sampling replay; `renderers` is bumped for mask support in
the rollout stack.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cee517e2266a2b819765612ccf3a10ba8801a23e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 15:47:54 -07:00
Mika SenghaasandGitHub fe325ac460 chore: bump verifiers (#3460)
## Summary

- advance the `deps/verifiers` submodule from `e2103d6` to `d4a2177`
- include merged Bash and RLM context compaction from verifiers #2454
and #2459
- pick up nano-rlm compaction commit `4ef3438` through the default RLM
harness pin
- refresh `uv.lock` for verifiers' `aiohttp>=3.14.1` requirement
- migrate three RLM examples to `compaction.summarize_at_tokens`; use
the former range's `98_304` midpoint
- include the optional ACP semantic-edge and shared harness utility
changes already on verifiers `main`

Companions: [verifiers
#2454](https://github.com/PrimeIntellect-ai/verifiers/pull/2454),
[verifiers
#2459](https://github.com/PrimeIntellect-ai/verifiers/pull/2459), and
[nano-rlm #147](https://github.com/PrimeIntellect-ai/nano-rlm/pull/147).

## Breaking

- RLM harness configs must move `summarize_at_tokens` to
`compaction.summarize_at_tokens`.
- Leave `compaction` unset to disable proactive and reactive compaction.

## Verification

- `git diff --check`
- `uv lock`
- `uv lock --check`
- `uv run pytest -q tests/unit/test_configs.py` — 133 passed
- `git submodule status deps/verifiers` —
`d4a217794fc0bfd70369a8230e56653c193da8ce`
- verified that `d4a2177` descends from the previous `e2103d6` pin

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Submodule bump plus a breaking harness config shape affects all RLM
runs still using the old `summarize_at_tokens` field; example migrations
are mechanical but custom configs must be updated.
> 
> **Overview**
> Advances the **`deps/verifiers`** submodule to pick up merged Bash/RLM
**context compaction** (and related harness defaults), with
**`uv.lock`** refreshed so **`aiohttp`** meets the new **`>=3.14.1`**
floor.
> 
> **Breaking for RLM harness TOML:** flat
**`env.agent.harness.summarize_at_tokens`** is replaced by
**`env.agent.harness.compaction.summarize_at_tokens`**. The three
advanced examples (**`glm-4.5-air/search`**, **`glm-4.5-air/terminal`**,
**`nemotron-3-super/swe`**) are updated accordingly—train sources that
used a two-threshold list **`[65536, 131072]`** now use a single
**`98304`** threshold; eval sources keep **`98304`** but under the
nested **`compaction`** key.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
7429aba97da77a30db191432d5295827c64ae621. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 11:46:35 -07:00
samsjaandGitHub 0f22eeb862 feat(evals): add resumable standalone runs (#3413)
## Summary

- add top-level `[ckpt]` and `[resume]` support to standalone `uv run
evals`
- write atomic cursor checkpoints at
`<output_dir>/checkpoints/step_N/evals/progress.pt`, where N is the
durable eval-source task cursor
- store only the cursor in eval progress checkpoints; generated episode
records are not copied into checkpoint payloads
- resume with `--resume`, `--resume.step N`, or `--resume.dir
path/to/checkpoints/step_N` by skipping the durable cursor prefix
- retry partial groups and out-of-order completions beyond the durable
cursor
- size resumed eval batches to the remaining queued task suffix
- reject checkpointing in online mode, where progress is coupled to the
trainer weight-broadcast lifecycle
- keep the training start-run skill current with the new workflow
- clarify that checkpoint writes use temp-file replacement so resume
never observes a partial pickle

## Verification

- `uv run pytest tests/unit/evals/test_ckpt.py` — 3 passed
- focused `ruff check` — passed
- focused Python `ruff format --check` — passed
- `git diff --check` — passed

Local note: `uv run evals --help` is currently blocked before CLI
loading by the locked `prime-sandboxes==0.2.39` / `connectrpc==0.11.1`
import mismatch (`connectrpc.client` is missing).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Shared orchestrator types (`Dispatcher`, `EvalSource`, `EvalSink`)
change, but checkpoint/resume logic is gated to standalone evals with
config validation; unit tests cover cursor and I/O semantics.
> 
> **Overview**
> Standalone `uv run evals` can now be made **interruptible** via
optional `[ckpt]` and `[resume]` on `EvalsConfig` (rejected when
`[online]` is set).
> 
> Progress is a **task cursor** over round-robin eval tasks:
`EvalSource` assigns `source_index`, advances the durable cursor only
over a fully completed prefix (`mark_completed`), and on resume skips
tasks below the loaded cursor. `CheckpointManager` writes only
`{"cursor": N}` to `<output_dir>/checkpoints/step_N/evals/progress.pt`
using atomic temp-file replace; saves run every `ckpt.interval`
completed groups in standalone mode.
> 
> The evals loop loads resume state at setup, sizes epochs with
`EvalSink.set_batch_size` from remaining queued tasks, and on each
finished eval group calls `dispatcher.pop_source_index` to drive
checkpointing. Online eval rollout totals use the triggered queue
instead of full env example counts.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d4dc69fac552a55cb6c7c412a0d4e1b194a39c03. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 19:31:16 -07:00
JannikStandGitHub 1fbf0b47a4 bugfix: install EFA userspace stack in-place in the runtime stage (#3454)
## Why

`libfabric` needs a newer `libefa.so.1` (symbol version `EFA_1.4`) than
this image's own apt-installed rdma-core provides, so NCCL fails to load
the OFI plugin: `version 'EFA_1.4' not found`.

## What

- The AWS EFA installer upgrades rdma-core system-wide via its own
apt/dpkg step, but running it in a separate build stage and copying out
only `/opt/amazon` left that system-wide upgrade behind — libfabric
ended up paired with the older, separately-apt-installed rdma-core.
- Run the installer directly in the runtime stage instead, so its
rdma-core upgrade lands in place with no copy-forwarding gap.
- Verified locally: before the installer, stock rdma-core
(50.0-2ubuntu0.2); after, upgraded to 61.0-1 system-wide,
`libfabric.so.1` resolves `libefa.so.1` cleanly, and
`libnccl-net-ofi.so` dlopens with zero missing dependencies.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes CUDA image build and RDMA/EFA library versions used for
multi-node NCCL; incorrect pairing could still break distributed
training on EFA hosts, but the change targets a known symbol-version
mismatch.
> 
> **Overview**
> Fixes NCCL OFI plugin load failures (`EFA_1.4` not found) by changing
**how** the CUDA image gets the AWS EFA stack, not by adding new runtime
behavior.
> 
> The dedicated `efa-installer` build stage and `COPY
--from=efa-installer /opt/amazon` are removed. The same AWS
`efa_installer.sh` run (still with `--skip-kmod` and
`--skip-limit-conf`) now executes **in the final runtime image**,
immediately after the base `apt` install of `libibverbs` / `librdmacm`
and related packages. That way the installer’s system-wide rdma-core
upgrades stay in the image libfabric actually runs in, instead of
shipping only `/opt/amazon` from an isolated stage paired with older
distro rdma-core.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6f879a4bf88704c58b5719b1c8635258121ae2de. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 02:45:32 +02:00
JannikStandGitHub 799ac26258 bugfix: install libhwloc15 for aws-ofi-nccl in runtime image (#3452)
## Why

NCCL now finds `libnccl-net-ofi.so` but fails to load it:
`libhwloc.so.15: cannot open shared object file`, falling back to
sockets.

## What

- Add `libhwloc15` to the runtime stage's apt install list.
- The EFA installer stage pulls in libhwloc as one of its own
dependencies, but only `/opt/amazon` gets copied forward into the
runtime stage — the shared lib itself never did.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-package addition to the Docker runtime image with no
application code or auth/data-path changes.
> 
> **Overview**
> Fixes NCCL failing to load the AWS OFI network plugin
(`libnccl-net-ofi.so`) because **`libhwloc.so.15`** was missing at
runtime, which forced a fallback to sockets.
> 
> The CUDA **runtime** stage now **`apt install`s `libhwloc15`**
alongside the other RDMA/EFA-related packages. The EFA installer stage
already pulled in hwloc as a dependency, but only **`/opt/amazon`** is
copied into the final image—not the distro **`libhwloc`** package—so the
shared library never landed in the runtime filesystem.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a1d18804238afc171a4e8b856e86c24818d2b95d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 00:57:11 +02:00
JannikStandGitHub d5b38216a5 bugfix: install prime-kernels extra in Docker build (#3449)
## Why

Trainer crashes with `ModuleNotFoundError: No module named
'prime_kernels'` on startup. `collectives.py` imports it unconditionally
at the top of the file.

## What

- `prime-kernels` is declared and pinned in `pyproject.toml`/`uv.lock`
under its own `kernels` extra, but that extra was never passed to `uv
sync` in `Dockerfile.cuda` — so it resolves but never actually installs.
- Add `--extra kernels` to both `uv sync` calls.
- Add `prime-kernels` to the post-sync version-check so a missing
install fails the build loudly instead of shipping silently.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Docker build-only dependency wiring with no runtime logic changes;
slightly larger images when the kernels extra is enabled.
> 
> **Overview**
> Fixes CUDA Docker images that could start the trainer without
**`prime-kernels`**, causing **`ModuleNotFoundError: No module named
'prime_kernels'`** even though the package is pinned under the
**`kernels`** optional extra.
> 
> Both **`uv sync`** stages in **`Dockerfile.cuda`** now pass **`--extra
kernels`**, so the wheel is actually installed into the venv. The
post-sync **`importlib.metadata`** smoke check also includes
**`prime-kernels`**, so a missing install fails the image build instead
of surfacing only at runtime.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
180ec8e7944f5be98a55a24200959fff882b652d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-01 00:28:16 +02:00
JannikStandGitHub f87ebcc239 improvement(docker): bundle AWS EFA libfabric + aws-ofi-nccl (#3448)
## Summary
- Bundles libfabric + the aws-ofi-nccl NCCL plugin into the image via
AWS's official installer, so NCCL can find the OFI plugin at runtime
instead of silently falling back to sockets
- Inert by default — only takes effect where a deployment's config
points `LD_LIBRARY_PATH` at it

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Docker build-only change that adds optional EFA libraries without
altering default runtime env or application code; main risk is larger
images and relying on the pinned AWS installer URL/version.
> 
> **Overview**
> The CUDA runtime image now **ships the AWS EFA userspace stack**
(libfabric and the **aws-ofi-nccl** NCCL plugin) so multi-node jobs on
EFA-capable hosts can use NCCL’s OFI path instead of silently falling
back to sockets.
> 
> A new **`efa-installer` build stage** on the same Ubuntu 24.04 base as
runtime downloads AWS’s official installer (default **1.47.0**), runs it
with **`--skip-kmod`** and **`--skip-limit-conf`**, and copies
**`/opt/amazon`** into the final image. **`LD_LIBRARY_PATH` is
unchanged** in the Dockerfile—deployments that have EFA on the host are
expected to prepend those libraries when needed; elsewhere the bundle
stays inert.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
007d6d6b8af5e5f567fa94fce5e2b6f06e02d62a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 23:41:31 +02:00
Matej SirovatkaandGitHub 866c3e1438 refactor(trainer): make activation checkpointing operator-based (#3419)
## Summary

- Replace method- and attribute-based selective activation checkpointing
with one non-reentrant checkpoint region around each selected
transformer block.
- Keep `mode = "full"` as the default. Full mode retains only mandatory
non-replayable operations and recomputes everything else; selective mode
additionally retains configured expensive operations through the same
Prime-owned policy.
- Allow selective mode to replace its public default targets with
explicit operator names or namespaces. Correctness-required targets
remain active for every selective configuration.
- Register real runtime boundaries for Torch EP/CP collectives, DeepEP
combine, ring attention, sparse MLA, dense/grouped DeepGEMM, MXFP8
transport, and MoE routing telemetry so checkpointing, autograd, and
compile observe the same operations.
- Keep sparse MLA dispatcher, fake, and autograd registration beside the
vendored forward/backward kernel entrypoints rather than in GLM model
code.
- Collapse ring attention into one backend-neutral forward/backward
custom-op pair. Its adapters call only the pinned FA2, FA3, and FA4 APIs
explicitly, without signature probing or generated per-backend
registrations.
- Remove checkpoint-only attention helpers and the model-specific
checkpointing module. Generic attention, AFMoE, Qwen3.5, and Laguna keep
their projection/output logic directly in `forward`; GLM DSA keeps only
its substantive `mla_latents` and `mla_up_proj` helpers.
- Rebase onto the Torch 2.13, CUDA 13, and vLLM 0.28 runtime from
current `main`, and update FlashAttention 4 to `0251105` with the shared
TVM FFI version required by vLLM.
- Ignore FSDP replay-only profiler markers when selective checkpointing
validates the saved forward operation sequence.
- Prefetch the final MoE block, experts, and separately wrapped router
before backward replay so FSDP collectives occur in the same order as
the saved forward.

## Runtime contract

- Model implementations do not expose checkpoint target names or
checkpoint-only methods.
- `freq` selects whole transformer blocks; the dispatched operator and
selected target set determine whether selective AC saves or recomputes
its result.
- Both modes retain mandatory MoE routing, telemetry, non-replayable
DeepEP, and CUDA-to-CPU metadata operations so they execute once. Full
mode recomputes every other operation; selective mode additionally
retains its configured targets.
- The default selective targets retain supported attention, matrix
multiplication, grouped GEMM, and distributed communication operators.
Elementwise operations, norms, reshapes, and RoPE replay.
- Custom targets replace the selective defaults and match either an
exact operator name or an operator namespace. They cannot exclude
mandatory routing, telemetry, non-replayable communication, or
CUDA-to-CPU metadata operations.
- Unsupported or missing backend operators fail at their normal call
site; there is no checkpoint fallback layer.
- MXFP8 transport resolves `mxfp8_moe` inside its custom-op
implementation. MXFP8 grouped compute still resolves it during runtime
setup because the exported grouped GEMM is already an operator boundary.

## Configuration

```toml
[trainer.model.ac]
mode = "selective" # full | selective
freq = 1
# targets = ["aten::mm", "prime_rl_collectives"]
```

Omitting `targets` uses the public Prime defaults. Any explicit list
replaces those defaults; an empty list retains only the mandatory
operations.

## Validation

- Ruff, Ruff formatting, `uv lock --check`, and `git diff --check`
passed.
- Focused config, checkpointing, and Qwen3.5 CP tests on the rebased
dependency stack: 138 passed.
- A6000 CI regression suite passed all eight checks: four-GPU peak
memory was 6.2467 GiB against the 6.2988 GiB baseline (down from 6.6185
GiB before the fix); one-GPU peak memory was 10.6738 GiB.
- Compiled selective AC with DeepEP completed a two-GPU, two-step
`samsja/mini-glm-moe` training smoke after rebasing onto the merged MoE
runtime.
- The pinned FA2, FA3, and FA4 varlen backends all use the `[heads,
total_tokens]` LSE layout; the ring fake and backward paths enforce that
single contract.
- Two-H200 compiled ring validation matched each backend's direct
attention reference exactly for FA2, FA3, and FA4 output and `dq`, `dk`,
and `dv`.
- Full H200 unit suite: 574 passed, 9 skipped.
- Eager and compiled output/gradient/replay validation passed for local
MoE, Torch EP, DeepEP with and without chunking, CP, FA2/FA3 ring
attention, sparse MLA, dense DeepGEMM, grouped DeepGEMM, and the
production MXFP8 transport boundary with a fake numerical kernel.
- FSDP parameter/state-dict parity and selective AC plus activation
offloading passed.
- Whole-model parity passed for Llama, Nemotron-H, GPT-OSS, AFMoE,
Laguna, and Qwen3.5 full-attention layers. Sparse MLA parity also passed
after restoring its substantive helper structure.
- On the stacked Qwen3.8 Flash Next implementation, selective and full
activation checkpointing each completed 20 RL steps on 24 H200s with
compile, FSDP, expert parallelism, SignSGD, NIXL policy reload, and CPU
optimizer-state offload. Steps 2-20 averaged 8,008 tokens/s for
selective and 7,211 tokens/s for full; both peaked at 130.4 GiB and held
mismatch KL at 0.0014-0.0021 with a final value of 0.0016.

## Hardware boundary

- Numerical MXFP8 grouped GEMM and transport still require SM100
hardware. The H200 validation exercised the production
custom-op/autograd/compile boundary with a BF16 fake transport kernel.
- FA4 forward/backward numerical validation passed on H200 (SM90);
Blackwell remains untested in this PR.
- Qwen3.5 GatedDeltaNet whole-model parity did not reach execution
because the no-AC reference forward remained in FLA kernel compilation
until the diagnostic jobs were cancelled. Qwen3.5 full-attention parity
passed, and the GatedDeltaNet runtime code itself is unchanged.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Touches core training memory/throughput (activation checkpointing),
distributed MoE/DeepEP/ring attention autograd, and compile
boundaries—incorrect replay or double-counted routing would show up as
silent wrong grads or NCCL deadlocks.
> 
> **Overview**
> **Replaces layer-specific selective activation checkpointing** with
whole-block non-reentrant checkpointing driven by a PyTorch selective
operator policy (`activation_checkpointing.py`). Semantic targets like
`norm` / `attn_proj` are gone; `model.ac.targets` is now optional
operator names or namespaces that replace Prime’s defaults, while
mandatory saves still cover MoE routing/top-k, DeepEP, and CUDA→CPU
copies.
> 
> **Registers distributed and kernel paths as `torch.library` custom
ops** so checkpoint replay, autograd, and compile see the same
boundaries: new `prime_rl_collectives` for EP/CP all-to-all and
gather/reduce-scatter, `deepep::combine`, unified `prime_rl_ring` ring
attention (FA2/FA3/FA4), `prime_rl::sparse_mla`, FP8/grouped FP8 GEMMs,
and `record_moe_routing_statistics` so routing counters are not
double-applied on recompute. Inline `autograd.Function` wrappers in
token dispatch, Mamba CP, and ring attention are removed in favor of
these ops.
> 
> **Simplifies trainer wiring and models**: `apply_ac` always wraps
whole transformer blocks; the old `layers/checkpointing.py` hook layer
is deleted and attention modules no longer expose checkpoint-only
`attn_projections` / `output_proj` splits. FSDP backward prefetch now
includes the last block’s MoE experts/router. Docs, examples, and
benchmarks drop legacy selective target lists; **flash-attn-4** is
bumped to `0251105` with a pinned **apache-tvm-ffi** override.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
3a51c78f1ed46b0603ec42c1011c36e14533b710. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 22:52:33 +02:00
Konstantin DunasandGitHub c176840626 chore: bump renderers to 0.1.11, verifiers and prime-envs to main (#3441) 2026-08-31 22:14:00 +02:00
Mika SenghaasandGitHub bb0c103f08 fix: shard SFT data and report worker progress (#3417)
## Summary

- Resolve SFT data shard identities after worker processes start.
- Shard fake data by DP rank while replicating it across CP ranks.
- Read epoch and sample progress from the furthest worker cursor.
- Aggregate per-source sample and token counters across workers.
- Preserve worker counters across dataloader checkpoint resume.
- Extend the existing CPU dataloader suite with tiny in-memory SFT data
across worker, DP, and CP layouts.
- Clarify the dummy renderer token decode in the sharding test.

## Verification

A one-GPU SFT run used two local dataset splits, two data workers, and
four logged steps.

- Before: sample progress was `5, 5, 9, 9`, and source ratio metrics
were absent.
- After: sample progress was `9, 10, 17, 18`, and source sample and
token ratios were present at every step.
- Before the sharding fix, two workers yielded `0, 0, 1, 1, 2, 2, 3, 3`
from increasing fake data.
- The CPU regression matrix verifies unique DP shards, CP replicas,
checkpoint resume, counters, and the `0 → 1` epoch transition.
- The fake-data test verifies distinct samples across DP ranks and
identical samples across CP ranks.
- The uneven-packing regression verifies that worker progress never
moves backward.
- `uv run pytest tests/unit/train/sft/test_dataloader.py -q` passed with
16 tests.
- `uv run ruff check tests/unit/train/sft/test_dataloader.py
src/prime_rl/trainer/sft/data.py src/prime_rl/trainer/sft/train.py`
passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes distributed data partitioning and checkpointed iterator state,
which can silently skew training if wrong; behavior is covered by
expanded unit tests but affects core SFT loops.
> 
> **Overview**
> Fixes **incorrect SFT data sharding and stale progress metrics** when
using multiple DataLoader workers and/or context-parallel (CP) ranks.
> 
> **Sharding:** `data_rank` / `data_world_size` are now derived from
**DP rank only** (`rank // non_dp_size`), so CP ranks see the same
samples while DP ranks stay distinct. Rank/worker identity is resolved
in **`__iter__` via `_setup_world_info()`** instead of at dataset
construction, so worker processes get the right shard after fork.
> 
> **Progress & checkpoints:** `CatDataset` state now stores and restores
per-source **`num_samples` / `num_tokens`**. New
**`get_dataset_progress()`** reads worker snapshots, uses the **furthest
worker** for `step`/`epoch`, and **sums** counters across workers. SFT
training logs **`progress/*`** from the dataloader instead of the
main-process dataset object (which stayed at zero after resume).
> 
> **Tests:** Dataloader tests drop the heavy tokenizer/GPU mark, add a
shared dummy renderer, and cover multi-rank/worker sharding, resume, CP
replication, and monotonic progress under uneven packing.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
30f7de1d229f8e88e0f334be6b8baaa7d2dccf14. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-31 13:00:38 -07:00
Mika SenghaasandGitHub 3fc28ddfb3 fix: remove dispatch failures from summaries (#3432)
## Summary

- Remove dispatch-failure rates from per-step success logs.
- Exclude dispatch-failure metrics from curated W&B overview panels.
- Keep raw dispatch-failure metrics unchanged.

## Verification

Before: training success lines and W&B overview panels showed
dispatch-failure rates.

After: both summaries omit dispatch failures while the raw metrics
remain available.

- `uv run ruff check src/prime_rl/orchestrator/orchestrator.py
src/prime_rl/monitors/wandb/overview.py`
- `UV_PROJECT_ENVIRONMENT=/home/ubuntu/prime-rl/.venv uv run --no-sync
pytest tests/unit/orchestrator/test_metrics.py`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Presentation-only changes to logs and W&B overview panels; dispatch
failure metrics and pipeline handling are unchanged.
> 
> **Overview**
> **Dispatch failure rates are removed from operator-facing train
summaries** while leaving underlying W&B metrics intact.
> 
> The per-step **Step …** success log (aggregate and per-env `╰─` lines)
no longer computes or prints **Dispatch Failure**; multi-env breakdowns
also stop folding `batch.failures` into env name lists. Docstrings now
describe window metrics as **Error**, **Cancelled**, and **Ratio** only,
and clarify that cancellations are pipeline decisions rather than
rollout failures.
> 
> The curated W&B **overview** saved view drops
`all/dispatch_failure/mean` from `COMMON_METRICS`, so the default
dashboard panels no longer highlight dispatch-failure rate alongside
turns, tokens, and error/truncation signals. `dispatch_failure_metrics`
in `finalize_train_batch` is unchanged, so raw
`train/*/all/dispatch_failure/*` series remain available outside the
overview.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
db0d538c93bbcfa9e764e9f9f295dca9c1b45ab3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 22:06:11 -07:00
Mika SenghaasandGitHub eaad03b9df chore: bump vllm to 0.28.0 (#3430)
## Summary

Builds on the CUDA 13, Torch 2.13, and vLLM 0.27.1 stack from #3425.

- Bump vLLM to 0.28.0. Torch stays at 2.13.0+cu130; only the wheel pins
move. vLLM 0.28 requires `nvidia-cutlass-dsl == 4.6.2` and
`quack-kernels == 0.6.4`, so the override pin and its dependency
metadata move with it.
- Drop patches obsoleted by the pinned release (reviewed the
0.27.0/0.27.1/0.28.0 release notes and diffed the patched vLLM sources
between 0.27.1 and 0.28.0):
- `monkey_patch_harmony_stop_token_propagation` — fixed upstream by
vllm#35076 (in the release since 0.27.1).
- `monkey_patch_fp32_router_logits` — vLLM reads `moe_router_dtype` off
the HF config (vllm#47410) and forces fp32 routing for GLM-5.x.
`inference.enable_fp32_router_logits` keeps its name and default but now
injects `hf_overrides = {"moe_router_dtype": "float32"}` instead of
patching `DeepseekV2MoE`.
- `PrimeRlServingTokens` — upstream `serve_tokens` now handles DP-rank
header routing, server-side `max_tokens` defaulting, and `usage`
reporting (cached tokens surface via `--enable-prompt-tokens-details`,
which the launcher now sets). The subclass shrinks to the compact
`routed_experts` export and the `kv_transfer_params` engine bridge
(vllm#42644 merged 6h after the 0.28.0 cut — drop at the next bump).
- Follow vLLM's own V1/V2 model runner resolution instead of pinning V1
globally. vLLM resolves non-MoE generate models (plus an arch allowlist)
to the V2 runner. Only routed-experts capture still requires V1 (the V2
runner silently never captures routing decisions): the launcher pins
`VLLM_USE_V2_MODEL_RUNNER=0` when `enable_return_routed_experts` is set,
and the NIXL routed-experts patch rejects a V2 resolution explicitly.

Patches verified still needed on 0.28.0 (targets byte-identical or issue
still open): kv-xfer freed-request assert (vllm#46240), qwen3_coder
param newline trim, minimax-m2 think-end passthrough, TokenizeParams
validation, DP coordinator startup timeout, LoRA expert-key acceptance
(vllm#38522 closed unmerged), Qwen3.5-MoE 2D LoRA format, online-fp8
Parameter cast, nano_v3 reasoning parser, fp32 lm_head (kept over vLLM's
`head_dtype=float32`, which upcasts the weight per forward instead of
using an fp32-out GEMM), chat routed-experts strip.

Known 0.28 caveats:
- NIXL connector handshake version bumps 5 → 7: a 0.27 and a 0.28 engine
refuse to transfer KV to each other, so rolling P/D upgrades need a full
pool restart.
- vllm#50465 (batch-sharded sampling, merged after 0.28.0) silently
drops sampling masks under TP; re-check vllm#53826 before the next bump.

Validated on GLM-4.5-Air SWE

<img width="882" height="241" alt="Screenshot 2026-08-28 at 9 08 56 PM"
src="https://github.com/user-attachments/assets/d1af34c4-a80a-410b-bcdc-afdf0ffabd81"
/>

## Verification

- `uv lock --check`
- `uv run --frozen pytest -q tests/unit/test_configs.py
tests/unit/inference` (137 passed)
- Ruff check and format checks for the changed Python files
- E2E reverse-text RL on this branch (Qwen3-0.6B-Reverse-Text-SFT, 20
steps, 1 trainer + 1 inference GPU, NCCL broadcast): reward 0.18 → 0.81,
0% rollout errors, 100% trainable, mismatch KL 0.003–0.005. The engine
ran the V2 model runner (vLLM's default for this model) with the fp32
lm_head patch active. W&B: `reverse-text/reverse-text-vllm028-smoke`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> A broad inference dependency bump plus behavioral changes to MoE
routing, model-runner selection, and P/D KV transfer bridging;
misconfiguration could affect logprob fidelity, router replay, or
disaggregated decode performance until upstream fixes land.
> 
> **Overview**
> Upgrades the GPU inference stack from **vLLM 0.27.1 to 0.28.0**, with
matching lockfile and wheel pins (`nvidia-cutlass-dsl` 4.6.2,
`quack-kernels` 0.6.4).
> 
> **Config / launcher:** `to_namespace()` now defaults
**`enable_prompt_tokens_details`** so `/inference/v1/generate` `usage`
includes cached prompt tokens for router billing.
**`enable_fp32_router_logits`** no longer sets `additional_config`; it
injects **`hf_overrides.moe_router_dtype = "float32"`** so vLLM’s native
MoE routing path applies. **`VLLM_USE_V2_MODEL_RUNNER=0`** is set only
when **`enable_return_routed_experts`** is on (V2 never captures routed
experts); other models follow vLLM’s V1/V2 resolution.
> 
> **Removed patches** superseded by 0.28: harmony stop-token merge on
chat completions, `DeepseekV2MoE` fp32 router monkey-patch, and most of
the custom `ServingTokens` fork (DP routing, `max_tokens` defaulting,
manual `usage` assembly). **`PrimeRlServingTokens`** now delegates to
upstream `serve_tokens` except for **`kv_transfer_params` →
`sampling_params.extra_args`** (PD disagg until vllm#42644 ships) and
compact **`routed_experts`** post-processing.
> 
> **Other:** NIXL routed-experts guard uses
**`config.use_v2_model_runner`** instead of the env flag. Unit tests for
deleted helpers are trimmed; post-process test asserts `usage` is
preserved from upstream responses.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
77c9264df8bb12af89eda7c238e2415e9a339857. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 21:57:26 -07:00
Mika SenghaasandGitHub 70117046ac fix: bump torch 2.13 + vllm 0.27.1 + custom wheels for cuda 13 (#3425)
## Summary

- upgrade Torch to 2.13 and vLLM to 0.27.1 on CUDA 13
- pin matching CUDA 13 wheels for FlashAttention, prime-kernels, DeepEP,
DeepGEMM, TorchAO, NIXL, CUTLASS DSL, cuDNN, and vLLM
- load DeepGEMM only when FP8 kernels execute so CPU imports do not
require a CUDA toolkit
- reject TorchAO MXFP8 on GPUs other than SM100
- move native wheel builds to prime-kernels and remove the duplicate
PrimeRL workflow and build scripts
- use the CUDA 13 toolkit and runtime in the PrimeRL CUDA image

Validated against GLM-4.5-Air SWE run

<img width="295" height="227" alt="Screenshot 2026-08-28 at 7 29 36 PM"
src="https://github.com/user-attachments/assets/d125177e-86e0-4a2e-bb78-3a44bb4f15ce"
/>

<img width="294" height="239" alt="Screenshot 2026-08-28 at 7 30 05 PM"
src="https://github.com/user-attachments/assets/ea277670-c42a-49b6-a2cc-b10c5d9b8713"
/>

## Breaking

- remove `scripts/install_deep_gemm.sh` and
`scripts/install_ep_kernels.sh`; use the builders under
`deps/prime-kernels/scripts/` for source builds

## Verification

- `uv lock --check`
- `git diff --check`
- `bash -n deps/prime-kernels/scripts/install_deep_gemm.sh
deps/prime-kernels/scripts/install_ep_kernels.sh`
- Ruff check and format checks for the changed Python files
- verified that importing `prime_rl.trainer.model` does not import
DeepGEMM
- verified that MXFP8 rejects the local SM120 GPU with an SM100
requirement
- ran FlashAttention 2 forward on the local SM120 GPU
- `uv run pytest tests/unit -m "not gpu"`: 476 passed and one unrelated
Qwen3-VL fake-response assertion failed
- after merging `main`, focused config and MoE tests passed: 148 passed
and 3 skipped


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Wide dependency and Docker CUDA migration affects training, inference,
MoE/FP8, and disaggregated NIXL paths; MXFP8 now fails on non-SM100 GPUs
that previously passed the SM100+ check.
> 
> **Overview**
> Moves the GPU stack from **CUDA 12.8 / torch 2.9 / vLLM 0.26** to
**CUDA 13 / torch 2.13 / vLLM 0.27.1**, with matching prebuilt wheels
(FlashAttention, prime-kernels, DeepEP, DeepGEMM, torchao, NIXL, cuDNN,
CUTLASS) pinned via `[tool.uv.sources]` to **prime-kernels** release
assets instead of prime-rl releases. `uv` **dependency-metadata**
overrides steer NIXL and CUTLASS toward CUDA 13 variants so cu12
packages are not pulled alongside extras.
> 
> **CI and packaging:** Deletes `.github/workflows/build_kernels.yaml`
and the release jobs that built kernel wheels before publishing; native
wheel builds are documented as owned by the **prime-kernels** repo.
Removes in-repo `install_deep_gemm.sh` / `install_ep_kernels.sh` in
favor of `deps/prime-kernels/scripts/`.
> 
> **Docker:** `Dockerfile.cuda` uses **nvidia/cuda 13.0.1** end-to-end,
drops the sidecar CUDA 13 runtime copy used for deep-gemm, and installs
**nixl_cu13** when building NIXL from source.
> 
> **Runtime behavior:** **DeepGEMM** is imported lazily inside FP8
autograd paths so CPU-only imports do not require the CUDA toolkit.
**MXFP8** quantization is restricted to **exactly SM100** (not
“SM100+”), and torchao’s MXFP8 linear helper import path is updated.
Benchmark baseline JSON files are refreshed for the new commit and
benchmark harness fields.
> 
> **Docs/skills:** Install and kernels skills describe `uv sync --extra
disagg` and prime-kernels release workflow instead of the removed
PrimeRL kernel CI.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
4f6159cbe8333759cb55720ca2abaeeb7ff8b40b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 21:01:28 -07:00
Matej SirovatkaandGitHub b2c6fe9aec refactor(moe): unify runtime and checkpoint layout (#3411)
## Summary

### Model and checkpoint contract

- Replace the separate standard, GPT-OSS, and Nemotron expert/router
implementations with one canonical MoE tree.
- Store routed expert weights as separate `gate_proj`, `up_proj`, and
`down_proj` parameters. Non-gated experts omit `gate_proj`.
- Nest every custom router at `mlp.router.gate`, routed experts at
`mlp.experts`, and optional shared experts inside `mlp`.
- Store the single selection-only router bias at
`mlp.router.selection_bias`; model-specific checkpoint names are
converted only at the HF boundary.
- Keep shared expert projections canonical. Qwen3.5 alone nests its
scalar sigmoid gate at `mlp.shared_expert.output_gate`, with conversion
mapping the standalone Hugging Face key at the boundary.
- Use the same activation protocol and `FeedForward` implementation for
dense MLPs, shared experts, and grouped experts.
- Make shared-expert construction exclusively parent-owned: model layers
pass an explicit `FeedForward`/subclass or `None`, while `MoEArgs` and
`MoE` never infer or construct one.
- Keep existing HF source layouts at the conversion boundary. GPT-OSS
alone adds the structural split/join required for its interleaved source
tensor.
- Require `.prime-v1` in reusable `<conversion_dir>/prime` caches so
legacy Prime layouts fail before loading.

### MoE runtime contract

- Use one routed execution sequence for every backend: dispatch tokens,
run canonical grouped experts, combine tokens.
- Select grouped expert compute through explicit BF16, DeepGEMM FP8, or
MXFP8 implementations. `MoEArgs` remains architecture-only.
- Select local/Torch or DeepEP token dispatch once during model setup.
Dispatchers own routing metadata, communication, padding, chunking, and
synchronization.
- Keep `TokenDispatcher` as the structural interface while a shared base
owns the canonical run/synchronize sequence; local, Torch, and DeepEP
implementations own only their dispatch/combine details.
- Keep DeepEP combine events, concatenate streams, and flattened
dispatch state owned by each dispatcher; chunking uses the equal input
shape shared by EP ranks and does not synthesize empty chunks.
- Ignore dispatch configuration when expert parallelism resolves to one
rank; local dispatch remains active and DeepEP has no optimizer side
effects.
- Keep grouped expert execution directly in `GroupedExperts.forward` and
router confidence accounting directly in
`TokenChoiceTopKRouter.forward`.
- Shard every canonical expert parameter with one backend-independent
`Shard(0)` placement.
- Keep dense linear quantization, routed-expert compute, and EP
transport independent.
- Remove the TorchTitan module hooks, expert decorator, dynamically
attached process group, backend attributes, tensor-subclass
interception, and process-global MXFP8 patches from the reachable path.
- Vendor the narrow MXFP8 grouped-GEMM and Torch EP transport
implementation in [prime-kernels PR
#1](https://github.com/PrimeIntellect-ai/prime-kernels/pull/1),
preserving the pinned torchao revision and BSD license.

## Public contracts

Checkpoint tree:

- `mlp.router.gate`: `nn.Linear`
- `mlp.router.selection_bias`: optional persistent selection-only buffer
- `mlp.experts.gate_proj`: stacked `nn.Parameter` for gated experts,
absent for non-gated experts
- `mlp.experts.up_proj`: stacked `nn.Parameter`
- `mlp.experts.down_proj`: stacked `nn.Parameter`
- `mlp.shared_expert.{gate_proj,up_proj,down_proj}`: `FeedForward`
projections when present
- `mlp.shared_expert.output_gate`: Qwen3.5-only scalar `nn.Linear`
- expert matrices: `[num_experts, output_features, input_features]`

Runtime configuration:

```toml
[trainer.model.moe.compute]
type = "bf16"  # bf16 | deepgemm_fp8 | mxfp8

[trainer.model.moe.dispatch]
type = "torch"  # torch | deepep
transport = "bf16"  # bf16 | mxfp8 for torch dispatch
```

DeepEP owns its tuning fields:

```toml
[trainer.model.moe.dispatch]
type = "deepep"
num_sms = 20
token_chunk_size = 4096
```

This is intentionally breaking. `enable_grouped_gemm`, `enable_a2a`,
`ep_comm_backend`, `deepep_num_sms`, and `deepep_token_chunk_size` are
removed without aliases.

## Validation completed

- Foundation conversion, detector, marker, state-loading, checkpoint,
NIXL graph, and wire-format tests passed.
- Focused CPU configuration and MoE contracts: 143 passed.
- Focused MoE runtime configuration parametrizations after the EP=1
no-op change: 6 passed.
- Affected custom-model CUDA suite: 24 passed, 3 skipped across AFMoE,
GLM, GPT-OSS, Nemotron, Qwen3/Qwen3.5, and state loading.
- Final H200 model suite after execution-path cleanup: 81 passed, 3
skipped (Slurm 2597).
- Torch EP on two H200 GPUs passed with BF16 and DeepGEMM FP8, top-k 2,
both score locations, shared experts, gated/non-gated/bias variants,
uneven routing, a rank receiving zero routed tokens, and
input/router/expert gradients.
- Final Torch EP BF16 and DeepGEMM FP8 matrix passed after the cleanup
(Slurm 2596).
- DeepEP on two H200 GPUs passed with BF16 and DeepGEMM FP8, chunking
on/off, both score locations, shared experts, a rank receiving zero
routed tokens, and gradients.
- Final DeepEP BF16 and DeepGEMM FP8 matrix passed after the cleanup
(Slurm 2595).
- Parent-owned shared-expert construction: 16 focused CPU tests and 64
H200 model tests passed, with 3 expected skips (Slurm 2600).
- Full-graph MoE and shared `FeedForward` compile validation passed
after the ownership cleanup (Slurm 2601).
- Local DeepGEMM FP8 passed across all supported topology, activation,
and bias combinations.
- `torch.compile(fullgraph=True)` forward/backward passed for the full
MoE and shared `FeedForward` across all supported topology/activation
combinations.
- Single-rank DCP and Torch EP + FSDP DCP model/optimizer resume passed.
- The `mxfp8_moe` wheel build includes its public module, manifest, and
license; the module imports against the pinned torchao build.
- Unsupported H200 MXFP8 selection fails before model mutation.
- Review audit: every queued DeepEP combine event is now synchronized,
including chunked execution (two-H200 Slurm 2604).
- Dispatcher review cleanup passed on two H200s: DeepEP BF16/DeepGEMM
with chunking and a zero-receive rank (Slurm 2847), plus Torch EP
topology/bias/zero-receive coverage (Slurm 2848).
- The exact `reverse_text_moe` integration passed end-to-end on two
H200s with an isolated conversion cache (Slurm 2607).
- Conversion ranks now make the create decision on master and validate
`.prime-v1` only after the final all-rank barrier.
- Canonical router selection bias: 12 CPU MoE/conversion tests passed;
CUDA checkpoint loading, Nemotron, and GLM model tests passed, with the
existing GLM BF16 gradient comparison passing on isolated rerun after
one threshold-edge miss (Slurm 2851/2852).
- Ruff, Ruff formatting, compileall, and `git diff --check` passed.

## Deliberate exclusions

- MultiLoRA is not adapted to the new runtime and may fail.
- Fused-MoE trainer integration is removed and will be reconsidered only
after the canonical runtime is finalized.
- Routed-expert selective activation checkpointing is removed; the
remaining selective targets are unchanged.

## Remaining before marking ready

- Run numerical MXFP8 grouped-GEMM and MXFP8 Torch EP transport
forward/backward on SM100 hardware. The available Slurm fleet currently
has only H200 nodes.
- Merge prime-kernels PR #1, publish wheels containing `mxfp8_moe`, and
update the `pyproject.toml`/lock wheel pins. The currently pinned v0.8.0
wheel does not contain this module.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> This changes the MoE forward/backward path, expert-parallel dispatch,
checkpoint key layout, and trainer TOML in breaking ways across all
custom MoE models.
> 
> **Overview**
> **Breaking trainer config:** MoE is configured via
`[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, `mxfp8`) and
`[trainer.model.moe.dispatch]` (`torch` with `transport`, or `deepep`
with `num_sms` / `token_chunk_size`). Dense
`[trainer.model.quantization]` no longer drives expert GEMMs or EP
transport. Removed flags include `ep_comm_backend`, `deepep_*`,
`moe_use_grouped_mm`, `moe_fused_kernel`, and quantization
`enable_grouped_gemm` / `enable_a2a`.
> 
> **Unified MoE execution:** All custom models share one `MoE`
path—`TokenChoiceTopKRouter`, stacked `GroupedExperts` (`gate_proj` /
`up_proj` / `down_proj`), and a pluggable `TokenDispatcher`
(`LocalTokenDispatcher`, `TorchTokenDispatcher`,
`MXFP8TorchTokenDispatcher`, `DeepEPTokenDispatcher`).
`configure_moe_runtime` wires grouped GEMM backends and dispatch at
setup; EP weight sharding is only `ExpertWeightParallel`. DeepEP
dispatch/combine, grouped-GEMM permutation, and chunk pipelining live in
the new dispatcher layer instead of ad hoc `MoE` hooks.
> 
> **Checkpoint and model surface:** PrimeRL checkpoints rename routed
weights from `w1/w2/w3` to `gate/down/up_proj`, move selection bias to
`mlp.router.selection_bias`, and add GPT-OSS HF↔prime conversion.
`LatentMoE` / Nemotron-specific expert classes are folded into the
canonical tree; dense layers use `FeedForward`. Reusable `prime`
conversion caches must include a `.prime-v1` marker.
> 
> **Removed / docs:** Fused `flash_moe` trainer integration and
`bench_fused_moe.py` are dropped; `routed_experts` selective activation
checkpointing is removed. Docs and examples (e.g. GLM-5) are updated for
the new tables.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ffd5be7d48d28b889f9d73c8815ab0eb618b9dc9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-29 01:03:32 +02:00
Yaser AfsharandGitHub 66e1c2cb07 chore(nixl): use canonical VRAM mem_type (#3215)
## Change

`prep_xfer_dlist(mem_type=...)` passed `"cuda"`, which nixl marks
deprecated in
favor of `"VRAM"` (`src/api/python/_api.py`):

    "VRAM": nixlBind.VRAM_SEG,
    "cuda": nixlBind.VRAM_SEG,  # deprecated

Both resolve to `VRAM_SEG`, so this is a no-op at runtime. `"VRAM"` is
also the
spelling nixl's own `_tensor_mem_type()` helper emits.

## Note

The accelerator-derived `UCX_TLS` defaults this PR originally carried
are dropped
per review. Since `set_ucx_env_defaults()` uses `setdefault`, a non-CUDA
accelerator supplies its own copy transport from the launcher
environment.

---------

Signed-off-by: Yaser Afshar <yaser.afshar@intel.com>
2026-08-29 00:27:17 +02:00
Matej SirovatkaandGitHub 26af0c49e6 perf(nixl): pipeline reusable weight pulls (#3341)
## Summary

- use ModelExpress only for startup peer discovery and the trainer
tensor table, then use exact versioned NIXL notifications for all policy
transfers, including startup
- prepare static NIXL READ requests once, repost them after completion,
and post every trainer-rank pull in a group before waiting
- attach trainer arena credits to READ completion instead of performing
a separate acknowledgement handshake
- add explicit, opt-in two-arena overlap through
`weight_broadcast.overlap_transfer_and_replay`

The path remains receiver-driven PULL. The default remains one arena
because the second arena has a model-dependent GPU-memory cost. This PR
adds no fallback protocol, runtime sizing heuristic, profiling
instrumentation, or inference-scheduler change.

## Protocol

ModelExpress is the one-time startup discovery plane. It exchanges the
trainer tensor table and NIXL agent metadata, after which the fixed
peers establish NIXL/UCX connections. The shared
`WeightSender`/`WeightReceiver` sentinel handshake offers and
acknowledges every policy version before the NIXL transport runs; this
is the same outer lifecycle used by the other transports. MX source
statuses are not used. Policy 0 and later policies use exact NIXL ready
and complete notifications for the transfer itself.

```mermaid
sequenceDiagram
    participant T as Trainer ranks
    participant B as Broadcast directory
    participant R as NIXL weight receiver
    participant MX as ModelExpress
    participant I as Inference ranks

    Note over T,I: One-time setup
    I->>MX: Publish inference NIXL metadata
    R->>MX: Publish receiver NIXL metadata

    loop Each policy version
        T->>B: Offer version with sender ready marker
        R->>B: Acknowledge with receiver ready marker
        T->>B: Mark transfer started
        alt First version
            T->>MX: Publish tensor table and trainer metadata
            T->>MX: Fetch inference and receiver metadata
            R->>MX: Fetch trainer table and metadata
            Note over T,I: Establish NIXL and UCX connections once
        end
        T-->>R: NIXL policy ready notification
        R->>I: Update weights
        loop Each transfer group
            T-->>I: NIXL group ready notification
            I->>T: Post READs to every trainer rank
            T-->>I: RDMA payload
            I-->>T: READ completion returns arena credit
        end
        I-->>R: Update complete
        R-->>T: NIXL policy complete notification
        T->>B: Commit version with finished marker
    end
```

Each group signal contains `(group index, generation)`, and each policy
signal contains `(step, event)`, so it is consumed exactly once. A
trainer staging slot is reused only after every inference rank completes
its READ from that slot.

`NIXLWeightReceiver` owns the ModelExpress discovery session, local NIXL
agent, and typed trainer peer in the orchestrator process. The generic
orchestrator and `WeightWatcher` only use the `WeightReceiver` API and
contain no NIXL-specific state. Transfer plans and the trainer
broadcaster store ordered `NixlPeer` lists, so positional trainer-agent
indices stay direct list lookups and raw NIXL agent names remain inside
the adapter. On the trainer, `finish_transfer_group` waits for every
inference rank to complete a group before advancing its generation and
allowing its arena slot to be reused.

Tensor addresses, shard routes, peers, and descriptor lists remain
static for the worker lifetime. Requests are therefore prepared once and
reposted after completion. For each group, inference waits for every
serving trainer rank, posts all trainer-rank READs, and then waits for
completion. Inference ranks rotate their trainer order, while #3340 pins
each process to the active InfiniBand port nearest its GPU.

With overlap enabled, trainer and inference allocate exactly two
largest-group-sized arenas. Inference replays and quantizes group N
while receiving group N+1. Allocation is explicit: there is no
free-memory probe, automatic downgrade, or hidden retry.

## Measured results

Every populated cell below is the median of the positive framework
`time/broadcast_weights` samples; terminal zero entries are excluded.
This is the only timing definition used in the description. Parentheses
contain Slurm job IDs, and blank cells mean that configuration was not
measured.

| Model | Old NIXL | New NIXL | New NIXL + overlap | NCCL |
|---|---:|---:|---:|---:|
| Qwen3-30B-A3B | 4.651 s (2260) | 1.898 s (2278) |  |  |
| GLM-4.5-Air | 8.676 s (2286) | 4.125 s (2288) | 3.043 s (2305) | 7.616
s (2289) |
| GLM-5.2 |  | 12.513 s (2297) | 8.577 s (2317, EP32) |  |

All NIXL baselines use the correct rail pinning, and router replay is
disabled. The GLM-4.5-Air old, new, and overlap measurements are 20-step
Hendrycks-math runs with 4096 maximum sampling tokens; the NCCL
comparison uses the same model and node roles over three positive
broadcasts. NCCL uses BF16 checkpoint-format transfer with
`quantize_in_weight_transfer = false`.

GLM-5.2 job 2317 completed 20 rollout steps and 18 steady trainer
broadcasts on 64 trainer and 32 inference H200s. Framework
`time/broadcast_weights` was 8.577s median and 12.987s p95. At the
inference client, end-to-end synchronization was 7.899s median and
12.577s p95: pause was 5.204s median / 9.882s p95, while the weight
update itself was 2.842s median / 2.960s p95. Each inference GPU
received 82.501 GB per policy; across all 576 rank/version samples, RDMA
was 1.864s median / 2.027s p95, replay was 1.954s median / 1.993s p95,
and their overlapped process time was 2.682s median / 2.836s p95. Median
payload was 44.26 GB/s per GPU, or approximately 354 GB/s across an
eight-GPU inference node. The [W&B
run](https://wandb.ai/primeintellect/prime-rl/runs/c3bee790465640d88958f100fb3d74f4)
contains the completed training metrics.

On this single framework metric, Qwen improves by 59.2% from old to new.
GLM-4.5-Air improves by 52.5% from old to new and 64.9% from old to the
final overlapped path; the final path is 60.1% faster than NCCL. GLM-5.2
improves by 31.5% from the measured EP16 one-arena path to the EP32
overlap run. Holding overlap constant, EP32 reduces median framework
broadcast time by 11.4% from the EP16 result (9.683s, job 2301), while
median client update time falls by 19.4% from 3.524s to 2.842s.
Framework timing includes the unchanged vLLM pause/resume interval,
whose variance dominates the EP32 tail, so it should not be interpreted
as raw fabric bandwidth.

## Memory and scope

Overlap adds one largest-group arena rather than another model copy. For
GLM-5.2, that is 0.308 GB per trainer GPU and 3.807 GB per inference
GPU. The EP32 run therefore used a 7.613 GB two-buffer arena per
inference GPU and added 141.5 GB across the tested
64-trainer/32-inference topology. The option is disabled by default;
models without that headroom retain the one-arena path.

GLM-5.2 uses 64 trainer H200s with EP=8 and full offload, plus DP/EP
inference with online blockwise FP8 and DeepGEMM. EP16 receives 127.800
GB per inference GPU and retains 5,056 host-side handles per rank; EP32
receives 82.501 GB per GPU and prepares 72,819 descriptors across 79
transfer groups per rank. These request structures add no model-sized
GPU allocation.

Every serving trainer rank connects to every inference rank so
completion returns exact source credits. Static membership is the
expected hot path; elastic scaling and fault tolerance remain out of
scope.

## Numerical validation

Jobs 2286 and 2305 completed the configured 20 GLM-4.5-Air rollout steps
and finalized metrics. Step 20 of job 2305 contained 0/8 trainable
traces, so it correctly emitted no optimizer or mismatch-KL row. Across
the 19 steps with measurements in both runs, mean mismatch KL was
0.002602538 before and 0.002608075 after (+0.2%); median was 0.002786405
before and 0.002702605 after (-3.0%). Router replay was deliberately
disabled, so individual steps include normal sampling variation.

## Validation

- Ruff 0.15.14: `uv run ruff format --check` and `uv run ruff check`
- `uv run python -m compileall` on changed Python modules
- `uv run pytest -q tests/unit/test_configs.py`
- ported onto main at `21a4a3245` through #3340 at `0d809b1e4`; the
generic orchestrator and `WeightWatcher` are unchanged
- two-node, three-step Qwen3-0.6B end-to-end NIXL smoke (Slurm job
2451): startup policy v0 and policies v1-v3 synchronized; trainer and
orchestrator completed
- Qwen3-30B-A3B and GLM-4.5-Air eight-rail transfer benchmarks
- GLM-5.2 ten-node EP16 and twelve-node EP32 runs with full trainer
offload, online blockwise FP8 inference, and DeepGEMM
- matched NCCL comparison on GLM-4.5-Air
- final 20-step GLM-4.5-Air Hendrycks-math run with 4096 sampling tokens
and router replay disabled

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes core distributed weight-sync choreography between trainer,
orchestrator, and vLLM; mis-sync would cause stale weights or hangs,
though scope is limited to the NIXL transport path.
> 
> **Overview**
> **NIXL weight broadcast** is reworked so ModelExpress is only used for
one-time peer discovery (trainer tensor table and NIXL agent metadata).
Per-group and per-policy coordination now uses **versioned NIXL
notifications** instead of ModelExpress READY/INITIALIZING buffer
sessions.
> 
> The NIXL adapter gains **`PreparedRead`** / **`NixlPeer`**: READ
descriptor lists are prepared once, reposted each update, and all
trainer-rank pulls in a group are posted before waiting. Arena reuse is
tied to READ completion via group `(index, generation)` signals; the
orchestrator participates with policy `ready` / `complete` notifications
over NIXL.
> 
> Inference follows the trainer’s **`staging_buffer_count`** (no GPU
free-memory sizing heuristic). Optional
**`weight_broadcast.overlap_transfer_and_replay`** allocates exactly
**two** largest-group arenas on trainer and inference so the next group
can be received while the current one is replayed; default remains one
arena.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0dc85f865aa7850e5a123fbb2791a9670c631d44. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 23:04:08 +02:00
Matej SirovatkaandGitHub fc12ef2c66 feat(slurm): launch ModelExpress for NIXL transfers (#3340)
## Summary

- start a job-scoped Redis and ModelExpress service when
`slurm.launch_modelexpress = true`
- inject the trainer-head service address into trainer, inference, and
orchestrator processes, or use the configured host when
`slurm.launch_modelexpress = false`
- pin every NIXL process to the active InfiniBand HCA nearest its GPU,
so an eight-GPU node uses all eight rails
- add a pinned, idempotent installer for ModelExpress v0.3.0 and Redis
7.4.2
- remove stale job-scoped ModelExpress and Redis processes before
managed-service startup

This is the launch prerequisite for the stacked transfer optimization in
#3341. It does not change the NIXL transfer protocol itself.

## Design

With `slurm.launch_modelexpress = true`, the generated job removes stale
ModelExpress and Redis processes from an interrupted managed launch,
then starts both services on the trainer head before launching the three
prime-rl components. The resolved ModelExpress address is passed to
every component, and service logs stay in the run directory. With
`slurm.launch_modelexpress = false`, the launcher performs no service
cleanup, starts no service, and uses `weight_broadcast.host` and
`weight_broadcast.port` unchanged.

Rail selection remains local to each NIXL process. Unless
`UCX_NET_DEVICES` is explicitly configured, startup resolves the process
GPU's PCI path, selects the nearest active InfiniBand port, and
constrains UCX to that port. TP8 therefore uses one distinct local rail
per GPU instead of relying on UCX's cluster-dependent default choice.
`UCX_NET_DEVICES` remains an explicit site override.

The installer pins both service versions, verifies their checksums, and
reuses valid existing installations. Generated jobs fail directly if a
required binary or UCX capability is missing.

## Scope

- ModelExpress provides startup discovery for a fixed Slurm allocation.
- Elastic discovery, autoscaling, and fault tolerance are intentionally
out of scope.
- The local service adds two small CPU processes on the trainer head and
no GPU allocation.

## Validation

- `bash -n scripts/install_modelexpress.sh`
- ran `scripts/install_modelexpress.sh` twice and verified that the
pinned binaries are reused
- rebased onto `main` at `21a4a3245`; rendered and shell-checked managed
and external ModelExpress modes for single-node and multi-node NIXL
Slurm jobs, including main’s trainer/orchestrator completion markers
- verified stale-service cleanup is present only in managed ModelExpress
renders and absent in external-service renders
- Ruff 0.15.14: `uv run ruff format --check` and `uv run ruff check`
- `uv run python -m compileall` on changed Python modules
- `uv run pytest -q tests/unit/test_configs.py` (122 passed)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes multi-node SLURM launch and NIXL UCX/IB selection for weight
sync; misconfiguration or rail selection bugs could break or degrade
policy updates, but scope is limited to NIXL SLURM paths.
> 
> **Overview**
> Adds **job-scoped ModelExpress + Redis** startup for SLURM RL when
`[weight_broadcast] type = "nixl"` and **`slurm.launch_modelexpress`**
is true (default). Single- and multi-node sbatch templates verify the
**`third_party/ucx`** build, optionally start pinned
**modelexpress-server** / **redis-server** (new
**`scripts/install_modelexpress.sh`**), wait for readiness, and pass
**`--weight-broadcast.host`** into trainer, orchestrator, and the local
`rl` launcher. With **`launch_modelexpress = false`**, jobs use
configured **`weight_broadcast.host`** / **`port`** and skip
managed-service cleanup.
> 
> **NIXL networking** now picks **`UCX_NET_DEVICES`** per process from
the **InfiniBand port nearest each GPU** (unless already set), and
inference workers **rotate which trainer ranks they pull from** so
concurrent pulls spread across rails.
> 
> Docs and the start-run skill describe install steps and the new SLURM
flag. **Does not change the NIXL transfer protocol** (prerequisite for
stacked transfer work).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0d809b1e4d24121690faab3a22b1f7f832de4f53. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-28 22:43:22 +02:00
Mika SenghaasandGitHub 95734aa1dd feat: make ipo the default rl loss (#3418)
## Summary

- Remove the DPPO loss and make IPO the default RL loss.
- Rename the IPO trust-region setting from `ipo_threshold` to `eps`.
- Update token exports, metrics, docs, tests, and agent skills for IPO.

## Breaking

- Remove `[trainer.loss] type = "default"`, `DefaultLossConfig`, and
`default_loss_fn`. Omit `[trainer.loss]` or set `type = "ipo"`.
- Rename `ipo_threshold` to `eps`. Update all IPO loss configs to use
`eps`.
- Remove the DPPO-only `dppo_mask_low` and `dppo_mask_high` settings.
- Remove the DPPO-only `is_masked_low`, `is_masked_high`, and
`masked_advantage_*` trainer metrics. Use `is_masked` for the IPO
trust-region mask.

## Verification

- RL loss GPU tests: 10 passed.
- Nemotron-H KL pipeline GPU tests: 7 passed.
- Ruff check and format hooks passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Removes the default RL loss and changes default training dynamics for
every run that relied on implicit DPPO; configs using `type = "default"`
or DPPO fields will fail or need migration.
> 
> **Overview**
> Makes **Importance Policy Optimization (IPO)** the only built-in RL
loss and the default when `[trainer.loss]` is omitted. The DPPO-based
`default` loss (`DefaultLossConfig`, `default_loss_fn`, `dppo_mask_low`
/ `dppo_mask_high`) is removed.
> 
> IPO trust-region config is renamed from `ipo_threshold` to **`eps`**
(default `0.1`). `setup_rl_loss_fn` always routes non-custom configs to
`ipo_loss_fn`.
> 
> **Breaking for configs:** use `type = "ipo"` or omit the section;
`type = "default"` and DPPO knobs no longer exist.
> 
> Monitoring and exports align with symmetric IPO masking: docs/skills
point to **`is_masked/mean`** instead of DPPO `masked_advantage_*`
metrics; W&B filtering drops the old DPPO-only series; token export
computes mask flags from `|prob_delta| > eps`. Unit tests now exercise
IPO instead of the default loss.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
2c4227527992519e8ff7e1d08c8866c5068febb1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-27 11:35:01 -07:00
Mika SenghaasandGitHub 0c58f007bc feat: record run invocation (#3409)
## Summary

- Write a shell-safe `command.txt` for every config attempt.
- Keep the outer command when a pinned child launch uses the same
attempt.
- Show each attempt's command in the dashboard Config view.
- Document the command artifact in the config and training runbooks.

<img width="2656" height="1506" alt="Screenshot 2026-08-26 at 11 34
20 AM"
src="https://github.com/user-attachments/assets/d5b4da3a-f6a9-4bdc-9c16-ae41c1d192c6"
/>

## Verification

- `uv run pytest tests/unit/utils/test_pathing.py -q`
- `uv run ruff check src/prime_rl/utils/pathing.py
src/prime_rl/entrypoints/rl.py src/prime_rl/entrypoints/sft.py
src/prime_rl/entrypoints/inference.py src/prime_rl/entrypoints/evals.py
src/prime_rl/dashboard/server.py tests/unit/utils/test_pathing.py
tests/integration/dashboard_smoke.py`
- `node --check src/prime_rl/dashboard/static/app.js`
- Ran reverse-text SFT through step 10 with `--max-steps 10`.
- Resumed reverse-text SFT from step 10 through step 11.
- Ran the dashboard browser smoke test against the per-attempt commands.
- Ran a two-node SFT SLURM dry-run and checked its pinned config
attempt.
- Ran a local SFT dry-run after the review changes and checked
`command.txt`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Adds run-metadata recording and dashboard read-only UI; no changes to
training, inference, or config resolution logic.
> 
> **Overview**
> Each launch now writes **`command.txt`** under `configs/attempt_<n>/`
with the full **`uv run <entrypoint>`** invocation (CLI overrides
included), using **`shlex.join`** for shell-safe quoting.
**`write_launch_artifacts`** replaces direct **`write_launch_toml`** on
**`rl`**, **`sft`**, **`inference`**, and **`evals`**; the command file
is created **only if missing** so a pinned child process reusing the
same attempt keeps the **outer** launcher command.
> 
> The dashboard **Config** tab surfaces that command (per attempt) with
a **copy** button; **`/api/runs/{run}/configs`** and
**`/api/runs/{run}/config`** expose **`command.txt`**. Docs and
training/config/dashboard skills describe the artifact and point
monitors to **`configs/latest/command.txt`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c9ce79c772d842af7556626a790e78faba20be75. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-26 12:05:54 -07:00
Mika SenghaasandGitHub d09bf96dbe feat: cancel superseded online eval episodes (#3402)
## Summary
- cancel queued and in-flight SFT eval episodes when the trainer offers
a newer checkpoint
- report scores from completed episodes and log the cancelled count and
fraction for each superseded checkpoint
- show the cancellation fraction in the local dashboard and W&B eval
sections
- allow `eval.cancel_on_new_checkpoint = false` to drain every epoch,
which can idle the trainer while slow evals finish
- document the online-eval behavior and configuration

## Verification
- `uv run ruff check
packages/prime-rl-configs/src/prime_rl/configs/evals.py
src/prime_rl/evals/evals.py src/prime_rl/monitors/wandb/overview.py
tests/unit/test_configs.py`
- `node --check src/prime_rl/dashboard/static/app.js`
- `uv run pytest tests/unit/test_configs.py -q` (122 passed)
- two-GPU SFT and online-eval run with NCCL broadcast (steps 0 and 1
reported partial scores with 6 of 8 episodes cancelled; step 2 completed
all 8 episodes; the launcher exited successfully)
- dashboard browser smoke test for the cancellation panel and run
metrics
- `PYTEST_OUTPUT_DIR=/tmp/prime-rl-eval-cancel-tests uv run pytest
tests/unit -m "not gpu" -q` (477 passed, 86 deselected; one unrelated
baseline Qwen3-VL fixture failure in
`tests/unit/orchestrator/test_qwen3_vl_e2e.py`)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes online eval scheduling and trainer–evals checkpoint handoff;
mis-cancellation could skew eval metrics or stall weight updates, but
behavior is configurable and scoped to online evals.
> 
> **Overview**
> Online SFT evals now **preempt unfinished epochs** when the trainer
publishes a newer checkpoint, so slow eval rollouts no longer block
loading the next weights. This is the default
(`eval.cancel_on_new_checkpoint = true`); set it to `false` to finish
every triggered epoch (the trainer may idle waiting).
> 
> The evals loop detects a superseding published step, calls
**`Dispatcher.cancel_eval_step`**, and **`EvalSink`** counts cancelled
groups toward partial epochs instead of treating `GroupCancellation` as
fatal. **`GroupCancellation`** carries the eval **`step`** and a
**`superseded`** reason. Weight reload hooks **`on_version_pending` /
`on_new_version`** run before consuming the epoch. Partial results still
log with **`eval/{env}/all/cancelled/count`** and **`cancelled/mean`**
(dashboard and W&B overview panels added).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
730dce804cc20fb3257c8c3a457bb22f95a82e94. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-26 11:32:01 -07:00
Mika SenghaasandGitHub 05967ffcd2 feat: preserve configs by attempt (#3405)
## Summary

- store launch TOML and resolved JSON files under `configs/attempt_<n>/`
- point `configs/latest` and `logs/latest` at the same launch attempt
- pin local and SLURM child processes to concrete attempt paths
- add config attempt selection to the dashboard
- default config and log selectors to `latest (attempt <n>)`
- keep the dashboard and checkpoint converter compatible with legacy
runs

## Breaking

- New runs no longer write configs to `configs/resolved/` or launch TOML
files directly under `configs/`. Update custom tooling to read
`configs/latest/resolved/` and `configs/latest/<entrypoint>.toml`. Use
`configs/attempt_<n>/` for a specific launch.

## Verification

Before this change, a resumed launch replaced the run-scoped config
files. After this change, both SFT and RL preserved attempt 1 and wrote
the resumed settings to attempt 2. Both `configs/latest` and
`logs/latest` resolved to `attempt_2`.

- SFT completed steps 1-5, then resumed from step 5 and completed steps
6-10
- RL completed steps 1-5, then resumed from step 5 and completed steps
6-10
- browser dashboard smoke passed for both resumed runs, including
attempt switching
- local, single-node SLURM, multi-node SLURM, and inference dry runs
produced matching attempt paths
- all generated SLURM scripts passed `bash -n`
- pathing unit tests passed: 11 tests
- Ruff checks and format checks passed

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the on-disk run layout and all launch paths (local, SLURM,
evals); legacy fallbacks limit breakage, but custom tooling must move
from `configs/resolved/` to `configs/latest/resolved/`.
> 
> **Overview**
> Each launch now keeps its **launch TOML and resolved JSON** under
**`configs/attempt_<n>/`** (resolved files in **`resolved/`**), with
**`configs/latest`** aligned to the same attempt as **`logs/latest`**.
Resumes no longer overwrite prior launch configs.
> 
> Launchers allocate matching config and log attempts via
**`prepare_attempt_dirs`** / **`create_attempt_dirs`**, pin children
with **`PRL_ATTEMPT_CONFIG_DIR`** and **`PRL_ATTEMPT_LOG_DIR`**, and
SLURM templates receive concrete **`config_dir`** / **`log_dir`**
instead of shell attempt loops. **`evals`** writes attempt-scoped
configs like **`rl`** / **`sft`**.
> 
> The **dashboard** adds a config **attempt** selector and **`attempt`**
query params on config APIs; logs already supported attempts and now
default to **`latest (attempt <n>)`**. **`get_config_dir`** and
dashboard resolution keep **legacy** `configs/resolved/` runs working.
> 
> Docs, skills, **`convert_dcp_to_bf16`**, and tests/smoke cover the new
paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
29cab3515b5c1b97eaa3aa53f9be3b947a11802c. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-26 11:06:00 -07:00
Mika SenghaasandGitHub 21a4a32450 fix: hide unused sft val plots (#3404)
## Summary

- Expose whether an SFT run has a validation dataset in dashboard
metadata.
- Hide `val/loss` and `val/perplexity` plots when validation is not
configured.
- Keep both validation plots when the resolved SFT config includes
`val.data`.

## Verification

Before: `dashboard-sft-no-val-1-step` showed empty `val/loss` and
`val/perplexity` plots.

After:

- `dashboard-sft-no-val-1-step` shows only training loss, perplexity,
and epoch plots.

<img width="1607" height="1045" alt="Screenshot 2026-08-26 at 12 15
49 AM"
src="https://github.com/user-attachments/assets/d4ebe5bf-48fa-4f07-a626-0cb9f369dfa1"
/>

- `dashboard-sft-with-val-1-step` shows both validation plots and
reports `val/loss = 5.811`.

<img width="1607" height="1045" alt="Screenshot 2026-08-26 at 12 15
32 AM"
src="https://github.com/user-attachments/assets/4746e568-dea3-4660-9692-545bf2dfa5dd"
/>

Both runs completed one SFT step. A browser check confirmed the expected
plot titles and rendered validation data.

- Ran `node --check src/prime_rl/dashboard/static/app.js`.
- Ran `uv run --no-sync ruff check src/prime_rl/dashboard/server.py`.
2026-08-26 00:17:10 -07:00
Mika SenghaasandGitHub a070beecbd fix: show single-point metrics as dots (#3403)
## Summary

- Render a dot when a metric series has one data point.
- Keep line-only rendering after a second data point arrives.
- Apply the same behavior to auxiliary band series.

## Verification

Before: a metric series with one sample rendered no visible data. After:
the sample renders as a dot at its chart coordinate. The dot disappears
when a second sample arrives.

<img width="546" height="285" alt="Screenshot 2026-08-26 at 12 07 40 AM"
src="https://github.com/user-attachments/assets/4af1930a-4bc0-47d3-990f-4bf723b641d6"
/>

- Confirmed that one-point series enable markers and two-point series
disable them.
- Ran `node --check src/prime_rl/dashboard/static/app.js`.
2026-08-26 00:08:31 -07:00
Mika SenghaasandGitHub 7da7c4d108 fix: unify multi-node SFT launch logging (#3401)
## Summary

- run multi-node SFT training and online evals in one SLURM job
- reserve `num_train_nodes + num_infer_nodes` and assign inference nodes
first
- keep every node in the shared step until trainer and eval completion
sentinels exist
- keep trainer, inference, router, evals, and env logs in one
`logs/attempt_<n>` directory
- give standalone `evals` launches an attempt directory and update
`logs/latest`
- update configuration help, training docs, and run skills for the new
topology

## Breaking

- Multi-node SFT online evals now require one combined SLURM allocation.
The scheduler must allocate all trainer and inference nodes together.
Trainer nodes remain allocated until the final eval finishes.
- The launcher no longer writes `launcher/eval.sbatch`. Custom
multi-node SFT templates must launch inference and eval roles from the
main SFT template.
- The bundled `multi_node_sft_eval.sbatch.j2` template is removed. Use
`multi_node_sft.sbatch.j2` as the template source.

## Verification

Before this change, a multi-node SFT dry run generated two batch
scripts. The eval script wrote inference, evals, and env logs directly
under `$OUTPUT_DIR/logs`.

After this change, the same dry run generates only
`launcher/sft.sbatch`. A `2 trainer + 1 inference` configuration renders
`#SBATCH --nodes=3`. The script contains one attempt allocator and no
`TRAIN_JOB_ID`, log-path marker, or NCCL-host marker. It backgrounds
trainer and evals roles. Every node waits for the job-specific trainer
and eval completion sentinels. Online-eval and trainer-only renders both
pass `bash -n` and sentinel checks.

Local two-GPU end-to-end smokes passed:

- SFT completed one training step with NCCL broadcasts and evals at
steps 0 and 1.
- RL completed one training step and evals at policy versions 0 and 1.
- Standalone inference served a standalone two-example eval run.

The filesystem audit found relative `latest -> attempt_1` links for all
three runs. Every component log was nonempty UTF-8 text. No component
log existed outside its attempt directory.

Targeted config, CLI parser, and pathing tests passed: 282 tests. Ruff
checks and formatting checks passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking change for multi-node SFT online evals: cluster scheduling
and custom SLURM templates must launch inference and trainer in one job;
misconfiguration could strand nodes or break NCCL broadcast wiring.
> 
> **Overview**
> **Multi-node SFT with online evals** no longer submits separate
trainer and eval SLURM jobs. One allocation reserves `num_train_nodes +
num_infer_nodes`; the first `num_infer_nodes` run the inference pool,
router, env servers, and `evals`, and the rest run the trainer. NCCL
weight broadcast uses the trainer rank-0 hostname directly—no cross-job
`TRAIN_JOB_ID` or shared run-dir host marker.
> 
> The launcher only writes `launcher/sft.sbatch` (
**`multi_node_sft_eval.sbatch.j2` is removed** ). The unified template
backgrounds trainer and eval roles, waits on job-specific completion
sentinels so the job can drain the final eval after a clean trainer
exit, and uses one attempt-scoped log tree under `logs/attempt_<n>/`
(including `evals.log` and env logs). Standalone/local SFT sets
`PRL_LOG_DIR` for evals; the dashboard still lists legacy `logs/envs/`
files for older runs.
> 
> Docs, `SFTConfig` field descriptions, and training skills are updated
for the single-job topology and log paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
997c8c1457c1ba95a013eb353abdcb754bc1a648. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 23:58:02 -07:00
parkerpettitandGitHub 9e3be00b39 feat(dashboard): add trace timeline viewer (#3390)
## Summary

- add a Prime-styled synchronized timeline for agent lifecycle phases
and model-call activity
- render VF-native root-to-leaf `Branch` paths instead of inferring
harness-specific subagent identities or hierarchy
- keep each environment agent as the main lane and show one flat row per
native zero-based branch index, ordered by its first unique activity
- retain shared-prefix calls on every branch path and mute them visually
to distinguish reuse from branch-unique execution
- show the trace reward on every branch training sample
- preserve exact call identity, including repeated calls, node-less
calls, and explicitly unknown timing
- show input, cached input, total input, output, reasoning, maximum
context length, total tokens, and cost in timeline tooltips and Overview
when reported
- keep large multi-agent tab strips horizontally scrollable and
integrate with Messages and Rendered transcript modes
- reject stale timeline responses after episode selection changes and
preserve unknown completed-phase end timing
- retain report navigation, transcript highlighting, rendered-token
mode, and dashboard view-command support

## Screenshot of multiagent episode (with subagent calls)
Codex harness
<img width="2400" height="2490" alt="image"
src="https://github.com/user-attachments/assets/1fe4a274-5cf2-49de-adf8-f328086d9f4a"
/>

RLM harness
<img width="2400" height="3260" alt="image"
src="https://github.com/user-attachments/assets/1ea0d693-a72e-495d-8133-c5b82770f2a0"
/>

## Validation

- `uv run --frozen ruff check .`
- `uv run --frozen ruff format --check .`
- `node --check src/prime_rl/dashboard/static/app.js`
- real interactive Codex multi-agent episode projects 29 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 46 actual calls covered
- real interactive RLM multi-agent episode projects 40 native branches
across four environment-agent traces, with every branch containing
exactly its root-to-leaf model calls and all 125 actual calls covered
- captured full-episode Playwright screenshots of both branch timelines
2026-08-25 17:53:01 -07:00
ef66401434 feat: traces -> hf dataset converter (#3382)
## Summary

- Replace `scripts/export_sft.py` with
`tools/convert_traces_to_hf_dataset.py`.
- Convert each branch of each agent trace into one dataset row.
- Export trainable and non-trainable agents without selection or
filtering.
- Add top-level outcome fields for downstream filters, including
`reward`, `stop_condition`, `has_error`, and `is_truncated`.
- Preserve task, run, agent, error, timing, usage, call, reward, metric,
and trace metadata.
- Push to a private Hugging Face Hub dataset by default, with `--public`
as an explicit opt-out.
- Use `--local` to write Parquet files with Hugging Face dataset-card
metadata.
- Preserve existing dataset-card content when local metadata is updated.

## Verification

### Eval → dataset → SFT

1. Generated eight GSM8K episodes without uploading the eval:

```bash
uv run --project /home/ubuntu/prime-rl eval gsm8k -n 8 -r 1 -c 8 \
    --no-push -o /tmp/trace-converter-e2e-20260825 \
    --run.name trace-converter-gsm8k --run.dir eval
```

All eight episodes succeeded. Mean reward was 1.0 and the error rate was
0.0.

2. Converted the trace file into a local Hugging Face dataset:

```bash
uv run --project /home/ubuntu/prime-rl python \
    tools/convert_traces_to_hf_dataset.py \
    /tmp/trace-converter-e2e-20260825/eval/traces.jsonl \
    --name /tmp/trace-converter-e2e-20260825/dataset --local
```

The converter wrote eight branch rows. The dataset loaded through
`load_dataset`.

3. Trained Qwen3-0.6B on the converted dataset:

```bash
uv run --project /home/ubuntu/prime-rl sft \
    --output-dir /tmp/trace-converter-e2e-20260825 --run.name sft \
    --max-steps 5 --model.name Qwen/Qwen3-0.6B \
    --data.type sft --data.name /tmp/trace-converter-e2e-20260825/dataset \
    --data.subsets '["default"]' --data.splits '["train"]' \
    --data.seq-len 2048 --data.batch-size 4 --data.micro-batch-size 1 \
    --deployment.gpus-per-node 2 --deployment.num-train-gpus 1
```

The run completed all five steps. Final loss was 0.7764, the NaN count
was zero, and peak GPU memory was 10.7 GiB. No Hub or Prime platform
uploads occurred.

### Additional checks

- Ran the Ruff check and format pre-commit hooks.
- Converted a separate saved file with 132 episodes and loaded all 132
branch rows with `load_dataset`.
- Verified that a non-trainable errored trace still emits its branch row
and top-level error fields.
- Verified that local updates preserve plain, valid-frontmatter, and
unclosed-frontmatter README content.
- Verified that default uploads pass `private=True`, while `--public`
passes `private=False`.

## Breaking

- `scripts/export_sft.py` is removed. Use `uv run python
tools/convert_traces_to_hf_dataset.py <traces.jsonl> --name
<dir-or-repo-id>`.
- The converter no longer accepts `--min-reward` or `--drop-truncated`.
Apply filters in a separate script.
- The converter pushes to the Hub by default. Use `--local` to write a
local dataset.
- New Hub datasets are private by default. Use `--public` to create a
public dataset.
- The `--push` flag is removed because Hub upload is now the default.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are limited to offline export tooling and CLI workflows; no
in-repo training or runtime code is modified in this diff.
> 
> **Overview**
> **Removes** `scripts/export_sft.py` and **adds**
`tools/convert_traces_to_hf_dataset.py` as the path from eval/train
`traces.jsonl` to Hugging Face datasets.
> 
> The new converter reads **one episode per line** (`WireEpisode`)
instead of per-trace wire rows, emits **one row per branch** for every
agent trace (no `--min-reward`, `--drop-truncated`, or empty-branch
skipping), and keeps **`messages`** plus JSON **`tools`** for SFT while
adding top-level filter fields (`reward`, `stop_condition`, `has_error`,
`is_truncated`, etc.) and JSON metadata for task, run, agent, errors,
timing, and usage.
> 
> **Output behavior changes:** Hub upload is the default via required
`--name`; use **`--local`** to write `<name>/<subset>/<split>.parquet`
and update **`README.md`** dataset-card configs for `load_dataset`.
**`--public`** controls visibility on new Hub repos; **`--push`** is
gone.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8834b7aea61f2e6e9ba467758b593cf6ffb7a29b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 16:14:03 -07:00
eligottsandGitHub be5855cfe3 Harden dashboard cited-report guidance (#3393) 2026-08-25 15:35:55 -07:00
Mika SenghaasandGitHub 43365ec52f feat: model converter scripts (#3348)
## Summary

- Add `tools/convert_dcp_to_bf16.py`: convert a DCP trainer checkpoint
to HF sharded safetensors offline. Recovers the converter deferred out
of #3316 and adapts it: required positional `ckpt_dir` (accepts
`<run>/checkpoints/step_{n}` or `.../step_{n}/trainer`), output defaults
to `<ckpt_dir>/weights` (or a second positional arg), model/tokenizer
configs read from the run's resolved `configs/trainer.json` / `sft.json`
(the single source of truth — the checkpoint must live in its run
directory), single-process (`uv run python`) and multi-rank (`torchrun`)
invocations. Local `trust_remote_code` models get their custom code
files copied next to the weights. Full fine-tunes only — LoRA
checkpoints are rejected up front. Export replaces training-only
attention, fused-MoE, and DeepEP settings with portable
model-construction values.
- Add `tools/convert_bf16_to_fp8.py`: quantize an HF safetensors dir to
blockwise FP8 (DeepSeek/GLM format: e4m3 weights + `weight_scale_inv`
per-128×128-block scales, `quantization_config` block vLLM loads
natively). Streams shard-by-shard; norms, embeddings, lm_head, router
gates, GatedDeltaNet low-rank projections, MTP projection, and vision
towers stay bf16. Reuses `quantize_to_fp8_blockwise` from
`prime_rl.trainer.models.fp8`. Inspired by slime/miles
`tools/convert_hf_to_fp8.py`.
- Add `tools/convert_dcp_to_fp8.py`: DCP straight to fp8 — same gather
as `dcp_to_bf16`, but each rank quantizes its slice on GPU and only fp8
shards are written to `<ckpt_dir>/weights-FP8` (no intermediate bf16
export on disk).
- Add `tools/convert_fp8_to_bf16.py`: the inverse (dequantize
blockwise-fp8 releases like GLM-5-FP8 to bf16 for training). Inspired by
slime/miles `tools/fp8_cast_bf16.py`.
- Fold converter e2e checks into the existing reverse-text CI runs (no
new CI matrix entries): both the SFT and RL integration tests convert
their final DCP checkpoint to bf16 and fp8 and assert the exports reload
in HF with a clean loading report; the RL test additionally asserts
direct `dcp_to_fp8` output is byte-identical to chained `bf16_to_fp8` on
a real trainer checkpoint. Shared helpers
`convert_checkpoint`/`check_hf_load` in `tests/utils.py`. (A standalone
per-arch byte-exactness matrix over the mini_moe archs — glm4_moe,
laguna, minimax_m2, qwen3.5-MoE VLM; bf16 exports byte-identical to
their random-init sources, both fp8 paths byte-identical — was validated
during development and dropped from CI in favor of these hooks.) Also
fixes the mini_moe VLM preset `mrope_section` for its shrunken head_dim.
- Read the run config from the `configs/resolved/` layout via
`get_config_dir` (adapted after merging main).
- Document the export flow in `docs/training.md` and
`skills/training/start-run/SKILL.md`, and note the CLI convention in
`AGENTS.md`: `tools/` scripts use plain argparse, `[project.scripts]`
entrypoints use pydantic-config.

## Verification

All run on 2× RTX PRO 6000 Blackwell (SM120), vLLM 0.26.

**dcp→hf, real RL run (qwen3 dense)** — 20-step reverse-text RL run with
`--ckpt.interval 10 --weight-broadcast.type filesystem`:
- step 10 converted single-process, step 20 with `torchrun
--nproc-per-node 2`.
- Both exports are **bit-identical** (all 310 tensors) to the trainer's
own filesystem-broadcast weights at the same step; tied `lm_head.weight`
is dropped per HF convention and verified equal to `embed_tokens`.
- `uv run inference --vllm.model .../step_10/weights` serves the export;
reverse-text eval (`uv run eval`, n=64 r=4) scores **0.754** vs 0.744
training reward at step 10. Step 20 export scores **0.801** vs ~0.80 at
end of training.

**dcp→hf, architecture matrix** — per arch: tiny random model
(`scripts/mini_moe.py`) → 3-step fake-data SFT → convert (exercises
`configs/sft.json` auto-detection) → verify:

| arch | strict HF load | prime reload + forward | notes |
|---|---|---|---|
| glm4_moe (MoE) | ✓ | ✓ | plus direct HF→DCP→HF round trip: 889/889
tensors bit-exact (expert stack/unstack) |
| laguna | ✓ (`trust_remote_code=True`) | ✓ | HF→DCP→HF round trip
433/433 tensors bit-exact modulo the conversion chain's canonical
per-expert layout (the same layout the live broadcast path emits;
poolside's HF class stores fused `experts.gate_up_proj` and re-inits
experts it doesn't recognize — see `converting_laguna.py` docstring) |
| minimax_m2 (MoE) | ✓ | ✓ | mini built via prime impl (MiniMax remote
code incompatible with transformers v5) |
| qwen3_5_moe VLM | ✓ (`Qwen3_5MoeForConditionalGeneration`) | key-set
identity vs source | vision tower + linear attention round-trip |


**bf16→fp8 + fp8→bf16** — on the real step-20 Qwen3-0.6B export and all
four minis: dequant error bounded (worst median relative error ~2.2%,
e4m3-consistent), skip-list modules bit-identical,
index/`quantization_config` consistent; fp8→bf16 round trip drops all
`*_scale_inv` keys and `quantization_config`. Structure matches the
official `Qwen/Qwen3-0.6B-FP8` release (same scale shapes/names).
Serving the fp8→bf16 round-tripped weights scores **0.798** (vs 0.801
bf16 baseline), confirming the stored values.

**fp8 serving on SM120 (vLLM kernel bug, not the script)**: serving the
fp8 checkpoint scores **0.31** with vLLM's default
`CutlassFp8BlockScaledMMKernel` on this box, but **0.790** with the same
checkpoint after forcing the Triton kernel
(`VLLM_DISABLED_KERNELS=...CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel`
→ `TritonFp8BlockScaledMMKernel`), and vLLM's *online* fp8 of the same
weights scores 0.79. vLLM's CUTLASS blockwise-fp8 GEMM silently degrades
on SM120 (RTX PRO 6000); upstream already tracks other SM120
blockwise-fp8 breakage (vllm-project/vllm#47990, #47436). Noted the
workaround in `skills/training/start-run/SKILL.md`; H100/H200/B200
(SM90/SM100) use different kernels.

## Not ported from slime/miles

Megatron converters (`convert_torch_dist_to_hf*`,
`convert_hf_to_torch_dist`) — prime-rl is FSDP/DCP; int4 converters
(Kimi-K2-specific); mxfp8/nvfp4 (no checkpoint-level use case yet);
`param_name_remap.py` (covered by prime conversion chains); profiling
tools (prime-rl has its own monitors).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Converters touch distributed gather, HF weight layout, and
quantization paths that must match live training/broadcast behavior;
mistakes could ship broken checkpoints, though integration tests and
LoRA rejection reduce exposure.
> 
> **Overview**
> Adds offline **checkpoint export and FP8 conversion** tooling under
`tools/convert_*.py`, plus docs/skills updates and integration-test
coverage.
> 
> **DCP → Hugging Face:** `convert_dcp_to_bf16.py` loads FSDP DCP
trainer checkpoints using the run’s resolved
`configs/resolved/trainer.json` or `sft.json`, gathers weights in
parallel (single GPU or `torchrun`), writes sharded bf16 safetensors and
tokenizer/config assets to `<ckpt_dir>/weights`, and **rejects LoRA**
checkpoints.
> 
> **FP8 round-trip:** `convert_bf16_to_fp8.py` blockwise-quantizes HF
safetensors (e4m3 + `weight_scale_inv`, vLLM-native
`quantization_config`); `convert_dcp_to_fp8.py` quantizes each rank’s
gathered slice straight to `<ckpt_dir>/weights-FP8` without a bf16
export on disk; `convert_fp8_to_bf16.py` dequantizes fp8-only releases
for training.
> 
> **CI:** Reverse-text RL and SFT integration tests convert the final
checkpoint, assert clean `AutoModelForCausalLM` loads, and (RL)
byte-identity between direct `dcp_to_fp8` and chained `bf16_to_fp8`.
Shared helpers `convert_checkpoint` / `check_hf_load` live in
`tests/utils.py`. `scripts/mini_moe.py` fixes `mrope_section` for the
shrunk VLM preset.
> 
> **Docs:** `docs/training.md` and training skills document the export
flow; `AGENTS.md` notes `tools/` scripts use plain argparse vs
pydantic-config entrypoints. Run artifact paths use `step_{n}`
consistently.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fe1241dec3e1369cc930ffa6b736fe6baf4e5200. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 14:30:07 -07:00
Mika SenghaasandGitHub ab5de8fff4 chore: release v0.9.0 (#3379)
Tag and Release / kernels-from-auto-tag (push) Canceled after 0s
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / resolve-release (push) Canceled after 0s
Tag and Release / kernels-from-tag (push) Canceled after 0s
Tag and Release / publish-release (push) Canceled after 0s
## Summary

- bump the prime-rl project version from 0.8.0 to 0.9.0
- update the matching prime-rl entry in uv.lock
- prepare the [draft v0.9.0 GitHub
release](https://github.com/PrimeIntellect-ai/prime-rl/releases/tag/untagged-6fdfe34d2c7a47da166a)
with notes for 105 commits since v0.8.0
- include the latest dashboard, SLURM teardown, weight synchronization,
and eval policy fixes in the release notes

## Verification

- uv lock --check
- git diff --check origin/main...HEAD
2026-08-25 13:11:39 -07:00
97d32d947f fix(orchestrator): pre-seed datasets' tqdm lock to avoid concurrent-load crash (#3391)
## Problem

`Envs.start()` starts every source concurrently
(`asyncio.gather(env.start() for env in self)`), and each `env.start()`
materializes its taskset via `load_dataset()` in a worker thread
(`asyncio.to_thread(lambda: list(taskset))`). HuggingFace `datasets`
reads cached arrow shards through
`tqdm.contrib.concurrent.thread_map(tqdm_class=hf_tqdm)`, whose
`ensure_lock()` is:

```python
old_lock = getattr(tqdm_class, "_lock", None)
lock = old_lock or tqdm_class.get_lock()
...
yield lock                       # the (slow) arrow read happens here
if old_lock is None:
    del tqdm_class._lock         # <-- racing line
else:
    tqdm_class.set_lock(old_lock)
```

When two of these run concurrently with the class lock unset, both
observe `old_lock is None`, both reach `del tqdm_class._lock` on exit,
and the second raises:

```
AttributeError: type object 'tqdm' has no attribute '_lock'
```

That kills the orchestrator during `setup()` ("Fatal error in
run_orchestrator"), and the trainer then hangs waiting for rollouts that
never come.

**When it triggers:** ≥2 sources load datasets concurrently at startup
(e.g. multiple train sources over the same taskset). The race window is
the arrow read, so more sources / colder caches make it more likely — 3
concurrent loads hit it essentially every run, 2 intermittently, 1
never. It is **not** caught by `--dry-run`, which never calls
`load_dataset()`.

Root cause is a tqdm thread-safety gap (`ensure_lock` isn't safe for
concurrent use on a single class), exposed by `datasets`' `thread_map`
plus concurrent taskset loading here.

## Fix

Pre-seed the `datasets` tqdm class lock once, before the concurrent
gather, so `old_lock` is never `None` and every `ensure_lock` takes the
non-deleting `else` branch — the same state tqdm is in whenever a
progress bar is active:

```python
from datasets.utils import tqdm as _hf_tqdm
_hf_tqdm.set_lock(_hf_tqdm.get_lock())
```

This targets the exact class `datasets` passes to `thread_map`
(`datasets.utils.tqdm.tqdm`, the same object `arrow_reader` imports). It
only stops the lock object from being created-and-deleted per call; no
change to progress-bar display, dataset contents, or ordering.

## Reproduction

Hammering the failing primitive directly (16 threads, window widened to
mimic the slow arrow read):

- **without** the fix: consistent `AttributeError: type object 'tqdm'
has no attribute '_lock'`
- **with** the fix: clean, 0 failures

Also observed live: a 3-train-source run crashed here every time; after
the fix all three arms load cleanly.

## Alternative considered

Loading sources sequentially in `Envs.start()` also avoids the race, at
the cost of startup parallelism. The pre-seed keeps the parallel load.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Single-line lock initialization before existing parallel env startup;
no auth, data, or algorithm changes.
> 
> **Overview**
> **Fixes a startup crash** when multiple train/eval sources load
HuggingFace datasets in parallel during `Envs.start()`.
> 
> Concurrent `load_dataset()` paths use `datasets`' `thread_map` with
tqdm's `ensure_lock()`, which can race on `del tqdm_class._lock` and
raise `AttributeError`—fatal during orchestrator `setup()` and leaving
the trainer waiting on rollouts.
> 
> Before `asyncio.gather` on `env.start()`, the change **pre-seeds** the
lock on `datasets.utils.tqdm` via `set_lock(get_lock())` so concurrent
readers never hit the delete branch. Parallel startup is preserved; no
change to dataset contents or progress display.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a1007d2d9cc0b8e15a2df959cec54cf3b366fce3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-25 13:09:20 -07:00
Mika SenghaasandGitHub 6b3364d1a8 fix: align evals with applied policies (#3385)
## Summary

- Route startup and later policy loads through one `WeightWatcher`
update path. Advance `policy.version` and trigger evals only after
inference applies the weights.
- Key fresh startup evals to policy v0. On resume, evaluate the loaded
checkpoint only when `retrigger_on_resume=true`.
- Pause rollout scheduling across each weight apply so rollout
provenance matches the policy served at dispatch.
- Remove the resume-step broadcast directory before the trainer rebuilds
its startup handshake.
- Always broadcast and consume the final RL policy. Remove the
conditional final-broadcast config and helper path.
- Remove the mixed-policy eval warning. Keep the minimum policy version
in metrics and success logs.
- Remove the parenthesized step from eval success logs.

## Verification

Before the fix, a 20-step reverse-text run with eval interval 1
reproduced the bug:

- Eval step 20 used policy v18.
- The final policy broadcast triggered eval step 21 with policy v20.
- The run wrote step-21 eval artifacts.

After the fix, this requested interval-10 run completed all 20 steps:

```bash
uv run rl @ examples/basic/reverse-text/rl.toml \
  --orchestrator.eval.interval 10 \
  --orchestrator.eval.num-examples 1 \
  --orchestrator.eval.group-size 1 \
  --orchestrator.eval.source '[{"name":"reverse-text-eval","env":{"taskset":{"id":"reverse-text"},"agent":{"harness":{"id":"null"},"runtime":{"type":"subprocess"}}}}]' \
  --no-monitors.wandb --no-dashboard
```

- Eval step 10 used policy v10.
- Final eval step 20 used policy v20.
- No step-21 eval artifacts were written.

A two-step run without evals applied final policy v2 and exited cleanly.
This verifies unconditional final broadcast and consumption.

Fresh and resumed two-step smokes verified the startup matrix:

- A fresh interval-1 run evaluated policies v0, v1, and v2.
- Resume from v2 with `retrigger_on_resume=false` skipped v2, then
evaluated v3 and v4.
- Resume from v2 with `retrigger_on_resume=true` evaluated v2, v3, and
v4.
- Resume from v2 with interval 3 skipped v2 and evaluated v3 only.
- Every resumed startup rebuilt its v2 broadcast handshake and exited
cleanly.

After the final review fixes, a fresh interval-1 run evaluated v0, v1,
and v2. A resume from v2 with `retrigger_on_resume=false` skipped only
v2, then evaluated v3 and v4.

```bash
uv run pytest \
  tests/unit/test_configs.py \
  tests/unit/orchestrator/test_batch.py \
  tests/unit/utils/test_pathing.py -q
# 156 passed

uv run ruff check \
  src/prime_rl/orchestrator/orchestrator.py \
  src/prime_rl/orchestrator/watcher.py \
  src/prime_rl/orchestrator/dispatcher.py \
  src/prime_rl/orchestrator/eval_source.py \
  src/prime_rl/utils/pathing.py \
  src/prime_rl/trainer/rl/train.py \
  src/prime_rl/utils/utils.py \
  packages/prime-rl-configs/src/prime_rl/configs/rl.py \
  packages/prime-rl-configs/src/prime_rl/configs/shared.py \
  tests/unit/utils/test_pathing.py \
  tests/utils.py
# All checks passed!
```

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes core RL orchestration around weight updates, rollout
scheduling barriers, and eval timing—incorrect ordering could cause
wrong-policy evals or inference crashes during weight swaps.
> 
> **Overview**
> Fixes evals running against stale or wrong policy versions by tying
**eval triggers and `policy.version` to inference actually applying
weights**, not merely publishing them.
> 
> **Policy lifecycle:** `WeightWatcher` now advances `policy.version`
only after `receive()` completes, routes startup sync through
`sync_startup` + shared `on_update` hooks, and registers orchestrator
hooks for eval and dispatch-gate refresh. Batch shipping and shutdown
waits refer to **inference-applied** versions.
> 
> **Eval scheduling:** Eval fires from `trigger_eval` after each applied
policy (including startup v0 on fresh runs). Resume skips re-eval at the
checkpoint step unless `retrigger_on_resume=true`; final eval uses
`force` at `max_steps` without a spurious step-21 epoch. The dispatcher
blocks new scheduling across weight swaps via `policy_update_pending`
and a scheduling lock.
> 
> **Broadcast config:** Removes `broadcast_final` and
`final_broadcast_version`; the trainer **always** broadcasts every step
including the final policy, and resume cleanup deletes broadcast dirs
from the resume step onward so the startup handshake is rebuilt.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5fa6b01df79f028ad974509ff78e9e51188cf1f0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 12:32:45 -07:00
eligottsandGitHub 544bd6205a feat(dashboard): agent view commands + report tab with verified citations (#3387) 2026-08-25 12:24:51 -07:00
rasdaniandGitHub 3460245d63 feat(dashboard): expose tool context and rendered tokens (#3377)
## Summary

- show `trace.tools` as a distinct, collapsible model-context block in
the Messages view, with tool counts/names, full descriptions, formatted
parameter schemas, and per-item/schema/all copy actions
- add a separate `Rendered` view that decodes recorded post-renderer
`token_ids` for the selected trace and branch as a full sequence,
retaining special tokens and offering decoded-text and authoritative-ID
copy actions
- compose both `Messages` and `Rendered` with the `Text`, `Advantage`,
`Logprob`, `Mask`, and `Content` signal dropdown, with explicit
unavailable states for missing IDs, missing model metadata, tokenizer
load failures, and decode failures

## Details

The Messages view continues to render literal `message.content`. Tool
definitions are shown immediately after the first system message in a
purple-accented context card, so they are not presented as
system-message text; traces without a system message keep the card at
the top. The collapsed row shows the count and normalized names;
expanding it exposes each full description and scrollable JSON schema.
Direct tool objects, OpenAI-style `function` wrappers, multiple
definitions, missing fields, and malformed values degrade to readable
fallback labels.

Rendered does not rerun or infer a chat template. The server uses
`client.renderer_model_name` with the existing run-model fallback,
concatenates the recorded node spans in the selected root-to-leaf order,
and calls the tokenizer once for the full sequence with special-token
skipping disabled. The selected branch controls which decoded sequence
is shown; the all-branches option uses recorded node write order. With
`Text` selected, Rendered shows that exact full-sequence decode. With
another signal selected, it shows the same recorded sequence as token
spans with the existing color scale and token hover metadata.

Compatibility is intentionally additive: the default endpoint response
and default Messages/Text display stay unchanged, token strings are
still fetched lazily for overlays, and full rendered text is only added
when `rendered=true` is requested. The mode buttons and signal dropdown
are independent, and a one-time preference migration recovers sessions
that briefly saved `Rendered` in the signal field.

Episode navigation and token/render enrichment use separate request
lifecycles. Opening or closing an episode invalidates prior enrichment,
while changing controls during an in-flight open no longer discards the
episode response; the newly opened episode then picks up any enrichment
required by the latest controls. Decode failures remain branch-local in
the viewer: valid text for the selected branch is shown even if another
branch fails to decode.

## Verification

- `uv run --no-sync ruff format --check
src/prime_rl/dashboard/server.py`
- `uv run --no-sync ruff check src/prime_rl/dashboard/server.py`
- `uv run ruff check src/prime_rl/dashboard`
- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff origin/main...HEAD --check`
- exercised a generic synthetic two-branch trace through the live
dashboard API with three tool-definition shapes; verified renderer-model
selection, retained `<|im_start|>` / `<|im_end|>` markers, separate
branch text, all-node ordering, and existing per-token pieces

## Visual description

A compact `Tool definitions · 3 tools · lookup, calculate, tool 3` row
appears directly after the system message. It expands into nested tool
cards with full prose and scrollable monospace schemas. `Messages` /
`Rendered` buttons sit beside a signal dropdown containing `Text`,
`Advantage`, `Logprob`, `Mask`, and `Content`. Either mode can use any
signal; Rendered/Text shows the exact decoded transcript, while Rendered
with an overlay shows colored token spans. A hover tooltip describes the
signal choices. A screenshot is not included because a browser runtime
was unavailable in the checkout used for verification.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Additive dashboard and optional episode API fields; no changes to
training, auth, or data persistence beyond larger lazy-loaded episode
payloads.
> 
> **Overview**
> The trace viewer adds **Messages** vs **Rendered** modes and surfaces
**`trace.tools`** as model context separate from message text.
> 
> In **Messages**, tool definitions appear in a collapsible context
block (after the first system message when present), with descriptions,
parameter schemas, and copy actions; message bodies still show literal
**`message.content`**. **Rendered** decodes recorded post-renderer
**`token_ids`** per branch (or all nodes) via **`renderer_model_name`**
with run-model fallback—no chat-template reconstruction—and reports
missing IDs, model, tokenizer, or decode failures.
> 
> The episode API accepts optional **`tokens`** and **`rendered`** query
params; **`rendered_token_text`** on the server concatenates branch
paths and decodes full sequences with special tokens retained. The UI
lazily fetches enrichment, versions open/enrichment requests to avoid
stale responses, and shares the Text / Advantage / Logprob / Mask /
Content signal dropdown across both modes.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
596f7d3fe9746c9283d8a872b1d506c26a525e1a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-25 11:40:30 -07:00
3758321f08 fix: preserve final eval during teardown (#3324)
## Summary

- Use successful trainer and orchestrator exits as the shared completion
condition in local and multi-node SLURM launchers.
- Let each SLURM component publish `.trainer.done` or
`.orchestrator.done`, then stop inference after both markers exist.
- Make trainer-only fake-data SLURM runs stop after `.trainer.done`; no
orchestrator exists in that mode.
- Store all generated SLURM scripts and coordination files under
`<run_dir>/launcher/`.
- Store SLURM stdout and stderr under `<run_dir>/launcher/logs/`.
- Apply the launcher layout to RL, SFT, decoupled SFT eval, and
standalone inference entrypoints.
- Keep local launchers unchanged on disk. They do not create `launcher/`
because they persist no launcher files.
- Preserve failure propagation through `srun --kill-on-bad-exit=1`.

At `max_steps`, the trainer can exit while the orchestrator still drains
the final eval. The template previously tore down the node after the
first background process exited. This killed the final eval. A clean
exit also did not trigger `--kill-on-bad-exit`, so inference nodes could
hold the allocation until wall time.

## Breaking

- Generated SLURM scripts move from `<run_dir>/*.sbatch` to
`<run_dir>/launcher/*.sbatch`. Update manual submission commands and
tooling to use the new paths.
- SLURM job logs move from `<run_dir>/*job_*.log` to
`<run_dir>/launcher/logs/*job_*.log`. Update log collection and
monitoring paths.

## Verification

Before this change, a 1000-step GLM-4.5-Air run lost its final eval at
450 of 500 tasks. The six-node allocation then remained active for
another 23 hours.

After this change, a 10-step reverse-text run evaluated at its final
step and exited successfully:

- The final eval completed all 64 rollouts with no rollout errors.
- The trainer finished at 01:39:08 UTC.
- The orchestrator drained its pipeline and finished at 01:39:14 UTC.
- Inference stopped after both terminal components finished.
- The launcher exited with code 0 and released both GPUs.

A two-node trainer-only fake-data dry run rendered a one-marker watcher
with no `ORCHESTRATOR_DONE` reference. The normal inference path still
rendered the two-marker watcher. Both scripts passed `bash -n`.

All RL, SFT, decoupled SFT eval, and inference SLURM variants rendered
successfully. Every rendered script passed `bash -n`. Local RL, SFT, and
inference dry runs did not create `launcher/`.

An additional two-node SLURM run used the regular reverse-text
configuration with 100 eval rollouts per evaluation:

- The trainer completed all 20 steps and wrote `launcher/.trainer.done`.
- The orchestrator continued to drain queued evaluations after trainer
completion.
- The orchestrator then wrote `launcher/.orchestrator.done`.
- Both nodes logged teardown with exit code 0, and the job released its
allocation.

Ruff passed. The pathing unit tests passed with 10 tests.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes multi-node SLURM lifecycle and coordination (eval completion
vs allocation hold time) and breaks paths for manual `sbatch` and log
monitoring; incorrect completion logic could still strand nodes or kill
in-flight evals.
> 
> **Overview**
> Fixes premature SLURM teardown at `max_steps` when the trainer exits
while the orchestrator is still draining the **final eval**. Multi-node
RL jobs no longer stop on the first background process exit; trainer
rank 0 and the orchestrator publish **`launcher/.trainer.done`** and
**`launcher/.orchestrator.done`** on success, and every node waits for
the appropriate pair (trainer-only vs trainer+orchestrator) before
killing inference and releasing the allocation. Failures still propagate
via **`srun --kill-on-bad-exit=1`**.
> 
> **Breaking layout change:** generated `*.sbatch` scripts, coordination
sentinels, and SLURM `job_*.log` output move from the run directory root
to **`&lt;run_dir&gt;/launcher/`** and **`launcher/logs/`** for RL, SFT,
decoupled SFT eval, and standalone inference. Entrypoints and Jinja
templates pass `launcher_dir` / `launcher_log_dir`; local launches stay
unchanged on disk (no `launcher/`). Docs and training skills note the
new paths; `format_log_message` and `LAUNCHER_ARTIFACTS` validation
follow the same layout.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
02f3807d4a4f9cd53830b9b90e4035c386d01bdc. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 21:58:23 -07:00
Mika SenghaasandGitHub 01dc127b1a fix: synchronize before the pre-broadcast empty_cache (#3383)
## Summary
- One-line fix for the deterministic `CUDA error: an illegal memory
access` that killed every SignSGD run without full optimizer offload
since #3234.
- `torch.cuda.empty_cache()` returns cached blocks to the driver; a
kernel still in flight that references a cached block faults once its
block is freed under it. The pre-broadcast `empty_cache` (added in #3234
for FP8 gather headroom) runs immediately after `optimizer.step()` —
SignSGD's per-param loop leaves thousands of tiny kernels still running
at that point, while AdamW's compact foreach step happens to finish in
time, which is why only SignSGD crashed. Draining pending work with
`torch.cuda.synchronize()` before releasing blocks closes the race for
every optimizer, at ~ms cost once per step.

## Verification

All on the same GLM-4.5-Air scaleswe config (2 trainer + 2 inference
nodes, `sign_sgd` + `optim_cpu_offload`, no full offload):

| state | outcome |
|---|---|
| main | illegal memory access right after step 1, 2/2 slurm attempts |
| main + `CUDA_LAUNCH_BLOCKING=1` | no crash — ordering, not indexing |
| **main + this one line** | [runs
clean](https://wandb.ai/primeintellect/swe-ablations?nw=nwuser&search=sgd-nooffload):
11+ steps and counting, healthy grad norms, no restarts |

Supersedes #3373 — its foreach SignSGD rewrite turned out to be
unnecessary for correctness (verified by running the untouched optimizer
with only this line).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches the per-step RL training hot path and GPU memory lifecycle
before weight broadcast; the change is narrow and matches existing
synchronize-before-empty_cache patterns elsewhere, but any extra sync
can affect step timing.
> 
> **Overview**
> Fixes a **CUDA illegal memory access** that could occur right after
`optimizer.step()` when the trainer frees GPU cache before broadcasting
weights.
> 
> The pre-broadcast `torch.cuda.empty_cache()` (for FP8 gather headroom)
can return cached blocks to the driver while **optimizer kernels are
still in flight**—especially with SignSGD’s many small per-parameter
updates. The change **drains pending GPU work** via
`torch.cuda.synchronize()` immediately before `empty_cache()`, with
expanded comments explaining the race.
> 
> This is a one-line behavioral fix in the RL training loop’s
weight-broadcast path; it does not change broadcast semantics, only
ordering so memory is not reclaimed under active kernels.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8947aa400631ca5a2dab829642f7755fab7dafd0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 18:33:04 -07:00
Konstantin DunasandGitHub 663b53bbc2 fix: silence W&B Weave advertisement on wandb.init (#3380) 2026-08-25 01:51:29 +02:00
f96a46f090 feat(configs): add PRL_OUTPUT_DIR env var for default output_dir (#3375)
Lets a user set a persistent default output location for all runs
without repeating --output-dir on every launch. Precedence stays class
default ("outputs") < PRL_OUTPUT_DIR < TOML < CLI, since the new
default_factory only fires when output_dir is untouched by TOML/CLI
merge.

Also respected by the dashboard UI.

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 19:15:19 -04:00
01994b8168 fix: misc dashboard improvs (#3374)
## Summary

- refresh live metrics and trace rows on the same five-second cadence
- better `no data yet` for unavailable overview data
- show episode and trace errors at the bottom of the trace viewer
- add the task key as `task ID` to the identity section of the trace
overview pane
- use `n/a` for missing value uniformly; some spots showed an en dash.
- allow filter from trace viewer

## Verification

### Overview empty state

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 54 20
PM"
src="https://github.com/user-attachments/assets/02e06087-5286-435e-9776-52ec9502f7f5"
/>

### Errors

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 52 29
PM"
src="https://github.com/user-attachments/assets/b39a28cc-c50d-467c-b7f7-39c354a5e008"
/>

### Task ID

<img width="318" height="151" alt="Screenshot 2026-08-24 at 3 52 42 PM"
src="https://github.com/user-attachments/assets/f12f50b5-685d-4ca5-8b80-5c89877cab43"
/>

### Checks

- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff --check`
- dashboard browser smoke against `outputs/reverse-text-rl`
- live append browser repro for metrics, trace rows, and new trace steps
- fake inference URL eval and browser layout check with a full traceback
- headless browser render of a synthetic `ProviderError` episode:
collapsed and expanded traceback, `task ID` row, consistent `n/a`
placeholders, red-marked error rows in the sidebar

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Frontend-only dashboard static assets; no API or training-path
changes. Risk is limited to UI regressions in metrics/traces polling and
the trace modal.
> 
> **Overview**
> This PR tightens **live updates** and **trace UX** in the static
dashboard (`app.js`, `index.html`, `style.css`).
> 
> **Polling & loading:** Poll interval moves to **5s**; metrics and
traces refresh when switching tabs with live on, on tab visibility, and
when re-enabling live. Metrics streaming stops retrying the same offset
when a partial JSONL line sits at EOF; `fetching` guards avoid
overlapping metrics/trace loads.
> 
> **Traces:** Step selection **follows the latest preferred step** while
you’re on the tail (historical picks and an open modal stay put). Empty
trace/metrics states use shorter labels and the episode table keeps its
chrome with an in-table empty row to avoid layout shift. Overview panels
show **“no data yet”** for configured eval sections before data lands.
> 
> **Trace viewer:** Episode/trace **errors render as banners** at the
bottom of the message column (with expandable tracebacks); **task ID**
appears in the identity pane. The modal gets the same
**filter/sort/env/errors** controls as the traces tab, synced through
shared state. Error episodes are highlighted in the sidebar list.
> 
> **Polish:** Missing numeric/overview fields use **`n/a`** instead of
en dashes (empty eval env list still shows **–**). Run overview merges
the full run record from the runs list on refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
239dc7797d996fb0b17badb9dd60b640474b431d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 16:11:11 -07:00
e6b5e4de5d feat: auto-started dashboard daemon (#3371)
## Summary

- Launchers (`rl`, `sft`) register their output dir in
`~/.cache/prime-rl/dashboard/dirs.json` and make sure one dashboard
serves it (`ensure_dashboard` in the new `entrypoints/dashboard.py`,
kept free of `dashboard`-extra imports). Every dashboard instance serves
its CLI dirs **plus** the registry, re-read live — a run in a new output
dir appears on the one live URL without a restart: one dashboard per
host per user.
- Discovery goes through `daemon.json` (pid + **actual** url), so it
survives port spillover — nothing ever probes port 7788. A live daemon's
URL is logged (`Dashboard running at <url>`); interactive sessions spawn
a detached daemon (own session — killing a run never takes it down) when
none is live (`Dashboard started at <url>`); non-tty launches (CI,
nohup) only register. A stale claim from a dead process is taken over on
the next start.
- `--isolated` is the escape hatch: serve only the given dirs, no
registry read/write, no discovery claim (launchers ignore the instance).
`dashboard: bool = True` on RL/SFT opts a run out via `--no-dashboard`.
- The daemon carries the process title `PRL::Dashboard` via the shared
`set_proc_title`. `psutil` is promoted from transitive to a core
dependency so `prime_rl.utils.process` imports in the slim GPU-free env.
- Launcher startup now ends with a `Dashboard · <url>` banner (blank
lines around, green url) as the last log, after `Launcher complete` (was
`Startup complete. Showing ... logs`). The launcher no longer tails
orchestrator/trainer logs into its terminal - the dashboard is the
monitoring surface.
- New `skills/dashboard/SKILL.md` teaches agents discovery, liveness
checks, and kill/restart commands; `monitor-run` and `start-run` skills
point at it.

Supersedes #3368, rebuilt on the (now merged) stack #3369 (PRL prefix) →
#3370 (GPU extra; the server is a normal package member, so no
setproctitle fallback and no duplicated cache-dir logic); targets
`main`.

## Verification

E2E on this box: daemon claims `daemon.json` with pid + url and shows
`PRL::Dashboard` in `ps`; `ensure_dashboard` from a second process
registers a fresh output dir and the live dashboard absorbs it (run
count grows without restart); a second instance spills to port 7789 and
does **not** steal the claim; `--isolated` serves only its dirs and
leaves the registry untouched; a pty-spawned launcher starts a detached
daemon that survives the launcher's exit; slim `uv sync --extra
dashboard` env (no torch/vllm) imports `entrypoints.dashboard`,
`dashboard.server`, and `set_proc_title`, and `dashboard --help` works;
`tests/unit/test_configs.py` passes (122).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are local dev/monitoring UX and read-only dashboard serving;
training paths are unchanged aside from optional subprocess spawn and
registry file writes.
> 
> **Overview**
> **RL and SFT launchers** now register each run’s `output_dir` in a
per-user registry and ensure a single local dashboard serves it. New
`dashboard: bool = True` (disable with `--no-dashboard`) drives
`ensure_dashboard` in `entrypoints/dashboard.py`, which reuses a live
daemon via `~/.cache/prime-rl/dashboard/daemon.json` or spawns a
detached process in interactive TTY sessions only.
> 
> The **dashboard server** merges CLI dirs with `dirs.json` (live
re-read), claims/releases daemon discovery, adds **`--isolated`** to opt
out of the registry, and moves sidecar cache under the shared dashboard
state dir. The **`dashboard` console script** now enters through
`entrypoints.dashboard.main`.
> 
> **Launcher UX** drops `tail -F` on orchestrator/trainer logs; startup
ends with **Launcher complete** and a **Dashboard · url** banner.
**`psutil`** is a direct dependency so process titles work without the
GPU stack. Agent skills/docs describe discovery, liveness, and
kill/restart.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
035e7ec4c1a2671db778a85a42147d332a8a73ed. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 15:12:09 -07:00
a5853ce9ab feat: slim uv sync (#3370)
## Summary

- The CUDA/linux-only stack (torch+cu128 index, vllm, torchtitan,
mooncake-transfer-engine, ring-flash-attn, dion, tilelang,
flash-linear-attention, torchao, nvidia-ml-py, modelexpress) moves from
core dependencies into a **`gpu` extra** (linux-marked), and
`darwin/arm64` joins `tool.uv.environments` — a bare `uv sync` now
resolves and installs on a MacBook (slim: configs, monitors, dashboard,
CLI tooling). `uv sync --all-extras` — already the recommended install
on GPU machines — pulls everything exactly as before (`all` aggregates
`gpu` too).
- Every other GPU extra (`flash-attn-3`, `flash-attn-cute`, `disagg`,
`gpt-oss`, `quack`, `kernels`, the `mamba-ssm` group) gets linux markers
so the darwin lock split resolves; the torch cu128 index sources are
linux-scoped.
- CI (`cpu_tests`, benchmarks) and the docker entrypoint's
`PRIME_RL_REF` override sync move to `--all-extras`; `Dockerfile.cuda`
adds `--extra gpu`; the install skill documents the split.
- The dashboard's standalone PEP 723 `--script` form is removed: `uv
sync --extra dashboard && uv run dashboard` is now the dependency-free
path everywhere, and `server.py` becomes a normal package member — it
imports the new `CACHE_DIR` from `utils/pathing` instead of duplicating
the cache-dir logic.

## Breaking

- `uv sync` without extras no longer installs the training/inference
stack; use `uv sync --all-extras` (recommended) or `--extra gpu`.
Anything invoking `uv sync --extra flash-attn` alone must add `--extra
gpu`.
- `uv run --script src/prime_rl/dashboard/server.py` no longer works
(header removed); use `uv sync --extra dashboard && uv run dashboard`.

## Verification

On linux: bare `uv sync --extra dashboard` produces an env with no
torch/vllm from which `uv run dashboard` serves real runs end to end;
`uv sync --all-extras --all-packages` restores the full env (torch
2.11+cu128, vllm import, `entrypoints.rl` import OK);
`tests/unit/test_configs.py` (122 passed) and the dashboard browser
smoke pass. `uv lock` resolves all three environments including the new
darwin split.

#3369 (PRL prefix) is merged and this now targets `main`; the
dashboard-daemon PR (#3371) lands on top.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes the default dependency contract and Docker runtime `uv sync`
behavior; anyone on bare `uv sync` or old dashboard script paths will
miss GPU deps, and PRIME_RL_REF overrides now pull all extras (including
heavy disagg/quack) at pod startup.
> 
> **Overview**
> **Slim default install:** Core dependencies no longer pull the Linux
CUDA training stack (torch/cu128, vllm, torchtitan, mooncake,
ring-flash-attn, dion, tilelang, flash-linear-attention, torchao,
modelexpress, nvidia-ml-py). Those move behind a new **`gpu` optional
extra** (linux-marked). Other GPU extras (`flash-attn-3`, `disagg`,
`quack`, `kernels`, `mamba-ssm`, etc.) get linux markers;
**`darwin/arm64`** is added to `tool.uv.environments` so a bare `uv
sync` resolves on macOS. The **`all`** extra now includes
`prime-rl[gpu]`.
> 
> **Install paths updated:** CI (`cpu_tests`, benchmarks) and
**`Dockerfile.cuda`** sync with **`--all-extras`** / explicit **`--extra
gpu`** so Linux GPU images still get the full stack.
**`scripts/docker-entrypoint.sh`** on `PRIME_RL_REF` overrides switches
from a hand-picked extra list to **`uv sync --inexact --all-extras`**
(plus `mamba-ssm` group)—so override checkouts may install disagg/quack
at startup, not only flash-attn/gpt-oss.
> 
> **Dashboard:** The PEP 723 **`uv run --script`** standalone form is
removed from `server.py`; docs/skills point to **`uv sync --extra
dashboard && uv run dashboard`**. Dashboard sidecar cache uses shared
**`CACHE_DIR`** from `utils/pathing` (`home_dir()` fallback to temp).
> 
> **Breaking:** `uv sync` alone no longer installs training/inference
deps—use **`uv sync --all-extras`** (recommended on GPU Linux) or
**`--extra gpu`** (and add flash-attn etc. as before). **`uv run
--script src/prime_rl/dashboard/server.py`** no longer works.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
64562e87834dc6ef1eba7ab372b50f102088cb5f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 14:43:45 -07:00
Mika SenghaasandGitHub 38582b2bf1 chore: bump verifiers to 0.3.1 (#3372)
## Summary

- require the stable `verifiers[harbor]>=0.3.1` release instead of a
development build
- point the Verifiers submodule at the published `v0.3.1` tag

## Verification

- `uv lock --check`
- built `verifiers-0.3.1-py3-none-any.whl` and `verifiers-0.3.1.tar.gz`
from `deps/verifiers`
- verified the submodule commit has the exact `v0.3.1` tag

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dependency constraint only—switches from a dev pre-release to the
stable 0.3.1 minimum with no application code changes in this diff.
> 
> **Overview**
> Pins **`verifiers[harbor]`** to the stable **`>=0.3.1`** release
instead of the prior **`>=0.3.1.dev59`** development build in
`pyproject.toml`.
> 
> This moves dependency resolution off a pre-release dev tag onto the
published 0.3.1 line while keeping the same optional **`harbor`** extra
and existing editable **`deps/verifiers`** source configuration.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f399e80c03ad6e26533aa770df28e90c69517891. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 14:24:46 -07:00
a266325605 feat: rename proc-title prefix to PRL (#3369)
## Summary

- `PRIME_RL_PROC_PREFIX` becomes `PRL`, so every component's process
title reads `PRL::Trainer`, `PRL::Orchestrator`, `PRL::Inference`,
`PRL::EnvServer`, `PRL::Launcher`, ... — shorter to type and grep. The
`monitor-run` skill's process tree is updated.

## Breaking

- Process titles change from `PRIME-RL::<Name>` to `PRL::<Name>`;
anything matching the old prefix (`pgrep -f PRIME-RL`, dashboards, ops
scripts) must switch.

First PR of a 3-stack: PRL prefix → CPU-only `uv sync` (GPU deps behind
an extra) → dashboard daemon.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 14:17:03 -07:00
Konstantin DunasandGitHub b9de4a0f7a fix(orchestrator): make dispatch failures explicit (#3364) 2026-08-24 22:23:30 +02:00
75663f0d4c feat: add local run dashboard (#3351)
## Summary

Adds a local run dashboard for SFT / RL / Eval runs. Start with

```bash
# default (all runs in outputs/, port 7788)
uv run dashboard 
```

For example, populate with

```
# rl run
uv run rl @ examples/basic/reverse-text/rl.toml --run.name reverse-text-rl

# sft run
uv run sft @ examples/basic/reverse-text/sft.toml --max-steps 10 --run.name reverse-text-sft

# eval run (multi-agent, multi-branch)
uv run eval \
  --env.id agentic-judge \
  --env.taskset.id terminal-bench-2 \
  --env.taskset.tasks '["fix-git"]' \
  --env.solver.harness.id rlm \
  --env.solver.harness.summarize-at-tokens 4000 \
  --env.judge.harness.id bash \
  --run.name tb2-agentic-judge
```

Combines the best things from W&B + PI platform. Fully isolated
agent-maintained logic in `prime_rl.dashboard`. Fully supersedes the
previously advertised tmux viewer. Should basically be always on when
working with prl locally.

## Gallery

**Configs**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 01 35
PM"
src="https://github.com/user-attachments/assets/a6dec2e2-26d0-49a9-a220-f1baa8c7b1ea"
/>

**Metrics**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 01 55
PM"
src="https://github.com/user-attachments/assets/c38cbac5-177e-4850-a3fc-d09e10da6185"
/>

**Trace Overview**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 02 08
PM"
src="https://github.com/user-attachments/assets/27f4d197-3969-4334-a629-161ac5df434d"
/>

**Trace Viewer**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 02 47
PM"
src="https://github.com/user-attachments/assets/2b9c4aed-20bb-4623-a272-93b5603a79d3"
/>

**Logs**

<img width="1608" height="1045" alt="Screenshot 2026-08-23 at 6 03 08
PM"
src="https://github.com/user-attachments/assets/91aa3334-8f97-409a-9f8a-d9e19bff1892"
/>

## Breaking

- `scripts/tmux.sh` is removed — the dashboard replaces the tmux
log-pane workflow (docs, example walkthroughs, and the monitor-run skill
updated).

- Resolved per-component configs move from `{run_dir}/configs/*.json` to
`{run_dir}/configs/resolved/*.json`; `configs/` now holds the launch
TOML (`rl.toml`/`sft.toml`). Anything reading the old paths must switch
(the dashboard reads both layouts).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are additive for training (new CLI and docs) plus removal of
the tmux helper; the config path split may break external tooling that
still reads `{run_dir}/configs/*.json` directly.
> 
> **Overview**
> This PR adds **`uv run dashboard`** — a local web UI (default
**http://localhost:7788**) for watching SFT/RL/eval runs from output
directories only: **metrics** (W&B-style overview from `metrics.jsonl`),
**configs** (launch TOML vs merged resolved JSON), **rollout traces**
with per-token advantage/logprob views, and **merged component logs**.
It ships as a **`dashboard` optional extra** (FastAPI/uvicorn) or as
**`uv run --script src/prime_rl/dashboard/server.py`** on machines
without full GPU deps.
> 
> **`scripts/tmux.sh` is removed**; docs, basic examples, and the
**monitor-run** skill now recommend two terminals plus the dashboard
instead of tmux panes. Side-by-side ablations on one node can use **`uv
run dashboard outputs`** to track multiple experiments.
> 
> **Resolved configs** from dry-run and launches are documented at
**`{run_dir}/configs/resolved/*.json`**, with the launch TOML at
**`configs/*.toml`**; the dashboard server still reads the old flat
`configs/*.json` layout for older runs.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
99d9a8f34e9c53b7de1f6a74f82c4053285ba506. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 12:59:39 -07:00
Mika SenghaasandGitHub a975cab86d chore: bump renderers to 0.1.10 (#3367)
## Summary

- Require renderers 0.1.10 in Prime RL and prime-rl-configs.
- Update the renderers submodule to the 0.1.10 release.
- Update the verifiers submodule to the latest main commit.
- Refresh lock metadata for both dependency constraints.

## Verification

- uv lock --check
- uv run --no-project --with pre-commit pre-commit run --files
pyproject.toml packages/prime-rl-configs/pyproject.toml uv.lock

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a
summary for commit 95ca34dcca9b2737cf2ebb431a47391ed874052a. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 11:33:20 -07:00
Garrett GoonandGitHub 9aa5f1f2c8 docs(install): document pre-commit hook install step (#3366)
`uv sync --group dev` only installs the pre-commit package; the git hook
stays inert until `uv run pre-commit install` runs, which the install
skill omitted (README's Development section already covers it).
2026-08-24 14:25:05 -04:00
Matej SirovatkaandGitHub c09bb0b30c fix(nccl): avoid cloning received weight tensors (#3365)
## Summary

- yield tensor views into the contiguous NCCL receive buffer instead of
cloning every reconstructed tensor
- avoid duplicating checkpoint payloads while vLLM performs layerwise
weight loading

The change intentionally keeps the existing flat receive stream and vLLM
reload lifecycle. Trainer state-dict boundaries are transport framing,
not loader semantics: vLLM tracks layer completion from the weights
loaded for each module.

## Safety

Each yielded tensor is a disjoint view of the receive buffer. A view
retains its underlying storage, so the buffer cannot be released while
the loader still references one of its tensors. The existing consumers
either copy tensors directly into model parameters or synchronously
process the ordered checkpoint stream.

## H200 reproduction

The reported Laguna-S-2.1 failure was reproduced with one EP8 trainer
node, one TP8 inference node, BF16 checkpoint transfer, and
`gpu_memory_utilization = 0.94`. The receiver code at the tested
baseline (`f53e4d9c`) is unchanged on current `main`.

| Receiver | Startup v0 | Post-training v1 |
|---|---:|---:|
| `main` | OOM on a 20 MiB clone in state dict 3/49; HTTP 500; retry
decoded `54639` state dicts | — |
| this change | 49/49 on all 8 ranks; HTTP 200 | 49/49 on all 8 ranks;
HTTP 200 |

Both successful transfers took approximately 12 seconds by broadcast
markers; the trainer reported `time/broadcast_weights = 13.2418s` for
v1. The inference server subsequently completed two rollout batches, and
the trainer completed its first optimization step.

At `gpu_memory_utilization = 0.97`, the baseline failed earlier while
allocating the 4.64 GiB receive buffer itself, so `0.94` was used to
isolate the additional clone allocation.

## Validation

- `uv run --no-sync pytest -q tests/unit/inference
tests/unit/transports/test_nccl_broadcast.py` — 14 passed, 1 existing
skip
- `uv run --no-sync ruff check
src/prime_rl/inference/vllm/worker/nccl.py`
- `uv run --no-sync python -m py_compile
src/prime_rl/inference/vllm/worker/nccl.py`
- `git diff --check`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches distributed weight-transfer memory semantics on the inference
path; incorrect view lifetime could corrupt loads, but consumers copy
into model parameters synchronously.
> 
> **Overview**
> Fixes GPU OOM during NCCL weight broadcast by **not cloning** each
tensor when splitting the per-dtype receive buffer in
`receive_state_dict`.
> 
> Reconstructed weights are now **views** into the contiguous
`concatenated` buffer (`view(shape)` only), so checkpoint payloads are
not duplicated while vLLM runs layerwise loading via
`load_weights_checkpoint_layerwise` / `load_weights_kernel`. The flat
NCCL stream and per-state-dict receive lifecycle stay the same; disjoint
views keep the buffer alive until consumers finish using yielded
tensors.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
d7bd908099d5cffb6792b9b40bdbd322851bc19a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-24 11:12:34 -07:00
3e93371dad chore: bump verifiers and prime-envs to latest main (#3363)
## Summary
- Bump the `deps/verifiers` submodule from `d4f3d5a8c` to `807aaf389`
(latest `main`).
  - Pulls in:
- [vf#2425](https://github.com/PrimeIntellect-ai/verifiers/pull/2425):
forward sampling parameters across dialects.
- [vf#2428](https://github.com/PrimeIntellect-ai/verifiers/pull/2428):
centralize v1 egress policy decisions.
- [vf#2427](https://github.com/PrimeIntellect-ai/verifiers/pull/2427):
simplify v1 CLI plumbing.
- Bump the `deps/prime-envs` submodule from `b30aad36` to `26dafdc9`
(latest `main`).
  - Pulls in:
-
[prime-envs#761](https://github.com/PrimeIntellect-ai/prime-envs/pull/761):
environment-design rules in AGENTS.md.
-
[prime-envs#762](https://github.com/PrimeIntellect-ai/prime-envs/pull/762):
CI fix for swebench 5 + prime-sandboxes 0.2.37.
-
[prime-envs#684](https://github.com/PrimeIntellect-ai/prime-envs/pull/684):
deshuffle-papers environment.
-
[prime-envs#675](https://github.com/PrimeIntellect-ai/prime-envs/pull/675):
DeepSWE environment.
- Relock `uv.lock`: new workspace members `deep-swe` and
`deshuffle-papers`; `mcp-atlas` 0.3.0 → 0.3.1, `swesmith-env` 0.1.2 →
0.1.3.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Dependency/submodule bump that pulls new training environments and
tighter swebench/prime-sandboxes pins; not auth-critical, but can change
eval/training behavior.
> 
> **Overview**
> Bumps `deps/verifiers` and `deps/prime-envs` to latest `main` and
relocks `uv.lock`.
> 
> **verifiers** picks up sampling-parameter forwarding across dialects,
centralized v1 egress policy, and simpler v1 CLI plumbing.
> 
> **prime-envs** adds the `deep-swe` and `deshuffle-papers` workspace
environments, plus env-design AGENTS.md rules. `mcp-atlas` goes 0.3.0 →
0.3.1 (`prime-sandboxes>=0.2.37`); `swesmith-env` goes 0.1.2 → 0.1.3
(`swebench>=4.1.0,<5`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b5b07f4795eb911daf72d30203dbd617dec63b37. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-23 18:11:10 -07:00
f53e4d9c63 fix: health-check only the router when admin clients bypass it (#3359)
## Summary

- `AdminClients.wait_for_ready` still health-checks every engine and the
router, but when admin URLs bypass a router, the per-engine waiting
lines log at debug. Startup then logs one info waiting line instead of
one per engine plus the router:

```
03:18:09    INFO Waiting for inference server at http://localhost:8000 to start up (30s elapsed)
03:18:09    INFO Waiting for inference server at http://localhost:8100 to start up (30s elapsed)
```

- `check_health` grows a `quiet` flag that demotes its periodic waiting
lines to debug.
- Deployments without a router (no `client.admin_base_url`) keep logging
at info, as before.

Waiting only on the router is not enough: the llm-d router (Envoy) only
routes `/v1/` and `/inference/v1/`, so `/health` 404s and `check_health`
treats that as "no health route" and skips. The engines therefore stay
part of the readiness wait for correctness; the router just owns the
info-level log. Caveat: on llm-d deployments the info-level waiting line
disappears once Envoy binds its port (the engine waits continue at
debug).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Readiness polling and log-level only; no change to auth, weights, or
request serving. Timeout behavior is the same, just split across two
concurrent health waits.
> 
> **Overview**
> Fixes readiness for llm-d/Envoy routers: `/health` on the router 404s
and was treated as “no health route,” so waiting on the router alone was
not a real ready signal.
> 
> `AdminClients.wait_for_ready` now health-checks engines and router in
parallel. Engine waits use a new `quiet` flag so periodic “waiting”
lines log at debug when a router is present; the router still logs at
info. Deployments without `admin_base_url` are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5167b63bac1ed60edf3f79a99ed470d25a6a026e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 22:03:11 -07:00
280 changed files with 29862 additions and 10393 deletions
+1 -1
View File
@@ -170,7 +170,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync
run: uv sync --all-extras
- name: Download all benchmark artifacts
uses: actions/download-artifact@v8
with:
-155
View File
@@ -1,155 +0,0 @@
name: Build Kernels
# Builds the `prime-kernels` wheel for x86_64 and aarch64 from the deps/prime-kernels submodule.
# Runs on every bump of that submodule to catch build breakage, and with `release_tag` to
# attach the wheels to a GitHub release — which is how they are consumed (see the `kernels`
# skill).
#
# `tag-and-release.yaml` calls this for every release, before it promotes the draft, so a
# published release always carries the wheels its `[tool.uv.sources]` pin can point at.
# `workflow_dispatch` does the same by hand, for backfilling an already published release.
#
# No GPU is needed: nvcc cross compiles for the architectures kernels.toml declares.
on:
pull_request:
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
push:
branches: [main]
paths:
- "deps/prime-kernels"
- ".gitmodules"
- ".github/workflows/build_kernels.yaml"
workflow_dispatch:
inputs:
release_tag:
description: "Existing release tag to attach the wheels to (e.g. v0.7.0). Empty = artifacts only."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the ref the workflow was started on."
required: false
type: string
workflow_call:
inputs:
release_tag:
description: "Release tag to attach the wheels to. The release may still be a draft."
required: false
type: string
ref:
description: "Ref to build the kernels from. Empty = the caller's ref."
required: false
type: string
env:
# Keep in sync with the CUDA the prime-rl image is built against (Dockerfile.cuda);
# the job container image below must be edited alongside it (no env context there).
CUDA_TAG: cu128
jobs:
build:
name: Build wheel (${{ matrix.arch }})
# Uploading the wheels to a release needs write; on workflow_call the caller
# must grant it too (tag-and-release.yaml does).
permissions:
contents: write
strategy:
fail-fast: false
matrix:
include:
- runner: image-builder
arch: x86_64
- runner: image-builder-arm-2204
arch: aarch64
runs-on: ${{ matrix.runner }}
container: nvidia/cuda:12.8.1-devel-ubuntu24.04
steps:
- name: Install build tooling
run: |
apt-get update
apt-get install -y --no-install-recommends git curl ca-certificates build-essential gh
- name: Checkout
uses: actions/checkout@v5
with:
submodules: false
ref: ${{ inputs.ref }}
# deps/prime-kernels is the prime-kernels submodule and carries every kernel's sources.
- name: Init the kernels submodule
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git submodule update --init -- deps/prime-kernels
- name: Install uv
run: |
curl -LsSf https://astral.sh/uv/install.sh | env INSTALLER_NO_MODIFY_PATH=1 UV_INSTALL_DIR=/usr/local/bin sh
uv --version
# The wheel only imports under the exact torch it was compiled against, so build
# against the torch prime-rl resolves rather than whatever is newest today.
- name: Create build environment
env:
UV_TORCH_BACKEND: ${{ env.CUDA_TAG }}
run: |
TORCH_PIN=$(grep -A1 '^name = "torch"$' uv.lock | sed -n 's/^version = "\([^"+]*\).*"$/\1/p' | head -n1)
if [ -z "$TORCH_PIN" ]; then
echo "Could not read torch's version from uv.lock" >&2
exit 1
fi
echo "Building against torch==$TORCH_PIN"
uv venv --python 3.12 /tmp/build-env
VIRTUAL_ENV=/tmp/build-env uv pip install "torch==$TORCH_PIN" setuptools wheel ninja
# torch C++ extensions are bound to the torch and CUDA they were compiled against, so
# the wheel carries both in its local version.
- name: Stamp ABI into the version
run: |
TORCH_VERSION=$(/tmp/build-env/bin/python -c 'import torch; print(torch.__version__.split("+")[0])')
LOCAL="${CUDA_TAG}torch${TORCH_VERSION}"
sed -i -E "s/^version = \"([^\"]+)\"$/version = \"\1+${LOCAL}\"/" deps/prime-kernels/pyproject.toml
grep '^version' deps/prime-kernels/pyproject.toml
- name: Build wheel
env:
VIRTUAL_ENV: /tmp/build-env
CUDA_HOME: /usr/local/cuda
PRIME_KERNELS_REQUIRE: "1"
MAX_JOBS: "8"
run: uv build --wheel --no-build-isolation --out-dir dist deps/prime-kernels
- name: Inspect wheel
run: |
ls -lh dist/
/tmp/build-env/bin/python - <<'PY'
import pathlib, zipfile
wheel = next(pathlib.Path("dist").glob("*.whl"))
extensions = [n for n in zipfile.ZipFile(wheel).namelist() if n.endswith(".so")]
assert extensions, f"{wheel.name} contains no compiled kernels"
print(wheel.name, *extensions, sep="\n ")
PY
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: prime-kernels-${{ matrix.arch }}
path: dist/*.whl
if-no-files-found: error
- name: Attach to release
if: inputs.release_tag != ''
env:
GH_TOKEN: ${{ github.token }}
# gh must not resolve the repo from the checkout: inside the container the
# workspace is owned by another uid, which git rejects as dubious ownership.
GH_REPO: ${{ github.repository }}
TAG: ${{ inputs.release_tag }}
run: |
gh release upload "$TAG" dist/*.whl --clobber
# The `[tool.uv.sources]` pin has to name the wheel exactly, ABI suffix and all.
WHEEL=$(basename dist/*.whl)
URL="https://github.com/${GITHUB_REPOSITORY}/releases/download/${TAG}/${WHEEL}"
echo "\`{ url = \"$URL\", marker = \"platform_machine == '${{ matrix.arch }}'\" },\`" >> "$GITHUB_STEP_SUMMARY"
+1 -1
View File
@@ -25,7 +25,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --extra flash-attn --all-packages --locked
run: uv sync --all-extras --all-packages --locked
- name: Run tests
env:
USERNAME_CI: CI_RUNNER
+2 -24
View File
@@ -113,21 +113,8 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
# Wheels are attached while the release is still a draft, so it is never published without
# them — `[tool.uv.sources]` pins prime-kernels at a release asset, and an install that
# resolves to a wheel-less release would fall back to compiling CUDA from source.
kernels-from-auto-tag:
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.auto-tag-on-main.outputs.tag }}
ref: ${{ needs.auto-tag-on-main.outputs.tag }}
release-from-auto-tag:
needs: [auto-tag-on-main, kernels-from-auto-tag]
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
@@ -219,17 +206,8 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
kernels-from-tag:
needs: resolve-release
permissions:
contents: write
uses: ./.github/workflows/build_kernels.yaml
with:
release_tag: ${{ needs.resolve-release.outputs.tag }}
ref: ${{ needs.resolve-release.outputs.tag }}
publish-release:
needs: [resolve-release, kernels-from-tag]
needs: resolve-release
runs-on: ubuntu-latest
permissions:
contents: write
+1
View File
@@ -31,6 +31,7 @@ Namespaces are one honking great idea -- let's do more of those!
## Running code
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
- **Tools vs entrypoints**: standalone scripts in `tools/` use plain argparse with positional args; `[project.scripts]` entrypoints use pydantic-config (`@ file.toml` + dotted CLI overrides).
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
+40 -26
View File
@@ -6,7 +6,7 @@
# Every pyproject.toml + uv.lock, so the dependency sync below caches
# independently of source edits.
FROM nvidia/cuda:12.8.1-base-ubuntu24.04 AS manifests
FROM nvidia/cuda:13.0.1-base-ubuntu24.04 AS manifests
# .git is ~735 MB, changes every commit, and would land in the registry cache.
COPY --exclude=.git . /ctx
RUN mkdir -p /manifests \
@@ -15,7 +15,7 @@ RUN mkdir -p /manifests \
&& cp uv.lock /manifests/
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
FROM nvidia/cuda:13.0.1-cudnn-devel-ubuntu24.04 AS builder
LABEL maintainer="prime intellect"
LABEL repository="prime-rl"
@@ -96,7 +96,7 @@ ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# mount here: .git would bust the cache every commit.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
@@ -132,9 +132,9 @@ 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 flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
uv sync --all-packages --extra gpu --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --extra kernels --group mamba-ssm --locked --no-dev \
&& \
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "quack-kernels", "vllm", "vllm-router")]'
/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
@@ -150,8 +150,8 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
&& 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_cu12-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu12-*.whl; \
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu13-*.whl \
&& rm -rf /tmp/nixl /app/deps/nixl_cu13-*.whl; \
fi
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
@@ -161,19 +161,14 @@ RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
# (uses pinned nvidia-* wheels) needs them. Keeps nvcc/nvvm/ptxas + headers +
# libcudart/libnvrtc/libcudadevrt for JIT compile+link.
FROM builder AS cuda-trim
RUN find /usr/local/cuda-12.8/targets/*/lib \
RUN find /usr/local/cuda-13.0/targets/*/lib \
\( -name 'libcublas*' -o -name 'libcusparse*' -o -name 'libcufft*' \
-o -name 'libcusolver*' -o -name 'libcurand*' -o -name 'libnpp*' \
-o -name 'libnvjpeg*' -o -name 'libnvblas*' \) -delete \
&& find /usr/local/cuda-12.8 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# CUDA 13 runtime libs source
FROM nvidia/cuda:13.0.1-runtime-ubuntu24.04 AS cuda13
RUN mkdir -p /cu13 && cp -d $(find /usr/local \
-name 'libcudart.so.13*' -o -name 'libnvrtc.so.13*' -o -name 'libnvrtc-builtins.so.13*') /cu13/
&& find /usr/local/cuda-13.0 -name '*.a' ! -name 'libcudadevrt.a' ! -name 'libcudart_static.a' -delete
# Runtime image
FROM nvidia/cuda:12.8.1-base-ubuntu24.04
FROM nvidia/cuda:13.0.1-base-ubuntu24.04
ENV DEBIAN_FRONTEND=noninteractive
@@ -203,24 +198,43 @@ RUN apt-get update && apt-get install -y \
libibverbs1 \
ibverbs-providers \
librdmacm1 \
libhwloc15 \
&& ln -sf /usr/bin/python3.12 /usr/local/bin/python \
&& apt-get clean autoclean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# CUDA 12.8 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-12.8 /usr/local/cuda-12.8
RUN ln -sfn /usr/local/cuda-12.8 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
# AWS EFA userspace stack: libfabric + the aws-ofi-nccl NCCL net plugin,
# installed as one version-matched unit via AWS's official installer rather
# than picking versions by hand. Do not substitute a host-mounted copy of
# these libraries instead of building them in -- symbol-version mismatches
# between a host's rdma-core and a container's can silently break the NCCL
# plugin. Run directly in this stage (not a separate one COPY'd in after):
# the installer's own apt-get/dpkg step upgrades system rdma-core packages
# (libibverbs, ibverbs-providers, librdmacm) in place to versions libfabric
# actually links against -- copying only /opt/amazon out of an isolated
# stage leaves that system-wide upgrade behind, so libfabric ends up paired
# with whatever older rdma-core this image's own apt install pulled in and
# fails to load (symbol version mismatch on libefa.so.1). --skip-kmod:
# containers share the host kernel and must never build/load a kernel
# module themselves; the EFA driver is expected to already be present on
# the host. --skip-limit-conf: ulimits config doesn't apply inside a build.
ARG EFA_INSTALLER_VERSION=1.47.0
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates tar gzip \
&& curl -fsSL "https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz" \
-o /tmp/aws-efa-installer.tar.gz \
&& tar -xzf /tmp/aws-efa-installer.tar.gz -C /tmp \
&& cd /tmp/aws-efa-installer \
&& ./efa_installer.sh -y --skip-kmod --skip-limit-conf \
&& cd / && rm -rf /tmp/aws-efa-installer.tar.gz /tmp/aws-efa-installer \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/*
# CUDA 13.0 toolkit (TileLang's runtime nvcc JIT)
COPY --from=cuda-trim /usr/local/cuda-13.0 /usr/local/cuda-13.0
RUN ln -sfn /usr/local/cuda-13.0 /usr/local/cuda && test -x /usr/local/cuda/bin/nvcc
ENV CUDA_HOME=/usr/local/cuda
ENV PATH="/usr/local/cuda/bin:${PATH}"
# CUDA 13 runtime libs for deep-gemm
COPY --from=cuda13 /cu13/ /opt/cuda13/lib64/
RUN echo /opt/cuda13/lib64 > /etc/ld.so.conf.d/cuda13.conf \
&& ldconfig \
&& ldconfig -p | grep -q libcudart.so.13 \
&& ldconfig -p | grep -q libnvrtc.so.13
ARG USER_ID=1000
ARG GROUP_ID=1000
+1 -1
View File
@@ -59,7 +59,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ✅ |
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
| GLM-4 · GLM-4.5 MoE · INTELLECT-3 (`glm4_moe`) | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5-Air`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | yes | ✅ | ✅ |
| GPT-OSS (HF, MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | yes | ✅ | ✅ |
| GPT-OSS (`gpt_oss`) | `unsloth/gpt-oss-20b-BF16`, … | yes | ✅ | ✅ |
| Other HF causal LMs | Qwen3 dense, Mistral, … (`impl = "hf"`) | varies | ❌ | ✅ |
@@ -6,43 +6,46 @@
"lora_rank": null,
"seq_len": 65536,
"ac": "Recompute",
"selective_targets": null,
"attention": "flash_attention_2",
"output": "benchmark_result.json",
"output": "benchmarks/baselines/benchmark-1xa6000-Qwen--Qwen3-0.6B-rl-full-1gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
"dry_run": false,
"timeout": 1500,
"timeout": 600,
"max_steps": 4,
"micro_batches": 2,
"ep": 1,
"cp": 1,
"fused_lm_head_token_chunk_size": 1024,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:50:40+00:00",
"commit_sha": "7007d2ef",
"timestamp": "2026-08-29T02:35:31.543870+00:00",
"success": true,
"error_reason": null,
"time_taken": 276.12556480802596
"time_taken": 295.5118532651104
},
"metrics": {
"mfu": {
"mean": 20.802552047875178,
"std": 0.16199364988631793,
"min": 20.664358307416567,
"max": 20.98082222151257
"mean": 16.701924322664684,
"std": 0.0999595293790186,
"min": 16.586575698092034,
"max": 16.763194274056005
},
"throughput": {
"mean": 2484.411208996455,
"std": 19.346608946709658,
"min": 2467.9069802355616,
"max": 2505.7016937694384
"mean": 1994.6806480062144,
"std": 11.937986005933869,
"min": 1980.9047701633856,
"max": 2001.998007610024
},
"step_time": {
"mean": 52.79691480938345,
"std": 0.4071756223542672,
"min": 52.35017399210483,
"max": 53.14720633160323
"mean": 65.74198961785685,
"std": 0.3962098986964774,
"min": 65.49867434287444,
"max": 66.19917749473825
},
"peak_memory": {
"gib": 11.728515625,
"pct": 24.742767157118376
"gib": 11.591145833333334,
"pct": 24.45296844104
}
}
}
}
@@ -6,43 +6,46 @@
"lora_rank": null,
"seq_len": 65536,
"ac": "Recompute",
"selective_targets": null,
"attention": "flash_attention_2",
"output": "benchmark_result.json",
"output": "benchmarks/baselines/benchmark-4xa6000-Qwen--Qwen3-0.6B-rl-full-4gpu-Recompute-flash_attention_2-65536-cp1-ep1.json",
"dry_run": false,
"timeout": 1500,
"timeout": 600,
"max_steps": 4,
"micro_batches": 2,
"ep": 1,
"cp": 1,
"fused_lm_head_token_chunk_size": 1024,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "c88d08fdf",
"timestamp": "2026-06-24T22:55:54+00:00",
"commit_sha": "7007d2ef",
"timestamp": "2026-08-29T02:28:40.728120+00:00",
"success": true,
"error_reason": null,
"time_taken": 291.91085167229176
"time_taken": 317.33935201819986
},
"metrics": {
"mfu": {
"mean": 17.217465998339005,
"std": 0.02905058130694137,
"min": 17.19503698271855,
"max": 17.250282374540514
"mean": 15.880248465863398,
"std": 0.005915779562921215,
"min": 15.873443653590638,
"max": 15.884167926432548
},
"throughput": {
"mean": 8225.003435798719,
"std": 13.877833769765575,
"min": 8214.288808538377,
"max": 8240.68023789224
"mean": 7586.197539502296,
"std": 2.826043462792163,
"min": 7582.946793757898,
"max": 7588.069915881657
},
"step_time": {
"mean": 63.90305413212627,
"std": 0.11015530079183487,
"min": 63.77801387012005,
"max": 63.985770548693836
"mean": 69.21047159920757,
"std": 0.022114607283211834,
"min": 69.19065106380731,
"max": 69.234325167723
},
"peak_memory": {
"gib": 6.298828125,
"pct": 13.288163877053583
"gib": 8.55078125,
"pct": 18.038939985655993
}
}
}
}
-113
View File
@@ -1,113 +0,0 @@
#!/usr/bin/env python3
"""
Time the routed-expert compute three ways: the fused MoE kernel (bf16 and mxfp8) against
the grouped-mm path a `model.moe_fused_kernel=false` run takes.
Forward and backward are timed separately, because only the forward is a kernel — the
backward is prime-rl's own closed-form bf16 gradients or, for mxfp8, autograd through the
grouped-mm reference. A speedup on the forward can be spent again on the backward.
uv run benchmarks/scripts/bench_fused_moe.py
uv run benchmarks/scripts/bench_fused_moe.py --tokens 16384 --num-experts 128
"""
from __future__ import annotations
import argparse
import torch
from prime_rl.trainer.models.layers.moe import _FusedMoE, _load_fused_moe_kernel, _run_experts_fused_reference
MODES = ("grouped_mm", "fused_bf16", "fused_mxfp8")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--tokens", type=int, default=8192, help="routed tokens (batch * seq)")
parser.add_argument("--dim", type=int, default=2048, help="model dim; must be a multiple of 256")
parser.add_argument("--hidden-dim", type=int, default=768, help="expert intermediate size; multiple of 128")
parser.add_argument("--num-experts", type=int, default=64)
parser.add_argument("--top-k", type=int, default=8)
parser.add_argument("--iters", type=int, default=20)
parser.add_argument("--warmup", type=int, default=5)
return parser.parse_args()
def make_inputs(args: argparse.Namespace) -> tuple[torch.Tensor, ...]:
torch.manual_seed(0)
randn = lambda *shape: torch.randn(*shape, device="cuda", dtype=torch.bfloat16)
x = (randn(args.tokens, args.dim) * 0.2).requires_grad_(True)
w1 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w3 = (randn(args.num_experts, args.hidden_dim, args.dim) * 0.05).requires_grad_(True)
w2 = (randn(args.num_experts, args.dim, args.hidden_dim) * 0.05).requires_grad_(True)
logits = torch.randn(args.tokens, args.num_experts, device="cuda", dtype=torch.float32)
top_scores, selected = torch.softmax(logits, dim=-1).topk(args.top_k, dim=-1)
return x, w1, w2, w3, selected, top_scores.requires_grad_(True)
def run_forward(mode: str, inputs: tuple[torch.Tensor, ...], num_experts: int) -> torch.Tensor:
x, w1, w2, w3, selected, top_scores = inputs
if mode == "grouped_mm":
return _run_experts_fused_reference(x, w1, w2, w3, selected, top_scores, num_experts)
return _FusedMoE.apply(x, w1, w2, w3, selected, top_scores, num_experts, mode == "fused_mxfp8")
def time_mode(mode: str, inputs: tuple[torch.Tensor, ...], args: argparse.Namespace) -> tuple[float, float, float]:
"""Median forward ms, median backward ms, peak MiB."""
forward_ms, backward_ms = [], []
grad_out = torch.randn(args.tokens, args.dim, device="cuda", dtype=torch.bfloat16)
start, end = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
torch.cuda.reset_peak_memory_stats()
for i in range(args.warmup + args.iters):
for tensor in inputs[:4] + (inputs[5],):
tensor.grad = None
torch.cuda.synchronize()
start.record()
out = run_forward(mode, inputs, args.num_experts)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
forward_ms.append(start.elapsed_time(end))
start.record()
out.backward(grad_out)
end.record()
torch.cuda.synchronize()
if i >= args.warmup:
backward_ms.append(start.elapsed_time(end))
median = lambda values: sorted(values)[len(values) // 2]
return median(forward_ms), median(backward_ms), torch.cuda.max_memory_allocated() / 2**20
def main() -> None:
args = parse_args()
if not torch.cuda.is_available():
raise SystemExit("no CUDA device")
kernel = _load_fused_moe_kernel()
for mxfp8 in (False, True):
reason = kernel.unsupported_shape_reason(args.dim, args.hidden_dim, mxfp8=mxfp8)
if reason is not None:
raise SystemExit(f"shape unsupported by the fused kernel: {reason}")
inputs = make_inputs(args)
print(
f"tokens={args.tokens} dim={args.dim} hidden_dim={args.hidden_dim} "
f"experts={args.num_experts} top_k={args.top_k} "
f"({args.iters} iters, {args.warmup} warmup, median)\n"
)
print(f"{'mode':<12} {'fwd ms':>9} {'bwd ms':>9} {'total ms':>9} {'speedup':>9} {'peak MiB':>10}")
baseline = None
for mode in MODES:
forward, backward, peak = time_mode(mode, inputs, args)
total = forward + backward
baseline = baseline or total
print(f"{mode:<12} {forward:>9.3f} {backward:>9.3f} {total:>9.3f} {baseline / total:>8.2f}x {peak:>10.0f}")
if __name__ == "__main__":
main()
+8 -10
View File
@@ -23,6 +23,7 @@ import torch
from pydantic import Field
from prime_rl.utils.config import BaseConfig, cli
from prime_rl.utils.pathing import get_file_monitor_dir
MAX_LORAS = 4
@@ -70,11 +71,6 @@ class BenchmarkConfig(BaseConfig):
Field(description="Activation checkpointing type"),
] = "Recompute"
selective_targets: Annotated[
list[str] | None,
Field(description="Selective activation checkpoint targets when ac=Selective"),
] = None
attention: Annotated[
Literal["sdpa", "flash_attention_2", "flash_attention_3", "flash_attention_4"],
Field(description="Attention implementation"),
@@ -160,8 +156,6 @@ def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
cmd.append("--model.ac")
elif config.ac == "Selective":
cmd.extend(["--model.ac", "--model.ac.mode", "selective"])
if config.selective_targets:
cmd.extend(["--model.ac.targets", json.dumps(config.selective_targets)])
elif config.ac == "Offload":
cmd.append("--model.ac-offloading")
@@ -214,13 +208,16 @@ def aggregate_metrics(metrics_path: Path) -> dict:
Each metrics.jsonl line is one monitor.log call (``{"step": N, ...}``);
merge the lines per step, drop the first (warmup) step, and compute
mean/std/min/max per metric like the old --bench JSON export did.
mean/std/min/max per metric like the old --bench JSON export did. Rows
keyed by wall time rather than step (``step: null``) are not per-step and
are skipped.
"""
per_step: dict[int, dict] = {}
with open(metrics_path) as f:
for line in f:
row = json.loads(line)
per_step.setdefault(row["step"], {}).update(row)
if row.get("step") is not None:
per_step.setdefault(row["step"], {}).update(row)
steps = sorted(per_step)[1:] # Exclude first warmup step
columns = {
@@ -262,7 +259,8 @@ def run_benchmark(config: BenchmarkConfig) -> None:
return
# The SFT entrypoint writes to output_dir/<run.name>, the RL trainer to output_dir directly
metrics_path = output_dir / "bench" / "metrics.jsonl" if config.type == "sft" else output_dir / "metrics.jsonl"
run_dir = output_dir / "bench" if config.type == "sft" else output_dir
metrics_path = get_file_monitor_dir(run_dir) / "metrics.jsonl"
start_time = time.perf_counter()
try:
+1 -1
+1 -1
+72 -11
View File
@@ -6,6 +6,7 @@ This page covers the specialized features layered on top of the core training st
- [Custom Modeling](#custom-modeling)
- [Expert Parallelism Backends](#expert-parallelism-backends)
- [Runtime Fusions](#runtime-fusions)
- [Multimodal Training](#multimodal-training)
- [Supported Families](#supported-families)
- [Enabling VLM Mode](#enabling-vlm-mode)
@@ -33,36 +34,96 @@ impl = "custom" # or "hf" to force the HF path
| Nemotron H | `nvidia/Nemotron-3-Nano-30B-A3B`, … | ✅ | ❌ |
| Trinity (AFMoE) | `arcee-ai/Trinity-Mini`, … | ✅ | ✅ |
| GLM-4 / GLM-4.5 / INTELLECT-3 | `THUDM/GLM-4-9B-0414`, `zai-org/GLM-4.5`, `PrimeIntellect/INTELLECT-3`, … | ✅ | ✅ |
| GPT-OSS (HF MoE) | `openai/gpt-oss-20b`, `openai/gpt-oss-120b` | ❌ | ✅ |
| GPT-OSS | `unsloth/gpt-oss-20b-BF16`, … | ✅ | ✅ |
The custom path enables you to set EP, CP, selective activation checkpointing, low-precision training (`[trainer.model.quantization]`), and faster MoE kernels (`moe_use_grouped_mm = true`, default). Forcing `impl = "hf"` is mostly useful when debugging — it's slower and disables most MoE-specific knobs.
Selective activation checkpointing works with either implementation. The custom path additionally enables EP, CP, low-precision training, and grouped MoE kernels. Forcing `impl = "hf"` is mostly useful when debugging and disables those model-specific runtime features.
GPT-OSS uses FlashAttention 4 with learned attention sinks. Training requires SM90 or SM100/SM110 GPUs
and a BF16 checkpoint such as `unsloth/gpt-oss-20b-BF16`; the original MXFP4 checkpoints are not supported.
### Low-precision training
Set `[trainer.model.quantization]` to train dense linears and MoE expert GEMMs in low precision. Two backends are available via the `type` discriminator:
Dense linear precision and routed-expert precision are configured independently. `[trainer.model.quantization]` applies only to dense `Linear` modules:
- `type = "fp8"` — DeepGEMM FP8 blockwise (requires SM90+ / Hopper). Options: `enable_grouped_gemm` (FP8 MoE expert GEMM). Both default on.
- `type = "mxfp8"` — torchao MXFP8 microscaling (requires SM100+ / Blackwell). Options: `enable_grouped_gemm`, `enable_a2a` (MXFP8 expert-parallel all-to-all), and `recipe` (`mxfp8_rceil` default or `mxfp8_rceil_wgrad_with_hp`).
- `type = "fp8"` — DeepGEMM FP8 blockwise linears (requires SM90+).
- `type = "mxfp8"` — torchao MXFP8 linears (requires SM100). `recipe` is `mxfp8_rceil` or `mxfp8_rceil_wgrad_with_hp`.
`[trainer.model.moe.compute]` selects routed-expert grouped GEMMs independently:
- `type = "bf16"` (default)
- `type = "deepgemm_fp8"` (requires DeepGEMM and SM90+)
- `type = "mxfp8"` (requires `prime-kernels`, torchao, and SM100)
```toml
[trainer.model.quantization]
type = "mxfp8"
recipe = "mxfp8_rceil"
enable_a2a = true
[trainer.model.moe.compute]
type = "mxfp8"
recipe = "mxfp8_rceil"
[trainer.model.moe.dispatch]
type = "torch"
transport = "mxfp8"
```
All MoE compute backends accept `apply_to`:
- `"all"` (default) applies the backend to all expert groups.
- `"85%"` applies it to the first 85% of model layers, rounded down. For a 48-layer model, this selects layers 0–39.
- `[0, 1, 2, 3]` selects explicit zero-based model layer indices; `[]` selects none.
Percentages must be between 0% and 100%; explicit indices must be within the model's layer count. Non-MoE blocks in hybrid models count toward layer indices and percentages. Each selected layer uses the backend for all its routed experts. Other expert groups use BF16 compute and BF16 token transport while retaining the configured dispatch backend and expert parallelism. Dense linear quantization is configured separately.
For example, this selects routed experts in Qwen3's first four model layers:
```toml
[trainer.model.moe.compute]
type = "mxfp8"
apply_to = [0, 1, 2, 3]
```
Backend shape checks and token alignment apply only to the selected compute path.
In RL runs, configure the same precision selection for rollouts. Inference module names can differ from the trainer's names, and inference precision is configured explicitly, not inferred from `apply_to`. Check the selected modules on both sides before comparing trainer and rollout logprobs.
GLM-5.2 adds IndexShare: the DSA sparse-attention indexer runs only on a subset of layers and the remaining layers reuse the cached top-k indices. The trainer reads this schedule from the model's `indexer_types` config field and enables the index cache automatically, so no extra config is needed. To override the schedule manually, set `[trainer.model.index_cache]` (`topk_freq` or `topk_pattern`).
### Expert Parallelism Backends
`model.ep_comm_backend` picks the all-to-all kernel used for EP dispatch/combine:
`[trainer.model.moe.dispatch]` selects how routed tokens are dispatched and combined:
- **`torch`** (default): TorchTitan's all-to-all collective. Works everywhere, no extra install.
- **`deepep`**: Utilizes DeepEP's custom all-to-all collectives. This provides better performance if EP dimension spans multiple nodes. We provide pre-built binaries for H100/H200 with cuda runtime 12.9 installed, you can install them by running `uv sync --all-extras`.
DeepEP requires some careful tuning to achieve optimal performance, tuning parameters are `deepep_num_sms` and `deepep_token_chunk_size`.
- **`torch`** (default): torch all-to-all with `transport = "bf16"` or, when MXFP8 expert compute is selected, `transport = "mxfp8"` on SM100.
- **`deepep`**: DeepEP custom dispatch/combine kernels. Set `num_sms` and optional `token_chunk_size` in the same table. Pre-built H100/H200 binaries use CUDA 13.0 and are installed by `uv sync --all-extras`.
```toml
[trainer.model.moe.dispatch]
type = "deepep"
num_sms = 20
token_chunk_size = 4096
```
With DeepEP, gradient clipping is currently not supported. (`optim.max_norm` is set to `None` automatically.)
### Runtime Fusions
`model.fusions` packs parameters that are always computed together into one tensor, turning several GEMMs into one. Both fusions are on by default:
- `gate_up` — each gated MoE expert's `gate_proj` and `up_proj` become one `[num_experts, 2 * intermediate_size, hidden_size]` weight, halving the routed-expert grouped GEMMs.
- `qkv` — an attention layer's `q_proj`, `k_proj` and `v_proj` (and their biases) become one linear layer.
```toml
[trainer.model.fusions]
enabled = ["gate_up", "qkv"] # [] disables
```
Fusions are runtime-only. Checkpoints keep the canonical parameter names and shapes, so a run can turn a fusion on or off at any point and still load its own checkpoints, and exported weights are unaffected. Only modules that support a fusion are packed; a requested fusion that no module supports logs a warning, or fails at startup with `raise_on_fail = true`. Fusions are skipped when LoRA is enabled.
Muon receives the packed layout as matrix partitions and orthogonalizes each logical matrix on its own, so a packed parameter trains exactly as the parameters it replaces would — including per-projection learning-rate scaling for grouped-query attention — while keeping a single momentum tensor.
The experimental `shard_fused_on_dim1 = true` shards fused 2-D weights along dim 1 under FSDP, which makes weight loading and checkpointing zero-copy: fused weights and their optimizer state are read and written in place rather than assembled into a full copy on each rank first. It requires `hidden_size` to be divisible by the FSDP shard mesh size.
## Multimodal Training
### Supported Families
@@ -141,7 +202,7 @@ If prefill queues and decode is idle, add prefill nodes (and vice versa).
```bash
salloc -N 1 --gres=gpu:1 bash -c 'bash scripts/install_nixl_from_source.sh'
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
uv pip install --reinstall --no-deps deps/nixl_cu13-*.whl
```
The script writes UCX 1.19 to `third_party/ucx/`; the bundled sbatch templates prepend it to `LD_LIBRARY_PATH` so it overrides the system version. Re-run both commands after every `uv sync`, since the lock pins the wheel.
+18 -27
View File
@@ -13,7 +13,7 @@ This page covers the math and the configurable algorithmic components: the algor
- [Async / Off-Policy Training](#async--off-policy-training)
- [Loss](#loss)
- [Loss Components](#loss-components)
- [Default RL Loss](#default-rl-loss)
- [IPO Loss](#ipo-loss)
- [Custom Loss](#custom-loss)
- [Advantage](#advantage)
- [Default Advantage](#default-advantage)
@@ -184,47 +184,36 @@ $$
\mathcal{L} = \frac{\sum \mathcal{L}_{rl}}{N_{rl}} + \frac{\sum \mathcal{L}_{ce}}{N_{ce}} + \frac{\sum \mathcal{L}_{ref\_kl}}{N_{ref\_kl}}
$$
- `rl` — the configured RL loss (`[trainer.loss]`): DPPO + KL by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `rl` — the configured RL loss (`[trainer.loss]`): IPO by default, or a [custom loss](#custom-loss). Fed by the advantage-assigning algorithms (`grpo`, `max_rl`, `rae`, `hierarchical_grpo`, and `echo`'s action tokens).
- `ce` — masked NLL. Used for frozen-model tokens (`sft`) and env-observation tokens (`echo`).
- `ref_kl` — the per-token reverse KL to a reference model ($\log \pi_{\text{ref}} - \log \pi$) as the policy-gradient signal, importance-ratio corrected with a one-sided trust region (`opd`, `opsd`). Requires `ref_logprobs` from a [reference scoring](#reference-scoring); the scoring model must be a vLLM server (it's the only one that exposes `prompt_logprobs`).
The orchestrator stamps each sample's component membership as per-token weight streams (`rl_weights` / `ce_weights` / `ref_kl_weights` on the wire): a weight scales that component's per-token loss, `0.0` leaves the token out of the component entirely (mask *and* denominator), and components may overlap on the same token — their gradients sum. Each $N$ is the global (all-reduced) count of that component's member tokens, so the components don't dilute each other: adding echo observation tokens never changes the rl term's effective per-token learning rate, and an sft env packed next to a GRPO env doesn't soften its gradient. Tokens of different components pack freely into the same micro batch, and a plain GRPO run ships no weight streams at all (absent streams mean rl weight 1.0 on every trainable token — the unchanged hot path). Advantages always ship per token (`advantages` on the wire), assigned as per-token streams from the start — uniform group credit is broadcast over completion tokens at assignment; algorithms with no rl credit (opd, opsd) ship none.
### Default RL Loss
### IPO Loss
The default RL loss is a DPPO policy-gradient term combined with a KL regularizer similar to Kimi-K2.5. For each prompt $x_j$ we sample a group of $G$ rollouts $\{y_i\}_{i=1}^G$, score them to get $s_i$, then optimize:
The default RL loss is Importance Policy Optimization (IPO). It combines an importance-weighted policy-gradient term with a squared log-ratio KL regularizer. A symmetric trust region removes tokens whose absolute probability change exceeds $\epsilon$:
$$
\mathcal{L}(\theta) = -\,\mathcal{J}_{\text{PG}}(\theta) \;+\; \tau_{KL}\,\mathcal{L}_{KL}(\theta)
\mathcal{L}(\theta) = \frac{1}{N}\sum_t
\left[
-\mathbb{1}\!\left(\left|\pi(y_t)-\mu(y_t)\right| \le \epsilon\right)
\tau_A \hat{A}_t \frac{\pi(y_t)}{\mu(y_t)}
+ \tau_{KL}\log^2\!\left(\frac{\pi(y_t)}{\mu(y_t)}\right)
\right].
$$
where the policy-gradient term is
$\mu$ is the policy that generated the rollout. $\pi$ is the current trainer policy. $\hat{A}_t$ is the token-level advantage. The trust region uses the sampled token probabilities, not their ratio.
$$
\mathcal{J}_{\text{PG}}(\theta)
= \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t}
\min\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}, \delta\right) \hat{A}^{(j)}_{i,t}
$$
and the KL regularizer penalizes drift between trainer and inference policies via the squared log importance ratio:
$$
\mathcal{L}_{KL}(\theta) = \frac{1}{\sum_{j,i} |y_i^{(j)}|}
\sum_{j,i,t} \log^2\!\left(\frac{\pi(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}{\mu(y_{i,t}^{(j)}\mid x_j, y_{i,<t}^{(j)})}\right).
$$
$\mu$ is the policy that generated the rollout (inference), $\pi$ is the current policy (trainer), $\hat{A}_{i,t}$ is the token-level advantage, $\delta$ is the importance-sampling clipping ratio, and $\tau_{KL}$ is the KL temperature. The `min` clamps the importance ratio from above so a stale rollout assigning very low probability to a high-reward token doesn't produce a runaway gradient.
The knobs (under `[trainer.loss]` with `type = "default"`):
The knobs under `[trainer.loss]` are:
| Knob | Default | What it does |
|---|---|---|
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
| `eps` | 0.1 | 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. |
Set `[trainer.loss] type = "default"` and configure via the knobs above. The `ce` and `ref_kl` components are fixed and unaffected by `[trainer.loss]`.
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]`.
### Custom Loss
@@ -424,7 +413,9 @@ demo_key = "demonstration"
Scoring runs before curriculum admission, so a rollout that is later rejected still costs its reference compute.
By default, zero-advantage RL tokens are removed after a complete batch cohort has been collected and before its payload is packed for the trainer. This does not backfill the batch. Samples that still carry CE or reference-KL components are retained, while pure zero-advantage RL samples are not shipped. Removing an RL token also removes its trainer/inference mismatch-KL contribution. Set `orchestrator.train.filter_zero_advantages = false` to retain them.
The orchestrator filters samples with no training signal. This includes samples with zero advantage on all RL tokens. Samples that still carry CE or reference-KL components are retained. Filtering an RL token also removes its trainer/inference mismatch-KL contribution.
`orchestrator.constant_trainer_batch_size` defaults to `true`. The orchestrator filters samples before they count toward the batch target. It collects replacements, so rollout-based batches contain `orchestrator.batch_size` training traces. Set the option to `false` to filter after collection without replacement. This setting can improve orchestrator throughput, but it produces smaller trainer batches.
## Curricula
@@ -436,7 +427,7 @@ Three small implementations are included:
- `StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
- `DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in post-batch zero-advantage filtering, rejection requests replacement work. Groups without an advantage stream are admitted.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in token filter, it can reject a configurable advantage range. Groups without an advantage stream are admitted.
```toml
[orchestrator.train.source.curriculum.sampler]
+9 -3
View File
@@ -2,7 +2,7 @@
Every `prime-rl` entrypoint uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config): TOML files for reproducible base configs, CLI flags for one-off overrides.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions, the trainer-side `enable_token_export` flag) that aren't surfaced here.
> **AI agents working in this repo:** the equivalent runbook is at [`skills/configs/SKILL.md`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/skills/configs/SKILL.md), with extra runtime hints (where config classes live, validator conventions) that aren't surfaced here.
## Table of Contents
@@ -247,8 +247,14 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
Then inspect the resolved config:
```bash
ls /tmp/reverse-dry/check/configs/
ls /tmp/reverse-dry/check/configs/latest/resolved/
# rl.json trainer.json orchestrator.json inference.json
```
Each per-process TOML reflects the final, validated configuration that the actual run would consume — exactly what each process sees when started standalone (`uv run trainer @ /tmp/reverse-dry/check/configs/trainer.json`, etc.). This is the easiest way to bisect a misbehaving config: dry-run a known-good base, dry-run your overlay, diff the two.
Each per-process JSON contains the final, validated configuration that the run
uses. This is also what each standalone process reads. For example, the trainer
reads `configs/latest/resolved/trainer.json`.
`configs/latest/command.txt` records the shell-safe launch command and its CLI
overrides. Each launch also remains under `configs/attempt_<n>/`. To compare
configs, dry-run a known-good base and your overlay. Then diff the two attempts.
+17 -1
View File
@@ -285,7 +285,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`.
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.
```toml
[trainer]
@@ -298,3 +298,19 @@ enable_return_routed_experts = true
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
### Sampling Replay
Truncated sampling (`top_p < 1`, `top_k`) renormalizes the sampling distribution over a sampling mask of surviving token ids. The rollout logprobs reflect that (`logprobs_mode = "processed_logprobs"`), so the trainer must renormalize over the same mask — otherwise every importance ratio is biased and training collapses (DeepSeek V3.2's "Keep Sampling Mask", [arXiv:2512.02556](https://arxiv.org/abs/2512.02556) §3.1; Cognition's [SWE-1.7 post](https://cognition.com/blog/swe-1-7)). prime-rl handles this automatically: vLLM records the sampling mask at sampling time (`--return-sampling-mask`, native since vLLM 0.28) and the trainer renormalizes its logprobs over it.
```toml
[orchestrator.train.sampling]
top_p = 0.95
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
```
That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.
Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.
When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
+44 -16
View File
@@ -43,19 +43,20 @@ uv run rl @ rl.toml \
The launcher allocates GPUs in order from `CUDA_VISIBLE_DEVICES` (or all visible GPUs): inference first, trainer next. To target a specific physical subset, pin `CUDA_VISIBLE_DEVICES` before launching.
For quick A/B ablations on the same node, run two RL instances side-by-side in separate tmux sessions, each pinned to half the GPUs and a separate inference port:
For quick A/B ablations on the same node, run two RL instances side-by-side in separate shells, each pinned to half the GPUs and a separate inference port, and track both in one dashboard:
```bash
# session 1, GPUs 0–1, default port 8000
bash scripts/tmux.sh -s exp1 -o outputs/exp1
# shell 1, GPUs 0–1, default port 8000
CUDA_VISIBLE_DEVICES=0,1 uv run rl @ rl.toml --run.name exp1
# session 2, GPUs 2–3, port 8001
bash scripts/tmux.sh -s exp2 -o outputs/exp2
# shell 2, GPUs 2–3, port 8001
CUDA_VISIBLE_DEVICES=2,3 uv run rl @ rl.toml \
--inference.server.port 8001 \
--orchestrator.model.client.base-url http://localhost:8001/v1 \
--run.name exp2
# watch both side by side
uv run dashboard outputs
```
#### SFT and Torchrun
@@ -98,17 +99,20 @@ EP shards MoE expert weights across the EP mesh, dramatically reducing the FSDP
```toml
[trainer.model]
impl = "custom"
ep = 8 # explicit EP degree; must divide num_experts
ep_comm_backend = "torch" # or "deepep"
ep = 8 # explicit EP degree; must divide num_experts
[trainer.model.moe.dispatch]
type = "torch"
transport = "bf16"
```
`ep_comm_backend = "deepep"` uses DeepEP's custom dispatch/combine kernels for speed, with two extra knobs (`deepep_num_sms`, `deepep_token_chunk_size`) — tune on your hardware.
For DeepEP, set `type = "deepep"` and tune `num_sms` plus optional `token_chunk_size` in the same dispatch table. Routed-expert precision is selected separately with `[trainer.model.moe.compute]` (`bf16`, `deepgemm_fp8`, or `mxfp8`).
### Context Parallelism
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. We reccomend using `ulysses` style CP for most of the models to get the most throughput. Some models (e.g. GLM-5) only support `ring` style CP. Wrong setting will be rejected on validation.
CP shards a single sequence across multiple GPUs along the token dimension — for long-context sequences. Prefer `ulysses`: it gets the most throughput and is the only style that works for hybrid linear-attention/Mamba models (Qwen3.5, NemotronH) and for VLMs. Each model class declares its supported styles in `cp_support`; an unsupported `cp_style`, or a model with no CP support at all (DeepSeek V4, GPT-OSS), is rejected at setup.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Hybrid Mamba layers head-shard independently (`cp_mamba`), which requires the CP degree to divide `mamba_num_heads` and `n_groups`.
`ulysses` head-shards Q/K/V, so the CP degree must divide `num_attention_heads`. GQA models with fewer KV heads than the CP degree (e.g. NemotronH: 32 query heads, 2 KV heads) are supported via KV-head replication; the CP degree must then be a multiple of `num_key_value_heads`. Nemotron-H redistributes its Mamba activations between sequence- and head-parallel layouts in the model-owned Mamba path; the CP degree must divide `mamba_num_heads` and `n_groups`.
```toml
[trainer.model]
@@ -126,15 +130,18 @@ cp_style = "ulysses" # "ring"
| `trainer.model.ac.mode = "selective"` | medium | small |
| `trainer.model.ac_offloading` | extra | a bit more |
AC and AC offloading are enabled by default (full mode). For the best memory/throughput tradeoff, switch to selective AC (custom impl only):
AC and AC offloading are enabled by default (full mode). Both AC modes retain stateful MoE routing updates and DeepEP communication that cannot safely replay. Selective AC uses the same transformer-block boundaries and additionally retains distributed communication, expensive matrix multiplications, grouped GEMMs, and supported attention kernels:
```toml
[trainer.model.ac]
mode = "selective"
targets = ["norm", "attn_proj"] # see Reference for the full list per architecture
```
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only lossing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
Set `targets` to operator names (for example, `"aten::mm"`) or namespaces (for example, `"prime_rl_collectives"`) to replace the default selective targets. Correctness-required operations remain retained.
Activation offloading still applies to tensors saved by autograd, but tensors retained by the checkpoint policy remain on the accelerator.
`ac_offloading` is also on by default with `max_inflight_activations = 5`. We've observed this feature to be very effective, lowering the peak memory usage by 30-40% in some cases, while only losing ~3-5% of throughput. To disable either, set `model.ac = "None"` or `model.ac_offloading = "None"`.
### Optimizer Offloading
@@ -193,9 +200,11 @@ Launch:
```bash
uv run rl @ base_rl.toml @ my_slurm.toml # submits via sbatch
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script + resolved config, exits
uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes launcher/rl.sbatch + resolved config, exits
```
Every SLURM entrypoint stores its generated scripts and coordination files under `<run_dir>/launcher/`. SLURM stdout and stderr go to `launcher/logs/`. Local launches do not create `launcher/`.
### `[deployment]` Block
`[deployment]` is a discriminated union picked by `type` — `single_node` or `multi_node` for RL/SFT, with an extra disaggregated variant for inference. RL multi-node:
@@ -214,7 +223,8 @@ SFT multi-node:
```toml
[deployment]
type = "multi_node"
num_nodes = 2
num_train_nodes = 2
num_infer_nodes = 1 # required only for online evals
gpus_per_node = 8
```
@@ -227,6 +237,24 @@ Full multi-node configs ship under [`examples/advanced/`](https://github.com/Pri
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.
### NIXL weight broadcast
Set `[weight_broadcast] type = "nixl"` to use receiver-driven NIXL weight transfer. Before the first SLURM run, install the NIXL/UCX build and the ModelExpress service binaries on the shared filesystem:
```bash
bash scripts/install_nixl_from_source.sh
uv pip install --reinstall --no-deps deps/nixl_cu12-*.whl
bash scripts/install_modelexpress.sh
```
The generated job starts a job-scoped ModelExpress server and Redis backend on the trainer head node and passes that address to every component. To use an existing service, set `slurm.launch_modelexpress = false` and configure `weight_broadcast.host` and `weight_broadcast.port`.
The launcher requires the CUDA and InfiniBand transports from `third_party/ucx`. Each NIXL process selects the active InfiniBand port nearest its GPU; an explicitly configured `UCX_NET_DEVICES` takes precedence. Inference ranks start their pulls at different trainer ranks so concurrent workers distribute traffic across all available source rails.
ModelExpress exchanges peer metadata during startup. Weight updates reuse prepared NIXL requests, post every trainer-rank read in a transfer group concurrently, and use versioned NIXL notifications for source readiness and buffer credits.
By default, the trainer and inference worker each allocate one transfer arena. Set `weight_broadcast.overlap_transfer_and_replay = true` to allocate two arenas on both sides and replay one weight group while receiving the next. The additional arena is the size of the largest transfer group per GPU; allocation errors are reported instead of silently disabling overlap.
### Custom Templates
For unusual partitions, module loads, or environment setup, supply your own Jinja2 template:
@@ -249,4 +277,4 @@ uv run sft @ sft.toml --data.type fake --max-steps 4
uv run trainer @ 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 `metrics.jsonl` to 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.
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.
+45 -26
View File
@@ -58,6 +58,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| Knob | What it does |
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.constant_trainer_batch_size` | Keep trainer batches constant when samples have no training signal, such as zero advantage on all tokens. Enabled by default. Disable it for faster collection with variable trainer batch sizes. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | Maximum staleness of a trained rollout (default 8): the version a batch trains on minus the oldest version that generated the rollout, queue time included. Episodes past the bound are dropped; a group shares one dispatch version, so its episodes age out together. The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `off_policy/*` and `mismatch_kl/all/mean` when tuning. |
| `[orchestrator.algo]` | Training algorithm — its `type` names it (`grpo` default, `max_rl`, `rae`, `hierarchical_grpo`, `opd`, `opsd`, `sft`, `echo`). See [Algorithms](#algorithms). |
@@ -77,11 +78,11 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
| Knob | What it does |
|---|---|
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). |
| `--output-dir outputs` | Directory that groups related runs. Each run writes its artifacts to its own run directory `<output_dir>/<run_name>` (`<run_dir>` below). Defaults to `$PRL_OUTPUT_DIR` if set, else `outputs`. |
| `--run.name <name>` | Run name, also the run directory name under `<output_dir>` (override the directory separately via `--run.dir`). Auto-generated as `<envs>--<model>--<short-id>` when unset, so every launch gets a fresh, readable run directory. Set an explicit name for a predictable path — required to resume the run later. |
| `--clean` | Wipe the run directory before starting. Useful when re-running a named run during iteration. |
| `--max-steps N` | Stop after `N` trainer steps. Overrides the config value. |
| `--dry-run` | Resolve + validate the full config, write per-process TOMLs to `<run_dir>/configs/`, and exit without launching. The fastest way to debug a misbehaving config. |
| `--dry-run` | Resolve + validate the full config, write per-process configs to `<run_dir>/configs/latest/resolved/`, and exit without launching. The fastest way to debug a misbehaving config. |
### Algorithms
@@ -125,7 +126,7 @@ Pulled from the console logs and mirrored to W&B.
- `mismatch_kl/{all,env}/{mean,std,max}` — KL between trainer's current policy and the (older) inference policy that generated the rollouts. A sustained, growing mean is the early-warning sign for off-policy collapse.
- `entropy/{all,env}/mean` — too low means mode-collapse; too high means the model isn't committing.
- `masked_advantage_{positive,negative}/mean` — fraction of DPPO-masked tokens, split by sign.
- `is_masked/mean` — fraction of tokens masked by the IPO trust region.
- `optim/grad_norm` — spikes precede divergence; check the loss config or lower the LR.
**Performance** (trainer + orchestrator step independently):
@@ -133,7 +134,9 @@ Pulled from the console logs and mirrored to W&B.
| Source | Metric | Reading |
|---|---|---|
| trainer | `time/wait_for_batch` | **high → orchestrator bottleneck** |
| orchestrator | `time/wait_for_ckpt` | **high → trainer bottleneck** |
| orchestrator | `time/wait_for_policy` | **high → trainer bottleneck** |
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window. This warning reports stale, errored, and no-signal counts.
## SFT Trainer
@@ -198,17 +201,17 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node (Decoupled Trainer and Inference Pool)
#### Multi-Node Trainer and Inference Pool
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two separate SLURM jobs**. `deployment.num_train_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evals process:
On a `multi_node` deployment, one SLURM job reserves `deployment.num_train_nodes + deployment.num_infer_nodes` nodes. The first `num_infer_nodes` run the inference pool, router, env servers, and evals process. The remaining nodes run the trainer. The inference pool runs one vLLM engine per DP rank behind one router, with `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evals)
num_train_nodes = 2 # trainer nodes
num_infer_nodes = 1 # inference pool + evals
[inference.vllm]
tensor_parallel_size = 8
@@ -217,7 +220,7 @@ tensor_parallel_size = 8
job_name = "my-run"
```
The launcher submits the eval job after the trainer allocation starts. The trainer publishes its rank-0 hostname in the shared run directory, and the eval job uses it to join the NCCL weight-broadcast group. Each weight transfer is synchronous, but eval rollout execution overlaps with later training steps. After the final transfer, the trainer job releases its nodes while the eval job finishes the final epoch and exits. Without `max_steps`, the eval job never sees a final broadcast and holds its allocation until walltime. Trainer and evals log to one shared W&B run — the trainer creates it, and the evals process finalizes it. Any trainer-to-inference node layout works because `num_train_nodes` and `num_infer_nodes` are independent.
The shared script passes the trainer rank-0 hostname directly to the evals process for NCCL weight broadcasts. Each transfer is synchronous, but eval rollout execution overlaps with later training steps. The allocation remains active while the final eval finishes. Without `max_steps`, evals never sees a final broadcast, so the job remains active until walltime. Trainer and evals log to one shared W&B run. The trainer creates it, and evals finalizes it.
### SFT-Specific Knobs
@@ -263,8 +266,8 @@ Checkpointing is split across processes because the orchestrator and trainer can
| Process | What's saved | Where |
|---|---|---|
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_N/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_N/orchestrator/` |
| Trainer | FSDP-sharded model (DCP), optimizer, scheduler, progress | `<run_dir>/checkpoints/step_{n}/trainer/` |
| Orchestrator | Progress, per-env data state | `<run_dir>/checkpoints/step_{n}/orchestrator/` |
| Inference | _nothing_ — re-pushed from the latest checkpoint on restart | n/a |
### Enabling Checkpoints
@@ -297,8 +300,29 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
--resume.dir outputs/my-run/checkpoints/step_10
```
### Exporting Checkpoints
Trainer checkpoints are DCP-sharded; export them to HF-format safetensors with `tools/convert_dcp_to_bf16.py`. The script reads the model config from the run's resolved config and writes sharded safetensors plus config/tokenizer assets to `<ckpt_dir>/weights` (or a second positional arg). It exports full fine-tunes only — LoRA checkpoints are rejected.
```bash
# single process (1 GPU)
uv run python tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
# multi-rank for faster gathers and models that don't fit one GPU
uv run torchrun --nproc-per-node 8 tools/convert_dcp_to_bf16.py outputs/my-run/checkpoints/step_10
```
The exported directory loads directly into `uv run inference --vllm.model <dir>` or any HF consumer. Quantize it to blockwise FP8 (DeepSeek/GLM format, loads natively in vLLM) with `tools/convert_bf16_to_fp8.py <dir>`, or go straight from the checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (each rank quantizes its gathered slice, writes only `<ckpt_dir>/weights-FP8` — no intermediate bf16 export); dequantize an fp8-only release (e.g. GLM-5-FP8) for training with `tools/convert_fp8_to_bf16.py <dir>`.
## Observability
### Config Files
Each launch writes its command, input TOML, and resolved JSON files to
`<run_dir>/configs/attempt_<n>/`. Resumed runs keep the earlier configs.
`command.txt` uses shell-safe quoting.
`configs/latest` points to the current attempt.
### Log Files
The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>/` — every launch (fresh or resumed) gets its own numbered attempt directory, and `logs/latest` symlinks to the current one. The full layout (single-node runs skip the `node_*.log` and `router.log` files — there the router logs into `inference.log`):
@@ -307,6 +331,7 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
<run_dir>/logs/latest/ # symlink -> attempt_<n>, one per launch
├── trainer.log # rank 0 only; symlink → trainer/node_0.log on multi-node
├── orchestrator.log # single instance, single file
├── evals.log # SFT online-eval process
├── inference.log # symlink → inference/node_0.log on multi-node
├── trainer/
│ ├── node_*.log # per-node trainer stdout (multi-node only)
@@ -317,31 +342,25 @@ The launcher tees every process's stdout/stderr into `<run_dir>/logs/attempt_<n>
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
```
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/latest/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
```bash
tail -F <run_dir>/logs/latest/{trainer,orchestrator,inference}.log
tail -F <run_dir>/logs/latest/{trainer,orchestrator,evals,inference}.log
tail -F <run_dir>/logs/latest/trainer/node_*.log # multi-node only
tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
```
### Console Output
### Dashboard
`scripts/tmux.sh` opens a 4-pane tmux session that follows `trainer.log`, `orchestrator.log`, `inference.log`, and the union of env worker logs. Start it before launching:
`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.
```bash
bash scripts/tmux.sh -o outputs/my-run
# then in the Launcher window:
uv run rl @ ... --run.name my-run
```
Pass `-s <session>` and `-o <run_dir>` (the run directory, `<output_dir>/<run_name>`) to run multiple parallel experiments side-by-side in different sessions. The helper also works on a SLURM head node — `bash scripts/tmux.sh my-rl-job /shared/outputs/my-rl-job`.
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.
### Weights & Biases
W&B is off by default (the file monitor, which writes `metrics.jsonl` and the per-step trace files to the run directory, is on by default):
W&B is off by default (the file monitor, which writes the metrics and the trace stream under the run's `monitors/file/` directory, is on by default):
```bash
uv run rl @ rl.toml --monitors.wandb # default project, random name
@@ -368,9 +387,9 @@ Or set it in TOML:
name = "my-experiment"
```
Every 10th step the orchestrator uploads the step's episodes (full conversations with rewards and advantages) to the run's sample viewer.
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.
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
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.
## Rules of Thumb
+2 -1
View File
@@ -9,9 +9,10 @@ End-to-end usage examples for prime-rl, referenced from the top-level [README](.
- `wiki-search` — multi-turn tool calling, LoRA
- `wordle` — multi-turn (~6-turn games)
- `hendrycks-sanity` — single-turn math, long-running
- `dynamo` — five-step Qwen3 math training with external Dynamo inference and NCCL weight updates
- **[`advanced/`](advanced)** — larger, mostly multi-node runs on frontier models, one folder
per model: `qwen3-30b-a3b` (math/swe/tool), `glm-4.5-air` (search/swe/terminal), `glm-5.2`
(large-scale + PD-disaggregated inference), `minimax-m2.5` (swe), `nemotron-3-super` (swe),
`intellect-3.1` (swe).
`intellect-3.1` (swe), `deepseek-v4-flash` (sft + a standalone vLLM serving pre-flight).
Dev-sized (2-GPU) counterparts of `basic/` live in [`configs/basic/`](../configs/basic).
@@ -0,0 +1,35 @@
# Standalone vLLM serving pre-flight: does this cluster's vLLM serve the real DeepSeek V4 Flash
# checkpoint at all, independent of the trainer? Uses vLLM's own native DeepSeek V4 support, not
# this repo's trainer port. Run directly on one allocated 8xH200 node (no [slurm] block):
#
# uv run inference @ examples/advanced/deepseek-v4-flash/inference.toml
#
# Then check /health and a /v1/chat/completions request from another shell on the same node, and
# confirm a coherent response before trusting the model for a real run.
#
# Reference: https://recipes.vllm.ai/deepseek-ai/DeepSeek-V4-Flash
# Mandatory for the fp8 checkpoint, not an optimization: without it the UE8M0-scaled fp8 weights
# route to a CUTLASS kernel that crashes on boot. That crash was observed during SM120 bring-up and
# has not been re-tested on Hopper, but the vLLM recipe sets the flag on every NVIDIA configuration.
# The mHC pre-norm GEMM does not need it on H200: measured there, the TileLang fallback matches the
# reference to 1.3e-06 relative at every token count, including the >= 1024 block-M kernel.
use_deep_gemm = true
[server]
port = 8000
[vllm]
model = "deepseek-ai/DeepSeek-V4-Flash-0731"
tensor_parallel_size = 8
enable_expert_parallel = true
gpu_memory_utilization = 0.85
max_model_len = 8192
# Required, not a tuning choice. Every DeepSeek V4 attention class sets
# `use_fp8_ds_mla_layout = True`, and the sparse-MLA layout then asserts
# "DeepseekV4 fp8_ds_mla layout only supports fp8 kv-cache" against the `auto` default. The vLLM
# recipe sets it on every vendor and every architecture.
kv_cache_dtype = "fp8"
# Recipe-derived rather than measured here: every NVIDIA configuration in the vLLM recipe pairs
# the fp8 KV cache with this block size.
block_size = 256
@@ -0,0 +1,62 @@
# Real-data SFT for deepseek-ai/DeepSeek-V4-Flash-0731 at full depth (all 43 layers, no
# `debug.num_layers` truncation) on 4 train nodes. Trainer only: no online eval, no inference
# node, and so no weight broadcast. Tested on 8xH200.
#
# uv run sft @ examples/advanced/deepseek-v4-flash/sft.toml --run.name ds-v4-sft-torch-4node
#
# Note: on 4 8xH200 nodes, this config is near the memory limit, using ~94%+ GPU memory.
#
# `dist_timeout_seconds = 14400` is needed on any run that has to build the HF -> prime-rl
# conversion cache, which takes far longer than the 3600s default.
#
# To buy memory back for quicker testing on fewer nodes, set `full_offload = true` under `[model]`,
# which keeps the fp32 masters, moments and gradients in CPU RAM and needs `optim_cpu_offload =
# false` and `optim.max_norm = "None"` set alongside it; the lighter `optim_cpu_offload = true` is
# already the default here.
#
# There is no `[ckpt]` block. The trainer saves unconditionally at the last step, and a 43-layer
# checkpoint (fp32 master weights plus two fp32 AdamW moments) is ~3 TiB. Add one with
# `ckpt.output_dir` pointed at a volume that can hold it if you need the trained weights.
dist_timeout_seconds = 14400
max_steps = 20
[model]
name = "deepseek-ai/DeepSeek-V4-Flash-0731"
impl = "custom"
ep = 8
# Torch all-to-all, not DeepEP. At full depth DeepEP dies on the first backward with
# "RuntimeError: Autograd not support dtype: Byte", raised from `Tensor.float()` in
# `DeepEPTokenDispatcher.combine` while the activation-checkpoint recompute replays through a
# `__torch_dispatch__` mode that hands back a uint8 tensor. Reproduced deterministically on 4
# nodes against the same weights and conversion cache this config trains on.
[model.moe.dispatch]
type = "torch"
[model.ac]
freq = 1
[model.ac_offloading]
max_inflight_activations = 5
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
seq_len = 2048
batch_size = 32
[optim]
lr = 1e-5
[monitors.wandb]
project = "deepseek-v4-flash"
name = "deepseek-v4-flash-sft"
# `num_infer_nodes` defaults to 0, so this allocates 4 nodes and runs only the trainer.
[deployment]
type = "multi_node"
num_train_nodes = 4
[slurm]
job_name = "ds-v4-sft"
partition = "all"
+3 -3
View File
@@ -100,7 +100,7 @@ name = "openseeker"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "openseeker"
@@ -124,7 +124,7 @@ name = "redsearcher"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
@@ -154,7 +154,7 @@ num_examples = 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"]
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-search"]
env.agent.timeout.rollout = 3600
env.taskset.id = "browsecomp"
+3 -3
View File
@@ -96,7 +96,7 @@ num_turns_weight = 0.1
[[orchestrator.train.source]]
name = "tmax"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.taskset.id = "tmax"
@@ -123,7 +123,7 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "swebench-verified"
@@ -144,7 +144,7 @@ env.taskset.id = "swebench-verified"
name = "terminal-bench-2"
group_size = 4 # avg@4
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "terminal-bench-2"
+3 -1
View File
@@ -84,7 +84,6 @@ partition = "all" # FILL IN: set to your cluster's partition
[trainer]
dist_timeout_seconds = 1800
enable_token_export = true
[trainer.model]
name = "zai-org/GLM-5.1"
@@ -97,6 +96,9 @@ ep = 8
[trainer.model.quantization]
type = "fp8"
[trainer.model.moe.compute]
type = "deepgemm_fp8"
[trainer.model.ac]
freq = 1
+2 -2
View File
@@ -89,7 +89,7 @@ truncate_history_thinking = false
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["nemotron-3-super-swe"]
[orchestrator.eval]
@@ -99,7 +99,7 @@ interval = 20
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.harness.compaction.summarize_at_tokens = 98304
env.agent.runtime.labels = ["nemotron-3-super-swe"]
env.agent.timeout.rollout = 3600
+8 -7
View File
@@ -12,9 +12,10 @@ The taskset is included through the Verifiers workspace. After syncing the repos
uv run python -c "import alphabet_sort"
```
Start the tmux session:
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
## Task
@@ -31,13 +32,13 @@ We use non-default settings to balance the difficulty: 3 fixed turns (instead of
Start the inference server:
```bash
# In the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507
```
Evaluate the base model:
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
@@ -91,7 +92,7 @@ We train with LoRA (rank 32, alpha 64) for 100 steps.
*Check out the logs on [W&B](https://wandb.ai/primeintellect/alphabet-sort-4b-lora/workspace?nw=nwuserandrewpi).*
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/alphabet-sort/rl.toml \
--run.name rl \
--monitors.wandb.project ... \
@@ -106,12 +107,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetS
Let's see how our final RL checkpoint performs on the eval set.
```bash
# In the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL
```
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run eval alphabet-sort --harness.id null \
-m PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL \
--client.base-url http://localhost:8000/v1 \
+73
View File
@@ -0,0 +1,73 @@
# Dynamo RL
This example runs five steps of GRPO training on the Hendrycks math environment with `Qwen/Qwen3-0.6B`, one trainer GPU, one external Dynamo inference worker, and NCCL weight transfer.
Prime-RL does not launch Dynamo from this configuration. Run the frontend, worker, and trainer as separate processes. This example requires two GPUs: GPU 0 for Prime-RL training and GPU 1 for Dynamo inference.
## Start Dynamo
Install Dynamo with its vLLM backend and activate its environment. Then start the RL-enabled frontend in the first terminal:
```bash
DYN_HTTP_HOST=127.0.0.1 DYN_ENABLE_RL=true DYN_RL_PORT=8001 python -m dynamo.frontend
```
Start the RL-enabled vLLM worker on GPU 1 in a second terminal:
```bash
CUDA_VISIBLE_DEVICES=1 DYN_SYSTEM_HOST=127.0.0.1 DYN_SYSTEM_PORT=8081 python -m dynamo.vllm \
--model Qwen/Qwen3-0.6B \
--enable-rl
```
The `--enable-rl` flag enables worker discovery and the administration routes used for NCCL weight updates. Keep GPU 0 out of `CUDA_VISIBLE_DEVICES` for this process so it remains available to the Prime-RL trainer.
These commands bind the HTTP, discovery, and worker administration endpoints to loopback. If Prime-RL and Dynamo run on different hosts, expose these endpoints only on a trusted control network; configured client headers are also sent to the discovery endpoint.
## Endpoint contract
The default configuration expects:
- The Dynamo OpenAI-compatible frontend at `http://127.0.0.1:8000/v1`.
- The Dynamo RL discovery endpoint at `http://127.0.0.1:8001/v1/rl/workers`.
- Exactly one discovered worker for `Qwen/Qwen3-0.6B` with an admin URL and `world_size = 1`.
- A vLLM worker with the Prime-RL NCCL weight-update extension enabled.
Verify both endpoints before starting training:
```bash
curl --fail http://127.0.0.1:8000/v1/models
curl --fail http://127.0.0.1:8001/v1/rl/workers
```
## Discovery URL
The example enables Dynamo with:
```toml
[orchestrator.model.client]
base_url = "http://127.0.0.1:8000/v1"
[orchestrator.model.client.dynamo]
enabled = true
```
When `discovery_url` is omitted, Prime-RL removes the path from `base_url` and increments its explicit non-default port by one. Here, `http://127.0.0.1:8000/v1` becomes `http://127.0.0.1:8001`.
If your Dynamo frontend and discovery service do not use adjacent ports, configure the discovery endpoint explicitly:
```toml
[orchestrator.model.client.dynamo]
enabled = true
discovery_url = "http://dynamo.example:9000"
```
## Run training
After both endpoint checks pass, run Prime-RL from the repository in a third terminal. With no managed `[inference]` section, Prime-RL assigns GPU 0 to its single trainer process and leaves the external Dynamo worker on GPU 1:
```bash
uv run rl @ examples/basic/dynamo/rl.toml
```
The example stops after five optimizer steps. Outputs are written under `outputs/` unless `output_dir` is overridden.
+40
View File
@@ -0,0 +1,40 @@
max_steps = 5
seq_len = 2048
[model]
name = "Qwen/Qwen3-0.6B"
[weight_broadcast]
type = "nccl"
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
[orchestrator]
batch_size = 32
group_size = 8
[orchestrator.train.sampling]
max_completion_tokens = 1024
[[orchestrator.train.source]]
name = "hendrycks-math"
env.taskset.id = "math-env"
env.taskset.dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
env.taskset.dataset_subset = "default"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
[orchestrator.model.client]
base_url = "http://127.0.0.1:8000/v1"
[orchestrator.model.client.dynamo]
enabled = true
[orchestrator.renderer]
name = "qwen3"
enable_thinking = false
+9 -9
View File
@@ -12,21 +12,21 @@ The `reverse-text` taskset is included through the Verifiers workspace. After sy
uv run python -c "import reverse_text"
```
First, let's start a `tmux` session which we will use throughout the experiment.
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
Let's check how well `Qwen3-0.6B` does out-of-the-box on the `reverse-text` environment.
```bash
# Run this in the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.model Qwen/Qwen3-0.6B
```
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m Qwen/Qwen3-0.6B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
@@ -41,7 +41,7 @@ We will fine-tune `PrimeIntellect/Qwen3-0.6B` ([HF](https://huggingface.co/Prime
To train on a single GPU, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run sft @ examples/basic/reverse-text/sft.toml \
--run.name sft \
--monitors.wandb.project ... \
@@ -51,7 +51,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml \
To train on multiple GPUs, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run torchrun \
--local-ranks-filter 0 \
--nproc-per-node ... \
@@ -71,7 +71,7 @@ For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of
*Check out the logs of the RL run on [W&B](https://wandb.ai/primeintellect/examples?nw=yxjwjc556do).*
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/reverse-text/rl.toml \
--model.name ... \
--run.name rl \
@@ -88,12 +88,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`
Let's see how our final RL checkpoints perform on the `reverse-text` environment.
```bash
# Run this in the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.model PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL
```
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run eval reverse-text --harness.id null -m PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
+13
View File
@@ -21,6 +21,19 @@ env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 5
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text-eval"
num_examples = 256
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+7 -7
View File
@@ -25,10 +25,10 @@ Set up the credentials for the configured reference judge:
export OPENAI_API_KEY=your_api_key_here
```
Start the tmux session:
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
## Task
@@ -69,14 +69,14 @@ Key configuration highlights:
Start the inference server:
```bash
# In the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model Qwen/Qwen3-4B-Instruct-2507 --vllm.tool-call-parser hermes
```
Evaluate the base model:
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m Qwen/Qwen3-4B-Instruct-2507 \
--client.base-url http://localhost:8000/v1 \
@@ -91,7 +91,7 @@ uv run eval wiki-search --harness.id null \
Train with the unified config file:
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/wiki-search/rl.toml \
--run.name rl \
--monitors.wandb.project your-project-name \
@@ -110,12 +110,12 @@ This will write DCP checkpoints in `outputs/rl/checkpoints/step_*`.
Evaluate your trained model:
```bash
# In the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.enable-lora --vllm.model <user>/Qwen3-4B-Instruct-WikiSearch-RL --vllm.tool-call-parser hermes
```
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run eval wiki-search --harness.id null \
-m <user>/Qwen3-4B-Instruct-WikiSearch-RL \
--client.base-url http://localhost:8000/v1 \
+9 -9
View File
@@ -12,23 +12,23 @@ The taskset is included through the Verifiers workspace. After syncing the repos
uv run python -c "import wordle"
```
Start the pre-layouted `tmux` session which we will use to run all experiments and view logs conveniently
We'll use two terminals: one for the inference server, one for everything else. To watch the run while it trains — metrics, resolved configs, rollout traces, and logs in one place — start the local dashboard and open http://localhost:7788:
```bash
bash scripts/tmux.sh
uv run dashboard
```
Before training, we want to get a baseline score and test how well `Qwen3-1.7B` does out-of-the-box in the `wordle` environment so that we quantify our training effect. To do so, first start a local inference server to serve `Qwen3-1.7B`.
```bash
# Run this in the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.model Qwen/Qwen3-1.7B
```
Then, use the `eval` entrypoint to evaluate the model in the `wordle` environment. We evaluate on the 20 evaluation examples which are distinct words not appearing in the training set of the environment. We constrain the response length to 1024 tokens as this should be more than enough to play a full game.
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run eval wordle --harness.id null -m Qwen/Qwen3-1.7B --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
@@ -43,7 +43,7 @@ We will fine-tune `PrimeIntellect/Qwen3-1.7B` ([HF](https://huggingface.co/Prime
To train on a single GPU, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run sft @ examples/basic/wordle/sft.toml \
--run.name sft \
--monitors.wandb.project ... \
@@ -53,7 +53,7 @@ uv run sft @ examples/basic/wordle/sft.toml \
To train on multiple GPUs, run
```bash
# In the `Trainer` pane
# Run this in the other terminal
uv run torchrun \
--local-ranks-filter 0 \
--nproc-per-node ... \
@@ -74,7 +74,7 @@ Finally, we will do multi-turn RL against the `wordle` environment using the mod
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run rl @ examples/basic/wordle/rl.toml \
--model.name ... \
--run.name rl \
@@ -91,12 +91,12 @@ We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](http
Let's see how our final RL checkpoint performs on the eval set.
```bash
# Run this in the `Inference` pane
# Run this in the inference terminal
uv run inference --vllm.model PrimeIntellect/Qwen3-1.7B-Wordle-RL
```
```bash
# Run this in the `Trainer` pane
# Run this in the other terminal
uv run eval wordle --harness.id null -m PrimeIntellect/Qwen3-1.7B-Wordle-RL --client.base-url http://localhost:8000/v1 -n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
-3
View File
@@ -23,11 +23,8 @@ rank = 32
alpha = 32
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", "experts"]
# MoE + mode="full" recomputes the router, whose non-deterministic top-k routing
# raises CheckpointError; selective AC excluding routed_experts avoids that.
[model.ac]
mode = "selective"
targets = ["norm", "attn_proj", "linear_attn"]
[data]
type = "sft"
+1 -1
View File
@@ -7,7 +7,7 @@ requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.3",
"renderers>=0.1.9",
"renderers>=0.1.11",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.3.0",
@@ -1,7 +1,8 @@
"""Algorithm abstraction: sampling and the per-token training signal.
An algorithm is a named, self-contained config — a discriminated union keyed
on ``type`` (``grpo``, ``max_rl``, ``opd``, ``opsd``, ``sft``, ``echo``).
on ``type`` (``grpo``, ``max_rl``, ``rae``, ``hierarchical_grpo``, ``opd``,
``opsd``, ``sft``, ``echo``, ``debug``).
The bundle *is* the algorithm: each variant carries
its sampling component and its credit-assignment / loss-routing parameters,
and its class defaults are the vetted setting — ``type = "opd"`` with a
@@ -364,6 +365,32 @@ class SFTAlgoConfig(BaseAlgoConfig):
return self
class DebugAlgoConfig(BaseAlgoConfig):
type: Literal["debug"] = "debug"
"""Debugging algorithm for infra work: every sampled token of every clean
trainable trace gets the same constant ``advantage`` (default 1.0),
ignoring rewards entirely. Every admitted rollout is trainable and every
action token carries gradient signal, so the full RL path (advantage
transport, importance ratios, trust region, optimizer, weight update)
can be exercised regardless of the reward function. Not a real training
signal — a policy pushed by it drifts monotonically."""
action_loss_type: ClassVar[ActionLossType] = "rl"
advantage: float = Field(1.0, allow_inf_nan=False)
"""The constant per-token advantage. Must be nonzero: a zero advantage
makes nothing trainable, the exact failure this debug tool exists to
rule out."""
@model_validator(mode="after")
def require_nonzero_advantage(self):
if self.advantage == 0.0:
raise ValueError(
"the 'debug' algorithm needs a nonzero advantage — a zero advantage leaves nothing trainable."
)
return self
AlgoConfig: TypeAlias = Annotated[
GRPOAlgoConfig
| EchoAlgoConfig
@@ -372,7 +399,8 @@ AlgoConfig: TypeAlias = Annotated[
| HierarchicalGRPOAlgoConfig
| OPDAlgoConfig
| OPSDAlgoConfig
| SFTAlgoConfig,
| SFTAlgoConfig
| DebugAlgoConfig,
Field(discriminator="type"),
]
"""The training algorithm: sampling plus the per-token training signal (credit
@@ -387,6 +415,8 @@ its class defaults are the vetted setting.
- ``opsd`` — SDFT: policy samples, demo-conditioned reverse KL against the live policy (the teacher is the policy itself).
- ``sft`` — a frozen model samples, the policy trains with CE on its tokens. Needs a frozen ``sampling.source``.
- ``echo`` — GRPO on action tokens + weighted CE on tool-response observation tokens.
- ``debug`` — the same constant advantage on every sampled token, ignoring
rewards. Debugging only: for infra work that needs every token trainable.
A new credit-assignment scheme is a new named algorithm in code (subclass
``Algorithm``, register it), not a config that points at an import path.
@@ -1,10 +1,10 @@
from pathlib import Path
import verifiers.v1 as vf
from pydantic import SerializeAsAny, model_validator
from pydantic import Field, SerializeAsAny, model_validator
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class EnvServerConfig(BaseConfig):
@@ -20,8 +20,8 @@ class EnvServerConfig(BaseConfig):
log: LogConfig = LogConfig()
output_dir: Path = Path("outputs")
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
@model_validator(mode="before")
@classmethod
@@ -4,9 +4,9 @@ from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.configs.shared import ClientConfig, LogConfig, ResumeConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class EvalsEvalConfig(EvalConfig):
@@ -27,6 +27,11 @@ class EvalsEvalConfig(EvalConfig):
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
cancel_on_new_checkpoint: bool = True
"""For online evals, cancel unfinished episodes when a newer trainer checkpoint is ready.
Disable to finish every triggered eval epoch before loading later weights. The trainer can
idle while it waits for slow evals."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
@@ -61,6 +66,13 @@ class OnlineConfig(BaseConfig):
this step."""
class CheckpointConfig(BaseConfig):
"""Checkpoint progress for an interruptible standalone eval run."""
interval: int = Field(1, ge=1)
"""Save after the task cursor advances by N completed groups."""
class EvalsConfig(BaseConfig):
"""``uv run evals``: run the configured evals against a live inference server.
Standalone (no ``[online]``), one epoch of every eval source runs against the
@@ -86,9 +98,15 @@ class EvalsConfig(BaseConfig):
"""Weight transport for online evals. The ``sft`` launcher fills this from its
resolved trainer transport. None uses filesystem reloads."""
output_dir: Path = Path("outputs")
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer for online evals."""
subdirectories. Shared with the trainer for online evals. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
ckpt: CheckpointConfig | None = None
"""Checkpoint standalone eval progress. Checkpoint steps are task cursor positions."""
resume: ResumeConfig | None = None
"""Resume a standalone eval run from a cursor checkpoint. A bare block loads the latest checkpoint."""
log: LogConfig = LogConfig()
@@ -112,3 +130,12 @@ class EvalsConfig(BaseConfig):
"would skip its only eval epoch. Remove it or add an [online] block."
)
return self
@model_validator(mode="after")
def validate_checkpointing_is_standalone_only(self):
if self.online is not None and (self.ckpt is not None or self.resume is not None):
raise ValueError(
"evals ckpt/resume only supports standalone evals - online evals are coordinated "
"with the trainer's live weight-broadcast lifecycle"
)
return self
@@ -7,7 +7,7 @@ from pydantic import ConfigDict, Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import EnvVars, LogConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource
from prime_rl.utils.config import default_output_dir, find_package_resource
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
# TODO: Set thinking/ solution budget
@@ -458,11 +458,14 @@ class InferenceConfig(BaseConfig):
use_pd_kv_transfer: bool = False
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""
enable_return_sampling_mask: bool = False
"""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."""
enable_fp32_router_logits: bool = True
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x) by setting ``out_dtype=float32`` on the gate: 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 as a monkey-patch over vLLM's DeepseekV2MoE, activated by setting ``additional_config["fp32_router_logits"] = True`` on the vLLM config."""
"""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)."""
# Launcher-only fields
@@ -471,8 +474,8 @@ class InferenceConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
output_dir: Path = Path("outputs")
"""Directory for SLURM logs and generated scripts."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory for SLURM logs and generated scripts. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
@@ -494,6 +497,20 @@ class InferenceConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_disaggregated_combined_replay(self):
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
if (
self.deployment.type == "disaggregated"
and self.enable_return_sampling_mask
and self.vllm.enable_return_routed_experts
):
raise ValueError(
"Combined router and sampling replay is not supported with disaggregated P/D: "
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
)
return self
@model_validator(mode="after")
def validate_router_deployment(self):
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
@@ -607,6 +624,21 @@ class InferenceConfig(BaseConfig):
if not hasattr(namespace, "logprobs_mode"):
namespace.logprobs_mode = "processed_logprobs"
# Always surface cached prompt tokens in `usage` — the router's
# cache-discount billing counters parse them off /inference/v1/generate.
if "enable_prompt_tokens_details" not in extra_fields:
namespace.enable_prompt_tokens_details = 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:
hf_overrides = getattr(namespace, "hf_overrides", None) or {}
hf_overrides.setdefault("moe_router_dtype", "float32")
namespace.hf_overrides = hf_overrides
if self.enable_return_sampling_mask:
namespace.return_sampling_mask = True
kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
@@ -616,8 +648,6 @@ class InferenceConfig(BaseConfig):
additional_config = getattr(namespace, "additional_config", None) or {}
if self.enable_fp32_lm_head:
additional_config["fp32_lm_head"] = True
if self.enable_fp32_router_logits:
additional_config["fp32_router_logits"] = True
if additional_config:
namespace.additional_config = additional_config
@@ -25,7 +25,22 @@ class WandbMonitorConfig(BaseConfig):
class FileMonitorConfig(BaseConfig):
path: Path = Path("metrics.jsonl")
"""Path of the JSONL file, relative to the component's ``output_dir`` (absolute paths win)."""
"""Path of the metrics JSONL file, relative to the file monitor's directory under the
component's ``output_dir`` (``monitors/file/``; absolute paths win)."""
chunk_bytes: int = 5 * 1024**3
"""Size at which a trace stream (the episodes, each producer's annotations) rolls to
a new numbered chunk file. A line never spans chunks."""
compress: bool = True
"""Seal full chunks with zstd once the stream rolls past them (the live chunk stays
plain text). Sealed chunks use seekable frames: a reader still lands on one line,
and ``zstd -dcf stream/* | jq`` reads a whole stream."""
float_decimals: int | None = 4
"""Decimals kept for per-token float streams (logprobs, entropies, advantages) in
trace and annotation records; ``None`` keeps every digit. Training reads the wire,
not the records, so this only trades record size against overlay precision."""
class PrimeMonitorConfig(BaseConfig):
@@ -1,3 +1,4 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
@@ -22,7 +23,7 @@ from prime_rl.configs.shared import (
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
class LoRAConfig(BaseConfig):
@@ -45,6 +46,16 @@ class TrainSamplingConfig(BaseConfig):
temperature: float = Field(1.0, ge=0, le=2.0)
"""Sampling temperature."""
top_p: float = Field(1.0, gt=0, le=1.0)
"""Nucleus (top-p) sampling for train rollouts. Values below 1.0 truncate the sampling
distribution; the ``rl`` entrypoint auto-enables sampling replay so trainer and
rollout distributions stay consistent — see docs/inference.md (Sampling Replay)."""
top_k: int | None = Field(None, ge=1)
"""Top-k sampling for train rollouts. Truncation triggers sampling replay, and
a default top-k is injected when only top-p truncates so sampling masks stay
bounded — see docs/inference.md (Sampling Replay)."""
max_completion_tokens: int | None = None
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
@@ -53,18 +64,46 @@ class TrainSamplingConfig(BaseConfig):
extra_body: dict[str, Any] = {}
"""Extra body forwarded with each request to the inference server."""
def truncates_distribution(self) -> bool:
return self.top_p < 1.0 or self.top_k is not None
@model_validator(mode="after")
def validate_no_extra_body_truncation(self):
"""Truncating values must come from the typed fields — the replay policy reads
them. Disabled values pass so resolved configs (where ``resolve_env_config``
stamped the ``top_k = -1`` / ``min_p = 0.0`` sentinels) re-validate cleanly."""
smuggled = [
key
for key, truncates in (
("top_p", self.extra_body.get("top_p", 1.0) < 1.0),
("top_k", self.extra_body.get("top_k") not in (None, -1, 0)),
("min_p", self.extra_body.get("min_p", 0.0) > 0.0),
)
if truncates
]
if smuggled:
raise ValueError(
f"extra_body carries truncating {smuggled}; set them as fields on the train "
"sampling config instead (they drive sampling replay)."
)
return self
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict, omitting None values."""
args: dict[str, Any] = {
"temperature": self.temperature,
"top_p": 1.0,
"top_p": self.top_p,
"logprobs": True,
}
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
if self.extra_body:
args["extra_body"] = dict(self.extra_body)
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if extra_body:
args["extra_body"] = extra_body
return args
@@ -265,9 +304,6 @@ class TrainConfig(BaseConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
filter_zero_advantages: bool = True
"""Remove zero-advantage RL tokens after collecting a batch, before shipping it."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
@@ -408,6 +444,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
@@ -439,6 +478,15 @@ class ConcurrencyConfig(BaseConfig):
return self
# Top-k injected on truncated policy sampling that has none, and the hard upper
# bound for explicit top-k. vLLM's native sampling-mask capture requires a
# per-request top_k > 0 to bound mask sizes, and the trainer pads each micro
# batch's masks to the largest sampling mask, so the bound also caps trainer
# mask tensors. Large enough that a 0.95-0.99 nucleus rarely reaches it (the
# sampling policy is essentially unchanged).
TRAIN_TOP_K_BOUND = 512
class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
@@ -491,8 +539,8 @@ class OrchestratorConfig(BaseConfig):
rollout_transport: TransportConfig = ZMQTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Shared with the trainer; should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Global rate limit on task dispatch, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. None disables rate limiting."""
@@ -503,6 +551,9 @@ class OrchestratorConfig(BaseConfig):
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
constant_trainer_batch_size: bool = True
"""Require each batch to reach its effective sample target."""
token_batch_size: int | None = Field(None, ge=1)
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
@@ -565,6 +616,55 @@ class OrchestratorConfig(BaseConfig):
env_cfg.algo.validate_env(env_cfg.env)
return self
@model_validator(mode="after")
def setup_truncated_sampling(self):
"""Truncated policy sampling trains with sampling replay (rollout
logprobs are renormalized — see docs/inference.md, Sampling Replay).
Owned here: every truncating config gets a top-k bound (bounds the sampling
masks); opd/opsd is rejected (full-vocab prefill refs would mix
normalizations). Frozen-source envs sample externally and are exempt."""
policy_samplings = [
env.sampling for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
] or ([self.train.sampling] if not self.train.source else [])
truncating = [sampling for sampling in policy_samplings if sampling.truncates_distribution()]
if not truncating:
return self
if any(sampling.temperature == 0 for sampling in truncating):
raise ValueError(
"Truncated train sampling (top_p/top_k) requires temperature > 0: greedy sampling has "
"no truncated distribution to replay, and the inference server rejects such requests "
"while sampling-mask capture is on."
)
oversized = [sampling.top_k for sampling in truncating if (sampling.top_k or 0) > TRAIN_TOP_K_BOUND]
if oversized:
raise ValueError(
f"Truncated train sampling with top_k = {max(oversized)} exceeds the sampling-replay "
f"bound ({TRAIN_TOP_K_BOUND}): the trainer pads each micro batch's masks to the largest "
f"sampling mask, so unbounded masks blow up trainer memory. Use top_k <= {TRAIN_TOP_K_BOUND}."
)
unbounded = [sampling for sampling in truncating if sampling.top_k is None]
if unbounded:
warnings.warn(
f"Truncated train sampling: defaulting top_k = {TRAIN_TOP_K_BOUND} so every sampling mask is "
"bounded and sampling replay stays exact. Set top_k explicitly to override.",
stacklevel=2,
)
for sampling in unbounded:
sampling.top_k = TRAIN_TOP_K_BOUND
algos = [env.algo for env in self.train.source if env.algo is not None] or [self.algo]
if any(algo.type in ("opd", "opsd") for algo in algos):
raise ValueError(
"opd/opsd is not supported with truncated train sampling: reference logprobs are full-vocab "
"prefill scores while trainer logprobs are renormalized over the sampling mask, biasing the "
"ref_kl term. Remove the truncation (top_p/top_k) or the opd/opsd algo."
)
return self
@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
@@ -643,6 +743,23 @@ class OrchestratorConfig(BaseConfig):
env.sampling.extra_body.setdefault("return_token_ids", True)
return self
@model_validator(mode="after")
def validate_policy_top_k_consistency(self):
"""Require one top-k capture mode across the live policy server."""
policy_sources = [
env for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
]
enabled = [env for env in policy_sources if env.sampling.top_k is not None]
disabled = [env for env in policy_sources if env.sampling.top_k is None]
if enabled and disabled:
names = ", ".join(env.resolved_name for env in disabled)
raise ValueError(
"Live-policy train sources cannot mix top_k > 0 and top_k = -1 because "
"sampling-mask capture is engine-wide. Set top_k > 0 for these sources: "
f"{names}."
)
return self
@property
def env_sources(self) -> list[tuple[str, EnvConfig]]:
"""Every ``(split, source)`` this run pulls from, train first then eval — the
@@ -41,7 +41,7 @@ from prime_rl.configs.trainer import (
TokenizerConfig,
TrainerConfig,
)
from prime_rl.utils.config import BaseConfig, find_package_resource
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
from prime_rl.utils.validation import (
propagate_shared_fields,
validate_shared_ckpt_config,
@@ -100,7 +100,7 @@ class SharedMonitorsConfig(BaseConfig):
"""Shared W&B config. Propagated to trainer and orchestrator."""
file: FileMonitorConfig | None = None
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator."""
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/monitors/file/metrics.jsonl`` on both trainer and orchestrator."""
prime: PrimeMonitorConfig | None = None
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
@@ -158,6 +158,9 @@ class SharedNIXLWeightBroadcastConfig(SharedInMemoryWeightBroadcastConfig):
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two transfer arenas so inference can replay one weight group while receiving the next."""
class SharedFileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
@@ -243,8 +246,8 @@ class RLConfig(BaseConfig):
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
output_dir: Path = Path("outputs")
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory that groups related runs. Each run writes its artifacts to ``output_dir / run.name``. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
clean: bool = False
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
@@ -299,6 +302,10 @@ class RLConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. If None, runs locally."""
dashboard: bool = True
"""Make sure a local dashboard daemon serves this run's output dir (started on
demand in interactive sessions; an already-running daemon's URL is logged)."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
@@ -467,9 +474,6 @@ class RLConfig(BaseConfig):
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
"have no disk artifact to load from."
)
# The final version v{max_steps} is broadcast iff something consumes it:
# training never samples from it, but a configured final eval measures it.
broadcast_final = self.orchestrator.eval is not None
if self.weight_broadcast.type in ("nccl", "nixl"):
inference_world_size = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
@@ -481,7 +485,6 @@ class RLConfig(BaseConfig):
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
broadcast_final=broadcast_final,
)
if self.weight_broadcast.type == "nccl":
transport_config = dict(
@@ -490,17 +493,20 @@ class RLConfig(BaseConfig):
trainer_config_type = TrainerNCCLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNCCLWeightBroadcastConfig
else:
transport_config = dict(session_id=self.weight_broadcast.session_id)
transport_config = dict(
session_id=self.weight_broadcast.session_id,
overlap_transfer_and_replay=self.weight_broadcast.overlap_transfer_and_replay,
)
trainer_config_type = TrainerNIXLWeightBroadcastConfig
orchestrator_config_type = OrchestratorNIXLWeightBroadcastConfig
self.trainer.weight_broadcast = trainer_config_type(**common_config, **transport_config)
self.orchestrator.weight_broadcast = orchestrator_config_type(**common_config, **transport_config)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout, broadcast_final=broadcast_final
timeout=self.weight_broadcast.timeout
)
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig(
timeout=self.weight_broadcast.timeout, broadcast_final=broadcast_final
timeout=self.weight_broadcast.timeout
)
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
@@ -634,6 +640,53 @@ class RLConfig(BaseConfig):
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
return self
@model_validator(mode="after")
def auto_setup_sampling_mask_capture(self):
"""Truncated train sampling needs the inference server to return the sampling
masks the trainer replays (OrchestratorConfig guarantees truncating
configs are bounded by TRAIN_TOP_K_BOUND). Capture is engine-wide: while it is
on, vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0``,
so eval sampling against the same server must set both."""
policy_samplings = [
env.sampling
for env in self.orchestrator.train.source
if env.algo is not None and env.algo.sampling.source == "policy"
] or ([self.orchestrator.train.sampling] if not self.orchestrator.train.source else [])
if not any(sampling.truncates_distribution() for sampling in policy_samplings):
return self
if self.inference is None:
warnings.warn(
"Truncated train sampling with no managed inference server: set "
"`enable_return_sampling_mask = true` on the standalone server's config so it "
"returns the sampling masks the trainer replays.",
stacklevel=2,
)
return self
self.inference.enable_return_sampling_mask = True
if self.orchestrator.eval is not None:
warnings.warn(
"Sampling-mask capture is engine-wide: eval requests without top_k > 0 (from the "
"eval sampling config or the model's generation config) or with temperature 0 are "
"rejected by the inference server while truncated train sampling is on.",
stacklevel=2,
)
return self
@model_validator(mode="after")
def validate_disaggregated_combined_replay(self):
inference = self.inference
if (
inference is not None
and inference.deployment.type == "disaggregated"
and inference.enable_return_sampling_mask
and inference.vllm.enable_return_routed_experts
):
raise ValueError(
"Combined router and sampling replay is not supported with disaggregated P/D: "
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
)
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
@@ -33,7 +33,7 @@ from prime_rl.configs.trainer import (
WeightBroadcastConfig,
validate_scheduler,
)
from prime_rl.utils.config import BaseConfig, find_package_resource
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
class BaseDataConfig(BaseConfig):
@@ -175,9 +175,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Training nodes."""
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
from the trainer job. The eval job can outlive the trainer job while it evaluates
the final weight broadcast."""
"""Inference nodes for online evals (alias: ``num_eval_nodes``). These nodes share
one SLURM allocation with the trainer nodes."""
nodes_per_fsdp_group: int | None = None
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
@@ -233,8 +232,8 @@ class SFTConfig(BaseConfig):
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
output_dir: Path = Path("outputs")
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory that groups related runs. Each run writes its artifacts (checkpoints, logs, ...) to ``output_dir / run.name``. Should be a persistent directory with enough disk space. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
clean: bool = False
"""Delete the run directory (``output_dir / run.name``) before starting training. Required to overwrite a run directory that contains artifacts from a previous run when not resuming."""
@@ -285,6 +284,10 @@ class SFTConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
dashboard: bool = True
"""Make sure a local dashboard daemon serves this run's output dir (started on
demand in interactive sessions; an already-running daemon's URL is logged)."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
@@ -321,7 +324,7 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
warnings.warn(
"Gradient clipping is not compatible with DeepEP. "
"Automatically setting optim.max_norm to None (disabled).",
@@ -390,18 +393,18 @@ class SFTConfig(BaseConfig):
raise ValueError("eval.retrigger_on_resume requires weight_broadcast.type = 'filesystem'.")
if self.deployment.type == "multi_node":
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
# inference pool (one engine per DP rank behind a router) plus the evals process.
# Dedicated nodes in the SFT allocation run the inference pool, router,
# env servers, and evals process.
if self.inference is None:
raise ValueError(
"Multi-node online evals require an [inference] block - the launcher submits "
"a dedicated SLURM job running the inference pool and the evals process."
"Multi-node online evals require an [inference] block - dedicated nodes in the "
"SFT allocation run the inference pool and evals process."
)
if self.deployment.num_infer_nodes < 1:
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
if self.inference.router is None:
raise ValueError(
"Multi-node online evals require an inference router - the eval job starts one "
"Multi-node online evals require an inference router - the launcher starts one "
"router in front of the per-rank engines. Remove inference.router = 'None'."
)
if self.inference.vllm.model != self.model.name:
@@ -422,10 +425,10 @@ class SFTConfig(BaseConfig):
if self.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evals process never sees a final checkpoint, "
"so the eval SLURM job holds its allocation until its walltime.",
"so the SFT SLURM job holds its allocation until its walltime.",
stacklevel=2,
)
# The client is wired at runtime by the eval sbatch script (the router and
# The client is wired at runtime by the SFT sbatch script (the router and
# per-rank admin URLs are only known once SLURM assigns hosts).
return self
@@ -42,12 +42,6 @@ class BaseWeightBroadcastConfig(BaseConfig):
"""Timeout in seconds for the broadcast handshake and transfer. The trainer
fails the run when no consumer acknowledges an offered version in time."""
broadcast_final: bool = True
"""Internal - stamped by the RL/SFT launcher, never set by users: whether the
trainer broadcasts the final version v{max_steps}. True iff something consumes
it (a configured final eval) - training itself never samples from the final
version."""
class RunConfig(BaseConfig):
name: str | None = None
@@ -112,6 +106,9 @@ class SlurmConfig(BaseConfig):
pre_run_command: str | None = None
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
launch_modelexpress: bool = True
"""Start a job-scoped ModelExpress service for NIXL weight transfer."""
cleanup_grace_period: int = Field(3600, ge=0)
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
@@ -165,6 +162,14 @@ class BaseModelConfig(BaseConfig):
"""VLM configuration. Setting this enables vision-language model support."""
class DynamoConfig(BaseConfig):
enabled: bool = True
"""Enable Dynamo worker discovery for the inference admin plane."""
discovery_url: str | None = Field(default=None, min_length=1, max_length=2048)
"""Dynamo frontend URL used to discover inference workers for RL control."""
class ClientConfig(BaseConfig):
wait_for_ready_timeout: int = 1800
"""Seconds to wait at startup for the inference pool to become ready."""
@@ -187,6 +192,9 @@ class ClientConfig(BaseConfig):
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in multi-replica or disaggregated P/D deployments where the router must not handle admin traffic."""
dynamo: DynamoConfig | None = None
"""Dynamo RL worker-discovery configuration."""
class LogConfig(BaseConfig):
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
@@ -1,8 +1,9 @@
import re
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import BeforeValidator, Field, model_validator
from pydantic import BeforeValidator, Field, field_validator, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -16,12 +17,11 @@ from prime_rl.configs.shared import (
TransportConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, default_output_dir
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
class GCConfig(BaseConfig):
@@ -31,20 +31,13 @@ class GCConfig(BaseConfig):
class ActivationCheckpointConfig(BaseConfig):
mode: Literal["full", "selective"] = "full"
"""``full`` checkpoints whole transformer blocks; ``selective`` checkpoints only the subcomponents listed in ``targets`` inside supported custom decoder layers."""
"""Both modes checkpoint whole transformer blocks. ``selective`` additionally retains selected operations."""
freq: int = Field(1, ge=1)
"""Apply activation checkpointing to every N layers."""
targets: list[str] = ["norm"]
"""Selective checkpoint targets. ``norm`` checkpoints every norm module inside selected layers. ``attn_proj`` checkpoints projection-side attention work outside the kernel (input/output projections, attention-local norms, RoPE, gating, model-specific MLA projection helpers). ``mlp`` checkpoints the entire dense MLP forward (not for MoE). ``mla_up_proj`` checkpoints MLA Q/KV up-projection where supported. ``routed_experts`` checkpoints routed expert compute in MoE layers (including LatentMoE). ``linear_attn`` checkpoints non-softmax token mixers (NemotronH Mamba, Qwen3.5-MoE GatedDeltaNet, AFMoE sliding-window attention)."""
@model_validator(mode="after")
def validate_selective_targets(self):
self.targets = list(dict.fromkeys(self.targets))
if self.mode == "selective" and not self.targets:
raise ValueError("Selective activation checkpointing requires at least one target.")
return self
targets: list[str] | None = None
"""Operator names or namespaces retained in selective mode. ``None`` uses the default targets; an explicit list replaces them."""
class ActivationOffloadingConfig(BaseConfig):
@@ -93,6 +86,17 @@ class CompileConfig(BaseConfig):
"""Compile transformer blocks with ``fullgraph=True``."""
class FusionsConfig(BaseConfig):
enabled: list[Literal["gate_up", "qkv"]] = ["gate_up", "qkv"]
"""Runtime parameter fusions. ``gate_up`` runs each MoE expert's gate and up projections as one grouped GEMM; ``qkv`` runs attention's q, k and v projections as one GEMM. Only modules that support a fusion are packed, checkpoints keep the canonical parameter names and shapes, and fusions are skipped when LoRA is enabled. Set to ``[]`` to disable."""
raise_on_fail: bool = False
"""Fail at startup when no module supports a requested fusion, instead of logging a warning and continuing without it."""
shard_fused_on_dim1: bool = False
"""Experimental. Shard fused 2-D weights along dim 1 under FSDP so that weight loading and checkpointing are zero-copy: the checkpoint reads and writes the fused weights and their optimizer state in place, instead of assembling a full copy of every fused weight on each rank first. Requires the hidden size to be divisible by the FSDP shard mesh size."""
class IndexCacheConfig(BaseConfig):
topk_freq: int = Field(1, ge=1)
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
@@ -123,7 +127,7 @@ class LoRAConfig(BaseConfig):
"fc1_latent_proj",
"fc2_latent_proj",
]
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches NonGatedGroupedExperts inside LatentMoE; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent up/down projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches the ReLU² grouped experts; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
modules_to_save: list[str] = []
"""Module names or regex patterns to keep fully trainable (not freeze). Same matching rules as ``target_modules``."""
@@ -151,7 +155,7 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
# in BF16 on the trainer while inference quantized it to FP8, causing
# hidden-state drift before the MoE router.
r"mlp\.gate\.",
"shared_expert_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
r"shared_expert\.output_gate", # Qwen3.5 MoE: nn.Linear(hidden, 1, bias=False)
"eh_proj",
"weights_proj",
"in_proj_a",
@@ -161,21 +165,107 @@ _DEFAULT_FP8_IGNORE_PATTERNS: list[str] = [
class FP8Config(BaseConfig):
type: Literal["fp8"] = "fp8"
enable_grouped_gemm: bool = True
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
"""Dense linear module names excluded from DeepGEMM FP8 replacement."""
class MXFP8Config(BaseConfig):
type: Literal["mxfp8"] = "mxfp8"
recipe: MXFP8Recipe = "mxfp8_rceil"
enable_grouped_gemm: bool = True
enable_a2a: bool = True
"""MXFP8 recipe for dense linear modules."""
ignore_patterns: list[str] = _DEFAULT_FP8_IGNORE_PATTERNS
"""Dense linear module names excluded from torchao MXFP8 replacement."""
QuantizationConfig: TypeAlias = Annotated[FP8Config | MXFP8Config, Field(discriminator="type")]
class MoEComputeConfigBase(BaseConfig):
apply_to: str | list[Annotated[int, Field(ge=0, strict=True)]] = "all"
"""Model layers to use this backend for: ``"all"``, a percentage such as ``"85%"``,
or zero-based layer indices such as ``[0, 1, 2]``. Percentages select the first fraction
of model layers, rounded down. Other expert groups use BF16 compute and transport.
"""
@field_validator("apply_to")
@classmethod
def validate_apply_to(cls, value: str | list[int]) -> str | list[int]:
if isinstance(value, str) and value != "all":
if re.fullmatch(r"\d+(?:\.\d+)?%", value) is None or float(value[:-1]) > 100:
raise ValueError('apply_to must be "all", a percentage from "0%" to "100%", or a list of layer indices')
return value
def resolve_layers(self, num_layers: int) -> set[int]:
if isinstance(self.apply_to, list):
invalid = [index for index in self.apply_to if index >= num_layers]
if invalid:
raise ValueError(
f"apply_to layer indices {invalid} are out of range for a model with {num_layers} layers"
)
return set(self.apply_to)
count = num_layers if self.apply_to == "all" else int(num_layers * float(self.apply_to[:-1]) / 100)
return set(range(count))
class BF16MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs in bfloat16."""
type: Literal["bf16"] = "bf16"
class DeepGemmFP8MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs with DeepGEMM FP8 kernels."""
type: Literal["deepgemm_fp8"] = "deepgemm_fp8"
class MXFP8MoEComputeConfig(MoEComputeConfigBase):
"""Run routed-expert grouped GEMMs with Prime's vendored MXFP8 implementation."""
type: Literal["mxfp8"] = "mxfp8"
recipe: MXFP8Recipe = "mxfp8_rceil"
"""MXFP8 expert-compute recipe."""
MoEComputeConfig: TypeAlias = Annotated[
BF16MoEComputeConfig | DeepGemmFP8MoEComputeConfig | MXFP8MoEComputeConfig,
Field(discriminator="type"),
]
class TorchMoEDispatchConfig(BaseConfig):
"""Dispatch and combine routed tokens with torch all-to-all collectives."""
type: Literal["torch"] = "torch"
transport: Literal["bf16", "mxfp8"] = "bf16"
"""Wire format for routed activations and their reverse-path gradients."""
class DeepEPMoEDispatchConfig(BaseConfig):
"""Dispatch and combine routed tokens with DeepEP."""
type: Literal["deepep"] = "deepep"
num_sms: int = Field(20, ge=1)
"""SMs allocated to DeepEP communication kernels."""
token_chunk_size: int | None = Field(None, ge=1)
"""Optional chunk size used to pipeline dispatch with local expert compute."""
MoEDispatchConfig: TypeAlias = Annotated[
TorchMoEDispatchConfig | DeepEPMoEDispatchConfig,
Field(discriminator="type"),
]
class MoERuntimeConfig(BaseConfig):
"""Independent routed-expert compute and token-dispatch choices."""
compute: MoEComputeConfig = BF16MoEComputeConfig()
dispatch: MoEDispatchConfig = TorchMoEDispatchConfig()
class ModelConfig(BaseModelConfig):
conversion_dir: Path | None = None
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
@@ -189,6 +279,9 @@ class ModelConfig(BaseModelConfig):
compile: CompileConfig | None = CompileConfig()
"""Compile the model with ``torch.compile``."""
fusions: FusionsConfig = FusionsConfig()
"""Runtime parameter fusions, on by default."""
ac: ActivationCheckpointConfig | None = ActivationCheckpointConfig()
"""Activation checkpointing configuration. If None, activation checkpointing is disabled."""
@@ -213,14 +306,8 @@ class ModelConfig(BaseModelConfig):
ep: int | Literal["auto"] = "auto"
"""Expert parallelism degree for MoE layers. 1 disables EP. ``auto`` resolves to ``min(fsdp_island_size, 8)`` for MoE models (where ``fsdp_island_size = world_size // dp_replicate``), and to 1 for non-MoE models. Set an explicit integer to override."""
ep_comm_backend: EPCommBackend = "torch"
"""Communication backend for expert parallelism. ``torch`` uses TorchTitan all-to-all collectives; ``deepep`` uses DeepEP custom kernels."""
deepep_num_sms: int = Field(20, ge=1)
"""SMs allocated for DeepEP intranode dispatch/combine kernels. Also determines internode RDMA channel count (``num_channels = num_sms / 2``). Lower values leave more SMs for compute; higher values speed up dispatch/combine. The optimal value depends on EP degree and hardware. Only used when ``ep_comm_backend='deepep'``."""
deepep_token_chunk_size: int | None = Field(None, ge=1)
"""Token chunk size for DeepEP MoE pipelining. When set, DeepEP dispatch for chunk i+1 is launched while experts compute chunk i. Only used when ``ep_comm_backend='deepep'``."""
moe: MoERuntimeConfig = MoERuntimeConfig()
"""Routed-expert compute and token-dispatch runtime."""
cp: int = 1
"""Context parallelism degree. 1 disables CP."""
@@ -240,12 +327,6 @@ class ModelConfig(BaseModelConfig):
moe_router_dtype: Literal["bfloat16", "float32"] = "float32"
"""Compute dtype for MoE router gates. ``float32`` (default) keeps router gate weights in fp32 through forward and backward (exempt from FSDP bf16 parameter casting) and computes the gate GEMM and routing logits in fp32, matching models trained with fp32 routing (e.g. GLM-5.x via Megatron's ``--moe-router-dtype fp32``). ``bfloat16`` computes the gate GEMM in the model compute dtype. Router score functions (sigmoid/softmax) run in fp32 regardless. Only affects the custom MoE implementation; a no-op for non-MoE and HF-impl models."""
moe_use_grouped_mm: bool = True
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
moe_fused_kernel: bool = False
"""Run MoE routed experts through the vendored fused MoE CUDA kernel (``prime_kernels.flash_moe``) in forward; backward recomputes the reference grouped-mm path. Picks the mxfp8 kernel when ``quantization`` is MXFP8 with ``enable_grouped_gemm`` (which additionally needs ``hidden_size`` divisible by 256), otherwise the bf16 one. Requires the ``prime-kernels`` wheel, Blackwell (SM100) GPUs, ``ep=1``, ``model.impl='custom'``, MoE layers with output-weighted scores (``score_before_experts=False``), and ``moe_intermediate_size`` divisible by 128."""
quantization: QuantizationConfig | None = None
index_cache: IndexCacheConfig | None = None
@@ -301,12 +382,6 @@ class ModelConfig(BaseModelConfig):
self.ac = ActivationCheckpointConfig()
return self
@model_validator(mode="after")
def selective_ac_only_with_custom_impl(self):
if self.ac is not None and self.ac.mode == "selective" and self.impl not in ("custom", "auto"):
raise ValueError("Selective activation checkpointing requires model.impl='custom' or 'auto'")
return self
@model_validator(mode="after")
def cpu_offload_mutual_exclusion(self):
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
@@ -332,19 +407,18 @@ class ModelConfig(BaseModelConfig):
return self
@model_validator(mode="after")
def validate_ep_comm_backend(self):
if self.ep_comm_backend == "torch":
def validate_moe_runtime(self):
if self.ep == 1:
return self
if isinstance(self.ep, int) and self.ep <= 1:
raise ValueError(f"model.ep_comm_backend='{self.ep_comm_backend}' requires model.ep > 1.")
return self
@model_validator(mode="after")
def mxfp8_only_with_torch_ep_backend(self):
if isinstance(self.quantization, MXFP8Config) and self.ep_comm_backend != "torch":
raise ValueError("MXFP8 quantization requires model.ep_comm_backend='torch'.")
compute = self.moe.compute
dispatch = self.moe.dispatch
if isinstance(dispatch, DeepEPMoEDispatchConfig):
if isinstance(compute, MXFP8MoEComputeConfig):
raise ValueError("MXFP8 expert compute does not support DeepEP dispatch.")
elif dispatch.transport == "mxfp8":
if not isinstance(compute, MXFP8MoEComputeConfig):
raise ValueError("MXFP8 transport requires model.moe.compute.type='mxfp8'.")
return self
@@ -492,26 +566,10 @@ class CheckpointConfig(BaseConfig):
"""Skip loading the optimizer state from checkpoint."""
class DefaultLossConfig(BaseConfig):
type: Literal["default"] = "default"
dppo_mask_low: float = Field(0.2, ge=0)
"""Lower DPPO masking threshold."""
dppo_mask_high: float = Field(0.2, ge=0)
"""Upper DPPO masking threshold."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
kl_tau: float = Field(1e-3, ge=0)
"""Temperature for the KL term."""
class IPOLossConfig(BaseConfig):
type: Literal["ipo"] = "ipo"
ipo_threshold: float = Field(0.1, ge=0)
"""Upper DPPO masking threshold."""
eps: float = Field(0.1, ge=0)
"""Maximum absolute probability change before a token is masked."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
@@ -530,7 +588,7 @@ class CustomLossConfig(BaseConfig):
"""Kwargs forwarded to the loss function."""
LossConfig: TypeAlias = Annotated[DefaultLossConfig | IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
LossConfig: TypeAlias = Annotated[IPOLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
@@ -581,6 +639,9 @@ class NIXLWeightBroadcastConfig(InMemoryWeightBroadcastConfig):
session_id: str = "default"
"""ModelExpress session ID."""
overlap_transfer_and_replay: bool = False
"""Allocate two staging arenas so inference can replay one weight group while receiving the next."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig | NIXLWeightBroadcastConfig,
@@ -595,7 +656,7 @@ class TrainerConfig(BaseConfig):
data: DataLoaderConfig = DataLoaderConfig()
loss: LossConfig = DefaultLossConfig()
loss: LossConfig = IPOLossConfig()
"""Loss config for the rl loss component (see ``setup_rl_loss_fn``). The ce / ref_kl components are fixed and do not read this."""
optim: OptimizerConfig = AdamWConfig()
@@ -619,8 +680,8 @@ class TrainerConfig(BaseConfig):
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
output_dir: Path = Field(default_factory=default_output_dir)
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node. Defaults to ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
matmul_precision: Literal["highest", "high", "medium"] = "high"
"""Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``."""
@@ -649,15 +710,12 @@ class TrainerConfig(BaseConfig):
metrics_server: MetricsServerConfig | None = None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
enable_token_export: bool = False
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
env_vars: EnvVars = {}
"""Extra environment variables for the trainer process(es). Merged on top of the launcher defaults."""
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
if self.model.ep != 1 and self.model.moe.dispatch.type == "deepep" and self.optim.max_norm is not None:
warnings.warn(
"Gradient clipping is not compatible with DeepEP. "
"Automatically setting optim.max_norm to None (disabled).",
@@ -1,3 +1,4 @@
import os
from pathlib import Path
from typing import Any
@@ -6,6 +7,11 @@ from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
def default_output_dir() -> Path:
"""Default output directory: ``$PRL_OUTPUT_DIR`` if set, else ``outputs``."""
return Path(os.environ.get("PRL_OUTPUT_DIR", "outputs"))
def dump_resolved_config(config: BaseModel, exclude: set[str] | None = None) -> dict:
"""Dump a resolved config for a machine-written JSON artifact.
@@ -5,6 +5,7 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
(re.compile(r"^deepseek-ai/DeepSeek-V4"), "deepseek_v4"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
@@ -25,6 +26,9 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
# V4 reasons inside <think> blocks, but vLLM only splits them out into `reasoning_content`
# when this parser is set; the checkpoint ships no chat template, so nothing else supplies it.
(re.compile(r"^deepseek-ai/DeepSeek-V4"), "deepseek_v4"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
(re.compile(r"^zai-org/GLM-"), "glm45"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
+110 -60
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.8.0"
version = "0.9.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -13,38 +13,27 @@ dependencies = [
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"numpy>=2.2.6",
"torch>=2.9.0",
"torchvision",
"torchaudio",
"torchdata>=0.11.0",
"transformers==5.6.2",
"vllm>=0.26.0",
"mooncake-transfer-engine>=0.3.10.post2",
"wandb>=0.26.1",
"wandb-workspaces>=0.4.3",
"ring-flash-attn>=0.1.8",
"prime>=0.6.19",
"prime-runs[train]>=0.1.1",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
"openai>=1.106.1",
"orjson>=3.11.0",
"psutil>=7.0.0",
"pyzstd>=0.16.2",
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.3.1.dev59",
"renderers",
"dion",
"tilelang>=0.1.8",
"flash-linear-attention",
"nvidia-ml-py>=12.575.51",
"verifiers[harbor]>=0.3.1",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
"msgspec>=0.18",
"torchao>=0.17.0",
"modelexpress==0.3.0",
]
[project.scripts]
@@ -55,43 +44,65 @@ trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evals = "prime_rl.entrypoints.evals:main"
env-server = "prime_rl.entrypoints.env_server:main"
dashboard = "prime_rl.entrypoints.dashboard:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
[project.optional-dependencies]
# Both wheels are the same flash-attn 2.8.3 / cu128 / torch 2.11 / cp312 build and carry
gpu = [
"torch>=2.13.0 ; sys_platform == 'linux'",
"torchvision ; sys_platform == 'linux'",
"torchaudio ; sys_platform == 'linux'",
"torchdata>=0.11.0 ; sys_platform == 'linux'",
"vllm>=0.28.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'",
"dion ; sys_platform == 'linux'",
"tilelang>=0.1.8 ; sys_platform == 'linux'",
"flash-linear-attention ; sys_platform == 'linux'",
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
"nvidia-ml-py>=12.575.51 ; sys_platform == 'linux'",
"torchao>=0.18.0 ; sys_platform == 'linux'",
"modelexpress==0.3.0 ; sys_platform == 'linux'",
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
]
dashboard = [
"fastapi>=0.115",
"uvicorn>=0.30",
]
dynamo = ["ai-dynamo==1.4.2 ; sys_platform == 'linux'"]
# Both wheels are the same flash-attn 2.8.3 / cu130 / torch 2.13 / cp312 build and carry
# sm_80 / sm_90 / sm_100 / sm_120 cubins. `attn="auto"` picks FA4 on sm_100 and FA3 on
# sm_90, so FA2 is the resolved backend on sm_120 (see `_resolve_attn_impl` in
# trainer/model.py).
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.22/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.48/flash_attn-2.8.3+cu130torch2.13-cp312-cp312-linux_aarch64.whl ; platform_machine == 'aarch64'",
]
flash-attn-3 = ["flash_attn_3"]
flash-attn-3 = ["flash_attn_3 ; sys_platform == 'linux'"]
flash-attn-cute = [
"flash-attn-4",
"flash-attn-4 ; sys_platform == 'linux'",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64' or platform_machine == 'aarch64'",
"deep-gemm",
"nixl",
"nixl-cu12 ; platform_machine == 'x86_64'",
"vllm-router",
]
gpt-oss = [
"kernels",
"deep-ep ; sys_platform == 'linux'",
"deep-gemm ; sys_platform == 'linux'",
"nixl ; sys_platform == 'linux'",
"nixl-cu13==0.10.1 ; sys_platform == 'linux'",
"vllm-router ; sys_platform == 'linux'",
]
quack = [
"quack-kernels>=0.4.1",
"quack-kernels>=0.4.1 ; sys_platform == 'linux'",
]
# Prebuilt `prime-kernels` wheels from a release (see the `kernels` skill). Compiled for
# sm_100a; on other GPUs the package installs fine and reports its kernels unavailable.
kernels = [
"prime-kernels",
"prime-kernels ; sys_platform == 'linux'",
]
all = [
"prime-rl[gpu]",
"prime-rl[flash-attn]",
"prime-rl[disagg]",
"prime-rl[quack]",
@@ -101,12 +112,13 @@ all = [
[dependency-groups]
mamba-ssm = [
"mamba-ssm>=2.3.0",
"mamba-ssm>=2.3.0 ; sys_platform == 'linux'",
]
dev = [
"ipykernel>=6.29.5",
"ipywidgets>=8.1.7",
"pre-commit>=4.2.0",
"playwright>=1.49",
"pytest>=8.4.1",
"pytest-asyncio>=0.23",
"ruff>=0.12.1",
@@ -123,14 +135,21 @@ no-build-isolation-package = ["flash-attn"]
environments = [
"sys_platform == 'linux' and platform_machine == 'x86_64'",
"sys_platform == 'linux' and platform_machine == 'aarch64'",
"sys_platform == 'darwin' and platform_machine == 'arm64'",
]
# Override torch's pinned cuDNN to fix Conv3d performance regression (torch 2.9 + cuDNN 9.8-9.14)
# Override torch's pinned cuDNN to fix the Conv3d performance regression.
# See: https://github.com/pytorch/pytorch/issues/166122
override-dependencies = [
"nvidia-cudnn-cu12>=9.15",
"nvidia-cutlass-dsl>=4.4.1",
# Keep vLLM's TileLang version; Nemotron uses Mamba-2's Triton kernels.
"tilelang==0.1.12",
# 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.
# Keep this pin aligned with quack-kernels and the flash-attn-4 revision below.
"nvidia-cutlass-dsl==4.6.2",
"transformers==5.6.2",
"torch>=2.9.0",
"torch>=2.13.0",
"openenv-core",
]
@@ -167,13 +186,39 @@ version = "0.3.0"
requires-dist = [
"grpcio>=1.66.2",
"huggingface_hub>=0.20.0",
"nixl[cu12]",
"nixl",
"numpy>=1.24.0",
"protobuf>=5.27.0,<7.0.0",
"pydantic>=2.0.0",
"torch>=2.6.0",
]
# Mirror the upstream Pydantic compatibility correction until the next release.
[[tool.uv.dependency-metadata]]
name = "ai-dynamo-runtime"
version = "1.4.2"
requires-dist = [
"pydantic>=2.10.6,<=2.13.5",
"uvloop>=0.21.0",
]
# NIXL publishes its CUDA 12 package as a base dependency even when the
# caller requests its CUDA 13 extra. Use the requested CUDA 13 package only.
[[tool.uv.dependency-metadata]]
name = "nixl"
version = "0.10.1"
requires-dist = ["nixl-cu13==0.10.1"]
# CUTLASS DSL has the same CUDA 12 default. vLLM requests its CUDA 13 extra,
# so resolve that variant without installing both runtime packages.
[[tool.uv.dependency-metadata]]
name = "nvidia-cutlass-dsl"
version = "4.6.2"
requires-dist = [
"nvidia-cutlass-dsl-libs-base==4.6.2",
"nvidia-cutlass-dsl-libs-cu13==4.6.2",
]
[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
@@ -188,6 +233,8 @@ flash_attn_3 = false
# appear in `uv tree` need to be listed; the resolver ignores entries for
# packages it never sees.
prime = false
prime-runs = false
prime-traces = false
prime-sandboxes = false
prime-tunnel = false
prime-evals = false
@@ -199,7 +246,7 @@ vllm-router = false
dion = false
deep-ep = false
deep-gemm = false
nixl-cu12 = false
nixl-cu13 = false
torchao = false
prime-kernels = false
@@ -210,53 +257,56 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torch = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
torchvision = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
torchaudio = [{ index = "pytorch-cu130", marker = "sys_platform == 'linux'" }]
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.6.0/torchao-0.17.0+git02105d46c-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
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" }
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'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ 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'" },
]
deep-ep = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.1.0+1fd57b0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ 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'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-gemm = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/v0.1.1/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
flash_attn_3 = { index = "pytorch-cu128-test" }
mamba-ssm = { git = "https://github.com/state-spaces/mamba", rev = "f577286" }
flash_attn_3 = { index = "pytorch-cu130-test" }
[tool.uv.extra-build-dependencies]
flash-attn = [{ requirement = "torch", match-runtime = true }]
flash-attn-3 = [{ requirement = "torch", match-runtime = true }]
mamba-ssm = [{ requirement = "torch", match-runtime = true }]
mamba-ssm = ["torch>=2.13.0"]
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/cu128"
name = "pytorch-cu130"
url = "https://download.pytorch.org/whl/cu130"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128-test"
url = "https://download.pytorch.org/whl/test/cu128"
name = "pytorch-cu130-test"
url = "https://download.pytorch.org/whl/test/cu130"
explicit = true
[tool.ruff.lint]
+4 -10
View File
@@ -53,16 +53,10 @@ if [ -n "$PRIME_RL_REF" ]; then
cp -a /app/.venv "$DEST/.venv"
fi
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
# Mirror the image's uv sync extras — explicit instead
# of --all-extras so we don't pull in `disagg` / `quack` and trigger
# heavy source builds (deep-ep, deep-gemm, quack-kernels) at pod
# startup. --inexact keeps the seeded venv's pre-built wheels
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra gpt-oss \
--group mamba-ssm )
# --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"
cd "$DEST"
-94
View File
@@ -1,94 +0,0 @@
"""Export a verifiers v1 eval run (traces.jsonl) as an SFT dataset for `uv run sft`.
Reads a finished run's saved traces and reshapes them into the dataset shape the SFT trainer
consumes directly (see `prime_rl.trainer.sft.data`): a `messages` column (OpenAI chat wire
shape) plus a `tools` column (the tools the model was shown, from `Trace.tools`,
JSON-encoded — heterogeneous JSON-schema dicts don't fit a fixed Arrow schema). One row per
branch: a linear rollout contributes one sample, a compacted/subagent rollout one per branch
(one training sample is built per branch).
Selection: generation-errored traces (`stop_condition == "error"`) always drop — a broken
transcript is not a sample. A scoring-only error keeps the generation outcome as its stop
condition and a complete conversation, so it stays; its reward may be partial/zero, which
`--min-reward` handles.
Usage (from the prime-rl repo):
uv run python scripts/export_sft.py <run-dir> [--min-reward 1.0] [--drop-truncated]
[-o OUT_DIR] [--push HF_REPO_ID]
Writes `<run-dir>/sft/train.parquet` by default — point the trainer at it with
`--data.name <run-dir>/sft`. Requires a verifiers release carrying `Trace.tools`
(PrimeIntellect-ai/verifiers#1963).
"""
import argparse
import json
from pathlib import Path
from datasets import Dataset
from verifiers.v1 import Trace, WireTrace
from verifiers.v1.dialects.chat import message_to_wire
def sft_rows(trace: Trace) -> list[dict]:
"""A trace's SFT rows — one per branch: the branch's conversation as OpenAI chat wire
dicts plus the trace's advertised tools, JSON-encoded."""
tools = json.dumps([t.model_dump(mode="json", exclude_none=True) for t in trace.tools or []])
return [
{
"messages": [message_to_wire(m) for m in branch.messages],
"tools": tools,
}
for branch in trace.branches
if branch.messages
]
def keep(trace: Trace, min_reward: float | None, drop_truncated: bool) -> bool:
"""Whether a trace is worth training on (see module docstring for the error semantics)."""
if trace.stop_condition == "error":
return False
if drop_truncated and trace.is_truncated:
return False
return min_reward is None or trace.reward >= min_reward
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("run_dir", type=Path, help="the eval run dir (holds traces.jsonl)")
parser.add_argument("--min-reward", type=float, default=None, help="keep traces with reward >= this")
parser.add_argument("--drop-truncated", action="store_true", help="drop budget-cut traces")
parser.add_argument("-o", "--output-dir", type=Path, default=None, help="default: <run-dir>/sft")
parser.add_argument("--push", default=None, help="HF repo id to push to instead of writing parquet")
args = parser.parse_args()
traces_path = args.run_dir / "traces.jsonl"
if not traces_path.exists():
raise SystemExit(f"no traces.jsonl in {args.run_dir}")
total, rows = 0, []
with traces_path.open(encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
total += 1
trace = WireTrace.model_validate(json.loads(line))
if keep(trace, args.min_reward, args.drop_truncated):
rows.extend(sft_rows(trace))
print(f"export-sft: {total} trace(s) -> {len(rows)} row(s)")
if not rows:
raise SystemExit("export-sft: no rows to export after selection")
dataset = Dataset.from_list(rows)
if args.push:
dataset.push_to_hub(args.push)
print(f"export-sft: pushed to {args.push}")
return
out = args.output_dir or args.run_dir / "sft"
out.mkdir(parents=True, exist_ok=True)
dataset.to_parquet(str(out / "train.parquet"))
print(f"export-sft: wrote {out / 'train.parquet'} -> train with --data.name {out}")
if __name__ == "__main__":
main()
-90
View File
@@ -1,90 +0,0 @@
#!/usr/bin/env bash
# Build and install DeepGEMM from source for FP8 MoE inference + FP8 training.
#
# Pinned to d30fc36 — the commit our FP8 grouped-GEMM training path requires
# (newer than the 477618c that vLLM 0.17/0.19 used). The matching prebuilt
# wheel lives at tools/wheels/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl
# and is what `pyproject.toml` consumes by default; this script is for
# rebuilding when torch / CUDA / vllm bumps invalidate that wheel.
#
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
#
# Usage:
# bash scripts/install_deep_gemm.sh # build + install in-place
# bash scripts/install_deep_gemm.sh --wheel-dir tools/wheels # build wheel only
#
# Options:
# --ref REF DeepGEMM commit hash (default: d30fc36)
# --wheel-dir DIR Output wheel to DIR instead of installing
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
DEEPGEMM_GIT_REF="d30fc36c8f229f4f873b90a492f6e19e6e610923"
WHEEL_DIR=""
while [[ $# -gt 0 ]]; do
case $1 in
--ref) DEEPGEMM_GIT_REF="$2"; shift 2 ;;
--wheel-dir) WHEEL_DIR="$2"; shift 2 ;;
*) echo "Unknown argument: $1" >&2; exit 1 ;;
esac
done
# Skip if already installed at the right version
INSTALLED_VER=$(python -c "import deep_gemm; print(deep_gemm.__version__)" 2>/dev/null || echo "")
SHORT_REF="${DEEPGEMM_GIT_REF:0:7}"
if [[ "$INSTALLED_VER" == *"$SHORT_REF"* ]]; then
echo "DeepGEMM ${INSTALLED_VER} already installed, skipping."
exit 0
fi
# Auto-detect CUDA version
CUDA_VERSION=$(nvcc --version 2>/dev/null | grep -oP 'release \K[\d.]+' || echo "")
if [ -z "$CUDA_VERSION" ]; then
echo "ERROR: nvcc not found. CUDA toolkit required." >&2
exit 1
fi
CUDA_MAJOR="${CUDA_VERSION%%.*}"
CUDA_MINOR="${CUDA_VERSION#*.}"
CUDA_MINOR="${CUDA_MINOR%%.*}"
if [ "$CUDA_MAJOR" -lt 12 ] || { [ "$CUDA_MAJOR" -eq 12 ] && [ "$CUDA_MINOR" -lt 8 ]; }; then
echo "Skipping DeepGEMM (requires CUDA 12.8+, got ${CUDA_VERSION})"
exit 0
fi
echo "================================================================"
echo " Building DeepGEMM (${SHORT_REF})"
echo " CUDA: ${CUDA_VERSION}"
echo "================================================================"
TMPDIR=$(mktemp -d)
cleanup() { rm -rf "$TMPDIR"; }
trap cleanup EXIT
git clone --recurse-submodules "$DEEPGEMM_GIT_REPO" "$TMPDIR/DeepGEMM" 2>&1
cd "$TMPDIR/DeepGEMM"
git checkout "$DEEPGEMM_GIT_REF"
git submodule update --init --recursive
cd "$REPO_ROOT"
if [ -n "$WHEEL_DIR" ]; then
mkdir -p "$WHEEL_DIR"
uv build --no-build-isolation --wheel --out-dir "$WHEEL_DIR" "$TMPDIR/DeepGEMM"
echo ""
echo "Wheel built:"
ls -lh "$WHEEL_DIR"/deep_gemm*.whl
else
uv pip install --no-build-isolation --reinstall "$TMPDIR/DeepGEMM"
echo ""
echo "Installed: $(python -c 'import deep_gemm; print(deep_gemm.__version__)')"
fi
echo "================================================================"
echo " DeepGEMM build complete"
echo "================================================================"
-170
View File
@@ -1,170 +0,0 @@
#!/usr/bin/env bash
# Install DeepEP kernels for expert-parallel disaggregated inference.
#
# Builds NVSHMEM + DeepEP from source and installs into the project venv.
# Required for disaggregated prefill/decode deployments with expert parallelism.
#
# Auto-detects the CUDA toolkit version that matches the installed PyTorch
# and looks for it at /usr/local/cuda-X.Y. Fails if not found.
#
# Prerequisites:
# - Matching CUDA toolkit installed (e.g. `sudo apt install cuda-toolkit-12-8`)
# - For multi-node: IBGDA driver configured (see --configure-drivers)
#
# Usage:
# bash scripts/install_ep_kernels.sh
#
# Options:
# --workspace DIR Build directory (default: ./ep_kernels_workspace)
# --deepep-ref REF DeepEP commit hash (default: 73b6ea4)
# --nvshmem-ver VER NVSHMEM version (default: 3.3.24)
# --configure-drivers Also configure IBGDA drivers (requires sudo, needs reboot)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
DEEPEP_COMMIT_HASH="73b6ea4"
NVSHMEM_VER="3.3.24"
WORKSPACE="$REPO_ROOT/ep_kernels_workspace"
CONFIGURE_DRIVERS=0
while [[ $# -gt 0 ]]; do
case $1 in
--workspace) WORKSPACE="$2"; shift 2 ;;
--deepep-ref) DEEPEP_COMMIT_HASH="$2"; shift 2 ;;
--nvshmem-ver) NVSHMEM_VER="$2"; shift 2 ;;
--configure-drivers) CONFIGURE_DRIVERS=1; shift ;;
*) echo "Unknown argument: $1" >&2; exit 1 ;;
esac
done
# Skip if DeepEP is already installed
if python -c "import deep_ep" 2>/dev/null; then
echo "DeepEP already installed, skipping."
exit 0
fi
# ── Auto-detect CUDA toolkit matching torch ───────────────────────────────────
TORCH_CUDA_VER=$(python -c "import torch; print(torch.version.cuda)")
CUDA_MAJOR_MINOR=$(echo "$TORCH_CUDA_VER" | grep -oP '^\d+\.\d+')
CUDA_MAJOR=$(echo "$CUDA_MAJOR_MINOR" | cut -d. -f1)
CUDA_HOME="/usr/local/cuda-${CUDA_MAJOR_MINOR}"
if [ ! -x "$CUDA_HOME/bin/nvcc" ]; then
echo "ERROR: Could not find CUDA toolkit matching torch (cuda ${TORCH_CUDA_VER}) at ${CUDA_HOME}" >&2
echo "Install it with: sudo apt install cuda-toolkit-${CUDA_MAJOR_MINOR//./-}" >&2
exit 1
fi
export CUDA_HOME
# Verify versions actually match
NVCC_VER=$("$CUDA_HOME/bin/nvcc" --version | grep -oP 'release \K[\d.]+')
echo "Torch CUDA: ${TORCH_CUDA_VER}, nvcc: ${NVCC_VER} (${CUDA_HOME})"
# ── Auto-detect GPU architecture ──────────────────────────────────────────────
GPU_NAME=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader,nounits -i 0 2>/dev/null)
case "$GPU_NAME" in
*H100*|*H200*|*H800*) TORCH_CUDA_ARCH_LIST="9.0" ;;
*B100*|*B200*|*GB200*) TORCH_CUDA_ARCH_LIST="10.0" ;;
*)
echo "Could not auto-detect GPU arch from '$GPU_NAME'. Set TORCH_CUDA_ARCH_LIST manually." >&2
echo " Hopper (H100/H200): TORCH_CUDA_ARCH_LIST=9.0" >&2
echo " Blackwell (B200): TORCH_CUDA_ARCH_LIST=10.0" >&2
exit 1
;;
esac
export TORCH_CUDA_ARCH_LIST
echo "================================================================"
echo " Installing DeepEP kernels"
echo " CUDA: ${CUDA_HOME} (${NVCC_VER})"
echo " GPU: ${GPU_NAME} (arch ${TORCH_CUDA_ARCH_LIST})"
echo " DeepEP: ${DEEPEP_COMMIT_HASH}"
echo " NVSHMEM: ${NVSHMEM_VER}"
echo " Workspace: ${WORKSPACE}"
echo "================================================================"
mkdir -p "$WORKSPACE"
# ── Step 1: Install build deps ────────────────────────────────────────────────
echo ""
echo "--- Installing build dependencies ---"
cd "$REPO_ROOT"
uv pip install cmake ninja
# ── Step 2: Download and extract NVSHMEM ──────────────────────────────────────
echo ""
echo "--- Setting up NVSHMEM ${NVSHMEM_VER} ---"
ARCH=$(uname -m)
case "${ARCH,,}" in
x86_64|amd64) NVSHMEM_SUBDIR="linux-x86_64" ;;
aarch64|arm64) NVSHMEM_SUBDIR="linux-sbsa" ;;
*) echo "Unsupported architecture: ${ARCH}" >&2; exit 1 ;;
esac
NVSHMEM_DIR="$WORKSPACE/nvshmem"
if [ ! -d "$NVSHMEM_DIR/lib" ]; then
NVSHMEM_FILE="libnvshmem-${NVSHMEM_SUBDIR}-${NVSHMEM_VER}_cuda${CUDA_MAJOR}-archive.tar.xz"
NVSHMEM_URL="https://developer.download.nvidia.com/compute/nvshmem/redist/libnvshmem/${NVSHMEM_SUBDIR}/${NVSHMEM_FILE}"
echo "Downloading ${NVSHMEM_URL}"
curl -fSL "${NVSHMEM_URL}" -o "$WORKSPACE/${NVSHMEM_FILE}"
tar -xf "$WORKSPACE/${NVSHMEM_FILE}" -C "$WORKSPACE"
mv "$WORKSPACE/${NVSHMEM_FILE%.tar.xz}" "$NVSHMEM_DIR"
rm -f "$WORKSPACE/${NVSHMEM_FILE}"
rm -rf "$NVSHMEM_DIR/lib/bin" "$NVSHMEM_DIR/lib/share"
echo "NVSHMEM extracted to ${NVSHMEM_DIR}"
else
echo "NVSHMEM already present at ${NVSHMEM_DIR}, skipping download"
fi
export CMAKE_PREFIX_PATH="${NVSHMEM_DIR}/lib/cmake:${CMAKE_PREFIX_PATH:-}"
export NVSHMEM_DIR
# ── Step 3: Build and install DeepEP ──────────────────────────────────────────
echo ""
echo "--- Building DeepEP (${DEEPEP_COMMIT_HASH}) ---"
DEEPEP_DIR="$WORKSPACE/DeepEP"
if [ ! -d "$DEEPEP_DIR/.git" ]; then
git clone https://github.com/deepseek-ai/DeepEP "$DEEPEP_DIR"
fi
cd "$DEEPEP_DIR"
git fetch origin
git checkout "$DEEPEP_COMMIT_HASH"
WHEEL_DIR="$REPO_ROOT/deps"
mkdir -p "$WHEEL_DIR"
python setup.py bdist_wheel --dist-dir "$WHEEL_DIR"
WHEEL=$(ls "$WHEEL_DIR"/deep_ep*.whl | head -1)
echo ""
echo "--- DeepEP wheel built at: $WHEEL ---"
# ── Step 4 (optional): Configure IBGDA drivers ───────────────────────────────
if [ "$CONFIGURE_DRIVERS" -eq 1 ]; then
echo ""
echo "--- Configuring IBGDA drivers (requires sudo) ---"
echo 'options nvidia NVreg_EnableStreamMemOPs=1 NVreg_RegistryDwords="PeerMappingOverride=1;"' | sudo tee -a /etc/modprobe.d/nvidia.conf
if command -v update-initramfs &> /dev/null; then
sudo update-initramfs -u
elif command -v dracut &> /dev/null; then
sudo dracut --force
else
echo "No supported initramfs update tool found." >&2
exit 1
fi
echo ""
echo "IBGDA configured. Please REBOOT the system to apply changes."
fi
echo ""
echo "================================================================"
echo " DeepEP installation complete"
echo " NVSHMEM: ${NVSHMEM_DIR}"
echo " To verify: uv run python -c 'import deep_ep; print(deep_ep.__file__)'"
echo "================================================================"
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Build the ModelExpress metadata server and Redis backend used by SLURM RL jobs.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
MODELEXPRESS_REPOSITORY="https://github.com/ai-dynamo/modelexpress.git"
MODELEXPRESS_REF="v0.3.0"
REDIS_VERSION="7.4.2"
REDIS_SHA256="4ddebbf09061cbb589011786febdb34f29767dd7f89dbe712d2b68e808af6a1f"
if [[ $# -gt 0 ]]; then
echo "This installer does not accept arguments" >&2
exit 1
fi
BIN_DIR="$PROJECT_DIR/third_party/modelexpress/bin"
mkdir -p "$BIN_DIR"
if [[ -x "$BIN_DIR/modelexpress-server" ]] \
&& "$BIN_DIR/modelexpress-server" --version 2>/dev/null | grep -q "${MODELEXPRESS_REF#v}"; then
echo "modelexpress-server $MODELEXPRESS_REF already installed at $BIN_DIR"
else
command -v cargo >/dev/null || {
echo "cargo not found; install Rust 1.90 or newer before running this script" >&2
exit 1
}
command -v protoc >/dev/null || {
echo "protoc not found; install Protocol Buffers before running this script" >&2
exit 1
}
BUILD_DIR=$(mktemp -d)
trap 'rm -rf "$BUILD_DIR"' EXIT
git clone --depth 1 --branch "$MODELEXPRESS_REF" "$MODELEXPRESS_REPOSITORY" "$BUILD_DIR/modelexpress"
(
cd "$BUILD_DIR/modelexpress"
cargo build --release --bin modelexpress-server
)
cp "$BUILD_DIR/modelexpress/target/release/modelexpress-server" "$BIN_DIR/"
fi
if [[ -x "$BIN_DIR/redis-server" ]] \
&& "$BIN_DIR/redis-server" --version | grep -q "v=$REDIS_VERSION"; then
echo "redis-server $REDIS_VERSION already installed at $BIN_DIR"
else
BUILD_DIR="${BUILD_DIR:-$(mktemp -d)}"
trap 'rm -rf "$BUILD_DIR"' EXIT
REDIS_ARCHIVE="$BUILD_DIR/redis-${REDIS_VERSION}.tar.gz"
curl --fail --location --silent --show-error \
--output "$REDIS_ARCHIVE" \
"https://download.redis.io/releases/redis-${REDIS_VERSION}.tar.gz"
echo "$REDIS_SHA256 $REDIS_ARCHIVE" | sha256sum --check
tar -xzf "$REDIS_ARCHIVE" -C "$BUILD_DIR"
make -C "$BUILD_DIR/redis-${REDIS_VERSION}" -j redis-server MALLOC=libc
cp "$BUILD_DIR/redis-${REDIS_VERSION}/src/redis-server" "$BIN_DIR/"
fi
echo "Installed ModelExpress server dependencies in $BIN_DIR"
+2 -3
View File
@@ -47,6 +47,8 @@ def _qwen3_5_moe_vlm_config():
tc.num_attention_heads = 4
tc.num_key_value_heads = 2
tc.head_dim = 64
# mrope_section must sum to rotary_dim // 2 for the shrunken head_dim
tc.rope_parameters["mrope_section"] = [3, 3, 2]
tc.moe_intermediate_size = 128
tc.shared_expert_intermediate_size = 128
tc.num_experts = 4
@@ -96,7 +98,6 @@ ARCH_PRESETS = {
first_k_dense_replace=1,
norm_topk_prob=True,
use_qk_norm=False,
use_grouped_mm=False,
pad_token_id=151329,
eos_token_id=[151329, 151336, 151338],
),
@@ -125,7 +126,6 @@ ARCH_PRESETS = {
use_routing_bias=True,
use_qk_norm=True,
qk_norm_type="per_layer",
use_grouped_mm=False,
auto_map={"AutoModelForCausalLM": "MiniMaxAI/MiniMax-M2.1--modeling_minimax_m2.MiniMaxM2ForCausalLM"},
),
"hf_model_class": None, # uses AutoModelForCausalLM with trust_remote_code
@@ -171,7 +171,6 @@ ARCH_PRESETS = {
num_experts_per_tok=4,
mlp_layer_types=["dense"] + ["sparse"] * 11,
moe_routed_scaling_factor=2.5,
use_grouped_mm=False,
pad_token_id=9,
bos_token_id=2,
eos_token_id=[2, 24],
-148
View File
@@ -1,148 +0,0 @@
#!/bin/bash
SESSION_NAME="prime-rl"
OUTPUT_DIR="outputs"
AGENT="claude"
# Optional CLI parsing
# Supports:
# -s|--session-name NAME
# -o|--output-dir DIR
# -a|--agent AGENT (claude|codex, default: claude)
# Positional: [SESSION_NAME [OUTPUT_DIR]]
POSITIONAL=()
while [[ $# -gt 0 ]]; do
case "$1" in
-s|--session-name)
if [[ -z "$2" ]]; then
echo "Error: --session-name requires a value" >&2
exit 1
fi
SESSION_NAME="$2"
shift 2
;;
-o|--output-dir)
if [[ -z "$2" ]]; then
echo "Error: --output-dir requires a value" >&2
exit 1
fi
OUTPUT_DIR="$2"
shift 2
;;
-a|--agent)
if [[ -z "$2" ]]; then
echo "Error: --agent requires a value (claude|codex)" >&2
exit 1
fi
AGENT="$2"
shift 2
;;
-h|--help)
echo "Usage: $0 [-s SESSION_NAME] [-o OUTPUT_DIR] [-a AGENT] [SESSION_NAME [OUTPUT_DIR]]" >&2
echo " -a, --agent claude|codex (default: claude)" >&2
exit 0
;;
--)
shift
break
;;
*)
POSITIONAL+=("$1")
shift
;;
esac
done
if [[ ${#POSITIONAL[@]} -ge 1 ]]; then
SESSION_NAME="${POSITIONAL[0]}"
fi
if [[ ${#POSITIONAL[@]} -ge 2 ]]; then
OUTPUT_DIR="${POSITIONAL[1]}"
fi
LOG_DIR="${OUTPUT_DIR}/logs/latest"
if tmux has-session -t "$SESSION_NAME" 2>/dev/null; then
echo "Attaching to tmux session: $SESSION_NAME"
exec tmux attach-session -t "$SESSION_NAME"
fi
echo "Creating new tmux session: $SESSION_NAME"
# Window 0: Launcher - empty shell
tmux new-session -d -s "$SESSION_NAME" -n "Launcher"
# Window 1: Logs - 4 vertical panes
tmux new-window -t "$SESSION_NAME" -n "Logs"
tmux split-window -v -t "$SESSION_NAME:Logs.0"
tmux split-window -v -t "$SESSION_NAME:Logs.1"
tmux split-window -v -t "$SESSION_NAME:Logs.2"
tmux select-layout -t "$SESSION_NAME:Logs" even-vertical
tmux select-pane -t "$SESSION_NAME:Logs.0" -T "Trainer"
tmux select-pane -t "$SESSION_NAME:Logs.1" -T "Orchestrator"
tmux select-pane -t "$SESSION_NAME:Logs.2" -T "Envs"
tmux select-pane -t "$SESSION_NAME:Logs.3" -T "Inference"
tmux send-keys -t "$SESSION_NAME:Logs.0" \
"tail -F ${LOG_DIR}/trainer.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.1" \
"tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.2" \
"tail -F ${LOG_DIR}/envs/*/*.log 2>/dev/null" C-m
tmux send-keys -t "$SESSION_NAME:Logs.3" \
"tail -F ${LOG_DIR}/inference.log 2>/dev/null" C-m
# Window 2: SUCCESS - grep SUCCESS on orch and trainer logs (two stacked panes)
tmux new-window -t "$SESSION_NAME" -n "SUCCESS"
tmux split-window -v -t "$SESSION_NAME:SUCCESS.0"
tmux select-layout -t "$SESSION_NAME:SUCCESS" even-vertical
tmux select-pane -t "$SESSION_NAME:SUCCESS.0" -T "Orchestrator"
tmux select-pane -t "$SESSION_NAME:SUCCESS.1" -T "Trainer"
tmux send-keys -t "$SESSION_NAME:SUCCESS.0" "tail -F ${LOG_DIR}/orchestrator.log 2>/dev/null | grep --line-buffered SUCCESS" C-m
tmux send-keys -t "$SESSION_NAME:SUCCESS.1" "tail -F ${LOG_DIR}/trainer.log 2>/dev/null | grep --line-buffered SUCCESS" C-m
# Window 3: Agent (claude code or codex) with log context
tmux new-window -t "$SESSION_NAME" -n "Agent"
AGENT_PROMPT="You are monitoring a prime-rl training run. The output directory is ${OUTPUT_DIR}. Log paths:
Trainer: ${LOG_DIR}/trainer.log
All nodes: ${LOG_DIR}/trainer/node_*.log
All ranks: ${LOG_DIR}/trainer/torchrun/*/*/*/*.log
Orchestrator: ${LOG_DIR}/orchestrator.log
Inference: ${LOG_DIR}/inference.log
Envs: ${LOG_DIR}/envs/*/*.log
Train envs: ${LOG_DIR}/envs/train/*.log
You are running inside tmux session \"${SESSION_NAME}\". The Launcher window (window 0) is where the user runs launch commands. You can read its contents with: tmux capture-pane -t ${SESSION_NAME}:Launcher -p
Help the user monitor and debug this run."
case "$AGENT" in
claude)
tmux send-keys -t "$SESSION_NAME:Agent" \
"claude --permission-mode auto --append-system-prompt \"${AGENT_PROMPT}\"" C-m
;;
codex)
tmux send-keys -t "$SESSION_NAME:Agent" \
"codex --yolo \"${AGENT_PROMPT}\"" C-m
;;
*)
echo "Error: unknown agent '$AGENT' (expected claude|codex)" >&2
exit 1
;;
esac
# Pane title styling
tmux set-option -t "$SESSION_NAME" -g pane-border-status top
tmux set-option -t "$SESSION_NAME" -g pane-border-format " #{pane_title} "
# Focus launcher window and attach
tmux select-window -t "$SESSION_NAME:Launcher"
exec tmux attach-session -t "$SESSION_NAME"
+8 -12
View File
@@ -17,7 +17,7 @@ uv run rl --model @ model.toml --data @ data.toml # nes
uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mixed
```
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base. `output_dir` has one extra fallback: CLI > config files > `$PRL_OUTPUT_DIR` > `"outputs"`.
Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max_model_len`).
@@ -25,9 +25,13 @@ Naming: CLI uses kebab-case (`--vllm.max-model-len`); TOML uses snake_case (`max
```bash
uv run rl --help # all fields and defaults
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved configs (JSON) to /tmp/x/check/configs
uv run rl @ rl.toml --dry-run --output-dir /tmp/x --run.name check # write resolved JSON to /tmp/x/check/configs/latest
```
Each attempt also writes `configs/attempt_<n>/command.txt`. It records the
shell-safe launch command, including CLI overrides. `configs/latest` points to
the current attempt.
## Validators
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, remove the old spelling: no `validation_alias`, no auto-translating `mode="before"` validator. The old key then fails as an unknown key, which is the signal. An alias that stays forever is worse than a break — it never gets retired, and a key whose *meaning* changed silently misconfigures the run.
@@ -69,6 +73,8 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
**Discriminated unions** — set the `type` field to pick the variant (`[orchestrator.algo] type = "max_rl"`). Omit `type` to keep the default variant.
**RL loss** — `[trainer.loss]` defaults to IPO with `eps = 0.1`, `adv_tau = 1.0`, and `kl_tau = 1e-3`. Omit the section to use these defaults. Set `type = "custom"` with `import_path` and optional `kwargs` to load a custom RL loss. The `ce` and `ref_kl` components are fixed.
**Algorithms** — `[orchestrator.algo] type = "grpo" | "max_rl" | "rae" | "hierarchical_grpo" | "opd" | "opsd" | "sft" | "echo"` — the type names the algorithm (credit assignment + loss routing, fused), and each type's class defaults are its vetted setting; any other key you set is your own assembly (e.g. `[orchestrator.algo.roles.user] alpha = 0.1` for echo — setting any echo role replaces the whole role table). `hierarchical_grpo` is only valid with a proposer-solver env: it compares solvers with attempts on the same proposed problem and proposers with other proposals in the group. There is no preset layer, and no config hook that points at user code — a new algorithm is a named class in the repo (subclass `Algorithm`, register it). Per-source override: `[orchestrator.train.source.algo] type = "opd"` (the source assembles its own algorithm). prime-rl only hosts the trainable policy; frozen models are inline external endpoints on the algorithm, named where the model is used — `[orchestrator.algo.teacher]` for opd (the frozen model scored against), `[orchestrator.algo.sampling.source]` for sft (the model it samples from), each with `name` + `base_url`. There is no shared `teacher` slot. opsd declares no model — it self-distills against the live policy. See `docs/algorithms.md`.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
@@ -80,16 +86,6 @@ The `sft` entrypoint takes the same eval shape at the top level for online evals
In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export with `trainer.enable_token_export = true` (or `--enable-token-export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `<run_dir>/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, component weight streams (rl/ce/ref_kl), advantages, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
enable_token_export = true
```
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
## Key files
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
+168
View File
@@ -0,0 +1,168 @@
---
name: dashboard
description: Find, start, use, and stop the local run dashboard for metrics, configs, traces, logs, and reports. Use when asked for its URL, to watch or inspect a run, to control the open dashboard, or to create a cited dashboard report explicitly requested by the user.
---
# Run dashboard
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default
`outputs/`, or `$PRL_OUTPUT_DIR` if set) serves a web UI at `http://localhost:7788`. It only reads run
dirs — safe against live runs — and installs anywhere (cluster head node,
laptop against a mounted outputs dir): GPU dependencies live behind the
`gpu` extra.
The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
to inspect the immutable config or log files from an earlier launch. The Config
view shows a copyable launch command above the launch TOML or resolved JSON.
The trace viewer has separate **Transcript**, **Timeline**, **Replay**, and
**Semantic** views. Timeline is a wall-clock Gantt of physical prefix branches.
Replay renders the selected agent branch as a terminal session with play/pause,
seek, restart, and speed controls. It preserves recorded model-call and
tool-result delays. Since the trace schema records a complete model-call span
but no per-token timestamps, response text is paced evenly across that measured
span and labeled as inferred; events without timestamps remain ordered and are
labeled untimed. Semantic projects Verifiers `MessageNode.semantic_parents` as a
top-to-bottom causal graph of model calls, including subagent calls, returns,
compactions, and custom edge types. Calls occupy compact causal ranks within
bounded agent lanes: the root stays centered, concurrent children fan out
symmetrically, and child slots are reused after return, so graph width reflects
peak agent concurrency rather than total subagents. Compaction starts a visibly
separate context segment. For display only, a missing continuation is recovered
when the physical parent chain proves a completed tool round-trip; fragments
that still cannot be placed are shown explicitly as unlinked instead of being
presented as contexts. Hover or click an agent or context label to see its
latest and peak prompt lengths first, followed by cumulative token processing
and cost. Exact timing remains available on model-call hover and in Timeline.
Traces without semantic parents keep the other views and disable Semantic.
Replay defaults to 8× so long coding-agent model waits remain watchable; select
1× for exact wall time or up to 32× for faster review. In-flight calls display
their measured progress and recorded output-token usage even when they produce
only tool calls. Enable **Skip inference** to collapse model calls to immediate
responses while preserving the recorded command-to-tool-output delays. This is
distinct from the speed control, which scales every delay uniformly. Recorded
model thinking is shown by default. Toggle **Thinking** in the replay controls
or press **T** while Replay is open to hide or show it without changing playback
timing. Do not advertise Ctrl+T: browsers reserve it for a new tab before the
page can handle the keypress. Use **Top** or the **Home** key to scroll to the
beginning without pausing the replay. Use **Live** or **End** to resume
following newly rendered output. Prompt-context nodes that were committed at
response time are placed at the linked call's start so their serialization
timestamp does not create a false blank wait before the replay.
Every dashboard instance serves the dirs it was started with **plus** every dir
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
live). Launchers (`rl`, `sft`) register their output dir on every
start and, in interactive sessions, auto-start a dashboard only when none is
live — an already-running one absorbs the new dir automatically, whatever port
it is on. `--no-dashboard` opts a run out; non-interactive launches (CI, nohup)
register their dir but never spawn.
## Isolated mode
`--isolated` serves only the given dirs: no registry read or write, no
discovery claim, and launchers ignore the instance. Use it for focused views
(demos, debugging one run dir) or to keep a scratch dir out of the registry.
## Finding the live dashboard
The live port can differ from 7788 (a taken port bumps to the next free one),
so read the discovery file:
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
curl -sf $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/runs > /dev/null && echo live
ps aux | grep PRL::Dashboard # process title
```
Hand the researcher the `url` from `daemon.json`. Launcher logs also print it:
startup ends with a `Dashboard · <url>` banner. The auto-started instance logs
to `~/.cache/prime-rl/dashboard/daemon.log`.
## Stopping / restarting
```bash
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # the discovered instance
pkill -f PRL::Dashboard # every dashboard on the host
```
A clean exit releases `daemon.json`; a stale file from a dead process is taken
over by the next start. Killing a dashboard never affects runs (it only reads),
and killing a run never takes the dashboard down (it runs in its own session).
Restart by launching any run, or directly: `uv run dashboard`.
## Point the open dashboard
Use `POST /api/view` to show relevant run data in every connected dashboard
tab:
```bash
curl -sS -X POST $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/view \
-H 'content-type: application/json' -d '{
"run": "demo-rl", "tab": "traces",
"step": 0, "kind": "train", "subset": "effective",
"episode": "ep-s00-reverse-text-0",
"highlight": [{"node": 3, "quote": "hint: reverse the words", "reason": "tool result the policy conditioned on"}]
}'
```
`run` is required; other fields are optional and leave unspecified UI state
unchanged. For trace evidence, supply `step`, `kind`, and `subset` together and
address the episode by stable `id`. The traces tab opens on the whole stream;
`subset: "effective"` switches it to the cohort that shipped at one step. Use
optional `trace` and `branch` indices
for multi-agent traces and `highlight` entries shaped as `{node, quote,
reason, field?}`. On `409`, tell the user to open the returned `url`; the stored
command applies when the tab connects.
## Write a report only when asked
Create a report only when the user explicitly asks for one. Otherwise answer
normally; use `/api/view` when showing trace evidence would help.
Write requested reports to `<run>/reports/<slug>.md`, then POST `{"run": ...,
"tab": "report", "report": "<slug>"}`. Use Markdown with a frontmatter
`title` and one-line JSON citation definitions:
```markdown
---
title: Why does reward dip at step 4?
---
The dip is provider errors, not policy regression [^err].
[^err]: {"step": 4, "kind": "train", "subset": "all", "episode": "ep-...", "node": 0, "quote": "engine overloaded", "note": "The failed call that emptied this step's batch."}
```
The frontmatter `title` is rendered as the report H1; do not repeat it with a
Markdown `#` heading. The inline renderer supports only HTTP(S) and anchor
links. Relative Markdown links render as literal text, so identify local source
files with inline code paths or link to a supported HTTP endpoint.
Each citation requires `step`, `kind`, `subset`, `episode`, `quote`, and `note`.
Use the top-level rollout record `id` returned by the dashboard episode-list
API—not a nested `traces[*].id`, and never `line`. Copy a short, distinctive
quote exactly; matching is case-sensitive and whitespace-insensitive. Keep
`note` to 1–2 sentences explaining why the quote supports the claim.
Cite major empirical, comparative, and diagnostic conclusions, but not routine
explanation. Use exact trace citations for trajectory-level claims. For
aggregate statistics, identify the run and source file; do not imply that one
example trajectory proves the aggregate.
Use adjacent markers (`[^a] [^b]`) only when one claim genuinely depends on
distinct passages, such as a comparison or corroboration. Use one citation
when one passage is sufficient.
Optional fields are `run`, `trace`, `branch`, `node`, `field`, `prefix`, and
`suffix`. Use `field: "content"` or `"reasoning"` only to disambiguate message
parts. Use verbatim adjacent `prefix`/`suffix` only when a quote repeats.
Ambiguous or mismatched citations remain broken and do not navigate.
Use Markdown; raw HTML is escaped.
Before handoff, reload the report and verify through the dashboard API that
every referenced citation resolves uniquely to its episode, node, and quote.
Confirm zero broken citations, one rendered title, and no unsupported relative
links.
+20 -7
View File
@@ -22,13 +22,15 @@ git submodule update --init --recursive
## Sync
```bash
uv sync # core only
uv sync # slim
uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
uv sync --package prime-rl --package gsm8k # core + just one env
```
`uv sync --group dev` installs the `pre-commit` package but leaves the git hook inert until it's wired up — run `uv run pre-commit install` once per clone (see `README.md`'s Development section).
Environment packages are uv **workspace members**. Those under `deps/prime-envs/environments/*/*` are auto-discovered — adding a new env there needs no `pyproject.toml` change. verifiers' example envs are enumerated explicitly in `[tool.uv.workspace].members` (only the ones prime-rl trains or tests on) — to use another, add its path to the list. Members are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
@@ -57,20 +59,31 @@ See the `kernels` skill.
### NemotronH (Mamba SSD kernels)
```bash
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
uv sync --extra gpu
```
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
Native NemotronH uses Mamba2 Triton SSD kernels and FLA's packed causal convolution. The pinned `mamba-ssm` source installs without `nvcc`; no separate `causal-conv1d` installation is needed. `uv sync --all-extras` includes these dependencies.
### Trainer DeepEP backend
`scripts/install_ep_kernels.sh` auto-detects the CUDA toolkit matching torch and the GPU arch, builds NVSHMEM + DeepEP from source, and skips if `deep_ep` already imports.
The `disagg` extra installs the prebuilt DeepEP wheel pinned in `[tool.uv.sources]`:
```bash
bash scripts/install_ep_kernels.sh
uv sync --extra disagg
```
Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver VER` (default `3.3.24`), `--configure-drivers` (multi-node IBGDA; needs sudo + reboot).
The prime-kernels repository owns source builds for DeepEP, DeepGEMM, and TorchAO. Use
its scripts when a local rebuild is required:
```bash
git submodule update --init deps/prime-kernels
bash deps/prime-kernels/scripts/install_ep_kernels.sh --wheel-dir /tmp/prime-kernels-wheels
uv pip install --reinstall --no-deps /tmp/prime-kernels-wheels/deep_ep-*.whl
```
The build needs a CUDA toolkit whose version matches torch. Set
`TORCH_CUDA_ARCH_LIST` when the build host has no GPU or when the wheel must support
more than the local GPU architecture.
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
@@ -89,4 +102,4 @@ Binaries land in `third_party/llmd/bin/{epp,envoy,pd-sidecar}` (a shared path, s
- `pyproject.toml` — dependencies, extras, dependency groups
- `uv.lock` — pinned lockfile (refresh with `uv sync --all-extras`)
- `scripts/install.sh` — bootstrap installer
- `scripts/install_ep_kernels.sh` — DeepEP build script
- `deps/prime-kernels/scripts/` — native wheel build scripts
+48 -50
View File
@@ -10,13 +10,13 @@ CUDA kernels live in their own monorepo,
git submodule `deps/prime-kernels`, alongside prime-rl's other submodules. That repo is the
wheel root (`setup.py`, `pyproject.toml`) and `prime_kernels/` inside it is the importable
package: one folder per kernel, holding the
kernel's Python surface *and* its C++/CUDA sources under `csrc/`, all declared in the single
kernel's Python surface and, for compiled kernels, its C++/CUDA sources under `csrc/`, all declared in the single
manifest `prime_kernels/kernels.toml`. See `deps/prime-kernels/README.md` once the submodule
is initialized.
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit, builds the
wheel from it, and installs the result — and stays a pure-Python wheel itself; never add
compiled extensions to it.
Nothing about a kernel lives in prime-rl. prime-rl pins a prime-kernels commit for local
source builds and a prime-kernels release for installs. prime-kernels builds and publishes
its own wheels. prime-rl stays a pure-Python wheel; never add compiled extensions to it.
Living under `deps/` means `tool.ruff.extend-exclude = ["deps"]` in `pyproject.toml`
already covers it — prime-rl lints none of it.
@@ -38,15 +38,18 @@ it once at startup rather than failing a run halfway through. `unavailable_reaso
the same answer for one kernel (`None` when it is usable), which is what a test's skip guard
wants; `is_available` is just that call compared to `None`.
`flash_moe` is the one kernel today: fused MoE forward (bf16 + mxfp8) on Blackwell
tcgen05, reached through `model.moe_fused_kernel=true`.
`flash_moe` is a compiled fused MoE forward kernel (bf16 + mxfp8) on Blackwell
tcgen05. Its trainer integration is dormant. `mxfp8_moe` is a Python-only registered
kernel package for MXFP8 grouped GEMM and torch EP transport on SM100; it owns the
MoE-specific torchao-derived orchestration and exports explicit BF16 boundaries instead
of tensor-subclass interception.
What a kernel requires of its inputs — block sizes, alignments, shape constraints — belongs
to prime-kernels, which exports it: `flash_moe.BLOCK_M`, `flash_moe.MXFP8_SCALE_BLOCK`, and
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`, which
`apply_fused_moe_kernel` calls once at setup so an unsupported model fails before training
rather than mid-step. Never hardcode a `128` on this side: then every requirement change is
a change in both repos.
`flash_moe.unsupported_shape_reason(dim, hidden_dim, mxfp8=...)`. When the trainer integration
is restored, call this once during setup so an unsupported model fails before training rather
than mid-step. Never hardcode a `128` on this side: then every requirement change is a change
in both repos.
## Building locally
@@ -72,14 +75,15 @@ The work happens in the prime-kernels repo, not here. Inside `deps/prime-kernels
1. Commit the sources under `prime_kernels/<name>/csrc/`.
2. Add a `[<name>]` table to `prime_kernels/kernels.toml` — `sources`, `include-dirs`,
`arch`, `cxx-std`; paths are relative to the kernel folder.
`arch`, `cxx-std`; paths are relative to the kernel folder. A vendored Python kernel
uses `python-only = true`, may declare import checks in `requires`, and omits compiled
extension fields.
3. Write `prime_kernels/<name>/__init__.py` — `from . import _C`, then per op a wrapper
calling `torch.ops.<ns>.<op>` and a `torch.library.register_fake`. No
`torch.library.custom_op` decorator: that defines a *Python* op, and `TORCH_LIBRARY`
has already defined these C++ side — only the fake (meta) kernel is missing. A kernel
used in training also needs `torch.library.register_autograd`, since a schema carries
no backward. (`flash_moe` is forward only; prime-rl wraps it in an `autograd.Function`
of its own.)
no backward. `flash_moe` is forward only and currently has no trainer integration.
4. Nothing else: `setup.py` and the runtime registry both read the manifest.
Rules the build assumes:
@@ -112,69 +116,63 @@ Then, in order:
- Read the diff for **host-side contract changes**, not just kernel internals. A change to
what the caller must pass (weight layout, scale packing, argument order) is silently wrong
numbers, not a build error, and prime-rl's call sites have to absorb it.
- Rebuild and re-run whatever exercises the kernel — the ABI is not checked for you. For
`flash_moe` that is `tests/unit/train/models/test_fused_moe.py`, which compares its
forward and its hand-written backward against the grouped-mm expert path; it is
`gpu`-marked and skips itself unless the kernel is available, so it only means anything
on a machine the kernel was built for.
- Rebuild and re-run the kernel repository's numerical coverage plus every PrimeRL runtime
path that calls the changed kernel; the ABI is not checked for you.
- The bump alone ships nothing: installs resolve `prime-kernels` from a release wheel, so the
new code only reaches users once a release rebuilds the wheels and the pin below moves.
## Prebuilt wheels
[`build_kernels.yaml`](../../.github/workflows/build_kernels.yaml) builds the wheel for
x86_64 and aarch64 in the CUDA devel image (no GPU needed — nvcc cross compiles). It inits
the `deps/prime-kernels` submodule itself, runs on every bump of it, and attaches the wheels
to a release when given a `release_tag`, alongside the deep-ep/deep-gemm/torchao wheels.
The [prime-kernels](https://github.com/PrimeIntellect-ai/prime-kernels) repository owns
`build_kernels.yaml`. It builds `prime-kernels`, `deep-ep`, `deep-gemm`, and `torchao` for
x86_64 and aarch64. It publishes the wheels as prime-kernels release assets.
Its `paths` trigger is `deps/prime-kernels` (the gitlink), **not** `deps/prime-kernels/**` —
no file under it is tracked by prime-rl, so a `**` pattern would match nothing and submodule
bumps would build no wheels.
Every release gets them: [`tag-and-release.yaml`](../../.github/workflows/tag-and-release.yaml)
calls this workflow after the tag is cut and **before** it promotes the draft, so a published
release always carries its wheels. To backfill a release that predates this, dispatch by hand:
Run that workflow in prime-kernels for each torch or CUDA bump:
```bash
gh workflow run build_kernels.yaml -f release_tag=vX.Y.Z -f ref=vX.Y.Z
gh workflow run build_kernels.yaml \
--repo PrimeIntellect-ai/prime-kernels \
-f release_tag=vX.Y.Z
```
The wheel version carries the ABI it was built against, e.g.
`prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl` — it imports only under
that exact torch, so the build installs the torch pinned in `uv.lock`, not the newest one.
The base version comes from `deps/prime-kernels/pyproject.toml` in the prime-kernels repo.
`prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl`. It imports only under
that exact torch and CUDA ABI. prime-kernels CI controls the build dependency pins.
### Pinning installs at the prebuilt wheels
`uv sync --extra kernels` installs `prime-kernels` from the wheels named in
`[tool.uv.sources]` — the pattern deep-ep, deep-gemm and vllm already use, and the only form
the extra may take, since a sync must never compile:
`[tool.uv.sources]`. deep-ep, deep-gemm, torchao, and vLLM use the same pattern. A sync must
never compile these packages:
```toml
[tool.uv.sources]
prime-kernels = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.8.0/prime_kernels-0.1.0+cu128torch2.11.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/vX.Y.Z/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-kernels/releases/download/vX.Y.Z/prime_kernels-0.1.0+cu130torch2.13.0-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
```
The wheels are prime-rl release assets — the kernels live in their own repo, but they ship
with prime-rl's releases. To move the pin, the build prints both lines, ready to paste, in
its job summary. Then `uv lock`.
The wheels are prime-kernels release assets. Get the exact names before you move all pins:
The pin necessarily trails by one release: a release's own assets do not exist until that
release is built, so `vX.Y.Z` can only point at wheels from an already published tag. Move it
whenever the kernels or the torch/CUDA pin change — a stale pin ships stale kernels, and a
pin whose torch no longer matches the lock fails at import, not at install.
```bash
gh release view vX.Y.Z \
--repo PrimeIntellect-ai/prime-kernels \
--json assets
```
Then run `uv lock`.
Move the pin when a kernel, torch, or CUDA pin changes. A stale pin ships stale kernels. A
torch ABI mismatch fails at import, not at install.
## Gotchas
- prime-kernels' `pyproject.toml` mirrors prime-rl's own `torch>=2.9.0`; keep the two
identical, and build against the torch in `uv.lock` (`build_kernels.yaml` reads it) — the
wheel imports only under the torch it was compiled against.
- Keep the torch floor in prime-kernels aligned with prime-rl. The wheel imports only under
the torch version it was compiled against.
- Never reintroduce `prime-kernels` as a path source: uv cannot read a source tree's metadata
without building it, so every `uv lock` would then need nvcc. A release-asset URL has static
metadata and does not.
- A fresh clone without the submodule still installs and trains — only the source build needs
it. `build_kernels.yaml` inits it and sets `PRIME_KERNELS_REQUIRE=1`, so a wheel is never
published with kernels silently skipped.
- A fresh prime-rl clone without the submodule still installs and trains. Only a local source
build needs it. prime-kernels CI sets `PRIME_KERNELS_REQUIRE=1`, so a release cannot omit
kernels silently.
+81 -34
View File
@@ -9,7 +9,7 @@ description: Monitor an ongoing prime-rl training run — find the output direct
### On launch
1. Find the run dir and read the resolved configs at `{run_dir}/configs/` (start with `rl.json`). The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
1. Find the run dir and read the resolved configs at `{run_dir}/configs/latest/resolved/` (start with `rl.json`, or `orchestrator.json` on local runs). Read the launch command from `{run_dir}/configs/latest/command.txt`. The launch TOML is copied verbatim to `{run_dir}/configs/latest/rl.toml`. The run dir is `{output_dir}/{run_name}` — `run.name` auto-generates as `<envs>--<model>--<short-id>`, so if you only know the output dir, pick the most recently modified subdirectory (`ls -t {output_dir} | head -1`) or read `run.name` from the launch command.
2. Confirm all processes are alive and the run is making progress.
3. Write the initial summary into `{run_dir}/STATUS.md`.
@@ -40,14 +40,7 @@ In W&B, each project auto-gets an **"overview" saved view** (train / eval / stab
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
**Never** run kill or launch commands from your own shell. Dispatch them to the tmux **Launcher** window so the researcher sees what was executed:
```bash
SESSION=$(tmux display-message -p '#S')
tmux send-keys -t "$SESSION:Launcher" 'your command here' Enter
```
After a restart, verify all processes are back up and progress resumed before the next check-in.
**Never** run kill or launch commands yourself. Hand the researcher the exact command and let them run it; after a restart, verify all processes are back up and progress resumed before the next check-in.
---
@@ -55,10 +48,33 @@ After a restart, verify all processes are back up and progress resumed before th
### Where to find things
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the run dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
- `{run_dir}/configs/` — resolved configs, written as JSON so explicit None settings round-trip (`rl.json` has the full picture).
- `{run_dir}/configs/latest/` — the current attempt's command, launch TOML, and `resolved/` JSON files. Each launch stays under `configs/attempt_<n>/`.
- `{run_dir}/logs/latest/` — the current attempt's logs (each launch gets `logs/attempt_<n>/`; resumes never overwrite earlier attempts). See below.
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
- `{run_dir}/monitors/file/` — the metrics, and the traces with the annotations about them (see Episodes below).
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`, or `$PRL_OUTPUT_DIR` if set; several dirs can be tracked at
once) serves a local web dashboard at `http://localhost:7788` with four views per run:
metrics (the W&B overview sections, read from `metrics.jsonl`), per-attempt config
files, a rollout trace viewer with per-token overlays (advantage, trainer logprob,
entropy, KL mismatch, stable/loss/content masks), and merged component logs. It only reads the run dirs — safe to run against a live run.
`--port`/`--host` pick the bind address; a taken port automatically bumps to the next
free one, so several dashboards run side by side without coordination. GPU deps live
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
without the training stack (e.g. on a head node).
**Daemon (auto-start)**: launchers auto-start one dashboard per host per user and a
live one absorbs each new run's output dir automatically — see the `dashboard` skill
for discovery, kill/restart commands, and `--isolated`. The short version: the live
port can differ from 7788 (a taken port bumps), so read the discovery file:
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
ps aux | grep PRL::Dashboard # the daemon's process title
```
Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`.
### Logs
@@ -66,7 +82,7 @@ After a restart, verify all processes are back up and progress resumed before th
{run_dir}/logs/latest/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
├── evals.log # SFT online-eval evals stdout
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -77,6 +93,8 @@ After a restart, verify all processes are back up and progress resumed before th
└── envs/{train,eval}/{env_name}.log # one log file per env
```
SLURM batch logs are under `{run_dir}/launcher/logs/*job_*.log`.
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
Scan for problems:
@@ -117,7 +135,7 @@ All metrics print to the console log (and W&B when configured).
|--------|-------------|
| `mismatch_kl/{all,env}/{mean,std,max}` | KL between trainer and (old) inference policy over trainable tokens |
| `entropy/{all,env}/{mean,std,max}` | policy entropy over trainable tokens |
| `masked_advantage_{positive,negative}/mean` | fraction of DPPO-masked tokens with +/- advantage |
| `is_masked/mean` | fraction of tokens masked by the IPO trust region |
| `optim/grad_norm` | spikes may precede divergence |
**Performance** — trainer and orchestrator step independently, so comparing step times shows who's waiting on whom.
@@ -134,6 +152,10 @@ All metrics print to the console log (and W&B when configured).
| orchestrator | `off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`, `off_policy/dropped` | per-step staleness of trained rollouts |
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
The trainer warns when batch wait time exceeds active trainer time. Add inference nodes when this warning persists. The orchestrator warns when policy wait time exceeds active orchestrator time. Add trainer nodes when this warning persists. The orchestrator also warns when it discards more than half of an episode window and reports stale, errored, and no-signal counts.
`orchestrator.constant_trainer_batch_size` defaults to `true`. It keeps each rollout batch at `orchestrator.batch_size` effective episodes. Set it to `false` for faster collection with variable trainer batch sizes.
For live vLLM stats, query Prometheus directly:
```bash
@@ -144,27 +166,52 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
### Episodes
```
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per episode as it completes
{run_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
{run_dir}/monitors/file/metrics.jsonl # every metric row, tagged by producer
{run_dir}/monitors/file/traces/stream/00000.jsonl.zst # every episode, appended as it arrives: sealed chunks ...
{run_dir}/monitors/file/traces/stream/00001.jsonl # ... and the live one, plain text
{run_dir}/monitors/file/traces/stream.index.jsonl # one compact row per episode, with its chunk and byte offset
{run_dir}/monitors/file/traces/annotations/{producer}/00000.jsonl # trace updates: orch ship-time facts, trainer per-token streams
{run_dir}/monitors/file/traces/annotations/{producer}.index.jsonl # each update's scalars and where its record sits
```
JSONL files of native `vf.Episode` records (training tensors excluded), one line per episode.
`all` gets every completed episode as it arrives — including trace-less failures,
curriculum-rejected work, and work that never enters a batch — so it is crash-durable.
`effective` contains the admitted clean trainable traces grouped into their original episodes
(eval: the non-errored trainable epoch cohort). Each record carries its provenance at the
episode level: `env` (`id` plus the orchestrator's `name`), full `task`, `group` (`id`),
and `run`. Training-run records discriminate train/eval work and include dispatch
step plus an optional live-policy version span. Traces retain their own task,
verifiers, agent, and runtime fields.
Everything the file monitor dumps lives under `monitors/file/`; nothing is written
there when the monitor is off. The traces and everything written about them sit under
`traces/`. Each stream is a directory of numbered chunks — the writer rolls to a new
chunk at `monitors.file.chunk_bytes` (5 GiB) and, with `monitors.file.compress` (on),
seals the full one with zstd in the background; a finished run seals its live chunk
too. Sealed chunks use seekable frames, so a seek still costs one frame, and
`zstd -dcf` streams them together with the plain live chunk. Every index is named for
the stream it indexes and sits beside it. Those indexes are what keep reading a run
cheap: a consumer browses them instead of the streams, and seeks by the chunk and
offset they carry to read a single episode or its token streams. Both are derived, so
deleting them only costs a reader the work of rebuilding what it needs. The stream
holds native `vf.Episode` records (training tensors excluded; per-token floats rounded
to `monitors.file.float_decimals`, 4 by default), one line per episode in arrival order, whatever kind of work it did —
including trace-less failures, curriculum-rejected work, and work that never enters a
batch, so it is crash-durable. Each record carries its provenance: `env` (`id` plus the
orchestrator's `name`), full `task`, `group` (`id`), and `run`.
A trace has several steps, so each is stamped as its own event rather than implied by
where the record sits. The file monitor stamps `info.kind` and `info.dispatch`/
`info.arrival` (`{step, time}` each) as an episode lands; the ship-time annotation adds
`info.effective` and `info.ship` — the orchestrator step whose batch shipped the
cohort, or for eval the step that produced the policy it measured. Staleness is
`ship.step - dispatch.step`. Only `effective` ties to a step; `all` is the whole stream.
Everything learned after arrival is an append-only trace update keyed by `trace_id`,
one file per producer so each has a single writer: the orchestrator records cohort
membership, the scalar advantage and per-branch advantage streams; the trainer records
its recomputed per-token logprobs and entropies. Readers fold the updates onto the
stream records, newest winning.
```bash
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
jq '.traces[].rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .env.id, errors}' {run_dir}/rollouts/step_*/train/all/traces.jsonl
wc -l {run_dir}/monitors/file/traces/stream.index.jsonl
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq '.traces[].rewards'
zstd -dcf {run_dir}/monitors/file/traces/stream/* | jq 'select(.ok | not) | {id, env: .env.id, errors}'
jq '{trace_id, info}' {run_dir}/monitors/file/traces/annotations/orch.index.jsonl
```
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/batches/step_{n}/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank).
### Common failure modes
@@ -180,13 +227,13 @@ A few warnings are normal. Escalate when errors are persistent, growing, or hit
All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
```
PRIME-RL::Launcher
├── PRIME-RL::Inference (vLLM server, GPU 0)
├── PRIME-RL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
PRL::Launcher
├── PRL::Inference (vLLM server, GPU 0)
├── PRL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
│ └── Verifiers::EnvWorker0..N
├── PRIME-RL::Orchestrator (CPU-only; connects to each env server)
├── PRL::Orchestrator (CPU-only; connects to each env server)
├── torchrun
│ └── PRIME-RL::Trainer (GPU 1+)
│ └── PRL::Trainer (GPU 1+)
└── tail trainer.log
```
+22 -2
View File
@@ -7,6 +7,8 @@ description: How to launch prime-rl training runs — the `rl`, `sft`, `inferenc
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
SLURM launches write generated scripts and coordination files under `<run_dir>/launcher/`, with batch logs under `launcher/logs/`. Local launches do not create this directory. Every launch writes configs and `command.txt` under `configs/attempt_<n>/`. `configs/latest` points to the current attempt. The command uses shell-safe quoting.
## Run directories
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, broadcasts, rollouts) to its own run directory `<output_dir>/<run_name>`. `run.name` auto-generates as `<envs>--<model>--<short-id>` (SFT: `<dataset>--<model>--<short-id>`), so every launch gets a fresh, readable run directory; `run.dir` overrides the directory leaf when it should differ from the name. Pass `--run.name <name>` to make the run directory predictable — required to resume the run later (`--resume`, or `--resume.step N`, reuses the named run directory; without `[ckpt]` it loads but saves no new checkpoints). Launching into a run directory that already contains artifacts fails unless resuming or `--clean` is set (which wipes only that run directory).
@@ -43,6 +45,8 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
- SLURM: single- and multi-node
- Multi-node SLURM stops after `.trainer.done` for trainer-only fake-data runs. Runs with inference stop after both `.trainer.done` and `.orchestrator.done`.
- NIXL on SLURM: install NIXL and ModelExpress with the provided scripts. The job starts ModelExpress and Redis unless `slurm.launch_modelexpress = false`.
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
@@ -66,6 +70,7 @@ uv run sft @ examples/basic/reverse-text/sft.toml --dry-run
- Config: `SFTConfig` (`packages/prime-rl-configs/src/prime_rl/configs/sft.py`)
- Entrypoint: `src/prime_rl/entrypoints/sft.py`
- SLURM: single- and multi-node
- Multi-node online evals use one SLURM job with `num_train_nodes + num_infer_nodes` nodes. The generated `launcher/sft.sbatch` assigns inference nodes first, then trainer nodes.
## `inference` — vLLM server
@@ -92,7 +97,7 @@ curl http://localhost:8000/v1/chat/completions \
## `evals` — multi-env evals
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. Add `[ckpt]` (`interval` counts completed task groups in the eval-source order) to make the run interruptible, then use `--resume`, `--resume.step N`, or `--resume.dir path/to/checkpoints/step_N`; for standalone evals, checkpoint step N means resume from task cursor N. Checkpoints store only the cursor, not generated episode records; partially completed groups and groups beyond the durable cursor are retried. Resume loads without `[ckpt]` but does not save new checkpoints. Checkpoint/resume is rejected with `[online]` because that process is coupled to the trainer's live broadcast handshake. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
```bash
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
@@ -117,13 +122,20 @@ group_size = 4
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # optional: make a standalone eval resumable
interval = 10 # completed task groups between cursor saves
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/latest/envs/eval/{name}.log`.
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
## Exporting checkpoints
Trainer checkpoints are DCP-sharded (`<run_dir>/checkpoints/step_{n}/trainer`). Convert to HF safetensors with `uv run python tools/convert_dcp_to_bf16.py <run_dir>/checkpoints/step_{n}` (writes `<ckpt_dir>/weights`, serveable via `uv run inference --vllm.model <dir>`; model config auto-read from the run’s `configs/latest/resolved/trainer.json`/`sft.json`; multi-rank via `torchrun --nproc-per-node N`; full fine-tunes only, LoRA rejected). Quantize a bf16 HF dir to blockwise FP8 with `tools/convert_bf16_to_fp8.py <dir>` (vLLM-native format), or straight from a checkpoint with `tools/convert_dcp_to_fp8.py <ckpt_dir>` (rank-parallel, writes only `<ckpt_dir>/weights-FP8`, no bf16 on disk); dequantize fp8-only releases with `tools/convert_fp8_to_bf16.py <dir>`. Caveat: on SM120 GPUs (RTX PRO 6000) vLLM 0.26 picks `CutlassFp8BlockScaledMMKernel` for blockwise-fp8 checkpoints and it silently degrades outputs — serve with `VLLM_DISABLED_KERNELS=CutlassFp8BlockScaledMMKernel,MarlinFP8ScaledMMLinearKernel` to fall back to the Triton kernel.
## Summary
| Command | Purpose | Typical use |
@@ -139,3 +151,11 @@ env.agent.runtime.type = "subprocess"
- `packages/prime-rl-configs/src/prime_rl/configs/` — all config classes
- `configs/debug/` — minimal debug configs
- `examples/` — full example configs (e.g. `reverse-text/`)
## Dashboard
Interactive launches auto-start one shared dashboard daemon per user (process title
`PRL::Dashboard`) and end startup with a `Dashboard · <url>` banner. Relay
that URL to the researcher. Discovery: `~/.cache/prime-rl/dashboard/daemon.json` holds
the live `url` (the port can differ from 7788 when it was taken). `--no-dashboard`
opts a run out.
+1 -2
View File
@@ -47,8 +47,7 @@ if _hub_kernels is not None:
try:
return _original_lazy_load_kernel(kernel_name, mapping)
except OfflineModeIsEnabled:
# Return None so NemotronH skips hub kernels; prime-rl's
# _patch_mamba2_use_triton_ssd() uses mamba_ssm directly.
# Return None so callers can use their non-hub implementation.
mapping[kernel_name] = None
return None
+52
View File
@@ -0,0 +1,52 @@
# Dashboard
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, 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
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
(one dashboard per host per user); `--isolated` serves only the given dirs and
skips the registry. See `skills/dashboard/SKILL.md` for discovery,
kill/restart commands, and the local view-command/report contract.
The Config and Logs views keep each launch attempt available. The Config view
shows a copyable command above the launch TOML or resolved JSON. Both views
open at `latest (attempt <n>)` and let you select an earlier attempt.
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
cluster head node, a laptop against a mounted outputs dir:
```bash
uv sync --extra dashboard && uv run dashboard [output_dir ...]
```
The trace viewer's **Messages** mode keeps structured `message.content` and
`trace.tools` visibly separate. **Rendered** decodes each selected branch's
recorded post-renderer `token_ids` as one sequence, retaining special tokens;
it never reconstructs a chat template. The recorded IDs remain the source of
truth, and the viewer reports when IDs, the renderer model, or its tokenizer
are unavailable. Text, advantage, logprob, mask, and content signals apply to
both views; Rendered with Text uses the exact full-sequence decode.
**Replay** plays the selected trace branch as a terminal session. Model
responses, tool commands, and tool results follow their recorded wall-clock
spans, with play/pause, seeking, restart, and speed controls. Providers persist
the full model-call span rather than timestamps for individual tokens, so text
is revealed evenly across that measured span and the UI labels the token cadence
as inferred. Replay defaults to 8× for long coding-agent waits while preserving
their relative timing; 1× restores exact wall time, and speeds up to 32× are
available. In-flight calls show measured progress and recorded output usage even
when the response contains only a tool call. Events from older traces without
timing stay in order and are marked untimed. Prompt context committed at response
time appears at the linked model call's start rather than creating a false blank
delay. **Skip inference** makes every model response immediate while retaining
the recorded delays between tool commands and their outputs. Recorded model
thinking is visible by default and can be toggled from the controls or with
**T** while Replay is open. **Top** (or **Home**) stops following the newest
line and scrolls to the beginning; **Live** (or **End**) resumes following output.
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
runs after every integration test).
View File
+2115
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.4 KiB

+286
View File
@@ -0,0 +1,286 @@
<!-- This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests. -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>prime-rl dashboard</title>
<link rel="icon" href="/static/butterfly-white.svg">
<link rel="stylesheet" href="/static/vendor/uPlot.min.css">
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<header id="topbar">
<div class="brand">
<img src="/static/butterfly-white.svg" alt="Prime Intellect">
</div>
<select id="run-select" title="run"></select>
<div id="compare-wrap" class="dd-wrap">
<button id="compare-btn" class="btn dd-btn">compare</button>
<div id="compare-menu" class="dd-menu" hidden></div>
</div>
<nav id="tabs">
<button data-tab="config">Config</button>
<button data-tab="metrics" class="active">Metrics</button>
<button data-tab="traces">Traces</button>
<button data-tab="report">Report</button>
<button data-tab="logs">Logs</button>
</nav>
<label class="toggle" title="apply agent view commands as they arrive"><input type="checkbox" id="follow-toggle" checked><span class="dot"></span>follow</label>
<label class="toggle" title="poll for updates"><input type="checkbox" id="live-toggle" checked><span class="dot"></span>live</label>
</header>
<div id="run-overview"></div>
<main>
<section id="tab-metrics">
<div class="controls">
<div class="seg" id="metrics-mode">
<button data-mode="overview" class="active">Overview</button>
<button data-mode="all">All</button>
</div>
<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>
<span id="metrics-status" class="muted"></span>
<div class="spacer"></div>
<div class="seg" id="all-layout" hidden>
<button data-layout="flat">Flat</button>
<button data-layout="nested">Nested</button>
</div>
<button id="metrics-collapse" class="btn">collapse</button>
<button id="metrics-expand" class="btn">expand</button>
</div>
<div id="metrics-body"></div>
</section>
<section id="tab-config" hidden>
<div class="controls">
<label class="t-label">attempt</label>
<select id="config-attempt-select"></select>
<div class="seg" id="config-format">
<button data-fmt="toml">TOML</button>
<button data-fmt="json">JSON</button>
</div>
<input id="config-search" class="search" type="search" placeholder="regex search, e.g. lora|lr">
<span id="config-hits" class="muted"></span>
</div>
<div id="config-command">
<div class="config-command-head">
<span class="t-label">command</span>
<button id="config-command-copy" class="btn" type="button">copy</button>
</div>
<div class="config-command-body">
<span class="config-command-prompt" aria-hidden="true">$</span>
<code id="config-command-text"></code>
</div>
</div>
<pre id="config-view"></pre>
</section>
<section id="tab-traces" hidden>
<div class="controls" id="trace-bar">
<div class="seg" id="trace-mode">
<button data-mode="stream" class="active" title="every episode, newest first">Stream</button>
<button data-mode="step" title="the cohort shipped at one step">Step</button>
</div>
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-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
<span id="trace-filter-count" class="badge" hidden></span>
</button>
<div class="dd-menu dd-filters" id="trace-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="trace-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="trace-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<select id="trace-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
<option value="group:asc">group</option>
<option value="duration:desc">total time ↓</option>
<option value="duration:asc">total time ↑</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
</select>
<span id="trace-status" class="muted"></span>
<div class="spacer"></div>
<button id="trace-clear-bin" class="btn" hidden>clear selection</button>
</div>
<div class="controls" id="step-bar" hidden>
<button id="step-prev" class="btn tm-nav" title="previous step">‹</button>
<div id="step-blocks"></div>
<button id="step-next" class="btn tm-nav" title="next step">›</button>
<span id="step-label" class="t-label"></span>
</div>
<div id="trace-chart">
<div class="chart-head"><span class="chart-title">Episodes finished</span><span id="trace-chart-sub" class="muted"></span></div>
<div id="trace-hist"></div>
<div id="hist-tip" hidden></div>
</div>
<div id="episode-table-wrap">
<table id="episode-table">
<thead><tr>
<th>#</th><th>arrived</th><th>took</th><th>kind</th><th>env</th><th>group</th><th>reward</th>
<th>tok</th><th>turns</th><th>branches</th><th>stop</th><th>status</th>
</tr></thead>
<tbody></tbody>
</table>
</div>
</section>
<section id="tab-report" hidden>
<div class="controls">
<label class="t-label">report</label>
<select id="report-select"></select>
<span id="report-verify" class="muted"></span>
<div class="spacer"></div>
<span id="report-status" class="muted"></span>
</div>
<div id="report-wrap"><article id="report-body"></article></div>
</section>
<section id="tab-logs" hidden>
<div class="controls">
<label class="t-label">attempt</label>
<select id="attempt-select"></select>
<div id="log-comp-wrap" class="dd-wrap">
<button id="log-comp-btn" class="btn dd-btn">components</button>
<div id="log-comp-menu" class="dd-menu" hidden></div>
</div>
<div class="seg" id="log-view">
<button data-view="merge" class="active">Merge</button>
<button data-view="split">Split</button>
</div>
<div class="stepper" id="log-level" title="minimum log level">
<button id="log-level-down" title="more verbose">‹</button>
<span id="log-level-label">all</span>
<button id="log-level-up" title="less verbose">›</button>
</div>
<input id="log-search" class="search" type="search" placeholder="regex filter, e.g. ERROR|WARN">
<button id="log-older" class="btn">load older</button>
</div>
<div id="log-panes"></div>
</section>
</main>
<div id="drawer-backdrop" hidden></div>
<div id="trace-modal" hidden>
<aside id="tm-left">
<div class="tm-head tm-stephead" id="tm-stephead">
<button id="tm-step-prev" class="btn tm-nav" title="previous step">‹</button>
<span id="tm-step-label"></span>
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-ctlrow">
<div id="tm-filter-wrap" class="dd-wrap">
<button id="tm-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="tm-filter-menu" hidden>
<div class="dd-sec">filter</div>
<div class="dd-row"><span class="t-label">kind</span>
<div class="seg toggle-seg" id="tm-kinds">
<button data-kind="train" class="on">train</button>
<button data-kind="eval" class="on">eval</button>
</div>
</div>
<label class="dd-row"><span class="t-label">env</span>
<select id="tm-env"><option value="">all envs</option></select>
</label>
<label class="toggle dd-row"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<select id="tm-sort" title="sort" data-label="sort">
<option value="arrival:desc">arrival ↓</option>
<option value="arrival:asc">arrival ↑</option>
<option value="group:asc">group</option>
<option value="duration:desc">total time ↓</option>
<option value="duration:asc">total time ↑</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
</select>
</div>
<div class="tm-head tm-ctlrow" id="tm-mode-row">
<div class="seg" id="tm-mode">
<button data-mode="stream">Stream</button>
<button data-mode="step">Step</button>
</div>
</div>
<div class="tm-head">
<span class="t-label">episodes</span>
<span id="tm-count" class="badge"></span>
</div>
<div id="tm-list"></div>
</aside>
<section id="tm-main">
<div class="tm-head">
<span class="tm-title">Trace Viewer</span>
<button id="tm-back" class="btn" hidden title="back to the report">← report</button>
<div class="seg" id="tm-view">
<button data-view="transcript" class="active">Transcript</button>
<button data-view="timeline">Timeline</button>
<button data-view="replay">Replay</button>
<button data-view="semantic">Semantic</button>
</div>
<div id="tm-semantic-nav" class="tm-semantic-nav" hidden>
<button id="tm-episode-prev" class="btn tm-nav" title="previous episode">‹</button>
<span id="tm-episode-label"></span>
<button id="tm-episode-next" class="btn tm-nav" title="next episode">›</button>
</div>
<div class="spacer"></div>
<div class="seg" id="trace-view-mode">
<button data-mode="messages" class="active">Messages</button>
<button data-mode="rendered">Rendered</button>
</div>
<select id="token-signal" title="Choose the token signal for either view. Text is uncolored; other options color recorded tokens by advantage, loss/content mask membership, or the trainer's annotations (entropy, the mismatch between its recomputed logprobs and the sampling ones, and the IPO stable mask).">
<option value="">Text</option>
<option value="advantage">Advantage</option>
<option value="entropy">Entropy</option>
<option value="mismatch_kl">Mismatch</option>
<option value="stable_mask">Stable mask</option>
<option value="mask">Loss Mask</option>
<option value="is_content">Content Mask</option>
</select>
<button id="tm-collapse" class="btn">collapse</button>
<button id="tm-expand" class="btn">expand</button>
<button id="drawer-close" class="btn">✕</button>
</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>
<div id="tm-evidence-tabs" class="seg" hidden></div>
</div>
<div id="tm-messages"></div>
<div id="tm-timeline" hidden></div>
<aside id="sg-inspector" hidden>
<div class="sg-inspector-head">
<span id="sg-inspector-title">Model call</span>
<button id="sg-inspector-close" class="btn" title="close inspector">✕</button>
</div>
<div id="sg-inspector-body"></div>
<button id="sg-open-transcript" class="btn">open in transcript</button>
</aside>
</section>
<aside id="tm-right">
<div class="tm-head"><span class="tm-title">Overview</span></div>
<div id="tm-meta"></div>
</aside>
</div>
<script src="/static/vendor/uPlot.iife.min.js"></script>
<script src="/static/app.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}
+127
View File
@@ -0,0 +1,127 @@
"""Launcher-side dashboard auto-start.
Every launcher registers its output dir in a shared registry and makes sure one
dashboard is running: every dashboard instance serves its own dirs plus the
registry (re-read live), so each new run shows up on one URL - one dashboard
per host per user. If a live daemon already exists, its URL is reused instead
of starting another. Discovery goes through
``~/.cache/prime-rl/dashboard/daemon.json`` (pid + actual url), which survives
port spillover. The daemon also carries the process title ``PRL::Dashboard``.
Kept free of ``dashboard``-extra imports on purpose: the launcher must work
without the extra (then it registers the dir and points at the missing extra
instead of spawning). ``main`` is the ``dashboard`` console script, delegating
to the actual server.
"""
import fcntl
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import time
import urllib.request
from contextlib import contextmanager
from pathlib import Path
from prime_rl.utils.pathing import CACHE_DIR
STATE_DIR = CACHE_DIR / "dashboard"
DAEMON_FILE = STATE_DIR / "daemon.json"
DIRS_FILE = STATE_DIR / "dirs.json"
DAEMON_LOG = STATE_DIR / "daemon.log"
SPAWN_TIMEOUT_S = 10.0
@contextmanager
def registry_lock():
"""Serialize read-modify-write cycles on the shared registry files: concurrent
launchers (or dashboard starts) must not drop each other's entries."""
STATE_DIR.mkdir(parents=True, exist_ok=True)
with open(STATE_DIR / ".lock", "w") as lock_file:
fcntl.flock(lock_file, fcntl.LOCK_EX)
yield
def register_output_dir(output_dir: Path) -> None:
"""Add the dir to the daemon's registry (idempotent, atomic)."""
with registry_lock():
try:
dirs = json.loads(DIRS_FILE.read_text())
except (OSError, ValueError):
dirs = []
entry = str(output_dir.resolve())
if entry in dirs:
return
dirs.append(entry)
tmp = DIRS_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(dirs))
tmp.replace(DIRS_FILE)
def find_daemon(timeout: float = 1.0) -> dict | None:
"""The live daemon's record ({pid, url, ...}), or None."""
try:
info = json.loads(DAEMON_FILE.read_text())
os.kill(info["pid"], 0)
except (OSError, ValueError, KeyError, TypeError):
return None
try:
with urllib.request.urlopen(f"{info['url']}/api/runs", timeout=timeout):
return info
except OSError:
return None
def ensure_dashboard(output_dir: Path, logger) -> str | None:
"""Register the run's output dir and make sure one dashboard daemon serves it.
Returns the dashboard URL (log it with ``log_dashboard_url``), or None when no
daemon could be found or started (missing extra, non-interactive session, or
startup failure).
"""
# The dir may not exist yet on a first run: create it up front, because the
# daemon only serves registered dirs that exist (and refuses to start with none).
output_dir.mkdir(parents=True, exist_ok=True)
register_output_dir(output_dir)
daemon = find_daemon()
if daemon is not None:
return daemon["url"]
if not sys.stdout.isatty():
logger.warning("Non-interactive session - not auto-starting a dashboard (the output dir stays registered)")
return None
# The console script exists even without the extra, so check the actual imports.
if importlib.util.find_spec("fastapi") is None or importlib.util.find_spec("uvicorn") is None:
logger.warning("Dashboard extra not installed - install with `uv sync --extra dashboard`")
return None
binary = shutil.which("dashboard")
if binary is None:
logger.warning("Dashboard entry point not found - install with `uv sync --extra dashboard`")
return None
with open(DAEMON_LOG, "ab") as log_file:
process = subprocess.Popen([binary], stdout=log_file, stderr=log_file, start_new_session=True)
deadline = time.monotonic() + SPAWN_TIMEOUT_S
while time.monotonic() < deadline:
daemon = find_daemon()
if daemon is not None:
return daemon["url"]
if process.poll() is not None:
break
time.sleep(0.25)
logger.warning(f"Dashboard daemon did not come up - see {DAEMON_LOG}")
return None
def log_dashboard_url(logger, url: str | None) -> None:
"""Banner pointing at the dashboard - meant as the launcher's last startup log."""
if url is None:
return
logger.opt(raw=True, colors=True).info(f"\n <b>Dashboard</b> · <green><u>{url}</u></green>\n\n")
def main() -> None:
from prime_rl.dashboard.server import main as server_main
server_main()
+11 -1
View File
@@ -6,15 +6,25 @@ lives in ``prime_rl.evals.evals``.
"""
import asyncio
import json
import os
from prime_rl.configs.evals import EvalsConfig
from prime_rl.utils.config import cli
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evals")
config = cli(EvalsConfig)
from prime_rl.utils.pathing import prepare_attempt_dirs, write_launch_artifacts
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
os.environ["PRL_ATTEMPT_CONFIG_DIR"] = str(config_dir)
os.environ["PRL_ATTEMPT_LOG_DIR"] = str(log_dir)
os.environ["PRL_LOG_DIR"] = str(log_dir)
write_launch_artifacts(config_dir, "evals")
(config_dir / "evals.json").write_text(json.dumps(dump_resolved_config(config), indent=2))
from prime_rl.evals.evals import run_evals
asyncio.run(run_evals(config))
+16 -6
View File
@@ -10,7 +10,13 @@ from typing import Any
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, latest_log_dir
from prime_rl.utils.pathing import (
format_log_message,
get_launcher_dir,
get_launcher_log_dir,
prepare_attempt_dirs,
write_launch_artifacts,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
@@ -51,7 +57,7 @@ def write_config(
return config_path
def write_slurm_script(config: InferenceConfig, config_path: Path, script_path: Path) -> None:
def write_slurm_script(config: InferenceConfig, config_path: Path, log_dir: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -70,7 +76,10 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
template_vars = dict(
**config.slurm.template_vars,
config_path=config_path,
config_dir=config_path.parent,
log_dir=log_dir,
output_dir=config.output_dir,
launcher_log_dir=get_launcher_log_dir(config.output_dir),
gpus_per_node=config.deployment.gpus_per_node,
dp_per_node=dp_per_node,
num_nodes=getattr(config.deployment, "num_nodes", 1),
@@ -116,6 +125,7 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
script = template.render(**template_vars)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.output_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
@@ -125,17 +135,17 @@ def inference_slurm(config: InferenceConfig):
logger = setup_logger(config.log.level, json_logging=config.log.json_logging)
config_dir = get_config_dir(config.output_dir)
config_dir, log_dir = prepare_attempt_dirs(config.output_dir)
write_launch_artifacts(config_dir, "inference")
is_multi_node = config.deployment.type in ("multi_node", "disaggregated")
exclude = {"deployment", "slurm", "dry_run"} if is_multi_node else {"slurm", "dry_run"}
config_path = write_config(config, config_dir, exclude=exclude, engine_only=is_multi_node)
logger.info(f"Wrote config to {config_path}")
script_path = config.output_dir / INFERENCE_SBATCH
write_slurm_script(config, config_path, script_path)
script_path = get_launcher_dir(config.output_dir) / INFERENCE_SBATCH
write_slurm_script(config, config_path, log_dir, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
log_dir = latest_log_dir(config.output_dir)
num_nodes = getattr(config.deployment, "num_nodes", 1)
log_message = format_log_message(log_dir=log_dir, inference=True, job_log=True, num_infer_nodes=num_nodes)
+50 -22
View File
@@ -14,18 +14,20 @@ from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
create_attempt_log_dir,
format_log_message,
get_ckpt_dir,
get_config_dir,
latest_log_dir,
get_launcher_dir,
get_launcher_log_dir,
prepare_attempt_dirs,
resolve_latest_ckpt_step,
validate_run_dir,
write_launch_artifacts,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
@@ -119,7 +121,8 @@ def rl_local(config: RLConfig):
json_logging=config.log.json_logging,
)
config_dir = get_config_dir(config.run_dir)
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "rl")
write_subconfigs(config, config_dir)
logger.info(f"Wrote subconfigs to {config_dir}")
@@ -127,6 +130,8 @@ def rl_local(config: RLConfig):
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs from deployment config
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
@@ -172,9 +177,6 @@ def rl_local(config: RLConfig):
f"Update the base_url to use port {expected_port} to match the inference server."
)
# Per-attempt log dir: a resume never overwrites an earlier attempt's logs
log_dir = create_attempt_log_dir(config.run_dir)
# Start processes
processes: list[Popen] = []
monitor_threads: list[Thread] = []
@@ -365,17 +367,12 @@ def rl_local(config: RLConfig):
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing orchestrator logs...")
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
tail_process = Popen(
f"tail -F '{log_dir / 'orchestrator.log'}'",
shell=True,
)
processes.append(tail_process)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
# Trainer and orchestrator completion is the successful stop condition.
completion_events = (stop_events["trainer"], stop_events["orchestrator"])
while not all(event.is_set() for event in completion_events):
if error_queue:
error = error_queue[0]
logger.error(f"Error: {error}")
@@ -418,7 +415,7 @@ def rl_local(config: RLConfig):
raise
def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) -> None:
def write_slurm_script(config: RLConfig, config_dir: Path, log_dir: Path, script_path: Path) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -457,11 +454,30 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
train_env_names = env_server_names(config, "train")
eval_env_names = env_server_names(config, "eval")
nixl_broadcast = (
config.weight_broadcast
if config.weight_broadcast is not None and config.weight_broadcast.type == "nixl"
else None
)
launch_modelexpress = nixl_broadcast is not None and config.slurm.launch_modelexpress
modelexpress_vars = {
"use_nixl_broadcast": nixl_broadcast is not None,
"launch_modelexpress": launch_modelexpress,
"modelexpress_host": nixl_broadcast.host if nixl_broadcast is not None else "",
"modelexpress_port": nixl_broadcast.port if nixl_broadcast is not None else 0,
"modelexpress_redis_port": 6380 if nixl_broadcast is not None and nixl_broadcast.port == 6379 else 6379,
}
if config.deployment.type == "single_node":
script = template.render(
**config.slurm.template_vars,
**modelexpress_vars,
config_path=config_dir / RL_CONFIG,
config_dir=config_dir,
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
gpus_per_node=config.deployment.gpus_per_node,
)
elif config.inference is not None and config.inference.deployment.type == "disaggregated":
@@ -472,7 +488,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
is_disaggregated=True,
run_name=config.run.name,
config_dir=config_dir,
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=infer_deploy.num_nodes * config.deployment.num_infer_replicas,
nodes_per_infer_replica=infer_deploy.num_nodes,
@@ -506,6 +525,7 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
**modelexpress_vars,
)
else:
script = template.render(
@@ -513,7 +533,10 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
is_disaggregated=False,
run_name=config.run.name,
config_dir=config_dir, # TODO: should prob have each subconfig path separately
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
@@ -543,9 +566,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
inference_env_vars=inference_env_vars,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
**modelexpress_vars,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
@@ -556,8 +581,8 @@ def rl_slurm(config: RLConfig):
config.log.level or os.environ.get("PRIME_LOG_LEVEL", "info"), json_logging=config.log.json_logging
)
config_dir = get_config_dir(config.run_dir)
log_dir = latest_log_dir(config.run_dir)
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "rl")
if config.deployment.type == "single_node":
write_config(config, config_dir, exclude={"slurm", "dry_run", "clean"})
@@ -593,14 +618,16 @@ def rl_slurm(config: RLConfig):
num_infer_nodes=config.deployment.total_infer_nodes if has_infer else 0,
)
script_path = config.run_dir / RL_SBATCH
write_slurm_script(config, config_dir, script_path)
script_path = get_launcher_dir(config.run_dir) / RL_SBATCH
write_slurm_script(config, config_dir, log_dir, script_path)
logger.info(f"Wrote SLURM script to {script_path}")
if config.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
@@ -608,6 +635,7 @@ def rl_slurm(config: RLConfig):
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
log_dashboard_url(logger, dashboard_url)
def rl(config: RLConfig):
+87 -142
View File
@@ -12,19 +12,20 @@ from prime_rl.configs.evals import EvalsConfig, OnlineConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
create_attempt_log_dir,
format_log_message,
get_broadcast_dir,
get_ckpt_dir,
get_config_dir,
get_log_dir,
latest_log_dir,
get_launcher_dir,
get_launcher_log_dir,
prepare_attempt_dirs,
resolve_latest_ckpt_step,
validate_run_dir,
write_launch_artifacts,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
@@ -39,8 +40,6 @@ from prime_rl.utils.process import (
SFT_CONFIG = "sft.json"
SFT_SBATCH = "sft.sbatch"
EVAL_SBATCH = "eval.sbatch"
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
INFERENCE_CONFIG = "inference.json"
EVALS_CONFIG = "evals.json"
@@ -140,14 +139,20 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
json.dump(env_server_dict, f, indent=2)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path, prl_run_id: str | None = None) -> None:
def write_slurm_script(
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
env = Environment(loader=FileSystemLoader(config.slurm.template_path.parent), keep_trailing_newline=True)
template_dirs = [config.slurm.template_path.parent]
bundled_templates = find_package_resource("templates")
if bundled_templates is not None:
template_dirs.append(bundled_templates)
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
template = env.get_template(config.slurm.template_path.name)
trainer_env_vars = {
@@ -160,190 +165,130 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
config_dir=config_path.parent,
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
gpus_per_node=config.deployment.gpus_per_node,
)
else:
online_eval = config.eval is not None
eval_vars = {}
if online_eval:
assert config.inference is not None
inference_env_vars = {
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
}
eval_vars = {
"router": config.inference.router,
"router_port": config.inference.server.port,
"backend_port": config.inference.backend_port,
"data_parallel_rpc_port": config.inference.vllm.data_parallel_rpc_port,
"dp_per_node": config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
"enable_expert_parallel": config.inference.vllm.enable_expert_parallel,
"inference_env_vars": inference_env_vars,
"evals_env_vars": {
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
},
"eval_env_names": [source.resolved_name for source, _ in eval_env_servers(config)],
}
script = template.render(
**config.slurm.template_vars,
config_path=config_path,
config_dir=config_path.parent,
log_dir=log_dir,
output_dir=config.run_dir,
launcher_dir=get_launcher_dir(config.run_dir),
launcher_log_dir=get_launcher_log_dir(config.run_dir),
trainer_env_vars=trainer_env_vars,
num_nodes=config.deployment.num_train_nodes,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
gpus_per_node=config.deployment.gpus_per_node,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
run_name=config.run.name,
online_eval=online_eval,
use_nccl_broadcast=(
config.eval is not None
and config.weight_broadcast is not None
and config.weight_broadcast.type == "nccl"
),
**eval_vars,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
"""Write the SLURM script for the decoupled online-eval job (inference pool +
env servers + evals) to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
assert config.deployment.type == "multi_node"
assert config.inference is not None
# The eval template is bundled next to the trainer templates; a custom
# slurm.template_path directory takes precedence so both can be overridden.
template_dirs = [config.slurm.template_path.parent]
bundled_templates = find_package_resource("templates")
if bundled_templates is not None:
template_dirs.append(bundled_templates)
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
template = env.get_template(EVAL_TEMPLATE)
inference_env_vars = {
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
}
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
script = template.render(
**config.slurm.template_vars,
config_dir=config_dir,
output_dir=config.run_dir,
num_infer_nodes=config.deployment.num_infer_nodes,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.router,
router_port=config.inference.server.port,
backend_port=config.inference.backend_port,
data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
inference_env_vars=inference_env_vars,
evals_env_vars=evals_env_vars,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
prl_run_id=prl_run_id,
run_name=config.run.name,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
)
script_path.parent.mkdir(parents=True, exist_ok=True)
get_launcher_log_dir(config.run_dir).mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def sft_slurm(config: SFTConfig):
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
trainer and the eval deployment (inference pool + evals) are two independent
SLURM jobs. The trainer publishes its rank-0 hostname through the shared run
directory so the eval deployment can join its NCCL weight-broadcast group."""
"""Run SFT training and its online-eval deployment in one SLURM allocation."""
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
decoupled_eval = config.deployment.type == "multi_node" and config.eval is not None
online_eval = config.deployment.type == "multi_node" and config.eval is not None
config_dir = get_config_dir(config.run_dir)
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "sft")
config_path = config_dir / SFT_CONFIG
exclude = (
{"deployment", "slurm", "dry_run", "clean"}
if config.deployment.type == "multi_node"
else {"slurm", "dry_run", "clean"}
)
if decoupled_eval:
if online_eval:
# The trainer job only needs [eval] for the weight-broadcast cadence; the
# inference pool lives in the eval job.
# inference pool runs on its dedicated nodes in the same allocation.
exclude = exclude | {"inference"}
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
# Trainer and evals processes log to a single shared W&B run across both jobs,
# keyed by the launcher's run id.
# Trainer and evals processes log to a single shared W&B run.
prl_run_id: str | None = None
if decoupled_eval and config.monitors.wandb is not None:
if online_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
script_path = config.run_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path, prl_run_id)
logger.info(f"Wrote SLURM script to {script_path}")
# The trainer job is submitted first and the eval job depends on it having started:
# the trainer creates the shared W&B run, and the evals process's joiner init only
# retries for a bounded window — starting the evals process while the trainer job pends
# would crash it at wandb init.
script_paths = [script_path]
if decoupled_eval:
launcher_dir = get_launcher_dir(config.run_dir)
if online_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Wrote eval subconfigs to {config_dir}")
eval_script_path = config.run_dir / EVAL_SBATCH
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
script_paths = [script_path, eval_script_path]
script_path = launcher_dir / SFT_SBATCH
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
logger.info(f"Wrote SLURM script to {script_path}")
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
log_message = format_log_message(
log_dir=latest_log_dir(config.run_dir),
log_dir=log_dir,
trainer=True,
num_train_nodes=num_nodes,
evals=online_eval,
inference=online_eval,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)] if online_eval else None,
num_infer_nodes=config.deployment.num_infer_nodes if online_eval else 0,
)
if decoupled_eval:
# The eval job logs at stable (non-attempt) paths under the run dir.
log_message += "\n" + format_log_message(
log_dir=get_log_dir(config.run_dir),
evals=True,
inference=True,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
num_infer_nodes=config.deployment.num_infer_nodes,
).removeprefix("Logs:\n")
if config.dry_run:
if decoupled_eval:
trainer_submit = f" TRAIN_JOB_ID=$(sbatch --parsable {script_paths[0]} | cut -d';' -f1)"
eval_submit = f" sbatch --dependency=after:$TRAIN_JOB_ID {script_paths[1]}"
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
eval_submit = (
" sbatch --dependency=after:$TRAIN_JOB_ID "
f"--export=ALL,TRAIN_JOB_ID=$TRAIN_JOB_ID {script_paths[1]}"
)
submit = "\n".join((trainer_submit, eval_submit))
else:
submit = f" sbatch {script_paths[0]}"
note = (
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
if decoupled_eval
else ""
)
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
submitted_job_ids: list[str] = []
for path in script_paths:
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
# (e.g. multi-cluster sbatch appends "on cluster <name>").
cmd = ["sbatch", "--parsable"]
if submitted_job_ids:
# Hold the eval job until the trainer job has started (not finished).
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl":
cmd.append(f"--export=ALL,TRAIN_JOB_ID={submitted_job_ids[-1]}")
cmd.append(str(path))
logger.info(f"Submitting: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
for job_id in submitted_job_ids:
logger.warning(f"Cancelling already-submitted job {job_id}")
subprocess.run(["scancel", job_id], capture_output=True, text=True)
sys.exit(1)
job_id = result.stdout.strip().split(";")[0]
submitted_job_ids.append(job_id)
logger.success(f"Submitted batch job {job_id}")
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
logger.success(log_message)
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
log_dashboard_url(logger, dashboard_url)
def sft_local(config: SFTConfig):
@@ -352,7 +297,8 @@ def sft_local(config: SFTConfig):
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
config_dir = get_config_dir(config.run_dir)
config_dir, log_dir = prepare_attempt_dirs(config.run_dir)
write_launch_artifacts(config_dir, "sft")
config_path = config_dir / SFT_CONFIG
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
@@ -365,7 +311,7 @@ def sft_local(config: SFTConfig):
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
log_dir = create_attempt_log_dir(config.run_dir)
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
@@ -464,6 +410,9 @@ def sft_local(config: SFTConfig):
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
"PRL_ATTEMPT_CONFIG_DIR": str(config_dir),
"PRL_ATTEMPT_LOG_DIR": str(log_dir),
"PRL_LOG_DIR": str(log_dir),
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evals",
},
@@ -503,12 +452,8 @@ def sft_local(config: SFTConfig):
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
shell=True,
)
processes.append(tail_process)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
+66
View File
@@ -0,0 +1,66 @@
"""Checkpoint standalone eval progress cursor."""
from __future__ import annotations
import contextlib
import os
import pickle
import tempfile
import time
from pathlib import Path
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_ckpt_dir, get_step_path
class CheckpointManager:
def __init__(self, output_dir: Path) -> None:
self.ckpt_dir = get_ckpt_dir(output_dir)
def get_ckpt_path(self, step: int) -> Path:
return get_step_path(self.ckpt_dir, step) / "evals"
def latest_step(self) -> int:
steps = [
step for step in get_all_ckpt_steps(self.ckpt_dir) if (self.get_ckpt_path(step) / "progress.pt").is_file()
]
if not steps:
raise FileNotFoundError(f"No evals checkpoints found in {self.ckpt_dir}")
return steps[-1]
def save(self, eval_source: EvalSource) -> None:
cursor = eval_source.cursor
ckpt_path = self.get_ckpt_path(cursor)
ckpt_path.mkdir(parents=True, exist_ok=True)
start = time.perf_counter()
# Replace atomically so resume never observes a partially written pickle.
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
pickle.dump(eval_source.state_dict(), f)
os.replace(tmp_name, ckpt_path / "progress.pt")
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp_name)
raise
get_logger().debug(
f"Evals checkpoint saved to {ckpt_path} (cursor={cursor}) in {format_time(time.perf_counter() - start)}"
)
def load(
self,
step: int,
eval_source: EvalSource,
path: Path | None = None,
) -> None:
ckpt_path = path if path is not None else self.get_ckpt_path(step)
state_file = ckpt_path / "progress.pt"
if not state_file.is_file():
raise FileNotFoundError(f"Evals checkpoint not found at {state_file}")
get_logger().info(f"Loading evals checkpoint from {state_file}")
with open(state_file, "rb") as f:
state = pickle.load(f)
if state["cursor"] != step:
raise ValueError(f"Evals checkpoint contains cursor {state['cursor']}, expected step {step}")
eval_source.load_state_dict(state)
+175 -40
View File
@@ -13,8 +13,9 @@ inside the handshake until the receiver acknowledges.
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
are version-pinned measurements, so an overload cut only blocks admission and
the in-flight pool drains through natural completions.
are version-pinned measurements. By default, a newer online checkpoint cancels
unfinished episodes from the prior version; callers can disable this when they need
every epoch to drain.
Env servers: sources without an explicit ``serve.address`` get an env server
spawned by the evals process at their derived address; sources with one are
@@ -28,29 +29,38 @@ import json
import os
import time
import uuid
from pathlib import Path
from subprocess import Popen
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.evals.ckpt import CheckpointManager
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.metrics import dispatch_failure_metrics
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import EvalBatch, Policy
from prime_rl.orchestrator.utils import eval_work, intercept_vf_logging, set_default_executor
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation, Policy
from prime_rl.orchestrator.utils import (
episode_group_id,
eval_work,
intercept_vf_logging,
set_default_executor,
)
from prime_rl.transports.weights import WeightReceiver, setup_weight_receiver
from prime_rl.utils.config import dump_resolved_config
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir
from prime_rl.utils.pathing import create_attempt_log_dir, get_all_ckpt_steps, get_config_dir
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
from prime_rl.utils.utils import clean_exit
@@ -66,8 +76,13 @@ STARTUP_BROADCAST_TIMEOUT_S = 1200
class Evals:
def __init__(self, config: EvalsConfig) -> None:
def __init__(self, config: EvalsConfig, log_dir: Path | None = None) -> None:
self.config = config
self.log_dir = log_dir or (
Path(os.environ["PRL_LOG_DIR"])
if "PRL_LOG_DIR" in os.environ
else create_attempt_log_dir(config.output_dir)
)
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
mode = f"online (broadcasts_dir={config.online.broadcasts_dir})" if config.online is not None else "standalone"
@@ -76,13 +91,15 @@ class Evals:
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
self.ckpt_manager = CheckpointManager(config.output_dir)
self.last_saved_cursor = 0
self.env_server_procs: list[Popen] = []
self.dispatcher_task: asyncio.Task | None = None
# Assigned in setup(); None-initialized so stop() can tear down a
# partially completed setup with plain attribute checks.
self.clients: InferenceClient | None = None
self.admin_clients: AdminClients | None = None
self.admin_plane: AdminPlane | None = None
self.dispatcher: Dispatcher | None = None
self.inference_metrics: InferenceMetricsCollector | None = None
self.periodic_logger: PeriodicLogger | None = None
@@ -93,6 +110,7 @@ class Evals:
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
producer="evals",
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
@@ -107,7 +125,7 @@ class Evals:
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.clients = InferenceClient(config.eval.client, model_name=config.model)
self.admin_clients = AdminClients(config.eval.client)
self.admin_plane = AdminPlane(config.eval.client)
self.spawn_env_servers()
@@ -117,7 +135,7 @@ class Evals:
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.admin_clients.wait_for_ready(config.model)
await self.admin_plane.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
self.receiver: WeightReceiver | None = None
@@ -130,7 +148,7 @@ class Evals:
self.receiver = setup_weight_receiver(
config.online.broadcasts_dir,
weight_broadcast,
admin_clients=self.admin_clients.clients,
admin_plane=self.admin_plane,
model_name=config.model,
)
await self.receiver.initialize()
@@ -138,6 +156,20 @@ class Evals:
is_resumed = config.online is not None and config.online.resume_step is not None
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
if config.resume is not None:
if config.resume.dir is not None:
resume_step = config.resume.dir_step
resume_path = config.resume.dir / "evals"
else:
resume_step = config.resume.step or self.ckpt_manager.latest_step()
resume_path = None
self.ckpt_manager.load(
resume_step,
self.eval_source,
path=resume_path,
)
self.last_saved_cursor = self.eval_source.cursor
get_logger().info(f"Resuming evals from task cursor {self.eval_source.cursor}")
self.policy = Policy(version=0, model_name=config.model)
# Pessimistic per-episode token cost for the controller's starting cap,
@@ -167,11 +199,10 @@ class Evals:
get_inflight=lambda: self.dispatcher.current_inflight,
)
# The collector always polls — it feeds the concurrency controller;
# W&B mirroring is gated on the registered monitor.
# metrics fan out to every registered monitor.
self.inference_metrics = InferenceMetricsCollector(
self.admin_clients.clients,
self.admin_plane.clients,
on_load=self.concurrency.observe,
log_to_wandb=wandb_enabled,
)
# Fail fast when adaptivity has no signal: external API endpoints
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
@@ -181,7 +212,7 @@ class Evals:
if not await self.inference_metrics.probe():
concurrency = config.eval.concurrency
if concurrency.min_inflight != concurrency.max_inflight:
urls = ", ".join(str(client.base_url) for client in self.admin_clients.clients)
urls = ", ".join(str(client.base_url) for client in self.admin_plane.clients)
raise ValueError(
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
@@ -208,7 +239,7 @@ class Evals:
config = self.config
addresses = config.eval.env_addresses
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
log_dir = self.log_dir / "envs" / "eval"
for source in config.eval.source:
if source.serve.address is not None:
continue
@@ -245,6 +276,8 @@ class Evals:
else:
await self.watch()
self.maybe_save_checkpoint(force=True)
# The periodic logger and the collector log to the W&B run, so they
# must stop before finalize marks the run finished.
await self.periodic_logger.stop()
@@ -315,6 +348,20 @@ class Evals:
break
await asyncio.sleep(POLL_INTERVAL_S)
def next_published_step(self, step: int) -> int | None:
"""Return the first newer checkpoint offered by the trainer."""
assert self.config.online is not None
assert self.config.online.broadcasts_dir is not None
assert self.receiver is not None
return next(
(
candidate
for candidate in get_all_ckpt_steps(self.config.online.broadcasts_dir)
if candidate > step and self.receiver.is_published(candidate)
),
None,
)
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
"""Eval-due steps up to the newest published broadcast that are missing from
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
@@ -349,54 +396,136 @@ class Evals:
# Every offered version must be received: the trainer blocks inside
# the handshake, so a failed receive fails the run loudly.
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
await self.dispatcher.on_version_pending(step)
await self.receiver.receive(step)
self.policy.version = step
await self.dispatcher.on_new_version(step)
if not fired:
return
for env_name in fired:
task_count = self.eval_source.triggered_task_count(env_name, step)
self.eval_sink.set_batch_size(env_name, step, task_count * self.eval_sink.group_size_for(env_name))
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
for env_name in fired
self.eval_envs.get(request.env_name).config.group_size
for request in self.eval_source.queue
if request.step == step and request.env_name in fired
)
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
# between the trigger above and the weight reload completing.
self.policy.version = step
if not reload_weights:
self.policy.version = step
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
await self.consume_epoch(fired)
await self.consume_epoch(fired, step)
async def consume_epoch(self, fired: list[str], step: int) -> None:
"""Consume one epoch, preempting it when a newer checkpoint is ready."""
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name, step) > 0}
cancellation_task: asyncio.Task[int] | None = None
superseding_step: int | None = None
online = self.config.online
async def consume_epoch(self, fired: list[str]) -> None:
"""Consume dispatcher episodes until every fired env's epoch finalizes,
routing them through the sink and monitors."""
# An env with no examples emits no episodes, so its epoch can never finalize.
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
while pending:
episode = await self.dispatcher.out_q.get()
step = eval_work(episode).step
await monitors.log([episode], step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
if (
cancellation_task is None
and online is not None
and self.config.eval.cancel_on_new_checkpoint
and (superseding_step := self.next_published_step(step)) is not None
):
get_logger().warning(
f"Checkpoint {superseding_step} is ready - cancelling unfinished eval episodes for step {step}"
)
cancellation_task = asyncio.create_task(
self.dispatcher.cancel_eval_step(step), name=f"cancel-eval-step-{step}"
)
try:
if online is not None and self.config.eval.cancel_on_new_checkpoint:
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=POLL_INTERVAL_S)
else:
item = await self.dispatcher.out_q.get()
except asyncio.TimeoutError:
if cancellation_task is not None and cancellation_task.done():
cancellation_task.result()
continue
if isinstance(item, GroupCancellation):
eval_batch = self.eval_sink.cancel(item)
group_completed = False
group_id = item.group_id
elif isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.fail(item)
group_completed = not self.eval_sink.has_pending_group(item.group_id)
group_id = item.group_id
else:
item_step = eval_work(item).step
stamp_arrival([item], "eval", item_step)
await monitors.log([item], item_step, "eval", "all")
eval_batch = self.eval_sink.add(item)
group_id = episode_group_id(item)
group_completed = not self.eval_sink.has_pending_group(group_id)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
if group_completed:
source_index = self.dispatcher.pop_source_index(group_id)
if self.config.online is not None:
continue
if source_index is None:
raise RuntimeError(f"Eval group {group_id} is missing its source cursor")
if self.eval_source.mark_completed(source_index):
self.maybe_save_checkpoint()
if cancellation_task is not None:
cancelled = await cancellation_task
get_logger().warning(
f"Cancelled {cancelled} unfinished eval episodes for step {step}; "
f"advancing to checkpoint {superseding_step}"
)
def maybe_save_checkpoint(self, *, force: bool = False) -> None:
if self.config.ckpt is None:
return
cursor = self.eval_source.cursor
if cursor <= 0 or cursor == self.last_saved_cursor:
return
if not force and cursor - self.last_saved_cursor < self.config.ckpt.interval:
return
self.ckpt_manager.save(self.eval_source)
self.last_saved_cursor = cursor
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.episodes:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no episodes returned, skipping log")
if not batch.episodes and not batch.failures and not batch.cancelled:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
return
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
if batch.episodes.effective:
await monitors.log(batch.episodes.effective.vf_episodes, batch.step, "eval", "effective")
await monitors.log_annotations(stamp_batch(batch.episodes.effective.vf_episodes, batch.step))
episodes = batch.episodes
effective = episodes.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
metrics |= dispatch_failure_metrics(
batch.failures,
prefix=f"eval/{batch.env_name}/all",
total_attempts=total_attempts,
)
if batch.cancelled:
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
@@ -404,6 +533,14 @@ class Evals:
eff, full = effective.metrics, episodes.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
if batch.cancelled:
get_logger().warning(
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Error {full.has_error.mean():.1%} | "
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
)
return
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
@@ -442,14 +579,14 @@ class Evals:
await self.dispatcher.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_clients is not None:
await self.admin_clients.aclose()
if self.admin_plane is not None:
await self.admin_plane.aclose()
cleanup_processes(self.env_server_procs)
@clean_exit
async def run_evals(config: EvalsConfig) -> None:
evals = Evals(config)
async def run_evals(config: EvalsConfig, log_dir: Path | None = None) -> None:
evals = Evals(config, log_dir)
try:
await evals.run()
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
@@ -459,11 +596,9 @@ async def run_evals(config: EvalsConfig) -> None:
def main() -> None:
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.entrypoints.evals import main as entrypoint_main
set_proc_title("Evals")
asyncio.run(run_evals(cli(EvalsConfig)))
entrypoint_main()
if __name__ == "__main__":
+431
View File
@@ -0,0 +1,431 @@
from __future__ import annotations
import asyncio
import os
import time
from collections.abc import Callable
from pathlib import Path
from typing import Literal
import httpx
from pydantic import BaseModel, Field
from prime_rl.configs.shared import ClientConfig
from prime_rl.orchestrator.clients import (
ADMIN_TIMEOUT_S,
UPDATE_WEIGHTS_TIMEOUT_S,
AdminPlane,
_admin_post,
check_health,
maybe_check_has_model,
setup_admin_clients,
)
from prime_rl.utils.logger import get_logger
class DynamoWorker(BaseModel):
admin_base_url: str
instance_id: int = Field(ge=0, strict=True)
class DynamoSnapshot(BaseModel):
protocol_version: Literal[1]
workers: tuple[dict[str, object], ...]
class DynamoDiscoveryPending(RuntimeError):
"""The discovery endpoint is healthy but has not published a complete worker set."""
def parse_dynamo_worker(
payload: object,
model_name: str,
*,
expected_admin_host: str | None = None,
) -> DynamoWorker:
snapshot = DynamoSnapshot.model_validate(payload)
matching_workers: list[DynamoWorker] = []
for raw_worker in snapshot.workers:
if raw_worker.get("model") != model_name:
continue
if raw_worker.get("error") is not None:
raise DynamoDiscoveryPending("Dynamo worker is not ready")
if raw_worker.get("admin_base_url") is None:
raise DynamoDiscoveryPending("Dynamo worker is missing admin_base_url")
if type(raw_worker.get("world_size")) is not int or raw_worker["world_size"] != 1:
raise ValueError("Dynamo RL currently supports exactly one inference rank")
worker = DynamoWorker.model_validate(raw_worker)
try:
admin_url = httpx.URL(worker.admin_base_url)
except httpx.InvalidURL as error:
raise ValueError("admin_base_url must be a valid URL") from error
if (
admin_url.scheme not in {"http", "https"}
or not admin_url.host
or (admin_url.port is not None and not 1 <= admin_url.port <= 65535)
or admin_url.userinfo
or admin_url.query
or admin_url.fragment
or admin_url.path != "/"
):
raise ValueError("admin_base_url must be an http(s) origin")
if expected_admin_host is not None and admin_url.host != expected_admin_host:
raise ValueError(
f"Dynamo worker admin host {admin_url.host!r} does not match discovery host {expected_admin_host!r}"
)
matching_workers.append(worker)
if not matching_workers:
raise DynamoDiscoveryPending(f"Dynamo returned no bound workers for model {model_name!r}")
if len(matching_workers) != 1:
raise ValueError("Dynamo RL currently supports exactly one inference worker")
return matching_workers[0]
def topology_fingerprint(worker: DynamoWorker) -> tuple[int, str]:
return worker.instance_id, str(httpx.URL(worker.admin_base_url))
def _discovery_headers(client_config: ClientConfig) -> dict[str, str]:
env_headers = {
name: value
for name, env_name in client_config.headers_from_env.items()
if (value := os.getenv(env_name)) is not None
}
headers = {**client_config.headers, **env_headers}
api_key = os.getenv(client_config.api_key_var)
if api_key and api_key != "EMPTY":
headers = {name: value for name, value in headers.items() if name.lower() != "authorization"}
headers["Authorization"] = f"Bearer {api_key}"
return headers
def resolve_dynamo_discovery_url(client_config: ClientConfig) -> str:
dynamo = client_config.dynamo
if dynamo is None or not dynamo.enabled:
raise ValueError("Dynamo discovery is not enabled")
if dynamo.discovery_url is not None:
return dynamo.discovery_url
try:
base_url = httpx.URL(client_config.base_url)
except httpx.InvalidURL as error:
raise ValueError("Set dynamo.discovery_url when client.base_url is not a valid URL") from error
if base_url.port is None or base_url.port == 65535:
raise ValueError("Set dynamo.discovery_url when client.base_url has no incrementable port")
return str(base_url.copy_with(port=base_url.port + 1, path="", query=None, fragment=None, userinfo=b""))
async def discover_dynamo_worker(
discovery_url: str,
model_name: str,
*,
headers: dict[str, str],
timeout: float,
) -> DynamoWorker:
try:
base_url = httpx.URL(discovery_url)
except httpx.InvalidURL as error:
raise ValueError("dynamo.discovery_url must be a valid URL") from error
if (
base_url.scheme not in {"http", "https"}
or not base_url.host
or (base_url.port is not None and not 1 <= base_url.port <= 65535)
or base_url.userinfo
or base_url.query
or base_url.fragment
):
raise ValueError("dynamo.discovery_url must be an http(s) URL without credentials, query, or fragment")
base_path = base_url.path.rstrip("/")
if base_path.endswith("/v1"):
base_path = base_path.removesuffix("/v1")
url = base_url.copy_with(path=f"{base_path}/v1/rl/workers")
try:
async with asyncio.timeout(timeout):
async with httpx.AsyncClient(headers=headers, timeout=timeout, trust_env=False) as client:
response = await client.get(url)
response.raise_for_status()
payload = response.json()
except TimeoutError as error:
raise TimeoutError(f"Dynamo discovery request exceeded {timeout} seconds") from error
return parse_dynamo_worker(payload, model_name, expected_admin_host=base_url.host)
class DynamoAdminPlane(AdminPlane):
"""Admin plane pinned to two identical snapshots from a trusted Dynamo discovery endpoint."""
def __init__(
self,
client_config: ClientConfig,
model_name: str,
*,
poll_interval: float = 1.0,
) -> None:
if client_config.dynamo is None or not client_config.dynamo.enabled:
raise ValueError("Dynamo discovery configuration is required")
self._discovery_url = resolve_dynamo_discovery_url(client_config)
self._client_config = client_config
self._model_name = model_name
self._poll_interval = poll_interval
self._timeout = client_config.wait_for_ready_timeout
self._headers = _discovery_headers(client_config)
self._frontend_clients = setup_admin_clients(client_config.model_copy(update={"admin_base_url": None}))
self.clients: list[httpx.AsyncClient] = []
self._fingerprint: tuple[int, str] | None = None
self._nccl_initialization_state: Literal["uninitialized", "initializing", "ready", "terminal"] = "uninitialized"
self._mutation_lock = asyncio.Lock()
def _require_uninitialized_nccl(self) -> None:
if self._nccl_initialization_state != "uninitialized":
raise RuntimeError(
"Dynamo NCCL can only be initialized once; restart the inference workers before retrying"
)
def _require_ready_nccl(self) -> None:
if self._nccl_initialization_state != "ready":
raise RuntimeError("Dynamo weight updates require a ready NCCL initialization")
def _terminalize_nccl(self) -> None:
self._nccl_initialization_state = "terminal"
async def _discover(self) -> DynamoWorker:
return await discover_dynamo_worker(
self._discovery_url,
self._model_name,
headers=self._headers,
timeout=min(30.0, max(1.0, float(self._timeout))),
)
async def wait_for_ready(self, model_name: str) -> None:
if model_name != self._model_name:
raise ValueError(f"Dynamo admin plane was configured for {self._model_name!r}, not {model_name!r}")
deadline = time.monotonic() + self._timeout
try:
async with asyncio.timeout(self._remaining(deadline)):
await check_health(self._frontend_clients, timeout=self._remaining(deadline))
await maybe_check_has_model(
self._frontend_clients,
model_name,
skip_model_check=self._client_config.skip_model_check,
)
except TimeoutError as error:
raise TimeoutError(f"Dynamo frontend readiness exceeded {self._timeout} seconds") from error
previous_fingerprint: tuple[int, str] | None = None
last_error: Exception | None = None
while (remaining := deadline - time.monotonic()) > 0:
try:
async with asyncio.timeout(remaining):
worker = await self._discover()
fingerprint = topology_fingerprint(worker)
if fingerprint == previous_fingerprint:
candidate_client = self._make_worker_client(worker)
try:
remaining = self._remaining(deadline)
async with asyncio.timeout(remaining):
await check_health([candidate_client], timeout=remaining, quiet=True)
except BaseException:
await candidate_client.aclose()
raise
self._bind(worker, fingerprint, candidate_client)
return
previous_fingerprint = fingerprint
except httpx.HTTPStatusError as error:
if error.response.status_code < 500:
raise
previous_fingerprint = None
last_error = error
except (DynamoDiscoveryPending, httpx.TransportError, TimeoutError) as error:
previous_fingerprint = None
last_error = error
remaining = deadline - time.monotonic()
if remaining > 0:
await asyncio.sleep(min(self._poll_interval, remaining))
raise TimeoutError("Dynamo workers did not become ready before the discovery timeout") from last_error
@staticmethod
def _remaining(deadline: float) -> float:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("Dynamo readiness deadline expired")
return remaining
def _make_worker_client(self, worker: DynamoWorker) -> httpx.AsyncClient:
worker_timeout = min(30.0, max(1.0, float(self._timeout)))
return httpx.AsyncClient(
base_url=worker.admin_base_url,
headers=self._headers,
limits=httpx.Limits(max_connections=4, max_keepalive_connections=1),
timeout=httpx.Timeout(worker_timeout),
trust_env=False,
)
def _bind(
self,
worker: DynamoWorker,
fingerprint: tuple[int, str],
client: httpx.AsyncClient | None = None,
) -> None:
self._fingerprint = fingerprint
self.clients = [client if client is not None else self._make_worker_client(worker)]
async def ensure_topology_current(self) -> None:
if self._nccl_initialization_state == "terminal":
raise RuntimeError("Dynamo administration is in a terminal state; restart is required")
if self._fingerprint is None:
raise RuntimeError("Dynamo topology has not been pinned")
previous_changed_fingerprint: tuple[int, str] | None = None
last_error: Exception | None = None
deadline = time.monotonic() + self._timeout
for attempt in range(3):
remaining = deadline - time.monotonic()
if remaining <= 0:
break
try:
async with asyncio.timeout(remaining):
worker = await self._discover()
fingerprint = topology_fingerprint(worker)
if fingerprint == self._fingerprint:
return
if fingerprint == previous_changed_fingerprint:
raise RuntimeError("Dynamo worker topology changed after initialization")
previous_changed_fingerprint = fingerprint
last_error = None
except httpx.HTTPStatusError as error:
if error.response.status_code < 500:
raise
last_error = error
except (DynamoDiscoveryPending, httpx.TransportError, TimeoutError) as error:
last_error = error
if attempt < 2:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
await asyncio.sleep(min(self._poll_interval, remaining))
if last_error is not None:
raise RuntimeError("Could not verify the pinned Dynamo topology") from last_error
raise RuntimeError("Dynamo topology changed but could not be confirmed")
async def _collective_rpc(
self,
client: httpx.AsyncClient,
*,
method: Literal["init_broadcaster", "update_weights_from_path"],
timeout: int | float,
args: list[object],
) -> None:
operation_timeout = max(1.0, float(timeout))
async with asyncio.timeout(operation_timeout + 15.0):
response = await client.post(
"/collective_rpc",
timeout=httpx.Timeout(connect=10.0, read=operation_timeout, write=10.0, pool=10.0),
json={"method": method, "timeout": operation_timeout, "args": args, "kwargs": {}},
)
response.raise_for_status()
payload = response.json()
if payload != {"results": [None]}:
raise ValueError("Dynamo worker returned an invalid collective RPC response")
async def update_weights(
self,
weight_dir: Path | None,
*,
transport: Literal["filesystem", "nccl", "nixl"],
step: int = 0,
on_paused: Callable[[], None] | None = None,
) -> None:
if transport != "nccl":
async with self._mutation_lock:
await self.ensure_topology_current()
await super().update_weights(
weight_dir,
transport=transport,
step=step,
on_paused=on_paused,
)
return
if weight_dir is None:
raise ValueError(f"{transport.upper()} weight updates require a broadcast directory")
self._require_ready_nccl()
async with self._mutation_lock:
await self.ensure_topology_current()
self._nccl_initialization_state = "terminal"
try:
await _admin_post(self.clients[0], "/pause", params={"mode": "keep", "clear_cache": "false"})
except BaseException as failure:
raise RuntimeError("Dynamo pause failed; worker state is unknown and restart is required") from failure
if on_paused is not None:
try:
on_paused()
except BaseException as error:
raise RuntimeError(
"Dynamo pause callback failed; engines remain paused and restart is required"
) from error
try:
await self._collective_rpc(
self.clients[0],
method="update_weights_from_path",
timeout=UPDATE_WEIGHTS_TIMEOUT_S,
args=[weight_dir.as_posix()],
)
except BaseException as failure:
self._terminalize_nccl()
raise RuntimeError(
f"Dynamo {transport} update failed; engines remain paused and restart is required"
) from failure
try:
await _admin_post(self.clients[0], "/resume", timeout_s=ADMIN_TIMEOUT_S)
except BaseException as failure:
self._terminalize_nccl()
raise RuntimeError("Dynamo resume failed; worker state is unknown and restart is required") from failure
self._nccl_initialization_state = "ready"
get_logger().info(f"Applied NCCL weights for policy v{step} to the Dynamo worker")
async def initialize_nccl(
self,
*,
host: str,
port: int,
timeout: int,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
async with self._mutation_lock:
self._require_uninitialized_nccl()
if inference_world_size != 1:
raise ValueError("Dynamo RL currently supports exactly one inference rank")
self._nccl_initialization_state = "initializing"
try:
await self.ensure_topology_current()
get_logger().info("Initializing Dynamo NCCL broadcast for one inference rank")
await self._collective_rpc(
self.clients[0],
method="init_broadcaster",
timeout=timeout,
args=[
host,
port,
0,
1,
timeout,
quantize_in_weight_transfer,
"default",
],
)
except asyncio.CancelledError:
self._terminalize_nccl()
raise
except BaseException as error:
self._terminalize_nccl()
raise RuntimeError(
"Dynamo NCCL initialization failed; inference workers must restart before retrying"
) from error
self._nccl_initialization_state = "ready"
async def aclose(self) -> None:
unique_clients = {id(client): client for client in [*self._frontend_clients, *self.clients]}
await asyncio.gather(*(client.aclose() for client in unique_clients.values()))
+252 -68
View File
@@ -9,6 +9,9 @@ def apply_shared_vllm_patches():
load failures (``load_plugins_by_group`` logs and continues), so a broken
entry-point target silently skips ALL of these patches.
"""
from prime_rl.inference.vllm.gpt_oss_weight_loading import patch_gpt_oss_weight_loading
patch_gpt_oss_weight_loading()
_patch_lora_key_prefix()
_patch_qwen35_moe_lora_format()
monkey_patch_nano_v3_reasoning_parser()
@@ -17,6 +20,26 @@ def apply_shared_vllm_patches():
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()
def monkey_patch_deepseek_v4_allowed_layer_types():
"""Let vLLM's `DeepseekV4Config` construct under a transformers pin below 5.15.
`vllm/transformers_utils/configs/deepseek_v4.py` leaves `layer_types` to
`PretrainedConfig`, whose validator checks it against a vocabulary that only gained V4's
compressed attention names in transformers 5.15, so `AutoConfig.from_pretrained` on any
DeepSeek V4 checkpoint raises. vLLM declares `transformers>=5.5.3`, so this is a gap in
upstream's own version floor rather than something prime-rl introduced.
`EngineArgs.__post_init__` loads general plugins before `create_model_config`, which is why
patching here is early enough. The trainer applies the same shim on its own import path.
"""
from prime_rl.utils.transformers_compat import allow_deepseek_v4_layer_types
allow_deepseek_v4_layer_types()
def monkey_patch_online_fp8_parameter_cast():
@@ -104,6 +127,110 @@ 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
@@ -207,7 +334,6 @@ def monkey_patch_minimax_m2_think_end_passthrough():
def monkey_patch_return_routed_experts_with_nixl_connector():
from vllm import envs
from vllm.config.vllm import VllmConfig
from vllm.logger import init_logger
@@ -233,8 +359,10 @@ def monkey_patch_return_routed_experts_with_nixl_connector():
if config.parallel_config.pipeline_parallel_size > 1:
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
if envs.VLLM_USE_V2_MODEL_RUNNER:
raise ValueError("VLLM_USE_V2_MODEL_RUNNER does not yet support: routed experts capture")
if config.use_v2_model_runner:
raise ValueError(
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
)
# vLLM rejects every KV connector, but our P/D path uses NIXL and
# stitches prefill/decode routed experts in the router. CPU KV offload
@@ -609,32 +737,6 @@ def monkey_patch_minimax_m2_for_lora():
)
def monkey_patch_harmony_stop_token_propagation():
"""Fix: vLLM doesn't merge harmony stop tokens into per-request SamplingParams.
The harmony mode sets stop_token_ids (including <|call|> and <|return|>) in
default_sampling_params at server init, but ChatCompletionRequest.to_sampling_params()
ignores them, using only self.stop_token_ids (which defaults to []).
Upstream: https://github.com/vllm-project/vllm/issues/22519
"""
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
_original_to_sampling_params = ChatCompletionRequest.to_sampling_params
def _patched_to_sampling_params(self, max_tokens, default_sampling_params):
params = _original_to_sampling_params(self, max_tokens, default_sampling_params)
# Merge harmony stop tokens from default_sampling_params
default_stop_ids = default_sampling_params.get("stop_token_ids", [])
if default_stop_ids:
existing = set(params.stop_token_ids or [])
merged = list(existing | set(default_stop_ids))
params.stop_token_ids = merged
return params
ChatCompletionRequest.to_sampling_params = _patched_to_sampling_params
def monkey_patch_no_moe_lora():
"""This disables LoRA for MoE layers and makes them pick better kernels.
@@ -717,45 +819,6 @@ def monkey_patch_fp32_lm_head():
logger.info("Installed fp32 lm_head patch (native out_dtype=fp32 mm).")
def monkey_patch_fp32_router_logits():
"""Emit fp32 MoE router logits for DeepSeek-family models (incl. GLM-5.x glm_moe_dsa).
vLLM's DeepseekV2MoE gate is a GateLinear with a bf16 weight and no out_dtype,
so router logits are rounded to bf16 before expert scoring. GLM-5.x was trained
with fp32 routing (Megatron ``--moe-router-dtype fp32``); upstream now runs its
gate fully in fp32 (vllm-project/vllm#47410, not in the pinned release).
Setting ``out_dtype=float32`` routes the gate through GateLinear's cuBLAS
bf16xbf16->fp32 tier: same GEMM, but the fp32 accumulator is written out
unrounded. Unlike the upstream PR, the gate weight stays bf16, so the LoRA
Triton kernel dtype assert and the bf16 weight-broadcast path are unaffected.
Activated by ``additional_config["fp32_router_logits"] = True``; the launcher
sets this when ``inference.enable_fp32_router_logits`` is set. The flag is read
at module construction, where vLLM guarantees a ``set_current_vllm_config()``
context. No-op if something else already set an out_dtype (e.g. the ROCm AITER
branch, whose kernel wants matching dtypes).
"""
import torch
from vllm.config import get_current_vllm_config
from vllm.logger import init_logger
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MoE
logger = init_logger(__name__)
_original_init = DeepseekV2MoE.__init__
def _patched_init(self, *args, **kwargs):
_original_init(self, *args, **kwargs)
additional_config = get_current_vllm_config().additional_config or {}
if not additional_config.get("fp32_router_logits", False):
return
if self.gate.out_dtype is None:
self.gate.set_out_dtype(torch.float32)
DeepseekV2MoE.__init__ = _patched_init
logger.info("Installed fp32 router logits patch (self-gates on additional_config['fp32_router_logits']).")
def monkey_patch_dp_coordinator_startup_timeout():
"""Raise the DP coordinator startup timeout from vLLM's hard-coded 120s.
@@ -787,3 +850,124 @@ 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
+9 -5
View File
@@ -10,11 +10,15 @@ def setup_vllm_env(config: InferenceConfig):
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
# stays overridable.
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# Standard deployments use V2 for both capture modes. NIXL P/D also uses V2
# for sampling-mask capture, but router replay remains on V1 because vLLM
# rejects routed-expert capture with KV connectors and prime-rl's stitching
# patch is V1-only. setdefault keeps an explicit env-var choice authoritative.
if config.enable_return_sampling_mask:
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
elif config.vllm.enable_return_routed_experts:
use_v2_runner = config.deployment.type != "disaggregated"
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
# grammar-constrains generation (xgrammar structural tags) for tool_choice
@@ -0,0 +1,145 @@
from collections.abc import Iterable
import torch
def patch_gpt_oss_weight_loading() -> None:
"""Route GPT-OSS BF16 expert and sink weights through vLLM loaders.
Remove this patch when the pinned vLLM version uses weight loaders for these
prepared tensors in ``GptOssModel._load_weights_other``.
"""
from vllm.model_executor.layers.fused_moe.routed_experts import RoutedExperts
from vllm.model_executor.model_loader.weight_utils import (
default_weight_loader,
maybe_remap_moe_expert_param_name,
)
from vllm.model_executor.models import gpt_oss
original_load_weights = gpt_oss.GptOssModel._load_weights_other
if getattr(original_load_weights, "_prime_rl_uses_weight_loaders", False):
return
original_expert_weight_loader = RoutedExperts.weight_loader
def expert_weight_loader(
self,
param,
loaded_weight,
weight_name,
shard_id,
expert_id,
return_success=False,
):
if expert_id is None:
if shard_id is not None:
raise ValueError("A combined expert tensor must already be sharded")
if param.shape != loaded_weight.shape:
raise ValueError(
f"Combined expert tensor shape {tuple(loaded_weight.shape)} does not match "
f"parameter shape {tuple(param.shape)}"
)
param.copy_(loaded_weight)
return True if return_success else None
return original_expert_weight_loader(
self,
param,
loaded_weight,
weight_name,
shard_id,
expert_id,
return_success,
)
RoutedExperts.weight_loader = expert_weight_loader
def load_weights(
self,
ep_rank_end: int,
ep_rank_start: int,
heads_per_rank: int,
head_start: int,
weights: Iterable[tuple[str, torch.Tensor]],
stacked_params_mapping: list[tuple[str, ...]],
) -> set[str]:
params = dict(self.named_parameters())
loaded_params: set[str] = set()
use_ep = self.parallel_config.enable_expert_parallel
tp_size, tp_rank = gpt_oss.FusedMoEParallelConfig.flatten_tp_across_dp_and_pcp(
tp_size=gpt_oss.get_tensor_model_parallel_world_size(),
dp_size=gpt_oss.get_dp_group().world_size,
dp_rank=gpt_oss.get_dp_group().rank_in_group,
pcp_size=gpt_oss.get_pcp_group().world_size,
pcp_rank=gpt_oss.get_pcp_group().rank_in_group,
)
intermediate_size = self.config.intermediate_size
per_rank_intermediate_size = gpt_oss.cdiv(intermediate_size, tp_size)
tp_rank_start = tp_rank * per_rank_intermediate_size
tp_rank_end = min((tp_rank + 1) * per_rank_intermediate_size, intermediate_size)
def remaining_weights():
for name, weight in weights:
if not (
name.endswith((".w13_weight", ".w2_weight", ".w13_bias", ".w2_bias")) or name.endswith(".sinks")
):
yield name, weight
continue
name = maybe_remap_moe_expert_param_name(name, params)
if gpt_oss.is_pp_missing_parameter(name, self):
continue
param = params[name]
if name.endswith(".w13_weight"):
if use_ep:
weight = weight[ep_rank_start:ep_rank_end]
else:
weight = weight[:, :, 2 * tp_rank_start : 2 * tp_rank_end]
weight = weight.permute(0, 2, 1).contiguous()
elif name.endswith(".w2_weight"):
if use_ep:
weight = weight[ep_rank_start:ep_rank_end]
else:
weight = weight[:, tp_rank_start:tp_rank_end]
weight = weight.permute(0, 2, 1).contiguous()
elif name.endswith(".w13_bias"):
if use_ep:
weight = weight[ep_rank_start:ep_rank_end]
else:
weight = weight[:, 2 * tp_rank_start : 2 * tp_rank_end]
elif name.endswith(".w2_bias"):
if use_ep:
weight = weight[ep_rank_start:ep_rank_end]
elif tp_rank != 0:
weight = weight.zero_()
else:
weight = weight.narrow(0, head_start, heads_per_rank)
weight_loader = getattr(param, "weight_loader", default_weight_loader)
weight_loader(param, weight)
loaded_params.add(name)
continue
param.weight_loader(
param,
weight,
weight_name=name,
shard_id=None,
expert_id=None,
)
loaded_params.add(name)
loaded_params.update(
original_load_weights(
self,
ep_rank_end,
ep_rank_start,
heads_per_rank,
head_start,
remaining_weights(),
stacked_params_mapping,
)
)
return loaded_params
load_weights._prime_rl_uses_weight_loaders = True
gpt_oss.GptOssModel._load_weights_other = load_weights
+1 -5
View File
@@ -20,17 +20,13 @@ from prime_rl.utils.logger import get_logger
logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_dp_coordinator_startup_timeout,
monkey_patch_harmony_stop_token_propagation,
monkey_patch_nano_v3_reasoning_parser,
monkey_patch_strip_routed_experts_from_chat,
monkey_patch_tokenize_params_validation,
)
# NOTE: Fix harmony stop token propagation for GPT-OSS models
# Upstream issue still open: https://github.com/vllm-project/vllm/issues/22519
monkey_patch_harmony_stop_token_propagation()
# NOTE: Monkeypatch TokenizeParams to fix overly conservative validation
# Still needed in vLLM 0.20 — upstream rejects prompt_len > max_model_len - max_tokens
# Still needed in vLLM 0.28 — 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.
+31 -271
View File
@@ -3,22 +3,20 @@
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 and server-side ``max_tokens``
defaulting. We subclass it for the bits still missing from the upstream handler:
priority, ``data_parallel_rank`` header routing, server-side ``max_tokens``
defaulting and ``usage`` reporting. We subclass it for the bits still missing
from the upstream handler:
1. ``data_parallel_rank`` routing — read from the ``X-data-parallel-rank``
header and forwarded to ``engine_client.generate``. Upstream ``ServingTokens``
now does this too; we keep the equivalent path for the DP-replicated
inference servers prime-RL runs.
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. Compact ``routed_experts`` export — when the engine emits routing
decisions, surface them as base64 raw-byte payloads without requiring a vLLM
source fork.
3. Server-side ``max_tokens`` defaulting — upstream ``ServingTokens`` now applies
this itself (via ``GenerateRequest.is_sampling_param_provided`` +
``get_max_tokens``); we keep an equivalent guard so callers that omit
``max_tokens`` don't truncate at vLLM's 16-token ``SamplingParams`` default.
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.
@@ -26,16 +24,13 @@ delegates to upstream so we track future vLLM changes for free.
from __future__ import annotations
from collections.abc import AsyncGenerator, AsyncIterable
from functools import cached_property
from collections.abc import AsyncGenerator
from typing import Any
from fastapi import Request
from vllm.entrypoints.openai.engine.protocol import (
ErrorResponse,
PromptTokenUsageInfo,
RequestResponseMetadata,
UsageInfo,
)
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
@@ -43,25 +38,20 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateResponseChoice,
)
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
from vllm.outputs import RequestOutput
from vllm.sampling_params import RequestOutputKind, SamplingParams
from prime_rl.inference.vllm.routed_experts import RoutedExpertsCapture
class PrimeRlGenerateResponseChoice(GenerateResponseChoice):
routed_experts: dict[str, Any] | None = None
# Overrides upstream's base64 ``.npy`` string form with the compact
# ``{data, shape, start, dtype}`` object the PD router merges and the
# renderers parse.
routed_experts: dict[str, Any] | None = None # type: ignore[assignment]
class PrimeRlGenerateResponse(GenerateResponse):
choices: list[PrimeRlGenerateResponseChoice]
# Upstream ``GenerateResponse`` doesn't declare a ``usage`` field, so the
# parent ``ServingTokens.serve_tokens_full_generator`` constructs it and
# Pydantic silently drops it on serialization. Declare it here so the
# router can extract per-run token counts (and cached-prefix tokens) for
# platform billing — see https://github.com/PrimeIntellect-ai/router/pull/43.
usage: UsageInfo | None = None
class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
@@ -73,236 +63,29 @@ class _GenerateRoutedExpertsCapture(RoutedExpertsCapture):
)
for choice in response.choices
]
return PrimeRlGenerateResponse(
request_id=response.request_id,
choices=choices,
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
class _FinalOutputCapture:
"""Wraps a ``RequestOutput`` async generator to record the last yielded item.
Needed so the response builder can construct a ``usage`` block from
``final_res.prompt_token_ids`` / ``output.token_ids`` / ``num_cached_tokens``
after delegating iteration to upstream.
"""
def __init__(self, source: AsyncIterable[RequestOutput]) -> None:
# ``source`` may be any async-iterable — including
# ``_GenerateRoutedExpertsCapture``, which exposes the protocol via
# ``async def __aiter__`` (an async generator function) and has no
# ``__anext__`` method. Drive it through ``async for`` rather than
# poking ``__anext__`` directly so both shapes work.
self._source = source
self.final_res: RequestOutput | None = None
async def __aiter__(self) -> AsyncGenerator[RequestOutput, None]:
async for item in self._source:
self.final_res = item
yield item
def _build_usage(final_res: RequestOutput) -> UsageInfo:
assert final_res.prompt_token_ids is not None
num_prompt_tokens = len(final_res.prompt_token_ids)
if final_res.encoder_prompt_token_ids is not None:
num_prompt_tokens += len(final_res.encoder_prompt_token_ids)
num_generated_tokens = sum(len(output.token_ids) for output in final_res.outputs)
usage = UsageInfo(
prompt_tokens=num_prompt_tokens,
completion_tokens=num_generated_tokens,
total_tokens=num_prompt_tokens + num_generated_tokens,
)
# Always emit cached tokens when vLLM reports any. Upstream gates this on
# ``enable_prompt_tokens_details`` (default False) for OpenAI-API compat,
# but ``/inference/v1/generate`` is prime-rl internal — the cache-discount
# billing pipeline always wants the cached subset surfaced.
if final_res.num_cached_tokens:
usage.prompt_tokens_details = PromptTokenUsageInfo(cached_tokens=final_res.num_cached_tokens)
return usage
async def _client_set_max_tokens(raw_request: Request | None) -> bool:
"""Whether the inbound JSON body carried ``sampling_params.max_tokens``.
``GenerateRequest.sampling_params`` is parsed into a ``SamplingParams``
instance, which means an unset ``max_tokens`` is indistinguishable from
an explicit ``max_tokens=16`` once the request reaches the handler —
both surface as ``sampling_params.max_tokens == 16``. We re-read the
cached body to recover that distinction. When we can't (no raw_request,
non-JSON body, or read error), pessimistically assume the client did
set it so we never clobber an explicit value.
"""
if raw_request is None:
return True
try:
body = await raw_request.json()
except Exception:
return True
if not isinstance(body, dict):
return True
sp = body.get("sampling_params")
return isinstance(sp, dict) and "max_tokens" in sp
return PrimeRlGenerateResponse(**{**dict(response), "choices": choices})
class PrimeRlServingTokens(ServingTokens):
"""ServingTokens + DP-rank routing + compact routed experts + max_tokens defaulting."""
@cached_property
def _max_tokens_defaults(self) -> tuple[dict, int | None]:
"""Server-side ``max_tokens`` defaulting inputs, mirroring upstream ``ServingTokens``.
Computed lazily because ``custom_init_app_state`` swaps in this
subclass via ``object.__new__`` + ``__dict__.update`` (so our
``__init__`` never runs).
"""
diff = self.model_config.get_diff_sampling_param()
mc = self.model_config
override = (
diff.get("max_tokens")
if mc.generation_config not in ("auto", "vllm")
# Upstream uses ``getattr(..., {})`` directly. Defensive ``or {}``
# in case a downstream caller ever sets the attribute to ``None``
# (``getattr``'s default only fires when the attribute is missing,
# not when it exists with a ``None`` value).
else (getattr(mc, "override_generation_config", None) or {}).get("max_new_tokens")
)
return diff, override
"""ServingTokens + compact routed experts + PD kv_transfer_params bridging."""
async def serve_tokens(
self,
request: GenerateRequest,
raw_request: Request | None = None,
) -> PrimeRlGenerateResponse | ErrorResponse | AsyncGenerator[str, None]:
# Mirrors upstream ``ServingTokens.serve_tokens``. Diffs:
# (a) inject ``data_parallel_rank`` from the inbound header into
# ``engine_client.generate``; (b) default ``sampling_params.max_tokens``
# to ``max_model_len - prompt_len`` when the caller didn't set it; and
# (c) dispatch to our overridden response builder so ``routed_experts``
# makes it into the JSON.
error_check_ret = await self._check_model(request)
if error_check_ret is not None:
return error_check_ret
if self.engine_client.errored:
raise self.engine_client.dead_error
lora_request = self._maybe_get_adapters(request, supports_default_mm_loras=True)
model_name = self.models.model_name(lora_request)
request_id = f"generate-tokens-{self._base_request_id(raw_request, request.request_id)}"
request_metadata = RequestResponseMetadata(request_id=request_id)
if raw_request:
raw_request.state.request_metadata = request_metadata
# Build the engine input — features-aware (MM) or text-only fallback.
# Identical to upstream so we keep tracking it.
if features := request.features:
from vllm.entrypoints.scale_out.token_in_token_out.mm_serde import decode_mm_kwargs_item
from vllm.inputs import mm_input
from vllm.multimodal.inputs import (
MultiModalKwargsItem,
MultiModalKwargsItems,
PlaceholderRange,
)
mm_placeholders = {
modality: [PlaceholderRange(offset=p.offset, length=p.length) for p in ranges]
for modality, ranges in features.mm_placeholders.items()
}
mm_kwargs: dict[str, list[MultiModalKwargsItem | None]] = {}
if features.kwargs_data is not None:
for modality, items in features.kwargs_data.items():
mm_kwargs[modality] = [decode_mm_kwargs_item(item) if item is not None else None for item in items]
else:
for modality, hashes in features.mm_hashes.items():
mm_kwargs[modality] = [None] * len(hashes)
engine_input = mm_input(
prompt_token_ids=request.token_ids,
mm_kwargs=MultiModalKwargsItems(mm_kwargs),
mm_hashes=features.mm_hashes,
mm_placeholders=mm_placeholders,
cache_salt=request.cache_salt,
)
else:
(engine_input,) = await self.online_renderer.preprocess_completion(
request,
prompt_input=request.token_ids,
prompt_embeds=None,
skip_mm_cache=True,
)
sampling_params: SamplingParams = request.sampling_params
# 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`` — decode receives an empty NIXL handshake
# and ends up re-prefilling the prompt locally (~100× slower under
# concurrency). Bridge it through ``sampling_params.extra_args`` so the
# engine's KV connector picks the params up.
#
# Upstream fix: https://github.com/vllm-project/vllm/pull/42644 — drop
# this block once we pin a vLLM version that includes it.
) -> 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 = sampling_params.extra_args or {}
extra = request.sampling_params.extra_args or {}
extra["kv_transfer_params"] = request.kv_transfer_params
sampling_params.extra_args = extra
request.sampling_params.extra_args = extra
# Server-side ``max_tokens`` defaulting — see module docstring. Upstream
# ``ServingTokens`` now does this too; kept here so callers that omit
# ``max_tokens`` don't get capped at vLLM's 16-token ``SamplingParams``
# default.
if not await _client_set_max_tokens(raw_request):
diff_sp, override = self._max_tokens_defaults
sampling_params.max_tokens = get_max_tokens(
max_model_len=self.model_config.max_model_len,
max_tokens=None,
input_length=len(request.token_ids),
default_sampling_params=diff_sp,
override_max_tokens=override,
)
if self.force_no_detokenize:
sampling_params.detokenize = False
if request.stream:
sampling_params.output_kind = RequestOutputKind.DELTA
self._log_inputs(
request_id,
engine_input,
params=sampling_params,
lora_request=lora_request,
)
trace_headers = None if raw_request is None else await self._get_trace_headers(raw_request.headers)
result_generator = self.engine_client.generate(
engine_input,
sampling_params,
request_id,
lora_request=lora_request,
trace_headers=trace_headers,
priority=request.priority,
data_parallel_rank=self._get_data_parallel_rank(raw_request),
)
if request.stream:
# Streaming path: defer to upstream — prime-RL's renderer client
# only consumes the full response, so adding routed_experts to the
# streaming choice schema is unnecessary churn.
return self.serve_tokens_stream_generator(
request,
result_generator,
request_id,
model_name,
request_metadata,
)
return await self.serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
return await super().serve_tokens(request, raw_request)
async def serve_tokens_full_generator( # type: ignore[override]
self,
@@ -317,40 +100,17 @@ class PrimeRlServingTokens(ServingTokens):
# experts surface in the JSON.
capture: _GenerateRoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
start = request.sampling_params.routed_experts_prompt_start
capture = _GenerateRoutedExpertsCapture(
result_generator,
start=start,
start=request.sampling_params.routed_experts_prompt_start,
)
result_generator = capture
# Always capture the final ``RequestOutput`` so we can attach a
# ``usage`` block to the response. The router parses ``usage`` for
# per-run billing metrics; without it the cache-discount counter
# (``vllm_router_run_cached_prompt_tokens_total``) stays at zero.
final_capture = _FinalOutputCapture(result_generator)
result_generator = final_capture
response = await super().serve_tokens_full_generator(
request, result_generator, request_id, model_name, request_metadata
)
if not isinstance(response, GenerateResponse):
return response
if capture is not None:
if capture is not None and isinstance(response, GenerateResponse):
response = capture.post_process(response)
elif not isinstance(response, PrimeRlGenerateResponse):
# Upgrade to the prime-rl subclass so the declared ``usage`` field
# actually surfaces in JSON (the parent class would drop it).
response = PrimeRlGenerateResponse(
request_id=response.request_id,
choices=[PrimeRlGenerateResponseChoice(**choice.model_dump()) for choice in response.choices],
prompt_logprobs=response.prompt_logprobs,
kv_transfer_params=response.kv_transfer_params,
)
if final_capture.final_res is not None:
response.usage = _build_usage(final_capture.final_res)
return response
@@ -3,7 +3,6 @@ import os
from prime_rl.inference.patches import (
monkey_patch_fp32_lm_head,
monkey_patch_fp32_router_logits,
monkey_patch_minimax_m2_for_lora,
monkey_patch_no_moe_lora,
)
@@ -21,6 +20,3 @@ else:
# Install fp32 lm_head patch; self-gates on additional_config["fp32_lm_head"] at call time
monkey_patch_fp32_lm_head()
# Install fp32 router logits patch; self-gates on additional_config["fp32_router_logits"]
monkey_patch_fp32_router_logits()
+1 -1
View File
@@ -51,7 +51,7 @@ def receive_state_dict(communicator: PyNcclCommunicator) -> Generator[tuple[str,
# Split concatenated tensor back into individual tensors
offset = 0
for key, shape, numel in tensor_info_list:
tensor = concatenated[offset : offset + numel].view(shape).clone()
tensor = concatenated[offset : offset + numel].view(shape)
offset += numel
try:
yield key, tensor
+52 -106
View File
@@ -13,17 +13,21 @@ from typing import TYPE_CHECKING, Any, cast
import torch
import torch.nn as nn
from modelexpress import p2p_pb2
from modelexpress.client import MxClient
from vllm.config import set_current_vllm_config
from vllm.logger import init_logger
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
from prime_rl.transports.weights.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
size_cuda_buffers,
use_cuda_malloc_pool,
from prime_rl.transports.weights.nixl.agent import (
MemDesc,
NixlAgent,
NixlPeer,
PreparedRead,
group_notification,
make_agent_name,
set_ucx_env_defaults,
)
from prime_rl.transports.weights.nixl.cuda_malloc_memory import use_cuda_malloc_pool
from prime_rl.transports.weights.nixl.graph import (
Destination,
OperationChain,
@@ -44,7 +48,6 @@ else:
Worker = object
logger = init_logger("vllm.inference.vllm.worker_nixl")
_BUFFER_POLL_INTERVAL = 0.01
@dataclass
@@ -69,13 +72,14 @@ class LayerWeightTransferPlan:
class WeightTransferGroup:
name: str
layers: list[LayerWeightTransferPlan]
pulls: list[tuple[Any, Any, list[int]]]
pulls: list[PreparedRead]
@dataclass
class WeightTransferPlan:
receive_arenas: dict[torch.dtype, torch.Tensor]
receive_buffer_count: int
trainer_peers: list[NixlPeer]
groups: list[WeightTransferGroup]
@@ -100,7 +104,7 @@ class NIXLWeightUpdateWorker(Worker):
del inference_world_size, quantize_in_weight_transfer
global_rank = rank_offset + self.device.index
server_url = f"{host}:{port}"
set_ucx_env_defaults()
set_ucx_env_defaults(self.device.index)
self.nixl_agent = NixlAgent(make_agent_name("inference", global_rank))
self.model_express = ModelExpressSession(
client=MxClient(server_url=server_url),
@@ -109,6 +113,7 @@ class NIXLWeightUpdateWorker(Worker):
session_id=session_id,
worker_id=f"inference-{global_rank}",
)
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
self.weight_transfer_timeout = timeout
self.weight_transfer_plan: WeightTransferPlan | None = None
logger.info(
@@ -126,30 +131,13 @@ class NIXLWeightUpdateWorker(Worker):
trainer_ref = self.model_express.wait_for(
"trainer",
count=1,
status=None,
timeout=self.weight_transfer_timeout,
)[0]
table = TrainerTensorTable.decode(self.model_express.fetch(trainer_ref).nixl_metadata)
copies = self.trace_weight_loads(table)
plan = self.build_transfer_plan(table, copies)
self.buffer_sessions = []
for buffer_index in range(table.staging_buffer_count):
session = ModelExpressSession(
client=self.model_express.client,
role="inference",
rank=self.model_express.rank,
session_id=f"{self.model_express.session_id}:layers:{buffer_index}",
worker_id=f"inference-buffer-{self.model_express.rank}-{buffer_index}",
)
session.publish()
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.buffer_sessions.append(session)
# Join the current generation directly. Publishing a transient READY
# before the first pull would let the trainer mistake initialization
# for a completed acknowledgement.
self.model_express.publish(nixl_metadata=self.nixl_agent.get_metadata())
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.weight_transfer_plan = plan
self.group_generations = [0] * len(plan.groups)
logger.info(
"Initialized NIXL transfer plan on rank %d with %d groups",
self.model_express.rank,
@@ -255,14 +243,16 @@ class NIXLWeightUpdateWorker(Worker):
copies,
replay_plans,
)
receive_buffer_count = self.choose_receive_buffer_count(
receive_buffer_elements,
table.staging_buffer_count,
)
receive_buffer_count = table.staging_buffer_count
receive_arenas = self.allocate_receive_arenas(
receive_buffer_elements,
receive_buffer_count,
)
peers: list[NixlPeer] = []
for agent in table.agents:
peer = self.nixl_agent.add_remote_agent(agent.metadata)
self.nixl_agent.make_connection(peer)
peers.append(peer)
groups = self.build_transfer_groups(
table,
copies,
@@ -270,10 +260,12 @@ class NIXLWeightUpdateWorker(Worker):
receive_buffer_elements,
receive_arenas,
receive_buffer_count,
peers,
)
return WeightTransferPlan(
receive_arenas=receive_arenas,
receive_buffer_count=receive_buffer_count,
trainer_peers=peers,
groups=groups,
)
@@ -310,31 +302,6 @@ class NIXLWeightUpdateWorker(Worker):
group_elements[source_dtype][tensor_groups[source.name]] += prod(replay_plans[id(copy)].source_shape)
return {dtype: max(elements, default=0) for dtype, elements in group_elements.items()}
def choose_receive_buffer_count(
self,
receive_buffer_elements: dict[torch.dtype, int],
staging_buffer_count: int,
) -> int:
receive_buffer_bytes = max(
1,
sum(elements * dtype.itemsize for dtype, elements in receive_buffer_elements.items()),
)
allocated_bytes = torch.cuda.memory_allocated(self.device)
peak_growth_bytes = max(
0,
torch.cuda.max_memory_allocated(self.device) - allocated_bytes,
)
free_bytes, _ = torch.cuda.mem_get_info(self.device)
max_receive_buffers = min(2, staging_buffer_count) if peak_growth_bytes else 1
if peak_growth_bytes or free_bytes < receive_buffer_bytes:
torch.cuda.empty_cache()
return size_cuda_buffers(
receive_buffer_bytes,
max_receive_buffers,
self.device,
extra_headroom_bytes=receive_buffer_bytes + peak_growth_bytes,
)
def allocate_receive_arenas(
self,
receive_buffer_elements: dict[torch.dtype, int],
@@ -362,6 +329,7 @@ class NIXLWeightUpdateWorker(Worker):
receive_buffer_elements: dict[torch.dtype, int],
receive_arenas: dict[torch.dtype, torch.Tensor],
receive_buffer_count: int,
peers: list[NixlPeer],
) -> list[WeightTransferGroup]:
tensors = {tensor.name: tensor for group in table.groups for tensor in group.tensors}
tensor_groups = {
@@ -390,7 +358,6 @@ class NIXLWeightUpdateWorker(Worker):
)
agent_devices = {agent_index: agent.device_id for agent_index, agent in enumerate(table.agents)}
peer_names: dict[int, str] = {}
transfer_groups: list[WeightTransferGroup] = []
for group_index, group in enumerate(table.groups):
@@ -432,10 +399,9 @@ class NIXLWeightUpdateWorker(Worker):
persistent_plans_by_layer,
),
pulls=self.prepare_group_pulls(
table,
local_descs,
remote_descs,
peer_names,
peers,
),
)
)
@@ -486,40 +452,37 @@ class NIXLWeightUpdateWorker(Worker):
def prepare_group_pulls(
self,
table: TrainerTensorTable,
local_descs: dict[int, list[MemDesc]],
remote_descs: dict[int, list[MemDesc]],
peer_names: dict[int, str],
) -> list[tuple[Any, Any, list[int]]]:
pulls: list[tuple[Any, Any, list[int]]] = []
for agent_index, remote in sorted(remote_descs.items()):
peer_name = peer_names.get(agent_index)
if peer_name is None:
peer_name = self.nixl_agent.add_remote_agent(table.agents[agent_index].metadata)
self.nixl_agent.make_connection(peer_name)
peer_names[agent_index] = peer_name
peers: list[NixlPeer],
) -> list[PreparedRead]:
pulls: list[PreparedRead] = []
agent_indices = sorted(remote_descs)
rotation = self.model_express.rank % len(agent_indices) if agent_indices else 0
agent_indices = agent_indices[rotation:] + agent_indices[:rotation]
for agent_index in agent_indices:
remote = remote_descs[agent_index]
peer = peers[agent_index]
local_prepared = self.nixl_agent.prepare_xfer_dlist(local_descs[agent_index])
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, agent_name=peer_name)
pulls.append((local_prepared, remote_prepared, list(range(len(remote)))))
remote_prepared = self.nixl_agent.prepare_xfer_dlist(remote, peer=peer)
pulls.append(
self.nixl_agent.prepare_read(
local_prepared,
list(range(len(remote))),
remote_prepared,
)
)
return pulls
@torch.no_grad()
def update_weights_from_path(self, weight_dir: str | None = None) -> None:
del weight_dir
plan = self.initialize_transfer()
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.model_express.wait_for(
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_READY,
timeout=self.weight_transfer_timeout,
)
started = time.perf_counter()
self.apply_transfer_plan(plan)
update_mla_absorbed_weights(self.raw_model)
torch.cuda.synchronize(self.device)
self.model_express.set_status(p2p_pb2.SOURCE_STATUS_READY)
logger.info(
"Applied NIXL policy update on rank %d in %.2fs",
self.model_express.rank,
@@ -542,44 +505,30 @@ class NIXLWeightUpdateWorker(Worker):
def pull_group(group_index: int) -> WeightTransferGroup:
transfer_group = plan.groups[group_index]
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
session.wait_for(
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_READY,
notification = group_notification(group_index, self.group_generations[group_index])
self.nixl_agent.wait_for_notification(
plan.trainer_peers,
notification,
timeout=self.weight_transfer_timeout,
poll_interval=_BUFFER_POLL_INTERVAL,
cancelled=cancelled.is_set,
)
for local, remote, indices in transfer_group.pulls:
handle = self.nixl_agent.post_read(local, indices, remote)
for read in transfer_group.pulls:
self.nixl_agent.post_read(read, notification)
for read in transfer_group.pulls:
self.nixl_agent.wait(
handle,
read,
context=f"weight pull for {transfer_group.name}",
timeout=self.weight_transfer_timeout,
cancelled=cancelled.is_set,
)
return transfer_group
def acknowledge_group(group_index: int) -> None:
session = self.buffer_sessions[group_index % len(self.buffer_sessions)]
session.set_status(p2p_pb2.SOURCE_STATUS_READY)
session.wait_for(
"trainer",
count=1,
status=p2p_pb2.SOURCE_STATUS_INITIALIZING,
timeout=self.weight_transfer_timeout,
poll_interval=_BUFFER_POLL_INTERVAL,
cancelled=cancelled.is_set,
)
session.set_status(p2p_pb2.SOURCE_STATUS_INITIALIZING)
self.group_generations[group_index] += 1
return transfer_group
def prefetch_group(group_index: int) -> WeightTransferGroup:
torch.cuda.set_device(self.device)
transfer_group = pull_group(group_index)
acknowledge_group(group_index)
return transfer_group
return pull_group(group_index)
def replay_group(transfer_group: WeightTransferGroup) -> None:
for layer_plan in transfer_group.layers:
@@ -625,9 +574,6 @@ class NIXLWeightUpdateWorker(Worker):
replay_group(transfer_group)
torch.cuda.synchronize(self.device)
if not pipelined:
acknowledge_group(group_index)
finally:
cancelled.set()
if executor is not None:
+13 -3
View File
@@ -45,6 +45,7 @@ async def setup(
file: FileMonitorConfig | None = None,
*,
output_dir: Path,
producer: str | None = None,
run_config: BaseConfig | None = None,
train_env_names: list[str] | None = None,
eval_env_names: list[str] | None = None,
@@ -79,7 +80,7 @@ async def setup(
)
)
if file is not None:
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir)))
monitors.append(("file", FileMonitor(file), dict(output_dir=output_dir, producer=producer)))
if not monitors:
return
@@ -99,7 +100,7 @@ def get(monitor_cls: type[Monitor]) -> Monitor | None:
@overload
async def log(data: dict[str, Any], step: int) -> None: ...
async def log(data: dict[str, Any], step: int | None) -> None: ...
@overload
@@ -108,7 +109,7 @@ async def log(data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset
async def log(
data: dict[str, Any] | vf.Episode | list[vf.Episode],
step: int,
step: int | None,
kind: Kind = "train",
subset: Subset = "effective",
) -> None:
@@ -121,6 +122,15 @@ async def log(
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def log_annotations(updates: list[dict[str, Any]]) -> None:
"""Log trace updates to all registered monitors."""
for monitor in MONITORS:
try:
await monitor.log_annotations(updates)
except Exception as e:
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def finalize() -> None:
"""Finalize the run on all registered monitors."""
for monitor in MONITORS:
+10 -4
View File
@@ -24,7 +24,7 @@ class Monitor(ABC):
"""Initialize run. Overrides name their own kwargs."""
@overload
async def log(self, data: dict[str, Any], step: int) -> None: ...
async def log(self, data: dict[str, Any], step: int | None) -> None: ...
@overload
async def log(self, data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None: ...
@@ -32,7 +32,7 @@ class Monitor(ABC):
async def log(
self,
data: dict[str, Any] | vf.Episode | list[vf.Episode],
step: int,
step: int | None,
kind: Kind = "train",
subset: Subset = "effective",
) -> None:
@@ -41,15 +41,21 @@ class Monitor(ABC):
await self.log_metrics(data, step=step)
else:
episodes = data if isinstance(data, list) else [data]
assert step is not None
await self.log_episodes(episodes, step=step, kind=kind, subset=subset)
@abstractmethod
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
"""Log scalar metrics."""
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
"""Log scalar metrics. ``step=None`` logs a time-keyed row (e.g. inference
metrics, which are sampled on wall time rather than the training step)."""
@abstractmethod
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Log episodes."""
async def log_annotations(self, updates: list[dict[str, Any]]) -> None:
"""Log trace updates — post-hoc facts about traces this run already logged.
Monitors that only carry scalars ignore them."""
async def finalize(self) -> None:
"""Finalize run."""
-62
View File
@@ -1,62 +0,0 @@
from __future__ import annotations
import asyncio
import json
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, TextIO
import orjson
from prime_rl.configs.monitors import FileMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.utils.utils import sanitize
if TYPE_CHECKING:
import verifiers.v1 as vf
class FileMonitor(Monitor):
"""Logs metrics and episodes to local JSONL files."""
config: FileMonitorConfig
file: TextIO
async def init(self, output_dir: Path) -> None:
self.output_dir = output_dir
self.path = output_dir / self.config.path
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
sanitized, dropped = sanitize(metrics)
if dropped:
self.logger.warning(
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
)
row = {"step": step, "time": time.time(), **sanitized}
self.file.write(json.dumps(row) + "\n")
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Append the cohort to its per-step episode file. ``all`` grows one
episode at a time as they complete, ``effective`` one batch at a time on finalize,
so an in-progress run can be inspected live. Episode-level failures are
preserved even when no trace was produced."""
def write() -> None:
path = self.output_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "ab") as f:
for episode in episodes:
f.write(orjson.dumps(episode.to_record(), default=str, option=opts))
# Record serialization is heavy pure-Python work; keep it off the event loop.
# Awaited (not fire-and-forget) so appends to one file never interleave.
await asyncio.to_thread(write)
async def finalize(self) -> None:
self.logger.info(f"Finalized metrics at {self.path}")
+3
View File
@@ -0,0 +1,3 @@
from prime_rl.monitors.file.monitor import FileMonitor
__all__ = ["FileMonitor"]
+115
View File
@@ -0,0 +1,115 @@
from __future__ import annotations
import asyncio
import json
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, BinaryIO, TextIO
import orjson
from prime_rl.configs.monitors import FileMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.file.traces import get_annotations_dir, get_index_path, get_trace_stream
from prime_rl.monitors.file.traces.chunks import ChunkedJsonl
from prime_rl.monitors.file.traces.index import index_row
from prime_rl.monitors.file.traces.update import update_index_row
from prime_rl.utils.pathing import get_file_monitor_dir
from prime_rl.utils.utils import sanitize
if TYPE_CHECKING:
import verifiers.v1 as vf
OPTS = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
class FileMonitor(Monitor):
"""Logs metrics and episodes to local JSONL files."""
config: FileMonitorConfig
file: TextIO
async def init(self, output_dir: Path, producer: str | None = None) -> None:
self.output_dir = output_dir
self.producer = producer
index = get_index_path(get_trace_stream(output_dir))
# a relaunch appends to the stream it finds, so the numbering carries on
self._logged = sum(1 for _ in index.open("rb")) if index.is_file() else 0
self.path = get_file_monitor_dir(output_dir) / self.config.path
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self._streams: dict[Path, tuple[ChunkedJsonl, BinaryIO]] = {}
self.logger.info(f"Logging metrics and episodes to the local filesystem ({output_dir})")
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
"""``step=None`` logs a time-keyed row (e.g. inference metrics, which are
sampled on wall time rather than the training step)."""
sanitized, dropped = sanitize(metrics)
if dropped:
self.logger.warning(
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
)
row = {"step": step, "time": time.time(), **sanitized}
if self.producer is not None:
row["producer"] = self.producer
self.file.write(json.dumps(row) + "\n")
def _stream(self, directory: Path) -> tuple[ChunkedJsonl, BinaryIO]:
"""A stream and its index, opened on first use and kept open. Writers flush the
stream before the index: a row a reader sees points at a record it can read."""
if directory not in self._streams:
stream = ChunkedJsonl(directory, self.config.chunk_bytes, self.config.compress)
self._streams[directory] = (stream, open(get_index_path(directory), "ab"))
return self._streams[directory]
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Append each episode to the trace stream as it completes — every episode is
serialized exactly once, in arrival order, whatever its kind, so an in-progress
run can be tailed. Episode-level failures are preserved even when no trace was
produced. The shipped cohort writes no second copy: what it learns arrives as
annotations that readers fold back onto the stream."""
if subset == "effective":
return
def write() -> None:
stream, index = self._stream(get_trace_stream(self.output_dir))
# An index row goes out with every episode: summarising the record here,
# while it is already in hand, saves every reader from parsing a stream
# that outgrows memory long before the run does.
for episode in episodes:
record = episode.to_record(float_decimals=self.config.float_decimals)
chunk, offset = stream.append(orjson.dumps(record, default=str, option=OPTS))
self._logged += 1
index.write(orjson.dumps(index_row(self._logged, record, chunk, offset), default=str, option=OPTS))
stream.flush()
index.flush()
# Record serialization is heavy pure-Python work; keep it off the event loop.
# Awaited (not fire-and-forget) so appends to one stream never interleave.
await asyncio.to_thread(write)
async def log_annotations(self, updates: list[dict[str, Any]]) -> None:
"""Append trace updates to this producer's annotation stream — one writer per
stream, so producers never interleave."""
if not updates:
return
def write() -> None:
stream, index = self._stream(get_annotations_dir(self.output_dir) / (self.producer or "unknown"))
# the scalars go to a sibling index so a reader can answer "which cohort,
# what credit" without touching the token streams
for update in updates:
chunk, offset = stream.append(orjson.dumps(update, option=OPTS))
index.write(orjson.dumps(update_index_row(update, chunk, offset), option=OPTS))
stream.flush()
index.flush()
await asyncio.to_thread(write)
async def finalize(self) -> None:
for stream, index in self._streams.values():
stream.close()
index.close()
self.logger.info(f"Finalized metrics at {self.path}")
@@ -0,0 +1,33 @@
"""Where the file monitor puts the traces, and everything written about them.
The stream and its annotations live under one directory so nothing beside them has to
be read as belonging to them. Each stream is a directory of chunks (see ``chunks``),
and every index is named for the stream it indexes and sits beside it.
"""
from pathlib import Path
from prime_rl.utils.pathing import get_file_monitor_dir
def get_trace_dir(output_dir: Path) -> Path:
return get_file_monitor_dir(output_dir) / "traces"
def get_trace_stream(output_dir: Path) -> Path:
"""Every episode, appended as it arrives."""
return get_trace_dir(output_dir) / "stream"
def get_annotations_dir(output_dir: Path) -> Path:
"""One stream per producer of trace updates: orch ship-time facts, trainer streams."""
return get_trace_dir(output_dir) / "annotations"
def get_index_path(stream: Path) -> Path:
"""A stream's index, beside it, so a reader pairs the two without knowing who
wrote them."""
return stream.with_name(stream.name.removesuffix(".jsonl") + ".index.jsonl")
__all__ = ["get_annotations_dir", "get_index_path", "get_trace_dir", "get_trace_stream"]
+115
View File
@@ -0,0 +1,115 @@
"""Chunked JSONL — an append-only stream split into numbered files, sealed as it grows.
stream/00000.jsonl.zst sealed: zstd in seekable frames, so a reader still lands on one line
stream/00001.jsonl live: plain text, so it can be tailed
A line never spans chunks. Once a chunk reaches its size the writer moves on and seals it
in the background: the compressed twin is written beside it and the plain file removed
only once the twin is complete, so a reader that misses the plain file finds the sealed
one. ``zstd -dcf stream/* | jq`` reads a whole stream, sealed and live alike.
"""
import shutil
import threading
from pathlib import Path
from typing import BinaryIO
import pyzstd
LEVEL = 3
"""zstd level: ~7x on episode records at hundreds of MB/s, so sealing keeps up with a run."""
FRAME_BYTES = 4 << 20
"""Independent frames in a sealed chunk: a seek decompresses one of these, not the chunk."""
def chunk_path(directory: Path, number: int) -> Path:
return directory / f"{number:05d}.jsonl"
def chunk_numbers(directory: Path) -> dict[int, bool]:
"""Chunk number -> whether its plain file is present (a sealed chunk has none)."""
numbers: dict[int, bool] = {}
for path in directory.glob("*.jsonl*"):
number = int(path.name.split(".", 1)[0])
numbers[number] = numbers.get(number, False) or path.suffix == ".jsonl"
return numbers
def open_chunk(directory: Path, number: int) -> BinaryIO:
"""A chunk for seeking reads, whether still plain or already sealed."""
path = chunk_path(directory, number)
try:
return open(path, "rb")
except FileNotFoundError:
return pyzstd.SeekableZstdFile(path.with_name(path.name + ".zst"), "rb")
def seal(path: Path) -> None:
"""Compress a finished chunk beside itself, then drop the plain file."""
target = path.with_name(path.name + ".zst")
partial = target.with_name(target.name + ".tmp")
with (
open(path, "rb") as src,
pyzstd.SeekableZstdFile(partial, "wb", level_or_option=LEVEL, max_frame_content_size=FRAME_BYTES) as dst,
):
shutil.copyfileobj(src, dst, 1 << 20)
partial.replace(target)
path.unlink()
class ChunkedJsonl:
"""Appends lines to the live chunk of a stream and reports where each one landed."""
def __init__(self, directory: Path, max_bytes: int, compress: bool) -> None:
directory.mkdir(parents=True, exist_ok=True)
self.directory = directory
self.max_bytes = max_bytes
self.compress = compress
self._sealing: list[threading.Thread] = []
numbers = chunk_numbers(directory)
last = max(numbers, default=-1)
# A relaunch appends to the live chunk it finds and starts a new one after a sealed
# last chunk; anything else still plain was left mid-seal by a crash.
self.number = last if numbers.get(last) else last + 1
for number, plain in numbers.items():
if plain and number != self.number and compress:
self._seal(number)
self.file = open(chunk_path(directory, self.number), "ab")
self.size = self.file.tell()
def append(self, line: bytes) -> tuple[int, int]:
"""Write one line; returns ``(chunk, offset)``, the address a reader seeks to."""
if self.size and self.size + len(line) > self.max_bytes:
self._roll()
offset = self.size
self.file.write(line)
self.size += len(line)
return self.number, offset
def flush(self) -> None:
self.file.flush()
def close(self) -> None:
"""Seal the live chunk too, so a finished run keeps nothing plain."""
self.file.close()
if not self.size:
chunk_path(self.directory, self.number).unlink()
elif self.compress:
self._seal(self.number)
for thread in self._sealing:
thread.join()
def _roll(self) -> None:
self.file.close()
if self.compress:
self._seal(self.number)
self.number += 1
self.file = open(chunk_path(self.directory, self.number), "ab")
self.size = 0
def _seal(self, number: int) -> None:
# not a daemon: a process that exits mid-seal waits for it rather than leaving a torn twin
thread = threading.Thread(target=seal, args=(chunk_path(self.directory, number),))
thread.start()
self._sealing.append(thread)
+134
View File
@@ -0,0 +1,134 @@
"""The episode index - one compact row per episode, so a reader never has to parse
the stream to browse it.
The file monitor writes a row as each episode lands, when the record is already in
hand and summarising it is nearly free, and records the chunk and byte offset it wrote
the episode at so a reader can seek straight to one. A stream another producer wrote
has no index, so its reader derives the same rows itself.
"""
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
if isinstance(obj.get("duration"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
for key, value in obj.items():
if isinstance(value, dict):
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
def episode_kind(rec: dict) -> str:
"""The kind of work an episode did. The file monitor stamps it as the episode
lands; a stream written by another producer (a verifiers ``uv run eval`` run) is
read off its run info instead."""
for trace in rec.get("traces") or []:
if (kind := (trace.get("info") or {}).get("kind")) in ("train", "eval"):
return kind
run = rec.get("run") or {}
return (run.get("work") or {}).get("type") or run.get("type") or "eval"
def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
"""One index row: what the table, the filters, the chart and the sort need.
``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
stop_condition = None
reward_parts: dict[str, list[float]] = {}
metric_parts: dict[str, list[float]] = {}
timing: dict[str, float] = {}
costs: list[float] = []
for trace in rec.get("traces") or []:
costs.extend(
usage["cost"]
for call in trace.get("calls") or []
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
)
nodes = trace.get("nodes") or []
parents = {node.get("parent") for node in nodes if "parent" in node}
branches += max(0, len(nodes) - len(parents))
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
rewards.append(
sum(
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
for r in trace["rewards"].values()
if isinstance(r, dict)
)
)
for name, r in (trace.get("rewards") or {}).items():
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
reward_parts.setdefault(name, []).append(r["score"])
for name, value in (trace.get("metrics") or {}).items():
if isinstance(value, (int, float)):
metric_parts.setdefault(name, []).append(value)
if isinstance(trace.get("timing"), dict):
walk_timing(trace["timing"], "", timing)
advantage = (trace.get("info") or {}).get("advantage")
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)
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
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
return {
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
"metrics": {name: sum(v) / len(v) for name, v in metric_parts.items()},
"timing": timing,
"cost": sum(costs) if costs else None,
"line": line,
"offset": offset,
"id": rec.get("id"),
"kind": episode_kind(rec),
"trace_ids": [trace_id for trace in rec.get("traces") or [] if (trace_id := trace.get("id"))],
"env": (rec.get("env") or {}).get("id") or (rec.get("env") or {}).get("name"),
"group": (rec.get("group") or {}).get("id"),
"ok": rec.get("ok"),
"num_errors": len(rec.get("errors") or []),
"reward": sum(rewards) / len(rewards) if rewards else None,
"advantage": sum(advantages) / len(advantages) if advantages else None,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"turns": turns,
"branches": branches,
"stop_condition": stop_condition,
# when the episode landed and how long it was alive: the stream's x axis,
# and the one duration worth sorting a stream by
"arrival": (first_info.get("arrival") or {}).get("time"),
"duration": _episode_duration(first_info, timing),
}
def _episode_duration(info: dict, timing: dict[str, float]) -> float | None:
"""Wall-clock seconds from dispatch to arrival, or the summed phases for a record
that predates those stamps."""
dispatched = (info.get("dispatch") or {}).get("time")
arrived = (info.get("arrival") or {}).get("time")
if isinstance(dispatched, (int, float)) and isinstance(arrived, (int, float)):
return max(0.0, arrived - dispatched)
phases = [value for key, value in timing.items() if "/" not in key]
return sum(phases) if phases else None
def index_row(line: int, rec: dict, chunk: int, offset: int) -> dict:
"""The row the file monitor writes. The nested reward/metric/timing maps are left
out: only the per-episode series view needs them, and they dominate the size."""
row = summarize_episode(line, rec, offset)
row["chunk"] = chunk
for key in ("rewards", "metrics", "timing"):
row.pop(key, None)
return row
+100
View File
@@ -0,0 +1,100 @@
"""Trace updates — post-hoc facts about a completed trace, recorded beside it.
An episode is serialized once, when it arrives. Everything a consumer learns later
is an update naming the trace: an ``info`` dict merged into the trace's own, plus
per-token streams over a branch, full-length across the branch's token prefix (nulls
mark unknown positions, so a stream never depends on the producer's loss mask).
Each producer appends its own stream under the trace directory's ``annotations/``, so
every stream has exactly one writer. Readers fold the updates onto the arrival records
in write order, newest wins.
"""
from typing import Any
UPDATE_VERSION = 1
STREAM_FIELDS = ("advantages", "trainer_logprobs", "entropies")
"""Per-token streams an update may carry, compacted onto node fields of the same name."""
def update_index_row(update: dict[str, Any], chunk: int, offset: int) -> dict[str, Any]:
"""An update's scalars plus where its record sits. The per-token streams stay in
the annotation stream: a reader browsing a run needs the scalars, and only the
episode it opens needs the streams."""
return {"trace_id": update.get("trace_id"), "chunk": chunk, "offset": offset, "info": update.get("info") or {}}
def make_update(
trace_id: str,
*,
info: dict[str, Any] | None = None,
branches: dict[int, dict[str, list]] | None = None,
) -> dict[str, Any]:
"""One update record. ``branches`` maps a branch index to its token streams."""
return {
"version": UPDATE_VERSION,
"trace_id": trace_id,
"info": info or {},
"branches": [{"index": index, **streams} for index, streams in (branches or {}).items()],
}
def branch_node_paths(nodes: list[dict]) -> list[list[int]]:
"""Root-to-leaf node indexes, one path per branch, in leaf order."""
if not nodes:
return []
parents = {parent for node in nodes if isinstance((parent := node.get("parent")), int) and 0 <= parent < len(nodes)}
paths = []
for leaf in (index for index in range(len(nodes)) if index not in parents):
path: list[int] = []
seen: set[int] = set()
node_index: int | None = leaf
while isinstance(node_index, int) and 0 <= node_index < len(nodes) and node_index not in seen:
seen.add(node_index)
path.append(node_index)
node_index = nodes[node_index].get("parent")
paths.append(list(reversed(path)))
return paths
def _deep_merge(old: Any, new: Any) -> Any:
if isinstance(old, dict) and isinstance(new, dict):
return {**old, **{key: _deep_merge(old.get(key), value) for key, value in new.items()}}
return new
def fold_trace_updates(trace: dict, updates: list[dict]) -> int:
"""Apply updates onto a raw trace record in write order, newest winning.
Merges each ``info`` and projects every branch stream onto the branch's nodes,
compact over each node's mask like the node's own ``logprobs``. A node takes a
stream only when it is fully covered with non-null values at every sampled
position, so a truncated stream leaves the tail nodes untouched. Returns how many
nodes carry trainer logprobs afterwards."""
nodes = trace.get("nodes") or []
paths = branch_node_paths(nodes)
for update in updates:
if update.get("info"):
trace["info"] = _deep_merge(trace.get("info") or {}, update["info"])
for branch in update.get("branches") or []:
branch_index = branch.get("index")
if not isinstance(branch_index, int) or not 0 <= branch_index < len(paths):
continue
for field in STREAM_FIELDS:
stream = branch.get(field)
if not stream:
continue
cursor = 0
for node_index in paths[branch_index]:
node = nodes[node_index]
token_ids = node.get("token_ids") or []
span = stream[cursor : cursor + len(token_ids)]
cursor += len(token_ids)
if len(span) < len(token_ids):
break
values = [v for v, sampled in zip(span, node.get("mask") or []) if sampled]
if not values or any(v is None for v in values):
continue
node[field] = values
return sum(1 for node in nodes if node.get("trainer_logprobs"))
+81 -292
View File
@@ -1,327 +1,116 @@
from __future__ import annotations
import asyncio
import atexit
import io
import json
import os
from datetime import datetime, timezone
from typing import Any, Coroutine
from typing import TYPE_CHECKING, Any
import httpx
import pyarrow as pa
import pyarrow.parquet as pq
import verifiers.v1 as vf
from prime_cli.core.config import Config as PrimeConfig
from verifiers.v1.utils.platform import build_samples
import prime_runs as pr
from prime_rl.configs.monitors import PrimeMonitorConfig
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.utils import sanitize
BASE_URL = "https://api.primeintellect.ai/api/v1/rft"
BASE_URL_VAR = "PRIME_API_BASE"
API_KEY_VAR = "PRIME_API_KEY"
if TYPE_CHECKING:
import verifiers.v1 as vf
SAMPLE_SCHEMA = pa.schema(
[
("run_id", pa.string()),
("step", pa.int64()),
("tag", pa.string()),
("problem_id", pa.int64()),
("sample_id", pa.int64()),
("prompt", pa.string()),
("completion", pa.string()),
("trajectory", pa.string()),
("answer", pa.string()),
("env_name", pa.string()),
("task", pa.string()),
("info", pa.string()),
("reward", pa.float64()),
("advantage", pa.float64()),
("metrics", pa.string()),
("timing", pa.string()),
("num_input_tokens", pa.int64()),
("num_output_tokens", pa.int64()),
("created_at", pa.timestamp("us", tz="UTC")),
]
)
BASE_URL_VAR = "PRIME_API_BASE"
# 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.
FINISH_TIMEOUT = 60.0
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."""
base = os.getenv(BASE_URL_VAR)
return base.rstrip("/").removesuffix("/rft") if base else None
class PrimeMonitor(Monitor):
"""Logs metrics and episodes to the Prime platform.
"""Logs metrics and episodes to the Prime platform through ``prime_runs``.
Uploads are fire-and-forget tasks on the caller's event loop — the prime
monitor only runs in the orchestrator, whose call sites are all async. The
platform calls and the episode serialization run in worker threads via
``asyncio.to_thread``, so they never stall the loop.
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.
``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
and backpressure, so they never stall the loop.
"""
config: PrimeMonitorConfig
run: pr.Run
async def init(self, config: BaseConfig | None = None) -> None:
api_key = os.getenv(API_KEY_VAR) or PrimeConfig().api_key
if not api_key:
raise RuntimeError(f"API key not found - set {API_KEY_VAR} or run `prime login`")
self.run = TrainRun(api_key)
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; finalize still marks it completed on clean exit.
self.run.id = run_id
self.logger.info(f"Logging metrics and episodes to platform run {run_id} (attached via $RUN_ID)")
return
run_fields: dict[str, Any] = {}
if config is not None:
run_fields = dict(
base_model=config.model.name,
max_steps=config.max_steps or 0,
batch_size=config.batch_size,
rollouts_per_example=config.group_size,
seq_len=config.seq_len,
# failure marking then; a clean finish() still marks it completed.
init_kwargs = {"id": run_id}
elif config is not None:
init_kwargs = dict(
name=self.config.name,
model=config.model.name,
environments=[env.env_id for env in config.train.source],
run_config=config.model_dump(exclude_none=True, mode="json"),
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
training=pr.TrainingSpec(
max_steps=config.max_steps or 0,
batch_size=config.batch_size,
rollouts_per_example=config.group_size,
seq_len=config.seq_len,
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
),
config=config.model_dump(exclude_none=True, mode="json"),
)
await self.run.create(name=self.config.name, **run_fields)
else:
# The RFT API requires a base model; "unknown" is what the
# pre-SDK register sent for a config-less init.
init_kwargs = {"name": self.config.name, "model": "unknown"}
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
# A configured monitor must work (see monitors.setup), so the default is
# mode="online": a missing key or a team outside the external-runs allowlist
# raises here instead of training silently untracked. $PRIME_RUNS_MODE=disabled
# stays the explicit opt-out.
self.run = await asyncio.to_thread(
pr.init,
kind="train",
mode=os.getenv(pr.MODE_ENV) or "online",
base_url=_base_url(),
finish_timeout=FINISH_TIMEOUT,
**init_kwargs,
)
if self.run.url:
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}")
else:
self.logger.info(f"Platform run disabled ({pr.MODE_ENV}=disabled)")
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
# The SDK also drops non-finite values, but silently; sanitize first so
# the dropped paths are named in the log.
metrics, dropped = sanitize(metrics)
if dropped:
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
self.run.submit("metrics upload", self.run.log_metrics(metrics))
# A queue put that can block briefly under backpressure - off the loop. The SDK
# stamps `_timestamp` on every row, so step=None rows keep a time anchor.
await asyncio.to_thread(self.run.log_metrics, metrics, step=step)
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Upload one platform sample per episode via the presigned-URL Parquet flow.
Only the trained cohort ships to the platform."""
# Upload every 10th step, unsampled - the pre-refactor cadence - to not
# overwhelm the platform's ingestion. TODO: Lift once we integrate the
# prime traces SDK.
if kind != "train" or subset != "effective" or not episodes or step % 10 != 0:
"""Only the trained cohort ships to the platform. The upload cadence
(every 10th step) and the Parquet encoding live in the SDK's training
samples sink, which reads each episode's dispatch step off ``run.work``
- the ``TrainRunInfo`` the dispatcher stamps at emit time."""
if kind != "train" or subset != "effective" or not episodes:
return
async def upload() -> None:
# Serialization dumps every episode's full model - heavy pure-Python work
# that would stall the event loop (and with it dispatch) if run inline.
parquet_bytes = await asyncio.to_thread(episodes_to_parquet_bytes, episodes, self.run.id, step)
if parquet_bytes is not None:
await self.run.upload_samples(parquet_bytes, step)
self.run.submit(f"episodes upload at step {step}", upload())
# A queue put that can block briefly under backpressure - off the loop.
await asyncio.to_thread(self.run.log_episodes, episodes)
async def finalize(self) -> None:
await self.run.finalize()
class TrainRun:
"""A training run on the Prime platform's RFT API.
Owns the HTTP client and the run lifecycle (create, log, finalize) — the
natural seam to be subsumed by the train SDK, and it mirrors ``wandb.Run``'s
exit behavior: a created run that is never finalized is marked failed at
process exit via an atexit hook that ``finalize`` disarms. Fully async,
except the atexit hook itself — at interpreter shutdown there is no event
loop, so it sends one synchronous request.
"""
def __init__(self, api_key: str):
self.id: str | None = None
self.logger = get_logger()
self._tasks: set[asyncio.Task] = set()
self.base_url = (os.getenv(BASE_URL_VAR) or BASE_URL).rstrip("/")
self.headers = {
"Authorization": f"Bearer {api_key}",
"x-api-key": api_key,
"Content-Type": "application/json",
}
self.client = httpx.AsyncClient(
base_url=self.base_url,
headers=self.headers,
timeout=30,
transport=httpx.AsyncHTTPTransport(retries=3),
)
def submit(self, what: str, request: Coroutine[Any, Any, None]) -> None:
"""Run a request as a fire-and-forget task; a failure only warns. The task set
keeps strong references - the loop alone won't."""
async def guarded() -> None:
try:
await request
except Exception as e:
self.logger.warning(f"Failed {what}: {type(e).__name__}: {e}")
task = asyncio.get_running_loop().create_task(guarded())
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
async def create(
self,
name: str | None = None,
team_id: str | None = None,
base_model: str = "unknown",
max_steps: int = 0,
batch_size: int | None = None,
rollouts_per_example: int | None = None,
seq_len: int | None = None,
environments: list[str] | None = None,
run_config: dict[str, Any] | None = None,
wandb_project: str | None = None,
) -> str:
"""Register the run with the platform and return its id."""
prime_config = PrimeConfig()
team_id = team_id or prime_config.team_id
payload: dict[str, Any] = {"base_model": base_model, "max_steps": max_steps}
if batch_size is not None:
payload["batch_size"] = batch_size
if rollouts_per_example is not None:
payload["rollouts_per_example"] = rollouts_per_example
if seq_len is not None:
payload["seq_len"] = seq_len
if environments is not None:
payload["environments"] = [{"id": env_id} for env_id in environments]
if run_config is not None:
payload["run_config"] = run_config
if wandb_project is not None:
payload["wandb_project"] = wandb_project
if name:
payload["name"] = name
if team_id:
payload["team_id"] = team_id
response = await self.client.post("/external-runs", json=payload)
if response.status_code != 201:
raise RuntimeError(f"Failed to create platform run (HTTP {response.status_code}): {response.text}")
self.id = response.json()["run"]["id"]
self._owner_pid = os.getpid()
atexit.register(self._mark_failed)
if prime_config.frontend_url:
self.logger.info(
f"Logging metrics and episodes to platform run {self.id} ({prime_config.frontend_url.rstrip('/')}/dashboard/training/{self.id})"
)
else:
self.logger.info(f"Logging metrics and episodes to platform run {self.id}")
return self.id
async def log_metrics(self, metrics: dict[str, Any]) -> None:
(await self.client.post("/metrics", json={"run_id": self.id, "metrics": metrics})).raise_for_status()
async def upload_samples(self, parquet_bytes: bytes, step: int) -> None:
"""Presigned-URL flow: presign -> R2 PUT -> confirm."""
presign = await self.client.post("/samples/presign", json={"run_id": self.id, "step": step})
presign.raise_for_status()
data = presign.json()["data"]
# Bare client - the presigned URL rejects the run client's auth headers.
async with httpx.AsyncClient(timeout=30) as client:
put = await client.put(
data["presignedUrl"], content=parquet_bytes, headers={"Content-Type": "application/parquet"}
)
put.raise_for_status()
confirm = await self.client.post(
"/samples/confirm", json={"run_id": self.id, "step": step, "s3_key": data["s3Key"]}
)
confirm.raise_for_status()
async def finalize(self) -> None:
"""Finalize the run as completed."""
self.logger.info(f"Finalizing platform run {self.id}")
# Drain in-flight uploads so the final step's metrics and episodes land
# before the run is marked completed.
await asyncio.gather(*self._tasks, return_exceptions=True)
try:
(await self.client.post("/finalize", json={"run_id": self.id, "summary": {}})).raise_for_status()
except httpx.HTTPError as e:
self.logger.warning(f"Failed to finalize platform run {self.id}: {e}")
await self.set_status(success=True)
atexit.unregister(self._mark_failed)
def _mark_failed(self) -> None:
# Forked children inherit the atexit table; only the creating process may
# flip the run's status. At interpreter shutdown there is no event loop and
# no executor for async DNS, so this path must stay synchronous.
if os.getpid() != self._owner_pid:
return
self.logger.info(f"Marking platform run {self.id} as failed")
try:
httpx.put(
f"{self.base_url}/external-runs/{self.id}/status",
headers=self.headers,
json={"status": "failed"},
timeout=30,
).raise_for_status()
except httpx.HTTPError as e:
self.logger.warning(f"Failed to mark platform run {self.id} as failed: {e}")
async def set_status(self, success: bool) -> None:
"""Mark the run as completed or failed."""
status = "completed" if success else "failed"
self.logger.info(f"Marking platform run {self.id} as {status}")
try:
put = await self.client.put(f"/external-runs/{self.id}/status", json={"status": status})
put.raise_for_status()
except httpx.HTTPError as e:
self.logger.warning(f"Failed to mark platform run {self.id} as {status}: {e}")
def episodes_to_parquet_bytes(episodes: list[vf.Episode], run_id: str | None, step: int) -> bytes | None:
"""One row per episode. Sample construction is shared with verifiers' eval
``--push`` (``build_samples``: complete native episode in ``info.native_wrapper``,
flat summary from one trainable trace), so a training episode and an eval sample
land on the platform identically; the RFT-only columns (run/step/advantage/
problem_id/env_name) are layered on here."""
advantages: dict[str, float | None] = {}
env_names: dict[str, str] = {}
for episode in episodes:
summary_trace = next((trace for trace in episode.traces if trace.agent.trainable), episode.traces[0])
advantages[episode.id] = summary_trace.info.get("advantage")
env_names[episode.id] = episode.env.id
now = datetime.now(timezone.utc)
rows = []
for sample_id, sample in enumerate(build_samples(episodes)):
trajectory = sample["trajectory"]
if not trajectory: # no branches (e.g. an episode that errored before any message)
continue
advantage = advantages.get(sample["episode_id"])
trajectory = [{**branch, "advantage": advantage} for branch in trajectory]
try:
problem_id = int(sample["example_id"]) if sample["example_id"] is not None else sample_id
except (TypeError, ValueError):
problem_id = sample_id
rows.append(
{
"run_id": run_id,
"step": step,
"tag": "",
"problem_id": problem_id,
"sample_id": sample_id,
"prompt": "",
"completion": json.dumps(sample["completion"]),
"trajectory": json.dumps(trajectory),
"answer": "",
"env_name": env_names.get(sample["episode_id"], ""),
"task": json.dumps(sample["task"]),
"info": json.dumps(sample["info"]),
"reward": sample["reward"],
"advantage": advantage,
"metrics": json.dumps(sample["metrics"]),
"timing": json.dumps(sample["timing"]),
"num_input_tokens": trajectory[-1]["num_input_tokens"],
"num_output_tokens": trajectory[-1]["num_output_tokens"],
"created_at": now,
}
)
if not rows:
return None
table = pa.Table.from_pylist(rows, schema=SAMPLE_SCHEMA)
buf = io.BytesIO()
pq.write_table(table, buf, compression="snappy", use_dictionary=True, write_statistics=True)
return buf.getvalue()
# Drains queued uploads so the final step's metrics and episodes land,
# then finalizes (idempotent on the platform side); an attached run's
# failure marking stays with the launcher.
await asyncio.to_thread(self.run.finish)
+18 -2
View File
@@ -42,6 +42,9 @@ class WandbMonitor(Monitor):
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
sys.argv = json.loads(wandb_args)
# W&B advertises Weave on every init when it sees openai/verifiers imported.
os.environ.setdefault("WANDB_DISABLE_WEAVE", "1")
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
# requires a server connection and can't work offline.
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and os.environ.get("WANDB_MODE") not in (
@@ -113,6 +116,9 @@ class WandbMonitor(Monitor):
self.wandb = init_wandb(max_retries)
wandb.define_metric("*", step_metric="step")
# key prefixes that arrived via step=None (wall-time rows); their time axis
# is defined lazily on first sight in log_metrics
self._time_prefixes: set[str] = set()
# Provision the curated "overview" saved view once per project (the run's primary process
# in shared mode, else the single master). Best-effort: a workspaces/API failure must never
@@ -133,8 +139,18 @@ class WandbMonitor(Monitor):
self.logger.info(f"Logging metrics to W&B ({self.wandb.url})")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
wandb.log({**metrics, "step": step})
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
# every log carries the monitor's own wall-time stamp
if step is None:
# time-keyed rows chart against wall time; whichever key prefixes show
# up this way get their time axis defined on first sight
for prefix in {key.split("/")[0] for key in metrics}:
if prefix not in self._time_prefixes:
self._time_prefixes.add(prefix)
wandb.define_metric(f"{prefix}/*", step_metric="_timestamp")
wandb.log({**metrics, "_timestamp": time.time()})
else:
wandb.log({**metrics, "step": step, "_timestamp": time.time()})
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
pass

Some files were not shown because too many files have changed in this diff Show More