Compare commits

...
Author SHA1 Message Date
15d6c81974 feat: online evals during sft (#3256)
* Add online evals to the SFT entrypoint

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

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

Online evals are single-node only for now.

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

* Harden the SFT online-eval launcher and evaluator

Address review findings on the initial implementation:

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

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

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

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

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

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

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

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

* Make the trainer own the shared W&B run

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

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

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

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

* Add an SFT-flavored W&B overview view

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

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

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

* address online-eval review findings

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

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

* address pr review comments

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

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

* address self-review comments

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

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

* bring back the evaluator weights_dir field

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

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

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

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

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

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

* alias num_eval_gpus/num_eval_nodes for the infer deployment knobs

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

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

* fix alias precedence via pydantic-config bump

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

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

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

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

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

* floor prime-pydantic-config at 0.4.3

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

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

---------

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

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-17 13:38:54 -07:00
d8f3d01016 perf(docker): split the uv dependency layer and add registry-backed build cache (#3279)
* perf(docker): cache the dependency sync independently of source edits

A one-line change under src/ currently busts the uv sync layer (source is
COPY'd before the sync) and re-downloads ~5 GB of wheels + recompiles
mamba-ssm. Split the sync in two:

- a manifests stage collects every pyproject.toml + uv.lock; the deps layer
  syncs against that skeleton with --no-install-workspace and the four path
  editables skipped, so it only busts when project metadata changes
- the source layer copies the real trees and reruns the original sync, which
  now only installs the first-party editables

Also fix the uv cache mount (UV_CACHE_DIR is /usr/local/share/uv/cache but
the mount targeted /app/.cache/uv, so it never cached anything) and add a
.dockerignore so local builds stop shipping .venv trees into the context
(packages/prime-rl-configs/.venv is 439 MB and was baked into local images
via COPY packages/). .git stays in the context: the pretend-version script
resolves submodule versions from .git/modules.

Validated: uv sync --locked --dry-run with the deps-layer flags against the
skeleton tree (linux, uv 0.11.9) resolves all 551 packages and plans 422
installs with no first-party editables and no lockfile errors.

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

* perf(ci): registry-backed BuildKit cache for image builds

setup-buildx-action creates a fresh builder per job, so every CI build is
cold even when nothing changed. Cache to ghcr buildcache-<arch> tags with
mode=max so the builder-stage dependency layer is reusable across runs;
blobs already present in GHCR are not re-uploaded.

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

* perf(docker): stop shipping .git in the cache and re-pushing immutable layers

Profiling the first warm build (run 31912669079) showed three avoidable
costs on top of the structural cache round-trip:

- the manifests stage COPY'd the full context into /ctx, so the ~735 MB
  .git landed in a layer that mode=max exports to the registry cache on
  every build; exclude it (it holds no pyprojects)
- the runtime stage copied the volatile /app remainder before the big
  immutable venv trees, so every code change re-executed and re-compressed
  the nvidia/torch/vllm/flash_attn copies; move the volatile layer last
- the "Remove unnecessary packages" step costs ~70s on the amd64 runner;
  only run it when the disk is actually tight

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

* chore(docker): condense build comments

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-16 22:33:54 -07:00
minh hoangandGitHub 7b97965bb3 fix(tests): migrate remaining --wandb.* flags to --monitors.wandb.* (#3280) 2026-08-16 10:01:07 -07:00
b8d9553c0f feat: overlap CPU optimizer with backward (#3234)
* feat: chunked per-layer optimizer step with stream-overlapped CPU offload

The CPUOffloadOptimizer now performs the optimizer.step() per-transformer-layer
instead of all-at-once. Each layer's optimizer states are moved to GPU, the step
runs for that layer only, and states are moved back to CPU before the next layer.

This bounds peak GPU optimizer-state memory to ~one layer's worth (plus one
prefetched layer for overlap) instead of the full model's, preventing OOM when
weight + grad + all_opt_states exceeds available VRAM.

H2D and D2H transfers are pipelined on dedicated CUDA streams so the next layer's
states are prefetched while the current layer computes, and the previous layer's
states are evicted while the next layer computes.

Pinned-memory D2H is fixed to pre-allocate the pinned destination and async-copy
into it, avoiding a race where pin_memory() reads a tensor whose async copy hasn't
completed.

Muon's per-group step counter is synced after all chunks complete, since the
param_groups are temporarily swapped during chunked stepping.

* feat: add on/off config for chunked offload and stream overlap

Add  and  config options
to independently toggle per-layer chunking and stream-overlapped H2D/D2H.

When stream is disabled, the chunked step uses a simple sequential
move→step→move loop with no CUDA stream logic, making the code path clearer
and easier to debug.

* chore: default optim_cpu_offload_chunked and optim_cpu_offload_stream to false

* fix: address bugbot review issues

1. Async D2H checkpoint corruption (HIGH): Add torch.cuda.synchronize()
   after _move_states('cpu') in state_dict() and in ckpt.py's
   AppState.state_dict() to ensure async pinned D2H copies complete
   before CPU tensors are read.

2. Incomplete stream dependency chain (MEDIUM): Replace wait_stream-only
   finish in _step_chunked_streamed with torch.cuda.synchronize() to
   block CPU. Add h2d_stream.wait_stream(d2h_stream) before prefetching
   chunk i+1 to prevent racing with the previous chunk's D2H into the
   same pinned CPU buffers.

3. First step OOM (HIGH): The init step now uses the same chunked path
   instead of a full optimizer.step() that materializes all states on
   GPU at once. States are created per-chunk and immediately evicted.

4. Defaults disagree (MEDIUM): Align setup_optimizer defaults for
   cpu_offload_chunked and cpu_offload_stream with config defaults
   (both False).

Also add torch.cuda.synchronize() at the end of _step_chunked (no-stream
path) to ensure async D2H completes before returning.

* fix: always sync step counters in _sync_step_counters

Remove the 'if step in group' guard so _sync_step_counters always writes
group['step'] = orig_step + 1. This handles optimizers that lazily create
the step key on per-chunk copies (e.g. Muon) where the original groups
might not have had the key set yet.

* fix: evaluate closure only once per chunked step (not per chunk)

Pass closure only to the first chunk's optimizer.step() and None to the
rest, so loss/grad recomputation happens once per training step rather than
once per layer.

* refactor: clean up CPUOffloadOptimizer for readability

- Remove redundant section separators and verbose docstrings
- Inline _build_chunk_param_groups into _step_chunk
- Inline _chunk_param_ids into _move_chunk_states
- Simplify _move_states to iterate values() directly
- Shorten comments to be targeted, not narrative

* fix: record_stream on D2H to prevent caching allocator race, align stream default

1. HIGH - Streamed D2H memory race: call record_stream on GPU tensors before
   replacing them during async D2H copy, so the caching allocator doesn't reuse
   their storage while the copy is still in flight on d2h_stream. Guard with
   is_cuda since some optimizer state tensors (e.g. AdamW step counter) live on CPU.

2. LOW - Stream default disagrees: change CPUOffloadOptimizer.__init__ stream
   default from True to False to match config and setup_optimizer defaults.

* fix: accurate docs for stream-mode GPU memory bound

Update docs, config docstring, and class docstring to say 'about one
layer's worth (two with stream overlap)' instead of 'a single layer's
worth', since stream overlap keeps up to ~3 layers resident on GPU
during the prefetch/D2H/compute overlap window.

* fix: restore param_groups in finally block to handle optimizer.step() errors

If optimizer.step() raises inside _step_chunk, the try/finally ensures
param_groups are restored to the original full set, preventing subsequent
steps from only updating a single chunk's parameters.

* revert: remove try/finally from _step_chunk per AGENTS.md philosophy

Let errors propagate — if optimizer.step() raises, training crashes
anyway and there's no point restoring param_groups.

* refactor: always use stream overlap when chunked, remove stream toggle

The stream path already caps GPU residency at 2 layers (prefetch waits for
eviction via h2d_stream.wait_stream(d2h_stream)), so the non-stream sequential
path and the stream config toggle are unnecessary. Removes optim_cpu_offload_stream
config field, the _step_chunked method, and the stream parameter from
CPUOffloadOptimizer and setup_optimizer.

* refactor: always chunk+stream when CPU offloading, remove chunked toggle

Removes optim_cpu_offload_chunked config field entirely. When
optim_cpu_offload is enabled, the optimizer step is always performed
per-transformer-layer with stream-overlapped H2D/D2H transfers (max 2
layers on GPU). This eliminates the non-chunked code path, the separate
_step_chunked_streamed method, and one config flag.

For large models (where offloading matters) chunked+stream is faster
than all-at-once because transfers overlap with compute. For small
models the absolute overhead is negligible.

* refactor: make stream param required in _move_chunk_states

Stream is always passed now — removes the None fallback, default_stream()
context manager, and all stream is not None guards.

* test: add parity tests for CPUOffloadOptimizer vs plain AdamW

Tests that per-layer chunked+stream stepping produces identical parameters
and optimizer states as all-at-once stepping, plus a state_dict round-trip
test.

* fix: remove redundant isinstance branch in test helper

* docs: remove chunked offload paragraph from scaling docs per review

* feat: make chunked optimizer offload opt-in per S1ro1 review

Adds optim_cpu_offload_chunked config flag (default False). When disabled,
CPUOffloadOptimizer uses the simple all-at-once path (move all states to
GPU, step, move back). When enabled, uses per-layer chunked stepping with
stream-overlapped H2D/D2H (max 2 layers on GPU).

Also adds torch.cuda.synchronize() to load_state_dict for async D2H safety.

* fix: reuse CUDA streams across steps to prevent memory leak

Creating new torch.cuda.Stream() on every step() caused the caching
allocator to hold onto memory via record_stream references on dead
streams. Streams are now created once in __init__ and reused.

* feat: stream FSDP gradients through CPU offload

* feat: fuse CPU offload with public FSDP hooks

* refactor: expose optimizer offload config

* refactor: always stream pinned offload transfers

* refactor: name CPU optimizer execution explicitly

* refactor: clarify CPU step config name

* chore: clarify offload runtime logging

* feat: run gradient-offloaded optimizer steps on CPU

* refactor: name fused optimizer offload full

* feat: restore gradient-only optimizer offload

* fix: keep GLM-5.2 weight broadcast within GPU memory at 4-node scale

With 4 train nodes the resident FP32 master shards are ~87 GiB/rank and the
per-layer broadcast (full expert gather + fp8 conversion) peaked ~49 GiB above
that, OOMing the post-step broadcast once training transients filled the cache.

- empty_cache() before broadcast so cached training pools are reusable
- drop consumed expert tensors eagerly and quantize into preallocated stacks
  instead of list+torch.stack copies (~49 -> ~31 GiB transient per layer)

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

* fix: preallocate pinned gradient buffers before the first collective

The post-accumulate offload hook runs inside FSDP foreach_reduce on the
autograd thread; lazily cudaHostAlloc'ing the staging buffer there stalls
against the device while peer ranks' NCCL kernels spin waiting for this
rank's next collective — a distributed deadlock (faulthandler-confirmed:
autograd thread at optim.py empty_like(pin_memory=True) under
_fsdp_collectives foreach_reduce; deterministic at 78 layers, independent of
seq len, act-offload, hook design, or staging pageability). Pinning is only
safe before any collective exists, so allocate accumulator + staging for
every param at manager init.

Cost: the staging set is now always allocated (~equal to the accumulator
set) even for single-micro-batch steps; a config gate can refine this later.

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

* fix: propagate dist timeout to device-mesh sub process groups

init_process_group applies the configured timeout only to the default PG;
device-mesh sub-groups fall back to torch's 10-minute module default, so
dist_timeout_seconds never reached the PGs doing the real work. Long
single-rank host phases (e.g. init-time pinned-buffer preallocation skew
across nodes) then trip peer watchdogs at 600s.

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

* perf: slab-allocate pinned gradient offload buffers

~800 per-param cudaHostAllocs (~1.4 TiB/node) took 10-20 minutes at init with
large node-to-node skew; one pinned slab per dtype for accumulators and one
for staging pins the same bytes in a handful of driver calls. Per-param
buffers become 256-byte-aligned views into the slabs.

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

* feat: overlap CPU optimizer with backward

* perf: fuse CPU gradient scaling into AdamW

* perf: add native CPU AdamW kernel

* perf: halve full-offload PCIe traffic

* harden native optimizer offload pipeline

* document optimizer offload handover

* chore(bench): add offload baseline configs and measured GLM-5 RAM feasibility

Config pack for the handover baseline matrix: Qwen3-30B-A3B four-variant
offload comparison and the GLM-5 one-node proxy, all validated with --dry-run.
Meta-device parameter counts show the 22-layer proxy (190.8B params, 2.78 TiB
CPU state) exceeds a 2 TiB node, and the four-node full-model job needs
2.71 TiB/node; handover.md updated with the measured feasibility numbers.

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

* fix(bench): 8-GPU deployment and CPU thread budget for offload baselines

The SFT entrypoint defaults deployment.num_gpus to 1, and the launcher
defaults OMP_NUM_THREADS to 1, which serializes the CPU optimizer
(measured 15.7 s/step vs 6.5 s at 28 threads/rank on 8xH200).

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

* feat: offload pipeline timing diagnostics and opt-in NUMA binding

Per-step wall-time counters for the bounded pipeline (D2H event wait, ring
slot waits, BF16-to-FP32 materialization, native Adam, post-backward drain),
logged at debug level. Profiling on 8xH200 showed the pipeline floor is
host-DRAM-bandwidth-bound: the Adam kernel takes ~3.4s/step against a ~0.4s
compute estimate and does not scale with OMP threads.

optim_cpu_offload.numa_bind pins each rank's CPUs to its GPU's NUMA node
before state allocation so first-touch keeps slabs and OMP threads local
(measured 6.39s -> 6.13s per step at seq 8K on Qwen3-30B-A3B).

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

* docs: one-node 8xH200 offload baseline results in handover

Four-variant matrix and 2K-64K sweep for Qwen3-30B-A3B with bit-identical
losses throughout. The short-sequence pipeline floor is DRAM-bandwidth-bound;
with numa_bind, native full offload beats no-offload from 16K per-GPU sequence
upward while roughly halving peak HBM. Benchmark configs enable numa_bind.

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

* fix: skip weight pre-download for random-init debug runs

pre_download_model fetched the full weight snapshot even when
debug.random_init never reads it — for GLM-5 that is ~1.4 TB pulled into
the shared HF cache. Random-init runs now fetch only config and tokenizer
files. GLM-5 proxy config drops to 20 layers to fit measured H200 node RAM.

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

* docs: GLM-5 20-layer proxy results on one 8xH200 node

16K/32K/64K native full offload with numa_bind: ~18s/step CPU Adam for
21.4B params/rank, exposed drain shrinking from 17.4s at 16K to 6.9s at
64K. 20 layers is the RAM/HBM ceiling for a 2.95 TiB H200 node.

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

* docs: GLM-5 8-layer no-offload vs full-offload comparison

10 layers OOMs an H200 with resident optimizer state at 16K; at 8 layers
full offload trails at 16K (38% TPS retained), wins outright at 32K (117%),
and is the only variant that runs at 64K. Halves peak HBM throughout.

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

* docs: state full offload's BF16 gradient-rounding semantics

Gradients reduce in FP32 but FSDP2 materializes them in the sharded
parameter's dtype — BF16 for the full-offload compute model — so full
offload rounds each reduced gradient to BF16 once before the FP32 CPU
update. An FP32-transport option is structurally blocked (FSDP2 has no
grad-dtype override), so document the semantics in the config, the
training skill, and the handover, and point to state-only offload as
the gradient-bit-faithful mode.

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

* docs: correct handover baselines — repo default is state offload

The 'no offload' rows measured the default state-offload path;
add the true GPU-resident baseline table (requires
--model.optim-cpu-offload None) and relabel accordingly.

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

* feat!: CPU optimizer offload is full offload only, disabled by default

optim_cpu_offload previously defaulted to state-only offload and carried
three modes (state-only, gradients, full) with separate streaming paths.
State-only streamed ~60 GiB/rank of optimizer state over PCIe every step
and cost ~45% of throughput at seq 8K against a GPU-resident baseline.

Now the option means one thing: full offload (FP32 masters, moments, and
gradients on CPU, optimizer overlapped with backward), enabled by setting
model.optim_cpu_offload, disabled by default so the baseline keeps
optimizer state on GPU. numa_bind defaults to true. Removes the GPU-
chunked step, state-move machinery, and per-mode branching; example
configs that enabled the old default drop the line.

Validated: config suite, dry-runs, full-native smoke with DCP checkpoint
at step 2 and resume (exact loss parity), torch-backend smoke, no-offload
default smoke.

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

* Make CPU optim multithreading by overwriting num-thread but without oversubscring intra-op parallelsism threads

* chore(bench): drop the OMP_NUM_THREADS workaround superseded by auto thread budget

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

* chore: trim optimizer offload artifacts

* docs: trim optimizer offload scaling guide

* refactor trainer optimizer modules

* restore state-only optimizer offload

* revert unrelated GLM-5 changes

* fix conflicts with current main

* refactor: make full offload setup explicit

* refactor: rename full optimizer offload config

* fix: refresh offload masters on model-only resume

* refactor: simplify optimizer offload interface

* fix: return checkpoint state to CPU

* fix: adapt offload resume test to run dirs

* fix: preserve mixed dtypes in full offload

* fix: restrict full offload to AdamW

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Mario Sieg <mario.sieg.64@gmail.com>
2026-08-15 19:03:57 -07:00
9975d8868d feat: refactor monitors (#3275)
* feat!: refactor monitors into prime_rl.monitors

Replace the Monitor class hierarchy (ABC with five abstract methods,
NoOpMonitor, MultiMonitor) with a flat prime_rl.monitors module: only
log() is abstract, monitors register once per process, and module-level
functions fan out to them without ever raising. Construction is now
side-effect free - run registration and file handles move to init(),
and a monitor whose init() fails is disabled instead of crashing.

Sample logging becomes episode logging: PrimeMonitor regroups rollouts
into vf.Episodes and uploads one platform sample per episode, sharing
verifiers' build_samples with eval --push so training and eval samples
land identically (native episode in info.native_wrapper). The W&B
sample/eval tables and distribution logging are removed, and
PrimeMonitor now runs on the shared BackgroundAsync helper.

Config surface is grouped under [monitors]: monitors.wandb,
monitors.file, and orchestrator-only monitors.prime, replacing the
wandb / file_monitor / prime_monitor siblings and WandbWithExtrasConfig.

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

* refactor: wandb subpackage, finalize instead of final summary

Split the W&B monitor into monitors/wandb/{base,overview} for
readability. Rename save_final_summary to finalize - its real job is
finalizing the platform run (with the last metrics as summary); the
local final_summary.json files had no consumers and are no longer
written. Drop close() from the interface and registry: nothing called
it, and PrimeMonitor's shutdown (mark unfinalized runs failed, stop the
background loop) lives in __del__.

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

* fix: track monitors/wandb package, drop prime monitor tests

The repo-wide **/wandb gitignore (W&B run dirs) silently swallowed the
new src/prime_rl/monitors/wandb/__init__.py, so CI imported the
subpackage as an empty namespace package. Negate the pattern for the
source directory.

The prime monitor unit tests mostly re-asserted the parquet column
mapping; drop them per the conservative-tests policy.

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

* refactor!: loop-native monitor uploads, drop usage reporter

Rewrite PrimeMonitor's async plumbing: uploads are fire-and-forget
tasks on the orchestrator's event loop with short-lived httpx clients
(connect retries inside the transport), replacing the hand-rolled
background thread + event loop + fork handling and the per-request
retry/backoff helpers. Construction now takes only the monitor config;
runtime context moves to init(), whose kwargs each monitor names
itself.

Remove the usage reporter entirely (per-step training-token billing
posts, PI_USAGE_* env-gated) and with it background_async.py, which
has no users left.

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

* fix: gate wandb-coupled paths on the registered monitor

The inference-metrics collector and the dispatcher's wandb flag were
gated on the config block, but they log to the global W&B session,
which only exists when WandbMonitor's init succeeded. A failed init
now disables the monitor instead of crashing, so the config gate let
the collector reach wandb.define_metric before any wandb.init. Gate
on monitors.get(WandbMonitor) instead.

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

* fix!: crash on monitor init failure

A configured monitor that cannot initialize (bad credentials, dead
platform) previously logged a warning and disabled itself, so the run
silently continued without its metrics. Let the exception propagate -
if monitoring was requested, losing it should stop the run.

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

* perf: offload episode serialization, atexit for failed-run marking

Move the parquet/JSON encode of episodes off the orchestrator's event
loop into the upload task via asyncio.to_thread - build_samples dumps
every episode's full model, and running it inline stalled dispatch on
every logging step (the one heavy call in finalize_train_batch not
already off-loop).

Replace PrimeMonitor's __del__ with an atexit hook for marking
unfinalized runs failed: __del__ can fire during interpreter teardown,
where httpx can no longer create a client, so the status PUT silently
died in 'Exception ignored' noise.

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

* refactor: sentinel-free non-finite JSON sanitizer

Test each child before recursing into it instead of signalling drops
through the recursive return value, which needed a module-global
sentinel object and dense sentinel-comparing comprehensions.

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

* refactor: type the JSON sanitizer, recurse via inner function

Rename drop_non_finite_json_values to sanitize with a recursive Json
type alias; the path-threading recursion moves into an inner walk()
so the public signature carries no recursion plumbing.

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

* chore: untype the sanitizer

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

* refactor: sanitize returns dropped paths

Return (sanitized, dropped_paths) instead of filling a caller-supplied
list - call sites were allocating an empty list just to read it back.

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

* chore: gather monitor configs into configs.monitors

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

* feat!: slim the monitor config surface

- FileMonitorConfig.filename -> path (relative to output_dir, absolute wins)
- drop EpisodeLogConfig: episodes upload every step, all of them - the
  serialization is off-loop and the platform is the sample store, so
  interval/sampling knobs bought nothing but config surface
- hardcode the platform base URL and API key env var, resolve the
  frontend URL from the Prime CLI config; PrimeMonitorConfig shrinks to
  name + team_id, with run_name renamed to name to match wandb (still
  auto-set from run.name / the W&B run name)
- WandbConfig -> WandbMonitorConfig; the rl entrypoint's Shared*
  monitor configs move back next to RLConfig in rl.py

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

* chore: rename _SAMPLE_SCHEMA to SAMPLE_SCHEMA

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

* chore: move sanitize into utils

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

* refactor: inline the prime monitor sanitize wrapper

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

* refactor: drop prime monitor state flags and last-metrics replay

Register the atexit mark-failed hook only when this process created
the platform run and unregister it in finalize - the hook's presence
replaces the _registered/_finalized flags. Drop _last_metrics: every
step's metrics were already posted, so replaying the last dict as the
finalize summary was redundant; /finalize now gets an empty summary.
Use the BASE_URL constant directly instead of mirroring it on self.

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

* refactor: extract TrainRun owning the platform HTTP lifecycle

PrimeMonitor delegates create/log/finalize/status/sample-upload to a
small synchronous TrainRun that owns one persistent httpx client
(transport-level connect retries, connection reuse). The monitor keeps
episode grouping, parquet building, sanitization, and the
fire-and-forget task plumbing - each TrainRun call runs in a worker
thread via asyncio.to_thread. TrainRun is the seam the train SDK can
subsume later, the way wandb.Run backs the W&B monitor.

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

* refactor: TrainRun.create takes explicit fields

The OrchestratorConfig-to-payload mapping moves to the monitor;
TrainRun's surface is plain API fields, keeping it prime-rl-agnostic.

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

* chore: rename init run_config param to config

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

* chore: type prime monitor init config as BaseConfig

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

* feat: polymorphic log, episodes through monitors, defaults on

monitors.log and Monitor.log accept either a metrics dict or a list of
vf.Episode with cohort coordinates (train/eval x all/effective); the
base class dispatches to log_metrics / log_episodes. The orchestrator's
trace-file writes move into FileMonitor (get_trace_path and
save_rollouts are inlined there), so all episode sinks share one entry
point: the streamed all cohort, the trained effective batch, and eval
epochs each fan out once, off-loop. group_episodes moves to
orchestrator utils and episode grouping happens at the source -
PrimeMonitor takes episodes and filters to the trained cohort.

The wandb and file monitors are now on by default (--no-monitors.wandb
/ --no-monitors.file to opt out), the registry list is MONITORS, and
wandb/base.py is renamed to wandb/monitor.py.

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

* refactor!: PRL_RUN_ID is the run identity, drop monitor run ids

Rollout provenance is stamped with the launcher's $PRL_RUN_ID (or a
local uuid for standalone runs) instead of the monitor identity, so
Monitor.run_id and the monitors.run_id() helper go away. The RUN_ID
env handshake is removed with them: PrimeMonitor always creates a
platform run, and its id stays internal to TrainRun.

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

* feat: singular episode overload, wandb log_episodes stub

log accepts a bare vf.Episode alongside dicts and episode lists (the
base dispatch wraps it); log_episodes is abstract now, so WandbMonitor
gets an explicit no-op.

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

* feat: fully async monitors, TrainRun mirrors wandb exit behavior

The whole Monitor surface is async now (init/log/log_metrics/
log_episodes/finalize); the orchestrator awaits the fan-out directly
and the sync trainers wrap calls in asyncio.run. FileMonitor offloads
record serialization via asyncio.to_thread (awaited, so appends to one
trace file never interleave); PrimeMonitor's fire-and-forget goes back
to plain create_task since nothing submits cross-thread anymore.

TrainRun now owns its exit behavior the way wandb.Run does: create arms
an atexit hook that marks the run failed, finalize marks it completed
and disarms the hook. The orchestrator finalizes monitors only on a
clean exit, so a crashed run reports failed on the platform just like
it does on W&B.

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

* fix: keep the platform mark-failed atexit path synchronous

asyncio.run at atexit dies with 'cannot schedule new futures after
interpreter shutdown': async httpx resolves DNS via run_in_executor,
and concurrent.futures marks itself shut down via
threading._register_atexit, which runs before module atexit hooks.
The failure PUT uses sync httpx; everything else on TrainRun stays
async.

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

* fix: make wandb monitor init async

The async conversion missed WandbMonitor.init's multi-line signature,
so the registry awaited None and setup crashed.

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

* fix: finish the W&B run explicitly, align monitor logs

In (experimental) shared mode the SDK's atexit finish does not land the
run state, so even clean runs decayed to 'crashed' - WandbMonitor's
finalize now calls wandb.finish(exit_code=0) off-loop. Every monitor
logs one info line at init and finalize; per-step uploads only warn on
failure.

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

* refactor: task cache and parquet builder out of the monitor

TrainRun owns the fire-and-forget submit machinery; the episode
parquet builder becomes a module helper below both classes.

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

* fix: propagate monitor disables, shared prime block, drain on finalize

With the monitor sub-configs defaulting to enabled, the rl entrypoint's
--no-monitors.wandb / --no-monitors.file were silently ignored - the
CLI disable (the string 'None') now propagates to both sub-configs like
the enable does. [monitors.prime] joins the shared block, propagated to
the orchestrator only (no trainer platform integration yet), and
PrimeMonitorConfig loses team_id (the Prime CLI team applies).

TrainRun.finalize now drains in-flight uploads first, so the final
step's metrics and episodes land before the run is marked completed.
Also prunes FileMonitor's unreachable pre-init guard.

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

* chore: fix stale TrainRun docstring

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

* feat: sample platform episode uploads to 10% capped at 128

All episodes every step overwhelms the platform's ingestion; sample
min(10% of the step's episodes, 128) instead. Lift once the prime
traces SDK is integrated.

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

* chore: take the first episodes instead of sampling

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

* docs: note monitor run names inherit run.name

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

* fix: wandb off by default, migrate integration test flags

The integration tests still passed the old --wandb.* flags, failing
config validation; and wandb-on-by-default would crash credential-less
environments at init. W&B is opt-in again (the file monitor stays on
by default); the tests use --monitors.wandb.*.

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

* fix: sample platform episode uploads randomly

The effective batch is ordered by group finalization, so a prefix
over-represents early-finishing envs on multi-env runs.

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

* feat: restore the RUN_ID attach handshake

Managed launches pre-create the platform run and inject its id via
$RUN_ID; attaching instead of registering prevents duplicate runs.
RUN_ID stays a dedicated backend channel - PRL_RUN_ID can't signal
attachment because the rl launcher always mints one locally. Attached
runs skip the atexit failure marking (the backend owns that); finalize
still marks them completed on clean exit.

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

* chore: restore pre-refactor episode upload defaults

Every 10th step, unsampled - what log_extras defaulted to on main.

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

* docs: episode upload cadence

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 17:39:40 -07:00
de626e934e chore: bump vllm-router wheel to v0.2.0 (#3274)
First release from the router's rebase onto upstream vllm-project/router
(PrimeIntellect-ai/router#51): upstream v0.1.15+18 with the re-ported
fork features (P/D routed-experts merge validated byte-identical against
a single-engine baseline, model-aware routing, phantom-load fixes,
validation 500->400 rewrite incl. vLLM 0.26 wording, per-run usage
metrics, JWT auth).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 12:36:30 -07:00
132 changed files with 5734 additions and 2560 deletions
+16
View File
@@ -0,0 +1,16 @@
# .git stays: docker-editable-pretend-versions.sh reads .git/modules via the bind mount.
**/.venv
**/__pycache__
**/*.py[cod]
**/.pytest_cache
**/.ruff_cache
**/.mypy_cache
**/wandb
**/checkpoints
**/weights
**/broadcasts
**/rollouts
**/torchrun
.claude
.vscode
*.ipynb
+11 -1
View File
@@ -161,7 +161,13 @@ jobs:
steps:
- name: Remove unnecessary packages
run: |
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
# Deleting the preinstalled toolchains costs ~70s; skip unless disk is tight.
avail_gb=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
if [ "${avail_gb:-0}" -lt 80 ]; then
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
else
echo "Skipping cleanup: ${avail_gb}G available on /"
fi
- name: Checkout
uses: actions/checkout@v5
@@ -198,6 +204,10 @@ jobs:
# rather than needlessly recompressed. Pulling zstd layers needs containerd >= 1.5
# or Docker >= 23.
outputs: type=image,push=true,compression=zstd,compression-level=3
# The per-job builder is ephemeral; mode=max caches builder-stage
# layers so warm builds skip the dependency sync.
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }}
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache-${{ matrix.suffix }},mode=max,image-manifest=true,oci-mediatypes=true,compression=zstd,compression-level=3
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
+1
View File
@@ -17,6 +17,7 @@ configs/endpoints.py
**/rollouts
**/logs
**/wandb
!src/prime_rl/monitors/wandb/
**/evals
**/run_*/
!configs/**/evals
+35 -10
View File
@@ -4,6 +4,16 @@
#inspired from https://github.com/astral-sh/uv-docker-example/blob/main/multistage.Dockerfile
# Every pyproject.toml + uv.lock, so the dependency sync below caches
# independently of source edits.
FROM nvidia/cuda:12.8.1-base-ubuntu24.04 AS manifests
# .git is ~735 MB, changes every commit, and would land in the registry cache.
COPY --exclude=.git . /ctx
RUN mkdir -p /manifests \
&& cd /ctx \
&& find . -name .git -prune -o -type f -name pyproject.toml -exec cp --parents {} /manifests/ \; \
&& cp uv.lock /manifests/
# Build stage - multi-arch base (supports amd64 + arm64)
FROM nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 AS builder
LABEL maintainer="prime intellect"
@@ -76,11 +86,23 @@ ENV UV_CACHE_DIR="/usr/local/share/uv/cache"
# the runtime stage's `COPY /app`
ENV UV_PROJECT_ENVIRONMENT="/app/.venv"
# Install Python dependencies (The gradual copies help with caching)
# Install Python dependencies
WORKDIR /app
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
# Third-party deps only — source edits don't bust this layer. First-party
# editables install in the source-layer sync below. No build-context bind
# mount here: .git would bust the cache every commit.
COPY --from=manifests /manifests /app
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra disagg --extra gpt-oss --extra quack --group mamba-ssm --locked --no-dev \
--no-install-workspace \
--no-install-package prime-rl-configs \
--no-install-package verifiers \
--no-install-package renderers \
--no-install-package prime-pydantic-config
COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY README.md /app/README.md
@@ -98,7 +120,7 @@ COPY scripts/docker-editable-pretend-versions.sh /app/scripts/docker-editable-pr
# /app/.git/modules to the read-only context before resolving versions.
ARG VERIFIERS_PRETEND_VERSION
ARG RENDERERS_PRETEND_VERSION
RUN --mount=type=cache,target=/app/.cache/uv \
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
--mount=type=bind,source=.,target=/build-context,readonly \
if [ -d /build-context/.git/modules ]; then mkdir -p /app/.git && ln -s /build-context/.git/modules /app/.git/modules; fi \
&& \
@@ -220,14 +242,9 @@ WORKDIR /app
# own layers. BuildKit compresses and pushes layers in parallel, so shipping the whole
# ~20 GB venv as one layer serialized the export behind a single compressor. Splitting
# also lets nodes pull the image in parallel. Keep the excludes below in sync with the
# per-tree copies that follow, or the data lands in the image twice.
COPY --from=builder --chown=appuser:appuser \
--exclude=.venv/lib/python3.12/site-packages/nvidia \
--exclude=.venv/lib/python3.12/site-packages/torch \
--exclude=.venv/lib/python3.12/site-packages/vllm \
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app /app
# per-tree copies above, or the data lands in the image twice.
# The volatile /app remainder goes last so a source edit re-pushes one layer,
# not all of them.
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/nvidia /app/.venv/lib/python3.12/site-packages/nvidia
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/torch /app/.venv/lib/python3.12/site-packages/torch
COPY --from=builder --chown=appuser:appuser /app/.venv/lib/python3.12/site-packages/vllm /app/.venv/lib/python3.12/site-packages/vllm
@@ -239,6 +256,14 @@ COPY --from=builder /opt/ucx /opt/ucx
COPY --chown=appuser:appuser scripts/docker-entrypoint.sh /app/docker-entrypoint.sh
RUN chmod +x /app/docker-entrypoint.sh
COPY --from=builder --chown=appuser:appuser \
--exclude=.venv/lib/python3.12/site-packages/nvidia \
--exclude=.venv/lib/python3.12/site-packages/torch \
--exclude=.venv/lib/python3.12/site-packages/vllm \
--exclude=.venv/lib/python3.12/site-packages/flash_attn \
--exclude=.venv/lib/python3.12/site-packages/flash_attn_2_cuda*.so \
/app /app
# Place executables in the environment at the front of the path
ENV PATH="/app/.venv/bin:$PATH"
ENV UCX_HOME=/opt/ucx
+1 -1
View File
@@ -146,7 +146,7 @@ def build_command(config: BenchmarkConfig, output_dir: Path) -> list[str]:
str(config.max_steps),
"--output-dir",
str(output_dir),
"--file-monitor.filename",
"--monitors.file.path",
"metrics.jsonl",
"--model.compile",
"--dist-timeout-seconds",
+1 -1
View File
@@ -11,7 +11,7 @@ num_infer_gpus = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
[monitors.wandb]
project = "alphabet-sort"
name = "alphabet-sort"
+1 -1
View File
@@ -10,7 +10,7 @@ num_infer_gpus = 1
[model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[wandb]
[monitors.wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
+1 -1
View File
@@ -11,7 +11,7 @@ num_infer_gpus = 1
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
+25 -2
View File
@@ -1,9 +1,11 @@
# SFT warmup for reverse-text on 2 GPUs. Dev-sized mirror of examples/basic/reverse-text/sft.toml.
# SFT warmup for reverse-text on 2 GPUs (1 train + 1 infer for online evals).
# Dev-sized mirror of examples/basic/reverse-text/sft.toml.
max_steps = 100
[deployment]
num_gpus = 2
num_train_gpus = 1
num_infer_gpus = 1
[ckpt] # Checkpoint at the end of training
@@ -17,3 +19,24 @@ batch_size = 32
[optim]
lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.sampling]
max_completion_tokens = 1024
[[eval.source]]
name = "reverse-text"
[eval.source.env.taskset]
id = "reverse-text"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
[inference]
+1 -1
View File
@@ -12,7 +12,7 @@ num_infer_gpus = 1
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
[monitors.wandb]
project = "wiki-search"
name = "wiki-search"
+1 -1
View File
@@ -8,7 +8,7 @@ seq_len = 8192
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
[monitors.wandb]
project = "wordle"
name = "wordle"
+1 -1
View File
@@ -3,7 +3,7 @@
max_steps = 20
[deployment]
num_gpus = 2
num_train_gpus = 2
[ckpt] # Checkpoint at the end of training
@@ -16,7 +16,7 @@ type = "filesystem"
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "reverse-text-ci"
name = "ci-rl-opd"
@@ -16,7 +16,7 @@ type = "filesystem"
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "reverse-text-ci"
name = "ci-rl-sft"
@@ -0,0 +1,21 @@
max_steps = 6
[ckpt]
skip_optimizer = true
skip_scheduler = true
[resume]
step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
optim_cpu_offload = false
full_offload = true
[optim]
lr = 0.0
[data]
name = "PrimeIntellect/Reverse-Text-SFT"
batch_size = 4
seq_len = 1024
+1 -1
View File
@@ -5,7 +5,7 @@ seq_len = 2048
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
[monitors.wandb]
project = "alphabet-sort"
name = "alphabet-sort"
+1 -1
View File
@@ -4,7 +4,7 @@ max_steps = 5000
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
[monitors.wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
+1 -1
View File
@@ -5,7 +5,7 @@ seq_len = 2048
num_train_gpus = 1
num_infer_gpus = 1
[wandb]
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
+1 -1
View File
@@ -5,7 +5,7 @@ seq_len = 4096
num_train_gpus = 4
num_infer_gpus = 4
[wandb]
[monitors.wandb]
project = "wiki-search"
name = "wiki-search"
+1 -1
View File
@@ -5,7 +5,7 @@ seq_len = 8192
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
[monitors.wandb]
project = "wordle"
name = "wordle"
+1 -1
View File
@@ -8,7 +8,7 @@ seq_len = 4096
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-echo"
+1 -1
View File
@@ -4,7 +4,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-rl"
+1 -1
View File
@@ -4,7 +4,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-max-rl"
+1 -1
View File
@@ -14,7 +14,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-mixed-grpo-opd"
+1 -1
View File
@@ -11,7 +11,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-opd"
+1 -1
View File
@@ -11,7 +11,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-opd-lora"
+1 -1
View File
@@ -4,7 +4,7 @@ seq_len = 4096
[model]
name = "Qwen/Qwen3-0.6B"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-rae"
+1 -1
View File
@@ -10,7 +10,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-self-distill"
+1 -1
View File
@@ -11,7 +11,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-sft"
+1 -1
View File
@@ -11,7 +11,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "algorithms-debug"
name = "debug-sft-lora"
+1 -1
+1 -1
View File
@@ -477,7 +477,7 @@ type = "repetition"
threshold = 0.4
```
Filtered rollouts still appear in W&B distributions, just not in the trainer batch — useful for spotting whether filtering is doing its job.
Filtered rollouts still appear in the W&B metrics, just not in the trainer batch — useful for spotting whether filtering is doing its job.
## Multi-Turn Trajectories
+2 -2
View File
@@ -218,7 +218,7 @@ PYTORCH_CUDA_ALLOC_CONF = "expandable_segments:False"
VLLM_USE_DEEP_GEMM = "1"
[orchestrator.env_vars]
PI_USAGE_BASE_URL = "https://..."
PRIME_LOG_LEVEL = "debug"
```
The `rl` launcher applies these the same way in both single-node and multi-node (SLURM) runs. Precedence, low to high:
@@ -257,7 +257,7 @@ Start from a shipped base config, override two fields on the CLI, and dry-run:
```bash
uv run rl @ examples/basic/reverse-text/rl.toml \
--wandb.name my-experiment \
--monitors.wandb.name my-experiment \
--trainer.optim.lr 5e-6 \
--output-dir /tmp/reverse-dry \
--run.name check \
+4 -10
View File
@@ -86,7 +86,8 @@ FSDP2 is the default model sharding strategy. By default the trainer fully shard
| `trainer.model.dp_replicate` | Number of dimensions to **replicate** instead of shard. Set to 2 to run 2-way DP replication × FSDP sharding within each replica — useful for very large clusters where pure FSDP communication dominates. |
| `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 only optimizer state. Mid-ground — small throughput cost, decent memory savings, especially at low GPU count. |
| `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. |
### Expert Parallelism
@@ -137,14 +138,7 @@ targets = ["norm", "attn_proj"] # see Reference for the full list per architect
### Optimizer Offloading
Offloading optimizer states to CPU is enabled by default (`optim_cpu_offload = true`) — a near-free memory win at low GPU counts:
```toml
[trainer.model]
optim_cpu_offload = true # already the default
```
Mutually exclusive with `fsdp_cpu_offload`. Muon doesn't support `fsdp_cpu_offload` but does support `optim_cpu_offload`.
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.
### LM Head Chunking
@@ -255,4 +249,4 @@ uv run sft @ sft.toml --data.type fake --max-steps 4
uv run trainer @ train.toml --data.fake --max-steps 4
```
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, enable the file monitor (`--file-monitor.filename metrics.jsonl`) and aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
Every step logs `Throughput`, `MFU`, and `Peak Mem.` to the console. For machine-readable numbers, the file monitor writes `metrics.jsonl` to the run's output directory by default (`monitors.file`); aggregate `perf/throughput`, `perf/mfu`, `time/step`, and `perf/peak_memory` from the run's `metrics.jsonl` — skip the first step, it is warmup. [`benchmarks/scripts/run_single_benchmark.py`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/benchmarks/scripts/run_single_benchmark.py) does exactly this and is what the CI benchmark matrix runs.
+68 -23
View File
@@ -70,8 +70,8 @@ A condensed view of the knobs you'll most often tune. For trainer-side paralleli
|---|---|
| `log.level` | Process log level for trainer + orchestrator (`info` default; falls back to `$PRIME_LOG_LEVEL`). Set per-process via `trainer.log.level` / `orchestrator.log.level`, or globally on the `rl` entrypoint to propagate to both. |
| `orchestrator.log.vf_level` | Env-worker / [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) log level (`info` default; `debug` is noisy but useful for env debugging). |
| `--wandb` (+ `--wandb.project`, `--wandb.name`) | Enable Weights & Biases logging. See [Weights & Biases](#weights--biases). |
| `--orchestrator.prime-monitor` | Stream metrics to the Prime Intellect platform (Prime Lab). See [Platform monitoring](#platform-monitoring). |
| `--monitors.wandb` (+ `--monitors.wandb.project`, `--monitors.wandb.name`) | Enable Weights & Biases logging. See [Weights & Biases](#weights--biases). |
| `--monitors.prime` | Stream metrics and episodes to the Prime Intellect platform (Prime Lab). See [Platform monitoring](#platform-monitoring). |
**Run management:**
@@ -171,11 +171,60 @@ See [Algorithms § Multi-Turn Trajectories](algorithms.md#multi-turn-trajectorie
The minimal SFT run trains `Qwen3-0.6B` on the `reverse-text` SFT dataset:
```bash
uv run sft @ examples/basic/reverse-text/sft.toml --wandb
uv run sft @ examples/basic/reverse-text/sft.toml --monitors.wandb
```
Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manages this for you — see [Scaling § SFT and Torchrun](scaling.md#sft-and-torchrun) for non-default layouts; multi-node SFT goes through [SLURM](scaling.md#slurm)).
### Online Evals
`uv run sft` can evaluate the model on rollout-based envs as it trains, reusing the RL orchestrator's eval machinery. Configure an `[eval]` block — the same shape as `[orchestrator.eval]`: multiple `[[eval.source]]` envs with per-source `interval` / `num_examples` / `group_size` / sampling overrides — plus an `[inference]` block for the vLLM server:
```toml
[eval]
interval = 25
num_examples = 32
[[eval.source]]
name = "reverse-text"
[eval.source.env.taskset]
id = "reverse-text"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
[inference]
[deployment]
num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evaluator` process next to the trainer. The handoff is the filesystem, not NCCL: the trainer writes an HF weight checkpoint at every step an eval env is due (in addition to `ckpt.interval`), and the evaluator watches `weights/step_{n}`, points the inference server at each stable checkpoint (`/update_weights` reload from disk), and runs the due envs against it — sequentially per checkpoint, so every epoch measures exactly one policy version. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final checkpoint always fires every env.
#### Multi-Node (Decoupled Trainer and Inference Pool)
On a `multi_node` deployment (SLURM), the trainer and the eval deployment are **two independent SLURM jobs**. `deployment.num_nodes` sizes the trainer job; `deployment.num_infer_nodes` sizes the eval job, which runs the inference pool (one vLLM engine per DP rank behind a single router, `gpus_per_node / inference.vllm.tensor_parallel_size` engines per node), one env server per eval source, and the evaluator:
```toml
[deployment]
type = "multi_node"
num_train_nodes = 2 # trainer job
num_infer_nodes = 1 # eval job (inference pool + evaluator)
[inference.vllm]
tensor_parallel_size = 8
[slurm]
job_name = "my-run"
```
The only coupling is weight checkpoints on the shared filesystem, so the jobs' lifetimes are independent: when training finishes, the trainer job exits and releases its nodes even while evals are still running; the eval job keeps draining pending checkpoints and exits after evaluating the final one (`max_steps` — without it the eval job never sees a final checkpoint and holds its allocation until walltime). Trainer and evaluator log to a single shared W&B run across both jobs — the trainer creates it, the evaluator finalizes it. Any train × inference layout works: `num_nodes` and `num_infer_nodes` are fully independent.
### SFT-Specific Knobs
| Knob | What it controls |
@@ -185,6 +234,7 @@ Multi-GPU and multi-node use torchrun under the hood (the `sft` entrypoint manag
| `data.seq_len` | Per-sample sequence length |
| `loss_mask.*` | Which roles contribute to loss (system / user / assistant / tool). |
| `val.interval` | Run validation every N steps; `val.data` mirrors `data` |
| `eval.interval` | Run online evals every N steps; see [Online Evals](#online-evals) |
### Important Metrics
@@ -192,8 +242,9 @@ Pulled from the console log and mirrored to W&B.
**Progress and loss:**
- `loss/mean` — main signal. Should decrease through the run.
- `val/loss` — validation loss when `[val]` is set, logged every `val.interval` steps.
- `loss/mean`, `loss/perplexity` — main signal. Should decrease through the run.
- `val/loss`, `val/perplexity` — validation metrics when `[val]` is set, logged every `val.interval` steps.
- `eval/{env}/...` — online eval metrics when `[eval]` is set, logged at each evaluated checkpoint step.
- `progress/epoch`, `progress/num_samples`, `progress/num_tokens` — dataset progress.
- `progress/<subset>/ratio_{samples,tokens}` — when training on multiple HF subsets/splits, the realized mixing ratio.
@@ -307,41 +358,35 @@ Pass `-s <session>` and `-o <run_dir>` (the run directory, `<output_dir>/<run_na
### Weights & Biases
W&B is off by default. Enable with `--wandb`:
W&B is off by default (the file monitor, which writes `metrics.jsonl` and the per-step trace files to the run directory, is on by default):
```bash
uv run rl @ rl.toml --wandb # default project, random name
uv run rl @ rl.toml --wandb.project my-proj --wandb.name run-42
uv run rl @ rl.toml --no-wandb # force-disable even if the TOML enables it
uv run rl @ rl.toml --monitors.wandb # default project, random name
uv run rl @ rl.toml --monitors.wandb.project my-proj --monitors.wandb.name run-42
uv run rl @ rl.toml --no-monitors.file # disable the local metric/trace files
```
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `wandb.offline = true`.
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `monitors.wandb.offline = true`.
By default, every 10 steps each process also logs a sample of prompts/completions (with rewards and advantages) and reward/advantage/entropy distributions as W&B tables. Tune via `--wandb.log-extras.interval` and `--wandb.log-extras.sample-ratio`, or disable subsets:
```bash
uv run rl @ rl.toml --wandb \
--orchestrator.wandb.log-extras.interval 50 \
--no-trainer.wandb.log-extras.distributions
```
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, every training run (RL and SFT) gets an **auto-created `overview` saved view** curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
### Platform Monitoring
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics, samples, and distributions to the platform dashboard. Bare flag uses defaults:
Register a run on the Prime Intellect platform (Prime Lab) and stream training metrics and episodes to the platform dashboard. Bare flag uses defaults:
```bash
uv run rl @ rl.toml --orchestrator.prime-monitor
uv run rl @ rl.toml --monitors.prime
```
Or set it in TOML:
```toml
[orchestrator.prime_monitor]
run_name = "my-experiment"
[monitors.prime]
name = "my-experiment"
```
Every 10th step the orchestrator uploads the step's episodes (full conversations with rewards and advantages) to the run's sample viewer.
Requires `PRIME_API_KEY` (set via `prime login` or env var) and an allowlisted team. Currently internal-only.
## Rules of Thumb
+2 -3
View File
@@ -21,7 +21,7 @@ num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
[monitors.wandb]
project = "search-ablations"
name = "glm45air-search"
@@ -50,7 +50,6 @@ attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
@@ -87,7 +86,7 @@ num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.0
[orchestrator.prime_monitor]
[monitors.prime]
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
+2 -3
View File
@@ -32,7 +32,7 @@ num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
[monitors.wandb]
project = "swe-ablations"
name = "glm45air-scaleswe"
@@ -61,7 +61,6 @@ attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
@@ -111,7 +110,7 @@ summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["glm45air-swe"]
[orchestrator.prime_monitor]
[monitors.prime]
# --- Eval: SWE-Bench Verified at step 0 + every 20 steps, rlm harness on prime ---
+2 -3
View File
@@ -22,7 +22,7 @@ num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
[monitors.wandb]
project = "terminal-ablations"
name = "glm45air-terminal"
@@ -51,7 +51,6 @@ attn = "flash_attention_3"
cp = 4
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
@@ -88,7 +87,7 @@ num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.prime_monitor]
[monitors.prime]
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
+1 -2
View File
@@ -9,7 +9,7 @@ name = "glm5-llmd"
[log]
level = "debug"
[wandb]
[monitors.wandb]
project = "glm5-llmd"
name = "base"
@@ -93,7 +93,6 @@ attn = "flash_attention_2" # ignored with GLM5
fused_lm_head_token_chunk_size = 1024
cp = 4 # context parallel for the 131K seq len
ep = 8
optim_cpu_offload = true
[trainer.model.quantization]
type = "fp8"
+1 -2
View File
@@ -3,7 +3,7 @@ seq_len = 131072
[log]
level = "debug"
[wandb]
[monitors.wandb]
project = "glm5-pd-disag"
[weight_broadcast]
@@ -43,7 +43,6 @@ name = "zai-org/GLM-5"
impl = "custom"
attn = "flash_attention_2" # dsa is skipping flash attn anyway
fused_lm_head_token_chunk_size = 2048
optim_cpu_offload = true
ep = 8
[trainer.model.ac]
+1 -1
View File
@@ -20,7 +20,7 @@ job_name = "swe-qwen30b"
[ckpt]
interval = 100
[wandb]
[monitors.wandb]
project = "intellect-3.1"
[trainer.model]
+1 -1
View File
@@ -20,7 +20,7 @@ job_name = "swe-minimax"
[ckpt]
interval = 100
[wandb]
[monitors.wandb]
project = "minimax-swe"
[trainer.model]
+2 -3
View File
@@ -18,7 +18,7 @@ num_train_nodes = 4
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
[monitors.wandb]
project = "nemotron-3-super"
name = "nemotron-3-super-swe"
@@ -47,7 +47,6 @@ cp = 8
cp_style = "ulysses"
ep = 8
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
@@ -95,7 +94,7 @@ summarize_at_tokens = [65536, 131072]
[orchestrator.train.source.env.agent.runtime]
labels = ["nemotron-3-super-swe"]
[orchestrator.prime_monitor]
[monitors.prime]
[orchestrator.eval]
interval = 20
+1 -1
View File
@@ -20,7 +20,7 @@ job_name = "math-qwen30b"
[ckpt]
interval = 100
[wandb]
[monitors.wandb]
project = "qwen30b-math"
[trainer.model]
+1 -1
View File
@@ -20,7 +20,7 @@ job_name = "swe-qwen30b"
[ckpt]
interval = 100
[wandb]
[monitors.wandb]
project = "qwen30b-swe"
[trainer.model]
+1 -1
View File
@@ -9,7 +9,7 @@ type = "multi_node"
num_train_nodes = 1
num_infer_nodes = 1
[wandb]
[monitors.wandb]
project = "general-agent-debug"
name = "qwen3-30b-a3b-rlm"
+2 -2
View File
@@ -94,8 +94,8 @@ We train with LoRA (rank 32, alpha 64) for 100 steps.
# In the `Trainer` pane
uv run rl @ examples/basic/alphabet-sort/rl.toml \
--run.name rl \
--wandb.project ... \
--wandb.name ...
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/rl/weights/step_100`. Upload it to HF to be able to use it as the final model for evaluation.
+1 -1
View File
@@ -7,7 +7,7 @@ seq_len = 2048
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
[monitors.wandb]
project = "alphabet-sort"
name = "alphabet-sort"
+2 -2
View File
@@ -12,6 +12,6 @@ Schedule training locally on a node with 8 GPUs
```bash
uv run rl @ examples/basic/hendrycks-sanity/rl.toml \
--wandb.project your-project \
--wandb.name your-run
--monitors.wandb.project your-project \
--monitors.wandb.name your-run
```
+1 -1
View File
@@ -1,6 +1,6 @@
max_steps = 5000
[wandb]
[monitors.wandb]
project = "hendrycks-sanity"
name = "hendrycks-sanity"
+6 -6
View File
@@ -44,8 +44,8 @@ To train on a single GPU, run
# In the `Trainer` pane
uv run sft @ examples/basic/reverse-text/sft.toml \
--run.name sft \
--wandb.project ... \
--wandb.name ...
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
To train on multiple GPUs, run
@@ -56,8 +56,8 @@ uv run torchrun \
--local-ranks-filter 0 \
--nproc-per-node ... \
src/prime_rl/trainer/sft/train.py @ examples/basic/reverse-text/sft.toml \
--wandb.project ... \
--wandb.name ...
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
This should write a weight checkpoint in `outputs/sft/weights/step_100`. Upload it to HF to be able to use it as the base model for RL.
@@ -79,8 +79,8 @@ For the RL we will only do 20 steps at 8x16 rollouts, for a total batch size of
uv run rl @ examples/basic/reverse-text/rl.toml \
--model.name ... \
--run.name rl \
--wandb.project ... \
--wandb.name ...
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/rl/weights/step_20`. As before, let's upload it to HF.
+1 -1
View File
@@ -4,7 +4,7 @@ seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
+27 -2
View File
@@ -8,7 +8,32 @@ name = "PrimeIntellect/Qwen3-0.6B"
[data]
name = "willcb/R1-reverse-wikipedia-paragraphs-v1-1000"
seq_len = 4096
batch_size = 32
batch_size = 32
[optim]
lr = 2e-5
lr = 2e-5
[eval]
interval = 25
num_examples = 32
[eval.sampling]
max_completion_tokens = 1024
[[eval.source]]
name = "reverse-text"
[eval.source.env.taskset]
id = "reverse-text"
[eval.source.env.agent.harness]
id = "null"
[eval.source.env.agent.runtime]
type = "subprocess"
[inference]
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
+2 -2
View File
@@ -94,8 +94,8 @@ Train with the unified config file:
# In the `Trainer` pane
uv run rl @ examples/basic/wiki-search/rl.toml \
--run.name rl \
--wandb.project your-project-name \
--wandb.name your-run-name
--monitors.wandb.project your-project-name \
--monitors.wandb.name your-run-name
```
The unified config file automatically configures:
+1 -1
View File
@@ -8,7 +8,7 @@ num_infer_gpus = 6
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
[monitors.wandb]
project = "wiki-search"
name = "wiki-search"
+6 -6
View File
@@ -46,8 +46,8 @@ To train on a single GPU, run
# In the `Trainer` pane
uv run sft @ examples/basic/wordle/sft.toml \
--run.name sft \
--wandb.project ... \
--wandb.name ...
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
To train on multiple GPUs, run
@@ -58,8 +58,8 @@ uv run torchrun \
--local-ranks-filter 0 \
--nproc-per-node ... \
src/prime_rl/trainer/sft/train.py @ examples/basic/wordle/sft.toml \
--wandb.project ... \
--wandb.name ...
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
After training completes, you will find the final weight checkpoint in `outputs/sft/weights/step_20`. Upload it to HF to be able to use it as the base model for RL we will do in the next section.
@@ -82,8 +82,8 @@ Finally, we will do multi-turn RL against the `wordle` environment using the mod
uv run rl @ examples/basic/wordle/rl.toml \
--model.name ... \
--run.name rl \
--wandb.project ... \
--wandb.name ...
--monitors.wandb.project ... \
--monitors.wandb.name ...
```
This will write a weight checkpoint in `outputs/rl/weights/step_100`. As before, let's upload it to HF.
+1 -1
View File
@@ -5,7 +5,7 @@ seq_len = 8192
num_train_gpus = 2
num_infer_gpus = 6
[wandb]
[monitors.wandb]
project = "wordle"
name = "wordle"
+2 -2
View File
@@ -8,7 +8,7 @@ optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
impl = "custom"
attn = "flash_attention_2"
ep = 8 # keep in sync with deployment.num_gpus
ep = 8 # keep in sync with deployment.num_train_gpus
[renderer]
name = "auto"
@@ -52,4 +52,4 @@ save_adapter_separately = true
[deployment]
type = "single_node"
num_gpus = 8
num_train_gpus = 8
+1 -1
View File
@@ -6,7 +6,7 @@ group_size = 16
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
@@ -4,7 +4,7 @@ max_steps = 20
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
seq_len = 2048
[wandb]
[monitors.wandb]
project = "reverse-text"
name = "reverse-text"
+1 -1
View File
@@ -6,7 +6,7 @@ readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.4.2",
"prime-pydantic-config>=0.4.3",
"renderers>=0.1.9",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
@@ -0,0 +1,84 @@
from pathlib import Path
from pydantic import Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.orchestrator import EvalConfig
from prime_rl.configs.shared import ClientConfig, LogConfig
from prime_rl.utils.config import BaseConfig
class OnlineEvalConfig(EvalConfig):
"""Online evals against a live inference server, driven by weight checkpoints
on disk. Extends the orchestrator ``EvalConfig`` (sources, sampling, intervals)
with the client of the inference deployment and evaluator-side knobs."""
client: ClientConfig = ClientConfig()
"""Client of the inference server evals run against. Auto-wired from the
``[inference]`` block when the launcher manages the server."""
env_server_base_port: int = Field(5000, ge=1, le=65535)
"""First port of the env-server port range: the eval source at position ``i`` is
served at ``tcp://127.0.0.1:<base + i>``. Sources with an explicit ``serve.address``
keep it instead, without shifting the other sources' ports."""
max_inflight_episodes: int = Field(128, ge=1)
"""Maximum eval episodes in flight — one episode is one agent run against an env server."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
Same contract as ``OrchestratorConfig.env_addresses``: the launcher binds env
servers at exactly these addresses and the evaluator connects to them."""
return {
("eval", source.resolved_name): source.serve.address
or f"tcp://127.0.0.1:{self.env_server_base_port + index}"
for index, source in enumerate(self.source)
}
class EvaluatorConfig(BaseConfig):
"""``uv run evaluator``: watch a weights directory for new HF checkpoints, point
the inference server at each one (``/update_weights`` from disk), and run the
configured evals against the updated weights. The ``sft`` launcher writes this
config; it can also be run standalone against any trainer that writes
``weights/step_{n}`` HF checkpoints with ``STABLE`` markers."""
model: str = "Qwen/Qwen3-0.6B"
"""Name the inference server serves the model under — the ``model`` field of every
eval request and the startup model check. Auto-filled from ``model.name`` by the
``sft`` launcher; the name stays fixed across checkpoint reloads (weights are
swapped in place), so per-step results are told apart by ``eval/{env}/policy_version``."""
eval: OnlineEvalConfig
"""Eval sources, sampling, intervals, and the inference client."""
weights_dir: Path | None = None
"""Directory to watch for ``step_{n}`` HF weight checkpoints. The ``sft`` launcher
fills it from ``ckpt.output_dir`` when checkpoints are redirected to another volume;
defaults to ``<output_dir>/weights``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — rollout traces and logs are written as
subdirectories. Shared with the trainer."""
max_steps: int | None = None
"""Trainer step at which the run ends. The final checkpoint always fires every
eval env, and the evaluator exits after processing it. If None, the evaluator
runs until terminated."""
resume_step: int | None = None
"""Trainer step the run resumed from. When set, the startup (base-model) eval is
skipped; set ``eval.retrigger_on_resume`` to re-fire interval-aligned evals at
this step."""
log: LogConfig = LogConfig()
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
@model_validator(mode="after")
def auto_setup_weights_dir(self):
if self.weights_dir is None:
self.weights_dir = self.output_dir / "weights"
return self
@@ -0,0 +1,46 @@
from pathlib import Path
from prime_rl.utils.config import BaseConfig
class WandbMonitorConfig(BaseConfig):
project: str = "prime-rl"
"""W&B project to log to."""
entity: str | None = None
"""W&B entity to log to."""
name: str | None = None
"""W&B run name. Inherits ``run.name`` when unset."""
group: str | None = None
"""W&B group."""
tags: list[str] | None = None
"""W&B tags attached to the run."""
offline: bool = False
"""Run W&B in offline mode."""
class FileMonitorConfig(BaseConfig):
path: Path = Path("metrics.jsonl")
"""Path of the JSONL file, relative to the component's ``output_dir`` (absolute paths win)."""
class PrimeMonitorConfig(BaseConfig):
name: str | None = None
"""Run name shown on the platform. Inherits ``run.name`` when unset."""
class MonitorsConfig(BaseConfig):
wandb: WandbMonitorConfig | None = None
"""Log metrics to Weights & Biases. Off by default; enable with ``--monitors.wandb``."""
file: FileMonitorConfig | None = FileMonitorConfig()
"""Log metrics and episode traces to the run's output directory. On by default; disable with ``--no-monitors.file``."""
class OrchestratorMonitorsConfig(MonitorsConfig):
prime: PrimeMonitorConfig | None = None
"""Log metrics and episodes to the Prime Intellect platform. If None, disabled."""
@@ -9,17 +9,15 @@ from prime_rl.configs.algorithm import (
AlgoConfig,
GRPOAlgoConfig,
)
from prime_rl.configs.monitors import OrchestratorMonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
EnvVars,
FileMonitorConfig,
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
ResumeConfig,
TransportConfig,
WandbWithExtrasConfig,
ZMQTransportConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
@@ -437,12 +435,8 @@ class OrchestratorConfig(BaseConfig):
env_vars: EnvVars = {}
"""Extra environment variables for the orchestrator process(es). Merged on top of the launcher defaults."""
wandb: WandbWithExtrasConfig | None = None
prime_monitor: PrimeMonitorConfig | None = None
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, orchestrator metrics are appended to ``<output_dir>/metrics.jsonl``."""
monitors: OrchestratorMonitorsConfig = OrchestratorMonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``, ``monitors.prime``)."""
collect_inference_metrics: bool = True
"""Collect inference-server metrics (requires wandb)."""
@@ -519,13 +513,13 @@ class OrchestratorConfig(BaseConfig):
return self
@model_validator(mode="after")
def auto_setup_prime_monitor_run_name(self):
"""Default ``prime_monitor.run_name`` to the W&B run name when monitoring
is enabled and the user hasn't named the prime-monitor run explicitly."""
if self.prime_monitor is None or self.prime_monitor.run_name is not None:
def auto_setup_prime_monitor_name(self):
"""Default ``monitors.prime.name`` to the W&B run name when monitoring
is enabled and the user hasn't named the platform run explicitly."""
if self.monitors.prime is None or self.monitors.prime.name is not None:
return self
if self.wandb is not None and self.wandb.name:
self.prime_monitor.run_name = self.wandb.name
if self.monitors.wandb is not None and self.monitors.wandb.name:
self.monitors.prime.name = self.monitors.wandb.name
return self
@model_validator(mode="after")
@@ -7,6 +7,7 @@ from pydantic import Field, model_validator
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig
from prime_rl.configs.orchestrator import (
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
)
@@ -21,7 +22,6 @@ from prime_rl.configs.orchestrator import (
)
from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
ResumeConfig,
RunConfig,
SlurmConfig,
@@ -70,7 +70,7 @@ class SharedWandbConfig(BaseConfig):
"""W&B entity."""
name: str | None = None
"""W&B run name."""
"""W&B run name. Inherits ``run.name`` when unset."""
group: str | None = None
"""W&B group."""
@@ -86,13 +86,26 @@ class SharedWandbConfig(BaseConfig):
if self.offline:
raise ValueError(
"W&B shared mode is always on for the rl entrypoint and requires server "
"connectivity; wandb.offline = true is not supported. Use offline mode "
"via the sub-config wandb blocks (trainer.wandb.offline, "
"orchestrator.wandb.offline) if you really need it per-process."
"connectivity; monitors.wandb.offline = true is not supported. Use offline mode "
"via the sub-config wandb blocks (trainer.monitors.wandb.offline, "
"orchestrator.monitors.wandb.offline) if you really need it per-process."
)
return self
class SharedMonitorsConfig(BaseConfig):
"""The ``rl`` entrypoint's shared monitor configs, propagated to trainer and orchestrator."""
wandb: SharedWandbConfig | None = None
"""Shared W&B config. Propagated to trainer and orchestrator."""
file: FileMonitorConfig | None = None
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator."""
prime: PrimeMonitorConfig | None = None
"""Prime platform monitor. Propagated to the orchestrator only — the trainer has no platform integration."""
class SharedCheckpointConfig(BaseConfig):
output_dir: Path | None = None
"""Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir``."""
@@ -259,11 +272,8 @@ class RLConfig(BaseConfig):
resume: ResumeConfig | None = None
"""Resume the run from a checkpoint (point at it with the previous run's ``run.name``). Without ``[ckpt]`` the run loads the checkpoint but saves no new ones. If None, does not resume."""
wandb: SharedWandbConfig | None = None
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
file_monitor: FileMonitorConfig | None = None
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator. If None, falls back to the sub-config settings."""
monitors: SharedMonitorsConfig = SharedMonitorsConfig()
"""Shared monitor configs (``monitors.wandb``, ``monitors.file``). Propagated to trainer and orchestrator; ``[orchestrator.monitors.prime]`` configures the platform monitor."""
model: SharedModelConfig | None = None
"""Shared model config. If None, falls back to the sub-config model settings."""
@@ -408,18 +418,18 @@ class RLConfig(BaseConfig):
"""Default the W&B and Prime platform run names to ``run.name``.
Explicit names always win: only unset names inherit. Runs after the
orchestrator's own ``auto_setup_prime_monitor_run_name``, so an explicitly
orchestrator's own ``auto_setup_prime_monitor_name``, so an explicitly
set W&B name still takes precedence for the platform run name. The run
identity itself is runtime-only ($PRL_RUN_ID / $PRL_RUN_NAME, set by the
``rl`` entrypoint), never sub-config.
"""
self._resolve_run_name()
for wandb in (self.wandb, self.trainer.wandb, self.orchestrator.wandb):
for wandb in (self.monitors.wandb, self.trainer.monitors.wandb, self.orchestrator.monitors.wandb):
if wandb is not None and wandb.name is None:
wandb.name = self.run.name
prime_monitor = self.orchestrator.prime_monitor
if prime_monitor is not None and prime_monitor.run_name is None:
prime_monitor.run_name = self.run.name
for prime in (self.monitors.prime, self.orchestrator.monitors.prime):
if prime is not None and prime.name is None:
prime.name = self.run.name
return self
### Validate shared configs (after sub-config construction)
@@ -2,20 +2,22 @@ import uuid
import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from urllib.parse import urlparse
from pydantic import Field, model_validator
from pydantic import AliasChoices, Field, model_validator
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
from renderers.base import MODEL_RENDERER_MAP
from prime_rl.configs.evaluator import OnlineEvalConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
EnvVars,
FileMonitorConfig,
HeartbeatConfig,
ResumeConfig,
RunConfig,
SlurmConfig,
TrainerLogConfig,
WandbConfig,
)
from prime_rl.configs.trainer import (
AdamWConfig,
@@ -143,24 +145,33 @@ class BaseDeploymentConfig(BaseConfig):
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
type: Literal["single_node"] = "single_node"
num_gpus: int = 1
"""GPUs to use."""
num_train_gpus: int = 1
"""GPUs allocated to the trainer."""
num_infer_gpus: int = Field(1, validation_alias=AliasChoices("num_infer_gpus", "num_eval_gpus"))
"""GPUs allocated to inference for online evals (alias: ``num_eval_gpus``). Only used when an ``[inference]`` block is configured."""
@model_validator(mode="after")
def validate_gpu_count(self):
if self.num_gpus > self.gpus_per_node:
raise ValueError(f"num_gpus ({self.num_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
if self.num_train_gpus > self.gpus_per_node:
raise ValueError(f"num_train_gpus ({self.num_train_gpus}) exceeds gpus_per_node ({self.gpus_per_node}).")
return self
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
type: Literal["multi_node"] = "multi_node"
num_nodes: int = 2
num_train_nodes: int = Field(2, ge=1)
"""Training nodes."""
num_infer_nodes: int = Field(0, ge=0, validation_alias=AliasChoices("num_infer_nodes", "num_eval_nodes"))
"""Inference nodes for online evals (alias: ``num_eval_nodes``). Submitted as a separate SLURM job, decoupled
from the trainer job: the handoff is weight checkpoints on the shared filesystem,
so the eval job can outlive the trainer job (evals drain after training ends) and
exits after evaluating the final checkpoint."""
nodes_per_fsdp_group: int | None = None
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_nodes / nodes_per_fsdp_group``."""
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
SFTDeploymentConfig: TypeAlias = Annotated[
@@ -184,6 +195,15 @@ class SFTConfig(BaseConfig):
val: SFTValConfig | None = None
"""Validation configuration. If None, no validation runs."""
eval: OnlineEvalConfig | None = None
"""Online evaluation configuration: rollout-based evals against a live inference
server that reloads the trainer's HF weight checkpoints from disk. If None, no
online evals run."""
inference: InferenceConfig | None = None
"""Inference server for online evals. If None (with ``eval`` set), the launcher
does not start a server and evals connect to ``eval.client.base_url``."""
optim: OptimizerConfig = AdamWConfig()
scheduler: SchedulerConfig = ConstantSchedulerConfig()
@@ -195,10 +215,8 @@ class SFTConfig(BaseConfig):
log: TrainerLogConfig = TrainerLogConfig()
wandb: WandbConfig | None = None
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, metrics are appended to ``<output_dir>/metrics.jsonl``."""
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
run: RunConfig = Field(default_factory=RunConfig)
"""Run metadata. ``run.name`` names the run directory under ``output_dir``."""
@@ -225,8 +243,8 @@ class SFTConfig(BaseConfig):
self.run.name = "--".join([*parts, uuid.uuid4().hex[:8]]).lower()
if self.run.dir is None:
self.run.dir = self.run.name
if self.wandb is not None and self.wandb.name is None:
self.wandb.name = self.run.name
if self.monitors.wandb is not None and self.monitors.wandb.name is None:
self.monitors.wandb.name = self.run.name
return self
matmul_precision: Literal["highest", "high", "medium"] = "high"
@@ -267,10 +285,26 @@ class SFTConfig(BaseConfig):
return data
deployment = data.get("deployment")
if isinstance(deployment, dict) and deployment.get("type") == "multi_node":
for key in ("num_gpus",):
for key in ("num_train_gpus", "num_infer_gpus"):
deployment.pop(key, None)
return data
@model_validator(mode="before")
@classmethod
def propagate_model_to_inference(cls, data):
"""Fill ``inference.vllm.model`` from ``model.name`` before InferenceConfig
construction, so its parser auto-resolution sees the right model name."""
if not isinstance(data, dict):
return data
inference = data.get("inference")
model = data.get("model")
name = model.get("name") if isinstance(model, dict) else None
if isinstance(inference, dict) and name:
vllm = inference.setdefault("vllm", {})
if isinstance(vllm, dict):
vllm.setdefault("model", name)
return data
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
@@ -284,12 +318,152 @@ class SFTConfig(BaseConfig):
self.optim.max_norm = None
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")
return self
@model_validator(mode="after")
def full_optimizer_offload_disables_grad_clipping(self):
if self.model.full_offload and self.optim.max_norm is not None:
warnings.warn(
"Gradient clipping prevents optimizer-in-backward overlap with CPU optimizer offload. "
"Automatically setting optim.max_norm to None (disabled).",
stacklevel=1,
)
self.optim.max_norm = None
return self
@model_validator(mode="after")
def validate_deployment(self):
if self.deployment.type == "multi_node" and self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
return self
@model_validator(mode="after")
def auto_setup_online_eval(self):
"""Wire online evals: require weight checkpoints (the disk handoff to
inference) and connect the eval client to the launcher-managed server."""
if self.eval is None:
if self.inference is not None:
raise ValueError("[inference] is only used for online evals — add an [eval] block or remove it.")
return self
# The trainer's HF weight checkpoints are how inference picks up new policies.
if self.ckpt is None:
self.ckpt = CheckpointConfig()
if self.ckpt.weights is None or self.ckpt.skip_gather_master_weights:
raise ValueError(
"Online evals require HF weight checkpoints. Enable ckpt.weights and "
"disable ckpt.skip_gather_master_weights."
)
if self.ckpt.keep_last is not None or self.ckpt.keep_interval is not None:
warnings.warn(
"ckpt.keep_last / ckpt.keep_interval can delete a weight checkpoint before the "
"evaluator consumes it when evals run slower than training - such steps are "
"skipped with a warning instead of evaluated.",
stacklevel=2,
)
if self.deployment.type == "multi_node":
# Decoupled deployment: the launcher submits a dedicated SLURM job running the
# inference pool (one engine per DP rank behind a router) plus the evaluator.
if self.inference is None:
raise ValueError(
"Multi-node online evals require an [inference] block - the launcher submits "
"a dedicated SLURM job running the inference pool and the evaluator."
)
if self.deployment.num_infer_nodes < 1:
raise ValueError("Online evals on a multi-node deployment require deployment.num_infer_nodes >= 1.")
if self.inference.router is None:
raise ValueError(
"Multi-node online evals require an inference router - the eval job starts one "
"router in front of the per-rank engines. Remove inference.router = 'None'."
)
if self.inference.vllm.model != self.model.name:
raise ValueError(
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
f"({self.model.name}). Remove inference.vllm.model to inherit it."
)
if self.deployment.gpus_per_node % self.inference.vllm.tensor_parallel_size != 0:
raise ValueError(
f"deployment.gpus_per_node ({self.deployment.gpus_per_node}) must be divisible by "
f"inference.vllm.tensor_parallel_size ({self.inference.vllm.tensor_parallel_size})."
)
if self.inference.weight_broadcast.type != "filesystem":
raise ValueError(
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
)
if self.max_steps is None:
warnings.warn(
"Online evals without max_steps: the evaluator never sees a final checkpoint, "
"so the eval SLURM job holds its allocation until its walltime.",
stacklevel=2,
)
# The client is wired at runtime by the eval sbatch script (the router and
# per-rank admin URLs are only known once SLURM assigns hosts).
return self
if self.inference is None:
warnings.warn(
"Online evals are configured without an [inference] block - the launcher will not "
f"start an inference server. Make sure one is running at eval.client.base_url "
f"({self.eval.client.base_url}) with weight_broadcast.type = 'filesystem', "
"otherwise the evaluator will hang waiting for it. If a router fronts the "
"deployment, set eval.client.admin_base_url to the engine URLs - admin ops "
"(pause/update_weights/resume) must bypass the router.",
stacklevel=2,
)
return self
total_gpus = self.deployment.num_train_gpus + self.deployment.num_infer_gpus
if total_gpus > self.deployment.gpus_per_node:
raise ValueError(
f"Total GPU count ({total_gpus} = {self.deployment.num_train_gpus} train + "
f"{self.deployment.num_infer_gpus} infer) exceeds gpus_per_node "
f"({self.deployment.gpus_per_node})."
)
if self.inference.vllm.model != self.model.name:
raise ValueError(
f"inference.vllm.model ({self.inference.vllm.model}) does not match model.name "
f"({self.model.name}). Remove inference.vllm.model to inherit it."
)
# Fill inference capacity with DP ranks (mirrors RLConfig.auto_setup_deployment).
num_infer_gpus = self.deployment.num_infer_gpus
vllm = self.inference.vllm
if num_infer_gpus != vllm.data_parallel_size * vllm.tensor_parallel_size:
if num_infer_gpus % vllm.tensor_parallel_size != 0:
raise ValueError(
f"deployment.num_infer_gpus ({num_infer_gpus}) must be divisible by "
f"inference.vllm.tensor_parallel_size ({vllm.tensor_parallel_size})."
)
vllm.data_parallel_size = num_infer_gpus // vllm.tensor_parallel_size
if vllm.api_server_count < vllm.data_parallel_size and not vllm.enable_lora:
vllm.api_server_count = vllm.data_parallel_size
if self.inference.weight_broadcast.type != "filesystem":
raise ValueError(
"Online evals reload weights from disk — inference.weight_broadcast.type must be 'filesystem'."
)
host = self.inference.server.host or "localhost"
client = self.eval.client
if "base_url" not in client.model_fields_set:
client.base_url = f"http://{host}:{self.inference.server.port}/v1"
elif urlparse(client.base_url).port != self.inference.server.port:
raise ValueError(
f"eval.client.base_url port ({urlparse(client.base_url).port}) does not match "
f"inference.server.port ({self.inference.server.port})."
)
if self.inference.router is not None and "admin_base_url" not in client.model_fields_set:
# Admin ops (pause/update_weights/resume) must bypass the router and hit
# the engine directly.
client.admin_base_url = [f"http://{host}:{self.inference.backend_port}/v1"]
return self
@model_validator(mode="after")
def validate_typed_renderer(self):
"""Require a typed renderer whenever SFT renders real samples."""
@@ -402,12 +576,12 @@ class SFTConfig(BaseConfig):
def auto_setup_deployment(self):
if self.deployment.type == "multi_node":
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_nodes % self.deployment.nodes_per_fsdp_group != 0:
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
raise ValueError(
f"deployment.num_nodes ({self.deployment.num_nodes}) must be divisible by "
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
)
self.model.dp_replicate = self.deployment.num_nodes // self.deployment.nodes_per_fsdp_group
self.model.dp_replicate = self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
return self
@model_validator(mode="after")
@@ -11,7 +11,16 @@ from prime_rl.utils.config import BaseConfig
# and the single shared W&B run. The launcher always sets these last, so allowing them in
# `env_vars` would be a silent no-op (or, on multi-node, a footgun) — reject them instead.
PROTECTED_ENV_VARS = frozenset(
{"CUDA_VISIBLE_DEVICES", "PRL_RUN_ID", "PRL_RUN_NAME", "WANDB_RUN_ID", "WANDB_SHARED_MODE", "WANDB_SHARED_LABEL"}
{
"CUDA_VISIBLE_DEVICES",
"PRL_RUN_ID",
"PRL_RUN_NAME",
"WANDB_RUN_ID",
"WANDB_SHARED_MODE",
"WANDB_SHARED_LABEL",
"WANDB_SHARED_PRIMARY",
"WANDB_SHARED_FINISHER",
}
)
@@ -192,78 +201,6 @@ class TrainerLogConfig(LogConfig):
"""Trainer ranks to show in console output. Passed to ``torchrun --local-ranks-filter``."""
class LogExtrasConfig(BaseConfig):
samples: bool = True
"""Log prompt/response samples."""
distributions: bool = True
"""Log distributions (rewards, advantages, etc.)."""
interval: int = Field(10, ge=1)
"""Step interval between extras logs."""
sample_ratio: float | None = Field(None, ge=0.0, le=1.0)
"""Fraction of rollouts to log per step. The effective cap is ``len(rollouts) * sample_ratio``; 1.0 = all, 0.5 = half, 0.0 = none."""
class WandbConfig(BaseConfig):
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
project: str = "prime-rl"
"""W&B project to log to."""
entity: str | None = None
"""W&B entity to log to."""
name: str | None = None
"""W&B run name."""
group: str | None = None
"""W&B group."""
tags: list[str] | None = None
"""W&B tags attached to the run."""
offline: bool = False
"""Run W&B in offline mode."""
class WandbWithExtrasConfig(WandbConfig):
log_extras: LogExtrasConfig | None = LogExtrasConfig()
"""Extras logging configuration. If None, no extras are logged."""
class FileMonitorConfig(BaseConfig):
"""Enable the local JSONL metric sink (``<output_dir>/metrics.jsonl``).
Present (non-None) enables it, mirroring the ``prime_monitor`` pattern. Metrics
are the same scalars sent to W&B; useful for self-hosted dashboards or when W&B
is disabled.
"""
filename: str = "metrics.jsonl"
"""Name of the JSONL file written under the component's ``output_dir``."""
class PrimeMonitorConfig(BaseConfig):
base_url: str = "https://api.primeintellect.ai/api/v1/rft"
"""Base URL for the Prime Intellect monitoring API."""
api_key_var: str = "PRIME_API_KEY"
"""Environment variable name containing the Prime Intellect API key, resolved via ``os.getenv``."""
log_extras: LogExtrasConfig | None = LogExtrasConfig()
"""Extras logging configuration. If None, no extras are logged."""
run_name: str | None = None
"""Run name shown on the platform. Defaults to the W&B run name when set, otherwise the platform auto-generates one."""
team_id: str | None = None
"""Team ID to associate the run with."""
frontend_url: str | None = None
"""Frontend base URL used for the dashboard link printed after registration. Defaults to the Prime CLI frontend URL when unset."""
class HeartbeatConfig(BaseConfig):
url: str
"""URL to send the heartbeat to."""
@@ -2,18 +2,17 @@ import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic import BeforeValidator, Field, model_validator
from prime_rl.configs.monitors import MonitorsConfig
from prime_rl.configs.shared import (
BaseModelConfig,
EnvVars,
FileMonitorConfig,
HeartbeatConfig,
MetricsServerConfig,
ResumeConfig,
TrainerLogConfig,
TransportConfig,
WandbConfig,
ZMQTransportConfig,
)
from prime_rl.utils.config import BaseConfig
@@ -55,6 +54,38 @@ class ActivationOffloadingConfig(BaseConfig):
"""Max activations kept in flight while offloading. More activations smooth overlap at the cost of GPU memory."""
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.
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.
"""
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."""
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."""
def _normalize_optimizer_in_backward_offload(value: Any) -> Any:
if value is True:
return {}
if value is False:
return None
return value
OptimizerInBackwardOffload = Annotated[
OptimizerInBackwardOffloadConfig | None, BeforeValidator(_normalize_optimizer_in_backward_offload)
]
class CompileConfig(BaseConfig):
fullgraph: bool = False
"""Compile transformer blocks with ``fullgraph=True``."""
@@ -168,6 +199,9 @@ class ModelConfig(BaseModelConfig):
optim_cpu_offload: bool = True
"""Offload only optimizer states (momentum, variance) to CPU, keeping weights on GPU. Avoids the H2D all-gather overhead of FSDP CPU offload while still saving GPU memory."""
full_offload: OptimizerInBackwardOffload = None
"""Full CPU optimizer offload: FP32 masters, moments, and gradients live in CPU RAM and the optimizer runs on CPU, overlapped with backward. Enable with ``true`` or a ``[model.full_offload]`` section; disabled by default."""
reshard_after_forward: bool = True
"""Reshard the model after each forward pass."""
@@ -270,8 +304,13 @@ class ModelConfig(BaseModelConfig):
@model_validator(mode="after")
def cpu_offload_mutual_exclusion(self):
if self.fsdp_cpu_offload and self.optim_cpu_offload:
raise ValueError("Cannot enable both fsdp_cpu_offload and optim_cpu_offload. Use one or the other.")
if self.fsdp_cpu_offload and (self.optim_cpu_offload or self.full_offload):
raise ValueError("Cannot combine fsdp_cpu_offload with optimizer CPU offloading.")
if self.optim_cpu_offload and self.full_offload:
raise ValueError(
"Cannot enable both optim_cpu_offload and full_offload. "
"Set optim_cpu_offload=false when enabling full optimizer offload."
)
return self
@model_validator(mode="after")
@@ -583,10 +622,8 @@ class TrainerConfig(BaseConfig):
log: TrainerLogConfig = TrainerLogConfig()
wandb: WandbConfig | None = None
file_monitor: FileMonitorConfig | None = None
"""Local JSONL metric sink. If set, trainer metrics are appended to ``<output_dir>/metrics.jsonl``."""
monitors: MonitorsConfig = MonitorsConfig()
"""Metric monitors (``monitors.wandb``, ``monitors.file``)."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
@@ -635,6 +672,23 @@ class TrainerConfig(BaseConfig):
self.optim.max_norm = None
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")
return self
@model_validator(mode="after")
def full_optimizer_offload_disables_grad_clipping(self):
if self.model.full_offload and self.optim.max_norm is not None:
warnings.warn(
"Gradient clipping prevents optimizer-in-backward overlap with CPU optimizer offload. "
"Automatically setting optim.max_norm to None (disabled).",
stacklevel=1,
)
self.optim.max_norm = None
return self
@model_validator(mode="after")
def vlms_require_bfloat16(self):
if self.model.vlm is not None and (
@@ -93,19 +93,22 @@ def propagate_shared_fields(data: Any) -> Any:
propagate("ckpt.keep_last", "trainer.ckpt.keep_last", "orchestrator.ckpt.keep_last")
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval", "orchestrator.ckpt.keep_interval")
# [wandb] leaves. (Bare empty ``[wandb]`` block enablement is at the end.)
# ``wandb.name`` flows verbatim to both sub-configs — shared W&B mode is
# [monitors.wandb] leaves. (Bare empty ``[monitors.wandb]`` block enablement is at the end.)
# ``monitors.wandb.name`` flows verbatim to both sub-configs — shared W&B mode is
# always on for the rl entrypoint, so the legacy ``-trainer`` /
# ``-orchestrator`` suffix split is gone.
propagate("wandb.project", "trainer.wandb.project", "orchestrator.wandb.project")
propagate("wandb.entity", "trainer.wandb.entity", "orchestrator.wandb.entity")
propagate("wandb.name", "trainer.wandb.name", "orchestrator.wandb.name")
propagate("wandb.group", "trainer.wandb.group", "orchestrator.wandb.group")
propagate("wandb.tags", "trainer.wandb.tags", "orchestrator.wandb.tags")
propagate("wandb.offline", "trainer.wandb.offline", "orchestrator.wandb.offline")
for leaf in ("project", "entity", "name", "group", "tags", "offline"):
propagate(
f"monitors.wandb.{leaf}",
f"trainer.monitors.wandb.{leaf}",
f"orchestrator.monitors.wandb.{leaf}",
)
# [file_monitor] leaf. (Bare empty ``[file_monitor]`` block enablement is at the end.)
propagate("file_monitor.filename", "trainer.file_monitor.filename", "orchestrator.file_monitor.filename")
# [monitors.file] leaf. (Bare empty ``[monitors.file]`` block enablement is at the end.)
propagate("monitors.file.path", "trainer.monitors.file.path", "orchestrator.monitors.file.path")
# [monitors.prime] leaf → orchestrator only (the trainer has no platform integration).
propagate("monitors.prime.name", "orchestrator.monitors.prime.name")
# [tokenizer]. ``chat_template`` also flows to ``inference.vllm`` (vLLM's
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
@@ -149,21 +152,31 @@ def propagate_shared_fields(data: Any) -> Any:
if trainer_chat_template is not None:
fill("inference.vllm.chat_template", trainer_chat_template)
# Bare ``[ckpt]`` / ``[wandb]`` block: presence-only signal that enables
# the section with defaults on both sub-configs. Necessary because
# Bare ``[ckpt]`` / ``[monitors.wandb]`` block: presence-only signal that
# enables the section with defaults on both sub-configs. Necessary because
# ``trainer.ckpt`` / ``orchestrator.ckpt`` are Optional[None] by default —
# without this an empty shared block would be a no-op. Leaf-level
# conflicts (e.g. shared ``ckpt.interval`` vs ``trainer.ckpt.interval``)
# are already caught above; the bare block is exempt because
# ``[ckpt]`` + ``[trainer.ckpt] keep_last = 3`` is a legitimate
# "enable + customise per side" pattern. The ``isinstance(dict)`` check
# (not ``is not None``) is what makes CLI ``--no-wandb`` / ``--no-ckpt``
# work — those land as the *string* ``"None"`` until ``BaseConfig``'s
# parent-class validator converts it, which happens after this one.
for key in ("ckpt", "wandb", "file_monitor"):
if isinstance(get(key), dict):
fill(f"trainer.{key}", {})
fill(f"orchestrator.{key}", {})
# without this an empty shared block would be a no-op. Leaf-level conflicts
# (e.g. shared ``ckpt.interval`` vs ``trainer.ckpt.interval``) are already
# caught above; the bare block is exempt because ``[ckpt]`` +
# ``[trainer.ckpt] keep_last = 3`` is a legitimate "enable + customise per
# side" pattern. CLI ``--no-ckpt`` / ``--no-monitors.wandb`` land as the
# *string* ``"None"`` until ``BaseConfig``'s parent-class validator converts
# it, which happens after this one — the disable must propagate too, since
# the monitor sub-configs default to enabled.
presence_targets = {
"ckpt": ("trainer", "orchestrator"),
"monitors.wandb": ("trainer", "orchestrator"),
"monitors.file": ("trainer", "orchestrator"),
"monitors.prime": ("orchestrator",),
}
for key, targets in presence_targets.items():
value = get(key)
if isinstance(value, dict):
for target in targets:
fill(f"{target}.{key}", {})
elif value == "None":
for target in targets:
fill(f"{target}.{key}", "None")
if conflicts:
lines = [
@@ -226,22 +239,22 @@ def validate_shared_wandb_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.wandb and not orchestrator.wandb:
if trainer.monitors.wandb and not orchestrator.monitors.wandb:
raise ValueError(
"Trainer W&B config is specified, but orchestrator W&B config is not. "
"This means only trainer metrics will be logged. Please specify [orchestrator.wandb] to log orchestrator metrics as well, "
"or use [wandb] to configure both at once."
"This means only trainer metrics will be logged. Please specify [orchestrator.monitors.wandb] to log orchestrator metrics as well, "
"or use [monitors.wandb] to configure both at once."
)
if orchestrator.wandb and not trainer.wandb:
if orchestrator.monitors.wandb and not trainer.monitors.wandb:
raise ValueError(
"Orchestrator W&B config is specified, but trainer W&B config is not. "
"This means only orchestrator metrics will be logged. Please specify [trainer.wandb] to log trainer metrics as well, "
"or use [wandb] to configure both at once."
"This means only orchestrator metrics will be logged. Please specify [trainer.monitors.wandb] to log trainer metrics as well, "
"or use [monitors.wandb] to configure both at once."
)
if trainer.wandb and orchestrator.wandb:
if trainer.wandb.project != orchestrator.wandb.project:
if trainer.monitors.wandb and orchestrator.monitors.wandb:
if trainer.monitors.wandb.project != orchestrator.monitors.wandb.project:
raise ValueError(
f"Trainer W&B project ({trainer.wandb.project}) and orchestrator W&B project ({orchestrator.wandb.project}) are not the same. Please specify the same W&B project for both."
f"Trainer W&B project ({trainer.monitors.wandb.project}) and orchestrator W&B project ({orchestrator.monitors.wandb.project}) are not the same. Please specify the same W&B project for both."
)
+7 -3
View File
@@ -6,7 +6,7 @@ readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"prime-rl-configs",
"prime-pydantic-config",
"prime-pydantic-config>=0.4.3",
"beartype>=0.21.0",
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
@@ -53,6 +53,7 @@ sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evaluator = "prime_rl.entrypoints.evaluator:main"
env-server = "prime_rl.entrypoints.env_server:main"
[project.entry-points."vllm.general_plugins"]
@@ -169,6 +170,9 @@ requires-dist = [
]
[tool.uv.exclude-newer-package]
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
@@ -208,8 +212,8 @@ torchao = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/downlo
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.2.0/vllm_router-0.2.0-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.26.0/vllm-0.26.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
+2
View File
@@ -71,6 +71,8 @@ type = "subprocess"
CLI: `--orchestrator.train.source.0.env.taskset.id reverse-text` or `--orchestrator.eval.source.0.env.taskset.id reverse-text`.
The `sft` entrypoint takes the same eval shape at the top level for online evals: `[eval]` + `[[eval.source]]` (with `[inference]` for the server), e.g. `--eval.source.0.env.taskset.id reverse-text`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--trainer.env-vars '{"key1": "value1"}'`. This works for plain `dict` fields only — nested pydantic-model fields (e.g. `algo`) reject JSON strings; use dotted keys (`--orchestrator.algo.type max_rl`) or a TOML overlay file.
**vLLM pass-through** — `[inference.vllm]` uses vLLM's own argument names (`model`, `tensor_parallel_size`, `data_parallel_size`, `max_model_len`, ...) and forwards *any* key to the vLLM server, typed by prime-rl or not: `[inference.vllm] max_num_seqs = 256`, or `--inference.vllm.max-num-seqs 256` on the CLI. CLI values are JSON-coerced, so dict-valued vLLM args work as `--inference.vllm.compilation-config '{"cudagraph_mode": "NONE"}'`. Non-vLLM knobs (router, deployment, weight broadcast, kv-cache offload, env vars) stay on `[inference]` itself.
+2 -1
View File
@@ -66,6 +66,7 @@ After a restart, verify all processes are back up and progress resumed before th
{run_dir}/logs/latest/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── evaluator.log # SFT online-eval evaluator stdout (single-node; the decoupled multi-node eval job logs at {run_dir}/logs/evaluator.log)
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
@@ -81,7 +82,7 @@ Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough
Scan for problems:
```bash
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/{trainer,orchestrator,evaluator,inference}.log
grep -E "WARNING|ERROR" {run_dir}/logs/latest/envs/{train,eval}/*.log
```
+6 -1
View File
@@ -19,11 +19,16 @@ All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/t
- Nested groups via dotted CLI paths — kebab-case on the CLI, snake_case in TOML.
- Bool toggles: bare `--flag` enables, `--no-flag` disables (nested too).
- Lists: space-separated or JSON literal. Dicts: JSON literal, deep-merged with file values.
- Optional sub-configs (`WandbConfig | None`): bare `--wandb` enables defaults; `--wandb @ wandb.toml` enables from a file; `--no-wandb` disables.
- Optional sub-configs (`WandbMonitorConfig | None`): bare `--monitors.wandb` enables defaults; `--monitors.wandb @ wandb.toml` enables from a file; `--no-monitors.wandb` disables.
- Discriminated unions are switched by the `type` tag (e.g. `--optimizer.type muon`).
- Validation aliases let renamed fields keep working; legacy keys can be remapped in a `model_validator(mode="before")`.
- Auto-generated `--help` panels from `Field(description=...)` or PEP 224 docstrings.
- Friendly errors: required-field boxes, validator errors point at the offending flag, unknown flags get a "did you mean" hint.
- 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
`[model.full_offload]` table only to select the Torch debugging backend or disable NUMA binding.
## `rl` — RL training
+24
View File
@@ -0,0 +1,24 @@
"""Lightweight launcher for the online evaluator.
Defers heavy ML imports until after ``cli()`` parses CLI args, so
``evaluator --help`` short-circuits in ``cli()``. The actual implementation
lives in ``prime_rl.orchestrator.evaluator``.
"""
import asyncio
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Evaluator")
config = cli(EvaluatorConfig)
from prime_rl.orchestrator.evaluator import run_evaluator
asyncio.run(run_evaluator(config))
if __name__ == "__main__":
main()
+1 -11
View File
@@ -10,8 +10,6 @@ from subprocess import Popen
from threading import Event, Thread
from urllib.parse import urlparse
import pynvml
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.orchestrator import EnvConfig
@@ -35,6 +33,7 @@ from prime_rl.utils.process import (
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
set_proc_title,
)
@@ -68,15 +67,6 @@ def env_server_names(config: RLConfig, split: str) -> list[str]:
return [source.resolved_name for source_split, source, _ in env_servers(config) if source_split == split]
def get_physical_gpu_ids() -> list[int]:
"""Return physical GPU IDs visible to the launcher."""
raw_visible = os.environ.get("CUDA_VISIBLE_DEVICES")
if raw_visible is None:
pynvml.nvmlInit()
return list(range(pynvml.nvmlDeviceGetCount()))
return [int(token.strip()) for token in raw_visible.split(",") if token.strip()]
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
output_dir.mkdir(parents=True, exist_ok=True)
+406 -51
View File
@@ -1,5 +1,7 @@
import json
import os
import shutil
import signal
import subprocess
import sys
import uuid
@@ -7,27 +9,90 @@ from pathlib import Path
from subprocess import Popen
from threading import Event, Thread
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
create_attempt_log_dir,
format_log_message,
get_all_ckpt_steps,
get_ckpt_dir,
get_config_dir,
get_log_dir,
get_step_path,
get_weights_dir,
latest_log_dir,
resolve_latest_ckpt_step,
validate_run_dir,
)
from prime_rl.utils.process import (
DEFAULT_COMMON_ENV_VARS,
DEFAULT_INFERENCE_ENV_VARS,
DEFAULT_TRAINER_ENV_VARS,
cleanup_processes,
cleanup_threads,
get_physical_gpu_ids,
monitor_process,
set_proc_title,
)
SFT_CONFIG = "sft.json"
SFT_SBATCH = "sft.sbatch"
EVAL_SBATCH = "eval.sbatch"
EVAL_TEMPLATE = "multi_node_sft_eval.sbatch.j2"
INFERENCE_CONFIG = "inference.json"
EVALUATOR_CONFIG = "evaluator.json"
ENVS_DIR = "envs"
def eval_env_servers(config: SFTConfig) -> list[tuple[EvalSourceConfig, str]]:
"""``(source, address)`` for every launcher-managed eval source. A source with
``serve.address`` set is externally managed — the launcher neither writes its
config nor spawns a server for it."""
if config.eval is None:
return []
addresses = config.eval.env_addresses
return [
(source, addresses[("eval", source.resolved_name)])
for source in config.eval.source
if source.serve.address is None
]
def get_ckpt_base(config: SFTConfig) -> Path:
"""Where checkpoints and weights live: ``ckpt.output_dir`` when set, else the run dir."""
return (config.ckpt.output_dir if config.ckpt else None) or config.run_dir
def resolve_resume_step(config: SFTConfig) -> int | None:
if config.resume is None:
return None
if config.resume.dir is not None:
return config.resume.dir_step
if config.resume.step is not None:
return config.resume.step
return resolve_latest_ckpt_step(get_ckpt_dir(get_ckpt_base(config)))
def build_evaluator_config(config: SFTConfig) -> EvaluatorConfig:
"""Derive the evaluator subconfig from the resolved SFT config."""
assert config.eval is not None
return EvaluatorConfig(
model=config.model.name,
eval=config.eval,
weights_dir=get_weights_dir(get_ckpt_base(config)),
output_dir=config.run_dir,
max_steps=config.max_steps,
resume_step=resolve_resume_step(config),
log=LogConfig(level=config.log.level, json_logging=config.log.json_logging),
monitors=config.monitors,
)
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
@@ -37,7 +102,39 @@ def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None
json.dump(dump_resolved_config(config, exclude=exclude), f, indent=2)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: bool = False) -> None:
"""Write the inference, evaluator, and env-server configs for online evals."""
config_dir.mkdir(parents=True, exist_ok=True)
if config.inference is not None:
# Exclude launcher-only fields that are not needed by the vLLM server
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
inference_dict = dump_resolved_config(config.inference, exclude=exclude_inference)
if strip_router:
# Per-rank processes run bare engines; the sbatch starts the single global router.
inference_dict["router"] = None
with open(config_dir / INFERENCE_CONFIG, "w") as f:
json.dump(inference_dict, f, indent=2)
with open(config_dir / EVALUATOR_CONFIG, "w") as f:
json.dump(dump_resolved_config(build_evaluator_config(config)), f, indent=2)
# One EnvServerConfig per launcher-managed eval source: `env-server @ <path>`
# binds at the source's deterministic address, where the evaluator connects.
for source, address in eval_env_servers(config):
env_dir = config_dir / ENVS_DIR / "eval"
env_dir.mkdir(parents=True, exist_ok=True)
source_dict = dump_resolved_config(source)
env_server_dict = {
"env": source_dict["env"],
"serve": {**(source_dict.get("serve") or {}), "address": address},
"log": {"level": config.log.vf_level, "json_logging": config.log.json_logging},
}
with open(env_dir / f"{source.resolved_name}.json", "w") as f:
json.dump(env_server_dict, f, indent=2)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path, prl_run_id: str | None = None) -> None:
"""Write the SLURM script to disk."""
from jinja2 import Environment, FileSystemLoader
@@ -66,21 +163,79 @@ def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path)
config_path=config_path,
output_dir=config.run_dir,
trainer_env_vars=trainer_env_vars,
num_nodes=config.deployment.num_nodes,
num_nodes=config.deployment.num_train_nodes,
gpus_per_node=config.deployment.gpus_per_node,
ranks_filter=",".join(map(str, config.log.ranks_filter)),
prl_run_id=prl_run_id,
run_name=config.run.name,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def write_eval_slurm_script(config: SFTConfig, config_dir: Path, script_path: Path, prl_run_id: str | None) -> None:
"""Write the SLURM script for the decoupled online-eval job (inference pool +
env servers + evaluator) to disk."""
from jinja2 import Environment, FileSystemLoader
assert config.slurm is not None
assert config.slurm.template_path is not None
assert config.deployment.type == "multi_node"
assert config.inference is not None
# The eval template is bundled next to the trainer templates; a custom
# slurm.template_path directory takes precedence so both can be overridden.
template_dirs = [config.slurm.template_path.parent]
bundled_templates = find_package_resource("templates")
if bundled_templates is not None:
template_dirs.append(bundled_templates)
env = Environment(loader=FileSystemLoader(template_dirs), keep_trailing_newline=True)
template = env.get_template(EVAL_TEMPLATE)
inference_env_vars = {
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
}
evaluator_env_vars = {**DEFAULT_COMMON_ENV_VARS, "LOGURU_FORCE_COLORS": "1", **config.env_vars}
script = template.render(
**config.slurm.template_vars,
config_dir=config_dir,
output_dir=config.run_dir,
num_infer_nodes=config.deployment.num_infer_nodes,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.router,
router_port=config.inference.server.port,
backend_port=config.inference.backend_port,
data_parallel_rpc_port=config.inference.vllm.data_parallel_rpc_port,
dp_per_node=config.deployment.gpus_per_node // config.inference.vllm.tensor_parallel_size,
enable_expert_parallel=config.inference.vllm.enable_expert_parallel,
inference_env_vars=inference_env_vars,
evaluator_env_vars=evaluator_env_vars,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
prl_run_id=prl_run_id,
run_name=config.run.name,
)
script_path.parent.mkdir(parents=True, exist_ok=True)
script_path.write_text(script)
def sft_slurm(config: SFTConfig):
"""Run SFT training via SLURM."""
"""Run SFT training via SLURM. With online evals on a multi-node deployment, the
trainer and the eval deployment (inference pool + evaluator) are two independent
SLURM jobs: the handoff is weight checkpoints on the shared filesystem, so the
trainer job releases its allocation when training finishes while the eval job
keeps draining evals and exits after the final checkpoint."""
assert config.slurm is not None
logger = setup_logger(config.log.level or "info", json_logging=config.log.json_logging)
decoupled_eval = config.deployment.type == "multi_node" and config.eval is not None
config_dir = get_config_dir(config.run_dir)
config_path = config_dir / SFT_CONFIG
exclude = (
@@ -88,28 +243,84 @@ def sft_slurm(config: SFTConfig):
if config.deployment.type == "multi_node"
else {"slurm", "dry_run", "clean"}
)
if decoupled_eval:
# The trainer job only needs [eval] for the weight-checkpoint cadence; the
# inference pool lives in the eval job.
exclude = exclude | {"inference"}
write_config(config, config_path, exclude=exclude)
logger.info(f"Wrote config to {config_path}")
# Trainer and evaluator processes log to a single shared W&B run across both jobs,
# keyed by the launcher's run id.
prl_run_id: str | None = None
if decoupled_eval and config.monitors.wandb is not None:
prl_run_id = os.environ["PRL_RUN_ID"]
script_path = config.run_dir / SFT_SBATCH
write_slurm_script(config, config_path, script_path)
write_slurm_script(config, config_path, script_path, prl_run_id)
logger.info(f"Wrote SLURM script to {script_path}")
log_dir = latest_log_dir(config.run_dir)
num_nodes = config.deployment.num_nodes if config.deployment.type == "multi_node" else 1
log_message = format_log_message(log_dir=log_dir, trainer=True, num_train_nodes=num_nodes)
# The trainer job is submitted first and the eval job depends on it having started:
# the trainer creates the shared W&B run, and the evaluator's joiner init only
# retries for a bounded window — starting the evaluator while the trainer job pends
# would crash it at wandb init.
script_paths = [script_path]
if decoupled_eval:
write_eval_subconfigs(config, config_dir, strip_router=True)
logger.info(f"Wrote eval subconfigs to {config_dir}")
eval_script_path = config.run_dir / EVAL_SBATCH
write_eval_slurm_script(config, config_dir, eval_script_path, prl_run_id)
logger.info(f"Wrote eval SLURM script to {eval_script_path}")
script_paths = [script_path, eval_script_path]
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
log_message = format_log_message(
log_dir=latest_log_dir(config.run_dir),
trainer=True,
num_train_nodes=num_nodes,
)
if decoupled_eval:
# The eval job logs at stable (non-attempt) paths under the run dir.
log_message += "\n" + format_log_message(
log_dir=get_log_dir(config.run_dir),
evaluator=True,
inference=True,
eval_env_names=[source.resolved_name for source, _ in eval_env_servers(config)],
num_infer_nodes=config.deployment.num_infer_nodes,
).removeprefix("Logs:\n")
if config.dry_run:
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
submit = "\n".join(f" sbatch {path}" for path in script_paths)
note = (
"\n\nSubmit the trainer job first — the evaluator joins the W&B run the trainer creates."
if decoupled_eval
else ""
)
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
return
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
sys.exit(1)
submitted_job_ids: list[str] = []
for path in script_paths:
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
# (e.g. multi-cluster sbatch appends "on cluster <name>").
cmd = ["sbatch", "--parsable"]
if submitted_job_ids:
# Hold the eval job until the trainer job has started (not finished).
cmd.append(f"--dependency=after:{submitted_job_ids[-1]}")
cmd.append(str(path))
logger.info(f"Submitting: {' '.join(cmd)}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
logger.error(f"sbatch failed: {result.stderr.strip()}")
for job_id in submitted_job_ids:
logger.warning(f"Cancelling already-submitted job {job_id}")
subprocess.run(["scancel", job_id], capture_output=True, text=True)
sys.exit(1)
job_id = result.stdout.strip().split(";")[0]
submitted_job_ids.append(job_id)
logger.success(f"Submitted batch job {job_id}")
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
logger.success(log_message)
def sft_local(config: SFTConfig):
@@ -123,60 +334,151 @@ def sft_local(config: SFTConfig):
write_config(config, config_path)
logger.info(f"Wrote config to {config_path}")
if config.eval is not None:
write_eval_subconfigs(config, config_dir)
logger.info(f"Wrote eval subconfigs to {config_dir}")
if config.dry_run:
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
log_dir = create_attempt_log_dir(config.run_dir)
from prime_rl.utils.utils import get_free_port
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
# launcher must partition GPUs between processes; plain SFT leaves them to torchrun.
infer_gpu_ids: list[int] = []
trainer_gpu_ids: list[int] = []
if config.inference is not None:
num_infer_gpus = config.deployment.num_infer_gpus
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
f"Requested {total_requested_gpus} GPUs via deployment settings, but only "
f"{len(physical_gpu_ids)} physical GPU(s) are available: {physical_gpu_ids}"
)
infer_gpu_ids = physical_gpu_ids[:num_infer_gpus]
trainer_gpu_ids = physical_gpu_ids[num_infer_gpus:total_requested_gpus]
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
(config_dir / SFT_CONFIG).as_posix(),
]
logger.info(f"Starting SFT trainer with {config.deployment.num_gpus} GPU(s)")
logger.debug(f"Trainer command: {' '.join(trainer_cmd)}")
# Trainer and evaluator log to a single shared W&B run whose id ($WANDB_RUN_ID)
# equals $PRL_RUN_ID, one label per process.
wandb_shared_env: dict[str, str] = {}
if config.eval is not None:
# The trainer creates the run; the evaluator (which drains its final evals
# after the trainer exits) finalizes it.
wandb_shared_env = {
"WANDB_SHARED_MODE": "1",
"WANDB_RUN_ID": os.environ["PRL_RUN_ID"],
"WANDB_SHARED_PRIMARY": "trainer",
"WANDB_SHARED_FINISHER": "evaluator",
"WANDB_PROGRAM": "uv run sft",
"WANDB_ARGS": json.dumps(sys.argv),
}
processes: list[Popen] = []
monitor_threads: list[Thread] = []
error_queue: list[Exception] = []
stop_events: dict[str, Event] = {}
def sigterm_handler(signum, frame):
logger.warning("Received SIGTERM, terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
signal.signal(signal.SIGTERM, sigterm_handler)
def start_process(name: str, cmd: list[str], env: dict[str, str], log_path: Path) -> Popen:
logger.debug(f"{name.capitalize()} command: {' '.join(cmd)}")
log_path.parent.mkdir(parents=True, exist_ok=True)
with open(log_path, "w") as log_file:
process = Popen(cmd, env=env, stdout=log_file, stderr=log_file)
processes.append(process)
stop_event = Event()
stop_events[name] = stop_event
monitor_thread = Thread(target=monitor_process, args=(process, stop_event, error_queue, name), daemon=True)
monitor_thread.start()
monitor_threads.append(monitor_thread)
return process
try:
with open(log_dir / "trainer.log", "w") as log_file:
trainer_process = Popen(
trainer_cmd,
# Optionally, start the inference server for online evals
if config.inference is not None:
logger.info(f"Starting inference on GPU(s) {' '.join(map(str, infer_gpu_ids))}")
start_process(
"inference",
["inference", "@", (config_dir / INFERENCE_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
**DEFAULT_INFERENCE_ENV_VARS,
**config.env_vars,
**config.inference.env_vars,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, infer_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
log_path=log_dir / "inference.log",
)
processes.append(trainer_process)
stop_event = Event()
monitor_thread = Thread(
target=monitor_process,
args=(trainer_process, stop_event, error_queue, "trainer"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Start one env server per eval source. The evaluator connects to each source's
# deterministic address, polling until the server is up.
for source, address in eval_env_servers(config):
name = source.resolved_name
logger.info(f"Starting eval env server {name} at {address}")
start_process(
f"env/eval/{name}",
["env-server", "@", (config_dir / ENVS_DIR / "eval" / f"{name}.json").as_posix()],
env={**os.environ, **DEFAULT_COMMON_ENV_VARS, **config.env_vars},
log_path=log_dir / ENVS_DIR / "eval" / f"{name}.log",
)
if config.eval is not None:
logger.info("Starting evaluator process")
start_process(
"evaluator",
["evaluator", "@", (config_dir / EVALUATOR_CONFIG).as_posix()],
env={
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
"LOGURU_FORCE_COLORS": "1",
**config.env_vars,
**wandb_shared_env,
"WANDB_SHARED_LABEL": "evaluator",
},
log_path=log_dir / "evaluator.log",
)
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
f"--rdzv-endpoint=localhost:{get_free_port()}",
f"--rdzv-id={uuid.uuid4().hex}",
f"--log-dir={log_dir / 'trainer' / 'torchrun'}",
f"--local-ranks-filter={','.join(map(str, config.log.ranks_filter))}",
"--redirect=3",
"--tee=3",
f"--nproc-per-node={config.deployment.num_train_gpus}",
"-m",
"prime_rl.trainer.sft.train",
"@",
config_path.as_posix(),
]
gpus_suffix = f" on GPU(s) {' '.join(map(str, trainer_gpu_ids))}" if trainer_gpu_ids else ""
logger.info(f"Starting SFT trainer with {config.deployment.num_train_gpus} GPU(s){gpus_suffix}")
trainer_env = {
**os.environ,
**DEFAULT_COMMON_ENV_VARS,
**DEFAULT_TRAINER_ENV_VARS,
**config.env_vars,
**wandb_shared_env,
}
if config.eval is not None:
trainer_env["LOGURU_FORCE_COLORS"] = "1"
trainer_env["WANDB_SHARED_LABEL"] = "trainer"
if trainer_gpu_ids:
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(
@@ -185,7 +487,22 @@ def sft_local(config: SFTConfig):
)
processes.append(tail_process)
stop_event.wait()
# Wait for the trainer (and the evaluator, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
terminal_events = [stop_events["trainer"]]
if "evaluator" in stop_events:
terminal_events.append(stop_events["evaluator"])
while True:
pending = [event for event in terminal_events if not event.is_set()]
if error_queue:
logger.error(f"Error: {error_queue[0]}")
logger.error("Terminating all processes...")
cleanup_threads(monitor_threads)
cleanup_processes(processes)
sys.exit(1)
if not pending:
break
pending[0].wait(timeout=1)
if trainer_process.returncode != 0:
logger.error(f"Trainer failed with exit code {trainer_process.returncode}")
@@ -209,11 +526,49 @@ def sft_local(config: SFTConfig):
raise
def clean_stale_eval_artifacts(config: SFTConfig) -> None:
"""Remove eval artifacts a previous run left behind: weight checkpoints and rollout
trace dirs — everything on a fresh start, steps past the resume step on resume.
Without this the evaluator would replay stale checkpoints (and then skip the
re-trained ones at the same steps), and the append-only trace files would mix two
policies' rollouts under one step."""
logger = setup_logger(config.log.level or "info")
if os.environ.get("NEVER_CLEAN"):
logger.warning("NEVER_CLEAN is set - keeping stale weight checkpoints; the evaluator may replay them")
return
resume_step = resolve_resume_step(config)
weights_dir = get_weights_dir(get_ckpt_base(config))
stale_steps = [step for step in get_all_ckpt_steps(weights_dir) if resume_step is None or step > resume_step]
if stale_steps:
logger.info(
f"Deleting {len(stale_steps)} stale weight checkpoint(s) in {weights_dir} "
f"({','.join(map(str, stale_steps))})"
)
for step in stale_steps:
shutil.rmtree(get_step_path(weights_dir, step), ignore_errors=True)
clean_future_steps(config.run_dir, resume_step if resume_step is not None else -1)
def sft(config: SFTConfig):
# The run identity is runtime-only, never sub-config: $PRL_RUN_ID / $PRL_RUN_NAME are
# the vehicle for runtime info between processes, and every spawned process inherits
# them. Components launched standalone have no run identity.
os.environ.setdefault("PRL_RUN_ID", uuid.uuid4().hex)
assert config.run.name is not None # resolved at construction
os.environ["PRL_RUN_NAME"] = config.run.name
resuming = config.resume is not None
clean = config.clean and not os.environ.get("NEVER_CLEAN")
validate_run_dir(config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean)
ckpt_output_dir = config.ckpt.output_dir if config.ckpt else None
validate_run_dir(
config.run_dir, output_dir=config.output_dir, resuming=resuming, clean=clean, ckpt_output_dir=ckpt_output_dir
)
config.run_dir.mkdir(parents=True, exist_ok=True)
if ckpt_output_dir is not None:
ckpt_output_dir.mkdir(parents=True, exist_ok=True)
if config.eval is not None and not config.dry_run:
clean_stale_eval_artifacts(config)
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
+122
View File
@@ -0,0 +1,122 @@
"""Metric monitors.
Monitors are registered once per process via ``setup`` and used through the
module-level functions (``log``, ``finalize``, ...), which fan out to every
registered monitor. Fan-out never raises — a monitoring failure must not take
down training.
"""
from __future__ import annotations
import os
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, overload
from prime_rl.configs.monitors import FileMonitorConfig, PrimeMonitorConfig, WandbMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.file import FileMonitor
from prime_rl.monitors.prime import PrimeMonitor
from prime_rl.monitors.wandb import WandbMonitor
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
import verifiers.v1 as vf
__all__ = [
"Monitor",
"WandbMonitor",
"PrimeMonitor",
"FileMonitor",
"setup",
"get",
"log",
"finalize",
]
# All monitors registered for the current run.
MONITORS: list[Monitor] = []
async def setup(
wandb: WandbMonitorConfig | None = None,
prime: PrimeMonitorConfig | None = None,
file: FileMonitorConfig | None = None,
*,
output_dir: Path,
run_config: BaseConfig | None = None,
train_env_names: list[str] | None = None,
eval_env_names: list[str] | None = None,
overview_flavor: Literal["rl", "sft"] = "rl",
) -> None:
"""Construct, initialize, and register one monitor per non-None config.
Only rank 0 registers monitors — on other ranks the fan-out functions are
no-ops. A monitor whose ``init`` raises crashes the run: a configured
monitor must work.
"""
assert not MONITORS, "Monitors already set up. Call `setup` only once per process."
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
if rank != 0:
return
monitors: list[tuple[Monitor, dict[str, Any]]] = []
if prime is not None:
monitors.append((PrimeMonitor(prime), dict(config=run_config)))
if wandb is not None:
monitors.append(
(
WandbMonitor(wandb),
dict(
output_dir=output_dir,
config=run_config,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
overview_flavor=overview_flavor,
),
)
)
if file is not None:
monitors.append((FileMonitor(file), dict(output_dir=output_dir)))
for monitor, init_kwargs in monitors:
await monitor.init(**init_kwargs)
MONITORS.append(monitor)
def get(monitor_cls: type[Monitor]) -> Monitor | None:
"""The registered monitor of the given type, None when it isn't running
(not configured, or a non-zero rank)."""
return next((monitor for monitor in MONITORS if isinstance(monitor, monitor_cls)), None)
@overload
async def log(data: dict[str, Any], step: int) -> None: ...
@overload
async def log(data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None: ...
async def log(
data: dict[str, Any] | vf.Episode | list[vf.Episode],
step: int,
kind: Kind = "train",
subset: Subset = "effective",
) -> None:
"""Log to all registered monitors: a dict of scalar metrics, or episodes
with their cohort coordinates (train/eval x all/effective)."""
for monitor in MONITORS:
try:
await monitor.log(data, step=step, kind=kind, subset=subset)
except Exception as e:
get_logger().warning(f"Failed to log to {monitor.__class__.__name__}: {e}")
async def finalize() -> None:
"""Finalize the run on all registered monitors."""
for monitor in MONITORS:
try:
await monitor.finalize()
except Exception as e:
get_logger().warning(f"Failed to finalize {monitor.__class__.__name__}: {e}")
+55
View File
@@ -0,0 +1,55 @@
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Literal, overload
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
import verifiers.v1 as vf
Kind = Literal["train", "eval"]
Subset = Literal["all", "effective"]
class Monitor(ABC):
"""Base class for monitors."""
def __init__(self, config: BaseConfig):
self.config = config
self.logger = get_logger()
async def init(self, **kwargs: Any) -> None:
"""Initialize run. Overrides name their own kwargs."""
@overload
async def log(self, data: dict[str, Any], step: int) -> None: ...
@overload
async def log(self, data: vf.Episode | list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None: ...
async def log(
self,
data: dict[str, Any] | vf.Episode | list[vf.Episode],
step: int,
kind: Kind = "train",
subset: Subset = "effective",
) -> None:
"""Log scalar metrics, or episodes."""
if isinstance(data, dict):
await self.log_metrics(data, step=step)
else:
episodes = data if isinstance(data, list) else [data]
await self.log_episodes(episodes, step=step, kind=kind, subset=subset)
@abstractmethod
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
"""Log scalar metrics."""
@abstractmethod
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Log episodes."""
async def finalize(self) -> None:
"""Finalize run."""
+62
View File
@@ -0,0 +1,62 @@
from __future__ import annotations
import asyncio
import json
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, TextIO
import orjson
from prime_rl.configs.monitors import FileMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.utils.utils import sanitize
if TYPE_CHECKING:
import verifiers.v1 as vf
class FileMonitor(Monitor):
"""Logs metrics and episodes to local JSONL files."""
config: FileMonitorConfig
file: TextIO
async def init(self, output_dir: Path) -> None:
self.output_dir = output_dir
self.path = output_dir / self.config.path
self.path.parent.mkdir(parents=True, exist_ok=True)
# Line-buffered append so a concurrently-running dashboard can tail the file.
self.file = open(self.path, "a", buffering=1) # noqa: SIM115
self.logger.info(f"Logging metrics to {self.path} and traces to {output_dir / 'rollouts'}")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
sanitized, dropped = sanitize(metrics)
if dropped:
self.logger.warning(
f"Dropping {len(dropped)} non-finite value(s) from {self.config.path}: {', '.join(dropped[:5])}"
)
row = {"step": step, "time": time.time(), **sanitized}
self.file.write(json.dumps(row) + "\n")
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Append the cohort's traces to its per-step trace file. ``all`` grows one
episode at a time as they complete, ``effective`` one batch at a time on finalize,
so an in-progress run's traces can be inspected live."""
def write() -> None:
path = self.output_dir / "rollouts" / f"step_{step}" / kind / subset / "traces.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "ab") as f:
for episode in episodes:
for trace in episode.traces:
f.write(orjson.dumps(trace.to_record(), default=str, option=opts))
# Record serialization is heavy pure-Python work; keep it off the event loop.
# Awaited (not fire-and-forget) so appends to one file never interleave.
await asyncio.to_thread(write)
async def finalize(self) -> None:
self.logger.info(f"Finalized metrics at {self.path}")
+327
View File
@@ -0,0 +1,327 @@
from __future__ import annotations
import asyncio
import atexit
import io
import json
import os
from datetime import datetime, timezone
from typing import Any, Coroutine
import httpx
import pyarrow as pa
import pyarrow.parquet as pq
import verifiers.v1 as vf
from prime_cli.core.config import Config as PrimeConfig
from verifiers.v1.utils.platform import build_samples
from prime_rl.configs.monitors import PrimeMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import sanitize
BASE_URL = "https://api.primeintellect.ai/api/v1/rft"
BASE_URL_VAR = "PRIME_API_BASE"
API_KEY_VAR = "PRIME_API_KEY"
SAMPLE_SCHEMA = pa.schema(
[
("run_id", pa.string()),
("step", pa.int64()),
("tag", pa.string()),
("problem_id", pa.int64()),
("sample_id", pa.int64()),
("prompt", pa.string()),
("completion", pa.string()),
("trajectory", pa.string()),
("answer", pa.string()),
("env_name", pa.string()),
("task", pa.string()),
("info", pa.string()),
("reward", pa.float64()),
("advantage", pa.float64()),
("metrics", pa.string()),
("timing", pa.string()),
("num_input_tokens", pa.int64()),
("num_output_tokens", pa.int64()),
("created_at", pa.timestamp("us", tz="UTC")),
]
)
class PrimeMonitor(Monitor):
"""Logs metrics and episodes to the Prime platform.
Uploads are fire-and-forget tasks on the caller's event loop — the prime
monitor only runs in the orchestrator, whose call sites are all async. The
platform calls and the episode serialization run in worker threads via
``asyncio.to_thread``, so they never stall the loop.
"""
config: PrimeMonitorConfig
async def init(self, config: BaseConfig | None = None) -> None:
api_key = os.getenv(API_KEY_VAR) or PrimeConfig().api_key
if not api_key:
raise RuntimeError(f"API key not found - set {API_KEY_VAR} or run `prime login`")
self.run = TrainRun(api_key)
if run_id := os.getenv("RUN_ID"):
# A managed launch pre-created the platform run and injected its id -
# attach instead of registering a duplicate. The backend owns the run's
# failure marking then; finalize still marks it completed on clean exit.
self.run.id = run_id
self.logger.info(f"Logging metrics and episodes to platform run {run_id} (attached via $RUN_ID)")
return
run_fields: dict[str, Any] = {}
if config is not None:
run_fields = dict(
base_model=config.model.name,
max_steps=config.max_steps or 0,
batch_size=config.batch_size,
rollouts_per_example=config.group_size,
seq_len=config.seq_len,
environments=[env.env_id for env in config.train.source],
run_config=config.model_dump(exclude_none=True, mode="json"),
wandb_project=config.monitors.wandb.project if config.monitors.wandb else None,
)
await self.run.create(name=self.config.name, **run_fields)
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
metrics, dropped = sanitize(metrics)
if dropped:
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
self.run.submit("metrics upload", self.run.log_metrics(metrics))
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
"""Upload one platform sample per episode via the presigned-URL Parquet flow.
Only the trained cohort ships to the platform."""
# Upload every 10th step, unsampled - the pre-refactor cadence - to not
# overwhelm the platform's ingestion. TODO: Lift once we integrate the
# prime traces SDK.
if kind != "train" or subset != "effective" or not episodes or step % 10 != 0:
return
async def upload() -> None:
# Serialization dumps every episode's full model - heavy pure-Python work
# that would stall the event loop (and with it dispatch) if run inline.
parquet_bytes = await asyncio.to_thread(episodes_to_parquet_bytes, episodes, self.run.id, step)
if parquet_bytes is not None:
await self.run.upload_samples(parquet_bytes, step)
self.run.submit(f"episodes upload at step {step}", upload())
async def finalize(self) -> None:
await self.run.finalize()
class TrainRun:
"""A training run on the Prime platform's RFT API.
Owns the HTTP client and the run lifecycle (create, log, finalize) — the
natural seam to be subsumed by the train SDK, and it mirrors ``wandb.Run``'s
exit behavior: a created run that is never finalized is marked failed at
process exit via an atexit hook that ``finalize`` disarms. Fully async,
except the atexit hook itself — at interpreter shutdown there is no event
loop, so it sends one synchronous request.
"""
def __init__(self, api_key: str):
self.id: str | None = None
self.logger = get_logger()
self._tasks: set[asyncio.Task] = set()
self.base_url = (os.getenv(BASE_URL_VAR) or BASE_URL).rstrip("/")
self.headers = {
"Authorization": f"Bearer {api_key}",
"x-api-key": api_key,
"Content-Type": "application/json",
}
self.client = httpx.AsyncClient(
base_url=self.base_url,
headers=self.headers,
timeout=30,
transport=httpx.AsyncHTTPTransport(retries=3),
)
def submit(self, what: str, request: Coroutine[Any, Any, None]) -> None:
"""Run a request as a fire-and-forget task; a failure only warns. The task set
keeps strong references - the loop alone won't."""
async def guarded() -> None:
try:
await request
except Exception as e:
self.logger.warning(f"Failed {what}: {type(e).__name__}: {e}")
task = asyncio.get_running_loop().create_task(guarded())
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
async def create(
self,
name: str | None = None,
team_id: str | None = None,
base_model: str = "unknown",
max_steps: int = 0,
batch_size: int | None = None,
rollouts_per_example: int | None = None,
seq_len: int | None = None,
environments: list[str] | None = None,
run_config: dict[str, Any] | None = None,
wandb_project: str | None = None,
) -> str:
"""Register the run with the platform and return its id."""
prime_config = PrimeConfig()
team_id = team_id or prime_config.team_id
payload: dict[str, Any] = {"base_model": base_model, "max_steps": max_steps}
if batch_size is not None:
payload["batch_size"] = batch_size
if rollouts_per_example is not None:
payload["rollouts_per_example"] = rollouts_per_example
if seq_len is not None:
payload["seq_len"] = seq_len
if environments is not None:
payload["environments"] = [{"id": env_id} for env_id in environments]
if run_config is not None:
payload["run_config"] = run_config
if wandb_project is not None:
payload["wandb_project"] = wandb_project
if name:
payload["name"] = name
if team_id:
payload["team_id"] = team_id
response = await self.client.post("/external-runs", json=payload)
if response.status_code != 201:
raise RuntimeError(f"Failed to create platform run (HTTP {response.status_code}): {response.text}")
self.id = response.json()["run"]["id"]
self._owner_pid = os.getpid()
atexit.register(self._mark_failed)
if prime_config.frontend_url:
self.logger.info(
f"Logging metrics and episodes to platform run {self.id} ({prime_config.frontend_url.rstrip('/')}/dashboard/training/{self.id})"
)
else:
self.logger.info(f"Logging metrics and episodes to platform run {self.id}")
return self.id
async def log_metrics(self, metrics: dict[str, Any]) -> None:
(await self.client.post("/metrics", json={"run_id": self.id, "metrics": metrics})).raise_for_status()
async def upload_samples(self, parquet_bytes: bytes, step: int) -> None:
"""Presigned-URL flow: presign -> R2 PUT -> confirm."""
presign = await self.client.post("/samples/presign", json={"run_id": self.id, "step": step})
presign.raise_for_status()
data = presign.json()["data"]
# Bare client - the presigned URL rejects the run client's auth headers.
async with httpx.AsyncClient(timeout=30) as client:
put = await client.put(
data["presignedUrl"], content=parquet_bytes, headers={"Content-Type": "application/parquet"}
)
put.raise_for_status()
confirm = await self.client.post(
"/samples/confirm", json={"run_id": self.id, "step": step, "s3_key": data["s3Key"]}
)
confirm.raise_for_status()
async def finalize(self) -> None:
"""Finalize the run as completed."""
self.logger.info(f"Finalizing platform run {self.id}")
# Drain in-flight uploads so the final step's metrics and episodes land
# before the run is marked completed.
await asyncio.gather(*self._tasks, return_exceptions=True)
try:
(await self.client.post("/finalize", json={"run_id": self.id, "summary": {}})).raise_for_status()
except httpx.HTTPError as e:
self.logger.warning(f"Failed to finalize platform run {self.id}: {e}")
await self.set_status(success=True)
atexit.unregister(self._mark_failed)
def _mark_failed(self) -> None:
# Forked children inherit the atexit table; only the creating process may
# flip the run's status. At interpreter shutdown there is no event loop and
# no executor for async DNS, so this path must stay synchronous.
if os.getpid() != self._owner_pid:
return
self.logger.info(f"Marking platform run {self.id} as failed")
try:
httpx.put(
f"{self.base_url}/external-runs/{self.id}/status",
headers=self.headers,
json={"status": "failed"},
timeout=30,
).raise_for_status()
except httpx.HTTPError as e:
self.logger.warning(f"Failed to mark platform run {self.id} as failed: {e}")
async def set_status(self, success: bool) -> None:
"""Mark the run as completed or failed."""
status = "completed" if success else "failed"
self.logger.info(f"Marking platform run {self.id} as {status}")
try:
put = await self.client.put(f"/external-runs/{self.id}/status", json={"status": status})
put.raise_for_status()
except httpx.HTTPError as e:
self.logger.warning(f"Failed to mark platform run {self.id} as {status}: {e}")
def episodes_to_parquet_bytes(episodes: list[vf.Episode], run_id: str | None, step: int) -> bytes | None:
"""One row per episode. Sample construction is shared with verifiers' eval
``--push`` (``build_samples``: complete native episode in ``info.native_wrapper``,
flat summary from one trainable trace), so a training episode and an eval sample
land on the platform identically; the RFT-only columns (run/step/advantage/
problem_id/env_name) are layered on here."""
advantages: dict[str, float | None] = {}
env_names: dict[str, str] = {}
for episode in episodes:
summary_trace = next((trace for trace in episode.traces if trace.agent.trainable), episode.traces[0])
advantages[episode.id] = summary_trace.scalar_advantage()
env_names[episode.id] = episode.env.id
now = datetime.now(timezone.utc)
rows = []
for sample_id, sample in enumerate(build_samples(episodes)):
trajectory = sample["trajectory"]
if not trajectory: # no branches (e.g. an episode that errored before any message)
continue
advantage = advantages.get(sample["episode_id"])
trajectory = [{**branch, "advantage": advantage} for branch in trajectory]
try:
problem_id = int(sample["example_id"]) if sample["example_id"] is not None else sample_id
except (TypeError, ValueError):
problem_id = sample_id
rows.append(
{
"run_id": run_id,
"step": step,
"tag": "",
"problem_id": problem_id,
"sample_id": sample_id,
"prompt": "",
"completion": json.dumps(sample["completion"]),
"trajectory": json.dumps(trajectory),
"answer": "",
"env_name": env_names.get(sample["episode_id"], ""),
"task": json.dumps(sample["task"]),
"info": json.dumps(sample["info"]),
"reward": sample["reward"],
"advantage": advantage,
"metrics": json.dumps(sample["metrics"]),
"timing": json.dumps(sample["timing"]),
"num_input_tokens": trajectory[-1]["num_input_tokens"],
"num_output_tokens": trajectory[-1]["num_output_tokens"],
"created_at": now,
}
)
if not rows:
return None
table = pa.Table.from_pylist(rows, schema=SAMPLE_SCHEMA)
buf = io.BytesIO()
pq.write_table(table, buf, compression="snappy", use_dictionary=True, write_statistics=True)
return buf.getvalue()
+3
View File
@@ -0,0 +1,3 @@
from prime_rl.monitors.wandb.monitor import WandbMonitor
__all__ = ["WandbMonitor"]
+145
View File
@@ -0,0 +1,145 @@
from __future__ import annotations
import asyncio
import json
import os
import sys
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
import wandb
from wandb.errors import CommError
from wandb.sdk.mailbox.mailbox_handle import ServerResponseError
from prime_rl.configs.monitors import WandbMonitorConfig
from prime_rl.monitors.base import Kind, Monitor, Subset
from prime_rl.monitors.wandb.overview import ensure_overview_view
from prime_rl.utils.config import BaseConfig
if TYPE_CHECKING:
import verifiers.v1 as vf
class WandbMonitor(Monitor):
"""Logs metrics to Weights and Biases."""
config: WandbMonitorConfig
async def init(
self,
output_dir: Path,
config: BaseConfig | None = None,
train_env_names: list[str] | None = None,
eval_env_names: list[str] | None = None,
overview_flavor: Literal["rl", "sft"] = "rl",
) -> None:
# W&B reads the start command off sys.argv; the launcher passes the original
# command to subprocesses via $WANDB_ARGS.
wandb_args = os.environ.get("WANDB_ARGS")
if wandb_args:
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
sys.argv = json.loads(wandb_args)
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
# requires a server connection and can't work offline.
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and os.environ.get("WANDB_MODE") not in (
"disabled",
"offline",
)
if shared_mode:
# W&B's native run-id var, set by the launcher to $PRL_RUN_ID.
run_id = os.environ.get("WANDB_RUN_ID")
label = os.environ.get("WANDB_SHARED_LABEL")
primary_label = os.environ.get("WANDB_SHARED_PRIMARY", "orchestrator")
primary = label == primary_label
# The primary creates the run; the finisher writes its final state. They can
# differ when the run's creator is not its last-alive writer (e.g. the SFT
# trainer creates the run, the evaluator outlives it and finalizes).
finisher = label == os.environ.get("WANDB_SHARED_FINISHER", primary_label)
settings = wandb.Settings(
mode="shared",
x_label=label,
x_primary=primary,
x_update_finish_state=finisher,
)
self.logger.info(f"Using shared W&B mode ({label=}, {primary=}, {finisher=})")
is_online = True
else:
run_id = None
primary = False
mode = os.environ.get("WANDB_MODE", "offline" if self.config.offline else "online")
settings = wandb.Settings(mode=mode)
is_online = mode == "online"
retryable_errors = (CommError, ServerResponseError) if shared_mode else (CommError,)
def init_wandb(max_retries: int):
for attempt in range(max_retries):
try:
return wandb.init(
id=run_id,
resume="allow" if run_id else None,
project=self.config.project,
entity=self.config.entity,
name=self.config.name,
group=self.config.group,
tags=self.config.tags,
dir=output_dir,
config=config.model_dump() if config else None,
settings=settings,
)
except retryable_errors as e:
if attempt + 1 == max_retries:
raise
if shared_mode and not primary:
msg = (
f"Shared W&B run not yet created by primary - retrying in 10s ({attempt + 1}/{max_retries})"
)
else:
msg = f"Transient W&B init error ({e}) - retrying in 10s ({attempt + 1}/{max_retries})"
self.logger.info(msg)
# A failed wandb.init leaves the run_id registered in the local
# wandb-core StreamMux, causing the next attempt to fail with
# "run ID ... is in use". Tear down the service so the retry
# starts from a clean state.
wandb.teardown()
time.sleep(10)
# Non-primary processes in shared mode wait for the primary to create the run.
# Everyone else still retries to absorb transient W&B server errors (e.g. 404 on upsertBucket).
max_retries = 30 if shared_mode and not primary else 5
self.wandb = init_wandb(max_retries)
wandb.define_metric("*", step_metric="step")
# Provision the curated "overview" saved view once per project (the run's primary process
# in shared mode, else the single master). Best-effort: a workspaces/API failure must never
# take down training.
if is_online and (primary if shared_mode else True):
try:
url = ensure_overview_view(
self.wandb.entity,
self.wandb.project,
train_envs=train_env_names or [],
eval_envs=eval_env_names or [],
flavor=overview_flavor,
)
if url:
self.logger.info(f"Created W&B overview view - {url}")
except Exception as e:
self.logger.warning(f"Failed to create W&B overview view - {e}")
self.logger.info(f"Logging metrics to W&B run {self.wandb.id} ({self.wandb.url})")
async def log_metrics(self, metrics: dict[str, Any], step: int) -> None:
wandb.log({**metrics, "step": step})
async def log_episodes(self, episodes: list[vf.Episode], step: int, kind: Kind, subset: Subset) -> None:
pass
async def finalize(self) -> None:
self.logger.info(f"Finalizing W&B run {self.wandb.id}")
# Explicit finish: in (experimental) shared mode the SDK's atexit finish does
# not land the run state - without this, even clean runs decay to "crashed".
await asyncio.to_thread(wandb.finish, exit_code=0)
+250
View File
@@ -0,0 +1,250 @@
"""Curated "overview" W&B saved view.
prime-rl logs many metrics; the default workspace auto-generates a panel per key, which buries the
few that matter. These build a named saved view grouping the important metrics into sections, so a
new project gets a usable overview without hand-picking panels. Panels are untitled — each shows
its raw metric name.
"""
from __future__ import annotations
import re
from collections.abc import Sequence
from typing import Literal
import wandb
import wandb_workspaces.reports.v2 as wr
import wandb_workspaces.workspaces as ws
from wandb_gql import gql
from prime_rl.utils.logger import get_logger
OVERVIEW_NAME = "overview"
# Rollout metrics (under "<scope>/") shown for BOTH train and eval. Quality metrics read the
# effective subset — the all subset includes errored rollouts, whose zero values skew the
# distributions. has_error only exists on all (effective drops errors by construction). The count
# metrics are episode-level exact keys; the trace-level metrics (reward, truncation, errors) live
# under the per-agent subtree, whose names are data-dependent — matched by regex, one panel per
# agent. Only the score metric differs — train scores with "reward/mean", eval with "avg@k" (its k
# dynamic, so also a regex) — and each section builder prepends its own.
COMMON_METRICS = [
"effective/num_total_tokens/mean",
"effective/num_turns/mean",
"effective/num_branches/mean",
]
COMMON_REGEXES = [
"all/[^/]+/has_error/mean",
"effective/[^/]+/is_truncated/mean",
]
STABILITY_METRICS = ["optim/grad_norm", "entropy/all/mean", "mismatch_kl/all/mean", "kl_ent_ratio/mean"]
PERFORMANCE_METRICS = [
"perf/mfu",
"time/step",
"time/wait_for_batch",
"time/wait_for_policy",
]
# Inference health panels: each pairs the fleet aggregate (mean/sum) with the cross-engine
# tail that flags a single sick engine - max for pressure metrics, min for health metrics.
# One saturated engine thrashing its KV cache (preempt -> re-prefill -> cache eviction) hides
# inside fleet means; the max/min series is what surfaces it.
INFERENCE_PANELS = [
[
"inference/agg/kv_cache_usage_perc/mean",
"inference/agg/kv_cache_usage_perc/min",
"inference/agg/kv_cache_usage_perc/max",
],
["inference/agg/num_preemptions_total:rate/sum", "inference/agg/num_preemptions_total:rate/max"],
[
"inference/agg/num_requests_running/mean",
"inference/agg/num_requests_running/min",
"inference/agg/num_requests_running/max",
],
[
"inference/agg/num_requests_waiting/mean",
"inference/agg/num_requests_waiting/min",
"inference/agg/num_requests_waiting/max",
],
["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"],
]
# SFT flavor: no rollout-based train sections — the training signal is the loss curve.
SFT_TRAIN_METRICS = ["loss/mean", "loss/perplexity", "val/loss", "val/perplexity", "progress/epoch"]
SFT_STABILITY_METRICS = ["optim/grad_norm", "optim/lr", "loss/nan_count"]
SFT_PERFORMANCE_METRICS = [
"perf/mfu",
"perf/throughput",
"perf/peak_memory",
"time/step",
"time/forward_backward",
"time/save_ckpt",
]
# Dense grid: more, smaller panels per row and enough rows that sections don't paginate.
COLUMNS = 4
ROWS = 6
def line_panels(metrics: Sequence[str], regexes: Sequence[str]) -> list[wr.LinePlot]:
# inference/* is logged against time (step_metric="_timestamp"), plotted on "RelativeTime(Wall)"
# (== W&B's "_absolute_runtime", seconds since run start) so runs started at different times
# overlay; everything else on "step" (prime-rl's logged training step, not internal "Step").
# x is set per-panel because LinePlot defaults it to "Step", which overrides the workspace x_axis.
return [wr.LinePlot(x="RelativeTime(Wall)" if m.startswith("inference/") else "step", y=[m]) for m in metrics] + [
wr.LinePlot(x="step", metric_regex=r) for r in regexes
]
def inference_section() -> ws.Section:
# Multi-series panels (aggregate + tail), on wall time like all inference/* metrics.
return ws.Section(
name="inference",
is_open=True,
panels=[wr.LinePlot(x="RelativeTime(Wall)", y=list(series)) for series in INFERENCE_PANELS],
layout_settings=ws.SectionLayoutSettings(columns=COLUMNS, rows=ROWS),
)
def section(name: str, metrics: Sequence[str] = (), regexes: Sequence[str] = ()) -> ws.Section:
return ws.Section(
name=name,
is_open=True,
panels=line_panels(metrics, regexes),
layout_settings=ws.SectionLayoutSettings(columns=COLUMNS, rows=ROWS),
)
def train_section(name: str, scope: str) -> ws.Section:
# Env names may carry regex metacharacters (e.g. "+"), so the scope is escaped in the
# regex-matched per-agent panels.
pattern = re.escape(scope)
return section(
name,
metrics=[f"{scope}/{m}" for m in COMMON_METRICS],
regexes=[f"{pattern}/all/[^/]+/reward/mean", f"{pattern}/effective/[^/]+/reward/mean"]
+ [f"{pattern}/{r}" for r in COMMON_REGEXES],
)
def eval_section(name: str, env_pattern: str) -> ws.Section:
# Same metrics as train, but eval's reward is the per-agent "avg@k" (dynamic k → regex).
# Everything is a regex so one section can also serve any env (env_pattern=".*").
return section(
name,
regexes=[f"eval/{env_pattern}/all/[^/]+/avg@.*", f"eval/{env_pattern}/effective/[^/]+/avg@.*"]
+ [f"eval/{env_pattern}/{m}" for m in COMMON_METRICS]
+ [f"eval/{env_pattern}/{r}" for r in COMMON_REGEXES],
)
def build_sections(
train_envs: Sequence[str] = (), eval_envs: Sequence[str] = (), flavor: Literal["rl", "sft"] = "rl"
) -> list[ws.Section]:
# SFT trains on a dataset, not rollouts: the train section is the loss/perplexity
# curves, eval sections are the same rollout-based ones as RL.
if flavor == "sft":
sections = [section("train", metrics=SFT_TRAIN_METRICS)]
if eval_envs:
sections += [eval_section(f"eval/{env}", re.escape(env)) for env in eval_envs]
else:
sections.append(eval_section("eval", ".*"))
sections.append(section("stability", metrics=SFT_STABILITY_METRICS))
sections.append(section("performance", metrics=SFT_PERFORMANCE_METRICS))
return sections
# With one env the aggregate == that env, so show only its section. With several, put the
# cross-env aggregate on top followed by a section per env.
if len(train_envs) == 1:
sections = [train_section(f"train/{train_envs[0]}", f"train/{train_envs[0]}")]
elif len(train_envs) > 1:
sections = [train_section("train/agg", "train/agg")]
sections += [train_section(f"train/{env}", f"train/{env}") for env in train_envs]
else:
# Env names unknown (e.g. SFT): fall back to the aggregate.
sections = [train_section("train", "train/agg")]
if eval_envs:
sections += [eval_section(f"eval/{env}", re.escape(env)) for env in eval_envs]
else:
# Env names unknown (e.g. SFT): one regex section matching any eval env.
sections.append(eval_section("eval", ".*"))
sections.append(section("stability", metrics=STABILITY_METRICS))
sections.append(inference_section())
sections.append(section("performance", metrics=PERFORMANCE_METRICS))
return sections
def list_views(entity: str, project: str) -> list[tuple[str, str]]:
"""``(display_name, internal_name)`` for every saved view in the project."""
query = gql(
"""
query Views($entity: String!, $project: String!) {
project(name: $project, entityName: $entity) {
allViews(viewType: "project-view") { edges { node { name displayName } } }
}
}
"""
)
res = wandb.Api().client.execute(query, variable_values={"entity": entity, "project": project})
edges = ((res.get("project") or {}).get("allViews") or {}).get("edges") or []
return [(e["node"]["displayName"], e["node"]["name"]) for e in edges if e.get("node")]
def view_signature(sections: Sequence[ws.Section]) -> tuple:
train = sorted(s.name[len("train/") :] for s in sections if s.name.startswith("train/") and s.name != "train/agg")
evals = sorted(s.name[len("eval/") :] for s in sections if s.name.startswith("eval/"))
panels = {
(getattr(p.x, "name", p.x), tuple(getattr(m, "name", m) for m in p.y or ()), p.metric_regex)
for s in sections
for p in s.panels
if isinstance(p, wr.LinePlot)
}
return (tuple(train), tuple(evals), tuple(sorted(panels, key=str)))
def next_overview_name(base: str, existing: Sequence[str]) -> str:
if base not in existing:
return base
prefix = f"{base}-v"
versions = [1] + [int(n[len(prefix) :]) for n in existing if n.startswith(prefix) and n[len(prefix) :].isdigit()]
return f"{base}-v{max(versions) + 1}"
def ensure_overview_view(
entity: str,
project: str,
name: str = OVERVIEW_NAME,
train_envs: Sequence[str] = (),
eval_envs: Sequence[str] = (),
flavor: Literal["rl", "sft"] = "rl",
) -> str | None:
"""Ensure an overview saved view exists for this run's env set. Reuses an existing overview built
for the same envs; when the env set is new, creates a fresh versioned view (``overview`` →
``overview-v2`` → …). Returns the URL of a newly created view, else None."""
sections = build_sections(train_envs, eval_envs, flavor)
target = view_signature(sections)
overviews = [(dn, iname) for dn, iname in list_views(entity, project) if dn == name or dn.startswith(f"{name}-v")]
for _, internal_name in overviews:
slug = internal_name.removeprefix("nw-").removesuffix("-v")
try:
existing = ws.Workspace.from_url(f"https://wandb.ai/{entity}/{project}?nw={slug}")
matches = view_signature(existing.sections) == target
except Exception as e:
# A single unreadable view must not abort reuse detection / versioning for the rest.
get_logger().warning(f"Could not inspect overview view {internal_name} - {e}")
continue
if matches:
return None
workspace = ws.Workspace(
entity=entity,
project=project,
name=next_overview_name(name, [dn for dn, _ in overviews]),
sections=sections,
auto_generate_panels=False,
settings=ws.WorkspaceSettings(x_axis="step"),
)
workspace.save()
return workspace.url
+5 -3
View File
@@ -43,15 +43,17 @@ class EvalSource:
# trigger fires every env (subject to ``skip_first_step``)
self.first_trigger = not is_resumed
def trigger(self, step: int) -> list[str]:
def trigger(self, step: int, *, force: bool = False) -> list[str]:
"""Fire eligible envs for ``step`` and return their names. On resume
``first_trigger`` is False, so the startup/base eval doesn't re-run."""
``first_trigger`` is False, so the startup/base eval doesn't re-run.
``force`` fires every env regardless of interval (e.g. the evaluator's
final-checkpoint eval)."""
is_first, self.first_trigger = self.first_trigger, False
if is_first and self.eval_config.skip_first_step:
return []
fired: list[str] = []
for name, interval in self.intervals.items():
if is_first or step % interval == 0:
if is_first or force or step % interval == 0:
fired.append(name)
# Round-robin across fired envs (A₁, B₁, A₂, B₂, …) so the
# dispatcher rotates at example granularity. ``try_schedule``'s
+320
View File
@@ -0,0 +1,320 @@
"""Online evaluator: disk-checkpoint-driven evals against a live inference server.
The trainer writes HF weight checkpoints to ``weights/step_{n}`` (``STABLE``
marker on completion) — that is its signal that a new policy is ready. The
evaluator watches the directory, tells the inference server to reload each
eligible checkpoint from disk (``/update_weights``, no NCCL rendezvous), and
runs the configured evals against the updated weights, sequentially per
checkpoint so every epoch measures exactly one policy version.
Reuses the orchestrator's eval components — ``EvalEnvs`` / ``EvalSource`` /
``EvalSink`` / ``EvalRollouts`` — and logs metrics and episodes through the same
monitors (``eval/{env}/...`` metrics, episode traces via the file monitor).
"""
from __future__ import annotations
import asyncio
import os
import time
import uuid
import verifiers.v1 as vf
from prime_rl import monitors
from prime_rl.configs.evaluator import EvaluatorConfig
from prime_rl.orchestrator.envs import EvalEnv, EvalEnvs
from prime_rl.orchestrator.eval_sink import EvalSink
from prime_rl.orchestrator.eval_source import EvalSource
from prime_rl.orchestrator.patches import (
monkey_patch_chat_completion_logprobs,
monkey_patch_oai_iterable_types,
)
from prime_rl.orchestrator.types import EvalBatch, Rollout
from prime_rl.orchestrator.utils import group_episodes, intercept_vf_logging, set_default_executor
from prime_rl.utils.client import InferencePool
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_step_path
from prime_rl.utils.utils import clean_exit
monkey_patch_oai_iterable_types()
monkey_patch_chat_completion_logprobs()
# How often to re-scan the weights directory for new checkpoints.
POLL_INTERVAL_S = 2.0
class Evaluator:
def __init__(self, config: EvaluatorConfig) -> None:
self.config = config
setup_logger(config.log.level, json_logging=config.log.json_logging)
intercept_vf_logging(logger="verifiers.v1", level="WARN")
get_logger().info(f"Starting evaluator (weights_dir={config.weights_dir})")
# The last weight-checkpoint step already handled (evaluated or skipped).
self.last_step = config.resume_step or 0
self.eval_triggered_at: dict[tuple[str, int], float] = {}
async def setup(self) -> None:
config = self.config
set_default_executor()
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
wandb=config.monitors.wandb,
file=config.monitors.file,
output_dir=config.output_dir,
run_config=config,
eval_env_names=[source.resolved_name for source in config.eval.source],
overview_flavor="sft",
)
# The launcher-set $PRL_RUN_ID is the run identity; standalone runs mint a local one.
self.run_id = os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
self.run_name = os.environ.get("PRL_RUN_NAME")
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.pool = InferencePool(config.eval.client, model_name=config.model)
get_logger().info("Loading eval environment(s)")
self.eval_envs = EvalEnvs(config.eval.source, config.eval.env_addresses)
await self.eval_envs.start()
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.pool.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
self.eval_source = EvalSource(self.eval_envs, config.eval, is_resumed=config.resume_step is not None)
self.eval_sink = EvalSink(eval_envs=self.eval_envs)
async def run(self) -> None:
await self.setup()
config = self.config
if config.resume_step is None:
# Base-model eval: the inference server starts with the untrained weights,
# so no reload is needed. The first trigger fires every env (policy v0)
# unless ``skip_first_step``.
await self.maybe_run_evals(step=0)
elif config.eval.retrigger_on_resume:
# Re-fire evals at the resume step (e.g. after a crash that lost in-flight
# evals). Requires the resume step's weights on disk. The final checkpoint
# force-fires every env, exactly like the watch loop below.
is_final = config.max_steps is not None and config.resume_step >= config.max_steps
await self.maybe_run_evals(step=config.resume_step, reload_weights=True, force=is_final)
get_logger().info(f"Watching {config.weights_dir} for new weight checkpoints (max_steps={config.max_steps})")
while True:
assert config.weights_dir is not None # resolved by the config validator
steps = get_all_ckpt_steps(config.weights_dir)
stable = {step: (get_step_path(config.weights_dir, step) / "STABLE").exists() for step in steps}
newest_stable = max((step for step in steps if stable[step]), default=None)
# Also walk eval-due steps that are no longer on disk: checkpoint cleaning
# (ckpt.keep_last / keep_interval) can delete a step before this scan sees
# it, and a vanished step would otherwise be skipped without a trace.
for step in sorted(set(steps) | self.deleted_due_steps(steps, newest_stable)):
if step <= self.last_step:
continue
if step not in stable:
get_logger().warning(
f"Weight checkpoint for eval step {step} was deleted before it could be "
"evaluated (checkpoint cleaning outpaced the evaluator) - skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
if not stable[step]:
# The trainer writes checkpoints in ascending order, so a marker-less
# step below a stable one is an abandoned partial write (e.g. a crash
# mid-save), not one in progress — skip it instead of wedging on it.
if newest_stable is None or newest_stable < step:
break # still being written — later steps can't be ready either
get_logger().warning(
f"Weight checkpoint step {step} has no STABLE marker but newer stable "
"checkpoints exist - treating it as abandoned and skipping its evals"
)
self.last_step = max(self.last_step, step)
continue
is_final = config.max_steps is not None and step >= config.max_steps
await self.maybe_run_evals(step=step, reload_weights=True, force=is_final)
if config.max_steps is not None and self.last_step >= config.max_steps:
break
await asyncio.sleep(POLL_INTERVAL_S)
get_logger().success("Evaluator finished!")
def deleted_due_steps(self, steps: list[int], newest_stable: int | None) -> set[int]:
"""Eval-due steps up to the newest stable checkpoint that are missing from the
weights dir — the trainer wrote them (it saves at every due step), so their
absence means checkpoint cleaning removed them before they were evaluated."""
if newest_stable is None:
return set()
due = {
step
for interval in self.eval_source.intervals.values()
for step in range(interval, newest_stable + 1, interval)
}
return due - set(steps)
async def maybe_run_evals(self, step: int, *, reload_weights: bool = False, force: bool = False) -> None:
"""Fire eligible envs for one checkpoint step and run the full epoch(s),
reloading the inference weights first. No-op when no env is due."""
assert self.config.weights_dir is not None # resolved by the config validator
weight_dir = get_step_path(self.config.weights_dir, step)
if reload_weights and not (weight_dir / "STABLE").exists():
get_logger().warning(f"No stable weight checkpoint for step {step} ({weight_dir}) - skipping eval")
self.last_step = max(self.last_step, step)
return
fired = self.eval_source.trigger(step, force=force)
self.last_step = max(self.last_step, step)
if not fired:
return
now = time.perf_counter()
for env_name in fired:
self.eval_triggered_at[(env_name, step)] = now
total_rollouts = sum(
self.eval_envs.get(env_name).config.group_size * len(self.eval_envs.get(env_name).examples)
for env_name in fired
)
if reload_weights:
get_logger().info(f"Updating inference weights to checkpoint step {step} ({weight_dir})")
try:
await self.pool.update_weights(weight_dir, step=step)
except Exception as exc:
# Skip this step instead of killing the run; drain the queued examples
# so they don't leak into a later epoch with the wrong eval_step.
while self.eval_source.next_example() is not None:
pass
get_logger().error(f"Failed to update inference weights to step {step} - skipping evals: {exc!r}")
return
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
await self.run_evals(step)
async def run_evals(self, step: int) -> None:
"""Drain the eval queue for one step under bounded concurrency, routing
finished episodes through the sink and finalizing each env's epoch."""
semaphore = asyncio.Semaphore(self.config.eval.max_inflight_episodes)
tasks: list[asyncio.Task] = []
while (example := self.eval_source.next_example()) is not None:
env = self.eval_envs.get(example["env_name"])
group_id = uuid.uuid4()
for _ in range(env.config.group_size):
tasks.append(asyncio.create_task(self.run_episode(env, example, group_id, step, semaphore)))
for future in asyncio.as_completed(tasks):
episode = await future
run = vf.EvalRunInfo(id=self.run_id, name=self.run_name, step=step)
for rollout in episode:
rollout.record_run(
run,
env_name=rollout.env_name,
group_id=str(rollout.group_id),
episode_id=rollout.episode_id,
policy_version=rollout.policy_version,
)
await monitors.log(group_episodes(episode), step, "eval", "all")
eval_batch = self.eval_sink.add(episode)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
async def run_episode(
self,
env: EvalEnv,
example: dict,
group_id: uuid.UUID,
step: int,
semaphore: asyncio.Semaphore,
) -> list[Rollout]:
"""Run one episode against the env server; failures synthesize an
error-marker rollout so the sink's count-based finalization still fires."""
async with semaphore:
try:
rollouts = await env.run(
client=self.pool.eval_client,
model_name=self.pool.model_name,
cache_salt=str(step),
task_data=example["task"].data.model_dump(mode="json"),
)
except Exception as exc:
get_logger().warning(f"Rollout task failed in group {group_id} ({env.name}): {exc!r}")
rollout = Rollout(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=example["task"].data.idx, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
)
rollout.record_error(exc)
rollouts = [rollout]
for rollout in rollouts:
if not rollout.has_error and rollout.num_turns == 0:
rollout.errors.append(
vf.Error(type="EmptyTrajectory", message="Rollout returned with no trajectory steps")
)
rollout.ok = False
get_logger().warning(f"Empty trajectory in group {group_id} ({env.name})")
rollout.kind = "eval"
rollout.env_name = env.name
rollout.group_id = group_id
# For SFT-driven evals the policy version *is* the checkpoint step.
rollout.policy_version = step
rollout.eval_step = step
return rollouts
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.rollouts:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
return
await monitors.log(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
rollouts = batch.rollouts
effective = rollouts.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", rollouts), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
eff, full = effective.metrics, rollouts.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Turns {eff.num_turns.mean():.1f} | Branches {eff.num_branches.mean():.1f} | "
f"Error {full.has_error.mean():.1%} | Truncation {eff.is_truncated.mean():.1%}"
)
async def stop(self) -> None:
"""Best-effort teardown; tolerates a partially completed ``setup()``."""
pool = getattr(self, "pool", None)
if pool is not None:
await pool.stop()
@clean_exit
async def run_evaluator(config: EvaluatorConfig) -> None:
evaluator = Evaluator(config)
try:
await evaluator.run()
# Finalize only on a clean exit — a crashed evaluator must not mark the run completed.
await monitors.finalize()
finally:
await evaluator.stop()
def main() -> None:
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
set_proc_title("Evaluator")
asyncio.run(run_evaluator(cli(EvaluatorConfig)))
if __name__ == "__main__":
main()
+28 -68
View File
@@ -39,8 +39,8 @@ if TYPE_CHECKING:
from prime_rl.orchestrator.ckpt import CheckpointManager
from prime_rl.transport.base import MicroBatchSender
from prime_rl.utils.client import InferencePool
from prime_rl.utils.monitor.base import Monitor
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
@@ -66,8 +66,8 @@ from prime_rl.orchestrator.types import (
)
from prime_rl.orchestrator.utils import (
get_weight_dir,
group_episodes,
intercept_vf_logging,
save_rollouts,
set_default_executor,
setup_policy_inference_pool,
trim_process_memory,
@@ -80,9 +80,6 @@ from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, s
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.monitor import setup_monitor
from prime_rl.utils.pathing import get_trace_path
from prime_rl.utils.usage_reporter import UsageReporter
from prime_rl.utils.utils import (
clean_exit,
resolve_latest_ckpt_step,
@@ -128,7 +125,6 @@ class Orchestrator:
# Always set by ``setup()``
tokenizer: PreTrainedTokenizer
policy_inference: InferencePool
monitor: Monitor
sender: MicroBatchSender | None
packer: BatchPacker
train_envs: TrainEnvs
@@ -143,7 +139,6 @@ class Orchestrator:
renderer: Renderer | None
mm_token_type_ids_mapping: dict[int, int] | None
heart: Heartbeat | None
usage_reporter: UsageReporter | None
inference_metrics: InferenceMetricsCollector | None
eval_envs: EvalEnvs | None
eval_sink: EvalSink | None
@@ -185,7 +180,6 @@ class Orchestrator:
self.renderer = None
self.mm_token_type_ids_mapping = None
self.heart = None
self.usage_reporter = None
self.inference_metrics = None
self.eval_envs = None
self.eval_sink = None
@@ -221,20 +215,18 @@ class Orchestrator:
if self.mm_token_type_ids_mapping == {}:
self.mm_token_type_ids_mapping = None
get_logger().info(f"Initializing monitor (wandb={config.wandb}, prime_monitor={config.prime_monitor})")
self.monitor = setup_monitor(
wandb_config=config.wandb,
prime_config=config.prime_monitor,
file_config=config.file_monitor,
get_logger().info(f"Initializing monitors ({config.monitors})")
await monitors.setup(
wandb=config.monitors.wandb,
prime=config.monitors.prime,
file=config.monitors.file,
output_dir=config.output_dir,
tokenizer=self.tokenizer,
run_config=config,
train_env_names=[env.resolved_name for env in config.train.source],
eval_env_names=[source.resolved_name for source in config.eval.source] if config.eval is not None else [],
)
# Prefer the monitor identity (platform run id, else W&B id) so traces link
# back to it, then the launcher-set $PRL_RUN_ID; standalone runs mint a local one.
self.run_id = self.monitor.run_id or os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex
# 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
# Base labels for sandboxes created in this process; env-server processes read
# the same launcher-set env var themselves.
self.run_name = os.environ.get("PRL_RUN_NAME")
@@ -244,11 +236,6 @@ class Orchestrator:
if config.heartbeat is not None:
self.heart = Heartbeat(config.heartbeat.url)
usage_base_url = os.environ.get("PI_USAGE_BASE_URL")
usage_api_key = os.environ.get("PI_USAGE_API_KEY")
if usage_base_url and usage_api_key:
self.usage_reporter = UsageReporter()
# Filters apply to train rollouts only
pre_filters = setup_filters(config.pre_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="pre-batch")
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
@@ -294,7 +281,9 @@ class Orchestrator:
*(env.algorithm.setup() for env in self.train_envs),
)
if config.wandb is not None and config.collect_inference_metrics:
# 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,
@@ -399,7 +388,7 @@ class Orchestrator:
assert config.max_inflight_episodes is not None, "max_inflight_episodes must be resolved before dispatcher init"
log_interval = config.log.interval
wandb_enabled = config.wandb is not None
wandb_enabled = monitors.get(monitors.WandbMonitor) is not None
self.dispatcher = RolloutDispatcher(
train_envs=self.train_envs,
eval_envs=self.eval_envs,
@@ -497,9 +486,11 @@ class Orchestrator:
elapsed = format_time(time.perf_counter() - start_time)
if clean_exit:
get_logger().success(f"Orchestrator step loop done in {elapsed}")
# 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()
else:
get_logger().warning(f"Orchestrator interrupted after {elapsed} — forcing cleanup (not a clean exit)")
self.monitor.save_final_summary()
# ``progress.step`` points at the next (unshipped) step; the last finished step is
# ``progress.step - 1``. Checkpoint it as ``step_{progress.step - 1}`` (no-op before the
# first ship).
@@ -549,11 +540,7 @@ class Orchestrator:
episode_id=rollout.episode_id,
policy_version=rollout.policy_version,
)
await asyncio.to_thread(
save_rollouts,
[rollout.to_record() for rollout in episode],
get_trace_path(self.config.output_dir, step, kind, "all"),
)
await monitors.log(group_episodes(episode), step, kind, "all")
if kind == "eval":
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
@@ -570,7 +557,7 @@ class Orchestrator:
async def finalize_train_batch(self, batch: TrainBatch) -> None:
"""Ship one ``TrainBatch`` out to the trainer and handle the I/O
side-effects (ckpt, save_rollouts, reference scoring, sender.send,
side-effects (ckpt, monitors.log, reference scoring, sender.send,
metrics, heartbeat, progress, eval trigger). The sink has already
done all data-transformation work."""
config = self.config
@@ -644,12 +631,9 @@ class Orchestrator:
if self.train_envs.get(r.env_name).sampler.samples_from_live_policy:
r.off_policy_steps = (step - 1) - r.policy_version
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
# at ship time; the full arrival window already streamed into ``all`` on arrival.
# to_record drops the per-node training tensors — they're for training, not the rollout
# record, and can't round-trip json (raw numpy bytes).
records = [r.to_record() for r in effective]
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
# The effective (clean, trained-on) subset is logged at ship time; the full arrival
# window already streamed into the ``all`` cohort on arrival.
await monitors.log(group_episodes(effective.rollouts), step, "train", "effective")
pack_start_time = time.perf_counter()
micro_batch_grid = await asyncio.to_thread(self.packer.pack, batch.samples)
@@ -701,25 +685,9 @@ class Orchestrator:
)
for name, count in self.train_sink.pre_filter_dropped_by_name.items():
metrics[f"pre_filters/all/{name}/rate"] = count / self.train_sink.pre_filter_seen
self.monitor.log(metrics, step=step)
await monitors.log(metrics, step=step)
self.wait_for_policy_time = 0.0
self.monitor.log_samples(effective.rollouts, step=step)
self.monitor.log_distributions(
distributions={
"rewards": [r.reward for r in effective],
"advantages": [a for r in effective if (a := r.scalar_advantage()) is not None],
},
step=step,
)
if self.usage_reporter is not None:
run_id = os.getenv("RUN_ID", "")
if run_id:
self.usage_reporter.report_training_usage(
run_id=run_id,
step=step,
tokens=num_input + num_output,
)
if self.heart is not None:
self.heart.beat()
@@ -857,21 +825,15 @@ class Orchestrator:
get_logger().success("\n\t\t ".join(lines))
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch (save_rollouts,
monitor.log_eval_samples, monitor.log)."""
"""Persist + log one completed eval epoch through the monitors."""
if not batch.rollouts:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
return
# The non-errored subset lands in the per-step ``effective`` trace file on epoch
# completion (multiple eval envs share the step file — each epoch appends its cohort
# once, and every record carries ``env_name``); the full returned cohort already
# streamed into ``all`` on arrival.
records = [r.to_record() for r in batch.rollouts.effective]
await asyncio.to_thread(
save_rollouts, records, get_trace_path(self.config.output_dir, batch.step, "eval", "effective")
)
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
# The non-errored subset is logged on epoch completion (multiple eval envs share the
# step's trace file — each epoch appends its cohort once, and every record carries
# ``env_name``); the full returned cohort already streamed into ``all`` on arrival.
await monitors.log(group_episodes(batch.rollouts.effective.rollouts), batch.step, "eval", "effective")
policy_versions = {r.policy_version for r in batch.rollouts}
policy_version = min(policy_versions)
if len(policy_versions) > 1:
@@ -887,7 +849,7 @@ class Orchestrator:
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
metrics[f"eval/{batch.env_name}/policy_version"] = float(policy_version)
metrics["step"] = float(batch.step)
self.monitor.log(metrics, step=batch.step)
await monitors.log(metrics, step=batch.step)
# Success line — quality metrics over the effective set, error rate over the full returned
# cohort. ``Stat.mean()`` is 0.0 for an empty set.
@@ -992,8 +954,6 @@ class Orchestrator:
for env in self.train_envs:
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
await pool.stop()
if self.usage_reporter is not None:
self.usage_reporter.close()
task = asyncio.create_task(teardown())
_, pending = await asyncio.wait({task}, timeout=SHUTDOWN_TIMEOUT_S)
+1 -1
View File
@@ -12,7 +12,7 @@
``add()`` takes one episode (``list[Rollout]``) and returns
``TrainBatch | None``; group accounting counts episodes, never loose traces.
I/O concerns (ship to trainer, save_rollouts, monitor.log) live on the
I/O concerns (ship to trainer, monitors.log) live on the
orchestrator.
"""
+22 -10
View File
@@ -6,8 +6,10 @@ import math
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import TYPE_CHECKING
import orjson
import verifiers.v1 as vf
from verifiers.v1.episode import EnvInfo
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.utils.client import InferencePool
@@ -18,6 +20,9 @@ from prime_rl.utils.utils import (
get_step_path,
)
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
"""Build the live policy inference pool + matching renderer. Returns
@@ -49,15 +54,22 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
return renderer, inference_pool
def save_rollouts(rollouts: list[dict], path: Path) -> None:
"""Append rollouts (Trace record dicts, already JSON-serializable) to a JSONL file.
The trace streams are append-only: ``all`` grows one rollout at a time as they
complete, ``effective`` one batch at a time on finalize."""
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "ab") as f:
for rollout in rollouts:
f.write(orjson.dumps(rollout, default=str, option=opts))
def group_episodes(rollouts: "list[Rollout]") -> list[vf.Episode]:
"""Regroup rollouts into their episodes. The dispatcher unwraps every
``vf.Episode`` into its traces on arrival; ``episode_id`` links them back
together (a rollout without one forms a single-trace episode)."""
groups: dict[str, list] = {}
for rollout in rollouts:
groups.setdefault(rollout.episode_id or rollout.id, []).append(rollout)
return [
vf.Episode(
id=episode_id,
env=EnvInfo(id=group[0].env_name),
traces=group,
ok=all(trace.ok for trace in group),
)
for episode_id, group in groups.items()
]
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
@@ -41,6 +41,19 @@ mkdir -p $LOG_DIR/trainer
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
# 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_LABEL=trainer
export WANDB_PROGRAM="uv run sft"
{% endif %}
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
echo "HOSTNAMES=${HOSTNAMES[@]}"
@@ -0,0 +1,250 @@
#!/bin/bash
#SBATCH --job-name={{ job_name }}-eval
#SBATCH --nodes={{ num_infer_nodes }}
#SBATCH --ntasks-per-node=1
#SBATCH --gres=gpu:{{ gpus_per_node }}
#SBATCH --partition={{ partition }}
{%- if account %}
#SBATCH --account={{ account }}
{%- endif %}
{%- if time %}
#SBATCH --time={{ time }}
{%- endif %}
{%- if nodelist %}
#SBATCH --nodelist={{ nodelist }}
{%- endif %}
{%- if exclude %}
#SBATCH --exclude={{ exclude }}
{%- endif %}
#SBATCH --exclusive
#SBATCH --output={{ output_dir }}/eval_job_%j.log
#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
# 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).
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
set -e
# Configs
export NUM_NODES={{ num_infer_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
export ROUTER_PORT={{ router_port }}
export BACKEND_PORT={{ backend_port }}
export RPC_PORT={{ data_parallel_rpc_port }}
# Paths
export PROJECT_DIR={{ project_dir }}
export CONFIG_DIR={{ config_dir }}
export CONFIG_PATH=$CONFIG_DIR/inference.json
export OUTPUT_DIR={{ output_dir }}
# Move a previous job's inference logs aside instead of deleting them: rm of log
# files another job's processes still hold open can wedge in the NFS client and
# hang the whole job before srun even runs.
[ -d $OUTPUT_DIR/logs/inference ] && mv $OUTPUT_DIR/logs/inference $OUTPUT_DIR/logs/inference_prev_$(date +%s)
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
# 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
# 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_PROGRAM="uv run sft"
{% endif %}
# Networking
export HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
export HOSTNAMES_STR="${HOSTNAMES[*]}"
# Single global router on node 0 fronts every per-rank endpoint; admin ops
# (pause/update_weights/resume) bypass it and hit each rank directly.
INFER_URLS="http://${HOSTNAMES[0]}:${ROUTER_PORT}/v1"
DP_PER_NODE={{ dp_per_node }}
ADMIN_URLS=""
ROUTER_ARGS=""
for host in ${HOSTNAMES[@]}; do
for ((d=0; d<DP_PER_NODE; d++)); do
ADMIN_URLS="${ADMIN_URLS:+$ADMIN_URLS }http://${host}:$((BACKEND_PORT + d))/v1"
ROUTER_ARGS="$ROUTER_ARGS http://${host}:$((BACKEND_PORT + d))"
done
done
export INFER_URLS
export ADMIN_URLS
export ROUTER_ARGS
echo "HOSTNAMES=${HOSTNAMES[@]}"
echo "INFER_URLS=${INFER_URLS}"
echo "ADMIN_URLS=${ADMIN_URLS}"
# Setup environment
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
{% if not shared_fs %}
# Node-local venv (e.g. UV_PROJECT_ENVIRONMENT on /tmp): a bare `uv sync` would only
# build the batch node, so srun runs it on every node (one task each) and blocks until
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -s <<'SYNC_SH'
cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages
SYNC_SH
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras --all-packages
{% endif %}
{% if pre_run_command %}
# Pre-run command
{{ pre_run_command }}
{% endif %}
# Cleanup stale node-local state from prior jobs. Orphan python/vllm processes and
# vLLM/torch IPC files under /dev/shm and /tmp can survive SLURM termination and
# cause the next launch to hang. Harmless on clean nodes.
#
# `bash -s` with a heredoc on stdin keeps the script body out of every bash
# / srun argv — otherwise `pkill -f "[v]llm"` self-matches the cleanup procs
# because the surviving literal `vllm` strings below appear in the cmdline.
srun bash -s <<'CLEANUP_SH'
pkill -9 -f "[p]ython.*prime_rl" 2>/dev/null
pkill -9 -f "[v]llm-router" 2>/dev/null
pkill -9 -f "[v]llm" 2>/dev/null
pkill -9 -f "[p]rime_rl" 2>/dev/null
# Also match prctl-set process names (kernel comm) like "vllm::router"
# which pkill -f does not see because -f only matches the cmdline.
pkill -9 "vllm" 2>/dev/null
pkill -9 "vllm::.*" 2>/dev/null
sleep 2
rm -rf /dev/shm/vllm-* /dev/shm/vllm_* /tmp/vllm-* /tmp/vllm_* /tmp/torch-* 2>/dev/null
procs=$(ps -eo comm,args | grep -E "python|vllm|vllm::" | grep -v grep | wc -l)
gpu=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | awk "{s+=\$1} END {print s}")
echo "[node-cleanup] $(hostname) procs=$procs gpu_mem=${gpu}MiB"
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
# of leaving the surviving ranks holding nodes.
#
# The body goes to bash on stdin through a quoted heredoc instead of a
# single-quoted `bash -c` argument: srun broadcasts stdin to every task, and the
# quoted delimiter passes the script through verbatim, so apostrophes and quotes
# (including in the shared _launch_*.sh.j2 includes) need no escaping. Nothing in
# the body reads stdin, which would otherwise eat the rest of the script.
srun --kill-on-bad-exit=1 bash -s <<'LAUNCH_SH'
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
# wait/cleanup block at the end of this script surfaces background
# process crashes (router, engines) as task failures.
set -o pipefail
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
# Higher ulimit
ulimit -n 65536
# Infiniband setup
IB_HCA=$(ibv_devinfo 2>/dev/null | sed -n -e "/hca_id/p" -e "/link_layer:/p" | grep -B1 InfiniBand | grep hca_id | sed -e "s/^hca_id://g" | tr -d "[[:blank:]]" | paste -sd,)
[ -n "$IB_HCA" ] && export NCCL_IB_HCA=$IB_HCA
INFER_NODE_RANK=$SLURM_PROCID
LOCAL_IP=$(hostname -I | awk "{print \$1}")
# Inference env vars: launcher defaults + [env_vars] + [inference.env_vars]
{%- for key, value in inference_env_vars.items() %}
export {{ key }}="{{ value }}"
{%- endfor %}
{% include '_launch_rank.sh.j2' %}
{% include '_launch_router.sh.j2' %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
DP_PER_NODE={{ dp_per_node }}
TP=$((GPUS_PER_NODE / DP_PER_NODE))
EP={{ "1" if enable_expert_parallel else "0" }}
# External-LB: one vLLM API server per DP rank on this node (BACKEND_PORT + dp_local),
# each pinned to its TP slice of GPUs. Each node is an independent replica, so any MoE EP
# group is node-local (rendezvous on LOCAL_IP); dense models run independent engines.
for ((d=0; d<DP_PER_NODE; d++)); do
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
else
# Dense or single-DP-rank EP (dp=1, e.g. EP within one tp=8 group):
# independent single-engine servers. vLLM rejects the external-LB DP
# args when data_parallel_size == 1; enable_expert_parallel in the
# inference config alone shards experts across the TP group.
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
fi
done
if [ "$INFER_NODE_RANK" -eq 0 ]; then
# Single global router on node 0 (external LB across all per-rank endpoints)
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
# source at its deterministic loopback address (so this node), polling until
# they are up - the servers and the evaluator 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 \
> $OUTPUT_DIR/logs/envs/eval/{{ name }}.log 2>&1 &
{%- endfor %}
{%- endif %}
# The evaluator 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() %}
export {{ key }}="{{ value }}"
{%- endfor %}
WANDB_SHARED_LABEL=evaluator uv run evaluator \
@ $CONFIG_DIR/evaluator.json \
--eval.client.base-url $INFER_URLS \
--eval.client.admin-base-url $ADMIN_URLS \
2>&1 | tee $OUTPUT_DIR/logs/evaluator.log &
EVALUATOR_PID=$!
else
# Watch for the completion sentinel so this node's wait below returns when
# the evaluator (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)
# 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
# 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"
fi
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
for pid in $(jobs -p); do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
LAUNCH_SH
+40 -39
View File
@@ -25,7 +25,7 @@ from prime_rl.configs.shared import ResumeConfig
from prime_rl.configs.trainer import CheckpointConfig, LoRAConfig, WeightCheckpointConfig
from prime_rl.trainer.lora import get_lora_state, has_lora_layers, save_lora_config
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.optim import CPUOffloadOptimizer
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
from prime_rl.trainer.weights import (
gather_weights_on_master,
save_state_dict,
@@ -62,7 +62,7 @@ class AppState(Stateful):
def __init__(
self,
model: Module,
optimizers: list[Optimizer],
optimizers: list[OptimizerLike],
scheduler: LRScheduler | None,
progress: Progress | None,
):
@@ -71,25 +71,24 @@ class AppState(Stateful):
self.scheduler = scheduler
self.progress = progress
def _get_base_optimizers(self) -> list[Optimizer]:
"""Extract base optimizers from wrappers like CPUOffloadOptimizer."""
return [opt.base_optimizer if isinstance(opt, CPUOffloadOptimizer) else opt for opt in self.optimizers]
def _get_checkpoint_optimizers(self) -> list[Optimizer]:
"""Expose optimizers keyed by their model parameters for DCP."""
return [
optimizer.checkpoint_optimizer() if isinstance(optimizer, OffloadOptimizer) else optimizer
for optimizer in self.optimizers
]
def _has_cpu_offload(self) -> bool:
return any(isinstance(opt, CPUOffloadOptimizer) for opt in self.optimizers)
return any(isinstance(optimizer, OffloadOptimizer) for optimizer in self.optimizers)
def state_dict(self) -> dict[str, Any]:
# get_state_dict requires optimizer states to live on param.device. For an
# already-initialized CPU-offload optimizer that means staging back to GPU
# before the call; the matching offload happens after the dict is built.
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer) and opt._initialized:
opt._move_states("cuda")
torch.cuda.synchronize()
for optimizer in self.optimizers:
if isinstance(optimizer, OffloadOptimizer):
optimizer.prepare_checkpoint_save()
# Automatically manages FSDP FQN's, as well as sets the default state dict type to FSDP.SHARDED_STATE_DICT
base_optimizers = self._get_base_optimizers()
model_state_dict, optimizer_state_dict = get_state_dict(self.model, base_optimizers)
checkpoint_optimizers = self._get_checkpoint_optimizers()
model_state_dict, optimizer_state_dict = get_state_dict(self.model, checkpoint_optimizers)
state_dict = {
"model": model_state_dict,
"optimizers": optimizer_state_dict,
@@ -101,28 +100,19 @@ class AppState(Stateful):
progress_state_dict = asdict(self.progress)
state_dict["progress"] = progress_state_dict
# Offload optimizer states to CPU for every CPUOffloadOptimizer, including
# ones that were uninitialized on entry. dcp_load calls this method to build
# a template, and get_state_dict's internal _init_optim_state populates an
# empty optim.state with GPU tensors. Optimizer.state_dict() returns those
# values via shallow copy, so optimizer_state_dict["state"][fqn] is the same
# dict object as optim.state[param]. Replacing the entries with CPU tensors
# in place therefore flips the template too — dcp_load reads bytes from disk
# straight into CPU storage and optim.state is loaded by the time the load
# returns, without GPU optimizer state ever existing for the duration of the
# read.
has_cpu_offload = self._has_cpu_offload()
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer):
opt._move_states("cpu")
if has_cpu_offload:
for optimizer in self.optimizers:
if isinstance(optimizer, OffloadOptimizer):
optimizer.finish_checkpoint_save()
if self._has_cpu_offload():
torch.cuda.synchronize()
gc.collect()
torch.cuda.empty_cache()
return state_dict
def load_state_dict(self, state_dict: dict[str, Any]):
base_optimizers = self._get_base_optimizers()
checkpoint_optimizers = self._get_checkpoint_optimizers()
has_cpu_offload = self._has_cpu_offload()
if has_cpu_offload:
@@ -138,13 +128,13 @@ class AppState(Stateful):
# apply the model side here and flip the wrappers to initialized so
# subsequent steps take the steady-state path.
set_model_state_dict(self.model, model_state_dict=state_dict["model"])
for opt in self.optimizers:
if isinstance(opt, CPUOffloadOptimizer):
opt._initialized = True
for optimizer in self.optimizers:
if isinstance(optimizer, OffloadOptimizer):
optimizer.finish_checkpoint_load()
else:
set_state_dict(
self.model,
base_optimizers,
checkpoint_optimizers,
model_state_dict=state_dict["model"],
optim_state_dict=state_dict["optimizers"],
)
@@ -194,7 +184,7 @@ class CheckpointManager:
self,
path: Path,
model: nn.Module,
optimizers: list[Optimizer],
optimizers: list[OptimizerLike],
scheduler: LRScheduler,
progress: Progress,
dataloader: StatefulDataLoader | None = None,
@@ -226,7 +216,7 @@ class CheckpointManager:
self,
path: Path,
model: nn.Module,
optimizers: list[Optimizer],
optimizers: list[OptimizerLike],
scheduler: LRScheduler | None,
progress: Progress | None,
dataloader: StatefulDataLoader | None = None,
@@ -239,6 +229,10 @@ class CheckpointManager:
app_state = AppState(model, optimizers if not self.skip_optimizer else [], scheduler, progress)
state_dict = {"app": app_state}
dcp_load(state_dict=state_dict, checkpoint_id=path)
if self.skip_optimizer:
for optimizer in optimizers:
if isinstance(optimizer, OffloadOptimizer):
optimizer.finish_model_only_checkpoint_load()
# Load the dataloader
if dataloader is not None:
@@ -260,7 +254,7 @@ class CheckpointManager:
self,
step: int,
model: nn.Module,
optimizers: list[Optimizer],
optimizers: list[OptimizerLike],
scheduler: LRScheduler | None,
progress: Progress | None,
dataloader: StatefulDataLoader | None = None,
@@ -277,7 +271,7 @@ class CheckpointManager:
self,
step: int,
model: nn.Module,
optimizers: list[Optimizer],
optimizers: list[OptimizerLike],
scheduler: LRScheduler,
progress: Progress,
dataloader: StatefulDataLoader | None = None,
@@ -502,6 +496,13 @@ class WeightCheckpointManager:
# Determine which steps to keep
steps_to_keep = set()
# 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
# max_steps checkpoint forever.
if self.ckpt_steps:
steps_to_keep.add(self.ckpt_steps[-1])
# Keep the most recent keep_last steps
if self.keep_last is not None:
steps_to_keep.update(self.ckpt_steps[-self.keep_last :])
+20
View File
@@ -442,6 +442,26 @@ def apply_fp32_moe_router(model: nn.Module) -> None:
logger.info(f"Running {num_routers} MoE router gates in fp32")
def get_full_offload_dtype_policy(
model: nn.Module,
config: ModelConfig,
) -> dict[int, tuple[torch.dtype, torch.dtype]]:
"""Return persistent parameter and reduced-gradient dtypes for full offload."""
# FSDP casts reduced gradients back to the persistent sharded-parameter dtype.
policy = {id(param): (torch.bfloat16, torch.bfloat16) for param in model.parameters() if param.is_floating_point()}
if config.moe_router_dtype != "float32":
return policy
language_model = get_language_model(model)
for layer in language_model.layers:
mlp = layer.mlp if hasattr(layer, "mlp") else layer.feed_forward if hasattr(layer, "feed_forward") else None
if isinstance(mlp, (MoE, LatentMoE)):
for param in mlp.router.parameters():
if param.is_floating_point():
policy[id(param)] = (torch.float32, torch.float32)
return policy
def freeze_sparse_indexer(model: nn.Module) -> None:
"""Freeze DSA sparse-attention indexer parameters.
@@ -1,124 +1,75 @@
import copy
import torch
from dion import Muon
from torch import nn
from torch.distributed.tensor import DTensor
from torch.optim import SGD, AdamW, Optimizer
from prime_rl.configs.trainer import OptimizerConfig
from prime_rl.configs.trainer import OptimizerConfig, OptimizerInBackwardOffloadConfig
from prime_rl.trainer.optim.base import OffloadOptimizer as OffloadOptimizer
from prime_rl.trainer.optim.base import OptimizerLike
from prime_rl.trainer.optim.offload import (
FullCPUOffloadOptimizer,
GradientOffloadManager,
_create_cpu_master_weights,
)
from prime_rl.trainer.optim.state_offload import CPUOffloadOptimizer
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.trainer.sign_sgd import SignSGD
from prime_rl.utils.logger import get_logger
class CPUOffloadOptimizer:
"""Wraps an optimizer to keep states on CPU, moving to GPU only for step().
Unlike FSDP's CPUOffload which offloads weights too, this keeps weights on GPU.
With activation checkpointing, activations and optimizer states are never on GPU
at the same time: peak memory becomes max(activations, opt_states) instead of sum.
"""
def __init__(self, optimizer: Optimizer, pin_memory: bool = True):
self.optimizer = optimizer
self.pin_memory = pin_memory
self._initialized = False
def _move_states(self, device: str):
"""Move optimizer states to CPU or back to GPU (matching each parameter's device)."""
for p in self.optimizer.state:
state = self.optimizer.state[p]
for k, v in state.items():
if isinstance(v, DTensor):
local_tensor = v._local_tensor
if device == "cpu":
non_blocking = not self.pin_memory
new_local = local_tensor.to("cpu", non_blocking=non_blocking)
if self.pin_memory and not new_local.is_pinned():
new_local = new_local.pin_memory()
else:
new_local = local_tensor.to(device, non_blocking=True)
new_dtensor = copy.copy(v)
new_dtensor._local_tensor = new_local
state[k] = new_dtensor
elif isinstance(v, torch.Tensor):
if device == "cpu":
non_blocking = not self.pin_memory
cpu_tensor = v.to("cpu", non_blocking=non_blocking)
if self.pin_memory and not cpu_tensor.is_pinned():
cpu_tensor = cpu_tensor.pin_memory()
state[k] = cpu_tensor
else:
state[k] = v.to(device, non_blocking=True)
def step(self, closure=None):
# First step initializes states on GPU - offload after
if not self._initialized:
result = self.optimizer.step(closure)
self._move_states("cpu")
self._initialized = True
return result
# Move states to GPU
self._move_states("cuda")
# Run optimizer step
result = self.optimizer.step(closure)
# Move states back to CPU
self._move_states("cpu")
return result
def zero_grad(self, set_to_none: bool = True):
self.optimizer.zero_grad(set_to_none=set_to_none)
def state_dict(self):
# Move to GPU temporarily for consistent state dict
if self._initialized:
self._move_states("cuda")
torch.cuda.synchronize()
sd = self.optimizer.state_dict()
if self._initialized:
self._move_states("cpu")
return sd
def load_state_dict(self, state_dict):
self.optimizer.load_state_dict(state_dict)
self._move_states("cpu")
self._initialized = True
@property
def param_groups(self):
return self.optimizer.param_groups
@param_groups.setter
def param_groups(self, value):
self.optimizer.param_groups = value
@property
def state(self):
return self.optimizer.state
@property
def base_optimizer(self) -> Optimizer:
return self.optimizer
def setup_optimizer(
config: OptimizerConfig,
named_params: list[tuple[str, nn.Parameter]],
parallel_dims: ParallelDims,
cpu_offload: bool = False,
) -> Optimizer | CPUOffloadOptimizer:
optimizer = _create_optimizer(config, named_params, parallel_dims)
full_offload_config: OptimizerInBackwardOffloadConfig | None = None,
model: nn.Module | None = None,
full_offload_dtype_policy: dict[int, tuple[torch.dtype, torch.dtype]] | None = None,
) -> 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.max_norm is not None:
get_logger().warning("Disabling gradient clipping because CPU optimizer offload updates during backward")
config.max_norm = None
optimizer_named_params = named_params
master_weights = None
if full_offload_config is not None:
if model is None:
raise ValueError("CPU optimizer offload requires the model")
if full_offload_dtype_policy is None:
raise ValueError("CPU optimizer offload requires an explicit per-parameter dtype policy")
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"),
dtype_policy=full_offload_dtype_policy,
)
optimizer = _create_optimizer(
config,
optimizer_named_params,
parallel_dims,
fused_adamw=full_offload_config is not None and config.type == "adamw",
)
if full_offload_config is not None:
assert master_weights is not None
get_logger().info("Using CPU offload for gradients and the optimizer step")
optimizer = FullCPUOffloadOptimizer(
optimizer,
offload_config=full_offload_config,
master_weights=master_weights,
dp_replicate=parallel_dims.dp_replicate,
)
return optimizer, optimizer._gradient_manager
if cpu_offload:
get_logger().info("Wrapping optimizer with CPUOffloadOptimizer for optimizer state CPU offloading")
return CPUOffloadOptimizer(optimizer)
return CPUOffloadOptimizer(optimizer), None
return optimizer
return optimizer, None
def _create_optimizer(
@@ -126,6 +77,7 @@ def _create_optimizer(
named_params: list[tuple[str, nn.Parameter]],
parallel_dims: ParallelDims,
lr: float | None = None,
fused_adamw: bool = False,
) -> Optimizer:
"""Create optimizer. If lr is None, uses config.lr."""
if lr is None:
@@ -150,6 +102,7 @@ def _create_optimizer(
lr=lr,
weight_decay=config.weight_decay,
betas=(config.betas1, config.betas2),
fused=fused_adamw,
)
case "muon":
return _create_muon_optimizer(config, named_params, parallel_dims, lr)
+28
View File
@@ -0,0 +1,28 @@
from abc import ABC, abstractmethod
from typing import TypeAlias
from torch.optim import Optimizer
class OffloadOptimizer(ABC):
@property
@abstractmethod
def base_optimizer(self) -> Optimizer: ...
@abstractmethod
def checkpoint_optimizer(self) -> Optimizer: ...
def prepare_checkpoint_save(self) -> None:
pass
def finish_checkpoint_save(self) -> None:
pass
@abstractmethod
def finish_checkpoint_load(self) -> None: ...
def finish_model_only_checkpoint_load(self) -> None:
pass
OptimizerLike: TypeAlias = Optimizer | OffloadOptimizer
@@ -0,0 +1,96 @@
from functools import cache
from pathlib import Path
from types import ModuleType
import torch
from torch.utils.cpp_extension import load
def _cpu_build_options() -> tuple[str, list[str]]:
capability = torch.backends.cpu.get_cpu_capability().upper()
if capability == "AVX512":
return "avx512", [
"-DCPU_CAPABILITY=AVX512",
"-DCPU_CAPABILITY_AVX512",
"-mavx512f",
"-mavx512dq",
"-mavx512vl",
"-mavx512bw",
"-mfma",
]
if capability == "AVX2":
return "avx2", [
"-DCPU_CAPABILITY=AVX2",
"-DCPU_CAPABILITY_AVX2",
"-mavx2",
"-mfma",
"-mf16c",
]
return "default", []
@cache
def _extension() -> ModuleType:
capability, capability_flags = _cpu_build_options()
return load(
name=f"prime_rl_cpu_adam_{capability}",
sources=[str(Path(__file__).with_name("kernel.cpp"))],
extra_cflags=["-O3", "-fopenmp", *capability_flags],
extra_ldflags=["-fopenmp"],
verbose=False,
)
def load_cpu_adamw_kernel() -> None:
_extension()
@torch.no_grad()
def add_bfloat16_(destination: torch.Tensor, source: torch.Tensor) -> None:
_extension().add_bfloat16_(destination, source)
@torch.no_grad()
def copy_bfloat16_(destination: torch.Tensor, source: torch.Tensor) -> None:
_extension().copy_bfloat16_(destination, source)
@torch.no_grad()
def copy_or_add_bfloat16_multi_(
destinations: list[torch.Tensor],
sources: list[torch.Tensor],
add: list[bool],
) -> None:
_extension().copy_or_add_bfloat16_multi_(destinations, sources, add)
@torch.no_grad()
def adamw_step(
params: list[torch.Tensor],
grads: list[torch.Tensor],
exp_avgs: list[torch.Tensor],
exp_avg_sqs: list[torch.Tensor],
state_steps: list[torch.Tensor],
compute_params: list[torch.Tensor] | None = None,
*,
lr: float,
beta1: float,
beta2: float,
weight_decay: float,
eps: float,
gradient_scale: float,
) -> None:
_extension().adamw_step(
params,
grads,
exp_avgs,
exp_avg_sqs,
state_steps,
compute_params or [],
lr,
beta1,
beta2,
weight_decay,
eps,
gradient_scale,
)
@@ -0,0 +1,350 @@
#include <ATen/Parallel.h>
#include <ATen/cpu/vec/functional.h>
#include <torch/extension.h>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <vector>
namespace {
struct TensorSpan {
float* param;
const void* grad;
void* compute_param;
float* exp_avg;
float* exp_avg_sq;
bool grad_bfloat16;
bool compute_param_bfloat16;
int64_t begin;
int64_t end;
float step_size;
float bias_correction2_sqrt;
};
struct BFloat16CopySpan {
float* destination;
const at::BFloat16* source;
bool add;
int64_t begin;
int64_t end;
};
void check_tensor(const torch::Tensor& tensor, const char* name) {
TORCH_CHECK(tensor.device().is_cpu(), name, " must be on CPU");
TORCH_CHECK(tensor.scalar_type() == torch::kFloat32, name, " must be float32");
TORCH_CHECK(tensor.is_contiguous(), name, " must be contiguous");
}
void check_grad(const torch::Tensor& tensor) {
TORCH_CHECK(tensor.device().is_cpu(), "grad must be on CPU");
TORCH_CHECK(
tensor.scalar_type() == torch::kFloat32 || tensor.scalar_type() == torch::kBFloat16,
"grad must be float32 or bfloat16");
TORCH_CHECK(tensor.is_contiguous(), "grad must be contiguous");
}
void copy_or_add_bfloat16_span(const BFloat16CopySpan& span, int64_t begin, int64_t end) {
float* destination_data = span.destination + begin;
const at::BFloat16* source_data = span.source + begin;
using Vec = at::vec::Vectorized<float>;
using BVec = at::vec::Vectorized<at::BFloat16>;
constexpr int64_t block_size = 2 * Vec::size();
int64_t i = 0;
const int64_t size = end - begin;
for (; i <= size - block_size; i += block_size) {
const BVec source_vec = BVec::loadu(source_data + i);
auto [source0, source1] = at::vec::convert_to_float<at::BFloat16>(source_vec);
if (span.add) {
(Vec::loadu(destination_data + i) + source0).store(destination_data + i);
(Vec::loadu(destination_data + i + Vec::size()) + source1)
.store(destination_data + i + Vec::size());
} else {
source0.store(destination_data + i);
source1.store(destination_data + i + Vec::size());
}
}
for (; i < size; ++i) {
const float source_value = static_cast<float>(source_data[i]);
destination_data[i] = span.add ? destination_data[i] + source_value : source_value;
}
}
void copy_or_add_bfloat16_multi_(
const std::vector<torch::Tensor>& destinations,
const std::vector<torch::Tensor>& sources,
const std::vector<bool>& add) {
const auto count = destinations.size();
TORCH_CHECK(sources.size() == count, "sources and destinations must have the same length");
TORCH_CHECK(add.size() == count, "add and destinations must have the same length");
std::vector<BFloat16CopySpan> spans;
spans.reserve(count);
int64_t total_numel = 0;
for (size_t i = 0; i < count; ++i) {
check_tensor(destinations[i], "destination");
TORCH_CHECK(sources[i].device().is_cpu(), "source must be on CPU");
TORCH_CHECK(sources[i].scalar_type() == torch::kBFloat16, "source must be bfloat16");
TORCH_CHECK(sources[i].is_contiguous(), "source must be contiguous");
TORCH_CHECK(destinations[i].numel() == sources[i].numel(), "source shape must match destination shape");
const int64_t numel = destinations[i].numel();
spans.push_back(BFloat16CopySpan{
destinations[i].data_ptr<float>(),
sources[i].const_data_ptr<at::BFloat16>(),
add[i],
total_numel,
total_numel + numel,
});
total_numel += numel;
}
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 BFloat16CopySpan& 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;
copy_or_add_bfloat16_span(*span_it, span_begin, span_end);
begin = std::min(end, span_it->end);
++span_it;
}
});
}
void add_bfloat16_(torch::Tensor destination, const torch::Tensor& source) {
copy_or_add_bfloat16_multi_({destination}, {source}, {true});
}
void copy_bfloat16_(torch::Tensor destination, const torch::Tensor& source) {
copy_or_add_bfloat16_multi_({destination}, {source}, {false});
}
void adamw_span(
const TensorSpan& span,
int64_t begin,
int64_t end,
float beta1,
float beta2,
float weight_decay_factor,
float eps,
float gradient_scale) {
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;
float* exp_avg = span.exp_avg + begin;
float* exp_avg_sq = span.exp_avg_sq + begin;
const int64_t size = end - begin;
const Vec beta1_vec(beta1);
const Vec beta2_vec(beta2);
const Vec one_minus_beta1(1.0f - beta1);
const Vec one_minus_beta2(1.0f - beta2);
const Vec weight_decay_vec(weight_decay_factor);
const Vec step_size_vec(span.step_size);
const Vec bias_correction2_sqrt_vec(span.bias_correction2_sqrt);
const Vec eps_vec(eps);
const Vec gradient_scale_vec(gradient_scale);
auto update = [&](int64_t offset, const Vec& grad_vec) {
Vec param_vec = Vec::loadu(param + offset) * weight_decay_vec;
Vec exp_avg_vec = Vec::loadu(exp_avg + offset);
Vec exp_avg_sq_vec = Vec::loadu(exp_avg_sq + offset);
const Vec scaled_grad = grad_vec * gradient_scale_vec;
exp_avg_vec = exp_avg_vec * beta1_vec + scaled_grad * one_minus_beta1;
exp_avg_sq_vec = exp_avg_sq_vec * beta2_vec + scaled_grad * scaled_grad * one_minus_beta2;
const Vec denominator = exp_avg_sq_vec.sqrt() / bias_correction2_sqrt_vec + eps_vec;
param_vec = param_vec - step_size_vec * exp_avg_vec / denominator;
param_vec.store(param + offset);
exp_avg_vec.store(exp_avg + offset);
exp_avg_sq_vec.store(exp_avg_sq + 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) {
float param_value = param[i] * weight_decay_factor;
const float grad_value =
(span.grad_bfloat16 ? static_cast<float>(bfloat16_grad[i]) : float_grad[i]) * gradient_scale;
const float exp_avg_value = beta1 * exp_avg[i] + (1.0f - beta1) * grad_value;
const float exp_avg_sq_value =
beta2 * exp_avg_sq[i] + (1.0f - beta2) * grad_value * grad_value;
const float denominator = std::sqrt(exp_avg_sq_value) / span.bias_correction2_sqrt + eps;
param_value -= span.step_size * exp_avg_value / denominator;
param[i] = param_value;
exp_avg[i] = exp_avg_value;
exp_avg_sq[i] = exp_avg_sq_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 adamw_step(
const std::vector<torch::Tensor>& params,
const std::vector<torch::Tensor>& grads,
const std::vector<torch::Tensor>& exp_avgs,
const std::vector<torch::Tensor>& exp_avg_sqs,
const std::vector<torch::Tensor>& state_steps,
const std::vector<torch::Tensor>& compute_params,
double lr,
double beta1,
double beta2,
double weight_decay,
double eps,
double gradient_scale) {
const auto count = params.size();
TORCH_CHECK(grads.size() == count, "grads and params must have the same length");
TORCH_CHECK(exp_avgs.size() == count, "exp_avgs and params must have the same length");
TORCH_CHECK(exp_avg_sqs.size() == count, "exp_avg_sqs and params must have the same length");
TORCH_CHECK(state_steps.size() == count, "state_steps 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<TensorSpan> 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]);
check_tensor(exp_avgs[i], "exp_avg");
check_tensor(exp_avg_sqs[i], "exp_avg_sq");
check_tensor(state_steps[i], "state_step");
TORCH_CHECK(params[i].numel() == grads[i].numel(), "grad shape must match param shape");
TORCH_CHECK(params[i].numel() == exp_avgs[i].numel(), "exp_avg shape must match param shape");
TORCH_CHECK(params[i].numel() == exp_avg_sqs[i].numel(), "exp_avg_sq shape must match param shape");
TORCH_CHECK(state_steps[i].numel() == 1, "state_step must contain one value");
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");
}
float* step = state_steps[i].data_ptr<float>();
*step += 1.0f;
const double bias_correction1 = 1.0 - std::pow(beta1, *step);
const double bias_correction2 = 1.0 - std::pow(beta2, *step);
const int64_t numel = params[i].numel();
spans.push_back(TensorSpan{
params[i].data_ptr<float>(),
grads[i].const_data_ptr(),
compute_params.empty() ? nullptr : compute_params[i].data_ptr(),
exp_avgs[i].data_ptr<float>(),
exp_avg_sqs[i].data_ptr<float>(),
grads[i].scalar_type() == torch::kBFloat16,
!compute_params.empty() && compute_params[i].scalar_type() == torch::kBFloat16,
total_numel,
total_numel + numel,
static_cast<float>(lr / bias_correction1),
static_cast<float>(std::sqrt(bias_correction2)),
});
total_numel += numel;
}
const float beta1_value = static_cast<float>(beta1);
const float beta2_value = static_cast<float>(beta2);
const float weight_decay_factor = static_cast<float>(1.0 - lr * weight_decay);
const float eps_value = static_cast<float>(eps);
const float gradient_scale_value = static_cast<float>(gradient_scale);
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 TensorSpan& 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;
adamw_span(
*span_it,
span_begin,
span_end,
beta1_value,
beta2_value,
weight_decay_factor,
eps_value,
gradient_scale_value);
begin = std::min(end, span_it->end);
++span_it;
}
});
}
} // namespace
PYBIND11_MODULE(TORCH_EXTENSION_NAME, module) {
module.def(
"add_bfloat16_",
&add_bfloat16_,
"Add a BF16 tensor into an FP32 tensor",
pybind11::call_guard<pybind11::gil_scoped_release>());
module.def(
"copy_bfloat16_",
&copy_bfloat16_,
"Copy a BF16 tensor into an FP32 tensor",
pybind11::call_guard<pybind11::gil_scoped_release>());
module.def(
"copy_or_add_bfloat16_multi_",
&copy_or_add_bfloat16_multi_,
"Copy or add BF16 tensors into FP32 tensors",
pybind11::call_guard<pybind11::gil_scoped_release>());
module.def(
"adamw_step",
&adamw_step,
"Read-only-gradient multi-tensor CPU AdamW",
pybind11::call_guard<pybind11::gil_scoped_release>());
}
File diff suppressed because it is too large Load Diff
+115
View File
@@ -0,0 +1,115 @@
import copy
import torch
from torch.distributed.tensor import DTensor
from torch.optim import Optimizer
from prime_rl.trainer.optim.base import OffloadOptimizer
class CPUOffloadOptimizer(OffloadOptimizer):
"""Wraps an optimizer to keep states on CPU, moving to GPU only for step().
Unlike FSDP's CPUOffload which offloads weights too, this keeps weights on GPU.
With activation checkpointing, activations and optimizer states are never on GPU
at the same time: peak memory becomes max(activations, opt_states) instead of sum.
"""
def __init__(self, optimizer: Optimizer, pin_memory: bool = True):
self.optimizer = optimizer
self.pin_memory = pin_memory
self._initialized = False
def _move_states(self, device: str):
"""Move optimizer states to CPU or back to GPU (matching each parameter's device)."""
for param in self.optimizer.state:
state = self.optimizer.state[param]
for key, value in state.items():
if isinstance(value, DTensor):
local_tensor = value._local_tensor
if device == "cpu":
non_blocking = not self.pin_memory
new_local = local_tensor.to("cpu", non_blocking=non_blocking)
if self.pin_memory and not new_local.is_pinned():
new_local = new_local.pin_memory()
else:
new_local = local_tensor.to(device, non_blocking=True)
new_dtensor = copy.copy(value)
new_dtensor._local_tensor = new_local
state[key] = new_dtensor
elif isinstance(value, torch.Tensor):
if device == "cpu":
non_blocking = not self.pin_memory
cpu_tensor = value.to("cpu", non_blocking=non_blocking)
if self.pin_memory and not cpu_tensor.is_pinned():
cpu_tensor = cpu_tensor.pin_memory()
state[key] = cpu_tensor
else:
state[key] = value.to(device, non_blocking=True)
def step(self, closure=None):
# First step initializes states on GPU - offload after
if not self._initialized:
result = self.optimizer.step(closure)
self._move_states("cpu")
self._initialized = True
return result
# Move states to GPU
self._move_states("cuda")
# Run optimizer step
result = self.optimizer.step(closure)
# Move states back to CPU
self._move_states("cpu")
return result
def zero_grad(self, set_to_none: bool = True):
self.optimizer.zero_grad(set_to_none=set_to_none)
def state_dict(self):
# Move to GPU temporarily for consistent state dict
if self._initialized:
self._move_states("cuda")
torch.cuda.synchronize()
state_dict = self.optimizer.state_dict()
if self._initialized:
self._move_states("cpu")
return state_dict
def load_state_dict(self, state_dict):
self.optimizer.load_state_dict(state_dict)
self._move_states("cpu")
self._initialized = True
@property
def param_groups(self):
return self.optimizer.param_groups
@param_groups.setter
def param_groups(self, value):
self.optimizer.param_groups = value
@property
def state(self):
return self.optimizer.state
@property
def base_optimizer(self) -> Optimizer:
return self.optimizer
def checkpoint_optimizer(self) -> Optimizer:
return self.optimizer
def prepare_checkpoint_save(self) -> None:
if self._initialized:
self._move_states("cuda")
torch.cuda.synchronize()
def finish_checkpoint_save(self) -> None:
self._move_states("cpu")
def finish_checkpoint_load(self) -> None:
self._initialized = True
+45 -20
View File
@@ -2,6 +2,7 @@ import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before im
from contextlib import nullcontext
import time
import asyncio
from datetime import timedelta
# Import environment before any other imports
@@ -37,6 +38,7 @@ from prime_rl.trainer.rl.loss import (
from prime_rl.trainer.rl.token_export import setup_token_exporter
from prime_rl.trainer.model import (
forward,
get_full_offload_dtype_policy,
setup_tokenizer,
setup_model,
is_tt_moe_model,
@@ -48,8 +50,14 @@ from prime_rl.trainer.utils import (
GarbageCollection,
MemoryProfiler,
Tensors,
begin_backward,
clip_grad_norm_,
filter_rl_trainer_tensor_stats_for_wandb,
finish_backward,
get_ckpt_disk_metrics,
prepare_gradient_offload,
scale_gradients_,
setup_full_cpu_optimizer_offload,
setup_torch_distributed,
)
from prime_rl.trainer.world import get_world
@@ -57,12 +65,11 @@ from prime_rl.trainer.lora import get_lora_state
from prime_rl.trainer.models.layers.lora import set_lora_num_tokens
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.metrics_server import HealthServer, MetricsServer
from prime_rl.utils.monitor import setup_monitor
from prime_rl import monitors
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.utils import clean_exit, resolve_latest_ckpt_step
from ring_flash_attn import substitute_hf_flash_attn
from torchtitan.distributed.utils import clip_grad_norm_
@clean_exit
@@ -75,10 +82,12 @@ def train(config: TrainerConfig):
)
logger.info(f"Starting RL trainer in {world} in {config.output_dir}")
# Setup the monitor
logger.info(f"Initializing monitor ({config.wandb})")
monitor = setup_monitor(
config.wandb, file_config=config.file_monitor, output_dir=config.output_dir, run_config=config
# Setup the monitors
logger.info(f"Initializing monitors ({config.monitors})")
asyncio.run(
monitors.setup(
wandb=config.monitors.wandb, file=config.monitors.file, output_dir=config.output_dir, run_config=config
)
)
# Setup heartbeat (only on rank 0)
@@ -104,6 +113,8 @@ def train(config: TrainerConfig):
setup_torch_distributed(
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
)
if config.model.full_offload is not None:
setup_full_cpu_optimizer_offload(config.model.full_offload)
# Configurable to support ROCm/AMD GPUs where reduced precision
# matmul corrupts softmax over large vocabularies. Override via config
# (e.g. matmul_precision = "highest") on ROCm.
@@ -148,11 +159,16 @@ def train(config: TrainerConfig):
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
optimizer = setup_optimizer(
optimizer, gradient_manager = setup_optimizer(
config.optim,
list(model.named_parameters()),
parallel_dims,
cpu_offload=config.model.optim_cpu_offload,
full_offload_config=config.model.full_offload,
model=model,
full_offload_dtype_policy=(
get_full_offload_dtype_policy(model, config.model) if config.model.full_offload is not None else None
),
)
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
@@ -311,6 +327,11 @@ def train(config: TrainerConfig):
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
dist.all_reduce(global_scales, op=dist.ReduceOp.SUM, group=dp_cp_group)
rl_scale, ce_scale, ref_kl_scale = (max(scale, 1) for scale in global_scales.tolist())
prepare_gradient_offload(
gradient_manager,
parallel_dims.fsdp_gradient_divide_factor,
overlap_optimizer=True,
)
logger.debug(f"Starting forward and backward pass ({batch_size=})")
tensors = Tensors() # Used to accumulate tensor statistics across micro-batches and ranks for logging
@@ -460,7 +481,9 @@ def train(config: TrainerConfig):
# Backward pass
with maybe_record_function("backward"):
begin_backward(gradient_manager, final_backward=micro_step == len(micro_batches) - 1)
loss.backward()
finish_backward(gradient_manager)
# Add relevant tensors to tensor dict for logging purposes
entropy = out["entropy"][loss_mask].detach().to("cpu")
@@ -537,18 +560,13 @@ def train(config: TrainerConfig):
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
# across dp_cp so the final gradient is the true per-token mean over the global batch.
for param in model.parameters():
if param.grad is not None:
param.grad.mul_(parallel_dims.fsdp_gradient_divide_factor)
if gradient_manager is None:
scale_gradients_(None, model, parallel_dims.fsdp_gradient_divide_factor)
# Optionally, clip the gradients
grad_norm: torch.Tensor | None = None
if config.optim.max_norm is not None:
grad_norm = clip_grad_norm_(
model.parameters(), max_norm=config.optim.max_norm, ep_enabled=parallel_dims.ep_enabled
)
if grad_norm.device.type == "cpu":
grad_norm = grad_norm.to(torch.device("cuda"))
grad_norm = clip_grad_norm_(gradient_manager, model, config.optim.max_norm, parallel_dims.ep_enabled)
# Update the model parameters
optimizer.step()
@@ -573,6 +591,10 @@ def train(config: TrainerConfig):
)
if not broadcast_unused:
broadcast_weights_start_time = time.perf_counter()
# The per-layer gather + fp8 conversion peaks ~50 GiB above the
# resident weights; release cached blocks (incl. offload-stream
# pools) so the broadcast gets the full headroom.
torch.cuda.empty_cache()
weight_broadcast.broadcast_weights(model, step=progress.step)
broadcast_weights_time = time.perf_counter() - broadcast_weights_start_time
# Clean up old broadcast directories (unless at ckpt interval if using filesystem weight broadcast)
@@ -649,7 +671,7 @@ def train(config: TrainerConfig):
"perf/peak_memory": peak_memory,
"step": progress.step,
}
monitor.log(perf_metrics, step=progress.step)
asyncio.run(monitors.log(perf_metrics, step=progress.step))
# Log optimizer metrics
optim_metrics = {
@@ -658,7 +680,7 @@ def train(config: TrainerConfig):
}
if grad_norm is not None:
optim_metrics["optim/grad_norm"] = grad_norm.item()
monitor.log(optim_metrics, step=progress.step)
asyncio.run(monitors.log(optim_metrics, step=progress.step))
# Compute derived metrics
entropy_mean = tensor_stats.get("entropy/all/mean", 0.0)
@@ -667,7 +689,7 @@ def train(config: TrainerConfig):
tensor_stats["kl_ent_ratio/mean"] = mismatch_kl_mean / entropy_mean
tensor_stats["step"] = progress.step
monitor.log(filter_rl_trainer_tensor_stats_for_wandb(tensor_stats), step=progress.step)
asyncio.run(monitors.log(filter_rl_trainer_tensor_stats_for_wandb(tensor_stats), step=progress.step))
# Log time metrics
time_metrics = {
@@ -679,12 +701,12 @@ def train(config: TrainerConfig):
"time/forward_backward": forward_backward_time,
"step": progress.step,
}
monitor.log(time_metrics, step=progress.step)
asyncio.run(monitors.log(time_metrics, step=progress.step))
# Log disk metrics
disk_metrics = get_ckpt_disk_metrics(config.output_dir)
disk_metrics["step"] = progress.step
monitor.log(disk_metrics, step=progress.step)
asyncio.run(monitors.log(disk_metrics, step=progress.step))
# Update Prometheus metrics if configured
if metrics_server is not None:
@@ -730,6 +752,9 @@ def train(config: TrainerConfig):
weight_ckpt_manager.save(progress.step, model, tokenizer)
weight_ckpt_manager.maybe_clean()
if gradient_manager is not None:
gradient_manager.close()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("RL trainer finished!")

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