Compare commits

...
Author SHA1 Message Date
72834b3b52 feat(trainer): prepare RL micro batches on a background thread pool (#3917)
This is an alternative to #3907. The RL trainer decoded and preprocessed
each micro batch's images on the main thread right before its forward
pass, leaving the GPU idle. `WorkerPool`, a small ordered thread pool
configured by `data.num_workers` like torch's DataLoader, now prepares
micro batches ahead of the loop through a single `prepare_micro_batch`
hook.

- `num_workers` defaults to 0, which prepares on the main thread as
before, and one thread gives the full speedup. Here it counts threads,
unlike SFT's DataLoader processes.
- An earlier version used forked worker processes. They pickle data
through `/dev/shm`, risk copy-on-write memory, and were 0.6 s/step
slower than a thread.
- Pinned memory and `non_blocking` copies are left to a follow-up that
first removes the per-micro-step CUDA syncs.

Qwen3.5-9B trainer-only on 4 H200s, mock micro batches of 1024 px JPEGs
(about 1 s of CPU decoding each), median s/step, lower is better
(benchmark code added in
[`331fc83fe`](https://github.com/PrimeIntellect-ai/prime-rl/commit/331fc83fed9ff8b6fb435df5207a07e37b08c0e5)
and removed in the next commit):

| Arm | main thread | prepared ahead | time saved |
|---|---|---|---|
| this PR, 1 thread | 24.98 | 18.86 | 24.5% |
| this PR, 1 thread, optimizer CPU offload | 26.56 | 20.24 | 23.8% |
| earlier process version, 2 workers | 24.79 | 19.02 | 23.3% |
| #3907 (thread with pinned memory) | 24.98 | 18.63 | 25.4% |

Every arm matches the main-thread baseline bit for bit in loss and grad
norm. Host memory stays flat over 30 steps, 0.3 GiB above the baseline
for the prefetched images.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 12:15:19 -04:00
faresobeidandGitHub 0bcb868e91 fix(configs): size the single-node NCCL transfer group after the DP fill (#3841)
## Summary
Two bugs in how `rl` sets `weight_broadcast.inference_world_size` on
main:

1. **World size computed before the DP fill.**
`auto_setup_weight_broadcast` set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
before `auto_setup_deployment` fills the single-node inference GPUs with
DP ranks. With `num_infer_gpus = 4` and `data_parallel_size` unset, the
NCCL group was sized for 1 inference worker while vLLM started 4, so the
first weight update cannot form the group.
2. **A single-node SLURM job cannot re-parse its `rl.json`** (since
#3788). The resolved `rl.json` always contains
`weight_broadcast.inference_world_size` (default 1), and #3788's guard
rejects any config that sets it. So `rl @ rl.json` in the single-node
sbatch fails validation for every NCCL config.

## Fix
- Single-node: set
`trainer`/`orchestrator.weight_broadcast.inference_world_size = dp * tp`
right after the DP fill in `auto_setup_deployment` (non-filesystem
only). Multi-node already sets it there.
- `auto_setup_weight_broadcast` copies `weight_broadcast` to the trainer
and orchestrator without touching the world size, and the guard is
removed. The top-level value is now only passed through: `rl` overwrites
it whenever it knows the inference size.

This also fixes what #3924 fixes.

## Behavior change
Yes (bug fixes).
- Resolved configs for every TOML in `configs/`, `examples/`, `k8s/`
that parses as `RLConfig` (41 of 78) are identical before and after,
except `trainer`/`orchestrator.weight_broadcast.inference_world_size`
goes from 1 to 4 in `examples/basic/hendrycks-sanity/rl.toml` and
`configs/ci/nightly/multimodal_color_codeword.toml` (4 infer GPUs, DP
unset).
- Re-parsing the dumped config (as the single-node sbatch does) fails on
main for all 18 single-node NCCL configs and passes for all of them
here.
- With `inference = None` and NCCL against external servers, a user-set
`weight_broadcast.inference_world_size` is now passed through instead of
rejected.

## Checks
- `pytest tests/unit/test_configs.py tests/unit/orchestrator -m "not
gpu"`: 298 passed
- `ruff check`, `ruff format --check`: clean
- New test `test_single_node_nccl_resolved_json_roundtrips`: dumps a
single-node NCCL config like `rl`'s `write_config`, re-parses it, and
checks it is equal. It fails on main with the guard error.
- `rl @ examples/basic/reverse-text/rl.toml --deployment.num-infer-gpus
2 --slurm.partition all --dry-run`, then re-parse the written `rl.json`:
fails on main, passes here (world size 2).
- GPU (one node): running: `rl @ examples/basic/hendrycks-sanity/rl.toml
--max-steps 3` on main and on this branch, plus the rendered single-node
sbatch for reverse-text (2 infer GPUs) run end to end.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes when NCCL weight broadcast groups are sized for single-node
runs; mis-sizing previously caused deadlocks or init failures during
weight updates.
> 
> **Overview**
> Fixes incorrect **NCCL/NIXL** `inference_world_size` on single-node RL
runs when vLLM **data parallel size** is inferred from `num_infer_gpus`
rather than set explicitly.
> 
> **`auto_setup_weight_broadcast`** no longer derives
`trainer`/`orchestrator.weight_broadcast.inference_world_size` from
`data_parallel_size × tensor_parallel_size` (which ran before DP was
filled) and no longer rejects a user-set `inference_world_size`.
**`auto_setup_deployment`** (single-node) now sets
`inference_world_size` to `dp × tensor_parallel_size` immediately after
the DP/`api_server_count` fill, so the in-memory transfer group matches
every inference GPU that joins NCCL.
> 
> Unit tests assert the resolved world size (2 infer GPUs → size 2) and
that a dumped `rl.json` round-trips unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f5553f5c5dd2f91aa11003338ef13e285a6c9ee6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:56:47 +01:00
faresobeidandGitHub 746d8a96d0 chore(models): drop rms_norm re-export, move fp8 quantizer into its tool (#3858)
## Summary
- Delete `trainer/models/layers/rms_norm.py`. It only re-exported
`RMSNorm`/`RMSNormConfig` from `layers/norms.py`, and nothing imported
it.
- Move `quantize_to_fp8_blockwise` from `trainer/models/fp8.py` into
`tools/convert_bf16_to_fp8.py`, its only user.
`tools/convert_dcp_to_fp8.py` still imports it through
`convert_bf16_to_fp8`. While moving it, the 9-line zero-pad block
becomes `F.pad(weight, (0, pad_cols, 0, pad_rows)).contiguous()`; the
output is bitwise identical to the old function (bf16/fp16/fp32, padded
and unpadded shapes, contiguous and transposed inputs).

## Behavior change
None.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Dead-code removal and relocating a tool-only quantizer; no trainer
inference or training path changes.
> 
> **Overview**
> Removes dead trainer surface area and keeps FP8 checkpoint conversion
self-contained in the tooling layer.
> 
> **`trainer/models/layers/rms_norm.py`** is deleted (it only
re-exported `RMSNorm` / `RMSNormConfig` with no importers).
**`trainer/models/fp8.py`** is removed and
**`quantize_to_fp8_blockwise`** now lives in
**`tools/convert_bf16_to_fp8.py`**, which was its only consumer;
**`convert_dcp_to_fp8.py`** continues to pull quantization helpers from
that script. Padding inside the moved helper uses **`F.pad`** instead of
manual zero-fill, with the same blockwise e4m3 logic otherwise
unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c35ca75057037c6d98f0080bdffae8efd24e2f85. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 12:46:12 +01:00
faresobeidandGitHub 765bbeba7b fix(launch): default TRITON_CACHE_DIR to a node-local path (#3877)
Processes that share `~/.triton` on a shared filesystem can hang or
crash (seen with Nemotron-H, where many ranks compile the Mamba Triton
kernels at once; reproduced below with Qwen3.5 and GLM-4.5-Air).

This PR adds `TRITON_CACHE_DIR = /tmp/triton-<uid>` to
`DEFAULT_COMMON_ENV_VARS`. It is per-user because `/tmp` is shared by
all users on a node. Like the other launcher defaults, it reaches every
launched component: the local `rl`/`sft`/`inference` launchers (also
used by the single-node sbatch scripts) and the trainer, orchestrator,
inference (incl. prefill/decode), and online-eval env blocks of the
multi-node and inference sbatch scripts. `[env_vars]` (or a component's
`env_vars`) overrides it; a value exported in the shell or `.env` does
not. It also removes the `TRITON_CACHE_DIR` overrides from six example
configs (glm-4.5-air swe/swe-budget/search/terminal, glm-5.3 and
qwen3-30b-a3b sft h200 base): they pointed every user at the same `/tmp`
dir and are now covered by the default. `docs/scaling.md` says so in one
paragraph.

vLLM 0.31's own default: when `TRITON_CACHE_DIR` is unset, its Inductor
adaptor points it at
`$VLLM_CACHE_ROOT/torch_compile_cache/<hash>/rank_<i>_<j>/triton_cache`
(`~/.cache/vllm` by default, so usually on the shared home). That only
covers Triton kernels compiled after torch.compile initializes, and it
is still on the shared filesystem. vLLM keeps a `TRITON_CACHE_DIR` that
is already set, so with this PR vLLM uses `/tmp/triton-<uid>` too.

### Measured cost (one H200 node, vLLM 0.31 venv, Triton 3.7.1)

Each run starts from a fresh process with the same config. "Ready" is
launch → first trainer step logged (Qwen) or launch → `/health` OK
(GLM). For GLM, the first generated token came 1.3–2 s after ready in
every run that came up. Inductor's cache dir was emptied before each run
except the warm node-local one.

| Triton cache | Qwen3.5-4B SFT, 8 GPUs, compiled blocks (step 1 time) |
GLM-4.5-Air vLLM TP8 |
|---|---|---|
| shared, cold (today on a new cluster / after a Triton or torch update)
| **failed 2/2**: `FileNotFoundError` on a cache file that another rank
was writing (`causal_conv1d_fwd_kernel.llir`, `l2norm_fwd_kernel.ptx`) |
**failed 2/2**: 4 of 8 ranks hit `FileNotFoundError` in the cache during
Inductor autotune, the other 4 hung in a collective until killed (1st
run). The 2nd run crashed instead of hanging. |
| shared, warm | not measured cleanly (see below) | 344 s |
| node-local, cold (this PR, first job on a node) | 233 s (step 1: 91
s), 164 kernels compiled | 375 s with vLLM's compile cache warm (106
kernels); 465 s if vLLM's cache is also cold (87 kernels) |
| node-local, warm (this PR, later jobs on the same node) | 138 s (step
1: 8.3 s) | 344 s |

- A cold node-local cache costs about **95 s per node for Qwen3.5** (FLA
+ Inductor kernels) and about **31 s for GLM-4.5-Air inference** when
vLLM's own compile cache is warm. Warm node-local and warm shared take
the same time.
- The rest of the GLM startup does not depend on the Triton cache: about
3.5 min of Python imports and process spawn from the shared venv, 13 s
to load weights.
- vLLM: `VLLM_CACHE_ROOT` (`~/.cache/vllm`, shared home) holds vLLM's
AOT/Inductor artifacts. With this PR it stays shared. On a new node,
vLLM loads those artifacts (`torch.compile` 0.6 s instead of 30 s), and
the Triton binaries are compiled into `/tmp/triton-<uid>` (106 kernels,
+31 s). `TORCHINDUCTOR_CACHE_DIR` (default `/tmp/torchinductor_<user>`,
already node-local) stayed empty in these runs. Inductor's Triton
kernels go to `TRITON_CACHE_DIR`.
- A crash on the shared cache can also break later starts. After the
first failed GLM run, the shared vLLM cache only had AOT artifacts from
the 4 ranks that got through. On the next start, those 4 ranks loaded
the artifacts and the other 4 recompiled, so the ranks diverged and hung
(Triton cache warm-ish, 60 kernels). For the same reason the Qwen
"shared, warm" run started from a partial cache and failed again. The
warm-shared GLM number comes from a shared dir seeded with a complete
cache.

### Possible middle ground (not implemented)

Because the cold cost is above 1 min per node for FLA-heavy models, a
run could seed the node-local cache from a shared read-only copy at job
start. For example, on each node before the components start:
`[ -n "$TRITON_CACHE_SEED" ] && cp -rn "$TRITON_CACHE_SEED"/.
"$TRITON_CACHE_DIR"/`
The seed would be a warm `/tmp/triton-<uid>` copied once to the shared
FS. Triton keys entries by source, compiler, and GPU, so stale entries
are never reused, only skipped. Only reads hit the shared FS, so the
concurrent-write race does not occur. I left it out to keep this PR
minimal.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Launch-time env default only; behavior is overridable via config and
fixes known multi-rank Triton cache races, with a one-time cold-compile
cost on each node.
> 
> **Overview**
> **Sets a global launcher default** so every trainer, orchestrator, and
inference process gets `TRITON_CACHE_DIR=/tmp/triton-<uid>` via
`DEFAULT_COMMON_ENV_VARS`, avoiding concurrent Triton kernel writes
under `~/.triton` on a shared filesystem (hangs / `FileNotFoundError`
under multi-rank compile).
> 
> **Removes redundant `[env_vars]` overrides** from six GLM-4.5-Air RL
and GLM-5.3 / Qwen3-30B SFT example configs that previously pinned
Triton cache paths under `/tmp`; those runs now inherit the per-user
node-local default (still overridable through config `env_vars`).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f21642046ea59cab0b9460863560b4df825f29c0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
2026-10-08 11:59:17 +01:00
faresobeidandGitHub fec3acd8e7 chore(orchestrator): fold GenerationSource into TrainEnv (#3838)
## Summary
Fold `GenerationSource` into `TrainEnv`, its only owner. Move
`connect_frozen_client` from `algo/base.py` to `clients.py`, so `algo`
no longer imports `clients` lazily. Give `TrainEnv` `setup()`/`aclose()`
so orchestrator setup and teardown no longer reach into its parts.

## What changed
- `orchestrator/generation_source.py` is deleted. `TrainEnv` (`envs.py`)
now holds `clients`, `renderer_config`, `connected` (the frozen source
clients it connected) and `uses_live_policy`. Dropping `logprobs` for
frozen sources happens in `TrainEnv.__init__`.
- `TrainEnv.setup()` connects the frozen generation source and runs
`algorithm.setup()` concurrently. `TrainEnv.aclose()` closes `connected`
and `algorithm.connected`, never the shared policy clients.
- `connect_frozen_client` is a plain function in `clients.py`, next to
`check_inference_ready`. `algo/base.py` imports it at module level. It
is no longer re-exported from `prime_rl.orchestrator.algo`.
- `dispatcher.py` reads the `TrainEnv` directly at the four former
`generation_source` call sites. `orchestrator.py` calls `env.setup()`
and `env.aclose()`.
- `docs/algorithms.md` and the `algo/__init__.py` docstrings refer to
`TrainEnv`.

## Behavior change
None.

## Checks run
- `pytest tests/unit/orchestrator tests/unit/test_configs* -m "not
gpu"`: 297 passed.
- `ruff check`, `ruff format --check`: clean.
- Equivalence script, old `GenerationSource` (`origin/main`) vs new
`TrainEnv`, on 4 configs: policy, policy with `top_p=0.9`, sft with a
frozen `sampling.source`, opd with a frozen teacher. Identical
`sampling_args`, `requires_sampling_masks` and `uses_live_policy`. After
`setup()`, the same generation clients (policy object, or the frozen
endpoint with the same train client config) and the same algorithm
clients. Teardown closes the same clients.
- GPU smoke on one node (vLLM 0.31): reverse-text RL (15 steps), sft
with a frozen `sampling.source` (5 steps), opd with a frozen teacher (5
steps). All three ran to "Training finished" and exited 0.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Internal orchestrator refactor with stated behavioral equivalence and
no changes to training algorithms or dispatch semantics beyond
indirection.
> 
> **Overview**
> **Refactors train rollout sourcing** by deleting `GenerationSource`
and moving its responsibilities onto `TrainEnv`: inference `clients`,
live-vs-frozen policy detection (`uses_live_policy`), sampling-arg
tweaks (e.g. dropping `logprobs` for frozen endpoints), and frozen-pool
connection in `setup()`.
> 
> `TrainEnv.setup()` now connects frozen `sampling.source` endpoints and
runs `algorithm.setup()` together; `TrainEnv.aclose()` closes only
env-owned clients (`connected` + algorithm pools), not the shared policy
pool. The orchestrator and dispatcher call these surfaces instead of
reaching into a nested `generation_source`.
> 
> `connect_frozen_client` moves from `algo/base.py` to `clients.py`
(next to `check_inference_ready`); it is no longer re-exported from
`prime_rl.orchestrator.algo`. Docs and package docstrings now describe
`TrainEnv` as owning the sampling half of the algorithm config.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e89ca1a663ae6ae808b05ff3326ce9ed63c9b467. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 11:52:10 +01:00
Florian BrandandGitHub adda4731fe fix(eval): salt inference caches only when policy weights change (#3825)
Apply a policy-version cache salt only when inference weights can change
during a run. Standalone evaluations and frozen-model requests omit the
training salt; live RL rollouts and online evaluation retain it so
caches distinguish policy versions.

## Before

The dispatcher added the policy version as `cache_salt` to every request
using the live policy source. Standalone evaluation used that same
source path, so fixed-weight evaluations received a training cache salt
even though no weight updates occurred. Frozen-model requests already
omitted it.

```mermaid
flowchart TD
    Standalone["Standalone evaluation with fixed weights"] --> Live["Live policy source"]
    Training["RL or online evaluation with changing weights"] --> Live
    Live --> Salt["Always add policy-version cache_salt"]
    Salt --> Request["Verifiers provider request"]
    Frozen["Frozen model source"] --> Plain["Omit training cache_salt"]
    Plain --> Request
```

## After

```mermaid
flowchart TD
    Request["Prime-RL dispatcher builds request sampling"] --> Mode{"Live policy source with changing weights?"}
    Mode -->|"Yes: RL or online evaluation"| Salt["Set cache_salt to policy version"]
    Mode -->|"No: standalone evaluation or frozen model"| Plain["Omit training cache_salt"]
    Salt --> Client["Verifiers client builds provider request"]
    Plain --> Client
    Client --> Provider["Inference provider"]
```

The dispatcher records whether policy weights can change. The standalone
evaluator disables version salting, SFT online evaluation enables it,
and RL orchestration keeps it enabled. The request decision also checks
whether the source uses the live policy.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Narrow behavior change to cache salting on eval paths; RL and online
eval keep prior salting via the default flag.
> 
> **Overview**
> Adds a **`policy_weights_change`** flag on `Dispatcher` so inference
**`cache_salt`** (policy version) is only attached when weights can
actually change during the run.
> 
> **Standalone eval** (`EvalConfig`) sets the flag to **false**, so
fixed-weight evaluation no longer invalidates prefix caches on every
training policy version. **SFT online eval** and **RL orchestration**
(default **true**) still salt live-sourced requests so caches stay
correct across weight updates.
> 
> The cache decision is now **`live_sourced and policy_weights_change`**
instead of salting all live policy paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5a2d7d9652740106e63fee31a6e79da13816dae7. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:52:39 -07:00
Florian BrandandGitHub a3f1f892c5 fix(eval): preserve empty outcomes and exclude zero-turn traces from training (#3809)
Keep successful empty environment outcomes in evaluation results. A
trace-less episode or clean zero-turn trace retains the verdict returned
by Verifiers, while training and curriculum logic exclude zero-turn
traces.

## Before

The dispatcher changed successful trace-less episodes into
`EmptyEpisode` failures. Clean, non-timeout zero-turn traces became
`EmptyTrajectory` failures, marking both the trace and episode
unsuccessful. Evaluation therefore recorded a failure even when the
environment had returned success, while training and curriculum filters
relied on those injected errors to exclude empty traces.

```mermaid
flowchart TD
    Env["Verifiers returns an empty successful outcome"] --> Dispatch["Prime-RL dispatcher"]
    Dispatch --> Episode["No traces: inject EmptyEpisode"]
    Dispatch --> Trace["Clean zero-turn trace: inject EmptyTrajectory"]
    Episode --> Failed["Rewrite outcome as failed"]
    Trace --> Failed
    Failed --> Eval["Evaluation records a failure"]
    Failed --> Training["Training and curriculum filter injected errors"]
```

## After

```mermaid
flowchart TD
    Env["Verifiers environment returns an episode"] --> Dispatch["Prime-RL dispatcher preserves empty outcome verdicts"]
    Dispatch --> Eval["Evaluation records and metrics"]
    Dispatch --> Filter["Training trace eligibility"]
    Filter --> Empty["Zero turns: no training sample"]
    Filter --> Sample["Eligible trace with sampled tokens: training sample"]
    Dispatch --> Curriculum["Curriculum ignores zero-turn traces and admits only trainable groups"]
```

Remove the synthetic `EmptyEpisode` and `EmptyTrajectory` errors.
`iter_trainable_traces()` filters empty traces alongside failed and
untrainable traces before advantages are assigned, so the advantage gate
needs no separate zero-turn check. Difficulty sampling also excludes
zero-turn traces. Empty groups finish without producing a trainer
payload, and mixed groups retain their eligible traces. Curriculum
admission also requires a trainable trace, so groups without training
samples cannot inflate admission metrics. Sampler observations of
completed turns are retained even when token metadata is unavailable.
Verifiers' no-agent validation and training timeout handling remain in
place.

[#3824](https://github.com/PrimeIntellect-ai/prime-rl/pull/3824) applies
the same ownership rule to partially failed episodes: preserve
environment results, then decide training eligibility explicitly.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes evaluation outcome recording and which rollouts feed
training/curriculum admission, which can shift eval metrics and training
batch composition without touching auth or data stores.
> 
> **Overview**
> Stops the dispatcher from **injecting** `EmptyEpisode` /
`EmptyTrajectory` errors on successful trace-less or zero-turn outcomes,
so **evaluation keeps Verifiers’ success verdict** instead of recording
synthetic failures.
> 
> Training and curriculum now **exclude zero-turn traces explicitly**:
`iter_trainable_traces()` skips `num_turns == 0`, difficulty-pool reward
updates require `num_turns > 0`, and curriculum admission requires
**both** passing gates **and** at least one trainable trace via
`iter_trainable_traces()`. Scored rollouts without token/advantage
metadata can still update sampler difficulty; groups with no trainable
samples no longer count as admitted.
> 
> Tests cover mixed groups with non-trainable traces, empty-only groups,
and reward-only observations for the sampler.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8582fb8c18e7cb4aa0dc7af58c6e0a4474bd7b40. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-08 01:51:52 -07:00
Florian BrandandGitHub e6acff78aa chore: align network prompt dependency pins (#3929) 2026-10-07 19:45:14 -07:00
32 changed files with 343 additions and 232 deletions
+1 -1
+1 -1
View File
@@ -139,7 +139,7 @@ algo.type = "echo"
### The Algorithm Classes
At runtime, each env's resolved config builds two objects: a `GenerationSource` (`prime_rl.orchestrator.generation_source`) that resolves the `sampling.source` model into the inference pool used for train episodes, and one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
At runtime, each env's `TrainEnv` (`prime_rl.orchestrator.envs`) resolves the `sampling.source` model into the inference pool used for train episodes, and its resolved config builds one of the named algorithm classes in `prime_rl.orchestrator.train.algo` (one module per algorithm: `algo/grpo.py`, `algo/opd.py`, …) from the algorithm config. Algorithm dispatch is keyed on `algo.type` — it names the algorithm, and each config class's defaults are its vetted parameterization:
| `algo.type` | Class | hook(s) — stage |
|---|---|---|
@@ -5,10 +5,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-search"
partition = "all"
@@ -23,11 +23,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
partition = "all"
-5
View File
@@ -19,11 +19,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-swe"
partition = "all"
@@ -6,10 +6,6 @@
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-terminal"
partition = "all"
@@ -2,7 +2,6 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "zai-org/GLM-5.3-BF16"
@@ -2,7 +2,6 @@ clean = true
[env_vars]
HF_HOME = "/home/huggingface"
TRITON_CACHE_DIR = "/tmp/.cache/triton_cache"
[model]
name = "Qwen/Qwen3-30B-A3B-Instruct-2507"
@@ -433,17 +433,8 @@ class RLConfig(BaseConfig):
"PEFT-shaped directory on disk (LoRAModel.from_local_checkpoint) - in-memory transports "
"have no disk artifact to load from."
)
if "inference_world_size" in self.weight_broadcast.model_fields_set:
raise ValueError("weight_broadcast.inference_world_size is set automatically by rl; remove it.")
update = {}
if self.weight_broadcast.type != "filesystem":
update["inference_world_size"] = (
self.inference.vllm.data_parallel_size * self.inference.vllm.tensor_parallel_size
if self.inference
else 1
)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy(update=update)
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy(update=update)
self.trainer.weight_broadcast = self.weight_broadcast.model_copy()
self.orchestrator.weight_broadcast = self.weight_broadcast.model_copy()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
return self
@@ -659,6 +650,11 @@ class RLConfig(BaseConfig):
dp = self.inference.vllm.data_parallel_size
if self.inference.vllm.api_server_count < dp and not self.inference.vllm.enable_lora:
self.inference.vllm.api_server_count = dp
if self.weight_broadcast.type != "filesystem":
# Every inference GPU joins the in-memory transfer group, so size it after the DP fill.
world_size = dp * self.inference.vllm.tensor_parallel_size
self.trainer.weight_broadcast.inference_world_size = world_size
self.orchestrator.weight_broadcast.inference_world_size = world_size
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = (
@@ -612,6 +612,9 @@ class DataLoaderConfig(BaseConfig):
fake: FakeDataLoaderConfig | None = None
"""Use a fake data loader sampling random micro-batches (for debugging)."""
num_workers: int = Field(0, ge=0)
"""Number of background threads that prepare micro batches ahead of the training loop, analogous to torch DataLoader's ``num_workers`` but with threads instead of processes. 0 prepares them on the main thread."""
class TrainerConfig(BaseConfig):
model: ModelConfig = ModelConfig()
+1
View File
@@ -114,6 +114,7 @@ class EvalRunner:
eval_source=self.eval_source,
policy_clients=self.clients,
policy=self.policy,
policy_weights_change=isinstance(config, SFTOnlineEvalConfig),
progress=None,
initial_max_inflight=self.concurrency.max_inflight,
max_inflight_ceiling=config.concurrency.max_inflight,
+4 -5
View File
@@ -2,8 +2,8 @@
The config side (``prime_rl.configs.algorithm``) defines *what* an algorithm
is — a bundle of sampling and the per-token training signal. This package
turns the signal half into runtime objects (the sampling half is the env's
:class:`~prime_rl.orchestrator.generation_source.GenerationSource`):
turns the signal half into runtime objects (the sampling half is interpreted by
:class:`~prime_rl.orchestrator.envs.TrainEnv`):
- one module per algorithm (``grpo``, ``echo``, ``max_rl``, ``rae``,
``hierarchical_grpo``, ``opd``, ``opsd``, ``sft``, ``debug``) — each named
@@ -22,7 +22,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.orchestrator.algo.base import Algorithm, connect_frozen_client
from prime_rl.orchestrator.algo.base import Algorithm
from prime_rl.orchestrator.algo.debug import DebugAlgorithm
from prime_rl.orchestrator.algo.echo import EchoAlgorithm
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
@@ -56,7 +56,7 @@ ALGORITHM_CLASSES: dict[str, type[Algorithm]] = {
def build_algorithm(config: AlgoConfig, clients: InferenceClient) -> Algorithm:
cls = ALGORITHM_CLASSES[config.type]
# The Algorithm is the runtime of the algorithm config's training signal
# (its sibling GenerationSource interprets the sampling half). Every algorithm is
# (its TrainEnv interprets the sampling half). Every algorithm is
# handed the live policy pool — opsd self-distills against it, others may
# judge against it or ignore it. Other models (a frozen teacher, a hint
# renderer) are built from the algorithm's own config in setup().
@@ -75,7 +75,6 @@ __all__ = [
"RAEAlgorithm",
"SFTDistillAlgorithm",
"build_algorithm",
"connect_frozen_client",
"assign_advantages",
"stamp_loss_routing",
]
+2 -26
View File
@@ -2,41 +2,17 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import verifiers.v1 as vf
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.utils.logger import get_logger
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
from prime_rl.orchestrator.clients import InferenceClient, check_inference_ready
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
def iter_trainable_traces(episodes: list[vf.Episode]):
"""Yield clean trainable traces that contain sampled tokens."""
for episode in episodes:
for trace in episode.traces:
if trace.has_error or not trace.agent.trainable:
if trace.has_error or not trace.agent.trainable or trace.num_turns == 0:
continue
if any(any(node.mask) for node in trace.nodes):
yield episode, trace
+16
View File
@@ -20,6 +20,7 @@ from verifiers.v1.configs.client import (
resolve_headers,
)
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.utils.logger import get_logger
@@ -228,6 +229,21 @@ async def check_inference_ready(client_config: ClientConfig, model_name: str) ->
await admin.aclose()
async def connect_frozen_client(
config: FrozenModelConfig, *, renderer_config: RendererConfig | None = None
) -> InferenceClient:
"""Connect to an externally hosted frozen model and wait for it."""
get_logger().info(f"Initializing frozen model pool (model={config.name}, base_url={config.base_url})")
if renderer_config is not None:
clients = InferenceClient(
config, model_name=config.name, train_client_type="renderer", renderer_config=renderer_config
)
else:
clients = InferenceClient(config, model_name=config.name)
await check_inference_ready(config, config.name)
return clients
def setup_client(
client_config: ClientConfig,
client_type: str = "openai_chat_completions",
+3 -2
View File
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Any
import verifiers.v1 as vf
from prime_rl.orchestrator.algo.base import iter_trainable_traces
from prime_rl.orchestrator.curriculum.gates import AdmissionGate
from prime_rl.orchestrator.curriculum.samplers import TaskSampler
@@ -48,7 +49,7 @@ class Curriculum:
self.gates[name] = gate
def on_result(self, group: list[vf.Episode]) -> bool:
"""Observe every result, evaluate every gate, and combine with AND."""
"""Observe every result and admit trainable groups that pass every gate."""
if not group:
raise ValueError("Cannot report an empty rollout group")
task_keys = {episode.task.key for episode in group}
@@ -63,7 +64,7 @@ class Curriculum:
if not isinstance(decision, bool):
raise TypeError(f"AdmissionGate {name!r}.admit() must return bool, got {type(decision).__name__}")
decisions.append(decision)
return all(decisions)
return all(decisions) and any(iter_trainable_traces(group))
def state_dict(self) -> dict[str, Any]:
return {
@@ -68,7 +68,7 @@ class DifficultyPoolSampler(TaskSampler):
trace.reward
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if not trace.has_error and trace.agent.trainable and trace.num_turns > 0
]
if not rewards:
return
+11 -23
View File
@@ -143,9 +143,11 @@ class Dispatcher:
max_off_policy_steps: int,
run_id: str,
run_name: str | None,
policy_weights_change: bool = True,
on_episode_complete: Callable[[int], None] | None = None,
) -> None:
self.policy = policy
self.policy_weights_change = policy_weights_change
self.progress = progress
self.train_envs = train_envs
self.eval_envs = eval_envs
@@ -214,10 +216,10 @@ class Dispatcher:
"""``(clients, model_name, is_live)`` for *train* rollouts of this env —
eval always uses the policy."""
assert self.train_envs is not None # train groups only exist when train is configured
source = self.train_envs.get(env_name).generation_source
if source.uses_live_policy:
return source.clients, self.policy.model_name, True
return source.clients, source.clients.model_name, False
env = self.train_envs.get(env_name)
if env.uses_live_policy:
return env.clients, self.policy.model_name, True
return env.clients, env.clients.model_name, False
@property
def inflight_train_count(self) -> int:
@@ -316,7 +318,7 @@ class Dispatcher:
return [
(self.progress.step - 1) - meta.policy_version
for meta in self.inflight.values()
if meta.kind == "train" and self.train_envs.get(meta.env_name).generation_source.uses_live_policy
if meta.kind == "train" and self.train_envs.get(meta.env_name).uses_live_policy
]
# ── lifecycle ──────────────────────────────────────────────────────────
@@ -423,7 +425,7 @@ class Dispatcher:
gid
for gid, group in self.groups.items()
if group.kind == "train"
and self.train_envs.get(group.env_name).generation_source.uses_live_policy
and self.train_envs.get(group.env_name).uses_live_policy
and group.policy_version_at_start < min_version
]
cancelled = 0
@@ -556,10 +558,8 @@ class Dispatcher:
if env_collection is None:
return False
env = env_collection.get(group.env_name)
# Frozen-sourced train rollouts hit a frozen pool; salting per policy
# version would invalidate its prefix cache every weight update for
# no reason.
if live_sourced:
# Only endpoints receiving policy weight updates need a cache salt.
if live_sourced and self.policy_weights_change:
cache_salt = str(group.policy_version_at_start)
else:
cache_salt = None
@@ -665,10 +665,6 @@ class Dispatcher:
)
return
if not episode.traces and episode.ok:
episode.ok = False
episode.errors.append(vf.Error(type="EmptyEpisode", message="Episode returned with no traces"))
for trace in episode.traces:
if trace.is_timeout and not trace.has_error and meta.kind == "train":
# Training keeps a timed-out rollout out of the batch: an error,
@@ -676,14 +672,6 @@ class Dispatcher:
trace.errors.append(vf.Error(type="Timeout", message=f"Trace stopped by {trace.stop_condition}"))
trace.ok = False
episode.ok = False
if not trace.has_error and not trace.is_timeout and trace.num_turns == 0:
# Empty trajectory: promote to an explicit error so the sink
# treats it like any other failure (``has_error`` reads ``ok``).
# A timed-out eval trace with no turns stays a timeout: scored, no samples.
trace.errors.append(vf.Error(type="EmptyTrajectory", message="Trace returned with no trajectory steps"))
trace.ok = False
episode.ok = False
get_logger().warning(f"Empty trajectory in group {meta.group_id} ({meta.env_name})")
if trace.has_error:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if trace.last_error is not None:
@@ -722,7 +710,7 @@ class Dispatcher:
live_policy = meta.kind == "eval"
if meta.kind == "train":
assert self.train_envs is not None
live_policy = self.train_envs.get(meta.env_name).generation_source.uses_live_policy
live_policy = self.train_envs.get(meta.env_name).uses_live_policy
policy = vf.PolicySpan(start=policy_version, end=self.policy.version) if live_policy else None
work: vf.WorkInfo = (
vf.EvalWorkInfo(step=meta.step, policy=policy)
+34 -11
View File
@@ -26,11 +26,13 @@ from pathlib import Path
from typing import Generic, TypeVar
import verifiers.v1 as vf
from renderers import RendererConfig
from verifiers.v1.serve import EnvClient
from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
from prime_rl.orchestrator.generation_source import GenerationSource
from prime_rl.orchestrator.clients import InferenceClient, connect_frozen_client
from prime_rl.utils.logger import format_time, get_logger
from prime_rl.utils.pathing import env_address_file
@@ -150,17 +152,38 @@ class TrainEnv(Env):
config: TrainSourceConfig,
address: str | None,
address_file: Path,
generation_source: GenerationSource,
clients: InferenceClient,
renderer_config: RendererConfig | None,
algorithm: Algorithm,
):
super().__init__(config, address, address_file)
self.generation_source = generation_source
# Train rollouts are generated from `clients`: the policy, or the frozen
# `sampling.source` connected in setup() with the renderer (token-in/out) client.
self.clients = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None
self.algorithm = algorithm
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
self.uses_live_policy = config.algo.sampling.source == "policy"
self.sampling_args = config.sampling.to_sampling_args()
if not self.uses_live_policy:
# Logprobs only feed importance ratios on policy-sampled tokens; frozen endpoints may reject the knob.
self.sampling_args.pop("logprobs", None)
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = (
config.sampling.truncates_distribution() and config.algo.sampling.source == "policy"
)
self.requires_sampling_masks = config.sampling.truncates_distribution() and self.uses_live_policy
async def setup(self) -> None:
async def connect_source() -> None:
source = self.config.algo.sampling.source
if isinstance(source, FrozenModelConfig):
self.connected = await connect_frozen_client(source, renderer_config=self.renderer_config)
self.clients = self.connected
await asyncio.gather(connect_source(), self.algorithm.setup())
async def aclose(self) -> None:
for clients in (self.connected, self.algorithm.connected):
if clients is not None:
await clients.aclose()
class EvalEnv(Env):
@@ -218,9 +241,8 @@ class Envs(Generic[EnvT]):
class TrainEnvs(Envs[TrainEnv]):
"""Collection of training environments, each paired with its
:class:`GenerationSource` and runtime :class:`Algorithm`, built from the env's
resolved algorithm config."""
"""Collection of training environments, each with its runtime
:class:`Algorithm`, built from the env's resolved algorithm config."""
def __init__(
self,
@@ -238,7 +260,8 @@ class TrainEnvs(Envs[TrainEnv]):
config,
addresses[("train", config.resolved_name)],
env_address_file(config_dir, "train", config.resolved_name),
GenerationSource(config.algo.sampling, clients, renderer_config),
clients,
renderer_config,
build_algorithm(config.algo, clients),
)
self._envs[env.name] = env
@@ -1,49 +0,0 @@
"""Resolve the model source used to generate an env's train episodes."""
from __future__ import annotations
from typing import TYPE_CHECKING
from prime_rl.configs.algorithm import FrozenModelConfig, SamplingConfig
from prime_rl.orchestrator.algo import connect_frozen_client
if TYPE_CHECKING:
from renderers import RendererConfig
from prime_rl.orchestrator.clients import InferenceClient
class GenerationSource:
"""One env's generation model and inference clients.
``clients`` is what train rollouts are generated from: the policy clients,
swapped for a connected frozen endpoint in :meth:`setup` when the source is
an inline frozen model. A frozen source *generates* rollouts, so it uses
the renderer (token-in/out) client (built from ``renderer_config``) — the
rollout must carry tokens for training."""
def __init__(self, config: SamplingConfig, clients: InferenceClient, renderer_config: RendererConfig | None = None):
assert config.source is not None, "sampling.source must be resolved by config validation"
self.config = config
self.clients: InferenceClient = clients
self.renderer_config = renderer_config
self.connected: InferenceClient | None = None # frozen clients connected in setup(); closed at shutdown
async def setup(self) -> None:
"""Connect clients to a frozen generation source and wait for
readiness. Must run before dispatching."""
if isinstance(self.config.source, FrozenModelConfig):
self.clients = await connect_frozen_client(self.config.source, renderer_config=self.renderer_config)
self.connected = self.clients
@property
def uses_live_policy(self) -> bool:
return self.config.source == "policy"
def sampling_args(self, args: dict) -> dict:
"""Source-specific sampling-arg overrides. Sampling logprobs are only
needed for importance ratios on policy-sampled tokens — frozen
endpoints may reject the knob."""
if not self.uses_live_policy:
args.pop("logprobs", None)
return args
+3 -8
View File
@@ -282,10 +282,7 @@ class Orchestrator:
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
await asyncio.gather(
*(env.generation_source.setup() for env in self.train_envs),
*(env.algorithm.setup() for env in self.train_envs),
)
await asyncio.gather(*(env.setup() for env in self.train_envs))
get_logger().info(f"Initializing weight broadcast ({config.weight_broadcast})")
t0 = time.perf_counter()
@@ -1024,11 +1021,9 @@ class Orchestrator:
if self.admin_plane is not None:
await self.admin_plane.aclose()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm clients")
get_logger().debug("Stopping train env clients")
for env in self.train_envs:
for clients in (env.generation_source.connected, env.algorithm.connected):
if clients is not None:
await clients.aclose()
await env.aclose()
get_logger().info("Stopping orchestrator components")
t0 = time.perf_counter()
-39
View File
@@ -1,39 +0,0 @@
import torch
from torch import Tensor
def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
"""Quantize a 2D tensor to FP8 e4m3 with per-block scales."""
if weight.ndim != 2:
raise ValueError(f"FP8 quantization expects a 2D tensor, got shape={tuple(weight.shape)}")
rows, cols = weight.shape
pad_rows = (block_size - rows % block_size) % block_size
pad_cols = (block_size - cols % block_size) % block_size
if pad_rows or pad_cols:
padded = torch.zeros(
rows + pad_rows,
cols + pad_cols,
dtype=weight.dtype,
device=weight.device,
)
padded[:rows, :cols] = weight
else:
padded = weight.contiguous()
padded_rows, padded_cols = padded.shape
blocks = padded.view(
padded_rows // block_size,
block_size,
padded_cols // block_size,
block_size,
).permute(0, 2, 1, 3)
fp8_max = torch.finfo(torch.float8_e4m3fn).max
max_abs = blocks.float().abs().amax(dim=(2, 3))
scales = (max_abs / fp8_max).clamp(min=1e-12)
blocks_fp8 = (blocks.float() / scales[:, :, None, None]).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
return quantized, scales.float().contiguous()
@@ -1,3 +0,0 @@
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
__all__ = ["RMSNorm", "RMSNormConfig"]
+24 -2
View File
@@ -1,5 +1,5 @@
from pathlib import Path
from typing import TypedDict
from typing import Any, NotRequired, TypedDict
import numpy as np
import torch
@@ -7,6 +7,8 @@ from jaxtyping import Bool, Float, Int
from torch import Tensor
from prime_rl.configs.trainer import FakeDataLoaderConfig
from prime_rl.multimodal import ForwardPolicy, MultimodalAdapter
from prime_rl.trainer.multimodal import materialize_mm_refs
from prime_rl.trainer.world import get_world
from prime_rl.transports.batch import (
BatchReceiver,
@@ -47,8 +49,11 @@ class TensorMicroBatch(TypedDict):
# maximum mask size. A row containing only -1 has no mask.
sampling_mask: Int[Tensor, "batch seq mask"] | None
# Materialized immediately before this microbatch's forward pass.
# Multimodal inputs. The data loader sets mm_refs (undecoded image references), and prepare_micro_batch
# replaces them with mm_kwargs (CPU tensors for the vision encoder) and mm_forward_policy.
mm_refs: MMRefs | None
mm_kwargs: NotRequired[dict[str, Tensor] | None]
mm_forward_policy: NotRequired[ForwardPolicy | None]
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: Int[Tensor, "batch seq"] | None
@@ -172,6 +177,23 @@ class FakeDataLoader:
}
def prepare_micro_batch(
micro_batch: TensorMicroBatch, processor: Any | None, mm_adapter: MultimodalAdapter | None
) -> TensorMicroBatch:
"""Prepare a micro batch for the training loop. Currently only multimodal samples need preparation."""
micro_batch["mm_kwargs"] = None
micro_batch["mm_forward_policy"] = None
mm_refs = micro_batch.get("mm_refs")
if mm_refs is not None:
if processor is None or mm_adapter is None:
raise ValueError("Received multimodal samples but [model.vlm] is not set")
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
micro_batch["mm_kwargs"] = materialized.kwargs
micro_batch["mm_forward_policy"] = materialized.forward_policy
micro_batch["mm_refs"] = None
return micro_batch
class DataLoader:
"""Receives packed micro batches from the orchestrator, one stream per DP rank."""
+11 -14
View File
@@ -1,6 +1,7 @@
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before import
from contextlib import nullcontext
from functools import partial
import time
import asyncio
from datetime import timedelta
@@ -17,7 +18,7 @@ from prime_rl.trainer.ckpt import Progress, setup_ckpt_manager
from prime_rl.trainer.optim import setup_optimizer
from prime_rl.trainer.scheduler import setup_scheduler
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader
from prime_rl.trainer.rl.data import DataLoader, FakeDataLoader, prepare_micro_batch
from prime_rl.utils.cp import (
gather_for_cp,
gather_for_cp_wo_grad,
@@ -37,7 +38,6 @@ from prime_rl.trainer.rl.loss import (
shift_tensor_right,
)
from prime_rl.multimodal import get_multimodal_adapter
from prime_rl.trainer.multimodal import materialize_mm_refs
from prime_rl.trainer.rl.annotations import AnnotationWriter
from prime_rl.trainer.model import (
forward,
@@ -71,6 +71,7 @@ from prime_rl.utils.heartbeat import Heartbeat
from prime_rl import monitors
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
from prime_rl.utils.worker_pool import WorkerPool
from prime_rl.utils.pathing import resolve_latest_ckpt_step
from prime_rl.utils.utils import clean_exit
@@ -147,6 +148,8 @@ def train(config: TrainerConfig):
if processor is None:
raise ValueError("Multimodal training requires a model image processor")
mm_adapter = get_multimodal_adapter(model.config.model_type)
prepare = partial(prepare_micro_batch, processor=processor, mm_adapter=mm_adapter)
micro_batch_workers = WorkerPool(config.data.num_workers)
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
raise ValueError("Packed multimodal training requires model support")
@@ -336,7 +339,7 @@ def train(config: TrainerConfig):
cp_size = parallel_dims.cp
step_tokens_per_expert = 0
for micro_step, micro_batch in enumerate(micro_batches):
for micro_step, micro_batch in enumerate(micro_batch_workers(prepare, micro_batches)):
input_ids = micro_batch["input_ids"].to("cuda")
position_ids = micro_batch["position_ids"].to("cuda")
advantages = micro_batch["advantages"].to("cuda")
@@ -365,17 +368,10 @@ def train(config: TrainerConfig):
micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] is not None else None
)
mm_kwargs = None
mm_forward_policy = None
mm_refs = micro_batch.get("mm_refs")
if mm_refs is not None:
if processor is None or mm_adapter is None:
raise ValueError("Received multimodal samples but [model.vlm] is not set")
materialized = materialize_mm_refs(mm_refs, processor, mm_adapter)
mm_kwargs = {key: value.to("cuda") for key, value in materialized.kwargs.items()}
mm_forward_policy = materialized.forward_policy
micro_batch["mm_refs"] = None
del materialized, mm_refs
mm_kwargs = micro_batch.pop("mm_kwargs")
if mm_kwargs is not None:
mm_kwargs = {key: value.to("cuda") for key, value in mm_kwargs.items()}
mm_forward_policy = micro_batch.pop("mm_forward_policy")
mm_token_type_ids = (
micro_batch["mm_token_type_ids"].to("cuda")
if micro_batch.get("mm_token_type_ids") is not None
@@ -732,6 +728,7 @@ def train(config: TrainerConfig):
if gradient_manager is not None:
gradient_manager.close()
micro_batch_workers.close()
logger.info(f"Peak memory: {max_peak_memory:.1f} GiB")
logger.success("RL trainer finished")
+2
View File
@@ -22,6 +22,8 @@ DEFAULT_COMMON_ENV_VARS: dict[str, str] = {
"PYTHONUNBUFFERED": "1",
"OMP_NUM_THREADS": "1",
"GIT_LFS_SKIP_SMUDGE": "1",
# Processes sharing ~/.triton on a shared FS hang or crash. Per-user because /tmp is shared by all users.
"TRITON_CACHE_DIR": f"/tmp/triton-{os.getuid()}",
}
DEFAULT_TRAINER_ENV_VARS: dict[str, str] = {
+55
View File
@@ -0,0 +1,55 @@
from collections import deque
from collections.abc import Callable, Iterable, Iterator
from concurrent.futures import Future, ThreadPoolExecutor
from typing import TypeVar
T = TypeVar("T")
R = TypeVar("R")
class WorkerPool:
"""Persistent background threads that map a function over an iterator in order, or the calling thread when ``num_workers`` is 0.
``map_fn`` runs concurrently on up to ``num_workers`` threads, so it must be thread-safe.
"""
def __init__(self, num_workers: int):
self.num_workers = num_workers
self.executor: ThreadPoolExecutor | None = None
if num_workers > 0:
# Threads share the trainer's memory, so items and results pass by reference: no pickling,
# no /dev/shm copies, and no forked copy-on-write memory, unlike worker processes.
self.executor = ThreadPoolExecutor(max_workers=num_workers, thread_name_prefix="worker-pool")
def __call__(self, map_fn: Callable[[T], R], items: Iterable[T]) -> Iterator[R]:
"""Yield ``map_fn(item)`` in input order, with at most ``2 * num_workers`` items submitted but not yet yielded.
The factor 2 plays the role of torch DataLoader's ``prefetch_factor`` (batches loaded ahead per worker),
hard-coded to its torch default for simplicity. Any bound above ``num_workers`` keeps every worker busy while
the caller holds a result; the extra slack absorbs items that take unusually long.
"""
if self.executor is None:
yield from map(map_fn, items)
return
max_in_flight = 2 * self.num_workers
pending: deque[Future[R]] = deque()
try:
for item in items:
pending.append(self.executor.submit(map_fn, item))
if len(pending) >= max_in_flight:
yield pending.popleft().result()
while pending:
yield pending.popleft().result()
finally:
for future in pending:
future.cancel()
def close(self) -> None:
if self.executor is not None:
self.executor.shutdown(cancel_futures=True)
def __enter__(self) -> "WorkerPool":
return self
def __exit__(self, *exc_info: object) -> None:
self.close()
+17 -2
View File
@@ -42,7 +42,7 @@ def make_rollout(
)
]
if advantages is not None
else []
else [vf.MessageNode(message=vf.AssistantMessage(content="answer"), sampled=True)]
)
trace = vf.Trace(
task=vf.TraceTask(
@@ -111,7 +111,9 @@ def test_train_source_composes_sampler_and_all_gates_with_state_and_metrics() ->
source = TrainSource([env])
sampled = source.next_task(step=1).task
assert source.on_result(make_rollout(sampled, reward=0.25, advantages=[0.0])) is False
empty = make_rollout(sampled, reward=1.0)
empty[0].traces[0].nodes[0].sampled = False
assert source.on_result(make_rollout(sampled, reward=0.25, advantages=[0.0]) + empty) is False
assert source.metrics() == {
"curriculum/test/admission_rate": 0.0,
"curriculum/test/sampler/pool/unseen": 2.0,
@@ -127,6 +129,19 @@ def test_train_source_composes_sampler_and_all_gates_with_state_and_metrics() ->
"admit": {},
}
assert source.on_result(empty) is False
assert source.metrics()["curriculum/test/admission_rate"] == 0.0
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.25}
# A scored rollout without token metadata still informs task difficulty.
assert source.on_result(make_rollout(sampled, reward=0.5)) is False
assert source.metrics()["curriculum/test/admission_rate"] == 0.0
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.5}
assert source.on_result(make_rollout(sampled, reward=0.75, advantages=[1.0])) is True
assert source.metrics()["curriculum/test/admission_rate"] == 1.0
assert source.curricula["test"].sampler.task_rewards == {sampled.key: 0.75}
def test_difficulty_pools_stack_with_advantage_gate_and_resume_sampling() -> None:
tasks = [make_task(i) for i in range(3)]
+21
View File
@@ -604,10 +604,31 @@ def test_single_node_auto_inference_ports_follow_server_port():
assert config.inference is not None
assert config.inference.vllm.data_parallel_size == 2
assert config.trainer.weight_broadcast.inference_world_size == 2
assert config.orchestrator.weight_broadcast.inference_world_size == 2
assert config.inference.backend_port == 8101
assert config.orchestrator.model.client.admin_base_url == ["http://localhost:8101/v1"]
def test_single_node_nccl_resolved_json_roundtrips(tmp_path):
"""The resolved rl.json re-parses (as a SLURM launch does) to the same config."""
import json
config = RLConfig.model_validate(
{
"trainer": {},
"orchestrator": {},
"inference": {"vllm": {"tensor_parallel_size": 1}},
"deployment": {"type": "single_node", "gpus_per_node": 4, "num_train_gpus": 2, "num_infer_gpus": 2},
}
)
path = tmp_path / "rl.json"
path.write_text(json.dumps(dump_resolved_config(config, exclude={"slurm", "dry_run", "clean"})))
reloaded = cli(RLConfig, args=["@", str(path)])
assert reloaded.trainer.weight_broadcast.inference_world_size == 2
assert reloaded == config
def test_multi_node_auto_inference_parallelism():
config = RLConfig.model_validate(
{
+46
View File
@@ -0,0 +1,46 @@
import itertools
import time
import pytest
from prime_rl.utils.worker_pool import WorkerPool
def _slowest_first(item: int) -> int:
time.sleep(0.05 / (item + 1))
return item
def _fail_on_two(item: int) -> int:
if item == 2:
raise KeyError(item)
return item
@pytest.mark.parametrize("num_workers", [0, 2])
def test_worker_pool_preserves_order(num_workers: int):
with WorkerPool(num_workers) as workers:
assert list(workers(_slowest_first, range(6))) == list(range(6))
@pytest.mark.parametrize("num_workers", [0, 2])
def test_worker_pool_propagates_worker_exception(num_workers: int):
with WorkerPool(num_workers) as workers, pytest.raises(KeyError):
list(workers(_fail_on_two, range(4)))
@pytest.mark.parametrize("num_workers", [0, 2])
def test_worker_pool_reads_input_lazily(num_workers: int):
pulled = []
def source():
for item in itertools.count():
pulled.append(item)
yield item
consumed = 4
with WorkerPool(num_workers) as workers:
assert list(itertools.islice(workers(lambda item: item, source()), consumed)) == list(range(consumed))
max_in_flight = 2 * num_workers
assert len(pulled) == (consumed + max_in_flight - 1 if num_workers else consumed)
+29 -2
View File
@@ -20,8 +20,8 @@ from pathlib import Path
import torch
from safetensors import safe_open
from safetensors.torch import save_file
from prime_rl.trainer.models.fp8 import quantize_to_fp8_blockwise
from torch import Tensor
from torch.nn import functional as F
# Module-name substrings that stay unquantized: norms, embeddings, output head,
# MoE router gates, GatedDeltaNet low-rank projections, MTP/indexer projections,
@@ -41,6 +41,33 @@ SKIP_SUBSTRINGS = (
)
def quantize_to_fp8_blockwise(weight: Tensor, block_size: int = 128) -> tuple[Tensor, Tensor]:
"""Quantize a 2D tensor to FP8 e4m3 with per-block scales."""
if weight.ndim != 2:
raise ValueError(f"FP8 quantization expects a 2D tensor, got shape={tuple(weight.shape)}")
rows, cols = weight.shape
pad_rows = (block_size - rows % block_size) % block_size
pad_cols = (block_size - cols % block_size) % block_size
padded = F.pad(weight, (0, pad_cols, 0, pad_rows)).contiguous()
padded_rows, padded_cols = padded.shape
blocks = padded.view(
padded_rows // block_size,
block_size,
padded_cols // block_size,
block_size,
).permute(0, 2, 1, 3)
fp8_max = torch.finfo(torch.float8_e4m3fn).max
max_abs = blocks.float().abs().amax(dim=(2, 3))
scales = (max_abs / fp8_max).clamp(min=1e-12)
blocks_fp8 = (blocks.float() / scales[:, :, None, None]).clamp(-fp8_max, fp8_max).to(torch.float8_e4m3fn)
quantized = blocks_fp8.permute(0, 2, 1, 3).reshape(padded_rows, padded_cols)[:rows, :cols].contiguous()
return quantized, scales.float().contiguous()
def should_quantize(name: str, tensor: torch.Tensor) -> bool:
return (
name.endswith(".weight")
Generated
+50 -11
View File
@@ -113,12 +113,14 @@ members = [
"pi-programbench",
"pi-swe-sweep",
"pi-terminal-bench-2",
"pi-terminalbench2-1",
"pinchbench",
"prime-rl",
"prolog",
"proofnet",
"proposer-solver",
"proverbench",
"ptx-remote",
"putnambench",
"r2e-gym",
"recursive-task-synthesis",
@@ -4719,7 +4721,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2
[[package]]
name = "pi-officeqa-pro-v2"
version = "0.1.4"
version = "0.1.5"
source = { editable = "deps/prime-envs/environments/search/pi_officeqa_pro_v2" }
dependencies = [
{ name = "verifiers" },
@@ -4741,7 +4743,7 @@ requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2
[[package]]
name = "pi-swe-sweep"
version = "0.1.0"
version = "0.1.1"
source = { editable = "deps/prime-envs/environments/swe/pi_swe_sweep" }
dependencies = [
{ name = "verifiers", extra = ["harbor"] },
@@ -4761,6 +4763,17 @@ dependencies = [
[package.metadata]
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.1" }]
[[package]]
name = "pi-terminalbench2-1"
version = "0.2.2"
source = { editable = "deps/prime-envs/environments/terminal/pi_terminalbench2_1" }
dependencies = [
{ name = "verifiers", extra = ["harbor"] },
]
[package.metadata]
requires-dist = [{ name = "verifiers", extras = ["harbor"], specifier = ">=0.3.2.dev162" }]
[[package]]
name = "pillow"
version = "12.3.0"
@@ -5264,7 +5277,7 @@ train = [
[[package]]
name = "prime-sandboxes"
version = "0.4.1"
version = "0.4.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiofiles" },
@@ -5276,9 +5289,9 @@ dependencies = [
{ name = "pyqwest" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/66/31/5ad18141756a8cdbff89061426cbb8816aafb513de935caa8e8f875c8819/prime_sandboxes-0.4.1.tar.gz", hash = "sha256:53f7577dc9070e3b8e30db360f9e3cce3bcc35f8765b26f24f64dbc3c7763b06", size = 134242, upload-time = "2026-10-01T01:58:55.117Z" }
sdist = { url = "https://files.pythonhosted.org/packages/d8/1b/01e02c9d2346956f5ed77d269f836905a017ad796a4b4c719debd8942dc4/prime_sandboxes-0.4.3.tar.gz", hash = "sha256:a2169182f74307485c73f897e224c978eba3276133ddb40715be4d346594c487", size = 140588, upload-time = "2026-10-08T00:24:03.668Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/af/c9/72067996420188928a6d5e05af46d60530edf24d78ca2d5bbf9fcef247cf/prime_sandboxes-0.4.1-py3-none-any.whl", hash = "sha256:1a1bb96afacc66d690815be82c0b7af180ea141421b7d180b4a0adbada4f38f0", size = 72136, upload-time = "2026-10-01T01:58:53.63Z" },
{ url = "https://files.pythonhosted.org/packages/e1/5f/d0b5cd1dabdb6e5cb1ab5d84c8ba9a96e2a9a0be8913ec9db9177c9645fb/prime_sandboxes-0.4.3-py3-none-any.whl", hash = "sha256:dd26007838c25b5d38a8b7af0514c07027b783406c0ea5b9fcf0eb74a45139bd", size = 75515, upload-time = "2026-10-08T00:24:02.208Z" },
]
[[package]]
@@ -5296,16 +5309,16 @@ wheels = [
[[package]]
name = "prime-tunnel"
version = "0.1.11"
version = "0.1.12"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
{ name = "pydantic" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/de/c7/55c21d8e1abfb66d3a0dc0e25b89abb506b0a49605fb4b0040590af82136/prime_tunnel-0.1.11.tar.gz", hash = "sha256:cd93e78824ef824b45e636f5f506898bc7f9a6c913fd5095ab1df2233a49b949", size = 15889, upload-time = "2026-09-04T17:09:25.258Z" }
sdist = { url = "https://files.pythonhosted.org/packages/9e/8b/b819661ea7dcfff21e4e000d7dfa799bc8107e2659cd5e0d961ecea08235/prime_tunnel-0.1.12.tar.gz", hash = "sha256:157c77cd15a16d091dba4b2df228a6b7e997ed1a3c5bc5f2c51ee989a31602e1", size = 16900, upload-time = "2026-10-04T20:33:47.617Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d0/7f/6ea38563db9414ed208758de6e8dc557b20e245787e42568f89531fc6717/prime_tunnel-0.1.11-py3-none-any.whl", hash = "sha256:19c5e02e389e5e61fff1507f07c46db9b05ad01424ff3b6a0cbe66187c957f61", size = 16676, upload-time = "2026-09-04T17:09:24.157Z" },
{ url = "https://files.pythonhosted.org/packages/cb/6a/b368c2cececc589bb8b13bf3c9cc819b4d29fc962d0ea9ffde005b873222/prime_tunnel-0.1.12-py3-none-any.whl", hash = "sha256:441d0a2f29c7e78a9337ee336c828fcc5ce1515c8cd12014b7d6c0b9728c355b", size = 16992, upload-time = "2026-10-04T20:33:46.17Z" },
]
[[package]]
@@ -5464,6 +5477,32 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/04/78/0acd37ca84ce3ddffaa92ef0f571e073faa6d8ff1f0559ab1272188ea2be/psutil-7.2.2-cp36-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc", size = 148266, upload-time = "2026-01-28T18:15:31.597Z" },
]
[[package]]
name = "ptx-remote"
version = "0.1.0"
source = { editable = "deps/prime-envs/environments/code/ptx_remote" }
dependencies = [
{ name = "httpx" },
{ name = "pydantic" },
{ name = "verifiers" },
]
[package.optional-dependencies]
server = [
{ name = "fastapi" },
{ name = "uvicorn" },
]
[package.metadata]
requires-dist = [
{ name = "fastapi", marker = "extra == 'server'", specifier = ">=0.115" },
{ name = "httpx", specifier = ">=0.27" },
{ name = "pydantic", specifier = ">=2" },
{ name = "uvicorn", marker = "extra == 'server'", specifier = ">=0.30" },
{ name = "verifiers", specifier = ">=0.3.2.dev150" },
]
provides-extras = ["server"]
[[package]]
name = "ptyprocess"
version = "0.7.0"
@@ -7766,9 +7805,9 @@ requires-dist = [
{ name = "openai", specifier = ">=2.54.0,<3.0.0" },
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
{ name = "prime-runs", specifier = ">=0.1.3" },
{ name = "prime-sandboxes", specifier = ">=0.4.1" },
{ name = "prime-tunnel", specifier = ">=0.1.8" },
{ name = "prime-runs", specifier = ">=0.1.4" },
{ name = "prime-sandboxes", specifier = ">=0.4.2" },
{ name = "prime-tunnel", specifier = ">=0.1.12" },
{ name = "pydantic", specifier = ">=2.12.3" },
{ name = "pyzmq", specifier = ">=27.1.0" },
{ name = "renderers", extras = ["multimodal"], specifier = ">=0.1.12.dev2" },