Compare commits

...
Author SHA1 Message Date
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
114 changed files with 4211 additions and 2433 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"
+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"
@@ -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
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.
+14 -20
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,7 +171,7 @@ 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)).
@@ -307,41 +307,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`.
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
```
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `monitors.wandb.offline = true`.
prime-rl deliberately logs a **large number of metrics** for maximum observability: every rollout metric is emitted per subset (`all`/`effective`), per statistic (`mean`/`max`/`min`/`p10`/`p90`), and per environment alongside a cross-env aggregate, so a multi-env run can emit thousands of series. To keep that navigable, W&B mode **auto-creates an `overview` saved view** on the first run into a project — curating the handful of metrics that matter into `train`, `eval`, `stability`, and `performance` sections (with per-env breakdowns). The view is created once per project and adapts to the run's environments; if a later run uses a different set of environments, a new versioned view (`overview-v2`, …) is created instead of overwriting the first.
### 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"
+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"
+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"
@@ -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)
@@ -7,15 +7,14 @@ from pydantic import Field, model_validator
from renderers import AutoRendererConfig, DefaultRendererConfig, RendererConfig
from renderers.base import MODEL_RENDERER_MAP
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,
@@ -195,10 +194,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 +222,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"
@@ -284,6 +281,23 @@ 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:
@@ -192,78 +192,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."
)
+2 -2
View File
@@ -208,8 +208,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'" },
+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
+120
View File
@@ -0,0 +1,120 @@
"""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, 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,
) -> 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,
),
)
)
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}")
+325
View File
@@ -0,0 +1,325 @@
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"
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.headers = {
"Authorization": f"Bearer {api_key}",
"x-api-key": api_key,
"Content-Type": "application/json",
}
self.client = httpx.AsyncClient(
base_url=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"{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"]
+138
View File
@@ -0,0 +1,138 @@
from __future__ import annotations
import asyncio
import json
import os
import sys
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any
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,
) -> 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 == "orchestrator"
settings = wandb.Settings(
mode="shared",
x_label=label,
x_primary=primary,
x_update_finish_state=primary,
)
self.logger.info(f"Using shared W&B mode ({label=}, {primary=})")
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 [],
)
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)
+223
View File
@@ -0,0 +1,223 @@
"""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
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"],
]
# 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] = ()) -> list[ws.Section]:
# 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] = (),
) -> 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)
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
+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):
+33 -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,
+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!")
+5 -5
View File
@@ -4,13 +4,13 @@ from torch.optim import Optimizer
from torch.optim.lr_scheduler import ConstantLR, CosineAnnealingLR, LinearLR, LRScheduler, SequentialLR
from prime_rl.configs.trainer import SchedulerConfig
from prime_rl.trainer.optim import CPUOffloadOptimizer
from prime_rl.trainer.optim import OffloadOptimizer, OptimizerLike
def _get_base_optimizer(optimizer: Optimizer | CPUOffloadOptimizer) -> Optimizer:
def _get_base_optimizer(optimizer: OptimizerLike) -> Optimizer:
"""Extract the base optimizer from a potentially wrapped optimizer."""
if isinstance(optimizer, CPUOffloadOptimizer):
return optimizer.optimizer
if isinstance(optimizer, OffloadOptimizer):
return optimizer.base_optimizer
return optimizer
@@ -85,7 +85,7 @@ def setup_cosine_scheduler(
def setup_scheduler(
optimizer: Optimizer | CPUOffloadOptimizer,
optimizer: OptimizerLike,
scheduler_config: SchedulerConfig,
max_steps: int | None,
lr: float,
+77 -42
View File
@@ -1,6 +1,7 @@
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before import
import time
import asyncio
from contextlib import nullcontext
from datetime import timedelta
@@ -27,6 +28,7 @@ from prime_rl.trainer.optim import setup_optimizer
from prime_rl.trainer.scheduler import setup_scheduler
from prime_rl.trainer.model import (
forward,
get_full_offload_dtype_policy,
get_load_balance_stats,
is_tt_moe_model,
setup_processor,
@@ -40,20 +42,24 @@ from prime_rl.trainer.sft.data import load_sft_dataset, setup_dataloader, setup_
from prime_rl.trainer.utils import (
GarbageCollection,
MemoryProfiler,
begin_backward,
clip_grad_norm_,
finish_backward,
get_ckpt_disk_metrics,
prepare_gradient_offload,
print_sample,
scale_gradients_,
setup_full_cpu_optimizer_offload,
setup_torch_distributed,
)
from prime_rl.trainer.world import get_world
from prime_rl.utils.heartbeat import Heartbeat
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
import torch.distributed as dist
from torchtitan.distributed.utils import clip_grad_norm_
@clean_exit
def train(config: SFTConfig):
@@ -65,9 +71,13 @@ def train(config: SFTConfig):
)
logger.info(f"Starting SFT trainer in {world}")
# Setup the monitor
logger.info(f"Initializing monitor ({config.wandb})")
monitor = setup_monitor(config.wandb, file_config=config.file_monitor, output_dir=config.run_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.run_dir, run_config=config
)
)
# Setup heartbeat (only on rank 0)
heart = None
@@ -79,6 +89,8 @@ def train(config: SFTConfig):
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.
@@ -170,8 +182,16 @@ def train(config: SFTConfig):
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
optimizer = setup_optimizer(
config.optim, list(model.named_parameters()), parallel_dims, cpu_offload=config.model.optim_cpu_offload
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
),
)
# Set up the learning rate scheduler
@@ -358,7 +378,7 @@ def train(config: SFTConfig):
logger.warning(f"Validation at step {step} had no valid tokens")
else:
logger.success(f"Validation | Step {step} | Loss {mean_loss:.4f}")
monitor.log({"val/loss": mean_loss, "step": step}, step=step)
asyncio.run(monitors.log({"val/loss": mean_loss, "step": step}, step=step))
gc_handler = GarbageCollection(config.gc.interval) if config.gc else None
@@ -385,7 +405,6 @@ def train(config: SFTConfig):
forward_backward_start_time = time.perf_counter()
step_loss_sum = torch.tensor(0.0, device="cuda")
step_local_token_count = torch.tensor(0, dtype=torch.int64, device="cuda")
nan_loss_count = torch.tensor(0, device="cuda")
is_moe_model = is_tt_moe_model(model)
moe_stats = (
@@ -396,18 +415,41 @@ def train(config: SFTConfig):
if is_moe_model
else {}
)
for micro_step in range(grad_accum_steps):
micro_batch = next(dataiter)
run_validation_this_step = config.val is not None and (
(is_first_step and config.val.eval_on_start)
or (not is_first_step and progress.step % config.val.interval == 0)
)
if gradient_manager is None:
micro_batches = (next(dataiter) for _ in range(grad_accum_steps))
step_local_token_count = torch.tensor(0, dtype=torch.int64, device="cuda")
else:
micro_batches = [next(dataiter) for _ in range(grad_accum_steps)]
local_token_count = sum(int(micro_batch["loss_mask"].sum()) for micro_batch in micro_batches)
global_step_token_count = torch.tensor(local_token_count, dtype=torch.int64, device="cuda")
dist.all_reduce(global_step_token_count, op=dist.ReduceOp.SUM, group=dp_cp_group)
global_token_count_val = global_step_token_count.item() // cp_size
grad_scale = (
parallel_dims.fsdp_gradient_divide_factor * grad_accum_steps / global_token_count_val
if global_token_count_val > 0
else 1.0
)
prepare_gradient_offload(
gradient_manager,
grad_scale,
overlap_optimizer=not run_validation_this_step,
)
for micro_step, micro_batch in enumerate(micro_batches):
if config.log.log_data:
print_sample(
micro_batch["input_ids"].flatten().tolist(), micro_batch["loss_mask"].flatten().tolist(), tokenizer
)
with maybe_record_function("forward"):
local_loss_sum, local_token_count = compute_loss(micro_batch)
local_loss_sum, batch_token_count = compute_loss(micro_batch)
step_local_token_count += local_token_count
if gradient_manager is None:
step_local_token_count += batch_token_count
if torch.isnan(local_loss_sum.detach()):
nan_loss_count += 1
@@ -418,7 +460,9 @@ def train(config: SFTConfig):
scaled_loss = local_loss_sum / grad_accum_steps
with maybe_record_function("backward"):
begin_backward(gradient_manager, final_backward=micro_step == grad_accum_steps - 1)
scaled_loss.backward()
finish_backward(gradient_manager)
if is_moe_model:
for name, values in get_load_balance_stats(model).items():
@@ -433,25 +477,17 @@ def train(config: SFTConfig):
forward_backward_time = time.perf_counter() - forward_backward_start_time
# All-reduce token counts and rescale gradients to get a global token-weighted mean.
# FSDP already divided grads by fsdp_gradient_divide_factor, so we undo that and
# divide by the true global token count instead.
global_step_token_count = step_local_token_count.clone()
dist.all_reduce(global_step_token_count, op=dist.ReduceOp.SUM, group=dp_cp_group)
global_token_count_val = global_step_token_count.item()
if global_token_count_val > 0:
grad_scale = parallel_dims.fsdp_gradient_divide_factor * grad_accum_steps / global_token_count_val
for param in model.parameters():
if param.grad is not None:
param.grad.mul_(grad_scale)
if gradient_manager is None:
global_step_token_count = step_local_token_count.clone()
dist.all_reduce(global_step_token_count, op=dist.ReduceOp.SUM, group=dp_cp_group)
global_token_count_val = global_step_token_count.item()
if global_token_count_val > 0:
grad_scale = parallel_dims.fsdp_gradient_divide_factor * grad_accum_steps / global_token_count_val
scale_gradients_(None, model, grad_scale)
# Run validation after forward-backward (so torch.compile sees training graph first) but before
# optimizer step (so eval_on_start evaluates untrained weights)
if config.val is not None and (
(is_first_step and config.val.eval_on_start)
or (not is_first_step and progress.step % config.val.interval == 0)
):
if run_validation_this_step:
run_validation(progress.step)
# Compute the global mean loss for logging.
@@ -466,11 +502,7 @@ def train(config: SFTConfig):
grad_norm: torch.Tensor | None = None
if config.optim.max_norm is not None:
logger.debug(f"Clipping gradients with max norm {config.optim.max_norm}")
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)
logger.debug("Optimizer step")
optimizer.step()
optimizer.zero_grad()
@@ -558,7 +590,7 @@ def train(config: SFTConfig):
for subset_or_split, num_tokens in dataset.num_tokens.items()
},
)
monitor.log(progress_metrics, step=progress.step)
asyncio.run(monitors.log(progress_metrics, step=progress.step))
# Log performance metrics
perf_metrics = {
@@ -568,7 +600,7 @@ def train(config: SFTConfig):
"perf/mfu": mfu,
"step": progress.step,
}
monitor.log(perf_metrics, step=progress.step)
asyncio.run(monitors.log(perf_metrics, step=progress.step))
# Log optimizer metrics
optim_metrics = {
@@ -577,7 +609,7 @@ def train(config: SFTConfig):
}
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))
loss_log_metrics = {
"loss/mean": batch_loss,
@@ -585,7 +617,7 @@ def train(config: SFTConfig):
"step": progress.step,
}
# Log tensor stats
monitor.log(loss_log_metrics, step=progress.step)
asyncio.run(monitors.log(loss_log_metrics, step=progress.step))
# Log time metrics
time_metrics = {
@@ -594,16 +626,16 @@ def train(config: SFTConfig):
"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.run_dir)
disk_metrics["step"] = progress.step
monitor.log(disk_metrics, step=progress.step)
asyncio.run(monitors.log(disk_metrics, step=progress.step))
moe_log_metrics = {f"{name}/mean": value.item() for name, value in moe_stats.items() if value.item() > 0}
if moe_log_metrics:
monitor.log({**moe_log_metrics, "step": progress.step}, step=progress.step)
asyncio.run(monitors.log({**moe_log_metrics, "step": progress.step}, step=progress.step))
is_first_step = False
@@ -636,6 +668,9 @@ def train(config: SFTConfig):
weight_ckpt_manager.save(progress.step, model, tokenizer, processor)
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("SFT trainer finished!")
+113 -2
View File
@@ -1,16 +1,19 @@
import gc
import os
import pickle
import shutil
import time
from collections import defaultdict
from datetime import timedelta
from pathlib import Path
from typing import TYPE_CHECKING
import torch
import torch.distributed as dist
from rich import print as rich_print
from rich.text import Text
from torch import Tensor
from torch import Tensor, nn
from torchtitan.distributed.utils import clip_grad_norm_ as torch_clip_grad_norm_
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.trainer.world import get_world
@@ -18,6 +21,10 @@ from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_ckpt_dir
from prime_rl.utils.utils import get_step_path
if TYPE_CHECKING:
from prime_rl.configs.trainer import OptimizerInBackwardOffloadConfig
from prime_rl.trainer.optim import GradientOffloadManager
DEFAULT_TIMEOUT = timedelta(seconds=600)
@@ -48,12 +55,55 @@ class GarbageCollection:
get_logger().info(f"[GC] collection took {time.monotonic() - begin:.2f}s")
def prepare_gradient_offload(
manager: "GradientOffloadManager | None",
gradient_scale: float,
*,
overlap_optimizer: bool,
) -> None:
if manager is not None:
manager.begin_step(gradient_scale, overlap_optimizer=overlap_optimizer)
def begin_backward(manager: "GradientOffloadManager | None", *, final_backward: bool) -> None:
if manager is not None:
manager.begin_backward(final_backward=final_backward)
def finish_backward(manager: "GradientOffloadManager | None", *, wait_for_copies: bool = False) -> None:
if manager is not None:
manager.finish_backward(wait_for_copies=wait_for_copies)
@torch.no_grad()
def scale_gradients_(manager: "GradientOffloadManager | None", model: nn.Module, factor: float) -> None:
if manager is not None:
manager.scale_(factor)
return
for param in model.parameters():
if param.grad is not None:
param.grad.mul_(factor)
def clip_grad_norm_(
manager: "GradientOffloadManager | None",
model: nn.Module,
max_norm: float,
ep_enabled: bool,
) -> Tensor:
if manager is not None:
grad_norm = manager.clip_grad_norm_(max_norm)
else:
grad_norm = torch_clip_grad_norm_(model.parameters(), max_norm=max_norm, ep_enabled=ep_enabled)
return grad_norm.cuda() if grad_norm.device.type == "cpu" else grad_norm
def get_ckpt_disk_metrics(output_dir: Path) -> dict[str, float]:
"""
Disk usage metrics for the checkpoint directory (<output_dir>/checkpoints).
Intended to be called by trainer(s) on rank 0 and included in an existing
monitor.log(...) call (once per step).
monitors.log(...) call (once per step).
"""
ckpt_dir = get_ckpt_dir(output_dir)
ckpt_dir.mkdir(parents=True, exist_ok=True)
@@ -67,6 +117,60 @@ def get_ckpt_disk_metrics(output_dir: Path) -> dict[str, float]:
}
def bind_process_to_gpu_numa_node() -> None:
"""Pin this rank's CPUs to its GPU's NUMA node.
Offloaded optimizer state is pageable host memory placed by first-touch, and the
CPU optimizer pipeline is DRAM-bandwidth-bound; binding before the state is
allocated keeps slabs, OMP threads, and pinned rings local to the socket the
GPU hangs off. Must run before CPU optimizer state allocation and before the
OMP thread pool spins up.
"""
import pynvml
logger = get_logger()
device_id = torch.cuda.current_device()
pynvml.nvmlInit()
try:
bus_id = pynvml.nvmlDeviceGetPciInfo(pynvml.nvmlDeviceGetHandleByIndex(device_id)).busId
finally:
pynvml.nvmlShutdown()
if isinstance(bus_id, bytes):
bus_id = bus_id.decode()
domain, rest = bus_id.split(":", 1)
sysfs_bus_id = f"{int(domain, 16):04x}:{rest}".lower()
numa_node = int(Path(f"/sys/bus/pci/devices/{sysfs_bus_id}/numa_node").read_text())
if numa_node < 0:
logger.warning(f"GPU {device_id} ({sysfs_bus_id}) reports no NUMA node; skipping NUMA binding")
return
cpus: set[int] = set()
for part in Path(f"/sys/devices/system/node/node{numa_node}/cpulist").read_text().strip().split(","):
if "-" in part:
start, end = part.split("-")
cpus.update(range(int(start), int(end) + 1))
else:
cpus.add(int(part))
os.sched_setaffinity(0, cpus)
logger.info(f"Bound rank with GPU {device_id} to NUMA node {numa_node} ({len(cpus)} CPUs)")
def configure_cpu_optimizer_threads() -> None:
available = os.sched_getaffinity(0)
fair_share = (os.cpu_count() or len(available)) // get_world().local_world_size
threads = max(1, min(len(available), fair_share))
torch.set_num_threads(threads)
get_logger().info(
f"CPU optimizer uses {threads} intra-op threads "
f"({len(available)} CPUs in this rank's affinity mask, {get_world().local_world_size} local ranks)"
)
def setup_full_cpu_optimizer_offload(config: "OptimizerInBackwardOffloadConfig") -> None:
if config.numa_bind:
bind_process_to_gpu_numa_node()
configure_cpu_optimizer_threads()
def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: bool = False):
device_id = get_world().local_rank
torch.cuda.set_device(device_id)
@@ -77,6 +181,13 @@ def setup_torch_distributed(timeout: timedelta = DEFAULT_TIMEOUT, enable_gloo: b
get_logger().info("Using Gloo backend for CPU and NCCL backend for GPU")
backend = "cpu:gloo,cuda:nccl"
# init_process_group applies `timeout` only to the default PG; device-mesh
# sub-groups (dp/cp/ep) are created via new_group without a timeout and fall
# back to torch's 10-minute module default — dist_timeout_seconds silently
# never reached the PGs doing the real work (watchdogs at 600s). Patch the
# module default so every subsequently created PG inherits it.
dist.distributed_c10d.default_pg_timeout = timeout
dist.init_process_group(backend=backend, timeout=timeout, device_id=device_id)
-97
View File
@@ -1,97 +0,0 @@
"""Background async runner for fire-and-forget HTTP work.
Owns an event loop running on a background thread plus an httpx.AsyncClient,
so callers can submit coroutines without blocking the main thread.
Fork-safe via ``os.register_at_fork``.
Used by UsageReporter; PrimeMonitor still has its own copy of the same
pattern and can be migrated to this helper in a follow-up.
"""
import asyncio
import os
from threading import Thread
from typing import Awaitable, Callable
import httpx
from prime_rl.utils.logger import get_logger
class BackgroundAsync:
"""Owns a background event loop + httpx client for fire-and-forget work."""
def __init__(self, *, client_timeout: float = 30.0):
self.logger = get_logger()
self._client_timeout = client_timeout
self._closed = False
self._init_runtime()
os.register_at_fork(after_in_child=self._reinit_after_fork)
@property
def client(self) -> httpx.AsyncClient:
return self._client
def submit(self, coro_factory: Callable[[], Awaitable[None]]) -> None:
"""Schedule a coroutine on the background loop. Fire-and-forget.
Takes a factory rather than a coroutine so the coroutine is created
on the background thread (avoids "coroutine was never awaited" warnings
if the loop is in the middle of restarting).
"""
if self._closed:
return
future = asyncio.run_coroutine_threadsafe(coro_factory(), self._loop)
self._pending_futures.append(future)
# Drop completed futures to avoid unbounded growth
self._pending_futures = [f for f in self._pending_futures if not f.done()]
def close(self, *, flush_timeout: float = 15.0) -> None:
if self._closed or not hasattr(self, "_loop"):
return
self._closed = True
self._flush(timeout=flush_timeout)
async def _close_client() -> None:
await self._client.aclose()
try:
future = asyncio.run_coroutine_threadsafe(_close_client(), self._loop)
future.result(timeout=5.0)
except Exception as e:
self.logger.debug("Error closing background async client: %s", e)
self._loop.call_soon_threadsafe(self._loop.stop)
self._thread.join(timeout=5.0)
def __del__(self) -> None:
self.close()
# -- internals --
def _init_runtime(self) -> None:
self._loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()
self._thread = Thread(target=self._run_loop, daemon=True)
self._thread.start()
self._client = httpx.AsyncClient(timeout=self._client_timeout)
self._pending_futures: list[asyncio.Future] = []
def _reinit_after_fork(self) -> None:
# Background thread doesn't survive fork — recreate everything.
self._closed = False
self._init_runtime()
def _run_loop(self) -> None:
asyncio.set_event_loop(self._loop)
self._loop.run_forever()
def _flush(self, timeout: float) -> None:
if not self._pending_futures:
return
self.logger.debug("Flushing %d pending background request(s)", len(self._pending_futures))
for future in self._pending_futures:
try:
future.result(timeout=timeout)
except Exception as e:
self.logger.debug("Pending background request completed with error: %s", e)
self._pending_futures.clear()
-96
View File
@@ -1,96 +0,0 @@
from pathlib import Path
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.configs.shared import FileMonitorConfig, PrimeMonitorConfig, WandbWithExtrasConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.monitor.base import Monitor, NoOpMonitor
from prime_rl.utils.monitor.file import FileMonitor
from prime_rl.utils.monitor.multi import MultiMonitor
from prime_rl.utils.monitor.prime import PrimeMonitor
from prime_rl.utils.monitor.wandb import WandbMonitor
__all__ = [
"Monitor",
"WandbMonitor",
"PrimeMonitor",
"FileMonitor",
"MultiMonitor",
"NoOpMonitor",
"setup_monitor",
"get_monitor",
]
_MONITOR: Monitor | None = None
def get_monitor() -> Monitor:
"""Returns the global monitor."""
global _MONITOR
if _MONITOR is None:
raise RuntimeError("Monitor not initialized. Please call `setup_monitor` first.")
return _MONITOR
def setup_monitor(
wandb_config: WandbWithExtrasConfig | None = None,
output_dir: Path | None = None,
tokenizer: PreTrainedTokenizer | None = None,
run_config: BaseConfig | None = None,
*,
prime_config: PrimeMonitorConfig | None = None,
file_config: FileMonitorConfig | None = None,
train_env_names: list[str] = [],
eval_env_names: list[str] = [],
# Backward compatibility: support old 'config' keyword argument
config: WandbWithExtrasConfig | None = None,
) -> Monitor:
"""Sets up monitors to log metrics."""
global _MONITOR
if _MONITOR is not None:
raise RuntimeError("Monitor already initialized. Please call `setup_monitor` only once.")
if config is not None and wandb_config is None:
wandb_config = config
monitors: list[Monitor] = []
if wandb_config is not None:
monitors.append(
WandbMonitor(
config=wandb_config,
output_dir=output_dir,
tokenizer=tokenizer,
run_config=run_config,
train_env_names=train_env_names,
eval_env_names=eval_env_names,
)
)
if prime_config is not None:
monitors.append(
PrimeMonitor(
config=prime_config,
output_dir=output_dir,
tokenizer=tokenizer,
run_config=run_config,
)
)
if file_config is not None:
monitors.append(
FileMonitor(
config=file_config,
output_dir=output_dir,
run_config=run_config,
)
)
if len(monitors) == 0:
_MONITOR = NoOpMonitor()
elif len(monitors) == 1:
_MONITOR = monitors[0]
else:
_MONITOR = MultiMonitor(monitors)
return _MONITOR
-120
View File
@@ -1,120 +0,0 @@
from __future__ import annotations
import math
import random
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
_DROPPED_JSON_VALUE = object()
def drop_non_finite_json_values(value: Any, dropped_paths: list[str], path: str = "") -> Any:
"""Recursively drop non-finite floats (NaN/inf) from a JSON-serializable value.
Appends the dotted path of each dropped value to `dropped_paths`. Used before
serializing metric payloads that must be strict JSON (the public Prime API and
the local `metrics.jsonl` sink), since NaN/Infinity are not valid JSON.
"""
if isinstance(value, float) and not math.isfinite(value):
dropped_paths.append(path)
return _DROPPED_JSON_VALUE
if isinstance(value, dict):
return {
key: sanitized_item
for key, item in value.items()
if (
sanitized_item := drop_non_finite_json_values(
item,
dropped_paths,
f"{path}.{key}" if path else str(key),
)
)
is not _DROPPED_JSON_VALUE
}
if isinstance(value, list):
return [
sanitized_item
for idx, item in enumerate(value)
if (sanitized_item := drop_non_finite_json_values(item, dropped_paths, f"{path}[{idx}]"))
is not _DROPPED_JSON_VALUE
]
return value
def sample_items_for_logging(items: list[Any], sample_ratio: float | None) -> list[Any]:
"""Apply monitor sample_ratio semantics to a batch of items.
- ``None`` keeps the full batch.
- ``<= 0`` logs nothing.
- ``0 < ratio < 1`` logs a random subset with a minimum of 1 item.
- ``>= 1`` keeps the full batch.
"""
if sample_ratio is None:
return items
if sample_ratio <= 0.0:
return []
if sample_ratio >= 1.0 or len(items) <= 1:
return items
max_samples = max(1, int(len(items) * sample_ratio))
if len(items) <= max_samples:
return items
return random.sample(items, max_samples)
class Monitor(ABC):
"""Base class for all monitoring implementations."""
run_id: str | None = None
"""External identifier of the run this monitor reports to (platform / W&B), when it has one."""
@abstractmethod
def log(self, metrics: dict[str, Any], step: int) -> None:
pass
@abstractmethod
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
pass
@abstractmethod
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
pass
@abstractmethod
def save_final_summary(self, filename: str = "final_summary.json") -> None:
pass
@abstractmethod
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
pass
def close(self) -> None:
"""Close any resources held by the monitor. Override in subclasses that need cleanup."""
pass
class NoOpMonitor(Monitor):
"""Monitor that does nothing. Used when no monitors are configured."""
def log(self, metrics: dict[str, Any], step: int) -> None:
pass
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
pass
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
pass
def save_final_summary(self, filename: str = "final_summary.json") -> None:
pass
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
pass
-98
View File
@@ -1,98 +0,0 @@
from __future__ import annotations
import json
import os
import time
from pathlib import Path
from typing import TYPE_CHECKING, Any
from prime_rl.configs.shared import FileMonitorConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor, drop_non_finite_json_values
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
class FileMonitor(Monitor):
"""Appends logged metrics to a local ``metrics.jsonl`` file.
A self-hosted, dependency-free mirror of what ``WandbMonitor.log`` sees: one
JSON object per line, ``{"step": step, "time": <wall>, **metrics}``. The file is
flushed after every write so an in-progress run can be read (e.g. to build a
static dashboard snapshot mid-run). Only rank 0 writes. Samples and
distributions are not persisted here (scalars only).
"""
def __init__(
self,
config: FileMonitorConfig | None,
output_dir: Path | None = None,
run_config: BaseConfig | None = None,
):
self.config = config
self.logger = get_logger()
self._last_metrics: dict[str, Any] = {}
self.output_dir = output_dir
self._file = None
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
self.enabled = self.config is not None
self.is_master = rank == 0
if not self.enabled or not self.is_master:
if not self.is_master:
self.logger.warning(f"Skipping {self.__class__.__name__} initialization from non-master rank ({rank})")
return
if output_dir is None:
self.logger.warning("FileMonitor requires an output_dir; disabling.")
self.enabled = False
return
output_dir.mkdir(parents=True, exist_ok=True)
self._path = output_dir / config.filename
# 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}")
def log(self, metrics: dict[str, Any], step: int) -> None:
self._last_metrics = metrics
if not self.is_master or not self.enabled or self._file is None:
return
dropped_paths: list[str] = []
sanitized = drop_non_finite_json_values(metrics, dropped_paths)
if dropped_paths:
preview = ", ".join(dropped_paths[:5])
suffix = " ..." if len(dropped_paths) > 5 else ""
self.logger.debug(
f"Dropping {len(dropped_paths)} non-finite value(s) from metrics.jsonl: {preview}{suffix}"
)
row = {"step": step, "time": time.time(), **sanitized}
self._file.write(json.dumps(row))
self._file.write("\n")
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
pass
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
pass
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
pass
def save_final_summary(self, filename: str = "final_summary.json") -> None:
if not self.is_master or not self.enabled or self.output_dir is None:
return
summary = self._last_metrics
dropped_paths: list[str] = []
sanitized = drop_non_finite_json_values(summary, dropped_paths)
with open(self.output_dir / filename, "w") as f:
json.dump(sanitized, f)
def close(self) -> None:
if self._file is not None:
self._file.close()
self._file = None
-63
View File
@@ -1,63 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor
from prime_rl.utils.monitor.prime import PrimeMonitor
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
class MultiMonitor(Monitor):
"""Monitor that wraps multiple monitors and delegates calls to all of them."""
def __init__(self, monitors: list[Monitor]):
self.monitors = monitors
self.logger = get_logger()
# Prefer the platform run id over W&B's when both report one.
prime = next((m for m in monitors if isinstance(m, PrimeMonitor)), None)
self.run_id = (prime.run_id if prime else None) or next((m.run_id for m in monitors if m.run_id), None)
def log(self, metrics: dict[str, Any], step: int) -> None:
for monitor in self.monitors:
try:
monitor.log(metrics, step=step)
except Exception as e:
self.logger.warning(f"Failed to log metrics to {monitor.__class__.__name__}: {e}")
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
for monitor in self.monitors:
try:
monitor.log_samples(rollouts=rollouts, step=step)
except Exception as e:
self.logger.warning(f"Failed to log samples to {monitor.__class__.__name__}: {e}")
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
for monitor in self.monitors:
try:
monitor.log_eval_samples(rollouts=rollouts, env_name=env_name, step=step)
except Exception as e:
self.logger.warning(f"Failed to log eval samples to {monitor.__class__.__name__}: {e}")
def save_final_summary(self, filename: str = "final_summary.json") -> None:
for monitor in self.monitors:
try:
monitor.save_final_summary(filename=filename)
except Exception as e:
self.logger.warning(f"Failed to save final summary to {monitor.__class__.__name__}: {e}")
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
for monitor in self.monitors:
try:
monitor.log_distributions(distributions=distributions, step=step)
except Exception as e:
self.logger.warning(f"Failed to log distributions to {monitor.__class__.__name__}: {e}")
def close(self) -> None:
for monitor in self.monitors:
try:
monitor.close()
except Exception as e:
self.logger.warning(f"Failed to close {monitor.__class__.__name__}: {e}")
-636
View File
@@ -1,636 +0,0 @@
from __future__ import annotations
import asyncio
import io
import json
import os
import time
from datetime import datetime, timezone
from pathlib import Path
from threading import Thread
from typing import TYPE_CHECKING, Any
import httpx
import pyarrow as pa
import pyarrow.parquet as pq
from prime_cli.core.config import Config as PrimeConfig
from transformers.tokenization_utils import PreTrainedTokenizer
from verifiers.v1.utils.platform import trace_to_sample
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.shared import PrimeMonitorConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor, drop_non_finite_json_values, sample_items_for_logging
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
_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 to Prime Intellect API."""
def _sanitize_json_payload(self, endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
"""Drop non-finite floats before sending JSON payloads to the public API."""
dropped_paths: list[str] = []
sanitized_payload = drop_non_finite_json_values(payload, dropped_paths)
if not dropped_paths:
return payload
preview = ", ".join(dropped_paths[:5])
suffix = " ..." if len(dropped_paths) > 5 else ""
self.logger.warning(
f"Dropping {len(dropped_paths)} non-finite value(s) from Prime monitor {endpoint} payload: "
f"{preview}{suffix}"
)
return sanitized_payload
def __init__(
self,
config: PrimeMonitorConfig | None,
output_dir: Path | None = None,
tokenizer: PreTrainedTokenizer | None = None,
run_config: OrchestratorConfig | None = None,
):
self.config = config
self.logger = get_logger()
self._last_metrics: dict[str, Any] = {}
self.output_dir = output_dir
self._registered = False
self._finalized = False
self._closed = False
self._owner_pid = os.getpid()
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
self.enabled = self.config is not None
self.is_master = rank == 0
if not self.enabled or not self.is_master:
if not self.is_master:
self.logger.warning(f"Skipping {self.__class__.__name__} initialization from non-master rank ({rank})")
return
assert config is not None
api_key = os.getenv(config.api_key_var)
if api_key is None:
prime_config = PrimeConfig()
api_key = prime_config.api_key
if not api_key:
self.logger.warning(
f"API key not found. Set {config.api_key_var} environment variable or run `prime login`. "
"PrimeMonitor will not be able to upload data."
)
self.enabled = False
return
self.api_key = api_key
self.base_url = config.base_url.rstrip("/")
self._headers = {
"Authorization": f"Bearer {api_key}",
"x-api-key": api_key,
"Content-Type": "application/json",
}
run_id = os.getenv("RUN_ID")
if not run_id:
run_id = self._register_run(config, run_config)
if run_id:
os.environ["RUN_ID"] = run_id
else:
self.enabled = False
return
self.run_id = run_id
# Set up async HTTP client with background event loop.
# Evals can run in a forked subprocess (see run_evals_subprocess in eval/utils.py). When a
# process forks, only the calling thread survives - our background thread running the
# event loop is not copied. The Thread object still exists but the OS thread is gone,
# so asyncio.run_coroutine_threadsafe() silently fails. We use register_at_fork to
# recreate the thread, event loop, and HTTP client in the child process.
self._init_async_client()
os.register_at_fork(after_in_child=self._reinit_after_fork)
# Optionally, initialize sample logging attributes
if config.log_extras:
if config.log_extras.samples:
self.last_log_samples_step = -1
self._pending_sample_steps: set[int] = set()
self.tokenizer = tokenizer
if config.log_extras.distributions:
self.last_log_distributions_step = -1
def _register_run(self, config: PrimeMonitorConfig, run_config: OrchestratorConfig | None) -> str | None:
"""Register an external run with the platform. Returns run_id on success, None on failure."""
prime_config = None
team_id = config.team_id
frontend_url = config.frontend_url
if team_id is None or frontend_url is None:
prime_config = PrimeConfig()
if team_id is None:
team_id = prime_config.team_id
if frontend_url is None:
frontend_url = prime_config.frontend_url
payload: dict[str, Any] = {
"base_model": run_config.model.name if run_config else "unknown",
"max_steps": (run_config.max_steps if run_config else None) or 0,
}
if run_config:
if run_config.batch_size is not None:
payload["batch_size"] = run_config.batch_size
payload["rollouts_per_example"] = run_config.group_size
payload["seq_len"] = run_config.seq_len
payload["environments"] = [{"id": env.env_id} for env in run_config.train.source]
payload["run_config"] = run_config.model_dump(exclude_none=True, mode="json")
if run_config.wandb:
payload["wandb_project"] = run_config.wandb.project
if config.run_name:
payload["name"] = config.run_name
if team_id:
payload["team_id"] = team_id
try:
response = httpx.post(
f"{self.base_url}/external-runs",
headers=self._headers,
json=payload,
timeout=30,
)
except httpx.HTTPError as e:
self.logger.warning(f"Failed to register platform run: {e}. PrimeMonitor will not be able to upload data.")
return None
if response.status_code != 201:
self.logger.warning(
f"Failed to create platform run (HTTP {response.status_code}): {response.text}. "
"PrimeMonitor will not be able to upload data."
)
return None
run_id = response.json()["run"]["id"]
if frontend_url:
dashboard_url = f"{frontend_url.rstrip('/')}/dashboard/training/{run_id}"
self.logger.success(f"Monitor run at: {dashboard_url}")
else:
self.logger.success(f"Registered platform run {run_id}")
self._registered = True
return run_id
def _finalize_run(self, success: bool) -> None:
"""Mark the run as completed or failed on the platform."""
if not self._registered:
return
payload: dict = {"status": "completed" if success else "failed"}
status_label = "completed" if success else "failed"
self.logger.info(f"Finalizing platform run {self.run_id} as {status_label}")
try:
response = httpx.put(
f"{self.base_url}/external-runs/{self.run_id}/status",
headers=self._headers,
json=payload,
timeout=30,
)
except httpx.HTTPError as e:
self.logger.warning(f"Failed to finalize platform run {self.run_id}: {e}")
return
if response.status_code != 200:
self.logger.warning(
f"Failed to finalize platform run {self.run_id} (HTTP {response.status_code}): {response.text}"
)
return
self.logger.info(f"Platform run {self.run_id} marked as {status_label}")
def log(self, metrics: dict[str, Any], step: int) -> None:
self._last_metrics = metrics
if not self.is_master:
return
if not self.enabled:
return
self._make_request(
"metrics",
{
"run_id": self.run_id,
"metrics": metrics,
},
)
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
"""Logs rollouts to Prime Intellect API using presigned URLs for direct R2 upload."""
if not self.is_master:
return
if not self.enabled:
return
if (
not self.config
or not self.config.log_extras
or not self.config.log_extras.samples
or step % self.config.log_extras.interval != 0
):
return
rollouts = sample_items_for_logging(
rollouts,
self.config.log_extras.sample_ratio,
)
if not rollouts:
return
assert self.last_log_samples_step <= step, "Step must be greater than last logged step"
assert step not in self._pending_sample_steps, f"Step {step} upload already in progress"
assert self.logger is not None, "Logger is required for sample logging"
self.logger.info(f"Logging {len(rollouts)} samples to Prime Intellect API at step {step}")
start_time = time.perf_counter()
parquet_bytes = self._rollouts_to_parquet_bytes(rollouts, step)
if not parquet_bytes:
self.logger.warning(f"No samples to log at step {step}")
return
self._pending_sample_steps.add(step)
# Use presigned URL flow for uploading samples
self._upload_samples_via_presigned_url(parquet_bytes, step)
self.logger.debug(
f"Initiated samples upload at step {step} to Prime Intellect API in {time.perf_counter() - start_time:.2f}s"
)
def _rollouts_to_parquet_bytes(self, rollouts: list[Rollout], step: int) -> bytes | None:
"""Convert rollouts to Parquet bytes for upload. One row per rollout. The conversation
is the unit (no prompt/completion split — meaningless mid-branch): `completion` is the
last branch's messages and `trajectory` is one message list per branch. Shares
`verifiers.v1.utils.platform.trace_to_sample` with verifiers' eval `--push`, so a training-run
sample and an eval sample land on the platform identically; the RFT-only columns
(run/step/advantage/problem_id/env_name) are layered on here."""
now = datetime.now(timezone.utc)
rows = []
for sample_id, rollout in enumerate(rollouts):
sample = trace_to_sample(rollout, rollout_number=sample_id + 1, episode_id=rollout.episode_id or None)
trajectory = sample["trajectory"]
if not trajectory: # no branches (e.g. a rollout that errored before any message)
continue
advantage = rollout.scalar_advantage()
trajectory = [{**branch, "advantage": advantage} for branch in trajectory]
example_id = sample["example_id"]
try:
problem_id = int(example_id) if example_id is not None else sample_id
except (TypeError, ValueError):
problem_id = sample_id
rows.append(
{
"run_id": self.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": rollout.env_name,
"task": json.dumps(sample["task"]),
"info": json.dumps(rollout.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()
def _upload_samples_via_presigned_url(self, parquet_bytes: bytes, step: int) -> None:
"""Upload Parquet samples using presigned URL flow (fire-and-forget)."""
future = asyncio.run_coroutine_threadsafe(
self._upload_samples_via_presigned_url_async(parquet_bytes, step),
self._loop,
)
self._pending_futures.append(future)
# Clean up completed futures to avoid memory growth
self._pending_futures = [f for f in self._pending_futures if not f.done()]
async def _upload_samples_via_presigned_url_async(
self, parquet_bytes: bytes, step: int, max_retries: int = 3
) -> None:
"""Upload Parquet bytes via presigned URL flow."""
try:
presign_data = await self._request_presigned_url(step)
if not presign_data:
self.logger.warning(f"Failed to get presigned URL for samples at step {step}")
return
presigned_url = presign_data["presigned_url"]
s3_key = presign_data["s3_key"]
upload_success = await self._upload_to_r2(
presigned_url, parquet_bytes, content_type="application/parquet", max_retries=max_retries
)
if not upload_success:
self.logger.warning(f"Failed to upload samples to R2 at step {step}")
return
confirm_success = await self._confirm_samples_upload(step, s3_key)
if not confirm_success:
self.logger.warning(f"Failed to confirm samples upload at step {step}")
return
self.last_log_samples_step = step
self.logger.debug(f"Successfully completed samples upload at step {step}")
except Exception as e:
self.logger.warning(f"Failed to upload samples via presigned URL at step {step}: {type(e).__name__}: {e}")
finally:
self._pending_sample_steps.discard(step)
async def _request_presigned_url(self, step: int) -> dict[str, Any] | None:
"""Request a presigned URL from the backend."""
try:
response = await self._client.post(
f"{self.base_url}/samples/presign",
headers=self._headers,
json={"run_id": self.run_id, "step": step},
)
response.raise_for_status()
response_data = response.json()["data"]
return {
"presigned_url": response_data["presignedUrl"],
"s3_key": response_data["s3Key"],
}
except Exception as e:
self.logger.warning(f"Failed to request presigned URL: {type(e).__name__}: {e}")
return None
async def _upload_to_r2(
self, presigned_url: str, data: bytes, content_type: str = "application/json", max_retries: int = 3
) -> bool:
"""Upload data to R2 using presigned URL."""
for attempt in range(max_retries):
try:
response = await self._client.put(presigned_url, content=data, headers={"Content-Type": content_type})
response.raise_for_status()
return True
except Exception as e:
if attempt == max_retries - 1:
self.logger.warning(f"Failed to upload to R2 after {max_retries} attempts: {type(e).__name__}: {e}")
return False
delay = 2**attempt
self.logger.debug(f"Retrying R2 upload in {delay}s (attempt {attempt + 1}/{max_retries})")
await asyncio.sleep(delay)
async def _confirm_samples_upload(self, step: int, s3_key: str, max_retries: int = 3) -> bool:
"""Confirm samples upload with the backend. Returns True on success."""
for attempt in range(max_retries):
try:
response = await self._client.post(
f"{self.base_url}/samples/confirm",
headers=self._headers,
json={"run_id": self.run_id, "step": step, "s3_key": s3_key},
)
response.raise_for_status()
return True
except Exception as e:
if attempt == max_retries - 1:
self.logger.warning(
f"Failed to confirm samples upload after {max_retries} attempts: {type(e).__name__}: {e}"
)
return False
delay = 2**attempt
self.logger.debug(f"Retrying samples confirm in {delay}s (attempt {attempt + 1}/{max_retries})")
await asyncio.sleep(delay)
return False
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
pass
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
"""Log distributions to Prime Intellect API."""
if not self.is_master:
return
if not self.enabled:
return
if (
not self.config
or not self.config.log_extras
or not self.config.log_extras.distributions
or step % self.config.log_extras.interval != 0
):
# Do not log distributions if not enabled or not log interval step
return
assert self.last_log_distributions_step <= step, "Step must be greater than last logged step"
assert self.logger is not None, "Logger is required for distribution logging"
self.logger.info(f"Logging distributions to Prime Intellect API at step {step}")
start_time = time.perf_counter()
# Upload distributions
self._make_request(
"distributions",
{
"run_id": self.run_id,
"step": step,
"distributions": distributions,
},
)
self.last_log_distributions_step = step
self.logger.debug(
f"Logged distributions at step {step} to Prime Intellect API in {time.perf_counter() - start_time:.2f}s"
)
def _submit_final_summary(self, summary: dict[str, Any]) -> bool:
"""Submit the final summary/finalize request synchronously."""
payload = self._sanitize_json_payload(
"finalize",
{"run_id": self.run_id, "summary": summary},
)
try:
response = httpx.post(
f"{self.base_url}/finalize",
headers=self._headers,
json=payload,
timeout=30,
)
except httpx.HTTPError as e:
self.logger.warning(f"Failed to submit final summary for platform run {self.run_id}: {e}")
return False
if response.status_code != 200:
self.logger.warning(
f"Failed to submit final summary for platform run {self.run_id} "
f"(HTTP {response.status_code}): {response.text}"
)
return False
return True
def save_final_summary(self, filename: str = "final_summary.json") -> None:
"""Save final summary to Prime Intellect API."""
if not self.is_master or not self.enabled:
return
self.logger.info("Saving final summary to Prime Intellect API")
summary = self._last_metrics
finalized_via_summary = self._submit_final_summary(summary)
if os.getpid() != self._owner_pid:
return
if finalized_via_summary:
self._finalized = True
return
self._finalize_run(success=True)
self._finalized = True
def close(self) -> None:
"""Close the HTTP client and stop the background event loop."""
if self._closed or not hasattr(self, "_client"):
return
self._closed = True
should_finalize = self.is_master and self.enabled and not self._finalized and os.getpid() == self._owner_pid
if should_finalize:
self._finalize_run(success=False)
self._finalized = True
self._flush()
# Close the async client within the event loop
async def _close_client() -> None:
await self._client.aclose()
try:
future = asyncio.run_coroutine_threadsafe(_close_client(), self._loop)
future.result(timeout=5.0) # Wait up to 5 seconds for client to close
except Exception as e:
self.logger.debug(f"Error closing HTTP client: {e}")
# Stop the event loop and wait for thread to finish
self._loop.call_soon_threadsafe(self._loop.stop)
self._thread.join(timeout=5.0)
def __del__(self) -> None:
"""Destructor to ensure cleanup."""
self.close()
def _init_async_client(self) -> None:
"""Initialize the event loop, background thread, and HTTP client."""
self._loop: asyncio.AbstractEventLoop = asyncio.new_event_loop()
self._thread = Thread(target=self._run_event_loop, daemon=True)
self._thread.start()
self._client = httpx.AsyncClient(timeout=30)
self._pending_futures: list[asyncio.Future] = []
if hasattr(self, "_pending_sample_steps") and self._pending_sample_steps:
self._pending_sample_steps.clear()
def _reinit_after_fork(self) -> None:
"""Reinitialize thread and event loop after fork."""
self._init_async_client()
def _run_event_loop(self) -> None:
"""Run the async event loop in a background thread."""
asyncio.set_event_loop(self._loop)
self._loop.run_forever()
def _flush(self, timeout: float = 30.0) -> None:
"""Wait for all pending async requests to complete."""
if not self.enabled or not hasattr(self, "_loop"):
return
if not self._pending_futures:
return
self.logger.debug(f"Flushing {len(self._pending_futures)} pending request(s)")
for future in self._pending_futures:
try:
future.result(timeout=timeout)
except Exception as e:
self.logger.debug(f"Pending request completed with error: {e}")
self._pending_futures.clear()
async def _make_request_async(self, endpoint: str, data: dict[str, Any], max_retries: int = 3) -> None:
"""Make an async POST request to the Prime Intellect API with retries."""
full_endpoint = f"{self.base_url}/{endpoint}"
sanitized_data = self._sanitize_json_payload(endpoint, data)
for attempt in range(max_retries):
try:
response = await self._client.post(
full_endpoint,
headers=self._headers,
json=sanitized_data,
)
response.raise_for_status()
return # Success
except Exception as e:
is_last_attempt = attempt == max_retries - 1
if is_last_attempt:
self.logger.warning(
f"Failed to upload to Prime Intellect API ({endpoint}) after {max_retries} attempts: {type(e).__name__}: {e}"
)
else:
# Exponential backoff: 1s, 2s, 4s...
delay = 2**attempt
self.logger.debug(
f"Retrying {endpoint} upload in {delay}s (attempt {attempt + 1}/{max_retries}): {type(e).__name__}: {e}"
)
await asyncio.sleep(delay)
def _make_request(self, endpoint: str, data: dict[str, Any]) -> None:
"""Submit a request to the async queue (fire-and-forget)."""
if not self.enabled:
return
future = asyncio.run_coroutine_threadsafe(
self._make_request_async(endpoint, data),
self._loop,
)
self._pending_futures.append(future)
# Clean up completed futures to avoid memory growth
self._pending_futures = [f for f in self._pending_futures if not f.done()]
-495
View File
@@ -1,495 +0,0 @@
from __future__ import annotations
import json
import os
import re
import sys
import time
from collections.abc import Sequence
from pathlib import Path
from typing import TYPE_CHECKING, Any
import wandb
import wandb_workspaces.reports.v2 as wr
import wandb_workspaces.workspaces as ws
from transformers.tokenization_utils import PreTrainedTokenizer
from wandb.errors import CommError
from wandb.sdk.mailbox.mailbox_handle import ServerResponseError
from wandb_gql import gql
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.logger import get_logger
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
if TYPE_CHECKING:
from prime_rl.orchestrator.types import Rollout
def _loggable_task(task) -> str:
"""A Table-safe JSON string of the task for sample logging. Image content parts are elided to
a short placeholder — their base64 data bloats the table and breaks wandb Table's nested-type
inference on the variable-length content list (a plain dict would otherwise crash on it)."""
def elide(obj):
if isinstance(obj, dict):
if obj.get("type") == "image_url":
return {"type": "image_url", "image_url": "<image>"}
return {k: elide(v) for k, v in obj.items()}
if isinstance(obj, list):
return [elide(v) for v in obj]
return obj
return json.dumps(elide(task.model_dump(mode="json")))
class WandbMonitor(Monitor):
"""Logs to Weights and Biases."""
def __init__(
self,
config: WandbConfig | WandbWithExtrasConfig | None,
output_dir: Path | None = None,
tokenizer: PreTrainedTokenizer | None = None,
run_config: BaseConfig | None = None,
train_env_names: list[str] = [],
eval_env_names: list[str] = [],
):
self.config = config
self.logger = get_logger()
self.output_dir = output_dir
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
self.enabled = self.config is not None
self.is_master = rank == 0
if not self.enabled or not self.is_master:
if not self.is_master:
self.logger.warning(f"Skipping {self.__class__.__name__} initialization from non-master rank ({rank})")
return
assert config is not None
self._maybe_overwrite_wandb_command()
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
# requires a server connection and can't work offline.
_wandb_mode = os.environ.get("WANDB_MODE")
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and _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 == "orchestrator"
settings = wandb.Settings(
mode="shared",
x_label=label,
x_primary=primary,
x_update_finish_state=primary,
)
self.logger.info(f"Using shared W&B mode ({label=}, {primary=})")
is_online = True
else:
run_id = None
primary = False
mode = os.environ.get("WANDB_MODE", "offline" if 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=config.project,
entity=config.entity,
name=config.name,
group=config.group,
tags=config.tags,
dir=output_dir,
config=run_config.model_dump() if run_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)
self.run_id = self.wandb.id
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,
eval_envs=eval_env_names,
)
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}")
# Optionally, initialize sample logging attributes
if config is not None and isinstance(config, WandbWithExtrasConfig) and config.log_extras:
if config.log_extras.samples:
self.last_log_samples_step = -1
self.samples_cols = ["step", "env_name", "task", "task_idx", "messages", "input_ids", "reward"]
self.samples_table = wandb.Table(
columns=self.samples_cols,
log_mode="INCREMENTAL",
)
self.tokenizer = tokenizer
self.eval_samples_cols = ["step", "env", "task", "task_idx", "completion", "reward"]
self.eval_samples_table = wandb.Table(
columns=self.eval_samples_cols,
log_mode="INCREMENTAL",
)
def _maybe_overwrite_wandb_command(self) -> None:
"""Overwrites sys.argv with the start command if it is set in the environment variables."""
wandb_args = os.environ.get("WANDB_ARGS", None)
if wandb_args:
self.logger.debug(f"Found WANDB_ARGS in environment variables {wandb_args}")
sys.argv = json.loads(wandb_args)
def log(self, metrics: dict[str, Any], step: int) -> None:
if not self.is_master:
return
if not self.enabled:
return
wandb.log({**metrics, "step": step})
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
"""Logs rollouts to W&B table."""
if not self.is_master:
return
if (
not self.config
or not isinstance(self.config, WandbWithExtrasConfig)
or not self.config.log_extras
or not self.config.log_extras.samples
or step % self.config.log_extras.interval != 0
):
# Do not log samples if not enabled or not log interval step
return
rollouts = sample_items_for_logging(
rollouts,
self.config.log_extras.sample_ratio,
)
if not rollouts:
return
assert self.tokenizer is not None, "Tokenizer is required for sample logging"
assert self.last_log_samples_step <= step, "Step must be greater than last logged step"
assert self.logger is not None, "Logger is required for sample logging"
self.logger.info(f"Logging {len(rollouts)} samples to W&B table at step {step}")
start_time = time.perf_counter()
for rollout in rollouts:
trace = rollout
for branch in trace.branches:
token_ids = branch.token_ids
if not token_ids:
continue
sample = {
"step": step,
"env_name": rollout.env_name,
"task": _loggable_task(trace.task.data),
"task_idx": trace.task.data.idx,
"messages": self.tokenizer.decode(token_ids),
"input_ids": str(token_ids),
"reward": trace.reward,
}
assert list(sample.keys()) == self.samples_cols, (
"Order of columns in the table must be the same as order of the keys here"
)
self.samples_table.add_data(*sample.values())
wandb.log({"samples": self.samples_table, "step": step})
self.last_log_samples_step = step
self.logger.debug(f"Logged samples at step {step} to W&B table in {time.perf_counter() - start_time:.2f}s")
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
"""Logs eval rollouts to a separate W&B table."""
if not self.is_master:
return
if (
not self.config
or not isinstance(self.config, WandbWithExtrasConfig)
or not self.config.log_extras
or not self.config.log_extras.samples
):
return
for rollout in rollouts:
trace = rollout
for branch in trace.branches:
# Eval runs the openai client (no token ids), so show the assistant message
# content rather than decoded tokens.
completion = "".join(m.content or "" for m in branch.messages if m.role == "assistant")
if not completion:
continue
sample = {
"step": step,
"env": env_name,
"task": _loggable_task(trace.task.data),
"task_idx": trace.task.data.idx,
"completion": completion,
"reward": trace.reward,
}
self.eval_samples_table.add_data(*sample.values())
wandb.log({"eval/samples": self.eval_samples_table, "step": step})
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
"""Log distributions (no-op for W&B)."""
pass
def save_final_summary(self, filename: str = "final_summary.json") -> None:
"""Save final summary to W&B table."""
if not self.is_master or not self.enabled:
return
self.logger.info("Saving final summary to file")
assert self.output_dir is not None, "Output directory is required for saving final summary"
dir_path = self.output_dir / f"run-{self.wandb.id}"
dir_path.mkdir(parents=True, exist_ok=True)
with open(dir_path / filename, "w") as f:
json.dump(wandb.summary._as_dict(), f)
# --- curated "overview" 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.
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"],
]
# 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] = ()) -> list[ws.Section]:
# 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] = (),
) -> 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)
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
-7
View File
@@ -102,13 +102,6 @@ def get_rollout_dir(output_dir: Path) -> Path:
return output_dir / "rollouts"
def get_trace_path(output_dir: Path, step: int, kind: str, subset: str) -> Path:
"""Where one trace file lives: ``rollouts/step_{n}/{train,eval}/{all,effective}/traces.jsonl``.
``all`` is appended per rollout the moment it completes; ``effective`` is written at once
per finalized train batch / eval epoch."""
return get_step_path(get_rollout_dir(output_dir), step) / kind / subset / "traces.jsonl"
def get_eval_dir(output_dir: Path) -> Path:
return output_dir / "evals"
-83
View File
@@ -1,83 +0,0 @@
"""Reports training token usage per step to the platform API for billing.
Activated entirely via environment variables — not exposed in user-facing
config. Self-hosted users are unaffected.
The platform API is idempotent on (run_id, step, usage_type), so replays
after crash-resume are safe.
"""
import asyncio
import os
from prime_rl.utils.background_async import BackgroundAsync
from prime_rl.utils.logger import get_logger
class UsageReporter:
"""Fire-and-forget training token usage reporter.
Activated when ``PI_USAGE_BASE_URL`` is set in the environment.
Wraps a ``BackgroundAsync`` runner so reporting never blocks training.
"""
def __init__(self) -> None:
self.logger = get_logger()
api_key = os.environ.get("PI_USAGE_API_KEY")
base_url = os.environ.get("PI_USAGE_BASE_URL", "").rstrip("/")
# Both must be set. The orchestrator already gates on this, but
# validate here too so any future caller fails fast at construction
# rather than crashing inside httpx (which rejects None header
# values with an obscure .encode() error on every retry).
if not api_key or not base_url:
raise ValueError(
"UsageReporter requires PI_USAGE_BASE_URL and PI_USAGE_API_KEY to be set in the environment."
)
self._api_key = api_key
self._base_url = base_url
self._runner = BackgroundAsync(client_timeout=30.0)
self.logger.debug(f"Usage reporter initialized (base_url={self._base_url})")
def report_training_usage(self, run_id: str, step: int, tokens: int) -> None:
url = f"{self._base_url}/usage"
payload = {"run_id": run_id, "step": step, "usage_type": "training", "tokens": tokens}
self._runner.submit(lambda: self._post(url, payload))
def close(self) -> None:
self._runner.close()
async def _post(self, url: str, data: dict, max_retries: int = 3) -> None:
headers = {"x-api-key": self._api_key, "Content-Type": "application/json"}
for attempt in range(max_retries):
try:
response = await self._runner.client.post(url, headers=headers, json=data)
if response.status_code == 200:
body = response.json()
if body.get("status") == "duplicate":
self.logger.debug(
"Usage already recorded: run=%s step=%s type=%s",
data.get("run_id"),
data.get("step"),
data.get("usage_type"),
)
return
response.raise_for_status()
return
except Exception as e:
if attempt == max_retries - 1:
self.logger.warning(
"Failed to report usage after %d attempts: %s: %s",
max_retries,
type(e).__name__,
e,
)
else:
delay = 2**attempt
self.logger.debug(
"Retrying usage report in %ds (attempt %d/%d): %s",
delay,
attempt + 1,
max_retries,
e,
)
await asyncio.sleep(delay)
+26
View File
@@ -1,6 +1,7 @@
import asyncio
import functools
import importlib
import math
import os
import sys
from collections import defaultdict
@@ -127,6 +128,31 @@ def format_num(num: float | int, precision: int = 2) -> str:
return f"{sign}{num / 1e9:.{precision}f}B"
def sanitize(obj: Any) -> tuple[Any, list[str]]:
"""Recursively drop non-finite floats (NaN/inf), which are not valid JSON.
Returns the sanitized object and the dotted paths of the dropped values."""
dropped_paths: list[str] = []
def keep(item: Any, path: str) -> bool:
if isinstance(item, float) and not math.isfinite(item):
dropped_paths.append(path)
return False
return True
def walk(value: Any, path: str) -> Any:
if isinstance(value, dict):
return {
key: walk(item, child)
for key, item in value.items()
if keep(item, child := f"{path}.{key}" if path else key)
}
if isinstance(value, list):
return [walk(item, child) for index, item in enumerate(value) if keep(item, child := f"{path}[{index}]")]
return value
return walk(obj, ""), dropped_paths
def get_free_port() -> int:
"""Find and return a free port"""
import socket
+2 -2
View File
@@ -46,9 +46,9 @@ def rl_process(
"@",
"configs/ci/integration/alphabet_sort.toml",
"--clean",
"--wandb.project",
"--monitors.wandb.project",
wandb_project,
"--wandb.name",
"--monitors.wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
+4 -4
View File
@@ -46,9 +46,9 @@ def rl_process(
"@",
"configs/ci/integration/reverse-text/start.toml",
"--clean",
"--wandb.project",
"--monitors.wandb.project",
wandb_project,
"--wandb.name",
"--monitors.wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
@@ -75,9 +75,9 @@ def rl_resume_process(
"rl",
"@",
"configs/ci/integration/reverse-text/resume.toml",
"--wandb.project",
"--monitors.wandb.project",
wandb_project,
"--wandb.name",
"--monitors.wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
+4 -4
View File
@@ -39,9 +39,9 @@ def rl_process(
"@",
"configs/ci/integration/reverse-text-lora/start.toml",
"--clean",
"--wandb.project",
"--monitors.wandb.project",
wandb_project,
"--wandb.name",
"--monitors.wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
@@ -68,9 +68,9 @@ def rl_resume_process(
"rl",
"@",
"configs/ci/integration/reverse-text-lora/resume.toml",
"--wandb.project",
"--monitors.wandb.project",
wandb_project,
"--wandb.name",
"--monitors.wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
+2 -2
View File
@@ -40,9 +40,9 @@ def rl_process(
"--clean",
"--trainer.model.impl",
"custom",
"--wandb.project",
"--monitors.wandb.project",
wandb_project,
"--wandb.name",
"--monitors.wandb.name",
f"{wandb_name}-custom",
"--output-dir",
output_dir.as_posix(),

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