Compare commits

...
Author SHA1 Message Date
minh hoangandGitHub 4f5d943a15 fix(monitors): allow overriding the platform base URL via $PRIME_API_BASE (#3287)
The prime monitor's TrainRun hardcodes the production public API
(https://api.primeintellect.ai/api/v1/rft). Managed launches need to point
it at the platform's internal ingestion path instead, and non-prod
environments currently post metrics to prod (where their per-run tokens
401) — silently, since uploads are fire-and-forget.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore(docker): condense build comments

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

---------

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

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

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

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

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

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

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

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

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

* chore: default optim_cpu_offload_chunked and optim_cpu_offload_stream to false

* fix: address bugbot review issues

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

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

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

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

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

* fix: always sync step counters in _sync_step_counters

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

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

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

* refactor: clean up CPUOffloadOptimizer for readability

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* refactor: make stream param required in _move_chunk_states

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

* test: add parity tests for CPUOffloadOptimizer vs plain AdamW

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

* fix: remove redundant isinstance branch in test helper

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

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

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

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

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

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

* feat: stream FSDP gradients through CPU offload

* feat: fuse CPU offload with public FSDP hooks

* refactor: expose optimizer offload config

* refactor: always stream pinned offload transfers

* refactor: name CPU optimizer execution explicitly

* refactor: clarify CPU step config name

* chore: clarify offload runtime logging

* feat: run gradient-offloaded optimizer steps on CPU

* refactor: name fused optimizer offload full

* feat: restore gradient-only optimizer offload

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

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

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

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

* fix: preallocate pinned gradient buffers before the first collective

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

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

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

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

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

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

* perf: slab-allocate pinned gradient offload buffers

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

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

* feat: overlap CPU optimizer with backward

* perf: fuse CPU gradient scaling into AdamW

* perf: add native CPU AdamW kernel

* perf: halve full-offload PCIe traffic

* harden native optimizer offload pipeline

* document optimizer offload handover

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore: trim optimizer offload artifacts

* docs: trim optimizer offload scaling guide

* refactor trainer optimizer modules

* restore state-only optimizer offload

* revert unrelated GLM-5 changes

* fix conflicts with current main

* refactor: make full offload setup explicit

* refactor: rename full optimizer offload config

* fix: refresh offload masters on model-only resume

* refactor: simplify optimizer offload interface

* fix: return checkpoint state to CPU

* fix: adapt offload resume test to run dirs

* fix: preserve mixed dtypes in full offload

* fix: restrict full offload to AdamW

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Mario Sieg <mario.sieg.64@gmail.com>
2026-08-15 19:03:57 -07:00
44 changed files with 2928 additions and 261 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 }}
+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
@@ -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
+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.
@@ -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]
-1
View File
@@ -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]
@@ -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]
-1
View File
@@ -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
View File
@@ -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]
@@ -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]
+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.
+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
```
+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.
+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:
+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.
@@ -281,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:
@@ -2,7 +2,7 @@ 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 (
@@ -54,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``."""
@@ -167,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."""
@@ -269,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")
@@ -632,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 (
+3
View File
@@ -169,6 +169,9 @@ requires-dist = [
]
[tool.uv.exclude-newer-package]
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
+5
View File
@@ -24,6 +24,11 @@ All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/t
- 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
+4 -2
View File
@@ -22,6 +22,7 @@ from prime_rl.utils.logger import get_logger
from prime_rl.utils.utils import sanitize
BASE_URL = "https://api.primeintellect.ai/api/v1/rft"
BASE_URL_VAR = "PRIME_API_BASE"
API_KEY_VAR = "PRIME_API_KEY"
SAMPLE_SCHEMA = pa.schema(
@@ -129,13 +130,14 @@ class TrainRun:
self.id: str | None = None
self.logger = get_logger()
self._tasks: set[asyncio.Task] = set()
self.base_url = (os.getenv(BASE_URL_VAR) or BASE_URL).rstrip("/")
self.headers = {
"Authorization": f"Bearer {api_key}",
"x-api-key": api_key,
"Content-Type": "application/json",
}
self.client = httpx.AsyncClient(
base_url=BASE_URL,
base_url=self.base_url,
headers=self.headers,
timeout=30,
transport=httpx.AsyncHTTPTransport(retries=3),
@@ -246,7 +248,7 @@ class TrainRun:
self.logger.info(f"Marking platform run {self.id} as failed")
try:
httpx.put(
f"{BASE_URL}/external-runs/{self.id}/status",
f"{self.base_url}/external-runs/{self.id}/status",
headers=self.headers,
json={"status": "failed"},
timeout=30,
+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
+32 -10
View File
@@ -38,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,
@@ -49,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
@@ -63,7 +70,6 @@ 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
@@ -107,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.
@@ -151,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)
@@ -314,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
@@ -463,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")
@@ -540,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()
@@ -576,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)
@@ -733,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,
+60 -30
View File
@@ -28,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,
@@ -41,8 +42,14 @@ 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
@@ -53,8 +60,6 @@ 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):
@@ -84,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.
@@ -175,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
@@ -390,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 = (
@@ -401,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
@@ -423,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():
@@ -438,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.
@@ -471,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()
@@ -641,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!")
+112 -1
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,6 +55,49 @@ 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).
@@ -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)
@@ -1,3 +1,4 @@
import hashlib
from pathlib import Path
from typing import Callable
@@ -86,6 +87,38 @@ def sft_resume_process(
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def sft_full_offload_model_only_resume_process(
sft_resume_process: ProcessResult,
run_process: Callable[..., ProcessResult],
wandb_project: str,
wandb_name: str,
output_dir: Path,
) -> ProcessResult:
"""Resume without optimizer state using full CPU offload."""
if sft_resume_process.returncode != 0:
pytest.skip("Regular SFT resume failed")
cmd = [
"uv",
"run",
"sft",
"@",
"configs/ci/integration/reverse-text-sft/full-offload-resume.toml",
"--deployment.num-gpus",
"2",
"--monitors.wandb.project",
wandb_project,
"--monitors.wandb.name",
f"{wandb_name}-full-offload-model-only-resume",
"--output-dir",
output_dir.as_posix(),
"--run.name",
RUN_NAME,
]
return run_process(cmd, timeout=TIMEOUT)
def test_no_error(sft_process: ProcessResult):
"""Tests that the SFT process does not fail."""
assert sft_process.returncode == 0, f"Process has non-zero return code ({sft_process})"
@@ -112,3 +145,24 @@ def test_loss_goes_down_resume(sft_resume_process: ProcessResult, run_dir: Path)
with open(trainer_log_path, "r") as f:
trainer_stdout = strip_escape_codes(f.read()).splitlines()
check_loss_goes_down(trainer_stdout)
def test_full_offload_model_only_resume_preserves_weights(
sft_full_offload_model_only_resume_process: ProcessResult,
run_dir: Path,
):
assert sft_full_offload_model_only_resume_process.returncode == 0, (
f"Process has non-zero return code ({sft_full_offload_model_only_resume_process})"
)
before_dir = run_dir / "weights" / "step_5"
after_dir = run_dir / "weights" / "step_6"
before_files = sorted(before_dir.glob("*.safetensors"))
after_files = sorted(after_dir.glob("*.safetensors"))
assert before_files
assert [path.name for path in before_files] == [path.name for path in after_files]
for before, after in zip(before_files, after_files):
with before.open("rb") as before_handle, after.open("rb") as after_handle:
assert (
hashlib.file_digest(before_handle, "sha256").digest()
== hashlib.file_digest(after_handle, "sha256").digest()
)
+2 -2
View File
@@ -35,9 +35,9 @@ def rl_process(
"rl",
"@",
"examples/basic/alphabet-sort/rl.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
@@ -41,9 +41,9 @@ def rl_process(
"rl",
"@",
"examples/basic/hendrycks-sanity/rl.toml",
"--wandb.project",
"--monitors.wandb.project",
wandb_project,
"--wandb.name",
"--monitors.wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
@@ -39,9 +39,9 @@ def rl_process(
"rl",
"@",
"configs/ci/nightly/multimodal_color_codeword.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
@@ -35,9 +35,9 @@ def rl_process(
"rl",
"@",
"examples/basic/reverse-text/rl.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
@@ -35,9 +35,9 @@ def rl_process(
"rl",
"@",
"examples/basic/wiki-search/rl.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
@@ -35,9 +35,9 @@ def rl_process(
"rl",
"@",
"examples/basic/wordle/rl.toml",
"--wandb.project",
"--monitors.wandb.project",
wandb_project,
"--wandb.name",
"--monitors.wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
+51
View File
@@ -161,6 +161,57 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
def test_optimizer_state_offload_keeps_legacy_default(config_cls):
config = config_cls.model_validate({})
assert config.model.optim_cpu_offload is True
assert config.model.full_offload is None
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
with pytest.warns(UserWarning, match="Gradient clipping prevents optimizer-in-backward"):
config = config_cls.model_validate(
{
"model": {"optim_cpu_offload": False, "full_offload": True},
"optim": {"max_norm": 1.0},
}
)
assert config.optim.max_norm is None
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
def test_full_optimizer_offload_accepts_debug_backend(config_cls):
config = config_cls.model_validate(
{
"model": {
"optim_cpu_offload": False,
"full_offload": {
"cpu_optimizer_backend": "torch",
},
},
"optim": {"max_norm": None},
}
)
assert config.model.full_offload is not None
assert config.model.full_offload.cpu_optimizer_backend == "torch"
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
@pytest.mark.parametrize("optimizer_type", ["sgd", "muon", "sign_sgd"])
def test_full_optimizer_offload_requires_adamw(config_cls, optimizer_type):
with pytest.raises(ValidationError, match="Full optimizer offload only supports AdamW"):
config_cls.model_validate(
{
"model": {"optim_cpu_offload": False, "full_offload": True},
"optim": {"type": optimizer_type, "max_norm": None},
}
)
def test_resolved_json_roundtrips_explicit_none(tmp_path):
"""An explicit None override survives the write/re-parse round-trip used by launches:
resolved configs are JSON, which keeps nulls (TOML cannot)."""
+132
View File
@@ -0,0 +1,132 @@
import torch
from prime_rl.trainer.optim.cpu_adam import (
adamw_step,
add_bfloat16_,
copy_bfloat16_,
copy_or_add_bfloat16_multi_,
)
from prime_rl.trainer.optim.offload import _cast_full_offload_compute_parameters
def test_full_offload_preserves_per_parameter_compute_dtypes():
model = torch.nn.Sequential(torch.nn.Linear(2, 2, bias=False), torch.nn.Linear(2, 2, bias=False))
bfloat16_param, float32_param = model.parameters()
float32_param.data.fill_(1.0001)
original_float32 = float32_param.detach().clone()
model.register_buffer("statistics", torch.tensor([1.0001], dtype=torch.float32))
original_statistics = model.statistics.detach().clone()
policy = {
id(bfloat16_param): (torch.bfloat16, torch.bfloat16),
id(float32_param): (torch.float32, torch.float32),
}
_cast_full_offload_compute_parameters(model, policy)
assert bfloat16_param.dtype == torch.bfloat16
assert float32_param.dtype == torch.float32
torch.testing.assert_close(float32_param, original_float32, rtol=0, atol=0)
torch.testing.assert_close(model.statistics, original_statistics, rtol=0, atol=0)
def test_native_cpu_adamw_matches_fused_torch_and_preserves_gradients():
torch.manual_seed(0)
accumulated = torch.randn(1025)
contribution = torch.randn(1025).bfloat16()
expected_accumulation = accumulated + contribution.float()
add_bfloat16_(accumulated, contribution)
torch.testing.assert_close(accumulated, expected_accumulation, rtol=0, atol=0)
copy_bfloat16_(accumulated, contribution)
torch.testing.assert_close(accumulated, contribution.float(), rtol=0, atol=0)
destinations = [torch.randn(1025), torch.randn(513)]
sources = [torch.randn(1025).bfloat16(), torch.randn(513).bfloat16()]
expected = [destinations[0] + sources[0].float(), sources[1].float()]
copy_or_add_bfloat16_multi_(destinations, sources, [True, False])
for actual, expected_tensor in zip(destinations, expected):
torch.testing.assert_close(actual, expected_tensor, rtol=0, atol=0)
shapes = [(17,), (33, 65), (257, 129)]
initial = [torch.randn(shape) for shape in shapes]
native_params = [tensor.clone() for tensor in initial]
float_gradient_params = [tensor.clone() for tensor in initial]
torch_params = [torch.nn.Parameter(tensor.clone()) for tensor in initial]
exp_avgs = [torch.zeros_like(tensor) for tensor in native_params]
exp_avg_sqs = [torch.zeros_like(tensor) for tensor in native_params]
state_steps = [torch.zeros((), dtype=torch.float32) for _ in native_params]
float_gradient_exp_avgs = [torch.zeros_like(tensor) for tensor in native_params]
float_gradient_exp_avg_sqs = [torch.zeros_like(tensor) for tensor in native_params]
float_gradient_state_steps = [torch.zeros((), dtype=torch.float32) for _ in native_params]
float_compute_params = [torch.empty_like(tensor) for tensor in native_params]
compute_dtypes = [torch.bfloat16, torch.float32, torch.bfloat16]
compute_params = [torch.empty_like(tensor, dtype=dtype) for tensor, dtype in zip(native_params, compute_dtypes)]
torch_optimizer = torch.optim.AdamW(
torch_params,
lr=3e-4,
betas=(0.9, 0.95),
eps=1e-8,
weight_decay=0.1,
fused=True,
)
for iteration in range(1, 6):
gradient_scale = 1.0 / (iteration * 7 + 3)
gradients = [torch.randn_like(tensor).bfloat16() for tensor in native_params]
native_gradients = [gradient.clone() for gradient in gradients]
for param, gradient in zip(torch_params, gradients):
param.grad = gradient.float()
torch_optimizer.grad_scale = torch.tensor(1.0 / gradient_scale)
torch_optimizer.found_inf = torch.zeros((), dtype=torch.float32)
torch_optimizer.step()
adamw_step(
float_gradient_params,
[gradient.float() for gradient in gradients],
float_gradient_exp_avgs,
float_gradient_exp_avg_sqs,
float_gradient_state_steps,
float_compute_params,
lr=3e-4,
beta1=0.9,
beta2=0.95,
weight_decay=0.1,
eps=1e-8,
gradient_scale=gradient_scale,
)
adamw_step(
native_params,
native_gradients,
exp_avgs,
exp_avg_sqs,
state_steps,
compute_params,
lr=3e-4,
beta1=0.9,
beta2=0.95,
weight_decay=0.1,
eps=1e-8,
gradient_scale=gradient_scale,
)
for actual, expected in zip(native_gradients, gradients):
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
for compute_param, native_param in zip(compute_params, native_params):
torch.testing.assert_close(compute_param, native_param.to(compute_param.dtype), rtol=0, atol=0)
for compute_param, native_param in zip(float_compute_params, float_gradient_params):
torch.testing.assert_close(compute_param, native_param, rtol=0, atol=0)
for actual, expected in zip(native_params, float_gradient_params):
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
for actual, expected in zip(exp_avgs, float_gradient_exp_avgs):
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
for actual, expected in zip(exp_avg_sqs, float_gradient_exp_avg_sqs):
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
for actual, expected in zip(state_steps, float_gradient_state_steps):
torch.testing.assert_close(actual, expected, rtol=0, atol=0)
for native_param, torch_param in zip(native_params, torch_params):
torch.testing.assert_close(native_param, torch_param, rtol=1e-6, atol=1e-7)
for index, torch_param in enumerate(torch_params):
state = torch_optimizer.state[torch_param]
torch.testing.assert_close(exp_avgs[index], state["exp_avg"], rtol=1e-6, atol=1e-8)
torch.testing.assert_close(exp_avg_sqs[index], state["exp_avg_sq"], rtol=1e-6, atol=1e-8)
assert state_steps[index].item() == state["step"].item() == 5
Generated
+13 -11
View File
@@ -17,6 +17,7 @@ exclude-newer-span = "P7D"
[options.exclude-newer-package]
vllm = false
verifiers = false
harbor = "2026-08-11T00:00:00Z"
prime-pydantic-config = false
vllm-router = false
dion = false
@@ -2198,7 +2199,7 @@ wheels = [
[[package]]
name = "harbor"
version = "0.20.0"
version = "0.21.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "dirhash" },
@@ -2223,9 +2224,9 @@ dependencies = [
{ name = "typer" },
{ name = "uvicorn" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1e/da/5a26998c6e7d9455321ab39bc8e9122993892ece13c3ad4f2b0de986aaf6/harbor-0.20.0.tar.gz", hash = "sha256:e2e5e88f772690fd121553ca34fd5d6dd6b4aaa51c8fae635abc84b112303112", size = 1590870, upload-time = "2026-07-18T21:25:22.578Z" }
sdist = { url = "https://files.pythonhosted.org/packages/d1/30/c854dcf2b6cbc67f97265e1fd07de02b29419007d4258cded336c23d6356/harbor-0.21.0.tar.gz", hash = "sha256:93f7c2e4b150b2983a90b226c61daf071c35a9dd0f76e1053413d9ee0d738395", size = 1690211, upload-time = "2026-08-10T20:52:34.767Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/76/03/b6617f32385295729f3af0ae0d512cf87ba4793b9ce462ea020d776a9025/harbor-0.20.0-py3-none-any.whl", hash = "sha256:4b7e48223aea2384cdb8c9eff35eaebd482fc9b1ec09f8193a121c47356ff19a", size = 1792416, upload-time = "2026-07-18T21:25:19.206Z" },
{ url = "https://files.pythonhosted.org/packages/2a/a4/b3e8aafbc0a002501c11c91958fc31a5098c2bd9376c46225af615373329/harbor-0.21.0-py3-none-any.whl", hash = "sha256:c77d779a03f1a9e8ecb3c449e17f39a9728b82238832f1fd28632eb9426c0a21", size = 1896665, upload-time = "2026-08-10T20:52:32.305Z" },
]
[[package]]
@@ -3031,7 +3032,7 @@ wheels = [
[[package]]
name = "litellm"
version = "1.87.0"
version = "1.95.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp" },
@@ -3047,9 +3048,10 @@ dependencies = [
{ name = "tiktoken" },
{ name = "tokenizers" },
]
sdist = { url = "https://files.pythonhosted.org/packages/77/0d/ccdf682ccfd7f18bf0e179c39d85616b8f8ef05a798588285310412db13d/litellm-1.87.0.tar.gz", hash = "sha256:cafc1882cb0cbab8374c41180af86e4a067796e4524e15f59e99f6e689cd1bd8", size = 15453755, upload-time = "2026-06-02T03:53:29.076Z" }
sdist = { url = "https://files.pythonhosted.org/packages/0e/96/8cdfb9aaf584b57af35a0423c111a1c1264a78b548cebbb5ed96defacdab/litellm-1.95.0.tar.gz", hash = "sha256:0ef126d52c7a559f8353e50d60fd0d5e7e6c8767ad54df25ddaf79b9edca1afc", size = 17513577, upload-time = "2026-08-02T02:52:49.465Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/98/20/88a372fa7e50fc2c33458c6eef94a79afcf7bdfa43610079531b82b484a3/litellm-1.87.0-py3-none-any.whl", hash = "sha256:fbbba7e47ae29b55f878fe1acc80effb92761bc168f6236bd81a0cb6e147d855", size = 17103948, upload-time = "2026-06-02T03:53:25.677Z" },
{ url = "https://files.pythonhosted.org/packages/33/d0/ad0272853cc450f8bb4a40a93d206e767e18ac2ff3f91870374e1d9fc090/litellm-1.95.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:cb667f84f08520f32b076e03c7a3fa51bf3f7e8b641dade34ab046bf00314d6b", size = 26421359, upload-time = "2026-08-02T02:52:16.048Z" },
{ url = "https://files.pythonhosted.org/packages/02/c1/4301aa8ef6d2fb0e4a2b8dec973d7c4499f680b26d2e1b77643864235a4b/litellm-1.95.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:1bdf7153557cc0851fa9477b137fde476c56d5de92a5778ecfc6c3a75439a4e1", size = 26300401, upload-time = "2026-08-02T02:52:19.501Z" },
]
[[package]]
@@ -5014,7 +5016,7 @@ requires-dist = [
[[package]]
name = "prime-sandboxes"
version = "0.2.36"
version = "0.2.37"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiofiles" },
@@ -5026,9 +5028,9 @@ dependencies = [
{ name = "pyqwest" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/d5/c8/ca5261ff5d5c2e944e198866ead91b09bc88eb0390a905925bb6d7f9cd28/prime_sandboxes-0.2.36.tar.gz", hash = "sha256:3a5c8a7912b1ea0fb775674650835f7f86aac1a05aa8566c2db129b9a622fe55", size = 88415, upload-time = "2026-08-12T23:30:15.214Z" }
sdist = { url = "https://files.pythonhosted.org/packages/5d/18/837603f47eae2cc86bd6652dbbebe955caaca8c0f987dfc7cb947e4c993b/prime_sandboxes-0.2.37.tar.gz", hash = "sha256:44a7cb4bc97ee04bbef824b7ccf185da78cffa90c3f0345ef69fbfbd75ca6bce", size = 89684, upload-time = "2026-08-17T17:07:18.985Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0b/26/081296fc8e6d8ce962f2aee0e47ac843982094dedb34a1fad22d10086f37/prime_sandboxes-0.2.36-py3-none-any.whl", hash = "sha256:a5db92d927cf4a3dd37ce230027a9d83dbf21804d4f6ed2255d276c1962fa8f2", size = 49316, upload-time = "2026-08-12T23:30:14.047Z" },
{ url = "https://files.pythonhosted.org/packages/c3/4c/346abc72f6891267f490abfbe9de867c3ba2ed64ae8a4f964ffc4065492a/prime_sandboxes-0.2.37-py3-none-any.whl", hash = "sha256:9687e1b698c183798138b5e2ca116554773e3e300307a599beb7fbe8ed65e783", size = 49587, upload-time = "2026-08-17T17:07:17.403Z" },
]
[[package]]
@@ -7448,7 +7450,7 @@ requires-dist = [
{ name = "anthropic", specifier = ">=0.78.0" },
{ name = "datasets", specifier = ">=3.3.0,<6.0.0" },
{ name = "gepa", specifier = ">=0.0.6" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.20.0" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.21.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "loguru", specifier = ">=0.7.0" },
{ name = "math-verify", specifier = ">=0.8.0" },
@@ -7463,7 +7465,7 @@ requires-dist = [
{ name = "openai-agents", specifier = ">=0.8.2" },
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.2" },
{ name = "prime-sandboxes", specifier = ">=0.2.36" },
{ name = "prime-sandboxes", specifier = ">=0.2.37" },
{ name = "prime-tunnel", specifier = ">=0.1.8" },
{ name = "pydantic", specifier = ">=2.12.3" },
{ name = "python-dotenv", marker = "extra == 'browser'", specifier = ">=1.0.0" },