Compare commits

...
Author SHA1 Message Date
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
Konstantin DunasandGitHub 61f2448d1d feat(orchestrator): add composable curricula (#3261) 2026-08-19 00:47:35 +02:00
c7a6573de5 chore: simplify ignore files to outputs/ (#3295)
* simplify artifact ignore rules to outputs/

Since the run-dir unification, every run artifact (logs, checkpoints,
weights, rollouts, evals, broadcasts, wandb, torchrun logs, sbatch
scripts) lives under output_dir, which defaults to outputs/. The
recursive **/<dir> patterns and their negations are redundant.

The **/wandb pattern also kept the wandb monitor source package out
of the docker build context (see #3292). Ignoring only outputs/
removes that class of bug.

Delete scripts/clean.sh: it mirrored the same recursive list, is
referenced nowhere, and rm -rf outputs/ replaces it.

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

* ignore .codex directory

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 10:52:22 -07:00
8b2819b4c7 fix(docker): re-include the wandb monitor package in the build context (#3292)
`**/wandb` (added in #3279) targets W&B's local run-output dirs, but it
also matches src/prime_rl/monitors/wandb/, which became a package in
#3275. `COPY src/ /app/src/` reads the filtered context, so the package
never reached the image and every entrypoint died at import:

    File "/app/src/prime_rl/monitors/__init__.py", line 19
      from prime_rl.monitors.wandb import WandbMonitor
    ModuleNotFoundError: No module named 'prime_rl.monitors.wandb'

monitors/__init__.py is imported unconditionally, so this took down the
orchestrator and trainer whether or not W&B was configured.

.gitignore already carries this exemption; mirror it here. The pair sits
above the bytecode patterns so those still strip __pycache__/*.pyc back
out of the re-included directory - last matching line wins.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 23:38:13 -07:00
1fd4fefd4a fix(tests): migrate full-offload SFT fixture to num-train-gpus (#3291)
PR #3256 renamed SFT deployment.num_gpus to num_train_gpus, but the
full-offload resume fixture from #3234 merged in parallel and kept the
old flag, failing config validation on main.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 20:22:33 -07:00
15d6c81974 feat: online evals during sft (#3256)
* Add online evals to the SFT entrypoint

The sft launcher now composes an inference server, one env server per
eval source, and a new evaluator process next to the trainer. The
handoff is the filesystem, not NCCL: the trainer writes HF weight
checkpoints at every step an eval env is due, and the evaluator points
the inference server at each stable checkpoint (/update_weights from
disk) before running the due evals, sequentially per checkpoint.

The evaluator reuses the orchestrator's eval components (EvalEnvs,
EvalSource, EvalSink, EvalRollouts) and logs eval/{env}/... metrics and
rollout traces exactly like RL, into the same W&B run as the trainer
(shared mode; the new WANDB_SHARED_PRIMARY env var selects the primary
process, defaulting to the previous orchestrator behavior).

Online evals are single-node only for now.

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

* Harden the SFT online-eval launcher and evaluator

Address review findings on the initial implementation:

- Skip an eval step (with an error log) when the weight reload fails
  instead of killing the training run; drain the queued examples so they
  cannot leak into a later epoch with the wrong eval_step.
- Clean stale weights/step_N dirs at launch (all on fresh start, past
  the resume step on resume) so the evaluator never replays checkpoints
  from an abandoned run.
- Reconcile deployment.num_infer_gpus with inference.vllm TP/DP,
  mirroring RLConfig.auto_setup_deployment.
- Install a SIGTERM handler in sft_local (it now spawns GPU-holding
  children beyond torchrun), avoid busy-spinning while the evaluator
  drains final evals, and probe GPUs only when partitioning them so
  plain SFT keeps its old no-NVML behavior.
- Make the evaluator the shared-W&B primary - it exits last, so it must
  own run finalization.
- Warn when ckpt.keep_last/keep_interval can clean a checkpoint before
  the evaluator consumes it, and document the retention interplay and
  the standalone admin_base_url requirement.
- Fix pre-existing is_last_step off-by-one: resuming from a checkpoint
  at step >= max_steps no longer trains forever.

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

* Add multi-node SFT online evals with decoupled SLURM jobs

With [eval] set on a multi_node deployment, the sft launcher submits
two independent SLURM jobs: the trainer (deployment.num_nodes) and an
eval job (deployment.num_infer_nodes) running the inference pool (one
vLLM engine per DP rank behind a router), one env server per eval
source, and the evaluator. The only coupling is weight checkpoints on
the shared filesystem, so the trainer job releases its allocation when
training finishes while the eval job keeps draining checkpoints and
exits after evaluating the final one. Any train x inference node
layout works.

The eval job is submitted first and the trainer depends on it having
started (--dependency=after), so the trainer joins the shared W&B run
the evaluator creates instead of timing out while the eval job pends;
a failed second submission cancels the first. On a clean evaluator
exit, node 0 publishes a job-scoped sentinel that releases the other
inference nodes, since a zero exit never trips --kill-on-bad-exit.

Also hardens the eval handoff paths: weight-checkpoint cleaning always
keeps the newest checkpoint (keep_interval-only cleaning used to
delete a non-aligned final checkpoint right after saving it, hanging
the evaluator), the evaluator skips abandoned STABLE-less checkpoints
instead of wedging on them, clean_stale_weights honors
NEVER_CLEAN_OUTPUT_DIR, and validate_output_dir sees ckpt.output_dir.

Verified e2e: Qwen3-30B-A3B-Thinking-2507 SFT on one node with AIME25
online evals on another; both jobs completed with exit code 0.

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

* Make the trainer own the shared W&B run

Split run creation from run finalization in shared W&B mode: the
WANDB_SHARED_PRIMARY process creates the run and the new
WANDB_SHARED_FINISHER process (defaulting to the primary) writes its
final state. The SFT trainer is now the primary in both the single-node
and decoupled multi-node online-eval deployments, so the run exists
even if the eval side never starts; the evaluator, which outlives the
trainer, stays the finisher so the run isn't marked finished while
final evals still log.

The decoupled submission order flips accordingly: the trainer job goes
first and the eval job depends on it having started, keeping the
joiner's bounded wandb-init retry window covering only startup lag.

Verified on a 2-node run: trainer inits with primary=True/
finisher=False, evaluator joins with primary=False/finisher=True, both
jobs exit 0, and the shared run ends in state "finished" with trainer
and eval metrics.

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

* Add an SFT-flavored W&B overview view

The auto-provisioned overview saved view previously only had an RL
shape; SFT runs fell back to rollout-metric train panels that SFT
never logs. build_sections gains an "sft" flavor: the train section is
the loss and perplexity curves (train + validation) plus epoch
progress, the eval sections stay the rollout-based ones shared with
RL, and stability/performance show the metrics the SFT trainer
actually emits. The SFT trainer and the evaluator select the flavor
through setup_monitor.

The trainer now also logs loss/perplexity and val/perplexity
(exp of the mean loss, clamped to avoid overflow on divergence).

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

* address online-eval review findings

- Warn when an eval-due weight checkpoint was deleted by ckpt.keep_last
  / keep_interval cleaning before the evaluator could evaluate it, and
  advance past it instead of silently gapping the eval curve.
- Restore RL's enable_lora guard in the api_server_count DP fill, which
  the copy from RLConfig.auto_setup_deployment had dropped.
- Also clean stale rollout trace dirs at launch (clean_future_steps),
  not just weight checkpoints: the append-only trace files would
  otherwise mix two policies' rollouts under one step after a crash and
  resume.
- Parse sbatch job ids with --parsable; the human-readable output
  varies on multi-cluster setups and broke the dependency/cancel paths.
- Mention the evaluator log in the monitor-run skill.

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

* address pr review comments

- Rename SFT deployment.num_gpus to num_train_gpus, matching the rl
  launcher's num_train_gpus / num_infer_gpus API. Breaking: the old key
  fails as unknown.
- Flatten EvaluatorConfig.model to model_name and document how it is
  used: the served-model name on every eval request, auto-filled from
  model.name by the sft launcher; weights swap in place under one name,
  so per-step results are told apart by eval/{env}/policy_version.
- Trim the online-evals docs detail paragraph and fold the W&B overview
  mention into one clause covering RL and SFT runs.
- Drop the [eval] explainer comment from the reverse-text example.

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

* address self-review comments

- Rename multi-node deployment.num_nodes to num_train_nodes (matching
  the rl launcher). Breaking: the old key fails as unknown.
- Rename EvaluatorConfig.model_name to model and raise the default
  max_inflight_episodes to 128.
- Hardcode the evaluator's weights dir to <output_dir>/weights (it was
  always launcher-derived); with [eval] set, ckpt.output_dir is now
  rejected instead of silently pointing the evaluator elsewhere.
- Drop the online-evals bullet from the start-run skill.

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

* bring back the evaluator weights_dir field

Weight checkpoints follow ckpt.output_dir when checkpoints are
redirected to another volume, so a hardcoded <output_dir>/weights
cannot cover that deployment. The launcher fills weights_dir from the
checkpoint base again, and ckpt.output_dir is supported with [eval].

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

* fix eval with redirected checkpoint dir and final-eval retrigger

The ckpt.output_dir rejection was meant to be removed when weights_dir
came back but the edit never landed (the format hook had reshaped the
raise and the scripted match failed silently) - remove it for real; the
evaluator watches <ckpt.output_dir>/weights via the launcher-filled
weights_dir.

Also force-fire every env when retrigger_on_resume resumes at the final
checkpoint (a crashed final eval was never retried when max_steps is
not interval-aligned), and trim a verbose comment.

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

* alias num_eval_gpus/num_eval_nodes for the infer deployment knobs

num_infer_gpus / num_infer_nodes stay canonical (rl-launcher parity)
and accept num_eval_gpus / num_eval_nodes via AliasChoices. The
deployment pre-validator collapses the alias onto the canonical key:
pydantic rejects a dict carrying both spellings, which is exactly the
common layering (canonical in the TOML, alias on the CLI).

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

* fix alias precedence via pydantic-config bump

The deployment pre-validator collapsed the num_eval_* aliases onto the
canonical keys with the alias always winning, which inverted
CLI-over-file precedence when the file used the alias and the CLI the
canonical spelling. The real gap was in pydantic-config:
_normalize_alias_keys never recursed into discriminated-union variants.
Bump the submodule to the fix (pydantic-config#23) and drop the
collapse - alias spellings now merge onto one key with normal
precedence in every layering.

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

* bump pydantic-config to v0.4.3 (merged alias fix)

Re-point the submodule from the PR-branch commit to the squash-merged
main commit, released as prime-pydantic-config 0.4.3.

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

* floor prime-pydantic-config at 0.4.3

The online-eval deployment aliases rely on 0.4.3's union-aware alias
normalization.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 17:41:34 -07:00
minh hoangandGitHub 4f5d943a15 fix(monitors): allow overriding the platform base URL via $PRIME_API_BASE (#3287)
The prime monitor's TrainRun hardcodes the production public API
(https://api.primeintellect.ai/api/v1/rft). Managed launches need to point
it at the platform's internal ingestion path instead, and non-prod
environments currently post metrics to prod (where their per-run tokens
401) — silently, since uploads are fire-and-forget.

$PRIME_API_BASE is taken verbatim when set (the platform already injects
it on managed orchestrator pods as {SERVICE_URL}/api/internal/rft);
otherwise the default is unchanged. Resolved once in __init__ and stored,
since the atexit _mark_failed hook must agree with the client.
2026-08-17 15:51:35 -07:00
572cc82e76 chore: bump verifiers to latest main (#3286)
Picks up 8 commits (91a267616..02cc940d8), notably the prime-sandboxes
0.2.37 floor (VM idle timeout + vm-opt-out validation) and the
intercepted-response replay gate (vf#2368). Adds a bounded harbor
cutoff mirroring deps/verifiers: verifiers pins harbor==0.21.0, which
the rolling exclude-newer window rejects.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 13:38:54 -07:00
141 changed files with 3547 additions and 1407 deletions
+1 -6
View File
@@ -1,16 +1,11 @@
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
outputs
**/.venv
**/__pycache__
**/*.py[cod]
**/.pytest_cache
**/.ruff_cache
**/.mypy_cache
**/wandb
**/checkpoints
**/weights
**/broadcasts
**/rollouts
**/torchrun
.claude
.vscode
*.ipynb
+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
+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: |
+3 -3
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
@@ -148,14 +148,14 @@ jobs:
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
+3 -19
View File
@@ -1,27 +1,13 @@
.vscode/*
.claude/scheduled_tasks.lock
.claude/worktrees/
.codex/
*.ipynb
*.jsonl
configs/endpoints.py
# Artifacts
**/slurm
!src/prime_rl/slurm
!examples/slurm
!docs/slurm.md
**/torchrun
**/weights
**/checkpoints
**/broadcasts
**/rollouts
**/logs
**/wandb
!src/prime_rl/monitors/wandb/
**/evals
**/run_*/
!configs/**/evals
final_summary.json
# Run artifacts
outputs/
.pydantic_config
.chroma_db
deps/nixl_*
@@ -202,6 +188,4 @@ cython_debug/
debug_I2_zero_band
.idea
outputs/
third_party/
+25 -2
View File
@@ -1,9 +1,11 @@
# SFT warmup for reverse-text on 2 GPUs. Dev-sized mirror of examples/basic/reverse-text/sft.toml.
# SFT warmup for reverse-text on 2 GPUs (1 train + 1 infer for online evals).
# Dev-sized mirror of examples/basic/reverse-text/sft.toml.
max_steps = 100
[deployment]
num_gpus = 2
num_train_gpus = 1
num_infer_gpus = 1
[ckpt] # Checkpoint at the end of training
@@ -17,3 +19,24 @@ batch_size = 32
[optim]
lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.sampling]
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"
[inference]
+1 -1
View File
@@ -3,7 +3,7 @@
max_steps = 20
[deployment]
num_gpus = 2
num_train_gpus = 2
[ckpt] # Checkpoint at the end of training
@@ -19,6 +19,9 @@ lr = 1e-5
batch_size = 128
group_size = 8
[orchestrator.concurrency]
max_inflight = 512
[orchestrator.train.sampling]
max_completion_tokens = 384
@@ -22,6 +22,9 @@ save_adapter_separately = true
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -19,6 +19,9 @@ save_adapter_separately = true
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -22,6 +22,9 @@ impl = "custom"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -24,6 +24,9 @@ name = "ci-rl-opd"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[orchestrator.algo]
type = "opd"
@@ -24,6 +24,9 @@ name = "ci-rl-sft"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[orchestrator.algo]
type = "sft"
@@ -22,6 +22,9 @@ lr = 3e-6
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -19,6 +19,9 @@ lr = 3e-6
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -18,6 +18,9 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
batch_size = 512
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[[orchestrator.train.source]]
name = "alphabet-sort"
@@ -18,6 +18,9 @@ batch_size = 512
group_size = 8
seq_len = 8192
[orchestrator.concurrency]
max_inflight = 512
[[orchestrator.train.source]]
name = "hendrycks-math"
+3
View File
@@ -18,6 +18,9 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[[orchestrator.train.source]]
name = "reverse-text"
+3 -4
View File
@@ -17,11 +17,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
oversampling_factor = 2.0
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[orchestrator.concurrency]
initial_inflight = 512
max_inflight = 512
[[orchestrator.train.source]]
name = "wiki-search"
+3
View File
@@ -18,6 +18,9 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[[orchestrator.train.source]]
name = "wordle"
@@ -17,6 +17,9 @@ language_model_attr = "model.language_model"
batch_size = 256
group_size = 16
[orchestrator.concurrency]
max_inflight = 512
[orchestrator.train.sampling]
max_completion_tokens = 64
-6
View File
@@ -44,12 +44,6 @@ type = "subprocess"
[orchestrator.train.sampling]
max_completion_tokens = 512
# ECHO learns from observation tokens even when the GRPO advantage collapses
# to zero — keep zero-advantage rollouts in the batch.
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
enforce = false
# Fine-tune inherits the PrimeIntellect Qwen3 template byte-for-byte.
[orchestrator.renderer]
name = "prime-qwen3"
+1 -1
+38 -25
View File
@@ -1,6 +1,6 @@
# Algorithms
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, how to plug in your own, the filters applied between rollout and training, and how multi-turn rollouts get merged into training samples.
This page covers the math and the configurable algorithmic components: the algorithm abstraction and its algorithms, how off-policy training works, the loss components and advantage functions, curricula, and how multi-turn rollouts get merged into training samples.
## Table of Contents
@@ -21,7 +21,7 @@ This page covers the math and the configurable algorithmic components: the algor
- [Self-Play Advantage (RAE)](#self-play-advantage-rae)
- [Authoring an Algorithm](#authoring-an-algorithm)
- [Reference Scoring](#reference-scoring)
- [Filters](#filters)
- [Curricula](#curricula)
- [Multi-Turn Trajectories](#multi-turn-trajectories)
- [Extension Property](#extension-property)
- [Best-Effort Interleaving](#best-effort-interleaving)
@@ -164,12 +164,12 @@ At runtime, each env's resolved config builds two objects: a `Sampler` (`prime_r
| `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 |
| `sft` | `SFTDistillAlgorithm` | `score_group`: group-norm credit (feeds filters) |
| `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:
- `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. Model I/O runs *before* the pre-batch filters, so it pays compute on rollouts that may then be filtered out.
- `score_group(group)` — the cohort, **before filtering** (filters read the streams), synchronous: group-relative credit (GRPO/MaxRL baselines). `group` is a list of `Rollout`.
- `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`.
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.
@@ -305,8 +305,8 @@ The per-token training signal is set by `algo.type` and the [algorithm](#the-alg
| `rae` | `rl` | Reward minus a per-agent EMA baseline (SPIRAL's role-conditioned advantage estimation) — for multi-agent self-play envs. |
| `hierarchical_grpo` | `rl` | GRPO for proposer-solver envs: solvers are compared within one proposed problem, while proposers are compared across proposals. |
| `echo` | `rl` + `ce` | Group-norm on action tokens, plus weighted CE on env-provided tokens selected by message role (each role's `alpha` is its ECHO λ), optionally narrowed by a user filter. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` (advantage-based filters never fire) and ship no advantage stream. |
| `opd` | `ref_kl` | On-policy distillation: per-token reverse KL to a reference model (`teacher`, an inline frozen hosted model), evaluated in the trainer from shipped reference logprobs. No credit — rollouts keep `advantages = None` and ship no advantage stream; `group_size` only fans out sampling. |
| `opsd` | `ref_kl` | SDFT: per-token reverse KL to a demo-conditioned reference. No credit — rollouts keep `advantages = None` and ship no advantage stream. |
| `sft` | `ce` | Cross-entropy on the sampled tokens. Assigns no advantage — trains on every sampled token. |
### Default Advantage
@@ -382,7 +382,7 @@ id = "null"
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 and the zero-advantage filter removes it.
`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.
This algorithm is accepted only for proposer-solver envs. Use the env's `train_proposer` and `train_solver` settings if you want to train only one role.
@@ -439,7 +439,7 @@ class MyAlgorithm(Algorithm):
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).
Each per-token list must match the rollout's completion-token count exactly — validated loudly when the view writes it. Advantage-based filters and metrics derive from the streams (the zero-advantage filter checks for all-zero streams; logged distributions use per-rollout means). 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.
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.
### Reference Scoring
@@ -454,31 +454,44 @@ type = "opsd"
demo_key = "demonstration"
```
Scoring runs at arrival, *before* the pre-batch filters, so a rollout that is later filtered still cost its reference compute — accepted for the simpler one-rollout-at-a-time shape (advantage-based filters never fire for opd/opsd anyway, since neither assigns an advantage).
Scoring runs at arrival, before curriculum admission, so a rollout that is later rejected still costs its reference compute.
## Filters
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.
Filters drop rollouts between scoring and training. Built-ins (composable):
## Curricula
| Filter | Effect |
|---|---|
| `gibberish` | Drops rollouts whose mean log-prob fall below a threshold — usually a sign of degenerate output. |
| `repetition` | Drops rollouts with high n-gram repetition. |
| `zero_advantage` | Drops rollouts whose advantage is zero, so the trainer doesn't waste tokens on them. |
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.
The default `[orchestrator]` config registers all three in both filter slots: `post_batch_filters` enforce by default (flagged rollouts are recorded but not shipped to the trainer), while `pre_batch_filters` run in monitor mode (`enforce = false`); flip `enforce = true` there to drop matching rollouts before they consume a slot in the batch. Setting a slot replaces its defaults wholesale:
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>/`.
Three small implementations are included:
- `StandardSampler` is the default: it advances the task iterator and cycles finite tasksets in source order.
- `DifficultyPoolSampler` samples finite tasksets with replacement and tracks each task's latest valid mean group reward. Each named pool has an inclusive reward threshold and a relative per-task sampling weight; weight `0` disables sampling from that pool. Unseen tasks use neutral weight `1.0`, so pool observations affect sampling immediately without waiting for a full taskset pass.
- `AdvRangeGate` rejects a group when every trainable-token advantage falls inside `reject_min` through `reject_max`. Unlike the built-in post-batch zero-advantage filtering, rejection requests replacement work. Groups without an advantage stream are admitted.
```toml
[[orchestrator.post_batch_filters]]
type = "zero_advantage"
[orchestrator.train.source.curriculum.sampler]
type = "difficulty_pool"
[[orchestrator.post_batch_filters]]
type = "repetition"
threshold = 0.4
[orchestrator.train.source.curriculum.sampler.pools.hard]
threshold = 0.25
weight = 0.2
[orchestrator.train.source.curriculum.sampler.pools.normal]
threshold = 0.75
weight = 1.0
[orchestrator.train.source.curriculum.sampler.pools.easy]
threshold = 1.0
weight = 0.2
[orchestrator.train.source.curriculum.gates.low_signal]
type = "advantage_range"
reject_min = -0.05
reject_max = 0.05
```
Filtered rollouts still appear in the W&B metrics, just not in the trainer batch — useful for spotting whether filtering is doing its job.
## Multi-Turn Trajectories
For multi-turn rollouts (tool use, browser environments, long conversations), `prime-rl` records each LLM request/response as an independent **trajectory step** and merges them at training time using best-effort interleaving — with [renderers](#renderers) as the mechanism that keeps the merge safe by construction.
+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 shrinks the cap *and* the pool, cancelling the youngest episodes (least work lost) until the engines are comfortable again.
- **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
+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
+54 -3
View File
@@ -176,6 +176,55 @@ uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
### Online Evals
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `num_examples` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
```toml
[eval]
interval = 25
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"
[inference]
[deployment]
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.
#### 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:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evaluator)
[inference.vllm]
tensor_parallel_size = 8
[slurm]
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.
### SFT-Specific Knobs
| Knob | What it controls |
@@ -185,6 +234,7 @@ Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manag
| `data.seq_len` | Per-sample sequence length |
| `loss_mask.*` | Which roles contribute to loss (system / user / assistant / tool). |
| `val.interval` | Run validation every N steps; `val.data` mirrors `data` |
| `eval.interval` | Run online evals every N steps; see [Online Evals](#online-evals) |
### Important Metrics
@@ -192,8 +242,9 @@ Pulled from the console log and mirrored to W&B.
**Progress and loss:**
- `loss/mean` — main signal. Should decrease through the run.
- `val/loss` — validation loss when `[val]` is set, logged every `val.interval` steps.
- `loss/mean`, `loss/perplexity` — main signal. Should decrease through the run.
- `val/loss`, `val/perplexity` — validation metrics when `[val]` is set, logged every `val.interval` steps.
- `eval/{env}/...` — online eval metrics when `[eval]` is set, logged at each evaluated checkpoint step.
- `progress/epoch`, `progress/num_samples`, `progress/num_tokens` — dataset progress.
- `progress/<subset>/ratio_{samples,tokens}` — when training on multiple HF subsets/splits, the realized mixing ratio.
@@ -317,7 +368,7 @@ uv run rl @ rl.toml --no-monitors.file # disable the local me
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `monitors.wandb.offline = true`.
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, every training run (RL and SFT) gets an **auto-created `overview` saved view** curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
### Platform Monitoring
+4 -1
View File
@@ -71,7 +71,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"
+17 -10
View File
@@ -7,10 +7,14 @@
# 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 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 (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,9 +32,9 @@ 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"
@@ -46,20 +50,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]
@@ -74,7 +80,7 @@ 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"
@@ -137,6 +142,7 @@ rollout = 3600
[inference]
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
@@ -145,4 +151,5 @@ FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.vllm]
max_model_len = 131072
tensor_parallel_size = 8
quantization = "fp8"
enable_return_routed_experts = true
+4 -1
View File
@@ -72,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"
+4 -1
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"
+4 -6
View File
@@ -65,9 +65,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"
@@ -86,11 +89,6 @@ id = "bash"
[orchestrator.eval.source.env.agent.runtime]
labels = ["glm5-pd-disag", "swe-bench-verified"]
[[orchestrator.post_batch_filters]]
type = "gibberish"
enforce = true
[inference]
# we need <0.85 bc glm5 layers are too large for 0.85
use_deep_gemm = true
+9 -5
View File
@@ -45,11 +45,15 @@ 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"
@@ -63,6 +67,7 @@ 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"
@@ -78,6 +83,7 @@ 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"
@@ -91,6 +97,7 @@ 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"
@@ -107,6 +114,7 @@ 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"
@@ -117,10 +125,6 @@ id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[orchestrator.eval]
interval = 25
+4 -1
View File
@@ -45,9 +45,12 @@ 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"
+4 -1
View File
@@ -66,7 +66,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"
+3 -1
View File
@@ -42,9 +42,11 @@ 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
+3 -1
View File
@@ -43,9 +43,11 @@ 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"
+27 -2
View File
@@ -8,7 +8,32 @@ name = "PrimeIntellect/Qwen3-0.6B"
[data]
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
seq_len = 4096
batch_size = 32
batch_size = 32
[optim]
lr = 2e-5
lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.sampling]
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"
[inference]
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
+4 -5
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"
@@ -42,6 +44,7 @@ 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"
@@ -52,10 +55,6 @@ id = "null"
[orchestrator.train.source.env.agent.runtime]
type = "subprocess"
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
enforce = true
[ckpt] # Checkpoint at the end of training
[inference.vllm]
+2 -2
View File
@@ -8,7 +8,7 @@ optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
attn = "flash_attention_2"
ep = 8 # keep in sync with deployment.num_gpus
ep = 8 # keep in sync with deployment.num_train_gpus
[renderer]
name = "auto"
@@ -52,4 +52,4 @@ save_adapter_separately = true
[deployment]
type = "single_node"
num_gpus = 8
num_train_gpus = 8
+1 -1
View File
@@ -6,7 +6,7 @@ readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.2",
"prime-pydantic-config>=0.4.3",
"renderers>=0.1.9",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
@@ -234,8 +234,7 @@ class MaxRLAlgoConfig(BaseAlgoConfig):
objective: low-pass-rate examples get ~1/p weight, and ``group_size`` is
the truncation order interpolating REINFORCE (1) → exact maximum
likelihood (∞). Designed for non-negative (canonically binary) rewards;
a group with mean reward 0 carries zero advantages everywhere (the
zero-advantage filter drops it, matching the paper's K=0 convention)."""
a group with mean reward 0 carries zero advantages everywhere."""
action_loss_type: ClassVar[ActionLossType] = "rl"
@@ -300,8 +299,8 @@ class OPDAlgoConfig(BaseAlgoConfig):
a reference model, evaluated in the trainer from reference prefill
logprobs scored over each sample's own context (``ref_logprobs`` on the
wire, ``ref_kl`` loss component). No scalar advantage is assigned —
rollouts keep ``advantages=None`` (advantage-based filters never fire) and
samples ship no advantage stream. ``group_size`` only fans out sampling."""
rollouts keep ``advantages=None`` and samples ship no advantage stream.
``group_size`` only fans out sampling."""
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
@@ -322,8 +321,7 @@ class OPSDAlgoConfig(BaseAlgoConfig):
prepended as a leading system message. The sample is scored verbatim (no
re-rendering), so it's robust to tool/multimodal prompts and works for any
number of turns. No scalar advantage is assigned — rollouts keep
``advantages=None`` (advantage-based filters never fire) and samples ship no
advantage stream."""
``advantages=None`` and samples ship no advantage stream."""
action_loss_type: ClassVar[ActionLossType] = "ref_kl"
@@ -347,8 +345,8 @@ class SFTAlgoConfig(BaseAlgoConfig):
type: Literal["sft"] = "sft"
"""SFT distillation: cross-entropy on the sampled tokens. The ``ce`` loss
ignores advantages and SFT assigns none — it trains on every sampled token.
Reward-based filtering, if wanted, is an explicit filter, not smuggled
through an unused advantage stream."""
A curriculum can reject results using reward or any other finalized
rollout data."""
action_loss_type: ClassVar[ActionLossType] = "ce"
@@ -0,0 +1,84 @@
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
@@ -157,6 +157,77 @@ class EnvConfig(BaseConfig):
return self
class StandardSamplerConfig(BaseConfig):
type: Literal["standard"] = "standard"
class DifficultyPoolConfig(BaseConfig):
threshold: float
"""Inclusive maximum reward assigned to this pool."""
weight: float = Field(ge=0)
"""Relative per-task sampling weight."""
def default_difficulty_pools() -> dict[str, DifficultyPoolConfig]:
return {
"hard": DifficultyPoolConfig(threshold=0.25, weight=0.2),
"normal": DifficultyPoolConfig(threshold=0.75, weight=1.0),
"easy": DifficultyPoolConfig(threshold=1.0, weight=0.2),
}
class DifficultyPoolSamplerConfig(BaseConfig):
type: Literal["difficulty_pool"] = "difficulty_pool"
pools: dict[str, DifficultyPoolConfig] = Field(default_factory=default_difficulty_pools)
"""Named pools ordered by their reward thresholds."""
seed: int = 42
@model_validator(mode="after")
def validate_pools(self):
if not self.pools:
raise ValueError("DifficultyPoolSampler requires at least one pool")
thresholds = [pool.threshold for pool in self.pools.values()]
if len(set(thresholds)) != len(thresholds):
raise ValueError("Difficulty pool thresholds must be unique")
if not any(pool.weight > 0 for pool in self.pools.values()):
raise ValueError("At least one difficulty pool must have a positive weight")
return self
TaskSamplerConfig: TypeAlias = Annotated[
StandardSamplerConfig | DifficultyPoolSamplerConfig,
Field(discriminator="type"),
]
class AdvRangeGateConfig(BaseConfig):
type: Literal["advantage_range"] = "advantage_range"
reject_min: float = 0.0
reject_max: float = 0.0
@model_validator(mode="after")
def validate_range(self):
if self.reject_min > self.reject_max:
raise ValueError("reject_min must be less than or equal to reject_max")
return self
AdmissionGateConfig: TypeAlias = AdvRangeGateConfig
class CurriculumConfig(BaseConfig):
sampler: TaskSamplerConfig = Field(default_factory=StandardSamplerConfig)
"""Task selection policy. The default cycles through the task iterator in source order."""
gates: dict[str, AdmissionGateConfig] = Field(default_factory=dict)
"""Named admission policies. Every gate observes every finalized group,
and a group trains only when every gate admits it."""
class TrainSourceConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
@@ -170,6 +241,10 @@ class TrainSourceConfig(EnvConfig):
``orchestrator.algo`` when unset; set ``type`` (and its params) to give
this env its own algorithm."""
curriculum: CurriculumConfig | None = None
"""User-authored task sampler and admission gates. The default cycles
through the taskset and admits every finalized group."""
class EvalSourceConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
@@ -192,6 +267,9 @@ class TrainConfig(BaseConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
filter_zero_advantages: bool = True
"""Remove zero-advantage RL tokens after collecting a batch, before shipping it."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling (the worker ``pool``
@@ -298,50 +376,6 @@ class CheckpointConfig(BaseConfig):
"""Skip loading the progress from checkpoint."""
# Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387).
class GibberishFilterConfig(BaseConfig):
type: Literal["gibberish"] = "gibberish"
enforce: bool = False
"""When True, skip detected rollouts entirely so they are not sent to the trainer. When False, only track detection metrics."""
token_id_threshold: int = 100_000
"""Token IDs above this are candidates for gibberish. BPE tokens are sorted by merge order."""
logprob_offset: float = 2.0
"""Offset from uniform-distribution logprob. Threshold = ``-log(vocab_size) - logprob_offset``."""
# Flags rollouts stuck in a repetition loop: emits high-confidence tokens for an extended stretch.
# Flagged when `window` consecutive tokens are each sampled with probability above `prob_threshold`.
# (Section 3.2, https://arxiv.org/abs/2506.13585)
class RepetitionFilterConfig(BaseConfig):
type: Literal["repetition"] = "repetition"
enforce: bool = False
"""When True, skip detected rollouts entirely so they are not sent to the trainer. When False, only track detection metrics."""
window: int = Field(3_000, ge=1)
"""Consecutive high-probability steps required to flag the rollout."""
prob_threshold: float = Field(0.99, gt=0, le=1)
"""Tokens sampled with probability above this are considered repetitive. Consecutive such tokens count toward the window."""
# Flags rollouts with zero advantage.
class ZeroAdvantageFilterConfig(BaseConfig):
type: Literal["zero_advantage"] = "zero_advantage"
enforce: bool = True
"""When True, skip detected rollouts entirely so they are not sent to the trainer. When False, only track detection metrics."""
FilterConfig: TypeAlias = Annotated[
GibberishFilterConfig | RepetitionFilterConfig | ZeroAdvantageFilterConfig,
Field(discriminator="type"),
]
class FileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
@@ -386,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
@@ -412,24 +470,6 @@ class OrchestratorConfig(BaseConfig):
eval: EvalConfig | None = None
"""Evaluation configuration."""
pre_batch_filters: list[FilterConfig] = [
GibberishFilterConfig(enforce=False),
RepetitionFilterConfig(enforce=False),
ZeroAdvantageFilterConfig(enforce=False),
]
"""Filters applied *before* a rollout enters the training batch buffer.
All three filter types are registered in monitor mode by default; flip ``enforce=true`` per type
to drop matching rollouts before they consume a slot in the batch (e.g. a zero-advantage group
never makes it into a training batch)."""
post_batch_filters: list[FilterConfig] = [
GibberishFilterConfig(),
RepetitionFilterConfig(),
ZeroAdvantageFilterConfig(),
]
"""Filters applied *after* a batch has been assembled. Each filter annotates each rollout;
rollouts flagged by an enforcing filter are still recorded but not shipped to the trainer."""
log: LogConfig = LogConfig()
env_vars: EnvVars = {}
@@ -439,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."""
@@ -471,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."""
@@ -522,16 +559,6 @@ class OrchestratorConfig(BaseConfig):
self.monitors.prime.name = self.monitors.wandb.name
return self
@model_validator(mode="after")
def validate_unique_filter_types(self):
for slot_name in ("pre_batch_filters", "post_batch_filters"):
types = [f.type for f in getattr(self, slot_name)]
if len(types) != len(set(types)):
raise ValueError(
f"Duplicate filter types in {slot_name}: {types}. Each filter type may only appear once per slot."
)
return self
@model_validator(mode="after")
def inherit_env_algorithms(self):
"""Envs without their own algorithm inherit the top-level one.
@@ -599,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:
@@ -2,11 +2,14 @@ import uuid
import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from urllib.parse import urlparse
from pydantic import Field, model_validator
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.inference import InferenceConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
EnvVars,
@@ -142,24 +145,33 @@ class BaseDeploymentConfig(BaseConfig):
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
type: Literal["single_node"] = "single_node"
num_gpus: int = 1
"""GPUs to use."""
num_train_gpus: int = 1
"""GPUs allocated to the trainer."""
num_infer_gpus: int = Field(1, validation_alias=AliasChoices("num_infer_gpus", "num_eval_gpus"))
"""GPUs allocated to inference for online evals (alias: ``num_eval_gpus``). Only used when an ``[inference]`` block is configured."""
@model_validator(mode="after")
def validate_gpu_count(self):
if self.num_gpus > self.gpus_per_node:
raise ValueError(f"num_gpus ({self.num_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
if self.num_train_gpus > self.gpus_per_node:
raise ValueError(f"num_train_gpus ({self.num_train_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
return self
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
type: Literal["multi_node"] = "multi_node"
num_nodes: int = 2
num_train_nodes: int = Field(2, ge=1)
"""Training nodes."""
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
from the trainer job: the 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."""
nodes_per_fsdp_group: int | None = None
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_nodes / nodes_per_fsdp_group``."""
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
SFTDeploymentConfig: TypeAlias = Annotated[
@@ -183,6 +195,15 @@ class SFTConfig(BaseConfig):
val: SFTValConfig | None = None
"""Validation configuration. If None, no validation runs."""
eval: OnlineEvalConfig | 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."""
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``."""
optim: OptimizerConfig = AdamWConfig()
scheduler: SchedulerConfig = ConstantSchedulerConfig()
@@ -264,10 +285,26 @@ class SFTConfig(BaseConfig):
return data
deployment = data.get("deployment")
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
for key in ("num_gpus",):
for key in ("num_train_gpus", "num_infer_gpus"):
deployment.pop(key, None)
return data
@model_validator(mode="before")
@classmethod
def propagate_model_to_inference(cls, data):
"""Fill ``inference.vllm.model`` from ``model.name`` before InferenceConfig
construction, so its parser auto-resolution sees the right model name."""
if not isinstance(data, dict):
return data
inference = data.get("inference")
model = data.get("model")
name = model.get("name") if isinstance(model, dict) else None
if isinstance(inference, dict) and name:
vllm = inference.setdefault("vllm", {})
if isinstance(vllm, dict):
vllm.setdefault("model", name)
return data
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
@@ -282,9 +319,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")
@@ -304,6 +341,129 @@ class SFTConfig(BaseConfig):
raise ValueError("Must use SLURM for multi-node deployment.")
return self
@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."""
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."
)
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.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.
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."
)
if self.deployment.num_infer_nodes < 1:
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
if self.inference.router is None:
raise ValueError(
"Multi-node online evals require an inference router - the eval job starts one "
"router in front of the per-rank engines. Remove inference.router = 'None'."
)
if self.inference.vllm.model != self.model.name:
raise ValueError(
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
f"({self.model.name}). Remove inference.vllm.model to inherit it."
)
if self.deployment.gpus_per_node % self.inference.vllm.tensor_parallel_size != 0:
raise ValueError(
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.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evaluator never sees a final checkpoint, "
"so the eval SLURM job holds its allocation until its walltime.",
stacklevel=2,
)
# The client is wired at runtime by the eval sbatch script (the router and
# per-rank admin URLs are only known once SLURM assigns hosts).
return self
if self.inference is None:
warnings.warn(
"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 "
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
"(pause/update_weights/resume) must bypass the router.",
stacklevel=2,
)
return self
total_gpus = self.deployment.num_train_gpus + self.deployment.num_infer_gpus
if total_gpus > self.deployment.gpus_per_node:
raise ValueError(
f"Total GPU count ({total_gpus} = {self.deployment.num_train_gpus} train + "
f"{self.deployment.num_infer_gpus} infer) exceeds gpus_per_node "
f"({self.deployment.gpus_per_node})."
)
if self.inference.vllm.model != self.model.name:
raise ValueError(
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
f"({self.model.name}). Remove inference.vllm.model to inherit it."
)
# Fill inference capacity with DP ranks (mirrors RLConfig.auto_setup_deployment).
num_infer_gpus = self.deployment.num_infer_gpus
vllm = self.inference.vllm
if num_infer_gpus != vllm.data_parallel_size * vllm.tensor_parallel_size:
if num_infer_gpus % vllm.tensor_parallel_size != 0:
raise ValueError(
f"deployment.num_infer_gpus ({num_infer_gpus}) must be divisible by "
f"inference.vllm.tensor_parallel_size ({vllm.tensor_parallel_size})."
)
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'."
)
host = self.inference.server.host or "localhost"
client = self.eval.client
if "base_url" not in client.model_fields_set:
client.base_url = f"http://{host}:{self.inference.server.port}/v1"
elif urlparse(client.base_url).port != self.inference.server.port:
raise ValueError(
f"eval.client.base_url port ({urlparse(client.base_url).port}) does not match "
f"inference.server.port ({self.inference.server.port})."
)
if self.inference.router is not None and "admin_base_url" not in client.model_fields_set:
# Admin ops (pause/update_weights/resume) must bypass the router and hit
# the engine directly.
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
return self
@model_validator(mode="after")
def validate_typed_renderer(self):
"""Require a typed renderer whenever SFT renders real samples."""
@@ -416,12 +576,12 @@ class SFTConfig(BaseConfig):
def auto_setup_deployment(self):
if self.deployment.type == "multi_node":
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_nodes % self.deployment.nodes_per_fsdp_group != 0:
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
raise ValueError(
f"deployment.num_nodes ({self.deployment.num_nodes}) must be divisible by "
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
)
self.model.dp_replicate = self.deployment.num_nodes // self.deployment.nodes_per_fsdp_group
self.model.dp_replicate = self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
return self
@model_validator(mode="after")
@@ -11,7 +11,16 @@ from prime_rl.utils.config import BaseConfig
# and the single shared W&B run. The launcher always sets these last, so allowing them in
# `env_vars` would be a silent no-op (or, on multi-node, a footgun) — reject them instead.
PROTECTED_ENV_VARS = frozenset(
{"CUDA_VISIBLE_DEVICES", "PRL_RUN_ID", "PRL_RUN_NAME", "WANDB_RUN_ID", "WANDB_SHARED_MODE", "WANDB_SHARED_LABEL"}
{
"CUDA_VISIBLE_DEVICES",
"PRL_RUN_ID",
"PRL_RUN_NAME",
"WANDB_RUN_ID",
"WANDB_SHARED_MODE",
"WANDB_SHARED_LABEL",
"WANDB_SHARED_PRIMARY",
"WANDB_SHARED_FINISHER",
}
)
@@ -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."""
@@ -255,7 +256,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")
@@ -673,9 +674,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")
+6 -2
View File
@@ -6,7 +6,7 @@ readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"prime-rl-configs",
"prime-pydantic-config",
"prime-pydantic-config>=0.4.3",
"beartype>=0.21.0",
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
@@ -33,7 +33,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.3.1.dev14",
"verifiers[harbor]>=0.3.1.dev33",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -53,6 +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"
env-server = "prime_rl.entrypoints.env_server:main"
[project.entry-points."vllm.general_plugins"]
@@ -169,6 +170,9 @@ requires-dist = [
]
[tool.uv.exclude-newer-package]
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
-36
View File
@@ -1,36 +0,0 @@
#!/usr/bin/env bash
set -e
# Colors for output
GREEN='\033[0;32m'
NC='\033[0m' # No Color
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
# Confirm destructive action
confirm_cleanup() {
echo "This will remove the following paths recursively:"
echo " - **/logs"
echo " - **/checkpoints"
echo " - **/weights"
echo " - **/rollouts"
echo " - **/wandb"
echo " - **/evals"
echo " - .pydantic_config"
while true; do
read -r -p "Proceed? [y/N]: " response
case "$response" in
[yY]|[yY][eE][sS]) break ;;
[nN]|[nN][oO]|"") echo "Aborted."; exit 1 ;;
*) echo "Please answer y or n." ;;
esac
done
}
# Remove logs, checkpoints, weights, rollouts, wandb
confirm_cleanup
rm -rf **/logs **/checkpoints **/weights **/rollouts **/wandb **/evals **/torchrun *.pydantic_config
log_info "Cleaned up!"
+2
View File
@@ -71,6 +71,8 @@ type = "subprocess"
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server), e.g. `--eval.source.0.env.taskset.id reverse-text`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**vLLM pass-through** — `[inference.vllm]` uses vLLM's own argument names (`model`, `tensor_parallel_size`, `data_parallel_size`, `max_model_len`, ...) and forwards *any* key to the vLLM server, typed by prime-rl or not: `[inference.vllm] max_num_seqs = 256`, or `--inference.vllm.max-num-seqs 256` on the CLI. CLI values are JSON-coerced, so dict-valued vLLM args work as `--inference.vllm.compilation-config '{"cudagraph_mode": "NONE"}'`. Non-vLLM knobs (router, deployment, weight broadcast, kv-cache offload, env vars) stay on `[inference]` itself.
+8 -6
View File
@@ -66,6 +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)
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -81,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,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evaluator,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
```
@@ -92,9 +93,9 @@ All metrics print to the console log (and W&B when configured).
**Progress** — orchestrator log. Rollout metrics mirror the episode/trace hierarchy, at two levels:
- `{scope}/{subset}/<metric>/<stat>` — episode-level facts only: the token/turn/branch counts, summed over an episode's traces.
- `{scope}/{subset}/<agent>/<metric>/<stat>` — every trace-level metric (reward, truncation, errors, timing, env metrics, filter verdicts, eval scores), keyed by agent name so seats never mix. Flat over that agent's traces: one sample is one trace, so an in-episode fan-out like n solvers contributes n samples.
- `{scope}/{subset}/<agent>/<metric>/<stat>` — every trace-level metric (reward, truncation, errors, timing, env metrics, curriculum admission, eval scores), keyed by agent name so seats never mix. Flat over that agent's traces: one sample is one trace, so an in-episode fan-out like n solvers contributes n samples.
`scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (post-filter). Single-agent envs have one agent — usually `agent` — and one trace per episode, so both levels agree; multi-agent envs name each seat (`proposer`, `solver`, `judge`, …).
`scope` is `train/agg` (all train envs) or `train/<env>` (`eval/<env>` for eval); `subset` is `all` (every rollout) or `effective` (admitted, clean, and trainable). Single-agent envs have one agent — usually `agent` — and one trace per episode, so both levels agree; multi-agent envs name each seat (`proposer`, `solver`, `judge`, …).
| Metric | Description |
|--------|-------------|
@@ -104,7 +105,8 @@ All metrics print to the console log (and W&B when configured).
| `train/<env>/effective/<agent>/num_turns/mean` | avg turns for that agent alone (also token counts, `num_branches`) |
| `train/agg/effective/<agent>/is_truncated/mean` | fraction of that agent's rollouts truncated |
| `train/agg/all/<agent>/has_error/mean` | fraction of that agent's rollouts errored (per-type under `train/agg/all/<agent>/error/<type>`; also `dispatcher/errored/{train,eval}`) |
| `train/agg/all/<agent>/is_trainable/mean` | fraction carrying a training signal — 0.0 for a frozen seat like a judge (also `is_filtered`, `filters/<name>`) |
| `train/agg/all/<agent>/is_trainable/mean` | fraction carrying a training signal — 0.0 for a frozen seat like a judge |
| `train/agg/all/<agent>/is_admitted/mean` | fraction accepted by the source curriculum; per-source counters and custom policy metrics live under `curriculum/<env>/` |
| `train/<env>/effective/<agent>/metrics/<name>/mean` | env-specific metrics for that agent (e.g. pass rate) |
| `train/<env>/effective/<agent>/timing/agent/model/mean` | model vs harness share of that agent's phase |
| `eval/<env>/effective/<agent>/{avg@k,pass@k}` | eval scores for that agent, when configured |
@@ -128,7 +130,7 @@ 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_level/{mean,max}`, `dispatcher/inflight/{train,eval}`, `dispatcher/queued/eval` | dispatcher / async state |
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
For live vLLM stats, query Prometheus directly:
@@ -147,7 +149,7 @@ curl -s http://localhost:8100/metrics | grep -E "num_requests|gpu_cache_usage"
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, filtered, and never-batched
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),
+2 -1
View File
@@ -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
+24
View File
@@ -0,0 +1,24 @@
"""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()
+1 -11
View File
@@ -10,8 +10,6 @@ from subprocess import Popen
from threading import Event, Thread
from urllib.parse import urlparse
import pynvml
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.orchestrator import EnvConfig
@@ -35,6 +33,7 @@ from prime_rl.utils.process import (
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
set_proc_title,
)
@@ -68,15 +67,6 @@ def env_server_names(config: RLConfig, split: str) -> list[str]:
return [source.resolved_name for source_split, source, _ in env_servers(config) if source_split == split]
def get_physical_gpu_ids() -> list[int]:
"""Return physical GPU IDs visible to the launcher."""
raw_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
if raw_visible is None:
pynvml.nvmlInit()
return list(range(pynvml.nvmlDeviceGetCount()))
return [int(token.strip()) for token in raw_visible.split(",") if token.strip()]
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
output_dir.mkdir(parents=True, exist_ok=True)
+406 -51
View File
@@ -1,5 +1,7 @@
import json
import os
import shutil
import signal
import subprocess
import sys
import uuid
@@ -7,27 +9,90 @@ from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
create_attempt_log_dir,
format_log_message,
get_all_ckpt_steps,
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,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
set_proc_title,
)
SFT_CONFIG = "sft.json"
SFT_SBATCH = "sft.sbatch"
EVAL_SBATCH = "eval.sbatch"
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
INFERENCE_CONFIG = "inference.json"
EVALUATOR_CONFIG = "evaluator.json"
ENVS_DIR = "envs"
def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
"""``(source, address)`` for every launcher-managed eval source. A source with
``serve.address`` set is externally managed — the launcher neither writes its
config nor spawns a server for it."""
if config.eval is None:
return []
addresses = config.eval.env_addresses
return [
(source, addresses[("eval", source.resolved_name)])
for source in config.eval.source
if source.serve.address is None
]
def get_ckpt_base(config: SFTConfig) -> Path:
"""Where checkpoints and weights live: ``ckpt.output_dir`` when set, else the run dir."""
return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir
def resolve_resume_step(config: SFTConfig) -> int | None:
if config.resume is None:
return None
if config.resume.dir is not None:
return config.resume.dir_step
if config.resume.step is not None:
return config.resume.step
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."""
assert config.eval is not None
return EvaluatorConfig(
model=config.model.name,
eval=config.eval,
weights_dir=get_weights_dir(get_ckpt_base(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,
)
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
@@ -37,7 +102,39 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> 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."""
config_dir.mkdir(parents=True, exist_ok=True)
if config.inference is not None:
# Exclude launcher-only fields that are not needed by the vLLM server
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
inference_dict = dump_resolved_config(config.inference, exclude=exclude_inference)
if strip_router:
# Per-rank processes run bare engines; the sbatch starts the single global router.
inference_dict["router"] = None
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)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
# binds at the source's deterministic address, where the evaluator connects.
for source, address in eval_env_servers(config):
env_dir = config_dir / ENVS_DIR / "eval"
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = dump_resolved_config(source)
env_server_dict = {
"env": source_dict["env"],
"serve": {**(source_dict.get("serve") or {}), "address": address},
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
json.dump(env_server_dict, f, indent=2)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path, prl_run_id: str | None = None) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -66,21 +163,79 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
config_path=config_path,
output_dir=config.run_dir,
trainer_env_vars=trainer_env_vars,
num_nodes=config.deployment.num_nodes,
num_nodes=config.deployment.num_train_nodes,
gpus_per_node=config.deployment.gpus_per_node,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
run_name=config.run.name,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
"""Write the SLURM script for the decoupled online-eval job (inference pool +
env servers + evaluator) to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
assert config.deployment.type == "multi_node"
assert config.inference is not None
# The eval template is bundled next to the trainer templates; a custom
# slurm.template_path directory takes precedence so both can be overridden.
template_dirs = [config.slurm.template_path.parent]
bundled_templates = find_package_resource("templates")
if bundled_templates is not None:
template_dirs.append(bundled_templates)
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
template = env.get_template(EVAL_TEMPLATE)
inference_env_vars = {
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
}
evaluator_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
script = template.render(
**config.slurm.template_vars,
config_dir=config_dir,
output_dir=config.run_dir,
num_infer_nodes=config.deployment.num_infer_nodes,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.router,
router_port=config.inference.server.port,
backend_port=config.inference.backend_port,
data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
inference_env_vars=inference_env_vars,
evaluator_env_vars=evaluator_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,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def sft_slurm(config: SFTConfig):
"""Run SFT training via SLURM."""
"""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."""
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
decoupled_eval = config.deployment.type == "multi_node" and config.eval is not None
config_dir = get_config_dir(config.run_dir)
config_path = config_dir / SFT_CONFIG
exclude = (
@@ -88,28 +243,84 @@ def sft_slurm(config: SFTConfig):
if config.deployment.type == "multi_node"
else {"slurm", "dry_run", "clean"}
)
if decoupled_eval:
# The trainer job only needs [eval] for the weight-checkpoint 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,
# keyed by the launcher's run id.
prl_run_id: str | None = None
if decoupled_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
script_path = config.run_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path)
write_slurm_script(config, config_path, script_path, prl_run_id)
logger.info(f"Wrote SLURM script to {script_path}")
log_dir = latest_log_dir(config.run_dir)
num_nodes = config.deployment.num_nodes if config.deployment.type == "multi_node" else 1
log_message = format_log_message(log_dir=log_dir, trainer=True, num_train_nodes=num_nodes)
# 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
# would crash it at wandb init.
script_paths = [script_path]
if decoupled_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Wrote eval subconfigs to {config_dir}")
eval_script_path = config.run_dir / EVAL_SBATCH
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
script_paths = [script_path, eval_script_path]
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
log_message = format_log_message(
log_dir=latest_log_dir(config.run_dir),
trainer=True,
num_train_nodes=num_nodes,
)
if decoupled_eval:
# The eval job logs at stable (non-attempt) paths under the run dir.
log_message += "\n" + format_log_message(
log_dir=get_log_dir(config.run_dir),
evaluator=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:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
submit = "\n".join(f" sbatch {path}" for path in script_paths)
note = (
"\n\nSubmit the trainer job first — the evaluator joins the W&B run the trainer creates."
if decoupled_eval
else ""
)
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
submitted_job_ids: list[str] = []
for path in script_paths:
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
# (e.g. multi-cluster sbatch appends "on cluster <name>").
cmd = ["sbatch", "--parsable"]
if submitted_job_ids:
# Hold the eval job until the trainer job has started (not finished).
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
cmd.append(str(path))
logger.info(f"Submitting: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
for job_id in submitted_job_ids:
logger.warning(f"Cancelling already-submitted job {job_id}")
subprocess.run(["scancel", job_id], capture_output=True, text=True)
sys.exit(1)
job_id = result.stdout.strip().split(";")[0]
submitted_job_ids.append(job_id)
logger.success(f"Submitted batch job {job_id}")
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
logger.success(log_message)
def sft_local(config: SFTConfig):
@@ -123,60 +334,151 @@ def sft_local(config: SFTConfig):
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
if config.eval is not None:
write_eval_subconfigs(config, config_dir)
logger.info(f"Wrote eval subconfigs to {config_dir}")
if config.dry_run:
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
log_dir = create_attempt_log_dir(config.run_dir)
from prime_rl.utils.utils import get_free_port
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
infer_gpu_ids: list[int] = []
trainer_gpu_ids: list[int] = []
if config.inference is not None:
num_infer_gpus = config.deployment.num_infer_gpus
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
(config_dir / SFT_CONFIG).as_posix(),
]
logger.info(f"Starting SFT trainer with {config.deployment.num_gpus} GPU(s)")
logger.debug(f"Trainer command: {' '.join(trainer_cmd)}")
# Trainer and evaluator 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
# 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_PROGRAM": "uv run sft",
"WANDB_ARGS": json.dumps(sys.argv),
}
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
def start_process(name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> Popen:
logger.debug(f"{name.capitalize()} command: {' '.join(cmd)}")
log_path.parent.mkdir(parents=True, exist_ok=True)
with open(log_path, "w") as log_file:
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
processes.append(process)
stop_event = Event()
stop_events[name] = stop_event
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, error_queue, name), daemon=True)
monitor_thread.start()
monitor_threads.append(monitor_thread)
return process
try:
with open(log_dir / "trainer.log", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
# Optionally, start the inference server for online evals
if config.inference is not None:
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
start_process(
"inference",
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
log_path=log_dir / "inference.log",
)
processes.append(trainer_process)
stop_event = Event()
monitor_thread = Thread(
target=monitor_process,
args=(trainer_process, stop_event, error_queue, "trainer"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start one env server per eval source. The evaluator 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
logger.info(f"Starting eval env server {name} at {address}")
start_process(
f"env/eval/{name}",
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
log_path=log_dir / ENVS_DIR / "eval" / f"{name}.log",
)
if config.eval is not None:
logger.info("Starting evaluator process")
start_process(
"evaluator",
["evaluator", "@", (config_dir / EVALUATOR_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evaluator",
},
log_path=log_dir / "evaluator.log",
)
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_train_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
config_path.as_posix(),
]
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
trainer_env = {
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
**config.env_vars,
**wandb_shared_env,
}
if config.eval is not None:
trainer_env["LOGURU_FORCE_COLORS"] = "1"
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
if trainer_gpu_ids:
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(
@@ -185,7 +487,22 @@ def sft_local(config: SFTConfig):
)
processes.append(tail_process)
stop_event.wait()
# Wait for the trainer (and the evaluator, 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"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
logger.error(f"Error: {error_queue[0]}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if not pending:
break
pending[0].wait(timeout=1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
@@ -209,11 +526,49 @@ def sft_local(config: SFTConfig):
raise
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
"""Remove eval artifacts a previous run left behind: weight checkpoints 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
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")
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):
# 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.
os.environ.setdefault("PRL_RUN_ID", uuid.uuid4().hex)
assert config.run.name is not None # resolved at construction
os.environ["PRL_RUN_NAME"] = config.run.name
resuming = config.resume is not None
clean = config.clean and not os.environ.get("NEVER_CLEAN")
validate_run_dir(config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean)
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
validate_run_dir(
config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir
)
config.run_dir.mkdir(parents=True, exist_ok=True)
if ckpt_output_dir is not None:
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
if config.eval is not None and not config.dry_run:
clean_stale_eval_artifacts(config)
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
+6 -6
View File
@@ -19,12 +19,12 @@ from vllm.config import set_current_vllm_config
from vllm.logger import init_logger
from prime_rl.inference.vllm.worker.weight_transfer import update_mla_absorbed_weights
from prime_rl.trainer.rl.broadcast.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.trainer.rl.broadcast.nixl.cuda_malloc_memory import (
from prime_rl.transports.weights.nixl.agent import MemDesc, NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.transports.weights.nixl.cuda_malloc_memory import (
size_cuda_buffers,
use_cuda_malloc_pool,
)
from prime_rl.trainer.rl.broadcast.nixl.graph import (
from prime_rl.transports.weights.nixl.graph import (
Destination,
OperationChain,
RecordedCopy,
@@ -34,9 +34,9 @@ from prime_rl.trainer.rl.broadcast.nixl.graph import (
make_hf_lazy_weights,
plan_tensor_replay,
)
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.trainer.rl.broadcast.nixl.tensor_routing import route_sharded_tensor
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import TrainerTensorTable
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.transports.weights.nixl.tensor_routing import route_sharded_tensor
from prime_rl.transports.weights.nixl.trainer_tensor_table import TrainerTensorTable
if TYPE_CHECKING:
from vllm.v1.worker.gpu_worker import Worker
+3 -1
View File
@@ -10,7 +10,7 @@ from __future__ import annotations
import os
from pathlib import Path
from typing import TYPE_CHECKING, Any, overload
from typing import TYPE_CHECKING, Any, Literal, overload
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig, WandbMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
@@ -47,6 +47,7 @@ async def setup(
run_config: BaseConfig | None = None,
train_env_names: list[str] | None = None,
eval_env_names: list[str] | None = None,
overview_flavor: Literal["rl", "sft"] = "rl",
) -> None:
"""Construct, initialize, and register one monitor per non-None config.
@@ -71,6 +72,7 @@ async def setup(
config=run_config,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
overview_flavor=overview_flavor,
),
)
)
+4 -2
View File
@@ -22,6 +22,7 @@ from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import sanitize
BASE_URL = "https://api.primeintellect.ai/api/v1/rft"
BASE_URL_VAR = "PRIME_API_BASE"
API_KEY_VAR = "PRIME_API_KEY"
SAMPLE_SCHEMA = pa.schema(
@@ -129,13 +130,14 @@ class TrainRun:
self.id: str | None = None
self.logger = get_logger()
self._tasks: set[asyncio.Task] = set()
self.base_url = (os.getenv(BASE_URL_VAR) or BASE_URL).rstrip("/")
self.headers = {
"Authorization": f"Bearer {api_key}",
"x-api-key": api_key,
"Content-Type": "application/json",
}
self.client = httpx.AsyncClient(
base_url=BASE_URL,
base_url=self.base_url,
headers=self.headers,
timeout=30,
transport=httpx.AsyncHTTPTransport(retries=3),
@@ -246,7 +248,7 @@ class TrainRun:
self.logger.info(f"Marking platform run {self.id} as failed")
try:
httpx.put(
f"{BASE_URL}/external-runs/{self.id}/status",
f"{self.base_url}/external-runs/{self.id}/status",
headers=self.headers,
json={"status": "failed"},
timeout=30,
+11 -4
View File
@@ -6,7 +6,7 @@ import os
import sys
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Literal
import wandb
from wandb.errors import CommError
@@ -32,6 +32,7 @@ class WandbMonitor(Monitor):
config: BaseConfig | None = None,
train_env_names: list[str] | None = None,
eval_env_names: list[str] | None = None,
overview_flavor: Literal["rl", "sft"] = "rl",
) -> None:
# W&B reads the start command off sys.argv; the launcher passes the original
# command to subprocesses via $WANDB_ARGS.
@@ -50,14 +51,19 @@ class WandbMonitor(Monitor):
# W&B's native run-id var, set by the launcher to $PRL_RUN_ID.
run_id = os.environ.get("WANDB_RUN_ID")
label = os.environ.get("WANDB_SHARED_LABEL")
primary = label == "orchestrator"
primary_label = os.environ.get("WANDB_SHARED_PRIMARY", "orchestrator")
primary = label == primary_label
# The primary creates the run; the finisher writes its final state. They can
# differ when the run's creator is not its last-alive writer (e.g. the SFT
# trainer creates the run, the evaluator outlives it and finalizes).
finisher = label == os.environ.get("WANDB_SHARED_FINISHER", primary_label)
settings = wandb.Settings(
mode="shared",
x_label=label,
x_primary=primary,
x_update_finish_state=primary,
x_update_finish_state=finisher,
)
self.logger.info(f"Using shared W&B mode ({label=}, {primary=})")
self.logger.info(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
is_online = True
else:
run_id = None
@@ -117,6 +123,7 @@ class WandbMonitor(Monitor):
self.wandb.project,
train_envs=train_env_names or [],
eval_envs=eval_env_names or [],
flavor=overview_flavor,
)
if url:
self.logger.info(f"Created W&B overview view - {url}")
+30 -2
View File
@@ -10,6 +10,7 @@ from __future__ import annotations
import re
from collections.abc import Sequence
from typing import Literal
import wandb
import wandb_workspaces.reports.v2 as wr
@@ -70,6 +71,19 @@ INFERENCE_PANELS = [
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
["dispatcher/inflight/train", "dispatcher/inflight/eval"],
]
# SFT flavor: no rollout-based train sections — the training signal is the loss curve.
SFT_TRAIN_METRICS = ["loss/mean", "loss/perplexity", "val/loss", "val/perplexity", "progress/epoch"]
SFT_STABILITY_METRICS = ["optim/grad_norm", "optim/lr", "loss/nan_count"]
SFT_PERFORMANCE_METRICS = [
"perf/mfu",
"perf/throughput",
"perf/peak_memory",
"time/step",
"time/forward_backward",
"time/save_ckpt",
]
# Dense grid: more, smaller panels per row and enough rows that sections don't paginate.
@@ -129,7 +143,20 @@ def eval_section(name: str, env_pattern: str) -> ws.Section:
)
def build_sections(train_envs: Sequence[str] = (), eval_envs: Sequence[str] = ()) -> list[ws.Section]:
def build_sections(
train_envs: Sequence[str] = (), eval_envs: Sequence[str] = (), flavor: Literal["rl", "sft"] = "rl"
) -> list[ws.Section]:
# SFT trains on a dataset, not rollouts: the train section is the loss/perplexity
# curves, eval sections are the same rollout-based ones as RL.
if flavor == "sft":
sections = [section("train", metrics=SFT_TRAIN_METRICS)]
if eval_envs:
sections += [eval_section(f"eval/{env}", re.escape(env)) for env in eval_envs]
else:
sections.append(eval_section("eval", ".*"))
sections.append(section("stability", metrics=SFT_STABILITY_METRICS))
sections.append(section("performance", metrics=SFT_PERFORMANCE_METRICS))
return sections
# With one env the aggregate == that env, so show only its section. With several, put the
# cross-env aggregate on top followed by a section per env.
if len(train_envs) == 1:
@@ -193,11 +220,12 @@ def ensure_overview_view(
name: str = OVERVIEW_NAME,
train_envs: Sequence[str] = (),
eval_envs: Sequence[str] = (),
flavor: Literal["rl", "sft"] = "rl",
) -> str | None:
"""Ensure an overview saved view exists for this run's env set. Reuses an existing overview built
for the same envs; when the env set is new, creates a fresh versioned view (``overview`` →
``overview-v2`` → …). Returns the URL of a newly created view, else None."""
sections = build_sections(train_envs, eval_envs)
sections = build_sections(train_envs, eval_envs, flavor)
target = view_signature(sections)
overviews = [(dn, iname) for dn, iname in list_views(entity, project) if dn == name or dn.startswith(f"{name}-v")]
for _, internal_name in overviews:
+9 -13
View File
@@ -19,8 +19,8 @@ I/O); a hook that only does advantage math never awaits:
I/O against another model — an inference pool the algorithm connected in
``setup()`` (a frozen teacher) or the live policy (opsd's self-distillation),
queried with bounded concurrency. No siblings.
- ``score_group(group)`` — the cohort, on group completion, *before* filtering
(filters read the streams): group-relative credit (GRPO/MaxRL baselines).
- ``score_group(group)`` — the cohort, on group completion: group-relative
credit (GRPO/MaxRL baselines).
How rollouts are *produced* is not the algorithm's concern: that is the env's
:class:`~prime_rl.orchestrator.sampler.Sampler`, and sample construction
@@ -95,21 +95,18 @@ class Algorithm:
directly — read the trace, write credit via
:meth:`Rollout.assign_advantages`. They are
async so either stage may do I/O — e.g. a process-reward model or a
teacher at arrival, or a judge at group time whose signal a pre-batch
filter then reads; a hook that only does advantage math simply never
awaits.
teacher at arrival, or a judge at group time; a hook that only does
advantage math simply never awaits.
- :meth:`score_rollout` — one rollout, on arrival: rollout-local credit,
observation ce weights, or per-token results from a model the algorithm
connected in :meth:`setup` (e.g. teacher reference logprobs). Default:
nothing.
- :meth:`score_group` — the cohort, *before* filtering (filters read the
streams): group-relative credit. Default: nothing — rollouts keep
``advantages=None``, so advantage-based filters skip them.
- :meth:`score_group` — the cohort: group-relative credit. Default:
nothing — rollouts keep ``advantages=None``.
Model I/O lives in :meth:`score_rollout`: it runs at arrival, *before* the
pre-batch filters, so it pays compute on rollouts that may then be filtered
out — accepted for the simpler one-rollout-at-a-time shape.
Model I/O lives in :meth:`score_rollout`: it runs at arrival, so it pays
compute on rollouts that the curriculum may later reject.
Constructed with the algorithm config it interprets plus the live policy
pool (``self.policy_pool`` — always available, never closed by the
@@ -145,8 +142,7 @@ class Algorithm:
group stats."""
async def score_group(self, group: list[Rollout]) -> None:
"""Group phase, the finalized cohort, before filtering: write
group-relative credit."""
"""Group phase over the finalized cohort: write group-relative credit."""
async def finalize_rollout(self, rollout: Rollout) -> None:
"""Arrival phase (non-virtual): rollout-local scoring as each rollout is
+1 -2
View File
@@ -20,8 +20,7 @@ class MaxRLAlgorithm(Algorithm):
likelihood as it grows).
Assumes non-negative (canonically binary) rewards; a group with mean reward
<= 0 carries no signal and gets zero advantages (the zero-advantage filter
drops it, matching the paper's no-success convention)."""
<= 0 carries no signal and gets zero advantages."""
async def score_group(self, group: list[Rollout]) -> None:
rewards = torch.tensor([rollout.reward for rollout in group], dtype=torch.float32)
+3 -4
View File
@@ -8,7 +8,7 @@ from prime_rl.orchestrator.algo.base import Algorithm
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
from prime_rl.transport import TrainingSample
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.utils.client import InferencePool
@@ -19,9 +19,8 @@ class OPDAlgorithm(Algorithm):
The policy samples its own rollouts; at ship time each sample's full
context is prefill-scored under the teacher (``ref_logprobs`` on the
wire), and the trainer evaluates the KL against the live policy. No
credit is assigned — rollouts keep ``advantages=None`` (advantage-based
filters never fire) and samples ship no advantage stream; ``group_size``
only fans out sampling."""
credit is assigned — rollouts keep ``advantages=None`` and samples ship no
advantage stream; ``group_size`` only fans out sampling."""
action_loss_type = "ref_kl"
+1 -1
View File
@@ -10,7 +10,7 @@ if TYPE_CHECKING:
from renderers.base import Renderer
from prime_rl.orchestrator.types import Rollout
from prime_rl.transport import TrainingSample
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.utils.client import InferencePool
+1 -1
View File
@@ -14,7 +14,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import ActionLossType
from prime_rl.transport import TrainingSample
from prime_rl.transports.rollouts import TrainingSample
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
+2 -2
View File
@@ -8,7 +8,7 @@ class SFTDistillAlgorithm(Algorithm):
rollouts (``sampling.source``); the policy trains with CE on its tokens.
Assigns no advantage — the ``ce`` loss ignores credit, and SFT trains on
every sampled token. Reward-based filtering, if wanted, is an explicit
filter, not smuggled through an unused advantage stream."""
every sampled token. A curriculum can reject results using reward or any
other finalized rollout data."""
action_loss_type = "ce"
+5 -12
View File
@@ -1,5 +1,4 @@
"""Checkpoint manager for the orchestrator state (``Progress`` counters +
``TrainSource`` data position). Layout:
"""Checkpoint manager for orchestrator progress and train-source state. Layout:
``<output_dir>/checkpoints/step_N/orchestrator/progress.pt``."""
from __future__ import annotations
@@ -57,7 +56,7 @@ class CheckpointManager:
get_logger().debug(f"Loading checkpoint from {state_file}")
start = time.perf_counter()
if self.config.skip_progress:
get_logger().info("Skipping progress and data position loading from checkpoint")
get_logger().info("Skipping progress and train source loading from checkpoint")
else:
with open(state_file, "rb") as f:
state = torch.load(f, weights_only=False)
@@ -66,15 +65,9 @@ class CheckpointManager:
if hasattr(progress, key):
setattr(progress, key, value)
train_source.load_state_dict(state["train_source"])
for name, position in state["train_source"]["envs"].items():
if name not in train_source.base_rows:
continue
rows = train_source.base_rows[name]
num_tasks = len(rows) if rows is not None else "infinite"
get_logger().info(
f"Resumed data position for env {name} - epoch={position['epoch']}, "
f"cursor={position['cursor']}/{num_tasks}"
)
for name in state["train_source"]["envs"]:
if name in train_source.curricula:
get_logger().info(f"Resumed curriculum state for env {name}")
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
+319
View File
@@ -0,0 +1,319 @@
"""ConcurrencyController: adaptive cap on in-flight units of inference work.
A unit is whatever the dispatcher admits against one permit — the controller
treats it as a black box. There is no cost model: the controller measures KV
pressure off the engines and reacts at the pipeline's own pace (AIMD):
- **Grow** the cap multiplicatively per pipeline turnover (each completion
advances the turnover by ``1/inflight``) while the engines are clear, KV
usage is below ``KV_USAGE_GROW``, and the cap binds admission.
- **Trim** above ``KV_USAGE_TRIGGER``: resize cap and pool to what the
engines hold at ``KV_USAGE_TARGET`` and cancel the excess, youngest first.
Cap moves alone cannot relieve pressure from units maturing in place.
- **Cut** on overload: preemptions (single-shot loads) or a persistent
capacity queue (agentic loads never preempt — admission control parks
excess load in the waiting queue). Cut, cancel the excess, then freeze
cuts until the pool drains below the new cap.
The cap starts at ``initial_inflight`` (else the pessimistic bound
``KV capacity / max_model_len``) and is clamped to
``[min_inflight, max_inflight]`` throughout.
The controller is a pure state machine — it owns no tasks or clients. The
metrics collector pushes ``observe(samples)`` every poll; the dispatcher
reports ``record_episode(...)`` per completed unit and consumes the cap via
the hooks bound in :meth:`bind`.
"""
from __future__ import annotations
import math
import time
from collections.abc import Callable
from dataclasses import dataclass
from typing import Literal
from prime_rl.configs.orchestrator import ConcurrencyConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import format_num
TURNOVER_GROWTH = 1.25
"""Cap growth per pipeline turnover while the engines are clear and the cap binds."""
BINDING_FRACTION = 0.9
"""The cap counts as binding when inflight reaches this fraction of it."""
KV_USAGE_GROW = 0.6
"""Grow only while every decode engine's KV usage is below this."""
KV_USAGE_TRIGGER = 0.8
"""Above this usage, trim the cap and the in-flight pool."""
KV_USAGE_TARGET = 0.7
"""A trim resizes to inflight * target / usage — below the trigger, so pool growth has headroom before the next trim."""
KV_TRIM_COOLDOWN_POLLS = 6
"""Polls between kv-headroom trims, letting each trim propagate before the next is sized."""
QUEUE_RATIO = 0.5
"""HARD once capacity-queued requests exceed this fraction of running requests for the persistence window."""
QUEUE_PERSISTENCE_POLLS = 6
"""Consecutive polls of queue overload before the HARD cut; filters natural turn-completion bursts."""
QUEUE_CUT_FRACTION = 0.9
"""A queue cut targets this fraction of the in-flight pool. Pool units, not
engine requests: agentic episodes idle between turns, so engine ``running``
undercounts the pool by the duty cycle and cutting to it over-cuts."""
PREEMPTION_CUT_FRACTION = 0.8
"""A preemption cut targets this fraction of the in-flight pool."""
ESCALATED_CUT_FRACTION = 0.5
"""Cut fraction when overload survives a full drain."""
ESCALATION_GRACE_POLLS = 6
"""Polls after a drain completes during which a repeat overload cuts at the
escalated fraction; past the grace window the system is considered recovered
and escalation resets."""
GROWTH_GATE_TTL_S = 15.0
"""The growth gate expires this long after the poll that set it — if the
metrics path stalls (an API server too loaded to answer is exactly the state
runaway growth creates), growth freezes instead of compounding blind."""
Signal = Literal["clear", "soft", "hard"]
"""Engine pressure, in increasing severity."""
SEVERITY: dict[Signal, int] = {"clear": 0, "soft": 1, "hard": 2}
@dataclass(frozen=True)
class EngineLoadSample:
"""Per-engine load facts for one ``/metrics`` poll. Raw values only —
thresholds and verdicts live in the controller."""
engine_id: str
role: str | None
kv_capacity_tokens: int | None
max_model_len: int | None
kv_usage: float
running: int
waiting: int
# Requests queued specifically for KV capacity (None if the engine does
# not report the by-reason breakdown; fall back to ``waiting``)
waiting_capacity: int | None
preemptions_delta: int
class ConcurrencyController:
def __init__(self, config: ConcurrencyConfig, *, fallback_cost: int) -> None:
self.config = config
self.floor = config.min_inflight
self.fallback_cost = fallback_cost
"""Pessimistic per-unit cost for the starting cap when the engine reports no max context."""
self.cap = float(config.initial_inflight or self.floor)
self.max_inflight = self.clamp(self.cap)
self.bootstrapped = config.initial_inflight is not None
self.engine_max_len: int | None = None
self.capacity_by_engine: dict[str, int] = {}
self.turnover = 0.0
self.signal: Signal = "clear"
# Growth gate from the last poll, consumed by per-completion growth
self.can_grow = False
self.can_grow_until = 0.0
self.prev_waiting: dict[str, int] = {}
self.queue_overload_polls = 0
self.trim_cooldown = 0
self.escalation_grace = 0
# After a cut, ignore further cuts until inflight has drained below
# the new cap — the overload during drain is stale
self.draining = False
self.escalated = False
self.set_limit: Callable[[int], None] | None = None
self.get_inflight: Callable[[], int] | None = None
self.on_overload: Callable[[int], None] | None = None
def bind(
self,
*,
set_limit: Callable[[int], None],
get_inflight: Callable[[], int],
on_overload: Callable[[int], None] | None = None,
) -> None:
"""Attach the outbound hooks. The dispatcher is constructed with this
controller's initial cap, so no ``set_limit`` fires here.
``on_overload`` receives the unit excess on a downward resize so the
dispatcher can cancel in-flight work instead of just blocking
admission."""
self.set_limit = set_limit
self.get_inflight = get_inflight
self.on_overload = on_overload
# ── inbound hooks ────────────────────────────────────────────────────────
def record_episode(self, env_name: str, kind: str, tokens: int, duration: float) -> None:
"""One completed unit (from the dispatcher). Advances the turnover
clock and, while the last poll was green, grows the cap — so growth
is paced by the pipeline itself at any concurrency scale."""
# The dispatcher releases the permit before this hook fires, so the
# completing episode is already off the count — add it back, or the
# binding check is unsatisfiable for caps below 10 (0.9 * cap > cap - 1)
inflight = (self.get_inflight() if self.get_inflight is not None else 0) + 1
fraction = 1 / inflight
self.turnover += fraction
if tokens <= 0:
# Error markers consumed no engine capacity: a slow-failing error
# storm keeps the pool binding while idle engines read CLEAR, and
# growing on it floods the engines once the environment recovers
return
if (
self.can_grow
and time.monotonic() < self.can_grow_until
and inflight >= BINDING_FRACTION * self.max_inflight
):
self.cap = self.clamp(self.cap * TURNOVER_GROWTH**fraction)
self.apply_limit(int(self.cap), reason=None)
def observe(self, samples: list[EngineLoadSample]) -> None:
"""Per-poll engine load push from the metrics collector: classify the
signal, gate growth, and apply trims and cuts."""
if not samples:
return
for sample in samples:
if sample.kv_capacity_tokens and sample.role != "prefill":
self.capacity_by_engine[sample.engine_id] = sample.kv_capacity_tokens
if sample.max_model_len:
self.engine_max_len = max(self.engine_max_len or 0, sample.max_model_len)
# Overload signals read decode engines only: in P/D deployments a
# prefill queue or prefill preemption is normal flow, not KV pressure
samples = [sample for sample in samples if sample.role != "prefill"]
if not samples:
return
worst: Signal = "clear"
max_usage = 0.0
total_running = 0
total_queued = 0
preempted = False
for sample in samples:
if sample.preemptions_delta > 0:
preempted = True
worst = "hard"
if sample.waiting > 0 and self.prev_waiting.get(sample.engine_id, 0) > 0:
worst = max(worst, "soft", key=SEVERITY.__getitem__)
max_usage = max(max_usage, sample.kv_usage)
total_running += sample.running
total_queued += sample.waiting_capacity if sample.waiting_capacity is not None else sample.waiting
self.prev_waiting = {sample.engine_id: sample.waiting for sample in samples}
if total_running > 0 and total_queued > QUEUE_RATIO * total_running:
self.queue_overload_polls += 1
else:
self.queue_overload_polls = 0
queue_overload = self.queue_overload_polls >= QUEUE_PERSISTENCE_POLLS
if queue_overload or max_usage > KV_USAGE_GROW:
worst = max(worst, "hard" if queue_overload else "soft", key=SEVERITY.__getitem__)
self.signal = worst
inflight = self.get_inflight() if self.get_inflight is not None else 0
# Release the drain only once the engines have settled too: cuts
# cancel episodes, so dispatcher inflight drops below the cap almost
# immediately while the engines are still churning through their own
# backlog — preemption deltas from that stale churn must not trigger
# follow-up cuts (observed: an escalated-cut cascade 1024 -> 8, one
# halving per poll).
if self.draining and inflight <= self.max_inflight and not preempted and not queue_overload:
self.draining = False
self.escalation_grace = ESCALATION_GRACE_POLLS
if not self.draining and self.escalated:
# Escalation persists only through the grace window after a
# drain: a repeat overload inside it cuts harder, anything later
# means the system recovered (steady state post-cut is SOFT, so
# gating the reset on a CLEAR poll would latch escalation forever)
self.escalation_grace -= 1
if self.escalation_grace <= 0:
self.escalated = False
self.trim_cooldown = max(0, self.trim_cooldown - 1)
self.can_grow = worst == "clear" and total_queued == 0 and not self.draining
self.can_grow_until = time.monotonic() + GROWTH_GATE_TTL_S
# First capacity observation without a user-set start: derive the
# pessimistic starting cap, once
if not self.bootstrapped and self.capacity is not None:
self.bootstrapped = True
cost = float(self.engine_max_len or self.fallback_cost)
self.cap = self.clamp(self.capacity / cost)
get_logger().info(
f"Derived initial max inflight {int(self.cap)} - {format_num(self.capacity, precision=1)} "
f"KV cache tokens / {format_num(cost, precision=1)} tokens per episode"
)
self.apply_limit(int(self.cap), reason=None)
if self.draining:
return
if preempted or queue_overload:
fraction = ESCALATED_CUT_FRACTION if self.escalated else None
if queue_overload:
self.queue_overload_polls = 0
target = int(self.clamp(inflight * (fraction or QUEUE_CUT_FRACTION)))
reason = "queue overload"
else:
target = int(self.clamp(inflight * (fraction or PREEMPTION_CUT_FRACTION)))
reason = "preemptions"
self.resize_down(target, inflight, reason=reason)
self.draining = True
self.escalated = True
return
if max_usage > KV_USAGE_TRIGGER and inflight > 0 and self.trim_cooldown == 0:
target = int(self.clamp(inflight * KV_USAGE_TARGET / max_usage))
self.resize_down(target, inflight, reason=f"kv headroom (usage {max_usage:.2f})")
self.trim_cooldown = KV_TRIM_COOLDOWN_POLLS
# ── internals ────────────────────────────────────────────────────────────
def resize_down(self, target: int, inflight: int, *, reason: str) -> None:
"""Lower the cap (never raise) and cancel the in-flight excess."""
target = min(target, self.max_inflight)
self.cap = float(target)
self.apply_limit(target, reason=reason)
if self.on_overload is not None and inflight > target:
self.on_overload(inflight - target)
def apply_limit(self, n_max: int, *, reason: str | None) -> None:
if n_max == self.max_inflight:
return
if reason is not None:
verb = "Increased" if n_max > self.max_inflight else "Decreased"
get_logger().info(
f"{verb} concurrency {self.max_inflight} -> {n_max} ({reason}) - "
f"turnover={self.turnover:.1f} signal={self.signal}"
)
self.max_inflight = n_max
if self.set_limit is not None:
self.set_limit(n_max)
def clamp(self, n_max: float) -> float:
ceiling = self.config.max_inflight or math.inf
return min(max(n_max, float(self.floor)), float(ceiling))
@property
def capacity(self) -> int | None:
"""Total KV tokens across decode engines; None until the first poll."""
return sum(self.capacity_by_engine.values()) or None
# ── observability ────────────────────────────────────────────────────────
def gauges(self) -> dict[str, float]:
return {
"concurrency/max_inflight": float(self.max_inflight),
"concurrency/turnover": self.turnover,
"concurrency/capacity": float(self.capacity or 0),
"concurrency/signal": float(SEVERITY[self.signal]),
}
@@ -0,0 +1,14 @@
"""Task selection and finalized-sample admission for training environments."""
from prime_rl.orchestrator.curriculum.base import Curriculum
from prime_rl.orchestrator.curriculum.gates import AdmissionGate, AdvRangeGate
from prime_rl.orchestrator.curriculum.samplers import DifficultyPoolSampler, StandardSampler, TaskSampler
__all__ = [
"AdmissionGate",
"AdvRangeGate",
"Curriculum",
"DifficultyPoolSampler",
"StandardSampler",
"TaskSampler",
]
@@ -0,0 +1,89 @@
"""Curriculum composition and lifecycle."""
from __future__ import annotations
from collections.abc import Iterator, Sequence
from typing import TYPE_CHECKING, Any
import verifiers.v1 as vf
from prime_rl.orchestrator.curriculum.gates import AdmissionGate
from prime_rl.orchestrator.curriculum.samplers import TaskSampler
if TYPE_CHECKING:
from prime_rl.configs.orchestrator import CurriculumConfig
from prime_rl.orchestrator.types import Rollout
class Curriculum:
"""One task sampler composed with zero or more admission gates."""
def __init__(
self,
config: CurriculumConfig | None,
tasks: Sequence[vf.Task] | Iterator[vf.Task],
) -> None:
from prime_rl.configs.orchestrator import (
AdvRangeGateConfig,
CurriculumConfig,
DifficultyPoolSamplerConfig,
StandardSamplerConfig,
)
from prime_rl.orchestrator.curriculum.gates import AdvRangeGate
from prime_rl.orchestrator.curriculum.samplers import DifficultyPoolSampler, StandardSampler
config = CurriculumConfig() if config is None else config
if isinstance(config.sampler, StandardSamplerConfig):
self.sampler: TaskSampler = StandardSampler(tasks)
elif isinstance(config.sampler, DifficultyPoolSamplerConfig):
self.sampler = DifficultyPoolSampler(config.sampler, tasks)
else:
raise TypeError(f"Unsupported task sampler config: {type(config.sampler).__name__}")
self.gates: dict[str, AdmissionGate] = {}
for name, gate_config in config.gates.items():
if isinstance(gate_config, AdvRangeGateConfig):
gate: AdmissionGate = AdvRangeGate(gate_config)
else:
raise TypeError(f"Unsupported admission gate config: {type(gate_config).__name__}")
self.gates[name] = gate
def on_result(self, group: list[Rollout]) -> bool:
"""Observe every result, evaluate every gate, and combine with AND."""
if not group:
raise ValueError("Cannot report an empty rollout group")
task_keys = {rollout.task.key for rollout in group}
if None in task_keys:
raise ValueError("A finalized group is missing Task.key")
if len(task_keys) != 1:
raise ValueError(f"A finalized group contains multiple task keys: {task_keys}")
self.sampler.observe(group)
decisions: list[bool] = []
for name, gate in self.gates.items():
decision = gate.admit(group)
if not isinstance(decision, bool):
raise TypeError(f"AdmissionGate {name!r}.admit() must return bool, got {type(decision).__name__}")
decisions.append(decision)
return all(decisions)
def state_dict(self) -> dict[str, Any]:
return {
"sampler": self.sampler.state_dict(),
"gates": {name: gate.state_dict() for name, gate in self.gates.items()},
}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
if "sampler" not in state_dict:
self.sampler.load_state_dict(state_dict)
return
self.sampler.load_state_dict(state_dict["sampler"])
for name, gate_state in state_dict["gates"].items():
gate = self.gates.get(name)
if gate is not None:
gate.load_state_dict(gate_state)
def metrics(self) -> dict[str, float]:
metrics = {f"sampler/{name}": float(value) for name, value in self.sampler.metrics().items()}
for gate_name, gate in self.gates.items():
metrics |= {f"gate/{gate_name}/{name}": float(value) for name, value in gate.metrics().items()}
return metrics
@@ -0,0 +1,6 @@
"""Admission gate interfaces and implementations."""
from prime_rl.orchestrator.curriculum.gates.adv import AdvRangeGate
from prime_rl.orchestrator.curriculum.gates.base import AdmissionGate
__all__ = ["AdmissionGate", "AdvRangeGate"]
@@ -0,0 +1,33 @@
"""Advantage-based training-sample admission."""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.curriculum.gates.base import AdmissionGate
if TYPE_CHECKING:
from prime_rl.configs.orchestrator import AdvRangeGateConfig
from prime_rl.orchestrator.types import Rollout
class AdvRangeGate(AdmissionGate):
"""Reject groups whose trainable-token advantages all fall inside a range.
The default ``[0, 0]`` interval filters groups with no online learning
signal. Groups without an advantage stream are admitted.
"""
def __init__(self, config: AdvRangeGateConfig) -> None:
self.config = config
def admit(self, group: list[Rollout]) -> bool:
advantages: list[float] = []
for rollout in group:
if rollout.advantages is None:
continue
trainable = [value for sample in rollout.samples for value in sample.mask]
advantages.extend(advantage for advantage, keep in zip(rollout.advantages, trainable, strict=True) if keep)
if not advantages:
return True
return not all(self.config.reject_min <= advantage <= self.config.reject_max for advantage in advantages)
@@ -0,0 +1,27 @@
"""Admission gate interface."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
class AdmissionGate:
"""Base class for user-authored training-sample admission policies."""
def admit(self, group: list[Rollout]) -> bool:
"""Return whether a finalized group should enter the training batch."""
return True
def state_dict(self) -> dict[str, Any]:
"""Return checkpoint state owned by this gate."""
return {}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
"""Restore checkpoint state before results resume."""
def metrics(self) -> dict[str, float]:
"""Return metrics relative to this gate's namespace."""
return {}
@@ -0,0 +1,7 @@
"""Task sampler interfaces and implementations."""
from prime_rl.orchestrator.curriculum.samplers.base import TaskSampler
from prime_rl.orchestrator.curriculum.samplers.pool import DifficultyPoolSampler
from prime_rl.orchestrator.curriculum.samplers.standard import StandardSampler
__all__ = ["DifficultyPoolSampler", "StandardSampler", "TaskSampler"]
@@ -0,0 +1,35 @@
"""Task sampler interface."""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Iterator
from typing import TYPE_CHECKING, Any
import verifiers.v1 as vf
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
class TaskSampler(Iterator[vf.Task], ABC):
"""Base class for user-authored task selection policies."""
@abstractmethod
def __next__(self) -> vf.Task:
"""Choose the next task."""
raise NotImplementedError
def observe(self, group: list[Rollout]) -> None:
"""Update sampling state from a finalized group."""
def state_dict(self) -> dict[str, Any]:
"""Return checkpoint state owned by this sampler."""
return {}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
"""Restore checkpoint state before sampling resumes."""
def metrics(self) -> dict[str, float]:
"""Return metrics relative to this sampler's namespace."""
return {}
@@ -0,0 +1,95 @@
"""Difficulty-pool task sampling."""
from __future__ import annotations
import random
from collections import Counter
from collections.abc import Iterator, Sequence
from typing import TYPE_CHECKING, Any
import verifiers.v1 as vf
from prime_rl.orchestrator.curriculum.samplers.base import TaskSampler
if TYPE_CHECKING:
from prime_rl.configs.orchestrator import DifficultyPoolSamplerConfig
from prime_rl.orchestrator.types import Rollout
class DifficultyPoolSampler(TaskSampler):
"""Weight finite tasks by a pool derived from their latest group mean.
Each pool's threshold is its inclusive maximum reward; the final pool is
the catch-all. Unseen tasks have neutral weight, so observations affect
sampling immediately without requiring a full taskset pass.
"""
def __init__(
self,
config: DifficultyPoolSamplerConfig,
tasks: Sequence[vf.Task] | Iterator[vf.Task],
) -> None:
if not isinstance(tasks, Sequence):
raise ValueError("DifficultyPoolSampler requires a finite taskset")
self.tasks = tuple(tasks)
if not self.tasks:
raise ValueError("DifficultyPoolSampler requires at least one task")
keys = [task.key for task in self.tasks]
duplicates = {key for key, count in Counter(keys).items() if count > 1}
if duplicates:
raise ValueError(f"Task keys must be unique within a taskset: {sorted(duplicates)}")
self.tasks_by_key = dict(zip(keys, self.tasks))
self.rng = random.Random(config.seed)
self.pools = config.pools
ordered = sorted(self.pools.items(), key=lambda item: item[1].threshold)
self._ordered_pools = tuple(ordered)
self.task_rewards: dict[str, float] = {}
def task_pool(self, task_key: str) -> str | None:
"""Return the task's current pool, or ``None`` until it has a score."""
score = self.task_rewards.get(task_key)
if score is None:
return None
for name, pool in self._ordered_pools:
if score <= pool.threshold:
return name
return self._ordered_pools[-1][0]
def __next__(self) -> vf.Task:
weights = []
for task in self.tasks:
pool = self.task_pool(task.key)
weights.append(1.0 if pool is None else self.pools[pool].weight)
if not any(weights):
raise RuntimeError("DifficultyPoolSampler has no tasks in a pool with positive weight")
return self.rng.choices(self.tasks, weights=weights, k=1)[0]
def observe(self, group: list[Rollout]) -> None:
rewards = [rollout.reward for rollout in group if not rollout.has_error and rollout.agent.trainable]
if not rewards:
return
task_key = group[0].task.key
if task_key is None:
raise ValueError("A finalized group is missing Task.key")
self.task_rewards[task_key] = sum(rewards) / len(rewards)
def state_dict(self) -> dict[str, Any]:
return {
"rng": self.rng.getstate(),
"task_rewards": dict(self.task_rewards),
}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
self.rng.setstate(state_dict["rng"])
self.task_rewards = dict(state_dict["task_rewards"])
def metrics(self) -> dict[str, float]:
occupancy = dict.fromkeys(self.pools, 0)
for task_key in self.task_rewards:
pool = self.task_pool(task_key)
if pool is not None:
occupancy[pool] += 1
return {
"pool/unseen": float(len(self.tasks_by_key) - len(self.task_rewards)),
**{f"pool/{name}": float(count) for name, count in occupancy.items()},
}
@@ -0,0 +1,49 @@
"""Standard task iteration."""
from __future__ import annotations
import itertools
from collections import Counter
from collections.abc import Iterator, Sequence
from typing import Any
import verifiers.v1 as vf
from prime_rl.orchestrator.curriculum.samplers.base import TaskSampler
class StandardSampler(TaskSampler):
"""Advance the task iterator, cycling finite tasksets in source order."""
def __init__(self, tasks: Sequence[vf.Task] | Iterator[vf.Task]) -> None:
self.tasks = tuple(tasks) if isinstance(tasks, Sequence) else None
if self.tasks is not None:
if not self.tasks:
raise ValueError("A finite curriculum needs at least one task")
keys = [task.key for task in self.tasks]
duplicates = {key for key, count in Counter(keys).items() if count > 1}
if duplicates:
raise ValueError(f"Task keys must be unique within a taskset: {sorted(duplicates)}")
self.task_iterator = itertools.cycle(self.tasks)
else:
self.task_iterator = tasks
self.cursor = 0
def __next__(self) -> vf.Task:
task = next(self.task_iterator)
self.cursor += 1
return task
def state_dict(self) -> dict[str, Any]:
return {"cursor": self.cursor}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
cursor = state_dict["cursor"]
if self.tasks is not None:
self.task_iterator = itertools.cycle(self.tasks)
offset = cursor % len(self.tasks)
else:
offset = cursor
for _ in range(offset):
next(self.task_iterator)
self.cursor = cursor
+133 -46
View File
@@ -1,7 +1,10 @@
"""RolloutDispatcher: schedules rollouts under a shared permit counter.
"""Dispatcher: schedules rollouts under a shared permit counter.
- Capacity (``max_inflight_episodes``) is shared across train + eval. One permit is
one episode: one ``run`` request against an env server.
- Capacity (``max_inflight``) is shared across train + eval. One permit is
one episode: one ``run`` request against an env server. The cap is dynamic —
the concurrency controller moves it via ``set_limit``; refills are
burst-capped so a raised (or drained) cap never lands all its prefills at
once.
- Optional rate limiting via ``AsyncLimiter(tasks_per_minute, 60)``.
- Emit-everything invariant: every dispatched episode eventually reaches
``out_q`` exactly once, as a ``list[Rollout]``. Failures
@@ -9,10 +12,10 @@
``trace.last_error`` set; sinks decide drop / partial-train policy.
- ``DispatcherMode.PREFER_TRAIN`` / ``PREFER_EVAL`` controls which kind to
schedule next. Transitions are level-triggered (driven by the eval
source's emptiness), so in-flight rollouts of the opposite kind drain
source's emptiness), so in-flight episodes of the opposite kind drain
naturally on either side of an eval boundary.
- ``on_version_pending`` (called by the watcher before the engines pause for
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
the weight update) bumps ``off_policy_steps`` on in-flight train episodes and
drops groups past ``max_off_policy_steps``.
Eval rollouts are measurements for the policy version they started with,
so they are allowed to finish even if training advances. Train rollouts
@@ -25,8 +28,10 @@
from __future__ import annotations
import asyncio
import time
import uuid
from collections import defaultdict
from collections.abc import Callable
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Literal
@@ -39,7 +44,7 @@ from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.train_source import TrainSource
from prime_rl.orchestrator.types import (
GroupState,
InflightRollout,
InflightEpisode,
Policy,
Rollout,
RolloutKind,
@@ -60,7 +65,7 @@ class DispatcherMode(Enum):
class DispatcherMetrics:
"""Per-tick drain counters for the orchestrator's periodic log.
``drained()`` returns the current values and clears them; point-in-time
gauges live on ``RolloutDispatcher.gauges`` instead."""
gauges live on ``Dispatcher.gauges`` instead."""
cancelled_by_kind_env: dict[tuple[Literal["train", "eval"], str], int] = field(
default_factory=lambda: defaultdict(int)
@@ -113,7 +118,19 @@ class DispatcherMetrics:
return keys
class RolloutDispatcher:
def error_trace_task(group: GroupState | None) -> vf.TraceTask:
"""Preserve task identity on a synthetic error trace."""
if group is None:
return vf.TraceTask(type="Task", data=vf.TaskData(idx=-1, prompt=None))
return vf.TraceTask(
type=type(group.task).__name__,
data=vf.TaskData(idx=group.task.data.idx, prompt=None),
key=group.task.key,
hash=group.task.hash,
)
class Dispatcher:
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
rollouts under shared capacity, and emits ``Rollout``\\ s to
@@ -129,9 +146,11 @@ class RolloutDispatcher:
eval_source: EvalSource | None,
policy_pool: InferencePool,
policy: Policy,
max_inflight_episodes: int,
initial_max_inflight: int,
max_inflight_ceiling: int | None,
tasks_per_minute: float | None,
max_off_policy_steps: int,
on_episode_complete: Callable[[str, str, int, float], None] | None = None,
) -> None:
self.policy = policy
self.train_envs = train_envs
@@ -142,19 +161,37 @@ class RolloutDispatcher:
self.train_source = train_source
self.eval_source = eval_source
self.max_off_policy_steps = max_off_policy_steps
# ``(env_name, kind, total_tokens, duration_s)`` per completed episode
self.on_episode_complete = on_episode_complete
self.max_inflight = max_inflight_episodes
self.inflight_permits = 0
# Starting value of the dynamic cap (the concurrency controller moves
# it); ``max_inflight_ceiling`` is the configured hard maximum, used to
# bound ``out_q``
self.max_inflight = initial_max_inflight
self.current_inflight = 0
self.rate_limiter: AsyncLimiter | None = (
AsyncLimiter(tasks_per_minute, time_period=60) if tasks_per_minute else None
)
# Admission smoothing: the pool may only GROW by ``burst_cap`` per
# window. Replacing a completed episode is always free (each natural
# completion refunds one admission); only net expansion is metered.
# This keeps a raised cap or post-drain refill from landing a wall of
# prefills at once, without rate-limiting fast-turning workloads at
# steady state.
self.admission_window_s = 5.0
self.admission_window_start = time.monotonic()
self.admissions_in_window = 0
self.min_burst = max((env.config.group_size for env in train_envs), default=8)
self.inflight: dict[asyncio.Task, InflightRollout] = {}
self.inflight: dict[asyncio.Task, InflightEpisode] = {}
self.groups: dict[uuid.UUID, GroupState] = {}
# Bounded so the dispatcher backpressures on a slow sink. One entry per
# episode — the sinks count episodes, never loose traces.
self.out_q: asyncio.Queue[list[Rollout]] = asyncio.Queue(maxsize=max(8, self.max_inflight))
# Bounded so the dispatcher backpressures on a slow sink (unbounded
# when no hard ceiling is configured — the dynamic cap still bounds
# in-flight work). One entry per episode — the sinks count episodes,
# never loose traces.
maxsize = max(8, max_inflight_ceiling) if max_inflight_ceiling is not None else 0
self.out_q: asyncio.Queue[list[Rollout]] = asyncio.Queue(maxsize=maxsize)
self.mode: DispatcherMode = DispatcherMode.PREFER_TRAIN
# Set by the orchestrator after the final train step; pipeline then
@@ -189,7 +226,51 @@ class RolloutDispatcher:
@property
def available_permits(self) -> int:
return self.max_inflight - self.inflight_permits
return self.max_inflight - self.current_inflight
def set_limit(self, max_inflight: int) -> None:
"""Move the in-flight cap (concurrency controller hook). A cap below
the current in-flight count sheds nothing — admissions just stay
blocked until enough episodes finish."""
self.max_inflight = max_inflight
def cancel_inflight(self, n: int) -> None:
"""Cancel roughly ``n`` in-flight train episodes, youngest groups
first (least inference spend so far). Called on an overload cut so
the working set shrinks immediately instead of waiting for the
over-admitted episodes to finish at thrashed throughput."""
asyncio.create_task(self._cancel_inflight(n))
async def _cancel_inflight(self, n: int) -> None:
# A group's age is its OLDEST member's start: max() would make a
# long-running group look young the moment it schedules another
# member, cancelling the most sunk cost instead of the least
group_age: dict[uuid.UUID, float] = {}
for meta in self.inflight.values():
if meta.kind != "train":
continue
age = group_age.get(meta.group_id)
group_age[meta.group_id] = meta.started_at if age is None else min(age, meta.started_at)
shed = 0
for group_id in sorted(group_age, key=lambda gid: group_age[gid], reverse=True):
if shed >= n:
break
# Count only live cancellations toward the excess: drop_group's
# return includes never-dispatched markers, which free no permits
live = sum(1 for meta in self.inflight.values() if meta.group_id == group_id)
await self.drop_group(group_id)
shed += live
if shed:
get_logger().warning(f"Cancelled {shed} youngest in-flight episodes after overload cut")
def admission_budget(self) -> int:
"""Admissions still allowed in the current burst window."""
now = time.monotonic()
if now - self.admission_window_start >= self.admission_window_s:
self.admission_window_start = now
self.admissions_in_window = 0
burst_cap = max(self.min_burst, self.max_inflight // 10)
return burst_cap - self.admissions_in_window
@property
def inflight_by_env(self) -> dict[tuple[RolloutKind, str], int]:
@@ -262,7 +343,7 @@ class RolloutDispatcher:
async def stop(self) -> None:
self.stopped.set()
await self.cancel_inflight_rollouts()
await self.cancel_inflight_episodes()
if self.task is not None:
await safe_cancel(self.task)
self.task = None
@@ -296,7 +377,7 @@ class RolloutDispatcher:
if cancelled:
get_logger().warning(
f"Cancelled {cancelled} train rollouts past max_off_policy_steps={self.max_off_policy_steps}. "
f"Cancelled {cancelled} train episodes past max_off_policy_steps={self.max_off_policy_steps}. "
"Consider increasing it to avoid this."
)
@@ -310,7 +391,7 @@ class RolloutDispatcher:
respects it. When ``PREFER_EVAL``'s source exhausts we flip back to
``PREFER_TRAIN`` so the eval tail drains alongside fresh train."""
while True:
if self.available_permits <= 0:
if self.available_permits <= 0 or self.admission_budget() <= 0:
return
if self.mode == DispatcherMode.PREFER_EVAL:
@@ -337,7 +418,7 @@ class RolloutDispatcher:
if new_mode == self.mode:
return
prefer = "eval" if new_mode == DispatcherMode.PREFER_EVAL else "train"
get_logger().info(f"Switching dispatcher mode to prefer {prefer} rollouts because {reason}")
get_logger().info(f"Switching dispatcher mode to prefer {prefer} episodes because {reason}")
self.mode = new_mode
async def try_schedule(self, kind: RolloutKind) -> bool:
@@ -424,6 +505,7 @@ class RolloutDispatcher:
group.rollouts_to_schedule -= 1
await self.acquire()
self.admissions_in_window += 1
task = asyncio.create_task(
env.run(
client=client,
@@ -433,13 +515,14 @@ class RolloutDispatcher:
)
)
self.inflight[task] = InflightRollout(
self.inflight[task] = InflightEpisode(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
policy_version=group.policy_version_at_start,
client_config=client,
eval_step=group.eval_step,
started_at=time.monotonic(),
)
return True
@@ -448,10 +531,15 @@ class RolloutDispatcher:
``available_permits >= 1``; this is not a blocking acquire."""
if self.rate_limiter is not None:
await self.rate_limiter.acquire()
self.inflight_permits += 1
self.current_inflight += 1
def release(self) -> None:
self.inflight_permits -= 1
def release(self, *, refund_admission: bool = False) -> None:
"""Free one permit. ``refund_admission`` only on natural completions:
refunding cancelled episodes would hand a mass shed's worth of burst
budget to the refill while the overload is still draining."""
self.current_inflight -= 1
if refund_admission:
self.admissions_in_window = max(0, self.admissions_in_window - 1)
async def handle_completed_rollout(self, task: asyncio.Task) -> None:
"""Emit every dispatched episode exactly once to ``out_q``. Task
@@ -462,8 +550,8 @@ class RolloutDispatcher:
"""
meta = self.inflight.pop(task, None)
if meta is None:
return # already handled by drop_group / cancel_inflight_rollouts
self.release()
return # already handled by drop_group / cancel_inflight_episodes
self.release(refund_admission=True)
group = self.groups.get(meta.group_id)
is_synth_exception = False
@@ -476,10 +564,9 @@ class RolloutDispatcher:
return
except Exception as exc:
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
task_idx = group.task.data.idx if group is not None else -1
rollouts = [
Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
task=error_trace_task(group),
agent=vf.AgentInfo(config=vf.AgentConfig()),
)
]
@@ -500,9 +587,12 @@ class RolloutDispatcher:
get_logger().warning(
f"Rollout failed in group {meta.group_id} ({meta.env_name}) — {r.last_error.type}: {r.last_error.message}"
)
if not is_synth_exception and self.on_episode_complete is not None and meta.started_at > 0:
total_tokens = sum(r.num_total_tokens for r in rollouts)
self.on_episode_complete(meta.env_name, meta.kind, total_tokens, time.monotonic() - meta.started_at)
await self.emit_episode(meta, group, rollouts)
async def emit_episode(self, meta: InflightRollout, group: GroupState | None, rollouts: list[Rollout]) -> None:
async def emit_episode(self, meta: InflightEpisode, group: GroupState | None, rollouts: list[Rollout]) -> None:
"""Stamp prime-rl metadata onto one completed episode and put it on
``out_q``. Pops the group from ``self.groups`` once every owed episode
has been emitted."""
@@ -532,14 +622,12 @@ class RolloutDispatcher:
(both in-flight and not-yet-scheduled). Returns the count for
off-policy metrics."""
group = self.groups.pop(group_id, None)
task_idx = group.task.data.idx if group is not None else -1
# Sync claim phase: pop matching tasks from ``self.inflight`` and
# release their permits in one non-yielding sweep. After this loop
# the dropped tasks are no longer reachable from ``self.inflight``,
# so ``handle_completed_rollout``'s existing None-guard makes the
# subsequent async emit phase race-free.
claimed: list[tuple[asyncio.Task, InflightRollout]] = []
claimed: list[tuple[asyncio.Task, InflightEpisode]] = []
for task, meta in list(self.inflight.items()):
if meta.group_id != group_id:
continue
@@ -549,10 +637,10 @@ class RolloutDispatcher:
tasks_to_cancel = [task for task, _ in claimed]
inflight_cancelled = len(claimed)
last_meta: InflightRollout | None = claimed[-1][1] if claimed else None
last_meta: InflightEpisode | None = claimed[-1][1] if claimed else None
for _, meta in claimed:
trace = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
task=error_trace_task(group),
agent=vf.AgentInfo(config=vf.AgentConfig()),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
@@ -569,7 +657,7 @@ class RolloutDispatcher:
# and us reaching it — synthesize a stand-in from the group state
unscheduled_cancelled = 0
if group is not None and group.rollouts_to_schedule > 0:
fallback_meta = last_meta or InflightRollout(
fallback_meta = last_meta or InflightEpisode(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
@@ -579,7 +667,7 @@ class RolloutDispatcher:
unscheduled_cancelled = group.rollouts_to_schedule
for _ in range(unscheduled_cancelled):
trace = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
task=error_trace_task(group),
agent=vf.AgentInfo(config=vf.AgentConfig()),
ok=False,
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
@@ -590,7 +678,7 @@ class RolloutDispatcher:
cancelled = inflight_cancelled + unscheduled_cancelled
if cancelled > 0:
meta_for_log = last_meta or (
InflightRollout(
InflightEpisode(
kind=group.kind,
env_name=group.env_name,
group_id=group_id,
@@ -611,8 +699,8 @@ class RolloutDispatcher:
await safe_cancel_all(tasks_to_cancel)
return cancelled
async def cancel_inflight_rollouts(self) -> None:
"""Cancel all in-flight rollouts. Used on shutdown — doesn't emit
async def cancel_inflight_episodes(self) -> None:
"""Cancel all in-flight episodes. Used on shutdown — doesn't emit
markers since the sinks are being torn down anyway."""
for meta in self.inflight.values():
self.metrics.record_cancellation(kind=meta.kind, env_name=meta.env_name)
@@ -623,8 +711,8 @@ class RolloutDispatcher:
if tasks:
await safe_cancel_all(tasks)
async def cancel_inflight_train_rollouts(self) -> int:
"""Cancel in-flight train rollouts, leaving eval alone. Used by the
async def cancel_inflight_train_episodes(self) -> int:
"""Cancel in-flight train episodes, leaving eval alone. Used by the
orchestrator at ``max_steps`` so triggered eval can still complete
through the pipeline while wasted train inference is short-circuited."""
train_tasks: list[asyncio.Task] = []
@@ -650,11 +738,10 @@ class RolloutDispatcher:
def gauges(self) -> dict[str, float]:
"""Instantaneous, read-only gauges sampled by the periodic logger."""
return {
"dispatcher/inflight_train": float(self.inflight_train_count),
"dispatcher/inflight_eval": float(self.inflight_eval_count),
"dispatcher/inflight/train": float(self.inflight_train_count),
"dispatcher/inflight/eval": float(self.inflight_eval_count),
"dispatcher/queued/eval": float(self.queued_eval_examples),
"dispatcher/mode": float(self.mode == DispatcherMode.PREFER_EVAL),
"dispatcher/groups_in_flight": float(len(self.groups)),
"dispatcher/off_policy_level_max": float(self.max_off_policy_level),
"dispatcher/off_policy_level_mean": self.mean_off_policy_level,
"dispatcher/off_policy_level/max": float(self.max_off_policy_level),
"dispatcher/off_policy_level/mean": self.mean_off_policy_level,
}
+1 -1
View File
@@ -10,7 +10,7 @@ once, and each dispatched episode ships its task's data on the request
(``task_data``); the server pydantic-validates it into the taskset's declared
``TaskData`` type and runs it. That keeps the server (and every worker in its
pool) stateless about data — no per-worker dataset loads, no idx-addressed task
cache — and gives the orchestrator real tasks to cycle, shuffle, and filter.
cache — and gives the orchestrator real tasks to sample.
The server answers one ``Episode`` per run request, whose traces we validate into
``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose dicts) whose task
+1 -1
View File
@@ -1,6 +1,6 @@
"""EvalSink: three-level rollout sink for eval epochs.
Same shape as ``TrainSink``, but no tokenization / advantages / filters:
Same shape as ``TrainSink``, but no tokenization, advantages, or admission:
1. ``process_rollout`` — no-op.
2. ``process_group`` — at ``group_size`` episodes, move the rollouts
+5 -3
View File
@@ -43,15 +43,17 @@ class EvalSource:
# trigger fires every env (subject to ``skip_first_step``)
self.first_trigger = not is_resumed
def trigger(self, step: int) -> list[str]:
def trigger(self, step: int, *, force: bool = False) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run."""
``first_trigger`` is False, so the startup/base eval doesn't re-run.
``force`` fires every env regardless of interval (e.g. the evaluator's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.eval_config.skip_first_step:
return []
fired: list[str] = []
for name, interval in self.intervals.items():
if is_first or step % interval == 0:
if is_first or force or step % interval == 0:
fired.append(name)
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
# dispatcher rotates at example granularity. ``try_schedule``'s
+320
View File
@@ -0,0 +1,320 @@
"""Online evaluator: disk-checkpoint-driven evals against a live inference server.
The trainer writes HF weight checkpoints to ``weights/step_{n}`` (``STABLE``
marker on completion) — that is its signal that a new policy is ready. The
evaluator watches the directory, tells the inference server to reload each
eligible checkpoint from disk (``/update_weights``, no NCCL rendezvous), and
runs the configured evals against the updated weights, sequentially per
checkpoint so every epoch measures exactly one policy version.
Reuses the orchestrator's eval components — ``EvalEnvs`` / ``EvalSource`` /
``EvalSink`` / ``EvalRollouts`` — and logs metrics and episodes through the same
monitors (``eval/{env}/...`` metrics, episode traces via the file monitor).
"""
from __future__ import annotations
import asyncio
import os
import time
import uuid
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.orchestrator.envs import EvalEnv, EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.types import EvalBatch, Rollout
from prime_rl.orchestrator.utils import group_episodes, intercept_vf_logging, set_default_executor
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_step_path
from prime_rl.utils.utils import clean_exit
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often to re-scan the weights directory for new checkpoints.
POLL_INTERVAL_S = 2.0
class Evaluator:
def __init__(self, config: EvaluatorConfig) -> None:
self.config = config
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
get_logger().info(f"Starting evaluator (weights_dir={config.weights_dir})")
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = config.resume_step or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
async def setup(self) -> None:
config = self.config
set_default_executor()
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.eval.source],
overview_flavor="sft",
)
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
self.run_name = os.environ.get("PRL_RUN_NAME")
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.pool = InferencePool(config.eval.client, model_name=config.model)
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
await self.eval_envs.start()
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.pool.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=config.resume_step is not None)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
async def run(self) -> None:
await self.setup()
config = self.config
if config.resume_step is None:
# Base-model eval: the inference server starts with the untrained weights,
# so no reload is needed. The first trigger fires every env (policy v0)
# unless ``skip_first_step``.
await self.maybe_run_evals(step=0)
elif config.eval.retrigger_on_resume:
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
# evals). Requires the resume step's weights on disk. The final checkpoint
# force-fires every env, exactly like the watch loop below.
is_final = config.max_steps is not None and config.resume_step >= config.max_steps
await self.maybe_run_evals(step=config.resume_step, reload_weights=True, force=is_final)
get_logger().info(f"Watching {config.weights_dir} for new weight checkpoints (max_steps={config.max_steps})")
while True:
assert config.weights_dir is not None # resolved by the config validator
steps = get_all_ckpt_steps(config.weights_dir)
stable = {step: (get_step_path(config.weights_dir, step) / "STABLE").exists() for step in steps}
newest_stable = max((step for step in steps if stable[step]), default=None)
# Also walk eval-due steps that are no longer on disk: checkpoint cleaning
# (ckpt.keep_last / keep_interval) can delete a step before this scan sees
# it, and a vanished step would otherwise be skipped without a trace.
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
if step <= self.last_step:
continue
if step not in stable:
get_logger().warning(
f"Weight checkpoint for eval step {step} was deleted before it could be "
"evaluated (checkpoint cleaning outpaced the evaluator) - skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
if not stable[step]:
# The trainer writes checkpoints in ascending order, so a marker-less
# step below a stable one is an abandoned partial write (e.g. a crash
# mid-save), not one in progress — skip it instead of wedging on it.
if newest_stable is None or newest_stable < step:
break # still being written — later steps can't be ready either
get_logger().warning(
f"Weight checkpoint step {step} has no STABLE marker but newer stable "
"checkpoints exist - treating it as abandoned and skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
is_final = config.max_steps is not None and step >= config.max_steps
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
if config.max_steps is not None and self.last_step >= config.max_steps:
break
await asyncio.sleep(POLL_INTERVAL_S)
get_logger().success("Evaluator finished!")
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
"""Eval-due steps up to the newest stable checkpoint that are missing from the
weights dir — the trainer wrote them (it saves at every due step), so their
absence means checkpoint cleaning removed them before they were evaluated."""
if newest_stable is None:
return set()
due = {
step
for interval in self.eval_source.intervals.values()
for step in range(interval, newest_stable + 1, interval)
}
return due - set(steps)
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
reloading the inference weights first. No-op when no env is due."""
assert self.config.weights_dir is not None # resolved by the config validator
weight_dir = get_step_path(self.config.weights_dir, step)
if reload_weights and not (weight_dir / "STABLE").exists():
get_logger().warning(f"No stable weight checkpoint for step {step} ({weight_dir}) - skipping eval")
self.last_step = max(self.last_step, step)
return
fired = self.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if not fired:
return
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
for env_name in fired
)
if reload_weights:
get_logger().info(f"Updating inference weights to checkpoint step {step} ({weight_dir})")
try:
await self.pool.update_weights(weight_dir, step=step)
except Exception as exc:
# Skip this step instead of killing the run; drain the queued examples
# so they don't leak into a later epoch with the wrong eval_step.
while self.eval_source.next_example() is not None:
pass
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
return
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
await self.run_evals(step)
async def run_evals(self, step: int) -> None:
"""Drain the eval queue for one step under bounded concurrency, routing
finished episodes through the sink and finalizing each env's epoch."""
semaphore = asyncio.Semaphore(self.config.eval.max_inflight_episodes)
tasks: list[asyncio.Task] = []
while (example := self.eval_source.next_example()) is not None:
env = self.eval_envs.get(example["env_name"])
group_id = uuid.uuid4()
for _ in range(env.config.group_size):
tasks.append(asyncio.create_task(self.run_episode(env, example, group_id, step, semaphore)))
for future in asyncio.as_completed(tasks):
episode = await future
run = vf.EvalRunInfo(id=self.run_id, name=self.run_name, step=step)
for rollout in episode:
rollout.record_run(
run,
env_name=rollout.env_name,
group_id=str(rollout.group_id),
episode_id=rollout.episode_id,
policy_version=rollout.policy_version,
)
await monitors.log(group_episodes(episode), step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
async def run_episode(
self,
env: EvalEnv,
example: dict,
group_id: uuid.UUID,
step: int,
semaphore: asyncio.Semaphore,
) -> list[Rollout]:
"""Run one episode against the env server; failures synthesize an
error-marker rollout so the sink's count-based finalization still fires."""
async with semaphore:
try:
rollouts = await env.run(
client=self.pool.eval_client,
model_name=self.pool.model_name,
cache_salt=str(step),
task_data=example["task"].data.model_dump(mode="json"),
)
except Exception as exc:
get_logger().warning(f"Rollout task failed in group {group_id} ({env.name}): {exc!r}")
rollout = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=example["task"].data.idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
)
rollout.record_error(exc)
rollouts = [rollout]
for rollout in rollouts:
if not rollout.has_error and rollout.num_turns == 0:
rollout.errors.append(
vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps")
)
rollout.ok = False
get_logger().warning(f"Empty trajectory in group {group_id} ({env.name})")
rollout.kind = "eval"
rollout.env_name = env.name
rollout.group_id = group_id
# For SFT-driven evals the policy version *is* the checkpoint step.
rollout.policy_version = step
rollout.eval_step = step
return rollouts
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.rollouts:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
return
await monitors.log(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
rollouts = batch.rollouts
effective = rollouts.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", rollouts), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
eff, full = effective.metrics, rollouts.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
)
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
pool = getattr(self, "pool", None)
if pool is not None:
await pool.stop()
@clean_exit
async def run_evaluator(config: EvaluatorConfig) -> None:
evaluator = Evaluator(config)
try:
await evaluator.run()
# Finalize only on a clean exit — a crashed evaluator must not mark the run completed.
await monitors.finalize()
finally:
await evaluator.stop()
def main() -> None:
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
set_proc_title("Evaluator")
asyncio.run(run_evaluator(cli(EvaluatorConfig)))
if __name__ == "__main__":
main()
-172
View File
@@ -1,172 +0,0 @@
"""Orchestrator-side rollout filters for detecting degenerate generations.
Filters run after rollouts complete, inspecting token IDs and logprobs to
detect gibberish or repetition. Detection metrics are always tracked.
When enforce=True, detected rollouts are skipped entirely during training and
are not sent to the trainer. Reward is kept as-is for baseline calculation.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import TYPE_CHECKING, Protocol
from prime_rl.configs.orchestrator import FilterConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
@dataclass
class FilterResult:
detected: bool
class RolloutFilter(Protocol):
name: str
enforce: bool
def check(self, rollout: Rollout) -> FilterResult: ...
@dataclass
class GibberishFilter:
"""Flags rollouts containing rare tokens generated at high entropy.
A token is flagged when both:
- id(token) > token_id_threshold (rare BPE token)
- logprob(token) < -log(vocab_size) - logprob_offset (high entropy)
References:
Section 5.2, https://arxiv.org/abs/2510.02387
"""
name: str
token_id_threshold: int
logprob_threshold: float
enforce: bool = False
def check(self, rollout: Rollout) -> FilterResult:
for branch in rollout.branches:
# branch.{token_ids,logprobs,sampled_mask} are flat and mutually aligned; the raw
# node arrays are not (node.logprobs covers only the sampled suffix, not the
# generation-prompt scaffold that token_ids/mask also span).
for token_id, logprob, sampled in zip(branch.token_ids, branch.logprobs, branch.sampled_mask):
if not sampled:
continue
if token_id > self.token_id_threshold and logprob < self.logprob_threshold:
return FilterResult(detected=True)
return FilterResult(detected=False)
@dataclass
class RepetitionFilter:
"""Flags rollouts with pathological repetition loops.
Counts consecutive tokens where logprob > log(prob_threshold), indicating
the model is generating with very high confidence. When the streak reaches
the window size, the rollout is flagged.
References:
Section 3.2, https://arxiv.org/abs/2506.13585
"""
name: str
window: int
logprob_threshold: float
enforce: bool = False
def check(self, rollout: Rollout) -> FilterResult:
for branch in rollout.branches:
# Aligned branch streams (see GibberishFilter), and reset the streak per branch:
# flat rollout.nodes interleaves distinct root->leaf paths (compaction/subagents),
# so a per-node walk would run a streak across a branch boundary.
consecutive = 0
for logprob, sampled in zip(branch.logprobs, branch.sampled_mask):
if not sampled:
continue
if logprob > self.logprob_threshold:
consecutive += 1
else:
consecutive = 0
if consecutive >= self.window:
return FilterResult(detected=True)
return FilterResult(detected=False)
@dataclass
class ZeroAdvantageFilter:
"""Flags rollouts whose advantage stream is all zero (e.g. all rollouts in
a GRPO group earned the same reward, so the centered advantage collapses)."""
name: str
enforce: bool = True
def check(self, rollout: Rollout) -> FilterResult:
if rollout.advantages is not None and all(a == 0.0 for a in rollout.advantages):
return FilterResult(detected=True)
return FilterResult(detected=False)
def setup_filter(config: FilterConfig, vocab_size: int) -> RolloutFilter:
"""Create a RolloutFilter from a filter config."""
if config.type == "gibberish":
return GibberishFilter(
name="gibberish",
token_id_threshold=config.token_id_threshold,
logprob_threshold=-math.log(vocab_size) - config.logprob_offset,
enforce=config.enforce,
)
elif config.type == "repetition":
return RepetitionFilter(
name="repetition",
window=config.window,
logprob_threshold=math.log(config.prob_threshold),
enforce=config.enforce,
)
elif config.type == "zero_advantage":
return ZeroAdvantageFilter(
name="zero_advantage",
enforce=config.enforce,
)
raise ValueError(f"Unknown filter type: {config.type}")
def setup_filters(configs: list[FilterConfig], vocab_size: int, *, kind: str) -> list[RolloutFilter]:
"""Create RolloutFilters from a list of filter configs."""
filters = [setup_filter(config, vocab_size) for config in configs]
if filters:
get_logger().info(f"Configured {len(filters)} {kind} rollout filter(s):")
for config, filt in zip(configs, filters):
mode = "Enforcing" if filt.enforce else "Monitoring"
params = ", ".join(f"{k}={v}" for k, v in config.model_dump().items())
get_logger().info(f" {mode} {filt.name} filter ({params})")
return filters
def apply_filters(filters: list[RolloutFilter], rollouts: list[Rollout]) -> None:
"""Flag ``Rollout``\\ s in place with per-filter detection + drop decision.
Each rollout's ``filter_results`` dict records per-filter detection bools;
``is_filtered`` is True iff an enforcing filter detected it. First matching
filter wins per rollout (no double-counting). Reward and trajectory tokens
are left untouched so the rollout can still contribute to baseline
calculations and metric aggregation.
"""
for rollout in rollouts:
rollout.filter_results = {f.name: False for f in filters}
rollout.is_filtered = False
if not filters:
return
for rollout in rollouts:
for filt in filters:
result = filt.check(rollout)
if result.detected:
rollout.filter_results[filt.name] = True
if filt.enforce:
rollout.is_filtered = True
break
+80 -21
View File
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import math
import time
from collections.abc import Callable
from dataclasses import dataclass, field
from statistics import mean, median
@@ -10,16 +11,16 @@ import wandb
from httpx import AsyncClient
from prometheus_client.parser import text_string_to_metric_families
from prime_rl.orchestrator.concurrency import EngineLoadSample
from prime_rl.utils.logger import get_logger
POLL_INTERVAL = 5.0
FETCH_TIMEOUT = 5.0
METRIC_PREFIX = "vllm:"
CACHE_CONFIG_FAMILY = "vllm:cache_config_info"
PD_ROLES = {"prefill", "decode"}
QUANTILES = {"p50": 0.5, "p90": 0.9, "p99": 0.99}
AGGREGATIONS = {"min": min, "max": max, "sum": sum, "mean": mean, "median": median}
OVERLOAD_WAITING_FRACTION = 0.2
OVERLOAD_WARN_INTERVAL = 60.0
# Scope-level ratios derived from counter deltas; each operand lists legacy and
# OpenMetrics sample names, whichever the running vLLM version emits.
@@ -50,6 +51,8 @@ class EngineSnapshot:
gauges: dict[str, float] = field(default_factory=dict)
counters: dict[str, float] = field(default_factory=dict)
histograms: dict[str, HistogramSnapshot] = field(default_factory=dict)
cache_config: dict[str, str] = field(default_factory=dict)
"""Labels of ``vllm:cache_config_info`` (e.g. ``num_gpu_blocks``, ``block_size``)."""
@dataclass(frozen=True)
@@ -92,7 +95,14 @@ def parse_prometheus_text(text: str) -> dict[str, EngineSnapshot]:
if sample.name.endswith("_created") or not math.isfinite(sample.value):
continue
engine = engines.setdefault(sample.labels.get("engine", "0"), EngineSnapshot())
if family.name == CACHE_CONFIG_FAMILY:
engine.cache_config.update(sample.labels)
continue
name = sample.name.removeprefix(METRIC_PREFIX)
# Keep the queue-reason breakdown instead of summing it away — the
# concurrency controller keys on capacity-queued requests
if name == "num_requests_waiting_by_reason":
name = f"num_requests_waiting_reason_{sample.labels.get('reason', 'unknown')}"
if family.type == "gauge":
engine.gauges[name] = engine.gauges.get(name, 0.0) + sample.value
elif family.type == "counter":
@@ -268,28 +278,31 @@ class InferenceMetricsCollector:
self,
admin_clients: list[AsyncClient],
roles: list[str | None] | None = None,
max_inflight_episodes: int | None = None,
on_load: Callable[[list[EngineLoadSample]], None] | None = None,
log_to_wandb: bool = True,
):
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
self.previous: dict[tuple[str, str], TimedSnapshot] = {}
self.max_model_len_by_endpoint: dict[str, int] = {}
self.task: asyncio.Task | None = None
self.has_pd_roles = {endpoint.role for endpoint in self.endpoints if endpoint.role is not None} == PD_ROLES
self.max_inflight_episodes = max_inflight_episodes
self.last_overload_warning = float("-inf")
self.on_load = on_load
self.log_to_wandb = log_to_wandb
get_logger().info(
"Collecting inference metrics from "
+ ", ".join(f"{endpoint.name}={endpoint.key}" for endpoint in self.endpoints)
)
async def start(self):
wandb.define_metric("inference/*", step_metric="_timestamp")
if self.log_to_wandb:
wandb.define_metric("inference/*", step_metric="_timestamp")
async def poll_loop():
while True:
try:
await self.collect_and_log()
except Exception as e:
get_logger().debug(f"Inference metrics poll failed: {e!r}")
get_logger().warning(f"Inference metrics poll failed: {e!r}")
await asyncio.sleep(POLL_INTERVAL)
self.task = asyncio.create_task(poll_loop())
@@ -316,28 +329,74 @@ class InferenceMetricsCollector:
if not samples:
return
metrics = self.build_metrics(samples)
await asyncio.gather(*[self.fetch_max_model_len(endpoint) for endpoint in self.endpoints])
metrics = self.build_metrics(samples) if self.log_to_wandb else {}
load_samples = [self.build_load_sample(sample) for sample in samples]
for sample in samples:
self.previous[sample.key] = TimedSnapshot(timestamp=sample.timestamp, snapshot=sample.snapshot)
waiting_requests = metrics.get("inference/agg/num_requests_waiting/sum", 0.0)
if (
self.max_inflight_episodes is not None
and waiting_requests > OVERLOAD_WAITING_FRACTION * self.max_inflight_episodes
and now - self.last_overload_warning >= OVERLOAD_WARN_INTERVAL
):
self.last_overload_warning = now
get_logger().warning(
f"Inference is overloaded: {waiting_requests:.0f} waiting request(s), more than "
f"{OVERLOAD_WAITING_FRACTION:.0%} of max_inflight_episodes={self.max_inflight_episodes} - "
"training is slowed by queued requests. If intermittent, wait it out - if persistent, "
"lower concurrency by decreasing max_inflight_episodes"
)
if self.on_load is not None:
self.on_load(load_samples)
if metrics:
metrics["_timestamp"] = time.time()
wandb.log(metrics)
async def fetch_max_model_len(self, endpoint: MetricsEndpoint) -> None:
"""Cache the engine's max context length from ``/v1/models`` (set
explicitly or derived from the model config). Static per engine
lifetime; retried next poll on failure."""
if endpoint.key in self.max_model_len_by_endpoint:
return
try:
response = await endpoint.client.get("/v1/models", timeout=FETCH_TIMEOUT)
response.raise_for_status()
lengths = [card.get("max_model_len") for card in response.json().get("data", [])]
lengths = [length for length in lengths if length]
if lengths:
self.max_model_len_by_endpoint[endpoint.key] = max(lengths)
except Exception as e:
get_logger().debug(f"Failed to fetch max_model_len from {endpoint.client.base_url}: {e!r}")
def build_load_sample(self, sample: EngineSample) -> EngineLoadSample:
"""Raw per-engine load facts for the concurrency controller."""
cache_config = sample.snapshot.cache_config
kv_capacity_tokens: int | None = None
# ``kv_cache_size_tokens`` is authoritative; the ``num_gpu_blocks``
# label does not reflect ``num_gpu_blocks_override`` (observed 4x off)
size_tokens = cache_config.get("kv_cache_size_tokens", "")
num_gpu_blocks, block_size = cache_config.get("num_gpu_blocks", ""), cache_config.get("block_size", "")
if size_tokens.isdigit():
kv_capacity_tokens = int(size_tokens)
elif num_gpu_blocks.isdigit() and block_size.isdigit():
kv_capacity_tokens = int(num_gpu_blocks) * int(block_size)
# First poll has no baseline — a nonzero cumulative counter (e.g. after
# an orchestrator restart) is not a fresh preemption
previous = self.previous.get(sample.key)
preemptions_delta = 0
if previous is not None:
for name in ("num_preemptions", "num_preemptions_total"):
if name in sample.snapshot.counters:
delta = sample.snapshot.counters[name] - previous.snapshot.counters.get(name, 0.0)
preemptions_delta = max(preemptions_delta, int(delta))
return EngineLoadSample(
engine_id=sample.engine_id,
role=sample.endpoint.role,
kv_capacity_tokens=kv_capacity_tokens,
max_model_len=self.max_model_len_by_endpoint.get(sample.endpoint.key),
kv_usage=sample.snapshot.gauges.get("kv_cache_usage_perc", 0.0),
running=int(sample.snapshot.gauges.get("num_requests_running", 0.0)),
waiting=int(sample.snapshot.gauges.get("num_requests_waiting", 0.0)),
waiting_capacity=(
int(capacity_waiting)
if (capacity_waiting := sample.snapshot.gauges.get("num_requests_waiting_reason_capacity")) is not None
else None
),
preemptions_delta=preemptions_delta,
)
def build_metrics(self, samples: list[EngineSample]) -> dict[str, float]:
values_per_engine = [engine_values(sample, self.previous.get(sample.key)) for sample in samples]
bucket_deltas_per_engine = [bucket_deltas(sample, self.previous.get(sample.key)) for sample in samples]
+6 -12
View File
@@ -333,7 +333,7 @@ class EpisodeMetrics:
class TrainMetrics(EpisodeMetrics):
"""Common metrics plus the per-agent filter-pipeline rates. ``reward`` (flat over all traces)
"""Common metrics plus per-agent pipeline rates. ``reward`` (flat over all traces)
serves the console log lines; the wandb reward stats are per-agent."""
@property
@@ -342,18 +342,12 @@ class TrainMetrics(EpisodeMetrics):
def to_wandb(self, *, prefix: str, subset: Subset) -> dict[str, float]:
out = super().to_wandb(prefix=prefix, subset=subset)
# The pipeline verdicts are per-trace (an untrainable seat is 0.0 throughout, and filters
# only ever run on trainable survivors), so they read per agent like the rest.
# Pipeline verdicts are per-trace, so they read per agent like the rest.
for agent, traces in self.by_agent().items():
p = f"{prefix}/{subset}/{agent}"
rollouts = traces.rollouts
out[f"{p}/is_trainable/mean"] = sum(float(r.is_trainable) for r in rollouts) / len(rollouts)
out[f"{p}/is_filtered/mean"] = sum(float(r.is_filtered) for r in rollouts) / len(rollouts)
names = sorted({name for r in rollouts for name in r.filter_results})
out |= {
f"{p}/filters/{name}/mean": sum(1 for r in rollouts if r.filter_results.get(name)) / len(rollouts)
for name in names
}
out[f"{p}/is_admitted/mean"] = sum(float(r.is_admitted) for r in rollouts) / len(rollouts)
return out
@@ -396,8 +390,8 @@ class EvalMetrics(EpisodeMetrics):
class TrainRollouts:
"""A list of train rollouts (everything that came back, errored + filtered + untrainable
included). ``effective`` is the clean trainable subset (a view of the same traces);
"""A list of train rollouts (everything that came back, including rejected,
errored and untrainable traces). ``effective`` is the clean trainable subset;
``metrics`` builds ``TrainMetrics`` over them."""
def __init__(self, rollouts: list[Rollout] | None = None) -> None:
@@ -414,7 +408,7 @@ class TrainRollouts:
@property
def effective(self) -> TrainRollouts:
return TrainRollouts([r for r in self.rollouts if not r.has_error and not r.is_filtered and r.agent.trainable])
return TrainRollouts([r for r in self.rollouts if r.is_admitted and not r.has_error and r.agent.trainable])
def by_env(self) -> dict[str, TrainRollouts]:
grouped: dict[str, list[Rollout]] = {}
+54 -53
View File
@@ -3,9 +3,9 @@
``Orchestrator`` owns the shared state (policy, progress, ckpt, monitor)
and drives the pipeline. Components are single-purpose:
- ``RolloutDispatcher`` schedules rollouts; emits ``Rollout`` (train/eval
- ``Dispatcher`` schedules rollouts; emits ``Rollout`` (train/eval
discriminated by ``kind``) on its queue.
- ``TrainSink`` ingests train rollouts (tokenize → advantages → filters)
- ``TrainSink`` ingests train rollouts (tokenize → advantages → admission)
and returns a ``TrainBatch`` when the threshold is met.
- ``EvalSink`` ingests eval rollouts and returns an ``EvalBatch`` (the full
returned cohort) on epoch completion.
@@ -37,17 +37,17 @@ if TYPE_CHECKING:
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.orchestrator.ckpt import CheckpointManager
from prime_rl.transport.base import MicroBatchSender
from prime_rl.transports.rollouts.base import MicroBatchSender
from prime_rl.utils.client import InferencePool
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive imports
from prime_rl import monitors
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.dispatcher import DispatcherMetrics, DispatcherMode, RolloutDispatcher
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.filters import setup_filters
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.packing import BatchPacker
from prime_rl.orchestrator.patches import (
@@ -74,8 +74,8 @@ from prime_rl.orchestrator.utils import (
)
from prime_rl.orchestrator.watcher import WeightWatcher
from prime_rl.trainer.model import setup_tokenizer
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.transport import setup_micro_batch_sender
from prime_rl.transports.rollouts import setup_micro_batch_sender
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
from prime_rl.utils.heartbeat import Heartbeat
@@ -93,9 +93,7 @@ monkey_patch_chat_completion_logprobs()
# shutdown wedges (env-server ZMQ recv, vLLM admin aclose, etc)
SHUTDOWN_TIMEOUT_S = 300
# Abort after this many consecutive train batches drop all rollouts to
# post-batch filters — usually a misconfigured filter or homogeneous-reward
# dataset; fail loudly instead of spinning
# Abort after this many consecutive train batches contain no samples.
MAX_CONSECUTIVE_EMPTY_BATCHES = 10
# Maximum batches the orchestrator may run ahead of the trainer. The
@@ -130,7 +128,8 @@ class Orchestrator:
train_envs: TrainEnvs
train_source: TrainSource
train_sink: TrainSink
dispatcher: RolloutDispatcher
dispatcher: Dispatcher
concurrency: ConcurrencyController
watcher: WeightWatcher
lag_monitor: EventLoopLagMonitor
periodic_logger: PeriodicLogger
@@ -236,10 +235,6 @@ class Orchestrator:
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
# Filters apply to train rollouts only
pre_filters = setup_filters(config.pre_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="pre-batch")
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
get_logger().info("Loading training environments")
self.train_envs = TrainEnvs(
config.train.source,
@@ -281,16 +276,6 @@ class Orchestrator:
*(env.algorithm.setup() for env in self.train_envs),
)
# Gate on the registered monitor, not the config - the collector logs to the global
# W&B session, which only exists when the monitor's init succeeded.
if monitors.get(monitors.WandbMonitor) is not None and config.collect_inference_metrics:
self.inference_metrics = InferenceMetricsCollector(
self.policy_inference.admin_clients,
roles=config.inference_metrics_roles,
max_inflight_episodes=config.max_inflight_episodes,
)
await self.inference_metrics.start()
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
if config.weight_broadcast.type == "nccl":
await init_nccl_broadcast(
@@ -386,20 +371,38 @@ class Orchestrator:
else None
)
assert config.max_inflight_episodes is not None, "max_inflight_episodes must be resolved before dispatcher init"
log_interval = config.log.interval
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
self.dispatcher = RolloutDispatcher(
self.concurrency = ConcurrencyController(config.concurrency, fallback_cost=config.seq_len)
self.dispatcher = Dispatcher(
train_envs=self.train_envs,
eval_envs=self.eval_envs,
train_source=self.train_source,
eval_source=self.eval_source,
policy_pool=self.policy_inference,
policy=self.policy,
max_inflight_episodes=config.max_inflight_episodes,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
tasks_per_minute=config.tasks_per_minute,
max_off_policy_steps=config.max_off_policy_steps,
on_episode_complete=self.concurrency.record_episode,
)
self.concurrency.bind(
set_limit=self.dispatcher.set_limit,
get_inflight=lambda: self.dispatcher.current_inflight,
on_overload=self.dispatcher.cancel_inflight,
)
# The collector always polls — it feeds the concurrency controller;
# W&B mirroring is gated on the registered monitor (the collector logs
# to the global W&B session, which only exists when init succeeded).
self.inference_metrics = InferenceMetricsCollector(
self.policy_inference.admin_clients,
roles=config.inference_metrics_roles,
on_load=self.concurrency.observe,
log_to_wandb=wandb_enabled and config.collect_inference_metrics,
)
await self.inference_metrics.start()
self.train_sink = TrainSink(
config,
tokenizer=self.tokenizer,
@@ -407,8 +410,7 @@ class Orchestrator:
mm_token_type_ids_mapping=self.mm_token_type_ids_mapping,
batch_size=config.batch_size,
token_batch_size=config.token_batch_size,
pre_filters=pre_filters,
post_filters=post_filters,
on_result=self.train_source.on_result,
)
self.eval_sink = EvalSink(eval_envs=self.eval_envs) if self.eval_envs is not None else None
self.watcher = WeightWatcher(
@@ -428,6 +430,7 @@ class Orchestrator:
collect=self.collect_pipeline_view,
metric_keys=[
*list(self.dispatcher.gauges().keys()),
*list(self.concurrency.gauges().keys()),
*DispatcherMetrics.drain_keys(
train_envs={e.name for e in self.train_envs},
eval_envs={e.name for e in self.eval_envs} if self.eval_envs is not None else set(),
@@ -486,6 +489,10 @@ class Orchestrator:
elapsed = format_time(time.perf_counter() - start_time)
if clean_exit:
get_logger().success(f"Orchestrator step loop done in {elapsed}")
# The collector logs to the W&B run, so it must stop before
# finalize marks the run finished
if self.inference_metrics is not None:
await self.inference_metrics.stop()
# Finalize only on a clean exit — a crashed run must not be marked
# completed; the platform run's atexit hook marks it failed instead.
await monitors.finalize()
@@ -520,7 +527,7 @@ class Orchestrator:
except asyncio.TimeoutError:
continue
# Every completed rollout — errored, filtered, or never batched — lands in the
# Every completed rollout — errored, rejected, or never batched — lands in the
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
# Train rollouts belong to the batch window currently collecting (``progress.step``),
# eval rollouts to the step whose eval triggered them.
@@ -573,9 +580,9 @@ class Orchestrator:
if config.max_steps is not None and step > config.max_steps:
self.draining = True
self.dispatcher.disable_train_scheduling()
n_cancelled = await self.dispatcher.cancel_inflight_train_rollouts()
n_cancelled = await self.dispatcher.cancel_inflight_train_episodes()
get_logger().info(
f"Draining pipeline (cancelled {n_cancelled} in-flight train rollout(s); "
f"Draining pipeline (cancelled {n_cancelled} in-flight train episode(s); "
f"any in-flight evals will complete)"
)
return
@@ -583,14 +590,14 @@ class Orchestrator:
if not batch.samples:
self.consecutive_empty_batches += 1
get_logger().warning(
f"Step {step}: empty train batch (0 of {len(batch.rollouts)} generated rollouts shipped — "
f"all errored or filtered out) "
f"(consecutive empty batches: {self.consecutive_empty_batches}/{MAX_CONSECUTIVE_EMPTY_BATCHES})"
f"Step {step}: empty train batch after {len(batch.rollouts)} finalized rollouts "
f"(consecutive empty batches: "
f"{self.consecutive_empty_batches}/{MAX_CONSECUTIVE_EMPTY_BATCHES})"
)
if self.consecutive_empty_batches >= MAX_CONSECUTIVE_EMPTY_BATCHES:
raise RuntimeError(
f"{self.consecutive_empty_batches} consecutive empty train batches — "
"check filter config (pre_batch_filters / post_batch_filters) or task difficulty."
"check algorithm credit and task difficulty."
)
return
self.consecutive_empty_batches = 0
@@ -599,7 +606,7 @@ class Orchestrator:
if effective and n_trainable / len(effective) <= 0.1:
get_logger().warning(
f"Only {n_trainable}/{len(effective)} effective rollouts are trainable "
f"({n_trainable / len(effective):.1%}) — consider reviewing task difficulty / filter config"
f"({n_trainable / len(effective):.1%}) — consider reviewing task difficulty"
)
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
@@ -646,14 +653,14 @@ class Orchestrator:
trim_process_memory()
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
# full arrival window (errored + filtered included); ``.effective`` is the clean subset.
# full arrival window (errored + rejected included); ``.effective`` is the clean subset.
metrics: dict[str, float] = {}
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
for env_name, env_pool in pool.by_env().items():
metrics |= env_pool.metrics.to_wandb(prefix=f"train/{env_name}", subset=subset)
# Progress / timing / env-share / pre-filter accounting (assembled here, not in the metrics
# Progress / timing / env-share accounting (assembled here, not in the metrics
# objects). ``num_tokens`` is over the full arrival window; the input/output breakdown is over
# the effective (shipped) subset, summing the same ``vf.Trace`` token properties the metric
# matrix reports.
@@ -679,12 +686,7 @@ class Orchestrator:
}
for env_name, env_pool in batch.rollouts.by_env().items():
metrics[f"batch/{env_name}"] = len(env_pool) / len(batch.rollouts)
if self.train_sink.pre_filter_seen > 0:
metrics["pre_filters/all/dropped_rate"] = (
self.train_sink.pre_filter_dropped / self.train_sink.pre_filter_seen
)
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
metrics |= self.train_source.metrics()
await monitors.log(metrics, step=step)
self.wait_for_policy_time = 0.0
@@ -697,7 +699,6 @@ class Orchestrator:
self.log_train_batch(batch, step=step, step_time=step_time)
self.train_sink.reset_pre_filter_stats()
self.maybe_trigger_eval(self.progress.step)
trim_process_memory()
@@ -715,11 +716,11 @@ class Orchestrator:
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
assert self.eval_envs is not None
total_rollouts = sum(
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
census = {
env_name: self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
for env_name in fired
)
get_logger().info(f"Starting evals in {', '.join(fired)} ({total_rollouts} total rollouts)")
}
get_logger().info(f"Starting evals in {', '.join(fired)} ({sum(census.values())} total rollouts)")
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
"""Pipeline view for the orchestrator's ``PeriodicLogger``. Returns
@@ -762,7 +763,7 @@ class Orchestrator:
# Unified inflight tail: total, then train/eval split, then per-env
# (only when more than one env of a kind makes the split ambiguous)
inflight_part = (
f"{inflight_train + inflight_eval} inflight rollouts (train={inflight_train}, eval={inflight_eval}"
f"{inflight_train + inflight_eval} inflight episodes (train={inflight_train}, eval={inflight_eval}"
)
if multi_train or multi_eval:
env_pairs = [(e.name, inflight_by_env.get(("train", e.name), 0)) for e in self.train_envs]
@@ -773,7 +774,7 @@ class Orchestrator:
body = train_batch_part + eval_batch_part + "; " + inflight_part
payload: dict[str, float] = {**disp_gauges, **disp_drain, **watcher_gauges}
payload: dict[str, float] = {**disp_gauges, **disp_drain, **watcher_gauges, **self.concurrency.gauges()}
if lag_stats.n > 0:
payload["event_loop_lag/min"] = lag_stats.min
payload["event_loop_lag/mean"] = lag_stats.mean
+1 -1
View File
@@ -2,7 +2,7 @@ from transformers import AutoConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.trainer.batch import build_bin_cost, prepare_batch
from prime_rl.transport.types import MicroBatch, TrainingSample
from prime_rl.transports.rollouts.types import MicroBatch, TrainingSample
from prime_rl.utils.logger import get_logger
+101 -54
View File
@@ -4,11 +4,12 @@
dispatcher producing more rollouts), then the env algorithm's
``finalize_rollout`` (rollout-local scoring + any reference I/O). Errored
and untrainable rollouts skip this.
2. ``process_group`` — filters errored rollouts, hands the trainable
2. ``process_group`` — removes errored rollouts, hands the trainable
survivors to the env algorithm's ``finalize_group`` (advantages +
per-sample wire stamping), runs the pre-batch filter pass.
3. ``process_batch`` — applies post-batch filter annotations and assembles
the trainer-bound ``TrainingSample`` list. Returns a ``TrainBatch``.
per-sample wire stamping), then asks the source curriculum whether the
result should train.
3. ``process_batch`` — assembles the trainer-bound ``TrainingSample`` list
and optionally removes zero-advantage RL payload.
``add()`` takes one episode (``list[Rollout]``) and returns
``TrainBatch | None``; group accounting counts episodes, never loose traces.
@@ -21,16 +22,18 @@ from __future__ import annotations
import asyncio
import uuid
from collections import defaultdict
from collections.abc import Callable
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.envs import TrainEnvs
from prime_rl.orchestrator.filters import RolloutFilter, apply_filters
from prime_rl.orchestrator.metrics import TrainRollouts
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import Rollout, TrainBatch
from prime_rl.transport import TrainingSample
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.utils.logger import get_logger
MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS = 10
def payload_tokens(rollout: Rollout) -> int:
"""Token cost of the rollout's trainer-bound payload — the samples built by
@@ -45,6 +48,38 @@ def payload_tokens(rollout: Rollout) -> int:
return sum(len(sample.token_ids) for sample in rollout.samples) or rollout.num_total_tokens
def _prune_zero_advantages(sample: TrainingSample) -> bool:
"""Remove zero-advantage tokens from the RL component.
Return whether the sample still carries any RL, CE, or reference-KL
component and therefore needs to be shipped.
"""
if sample.advantages is None:
return True
if sample.rl_weights is None:
rl_weights = [1.0 if trainable else 0.0 for trainable in sample.mask]
else:
rl_weights = list(sample.rl_weights)
changed = False
for index, (trainable, advantage, weight) in enumerate(
zip(sample.mask, sample.advantages, rl_weights, strict=True)
):
if trainable and advantage == 0.0 and weight != 0.0:
rl_weights[index] = 0.0
changed = True
if not changed:
return True
sample.rl_weights = rl_weights
has_rl = any(trainable and weight != 0.0 for trainable, weight in zip(sample.mask, rl_weights, strict=True))
has_ce = sample.ce_weights is not None and any(weight != 0.0 for weight in sample.ce_weights)
has_ref_kl = sample.ref_kl_weights is not None and any(weight != 0.0 for weight in sample.ref_kl_weights)
return has_rl or has_ce or has_ref_kl
class TrainSink:
"""Three-level train sink. Constructed once, fed via ``add(rollout)``."""
@@ -57,8 +92,7 @@ class TrainSink:
mm_token_type_ids_mapping: dict[int, int] | None,
batch_size: int | None,
token_batch_size: int | None,
pre_filters: list[RolloutFilter],
post_filters: list[RolloutFilter],
on_result: Callable[[list[Rollout]], bool] | None = None,
) -> None:
assert (batch_size is None) != (token_batch_size is None), (
"Exactly one of batch_size / token_batch_size must be set"
@@ -69,11 +103,10 @@ class TrainSink:
self.mm_token_type_ids_mapping = mm_token_type_ids_mapping
self.batch_size = batch_size
self.token_batch_size = token_batch_size
self.pre_filters = pre_filters
self.post_filters = post_filters
self.on_result = on_result
# Observation window for the next shipped batch: rollouts of groups
# finalized since the last ship (errored + filtered + survivors).
# finalized since the last ship (errored + rejected + admitted).
# In-progress groups stay out until they finalize.
self.pending_rollouts: TrainRollouts = TrainRollouts()
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
@@ -88,11 +121,10 @@ class TrainSink:
# runs), kept in sync on append/pop so the readiness check never
# re-sums per arrival.
self.pending_tokens: int = 0
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
self.pre_filter_seen = 0
self.pre_filter_dropped = 0
self.pre_filter_dropped_by_name: dict[str, int] = {}
# Finalized work since the most recent positive contribution, measured
# in the active batch unit.
self.zero_output_units: int = 0
self.reported_zero_output_windows: int = 0
def group_size_for(self, env_name: str) -> int:
return self.train_envs.get(env_name).config.group_size
@@ -166,8 +198,7 @@ class TrainSink:
await self.train_envs.get(rollout.env_name).algorithm.finalize_rollout(rollout)
async def process_group(self, group_id: uuid.UUID) -> None:
"""Finalize one GRPO group: drop errored rollouts, assign advantages,
run pre-batch filters, append survivors to ``pending_batch``."""
"""Finalize one group, ask its curriculum for admission, and queue it."""
group = self.pending_groups.pop(group_id, [])
self.pending_group_episodes.pop(group_id, None)
if not group:
@@ -187,6 +218,8 @@ class TrainSink:
# Untrainable traces carry no samples and must not skew the group baseline.
survivors = [r for r in survivors if r.agent.trainable]
if not survivors:
self._admit(group)
self._record_zero_output(group)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}) | dropped: no trainable survivors"
@@ -205,44 +238,65 @@ class TrainSink:
for sample in r.samples:
sample.temperatures = [temperature] * len(sample.token_ids)
if self.pre_filters:
apply_filters(self.pre_filters, survivors)
filtered_by_name: dict[str, int] = {}
num_filtered = 0
if not self._admit(group):
self._record_zero_output(group)
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}) | rejected by curriculum"
)
return
for r in survivors:
self.pre_filter_seen += 1
if r.is_filtered:
self.pre_filter_dropped += 1
num_filtered += 1
for name, hit in r.filter_results.items():
if hit:
self.pre_filter_dropped_by_name[name] = self.pre_filter_dropped_by_name.get(name, 0) + 1
filtered_by_name[name] = filtered_by_name.get(name, 0) + 1
continue
# Reset annotations so the post-batch filter pass starts clean
r.filter_results = {}
r.is_filtered = False
self.pending_batch.append(r)
if self.token_batch_size is not None:
self.pending_tokens += payload_tokens(r)
self.zero_output_units = 0
self.reported_zero_output_windows = 0
# Per-group summary. One line per finalized group; per-filter
# detection breakdown lives at debug level in ``apply_filters``
rewards = [r.reward for r in survivors]
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
filter_str = ", ".join(f"{n}={c}" for n, c in filtered_by_name.items()) if filtered_by_name else "—"
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} | "
f"rollouts={len(group)} (errored={num_errored}, filtered={num_filtered}) | "
f"reward={avg_reward:.4f} | filters: {filter_str}"
f"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
)
def _admit(self, group: list[Rollout]) -> bool:
admitted = self.on_result(group) if self.on_result is not None else True
for rollout in group:
rollout.is_admitted = admitted
return admitted
def _record_zero_output(self, group: list[Rollout]) -> None:
if self.batch_size is not None:
self.zero_output_units += len(group)
else:
payload = sum(payload_tokens(rollout) for rollout in group)
self.zero_output_units += payload or self.config.seq_len * len(group)
self._check_zero_output_budget()
def _check_zero_output_budget(self) -> None:
target = self.batch_size if self.batch_size is not None else self.token_batch_size
assert target is not None
windows = self.zero_output_units // target
if windows <= self.reported_zero_output_windows:
return
self.reported_zero_output_windows = windows
get_logger().warning(
f"No admitted train payload after {self.zero_output_units} finalized units "
f"(consecutive zero-output batch equivalents: "
f"{windows}/{MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS})"
)
if windows >= MAX_CONSECUTIVE_ZERO_OUTPUT_BATCH_EQUIVALENTS:
raise RuntimeError(
f"{windows} consecutive zero-output batch equivalents — "
"check the curriculum admission policy and task difficulty."
)
def process_batch(self) -> TrainBatch:
"""Pop a cohort off ``pending_batch`` (by rollout count when
``batch_size`` is set, by token count when ``token_batch_size`` is
set), apply post-batch filter annotations, and assemble the
trainer-bound ``TrainingSample`` list. Overflow stays for the next
batch."""
set), and assemble the trainer-bound ``TrainingSample`` list. Overflow
stays for the next batch."""
if self.batch_size is not None:
cohort = self.pending_batch[: self.batch_size]
self.pending_batch = self.pending_batch[self.batch_size :]
@@ -259,15 +313,13 @@ class TrainSink:
self.pending_batch = self.pending_batch[cut:]
self.pending_tokens -= running
if self.post_filters:
apply_filters(self.post_filters, cohort)
# Samples are pre-built by ``process_rollout``; ``process_group`` already stamped the
# advantage stream and loss routing on each sample. Filtered rollouts don't ship.
samples: list[TrainingSample] = [sample for r in cohort if not r.is_filtered for sample in r.samples]
if self.config.train.filter_zero_advantages:
for rollout in cohort:
rollout.samples = [sample for sample in rollout.samples if _prune_zero_advantages(sample)]
samples: list[TrainingSample] = [sample for rollout in cohort for sample in rollout.samples]
# ``rollouts`` is the observation window — every rollout of every group finalized since the
# last ship (errored + filtered + survivors) — while ``samples`` is the shipped cohort's
# last ship (errored + rejected + admitted) — while ``samples`` is the shipped cohort's
# trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive the clean subset +
# metric views on demand. Reset the window only when the batch actually ships (non-empty
# samples) — an empty batch is dropped unlogged by the orchestrator, so keep accumulating its
@@ -276,8 +328,3 @@ class TrainSink:
if samples:
self.pending_rollouts = TrainRollouts()
return TrainBatch(rollouts=rollouts, samples=samples)
def reset_pre_filter_stats(self) -> None:
self.pre_filter_seen = 0
self.pre_filter_dropped = 0
self.pre_filter_dropped_by_name.clear()
+57 -86
View File
@@ -1,35 +1,20 @@
"""TrainSource: weighted round-robin across train envs, infinite pull.
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
per env). An env serves the tasks the orchestrator loaded client-side: a
finite one as a shuffled table (reshuffled with ``seed=epoch`` on cursor
exhaustion), an infinite one (``num_tasks is None``) straight off its
generator — every pull is a fresh task and there are no epochs to shuffle."""
"""Training source selection and curriculum lifecycle."""
from __future__ import annotations
import random
from collections.abc import Iterator
import verifiers.v1 as vf
from collections import defaultdict
from typing import TYPE_CHECKING, Any
from prime_rl.orchestrator.curriculum import Curriculum
from prime_rl.orchestrator.envs import TrainEnvs
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
class TrainSource:
"""``next_example()`` picks a weighted-RR env and returns its next
example. Returned dicts carry ``env_name`` + ``task``, whose data is
shipped to the env server at dispatch.
The data position round-trips through a checkpoint via ``state_dict()``
/ ``load_state_dict()``: per-env ``{epoch, cursor}`` plus the env-choice
RNG state, making the dispatch sequence reproducible across resumes. For
a finite env, epochs are 1-indexed and seed that epoch's shuffle; for an
infinite env the epoch stays 1 and the cursor counts generator pulls,
replayed on restore by fast-forwarding the generator (exact iff it's
deterministic). Cursors advance at dispatch time (ahead of shipped
batches), so a resume skips the tasks that were in flight at checkpoint
time."""
"""Mix train envs and host one user-authored curriculum per env."""
def __init__(self, train_envs: TrainEnvs) -> None:
self.rng = random.Random(42)
@@ -37,73 +22,59 @@ class TrainSource:
if not self.envs:
raise ValueError("TrainSource needs at least one train env")
# A finite env's example table in canonical order (each epoch's shuffle
# starts from this); ``None`` for an infinite env, whose generator
# (``self.iters``) is pulled per example.
self.base_rows: dict[str, list[dict] | None] = {}
self.examples: dict[str, list[dict] | None] = {}
self.iters: dict[str, Iterator[vf.Task]] = {}
self.epochs: dict[str, int] = {}
self.cursors: dict[str, int] = {}
self.curricula: dict[str, Curriculum] = {}
for env in self.envs:
assert env.tasks is not None, f"env {env.name} not started"
if env.num_tasks is None: # infinite: pull the generator per example
rows: list[dict] | None = None
self.iters[env.name] = env.tasks
else:
rows = [{"task": task, "env_name": env.name} for task in env.tasks]
self.base_rows[env.name] = rows
self.epochs[env.name] = 1
self.cursors[env.name] = 0
self.examples[env.name] = self._shuffle(env.name)
if env.tasks is None:
raise RuntimeError(f"env {env.name} not started")
tasks = env.tasks if env.num_tasks is None else list(env.tasks)
self.curricula[env.name] = Curriculum(env.config.curriculum, tasks)
self.env_names = [e.name for e in self.envs]
self.weights: list[float] = [float(e.config.ratio) for e in self.envs]
self.env_names = [env.name for env in self.envs]
self.weights = [float(env.config.ratio) for env in self.envs]
self._admitted: dict[str, int] = defaultdict(int)
self._rejected: dict[str, int] = defaultdict(int)
def _shuffle(self, env_name: str) -> list[dict] | None:
"""The env's example table shuffled for its current epoch — a pure
function of (canonical order, epoch), so a restored position replays
the exact epoch permutation."""
rows = self.base_rows[env_name]
if rows is None:
return None
rows = rows.copy()
random.Random(self.epochs[env_name]).shuffle(rows)
return rows
def state_dict(self) -> dict:
"""Env-choice RNG state + per-env ``{epoch, cursor}``."""
def next_example(self) -> dict[str, Any]:
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
return {
"rng": self.rng.getstate(),
"envs": {name: {"epoch": self.epochs[name], "cursor": self.cursors[name]} for name in self.epochs},
"env_name": env_name,
"task": next(self.curricula[env_name].sampler),
}
def load_state_dict(self, state_dict: dict) -> None:
self.rng.setstate(state_dict["rng"])
for name, position in state_dict["envs"].items():
if name not in self.base_rows:
continue
self.epochs[name] = position["epoch"]
self.cursors[name] = position["cursor"]
if self.base_rows[name] is None:
for _ in range(position["cursor"]):
next(self.iters[name])
else:
self.examples[name] = self._shuffle(name)
def on_result(self, group: list[Rollout]) -> bool:
"""Report a finalized group and return whether it should train."""
if not group:
raise ValueError("Cannot report an empty rollout group")
env_name = group[0].env_name
admitted = self.curricula[env_name].on_result(group)
if not isinstance(admitted, bool):
raise TypeError(f"Curriculum.on_result() must return bool, got {type(admitted).__name__}")
if admitted:
self._admitted[env_name] += 1
else:
self._rejected[env_name] += 1
return admitted
def next_example(self) -> dict | None:
env_name = self.rng.choices(self.env_names, weights=self.weights, k=1)[0]
rows = self.examples[env_name]
cursor = self.cursors[env_name]
if rows is None: # infinite env: pull the next generated task
task = next(self.iters[env_name])
self.cursors[env_name] = cursor + 1
return {"task": task, "env_name": env_name}
if cursor >= len(rows):
self.epochs[env_name] += 1
rows = self._shuffle(env_name)
self.examples[env_name] = rows
cursor = 0
example = rows[cursor]
self.cursors[env_name] = cursor + 1
return example
def metrics(self) -> dict[str, float]:
metrics: dict[str, float] = {}
for env_name, curriculum in self.curricula.items():
admitted = self._admitted.pop(env_name, 0)
rejected = self._rejected.pop(env_name, 0)
total = admitted + rejected
if total:
metrics[f"curriculum/{env_name}/admission_rate"] = admitted / total
metrics |= {f"curriculum/{env_name}/{name}": float(value) for name, value in curriculum.metrics().items()}
return metrics
def state_dict(self) -> dict[str, Any]:
return {
"rng": self.rng.getstate(),
"envs": {name: curriculum.state_dict() for name, curriculum in self.curricula.items()},
}
def load_state_dict(self, state_dict: dict[str, Any]) -> None:
self.rng.setstate(state_dict["rng"])
for name, curriculum_state in state_dict["envs"].items():
curriculum = self.curricula.get(name)
if curriculum is not None:
curriculum.load_state_dict(curriculum_state)
+2 -2
View File
@@ -20,8 +20,8 @@ from collections.abc import Iterator
import numpy as np
import verifiers.v1 as vf
from prime_rl.transport import TrainingSample
from prime_rl.transport.types import EncodedTensor, RoutedExperts
from prime_rl.transports.rollouts import TrainingSample
from prime_rl.transports.rollouts.types import EncodedTensor, RoutedExperts
from prime_rl.utils.logger import get_logger
+8 -8
View File
@@ -10,7 +10,7 @@ import verifiers.v1 as vf
from pydantic import ConfigDict, Field
from verifiers.v1.task import DataT
from prime_rl.transport import TrainingSample
from prime_rl.transports.rollouts import TrainingSample
if TYPE_CHECKING:
from prime_rl.orchestrator.metrics import EvalRollouts, TrainRollouts
@@ -39,7 +39,7 @@ RolloutKind = Literal["train", "eval"]
@dataclass
class InflightRollout:
class InflightEpisode:
"""Per-task scheduling state in the dispatcher; one entry per in-flight
``run`` task."""
@@ -50,6 +50,8 @@ class InflightRollout:
client_config: vf.ClientConfig | None = None
off_policy_steps: int = 0
eval_step: int | None = None
started_at: float = 0.0
"""``time.monotonic()`` at dispatch; feeds episode-duration estimates."""
@dataclass
@@ -96,11 +98,9 @@ class Rollout(vf.Trace[DataT], Generic[DataT]):
samples: list[TrainingSample] = Field(default_factory=list, exclude=True)
# Per-token rl advantage stream, full-length-N (= len(token_ids)) per
# sample, concatenated across the rollout's samples in order; 0.0 on
# non-trainable positions. None = no credit assigned (advantage-based
# filters skip it; the wire ships no advantage stream).
# non-trainable positions. None means no credit was assigned.
advantages: list[float] | None = Field(default=None, exclude=True)
is_filtered: bool = Field(default=False, exclude=True)
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
is_admitted: bool = Field(default=True, exclude=True)
eval_step: int | None = Field(default=None, exclude=True)
def assign_advantages(self, values: float | list[float]) -> None:
@@ -140,9 +140,9 @@ class Rollout(vf.Trace[DataT], Generic[DataT]):
@dataclass
class TrainBatch:
"""``rollouts`` is the observation window since the last ship — every rollout of every group
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
finalized in that span (errored + rejected included; rollouts of still-incomplete groups wait
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
trainer-bound payload from the admitted cohort — an empty list means nothing
ships, which would stall the trainer. Trainable counts derive from ``rollouts.effective``
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
+1 -1
View File
@@ -11,7 +11,7 @@ from modelexpress import p2p_pb2
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.types import Policy, VersionObserver
from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.utils.async_utils import safe_cancel
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import format_time, get_logger

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