Compare commits

...
Author SHA1 Message Date
Mika SenghaasandGitHub adfbc6003d feat: expose repository skills to codex (#3347)
## Summary

- Add `.agents/skills` as a symlink to the shared `skills/` directory.
- Make repository skills available through Codex default discovery.

## Verification

- Confirmed `.agents/skills` resolves to `../skills`.
- Commit hooks passed.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Config-only symlink for agent skill discovery; no runtime, auth, or
data-handling changes.
> 
> **Overview**
> Adds a `.agents/skills` symlink to `../skills` so Codex can discover
the repo’s shared skills via its default lookup path.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
625149a26b20bafa2d3901222d4c1b7f4bdef35b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-22 15:44:18 -07:00
94a93203cf fix: only pkill zombie torchrun/vLLM processes in CI (#3346)
## Summary
- Gate the autouse `cleanup_zombies` fixture in `tests/conftest.py` on
`USERNAME_CI`.
- The fixture pkills `-f torchrun` / `-f VLLM` host-wide at every test
module start. In CI this cleans up zombies from previous tests, but
locally it kills any concurrent training run on the box.
- `USERNAME_CI` is already set to `CI_RUNNER` by all CI pytest jobs
(`cpu_tests`, `gpu_tests`, `nightly_tests`) and already keys the `user`
fixture, so CI behavior is unchanged and no workflow changes are needed.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Test-only fixture change; CI behavior is preserved. Residual risk is
local leftover processes if tests leak zombies without USERNAME_CI.
> 
> **Overview**
> Stops the autouse `cleanup_zombies` fixture from host-wide `pkill` of
`torchrun`/`VLLM` on local pytest runs, so concurrent training jobs are
no longer killed.
> 
> The kill still runs when `USERNAME_CI` is set (already used by CI
pytest jobs), so CI zombie cleanup is unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
454f89e5c269d62410f2ea007b884537dd964045. 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 15:44:00 -07:00
f0d27513a4 chore: glm-4.5-air swe example to bf16 + bash harness (#3343)
## Summary

- `examples/advanced/glm-4.5-air/swe.toml`: serve inference from the
bf16 checkpoint directly — drop `quantization = "fp8"` from
`[inference.vllm]`.
- Switch the train and eval harnesses from `rlm` to `bash`. Drop the
rlm-only `summarize_at_tokens` knobs.
- Update the header comments to match.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Example-only TOML config; no training, inference, or harness code
changes.
> 
> **Overview**
> Updates the GLM-4.5-Air SWE example so inference serves the **bf16**
checkpoint directly (drops vLLM `fp8` quantization) and train/eval use
the **bash** harness instead of **rlm**, including removing
`summarize_at_tokens`. Header comments are aligned with that.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
72032855baa5712daab635147683cf9c09541bf0. 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 13:45:23 -07:00
684f0d0afe chore: fold source sub-configs into dotted keys (#3344)
## Summary

- Fold every `[[...source]]` entry's nested sub-configs into dotted keys
in one block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`)
instead of one full-path subsection header per nested config. Applies to
all train/eval source blocks in `configs/`, `examples/`, and `k8s/` (51
TOML files, −868/+322 lines).
- Move the top-level `[monitors.prime]` block up next to
`[monitors.wandb]` in the 4 files where it sat inside the orchestrator
section.
- Apply the same style to the TOML snippets in `docs/` and the `configs`
/ `training/start-run` skills, and document the convention in the
configs skill. Nested arrays of tables (e.g.
`[[...source.env.taskset.task.judges]]`) keep their full-path headers.

Purely cosmetic — no config semantics change. Verified by asserting
`tomllib` parses every file to an identical dict before and after, and
by diffing the resolved-config JSON from `rl --dry-run` (identical up to
the CLI-passed `output_dir`).

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 13:39:56 -07:00
559b44772e chore: bump verifiers to latest main (#3337)
## Summary
- Bump the `deps/verifiers` submodule from `4bcb48e` to `a60a606`
(latest `main`).
- Pulls in:
- [vf#2410](https://github.com/PrimeIntellect-ai/verifiers/pull/2410):
prime-sandboxes 0.2.39 + pooled per-loop sandbox client.
- [vf#2422](https://github.com/PrimeIntellect-ai/verifiers/pull/2422):
evals run through the env server by default.
- [vf#2423](https://github.com/PrimeIntellect-ai/verifiers/pull/2423):
strip the hub org prefix before importing a plugin module.
- Relock `uv.lock`: prime-sandboxes 0.2.37 → 0.2.39, connect-python →
connectrpc 0.11.1, new protobuf-py transitive deps.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Dependency bump of the verifiers/sandbox stack can change eval routing
and RPC client behavior; lockfile-only surface but runtime impact is
non-trivial.
> 
> **Overview**
> Advances the `verifiers` pin and relocks `uv.lock` so
`prime-sandboxes` moves **0.2.37 → 0.2.39**.
> 
> That pull also replaces `connect-python` with `connectrpc` 0.11.1 and
adds transitive `protobuf-py` / `protobuf-py-ext`. Upstream verifiers
changes include a pooled per-loop sandbox client, evals defaulting
through the env server, and stripping the hub org prefix on plugin
import.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
13b8ad796e06175e26b6196815631c2bbf40e36a. 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-21 22:39:59 -07:00
Konstantin DunasandGitHub 1e756307ae refactor(orchestrator): make dispatch contracts explicit (#3334) 2026-08-22 00:58:37 +02:00
2441fd5142 feat: drop on in-queue staleness + first-class cancellation type (#3313)
## Summary

Refactors staleness handling around the exact consumption-lag definition
(#3050's framing), toward #3310.

- **Exact measurement**: `episode_staleness()` decomposes each trained
episode's staleness from its `PolicySpan` into the in-flight share (`end
- start`, weight updates during generation) and the in-queue remainder
(buffered between completion and ship). New per-step metrics:
`off_policy/{mean,max}`, `off_policy/{in_flight,in_queue}/{mean,max}`,
`off_policy/dropped`; the step log line's `Max Off-Policy` uses the
exact definition. Every quality metric in the step log and the wandb
`effective` subset is computed over exactly the traces shipped to the
trainer this step (`batch.cohort`); only `Error`/`Cancelled`/`Ratio` are
arrival-window rates, since over the shipped set they are
0/0/share-of-shipped by construction.
- **In-queue enforcement**: previously only in-flight episodes were aged
and dropped — an episode that finished quickly and sat in the sink
accumulated staleness that was measured at ship but never enforced. Now
the sink sweeps `pending_batch` before every readiness check and voids
anything past `max_off_policy_steps`, so the bound is a hard guarantee
on trained data. The dispatcher's version-boundary sweep remains as a
compute saver (it must run before the engine pause for KV-abort safety)
and uses the same exact step-based formula.
- **Tail semantics**: the trainer now broadcasts every version except
`v{max_steps}` (the only one nothing can sample from), instead of
skipping the final `TARGET_LAG+1`. The orchestrator stays alive for the
last rendezvous (`wait_for_final_broadcast`), so `max_off_policy_steps`
holds exactly on every step including the final batch, and the tail
special-casing this used to need is gone (the dispatch gate's
final-batch exception and the watcher's shortened ModelExpress window).
Draining now starts right after shipping the final batch — the old
trigger needed a further batch to *fill*, which burned a batch of
inference and, under a tight `max_off_policy_steps`, never filled at all
(end-of-run livelock).
- **First-class cancellation**: dropped groups emit one typed
`Cancellation(group_id, count, reason)` on `out_q` instead of
per-episode synthetic `Cancelled`-error episodes; queue-voided episodes
are tracked in a `cancelled` id-set on the episode collections,
alongside `sampled`/`admitted`. Cancellations no longer confound error
metrics: `has_error` stays pure (overload cuts and staleness drops are
no longer counted as errors), the effective subset excludes cancelled
episodes explicitly, and the step log / wandb gain separate `Cancelled`
rates. A stale-voided group also bypasses curriculum admission — a
pipeline decision is not a task result.

## Breaking

- **wandb**: new `train/*/all/**/cancelled/mean` and per-step
`off_policy/*` keys; cancellations no longer appear under
`*/error/Cancelled` or inflate `has_error/mean`.
`dispatcher/off_policy_level/{mean,max}` →
`dispatcher/off_policy/{mean,max}`, now reporting the exact step-based
staleness of in-flight work instead of the aged in-flight counter.
- **Zero-output abort accounting**: cancelled groups still advance the
zero-output budget (by their full owed episode count), but stale-voided
groups no longer feed the curriculum via `on_result`.
- **Trainer broadcast schedule**: in-memory transports now broadcast
`v{max_steps-1}` (previously skipped); the orchestrator waits for it
before tearing down. The final drain no longer requires (or generates) a
throwaway post-final batch.
- **The bound's meaning tightened**: staleness now counts queue time,
not just weight updates during generation. A config tuned under the old
in-flight-only definition drops more aggressively at the same numeric
value; `max_off_policy_steps = 0` now means strictly synchronous (heavy
oversampling drops), where the old `0` only meant "no update
mid-generation".

## Verification

- Behavioral smoke (stubbed envs, no GPU): stale `Cancellation` voids
arrived episodes without reading as error; a fully-cancelled group still
advances the zero-output budget by its owed count; overload cancellation
finalizes the partial group and its survivors still train; the queue
sweep un-fills a batch, marks the episode cancelled, and counts drops;
the dispatcher drops exactly the groups past the bound and emits one
typed `Cancellation`; `effective` excludes cancelled while
`has_error`/`cancelled` stay disjoint.
- `tests/unit/orchestrator`, `tests/unit/test_configs.py`,
`tests/unit/transports`: 201 passed (the `test_qwen3_vl_e2e` failure is
pre-existing on `main`).
- `ruff check` and `ruff format --check` clean.
- E2E: 15-step reverse-text run with
`--orchestrator.max-off-policy-steps 0` (true on-policy), clean exit in
3m 21s. **All 15 step lines report `Max Off-Policy 0` and `Error 0.0%`**
— including the final batch, which now trains on the freshly-broadcast
`v{max_steps-1}`. Both enforcement layers fired throughout (45
queue-sweep drops, 14 in-flight cancel sweeps) with per-step `Cancelled`
up to 70% and zero genuine rollout failures — e.g. `Step 2 | … | Max
Off-Policy 0 | Error 0.0% | Cancelled 70.3% | …`; under the old
error-marker representation those cancellations would have read as
`Error ~70%`. Draining started immediately at the final ship (`Shipped
the final batch — draining pipeline`). Reward climbed 0.14 → ~0.77.
- E2E (filesystem broadcast): 8-step reverse-text run with
`--weight-broadcast.type filesystem --orchestrator.max-off-policy-steps
0`, clean exit for both processes. All 8 steps report `Max Off-Policy 0`
and `Error 0.0%` — including the final batch, since filesystem writes
every version (no skip path) and the final-broadcast wait is correctly
inert (0 occurrences). Drain fired at the final ship; the trainer wrote
all broadcast dirs and finished cleanly. NIXL is safe by construction
(trainer skip window and the watcher's ModelExpress guard both derive
from `max_steps` and moved in lockstep) but has not been exercised
end-to-end.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 14:55:24 -07:00
967fbf25ef fix(sft): resumed runs restart the data stream with num_workers > 0 (#3332)
## Summary

Since #3299 made `data.num_workers` default to 1, **every resumed SFT
run silently restarts the training data from the beginning** and freezes
the data position it writes into subsequent checkpoints.

Root cause: `train()` called `iter(dataloader)` before the resume path's
`ckpt_manager.load(..., dataloader=dataloader)`. With worker processes,
`iter()` forks the worker with a copy of the dataset in its *initial*
state; the later `load_state_dict` only stashes state for a future
iterator that is never created. Two symptoms:

- the resumed run consumes the dataset from row 0 again (visible as a
loss-slope kink at every resume — repeated data);
- `state_dict()` keeps returning the stashed loaded state, so every
post-resume checkpoint stores the resume-point position instead of the
live one, compounding across restarts.

Fix: create the iterator only after the potential resume load, with a
comment stating the constraint.

Also: `get_dataset_state` unpacked exactly one worker snapshot, crashing
**any** run with `num_workers > 1` at the startup log line (start or
resume) — it now returns positions keyed per worker, and stops dumping
`pending_sample` token buffers into the log. It keeps parsing the
loader's stashed state rather than the dataset object: after a resume
the restored position exists only there (the main-process dataset object
stays at position 0; workers receive the state on fork). This is now the
single code path: `num_workers = 0` (the only case with a different,
inline state layout) is no longer supported.

## Breaking

- `data.num_workers = 0` is rejected at config time (`ge=1`). Inline
main-process data loading is gone; use `num_workers = 1` (the default).

## Verification

A/B on `configs/ci/integration/reverse-text-sft/{start,resume}.toml`
(Qwen3-0.6B, 1 node, 2 GPUs, 5 steps + resume to 10), comparing
`checkpoints/step_N/trainer/dataloader/rank_0.pt` worker-snapshot
dataset state:

| variant | ckpt step_5 | ckpt step_10 (post-resume) |
|---|---|---|
| main, `num_workers=1` | `{'step': 213}` | `{'step': 213}` — frozen,
data restarted from row 0 |
| main, `num_workers=2` | — | crashes at startup (`ValueError: too many
values to unpack` in `get_dataset_state`) |
| this PR, `num_workers=1` | `{'step': 213}` | `{'step': 407}` —
advanced correctly |
| this PR, `num_workers=2` | `{'worker_0': 111, 'worker_1': 111}` |
`{'worker_0': 213, 'worker_1': 213}` — per-worker state restored and
advanced; workers consume disjoint shards |

Discovered on a production 500-step GLM-4.5-Air SFT run (india): after
two crash-resumes, both post-resume checkpoints carried the identical
dataset position (`{'step': 6657}` at step 150 *and* step 300) and the
loss slope steepened at each resume boundary from re-trained data.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 14:04:58 -07:00
e6d2b3f252 fix: meta load order (#3333)
* test(trainer): add xfail demonstrating buffer-reinit-after-load bug

load_dcp_from_hf runs init_buffers_post_meta() after dcp_load() writes
checkpoint values into persistent buffers, so any model whose reinit
touches a persistent buffer (e.g. Laguna's MoE expert_bias) has the
loaded value silently clobbered back to its reinit default.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(trainer): reinit buffers before loading checkpoint, not after

load_dcp_from_hf ran init_buffers_post_meta()/fix_model_post_empty()
after dcp_load() had already copied checkpoint values into persistent
buffers, silently clobbering any buffer both a reinit hook touches and
a checkpoint legitimately ships (e.g. Laguna's MoE expert_bias). Move
the call to run once, immediately after to_empty(), matching the
existing correct ordering in setup_model's checkpoint-deferred branch.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(trainer): rename test_model_load_order.py to models/test_state_loading.py

Group it with the other cross-cutting model-mechanism tests
(test_checkpointing.py, test_fused_moe.py) rather than the top-level
train/ dir, and name it for what it covers (weight-checkpoint state
loading) since models/test_checkpointing.py already covers activation
checkpointing.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-21 16:41:15 -04:00
Konstantin DunasandGitHub 13553dd88a refactor(orchestrator): rename sampler to generation source (#3330) 2026-08-21 20:36:15 +02:00
Konstantin DunasandGitHub d37b57ba6e docs(training): correct saved episode references (#3329) 2026-08-21 20:36:08 +02:00
Konstantin DunasandGitHub 802a364e6a fix(orchestrator): label eval avg@k by episode group size (#3328) 2026-08-21 20:36:03 +02:00
Konstantin DunasandGitHub 9b9de2f1bc fix(orchestrator): apply taskset system_prompt override on the RL path (#3327) 2026-08-21 19:42:57 +02:00
fe38722e8b feat: enable nccl for sft online evals (#3323)
* enable nccl for sft online evals

* support multi-node sft nccl evals

* fix: enforce NCCL-requires-inference at the launcher, not the model validator

The launcher strips [inference] and [deployment] from the trainer sub-config
of a decoupled multi-node deployment, so the re-parsed sub-config tripped the
validator's guard and crashed every trainer rank at startup.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: remove accidentally committed gitlink

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: broken line continuation in NCCL sbatch template blocks

The {% if %} blocks left a whitespace-only line after the backslash
continuation, terminating the launch command early: the trainer/evals
processes ran without their tee pipelines (empty node_*.log/evals.log)
and the stray '2>&1 | tee ... &' ran as a separate command, mis-assigning
EVALS_PID.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* share weight broadcast config policy

* revert shared weight broadcast policy

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 22:34:32 -07:00
minh hoangandGitHub c69f5b0389 feat: support Qwen3.8 (#3314)
Qwen3.8 reuses the Qwen3.5 architecture verbatim — the dense 27B reports
`model_type: qwen3_5` / `Qwen3_5ForConditionalGeneration`, the 2.4T-A95B
reports `qwen3_5_moe_text` — but both places that enable Qwen3.5 keyed off
the repo name, so neither picked it up.

Trainer: gate the three Qwen3.5 patches on the loaded config's `model_type`
instead of a substring of `model.name`. The name check missed
`Qwen/Qwen3.8-27B` and the `qwen3_5_moe` fallback only caught the MoE
sibling, so the dense 27B trained without `_patch_qwen3_5_linear_attn_varlen`
— GatedDeltaNet gets no cu_seqlens, conv/SSM state leaks across packed
sequences, and 48 of its 64 layers are linear attention. model_type also
covers Qwen3.6 and renamed fine-tunes, which the name check missed too.

Parsers: `^Qwen/Qwen3\.5-` doesn't match the dotted 3.6/3.8 names and the
`^Qwen/Qwen3-` catch-all only matches hyphenated ones, so both parsers
auto-resolved to None and vLLM launched without either flag. Qwen3.8's chat
template opens `<think>` at the generation prompt, so reasoning would land
in `content` and tool calls would go unparsed.
2026-08-20 21:59:40 -07:00
29e4222767 feat: remove weight checkpointing (#3316)
* feat!: remove weight checkpointing

The trainer saves only DCP checkpoints. HF weights on disk exist in two
forms: weight broadcasts — the transient trainer-to-inference transport,
which SFT now ships for online evals (same filesystem component RL
uses, broadcast at eval steps, newest kept only) — and offline
conversion of DCP checkpoints via scripts/dcp_to_hf.py (full models and
LoRA adapters).

WeightCheckpointManager, the weights/step_N dirs, and the ckpt.weights
config surface (weights, weights_only, skip_gather_master_weights,
save_adapter_separately) are removed. The evals process watches
broadcasts/step_N (OnlineConfig.weights_dir renamed to broadcasts_dir)
and loads adapter broadcasts of LoRA runs via /load_lora_adapter. The
weight save/gather helpers move to prime_rl.utils.weights.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: wait for the resume-step broadcast before retriggering

The trainer rebroadcasts the resumed policy only after loading the
model, so a one-shot STABLE check usually lost the race and the watch
loop never retried (last_step is pre-seeded to the resume step). Wait
for the broadcast; give up only when a newer stable broadcast proves it
was already cleaned away.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: enable LoRA on the eval inference server

SFT LoRA online evals reload raw adapter broadcasts via
/load_lora_adapter, which requires enable_lora on the server. Mirror
the RL validator: set enable_lora and max_lora_rank when LoRA is on,
warn when inference is externally managed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: defer offline DCP->HF converter to a follow-up

The converter needs more standalone testing (incl. GPU-free use) and will
land in its own PR. The resume-preserves-weights test now compares the DCP
checkpoints directly via dcp_to_torch_save; the PEFT adapter-export tests
move to the follow-up with the script.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: DCP comparison keys and dtypes in resume test; idempotent rebroadcast

The trainer wraps DCP state as {app: {model: ...}}, so the converted
torch save must be indexed through 'app' — the bare 'model' lookup
raised KeyError. The two compared runs also train in different compute
dtypes (fp32 vs bf16 under full offload), so compare in bf16, which is
what the resumed model actually loaded.

The SFT startup rebroadcast now skips when the resume step's broadcast
already exists with STABLE: rewriting the same dir in place would race
an evals process already reloading it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 20:29:42 -07:00
e3e3a87dea feat: rank-parallel sharded save for filesystem broadcast (#3315)
* feat: rank-parallel sharded save for filesystem broadcast

Gather full weights cooperatively and let every rank convert and write
its own layer-aligned slice as safetensors shards, instead of funneling
everything through the master rank. D2H copies go through persistent
pinned buffers and overlap the per-tensor all-gathers. The broadcast is
always sharded safetensors now; the save_sharded and save_format knobs
are gone.

Laguna-XS.2 (68GB bf16) on 2 GPUs: gather 25.1s -> 2.7s, total save
83.1s -> 51.9s (the write phase is disk-bound on a single NVMe;
rank-parallel writes scale with per-node writers on shared
filesystems).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: create save dir in save_state_dict_parallel

Callers no longer need to pre-create the directory; a fresh save dir
made every rank's shard write fail with a safetensors I/O error.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: note the same-stream invariant on the staging copy

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: clarify HF conversion branches and resolve_fqn

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: blocking D2H copies in the parallel gather

Drop the pinned staging buffers and non-blocking copies: their safety
rested on same-stream allocator-reuse ordering, which is subtle to
maintain. Each rank still copies only its slice, and the parallel shard
writes — the dominant cost at scale — are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: derive layer ownership from the module tree

Replace the FQN regex with prefixes taken from the children of every
'layers' ModuleList. State-dict keys and module names come from the
same tree traversal, so the prefixes match keys verbatim, wrapper
components and all.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Revert "refactor: derive layer ownership from the module tree"

This reverts commit 740059c835ac8025af00ab58cdbe1aef941168ee.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 20:29:14 -07:00
NeoandGitHub 65e4b915ba Relock prime-kernels after refreshing the v0.8.0 wheels (#3321) 2026-08-21 01:44:20 +02:00
a686a90405 Add custom vendored kernels (#3154)
* Add custom vendored kernels

* Add fused MoE kernel

* Fix comments, simplify kernel toml metadata, make sure deps for prime-kernels match prime-rl directly

* Update to latest fused moe kernel

* Add prime-flash-moe integration in addition to locally compiled kernels

* Add mxfp8 routing support for prime-flash-moe

* Fix MXFP8 backward for fused MoE for correctly group aligned experts

* Torch fused grouped_mm backward for fused MoE forward

* Fix release upload in kernel build: install gh in container, grant contents write

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Set GH_REPO for release upload: container checkout trips git dubious-ownership

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Pin prime-kernels at the v0.8.0 prebuilt wheels behind a kernels extra

The wheels were backfilled onto v0.8.0 from this branch
(build_kernels.yaml run 31429866271); uv sync --extra kernels now
installs them instead of requiring a local nvcc build.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Format kernel MoE files with ruff 0.13

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix memory corruption of triton kernel for large numel quants, where N >= 2^31=INT_MAX

* Make the kernel a git-submodule

* Move the kernels into the prime-kernels submodule

The `prime-kernels` wheel — build system, registry and every kernel's Python
surface — now lives in its own monorepo, PrimeIntellect-ai/prime-kernels,
checked out here as the `kernels/` submodule. flash_moe's C++/CUDA sources,
previously a nested prime-flash-moe submodule, are committed there too, so one
non-recursive init brings in everything a source build needs.

Integration is unchanged: `uv sync --extra kernels` still resolves the prebuilt
wheels from a prime-rl release, `uv pip install --no-build-isolation -e kernels`
still builds from source, and build_kernels.yaml still attaches the wheels to
every release. Its `paths` trigger moves from `kernels/**` to the `kernels`
gitlink, which is the only path prime-rl tracks now, and ruff excludes the whole
submodule rather than just the vendored sources.

* Update kernels

* Fix comments

* Add tests for the fused MoE

* Bump prime-kernels to 2ceaf9e

* Remove stray uv.lock for prime-rl-configs

* Verify mxfp8 grad values and needs_input_grad handling

* Print epsilons in tests

* Print epsilons in tests

* Print epsilons in tests

* Print epsilons in tests

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 01:28:32 +02:00
991b925e6e validate scheduler steps at config time (#3318)
A linear scheduler with warmup_steps + decay_steps > max_steps only
failed deep into trainer setup, via a bare assert in
setup_linear_scheduler. Add validate_scheduler to the configs package
and call it from TrainerConfig and SFTConfig so the run fails at
config validation instead. Also covers cosine schedulers, which need
max_steps and warmup_steps < max_steps.

The runtime assert stays as a backstop (SFT resume with skip_scheduler
shrinks the step budget at runtime) but now carries a message.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 15:06:34 -07:00
Konstantin DunasandGitHub 03cdc51575 refactor(orchestrator): score native episodes (#3297) 2026-08-21 00:06:29 +02:00
NeoandGitHub cb5f1e72bb Turn fused adamw on by default except when we do cpu offloading (#3305) 2026-08-20 09:01:59 -07:00
samsjaandGitHub 52eebada92 fix(tests): seed qwen3_moe parity test RNG and widen grad tolerance (#3290)
test_qwen3_moe compares HF and prime-rl gradients in bf16 with an
unseeded random draw; FA2 backward is not bit-deterministic, so the
embedding grad diff (observed 512-1344) occasionally crosses the
atol=1000 threshold, failing CI with 'Max grad diff: 1024.0' on main
and unrelated PRs.

- autouse fixture pins torch.manual_seed(0) so the input/init draw is
  deterministic (verified grad diff stays in 512-768 on this seed)
- bump grad atol 1000 -> 2048 to absorb FA2 backward reduction-order
  noise that seeding cannot remove (60/60 random seeds pass at 2048,
  worst observed 1344)
2026-08-19 20:30:47 -07:00
NeoandGitHub 5d0fc8ba2e Mario/cpu optimization dataloader (#3299)
* USe dataloder threads and pinnd memory tranfers async

* Fix PRNG

* Reset fused lm head token chunk size to 4k

* Revert lm head chunk size to default, another PR does this

* Remove unused prefetch factor

* Fix PRNG bug
2026-08-19 20:26:12 -07:00
Mika SenghaasandGitHub c2a25f0622 feat: soft and hard kv cap (#3307)
* Split kv trims into soft and hard tiers

A trim at the 0.8 trigger now only lowers the cap and lets completions
drain the pool — at that level there is still headroom, and at steady
state completions usually outrun in-place context growth, so
cancelling immediately pays a certain cost to avoid a merely possible
one. Only if usage climbs past 0.9 despite the closed gate does the
trim also cancel the excess (the prior behavior), preserving the
thrash-cliff guarantee: worst case, a soft trim escalates to a hard
one a cooldown later, still well before the cliff. Emergency cuts are
unchanged.

* Add 2-node concurrency debug config

GLM-4.5-Air scaleswe on the bash harness, 1 train + 1 infer node,
default concurrency, 100-instance SWE-Bench eval.

* Rename trim thresholds to KV_USAGE_SOFT_CAP / KV_USAGE_HARD_CAP

* Fix stale header in the concurrency debug config
2026-08-19 16:00:14 -07:00
bc9e186963 feat: adaptive concurrency for online evals (#3309)
* feat: first-class evaluator with adaptive concurrency

Promote the evaluator out of the orchestrator package into
prime_rl.evaluator and let it run standalone multi-env evals (no
[online] block: one epoch against the served weights, then exit) as
well as SFT online evals ([online]: watch the weights dir per
checkpoint; the sft launcher writes this config).

Scheduling reuses the orchestrator pipeline 1:1: an eval-only
Dispatcher sized by the adaptive ConcurrencyController
([eval.concurrency], replaces eval.max_inflight_episodes), fed by the
InferenceMetricsCollector's /metrics polls. Overload cuts only block
admission - eval episodes are measurements and always run to
completion.

The evaluator spawns an env server per source without an explicit
serve.address; the sft launcher keeps spawning its own and stamps the
derived addresses into the evaluator config.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: stop evaluator collectors before monitor finalize

The periodic logger and the inference-metrics collector log to the W&B
run, so a poll landing after monitors.finalize() warns about a finished
run - mirror the orchestrator and stop them on the clean path first.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: fail fast when adaptive concurrency has no metrics

External inference APIs (e.g. Prime Inference) expose no vLLM /metrics,
so the concurrency controller never bootstraps and the cap would
silently sit at min_inflight forever. The evaluator now probes /metrics
once at startup: no engine metrics + an adaptive band raises with the
fix (pin min_inflight = max_inflight); a pinned band runs fixed with a
warning. A successful probe also bootstraps the controller before the
first dispatch.

Add examples/evals/swe.toml: SWE-bench Verified + Terminal-Bench 2
against deepseek/deepseek-v4-flash on Prime Inference, 1h agent cap,
pinned band.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: rename evaluator command and configs to evals

Per review: the command is uv run evals, the config classes are
EvalsConfig / EvalsEvalConfig in prime_rl.configs.evals, the package is
prime_rl.evals, and the launcher artifacts follow (evals.json,
evals.log, shared-W&B labels). Docs section is Evals. Add EvalsConfig
to the config-load CI check so examples/evals/*.toml are validated.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: drop the Evaluator name entirely

Class Evals in prime_rl.evals.evals, run_evals wrapper, Evals proc
title and log lines; prose refers to the evals process. No identifier
or doc references evaluator anymore.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: drop the standalone evals section for now

Keep the online-evals doc updates (command rename, [eval.concurrency])
and the start-run skill runbook.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: reject skip_first_step on standalone evals

The first trigger honors skip_first_step, and standalone mode has only
that trigger - the run would exit successfully without evaluating
anything. Reject the combination at config time.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: cap CI concurrency at 128 in-flight episodes

The adaptive ramp on CI's small engine floods the router until its
circuit breakers open (ProviderError: No available workers) - 512 is
still past what the deployment sustains.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: lower wiki-search initial_inflight to the CI cap

initial_inflight must not exceed max_inflight.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 15:05:19 -07:00
NeoandGitHub bfb0fe346e Remove pipeline sync in inner loss function loop by replacing the bra… (#3294)
* Remove pipeline sync in inner loss function loop by replacing the branch with branchless code

* Ruff format
2026-08-19 12:56:19 -07:00
NeoandGitHub 2acb19eccd Increase chunk size to 8k (#3302) 2026-08-19 12:53:00 -07:00
69308b88cb chore: move transport code to prime_rl.transports (#3308)
Consolidate the two send/recv stacks under one package:

- prime_rl.transport (rollouts, orch -> trainer) is now
  prime_rl.transports.rollouts
- prime_rl.trainer.rl.broadcast (weights, trainer -> orch -> infer)
  is now prime_rl.transports.weights

Both keep the base.py + concrete implementations structure. The vLLM
worker extensions and the orchestrator weight watcher stay in place
and import the shared primitives from the new location.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 12:14:21 -07:00
0630b7bff7 feat: adaptive concurrency (#3285)
* docs: add adaptive concurrency design

Feedforward token budget (n_max = kappa * C / G) from learned per-env
episode costs, trimmed by a binary engine-overload signal (AIMD on
kappa). Covers eval/train cost weighting, the step-1 freeze, and KV
offloading. Supersedes the reactive KV-target controller from #2908.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: clock adaptive-concurrency updates to steps

Re-evaluate n_max once per training step (G reweigh + at most one
kappa growth) - aligned with the per-step eval gate and naturally
plant-clocked, since step time tracks mean episode time. HARD cuts
stay on the 5s poll: waiting for a step boundary would sustain thrash.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: spec ConcurrencyController abstraction + config

Self-contained controller with [orchestrator.concurrency] config:
max_inflight ceiling (replaces orchestrator.max_inflight_episodes),
optional initial_inflight to skip the ramp, adaptive kill switch.
Kappa initialized by continuity at freeze exit. Pure state machine
driven by collector pushes, dispatcher completions, and the step loop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: adaptive concurrency always on

Drop the adaptive flag from the design - the controller is not
optional. max_inflight is the only escape hatch (hard ceiling).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: adaptive rollout concurrency controller

ConcurrencyController sizes the dispatcher's in-flight cap as
n_max = clamp(kappa * C / G, group_size, max_inflight): a feedforward
token budget from engine KV capacity and learned per-env episode
costs, trimmed by a binary per-engine overload signal (HARD
preemption cut on the 5s poll, per-step growth otherwise). Always on.

- [orchestrator.concurrency]: max_inflight ceiling + initial_inflight;
  replaces max_inflight_episodes and oversampling_factor
- InferenceMetricsCollector always polls (wandb mirroring stays
  gated), parses cache_config_info labels for KV capacity, and pushes
  EngineLoadSample facts to the controller; the old waiting-queue
  overload warning is subsumed by the SOFT signal
- Dispatcher: dynamic set_limit, burst-capped refill, episode
  completion hook (env, kind, tokens, duration)
- configs/concurrency/: three e2e configs (low start, overload start,
  GLM-Air SWE with 10-turn eval)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: backoff naming + config comment fixes

Rename cut factors to BACKOFF_FACTOR / ESCALATED_BACKOFF_FACTOR,
describe kappa as the over-commit factor, add wandb project +
max_num_seqs to the hendrycks e2e configs (the vLLM default of 128
would queue instead of building KV pressure), and point verification
at the W&B gauges (the periodic logger does not feed metrics.jsonl).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: add no-eval concurrency e2e config

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: frozen_steps knob + 50-step e2e configs

concurrency.frozen_steps (default 0) pins the cap for the first k
steps; the first re-evaluation lands at the k -> k+1 boundary. HARD
cuts stay live inside the freeze. The e2e configs run 50 steps at
default gpu_memory_utilization with AIME avg@4 evals every 10 steps,
8k max_model_len, and run names matching the config file names.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: motivate higher frozen_steps values

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: rename concurrency e2e configs

hendrycks-low-no-eval -> hendrycks-initial-low,
hendrycks-low -> hendrycks-initial-low-eval,
hendrycks-high -> hendrycks-initial-high-eval.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: migrate example configs to initial_inflight

The old max_inflight_episodes values become concurrency.initial_inflight
starting caps - a hard ceiling is usually not wanted with the adaptive
controller.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: use config blocks for concurrency in examples

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: raise max_off_policy_steps in hendrycks configs

The adaptive cap runs hundreds of episodes in flight against a
64-sample batch, so episodes span more steps than the default
off-policy budget of 8.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: slash-namespace dispatcher gauge keys

dispatcher/inflight/{train,eval,groups} and
dispatcher/off_policy_level/{max,mean}, mirroring the
cancelled/errored/queued key scheme.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop groups-in-flight gauge

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: derive initial cap from engine max context

With initial_inflight unset, the starting cap is the pessimistic
bound C / max_model_len: an episode cannot exceed the engine context,
so that many episodes always fit. max_model_len comes from /v1/models
(set explicitly or taken from the model config) and also replaces
seq_len as the cost-estimate bootstrap once known.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: richer concurrency logging + wandb inflight mirror

- Active-voice change lines with state snapshots:
  '{Increased,Decreased} concurrency {x} -> {y} at step {n} ({reason})
  - kappa=.. cost=.. capacity=.. signal=..' plus per-env EWMA
  snapshots at debug
- One-time capacity report after the first poll ('Inference reports
  3.0M tokens of KV cache capacity - max model len 8.2K') and a
  derivation line when the initial cap is runtime-derived
- Collector accepts extra_metrics and mirrors
  inference/dispatcher/inflight/{train,eval} into the per-poll W&B
  payload so inflight reads on the engine time axis

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: show inflight vs cap in the wandb overview

Drop the inference/-prefixed mirror; the dispatcher gauges keep their
own keys and join the overview's inference section as one panel
(dispatcher/inflight/{train,eval} + concurrency/max_inflight), on the
same wall-time axis as the engine metrics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: survive out-of-vocab ids in logprobs detokenization

Padded-vocab models (Qwen: logits dim > tokenizer vocab) can sample
out-of-vocab ids once RL updates shift the untrained tail logits.
vLLM's _restore_leading_spaces then iterates a None raw piece and the
TypeError kills the async output processor and the engine (hit twice
in the 50-step concurrency verification runs, at steps 37 and 12).
Guard the raw piece; the id still detokenizes via decode.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: apply concurrency bootstrap only once

The bootstrap guard in observe() held true on every metrics poll
until the first train step set kappa. The cap was recomputed from
the moving cost EWMA every ~5s, so it flapped by hundreds of
episodes before step 1. Latch it: one feedforward raise on the
first capacity observation, then updates only at step boundaries
(HARD cuts stay live).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: say episodes for in-flight units

The dispatcher's permit unit is one episode (one env.run, possibly
several traces), so in-flight logs and identifiers now say episodes:
InflightEpisode, cancel_inflight_{train_,}episodes, and the console
lines (pipeline view, off-policy cancel warning, drain notice, mode
switch).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop cap series from overview inflight panel

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: fix stale overview comment

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: step-clock the cost EWMA folding

The estimates updated per completed episode with alpha 0.1 - a
~10-episode memory over a heavy-tailed length distribution, which
swung G (and the cap) by 20-30% between steps. Completions now
accumulate between step boundaries and fold in as one interval mean
(alpha 0.3 per step), so a step's worth of episodes averages out
before the estimate moves. Simulated max step-to-step cap swing drops
to ~5% under a Pareto length mix at 150 completions/step.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: interpolate eval and train cost mixes

The eval census was a hard 0 -> 1 -> 0 gate: while any eval work was
in flight, G priced the whole pool from the eval mix, then snapped
back to the train mix at the drain boundary. Now the census decrements
per completed eval episode and G blends the two mixes on the eval
share of the cap, min(1, remaining / n_max): a full jump only when the
epoch actually fills the pool, and a continuous glide back to the
train price as it drains.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: 512-episode bias-corrected cost EWMA

Replace the step-folded estimator with a per-episode EWMA at
alpha = 1/512: the smoothing horizon is fixed in episodes, so it no
longer scales with batch size or step cadence. Bias-corrected
(decayed sum over decayed weight) so early estimates equal the plain
mean instead of anchoring on the first episode - an eval env at 120
episodes per epoch prices correctly from its first epoch. Simulated
step-to-step cap swing stays ~5% under a Pareto length mix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: default frozen_steps to 1

At the step-1 boundary the cost EWMA has only seen the episodes that
completed fastest — the short ones — so the first re-evaluation
overshoots the cap (observed 256 -> 2139 with a 2K estimate on SWE
episodes that average far longer). Holding the cap for one step lets
the first full batch complete before the estimate is trusted.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: make frozen_steps=1 actually freeze the first boundary

on_step incremented completed_steps before checking frozen, so the
step-1 boundary compared 1 < frozen_steps and values 0 and 1 behaved
identically (observed: frozen_steps=1 still re-evaluated at step 1
off a 1.8K biased cost estimate). Snapshot frozen before the
increment: k now freezes the first k boundaries.

Also exempt the one-shot bootstrap derivation from the freeze — it
sets the starting value the freeze pins, so blocking it under the
new default of 1 would strand no-initial_inflight runs at the floor.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: simplify frozen_steps docstring

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: cap hendrycks e2e configs at 1024 inflight

The duty-cycle gap (episodes spend ~35% of wall time outside an open
engine request) lets kappa compound the cap well past useful engine
load on the sanity envs - ceiling it at 1024.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: allow SignSGD with full optimizer offload

SignSGD is stateless, so it runs through the wrapper's generic
per-chunk CPU step path (plain GradientOffloadManager + _step_chunk)
with no AdamW-specific machinery. Halves per-rank CPU optimizer
state vs AdamW full offload by dropping both moment buffers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: queue-overload HARD cut for agentic rollouts

Agentic rollouts overload inference by queueing, not preempting:
vLLM's admission control parks excess load in the waiting queue, so
the preemption HARD gate never fires (observed: 213 capacity-queued
vs 192 running, prefix-cache hit rate 0.06, num_preemptions_total 0,
and a 5x step-time blowup while the controller raised the cap on a
SOFT signal).

Classify HARD when capacity-queued requests exceed QUEUE_RATIO of
running for QUEUE_PERSISTENCE_POLLS consecutive polls (persistence
filters natural turn-completion bursts), and cut to just under what
the engines actually serve (0.9x running) instead of backing off
from inflated inflight. The metrics collector now ships running and
the by-reason waiting breakdown in EngineLoadSample; engines without
the breakdown fall back to total waiting.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: shed youngest episodes on overload cut

A cut only blocks new admissions, so the over-admitted episodes keep
thrashing the prefix cache until they finish at degraded throughput
(observed: 690 -> 320 cut took 20+ min to drain, with 10-18 min steps
and a 0.05 hit rate the whole way). Bind an on_overload hook from the
controller to the dispatcher: cut() reports the episode excess and
the dispatcher drops that many in-flight train episodes, youngest
groups first (least inference spend), reusing the off-policy
drop_group path so the sink finalizes partial groups.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: slew-limit cap growth to 1.25x per re-evaluation

A raise floods in fresh episodes whose fast finishers drag the cost
EWMA down, inviting a bigger raise (observed 256 -> 567 -> 690 while
the estimate fell 7.7K -> 6.3K). Limiting upward moves to 1.25x per
step turns the spiral into a ramp the queue-overload cut interrupts
after one increment. Cuts stay unlimited.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: cuts never raise the cap; unwire shed-youngest for now

The queue cut targets 0.9x running, but running can be inflated by
work the dispatcher no longer tracks — observed live: 'Increased
concurrency 231 -> 256 (queue overload)'. Clamp cut targets to the
current cap.

Unwire on_overload -> shed_youngest: cancelling the orchestrator task
does not abort the env-side rollout (3195 starts vs 2616 done after
shedding 489 episodes, none stopped Cancelled), so shedding leaves
zombies hitting inference while the freed permits admit new episodes
on top — total load rises. Keep the dispatcher method; rewire once
rollout abort propagates to the env server.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: floor the cost estimate with measured request cost

Completion-based estimates only see finished episodes; after a cap
raise the fast short episodes finish first and drag the estimate
down, inviting a bigger raise (observed 7.7K -> 6.3K -> 5.5K while
the cap spiraled 256 -> 690). The live request stream has no such
bias: every turn resends its episode's full context, so in-flight
episodes are counted at their current size the whole time they run,
and single-turn workloads are covered by the generation term.

The collector derives mean prompt+generation tokens per request from
the vLLM histogram deltas each poll; the controller folds them into
a request-weighted decayed mean and takes the max of it and the
completion mix. Drop frozen_steps in the e2e config to test that the
cold-start freeze is no longer needed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: size-bias the measured request cost

A plain per-request mean under-prices the in-flight pool: small
contexts take turns far more often than the large residents that
actually fill KV (observed: request mean 6.7K while resident cost
was 13.2K per running request, so the feedforward equilibrium sat
2x above true capacity and every ramp ended in a queue cut).
Weigh each request by its own token mass instead — E[X^2]/E[X]
from the prompt-histogram bucket deltas, midpoint-approximated,
+Inf bucket bounded by the engine max context. On the live GLM
distribution this reads 16.8K vs the 13.2K resident measure:
slightly conservative, and kappa growth learns back the slack.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: clock kappa growth on polls, not step boundaries

Step-clocked growth adapts at wildly different speeds across
workloads (steps range seconds to tens of minutes), and its binding
check sampled inflight at the boundary instant — exactly when
episode completions burst — so kappa stalled while the cap was
binding all step long (observed: kappa stuck at 1.13 for three clear
steps with the engine at 0.99 prefix hit). Grow kappa a small factor
per clear-and-binding poll instead; SOFT vetoes become per-poll for
free.

Also fall back to the observed request cost (not the pessimistic
engine max context) for envs without completions — the max-context
fallback made kappa's continuity init read a user-set start as an
intentional ~4x over-commit whenever step 1 completed before any
episode did.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: early growth brake and kappa ceiling memory

Thrash onset is a cliff, not a slope: prefix hit went 0.97 -> 0.06
within two minutes of kappa growing past the workload's true
over-commit (job 748: clean climb to kappa 1.51 / cap 380, then a
queue cut to 197). Two additions:

- Veto kappa growth on any poll with capacity-queued requests.
  Unlike generic waiting, capacity-queuing means KV blocks are full
  right now; the 2-poll waiting filter let growth feed the cap
  through the cliff between bursts.
- Remember the ceiling: an overload cut pins growth at 0.9x the
  kappa that overloaded, so the ceiling is rediscovered by a wobble
  instead of a fresh thrash episode every cycle (without memory the
  sawtooth re-pays the full discovery cost forever). A slow relief
  (~+2% per 10 min) lets a genuinely lightened workload re-probe.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* docs: update adaptive concurrency for the measured-cost controller

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: clock the controller on pipeline turnovers, not steps

Step duration varies from seconds to tens of minutes across
workloads, so anything step-clocked adapts at workload-dependent
speed. Re-evaluate the cap every poll (with a 2% deadband against
estimate noise) and bound raises by the pipeline turnover: each
completion advances the clock by 1/inflight, so one turnover means
the in-flight pool has been replaced once regardless of scale — 100
completions at concurrency 10 buy 10x the raise budget of 100 at
concurrency 1000, matching how much less biased their estimates
are. Raises compound at most 1.25x per turnover; cuts and decreases
are never limited.

The turnover slew subsumes frozen_steps (the cap can never outrun
the pipeline's demonstrated stability), so the config field is
removed. Kappa now initializes on the first poll with real cost
data instead of the first step boundary; on_step shrinks to eval
bookkeeping and backoff reset.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: SOFT signal on high KV usage

Thrash onset is a cliff at full KV, and the queue-based signals only
fire once it is already happening. Live-request KV usage rises ahead
of it (measured ~0.53 at healthy load, ~1.0 at thrash), so treat any
decode engine above 0.8 as SOFT: growth stops while there is still
headroom to absorb in-flight context growth, cuts stay queue-driven.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: lower KV-usage SOFT threshold to 0.7

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: shed on overload now that rollout abort propagates

Bump verifiers to feat/rollout-abort (26eafc07): cancelling the
orchestrator-side task now aborts the env-side rollout, so
Dispatcher.shed_youngest no longer creates zombies — rewire it to
the controller's on_overload hook. An overload cut now sheds the
youngest in-flight episodes immediately instead of draining the
excess for tens of minutes at thrashed throughput.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: proportional kv-headroom trim

Cap moves alone cannot relieve pressure from episodes maturing in
place — they only block admissions. Observed on the kv-soft gate:
growth froze at usage 0.7 and the cap eased 371 -> 326, but the
admitted pool's contexts grew ~15%/step under it and crossed the
thrash cliff (prefix hit 0.05) within minutes anyway.

With rollout abort now propagating, trim the pool itself: above
KV_USAGE_TARGET (0.85), set the cap to inflight * target / usage and
shed the excess youngest episodes, on a short cooldown so each trim
propagates before the next is sized. Holds usage at the target
continuously instead of riding to the cliff and paying a full
queue-overload cut; the queue gate remains the backstop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: kv-headroom trims re-derive kappa

A trim that lowers only the cap gets undone by the feedforward: the
slew allowance regrows per completion and the cap creeps back into
the trim zone, shedding ~8-16 young episodes every cooldown
(observed: 4 trims in 2.5 min). Re-derive kappa from the trimmed cap
the way cuts do; with growth already vetoed above KV_USAGE_SOFT this
yields a grow (<0.7) / hold (0.7-0.85) / trim (>0.85) usage band
instead of a shed loop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: address PR review comments

- Treat the admitted unit as a black box in the controller docstring;
  docstring-style constants describing meaning only.
- Constants: ESTIMATE_ALPHA 1/1024, BACKOFF_FACTOR 0.8, KAPPA_MAX 8,
  QUEUE_PERSISTENCE_POLLS 6 (react within a minute).
- Rename RolloutDispatcher -> Dispatcher, inflight_permits ->
  current_inflight, shed_youngest -> cancel_inflight.
- Drop the out-of-vocab detokenization patch.
- Configs: initial_inflight = batch_size with a 2x max_inflight
  ceiling across the example and nightly configs.
- Docs: trim the adaptive-concurrency intro.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: weight the cost mix by live in-flight counts

The sampling-ratio weighting predicted the standing mix and needed
two corrections bolted on: duration weighting (admission mix vs
standing mix) and the eval-census interpolation (predicting the mix
through eval epochs). The dispatcher knows the standing mix exactly
— weight the per-env estimates by its live per-(kind, env) in-flight
counts instead. Train and eval need no separate treatment (eval
units enter the mix as they are admitted), so the census, its
interpolation, and the duration weighting are deleted; the
configured ratios remain only as the empty-pool fallback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: hysteresis for kv-headroom trims

Trimming exactly to the trigger guarantees an immediate re-trigger
under monotonic pool growth (observed: trims every cooldown, 16-40
units each, while survivors grew ~15%/step). Trigger at 0.85 but
resize to 0.75, so each trim buys growth headroom before the next.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: lower kv-usage thresholds (soft 0.6, trigger 0.8, target 0.7)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat!: reduce the controller to measured AIMD

The feedforward kappa*C/G no longer controlled anything: the
turnover slew was the binding constraint on every ramp (raw targets
sat 2-5x above the cap), the usage trim overrides it on the way down
(it was added precisely because G-tracking is too slow for in-place
pool growth), and the gates own overload. Everything that computed G
existed to produce a number the other mechanisms clipped.

Replace it with AIMD on measured KV pressure, turnover-clocked:
grow the cap x1.25 per pipeline turnover while engines are clear,
usage < 0.6 and the cap binds; trim pool+cap to usage 0.7 above 0.8;
cut on preemptions (0.8x inflight) or persistent capacity-queueing
(0.9x running), cancel the excess, drain-latch, escalate to 0.5x if
overload survives a drain. The starting cap is user-set or
C / max_model_len — the only cost-like quantity left, read once.

Deleted: kappa and its ceiling/relief, both cost estimators (per-env
completion EWMAs and the size-biased request census with its
histogram parsing), cost_estimate/mix_cost, the inflight-mix hook,
the re-evaluation deadband, slew_allowance as a separate mechanism
(the growth law absorbs it), and on_step. ~480 -> ~280 lines with
no model of unit cost anywhere.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: align tests, configs and docs with the AIMD controller

Fix the hendrycks configs (high-eval start needs its ceiling at the
starting cap; freeze-era header comments), rewrite the adaptive
concurrency docs for the measured-AIMD design, and revert the
SignSGD full-offload allowance — SignSGD crashes with an async CUDA
illegal memory access on this stack, so the guard stays until that
is fixed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: min_inflight escape hatch

A hard floor on the adaptive cap (None auto-sets to 1). Setting
min_inflight = max_inflight pins the cap, recovering fixed-concurrency
behavior; not recommended in practice.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: address second review round

- Rename Dispatcher param max_inflight_episodes -> initial_max_inflight
  and document its relation to max_inflight_ceiling (starting value of
  the dynamic cap vs the configured hard maximum bounding out_q).
- Drop the dead n <= 0 guard in cancel_inflight (resize_down only
  calls it with a positive excess).
- Public hook attributes on the controller (set_limit, get_inflight,
  on_overload); single float-returning clamp; unconditional
  apply_limit on growth (it no-ops when unchanged).
- Gauges: capacity_tokens -> capacity; drop queue_overload_polls.
- Remove the stale detokenization NOTE in the vLLM server.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: revamp the concurrency e2e config matrix

Two workloads x four scenarios, all descriptively named and capped at
max_inflight = 1024:

- hendrycks (single node, 4 train + 4 infer GPUs, mirrors the
  hendrycks-sanity example; replaces the 2-GPU variants):
  initial-low (16, grow from near zero), initial-none (derived
  start), initial-high (1024, cut from overload), evals (256 + AIME
  avg@4 every 10 steps). gpu_memory_utilization = 0.2 shrinks the KV
  budget artificially so the controller operates below the ceiling
  instead of at huge concurrency.
- glm-air (2 nodes, replaces glm-air-swe): the same three initial
  scenarios plus evals (256 + 10-turn-capped SWE-Bench Verified
  every 10 steps). Each config uses its own sandbox label so
  parallel runs cannot delete each other's sandboxes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: slurm blocks for the hendrycks e2e configs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: pin flash_attention_2 for the hendrycks e2e configs

R1-Distill-Qwen-1.5B resolves to the HF model impl, and attn=auto
resolves to flash_attention_3, which requires the custom impl — the
trainer refused to start.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop the initial-low e2e variants

The low start exercises the same turnover ramp as the derived start,
just from a lower anchor — the none variant covers it. Final matrix:
{none, high, evals} x {hendrycks, glm-air}.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: 4 API server processes for the hendrycks e2e configs

The initial-high run (1024 concurrent clients) killed vLLM's single
ApiServer process; the frontend needs to scale with the client
count.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: pin the hendrycks KV budget via num_gpu_blocks_override

Even at low gpu_memory_utilization the 1.5B model gets ~12.8M KV
tokens, putting the usage band above the max_inflight ceiling — the
derived start clamped to the ceiling and the none scenario
degenerated into the high one. Pin ~2.1M tokens so the derived start
(~256) and the band (~350-400) sit well below the ceiling.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: min_inflight is the only cap floor

Drop the implicit group_size floor: group episodes are admitted
individually, so a group trickles through in waves below its size —
nothing requires a group to fit in flight at once. min_inflight
(default 1) is now the single lower bound, and recovery from tiny
caps is fast in turnover terms (at inflight 1 every completion is a
full turnover).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: start hendrycks-initial-high at 700

Two attempts at a 1024 start died to vLLM ApiServer processes being
signal-killed under the client connection storm (with 1 and with 4
frontend processes). 700 is still decisively over the pinned ~350-400
usage band, so the overload-cut scenario is intact without stressing
the frontend.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: prime VM sandboxes for hendrycks-initial-high

The ApiServer deaths under the 1024 start were host thrash from 1024
subprocess-runtime episodes spawning local processes, not the client
connections. Run the high scenario on prime VM sandboxes and restore
the 1024 start.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: hold the drain latch until the engines settle

Cuts cancel episodes, so dispatcher inflight drops below the cap
almost immediately while the engines still churn through their own
backlog — preemption deltas from that stale churn re-triggered
escalated cuts every poll (observed cascade: 1024 -> 8, one halving
per 5s). Release the drain only when inflight is under the cap AND
the poll shows no preemptions or queue overload.

Also fix the hendrycks KV pin for 64-token blocks (32768 blocks gave
8.4M tokens, not 2.1M — the derived start clamped to the ceiling and
triggered the storm in the first place).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: say episodes, not units, in console logs

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Refund admission burst budget on episode completion

The burst window capped gross admissions at max(group_size, cap/10)
per 5s. For fast single-turn episodes the completion rate exceeds that
admission rate, so inflight equilibrates at admission_rate x duration
(observed: 24 at cap 58) and the cap never binds, locking out growth.
Completions now refund the window budget: the window meters net pool
growth, so ramps stay smoothed while steady-state replacement is
never throttled.

Also switch the hendrycks e2e configs to prime VM sandboxes and fix
num_gpu_blocks_override for 16-token blocks (FA2 backend), restoring
the intended 2.1M-token KV budget.

* Fix four controller/dispatcher bugs from review

- Growth was dead below cap 10: the permit is released before the
  completion hook fires, so the binding check read inflight <= cap - 1
  and 0.9 * cap was unsatisfiable for small caps. Count the completing
  episode back in.
- Queue cuts targeted 0.9 x engine running requests but the cap counts
  episodes; agentic episodes idle between turns, so this over-cut by
  the duty cycle. Cut in pool units like the preemption path.
- Escalation latched forever: it only reset on a CLEAR-poll drain
  release, but steady state post-cut sits in the SOFT usage band, so
  every later cut halved. Reset via a grace window of polls after the
  drain instead.
- Overload sheds count only live cancellations toward the excess;
  never-dispatched markers free no permits and made sheds undershoot.

Also expire the growth gate 15s after the poll that set it: if the
metrics path stalls (the very state runaway growth creates), growth
freezes instead of compounding blind. And skip growth on error-marker
completions (tokens <= 0) — they consumed no engine capacity, and a
slow-failing error storm otherwise grows the cap against idle engines.

* Drop cluster-specific node exclude from e2e configs

* Budget hendrycks e2e concurrency for the sandbox gateway

VM-sandbox runtimes hold one sandbox per in-flight episode, so peak
concurrency across concurrent runs must stay under ~1k or the gateway
429s. Cap the three runs at 400/300/256 and shrink the KV budget to
786K tokens (12288 blocks x 16-token FA2 blocks x 4 engines) so the
optimal band (~175) sits below every ceiling and each run still
exercises its intended path (cut down / grow up / absorb eval waves).

* Read KV capacity from kv_cache_size_tokens

The num_gpu_blocks label in vllm:cache_config_info does not reflect
num_gpu_blocks_override, so the derived capacity was 4x too high on
runs that pin the block count. kv_cache_size_tokens reports the
actual budget; keep the block product as a fallback for engines that
do not expose it.

* Adapt GLM-4.5-Air SWE example to a 4-node FP8 recipe

1 trainer node (sign-SGD full CPU offload, cp=4) + 3 FP8 inference
replicas with online quantization. The concurrency section is removed:
the controller runs on defaults, deriving its start from the measured
KV budget.

* Remove concurrency debug configs

The hendrycks/glm-air matrix configs were development scaffolding for
the e2e verification runs; the results live in the PR description.
The GLM-4.5-Air SWE example is the maintained recipe.

* Use fp8_per_block online quantization in the GLM-Air example

Matches the research-prod GLM recipe: the bf16 checkpoint is loaded
and quantized online, since NCCL weight broadcasts push bf16 trainer
weights into the engines on every update.

* Guard None raw tokens in logprobs detokenization

tokenizer.convert_ids_to_tokens returns None for ids outside the
tokenizer vocabulary. Models with embedding padding past the tokenizer
(e.g. R1-Distill-Qwen) can sample such ids; _restore_leading_spaces
then iterates None and the TypeError kills the AsyncLLM output loop
and the whole API server with it. Observed as recurring random
'ApiServer died with exit code None' crashes under sustained sampling.

* Revert "Guard None raw tokens in logprobs detokenization"

This reverts commit 0c1b5d4992eb99f1ea4c0a7c6a999daeca5cc95c.

* Order concurrency fields initial, min, max

* Route GLM-Air FP8 through DeepGEMM kernels

Without a block-wise FP8 GEMM backend the engine falls back to
torch._scaled_mm, which asserts on block-scale shapes during engine
init. Enable DeepGEMM and disable the FlashInfer block-scale GEMM,
matching the research-prod GLM recipe.

* Serve GLM-Air FP8 checkpoint with kernel-format weight transfer

The online fp8_per_block path crashes for glm4_moe on this stack (the
block-scale GEMM falls back to torch._scaled_mm and asserts), so the
example serves the native FP8 checkpoint instead. Weight updates then
need trainer-side quantization: implement convert_layer_to_vllm_kernel
for glm4_moe (standard GQA qkv fusion; the MoE handling mirrors
GLM-MoE-DSA, whose MoE layout is identical) and enable
quantize_in_weight_transfer.

The kernel copy path has no TP shard handling, so the engines run
EP experts + DP attention (data_parallel_size=8), matching the GLM
prod deployment shape. Trainer keeps the bf16 checkpoint; the
orchestrator addresses the served FP8 name.

* Disable MoE DP chunking for the FP8 GLM-Air engines

The cutlass FP8 MoE DP-chunking path under-sizes its permute scratch
for large profile/prefill batches (moe_permute asserts
n_token <= max_num_tokens), killing the engine at init. Same
mitigation as the GLM prod recipe.

* Serve GLM-Air FP8 via per-tensor online quantization

Both block-scale FP8 attempts crash for glm4_moe on this stack (the
blockscale GEMM asserts at engine init; the cutlass MoE DP-chunk
scratch under-sizes). Per-tensor online quant uses the standard
scaled_mm and fused-MoE FP8 kernels, keeps plain TP=8, and re-uses the
same quantize-on-load path for weight broadcasts.

* fix: stop metrics collector before finalizing monitors

The collector's poll loop outlived monitors.finalize() on clean exit,
so its next wandb.log hit the finished run and surfaced as a spurious
'Inference metrics poll failed: UsageError' warning. Stop it first;
the teardown's second stop() is a no-op.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Bump verifiers to a3188c06

Rollout-abort cleanup hardening: shielded sandbox create, strongly
referenced cancel tasks, and cancel drain on client close.

* Fix four review findings; drop unused glm4_moe kernel converter

- Overload signals read decode engines only: in P/D deployments a
  prefill queue or prefill preemption is normal flow and must not
  trigger cuts.
- Batch/group divisibility is checked after the batch-size default
  lands, so a config setting only group_size cannot pass with a
  non-divisible default.
- A group's age for youngest-first shedding is its oldest member's
  start; taking the newest made long-running groups look young and
  cancelled the most sunk cost.
- Admission-window refunds apply only to natural completions: refunding
  cancelled episodes handed a mass shed's worth of burst budget to the
  refill while the overload was still draining.

The glm4_moe kernel-format converter served the abandoned
quantize_in_weight_transfer experiment; the example now uses plain
online quantization, which needs no trainer-side support.

* Explain adaptive concurrency by intuition in the docs

Drop thresholds, constants, and the config listing from the docs
section; describe grow/trim/cut as probe-and-back-off against the
engines. Bump verifiers for the cancel-path race fixes.

* Drop unrelated changes from the branch

The detokenizer patch ships separately in #3304; the pydantic-config
pointer bump was an accidental sweep of local submodule state.

* Address review: config defaults and small cleanups

- max_inflight defaults to 1024: an unbounded default made the growth
  path's failure modes existential; None still removes the ceiling.
- min_inflight defaults to 1 instead of None-meaning-1, simplifying
  the bounds validator.
- Signal is a Literal instead of an Enum.
- Reword the admission-smoothing comment.

* Raise max_inflight in examples exceeding the new default ceiling

* a few minor tweaks

* Bump verifiers to 6bcedc76 (merge main into rollout-abort)

* Update lockfile for verifiers 0.3.1.dev57

* chore: cap CI RL runs at 512 inflight

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: dedupe concurrency block in wiki-search CI config

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Bump verifiers to main (rollout-abort merged)

feat/rollout-abort landed as PrimeIntellect-ai/verifiers#2396; the
submodule now tracks verifiers main.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 11:17:21 -07:00
Mika SenghaasandGitHub 5ed05cf6ac chore: bump workflow actions to latest versions (#3306)
checkout v5 -> v7, setup-uv v7 -> v10.0.1, upload-artifact v4/v5 -> v7,
download-artifact v6 -> v8, github-script v8 -> v9. All self-hosted
runners are on 2.336.0, above the 2.327.1 floor the node24-based
majors require. setup-uv stopped publishing floating major tags with
v8, so it now pins the exact release.

Also sync the CI ruff pin (0.13.0 -> 0.15.14) with uv.lock so CI
lints with the same ruff version as local runs.
2026-08-19 20:15:06 +02:00
1c0720d975 feat: sign-SGD support for full CPU optimizer offload (#3303)
Allow optim.type = "sign_sgd" with model.full_offload. SignSGD is
stateless, so full offload needs only 8 B/param of host RAM (FP32
master + FP32 accumulated gradient) instead of AdamW's 16 B/param
(master + two FP32 moments + accumulated gradient).

- Add a native multi-tensor CPU sign_sgd_step kernel mirroring the
  AdamW span kernel (BF16/FP32 grads, BF16/FP32 compute-param
  write-out, at::parallel_for). The kernel drops the gradient scale:
  sign(scale * g) == sign(g) for scale > 0.
- Generalize FullCPUOffloadOptimizer's native plumbing (bounded
  gradient manager, chunk stepping, sync fallback, checkpoint load,
  scheduler _opt_called marker) over a combined native-optimizer flag.
- Skip CPU optimizer state materialization for SignSGD everywhere:
  checkpoints carry only the FP32 masters.
- Relax the trainer/SFT config validators and setup_optimizer guard to
  accept sign_sgd; update docs and the start-run skill.
- Add a bit-exact parity test against the python SignSGD reference
  (BF16/FP32 grads, wd 0 and >0, zero grads, scalar-tail sizes).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 17:08:50 -07:00
195 changed files with 6004 additions and 4016 deletions
+1
View File
@@ -0,0 +1 @@
../skills
+4 -4
View File
@@ -146,7 +146,7 @@ jobs:
id: artifact
run: echo "name=benchmark-${{ matrix.runner }}-$(echo '${{ matrix.model }}' | sed 's/\//--/')-${{ matrix.type }}-${{ matrix.lora_rank || 'full' }}-${{ matrix.num_gpus }}gpu-${{ matrix.ac }}-${{ matrix.attention }}-${{ matrix.seq_len }}-cp${{ matrix.cp }}-ep${{ matrix.ep }}" >> "$GITHUB_OUTPUT"
- name: Upload benchmark result
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v7
if: always()
with:
name: ${{ steps.artifact.outputs.name }}
@@ -163,16 +163,16 @@ jobs:
pull-requests: write
steps:
- name: Checkout repository # We can't use the image because then no git
uses: actions/checkout@v5
uses: actions/checkout@v7
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync
- name: Download all benchmark artifacts
uses: actions/download-artifact@v6
uses: actions/download-artifact@v8
with:
path: /tmp/benchmark_artifacts
pattern: benchmark-*
+2 -2
View File
@@ -103,7 +103,7 @@ jobs:
esac
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
ref: ${{ env.BUILD_REF }}
fetch-depth: 0
@@ -170,7 +170,7 @@ jobs:
fi
- name: Checkout
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
ref: ${{ needs.prepare.outputs.ref }}
fetch-depth: 0
+155
View File
@@ -0,0 +1,155 @@
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"
+4 -4
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
@@ -20,7 +20,7 @@ jobs:
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
@@ -48,9 +48,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
+1 -1
View File
@@ -20,7 +20,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Create next .dev tag from latest release
uses: actions/github-script@v8
uses: actions/github-script@v9
with:
script: |
const { owner, repo } = context.repo;
+5 -5
View File
@@ -26,7 +26,7 @@ jobs:
apt-get install -y git
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
@@ -34,7 +34,7 @@ jobs:
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
@@ -94,7 +94,7 @@ jobs:
apt-get install -y git
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
@@ -102,7 +102,7 @@ jobs:
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
@@ -120,7 +120,7 @@ jobs:
run: uv run pytest -vvs ${{ matrix.pytest_args }}
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v7
with:
name: ${{ matrix.test }}-logs
path: /tmp/outputs/**/*.log
+3 -3
View File
@@ -31,7 +31,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
@@ -70,7 +70,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
@@ -159,7 +159,7 @@ jobs:
echo "tag=$tag" >> "$GITHUB_OUTPUT"
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
- name: Install prime CLI (latest)
run: uv tool install prime
+3 -3
View File
@@ -23,7 +23,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
@@ -73,7 +73,7 @@ jobs:
apt-get install -y git
git config --global --add safe.directory "$GITHUB_WORKSPACE"
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
@@ -81,7 +81,7 @@ jobs:
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v7
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
+3 -3
View File
@@ -15,17 +15,17 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v5
uses: actions/checkout@v7
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
with:
submodules: false
- name: Run ruff
uses: astral-sh/ruff-action@v4.1.0
with:
version: "0.13.0"
version: "0.15.14"
args: "check --config=pyproject.toml"
- name: Run ruff format (check)
uses: astral-sh/ruff-action@v4.1.0
with:
version: "0.13.0"
version: "0.15.14"
args: "format --check --config=pyproject.toml"
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
trigger-docs-sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v7
- name: Validate mint.json pages exist
run: |
+40 -11
View File
@@ -29,7 +29,7 @@ jobs:
version: ${{ steps.tag.outputs.version }}
steps:
- name: Checkout main
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
fetch-depth: 0
@@ -113,9 +113,22 @@ jobs:
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
release-from-auto-tag:
# 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]
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
contents: write
@@ -138,24 +151,23 @@ jobs:
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
tag-and-release:
resolve-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
outputs:
tag: ${{ steps.release.outputs.tag }}
version: ${{ steps.release.outputs.version }}
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
fetch-depth: 0
ref: refs/tags/${{ inputs.tag }}
- name: Checkout tagged release (push)
if: github.event_name != 'workflow_dispatch'
uses: actions/checkout@v5
uses: actions/checkout@v7
with:
fetch-depth: 0
@@ -207,11 +219,28 @@ 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]
runs-on: ubuntu-latest
permissions:
contents: write
# Needed to dispatch build_image.yaml below (POST .../dispatches).
actions: write
steps:
- name: Publish draft release
id: publish
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
TAG: ${{ needs.resolve-release.outputs.tag }}
run: |
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
@@ -232,6 +261,6 @@ jobs:
if: steps.publish.outputs.published == 'true'
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
TAG: ${{ needs.resolve-release.outputs.tag }}
run: |
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
+3
View File
@@ -10,3 +10,6 @@
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
[submodule "prime-kernels"]
path = deps/prime-kernels
url = https://github.com/PrimeIntellect-ai/prime-kernels
+113
View File
@@ -0,0 +1,113 @@
#!/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()
+6 -14
View File
@@ -34,20 +34,12 @@ max_completion_tokens = 768
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
+5 -11
View File
@@ -21,17 +21,11 @@ seq_len = 8192
[[orchestrator.train.source]]
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
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.model]
seq_len = 16384
+3 -9
View File
@@ -24,15 +24,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+3 -9
View File
@@ -29,14 +29,8 @@ max_completion_tokens = 1024
[[eval.source]]
name = "reverse-text"
[eval.source.env.taskset]
id = "reverse-text"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
+3 -9
View File
@@ -42,15 +42,9 @@ max_completion_tokens = 512
[[orchestrator.train.source]]
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
+3 -9
View File
@@ -23,15 +23,9 @@ group_size = 8
[[orchestrator.train.source]]
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
+12 -17
View File
@@ -19,28 +19,23 @@ lr = 1e-5
batch_size = 128
group_size = 8
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 384
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 2
max_turns = 2
min_names_per_turn = 1
max_names_per_turn = 3
[orchestrator.train.source.env.taskset.task]
similarity_power = 4
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 2
env.taskset.max_turns = 2
env.taskset.min_names_per_turn = 1
env.taskset.max_names_per_turn = 3
env.taskset.task.similarity_power = 4
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -15,13 +15,13 @@ lr = 5e-5
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -30,15 +30,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -12,13 +12,13 @@ lr = 5e-5
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -27,15 +27,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -22,20 +22,17 @@ impl = "custom"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -24,6 +24,9 @@ name = "ci-rl-opd"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.algo]
type = "opd"
@@ -39,15 +42,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -58,15 +55,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -24,6 +24,9 @@ name = "ci-rl-sft"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.algo]
type = "sft"
@@ -45,15 +48,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -64,15 +61,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
@@ -5,9 +5,6 @@ max_steps = 10
[resume]
step = 5
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -2,9 +2,6 @@ max_steps = 5
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -22,20 +22,17 @@ lr = 3e-6
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -19,20 +19,17 @@ lr = 3e-6
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
+9 -14
View File
@@ -18,22 +18,17 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 768
+11 -20
View File
@@ -18,19 +18,16 @@ batch_size = 512
group_size = 8
seq_len = 8192
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
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"
[orchestrator.eval]
interval = 50
@@ -38,15 +35,9 @@ interval = 50
[[orchestrator.eval.source]]
name = "aime2024"
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "aime24"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer]
+6 -9
View File
@@ -18,17 +18,14 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 128
+7 -10
View File
@@ -17,19 +17,16 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
oversampling_factor = 2.0
[orchestrator.concurrency]
initial_inflight = 128
max_inflight = 128
[[orchestrator.train.source]]
name = "wiki-search"
[orchestrator.train.source.env.taskset]
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
+6 -9
View File
@@ -18,17 +18,14 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[[orchestrator.train.source]]
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
@@ -17,21 +17,18 @@ language_model_attr = "model.language_model"
batch_size = 256
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.source]]
name = "color-codeword"
[orchestrator.train.source.env.taskset]
id = "color-codeword"
images_per_turn = 1
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "color-codeword"
env.taskset.images_per_turn = 1
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer]
+6 -14
View File
@@ -26,20 +26,12 @@ alpha = 0.1
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
+6 -18
View File
@@ -23,15 +23,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -42,15 +36,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -23,15 +23,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -42,15 +36,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+12 -34
View File
@@ -33,34 +33,18 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-grpo"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-opd"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[orchestrator.train.source.algo]
type = "opd"
[orchestrator.train.source.algo.teacher]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
base_url = "http://localhost:8001/v1"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
algo.type = "opd"
algo.teacher.name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
algo.teacher.base_url = "http://localhost:8001/v1"
[orchestrator.eval]
interval = 5
@@ -71,15 +55,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -35,15 +35,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -54,15 +48,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -21
View File
@@ -35,15 +35,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -54,15 +48,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 1e-4
@@ -70,9 +58,6 @@ lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
+10 -30
View File
@@ -23,21 +23,11 @@ max_completion_tokens = 512
[[orchestrator.train.source]]
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -48,21 +38,11 @@ max_completion_tokens = 512
[[orchestrator.eval.source]]
name = "kuhn-poker"
[orchestrator.eval.source.env.taskset]
id = "kuhn-poker"
[orchestrator.eval.source.env.player0.harness]
id = "null"
[orchestrator.eval.source.env.player0.runtime]
type = "subprocess"
[orchestrator.eval.source.env.player1.harness]
id = "null"
[orchestrator.eval.source.env.player1.runtime]
type = "subprocess"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -31,15 +31,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -50,15 +44,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -18
View File
@@ -40,15 +40,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -59,15 +53,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+6 -21
View File
@@ -40,15 +40,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 1
@@ -59,15 +53,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 1e-4
@@ -75,9 +63,6 @@ lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
+139
View File
@@ -0,0 +1,139 @@
# Concurrency-controller debug run: GLM-4.5-Air on the v1 `scaleswe` SWE taskset,
# bash harness on a prime sandbox runtime, 1 train + 1 infer node, eval on 100
# SWE-Bench Verified instances. Concurrency is fully default: the controller
# derives its start from the measured KV budget and adapts from there — watch
# the concurrency/* gauges in W&B or the "Concurrency ..." lines in the
# orchestrator log.
#
# Inference serves FP8 via online per-tensor quantization of the bf16
# checkpoint; weight broadcasts re-quantize through the same path on every
# update. The trainer fits on one node via cp=4 (ulysses), full CPU optimizer
# offload with the stateless sign-SGD optimizer, plus the memory improvements
# from the GLM-5.1 prod run: LM-head token chunking, activation checkpointing
# (freq=1) + activation offloading (max_inflight=1), and skip-gather /
# skip-optimizer checkpointing. Router replay is enabled — GLM-4.5-Air is a
# glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the input-token and turns
# coefficients set to 0.1.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "debug-concurrency"
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "debug-concurrency" -y || true'
[deployment]
type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 1
[monitors.wandb]
project = "swe-ablations"
name = "debug-concurrency"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
[resume]
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_optimizer = true
[trainer.optim]
type = "sign_sgd"
# --- Orchestrator ---
[orchestrator]
batch_size = 128
group_size = 8
max_off_policy_steps = 32
[orchestrator.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
num_examples = 100
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["debug-concurrency"]
env.agent.timeout.rollout = 3600
# --- Inference ---
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
quantization = "fp8"
enable_return_routed_experts = true
+9 -27
View File
@@ -19,27 +19,15 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text-a"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text-b"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 5
@@ -50,15 +38,9 @@ max_completion_tokens = 128
[[orchestrator.eval.source]]
name = "reverse-text"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
Vendored Submodule
+1
Submodule deps/prime-kernels added at 2ceaf9eccb
+1 -1
+1 -6
View File
@@ -115,12 +115,7 @@ dropout = 0.0
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
```toml
[ckpt.weights]
save_adapter_separately = true
```
LoRA is supported across SFT and RL. NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. Broadcast dirs of LoRA runs contain the raw adapter (`adapter_model.safetensors` + `adapter_config.json`).
## Disaggregated Prefill/Decode Inference
+38 -70
View File
@@ -124,54 +124,40 @@ type = "grpo"
[[orchestrator.train.source]]
name = "math" # inherits the top-level grpo
[orchestrator.train.source.env.taskset]
id = "math"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "terminal"
[orchestrator.train.source.env.taskset]
id = "terminal"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "terminal"
env.agent.harness.id = "bash"
env.agent.runtime.type = "subprocess"
# this env runs its own algorithm
[orchestrator.train.source.algo]
type = "echo"
algo.type = "echo"
```
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_rl.orchestrator.sampler`) from the `sampling` component — the pool rollouts are generated from, and the home of future sampling strategies like replay buffers or branching — and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
| `grpo` | `GRPOAlgorithm` | `score_group`: group-norm credit (optional length penalty) |
| `echo` | `EchoAlgorithm` | `score_rollout`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `echo` | `EchoAlgorithm` | `score_episode`: weighted ce on observation tokens; `score_group`: group-norm credit (inherited) |
| `max_rl` | `MaxRLAlgorithm` | `score_group`: mean-normalized group credit |
| `rae` | `RAEAlgorithm` | `score_group`: per-agent EMA-baseline credit |
| `hierarchical_grpo` | `HierarchicalGRPOAlgorithm` | `score_group`: GRPO baseline per episode for solvers, per group for the proposer |
| `opd` | `OPDAlgorithm` | `score_rollout`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_rollout`: demo-conditioned prefill under the live policy |
| `opd` | `OPDAlgorithm` | `score_episode`: own-context prefill under the teacher |
| `opsd` | `OPSDAlgorithm` | `score_episode`: demo-conditioned prefill under the live policy |
| `sft` | `SFTDistillAlgorithm` | no credit assignment; CE on sampled tokens |
Each class owns its hooks outright — reading one top to bottom reads the algorithm, and everything on the class is an override point. The two hooks are one scope-and-timing ladder — the wider scope is unlocked by a later barrier, so the two axes coincide. Each is handed the `Rollout` directly — the env's typed trace (`reward`, `nodes`, `num_turns`, ...) with `samples` attached, plus `assign_advantages` to write credit:
Algorithms operate on native verifier artifacts and annotate their message graphs directly:
- `async score_rollout(rollout)` — one rollout, **on arrival** (as it's tokenized, before its group is complete): rollout-local credit (`rollout.assign_advantages(...)`, scalar broadcast or per-token), observation ce weights, **or** model I/O — query a reference pool (e.g. `self.teacher_pool`, connected in `setup()` via `self.connect(...)`, or the live `self.policy_pool` for opsd) and attach per-token results (e.g. teacher logprobs) with bounded concurrency. No siblings. `echo` weights observation tokens here, identifying env-provided observation nodes by their non-sampled status and source step role attribution, applying the optional user filter, and writing the `ce_weights` stream.
- `score_group(group)` — the completed cohort, synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
- `async score_episode(episode)` — rollout-local scoring as one episode arrives.
- `async score_group(episodes)` — group-relative scoring after the cohort completes.
The pipeline drives the hooks through two non-virtual methods it never looks inside: `algorithm.finalize_rollout(rollout)` per arrival (rollout-local scoring + reference I/O) and `algorithm.finalize_group(rollouts)` per group (scoring + wire stamping; after this the records are frozen — groups die at stamping). Sample construction (interleaving) is pure pipeline — observation-token provenance is available through structural attribution (`node.sampled`, `node.is_content`) for any algorithm that trains on env-provided tokens.
The pipeline drives these through `finalize_episode` and `finalize_group`. Advantages, reference logprobs, and named loss weights stay on verifier nodes through admission. Only admitted traces are flattened into `TrainingSample`s.
Class-level declarations state what the algorithm needs: which loss component its action tokens feed (`action_loss_type`). Every class is constructed with its algorithm config plus the one host-owned resource it can't rebuild — the live policy pool (`self.policy_pool`). Everything else an algorithm needs it builds from its own config in `setup()`: `opd` connects its frozen `teacher`; `opsd` builds the renderer for its demonstration hint (tokenizer is always the live policy's — self-distillation has no separate model). The pipeline only ever calls the two `finalize_*` methods — writing your own algorithm is subclassing `Algorithm` and overriding the hooks its signal needs (see [Authoring an Algorithm](#authoring-an-algorithm)). Shared math (efficiency shaping, prefill alignment) lives as plain functions in `prime_rl.orchestrator.algo.advantage`.
@@ -365,21 +351,11 @@ episode_agents = ["solver"]
name = "proposer-solver"
group_size = 4 # proposed problems per source task
env.n = 4 # solver attempts per proposed problem
[orchestrator.train.source.env.taskset]
id = "proposer-solver"
[orchestrator.train.source.env.proposer.harness]
id = "null"
[orchestrator.train.source.env.proposer.runtime]
type = "subprocess"
[orchestrator.train.source.env.solver.harness]
id = "null"
[orchestrator.train.source.env.solver.runtime]
type = "subprocess"
env.taskset.id = "proposer-solver"
env.proposer.harness.id = "null"
env.proposer.runtime.type = "subprocess"
env.solver.harness.id = "null"
env.solver.runtime.type = "subprocess"
```
`group_size` controls how many problems are proposed from each source task. `env.n` controls how many solvers attempt each proposed problem. If a comparison contains only one trace—for example, a solver when `env.n = 1`—its advantage is zero.
@@ -399,51 +375,43 @@ decay = 0.95
[[orchestrator.train.source]]
name = "kuhn-poker"
[orchestrator.train.source.env.taskset]
id = "kuhn-poker"
[orchestrator.train.source.env.player0.harness]
id = "null"
[orchestrator.train.source.env.player0.runtime]
type = "subprocess"
[orchestrator.train.source.env.player1.harness]
id = "null"
[orchestrator.train.source.env.player1.runtime]
type = "subprocess"
env.taskset.id = "kuhn-poker"
env.player0.harness.id = "null"
env.player0.runtime.type = "subprocess"
env.player1.harness.id = "null"
env.player1.runtime.type = "subprocess"
```
Both of `kuhn-poker`'s agents late-bind to the run's own model — shared-policy self-play against a continuously improving opponent. Pin one agent to a frozen endpoint (`env.player1.model = ...`) for asymmetric play; its traces are marked untrainable by the env and never reach the advantage computation. A single-agent env under `rae` degrades to REINFORCE with an EMA baseline.
### Authoring an Algorithm
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class. The hook receives the group's `Rollout`s (each the env's typed `verifiers.Trace` — turns, tool calls, metadata in `info` — with `samples` attached) and writes credit via `assign_advantages`:
There is no config hook that points at user code — a new credit-assignment scheme is a new named algorithm in the repo. Subclass `Algorithm`, assign credit in the scoring hook whose timing fits your signal, and register the class:
```python
# src/prime_rl/orchestrator/algo/my_algo.py
import torch
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.routing import assign_advantages
class MyAlgorithm(Algorithm):
async def score_group(self, group):
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
advantages = ... # one value per rollout
for rollout, advantage in zip(group, advantages.tolist(), strict=True):
rollout.assign_advantages(advantage)
async def score_group(self, episodes):
traces = [trace for episode in episodes for trace in episode.traces]
rewards = torch.tensor([trace.reward for trace in traces], dtype=torch.float32)
advantages = ... # one value per trace
for trace, advantage in zip(traces, advantages.tolist(), strict=True):
assign_advantages(trace, advantage)
```
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick the hook by *when* your signal is ready: `score_rollout` for per-arrival credit or credit that needs a model call (it's `async`), `score_group` for group-relative credit (GRPO/MaxRL). `assign_advantages` takes a scalar (broadcast over the rollout's trainable tokens — the common case) or a full-length per-token list aligned to the concatenated sample token_ids (process rewards, step-level credit; `0.0` off-mask).
Add a typed `MyAlgoConfig` to `prime_rl.configs.algorithm` and its discriminated union, then register `"my_algo": MyAlgorithm` in `ALGORITHM_CLASSES`. Pick `score_episode` for rollout-local work or model calls, and `score_group` for group-relative credit. `assign_advantages` takes a scalar or a list aligned to the trace graph's sampled tokens.
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Curriculum admission and metrics can inspect these streams after group scoring. Signals that depend on the live policy's weights (like OPD's reverse KL) cannot be precomputed here; those are reference-scoring algorithms, evaluated in the trainer.
Curriculum admission and metrics can inspect the resulting graph-native streams after group scoring.
### Reference Scoring
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_rollout`: as each rollout arrives they query a reference (the sample's own context for `opd`, the demo-conditioned context for `opsd`) and attach per-token reference logprobs to each sample. Rollouts are consumed serially by the orchestrator's main loop and each carries only a handful of samples, so the in-flight request count is naturally bounded — no explicit concurrency cap:
`OPDAlgorithm` / `OPSDAlgorithm` do their model I/O in `score_episode`: as each episode arrives they query a reference and attach sampled-token reference logprobs to its graph nodes:
- `opd` — score each sample's own context under the `teacher` (a frozen [model reference](#model-references)) via prefill; fills `ref_logprobs` for the `ref_kl` loss component (on-policy distillation). The `teacher` is typed `FrozenModelConfig`, so `"policy"` isn't representable (the KL would be identically zero).
- `opsd` — SDFT: prepend an expert demonstration as a leading system message (`template`, with a `{demonstration}` placeholder) and score the sample under that demo-conditioned context. The sample is scored verbatim (`hint_block + token_ids`, slicing the hint's logprobs back off), so the join is BPE-clean and it's robust to tool/multimodal prompts and any number of turns. The scoring reference *is* the live policy — self-distillation names no teacher. opsd builds its own renderer to tokenize the hint block: the tokenizer is always the live policy's (not configurable — there is no separate model), and only the `renderer` family is settable (defaults to `"auto"`, resolved from the policy tokenizer; set it to match a non-auto policy renderer). The demonstration is read from the example's `info[demo_key]`, falling back to a top-level rollout field of the same name (e.g. `answer`).
@@ -454,13 +422,13 @@ type = "opsd"
demo_key = "demonstration"
```
Scoring runs at arrival, before curriculum admission, so a rollout that is later rejected still costs its reference compute.
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.
## Curricula
Each training source has a `Curriculum` composed from one `TaskSampler` and any number of named `AdmissionGate`s. The sampler chooses tasks and observes every finalized result. Every gate evaluates every result; the group trains only if every gate admits it. Rejected groups remain observable while the orchestrator samples again to fill the batch.
Each training source has a `Curriculum` composed from one `TaskSampler` and any number of named `AdmissionGate`s. The sampler chooses tasks and observes every finalized `list[vf.Episode]`; each gate inspects the same native episodes. The group trains only if every gate admits it. Rejected groups remain observable while the orchestrator samples again to fill the batch.
Samplers and gates can be stateful. Their `state_dict`, `load_state_dict`, and `metrics` methods are included in orchestrator checkpoints and logged under `curriculum/<env>/`.
+13 -33
View File
@@ -106,10 +106,8 @@ uv run rl @ rl.toml --orchestrator.train.source.0.args \
```toml
[[orchestrator.train.source]]
[orchestrator.train.source.args]
dataset_name = "openai/gsm8k"
dataset_subset = "main"
args.dataset_name = "openai/gsm8k"
args.dataset_subset = "main"
```
### Optional Sub-Configs
@@ -153,42 +151,24 @@ Training and evaluation sources are arrays of tables. Set one source per environ
[[orchestrator.train.source]]
name = "gsm8k"
ratio = 3 # 75% of batches
[orchestrator.train.source.env.taskset]
id = "gsm8k"
split = "train"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "gsm8k"
env.taskset.split = "train"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "reverse-text"
ratio = 1 # default — 25% of batches
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.eval.source]]
name = "gsm8k-eval"
[orchestrator.eval.source.env.taskset]
id = "gsm8k"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "gsm8k"
env.taskset.split = "test"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
`ratio` defaults to `1` (equal weight per env); values are relative weights normalized to probabilities across envs.
+1 -1
View File
@@ -109,7 +109,7 @@ uv run sft \
--data.name PrimeIntellect/Reverse-Text-SFT \
--max_steps 200 \
--optim.lr 1e-4 \
--ckpt.weights
--ckpt
```
Then run the full RL stack on reverse-text:
+14 -1
View File
@@ -12,6 +12,7 @@ This page covers the inference configuration and the supported features/deployme
- [P/D Disaggregation](#pd-disaggregation)
- [Router](#router)
- [Routing policies](#routing-policies)
- [Adaptive Concurrency](#adaptive-concurrency)
- [Advanced Configuration](#advanced-configuration)
- [KV Cache Offload](#kv-cache-offload)
- [Optimized P/D disaggregation deployment](#optimized-pd-disaggregation-deployment)
@@ -72,7 +73,7 @@ data_parallel_size = 4
type = "single_node"
```
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required `orchestrator.max_inflight_requests`. Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
We reccomend choosing your parallelism based on the expected throughput and latency requirements. High `dp` might create high latency, however it will also give you the highest throughput. This is a tradeoff you need to make based on your use case and required concurrency (see [Adaptive Concurrency](#adaptive-concurrency)). Setting `tp` to a higher value will usually give you lower latency, but the inference server also will become saturated faster with lower number of requests.
Another thing to consider, is the memory usage. You need to make sure that the model will fit into the available GPU memory. We will not go into the details on how to do this in this document. Related thing to consider, is the space for the KV cache. This will heavily affect the amount of requests your inference server can handle. You want to shard your model, either using `inference.vllm.enable_expert_parallel` or `inference.vllm.tensor_parallel_size` to maximize the available GPU memory.
@@ -203,6 +204,18 @@ X-Session-ID = "trajectory_id" # this is the default - each rollout has a unique
- `round_robin` - this policy will round-robin the requests between the available replicas. This is useful if you want to balance the load between the replicas. This might give you better results if you don't have enough rollouts to make `consistent_hash` hashing saturated.
## Adaptive Concurrency
The orchestrator continuously sizes how many episodes run against the inference engines at once. A static cap cannot be right: too low starves the engines, too high crosses into KV thrash — the engines evict prefix cache, re-prefill the evicted work, and throughput collapses. The optimal value depends on the model, the deployment, and the workload's episode lengths, and it moves as training changes the policy.
The controller's idea is to treat the engines as ground truth and probe, instead of modeling episode cost: while the engines show headroom, admit a little more; when they show pressure, back off. Three behaviors, in increasing severity:
- **Grow**: while the engines look healthy and the current cap is fully used, raise it multiplicatively. Growth is clocked by the pipeline itself — the cap rises by a fixed factor each time the in-flight pool has turned over once — so a fast single-turn workload ramps in seconds while a slow agentic workload ramps at its own pace, with no tuning per workload.
- **Trim**: episodes grow their context *while running*, so a pool that fit comfortably an hour ago can outgrow memory without a single new admission. When KV usage nears the ceiling, the controller first lowers the cap and lets completions drain the pool naturally (soft — no work lost); only if usage keeps climbing despite the closed gate does it also cancel the youngest episodes (hard — least work lost).
- **Cut**: when the engines are demonstrably overloaded — requests being preempted, or piling up in the waiting queue — cut the pool hard, cancel the excess, and hold further cuts until the system settles.
The cap starts from a safe bound derived from the engines (KV capacity divided by the maximum context length), or from `initial_inflight` when a good value is known, and always stays within `[min_inflight, max_inflight]`.
## Advanced Configuration
### KV Cache Offload
+1 -1
View File
@@ -32,7 +32,7 @@ Train an SFT-warmed `Qwen3-0.6B` on the `reverse-text` task — the env is bundl
uv run rl @ examples/basic/reverse-text/rl.toml
```
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes and final HF-compatible weights land at `outputs/<run_name>/weights/step_20`.
The `rl` entrypoint reads `examples/basic/reverse-text/rl.toml`, splits it into per-process sub-configs, picks GPU 0 for inference and GPU 1 for the trainer, launches all three processes, and tees their stdout into the run directory at `outputs/<run_name>/logs/{trainer,orchestrator,inference}.log` (`run.name` auto-generates as `<envs>--<model>--<short-id>`; pass `--run.name <name>` for a predictable path). Within a minute the trainer should log `step 1` and a reward sample; after 20 steps the run completes with a final DCP checkpoint at `outputs/<run_name>/checkpoints/step_20`.
## Documentation
+2 -2
View File
@@ -87,7 +87,7 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
| `trainer.model.reshard_after_forward` | If `true` (default), parameters are resharded after the forward pass to free memory; the backward pass re-gathers. Set `false` to keep params resident — faster but more memory. |
| `trainer.model.fsdp_cpu_offload` | Offload params + grads + optimizer state to CPU. Big memory win, large throughput hit. |
| `trainer.model.optim_cpu_offload` | Offload optimizer state to CPU between steps. Enabled by default. |
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run AdamW on CPU during backward. Disabled by default. |
| `trainer.model.full_offload` | Offload gradients, FP32 masters, and optimizer state and run the optimizer (AdamW or SignSGD) on CPU during backward. Disabled by default. |
### Expert Parallelism
@@ -138,7 +138,7 @@ targets = ["norm", "attn_proj"] # see Reference for the full list per architect
### Optimizer Offloading
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU AdamW chunks as gradients become ready during backward. Full offload only supports AdamW and disables gradient clipping.
State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`. For full offload, set `model.optim_cpu_offload = false` and `model.full_offload = true`; this keeps BF16 compute weights on GPU and runs CPU optimizer chunks as gradients become ready during backward. Full offload only supports AdamW and SignSGD (`optim.type = "sign_sgd"`) and disables gradient clipping. SignSGD is stateless, so it halves the host RAM footprint versus AdamW (8 instead of 16 bytes per parameter: FP32 master + FP32 accumulated gradient, no moments).
### LM Head Chunking
+8 -25
View File
@@ -59,7 +59,7 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|---|---|
| `orchestrator.batch_size` | Tasks per trainer step. |
| `orchestrator.group_size` | Rollouts generated per task. |
| `orchestrator.max_off_policy_steps` | How many distinct policies may have contributed to one rollout before it's discarded (default 8). The main off-policy dial on long agentic rollouts — bump for throughput, lower for tighter on-policyness. Watch `errored_rollouts` and `mismatch_kl/all/mean` when tuning. |
| `orchestrator.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). |
| `[[orchestrator.train.source]]` | Training sources. List multiple tables for multi-env training; weight them via `ratio`. See [Configuration § Training sources](configuration.md#training-sources-orchestratortrainsource). |
| `[[orchestrator.eval.source]]` + `orchestrator.eval.interval` | Eval environments and cadence (default every 100 steps). |
@@ -187,15 +187,9 @@ num_examples = 32
[[eval.source]]
name = "reverse-text"
[eval.source.env.taskset]
id = "reverse-text"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
@@ -204,17 +198,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 `evaluator` process next to the trainer. The handoff is the filesystem, not NCCL: the trainer writes an HF weight checkpoint at every step an eval env is due (in addition to `ckpt.interval`), and the evaluator watches `weights/step_{n}`, points the inference server at each stable checkpoint (`/update_weights` reload from disk), and runs the due envs against it — sequentially per checkpoint, so every epoch measures exactly one policy version. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final checkpoint always fires every env.
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 every step an eval env is due, and the evals process watches `broadcasts/step_{n}` for synchronization markers before it drives the NCCL receive. 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).
#### Multi-Node (Decoupled Trainer and Inference Pool)
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two independent SLURM jobs**. `deployment.num_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 evaluator:
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:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evaluator)
num_infer_nodes = 1 # eval job (inference pool + evals)
[inference.vllm]
tensor_parallel_size = 8
@@ -223,7 +217,7 @@ tensor_parallel_size = 8
job_name = "my-run"
```
The only coupling is weight checkpoints on the shared filesystem, so the jobs' lifetimes are independent: when training finishes, the trainer job exits and releases its nodes even while evals are still running; the eval job keeps draining pending checkpoints and exits after evaluating the final one (`max_steps` — without it the eval job never sees a final checkpoint and holds its allocation until walltime). Trainer and evaluator log to a single shared W&B run across both jobs — the trainer creates it, the evaluator finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
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.
### SFT-Specific Knobs
@@ -272,7 +266,6 @@ Checkpointing is split across processes because the orchestrator and trainer can
| 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 |
| Trainer (HF weights) | HF-compatible weight snapshot for serving | `<run_dir>/weights/step_N/` |
### Enabling Checkpoints
@@ -304,16 +297,6 @@ uv run rl @ rl.toml --max-steps 20 --ckpt --run.name my-fork \
--resume.dir outputs/my-run/checkpoints/step_10
```
### Serving Checkpoints
HF-compatible weight snapshots are written under `<run_dir>/weights/step_N/` whenever a full checkpoint runs (or you can write weights-only via `--ckpt.weights-only` for cheaper snapshots). Upload directly:
```bash
uv run hf upload <user>/<model>-RL outputs/<run_name>/weights/step_100
```
For LoRA runs, set `ckpt.weights.save_adapter_separately = true` to also write the raw adapter alongside the merged weights — useful when serving the adapter through a separate `/load_lora_adapter` call.
## Observability
### Log Files
+26 -46
View File
@@ -25,6 +25,8 @@ num_infer_replicas = 4
project = "search-ablations"
name = "glm45air-search"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -59,7 +61,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
@@ -71,7 +72,10 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_episodes = 512
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -86,8 +90,6 @@ num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.0
[monitors.prime]
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
@@ -95,18 +97,12 @@ num_turns_weight = 0.0
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.source]]
name = "openseeker"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "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.runtime.labels = ["glm45air-search"]
env.taskset.id = "openseeker"
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
@@ -125,18 +121,12 @@ choices = ["A", "B"]
[[orchestrator.train.source]]
name = "redsearcher"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-search"]
[orchestrator.train.source.env.taskset]
id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
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.runtime.labels = ["glm45air-search"]
env.taskset.id = "redsearcher" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.source.env.taskset.task.judges]]
id = "reference"
@@ -161,24 +151,14 @@ interval = 20
[[orchestrator.eval.source]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-search"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "browsecomp"
[orchestrator.eval.source.env.taskset.task.judge]
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
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.runtime.labels = ["glm45air-search"]
env.agent.timeout.rollout = 3600
env.taskset.id = "browsecomp"
env.taskset.task.judge.model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.eval.source.env.taskset.task.judges]]
+25 -38
View File
@@ -1,4 +1,4 @@
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, rlm harness on a prime sandbox
# v1 RL: GLM-4.5-Air (100B MoE) on the v1 `scaleswe` SWE taskset, bash harness on a prime sandbox
# runtime; eval on SWE-Bench Verified. Router replay is enabled (trainer.enable_router_replay replays
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
# a glm4_moe model, which supports routed_experts.
@@ -7,10 +7,13 @@
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# 2 train + 4 infer nodes. Trainer uses cp=4 (ulysses) plus
# 1 train + 3 infer nodes. Inference serves the bf16 checkpoint as-is (no quantization). The trainer
# fits on one node via cp=4 (ulysses), full CPU optimizer offload with the stateless sign-SGD optimizer, plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
# CPU offload, and skip-gather / skip-optimizer checkpointing.
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), and
# skip-gather / skip-optimizer checkpointing.
# Concurrency is fully default: the controller derives its start from the measured KV budget and
# adapts from there.
max_steps = 1000
seq_len = 131072
@@ -28,14 +31,16 @@ pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y ||
[deployment]
type = "multi_node"
num_train_nodes = 2
num_train_nodes = 1
num_infer_nodes = 1
num_infer_replicas = 4
num_infer_replicas = 3
[monitors.wandb]
project = "swe-ablations"
name = "glm45air-scaleswe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -46,20 +51,22 @@ keep_last = 1
[resume]
[model]
name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[model]
name = "zai-org/GLM-4.5-Air"
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
optim_cpu_offload = false
full_offload = true
fused_lm_head_token_chunk_size = 1024
[trainer.model.ac]
@@ -70,11 +77,10 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
type = "muon"
type = "sign_sgd"
# --- Orchestrator ---
@@ -82,7 +88,6 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_episodes = 512
[orchestrator.algo]
type = "grpo"
@@ -99,39 +104,21 @@ thinking_retention = "all"
[[orchestrator.train.source]]
name = "scaleswe"
env.taskset.id = "scaleswe"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe"]
[orchestrator.train.source.env.taskset]
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-swe"]
[monitors.prime]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, bash harness on prime ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-swe"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm45air-swe"]
env.agent.timeout.rollout = 3600
# --- Inference ---
+20 -42
View File
@@ -26,6 +26,8 @@ num_infer_replicas = 4
project = "terminal-ablations"
name = "glm45air-terminal"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -60,7 +62,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
@@ -72,7 +73,10 @@ type = "muon"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_episodes = 512
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
[orchestrator.renderer]
name = "glm-4.5"
@@ -87,22 +91,14 @@ num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[monitors.prime]
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
[[orchestrator.train.source]]
name = "tmax"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-terminal"]
[orchestrator.train.source.env.taskset]
id = "tmax"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["glm45air-terminal"]
env.taskset.id = "tmax"
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
# [[orchestrator.train.source.env.taskset.judges]]
@@ -126,27 +122,17 @@ interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "swebench-verified"
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/prime-envs/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
# name = "swe"
@@ -157,19 +143,11 @@ id = "swebench-verified"
[[orchestrator.eval.source]]
name = "terminal-bench-2"
group_size = 4 # avg@4
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm45air-terminal"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
[orchestrator.eval.source.env.taskset]
id = "terminal-bench-2"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["glm45air-terminal"]
env.agent.timeout.rollout = 3600
env.taskset.id = "terminal-bench-2"
# [[orchestrator.eval.source.env.taskset.judges]]
# id = "rubric"
+7 -10
View File
@@ -113,9 +113,12 @@ weight_decay = 0.0
[orchestrator]
batch_size = 256
group_size = 16
max_inflight_episodes = 2048
max_off_policy_steps = 8 # 16/32 can be better, 8 is more CPU stable
[orchestrator.concurrency]
initial_inflight = 256
max_inflight = 512
[orchestrator.model]
name = "zai-org/GLM-5.1-FP8"
@@ -131,15 +134,9 @@ clear_thinking = false
[[orchestrator.train.source]]
name = "r2e"
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
[orchestrator.train.source.env.agent.runtime]
labels = ["glm5-llmd"]
env.taskset.id = "r2e-gym"
env.agent.harness.id = "rlm"
env.agent.runtime.labels = ["glm5-llmd"]
[inference]
# <0.80 because glm5 layers are too large for 0.85
+7 -11
View File
@@ -55,7 +55,6 @@ max_inflight_activations = 1
[trainer.ckpt]
skip_optimizer = true
skip_gather_master_weights = true
[trainer.optim]
type = "adamw"
@@ -65,9 +64,12 @@ weight_decay = 0.1
[orchestrator]
batch_size = 4096
group_size = 16
oversampling_factor = 3
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 8192
[orchestrator.model]
name = "zai-org/GLM-5-FP8"
@@ -76,15 +78,9 @@ interval = 20
[[orchestrator.eval.source]]
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm5-pd-disag", "swe-bench-verified"]
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["glm5-pd-disag", "swe-bench-verified"]
[inference]
# we need <0.85 bc glm5 layers are too large for 0.85
+28 -69
View File
@@ -45,109 +45,68 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
oversampling_factor = 2
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 4096
[[orchestrator.train.source]]
name = "swe"
ratio = 0.3
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["intellect-3.1", "swe"]
env.taskset.id = "r2e-gym"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["intellect-3.1", "swe"]
[[orchestrator.train.source]]
name = "deepdive"
ratio = 0.2
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "deepdive"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
skills = ["search"]
forward_env = ["SERPER_API_KEY"]
[orchestrator.train.source.env.agent.runtime]
labels = ["intellect-3.1", "deepdive"]
env.taskset.id = "deepdive"
env.agent.harness.id = "rlm"
env.agent.harness.skills = ["search"]
env.agent.harness.forward_env = ["SERPER_API_KEY"]
env.agent.runtime.labels = ["intellect-3.1", "deepdive"]
[[orchestrator.train.source]]
name = "math"
ratio = 0.3
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "i3_math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "logic"
ratio = 0.2
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "i3_logic"
[orchestrator.train.source.env.taskset.filter]
max = 0.874
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "i3_logic"
env.taskset.filter.max = 0.874
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.train.source]]
name = "code"
ratio = 0.2
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "i3_code"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "i3_code"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["intellect-3.1", "swe-bench-verified"]
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["intellect-3.1", "swe-bench-verified"]
[[orchestrator.eval.source]]
name = "aime2025"
[orchestrator.eval.source.env.taskset]
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference.vllm]
tensor_parallel_size = 8
+10 -19
View File
@@ -45,35 +45,26 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
oversampling_factor = 2
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 4096
[[orchestrator.train.source]]
name = "swe"
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["minimax-swe", "swe"]
env.taskset.id = "r2e-gym"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["minimax-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["minimax-swe", "swe-bench-verified"]
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["minimax-swe", "swe-bench-verified"]
[inference.vllm]
tensor_parallel_size = 8
+15 -27
View File
@@ -22,6 +22,8 @@ num_infer_replicas = 4
project = "nemotron-3-super"
name = "nemotron-3-super-swe"
[monitors.prime]
[weight_broadcast]
type = "nccl"
timeout = 3600
@@ -56,7 +58,6 @@ max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
@@ -66,7 +67,10 @@ type = "adamw"
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_episodes = 1536
[orchestrator.concurrency]
initial_inflight = 1536
max_inflight = 1536
[orchestrator.algo]
type = "grpo"
@@ -83,37 +87,21 @@ truncate_history_thinking = false
[[orchestrator.train.source]]
name = "scaleswe"
[orchestrator.train.source.env.taskset]
id = "scaleswe"
[orchestrator.train.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["nemotron-3-super-swe"]
[monitors.prime]
env.taskset.id = "scaleswe"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = [65536, 131072]
env.agent.runtime.labels = ["nemotron-3-super-swe"]
[orchestrator.eval]
interval = 20
[[orchestrator.eval.source]]
name = "swebench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "rlm"
summarize_at_tokens = 98304
[orchestrator.eval.source.env.agent.runtime]
labels = ["nemotron-3-super-swe"]
[orchestrator.eval.source.env.agent.timeout]
rollout = 3600
env.taskset.id = "swebench-verified"
env.agent.harness.id = "rlm"
env.agent.harness.summarize_at_tokens = 98304
env.agent.runtime.labels = ["nemotron-3-super-swe"]
env.agent.timeout.rollout = 3600
[inference]
# vLLM disables prefix caching by default for hybrid-Mamba models; SWE turns share long prefixes.
+9 -19
View File
@@ -42,38 +42,28 @@ lr = 1e-6
[orchestrator]
batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 8
[orchestrator.concurrency]
initial_inflight = 1024
[orchestrator.train.sampling]
max_completion_tokens = 32768
[[orchestrator.train.source]]
name = "math"
[orchestrator.train.source.env.taskset]
id = "i3_math"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "i3_math"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "aime2025"
[orchestrator.eval.source.env.taskset]
id = "aime25"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference.vllm]
tensor_parallel_size = 8
+9 -19
View File
@@ -43,35 +43,25 @@ lr = 1e-6
[orchestrator]
batch_size = 512
oversampling_factor = 2
max_off_policy_steps = 16
[orchestrator.concurrency]
initial_inflight = 1024
[[orchestrator.train.source]]
name = "swe"
[orchestrator.train.source.env.taskset]
id = "r2e-gym"
[orchestrator.train.source.env.agent.harness]
id = "bash"
[orchestrator.train.source.env.agent.runtime]
labels = ["qwen30b-swe", "swe"]
env.taskset.id = "r2e-gym"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["qwen30b-swe", "swe"]
[orchestrator.eval]
interval = 25
[[orchestrator.eval.source]]
name = "swe-bench-verified"
[orchestrator.eval.source.env.taskset]
id = "swebench-verified"
[orchestrator.eval.source.env.agent.harness]
id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["qwen30b-swe", "swe-bench-verified"]
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.runtime.labels = ["qwen30b-swe", "swe-bench-verified"]
[inference.vllm]
tensor_parallel_size = 8
+5 -13
View File
@@ -36,19 +36,11 @@ group_size = 16
max_off_policy_steps = 32
[[orchestrator.train.source]]
[orchestrator.train.source.env.taskset]
id = "general-agent"
min_tier = 1
[orchestrator.train.source.env.taskset.task.tools]
colocated = true
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "modal"
env.taskset.id = "general-agent"
env.taskset.min_tier = 1
env.taskset.task.tools.colocated = true
env.agent.harness.id = "null"
env.agent.runtime.type = "modal"
[inference]
+1 -5
View File
@@ -98,11 +98,7 @@ uv run rl @ examples/basic/alphabet-sort/rl.toml \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/rl/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
```bash
uv run hf upload <user>/Qwen3-4B-Instruct-AlphabetSort-RL outputs/rl/weights/step_100
```
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL`](https://huggingface.co/PrimeIntellect/Qwen3-4B-Instruct-AlphabetSort-RL).
+6 -14
View File
@@ -33,19 +33,11 @@ max_completion_tokens = 768
[[orchestrator.train.source]]
name = "alphabet-sort"
[orchestrator.train.source.env.taskset]
id = "alphabet-sort"
min_turns = 3
max_turns = 5
[orchestrator.train.source.env.taskset.task]
power_per_turn = false
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "alphabet-sort"
env.taskset.min_turns = 3
env.taskset.max_turns = 5
env.taskset.task.power_per_turn = false
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference] # Default inference config
+8 -20
View File
@@ -18,17 +18,11 @@ seq_len = 8192
[[orchestrator.train.source]]
name = "hendrycks-math"
[orchestrator.train.source.env.taskset]
id = "math-env"
dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B"
dataset_subset = "default"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
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"
[orchestrator.eval]
interval = 50
@@ -36,15 +30,9 @@ interval = 50
[[orchestrator.eval.source]]
name = "aime2024"
group_size = 32
[orchestrator.eval.source.env.taskset]
id = "aime24"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "aime24"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.model]
seq_len = 16384
+5 -23
View File
@@ -60,11 +60,7 @@ uv run torchrun \
--monitors.wandb.name ...
```
This should write a weight checkpoint in `outputs/sft/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
```bash
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT outputs/sft/weights/step_100
```
This should write a DCP checkpoint in `outputs/sft/checkpoints/step_100`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT).
@@ -83,11 +79,7 @@ uv run rl @ examples/basic/reverse-text/rl.toml \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/rl/weights/step_20`. As before, let's upload it to HF.
```bash
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-RL outputs/rl/weights/step_20
```
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_20`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL`](https://huggingface.co/PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL).
@@ -134,17 +126,7 @@ Exec into the trainer pod and run SFT:
```bash
kubectl exec -it my-exp-trainer-0 -- bash
uv run sft @ /app/examples/basic/reverse-text/sft.toml --output-dir /data/outputs --run.name sft
# This will save checkpoints to /data/outputs/sft/weights/step_100
```
Upload the checkpoint to HuggingFace or use it directly from shared storage:
```bash
# Option 1: Upload to HuggingFace (from within the pod)
uv run hf upload <user>/Qwen3-0.6B-Reverse-Text-SFT /data/outputs/sft/weights/step_100
# Option 2: Use local checkpoint path in RL config
# Update the model.name in the RL configs to point to /data/outputs/sft/weights/step_100
# This will save DCP checkpoints to /data/outputs/sft/checkpoints/step_100
```
### Step 3: Deploy RL Training
@@ -212,11 +194,11 @@ kubectl exec -it my-exp-trainer-0 -- bash
# If inference server isn't running with the RL model, start it in another terminal:
kubectl exec -it my-exp-inference-0 -- bash
uv run inference --vllm.model /data/outputs/weights/step_20
uv run inference --vllm.model /data/outputs/weights_hf/step_20
# Back in trainer pod, run evaluation
uv run eval reverse-text --harness.id null \
-m /data/outputs/weights/step_20 \
-m /data/outputs/weights_hf/step_20 \
--client.base-url $INFERENCE_URL \
-n 20 -r 3 --sampling.max-tokens 1024 --no-push
```
+3 -9
View File
@@ -17,15 +17,9 @@ max_completion_tokens = 128
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[trainer.optim]
lr = 3e-6
+3 -9
View File
@@ -22,15 +22,9 @@ max_completion_tokens = 1024
[[eval.source]]
name = "reverse-text"
[eval.source.env.taskset]
id = "reverse-text"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[inference]
+1 -5
View File
@@ -103,11 +103,7 @@ The unified config file automatically configures:
- **Orchestrator**: Rollout generation with tool calling enabled
- **Inference**: vLLM server for Qwen3-4B-Instruct-2507 with tool parsing enabled
This will write weight checkpoints in `outputs/rl/weights/step_*`. Upload the final checkpoint to HuggingFace:
```bash
uv run hf upload <user>/Qwen3-4B-Instruct-WikiSearch-RL outputs/rl/weights/step_500
```
This will write DCP checkpoints in `outputs/rl/checkpoints/step_*`.
## Evaluation
+6 -10
View File
@@ -32,7 +32,9 @@ target_modules = [
[orchestrator]
batch_size = 512
group_size = 16
oversampling_factor = 2.0
[orchestrator.concurrency]
initial_inflight = 1024
[orchestrator.model.lora]
name = "qwen3-4b-wiki-search"
@@ -43,15 +45,9 @@ max_completion_tokens = 512
[[orchestrator.train.source]]
name = "wiki-search"
curriculum = { gates = { zero_advantage = { type = "advantage_range" } } }
[orchestrator.train.source.env.taskset]
id = "wiki-search"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "wiki-search"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[ckpt] # Checkpoint at the end of training
+2 -10
View File
@@ -62,11 +62,7 @@ uv run torchrun \
--monitors.wandb.name ...
```
After training completes, you will find the final weight checkpoint in `outputs/sft/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
```bash
uv run hf upload <user>/Qwen3-1.7B-Wordle-SFT outputs/sft/weights/step_20
```
After training completes, you will find the final DCP checkpoint in `outputs/sft/checkpoints/step_20`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-SFT`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-SFT).
@@ -86,11 +82,7 @@ uv run rl @ examples/basic/wordle/rl.toml \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/rl/weights/step_100`. As before, let's upload it to HF.
```bash
uv run hf upload <user>/Qwen3-1.7B-Wordle-RL outputs/rl/weights/step_100
```
This will write a DCP checkpoint in `outputs/rl/checkpoints/step_100`.
We have uploaded the final model as [`PrimeIntellect/Qwen3-1.7B-Wordle-RL`](https://huggingface.co/PrimeIntellect/Qwen3-1.7B-Wordle-RL).
+3 -9
View File
@@ -20,15 +20,9 @@ group_size = 16
[[orchestrator.train.source]]
name = "wordle"
[orchestrator.train.source.env.taskset]
id = "wordle"
[orchestrator.train.source.env.player.harness]
id = "null"
[orchestrator.train.source.env.player.runtime]
type = "subprocess"
env.taskset.id = "wordle"
env.player.harness.id = "null"
env.player.runtime.type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 1024
+32
View File
@@ -0,0 +1,32 @@
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
# against DeepSeek V4 Flash on Prime Inference.
#
# export PRIME_API_KEY=<your Prime Inference key>
# uv run evals @ examples/evals/swe.toml
#
# The tasksets run in prime sandboxes (the default runtime), so the key also
# authenticates sandbox creation. External API endpoints expose no vLLM
# /metrics, so adaptive concurrency has no load signal - the band must be
# pinned (min_inflight = max_inflight) or the evals process refuses to start.
model = "deepseek/deepseek-v4-flash"
[eval.client]
base_url = "https://api.pinference.ai/api/v1"
api_key_var = "PRIME_API_KEY"
[eval.concurrency]
min_inflight = 32
max_inflight = 32
[[eval.source]]
name = "swebench-verified"
env.taskset.id = "swebench-verified"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
[[eval.source]]
name = "terminal-bench-2"
env.taskset.id = "terminal-bench-2"
env.agent.harness.id = "bash"
env.agent.timeout.rollout = 3600
-2
View File
@@ -1,8 +1,6 @@
max_steps = 20
[ckpt]
[ckpt.weights]
save_adapter_separately = true
[model]
name = "Qwen/Qwen3.5-0.8B"
-2
View File
@@ -47,8 +47,6 @@ lr = 1e-5
[ckpt]
interval = 200
[ckpt.weights]
save_adapter_separately = true
[deployment]
type = "single_node"
+3 -9
View File
@@ -15,15 +15,9 @@ max_completion_tokens = 128
[[train.source]]
name = "reverse-text"
[train.source.env.taskset]
id = "reverse-text"
[train.source.env.agent.harness]
id = "null"
[train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[renderer]
name = "prime-qwen3"
@@ -0,0 +1,114 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.utils.config import BaseConfig
class EvalsEvalConfig(EvalConfig):
"""Evals against a live inference server. Extends the orchestrator ``EvalConfig``
(sources, sampling, intervals) with the client of the inference deployment and
evals-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: sources with an explicit
``serve.address`` are externally managed; the evals process spawns an env server at
the derived address for every other source."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class OnlineConfig(BaseConfig):
"""Broadcast-driven online evals: watch a broadcasts directory for new weight
broadcasts and evaluate each eligible one. Without this block the evals process runs
every eval source once against the weights the inference server currently serves,
then exits."""
broadcasts_dir: Path | None = None
"""Directory to watch for ``step_{n}`` weight broadcasts. Defaults to
``<output_dir>/broadcasts``."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evals process exits after processing it. If None, the evals process
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
class EvalsConfig(BaseConfig):
"""``uv run evals``: run the configured evals against a live inference server.
Standalone (no ``[online]``), one epoch of every eval source runs against the
served weights and the evals process exits. With ``[online]``, the evals process watches a
broadcasts directory for new weight broadcasts, updates the inference server through
the configured transport, and runs the configured evals against the updated weights.
The ``sft`` launcher writes this config; filesystem mode also works standalone against
any trainer that writes ``broadcasts/step_{n}`` directories with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across weight updates (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: EvalsEvalConfig
"""Eval sources, sampling, intervals, concurrency, and the inference client."""
online: OnlineConfig | None = None
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
weight_broadcast: WeightBroadcastConfig | None = None
"""Weight transport for online evals. The ``sft`` launcher fills this from its
resolved trainer transport. None uses filesystem reloads."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer for online evals."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_broadcasts_dir(self):
if self.online is not None and self.online.broadcasts_dir is None:
self.online.broadcasts_dir = self.output_dir / "broadcasts"
return self
@model_validator(mode="after")
def validate_skip_first_step_is_online_only(self):
"""``skip_first_step`` gates the base-model eval between checkpoints; a
standalone run has only that one epoch, so skipping it would exit
successfully without evaluating anything."""
if self.online is None and self.eval.skip_first_step:
raise ValueError(
"eval.skip_first_step only applies to online evals - a standalone run "
"would skip its only eval epoch. Remove it or add an [online] block."
)
return self
@@ -1,84 +0,0 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.utils.config import BaseConfig
class OnlineEvalConfig(EvalConfig):
"""Online evals against a live inference server, driven by weight checkpoints
on disk. Extends the orchestrator ``EvalConfig`` (sources, sampling, intervals)
with the client of the inference deployment and evaluator-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
max_inflight_episodes: int = Field(128, ge=1)
"""Maximum eval episodes in flight — one episode is one agent run against an env server."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: the launcher binds env
servers at exactly these addresses and the evaluator connects to them."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class EvaluatorConfig(BaseConfig):
"""``uv run evaluator``: watch a weights directory for new HF checkpoints, point
the inference server at each one (``/update_weights`` from disk), and run the
configured evals against the updated weights. The ``sft`` launcher writes this
config; it can also be run standalone against any trainer that writes
``weights/step_{n}`` HF checkpoints with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across checkpoint reloads (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: OnlineEvalConfig
"""Eval sources, sampling, intervals, and the inference client."""
weights_dir: Path | None = None
"""Directory to watch for ``step_{n}`` HF weight checkpoints. The ``sft`` launcher
fills it from ``ckpt.output_dir`` when checkpoints are redirected to another volume;
defaults to ``<output_dir>/weights``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evaluator exits after processing it. If None, the evaluator
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_weights_dir(self):
if self.weights_dir is None:
self.weights_dir = self.output_dir / "weights"
return self
@@ -420,6 +420,30 @@ WeightBroadcastConfig: TypeAlias = Annotated[
]
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
in-flight episode cap from engine KV capacity and learned per-env episode
costs; these fields only bound and seed it."""
initial_inflight: int | None = Field(None, ge=1)
"""Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime."""
min_inflight: int = Field(1, ge=1)
"""Minimum number of in-flight episodes. Set ``min_inflight = max_inflight`` to recover fixed concurrency."""
max_inflight: int | None = Field(1024, ge=1)
"""Maximum number of in-flight episodes. Set it to avoid runaway concurrency, especially to limit other external resources (e.g. sandboxes). None removes the ceiling."""
@model_validator(mode="after")
def validate_bounds(self):
if self.max_inflight is not None:
if self.initial_inflight is not None and self.initial_inflight > self.max_inflight:
raise ValueError("concurrency.initial_inflight must not exceed concurrency.max_inflight")
if self.min_inflight > self.max_inflight:
raise ValueError("concurrency.min_inflight must not exceed concurrency.max_inflight")
return self
class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
@@ -455,7 +479,7 @@ class OrchestratorConfig(BaseConfig):
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
collect_inference_metrics: bool = True
"""Collect inference-server metrics (requires wandb)."""
"""Mirror inference-server metrics to W&B (requires wandb). The ``/metrics`` poll itself always runs — it feeds the concurrency controller."""
inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None
"""Role for each policy admin client when collecting P/D inference metrics."""
@@ -487,11 +511,8 @@ class OrchestratorConfig(BaseConfig):
token_batch_size: int | None = Field(None, ge=1)
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
oversampling_factor: float | None = Field(None, gt=0)
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_episodes`` from ``batch_size`` when ``max_inflight_episodes`` is unset. Values below 1.0 intentionally cap in-flight episode capacity below ``batch_size``."""
max_inflight_episodes: int | None = Field(None, ge=1)
"""Maximum number of episodes kept in-flight — one episode is one agent run at a time, whatever the env's agents are. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight concurrency control (``[orchestrator.concurrency]``)."""
group_size: int = Field(1, ge=1)
"""Output sequences returned per example during training."""
@@ -509,7 +530,7 @@ class OrchestratorConfig(BaseConfig):
"""Maximum training steps. If None, runs indefinitely."""
max_off_policy_steps: int = Field(8, ge=0)
"""Maximum policies allowed to generate a single rollout. Rollouts generated more than ``max_off_policy_steps`` ahead of training are discarded. Higher values yield better throughput at the cost of off-policy noise."""
"""Maximum staleness of a trained rollout: the version a batch trains on (v{step-1}) minus the oldest version that generated the rollout (a rollout can span several weight updates), queue time included. Episodes past the bound are dropped, in-flight and queued; a group shares one dispatch version, so its episodes age out together. Higher values yield better throughput at the cost of off-policy noise."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
@@ -605,29 +626,13 @@ class OrchestratorConfig(BaseConfig):
if not has_rollout_batch and not has_token_batch:
self.batch_size = 128
if has_token_batch:
if self.oversampling_factor is not None:
raise ValueError("oversampling_factor can only be set when batch_size is set")
if self.max_inflight_episodes is None:
raise ValueError("max_inflight_episodes must be set when token_batch_size is set")
else:
assert self.batch_size is not None
if self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
resolved_max_inflight_episodes = max(
self.group_size,
int(self.batch_size * oversampling_factor),
)
if self.max_inflight_episodes is not None and self.oversampling_factor is not None:
expected_max_inflight_episodes = resolved_max_inflight_episodes
if self.max_inflight_episodes != expected_max_inflight_episodes:
raise ValueError("max_inflight_episodes conflicts with oversampling_factor * batch_size")
if self.max_inflight_episodes is None:
self.max_inflight_episodes = resolved_max_inflight_episodes
if self.batch_size is not None and self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
if self.max_inflight_episodes is not None and self.max_inflight_episodes < self.group_size:
raise ValueError("max_inflight_episodes must be at least the number of rollouts per example")
for field in ("max_inflight", "initial_inflight"):
value = getattr(self.concurrency, field)
if value is not None and value < self.group_size:
raise ValueError(f"concurrency.{field} must be at least the number of rollouts per example")
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
for env_cfg in self.train.source:
@@ -8,7 +8,7 @@ from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.evaluator import OnlineEvalConfig
from prime_rl.configs.evals import EvalsEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -23,11 +23,15 @@ from prime_rl.configs.trainer import (
AdamWConfig,
CheckpointConfig,
ConstantSchedulerConfig,
FileSystemWeightBroadcastConfig,
GCConfig,
ModelConfig,
NCCLWeightBroadcastConfig,
OptimizerConfig,
SchedulerConfig,
TokenizerConfig,
WeightBroadcastConfig,
validate_scheduler,
)
from prime_rl.utils.config import BaseConfig, find_package_resource
@@ -42,6 +46,9 @@ class BaseDataConfig(BaseConfig):
micro_batch_size: int = Field(1, ge=1)
"""Per-step micro batch size. ``batch_size`` must be divisible by this."""
num_workers: int = Field(1, ge=1)
"""Number of dataloader worker processes. Batches are prepared and pinned in the background so tokenization/packing overlaps with training."""
@model_validator(mode="after")
def validate_batch_size(self):
if self.batch_size % self.micro_batch_size != 0:
@@ -60,6 +67,9 @@ class FakeDataConfig(BaseDataConfig):
input_ids: Literal["increasing", "random"] = "increasing"
"""Token id generator: ``increasing`` for deterministic sequences, ``random`` for random ids."""
seed: int = 0
"""Seed for the per-rank packing/token generator, combined with the data rank."""
class LossMaskConfig(BaseConfig):
system: bool = False
@@ -166,9 +176,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
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 handoff is weight checkpoints on the shared filesystem,
so the eval job can outlive the trainer job (evals drain after training ends) and
exits after evaluating the final checkpoint."""
from the trainer job. The eval job can outlive the trainer job while it evaluates
the final weight broadcast."""
nodes_per_fsdp_group: int | None = None
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
@@ -195,15 +204,18 @@ class SFTConfig(BaseConfig):
val: SFTValConfig | None = None
"""Validation configuration. If None, no validation runs."""
eval: OnlineEvalConfig | None = None
eval: EvalsEvalConfig | None = None
"""Online evaluation configuration: rollout-based evals against a live inference
server that reloads the trainer's HF weight checkpoints from disk. If None, no
online evals run."""
server that receives the trainer's weight broadcasts. If None, no online evals run."""
inference: InferenceConfig | None = None
"""Inference server for online evals. If None (with ``eval`` set), the launcher
does not start a server and evals connect to ``eval.client.base_url``."""
weight_broadcast: WeightBroadcastConfig | None = None
"""Trainer-to-inference weight transport for online evals. Defaults to NCCL.
LoRA and external inference use filesystem broadcast."""
optim: OptimizerConfig = AdamWConfig()
scheduler: SchedulerConfig = ConstantSchedulerConfig()
@@ -319,9 +331,9 @@ class SFTConfig(BaseConfig):
return self
@model_validator(mode="after")
def full_optimizer_offload_requires_adamw(self):
if self.model.full_offload and self.optim.type != "adamw":
raise ValueError("Full optimizer offload only supports AdamW")
def full_optimizer_offload_requires_supported_optimizer(self):
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
return self
@model_validator(mode="after")
@@ -343,37 +355,47 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_online_eval(self):
"""Wire online evals: require weight checkpoints (the disk handoff to
inference) and connect the eval client to the launcher-managed server."""
"""Wire online evals and the trainer-to-inference weight transport."""
if self.eval is None:
if self.inference is not None:
raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.")
return self
# The trainer's HF weight checkpoints are how inference picks up new policies.
if self.ckpt is None:
self.ckpt = CheckpointConfig()
if self.ckpt.weights is None or self.ckpt.skip_gather_master_weights:
raise ValueError(
"Online evals require HF weight checkpoints. Enable ckpt.weights and "
"disable ckpt.skip_gather_master_weights."
)
# LoRA runs broadcast the raw adapter, which evals reload via /load_lora_adapter
if self.model.lora is not None:
if self.inference is not None:
self.inference.vllm.enable_lora = True
self.inference.vllm.max_lora_rank = self.model.lora.rank
else:
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
"make sure to set --enable_lora and --max-lora-rank.",
stacklevel=2,
)
if self.ckpt.keep_last is not None or self.ckpt.keep_interval is not None:
warnings.warn(
"ckpt.keep_last / ckpt.keep_interval can delete a weight checkpoint before the "
"evaluator consumes it when evals run slower than training - such steps are "
"skipped with a warning instead of evaluated.",
stacklevel=2,
)
if self.weight_broadcast is None:
if self.model.lora is not None or self.inference is None:
self.weight_broadcast = FileSystemWeightBroadcastConfig()
else:
self.weight_broadcast = NCCLWeightBroadcastConfig()
if self.weight_broadcast.type != "filesystem":
if self.weight_broadcast.type == "nixl":
raise ValueError("NIXL weight broadcast is not supported for SFT online evals.")
if self.model.lora is not None:
raise ValueError(
"LoRA training is not yet supported with in-memory weight broadcast. "
"Set weight_broadcast.type = 'filesystem'."
)
if self.eval.retrigger_on_resume:
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 evaluator.
# inference pool (one engine per DP rank behind a router) plus the 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 evaluator."
"a dedicated SLURM job running the inference pool and the evals process."
)
if self.deployment.num_infer_nodes < 1:
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
@@ -392,13 +414,14 @@ class SFTConfig(BaseConfig):
f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by "
f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})."
)
if self.inference.weight_broadcast.type != "filesystem":
raise ValueError(
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
if self.weight_broadcast.type == "nccl":
self.weight_broadcast.inference_world_size = (
self.deployment.num_infer_nodes * self.deployment.gpus_per_node
)
self.inference.weight_broadcast.type = self.weight_broadcast.type
if self.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evaluator never sees a final checkpoint, "
"Online evals without max_steps: the evals process never sees a final checkpoint, "
"so the eval SLURM job holds its allocation until its walltime.",
stacklevel=2,
)
@@ -411,7 +434,7 @@ class SFTConfig(BaseConfig):
"Online evals are configured without an [inference] block - the launcher will not "
f"start an inference server. Make sure one is running at eval.client.base_url "
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
"otherwise the evaluator will hang waiting for it. If a router fronts the "
"otherwise the evals process will hang waiting for it. If a router fronts the "
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
"(pause/update_weights/resume) must bypass the router.",
stacklevel=2,
@@ -444,10 +467,9 @@ class SFTConfig(BaseConfig):
vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size
if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora:
vllm.api_server_count = vllm.data_parallel_size
if self.inference.weight_broadcast.type != "filesystem":
raise ValueError(
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
)
if self.weight_broadcast.type == "nccl":
self.weight_broadcast.inference_world_size = vllm.data_parallel_size * vllm.tensor_parallel_size
self.inference.weight_broadcast.type = self.weight_broadcast.type
host = self.inference.server.host or "localhost"
client = self.eval.client
@@ -539,14 +561,8 @@ class SFTConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
lora_enabled = self.model and self.model.lora
if not lora_enabled:
raise ValueError(
"save_adapter_separately=True requires LoRA to be enabled. "
"Set model.lora or disable save_adapter_separately."
)
def validate_scheduler_steps(self):
validate_scheduler(self.scheduler, self.max_steps)
return self
@model_validator(mode="after")
@@ -55,19 +55,20 @@ class ActivationOffloadingConfig(BaseConfig):
class OptimizerInBackwardOffloadConfig(BaseConfig):
"""Full CPU optimizer offload: FP32 masters, moments, and accumulated gradients live in
CPU RAM, each optimizer chunk runs on CPU as soon as its last gradient arrives, and the
refreshed BF16 weights stream back while backward is still executing.
"""Full CPU optimizer offload: FP32 masters, optimizer state (AdamW moments; SignSGD is
stateless), and accumulated gradients live in CPU RAM, each optimizer chunk runs on CPU as
soon as its last gradient arrives, and the refreshed BF16 weights stream back while backward
is still executing.
Gradient numerics: gradients are reduced across ranks in FP32 (``reduce_dtype``) but FSDP2
materializes them in the sharded parameter's dtype, which is BF16 for the offload compute
model — so each gradient is rounded to BF16 once before the FP32 CPU update. Masters,
moments, accumulation, and Adam arithmetic remain FP32. For gradient numerics bit-faithful
to that path, disable offloading.
moments, accumulation, and optimizer arithmetic remain FP32. For gradient numerics
bit-faithful to that path, disable offloading.
"""
cpu_optimizer_backend: Literal["native", "torch"] = "native"
"""CPU AdamW implementation used by full offload. ``native`` is the production kernel; ``torch`` is a slower debugging and parity fallback."""
"""CPU optimizer implementation used by full offload (AdamW or SignSGD). ``native`` is the production kernel; ``torch`` is a slower debugging and parity fallback."""
numa_bind: bool = True
"""Pin each rank's CPUs to its GPU's NUMA node. Disable when the launcher already manages CPU affinity or GPU sysfs topology is unavailable."""
@@ -241,6 +242,9 @@ class ModelConfig(BaseModelConfig):
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
@@ -255,7 +259,7 @@ class ModelConfig(BaseModelConfig):
debug: DebugModelConfig = DebugModelConfig()
"""Debugging knobs for the model and distributed training."""
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 1024
fused_lm_head_token_chunk_size: int | Literal["disabled"] = 8192
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``disabled`` uses the vanilla LM head. SFT training silently disables this (not supported yet)."""
@model_validator(mode="after")
@@ -386,6 +390,28 @@ SchedulerConfig: TypeAlias = Annotated[
]
def validate_scheduler(scheduler: SchedulerConfig, max_steps: int | None) -> None:
"""Check scheduler phases against max_steps so misconfigurations fail at config time."""
if isinstance(scheduler, LinearSchedulerConfig):
if scheduler.warmup_steps == 0 and scheduler.decay_steps == 0:
raise ValueError(
"Linear scheduler requires warmup_steps > 0 or decay_steps > 0 (use the constant scheduler instead)"
)
if scheduler.decay_steps > 0:
if max_steps is None:
raise ValueError("Must specify max_steps when using a linear scheduler with decay_steps > 0")
if scheduler.warmup_steps + scheduler.decay_steps > max_steps:
raise ValueError(
f"warmup_steps ({scheduler.warmup_steps}) + decay_steps ({scheduler.decay_steps}) "
f"must not exceed max_steps ({max_steps})"
)
if isinstance(scheduler, CosineSchedulerConfig):
if max_steps is None:
raise ValueError("Must specify max_steps when using a cosine scheduler")
if scheduler.warmup_steps >= max_steps:
raise ValueError(f"warmup_steps ({scheduler.warmup_steps}) must be less than max_steps ({max_steps})")
class BaseOptimizerConfig(BaseConfig):
lr: float = Field(1e-6, ge=0)
"""Peak learning rate."""
@@ -439,33 +465,13 @@ OptimizerConfig: TypeAlias = Annotated[
]
class WeightCheckpointConfig(BaseConfig):
save_sharded: bool = True
"""Save the weight checkpoint in sharded format."""
save_format: Literal["safetensors", "torch"] = "safetensors"
"""Weight checkpoint serialization format."""
save_adapter_separately: bool = False
"""Save LoRA adapters separately before merging into full model weights."""
class CheckpointConfig(BaseConfig):
output_dir: Path | None = None
"""Override directory for checkpoints and weights. If set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir`` — useful for writing large checkpoints to a separate storage volume."""
"""Override directory for checkpoints. If set, checkpoints are written here instead of under the trainer ``output_dir`` — useful for writing large checkpoints to a separate storage volume."""
interval: int | None = Field(None, ge=1)
"""Interval at which to save the training checkpoint. If None, only checkpoints at the end of training."""
weights: WeightCheckpointConfig | None = WeightCheckpointConfig()
"""Weight-checkpoint sub-configuration. If None, no HF-compatible weight checkpoints are written."""
skip_gather_master_weights: bool = False
"""Skip gathering and saving HF-compatible weight checkpoints. Useful for large models where the gather is expensive and only DCP checkpoints are needed."""
weights_only: bool = False
"""Save only weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
@@ -546,12 +552,6 @@ class BaseWeightBroadcastConfig(BaseConfig):
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
save_sharded: bool = True
"""Save the weight checkpoint in sharded format."""
save_format: Literal["safetensors", "torch"] = "safetensors"
"""Weight checkpoint serialization format."""
class InMemoryWeightBroadcastConfig(BaseWeightBroadcastConfig):
host: str = "localhost"
@@ -673,9 +673,9 @@ class TrainerConfig(BaseConfig):
return self
@model_validator(mode="after")
def full_optimizer_offload_requires_adamw(self):
if self.model.full_offload and self.optim.type != "adamw":
raise ValueError("Full optimizer offload only supports AdamW")
def full_optimizer_offload_requires_supported_optimizer(self):
if self.model.full_offload and self.optim.type not in ("adamw", "sign_sgd"):
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
return self
@model_validator(mode="after")
@@ -720,14 +720,8 @@ class TrainerConfig(BaseConfig):
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
lora_enabled = self.model and self.model.lora
if not lora_enabled:
raise ValueError(
"save_adapter_separately=True requires LoRA to be enabled. "
"Set model.lora or disable save_adapter_separately."
)
def validate_scheduler_steps(self):
validate_scheduler(self.scheduler, self.max_steps)
return self
@model_validator(mode="after")
@@ -16,8 +16,8 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Qwen3.5 and Qwen3-Coder use qwen3_coder — must be before the Qwen3 catch-all.
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3_coder"),
# Qwen3.5/3.6/3.8 and Qwen3-Coder use qwen3_coder — must be before the Qwen3 catch-all.
(re.compile(r"^Qwen/Qwen3\.(5|6|8)-"), "qwen3_coder"),
(re.compile(r"^Qwen/Qwen3-Coder"), "qwen3_coder"),
(re.compile(r"^Qwen/Qwen3-"), "hermes"),
]
@@ -37,7 +37,7 @@ REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Only Qwen3 Thinking models reason — Instruct/base models do not.
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3"),
(re.compile(r"^Qwen/Qwen3\.(5|6|8)-"), "qwen3"),
]
+12 -5
View File
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.3.1.dev33",
"verifiers[harbor]>=0.3.1.dev59",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -53,7 +53,7 @@ sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evaluator = "prime_rl.entrypoints.evaluator:main"
evals = "prime_rl.entrypoints.evals:main"
env-server = "prime_rl.entrypoints.env_server:main"
[project.entry-points."vllm.general_plugins"]
@@ -86,6 +86,11 @@ gpt-oss = [
quack = [
"quack-kernels>=0.4.1",
]
# 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",
]
all = [
"prime-rl[flash-attn]",
"prime-rl[disagg]",
@@ -196,6 +201,7 @@ deep-ep = false
deep-gemm = false
nixl-cu12 = false
torchao = false
prime-kernels = false
[tool.uv.sources]
prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
@@ -227,6 +233,10 @@ 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'" },
]
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'" },
]
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" }
@@ -261,9 +271,6 @@ select = ["F", "I"]
"src/prime_rl/trainer/sft/data.py" = ["F722", "F821"]
[tool.ruff.lint.isort]
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
# Without this, ruff classifies prime_rl.configs.* as third-party because it
# doesn't live under src/.
known-first-party = ["prime_rl"]
known-third-party = ["verifiers", "renderers", "pydantic_config"]
+10 -20
View File
@@ -34,7 +34,9 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
## Special syntax
**No inline tables** — checked-in configs use `[section]` headers, never `key = { ... }`. Expand `env.taskset = { id = "..." }` to a full-path header (`[orchestrator.train.source.env.taskset]` — subtable headers after a `[[...]]` entry attach to that entry).
**No inline tables** — checked-in configs use `[section]` headers or dotted keys, never `key = { ... }`.
**Sources are one block** — inside a `[[...source]]` entry, write nested sub-configs as dotted keys in the same block (`env.taskset.id = "..."`, `env.agent.harness.id = "..."`), not one subsection header per nested config. Nested arrays of tables (e.g. `[[orchestrator.train.source.env.taskset.task.judges]]`) keep full-path headers — they attach to the preceding `[[...source]]` entry.
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
@@ -45,28 +47,16 @@ Incompatible combinations (e.g. CP requires flash attention) must raise in a `mo
```toml
[[orchestrator.train.source]]
name = "reverse-text"
[orchestrator.train.source.env.taskset]
id = "reverse-text"
[orchestrator.train.source.env.agent.harness]
id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
[[orchestrator.eval.source]]
name = "reverse-text-eval"
[orchestrator.eval.source.env.taskset]
id = "reverse-text"
split = "test"
[orchestrator.eval.source.env.agent.harness]
id = "null"
[orchestrator.eval.source.env.agent.runtime]
type = "subprocess"
env.taskset.id = "reverse-text"
env.taskset.split = "test"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
+19
View File
@@ -35,6 +35,25 @@ When bumping a package past the workspace-wide `exclude-newer = "7 days"` window
## Optional extras
### CUDA kernels
Prebuilt wheels, pinned at a release in `[tool.uv.sources]`:
```bash
uv sync --extra kernels
```
No plain sync compiles CUDA — building from source stays an explicit, manual step (needs
`nvcc` whose CUDA major matches torch's and the `deps/prime-kernels` submodule initialized),
and overrides the wheel until the next sync:
```bash
git submodule update --init deps/prime-kernels
uv pip install --no-build-isolation -e deps/prime-kernels
```
See the `kernels` skill.
### NemotronH (Mamba SSD kernels)
```bash
+180
View File
@@ -0,0 +1,180 @@
---
name: kernels
description: How prime-rl vendors, builds, and ships CUDA kernels (the `deps/prime-kernels` submodule and the `prime-kernels` wheel). Use when adding a kernel, building it locally, calling one from training code, or publishing prebuilt wheels.
---
# CUDA kernels
CUDA kernels live in their own monorepo,
[prime-kernels](https://github.com/PrimeIntellect-ai/prime-kernels), checked out here as the
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
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.
Living under `deps/` means `tool.ruff.extend-exclude = ["deps"]` in `pyproject.toml`
already covers it — prime-rl lints none of it.
## Calling a kernel from prime-rl
Kernels are compiled for exact compute capabilities and may not be built at all, so always
gate. Never import `prime_kernels.<name>` directly in training code:
```python
import prime_kernels
if prime_kernels.is_available("flash_moe"):
flash_moe = prime_kernels.load("flash_moe")
```
`prime_kernels.status()` maps every kernel to `"available"` or the reason it is not — log
it once at startup rather than failing a run halfway through. `unavailable_reason(name)` is
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`.
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.
## Building locally
`uv sync --extra kernels` installs the prebuilt wheel (see "Pinning installs at the prebuilt
wheels"); building from source is for changing kernels. It is manual by design — no `uv sync`
may compile CUDA, so the extra resolves to release wheels, never to this source tree:
```bash
git submodule update --init deps/prime-kernels
uv pip install --no-build-isolation -e deps/prime-kernels
```
Requirements: `nvcc` on `CUDA_HOME` with the **same CUDA major as torch** (torch refuses to
build extensions otherwise).
Kernels whose toolkit is unsuitable are skipped with a message and reported unavailable at
runtime — the build still succeeds. `PRIME_KERNELS=a,b` builds a subset;
`PRIME_KERNELS_REQUIRE=1` turns any skip into an error.
## Changing or adding a kernel
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.
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.)
4. Nothing else: `setup.py` and the runtime registry both read the manifest.
Rules the build assumes:
- The extension is always `prime_kernels.<name>._C`, so the C++ side defines
`PYBIND11_MODULE(_C, m)` and registers ops with `TORCH_LIBRARY*`.
- `arch` matches the device **exactly** at runtime (`10.0a` runs only on sm_100a); no PTX is
shipped to JIT from.
- Two packages registering the same `torch.ops` namespace collide. If a kernel's sources are
also installed as a standalone package (e.g. `prime_moe` from prime-flash-moe, where
`flash_moe` originally came from), uninstall it.
- Only the Python surface and the compiled `_C` ship in the wheel; `csrc/` is build input.
Then land it in prime-rl as a submodule bump.
## Bumping the pin
Kernel sources are pinned by the submodule commit, so picking up any kernel change — yours
or someone else's — is a bump:
```bash
git -C deps/prime-kernels fetch origin
git -C deps/prime-kernels log --oneline HEAD..origin/main
git -C deps/prime-kernels checkout origin/main
git add deps/prime-kernels
```
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.
- 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.
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:
```bash
gh workflow run build_kernels.yaml -f release_tag=vX.Y.Z -f ref=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.
### 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:
```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'" },
]
```
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 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.
## 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.
- 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.
+16 -2
View File
@@ -9,7 +9,8 @@ Releases are driven by [`.github/workflows/tag-and-release.yaml`](../../.github/
1. You create a **draft GitHub Release** with the notes inline (`gh release create --draft`).
2. You open a **draft PR** that bumps `version` in `pyproject.toml`.
3. Maintainer merges. The workflow tags the commit and promotes the draft.
3. Maintainer merges. The workflow tags the commit, builds the `prime-kernels` wheels and
attaches them to the draft, then promotes it.
Release notes live on the GitHub Release, not in the repo. Prime-rl is **not** on PyPI. `.dev` tags are handled separately by `devx_tag.yaml`; `tag-and-release.yaml` ignores them.
@@ -64,6 +65,19 @@ gh pr create --draft --title "chore: release $NEW" --body "Bumps version to ${NE
Stop. Do not tag, push tags, or flip the draft to published — the workflow does that on merge.
## 5. After it publishes: move the kernel pin
The release now carries `prime_kernels-*.whl` for x86_64 and aarch64. Point installs at them
so nobody compiles CUDA, in a follow-up PR:
```bash
gh release view "$NEW" --json assets --jq '.assets[].name' # exact filenames, ABI and all
```
Update the `prime-kernels` URLs under `[tool.uv.sources]` in `pyproject.toml` to `$NEW`, then
`uv sync --all-extras` to relock. The pin always trails one release — `$NEW`'s wheels do not
exist until `$NEW` is built. See the `kernels` skill.
## Recovery
If the workflow tagged the commit but failed to promote the draft, the next main push (or `workflow_dispatch` with `tag: v{new}`) re-promotes it.
If the workflow tagged the commit but failed to promote the draft, the next main push (or `workflow_dispatch` with `tag: v{new}`) re-promotes it. A rerun rebuilds and re-uploads the kernel wheels (`--clobber`), which is harmless.
+19 -19
View File
@@ -58,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
- `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}/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 rollout traces (see Traces below).
- `{run_dir}/rollouts/step_N/{train,eval}/` — saved episodes (see Episodes below).
### Logs
@@ -66,7 +66,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
├── evaluator.log # SFT online-eval evaluator stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evaluator.log)
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -82,7 +82,7 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
Scan for problems:
```bash
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evaluator,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evals,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
```
@@ -130,7 +130,8 @@ All metrics print to the console log (and W&B when configured).
| trainer | `perf/throughput`, `perf/mfu` | tokens/s and MFU % |
| orchestrator | `time/step`, `time/save_ckpt` | phase timings |
| orchestrator | `time/wait_for_policy` | **high → trainer is bottleneck** |
| orchestrator | `dispatcher/off_policy_level_{mean,max}`, `dispatcher/inflight_{train,eval}`, `dispatcher/groups_in_flight`, `dispatcher/queued/eval` | dispatcher / async state |
| orchestrator | `dispatcher/off_policy/{mean,max}`, `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
| 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 |
For live vLLM stats, query Prometheus directly:
@@ -140,31 +141,30 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
```
### Traces
### Episodes
```
{run_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
{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
```
JSONL files of `vf.Trace` records (training tensors excluded), one line per trace — a
multi-agent env's episode contributes several lines sharing one `info.episode_id`. `all`
gets every completed rollout the moment it arrives — errored, curriculum-rejected, and never-batched
ones included — so it's crash-durable; `effective` gets the clean trainable subset that went
into the step's train batch (eval: the non-errored trainable epoch cohort; multiple eval envs
share the step file) — untrainable traces (a frozen judge's) appear only in `all`. Each record carries `run` (`{type, id, step}`; for eval, `step` is the trigger step),
`verifiers` (producing build), `agent` (model, sampling, harness, `name`, `trainable`), `ok`
(the success sentinel — `errors` alone keeps retry history even after a recovery), and
`runtime` (config + provisioned resource id, e.g. the sandbox id), plus `env_name`,
`group_id`, `episode_id`, and `policy_version` under `info`.
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.
```bash
wc -l {run_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
jq '.rewards' {run_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.ok | not) | {id, env: .info.env_name, runtime}' {run_dir}/rollouts/step_*/train/all/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
```
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 trace subtrees.
The batches consumed by the trainer are shipped over ZMQ by default, so nothing binary is written. With `rollout_transport.type = "filesystem"` they land at `{run_dir}/rollouts/step_N/rank_<rank>.bin` (one packed micro-batch file per trainer DP rank), next to the episode subtrees.
### Common failure modes
+43 -5
View File
@@ -1,6 +1,6 @@
---
name: start-run
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
description: How to launch prime-rl training runs — the `rl`, `sft`, `inference`, and `evals` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
---
# Start a run
@@ -9,7 +9,7 @@ All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/t
## Run directories
`output_dir` (default `outputs`) groups related runs; each run writes all its artifacts (logs, configs, checkpoints, weights, 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).
`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).
## Config system at a glance
@@ -27,7 +27,8 @@ All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/t
- State-only optimizer offload remains enabled by default with `model.optim_cpu_offload = true`.
- For gradients, FP32 masters, optimizer state, and optimizer-in-backward CPU execution, set
`model.optim_cpu_offload = false` and `model.full_offload = true`. This mode uses the native
CPU AdamW kernel, only supports AdamW, and disables gradient clipping. Use a
CPU optimizer kernel, only supports AdamW and SignSGD (SignSGD is stateless and
halves the host RAM footprint), and disables gradient clipping. Use a
`[model.full_offload]` table only to select the Torch debugging backend or disable NUMA binding.
## `rl` — RL training
@@ -47,8 +48,10 @@ uv run rl @ examples/basic/reverse-text/rl.toml --dry-run
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym'))"`).
If a local env exists under `deps/prime-envs/environments/` or
`deps/verifiers/environments/` but does not import, install the env workspace
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
members with `uv sync --all-extras --all-packages` (all) or `uv sync --all-extras
--package prime-rl --package <env>` (one) — they're auto-discovered, no
`pyproject.toml` edit needed. Keep `--all-extras` for training so a targeted
package sync does not prune accelerator dependencies from the environment.
## `sft` — SFT training
@@ -87,6 +90,40 @@ curl http://localhost:8000/v1/chat/completions \
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
- SLURM: single-node, multi-node, and disaggregated deployments
## `evals` — multi-env evals
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. 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.
```bash
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
uv run evals @ eval.toml
```
Minimal standalone `eval.toml`:
```toml
model = "Qwen/Qwen3-4B"
[eval.client]
base_url = "http://localhost:8000/v1"
[eval.concurrency] # adaptive; same controller as [orchestrator.concurrency]
min_inflight = 8
max_inflight = 128
[[eval.source]]
num_examples = 32 # always cap eval size for smokes
group_size = 4
env.taskset.id = "aime25"
env.agent.harness.id = "null"
env.agent.runtime.type = "subprocess"
```
- 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`.
- 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`)
## Summary
| Command | Purpose | Typical use |
@@ -94,6 +131,7 @@ curl http://localhost:8000/v1/chat/completions \
| `rl` | Full RL pipeline | Production RL training |
| `sft` | Supervised fine-tuning | SFT and hard-distill |
| `inference` | vLLM server | Standalone serving / debugging |
| `evals` | Multi-env evals | Standalone evals / SFT online evals |
## Key paths
+24
View File
@@ -0,0 +1,24 @@
"""Lightweight launcher for the online evals.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evals --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.evals.evals``.
"""
import asyncio
from prime_rl.configs.evals import EvalsConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evals")
config = cli(EvalsConfig)
from prime_rl.evals.evals import run_evals
asyncio.run(run_evals(config))
if __name__ == "__main__":
main()
-24
View File
@@ -1,24 +0,0 @@
"""Lightweight launcher for the online evaluator.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evaluator --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.orchestrator.evaluator``.
"""
import asyncio
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evaluator")
config = cli(EvaluatorConfig)
from prime_rl.orchestrator.evaluator import run_evaluator
asyncio.run(run_evaluator(config))
if __name__ == "__main__":
main()
+78 -56
View File
@@ -1,6 +1,5 @@
import json
import os
import shutil
import signal
import subprocess
import sys
@@ -9,7 +8,7 @@ from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.evaluator import EvaluatorConfig
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
@@ -19,12 +18,10 @@ from prime_rl.utils.pathing import (
clean_future_steps,
create_attempt_log_dir,
format_log_message,
get_all_ckpt_steps,
get_broadcast_dir,
get_ckpt_dir,
get_config_dir,
get_log_dir,
get_step_path,
get_weights_dir,
latest_log_dir,
resolve_latest_ckpt_step,
validate_run_dir,
@@ -46,7 +43,7 @@ EVAL_SBATCH = "eval.sbatch"
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
INFERENCE_CONFIG = "inference.json"
EVALUATOR_CONFIG = "evaluator.json"
EVALS_CONFIG = "evals.json"
ENVS_DIR = "envs"
@@ -66,7 +63,7 @@ def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
def get_ckpt_base(config: SFTConfig) -> Path:
"""Where checkpoints and weights live: ``ckpt.output_dir`` when set, else the run dir."""
"""Where checkpoints live: ``ckpt.output_dir`` when set, else the run dir."""
return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir
@@ -80,16 +77,25 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_evaluator_config(config: SFTConfig) -> EvaluatorConfig:
"""Derive the evaluator subconfig from the resolved SFT config."""
def build_evals_config(config: SFTConfig) -> EvalsConfig:
"""Derive the evals subconfig from the resolved SFT config. The launcher
spawns the env servers itself, so each source's derived address is stamped in,
marking it externally managed for the evals process."""
assert config.eval is not None
return EvaluatorConfig(
eval_config = config.eval.model_copy(deep=True)
addresses = config.eval.env_addresses
for source in eval_config.source:
source.serve.address = addresses[("eval", source.resolved_name)]
return EvalsConfig(
model=config.model.name,
eval=config.eval,
weights_dir=get_weights_dir(get_ckpt_base(config)),
eval=eval_config,
weight_broadcast=config.weight_broadcast,
online=OnlineConfig(
broadcasts_dir=get_broadcast_dir(config.run_dir),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
),
output_dir=config.run_dir,
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
)
@@ -103,7 +109,7 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
"""Write the inference, evaluator, and env-server configs for online evals."""
"""Write the inference, evals, and env-server configs for online evals."""
config_dir.mkdir(parents=True, exist_ok=True)
if config.inference is not None:
@@ -116,11 +122,11 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
with open(config_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
with open(config_dir / EVALUATOR_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evaluator_config(config)), f, indent=2)
with open(config_dir / EVALS_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evals_config(config)), f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
# binds at the source's deterministic address, where the evaluator connects.
# binds at the source's deterministic address, where the evals process connects.
for source, address in eval_env_servers(config):
env_dir = config_dir / ENVS_DIR / "eval"
env_dir.mkdir(parents=True, exist_ok=True)
@@ -168,6 +174,11 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
run_name=config.run.name,
use_nccl_broadcast=(
config.eval is not None
and config.weight_broadcast is not None
and config.weight_broadcast.type == "nccl"
),
)
script_path.parent.mkdir(parents=True, exist_ok=True)
@@ -176,7 +187,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
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 + evaluator) to disk."""
env servers + evals) to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
@@ -199,7 +210,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
**config.env_vars,
**config.inference.env_vars,
}
evaluator_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
script = template.render(
**config.slurm.template_vars,
@@ -214,10 +225,11 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
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,
evaluator_env_vars=evaluator_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)
@@ -226,10 +238,9 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
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 + evaluator) are two independent
SLURM jobs: the handoff is weight checkpoints on the shared filesystem, so the
trainer job releases its allocation when training finishes while the eval job
keeps draining evals and exits after the final checkpoint."""
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."""
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
@@ -244,13 +255,13 @@ def sft_slurm(config: SFTConfig):
else {"slurm", "dry_run", "clean"}
)
if decoupled_eval:
# The trainer job only needs [eval] for the weight-checkpoint cadence; the
# The trainer job only needs [eval] for the weight-broadcast cadence; the
# inference pool lives in the eval job.
exclude = exclude | {"inference"}
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
# Trainer and evaluator processes log to a single shared W&B run across both jobs,
# Trainer and evals processes log to a single shared W&B run across both jobs,
# keyed by the launcher's run id.
prl_run_id: str | None = None
if decoupled_eval and config.monitors.wandb is not None:
@@ -261,8 +272,8 @@ def sft_slurm(config: SFTConfig):
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 evaluator's joiner init only
# retries for a bounded window — starting the evaluator while the trainer job pends
# 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:
@@ -283,16 +294,26 @@ def sft_slurm(config: SFTConfig):
# 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),
evaluator=True,
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:
submit = "\n".join(f" sbatch {path}" for path in script_paths)
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 evaluator joins the W&B run the trainer creates."
"\n\nSubmit the trainer job first. The eval job starts after the trainer allocation is ready."
if decoupled_eval
else ""
)
@@ -307,6 +328,8 @@ def sft_slurm(config: SFTConfig):
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)
@@ -360,17 +383,17 @@ def sft_local(config: SFTConfig):
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
# Trainer and evaluator log to a single shared W&B run whose id ($WANDB_RUN_ID)
# Trainer and evals log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
wandb_shared_env: dict[str, str] = {}
if config.eval is not None:
# The trainer creates the run; the evaluator (which drains its final evals
# The trainer creates the run; the evals process (which drains its final evals
# after the trainer exits) finalizes it.
wandb_shared_env = {
"WANDB_SHARED_MODE": "1",
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
"WANDB_SHARED_PRIMARY": "trainer",
"WANDB_SHARED_FINISHER": "evaluator",
"WANDB_SHARED_FINISHER": "evals",
"WANDB_PROGRAM": "uv run sft",
"WANDB_ARGS": json.dumps(sys.argv),
}
@@ -419,7 +442,7 @@ def sft_local(config: SFTConfig):
log_path=log_dir / "inference.log",
)
# Start one env server per eval source. The evaluator connects to each source's
# Start one env server per eval source. The evals process connects to each source's
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
name = source.resolved_name
@@ -432,19 +455,19 @@ def sft_local(config: SFTConfig):
)
if config.eval is not None:
logger.info("Starting evaluator process")
logger.info("Starting evals process")
start_process(
"evaluator",
["evaluator", "@", (config_dir / EVALUATOR_CONFIG).as_posix()],
"evals",
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evaluator",
"WANDB_SHARED_LABEL": "evals",
},
log_path=log_dir / "evaluator.log",
log_path=log_dir / "evals.log",
)
from prime_rl.utils.utils import get_free_port
@@ -487,11 +510,11 @@ def sft_local(config: SFTConfig):
)
processes.append(tail_process)
# Wait for the trainer (and the evaluator, which drains its final evals after
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "evaluator" in stop_events:
terminal_events.append(stop_events["evaluator"])
if "evals" in stop_events:
terminal_events.append(stop_events["evals"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
@@ -527,29 +550,28 @@ def sft_local(config: SFTConfig):
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
"""Remove eval artifacts a previous run left behind: weight checkpoints and rollout
"""Remove eval artifacts a previous run left behind: weight broadcasts and rollout
trace dirs — everything on a fresh start, steps past the resume step on resume.
Without this the evaluator would replay stale checkpoints (and then skip the
Without this the evals process would replay stale broadcasts (and then skip the
re-trained ones at the same steps), and the append-only trace files would mix two
policies' rollouts under one step."""
logger = setup_logger(config.log.level or "info")
if os.environ.get("NEVER_CLEAN"):
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evaluator may replay them")
logger.warning("NEVER_CLEAN is set - keeping stale weight broadcasts; the evals process may replay them")
return
resume_step = resolve_resume_step(config)
weights_dir = get_weights_dir(get_ckpt_base(config))
stale_steps = [step for step in get_all_ckpt_steps(weights_dir) if resume_step is None or step > resume_step]
if stale_steps:
logger.info(
f"Deleting {len(stale_steps)} stale weight checkpoint(s) in {weights_dir} "
f"({','.join(map(str, stale_steps))})"
)
for step in stale_steps:
shutil.rmtree(get_step_path(weights_dir, step), ignore_errors=True)
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
def sft(config: SFTConfig):
# Launcher-only check: the trainer re-parses a sub-config with [inference] and
# [deployment] stripped, so the model validator cannot enforce this.
if config.weight_broadcast is not None and config.weight_broadcast.type == "nccl" and config.inference is None:
raise ValueError(
"NCCL weight broadcast requires launcher-managed inference. "
"Add an [inference] block or set weight_broadcast.type = 'filesystem'."
)
# The run identity is runtime-only, never sub-config: $PRL_RUN_ID / $PRL_RUN_NAME are
# the vehicle for runtime info between processes, and every spawned process inherits
# them. Components launched standalone have no run identity.
View File

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