Compare commits

...
Author SHA1 Message Date
bc9e186963 feat: adaptive concurrency for online evals (#3309)
* feat: first-class evaluator with adaptive concurrency

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

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

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

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

* fix: stop evaluator collectors before monitor finalize

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

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

* feat: fail fast when adaptive concurrency has no metrics

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

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

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

* refactor: rename evaluator command and configs to evals

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

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

* refactor: drop the Evaluator name entirely

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

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

* docs: drop the standalone evals section for now

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

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

* fix: reject skip_first_step on standalone evals

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

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

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

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

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

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

initial_inflight must not exceed max_inflight.

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

---------

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

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

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

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

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

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

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

* docs: clock adaptive-concurrency updates to steps

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

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

* docs: spec ConcurrencyController abstraction + config

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

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

* docs: adaptive concurrency always on

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

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

* feat: adaptive rollout concurrency controller

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

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

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

* chore: backoff naming + config comment fixes

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

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

* feat: add no-eval concurrency e2e config

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

* feat: frozen_steps knob + 50-step e2e configs

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

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

* docs: motivate higher frozen_steps values

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

* chore: rename concurrency e2e configs

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

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

* chore: migrate example configs to initial_inflight

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

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

* chore: use config blocks for concurrency in examples

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

* chore: raise max_off_policy_steps in hendrycks configs

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

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

* chore: slash-namespace dispatcher gauge keys

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

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

* chore: drop groups-in-flight gauge

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

* feat: derive initial cap from engine max context

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

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

* feat: richer concurrency logging + wandb inflight mirror

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

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

* feat: show inflight vs cap in the wandb overview

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

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

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

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

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

* fix: apply concurrency bootstrap only once

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

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

* chore: say episodes for in-flight units

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

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

* chore: drop cap series from overview inflight panel

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

* chore: fix stale overview comment

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

* fix: step-clock the cost EWMA folding

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

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

* feat: interpolate eval and train cost mixes

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

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

* feat: 512-episode bias-corrected cost EWMA

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

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

* feat: default frozen_steps to 1

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

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

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

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

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

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

* chore: simplify frozen_steps docstring

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

* chore: cap hendrycks e2e configs at 1024 inflight

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

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

* feat: allow SignSGD with full optimizer offload

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

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

* feat: queue-overload HARD cut for agentic rollouts

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

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

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

* feat: shed youngest episodes on overload cut

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

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

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

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

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

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

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

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

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

* feat: floor the cost estimate with measured request cost

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

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

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

* feat: size-bias the measured request cost

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

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

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

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

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

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

* feat: early growth brake and kappa ceiling memory

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

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

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

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

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

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

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

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

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

* feat: SOFT signal on high KV usage

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

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

* chore: lower KV-usage SOFT threshold to 0.7

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

* feat: shed on overload now that rollout abort propagates

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

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

* feat: proportional kv-headroom trim

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

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

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

* fix: kv-headroom trims re-derive kappa

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

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

* chore: address PR review comments

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

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

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

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

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

* feat: hysteresis for kv-headroom trims

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

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

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

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

* feat!: reduce the controller to measured AIMD

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

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

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

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

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

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

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

* feat: min_inflight escape hatch

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

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

* chore: address second review round

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

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

* feat: revamp the concurrency e2e config matrix

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

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

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

* chore: slurm blocks for the hendrycks e2e configs

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

* fix: pin flash_attention_2 for the hendrycks e2e configs

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

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

* chore: drop the initial-low e2e variants

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

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

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

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

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

* fix: pin the hendrycks KV budget via num_gpu_blocks_override

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

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

* feat: min_inflight is the only cap floor

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

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

* fix: start hendrycks-initial-high at 700

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

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

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

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

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

* fix: hold the drain latch until the engines settle

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

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

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

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

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

* Refund admission burst budget on episode completion

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

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

* Fix four controller/dispatcher bugs from review

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

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

* Drop cluster-specific node exclude from e2e configs

* Budget hendrycks e2e concurrency for the sandbox gateway

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

* Read KV capacity from kv_cache_size_tokens

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

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

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

* Remove concurrency debug configs

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

* Use fp8_per_block online quantization in the GLM-Air example

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

* Guard None raw tokens in logprobs detokenization

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

* Revert "Guard None raw tokens in logprobs detokenization"

This reverts commit 0c1b5d4992eb99f1ea4c0a7c6a999daeca5cc95c.

* Order concurrency fields initial, min, max

* Route GLM-Air FP8 through DeepGEMM kernels

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

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

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

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

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

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

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

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

* fix: stop metrics collector before finalizing monitors

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

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

* Bump verifiers to a3188c06

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

* Fix four review findings; drop unused glm4_moe kernel converter

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

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

* Explain adaptive concurrency by intuition in the docs

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

* Drop unrelated changes from the branch

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

* Address review: config defaults and small cleanups

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

* Raise max_inflight in examples exceeding the new default ceiling

* a few minor tweaks

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

* Update lockfile for verifiers 0.3.1.dev57

* chore: cap CI RL runs at 512 inflight

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

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

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

* Bump verifiers to main (rollout-abort merged)

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

---------

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

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

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 17:08:50 -07:00
106 changed files with 1903 additions and 779 deletions
+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
@@ -19,6 +19,9 @@ lr = 1e-5
batch_size = 128
group_size = 8
[orchestrator.concurrency]
max_inflight = 128
[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 = 128
[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 = 128
[orchestrator.model.lora]
name = "r8-1e-4"
@@ -22,6 +22,9 @@ impl = "custom"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[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 = 128
[orchestrator.algo]
type = "opd"
@@ -24,6 +24,9 @@ name = "ci-rl-sft"
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.algo]
type = "sft"
@@ -22,6 +22,9 @@ lr = 3e-6
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[orchestrator.train.sampling]
max_completion_tokens = 128
@@ -19,6 +19,9 @@ lr = 3e-6
batch_size = 128
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[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 = 128
[[orchestrator.train.source]]
name = "alphabet-sort"
@@ -18,6 +18,9 @@ batch_size = 512
group_size = 8
seq_len = 8192
[orchestrator.concurrency]
max_inflight = 128
[[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 = 128
[[orchestrator.train.source]]
name = "reverse-text"
+4 -1
View File
@@ -17,7 +17,10 @@ name = "Qwen/Qwen3-4B-Instruct-2507"
[orchestrator]
batch_size = 512
group_size = 16
oversampling_factor = 2.0
[orchestrator.concurrency]
initial_inflight = 128
max_inflight = 128
[[orchestrator.train.source]]
name = "wiki-search"
+3
View File
@@ -18,6 +18,9 @@ name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
batch_size = 512
group_size = 16
[orchestrator.concurrency]
max_inflight = 128
[[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 = 128
[orchestrator.train.sampling]
max_completion_tokens = 64
+1 -1
+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
+4 -4
View File
@@ -204,17 +204,17 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evaluator` process next to the trainer. The handoff is the filesystem, not NCCL: the trainer writes an HF weight checkpoint at every step an eval env is due (in addition to `ckpt.interval`), and the evaluator watches `weights/step_{n}`, points the inference server at each stable checkpoint (`/update_weights` reload from disk), and runs the due envs against it — sequentially per checkpoint, so every epoch measures exactly one policy version. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final checkpoint always fires every env.
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. 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 evals process 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. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node (Decoupled Trainer and Inference Pool)
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two independent SLURM jobs**. `deployment.num_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evaluator:
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two 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 evals process:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evaluator)
num_infer_nodes = 1 # eval job (inference pool + evals)
[inference.vllm]
tensor_parallel_size = 8
@@ -223,7 +223,7 @@ tensor_parallel_size = 8
job_name = "my-run"
```
The only coupling is weight checkpoints on the shared filesystem, so the jobs' lifetimes are independent: when training finishes, the trainer job exits and releases its nodes even while evals are still running; the eval job keeps draining pending checkpoints and exits after evaluating the final one (`max_steps` — without it the eval job never sees a final checkpoint and holds its allocation until walltime). Trainer and evaluator log to a single shared W&B run across both jobs — the trainer creates it, the evaluator finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
The 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 evals log to a single shared W&B run across both jobs — the trainer creates it, the evals process finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
### SFT-Specific Knobs
+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 -1
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"
+4 -1
View File
@@ -45,7 +45,10 @@ weight_decay = 0.01
[orchestrator]
batch_size = 2048
oversampling_factor = 2
[orchestrator.concurrency]
initial_inflight = 4096
max_inflight = 4096
[[orchestrator.train.source]]
name = "swe"
+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"
+3 -1
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"
+44
View File
@@ -0,0 +1,44 @@
# Standalone SWE evals: SWE-bench Verified + Terminal-Bench 2, one epoch each,
# against DeepSeek V4 Flash on Prime Inference.
#
# export PRIME_API_KEY=<your Prime Inference key>
# uv run evals @ examples/evals/swe.toml
#
# The tasksets run in prime sandboxes (the default runtime), so the key also
# authenticates sandbox creation. External API endpoints expose no vLLM
# /metrics, so adaptive concurrency has no load signal - the band must be
# pinned (min_inflight = max_inflight) or the evals process refuses to start.
model = "deepseek/deepseek-v4-flash"
[eval.client]
base_url = "https://api.pinference.ai/api/v1"
api_key_var = "PRIME_API_KEY"
[eval.concurrency]
min_inflight = 32
max_inflight = 32
[[eval.source]]
name = "swebench-verified"
[eval.source.env.taskset]
id = "swebench-verified"
[eval.source.env.agent.harness]
id = "bash"
[eval.source.env.agent.timeout]
rollout = 3600
[[eval.source]]
name = "terminal-bench-2"
[eval.source.env.taskset]
id = "terminal-bench-2"
[eval.source.env.agent.harness]
id = "bash"
[eval.source.env.agent.timeout]
rollout = 3600
@@ -0,0 +1,109 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import ConcurrencyConfig, EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.utils.config import BaseConfig
class EvalsEvalConfig(EvalConfig):
"""Evals against a live inference server. Extends the orchestrator ``EvalConfig``
(sources, sampling, intervals) with the client of the inference deployment and
evals-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: sources with an explicit
``serve.address`` are externally managed; the evals process spawns an env server at
the derived address for every other source."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class OnlineConfig(BaseConfig):
"""Checkpoint-driven online evals: watch a weights directory for new HF checkpoints
and evaluate each eligible one. Without this block the evals process runs every eval
source once against the weights the inference server currently serves, then exits."""
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``."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evals process exits after processing it. If None, the evals process
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
class EvalsConfig(BaseConfig):
"""``uv run evals``: run the configured evals against a live inference server.
Standalone (no ``[online]``), one epoch of every eval source runs against the
served weights and the evals process exits. With ``[online]``, the evals process watches a
weights directory for new HF checkpoints, points the inference server at each one
(``/update_weights`` from disk), and runs the configured evals against the updated
weights — the ``sft`` launcher writes this config; it also works 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: EvalsEvalConfig
"""Eval sources, sampling, intervals, concurrency, and the inference client."""
online: OnlineConfig | None = None
"""Checkpoint watching (``[online]``). None runs the evals once and exits."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer for online evals."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_weights_dir(self):
if self.online is not None and self.online.weights_dir is None:
self.online.weights_dir = self.output_dir / "weights"
return self
@model_validator(mode="after")
def validate_skip_first_step_is_online_only(self):
"""``skip_first_step`` gates the base-model eval between checkpoints; a
standalone run has only that one epoch, so skipping it would exit
successfully without evaluating anything."""
if self.online is None and self.eval.skip_first_step:
raise ValueError(
"eval.skip_first_step only applies to online evals - a standalone run "
"would skip its only eval epoch. Remove it or add an [online] block."
)
return self
@@ -1,84 +0,0 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.utils.config import BaseConfig
class OnlineEvalConfig(EvalConfig):
"""Online evals against a live inference server, driven by weight checkpoints
on disk. Extends the orchestrator ``EvalConfig`` (sources, sampling, intervals)
with the client of the inference deployment and evaluator-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
max_inflight_episodes: int = Field(128, ge=1)
"""Maximum eval episodes in flight — one episode is one agent run against an env server."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: the launcher binds env
servers at exactly these addresses and the evaluator connects to them."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class EvaluatorConfig(BaseConfig):
"""``uv run evaluator``: watch a weights directory for new HF checkpoints, point
the inference server at each one (``/update_weights`` from disk), and run the
configured evals against the updated weights. The ``sft`` launcher writes this
config; it can also be run standalone against any trainer that writes
``weights/step_{n}`` HF checkpoints with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across checkpoint reloads (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: OnlineEvalConfig
"""Eval sources, sampling, intervals, and the inference client."""
weights_dir: Path | None = None
"""Directory to watch for ``step_{n}`` HF weight checkpoints. The ``sft`` launcher
fills it from ``ckpt.output_dir`` when checkpoints are redirected to another volume;
defaults to ``<output_dir>/weights``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evaluator exits after processing it. If None, the evaluator
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_weights_dir(self):
if self.weights_dir is None:
self.weights_dir = self.output_dir / "weights"
return self
@@ -420,6 +420,30 @@ WeightBroadcastConfig: TypeAlias = Annotated[
]
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
in-flight episode cap from engine KV capacity and learned per-env episode
costs; these fields only bound and seed it."""
initial_inflight: int | None = Field(None, ge=1)
"""Optional initial in-flight episodes to start from. Set it when a good value is known to skip the initial ramp; otherwise auto-derive a pessimistic bound at runtime."""
min_inflight: int = Field(1, ge=1)
"""Minimum number of in-flight episodes. Set ``min_inflight = max_inflight`` to recover fixed concurrency."""
max_inflight: int | None = Field(1024, ge=1)
"""Maximum number of in-flight episodes. Set it to avoid runaway concurrency, especially to limit other external resources (e.g. sandboxes). None removes the ceiling."""
@model_validator(mode="after")
def validate_bounds(self):
if self.max_inflight is not None:
if self.initial_inflight is not None and self.initial_inflight > self.max_inflight:
raise ValueError("concurrency.initial_inflight must not exceed concurrency.max_inflight")
if self.min_inflight > self.max_inflight:
raise ValueError("concurrency.min_inflight must not exceed concurrency.max_inflight")
return self
class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
@@ -455,7 +479,7 @@ class OrchestratorConfig(BaseConfig):
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
collect_inference_metrics: bool = True
"""Collect inference-server metrics (requires wandb)."""
"""Mirror inference-server metrics to W&B (requires wandb). The ``/metrics`` poll itself always runs — it feeds the concurrency controller."""
inference_metrics_roles: list[Literal["prefill", "decode"]] | None = None
"""Role for each policy admin client when collecting P/D inference metrics."""
@@ -487,11 +511,8 @@ class OrchestratorConfig(BaseConfig):
token_batch_size: int | None = Field(None, ge=1)
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
oversampling_factor: float | None = Field(None, gt=0)
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_episodes`` from ``batch_size`` when ``max_inflight_episodes`` is unset. Values below 1.0 intentionally cap in-flight episode capacity below ``batch_size``."""
max_inflight_episodes: int | None = Field(None, ge=1)
"""Maximum number of episodes kept in-flight — one episode is one agent run at a time, whatever the env's agents are. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
concurrency: ConcurrencyConfig = ConcurrencyConfig()
"""Adaptive in-flight concurrency control (``[orchestrator.concurrency]``)."""
group_size: int = Field(1, ge=1)
"""Output sequences returned per example during training."""
@@ -605,29 +626,13 @@ class OrchestratorConfig(BaseConfig):
if not has_rollout_batch and not has_token_batch:
self.batch_size = 128
if has_token_batch:
if self.oversampling_factor is not None:
raise ValueError("oversampling_factor can only be set when batch_size is set")
if self.max_inflight_episodes is None:
raise ValueError("max_inflight_episodes must be set when token_batch_size is set")
else:
assert self.batch_size is not None
if self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
resolved_max_inflight_episodes = max(
self.group_size,
int(self.batch_size * oversampling_factor),
)
if self.max_inflight_episodes is not None and self.oversampling_factor is not None:
expected_max_inflight_episodes = resolved_max_inflight_episodes
if self.max_inflight_episodes != expected_max_inflight_episodes:
raise ValueError("max_inflight_episodes conflicts with oversampling_factor * batch_size")
if self.max_inflight_episodes is None:
self.max_inflight_episodes = resolved_max_inflight_episodes
if self.batch_size is not None and self.batch_size % self.group_size != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
if self.max_inflight_episodes is not None and self.max_inflight_episodes < self.group_size:
raise ValueError("max_inflight_episodes must be at least the number of rollouts per example")
for field in ("max_inflight", "initial_inflight"):
value = getattr(self.concurrency, field)
if value is not None and value < self.group_size:
raise ValueError(f"concurrency.{field} must be at least the number of rollouts per example")
# Propagate the top-level ``group_size`` into each train env that didn't set its own.
for env_cfg in self.train.source:
@@ -8,7 +8,7 @@ from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.evaluator import OnlineEvalConfig
from prime_rl.configs.evals import EvalsEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
@@ -195,7 +195,7 @@ class SFTConfig(BaseConfig):
val: SFTValConfig | None = None
"""Validation configuration. If None, no validation runs."""
eval: OnlineEvalConfig | None = None
eval: EvalsEvalConfig | None = None
"""Online evaluation configuration: rollout-based evals against a live inference
server that reloads the trainer's HF weight checkpoints from disk. If None, no
online evals run."""
@@ -319,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")
@@ -362,18 +362,18 @@ class SFTConfig(BaseConfig):
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 "
"evals 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.
# inference pool (one engine per DP rank behind a router) plus the evals process.
if self.inference is None:
raise ValueError(
"Multi-node online evals require an [inference] block - the launcher submits "
"a dedicated SLURM job running the inference pool and the evaluator."
"a dedicated SLURM job running the inference pool and the evals process."
)
if self.deployment.num_infer_nodes < 1:
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
@@ -398,7 +398,7 @@ class SFTConfig(BaseConfig):
)
if self.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evaluator never sees a final checkpoint, "
"Online evals without max_steps: the evals process never sees a final checkpoint, "
"so the eval SLURM job holds its allocation until its walltime.",
stacklevel=2,
)
@@ -411,7 +411,7 @@ class SFTConfig(BaseConfig):
"Online evals are configured without an [inference] block - the launcher will not "
f"start an inference server. Make sure one is running at eval.client.base_url "
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
"otherwise the evaluator will hang waiting for it. If a router fronts the "
"otherwise the evals process will hang waiting for it. If a router fronts the "
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
"(pause/update_weights/resume) must bypass the router.",
stacklevel=2,
@@ -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")
+1 -1
View File
@@ -53,7 +53,7 @@ sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evaluator = "prime_rl.entrypoints.evaluator:main"
evals = "prime_rl.entrypoints.evals:main"
env-server = "prime_rl.entrypoints.env_server:main"
[project.entry-points."vllm.general_plugins"]
+3 -3
View File
@@ -66,7 +66,7 @@ After a restart, verify all processes are back up and progress resumed before th
{run_dir}/logs/latest/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── evaluator.log # SFT online-eval evaluator stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evaluator.log)
├── evals.log # SFT online-eval evals stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evals.log)
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -82,7 +82,7 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
Scan for problems:
```bash
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evaluator,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evals,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
```
@@ -130,7 +130,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:
+44 -2
View File
@@ -1,6 +1,6 @@
---
name: start-run
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
description: How to launch prime-rl training runs — the `rl`, `sft`, `inference`, and `evals` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
---
# Start a run
@@ -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
@@ -87,6 +88,46 @@ curl http://localhost:8000/v1/chat/completions \
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
- SLURM: single-node, multi-node, and disaggregated deployments
## `evals` — multi-env evals
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`weights_dir`, `max_steps`, `resume_step`): watch the weights dir for stable `step_{n}` HF checkpoints and evaluate each — the `sft` launcher writes this config for online evals.
```bash
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
uv run evals @ eval.toml
```
Minimal standalone `eval.toml`:
```toml
model = "Qwen/Qwen3-4B"
[eval.client]
base_url = "http://localhost:8000/v1"
[eval.concurrency] # adaptive; same controller as [orchestrator.concurrency]
min_inflight = 8
max_inflight = 128
[[eval.source]]
num_examples = 32 # always cap eval size for smokes
group_size = 4
[eval.source.env.taskset]
id = "aime25"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
```
- Env servers: spawned by the evals process, one per source without an explicit `serve.address`, at `tcp://127.0.0.1:<eval.env_server_base_port + index>`; logs at `{output_dir}/logs/envs/eval/{name}.log`.
- External inference APIs (no vLLM `/metrics`, e.g. Prime Inference) have no load signal for adaptive concurrency: the startup `/metrics` probe fails fast unless the band is pinned (`min_inflight = max_inflight`). Full example: `examples/evals/swe.toml` (SWE-bench Verified + Terminal-Bench 2 on Prime Inference, `agent.timeout.rollout = 3600`).
- Config: `EvalsConfig` (`packages/prime-rl-configs/src/prime_rl/configs/evals.py`)
- Entrypoint: `src/prime_rl/entrypoints/evals.py` (implementation: `src/prime_rl/evals/evals.py`)
## Summary
| Command | Purpose | Typical use |
@@ -94,6 +135,7 @@ curl http://localhost:8000/v1/chat/completions \
| `rl` | Full RL pipeline | Production RL training |
| `sft` | Supervised fine-tuning | SFT and hard-distill |
| `inference` | vLLM server | Standalone serving / debugging |
| `evals` | Multi-env evals | Standalone evals / SFT online evals |
## Key paths
+24
View File
@@ -0,0 +1,24 @@
"""Lightweight launcher for the online evals.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evals --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.evals.evals``.
"""
import asyncio
from prime_rl.configs.evals import EvalsConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evals")
config = cli(EvalsConfig)
from prime_rl.evals.evals import run_evals
asyncio.run(run_evals(config))
if __name__ == "__main__":
main()
-24
View File
@@ -1,24 +0,0 @@
"""Lightweight launcher for the online evaluator.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evaluator --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.orchestrator.evaluator``.
"""
import asyncio
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evaluator")
config = cli(EvaluatorConfig)
from prime_rl.orchestrator.evaluator import run_evaluator
asyncio.run(run_evaluator(config))
if __name__ == "__main__":
main()
+44 -36
View File
@@ -9,7 +9,7 @@ from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.configs.evals import EvalsConfig, OnlineConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
@@ -46,7 +46,7 @@ EVAL_SBATCH = "eval.sbatch"
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
INFERENCE_CONFIG = "inference.json"
EVALUATOR_CONFIG = "evaluator.json"
EVALS_CONFIG = "evals.json"
ENVS_DIR = "envs"
@@ -80,16 +80,24 @@ def resolve_resume_step(config: SFTConfig) -> int | None:
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_evaluator_config(config: SFTConfig) -> EvaluatorConfig:
"""Derive the evaluator subconfig from the resolved SFT config."""
def build_evals_config(config: SFTConfig) -> EvalsConfig:
"""Derive the evals subconfig from the resolved SFT config. The launcher
spawns the env servers itself, so each source's derived address is stamped in,
marking it externally managed for the evals process."""
assert config.eval is not None
return EvaluatorConfig(
eval_config = config.eval.model_copy(deep=True)
addresses = config.eval.env_addresses
for source in eval_config.source:
source.serve.address = addresses[("eval", source.resolved_name)]
return EvalsConfig(
model=config.model.name,
eval=config.eval,
weights_dir=get_weights_dir(get_ckpt_base(config)),
eval=eval_config,
online=OnlineConfig(
weights_dir=get_weights_dir(get_ckpt_base(config)),
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
),
output_dir=config.run_dir,
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
)
@@ -103,7 +111,7 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
"""Write the inference, evaluator, and env-server configs for online evals."""
"""Write the inference, evals, and env-server configs for online evals."""
config_dir.mkdir(parents=True, exist_ok=True)
if config.inference is not None:
@@ -116,11 +124,11 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
with open(config_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
with open(config_dir / EVALUATOR_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evaluator_config(config)), f, indent=2)
with open(config_dir / EVALS_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evals_config(config)), f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
# binds at the source's deterministic address, where the evaluator connects.
# binds at the source's deterministic address, where the evals process connects.
for source, address in eval_env_servers(config):
env_dir = config_dir / ENVS_DIR / "eval"
env_dir.mkdir(parents=True, exist_ok=True)
@@ -176,7 +184,7 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path,
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
"""Write the SLURM script for the decoupled online-eval job (inference pool +
env servers + evaluator) to disk."""
env servers + evals) to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
@@ -199,7 +207,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
**config.env_vars,
**config.inference.env_vars,
}
evaluator_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
evals_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
script = template.render(
**config.slurm.template_vars,
@@ -214,7 +222,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
inference_env_vars=inference_env_vars,
evaluator_env_vars=evaluator_env_vars,
evals_env_vars=evals_env_vars,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
prl_run_id=prl_run_id,
run_name=config.run.name,
@@ -226,7 +234,7 @@ def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Pa
def sft_slurm(config: SFTConfig):
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
trainer and the eval deployment (inference pool + evaluator) are two independent
trainer and the eval deployment (inference pool + evals) 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."""
@@ -250,7 +258,7 @@ def sft_slurm(config: SFTConfig):
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
# Trainer and evaluator processes log to a single shared W&B run across both jobs,
# Trainer and evals processes log to a single shared W&B run across both jobs,
# keyed by the launcher's run id.
prl_run_id: str | None = None
if decoupled_eval and config.monitors.wandb is not None:
@@ -261,8 +269,8 @@ def sft_slurm(config: SFTConfig):
logger.info(f"Wrote SLURM script to {script_path}")
# The trainer job is submitted first and the eval job depends on it having started:
# the trainer creates the shared W&B run, and the evaluator's joiner init only
# retries for a bounded window — starting the evaluator while the trainer job pends
# the trainer creates the shared W&B run, and the evals process's joiner init only
# retries for a bounded window — starting the evals process while the trainer job pends
# would crash it at wandb init.
script_paths = [script_path]
if decoupled_eval:
@@ -283,7 +291,7 @@ def sft_slurm(config: SFTConfig):
# The eval job logs at stable (non-attempt) paths under the run dir.
log_message += "\n" + format_log_message(
log_dir=get_log_dir(config.run_dir),
evaluator=True,
evals=True,
inference=True,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
num_infer_nodes=config.deployment.num_infer_nodes,
@@ -292,7 +300,7 @@ def sft_slurm(config: SFTConfig):
if config.dry_run:
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."
"\n\nSubmit the trainer job first — the evals process joins the W&B run the trainer creates."
if decoupled_eval
else ""
)
@@ -360,17 +368,17 @@ def sft_local(config: SFTConfig):
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
# Trainer and evaluator log to a single shared W&B run whose id ($WANDB_RUN_ID)
# Trainer and evals log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
wandb_shared_env: dict[str, str] = {}
if config.eval is not None:
# The trainer creates the run; the evaluator (which drains its final evals
# The trainer creates the run; the evals process (which drains its final evals
# after the trainer exits) finalizes it.
wandb_shared_env = {
"WANDB_SHARED_MODE": "1",
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
"WANDB_SHARED_PRIMARY": "trainer",
"WANDB_SHARED_FINISHER": "evaluator",
"WANDB_SHARED_FINISHER": "evals",
"WANDB_PROGRAM": "uv run sft",
"WANDB_ARGS": json.dumps(sys.argv),
}
@@ -419,7 +427,7 @@ def sft_local(config: SFTConfig):
log_path=log_dir / "inference.log",
)
# Start one env server per eval source. The evaluator connects to each source's
# Start one env server per eval source. The evals process connects to each source's
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
name = source.resolved_name
@@ -432,19 +440,19 @@ def sft_local(config: SFTConfig):
)
if config.eval is not None:
logger.info("Starting evaluator process")
logger.info("Starting evals process")
start_process(
"evaluator",
["evaluator", "@", (config_dir / EVALUATOR_CONFIG).as_posix()],
"evals",
["evals", "@", (config_dir / EVALS_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evaluator",
"WANDB_SHARED_LABEL": "evals",
},
log_path=log_dir / "evaluator.log",
log_path=log_dir / "evals.log",
)
from prime_rl.utils.utils import get_free_port
@@ -487,11 +495,11 @@ def sft_local(config: SFTConfig):
)
processes.append(tail_process)
# Wait for the trainer (and the evaluator, which drains its final evals after
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "evaluator" in stop_events:
terminal_events.append(stop_events["evaluator"])
if "evals" in stop_events:
terminal_events.append(stop_events["evals"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
@@ -529,12 +537,12 @@ def sft_local(config: SFTConfig):
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
"""Remove eval artifacts a previous run left behind: weight checkpoints and rollout
trace dirs — everything on a fresh start, steps past the resume step on resume.
Without this the evaluator would replay stale checkpoints (and then skip the
Without this the evals process would replay stale 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")
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evals process may replay them")
return
resume_step = resolve_resume_step(config)
weights_dir = get_weights_dir(get_ckpt_base(config))
View File
+443
View File
@@ -0,0 +1,443 @@
"""Evals: multi-env evals against a live inference server.
Standalone (no ``[online]``), it runs one epoch of every configured eval
source against the weights the inference server currently serves, then exits.
With ``[online]``, it watches a weights directory for new HF checkpoints —
the trainer writes ``weights/step_{n}`` with a ``STABLE`` marker on
completion — 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.
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
are version-pinned measurements, so an overload cut only blocks admission and
the in-flight pool drains through natural completions.
Env servers: sources without an explicit ``serve.address`` get an env server
spawned by the evals process at their derived address; sources with one are
externally managed (e.g. spawned by the ``sft`` launcher, which stamps the
derived addresses into this config)."""
from __future__ import annotations
import asyncio
import json
import os
import time
import uuid
from subprocess import Popen
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.evals import EvalsConfig
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.periodic_logger import PeriodicLogger
from prime_rl.orchestrator.types import EvalBatch, Policy, 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.config import dump_resolved_config
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_config_dir, get_log_dir, get_step_path
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, cleanup_processes
from prime_rl.utils.utils import clean_exit
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often to re-scan the weights directory for new checkpoints.
POLL_INTERVAL_S = 2.0
class Evals:
def __init__(self, config: EvalsConfig) -> None:
self.config = config
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
mode = f"online (weights_dir={config.online.weights_dir})" if config.online is not None else "standalone"
get_logger().info(f"Starting evals ({mode})")
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = (config.online.resume_step if config.online is not None else None) or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
self.env_server_procs: list[Popen] = []
self.dispatcher_task: asyncio.Task | None = None
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")
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.pool = InferencePool(config.eval.client, model_name=config.model)
self.spawn_env_servers()
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
await self.eval_envs.start()
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.pool.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
is_resumed = config.online is not None and config.online.resume_step is not None
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=is_resumed)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
self.policy = Policy(version=0, model_name=config.model)
# Pessimistic per-episode token cost for the controller's starting cap,
# only used when the engine doesn't report its max context length.
fallback_cost = max((source.sampling.max_completion_tokens or 0) for source in config.eval.source) or 8192
self.concurrency = ConcurrencyController(config.eval.concurrency, fallback_cost=fallback_cost)
self.dispatcher = Dispatcher(
train_envs=None,
eval_envs=self.eval_envs,
train_source=None,
eval_source=self.eval_source,
policy_pool=self.pool,
policy=self.policy,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.eval.concurrency.max_inflight,
tasks_per_minute=None,
max_off_policy_steps=0,
on_episode_complete=self.concurrency.record_episode,
)
# No ``on_overload``: eval episodes are measurements and are never
# cancelled — a cut only blocks admission until the pool drains.
self.concurrency.bind(
set_limit=self.dispatcher.set_limit,
get_inflight=lambda: self.dispatcher.current_inflight,
)
# The collector always polls — it feeds the concurrency controller;
# W&B mirroring is gated on the registered monitor.
self.inference_metrics = InferenceMetricsCollector(
self.pool.admin_clients,
on_load=self.concurrency.observe,
log_to_wandb=wandb_enabled,
)
# Fail fast when adaptivity has no signal: external API endpoints
# (e.g. Prime Inference) expose no vLLM /metrics, so without a probe
# hit the cap would silently sit at min_inflight forever. A pinned
# band (min_inflight = max_inflight) makes the controller inert and
# is the supported way to run against such endpoints.
if not await self.inference_metrics.probe():
concurrency = config.eval.concurrency
if concurrency.min_inflight != concurrency.max_inflight:
urls = ", ".join(str(client.base_url) for client in self.pool.admin_clients)
raise ValueError(
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
"pin the concurrency by setting eval.concurrency.min_inflight = max_inflight."
)
get_logger().warning(f"No engine metrics - running with concurrency pinned at {concurrency.min_inflight}")
await self.inference_metrics.start()
self.periodic_logger = PeriodicLogger(
name="Evals",
collect=self.collect_pipeline_view,
metric_keys=[
*list(self.dispatcher.gauges().keys()),
*list(self.concurrency.gauges().keys()),
*DispatcherMetrics.drain_keys(train_envs=set(), eval_envs={env.name for env in self.eval_envs}),
],
interval=config.log.interval,
wandb_enabled=wandb_enabled,
)
def spawn_env_servers(self) -> None:
"""Spawn one env server per source without an explicit ``serve.address``,
at the source's derived address."""
config = self.config
addresses = config.eval.env_addresses
config_dir = get_config_dir(config.output_dir) / "envs" / "eval"
log_dir = get_log_dir(config.output_dir) / "envs" / "eval"
for source in config.eval.source:
if source.serve.address is not None:
continue
name = source.resolved_name
address = addresses[("eval", name)]
source_dict = dump_resolved_config(source)
server_config = {
"env": source_dict["env"],
"serve": {**(source_dict.get("serve") or {}), "address": address},
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
}
config_dir.mkdir(parents=True, exist_ok=True)
config_path = config_dir / f"{name}.json"
config_path.write_text(json.dumps(server_config, indent=2))
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / f"{name}.log"
get_logger().info(f"Starting env server {name} at {address} (logs: {log_path})")
with open(log_path, "w") as log_file:
process = Popen(
["env-server", "@", config_path.as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS},
stdout=log_file,
stderr=log_file,
)
self.env_server_procs.append(process)
async def run(self) -> None:
await self.setup()
self.dispatcher_task = asyncio.create_task(self.dispatcher.start(), name="dispatcher")
await self.periodic_logger.start()
if self.config.online is None:
await self.maybe_run_evals(step=0)
else:
await self.watch()
# The periodic logger and the collector log to the W&B run, so they
# must stop before finalize marks the run finished.
await self.periodic_logger.stop()
await self.inference_metrics.stop()
get_logger().success("Evals finished!")
async def watch(self) -> None:
"""Online mode: evaluate each eligible weight checkpoint as it appears."""
config = self.config
assert config.online is not None
online = config.online
if online.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 = online.max_steps is not None and online.resume_step >= online.max_steps
await self.maybe_run_evals(step=online.resume_step, reload_weights=True, force=is_final)
get_logger().info(f"Watching {online.weights_dir} for new weight checkpoints (max_steps={online.max_steps})")
while True:
assert online.weights_dir is not None # resolved by the config validator
steps = get_all_ckpt_steps(online.weights_dir)
stable = {step: (get_step_path(online.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 evals process) - 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 = online.max_steps is not None and step >= online.max_steps
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
if online.max_steps is not None and self.last_step >= online.max_steps:
break
await asyncio.sleep(POLL_INTERVAL_S)
def 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."""
if reload_weights:
assert self.config.online is not None and self.config.online.weights_dir is not None
weight_dir = get_step_path(self.config.online.weights_dir, step)
if 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
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
# between the trigger above and the weight reload completing.
self.policy.version = step
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
await self.consume_epoch(fired)
async def consume_epoch(self, fired: list[str]) -> None:
"""Consume dispatcher episodes until every fired env's epoch finalizes,
routing them through the sink and monitors."""
# An env with no examples emits no episodes, so its epoch can never finalize.
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
while pending:
episode: list[Rollout] = await self.dispatcher.out_q.get()
step = episode[0].eval_step
assert step is not None
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)
pending.discard(eval_batch.env_name)
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.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%}"
)
def collect_pipeline_view(self) -> tuple[str, dict[str, float]]:
"""Pipeline view for the ``PeriodicLogger``: per-env epoch progress plus the
in-flight pool against the controller's current cap."""
disp_gauges = self.dispatcher.gauges()
disp_drain = self.dispatcher.metrics.drained(train_envs=set(), eval_envs={env.name for env in self.eval_envs})
parts = []
for env_name, _step, arrived, expected, buffered in sorted(self.eval_sink.batch_progress()):
part = f"{env_name} {arrived}/{expected} ({arrived / expected:.1%})" if expected else env_name
if buffered:
part += f" (+{buffered} buffered)"
parts.append(part)
progress_part = " | ".join(parts) if parts else "Idle"
body = (
f"{progress_part}; {self.dispatcher.inflight_eval_count} inflight episodes "
f"(cap {self.dispatcher.max_inflight}, signal {self.concurrency.signal})"
)
payload = {**disp_gauges, **disp_drain, **self.concurrency.gauges()}
return body, payload
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
periodic_logger: PeriodicLogger | None = getattr(self, "periodic_logger", None)
if periodic_logger is not None:
await periodic_logger.stop()
inference_metrics: InferenceMetricsCollector | None = getattr(self, "inference_metrics", None)
if inference_metrics is not None:
await inference_metrics.stop()
dispatcher: Dispatcher | None = getattr(self, "dispatcher", None)
if dispatcher is not None:
await dispatcher.stop()
pool: InferencePool | None = getattr(self, "pool", None)
if pool is not None:
await pool.stop()
cleanup_processes(self.env_server_procs)
@clean_exit
async def run_evals(config: EvalsConfig) -> None:
evals = Evals(config)
try:
await evals.run()
# Finalize only on a clean exit — a crashed evals must not mark the run completed.
await monitors.finalize()
finally:
await evals.stop()
def main() -> None:
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
set_proc_title("Evals")
asyncio.run(run_evals(cli(EvalsConfig)))
if __name__ == "__main__":
main()
+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
+1 -1
View File
@@ -55,7 +55,7 @@ class WandbMonitor(Monitor):
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).
# trainer creates the run, the evals process outlives it and finalizes).
finisher = label == os.environ.get("WANDB_SHARED_FINISHER", primary_label)
settings = wandb.Settings(
mode="shared",
+1
View File
@@ -71,6 +71,7 @@ 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.
+1 -1
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
+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
+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]),
}
+123 -42
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)
@@ -125,7 +130,7 @@ def error_trace_task(group: GroupState | None) -> vf.TraceTask:
)
class RolloutDispatcher:
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
@@ -135,15 +140,17 @@ class RolloutDispatcher:
def __init__(
self,
*,
train_envs: TrainEnvs,
train_envs: TrainEnvs | None,
eval_envs: EvalEnvs | None,
train_source: TrainSource,
train_source: TrainSource | None,
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
@@ -154,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 or ()), 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
@@ -186,6 +211,7 @@ class RolloutDispatcher:
def _train_pool_for(self, env_name: str) -> tuple[InferencePool, str, bool]:
"""``(pool, model_name, is_live)`` for *train* rollouts of this env —
the env sampler's pool. (Eval always uses the policy.)"""
assert self.train_envs is not None # train groups only exist when train is configured
sampler = self.train_envs.get(env_name).sampler
if sampler.samples_from_live_policy:
return sampler.pool, self.policy.model_name, True
@@ -201,7 +227,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]:
@@ -274,7 +344,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,6 +366,7 @@ class RolloutDispatcher:
continue
# Frozen-sourced rollouts never go stale — their sampler doesn't
# change with policy updates.
assert self.train_envs is not None
if not self.train_envs.get(meta.env_name).sampler.samples_from_live_policy:
continue
meta.off_policy_steps += 1
@@ -308,7 +379,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."
)
@@ -322,7 +393,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:
@@ -349,7 +420,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:
@@ -379,6 +450,7 @@ class RolloutDispatcher:
"""Pop the next example from the corresponding source and wrap it in
a ``GroupState``. Returns ``None`` if the source is empty."""
if kind == "train":
assert self.train_source is not None
source = self.train_source
else:
assert self.eval_source is not None
@@ -436,6 +508,7 @@ class RolloutDispatcher:
group.rollouts_to_schedule -= 1
await self.acquire()
self.admissions_in_window += 1
task = asyncio.create_task(
env.run(
client=client,
@@ -445,13 +518,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
@@ -460,10 +534,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
@@ -474,8 +553,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
@@ -511,9 +590,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."""
@@ -548,7 +630,7 @@ class RolloutDispatcher:
# 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
@@ -558,7 +640,7 @@ 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=error_trace_task(group),
@@ -578,7 +660,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,
@@ -599,7 +681,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,
@@ -620,8 +702,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)
@@ -632,8 +714,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] = []
@@ -659,11 +741,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
@@ -46,7 +46,7 @@ class EvalSource:
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.
``force`` fires every env regardless of interval (e.g. the evaluator's
``force`` fires every env regardless of interval (e.g. the evals process's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.eval_config.skip_first_step:
-320
View File
@@ -1,320 +0,0 @@
"""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()
+96 -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,32 +278,51 @@ 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())
async def probe(self, attempts: int = 3, interval: float = 2.0) -> bool:
"""Scrape once, outside the poll loop, and report whether any engine
answered with metrics. External API endpoints (no vLLM ``/metrics``)
fail every attempt immediately; the retries only cover a real engine
racing its first exposition."""
for attempt in range(attempts):
if attempt > 0:
await asyncio.sleep(interval)
try:
await self.collect_and_log()
except Exception as e:
get_logger().warning(f"Inference metrics probe failed: {e!r}")
if self.previous:
return True
return False
async def collect_and_log(self):
now = time.monotonic()
@@ -316,28 +345,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]
+42 -27
View File
@@ -3,7 +3,7 @@
``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 → admission)
and returns a ``TrainBatch`` when the threshold is met.
@@ -37,13 +37,14 @@ 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
@@ -73,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
@@ -127,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
@@ -274,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(
@@ -379,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,
@@ -420,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(),
@@ -478,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()
@@ -565,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
@@ -701,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
@@ -748,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]
@@ -759,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
+1 -1
View File
@@ -29,7 +29,7 @@ from prime_rl.orchestrator.envs import TrainEnvs
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
+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
+4 -2
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
+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
@@ -42,15 +42,15 @@ ln -sfn attempt_$ATTEMPT $OUTPUT_DIR/logs/latest
ln -sfn trainer/node_0.log $LOG_DIR/trainer.log
{% if prl_run_id %}
# Trainer and evaluator (separate SLURM job) log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evaluator (which
# Trainer and evals (separate SLURM job) log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
# outlives the trainer) finalizes it.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
export WANDB_SHARED_FINISHER=evaluator
export WANDB_SHARED_FINISHER=evals
export WANDB_SHARED_LABEL=trainer
export WANDB_PROGRAM="uv run sft"
{% endif %}
@@ -22,7 +22,7 @@
#SBATCH --error={{ output_dir }}/eval_job_%j.log
# Online-eval job for a decoupled SFT run: the inference pool (one vLLM engine per
# DP rank behind a single router) plus the evaluator and its env servers. The trainer
# DP rank behind a single router) plus the evals process and its env servers. The trainer
# runs in a separate SLURM job and hands weights over via checkpoints on the shared
# filesystem, so this job outlives the trainer and exits after evaluating the final
# checkpoint (max_steps).
@@ -50,22 +50,22 @@ export OUTPUT_DIR={{ output_dir }}
mkdir -p $OUTPUT_DIR/logs/inference
ln -sfn inference/node_0.log $OUTPUT_DIR/logs/inference.log
# A clean evaluator exit cannot trip srun --kill-on-bad-exit (which only propagates
# A clean evals exit cannot trip srun --kill-on-bad-exit (which only propagates
# failures), so node 0 publishes completion through this job-scoped sentinel and the
# other nodes watch for it to release their engines. Stale sentinels from other job
# IDs are inert, so only this job's own path needs clearing.
export EVAL_DONE=$OUTPUT_DIR/.eval_done_$SLURM_JOB_ID
rm -f "$EVAL_DONE"
{% if prl_run_id %}
# Trainer (separate SLURM job) and evaluator log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evaluator (which
# Trainer (separate SLURM job) and evals log to a single shared W&B run whose id
# ($WANDB_RUN_ID) equals $PRL_RUN_ID: the trainer creates it, the evals process (which
# outlives the trainer) finalizes it.
export PRL_RUN_ID={{ prl_run_id }}
export PRL_RUN_NAME={{ run_name }}
export WANDB_RUN_ID=$PRL_RUN_ID
export WANDB_SHARED_MODE=1
export WANDB_SHARED_PRIMARY=trainer
export WANDB_SHARED_FINISHER=evaluator
export WANDB_SHARED_FINISHER=evals
export WANDB_PROGRAM="uv run sft"
{% endif %}
# Networking
@@ -139,7 +139,7 @@ CLEANUP_SH
# Run the eval deployment
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed engine/router/evaluator terminates the SLURM job instead
# tasks so a crashed engine/router/evals terminates the SLURM job instead
# of leaving the surviving ranks holding nodes.
#
# The body goes to bash on stdin through a quoted heredoc instead of a
@@ -204,9 +204,9 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
launch_router regular "$ROUTER_ARGS" "$ROUTER_PORT" "{{ router.policy }}" "$OUTPUT_DIR/logs/inference/router.log"
{%- if eval_env_names %}
# One env server per eval source next to the evaluator, which connects to each
# One env server per eval source next to the evals process, which connects to each
# source at its deterministic loopback address (so this node), polling until
# they are up - the servers and the evaluator start in parallel.
# they are up - the servers and the evals process start in parallel.
{%- for name in eval_env_names %}
mkdir -p $OUTPUT_DIR/logs/envs/eval
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.json \
@@ -214,30 +214,30 @@ srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
{%- endfor %}
{%- endif %}
# The evaluator watches the trainer's weights dir on the shared filesystem and
# The evals process watches the trainer's weights dir on the shared filesystem and
# drives the pool: data plane through the router, admin ops per rank.
{%- for key, value in evaluator_env_vars.items() %}
{%- for key, value in evals_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
WANDB_SHARED_LABEL=evaluator uv run evaluator \
@ $CONFIG_DIR/evaluator.json \
WANDB_SHARED_LABEL=evals uv run evals \
@ $CONFIG_DIR/evals.json \
--eval.client.base-url $INFER_URLS \
--eval.client.admin-base-url $ADMIN_URLS \
2>&1 | tee $OUTPUT_DIR/logs/evaluator.log &
EVALUATOR_PID=$!
2>&1 | tee $OUTPUT_DIR/logs/evals.log &
EVALS_PID=$!
else
# Watch for the completion sentinel so this node's wait below returns when
# the evaluator (on node 0) finishes cleanly.
# the evals process (on node 0) finishes cleanly.
( until [ -f "$EVAL_DONE" ]; do sleep 10; done ) &
fi
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (engines, router, env servers, evaluator)
# turns background process crashes (engines, router, env servers, evals)
# into task failures that --kill-on-bad-exit=1 can broadcast to the other nodes
# so the whole job tears down instead of leaving zombies holding the allocation.
wait -n -p FINISHED_PID
EXIT_CODE=$?
if [ "${FINISHED_PID:-}" = "${EVALUATOR_PID:-none}" ]; then
if [ "${FINISHED_PID:-}" = "${EVALS_PID:-none}" ]; then
# Publish completion so the sentinel watchers on the other nodes release too
# (a zero exit here never trips --kill-on-bad-exit).
touch "$EVAL_DONE"
+1 -1
View File
@@ -6,7 +6,7 @@ from typing import Any
import numpy as np
from prime_rl.transport.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
from prime_rl.transports.rollouts.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample
# Backfill value per component weight stream when a packed sample doesn't
# carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl
+1 -1
View File
@@ -498,7 +498,7 @@ class WeightCheckpointManager:
# Always keep the newest weight checkpoint — it is the current policy. With
# keep_interval-only cleaning, a freshly saved non-aligned final checkpoint would
# otherwise be deleted immediately, and the online evaluator would wait for the
# otherwise be deleted immediately, and the online evals would wait for the
# max_steps checkpoint forever.
if self.ckpt_steps:
steps_to_keep.add(self.ckpt_steps[-1])
+15 -11
View File
@@ -136,16 +136,20 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
m, s, t = _online_logsumexp_and_weighted_update(m, s, t, scaled_logits)
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
target_logits[mask] = scaled_logits[mask, idx]
# Branchless target extraction - we don't want to stall the GPU here (because: if torch.any()) calls bool(Tensor) calls Tensor.items() <- sync here we don't want
in_range = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
local_idx = (labels_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1).to(torch.int64)
chunk_target = scaled_logits.gather(1, local_idx.unsqueeze(1)).squeeze(1)
target_logits = torch.where(in_range, chunk_target, target_logits)
logz_chunk = m + torch.log(s)
logz[start:end] = logz_chunk
logprobs[start:end] = target_logits - logz_chunk
entropy[start:end] = logz_chunk - (t / s)
ctx.set_materialize_grads(
False
) # Without materialized grads unused outputs get grad None instead of zeros and backward can reject them without a sync
ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz)
ctx.chunk_size = chunk_size
@@ -153,9 +157,9 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
@staticmethod
def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor | None):
assert grad_entropy is None or torch.all(grad_entropy == 0.0), (
"Backward through entropy is not implemented in FusedOutputLinear"
)
# Grads are not materialized (see forward above) so an unused entropy output arrives becomes None, and as we don't compare values we don't have any sync
assert grad_entropy is None, "Backward through entropy is not implemented in FusedOutputLinear"
assert grad_logprobs is not None, "FusedOutputLinear backward requires logprobs gradients"
hidden, weight, labels, inv_temperature, logz = ctx.saved_tensors
chunk_size: int = ctx.chunk_size
@@ -184,10 +188,10 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
probs = torch.exp(scaled_logits - logz_chunk.unsqueeze(-1))
grad_logits = (-grad_chunk).unsqueeze(-1) * probs
mask = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
if torch.any(mask):
idx = (labels_chunk[mask] - vocab_start).to(torch.long)
grad_logits[mask, idx] += grad_chunk[mask]
# Branchless grad scatter like we did in the sync-free forward
in_range = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end)
local_idx = (labels_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1).to(torch.int64)
grad_logits.scatter_add_(1, local_idx.unsqueeze(1), (grad_chunk * in_range).unsqueeze(1))
grad_logits = grad_logits * inv_t_chunk
if needs_hidden:
+5 -3
View File
@@ -28,8 +28,8 @@ def setup_optimizer(
) -> tuple[OptimizerLike, GradientOffloadManager | None]:
if cpu_offload and full_offload_config is not None:
raise ValueError("State-only and full optimizer CPU offload cannot both be enabled")
if full_offload_config is not None and config.type != "adamw":
raise ValueError("Full optimizer offload only supports AdamW")
if full_offload_config is not None and config.type not in ("adamw", "sign_sgd"):
raise ValueError("Full optimizer offload only supports AdamW and SignSGD")
if full_offload_config is not None and config.max_norm is not None:
get_logger().warning("Disabling gradient clipping because CPU optimizer offload updates during backward")
config.max_norm = None
@@ -43,7 +43,9 @@ def setup_optimizer(
optimizer_named_params, master_weights = _create_cpu_master_weights(
model,
named_params,
pin_memory=not (config.type == "adamw" and full_offload_config.cpu_optimizer_backend == "native"),
pin_memory=not (
config.type in ("adamw", "sign_sgd") and full_offload_config.cpu_optimizer_backend == "native"
),
dtype_policy=full_offload_dtype_policy,
)
@@ -94,3 +94,21 @@ def adamw_step(
eps,
gradient_scale,
)
@torch.no_grad()
def sign_sgd_step(
params: list[torch.Tensor],
grads: list[torch.Tensor],
compute_params: list[torch.Tensor] | None = None,
*,
lr: float,
weight_decay: float,
) -> None:
_extension().sign_sgd_step(
params,
grads,
compute_params or [],
lr,
weight_decay,
)
@@ -23,6 +23,16 @@ struct TensorSpan {
float bias_correction2_sqrt;
};
struct SignSgdTensorSpan {
float* param;
const void* grad;
void* compute_param;
bool grad_bfloat16;
bool compute_param_bfloat16;
int64_t begin;
int64_t end;
};
struct BFloat16CopySpan {
float* destination;
const at::BFloat16* source;
@@ -324,6 +334,154 @@ void adamw_step(
});
}
void sign_sgd_span(
const SignSgdTensorSpan& span,
int64_t begin,
int64_t end,
float minus_lr,
float minus_lr_weight_decay,
bool apply_weight_decay) {
using Vec = at::vec::Vectorized<float>;
using BVec = at::vec::Vectorized<at::BFloat16>;
float* param = span.param + begin;
const float* float_grad = span.grad_bfloat16 ? nullptr : static_cast<const float*>(span.grad) + begin;
const at::BFloat16* bfloat16_grad =
span.grad_bfloat16 ? static_cast<const at::BFloat16*>(span.grad) + begin : nullptr;
at::BFloat16* bfloat16_compute_param =
span.compute_param != nullptr && span.compute_param_bfloat16
? static_cast<at::BFloat16*>(span.compute_param) + begin
: nullptr;
float* float_compute_param =
span.compute_param != nullptr && !span.compute_param_bfloat16
? static_cast<float*>(span.compute_param) + begin
: nullptr;
const int64_t size = end - begin;
const Vec zero_vec(0.0f);
const Vec one_vec(1.0f);
const Vec minus_lr_vec(minus_lr);
const Vec minus_lr_weight_decay_vec(minus_lr_weight_decay);
auto update = [&](int64_t offset, const Vec& grad_vec) {
// Comparisons yield all-ones masks; bitwise-and with 1.0f turns them into
// {0.0f, 1.0f} so the difference is sign(g) with sign(0) == 0.
const Vec sign_vec = ((zero_vec < grad_vec) & one_vec) - ((grad_vec < zero_vec) & one_vec);
Vec param_vec = Vec::loadu(param + offset);
if (apply_weight_decay) {
param_vec = at::vec::fmadd(param_vec, minus_lr_weight_decay_vec, param_vec);
}
param_vec = at::vec::fmadd(sign_vec, minus_lr_vec, param_vec);
param_vec.store(param + offset);
return param_vec;
};
int64_t i = 0;
constexpr int64_t block_size = 2 * Vec::size();
for (; i <= size - block_size; i += block_size) {
Vec grad0;
Vec grad1;
if (span.grad_bfloat16) {
const BVec grad_bvec = BVec::loadu(bfloat16_grad + i);
std::tie(grad0, grad1) = at::vec::convert_to_float<at::BFloat16>(grad_bvec);
} else {
grad0 = Vec::loadu(float_grad + i);
grad1 = Vec::loadu(float_grad + i + Vec::size());
}
const Vec param0 = update(i, grad0);
const Vec param1 = update(i + Vec::size(), grad1);
if (bfloat16_compute_param != nullptr) {
at::vec::convert_from_float<at::BFloat16>(param0, param1).store(bfloat16_compute_param + i);
} else if (float_compute_param != nullptr) {
param0.store(float_compute_param + i);
param1.store(float_compute_param + i + Vec::size());
}
}
for (; i < size; ++i) {
const float grad_value = span.grad_bfloat16 ? static_cast<float>(bfloat16_grad[i]) : float_grad[i];
const float sign_value = grad_value > 0.0f ? 1.0f : (grad_value < 0.0f ? -1.0f : 0.0f);
float param_value = param[i];
if (apply_weight_decay) {
param_value = std::fma(param_value, minus_lr_weight_decay, param_value);
}
param_value = std::fma(sign_value, minus_lr, param_value);
param[i] = param_value;
if (bfloat16_compute_param != nullptr) {
bfloat16_compute_param[i] = at::BFloat16(param_value);
} else if (float_compute_param != nullptr) {
float_compute_param[i] = param_value;
}
}
}
void sign_sgd_step(
const std::vector<torch::Tensor>& params,
const std::vector<torch::Tensor>& grads,
const std::vector<torch::Tensor>& compute_params,
double lr,
double weight_decay) {
const auto count = params.size();
TORCH_CHECK(grads.size() == count, "grads and params must have the same length");
TORCH_CHECK(
compute_params.empty() || compute_params.size() == count,
"compute_params must be empty or have the same length as params");
if (count == 0) {
return;
}
std::vector<SignSgdTensorSpan> spans;
spans.reserve(count);
int64_t total_numel = 0;
for (size_t i = 0; i < count; ++i) {
check_tensor(params[i], "param");
check_grad(grads[i]);
TORCH_CHECK(params[i].numel() == grads[i].numel(), "grad shape must match param shape");
if (!compute_params.empty()) {
TORCH_CHECK(compute_params[i].device().is_cpu(), "compute_param must be on CPU");
TORCH_CHECK(
compute_params[i].scalar_type() == torch::kBFloat16 ||
compute_params[i].scalar_type() == torch::kFloat32,
"compute_param must be bfloat16 or float32");
TORCH_CHECK(compute_params[i].is_contiguous(), "compute_param must be contiguous");
TORCH_CHECK(params[i].numel() == compute_params[i].numel(), "compute_param shape must match param shape");
}
const int64_t numel = params[i].numel();
spans.push_back(SignSgdTensorSpan{
params[i].data_ptr<float>(),
grads[i].const_data_ptr(),
compute_params.empty() ? nullptr : compute_params[i].data_ptr(),
grads[i].scalar_type() == torch::kBFloat16,
!compute_params.empty() && compute_params[i].scalar_type() == torch::kBFloat16,
total_numel,
total_numel + numel,
});
total_numel += numel;
}
const float minus_lr = static_cast<float>(-lr);
const float minus_lr_weight_decay = static_cast<float>(-lr * weight_decay);
const bool apply_weight_decay = weight_decay > 0.0;
constexpr int64_t grain_size = 32 * 1024;
at::parallel_for(0, total_numel, grain_size, [&](int64_t begin, int64_t end) {
auto span_it = std::upper_bound(
spans.begin(),
spans.end(),
begin,
[](int64_t offset, const SignSgdTensorSpan& span) { return offset < span.end; });
while (begin < end) {
TORCH_INTERNAL_ASSERT(span_it != spans.end());
const int64_t span_begin = begin - span_it->begin;
const int64_t span_end = std::min(end, span_it->end) - span_it->begin;
sign_sgd_span(*span_it, span_begin, span_end, minus_lr, minus_lr_weight_decay, apply_weight_decay);
begin = std::min(end, span_it->end);
++span_it;
}
});
}
} // namespace
PYBIND11_MODULE(TORCH_EXTENSION_NAME, module) {
@@ -347,4 +505,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, module) {
&adamw_step,
"Read-only-gradient multi-tensor CPU AdamW",
pybind11::call_guard<pybind11::gil_scoped_release>());
module.def(
"sign_sgd_step",
&sign_sgd_step,
"Read-only-gradient multi-tensor CPU SignSGD",
pybind11::call_guard<pybind11::gil_scoped_release>());
}
+72 -21
View File
@@ -20,6 +20,8 @@ from prime_rl.trainer.optim.cpu_adam import adamw_step as native_cpu_adamw_step
from prime_rl.trainer.optim.cpu_adam import add_bfloat16_ as native_add_bfloat16_
from prime_rl.trainer.optim.cpu_adam import copy_or_add_bfloat16_multi_ as native_copy_or_add_bfloat16_multi_
from prime_rl.trainer.optim.cpu_adam import load_cpu_adamw_kernel
from prime_rl.trainer.optim.cpu_adam import sign_sgd_step as native_cpu_sign_sgd_step
from prime_rl.trainer.sign_sgd import SignSGD
from prime_rl.utils.logger import get_logger
@@ -1089,6 +1091,8 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
self._all_param_groups = self.optimizer.param_groups
self._chunk_groups = self._build_chunk_groups()
self._native_cpu_adamw = isinstance(optimizer, AdamW) and offload_config.cpu_optimizer_backend == "native"
self._native_cpu_sign_sgd = isinstance(optimizer, SignSGD) and offload_config.cpu_optimizer_backend == "native"
self._native_cpu_optimizer = self._native_cpu_adamw or self._native_cpu_sign_sgd
self._fused_cpu_adamw = (
isinstance(optimizer, AdamW)
and all(group["fused"] for group in optimizer.param_groups)
@@ -1096,11 +1100,12 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
)
self._adamw_grad_scale = torch.ones((), dtype=torch.float32) if self._fused_cpu_adamw else None
self._adamw_found_inf = torch.zeros((), dtype=torch.float32) if self._fused_cpu_adamw else None
if self._native_cpu_adamw:
get_logger().info("Loading native read-only-gradient multi-tensor CPU AdamW kernel")
if self._native_cpu_optimizer:
kernel_name = "AdamW" if self._native_cpu_adamw else "SignSGD"
get_logger().info(f"Loading native read-only-gradient multi-tensor CPU {kernel_name} kernel")
load_cpu_adamw_kernel()
gradient_chunks = [[master_weights[id(param)].model_param for param in chunk] for chunk in self._chunks]
if self._native_cpu_adamw:
if self._native_cpu_optimizer:
gradient_dtypes = {id(master.model_param): master.gradient_dtype for master in master_weights.values()}
compute_dtypes = {id(master.model_param): master.compute_dtype for master in master_weights.values()}
self._gradient_manager = BoundedGradientOffloadManager(
@@ -1231,6 +1236,49 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
gradient_scale=self._gradient_manager.gradient_scale,
)
def _step_native_cpu_sign_sgd_chunk(
self,
chunk_idx: int,
gradients: list[torch.Tensor | None],
compute_params: list[torch.Tensor],
) -> None:
assert self._gradient_manager is not None
assert self._master_weights is not None
# The kernel consumes unscaled gradients: sign(scale * g) == sign(g) for scale > 0,
# so the positive gradient scale can be dropped entirely.
assert self._gradient_manager.gradient_scale > 0
gradient_by_param_id = {
id(param): gradient for param, gradient in zip(self._chunks[chunk_idx], gradients) if gradient is not None
}
compute_by_param_id = {
id(param): compute_param for param, compute_param in zip(self._chunks[chunk_idx], compute_params)
}
for param, gradient, compute_param in zip(self._chunks[chunk_idx], gradients, compute_params):
if gradient is None:
compute_param.copy_(self._master_weights[id(param)].cpu_tensor)
for group, params in self._chunk_groups[chunk_idx]:
params_with_grad = [param for param in params if id(param) in gradient_by_param_id]
if not params_with_grad:
continue
native_cpu_sign_sgd_step(
params_with_grad,
[gradient_by_param_id[id(param)] for param in params_with_grad],
[compute_by_param_id[id(param)] for param in params_with_grad],
lr=group["lr"],
weight_decay=group["weight_decay"],
)
def _step_native_cpu_chunk(
self,
chunk_idx: int,
gradients: list[torch.Tensor | None],
compute_params: list[torch.Tensor],
) -> None:
if self._native_cpu_adamw:
self._step_native_cpu_adamw_chunk(chunk_idx, gradients, compute_params)
else:
self._step_native_cpu_sign_sgd_chunk(chunk_idx, gradients, compute_params)
def _step_cpu_chunk(self, chunk_idx: int) -> None:
assert self._gradient_manager is not None
self._prepare_fused_cpu_adamw()
@@ -1238,19 +1286,19 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
chunk_idx,
self._chunks[chunk_idx],
wait=False,
apply_scale=not (self._native_cpu_adamw or self._fused_cpu_adamw),
assign_grad=not self._native_cpu_adamw,
apply_scale=not (self._native_cpu_optimizer or self._fused_cpu_adamw),
assign_grad=not self._native_cpu_optimizer,
)
if self._native_cpu_adamw:
if self._native_cpu_optimizer:
if not isinstance(self._gradient_manager, BoundedGradientOffloadManager):
raise TypeError("Native CPU AdamW requires bounded gradient offload")
raise TypeError("Native CPU optimizers require bounded gradient offload")
timings = self._gradient_manager._timings
acquire_start = time.perf_counter()
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(chunk_idx)
adam_start = time.perf_counter()
timings["output_slot_wait"] = timings.get("output_slot_wait", 0.0) + adam_start - acquire_start
self._step_native_cpu_adamw_chunk(chunk_idx, gradients, compute_params)
timings["adam_kernel"] = timings.get("adam_kernel", 0.0) + time.perf_counter() - adam_start
kernel_start = time.perf_counter()
timings["output_slot_wait"] = timings.get("output_slot_wait", 0.0) + kernel_start - acquire_start
self._step_native_cpu_chunk(chunk_idx, gradients, compute_params)
timings["optimizer_kernel"] = timings.get("optimizer_kernel", 0.0) + time.perf_counter() - kernel_start
else:
self._step_chunk(chunk_idx)
self._gradient_manager.release_chunk(chunk_idx, self._chunks[chunk_idx])
@@ -1258,9 +1306,9 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
self._update_compute_weights(
chunk_idx,
self._h2d_stream,
compute_params if self._native_cpu_adamw else None,
compute_params if self._native_cpu_optimizer else None,
)
if self._native_cpu_adamw:
if self._native_cpu_optimizer:
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
def _prepare_fused_cpu_adamw(self) -> None:
@@ -1274,7 +1322,7 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
self.optimizer.found_inf = self._adamw_found_inf
def _record_native_optimizer_step(self) -> None:
if self._native_cpu_adamw:
if self._native_cpu_optimizer:
# LRScheduler normally sets this marker through its optimizer.step wrapper.
self.optimizer._opt_called = True
@@ -1302,16 +1350,16 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
self._gradient_manager.load_cpu_chunk(
i,
self._chunks[i],
apply_scale=not (self._native_cpu_adamw or self._fused_cpu_adamw),
assign_grad=not self._native_cpu_adamw,
apply_scale=not (self._native_cpu_optimizer or self._fused_cpu_adamw),
assign_grad=not self._native_cpu_optimizer,
)
)
if self._native_cpu_adamw:
if self._native_cpu_optimizer:
if not isinstance(self._gradient_manager, BoundedGradientOffloadManager):
raise TypeError("Native CPU AdamW requires bounded gradient offload")
raise TypeError("Native CPU optimizers require bounded gradient offload")
for i in range(len(self._chunks)):
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
self._step_native_cpu_adamw_chunk(i, gradients_by_chunk[i], compute_params)
self._step_native_cpu_chunk(i, gradients_by_chunk[i], compute_params)
self._gradient_manager.release_chunk(i, self._chunks[i])
self._update_compute_weights(i, self._h2d_stream, compute_params)
self._gradient_manager.release_output_chunk(output_slots, self._h2d_stream)
@@ -1354,6 +1402,9 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
@torch.no_grad()
def _initialize_cpu_optimizer_state(self) -> None:
if isinstance(self.optimizer, SignSGD):
# SignSGD is stateless: no moments or step counters to materialize.
return
if self.optimizer.state:
return
if self._native_cpu_adamw:
@@ -1439,9 +1490,9 @@ class FullCPUOffloadOptimizer(OffloadOptimizer):
@torch.no_grad()
def finish_checkpoint_load(self) -> None:
if self._master_weights is not None:
if self._native_cpu_adamw:
if self._native_cpu_optimizer:
if not isinstance(self._gradient_manager, BoundedGradientOffloadManager):
raise TypeError("Native CPU AdamW requires bounded gradient offload")
raise TypeError("Native CPU optimizers require bounded gradient offload")
for i in range(len(self._chunks)):
output_slots, compute_params = self._gradient_manager.acquire_output_chunk(i)
for param, compute_param in zip(self._chunks[i], compute_params):
+1 -1
View File
@@ -7,7 +7,7 @@ from torch import Tensor
from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.trainer.world import get_world
from prime_rl.transport import (
from prime_rl.transports.rollouts import (
MicroBatch,
MicroBatchReceiver,
TransportConfig,
+1 -1
View File
@@ -9,7 +9,7 @@ from datetime import timedelta
# ruff: noqa: I001
from prime_rl.trainer.models.layers.attn import substitute_ring_attn
from prime_rl.trainer.rl.broadcast import setup_weight_broadcast
from prime_rl.transports.weights import setup_weight_broadcast
from prime_rl.utils.act_offloading import maybe_activation_offloading
import torch
import torch.distributed as dist
@@ -1,17 +1,17 @@
from pathlib import Path
from prime_rl.configs.shared import TransportConfig
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transport.filesystem import (
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transports.rollouts.filesystem import (
FileSystemMicroBatchReceiver,
FileSystemMicroBatchSender,
)
from prime_rl.transport.types import (
from prime_rl.transports.rollouts.types import (
MicroBatch,
RoutedExperts,
TrainingSample,
)
from prime_rl.transport.zmq import (
from prime_rl.transports.rollouts.zmq import (
ZMQMicroBatchReceiver,
ZMQMicroBatchSender,
)
@@ -3,7 +3,7 @@ from pathlib import Path
import msgspec
from prime_rl.transport.types import MicroBatch
from prime_rl.transports.rollouts.types import MicroBatch
from prime_rl.utils.logger import get_logger
@@ -1,8 +1,8 @@
import asyncio
from pathlib import Path
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transport.types import MicroBatch
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transports.rollouts.types import MicroBatch
from prime_rl.utils.pathing import get_rollout_dir, get_step_path, sync_wait_for_path
@@ -4,8 +4,8 @@ import zmq
import zmq.asyncio
from prime_rl.configs.shared import ZMQTransportConfig
from prime_rl.transport.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transport.types import MicroBatch
from prime_rl.transports.rollouts.base import MicroBatchReceiver, MicroBatchSender
from prime_rl.transports.rollouts.types import MicroBatch
class ZMQMicroBatchSender(MicroBatchSender):
@@ -4,10 +4,10 @@ import torch
from prime_rl.configs.trainer import LoRAConfig, WeightBroadcastConfig
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.rl.broadcast.filesystem import FileSystemWeightBroadcast
from prime_rl.trainer.rl.broadcast.nccl import NCCLWeightBroadcast
from prime_rl.trainer.rl.broadcast.nixl import NIXLWeightBroadcast
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.transports.weights.filesystem import FileSystemWeightBroadcast
from prime_rl.transports.weights.nccl import NCCLWeightBroadcast
from prime_rl.transports.weights.nixl import NIXLWeightBroadcast
def setup_weight_broadcast(
@@ -8,13 +8,13 @@ from torch.distributed.tensor import DTensor
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig, LoRAConfig
from prime_rl.trainer.lora import get_lora_state, save_lora_config
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.utils import maybe_clean
from prime_rl.trainer.weights import (
gather_weights_on_master,
save_state_dict,
)
from prime_rl.trainer.world import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.utils.utils import get_broadcast_dir, get_step_path
@@ -14,8 +14,8 @@ from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.utils import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.utils.client import NCCL_READY_MARKER
from prime_rl.utils.logger import get_logger
from prime_rl.utils.nccl import disable_nccl_p2p_if_unavailable
@@ -1,5 +1,5 @@
"""NIXL weight broadcasting and transfer helpers."""
from prime_rl.trainer.rl.broadcast.nixl.nixl import NIXLWeightBroadcast
from prime_rl.transports.weights.nixl.nixl import NIXLWeightBroadcast
__all__ = ["NIXLWeightBroadcast"]
@@ -7,7 +7,7 @@ from typing import Any, Callable
import torch
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import TrainerTensorTable
from prime_rl.transports.weights.nixl.trainer_tensor_table import TrainerTensorTable
@dataclass(frozen=True)
@@ -22,21 +22,21 @@ from torch.distributed.tensor._utils import compute_local_shape_and_global_offse
from prime_rl.configs.trainer import NIXLWeightBroadcastConfig
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.rl.broadcast.base import WeightBroadcast
from prime_rl.trainer.rl.broadcast.nixl.agent import NixlAgent, make_agent_name, set_ucx_env_defaults
from prime_rl.trainer.rl.broadcast.nixl.cuda_malloc_memory import (
from prime_rl.trainer.utils import get_world
from prime_rl.transports.weights.base import WeightBroadcast
from prime_rl.transports.weights.nixl.agent import 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.model_express import ModelExpressSession
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import (
from prime_rl.transports.weights.nixl.model_express import ModelExpressSession
from prime_rl.transports.weights.nixl.trainer_tensor_table import (
TrainerAgent,
TrainerGroup,
TrainerShard,
TrainerTensor,
TrainerTensorTable,
)
from prime_rl.trainer.utils import get_world
LAYER_RE = re.compile(r"(?:^|\.)layers\.(\d+)(?=\.|$)")
BUFFER_POLL_INTERVAL = 0.01
@@ -6,8 +6,8 @@ from dataclasses import dataclass
import torch
from prime_rl.trainer.rl.broadcast.nixl.graph import TensorReplayPlan
from prime_rl.trainer.rl.broadcast.nixl.trainer_tensor_table import TrainerTensor
from prime_rl.transports.weights.nixl.graph import TensorReplayPlan
from prime_rl.transports.weights.nixl.trainer_tensor_table import TrainerTensor
@dataclass(frozen=True)
+3 -3
View File
@@ -43,7 +43,7 @@ def format_log_message(
log_dir: Path,
trainer: bool = False,
orchestrator: bool = False,
evaluator: bool = False,
evals: bool = False,
inference: bool = False,
job_log: bool = False,
train_env_names: list[str] | None = None,
@@ -68,8 +68,8 @@ def format_log_message(
log_lines.append(f"{i2}{'All ranks:':<{col - 1}}tail -F {log_dir}/trainer/torchrun/*/*/*/*.log")
if orchestrator:
log_lines.append(f"{i1}{'Orchestrator:':<{col}}tail -F {log_dir}/orchestrator.log")
if evaluator:
log_lines.append(f"{i1}{'Evaluator:':<{col}}tail -F {log_dir}/evaluator.log")
if evals:
log_lines.append(f"{i1}{'Evals:':<{col}}tail -F {log_dir}/evals.log")
if inference:
log_lines.append(f"{i1}{'Inference:':<{col}}tail -F {log_dir}/inference.log")
if num_infer_nodes > 1:
+1 -1
View File
@@ -11,7 +11,7 @@ from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.orchestrator.algo import EchoAlgorithm, stamp_advantages, stamp_loss_routing
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.orchestrator.types import Rollout
from prime_rl.transport.types import TrainingSample
from prime_rl.transports.rollouts.types import TrainingSample
FROZEN = {"name": "org/ref-model", "base_url": "http://ref:8001/v1"}

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