Compare commits

...
Author SHA1 Message Date
Konstantin DunasandGitHub 88faa6dc22 feat(sft): warn when renderer is not prefix stable (#3953)
Warn when SFT constructs a renderer that does not guarantee prefix
stability. The warning explains that each conversation is rendered once
into one training sample, that N assistant turns are not expanded into N
samples, and that earlier reasoning may be omitted by the template.
Cached renderers warn only on construction; stable renderers stay quiet.
Custom renderers without the capability are conservatively treated as
unknown.

Pin `deps/renderers` to merged main revision `41f9290`, which includes
https://github.com/PrimeIntellect-ai/renderers/pull/184. It provides the
resolved capability and the manual, opt-in witness audit. Sample
construction is unchanged.

Validation: all **73 SFT dataset tests passed**, including
stable/unstable renderer selection and cache-warning behavior. Prime-rl
unit-test CI passed on the preceding revision; this update changes only
the renderer gitlink to the merged revision. Dependency requirements are
unchanged apart from renderer Python >=3.11, compatible with prime-rl
Python 3.12. The manually invoked renderer audit passes **59 tests** and
is excluded from normal CI discovery.
2026-10-09 11:53:24 +02:00
Florian BrandandGitHub 083b8fe9ec ci: reduce GPU usage and parallelize test setup (#3944)
Reduce CI time and GPU usage by selecting the relevant test suites for
each PR, moving hosted eval to CPU, and running independent setup steps
in parallel.

- Select GPU unit tests, SFT, RL, and hosted eval from changed paths
before allocating runners. Shared runtime and dependency changes retain
broad coverage; pushes to `main` and manual runs execute the full suite.
- Keep RL/SFT coverage for checkpoint converters, dashboard code, and
the shared dashboard smoke helper.
- Run `gsm8k_eval` on `ubuntu-latest` because it uses hosted inference.
- Run public submodule initialization and `uv` setup concurrently, then
wait for both before installing dependencies. Keep dependency caching
keyed on `uv.lock` and the five-job limit on GPU integration tests.
- Cancel superseded CPU and style runs on the same PR.
- Give the GPU workflow read-only contents access and the test selector
PR read access.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Path-based GPU job gating can skip integration coverage on PRs if
filters miss a dependency; full suite still runs on main and manual
dispatch.
> 
> **Overview**
> **GPU CI now picks which jobs to run from the PR diff**, instead of
always running the full GPU unit + integration matrix on every non-draft
PR. A new **Select tests** job uses path filters for unit, SFT, RL, and
eval; pushes to `main` and `workflow_dispatch` still run everything.
RL/SFT integration scenarios are built dynamically (still capped at
`max-parallel: 5` on `prime-rl-2xh200`).
> 
> **`gsm8k_eval` is split out** into a dedicated job on `ubuntu-latest`
(hosted inference), so it no longer consumes GPU runners. Integration
pytest invocations use `tests/integration/test_${{ matrix.test }}.py`
from the dynamic matrix rather than per-row `pytest_args`.
> 
> **Setup and queueing tweaks:** submodule init and `setup-uv` run in
parallel in CPU/GPU jobs; CPU and style workflows cancel in-progress
runs per PR; GPU workflow gets `workflow_dispatch`, read-only
`contents`, and PR-scoped concurrency cancel. `docs/development.md`
documents the new triggers and runner split.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
20da35f30de85b2b18cf82e29598846a1228ca12. 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 17:17:55 -07:00
853208336e feat(sft): pad to a multiple of cp and remove fp8 indexer dynamism (#3948)
SFT now pads packed rows only to a multiple of cp, as RL does, instead
of to `seq_len`. The fp8 indexer drops its autotuning, which
re-benchmarked configs on every new row length and made unpadded rows
slower than padded ones on DeepSeek-V4 (#3726).

- The indexer pads keys to a multiple of 16 and runs one fixed config,
within 1.05x of the best.
- Every rank, including RL on DeepSeek-V4 and GLM-5, runs that config
with bitwise-identical top-k.
- SFT and RL throughput count trained tokens, not `seq_len` × rows or
the first row × count.
- The SFT `seq_len % (2 * cp)` check is gone: CP only needs `seq_len %
cp`, which configs enforce.

Same samples per arm, time summed over steps 5 to 20, one H200 node:

| Workload | Padding on main | main | This PR | Speedup |
|---|---|---|---|---|
| DeepSeek-V4-Flash 6L, scaleswe, 256K rows, cp 8 | 19.8% | 61.2 s |
38.2 s | 1.60x |
| GLM-4.5-Air 8L, math, 131K rows, dp 4 cp 2 | 7.3% | 223.8 s | 200.1 s
| 1.12x |
| GLM-4.5-Air 8L, scaleswe, 131K rows, dp 4 cp 2 | 19.7% | 701.0 s |
623.0 s | 1.13x |

On DeepSeek-V4, the 1.60x exceeds the 1.25x that removing 19.8% of
tokens predicts because two effects multiply: main's token-0 pads crowd
onto the same experts, and the padding itself costs compute. The
DeepSeek-V4 ablation section below separates the two.

On GLM with scaleswe, removing 19.7% of the tokens would predict about
1.25x, but it measured 1.13x. Its 4 data-parallel ranks now get rows of
different lengths, and each step likely waits for the rank with the
longest rows.

Loss matches main to within 1e-3 per step. This overlaps
https://github.com/PrimeIntellect-ai/prime-rl/pull/3932 in
`CatDataset._finalize_pack`. Harness:
[`benchmarks/scripts/sft_pad_to_cp/`](https://github.com/PrimeIntellect-ai/prime-rl/tree/0ed0e78b33e8533d7fd1e0d603759dc2ab50e5dd/benchmarks/scripts/sft_pad_to_cp)
(removed before merge).

## DeepSeek-V4 ablation

Each row changes one thing on the DeepSeek-V4 workload above, to
separate the cost of the padding length, of token-0 pads crowding onto
the same experts, and of indexer re-tuning:

| Arm | Time | Speedup vs main |
|---|---|---|
| main: pads every row to `seq_len` with token 0 | 61.2 s | 1.00x |
| main, but pads with the row's own tokens (#3932) | 49.6 s | 1.23x |
| pads only to a multiple of cp, indexer still autotuned | 73.6 s |
0.83x |
| pads only to a multiple of cp, fixed-config indexer (this PR) | 38.2 s
| **1.60x** |

## Alternatives considered

- Bucketing the autotune key on `next_power_of_2(S_q)` reached 1.47x on
DeepSeek-V4. Each bucket kept its first row's config (up to 1.44x slower
later), short rows paid extra tunes, and each rank still tuned on its
own rows, so ranks could run different kernels.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 19:13:22 -04:00
Konstantin DunasandGitHub 31281d88f9 feat(sft): pass per-message loss selection to renderers (#3950)
SFT samples can contain prefilled assistant turns that must remain in
context without becoming training targets. Read an optional
`message_loss_mask` dataset column and pass it directly to
`renderers.build_training_sample`; for a user/assistant/user/assistant
conversation, `[0, 0, 0, 1]` trains only the final assistant turn.

The renderer owns token attribution and mask validation, including GLM's
assistant-generated closing markers. prime-rl performs no owner walking
or template-specific mask reconstruction. Selection only removes
existing loss targets and preserves input/target token IDs. Missing or
null masks preserve normal supervision; fully masked samples follow the
existing skip behavior.

`data.columns.message_loss_mask` supports renamed columns. For
prompt/completion rows, the mask covers their concatenated message list.
This API reads a separate column; datasets with inline
`messages[].trainable_mask` need conversion before use.

Pins `deps/renderers` to upstream main commit
`e3ace557545274385abb30435975c134c7c2429d`, which merges
https://github.com/PrimeIntellect-ai/renderers/pull/181. The renderer
dependency is now merged.

Validation:
- Signed pin update `838828713` points to the merged renderer commit.
Its Git tree is identical to the previously tested renderer head; no
source changes accompany the pin update.
- The following tests and checks passed on signed implementation commit
`7e0800051`:
- 73 SFT dataset tests passed, including real GLM-5 and Qwen3
tokenizers, both dataset layouts, custom column names,
missing/null/all-enabled masks, excluded initial/final turns, fully
masked samples, and invalid values/lengths.
- Ruff 0.13.0 lint and formatting checks passed for the changed Python
files; `git diff --check` passed.
- CPU tests ran in an isolated Python 3.12 environment with Transformers
5.6.2 and PyTorch 2.14.1. No GPU training run performed.
- Commit signature verified locally.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes which tokens receive loss during SFT when datasets supply
masks; incorrect masks could silently train the wrong turns, though
behavior is opt-in and heavily tested against real renderers.
> 
> **Overview**
> Adds **optional per-message SFT loss selection** via a dataset
`message_loss_mask` column (0/1 or booleans, one entry per resolved
message—including prompt+completion rows). The trainer forwards the
column to `build_training_sample` so renderers drop supervision on
excluded turns **without changing token IDs** (e.g. `[0, 0, 0, 1]` keeps
context but trains only the last assistant reply). Missing/null masks
behave as today; all-zero masks still skip the sample.
> 
> **Config and docs:** `SFTColumnsConfig.message_loss_mask` defaults to
`"message_loss_mask"` and can be remapped (e.g. `"selection"`); dataset
init errors if a remap points at a missing column. `docs/training.md`
documents the format and semantics.
> 
> **Tests:** Coverage for GLM-5 and Qwen3, both dataset layouts, custom
column names, partial masks, fully masked rows, and invalid mask
values/lengths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
838828713529afa49a57cf441071f946ec195cdf. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-09 00:36:22 +02:00
samsjaandGitHub bc250759bf fix(ci): uv cache on h200 runners, drop phantom 4xa6000 job, cap fan-out (#3909)
## Why

Since **Sep 2** the `4xa6000` runner has been offline. Since then,
`benchmark_regression` has queued on a dead label on **every single GPU
Tests run**, hit GitHub's 24h self-hosted queue timeout, and failed the
workflow. There has not been one green GPU Tests run in over a month, so
the per-PR GPU check is permanently red and real regressions hide in the
noise. Measured over Sep 29-Oct 6: all 28 completed runs failed at
exactly 1440 +/- 1 min, and 20+ phantom `benchmark_regression` jobs were
sitting in the queue at any time.

## What changes

1. **uv cache on the GPU jobs** (`enable-cache: true`, keyed on
`uv.lock`, mirroring `cpu_tests.yaml`) — each h200 pod currently
re-resolves and re-downloads the full dependency set from PyPI on every
job.
2. **`benchmark_regression` removed from the PR matrix.** It cannot
simply move to `prime-rl-2xh200`: the test unconditionally runs a 1-GPU
**and** a 4-GPU benchmark (a 2-GPU pod cannot host the latter), and it
asserts against A6000-captured baselines with a 15% tolerance (H200
results would blow through it). It belongs on benchmark hardware
(`benchmarks.yaml`) or behind a 4-GPU scale set when one exists — happy
to re-add once either exists.
3. **`max-parallel: 5` on the integration matrix** — a concrete per-PR
ceiling:
- 9 integration jobs + unit-tests = **6 h200 pods peak per PR**, 2 waves
- at current job durations (~10-15 min each) a PR finishes in ~25-35 min
- with 2-3 PRs in flight: <= ~18 pods steady-state; the ARC scale set
`maxRunners` (suggest 16-20) is the complementary global cap
4. `docs/development.md` CI table updated to match (also adds
`gsm8k_eval`, which was missing, and the current runner).

## Result

GPU Tests runs **only** on the `prime-rl-2xh200` scale set, and every PR
gets a real green or red within ~30-60 min instead of a guaranteed 24h
failure.

## Not in this PR (follow-ups)

- Bake git/uv into the CI image to kill the per-job `apt-get install
git`
- PVC-backed `~/.cache/uv` mount to avoid per-pod cache archive
downloads
- Nightly Tests still target a `research-cluster` runner that does not
exist — needs the same treatment or a cron disable

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> CI workflow and documentation only; no runtime or auth changes.
Benchmark regression no longer runs on every PR until re-homed to
suitable hardware.
> 
> **Overview**
> **GPU Tests** is adjusted so PR runs can finish on live hardware
instead of timing out on a dead runner label.
> 
> Both GPU jobs now enable **uv dependency caching** keyed on `uv.lock`
(same pattern as `cpu_tests.yaml`), cutting repeated PyPI
resolves/downloads on each H200 pod. The integration matrix **drops
`benchmark_regression`** (it targeted offline `4xa6000` hardware and
cannot run meaningfully on 2×H200), and adds **`max-parallel: 5`** so at
most five integration jobs run at once per PR. **`docs/development.md`**
updates the CI table to list the current integration scenarios
(`gsm8k_eval` included), `max-parallel`, and **`prime-rl-2xh200`** as
the runner.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8207cc05d9a731a4c5d7c561354284f1a79792d4. 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 15:18:58 -07:00
1983d8dfed chore: bump verifiers to main (#3934)
## Summary

- Bump `deps/verifiers` from `1fa2bbc42` to main `da75527ca`. This pulls
in the Harbor adapter changes from PrimeIntellect-ai/verifiers#2808:
  - Honor reward-file precedence and select named rewards explicitly.
  - Resolve separate verifier definitions by Harbor image precedence.
  - Align the adapter with Harbor 0.24.0 and reject multi-step tasks.
- Move the `harbor` upload cutoff in `[tool.uv.exclude-newer-package]`
from 2026-08-11 to 2026-10-08, which matches `deps/verifiers`. verifiers
now pins `harbor==0.24.0`, which the old cutoff excluded.
- Relock: `harbor` 0.21.0 → 0.24.0, and `semver` 3.1.0 is new.

`deps/prime-envs` is already at its main head (`89dcc7ffc`). The current
verifiers pin already has the network notice
(PrimeIntellect-ai/verifiers#2769), so this bump supersedes #3734.

## Verification

- `uv sync --all-extras --all-packages --locked` succeeds.
- `uv run pytest -m "not gpu" tests/unit`: 663 passed.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Lockfile and uv policy changes only; risk is mainly behavioral shifts
from Harbor 0.24.0 and updated verifiers Harbor adapter usage in
eval/training paths.
> 
> **Overview**
> Updates dependency resolution so **`harbor` 0.24.0** (via the
`verifiers[harbor]` pin) can install under uv’s rolling
**exclude-newer** policy by moving the bounded **`harbor` cutoff** from
`2026-08-11` to **`2026-10-08`** in `pyproject.toml`, mirrored in
`uv.lock`.
> 
> The lockfile refresh bumps **`harbor` 0.21.0 → 0.24.0**, records new
transitive deps **`jsonschema`** and **`semver`**, and aligns the
verifiers harbor extra specifier to **`==0.24.0`**. This pairs with the
verifiers main bump described in the PR (Harbor adapter alignment and
reward/verifier precedence behavior), even though those code changes
live outside this diff.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
69e62c1fc116896ce99c79dbfc454959c748cb47. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:18:33 -07:00
26681fc6c7 fix(models): pass contiguous router-replay experts to compiled layers (#3947)
On torch 2.13.0 with compile and router replay, some MoE layers silently
replay layer 0's routing instead of their own from the second training
step on. This PR calls `.contiguous()` on each layer's routed-experts
slice, which removes the bug.

Each decoder layer `l` receives `routed_experts[:, :, l]`, a view into
one shared int32 tensor with axes (batch, sequence, layer, expert slot).
When `top_k` is not a multiple of 4, that view starts at a byte offset
that is not 16-byte aligned for some layers (odd layers on DeepSeek V4,
`top_k = 6`).

Inductor copies a misaligned input into a fresh aligned buffer, which
starts at offset 0. Once automatic dynamic shapes recompile the layer,
AOTAutograd mistakenly applies that offset 0 to the original shared
tensor when it rebuilds the layer's routed-experts output. Offset 0 of
the shared tensor holds layer 0's experts. A contiguous slice is its own
aligned tensor, so Inductor never makes the copy.

- Applied to the eight models that passed the raw view. `glm4_moe`
already called `.contiguous()`.
- Fixed upstream in pytorch/pytorch#191002 (torch 2.14.0 and 2.14.1, no
2.13.x release). The copy is cheap, so it can stay after an upgrade.
- Models with `top_k = 8` (Qwen3-30B-A3B, Trinity-Mini, GLM-4.5-Air)
were unaffected.

DeepSeek V4 Flash RL probe (compile on, router replay on, lr 0),
mismatch KL mean, lower is better:

| trainer | step 1 | steps 2-10 |
|---|---|---|
| compiled, strided slice (main) | 0.0008 | 0.022-0.11 |
| compiled, contiguous slice (this PR) | 0.0009 | 0.0007-0.0025 |

With compile off, the same probe spans 0.0008-0.0032 over steps 1-10.

## Verification

A standalone torch reproducer was added in
66641b0b0b31da76082edaadd70b4f601b13a53a and removed again at the end of
this branch, so main never carries it. Run it on one CUDA device from
that commit with `TORCHINDUCTOR_FORCE_DISABLE_CACHES=1 uv run python
tools/repro_misaligned_replay_alias.py`. In earlier runs it printed `BUG
REPRODUCED` on torch 2.13.0 and was clean on the 2.14.0.dev20260809 and
2.16.0.dev20261008 nightlies.

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 17:03:55 -04:00
Florian BrandandGitHub 6b0906c900 fix(eval): preserve sibling trace verdicts when an episode fails (#3824) 2026-10-08 12:12:16 -07:00
JannikStandGitHub 5e963f027a fix(monitors): send online-eval metrics to the parent training run (#3941)
Hosted runs with online evals score real rewards but the run dashboard
shows no `eval` metric group (ENG-6573).

The dashboard's `eval` group is built from the run's own metric keys
(`eval/{env}/...`). The orchestrator's in-process evals reach it through
the train monitor, but when evals run in a process of their own (SFT
online evals) the metrics are dropped: `PrimeEvalMonitor.log_metrics`
was a deliberate no-op.

- `PrimeEvalMonitor` now attaches to the parent training run via
`$RUN_ID` and forwards each epoch's `eval/...` metrics there.
- The eval process never reports the parent run's status: the SDK's
atexit crash hook is unregistered and `finalize()` only drains the
queue. Without that, an eval process exiting while the trainer is still
going would mark the whole run failed.
- No parent attached without `$RUN_ID`, so a standalone `prime eval` is
unchanged.

Note the ticket proposes exposing `environmentshub/resolve` on the
platform's internal API instead. That's a separate gap: it silences the
`EnvironmentResolutionError` warning and would create per-epoch
Evaluation records, but it does not produce the `eval` metric group, and
it needs four more `/evaluations` routes that the internal surface also
lacks.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes how eval processes interact with the parent platform run
(metrics + SDK lifecycle hooks); mistakes could misreport run status or
drop metrics, but behavior is gated on $RUN_ID and explicitly avoids
finishing the parent.
> 
> **Overview**
> Fixes hosted runs where **SFT online evals** compute rewards but the
run dashboard never shows the **`eval`** metric group (keys like
`eval/{env}/...`).
> 
> **`PrimeEvalMonitor`** now attaches a metrics-only handle to the
parent training run when **`$RUN_ID`** is set, and **`log_metrics`**
forwards sanitized epoch aggregates there instead of being a no-op.
Standalone **`prime eval`** (no **`$RUN_ID`**) is unchanged.
> 
> Lifecycle is guarded so the eval subprocess cannot poison the parent
run: the SDK **atexit** hook on the attached parent is **unregistered**,
and **`finalize()`** only **`flush`**es the upload queue—never finishes
or reports status on the trainer’s run.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
892035628173119b14a591b2975a5b6176f4c357. 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 19:44:51 +02:00
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
41 changed files with 615 additions and 201 deletions
+14 -9
View File
@@ -6,6 +6,10 @@ on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
unit-tests:
name: Unit tests
@@ -15,15 +19,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run tests
+156 -47
View File
@@ -5,20 +5,103 @@ on:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
changes:
name: Select tests
runs-on: ubuntu-latest
if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
permissions:
pull-requests: read
outputs:
unit: ${{ github.event_name != 'pull_request' || steps.filter.outputs.unit == 'true' }}
integration: ${{ steps.matrix.outputs.tests }}
eval: ${{ github.event_name != 'pull_request' || steps.filter.outputs.eval == 'true' }}
steps:
- uses: dorny/paths-filter@v4
id: filter
if: github.event_name == 'pull_request'
with:
filters: |
unit:
- &runtime
- '.github/workflows/gpu_tests.yaml'
- '{pyproject.toml,uv.lock,.python-version,.gitmodules}'
- 'deps/**'
- 'packages/**/pyproject.toml'
- 'packages/prime-rl-configs/src/prime_rl/configs/{trainer,shared,__init__}.py'
- 'packages/prime-rl-configs/src/prime_rl/utils/**'
- 'src/prime_rl/*.py'
- 'src/prime_rl/{trainer,multimodal,transports,utils}/**'
- 'tests/{__init__.py,conftest.py,utils.py}'
- 'tests/integration/{__init__.py,conftest.py}'
- 'tests/unit/{train,inference}/**'
- 'src/prime_rl/inference/**'
sft:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{sft,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{sft,dashboard}.py'
- 'src/prime_rl/monitors/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text_sft{,_lora}.py'
- 'configs/ci/integration/reverse-text-sft{,-lora}/**'
rl:
- *runtime
- 'tools/convert_{dcp_to_bf16,dcp_to_fp8,bf16_to_fp8,fp8_to_bf16}.py'
- 'src/prime_rl/dashboard/**'
- 'tests/integration/dashboard_smoke.py'
- 'packages/prime-rl-configs/src/prime_rl/configs/{rl,orchestrator,inference,env_server,algorithm,eval,monitors}.py'
- 'src/prime_rl/entrypoints/{rl,trainer,inference,orchestrator,env_server,dashboard}.py'
- 'src/prime_rl/{inference,orchestrator,monitors}/**'
- 'src/prime_rl/eval/{online,runner}.py'
- 'tests/integration/test_reverse_text{,_lora,_moe,_rl_opd,_rl_sft}.py'
- 'tests/integration/test_alphabet_sort.py'
- 'configs/ci/integration/reverse-text{,-lora,-moe,-rl-opd,-rl-sft}/**'
- 'configs/ci/integration/alphabet_sort.toml'
eval:
- *runtime
- 'packages/prime-rl-configs/src/prime_rl/configs/{eval,orchestrator,inference,env_server,algorithm,monitors}.py'
- 'src/prime_rl/{eval,orchestrator,monitors}/**'
- 'src/prime_rl/entrypoints/{eval,env_server}.py'
- 'tests/integration/test_gsm8k_eval.py'
- 'configs/ci/integration/gsm8k-eval.toml'
- name: Build integration matrix
id: matrix
env:
# Main and manual runs retain the full suite.
RUN_ALL: ${{ github.event_name != 'pull_request' }}
SFT: ${{ steps.filter.outputs.sft || 'false' }}
RL: ${{ steps.filter.outputs.rl || 'false' }}
run: |
tests=$(jq -cn --argjson all "$RUN_ALL" --argjson sft "$SFT" --argjson rl "$RL" '[
if $all or $sft then "reverse_text_sft", "reverse_text_sft_lora" else empty end,
if $all or $rl then
"reverse_text", "reverse_text_rl_opd", "reverse_text_rl_sft",
"alphabet_sort", "reverse_text_lora", "reverse_text_moe"
else empty end
]')
echo "tests=$tests" >> "$GITHUB_OUTPUT"
unit-tests:
name: Unit tests
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 45
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.unit == 'true'
steps:
- name: Install Git
run: |
@@ -29,12 +112,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
@@ -50,46 +137,20 @@ jobs:
integration-tests:
name: Integration tests (${{ matrix.test }})
runs-on: ${{ matrix.runner }}
needs: changes
runs-on: prime-rl-2xh200
container:
image: pytorch/pytorch:2.10.0-cuda13.0-cudnn9-devel
options: --gpus all
timeout-minutes: 60
if: github.event_name == 'push' || github.event.pull_request.draft == false
if: needs.changes.outputs.integration != '[]'
strategy:
fail-fast: false
# Bound per-PR fan-out: at most 5 integration jobs at a time (plus unit-tests),
# i.e. 6 h200 pods per PR. Tune together with the ARC scale set maxRunners.
max-parallel: 5
matrix:
include:
- test: reverse_text_sft
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_sft.py"
- test: reverse_text_sft_lora
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
- test: reverse_text
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text.py"
- test: reverse_text_rl_opd
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
- test: reverse_text_rl_sft
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
- test: alphabet_sort
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_alphabet_sort.py"
- test: reverse_text_lora
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_lora.py"
- test: reverse_text_moe
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py"
- test: gsm8k_eval
runner: prime-rl-2xh200
pytest_args: "tests/integration/test_gsm8k_eval.py"
test: ${{ fromJSON(needs.changes.outputs.integration) }}
steps:
- name: Install Git
run: |
@@ -100,12 +161,16 @@ jobs:
uses: actions/checkout@v7
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
@@ -120,7 +185,7 @@ jobs:
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest -vvs ${{ matrix.pytest_args }}
run: uv run pytest -vvs tests/integration/test_${{ matrix.test }}.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
@@ -129,3 +194,47 @@ jobs:
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
eval-tests:
name: Integration tests (gsm8k_eval)
needs: changes
if: needs.changes.outputs.eval == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@v7
with:
submodules: false
- parallel:
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/prime-envs deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --all-packages --locked
- name: Run eval tests
env:
USERNAME_CI: CI_RUNNER
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
run: uv run pytest -vvs tests/integration/test_gsm8k_eval.py
- name: Upload run logs on failure
if: failure()
uses: actions/upload-artifact@v7
with:
name: gsm8k_eval-logs
path: /tmp/outputs/**/*.log
retention-days: 7
if-no-files-found: ignore
+4
View File
@@ -9,6 +9,10 @@ on:
# This will trigger the workflow for pull requests to any branch
types: [opened, synchronize, reopened]
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
ruff:
name: Ruff
+1 -1
+1 -1
+1 -1
View File
@@ -42,7 +42,7 @@ uv run pytest tests/integration/test_reverse_text.py -vvs # one specific scenar
| Workflow | Trigger | What runs | Where |
|---|---|---|---|
| [`cpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/cpu_tests.yaml) | every PR + push to `main` | `pytest tests/unit -m "not gpu"`, plus a slim-wheel install check that `prime-rl-configs` imports cleanly without heavy deps (no torch / vllm / transformers / wandb / verifiers / datasets / liger / loguru in `sys.modules`) | `ubuntu-latest` |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | every non-draft PR + push to `main` | `pytest tests/unit -m gpu`, plus a matrix of named integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `reverse_text_sft_lora`, `alphabet_sort`, `benchmark_regression`) | self-hosted GPU runners (`vm`, `4xa6000`) |
| [`gpu_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/gpu_tests.yaml) | relevant changes in non-draft PRs; full suite on push to `main` or manual dispatch | `pytest tests/unit -m gpu`, plus RL/SFT integration scenarios (`reverse_text`, `reverse_text_sft`, `reverse_text_sft_lora`, `reverse_text_lora`, `reverse_text_moe`, `reverse_text_rl_opd`, `reverse_text_rl_sft`, `alphabet_sort`) with `max-parallel: 5`; separate hosted `gsm8k_eval` job | self-hosted `prime-rl-2xh200` k8s scale set (2xH200); `ubuntu-latest` for test selection and hosted eval |
| [`nightly_tests.yaml`](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/.github/workflows/nightly_tests.yaml) | 03:00 PST daily + manual `workflow_dispatch` (single-file filter optional) | every file in `tests/nightly/`, one matrix job per file | `research-cluster` |
The GPU + Nightly workflows skip drafts — open the PR as **Draft** until you're ready to consume CI compute, then mark it ready for review to trigger the GPU matrix.
+4
View File
@@ -159,6 +159,10 @@ messages = "conversation"
tools = "schemas"
```
**Per-message loss selection.** An optional `message_loss_mask` column contains one boolean or integer 0/1 per message. For example, `[0, 0, 0, 1]` on a user/assistant/user/assistant conversation trains only the final assistant turn while retaining the full context. For prompt-completion rows, the mask covers the concatenated prompt and completion messages. Zero excludes a message; one preserves the normal role and renderer loss settings. A missing or null mask leaves those settings unchanged. The renderer applies selection without changing token IDs, including ownership of assistant closing tokens. Invalid mask lengths or entries raise an error.
To read a differently named column, set `data.columns.message_loss_mask = "selection"`.
**Tool definitions and renderer controls.** For tool-use SFT, add a `tools` column in OpenAI function-calling format. Each row's value can be either a list of dicts or a JSON-encoded string of a list.
Renderer-backed SFT reads template controls from the typed `[renderer]` config in the SFT TOML. For example:
@@ -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 = (
@@ -101,6 +101,9 @@ class SFTColumnsConfig(BaseConfig):
tools: str = "tools"
"""Column with the tool schemas in OpenAI function-calling format."""
message_loss_mask: str = "message_loss_mask"
"""Optional column of booleans or integer 0/1 flags, one per resolved message (prompt + completion for split rows). Zero excludes a message from loss; one preserves its normal supervision. Missing or null masks leave supervision unchanged."""
renderer: dict[str, str] = {"reasoning_effort": "reasoning_effort"}
"""Per-sample renderer arguments as ``renderer field = dataset column``, e.g. ``reasoning_effort = "effort"``. A row's non-null value overrides the ``[renderer]`` setting; rows and datasets without the column use it unchanged."""
@@ -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()
+2 -2
View File
@@ -225,9 +225,9 @@ requires-dist = [
]
[tool.uv.exclude-newer-package]
# verifiers pins harbor==0.21.0, published minutes inside the rolling window;
# verifiers pins harbor==0.24.0, published inside the rolling window;
# bounded cutoff mirroring the one in deps/verifiers/pyproject.toml
harbor = "2026-08-11T00:00:00Z"
harbor = "2026-10-08T00:00:00Z"
tokenspeed-mla = false
# vLLM 0.31.0 pins flashinfer-python 0.7.0.post1, published inside the rolling window
flashinfer-python = false
+45 -2
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
import atexit
import fcntl
import os
import time
@@ -251,7 +252,12 @@ class PrimeEvalMonitor(Monitor):
evaluation per env and step, opened when the epoch starts (``log_eval_plan``), fed
every episode as it lands (``log_episodes``) and finished with the epoch's aggregates
(``log_eval_epoch``), so the platform page follows the run from its first episode.
Metrics are not forwarded; the evaluation is the epoch."""
Under a managed launch ($RUN_ID) the epoch's ``eval/{env}/...`` metrics ALSO go to
the parent training run, which is what the run dashboard groups into its `eval`
section. The orchestrator's in-process evals reach it through the train monitor, but
an eval process of its own (SFT online evals) has no other way there, so without
this the run shows every metric group except the one its evals produced."""
config: PrimeEvalMonitorConfig
@@ -268,6 +274,7 @@ class PrimeEvalMonitor(Monitor):
# (env, step) -> its open evaluation; None once opening it failed, so the epoch's
# episodes do not retry the platform on every arrival
self.runs: dict[tuple[str, int], pr.Run | None] = {}
self.parent: pr.Run | None = None
self._lock = asyncio.Lock()
self.evaluation_id = os.getenv(EVAL_ID_VAR)
if self.evaluation_id and len(self.sources) != 1:
@@ -277,6 +284,7 @@ class PrimeEvalMonitor(Monitor):
)
if self.mode == "online":
self.logger.info("Streaming eval epochs to the Prime platform")
self.parent = await asyncio.to_thread(self._attach_parent)
if output_dir is not None:
# Merge, not overwrite: when the eval process shares the
# trainer's run dir (SFT online evals), the train record's
@@ -294,8 +302,39 @@ class PrimeEvalMonitor(Monitor):
else:
self.logger.info(f"Platform evaluations disabled ({pr.MODE_ENV}=disabled)")
def _attach_parent(self) -> pr.Run | None:
"""The parent training run this eval process belongs to, for metrics only.
Blocking: runs in a worker thread.
Attaching is a local handle, not a request, so a run that turns out to be
unreachable costs the eval nothing. The caller owns the run's lifecycle: we
drop the SDK's atexit crash hook, because an eval process that exits while the
trainer is still going would otherwise report the WHOLE run failed."""
run_id = os.getenv("RUN_ID")
if not run_id:
return None
run = pr.init(
kind="train",
mode=self.mode,
base_url=_base_url(),
id=run_id,
finish_timeout=FINISH_TIMEOUT,
)
atexit.unregister(run._atexit_hook) # the SDK's own unregister handle
self.logger.info(f"Logging eval metrics to parent training run {run.id}")
return run
async def log_metrics(self, metrics: dict[str, Any], step: int | None) -> None:
pass
"""An epoch's aggregates (``eval/{env}/...``) onto the parent training run.
Only there: a standalone eval has no parent, and the per-epoch evaluation
carries its own aggregates through ``log_eval_epoch``."""
if self.parent is None:
return
metrics, dropped = sanitize(metrics)
if dropped:
self.logger.warning(f"Dropping {len(dropped)} non-finite metric value(s): {', '.join(dropped[:5])}")
# A queue put that can block briefly under backpressure - off the loop.
await asyncio.to_thread(self.parent.log_metrics, metrics, step=step)
def open(self, env_name: str, step: int, expected: int | None) -> pr.Run:
"""Open the platform evaluation of one epoch. Blocking: runs in a worker thread."""
@@ -400,3 +439,7 @@ class PrimeEvalMonitor(Monitor):
await asyncio.to_thread(run.finish, status=pr.RunStatus.CANCELLED, error="interrupted")
except Exception as e:
self.logger.warning(f"Failed to close the {env_name} (Step {step}) evaluation: {type(e).__name__}: {e}")
if self.parent is not None:
# Drain only. The parent run belongs to the trainer and the platform: an
# eval process must never report its status, not even a clean completion.
await asyncio.to_thread(self.parent.flush, FINISH_TIMEOUT)
+1 -1
View File
@@ -12,7 +12,7 @@ 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 or trace.num_turns == 0:
if not episode.ok or 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
+2 -3
View File
@@ -696,11 +696,10 @@ def _distribute_group(
def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBatch:
"""
Pad a micro batch with the given padding size sample
Return the padded micro batch.
Pad a micro batch with loss-masked tokens up to the next multiple of `pad_to_multiple_of`.
Args:
micro_batch: The micro batch to pad.
padding_size: The number of padding tokens to add.
pad_to_multiple_of: The multiple to pad the sequence length up to.
Returns:
The padded micro batch.
"""
@@ -27,7 +27,7 @@ class AdvRangeGate(AdmissionGate):
advantage
for episode in group
for trace in episode.traces
if not trace.has_error and trace.agent.trainable
if episode.ok and not trace.has_error and trace.agent.trainable
for node in trace.nodes
for advantage in node.advantages or []
]
@@ -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 and trace.num_turns > 0
if episode.ok and not trace.has_error and trace.agent.trainable and trace.num_turns > 0
]
if not rewards:
return
+8 -2
View File
@@ -679,8 +679,14 @@ class Dispatcher:
f"Trace failed in group {meta.group_id} ({meta.env_name}) — "
f"{trace.last_error.type}: {trace.last_error.message}"
)
if not episode.ok and not episode.traces:
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
if not episode.ok:
if not any(trace.has_error for trace in episode.traces):
self.metrics.record_error(kind=meta.kind, env_name=meta.env_name)
error = episode.last_error
get_logger().warning(
f"Episode failed in group {meta.group_id} ({meta.env_name})"
+ (f" — {error.type}: {error.message}" if error is not None else "")
)
if self.on_episode_complete is not None and meta.started_at > 0:
self.on_episode_complete(episode.num_total_tokens)
await self.emit_episode(meta, group, episode)
+2 -11
View File
@@ -123,25 +123,16 @@ class Env:
task_data: dict,
on_delta: Callable[[dict], None] | None = None,
) -> vf.WireEpisode:
"""Run and return one typed episode. A failed multi-trace episode marks
its otherwise-clean traces failed so partial episodes never train.
"""Run and return the native typed episode.
``on_delta`` sees each delta of the env server's stream — a turn or a phase
change of one of the episode's traces — as it lands."""
episode = await self.env_client.run(
return await self.env_client.run(
task_data=task_data,
client=client,
model=model_name,
sampling=self._sampling(cache_salt),
on_delta=on_delta,
)
for trace in episode.traces:
if not episode.ok and trace.ok:
error = episode.last_error or vf.Error(
type="EpisodeFailed", message="A sibling trace in this episode failed"
)
trace.errors = [*trace.errors, error]
trace.ok = False
return episode
class TrainEnv(Env):
@@ -367,7 +367,9 @@ class AfmoeModel(AfmoePreTrainedModel):
for layer_idx, decoder_layer in enumerate(self.layers):
mask = causal_mask_mapping[decoder_layer.attention_type] if causal_mask_mapping is not None else None
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
@@ -267,7 +267,9 @@ class DeepseekV4Model(DeepseekV4PreTrainedModel):
mhc_states = inputs_embeds.unsqueeze(2).expand(-1, -1, self.config.hc_mult, -1).contiguous()
for layer_idx, decoder_layer in enumerate(self.layers):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
mhc_states = decoder_layer(
mhc_states,
input_ids=input_ids,
@@ -241,7 +241,9 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
cached_indices = None
use_index_cache = getattr(self.config, "use_index_cache", False)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states, next_cached_indices = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -148,7 +148,7 @@ class GptOssModel(GptOssPreTrainedModel):
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers):
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
position_embeddings,
@@ -12,6 +12,7 @@ import triton.language as tl
FP8_MAX = 448.0
FP8_MIN = -448.0
FP8_EPS = 1e-10
KEY_ALIGNMENT = 16
@triton.jit
@@ -88,17 +89,6 @@ def per_token_group_quant_fp8(
return x_q, x_s
@triton.autotune(
configs=[
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=4, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 64}, num_warps=8, num_stages=2),
triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=8, num_stages=2),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
],
key=["S_Q", "S_K_BUCKET", "H", "D"],
)
@triton.jit
def _triton_fp8_indexer_kernel(
Q_fp8,
@@ -116,7 +106,6 @@ def _triton_fp8_indexer_kernel(
stride_ws,
H: tl.constexpr,
D: tl.constexpr,
S_K_BUCKET: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
@@ -201,6 +190,8 @@ def fp8_indexer(
q_flat = q.reshape(S_q * H, D).contiguous()
q_fp8, q_scales = per_token_group_quant_fp8(q_flat, group_size=D, use_ue8m0=True)
S_k_aligned = triton.cdiv(S_k, KEY_ALIGNMENT) * KEY_ALIGNMENT
k = torch.nn.functional.pad(k, (0, 0, 0, S_k_aligned - S_k))
k_fp8, k_scales = per_token_group_quant_fp8(k.contiguous(), group_size=D, use_ue8m0=True)
q_fp8 = q_fp8.view(S_q, H, D).permute(1, 0, 2).contiguous()
@@ -209,12 +200,10 @@ def fp8_indexer(
q_scales = q_scales.view(S_q, H)
w = w * q_scales
logits = torch.empty(S_q, S_k, dtype=torch.float32, device=device)
logits = torch.empty(S_q, S_k_aligned, dtype=torch.float32, device=device)
grid = lambda meta: (
triton.cdiv(S_q, meta["BLOCK_M"]),
triton.cdiv(S_k, meta["BLOCK_N"]),
)
BLOCK_M, BLOCK_N = 64, 128
grid = (triton.cdiv(S_q, BLOCK_M), triton.cdiv(S_k_aligned, BLOCK_N))
_triton_fp8_indexer_kernel[grid](
q_fp8,
k_fp8,
@@ -224,16 +213,17 @@ def fp8_indexer(
ks,
ke,
S_q,
S_k,
S_k_aligned,
q_fp8.stride(0),
q_fp8.stride(1),
k_fp8.stride(0),
w.stride(0),
H=H,
D=D,
# Packed document tails change S_k between batches. Reuse tuning within
# a size bucket; exact S_k still controls strides and all bounds masks.
S_K_BUCKET=triton.next_power_of_2(S_k),
BLOCK_M=BLOCK_M,
BLOCK_N=BLOCK_N,
num_warps=4,
num_stages=2,
)
actual_topk = min(topk, S_k)
@@ -329,7 +329,9 @@ class LagunaModel(LagunaPreTrainedModel):
}
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[self.config.layer_types[layer_idx]],
@@ -177,7 +177,9 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
@@ -192,7 +192,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
torch._dynamo.mark_dynamic(cu_seqlens, 0)
for layer_idx, decoder_layer in enumerate(self.layers):
layer_routed_experts = routed_experts[:, :, layer_idx] if routed_experts is not None else None
layer_routed_experts = routed_experts[:, :, layer_idx].contiguous() if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states,
cu_seqlens,
@@ -210,7 +210,9 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
routed_experts_layer = (
routed_experts[:, :, layer_idx, :].contiguous() if routed_experts is not None else None
)
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
+3 -18
View File
@@ -112,7 +112,7 @@ class ParallelDims:
# Create all the submesh here to ensure all required process groups are
# initialized:
# Mesh for data loading (no communication on this mesh)
# Mesh for data loading and per-step token counts
dp_mesh_dim_names = []
# Mesh for param sharding
dp_shard_cp_mesh_dim_names = []
@@ -172,7 +172,7 @@ class ParallelDims:
# Create all the submesh here to ensure all required process groups are
# initialized:
# Mesh for data loading (no communication on this mesh)
# Mesh for data loading and per-step token counts
dp_mesh_dim_names = []
# Mesh for param sharding
dp_shard_cp_mesh_dim_names = []
@@ -263,13 +263,6 @@ class ParallelDims:
def non_data_parallel_size(self):
return self.cp * self.pp
@cached_property
def seq_len_divisor(self):
# Context Parallel requires that seq_len be divisible by 2 * CP degree,
# when load balancing is enabled (by default).
# https://github.com/pytorch/pytorch/blob/4f62dcc/torch/distributed/tensor/experimental/_attention.py#L1246
return self.cp * 2
@cached_property
def logger(self):
return get_logger()
@@ -309,7 +302,7 @@ def resolve_ep(config: ModelConfig) -> None:
get_logger().info(f"EP auto: world_size={world_size}, dp_replicate={dp_replicate} -> resolved ep={resolved_ep}")
def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> ParallelDims:
def get_parallel_dims(config: ModelConfig) -> ParallelDims:
assert isinstance(config.ep, int), (
f"config.ep must be resolved to an int before get_parallel_dims; got {config.ep!r}. "
"Call resolve_ep(config) first."
@@ -325,12 +318,4 @@ def get_parallel_dims(config: ModelConfig, seq_len: int | None = None) -> Parall
world_size=dist.get_world_size(),
)
# Validate sequence length against parallel dimensions requirements
if seq_len is not None and seq_len % parallel_dims.seq_len_divisor != 0:
raise ValueError(
f"Sequence length ({seq_len}) must be divisible by "
f"seq_len_divisor ({parallel_dims.seq_len_divisor}) for the given parallel dimensions. "
f"This requirement comes from context parallel (CP={config.cp})."
)
return parallel_dims
+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."""
+17 -17
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,9 @@ def train(config: TrainerConfig):
cp_size = parallel_dims.cp
step_tokens_per_expert = 0
for micro_step, micro_batch in enumerate(micro_batches):
step_local_num_tokens = 0
for micro_step, micro_batch in enumerate(micro_batch_workers(prepare, micro_batches)):
step_local_num_tokens += micro_batch["input_ids"].shape[1]
input_ids = micro_batch["input_ids"].to("cuda")
position_ids = micro_batch["position_ids"].to("cuda")
advantages = micro_batch["advantages"].to("cuda")
@@ -365,17 +370,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
@@ -631,9 +629,10 @@ def train(config: TrainerConfig):
if is_moe_model:
tensor_stats.update(get_expert_load_stats(step_tokens_per_expert, dp_cp_group))
# Compute step metrics
num_local_tokens = seq_len * batch_size
num_tokens = parallel_dims.get_mesh("dp").size() * num_local_tokens
# The dp mesh excludes cp, whose ranks hold the same rows.
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
num_tokens = global_num_tokens.item()
progress.total_tokens += num_tokens
progress.total_samples += batch_size
perf_counter = get_perf_counter(model, seq_len)
@@ -732,6 +731,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")
+16 -9
View File
@@ -249,6 +249,13 @@ class RendererResolver:
renderer = create_renderer(self.tokenizer, config)
if self.processor is not None and hasattr(renderer, "_processor"):
renderer._processor = self.processor
if not getattr(renderer, "is_prefix_stable", False):
get_logger().warning(
f"SFT renderer {type(renderer).__name__} does not guarantee prefix stability. "
"SFT renders each conversation once to produce one training sample; "
"it does not expand N assistant turns into N samples. Depending on the template, "
"reasoning from earlier turns may be omitted from the training sample."
)
self.renderers[config] = renderer
return renderer
@@ -279,7 +286,7 @@ class SFTDataset(StatefulIterableDataset):
# Default names are optional: a dataset carries either messages or
# prompt/completion, and tools only for tool use. A name set in the
# config must exist.
for field in ("messages", "prompt", "completion", "tools"):
for field in ("messages", "prompt", "completion", "tools", "message_loss_mask"):
column = getattr(columns, field)
if column != field and column not in dataset.column_names:
raise ValueError(f"data.columns.{field} is {column!r}, but the dataset has only {dataset.column_names}")
@@ -342,9 +349,7 @@ class SFTDataset(StatefulIterableDataset):
case _:
raise ValueError(f"Invalid message role: {message['role']}")
# Defer to the renderer's sampled_mask by default: a role filter would
# drop sampled stop markers attributed to the next message (e.g. GLM's
# turn-closing <|user|> / <|observation|>).
# Let the renderer identify sampled targets when assistant loss is enabled.
role_to_mask = None if self.loss_mask_config.assistant else should_mask
# Non-assistant roles are opted into the loss via the renderer's
@@ -359,6 +364,7 @@ class SFTDataset(StatefulIterableDataset):
tools=tools,
content_sft_roles=content_sft_roles or None,
ensure_final_stop=True,
message_loss_mask=example.get(self.columns.message_loss_mask),
)
input_ids = list(sample.token_ids)
loss_mask = list(sample.loss_mask)
@@ -474,12 +480,13 @@ class SFTDataset(StatefulIterableDataset):
class CatDataset(StatefulIterableDataset):
"""Concatenate text and multimodal samples into one fixed-length row."""
"""Pack samples into rows of at most `seq_len` tokens, padded to a multiple of `pad_to_multiple_of`."""
def __init__(self, dataset: StatefulIterableDataset, seq_len: int):
def __init__(self, dataset: StatefulIterableDataset, seq_len: int, pad_to_multiple_of: int):
self.logger = get_logger()
self.dataset = dataset
self.seq_len = seq_len
self.pad_to_multiple_of = pad_to_multiple_of
self.pending_sample: Sample | None = None
def state_dict(self) -> dict:
@@ -583,7 +590,7 @@ class CatDataset(StatefulIterableDataset):
if kept > 0:
result["seq_lens"].append(kept)
remaining -= kept
pad_len = seq_len - len(result["input_ids"])
pad_len = -len(result["input_ids"]) % self.pad_to_multiple_of
if pad_len > 0:
result["input_ids"].extend([0] * pad_len)
result["position_ids"].extend(range(pad_len))
@@ -753,8 +760,8 @@ def setup_dataset(
raise ValueError(f"Invalid dataset type: {config.type}")
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig) -> StatefulDataLoader:
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size)
def setup_dataloader(dataset: StatefulIterableDataset, config: DataConfig, cp: int) -> StatefulDataLoader:
packing_dataset = CatDataset(dataset, config.seq_len * config.micro_batch_size, pad_to_multiple_of=cp)
return StatefulDataLoader(
packing_dataset,
batch_size=1,
+10 -12
View File
@@ -113,7 +113,7 @@ def train(config: SFTConfig):
resolve_ep(config.model)
# Initialize parallel dimensions
parallel_dims = get_parallel_dims(config.model, config.data.seq_len)
parallel_dims = get_parallel_dims(config.model)
total_micro_batches = config.data.batch_size * config.model.cp
micro_batches_per_step = world.world_size * config.data.micro_batch_size
@@ -192,7 +192,7 @@ def train(config: SFTConfig):
processor=processor,
multimodal=multimodal,
)
dataloader = setup_dataloader(dataset, config.data)
dataloader = setup_dataloader(dataset, config.data, config.model.cp)
val_raw_dataset = None
if config.val is not None:
@@ -257,7 +257,7 @@ def train(config: SFTConfig):
if cp_enabled:
# CP requires the sequence length to be divisible by cp_size. CatDataset
# pads every pack to seq_len; shard_for_cp raises on violations.
# pads every pack to a multiple of it; shard_for_cp raises on violations.
defer_vlm_cp_to_model = (
mm_kwargs is not None and "image_grid_thw" in mm_kwargs and config.model.cp_style == "ulysses"
)
@@ -345,7 +345,7 @@ def train(config: SFTConfig):
processor=processor,
multimodal=multimodal,
)
val_dataloader = setup_dataloader(val_dataset, config.val.data)
val_dataloader = setup_dataloader(val_dataset, config.val.data, config.model.cp)
# No train/eval switch: no dropout in these models, and toggling would trigger torch.compile recompilation
mean_loss, nan_count = run_eval_loop(val_dataloader)
@@ -451,7 +451,9 @@ def train(config: SFTConfig):
)
step_tokens_per_expert = 0
step_local_num_tokens = 0
for micro_step, micro_batch in enumerate(micro_batches):
step_local_num_tokens += micro_batch["input_ids"].shape[1]
if config.log.log_data:
print_sample(
micro_batch["input_ids"].flatten().tolist(), micro_batch["loss_mask"].flatten().tolist(), tokenizer
@@ -549,14 +551,10 @@ def train(config: SFTConfig):
if memory_profiler is not None:
memory_profiler.step()
# Compute step metrics. CP shards the same sequences across cp ranks
# (sequence-sharded data parallelism on the seq dim), so the unique
# training tokens per step is dp_size * (batch_per_dp_rank * seq).
# The `dp` mesh excludes cp by construction (parallel_dims.py), mirroring
# the RL trainer's accounting (rl/train.py).
dp_size = parallel_dims.get_mesh("dp").size()
num_local_tokens = config.data.seq_len * (config.data.batch_size // dp_size)
num_tokens = dp_size * num_local_tokens
# The dp mesh excludes cp, whose ranks hold the same rows.
global_num_tokens = torch.tensor(step_local_num_tokens, dtype=torch.int64, device="cuda")
dist.all_reduce(global_num_tokens, op=dist.ReduceOp.SUM, group=parallel_dims.get_mesh("dp").get_group())
num_tokens = global_num_tokens.item()
progress.total_tokens += num_tokens
dataset_progress = get_dataset_progress(dataloader)
progress.total_samples = dataset_progress["step"]
+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()
@@ -110,6 +110,7 @@ def _build_episode(
task=trace.task,
group=vf.GroupInfo(id="group"),
traces=[trace],
ok=True,
)
return episode
@@ -9,6 +9,7 @@ from verifiers.v1.types import AssistantMessage, ToolMessage, UserMessage
from prime_rl.configs.algorithm import AlgoConfig, FrozenModelConfig
from prime_rl.orchestrator.algo import EchoAlgorithm, assign_advantages, stamp_loss_routing
from prime_rl.orchestrator.algo.base import iter_trainable_traces
from prime_rl.orchestrator.trajectories import trace_to_samples
from prime_rl.transports.batch.types import TrainingSample
@@ -201,10 +202,33 @@ def _make_episode() -> vf.Episode:
task=trace.task,
group=vf.GroupInfo(id="group"),
traces=[trace],
ok=True,
)
return episode
@pytest.mark.parametrize("failure", ["participant", "untrainable_participant", "environment"])
def test_trainable_traces_exclude_failed_episodes_without_changing_verdicts(failure):
good = _make_episode()
good.errors = [vf.Error(type="RecoveredError", message="Previous attempt failed")]
good.traces[0].errors = list(good.errors)
failed = _make_episode()
failed.ok = False
if failure == "environment":
failed.errors = [vf.Error(type="EnvError", message="Finalization failed")]
else:
sibling = failed.traces[0].model_copy(deep=True)
sibling.id = "failed-sibling"
sibling.ok = False
sibling.errors = [vf.Error(type="AgentError", message="Participant failed")]
sibling.agent.trainable = failure == "participant"
failed.traces.append(sibling)
before = failed.model_dump()
assert list(iter_trainable_traces([failed, good])) == [(good, good.traces[0])]
assert failed.model_dump() == before
def test_assign_advantages_full_length_stream():
# The advantage stream is full-length-N: 0.0 on prompt + non-trainable
# positions, the rl credit on trainable (mask True) tokens.
+5 -1
View File
@@ -61,6 +61,7 @@ def make_rollout(
task=trace.task,
group=vf.GroupInfo(id=str(uuid.uuid4())),
traces=[trace],
ok=True,
)
return [episode]
@@ -113,7 +114,10 @@ def test_train_source_composes_sampler_and_all_gates_with_state_and_metrics() ->
sampled = source.next_task(step=1).task
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
group = make_rollout(sampled, reward=0.25, advantages=[0.0])
failed = make_rollout(sampled, reward=1.0, advantages=[1.0])
failed[0].ok = False
assert source.on_result(group + failed + empty) is False
assert source.metrics() == {
"curriculum/test/admission_rate": 0.0,
"curriculum/test/sampler/pool/unseen": 2.0,
+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(
{
+5 -4
View File
@@ -19,7 +19,7 @@ def setup_fake_dataloader(config: FakeDataConfig, non_dp_size: int = 1):
seed=config.seed,
non_dp_size=non_dp_size,
)
return dataset, setup_dataloader(dataset, config)
return dataset, setup_dataloader(dataset, config, cp=1)
def test_fake_dataset_single_rank_state():
@@ -88,7 +88,7 @@ def test_fake_dataset_single_rank_resume():
# Reload dataloader
state_dict = dataloader.state_dict()
dataloader = setup_dataloader(dataset, config)
dataloader = setup_dataloader(dataset, config, cp=1)
dataloader.load_state_dict(state_dict)
dataiter = iter(dataloader)
@@ -110,7 +110,8 @@ def test_fake_dataset_single_rank_state_with_packing():
micro_batch = next(dataiter)
num_packed_examples = len(micro_batch["input_ids"][micro_batch["loss_mask"]].unique())
step += num_packed_examples
assert micro_batch["input_ids"].shape == (1, 128)
assert micro_batch["input_ids"].shape[0] == 1
assert micro_batch["input_ids"].shape[1] <= 128
assert micro_batch["seq_lens"].sum() == micro_batch["input_ids"].shape[1]
worker_state = dataloader.state_dict()["_snapshot"]["_worker_snapshots"]["worker_0"]["dataset_state"]
pending_sample = worker_state.get("pending_sample")
@@ -186,7 +187,7 @@ def test_dataloader_shards_across_ranks_and_workers(
seq_len=config.seq_len,
non_dp_size=non_dp_size,
)
return setup_dataloader(dataset, config)
return setup_dataloader(dataset, config, cp=1)
dataloader = setup_epoch_dataloader()
dataiter = iter(dataloader)
+85 -11
View File
@@ -443,6 +443,7 @@ def test_cat_dataset_packs_multimodal_samples():
),
],
seq_len=5,
pad_to_multiple_of=1,
)
packed = next(iter(dataset))
@@ -467,23 +468,24 @@ def test_cat_dataset_packs_text_and_multimodal_samples_together():
mm_token_type_ids=[0, 1],
),
_sft_sample([4]),
_sft_sample([5, 6]),
_sft_sample([5, 6, 7, 8, 9, 10]),
],
seq_len=5,
seq_len=9,
pad_to_multiple_of=3,
)
dataiter = iter(dataset)
packed = next(dataiter)
text_pack = next(dataiter)
assert packed["input_ids"] == [1, 2, 3, 4, 0]
assert packed["loss_mask"] == [True, True, True, True, False]
assert packed["seq_lens"] == [1, 2, 2]
assert packed["input_ids"] == [1, 2, 3, 4, 0, 0]
assert packed["loss_mask"] == [True, True, True, True, False, False]
assert packed["seq_lens"] == [1, 2, 3]
assert packed["mm_kwargs"] is not None
assert packed["mm_token_type_ids"] == [0, 0, 1, 0, 0]
assert text_pack["input_ids"] == [5, 6, 0, 0, 0]
assert text_pack["loss_mask"] == [True, True, False, False, False]
assert text_pack["seq_lens"] == [5]
assert packed["mm_token_type_ids"] == [0, 0, 1, 0, 0, 0]
assert text_pack["input_ids"] == [5, 6, 7, 8, 9, 10]
assert text_pack["loss_mask"] == [True] * 6
assert text_pack["seq_lens"] == [6]
assert text_pack["mm_kwargs"] is None
assert text_pack["mm_token_type_ids"] is None
@@ -508,6 +510,10 @@ class EffortRenderer:
def __init__(self, tokenizer, config):
self.config = config
@property
def is_prefix_stable(self):
return self.config.reasoning_effort == "low"
def render(self, messages, **kwargs):
return RenderedTokens(token_ids=[0, 1], message_indices=[-1, 0], sampled_mask=[False, True])
@@ -528,8 +534,21 @@ def custom_renderer_config(tmp_path):
def test_renderer_resolver_applies_renderer_columns_to_custom_renderer(custom_renderer_config):
resolver = sft_data.RendererResolver(tokenizer=None, config=custom_renderer_config)
default = resolver({"messages": [], "reasoning_effort": None})
high = resolver({"messages": [], "reasoning_effort": "high"})
warnings = []
logger = sft_data.get_logger()
sink = logger.add(lambda message: warnings.append(str(message)), level="WARNING", format="{message}")
try:
default = resolver({"messages": [], "reasoning_effort": None})
assert warnings == []
high = resolver({"messages": [], "reasoning_effort": "high"})
assert resolver({"reasoning_effort": "high"}) is high
assert len(warnings) == 1
assert "does not guarantee prefix stability" in warnings[0]
assert "one training sample" in warnings[0]
assert "does not expand N assistant turns into N samples" in warnings[0]
assert "reasoning from earlier turns may be omitted" in warnings[0]
finally:
logger.remove(sink)
assert default.config.reasoning_effort == "low"
assert high.config.reasoning_effort == "high"
@@ -569,6 +588,8 @@ def test_sft_dataset_reads_mapped_message_columns(dummy_renderer):
with pytest.raises(ValueError, match="'messages' column"):
next(iter(SFTDataset(dataset, lambda _: dummy_renderer)))
with pytest.raises(ValueError, match="data.columns.message_loss_mask"):
SFTDataset(dataset, lambda _: dummy_renderer, columns=SFTColumnsConfig(message_loss_mask="selection"))
with pytest.raises(ValueError, match="data.columns.prompt"):
SFTDataset(dataset, lambda _: dummy_renderer, columns=SFTColumnsConfig(prompt="question"))
@@ -594,3 +615,56 @@ def test_sft_dataset_passes_tools_through_from_the_mapped_column(dummy_renderer)
next(iter(SFTDataset(dataset, lambda _: RecordingRenderer(), columns=SFTColumnsConfig(tools="schemas"))))
assert seen == [[], tools]
@pytest.mark.parametrize("model", ["zai-org/GLM-5", "Qwen/Qwen3-0.6B"])
@pytest.mark.parametrize("layout", ["messages", "prompt_completion"])
@pytest.mark.parametrize("column", ["message_loss_mask", "selection"])
@pytest.mark.parametrize("mask", [None, [True, True, True, True], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]])
def test_sft_message_selection(model, layout, column, mask):
from prime_rl.configs.sft import SFTColumnsConfig
tokenizer = AutoTokenizer.from_pretrained(model)
renderer = create_renderer(tokenizer)
messages = [
{"role": "user", "content": "Question"},
{"role": "assistant", "content": "Prefilled"},
{"role": "user", "content": "Follow up"},
{"role": "assistant", "content": "Answer"},
]
row = {"messages": messages} if layout == "messages" else {"prompt": messages[:2], "completion": messages[2:]}
baseline = SFTDataset(Dataset.from_list([row]), lambda _: renderer)._process(row)
row[column] = mask
dataset = SFTDataset(
Dataset.from_list([row]), lambda _: renderer, columns=SFTColumnsConfig(message_loss_mask=column)
)
sample = dataset._process(row)
if mask == [0, 0, 0, 0]:
assert sample is None
return
assert sample["input_ids"] == baseline["input_ids"]
assert sample["target_ids"] == baseline["target_ids"]
if mask is None or all(mask):
assert sample["loss_mask"] == baseline["loss_mask"]
return
trained = tokenizer.decode([token for token, keep in zip(sample["target_ids"], sample["loss_mask"]) if keep])
if mask[1]:
assert "Prefilled" in trained
assert "Answer" not in trained
if model == "zai-org/GLM-5":
assert trained == "Prefilled<|user|>"
else:
assert "Prefilled" not in trained
assert "Answer" in trained
if model == "zai-org/GLM-5":
assert trained == "Answer<|endoftext|>"
assert "Question" not in trained
assert "Follow up" not in trained
@pytest.mark.parametrize("mask", [[], [1, 0], ["0"], [2], [None]])
def test_sft_rejects_invalid_message_selection(dummy_renderer, mask):
row = {"messages": [{"role": "assistant", "content": "Answer"}], "message_loss_mask": mask}
dataset = SFTDataset(Dataset.from_list([row]), lambda _: dummy_renderer)
with pytest.raises(ValueError, match="message_loss_mask"):
dataset._process(row)
+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)
Generated
+16 -5
View File
@@ -24,7 +24,7 @@ fastokens = false
flash-attn-3 = false
flash-mla = false
flashinfer-python = false
harbor = "2026-08-11T00:00:00Z"
harbor = "2026-10-08T00:00:00Z"
nixl-cu13 = false
prime = false
prime-evals = false
@@ -2208,7 +2208,7 @@ wheels = [
[[package]]
name = "harbor"
version = "0.21.0"
version = "0.24.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "dirhash" },
@@ -2216,6 +2216,7 @@ dependencies = [
{ name = "filelock" },
{ name = "httpx" },
{ name = "jinja2" },
{ name = "jsonschema" },
{ name = "litellm" },
{ name = "packaging" },
{ name = "pathspec" },
@@ -2226,6 +2227,7 @@ dependencies = [
{ name = "pyyaml" },
{ name = "requests" },
{ name = "rich" },
{ name = "semver" },
{ name = "shortuuid" },
{ name = "supabase" },
{ name = "tenacity" },
@@ -2233,9 +2235,9 @@ dependencies = [
{ name = "typer" },
{ name = "uvicorn" },
]
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" }
sdist = { url = "https://files.pythonhosted.org/packages/82/7d/16e21cfd52938260dce71ff77ec1ed156bd8c327642760fe66163b0cd3ce/harbor-0.24.0.tar.gz", hash = "sha256:6c5185e6a76abc677ed3f95e688dc0dbf8597e4fa50847cb9a37a4448c91b1e5", size = 2090577, upload-time = "2026-10-05T05:04:46.252Z" }
wheels = [
{ 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" },
{ url = "https://files.pythonhosted.org/packages/9e/63/0e3d788e8d1ed116125507c6a01e3fb95cf82be71f2ea7040a1458709d21/harbor-0.24.0-py3-none-any.whl", hash = "sha256:23b7ba616a3aae4eff561ced5e2c51c7186f2981e53a770dea9c689d3969877c", size = 2331740, upload-time = "2026-10-05T05:04:42.088Z" },
]
[[package]]
@@ -6377,6 +6379,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/65/94/7698add8f276dbab7a9de9fb6b0e02fc13ee61d51c7c3f85ac28b65e1239/scipy-1.17.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f590cd684941912d10becc07325a3eeb77886fe981415660d9265c4c418d0bea", size = 37625856, upload-time = "2026-02-23T00:19:00.307Z" },
]
[[package]]
name = "semver"
version = "3.1.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/92/f5/e1dfe8e1d91c54ce212fd93916eb01fd1c590f413be0a0978c39a97aa1bb/semver-3.1.0.tar.gz", hash = "sha256:14bc073439513d7773662a338f4db9829cf16c12b74b9568e2d2689975fbd7fc", size = 304162, upload-time = "2026-09-12T18:38:14.045Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/be/02/bce7a1d70e9d0f6ea8623c16386138c251b5855af6cd3a11433d3fba4e66/semver-3.1.0-py3-none-any.whl", hash = "sha256:6e4998f8b4762acdfea85f9bfd5b4032e0bb50038dc04bf82011b42d5d1145c5", size = 18783, upload-time = "2026-09-12T18:38:12.457Z" },
]
[[package]]
name = "senior-swe-bench"
version = "0.1.1"
@@ -7792,7 +7803,7 @@ requires-dist = [
{ name = "e2b", marker = "extra == 'e2b'", specifier = ">=2.35.0,<3" },
{ name = "gepa", specifier = ">=0.0.6" },
{ name = "h11", specifier = ">=0.16.0" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.21.0" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.24.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "httpx2", specifier = ">=2.12.0" },
{ name = "loguru", specifier = ">=0.7.0" },