Compare commits

...
Author SHA1 Message Date
1e0fe9637d [R3]: Move to new vLLM routed experts format (#2487)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: wire r3 v3 routed experts stack

* feat: reset routing caches on policy update

* fix: rely on native vllm routed experts

* fix: pin routed experts dependencies for ci

* fix: update scheduler tests for prefix reset

* fix: clean routed experts replay integration

* fix: keep routed experts transport first class

* fix: keep routed experts on samples

* fix: use upstream vllm nightly wheel

* fix: pin latest routed experts verifiers

* fix: pin routed experts dependencies

* fix: allow routed experts with nixl

* style: format nixl patch

* Use raw uint8 routed experts payloads

* Remove unrelated rlm-swe dependency

* Pin vllm-router 0.1.25 wheel

* Keep verifiers routed experts opaque

* Forward renderer thinking preservation config

* Avoid duplicate routed experts in token responses

* [codex] Guard checkpoint disk metrics mkdir (#2523)

* Guard checkpoint disk metrics mkdir

* Remove test_trainer_utils.py per review feedback

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Simplify ckpt disk metrics guard

Drop the rank-0 gate and the disk_usage path fallback per review feedback.
Catching FileExistsError on mkdir is sufficient: every rank that races on
mkdir either wins or harmlessly catches the BeegFS race, and shutil.disk_usage
can then operate on the now-existing ckpt_dir.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Pin verifiers routed experts sidecar

* Pin cleaned verifiers routed experts handling

* Pin rebased verifiers routed experts handling

* fix: remove unrelated prime-rl changes

* fix: pack routed experts as typed payloads

* refactor: inline routed experts trajectory packing

* fix: restore trajectory tokenization helpers

* refactor: simplify routed experts packing

* chore: pin vllm router wheel

* chore: update renderers and verifiers

* Pin vLLM PR39568 backport wheel

* Pin vLLM revert42434 PR39568 wheel

---------

Co-authored-by: Sami <sami@primeintellect.ai>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:39:40 +02:00
samsjaandGitHub badd2b0fe2 feat: write token exports per step (#2596)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-21 21:09:57 -07:00
samsjaandGitHub e971d905a2 Add trainer token JSONL export (#2592)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: add trainer token jsonl export

* chore: use docstrings for token export config
2026-05-21 20:31:03 -07:00
Matej SirovatkaandGitHub 710e11912f fix: set deepgemm moe env for inference (#2591)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-22 03:46:08 +02:00
c95a943c39 feat(scheduler): train on partial groups instead of dropping on rollout error (#2590)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(scheduler): train on partial groups instead of dropping on rollout error

When an individual-scoring env returns N rollouts for a single example and one
errors out, scrap only the failed rollout — keep the survivors and ship the
group through as soon as every dispatched rollout has come back (success or
failure). Group-scoring envs still drop the whole group on any failure because
their per-rollout scores are computed against the now-missing rollouts.

To make variable-size groups round-trip through advantage computation, group
rollouts by (env_name, example_id) instead of positional slicing, and bucket
groups by size so each advantage_fn call still sees a uniform 2D rewards
tensor. Singleton groups produce zero advantage and get filtered out by the
existing zero-advantage filter — no special-casing.

Closes #2585.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(advantage): make advantage_fn per-group

Drop the bucket-by-size workaround in compute_advantages by changing the
advantage_fn contract: AdvantageInputs.rollouts is now a single group
(list[RolloutOutput]) and AdvantageOutputs.advantages is 1D. The framework
calls advantage_fn once per group, which works cleanly for variable-size
groups (partial-group training).

BREAKING: second change to this public API in three weeks. Custom advantage
functions must drop the outer list dim. Migration documented in CHANGELOG.md
and docs/bring-your-own-algorithms.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(advantage): return list[float] from advantage_fn

Drops the torch tensor from the public AdvantageOutputs contract; internal
math stays in torch and converts via .tolist() at the boundary. Same partial-
group support, simpler downstream consumers (no more .tolist() / no shape
gymnastics in custom advantages).

BREAKING (folds into the per-group change in the previous commit): custom
advantage functions must return AdvantageOutputs(advantages=[...]) rather
than a tensor. CHANGELOG entry and docs example updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(scheduler): log each rollout failure inline, drop GroupState.last_failure_reason

The reason is now logged at the moment the failure is observed (one warning
per failed rollout) instead of being stashed on the group and replayed at
finalization. Removes the per-group field entirely and avoids the "first vs
latest wins" semantic question that came up in review - each log line carries
its own actual reason. Finalization warnings only carry counts now.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(scheduler): drop verbose comment on GroupState.failed_rollouts

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:40:34 -07:00
ca03d89fad feat(orchestrator): per-env state_columns for extra rollout fields (#2589)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): per-env state_columns for extra rollout fields

Adds `state_columns: list[str] = []` to `EnvConfig` so each env can
persist additional `State` fields into the saved JSONL rollouts on top
of the always-saved `trajectory` and `sampling_args`. Merged at the
call site (required first, deduped).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: drop seen set from state_columns dedup

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 18:23:30 -07:00
Matej SirovatkaandGitHub e6e814697a fix: patch deepgemm silu quant addressing (#2582)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-21 15:57:53 -07:00
f9cebaa19c fix(slurm): stop cleanup srun from self-killing (#2586)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The pre-launch cleanup block runs `pkill -9 -f "[v]llm"` to mop up
orphans from prior jobs. The `[v]llm` regex-trick relies on no literal
`vllm` appearing in the matching cmdline, but the surviving lines in the
same block do — `pkill -9 "vllm"`, `pkill -9 "vllm::.*"`, the
`/tmp/vllm-*` glob, and the closing `grep -E "...vllm..."`. With
`srun bash -c '<script>'` the entire script body lives in both srun's and
the inner bash's argv, so `[v]llm` matches them and SIGKILLs the cleanup
processes mid-flight. `set -e` then bubbles it up and the batch dies
before any component starts.

Switch to `srun bash -s <<'CLEANUP_SH' ... CLEANUP_SH`. The heredoc goes
over stdin, so the cmdline of srun and bash on every task is just
`srun bash -s` / `bash -s`. `pkill -f "[v]llm"` no longer self-matches
and the cleanup completes normally on every node.

Verified on cluster (multinode RL example): pre-fix the cleanup step
died with `9:0` in 6 s; post-fix the cleanup step exits `0:0` and the
log shows `[node-cleanup] <host> procs=1 gpu_mem=0MiB` from both nodes.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 13:45:00 -07:00
c656d2f8f2 fix(orchestrator): deep-merge legacy model/client aliases; switch multinode template to canonical CLI path (#2584)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): deep-merge legacy model/client aliases; switch multinode template to canonical CLI path

`fold_student_shortcuts` previously skipped re-nesting top-level `client`
into `student.client` when the latter was already populated (and used
`setdefault` for `model`, so existing keys won). That meant a CLI override
like `--client.base-url URL` could never reach `student.client.base_url`
once the TOML provided `[student.client]` — pydantic's `extra="forbid"`
rejected the leftover top-level `client` with `Extra inputs are not
permitted`. Same shape for `--model.<k>` against TOML `[student.model]`.

Deep-merge with the legacy (top-level / CLI) side winning at the leaf.
TOML values that the CLI doesn't touch are preserved.

Also update `multi_node_rl.sbatch.j2` to use the canonical
`--student.client.{base-url,admin-base-url}` instead of the legacy alias.
The new path is a known leaf in pydantic-config, so single-value args
get list-wrapped correctly (the legacy alias goes through the unknown-leaf
branch and would still produce a raw string).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* nit: rename _deep_merge_into -> deep_merge, drop redundant comment

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 12:17:10 -07:00
9ef2705898 fix(scheduler): drop group on rollout error instead of rescheduling (#2581)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(scheduler): drop group on rollout error instead of rescheduling

Raise per-env max_retries default from 0 to 3 so transient infra failures
are absorbed inside the env server. Drop any group whose rollout bubbles
up with an error or empty trajectory, log it, and let the rest of the
batch proceed — no in-orchestrator reschedule, no partial-group salvage.

Removes max_error_reschedule_attempts and the GroupState round/attempt
tracking. Closes #2475.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(scheduler): count every failed rollout in error metrics

Iterating over the rollouts and breaking on the first failure undercounted
errored_rollouts/empty_rollouts for group-scoring envs (which return N
rollouts per task), deflating the reported error rate.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(scheduler): emit error/<type>/count metric per step

Adds errors_by_type tracking keyed by ErrorInfo["error"] (the outermost
exception class name from the verifiers error chain), surfaced to wandb
as error/<type>/count. Lets dashboards see which failure mode (e.g.
OverlongPromptError vs InterceptionError vs SandboxError) is driving
dropped groups, instead of one opaque errored_rollouts rate.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 12:16:54 -07:00
1d9ca92551 fix(rl): normalize loss by global token count across dp_cp (#2562)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Each DP rank was dividing its summed token loss by its own local
loss_scale, then FSDP averaged the resulting gradients. Because ranks
process different sequence lengths, that mean is not the true per-token
mean over the global batch — ranks with fewer loss tokens get implicitly
upweighted.

Mirror the SFT trainer fix (src/prime_rl/trainer/sft/train.py:416-427):
all-reduce the local token count across dp_cp, divide by that global
denominator on every rank, and multiply grads by fsdp_gradient_divide_factor
after the microbatch loop so FSDP's per-rank averaging is undone and the
final gradient is the per-token mean over the global batch.

Closes #2358. Adapted from #2359, which first diagnosed the bias and
proposed the all-reduce-then-rescale approach.

Co-authored-by: irfanjamil <irfanjamil9@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 20:12:08 -07:00
ea2f390045 feat: renderer-only multimodal path — rip MITO branch, pack pixel_values from renderer (#2473)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: drop use_renderer=True VLM skip; pack pixel_values from renderer

interleave_rollout now consumes renderer-emitted multi_modal_data on each
trajectory step (when present), packs the per-image pixel_values and
image_grid_thw onto the TrainingSample, and computes mm_token_type_ids —
no VLMImageCache lookup required when the rollout went through a
multimodal renderer. VLMImageCache stays as the fallback for
MITO/chat-completions rollouts.

build_trajectory_step (renderers package) was updated separately to
surface mm_data on its output, so the pretokenize-fallback path also
carries images through correctly.

Other changes:
- orchestrator config: removed validate_renderer_vs_vlm validator that
  previously rejected use_renderer=True for VLMs (it's now supported).
- e2e test: a real Qwen3VLRenderer + RendererClient -> /inference/v1/generate
  mock POST, plus a roundtrip through vllm's GenerateRequest pydantic
  model and decode_mm_kwargs_item. Strongest end-to-end check we can
  run without a GPU.
- 20-step A/B configs for color-codeword (feat-renderer vs main-mito),
  both logging to W&B project 'multimodal-renderer'.

126 orchestrator unit tests pass (+2 new for renderer-mm packing).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(orchestrator): rip MITO multimodal path, renderer-only for VLMs

Delete the MITO chat-completions multimodal branch from the orchestrator
and the ~370 lines of image-cache/preprocess machinery in trajectories.py
that supported it. VLM training now goes through the renderer path
exclusively — the renderer owns the processor, ships byte-identical
pixel_values to both vLLM (via /inference/v1/generate features) and the
trainer (via mm_kwargs).

Renderer-shipped mm_token_type_ids: the orchestrator reads the renderer's
`mm_token_type_id_map` property (1=image_pad, 2=video_pad) and stamps a
per-token list onto each TrainingSample. Trainer's `_get_qwen3_vl_mm_token_type_ids`
auto-path remains as a fallback but the renderer is now the source of truth.

forward() now takes a generic `mm_kwargs: dict` (e.g. {pixel_values,
image_grid_thw}) instead of the Qwen3-VL-specific (pixel_values, image_grid_thw)
keyword pair, so adding new VLM families (Gemma3, LLaVA, etc.) doesn't
require touching forward.

Config validator: orchestrator.use_renderer must be true when model.vlm is
set — fail at config-load instead of producing cryptic runtime errors.

Test cleanup: drop 25 tests for removed helpers (VLMImageCache, _extract_images,
etc.); update the one remaining renderer-mm trajectory test to pass
`mm_token_type_ids_mapping` directly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: align with renderer-multimodal PR surface (configs + deps + tests)

CI was failing for three reasons after the cherry-pick of the renderer
multimodal commits onto current origin/main. Three fixes:

1. Multimodal configs missing the renderer flag pair. The orchestrator
   config validator (added in the same PR) requires
   ``use_renderer = true`` when ``model.vlm`` is set, AND it's mutually
   exclusive with ``use_token_client`` (default ``true``). Three configs
   (``rl_color_codeword_test.toml``, ``rl_color_codeword.toml``,
   ``ci/nightly/multimodal_color_codeword.toml``) needed both flags set
   explicitly in ``[orchestrator]``. Delete
   ``rl_color_codeword_main_mito.toml`` — that was the A/B reference for
   the legacy MITO path, which this PR rips out. With MITO gone the
   config is no longer runnable; the ``rl_color_codeword_feat_renderer``
   counterpart already covers the new renderer-driven path.

2. ``test_model_forward.py`` was still calling ``forward(...,
   pixel_values=..., image_grid_thw=...)``. ``forward()`` now takes a
   generic ``mm_kwargs: dict`` (so adding new VLM families doesn't
   require touching the trainer signature) — update both tests to pass
   ``mm_kwargs={"pixel_values": ..., "image_grid_thw": ...}`` instead.

3. ``renderers`` / ``verifiers`` deps stale. The orchestrator imports
   ``MultiModalData`` from ``renderers.base`` (introduced in the
   companion renderers PR) and threads ``multi_modal_data`` end-to-end
   via the verifiers ``RendererClient`` changes. Pin both to their
   feature branches until the upstream PRs merge and PyPI / git
   rev-pins are bumped:

     - renderers @ feat/multimodal-vlm
     - verifiers @ feat/renderer-multimodal-passthrough

   Drops the ``renderers==0.1.6`` PyPI pin (the new symbols are post-0.1.6).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: bump renderers + verifiers to latest feature-branch commits

Picks up:
- renderers c3feaa5: RendererPool implements Renderer protocol structurally
  (callers can drop pool unwrap + isinstance branching), size=1 fast path,
  is_multimodal helper with per-type cache.
- verifiers 64f2555a: bugbot pass — multimodal dispatch fix (was broken
  for pooled renderers), tighter is_json_serializable, response-tokens
  mm_data strip on intermediate steps.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: bump renderers + verifiers to pick up isinstance dispatch fix

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: drop renderers git source, pin to released 0.1.7

renderers v0.1.7 is now on PyPI with the multimodal feature set this
branch consumes (RenderedTokens, MultiModalData, MultimodalRenderer
protocol, mm_token_type_id_map, RendererPool delegation).

verifiers still pinned to feat/renderer-multimodal-passthrough until
that companion PR merges.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: repin verifiers to main + bump renderers to 0.1.8.dev2

The multimodal renderer-passthrough work has merged on verifiers
(verifiers#1346 → c7731bbb, on main since 2026-05-12), so we no longer
need the feature-branch pin. Switching to a `rev =` pin on main
(f633365f) — consistent with how every other git source in this file
is pinned — and bumping renderers to 0.1.8.dev2 to match what verifiers
main now requires.

Pin updates:
- verifiers: branch `feat/renderer-multimodal-passthrough`
  (0.1.14 @ 397b8aa5)  ->  rev `f633365f` (0.1.15.dev7)
- renderers: `>=0.1.7` -> `>=0.1.8.dev2`
- prime-sandboxes: 0.2.22 -> 0.2.26 (transitive from verifiers main)
- fastokens added (transitive from renderers 0.1.8.dev1+; renderers
  routes `load_tokenizer` through fastokens by default)

What's in the verifiers delta (397b8aa5..f633365f) that touches our
surface:
- `RendererClient.from_native_response` migrated to renderers'
  `ParsedToolCall` dataclass shape and filters non-OK parse attempts
  (verifiers#1366 / renderers#22). Internal — the Response we consume
  is unchanged.
- Routed-experts payloads now flow as opaque bytes through the chat
  completions clients (verifiers PRs around the `routed_experts`
  changes). Prime-rl consumes the surface that emits these; no caller
  change needed.

Test plan:
- [x] `uv run pytest tests/unit/orchestrator` — 101 passed against the
  new pins, including `test_qwen3_vl_e2e` which exercises the renderer
  -> RendererClient -> /inference/v1/generate roundtrip path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: drop renderers version pin, defer to verifiers' transitive constraint

We import directly from `renderers` (orchestrator + tests), so the dep
needs to be declared — but pinning a floor here is just second-guessing
verifiers, which already requires `renderers>=0.1.8.dev2`. Let verifiers
be the source of truth for the version.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(trainer): drop mm_token_type_ids auto-compute, trust renderer

The auto-compute path (`_get_qwen3_vl_mm_token_type_ids`) was preferred
over the renderer-shipped `mm_token_type_ids` in `forward()`. For
Qwen3-VL the auto function never returns `None` (allocates
`torch.zeros_like(input_ids)` then masked_fills), so the explicit
orchestrator-shipped list was silently discarded — contradicting both
the "renderer is source of truth" design and the trajectories.py
comment noting the explicit list produces ~30x lower mismatch KL.

The new `vlm_requires_renderer` validator (this PR) mandates the
renderer for every VLM config, so the auto path is no longer reachable
as a real fallback. Deleting it. The renderer's `mm_token_type_id_map`
is now the sole source of truth, exactly as advertised.

Also adding the CHANGELOG entry the validator missed — removing the
`[model.vlm]` + `use_renderer = false` combo is a breaking config
change per CHANGELOG.md's stated policy.

The remaining `if "image_grid_thw" not in mm_kwargs` branch is *not*
renderer-replaceable: it skips `position_ids` for MRoPE families
because HF's Qwen-VL `forward()` internally recomputes 3D positions
from `image_grid_thw` and breaks if given the trainer's pre-computed
1D `position_ids`. Duck-typed against the kwargs schema so any future
MRoPE family that ships `image_grid_thw` is handled without a
`model_type` enumeration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(orchestrator): union per-step delta mm_data across sample's step range

verifiers ≥ c7731bbb (PR #1346 merge) replaced ``_strip_intermediate_mm_data``
with ``_delta_intermediate_mm_data`` (commit 9aafa659): each trajectory
step now carries only the items whose ``mm_hash`` was NOT in the prior
step's cumulative set, with multiset-aware semantics. The intended
contract is that per-window assemblers union deltas to recover the
per-sample cumulative.

Prime-rl's ``interleave_rollout`` was that assembler but still read
``prepared_steps[last_step_idx].get("multi_modal_data")`` alone,
assuming the last step held the cumulative set. With the new delta
encoding, the last step often holds **0 items** (everything was a
duplicate of step 0's cumulative set) — so the trainer was given
pixel_values for only the first turn's images. For ``color-codeword``
with ``max_turns=2, images_per_turn=2`` (4 images total), the trainer
saw a subset → wildly wrong attention → mismatch KL jumped from
~0.04 to ~7 (>100× regression). On Qwen3-VL the model raised
``ValueError: Image features and image tokens do not match`` when the
delta drop left the trainer with fewer feature blocks than placeholder
runs.

Fix: track ``start_step_idx`` per active sample and concatenate
``mm_items`` / ``mm_hashes`` across ``[start_step_idx, last_step_idx]``
in step order. No dedup here — verifiers' delta already handled
cross-step dedup with multiset semantics (legitimate duplicate
placeholders, where the same image appears in two turns' separate
placeholder runs, are preserved).

Test plan:
- ``uv run pytest tests/unit/orchestrator/test_trajectories.py`` — 20 passed
- ``uv run pytest tests/unit/orchestrator tests/unit/train`` — 216 passed, 6 skipped, 1 xfailed
- ``uv run rl @ configs/multimodal/rl_color_codeword_feat_renderer.toml``
  on 2× RTX PRO 6000: Step 0 KL **0.020** (was 7.0), Step 1 **0.090**,
  Step 2 **0.253** — all within the baseline range published in #2473
  (max 0.487 across 20 steps).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(orchestrator): track explicit step indices per sample for mm union

interleave_rollout used (start_step_idx, last_step_idx) to bound the
mm_data union per sample. When agents interleave (e.g. agent1 at steps
0,1,3 and agent2 at step 2), the range [0,3] over-collects step 2 and
agent2's delta mm_items leak into agent1's sample.mm_kwargs — placeholder
count vs. patch count mismatches at the VLM forward.

Replace the (start, last) pair with the explicit list of prepared_steps
positions merged into the sample. _union_step_mm_data iterates the list
directly, so non-owned steps are skipped by construction.

Non-interleaved trajectories produce step_indices = [0..N], iterating
identically to the old range — bit-for-bit unchanged for the common path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: eligotts <78387377+eligotts@users.noreply.github.com>
2026-05-20 19:00:55 -07:00
44dcc5ab40 fix(slurm): release allocation when any component crashes (#2577)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Previously a trainer/inference/orchestrator/router crash left surviving
components running, holding the SLURM allocation until walltime. The
sbatch script propagates the failure now:

- srun uses --kill-on-bad-exit=1 so a non-zero exit on any task kills
  tasks on the other nodes.
- All per-node components run in the background; `wait -n` turns the
  first exit (success or crash) into the task exit code, surfacing
  background crashes (router, orchestrator) that the previous foreground
  layout silently ignored.
- `set -o pipefail` inside the task and `set -e` in the outer sbatch
  keep failures from being swallowed by `| tee` or by setup commands.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 17:04:39 -07:00
271801bd4d fix(wandb): handle shared mode breakage from wandb v0.26.1 (#2578)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(wandb): handle shared mode breakage from wandb v0.26.1

wandb v0.26.1 (PR #11759) changed `inform_init` to propagate
duplicate stream ID errors as `ServerResponseError` instead of
silently swallowing them. This breaks shared mode where multiple
processes intentionally call `wandb.init(id=same_run_id)`.

- Add `resume="allow"` when a run ID is provided so wandb attaches
  to the existing run instead of rejecting it
- Catch `ServerResponseError` (alongside `CommError`) for non-primary
  shared-mode processes to handle transient init races

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(wandb): teardown wandb-core between init retries

A failed wandb.init leaves the run_id registered in the local
wandb-core StreamMux. The next retry hits the same wandb-core,
finds the stream still there, and raises ServerResponseError
("run ID ... is in use") regardless of resume="allow" — the check
fires before reaching the server.

Tearing down the service before sleeping clears the StreamMux so
the retry starts fresh. Also catch ServerResponseError on the
primary side, since the race is symmetric: either side can win
the upsertBucket and the other can hit this path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-20 17:00:04 -07:00
851233e5de feat(release): automated tagging + release flow (#2573)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(release): add tag-and-release workflow, backfill release notes, expand release skill

Port the verifiers tag-and-release pattern: on version bump in pyproject.toml,
auto-tag main and create the GitHub Release using assets/release/RELEASE_v{tag}.md
as the body. Skip the PyPI publish steps since prime-rl is not on PyPI.

Backfill release-note files for v0.1 through v0.5.0 by copying each existing
GitHub Release body so the workflow has historical artifacts to compare against.

Expand skills/release/SKILL.md so an agent can prepare the full release PR
(version bump, release notes file, draft PR) — merging the PR is then enough
to publish the release.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(release): rename v0.1/v0.2 notes to v0.1.0/v0.2.0 for consistency

Aligns all backfilled release note filenames on a MAJOR.MINOR.PATCH suffix.
The historical GitHub tags (v0.1, v0.2) keep their original names; this only
touches the on-disk filenames.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(ci): rename release.yaml to docker-push.yaml; exclude dev tags from tag-and-release

The old release.yaml only builds and pushes the Docker image; the new
tag-and-release.yaml is now the canonical "release" workflow. Renaming
removes the ambiguity.

Add a trigger filter to tag-and-release so '*dev*' tags do not flow through
the release path. devx_tag.yaml creates dev tags via GITHUB_TOKEN, which
already does not retrigger workflows; this exclusion is defensive for any
manual dev-tag pushes. Skill note updated to clarify the two workflows
coexist.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(ci): check release notes before tagging, and retry on tag-without-release

Two bugbot fixes in tag-and-release.yaml:

1. Move the assets/release/RELEASE_*.md presence check into auto-tag-on-main,
   before the tag is created and pushed. Missing notes used to fail in
   release-from-auto-tag, but only after the tag was already on the remote,
   blocking a clean retry.

2. If the target tag already exists (locally or on origin) but no GitHub
   Release exists for it yet, still emit created=true so release-from-auto-tag
   runs against the existing tag. This unblocks recovery from a partial
   failure (e.g. the release step crashed after the tag push) without
   requiring manual cleanup or workflow_dispatch.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(release): drop in-repo release notes; promote pre-existing draft release on tag

Pivot the release flow:
- Release notes live as a draft GitHub Release created via `gh release create
  --draft` (no longer tracked in the repo). Removed assets/release/*.
- The release skill instructs an agent to (1) draft the release on GitHub
  with the notes inline and (2) open a draft PR that only bumps `version` in
  pyproject.toml.
- On merge, tag-and-release verifies the draft release exists for the new
  tag, pushes the tag, then promotes the draft via `gh release edit
  --draft=false --latest`. Recovery path: if the tag exists with a draft,
  the next main push (or workflow_dispatch) re-promotes it.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 14:43:06 -07:00
7f7ce8a0f4 chore(skills): slim skills, rename, regroup under training/ (#2576)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore(skills): slim skills, rename, regroup under training/

Rename `config` -> `configs`, `installation` -> `install`. Move
`entrypoints` (as `start-run`) and `monitor-run` under a new
`training/` skill. Slim each skill (~37% fewer lines overall) and
fact-check paths/commands against the current codebase — most
notably the config-class paths now live under
`packages/prime-rl-configs/`, and rollouts are saved to
`{output_dir}/rollouts/step_N/` (no `run_default` prefix).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(skills): drop tyro mention in configs skill

pydantic-config is now Pydantic-only (TOML + CLI), no tyro dependency.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(skills): drop unsupported `@ toml --help` example

`pydantic-config` doesn't merge TOML into `--help` output; only the
class-level defaults are shown either way. Keep the plain `--help`
and `--dry-run` examples instead.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(skills): summarize pydantic-config features in start-run; trim configs

- start-run: add a brief feature summary of `pydantic-config` so the
  config primitives are visible alongside the launch commands.
- configs: drop the SFT/RL domain notes (they belong with the
  respective training docs, not the config primer) and collapse the
  two config-package paths in "Key files" into one line.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 14:27:48 -07:00
09e2977437 feat(config): regex-based auto-resolution of tool-call & reasoning parsers (#2569)
Release / Push CUDA image to Docker (push) Canceled after 0s
Replace the ~100-entry MODEL_TOOL_CALL_PARSER dict + runtime resolver in
server.py with regex patterns in utils/parsers.py — new model variants
match automatically without a dict entry per checkpoint. Reasoning parser
gets the same treatment (previously only the tool-call side auto-resolved).

Resolution moves to a ModelConfig after-validator (auto_resolve_parsers),
not the entrypoint. It piggybacks on RLConfig's before-validator
propagation: the shared [model] name lands in inference.model.name BEFORE
ModelConfig is constructed, so the after-validator sees the resolved name.
Testable without a running server.

Also fixes INTELLECT-3 / Qwen3-Coder mapping from hermes to qwen3_coder,
which matches the upstream HF model docs.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 10:57:33 -07:00
fa191e589b refactor(config): propagate shared RL fields via before-validator (#2565)
Release / Push CUDA image to Docker (push) Canceled after 0s
pydantic-config 0.3 (drop-tyro, #2564) removed the typed-default mirror
that previously round-tripped CLI args through tyro. With that gone, a
``mode="before"`` validator on RLConfig now sees a clean dict-of-dicts and
can propagate shared top-level fields into the right sub-config keys
*before* sub-configs are constructed. Sub-configs' own ``mode="after"``
validators then see the resolved values (e.g. ``OrchestratorConfig.auto_setup_tokenizer``
sees the propagated ``student.model.name`` at the moment it derives
``tokenizer.name``, instead of running with the stale class default and
then being patched up by a load-bearing RL-level re-derive).

Replaces eight per-field ``auto_setup_*`` ``mode="after"`` validators with
a single ``auto_setup_shared_configs`` ``mode="before"`` validator using a
``fill``-if-absent helper. The previous fix-up at the RL level
(``auto_setup_tokenizer``'s "no shared tokenizer: re-derive from
(now-correct) model names") silently overrode explicit
``[orchestrator.tokenizer] name = ...`` values; with the before-validator,
explicit sub-config values survive untouched.

Also:
  - keep per-field mutex ``validate_no_shared_field_conflicts`` —
    duplicating a field in shared + sub-config is still ambiguous and the
    mutex catches it explicitly.
  - drop ``RLConfig.max_model_len`` — declared but never wired to a
    validator. Users set ``inference.model.max_model_len`` directly.
  - move ``auto_setup_session_headers`` from RLConfig onto
    ``OrchestratorConfig`` (now ``self.student.client``), so the hosted
    orchestrator entrypoint also enforces it when loading standalone.
  - collapse the per-field ``validate_shared_*`` calls into a single
    ``validate_shared_configs`` ``mode="after"`` validator that runs the
    full consistency suite post-construction.
  - add ``validate_shared_seq_len`` to ``utils.validation`` and the
    propagation map; ``seq_len`` now also goes through the same flow.

Tests (``tests/unit/test_configs.py``): 24 new cases covering propagation
of ``model.name`` / ``tokenizer`` / ``seq_len`` / ``max_steps`` /
``output_dir`` / ``[ckpt]`` / ``[wandb]``, the per-field mutex on every
shared key, the "empty shared block coexists with sub-block" rule, the
"disjoint shared + sub fields coexist" rule, and end-to-end CLI override
of ``--seq-len`` propagating through TOML.

Crucially, ``test_explicit_subconfig_tokenizer_name_survives_shared_model_propagation``
regression-tests the case that the old RL-level fix-up silently broke:
shared ``[model] name`` propagates everywhere it should, but an explicit
``[orchestrator.tokenizer] name`` is left alone.

Three in-repo configs were tripping the new mutex; same fixes:
  - configs/hendrycks_math/sanity.toml: drop redundant ``[trainer.model] name``
  - examples/hendrycks_sanity/rl.toml: drop redundant ``[trainer.model] name``,
    move shared ``seq_len = 8192`` under ``[orchestrator]`` so the trainer
    keeps its longer 16384 context
  - examples/glm5_pd_disag/rl.toml: split shared ``[model] name`` into
    per-component names (trainer = GLM-5 BF16, orchestrator + inference =
    GLM-5-FP8 to satisfy ``validate_shared_model_name``).

Closes #2430. Supersedes #2517 — the same approach, rebased onto
post-tyro pydantic-config which removes the need for the
``_dump_preserving_discriminators`` workaround the original PR carried.

CPU suite (matches cpu_tests.yaml): 374 passed.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 09:36:57 -07:00
d718fddaa4 chore: bump version to 0.5.0 (#2571)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 22:47:40 -07:00
1f26eeeb52 feat: convert config field descriptions to docstrings + config simplification (#2567)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore(configs): convert field descriptions to PEP 224 docstrings

Now that the pydantic-config bump supports attribute docstrings, switch
every config field from ``Annotated[T, Field(description=...)]`` to a
plain typed assignment plus a single-line docstring on the next line.
``Field(...)`` is kept only where it carries other metadata
(``ge=``/``gt=``, ``validation_alias=``, ``default_factory=``).

Descriptions are tightened: dropped redundant restatements of the field
name, dropped mentions of defaults and aliases (the help renderer shows
those automatically), and dropped pydantic model docstrings (mostly
redundant). Net change is ~1.4k fewer lines across the seven config
modules.

Bumps the pydantic-config submodule to pick up MRO-aware docstring
extraction (so inherited fields keep their description) and
``default_factory`` rendering in --help.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(configs): drop trivial sub-config docstrings, base DUV variants on BaseConfig

- Drop sub-config field docstrings that just restated the field name
  (e.g. ``"""Logger configuration."""`` on ``log: LogConfig``). Without
  the docstring the help renderer falls back to ``<path> options`` for
  the panel title, which is just as readable. Keep docstrings that carry
  real info (gating semantics, propagation, side-effects, etc.).
- Switch every discriminated-union variant (and standalone ``BaseModel``
  configs like ``KVCacheOffloadConfig``) from ``BaseModel`` to
  ``BaseConfig`` and drop the per-class
  ``model_config = ConfigDict(extra="forbid")`` line — ``BaseConfig``
  already bakes in ``extra="forbid"`` and the TOML ``"None"`` →
  ``None`` coercion, so this is both leaner and more consistent (some
  variants previously had ``extra="forbid"``, others did not).
- Fix typo in ``examples/wordle/sft.toml`` (``micro-batch-size`` →
  ``micro_batch_size``) that was silently dropped under the old
  ``extra="ignore"`` and would now be rejected.
- Bump pydantic-config submodule to the merged upstream commit
  (PrimeIntellect-ai/pydantic-config#12) for MRO-aware docstring
  extraction and ``default_factory`` rendering in ``--help``.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deps): bump pydantic-config to merged help-rendering fixes

Picks up PrimeIntellect-ai/pydantic-config#13: per-panel flag column
widths, 60-char cap on the flag column with oversize flags rendered on
their own line, inline ``(default: X)`` in place of the right-aligned
annotation column, and title/flag wrapping so the box always fits the
terminal width.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deps): bump slim-wheel pydantic-config floor to 0.3.0.dev82

The PyPI floor on ``prime-pydantic-config`` only matters for the slim
wheel install (plain ``pip install prime-rl-configs`` outside the uv
workspace). Bump it to ``0.3.0.dev82``, the dev release auto-published
when PrimeIntellect-ai/pydantic-config#13 merged — the help-rendering
fixes prime-rl now relies on for clean ``--help`` output.

Workspace installs are unaffected; they keep resolving
``prime-pydantic-config`` editable from ``deps/pydantic-config`` via
the root ``[tool.uv.sources]`` override.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 22:11:58 -07:00
90e9ae98bf fix(tests): bump benchmark regression METRIC_TOLERANCE to 15% (#2570)
Release / Push CUDA image to Docker (push) Canceled after 0s
The 4-GPU step time test flaked at 55.50 vs an upper bound of 55.44 (10.13%
measured deviation) on run 26141695659. Slight bump to 15% to absorb runner
variance between hyperstack (baseline) and massed compute A6000s.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 22:11:02 -07:00
67cdc55521 perf(cli): defer heavy imports so --help short-circuits in cli() (#2566)
Release / Push CUDA image to Docker (push) Canceled after 0s
* perf(cli): defer heavy ML imports so --help short-circuits in cli()

The rl/sft/trainer/orchestrator entrypoints loaded torch, transformers,
torchtitan and friends at module top — so `--help` blocked on ~10s of
import work before cli() got a chance to exit. Mirror the inference
entrypoint pattern: keep module top light, push heavy imports into the
function body that actually uses them.

For `trainer` and `orchestrator`, add lightweight shim entrypoints under
src/prime_rl/entrypoints/ (the heavy implementation modules stay
runnable via `python -m` for torchrun).

--help timings:
  inference   0.35s -> 0.14s
  rl          9.96s -> 0.42s  (24x)
  trainer    10.21s -> 0.20s  (51x)
  sft        10.42s -> 0.20s  (52x)
  orchestrator 9.20s -> 0.24s (38x)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* perf(cli): drop redundant _compat import from rl/sft entrypoints

`prime_rl._compat` is already imported at the only two files that
directly pull in ring_flash_attn (`utils/cp.py:4` and
`trainer/models/layers/ring_attn.py:4`, both with ruff:noqa: I001 to
lock the order). Any transitive import path reaches one of those before
ring_flash_attn loads, so the entrypoint-level import is redundant.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:16:48 -07:00
d3e478d732 chore(deps): bump pydantic-config (drop tyro) (#2564)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore(deps): bump pydantic-config to refactor/drop-tyro tip (1659db2)

Point both the submodule and the pyproject.toml source at
PrimeIntellect-ai/pydantic-config @ 1659db2, the latest commit on
refactor/drop-tyro. The package is renamed to prime-pydantic-config,
so update prime-rl-configs and tool.uv.{sources,exclude-newer-package}
accordingly.

Brings in the legacy key remapping (via before-validators), so e.g.
`uv run orchestrator --model.name <name>` now routes to
`student.model.name`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deps): wire pydantic-config submodule as editable workspace member

Add deps/pydantic-config to [tool.uv.workspace] members and switch the
source from a pinned git rev to { workspace = true }. uv now installs
prime-pydantic-config editable from the submodule on disk, so local
edits propagate to .venv without re-syncing a wheel.

Drop the [tool.uv.exclude-newer-package] entry — that knob only matters
for non-workspace pins.

Bumps the submodule pointer to df5b38e to pick up the upstream ruff
bump (==0.5.0 -> >=0.12.1), which is required so prime-pydantic-config's
dev group unifies with prime-rl's (ruff>=0.12.1).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deps): pin slim-wheel prime-pydantic-config dep to a git rev

The slim wheel CI installs prime-rl-configs in a venv with no workspace
context, so it has to resolve prime-pydantic-config from somewhere
reachable. PyPI only has older 0.3.0.dev* wheels that pre-date the new
RLConfig schema, so the slim parse test was tripping on them.

Embed the git URL directly in the dep string (same pattern as before
the rename, just pointed at PrimeIntellect-ai's repo + the rev we
already track via submodule). In-workspace builds keep using the
editable submodule via the root [tool.uv.sources] override.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deps): bump pydantic-config to 7481096

Pulls in fix for --no-optional.field negation, "did you mean" hints,
and stale tyro refs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deps): bump pydantic-config submodule to main (ab3a8e7), pin slim wheel to PyPI 0.3.0.dev80

refactor/drop-tyro merged into pydantic-config's main as ab3a8e7. Bump
the submodule to that tip and switch the slim-wheel dep from a git URL
to the PyPI release (`prime-pydantic-config>=0.3.0.dev80`, auto-published
on the merge). uv workspace install still uses the editable submodule
via the root [tool.uv.sources] override.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ci): use [model] alias on CLI for multi_run orchestrator overrides

The orchestrator TOML uses the legacy `[model]` shortcut (which
`fold_student_shortcuts` re-routes to `student.model`). Pairing that with
`--student.X` CLI overrides triggers an alias-collision in the bumped
pydantic-config's `_normalize_alias_keys`: both `model` (from TOML) and
`student` (from CLI) survive the deep-merge, and the canonical-key pass
overwrites instead of merging — silently resetting `student.model.name`
to the default. Inference servers serve the wrong model and the
orchestrator times out before reaching Step 11.

Keep all layers on the `model` alias by using `--model.lora.name` and
`--model.client.base-url`. Pydantic-config side fix lands separately.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:02:34 -07:00
d8698f4e53 test(ci): add reverse-text smoke tests for RL OPD + SFT training modes (#2563)
Release / Push CUDA image to Docker (push) Canceled after 0s
* test(ci): add reverse-text smoke tests for RL OPD + SFT training modes

Covers the rl-entrypoint training_mode = "opd" / "sft" paths on the
existing `vm` integration runner. The student inference deployment is
launched by the rl entrypoint; the teacher is started as a dedicated
`uv run inference` process by the test fixture (low gpu_memory_utilization
on GPU 0 so the student still fits), with orchestrator.teacher.client
pointing at it.

Both tests pass locally on 2× Blackwell GPUs in ~1m40s each.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(ci): match reverse_text training config + symmetric 0.4 gpu util

Aligns max_steps / seq_len / batch_size / rollouts_per_example / max_completion_tokens
with the existing reverse_text smoke test, and switches the student+teacher
overlap from asymmetric (0.85 + 0.1) to symmetric 0.4 + 0.4 — both fit on one
Blackwell GPU with the small Qwen3-0.6B models. Both tests still pass locally
(~2m10s each).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(ci): drop to 5 steps and remove [ckpt] for the OPD/SFT smoke tests

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(ci): drop [deployment] and enforce_eager from OPD/SFT configs

Matches the rest of `configs/ci/integration/` — the default
SingleNodeDeploymentConfig (1 train + 1 infer GPU, gpus_per_node=8)
works on the 2-GPU vm runner, and no other CI config sets
enforce_eager. OPD test still passes locally (2m18s).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test(ci): assert eval reward goes up instead of loss goes down

Loss going down is a weak signal for distillation training modes — both OPD
(KL-style) and SFT (teacher-token CE) loss curves are noisy across the 5
smoke steps. Switch to checking that the per-step eval reward on the same
reverse-text env actually improves end-to-end.

- Add [orchestrator.eval] (interval=1, num_examples=16) to both configs.
- New `check_eval_avg_goes_up` helper greps the orchestrator log for
  "Evaluated <env> ... Avg@K=X.XXXX" and asserts last > first.

Both tests pass locally (OPD 1m52s, SFT 1m42s).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 15:30:44 -07:00
rasdaniandGitHub 845eb6e6f2 Scrub padded vLLM model inputs (#2506)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Scrub padded vLLM model inputs

* Fix padded input scrub vLLM wrapper

* Document vLLM patch removal points
2026-05-19 21:31:23 +02:00
eaf95997f7 feat: first-class sft+opd training modes (#2546)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: add student eval inference pool for SFT hard distillation

When teacher_rollout_model is configured for SFT distillation, the
orchestrator now supports a separate student inference pool for online
evals and weight sync. Previously, configuring [inference] alongside
teacher_rollout_model was forbidden — evals either ran on the teacher
or were skipped entirely.

Changes:
- Relax RLConfig validator to allow [inference] + teacher_rollout_model
- Create eval_inference_pool from config.client when teacher_rollout_model
  is set, pointing at the student vLLM server
- Route eval calls and weight updates to the student pool
- Add eval_inference_pool param to Scheduler for weight sync targeting
- All existing RL/soft-distill paths are unchanged (eval_inference_pool
  defaults to inference_pool when no teacher_rollout_model is configured)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: keep hard distill student eval pool optional

* fix: scope teacher rollout routing

* fix: address teacher rollout review comments

* fix: clarify teacher rollout client routing

* fix: honor teacher rollout client type

* refactor(orchestrator): rename model/teacher_model to student/teacher

Consolidates 3 training modes (rl, opd, sft) under a unified config
structure: `student` (always present) and `teacher` (optional, role
determined by `training_mode`). Removes scattered flags (`use_sft_loss`,
`update_student_inference_weights`) in favour of a single discriminator.

Backward-compat aliases (`model` → `student`, `teacher_model` → `teacher`)
keep existing TOML configs parsing without changes.

Also adds `configs/reverse_text/debug_{rl,opd,sft}.toml` for local
mode debugging.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): cap reverse-text debug eval at 64 examples

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): cap reverse-text debug eval completion tokens at 128

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): use correct PI inference teacher model name

qwen/qwen3-4b-instruct doesn't exist on PI inference;
use Qwen/Qwen3-4B-Instruct-2507 instead.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): use qwen3-30b-a3b-instruct as debug teacher model

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): correct teacher model name to qwen3-30b-a3b-instruct-2507

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(client): add headers_from_env to ClientConfig

Maps header names to env var names, resolved at client setup time.
Analogous to api_key_var but for arbitrary headers. Useful for e.g.
X-Prime-Team-ID when hitting the PI inference API.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(client): auto-inject X-Prime-Team-ID header for PI inference

When ClientConfig.base_url targets pinference.ai, auto-add a
headers_from_env mapping for X-Prime-Team-ID -> PRIME_TEAM_ID so team
billing works without each config repeating the boilerplate.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): set debug eval to 256 rollouts (64 examples x 4)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): use local vLLM teacher for debug OPD instead of PI inference

PI inference is OpenAI-compatible but doesn't expose vLLM's
/inference/v1/generate prefill endpoint that compute_teacher_logprobs
needs - so OPD against PI inference 404s. SFT mode kept working
because that path only hits /chat/completions.

Switch debug_opd.toml to use the existing teacher_inference auto-setup:
set num_teacher_gpus = 1, and an empty [orchestrator.teacher] block to
satisfy the orchestrator validator (which runs before
auto_setup_teacher_inference can populate it). The validator chain
spins up a local vLLM teacher on port 8001 using the same reverse-text
student model.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs+validate: training modes grid + cross-config constraints

- Add docs/training_modes.md with the rl/opd/sft role grid, implications
  (e.g. OPD needs local vLLM teacher, SFT teacher is any OAI-compatible
  endpoint), and minimal config per mode. Linked from mint.json nav.
- Add validate_training_mode_loss_consistency on RLConfig enforcing:
  sft mode <-> sft loss type, opd mode requires teacher_tau > 0,
  non-sft modes forbid sft loss type. These cross orchestrator and
  trainer fields so they live on RLConfig (per-component validators in
  OrchestratorConfig already cover the within-orchestrator constraints).
- Fix debug_sft.toml to set trainer.loss.type = "sft" (was relying on
  default loss which is now explicitly rejected).
- Make training_mode explicit in debug_rl.toml and debug_opd.toml.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(configs): lift training_mode to RLConfig + point debug teacher at local vLLM

- Add shared training_mode field to RLConfig (rl | opd | sft). A mode="before"
  validator propagates it into orchestrator.training_mode and (for sft)
  trainer.loss.type before nested validation runs. Must be a before-validator
  because OrchestratorConfig.validate_training_mode would otherwise reject
  configs like training_mode = "opd" + [orchestrator.teacher] - the
  orchestrator-level default of "rl" would conflict with the teacher block
  before the after-validator could propagate the shared value.

- Point debug_opd and debug_sft at a manually-deployed teacher vLLM
  (Qwen3-0.6B-Reverse-Text-RL on localhost:8001). Add a comment with the
  exact teacher start command at the top of each config. Drop the
  num_teacher_gpus auto-launch from debug_opd since we now use the
  external teacher.

- Set student inference gpu_memory_utilization = 0.5 in all three debug
  configs (matches the teacher's mem budget, leaves room when both are
  co-located).

- Add configs/reverse_text/README.md with the start commands.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: drop GPU-occupancy runtime check; teacher uses uv run inference

- Remove check_gpus_available in rl entrypoint - it raised RuntimeError
  when other processes held GPUs, which blocked iterating with a
  long-lived teacher inference server on a sibling GPU.
- Update debug_opd / debug_sft / README to start the teacher via
  uv run inference (the prime-rl variant) instead of raw vllm serve.
  Same port (8001), same model, same flags.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): accept legacy flat [orchestrator.model.lora] layout

Pre-refactor, orchestrator.model was a ModelConfig directly (name, lora,
trust_remote_code, vlm). After the student/teacher rename it's a
RolloutModelConfig wrapping ModelConfig + ClientConfig, so existing
[orchestrator.model.lora] TOML sections stopped parsing because they
landed on the wrong nesting level.

Add a mode="before" validator on RolloutModelConfig that detects a flat
ModelConfig dict (any of {name, trust_remote_code, vlm, lora} at the top
level, no nested model/client keys) and re-nests it under "model". This
lets the three existing LoRA configs revert to their original syntax.

Also fix examples/alphabet_sort/sft_distill_hard.toml: hoist training_mode
to the top-level shared field so trainer.loss.type = "sft" gets auto-set
(previously the orchestrator-only flag triggered the new sft/loss
consistency validator).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(orchestrator): split into student_inference + teacher_inference pools

Replace the "one pool plus optional teacher-client overlay" model with two
explicit pools:

- student_inference: InferencePool | None
  - Required for rl/opd, optional for sft (set iff [inference] is configured)
  - Target for evals, weight broadcast, and inference metrics
  - When None, online evals and policy updates are skipped automatically
- teacher_inference: InferencePool | None
  - Set whenever orchestrator.teacher is configured (opd or sft)
  - Source of teacher logprobs in opd
  - Source of train rollouts in sft
  - Always MITO (chat completions) for simplicity; external OAI-compatible
    teachers (PI inference, OpenAI) work as drop-in endpoints

Scheduler now takes both pools and resolves the rollout target internally
(rollout_inference = teacher_inference if sft else student_inference).
The old _resolve_rollout_request_target overlay is gone - the rollout pool
serves rollouts directly. Fixes a latent bug where SFT-mode LoRA updates
would overwrite scheduler.model_name and route subsequent teacher requests
with the student's LoRA name.

Also:
- Drop setup_external_rollout_model (logic is now inline + clearer)
- Rename setup_rollout_inference_pool -> setup_student_inference_pool;
  always handles only the student pool, teacher is plain setup_inference_pool
- Log the resolved training_mode + one-line description at orchestrator start
- Update tests: cover both sft (rollout != student) and rl (rollout = student)
  LoRA paths; drop the now-obsolete teacher-overlay scheduler test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs+configs: legacy [orchestrator.client] shim + merge OPD doc into training_modes

- Add _accept_top_level_client validator on OrchestratorConfig: legacy
  [orchestrator.client...] re-nests under [orchestrator.student.client...]
  matching the existing _accept_flat_model_layout shim pattern. Revert
  configs/elastic/rl.toml back to the original [orchestrator.client.elastic]
  syntax.
- Revert configs/ci/integration/reverse_text_multi_run/orchestrator.toml
  [model.model] -> [model]; the flat-layout shim on RolloutModelConfig
  already handles it (verified).
- Merge docs/on_policy_distillation.md into docs/training_modes.md. The
  training_modes page is now the single entry point; OPD-specific details
  (external teacher, pure distillation, monitoring, VLM, params) live as
  subsections. Delete the standalone OPD page.
- Drop the redundant "Initializing static inference pool" / WandbMonitor /
  PrimeMonitor init logs - they duplicate the immediately-preceding
  per-pool init line.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(orchestrator): probe teacher for prompt_logprobs before training

In OPD mode, send a tiny probe request to the teacher's /inference/v1/generate
endpoint after the pool is ready. If the endpoint 404s or doesn't return
prompt_logprobs, raise an informative error pointing at docs/training_modes.md
instead of crashing mid-training with a 404.

Verified that PI inference fails this probe on all three plausible routes:
- /inference/v1/generate -> 404
- /v1/chat/completions with logprobs=true -> logprobs:null in response
- /v1/completions with echo=true,logprobs=1 -> 404

Also add configs/reverse_text/debug_sft_thinking.toml: SFT from
qwen3-30b-a3b-thinking-2507 via PI inference (sft path needs only
chat completions, so PI inference is fine here).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(orchestrator): deprecate use_token_client (server-tokenized TITO)

Drop the server-tokenized TITO path (``openai_chat_completions_token`` /
``/v1/chat/completions/tokens``). The orchestrator now picks between
renderer-backed TITO (``use_renderer = true``, default) and MITO
(``use_renderer = false``, fallback for VLMs and external teacher rollouts).

- Remove ``OrchestratorConfig.use_token_client`` field and its validators
- Drop the TITO branch in ``setup_rollout_inference_pool``
- Drop the obsolete TITO warning in ``setup_inference_pool`` and flip the
  default ``train_client_type`` to ``openai_chat_completions`` in
  ``StaticInferencePool`` / ``ElasticInferencePool``
- Strip ``use_token_client = false`` from configs/examples/docs that
  carried the no-op fallback line
- CHANGELOG entry documenting the breaking removal

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(inference): remove server-side TITO route

Drop the ``/v1/chat/completions/tokens`` endpoint and the
``OpenAIServingChatWithTokens`` / ``ChatCompletionRequestWithTokens``
wrappers now that no client routes to them. Also drop the obsolete
``base()`` helper and unused imports from ``server.py``.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: require student_inference in all training modes

Student inference was already required for rl/opd and optional for sft;
making it required everywhere simplifies the orchestrator + scheduler:

- Drop has_student_inference / enable_policy_updates gating
- student_inference: InferencePool (no longer Optional) in Scheduler.__init__
- Weight broadcast init, weight sync, metrics collector, eval routing, and
  shutdown all unconditionally use student_inference
- Drop the now-stale OPD probe (will revisit in a follow-up PR)
- Add is_vlm property on BaseModelConfig; replace local is_vlm vars in the
  orchestrator with config.student.model.is_vlm
- Merge the two legacy student-layout shims on OrchestratorConfig into one
  before-validator (_accept_legacy_student_layout) covering both
  [orchestrator.client.*] and flat [orchestrator.model.<k>] paths
- Drop redundant pool / WandbMonitor / PrimeMonitor init log lines
- Reorder OrchestratorConfig fields: training_mode > student > teacher
- Drop "OAI" from RolloutModelConfig.client description
- Update docs/training_modes.md: SFT student inference is now required;
  evals and weight sync are unconditional

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(configs): default OPD to pure distillation (teacher_tau=1, adv_tau=0)

auto_setup_training_mode now seeds trainer.loss defaults when training_mode
is opd: teacher_tau=1.0 and adv_tau=0.0 (pure distillation: drop the reward
signal, full weight on the teacher KL). User-provided values still win via
setdefault. Also accept training_mode set only inside [orchestrator] - same
auto-setup applies for both the shared top-level and orchestrator-local
forms.

Drop the redundant [trainer.loss] teacher_tau = 0.5 block from
configs/reverse_text/debug_opd.toml; verified the auto-setup applies
end-to-end (3 train steps, teacher logprobs computed each step, clean exit).

Also drop the now-redundant InferencePool type annotation on
self.rollout_inference - both branches assign a definite InferencePool now
that student_inference is non-Optional.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): rename debug_sft_thinking -> debug_sft_external; drop examples/alphabet_sort/sft_distill_hard.toml

debug_sft_external describes the role better - external SFT teacher via
OAI-compatible endpoint (PI inference). The "thinking" label was about the
specific model the config picks (qwen3-30b-a3b-thinking-2507), not about
what the config demonstrates.

Drop examples/alphabet_sort/sft_distill_hard.toml: configs/reverse_text/
debug_sft* are the canonical SFT examples now.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(tests): unbreak CPU tests after student/teacher rename + headers_from_env

- tests/unit/train/test_runs.py: orchestrator config attribute access
  changed from config.model.name to config.student.model.name after the
  RolloutModelConfig rename.
- tests/unit/utils/test_elastic.py: MagicMock client_config needs
  headers_from_env set to {} - the field was added in this PR and the
  test's hand-built mock missed it (pydantic rejects MagicMock as a dict).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(orchestrator): strip logprobs from train sampling in sft mode

The trainer in sft mode reconstructs teacher tokens via the student
tokenizer - it never reads inference-side logprobs from the teacher
endpoint. Stripping logprobs at runtime lets external reasoning-model
endpoints (openai/gpt-5*, etc.) accept the rollout request - they
reject logprobs with 400 invalid_request "logprobs are not supported
with reasoning models".

Done at orchestrator-startup time on each TrainEnv's sampling_args
rather than as a public config field, since this is a mode-specific
runtime concern.

Also: bump configs/reverse_text/debug_sft_external.toml to use
openai/gpt-5-mini (faster than qwen3-30b-a3b-thinking-2507).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): bump debug_sft_external for gpt-5-mini reasoning budget

gpt-5-mini's max_completion_tokens budget includes reasoning tokens.
At 128 the model burned the whole budget on internal CoT before
producing the final answer, returning empty content. Raise to 2048
and set reasoning_effort=minimal so the chat-completions response
includes the actual output.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: fix stale SFT references after the student/teacher refactor

- skills/config/SKILL.md: update the SFT hard distill section -
  orchestrator.teacher_model -> orchestrator.teacher, drop the
  "student inference is optional" guidance (the orchestrator now
  unconditionally sets up student_inference), and add a note that
  shared training_mode auto-propagates to trainer.loss.type.
- rl.py: auto_setup_inference_client docstring referenced the deleted
  setup_external_rollout_model function. Rewrite to explain what the
  validator actually does for each mode.

Also note the behavior change in the PR description: SFT now requires
[inference] (was previously optional).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(loss): batch-driven loss dispatch via TrainingSample.training_mode

Replace TrainingSample/MicroBatch.sft_loss bool with training_mode literal
(rl|opd|sft). The trainer's compute_loss reads training_mode from the
micro batch and dispatches:

- "sft"     -> sft_loss_fn (masked NLL on teacher tokens)
- "rl"      -> default_loss_fn with (adv_tau=1.0, teacher_tau=0.0)
- "opd"     -> default_loss_fn with (adv_tau=0.0, teacher_tau=1.0)

Taus move from trainer.loss config to compute_loss's mode->tau table and
flow into LossInputs per batch; DefaultLossConfig drops the teacher_tau /
adv_tau fields. The orchestrator stamps each sample with
config.training_mode at the same point it used to set sft_loss.

Packer enforces same-mode packing (samples with different training_mode
cannot share a micro batch). RLConfig drops the OPD tau auto-setup +
"opd requires teacher_tau > 0" validator + the validate_teacher_model
teacher_tau gate (all redundant under batch-driven dispatch).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): dedicated opd_loss_fn instead of routing taus through inputs

Replace the per-batch adv_tau/teacher_tau routing through LossInputs with a
dedicated opd_loss_fn that lives alongside default_loss_fn and sft_loss_fn.
A bit of code dup in opd_loss_fn (clone of default's DPPO math) makes the
two paths read as separate losses rather than the same function with magic
multipliers.

- setup_loss_fn -> setup_loss_fns: returns a dict {training_mode: LossFn}.
  rl uses the configured loss (default/custom). opd uses opd_loss_fn (only
  available when loss_config is DefaultLossConfig). sft is always available.
- compute_loss takes loss_fns + training_mode, looks up the right fn.
- opd_loss_fn requires teacher_logprobs (raises otherwise).
- LossInputs no longer carries adv_tau/teacher_tau - those values are baked
  into each loss fn.
- Add validator: opd mode requires trainer.loss.type = "default".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): drop trainer.loss type discriminator + shared training_mode

Now that loss dispatch is fully batch-driven (TrainingSample.training_mode),
the trainer.loss type union and the shared RLConfig.training_mode propagator
are redundant. Flatten:

- Delete SFTLossConfig (the mode implies it; no fields).
- trainer.loss: DefaultLossConfig = DefaultLossConfig() (flat, not a union).
- trainer.custom_loss: CustomLossConfig | None = None - optional override
  for rl-mode loss only; opd and sft always use opd_loss_fn / sft_loss_fn.
- setup_loss_fns(loss_config, custom_loss) always returns all three keys -
  mixed-mode batches dispatch correctly at the trainer level (orchestrator
  still stamps a single mode per run; that's a separate concern).
- Drop RLConfig.training_mode shared field, the auto_setup_training_mode
  before-validator, and validate_training_mode_loss_consistency. The
  orchestrator-level [orchestrator] training_mode is the single source.

Move training_mode = "sft" out of top-level into [orchestrator] in the
three SFT debug configs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(rl entrypoint): warn for missing [inference] in all modes (incl. sft)

After the always-require-student refactor, sft runs need a student
inference pool too (orchestrator unconditionally creates it for evals +
weight sync). The old "sft mode, using teacher for rollouts" info log
was correct under the old semantics but now silently puts the user on a
path where the orchestrator hangs waiting for a non-existent student
server at the default localhost:8000. Replace with a single warning
that prints the configured student base_url and flags the hang risk.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): make opd_loss_fn's tau values explicit (adv_tau=0, teacher_tau=1)

Mirror default_loss_fn's structure literally: declare the two tau locals at
the top, then use them in the same `adv_tau * advantages + teacher_tau *
teacher_kl.detach()` expression. The "this is the default loss with those
specific knobs baked in" relationship is now visible in the code rather than
hidden in a substituted expression.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): restore DefaultLossConfig.adv_tau + LossConfig union (rl-only)

- DefaultLossConfig regains adv_tau (= 1.0). default_loss_fn reads it.
- trainer.loss is back to a discriminated union of DefaultLossConfig |
  CustomLossConfig (drop SFTLossConfig stays dropped). type discriminator
  restored.
- trainer.loss only applies to rl-mode batches. opd and sft batches dispatch
  unconditionally to opd_loss_fn / sft_loss_fn - they don't read trainer.loss.
- opd_loss_fn is self-contained: the DPPO/KL knobs (dppo_mask_*, kl_tau)
  are baked in as module-level _OPD_* constants matching DefaultLossConfig's
  defaults. No loss_config parameter.
- Drop the trainer.custom_loss sibling field (subsumed by the union).

Also add debug_opd_lora.toml + bump lr to 1e-4 in both lora debug configs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(loss): inline opd_loss_fn knobs (no named locals/constants)

Drop the module-level _OPD_* constants and the local adv_tau/teacher_tau
bindings - inline the literal values into the math. Keeps the parallel
structure to default_loss_fn visible: `0.0 * advantages + 1.0 * teacher_kl`
in the same place default_loss_fn has `loss_config.adv_tau * advantages`.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(loss): trim opd_loss_fn docstring

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update reverse_text README — add lora configs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* polish: auto-disable renderer in sft + CHANGELOG + log/shim cleanup

- OrchestratorConfig auto-sets use_renderer=False when training_mode='sft'
  via an after-validator placed before the renderer validators in
  declaration order, so the user doesn't have to set it. Drop the rejecting
  branch in validate_training_mode + the explicit use_renderer=false lines
  in the three sft debug configs.
- CHANGELOG: add a "first-class training_mode + batch-driven loss dispatch"
  entry covering the breaking removals (orchestrator.use_sft_loss,
  orchestrator.teacher_rollout_model, trainer.loss.type='sft' /
  SFTLossConfig, trainer.loss.teacher_tau) with migration notes.
- _accept_legacy_student_layout: use set(ModelConfig.model_fields) instead
  of hardcoding the field list, so new ModelConfig fields are picked up
  automatically.
- Trim the orchestrator startup log to just '(<training_mode>)'; the
  prose description was redundant with docs/training_modes.md.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(configs): unbreak OPD auto-wiring when num_teacher_gpus is set

Add a mode="before" validator on RLConfig that stubs an empty
[orchestrator.teacher] block when deployment.num_teacher_gpus is set and
the user didn't write one. Without this, OrchestratorConfig.validate_training_mode
("opd requires orchestrator.teacher") fires during nested validation - before
auto_setup_teacher_inference can wire the teacher from teacher_inference.

Repro that now passes:

  RLConfig.model_validate({
      "deployment": {"num_teacher_gpus": 1},
      "trainer": {},
      "orchestrator": {"training_mode": "opd"},
      "inference": {},
  })

-> auto_setup_teacher_inference fills in orchestrator.teacher.client.base_url
   = ["http://localhost:8001/v1"] and model.name from teacher_inference.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(training_modes): shrink mode-comparison table + add sft/opd teacher note

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(configs): move training-mode debug configs to configs/debug/training_modes/

The reverse-text debug configs are about exercising the training modes, not
about reverse-text specifically. Move to configs/debug/training_modes/ and
drop the debug_ prefix from each filename (the directory name carries it).

  configs/reverse_text/debug_rl.toml          -> configs/debug/training_modes/rl.toml
  configs/reverse_text/debug_opd.toml         -> configs/debug/training_modes/opd.toml
  configs/reverse_text/debug_opd_lora.toml    -> configs/debug/training_modes/opd_lora.toml
  configs/reverse_text/debug_sft.toml         -> configs/debug/training_modes/sft.toml
  configs/reverse_text/debug_sft_lora.toml    -> configs/debug/training_modes/sft_lora.toml
  configs/reverse_text/debug_sft_external.toml -> configs/debug/training_modes/sft_external.toml
  configs/reverse_text/README.md              -> configs/debug/training_modes/README.md

Update path references in each TOML's header comment, the README, and
docs/training_modes.md.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(configs): drop auto pinference team-id, rename student-shortcut shim

- ClientConfig.auto_setup_pinference_team_header dropped. The hostname-sniff
  was implicit magic. Configs that need the X-Prime-Team-ID header against
  PI inference set it explicitly under [...client.headers_from_env] now.
  Update configs/debug/training_modes/sft_external.toml accordingly and
  drop the auto-injection note from the file header.
- Rename OrchestratorConfig._accept_legacy_student_layout (with leading
  underscore + "backward-compat" framing) to fold_student_shortcuts. The
  shim is more than a back-compat: it's the ergonomic path for rl configs
  too, letting users write [orchestrator.model.name] / [orchestrator.client]
  rather than [orchestrator.student.model.name] / [orchestrator.student.client].
  Docstring reframed accordingly. Teacher has no equivalent shortcut on
  purpose: rl mode forbids teacher, so the same shortcut routing to two
  roles would be ambiguous.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(tests): update multi_run CLI args after student rename

test_reverse_text_multi_run.start_orchestrator passes --client.base-url
and --model.lora.name as CLI flags to `uv run orchestrator`. After the
student rename, those tyro args don't exist anymore (they're now
--student.client.base-url and --student.model.lora.name). tyro rejects
them before the fold_student_shortcuts before-validator can re-nest the
dict, so the orchestrator process exits immediately and the test times
out waiting for "Step 11" to appear in the log.

Rename both CLI args to their new student-scoped form.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Timothy Kostolansky <39891386+tim0120@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-19 10:39:58 -07:00
09e11c7527 fix(benchmarks): refresh a6000 rl baselines after lm_head speedup (#2558)
Release / Push CUDA image to Docker (push) Canceled after 0s
#2547 cut step time ~27% (1-GPU: 65.87s -> 48.29s, 4-GPU: 68.34s -> 50.40s)
and peak memory (1-GPU: 31.81 GiB -> 24.25 GiB), pushing the regression tests
above the 10% tolerance. Refresh baselines from CI run 26067881101.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 23:21:38 -07:00
samsjaandGitHub 03f7feff14 Add pydantic-config submodule (#2556)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-18 21:46:40 -07:00
87ab84b666 chore(orchestrator): deprecate use_token_client (#2549)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore(orchestrator): deprecate use_token_client (server-tokenized TITO)

Drop the server-tokenized TITO path (``openai_chat_completions_token`` /
``/v1/chat/completions/tokens``). The orchestrator now picks between
renderer-backed TITO (``use_renderer = true``, default) and MITO
(``use_renderer = false``, fallback for VLMs and external teacher rollouts).

- Remove ``OrchestratorConfig.use_token_client`` field and its validators
- Drop the TITO branch in ``setup_rollout_inference_pool``
- Drop the obsolete TITO warning in ``setup_inference_pool`` and flip the
  default ``train_client_type`` to ``openai_chat_completions`` in
  ``StaticInferencePool`` / ``ElasticInferencePool``
- Strip ``use_token_client = false`` from configs/examples/docs that
  carried the no-op fallback line
- CHANGELOG entry documenting the breaking removal

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(inference): remove server-side TITO route

Drop the ``/v1/chat/completions/tokens`` endpoint and the
``OpenAIServingChatWithTokens`` / ``ChatCompletionRequestWithTokens``
wrappers now that no client routes to them. Also drop the obsolete
``base()`` helper and unused imports from ``server.py``.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:22:07 -07:00
halleriteandGitHub 0b37bc923e fix(tests): inject prime lm_head + complete ring-attn restore (#2547)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-19 02:08:06 +02:00
halleriteandGitHub 6591943919 feat(orchestrator): validate renderer auto-resolution at config time (#2537) (#2540)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-19 01:06:07 +02:00
alelpoanandGitHub 4748472b9f docs: add testing-moe-at-small-scale to mint.json navigation (#2542)
Release / Push CUDA image to Docker (push) Canceled after 0s
Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>
2026-05-18 15:31:27 -07:00
samsjaandGitHub 8106bf0a02 [codex] add custom qwen3 dense model (#2505)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add custom qwen3 dense model

* format qwen3 model files

* remove qwen3 unit test
2026-05-18 15:30:47 -07:00
46653c1d70 [codex] add per-env trainer metrics (#2478)
Release / Push CUDA image to Docker (push) Canceled after 0s
* add per-env trainer metrics

* require env names for trainer batches

* address per-env metric review feedback

* reuse tensor stats for env metrics

* fix sft trajectory env-name fixture

* address trainer metric naming comments

* fix: reuse trainer ratio tensors for env metrics

* fix: derive dppo mask from shared ratio

* address PR review: drop precomputed loss inputs, use {all,env} keys

- compute importance-ratio / mismatch_kl inside the loss functions instead of
  passing them in via LossInputs (per Mika)
- compute mismatch_kl inline in train.py only for per-env logging
- rename trainer aggregate keys to entropy/all and mismatch_kl/all to match the
  orchestrator {all,env}/{mean,std,max} convention; drop the leftover bare
  entropy/* and mismatch_kl/* keys
- drop the overly defensive env_names length check in DataLoader

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* guard mismatch_kl logging behind sft_loss flag

SFT batches don't have meaningful inference_logprobs (sft_loss_fn ignores
them), so computing and logging mismatch_kl for those microbatches is wasted
work and produces misleading numbers. Skip the inline mismatch_kl compute and
the per-env / debug-log emissions when sft_loss is True.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* address review: simplify probs_diff and move mismatch_kl/all to trainer loop

* reserve env_name='all' for aggregate metric keys

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 15:19:52 -07:00
samsjaandGitHub c5fb9591b2 feat(orchestrator): default max_error_reschedule_attempts to 3 (#2484)
Release / Push CUDA image to Docker (push) Canceled after 0s
Follow-up to #2459. Switches the default from `None` (retry indefinitely)
to `3`, so single-example hangs in agent envs no longer block step progress
out of the box. Users who want the legacy infinite-retry behavior can still
set `None` explicitly.
2026-05-18 14:51:13 -07:00
alelpoanandGitHub b22e768fc4 docs: fix typos and grammar errors in documentation (#2544)
Release / Push CUDA image to Docker (push) Canceled after 0s
* docs: fix "seemless" typo

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix model name Qwen-4B to Qwen3-4B

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix "violation to" grammar error

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix "asynchronoously" typo

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

* docs: fix duplicate "the the"

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>

---------

Signed-off-by: alelpoan <155192176+alelpoan@users.noreply.github.com>
2026-05-18 14:34:27 -07:00
faresobeidandGitHub ef8f459ca0 clean quack norm (#2543)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-18 14:28:54 -07:00
c3c6b70f11 [codex] chore: bump vllm to 0.21.0 (#2519)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump vllm

* fix: adapt dp pause patch for vllm 0.21

* Drop deep_gemm ep_scatter and silu_mul_quant int64 monkey patches

Both int64-addressing carries are fixed upstream in vLLM 0.21.0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 13:55:08 -07:00
f18297fd7d chore(verifiers): bump submodule to main (dd89b5e9) (#2534)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 20:18:58 -07:00
HubertandGitHub 6d80c412b6 Allow capped inflight rollout capacity (#2533)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-17 20:08:31 -07:00
a166a8b8df fix(orchestrator): trim glibc heap after each step to prevent RSS growth (#2527)
Release / Push CUDA image to Docker (push) Canceled after 0s
numpy/pandas allocate array data via malloc() (outside Python's allocator),
so gc.collect() alone doesn't reclaim RSS after per-step DataFrames are freed.
glibc retains freed pages in its internal pool, causing ~+6 MB/step monotonic
RssAnon growth on the orchestrator process.

malloc_trim(0) forces glibc to return freed heap pages to the OS, producing
a stable sawtooth pattern (peak during rollout generation, drops after trim)
with no upward trend.

Verified on alphabet-sort (512 rollouts/step, 20 steps, no wandb):
- Without fix: 941 MB → 973 MB by step 3 (+6 MB/step, unbounded)
- With fix:    941 MB → 942 MB by step 5 (flat, sawtooth only)

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 15:57:34 -07:00
samsjaandGitHub 66ff00d117 make renderers default for rollouts (#2521)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-17 12:58:38 +02:00
ae610d9dd8 feat(renderer): expose preserve_*_thinking flags in RendererConfig (#2436)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(renderer): expose preserve_*_thinking flags in RendererConfig

Adds two new fields to RendererConfig:
  - preserve_all_thinking
  - preserve_thinking_between_tool_calls

The orchestrator forwards them in two places so train and infer stay
consistent:

  1. create_renderer() — bound at construction on the training-side
     renderer used by build_trajectory_step / render_ids.
  2. setup_inference_pool() → setup_clients() → vf.ClientConfig — the
     verifiers RendererClient picks them up and forwards to its
     create_renderer_pool, so every inference render carries the same
     thinking-preservation behaviour.

Both flags are off by default → zero behaviour change for existing
configs. Setting either without orchestrator.use_renderer=True is
rejected by validate_renderer_args, matching the existing renderer
knobs.

Bumps source pins:
  - verifiers 3b77145 → a7516a1 (PR #1298: ClientConfig propagation)
  - renderers (now a separate repo): pinned to fe67f9f (PR #4:
    construction-time preserve flags)

Re-applies #2433, which was merged into feat/unify-inference-generate
by mistake.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(sft): forward preserve_*_thinking flags through SFT renderer path

The flags were added to the shared RendererConfig but only wired up
in the orchestrator. SFT also constructs a renderer via create_renderer
for training-side tokenization, so it must forward both flags or
silently ignore them.

Also tighten validate_renderer_args to reject either flag when
use_renderer=False, matching the orchestrator validator.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:38:53 -07:00
Matej SirovatkaandGitHub c935497d71 fix sparse MLA backward tilelang pass (#2520)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-16 22:10:12 +02:00
halleriteandGitHub cd2f3daeb2 chore(renderers): advance to latest main (PR #38) (#2518)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-16 17:40:39 +02:00
897b935cae feat: turn prime-rl into a monorepo (#2507)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: turn prime-rl into a monorepo with submodules

Add verifiers, renderers, and research-environments as git submodules and
uv workspace members. Source edits in any of them now apply to prime-rl's
venv without a re-sync. Drops the PrimeIntellect PyPI index in favor of
installing env packages editable from the submodule trees.

- envs extra expanded from ~14 curated packages to ~98 env packages across
  verifiers/environments and research-environments/environments
- 11 envs excluded from the workspace due to upstream dependency conflicts
  (tau2 fork divergence, openenv-core unreleased, scicode protobuf clash,
  gem-wordle nltk pin, two envs with hardcoded verifiers git URLs)
- override-dependencies adds torch>=2.9.0 (to override verifiers[rl]'s
  torch<2.9 pin) and openenv-core (to avoid an unreleased version pin)
- scripts/install.sh now initializes submodules per-path so a missing
  private repo (e.g. configs/private) does not abort the install
- installation/config/entrypoints skills updated to mention submodules and
  the configs/private path

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: scope ruff to prime-rl source only

Submodules (verifiers, renderers, research-environments) have their own
ruff configuration and style. Excluding them from prime-rl's checks avoids
spurious CI failures on third-party code that we don't own.

- pyproject.toml: extend-exclude the three submodule paths
- style.yaml: don't fetch submodules in the ruff job (nothing to lint there)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: add configs/private submodule pointing to research-configs

The private repo holds training/eval configs not meant for the public
prime-rl tree. People without access skip the submodule init via the
install script.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: bump configs/private + lock CI to public submodules only

- configs/private: pulls in all 88 TOML configs from research-prod
- CI workflows: replace 'submodules: true' with explicit init of just
  verifiers/renderers/research-environments, so no CI run ever attempts
  to fetch the private configs/private submodule

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: move submodules under packages/ + scope config tests

- packages/{verifiers,renderers,research-environments}: submodules now
  live alongside packages/prime-rl-configs as workspace members
- pyproject.toml: workspace members/exclude and ruff extend-exclude
  updated to the new paths
- CI workflows: revert to submodules: true (the GITHUB_TOKEN doesn't
  give access to configs/private, so it can't leak); the test fix
  below handles the in-tree case
- tests/unit/test_configs.py: skip configs/private/ when collecting
  TOMLs so private configs aren't loaded through public schemas
- scripts/install.sh: drop redundant -c url.insteadOf on clone; the
  later persistent git config line is what actually rewrites URLs
  for the submodule init step
- skills/installation/SKILL.md: point to packages/<submodule>/ paths

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: scope envs extra to union of main + research-prod

Drop the "install everything" approach. The envs extra now installs only
the union of (1) envs prime-rl main shipped before this PR and (2) envs
referenced in research-prod TOMLs. The rest of the env packages remain
workspace members (installable via `uv add <name>`), but aren't pulled
in by `--extra envs`.

This trims the install set from ~95 to 27 packages — fewer transitive
dep conflicts to keep alive, and the install set actually matches what
our active configs use.

tau2-bench is un-excluded from the workspace and added as a source so
research-prod's tau2-bench configs install cleanly. The other tau2 forks
(tau2-bench-v1, tau2-synth, tau3-bench, tau3-bench-rlm) stay excluded —
they pull tau2 from divergent forks/commits that can't coexist in a
single venv.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: scope workspace members to installed envs only

The previous setup pulled every env subdir under packages/verifiers
and packages/research-environments into the workspace via globs, then
maintained an exclude list for envs that couldn't co-resolve. With the
envs extra now narrowed to the union of (prime-rl main + research-prod),
the workspace can list exactly those env packages and skip the rest —
no exclude list needed.

Also: extend-exclude in ruff config simplified to ["packages"] so
prime-rl's checks ignore anything under packages/. The submodules
have their own ruff configs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ci): don't try to fetch the private configs/private submodule

The default GITHUB_TOKEN that actions/checkout uses is scoped to the
current repo only, so 'submodules: true' aborts with 404 when it
hits configs/private (the research-configs repo). Skip the checkout
action's submodule init and explicitly update just the three public
submodules.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: strip noisy comments

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: prune [tool.uv.sources] to installed env packages only

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ci): rewrite SSH to HTTPS for submodule init

Runners have no SSH key, so cloning git@github.com:... fails. The
actions/checkout step handles this automatically when submodules: true
is set, but the explicit submodule update we run after submodules: false
doesn't. Set the insteadOf rewrite before the update.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: move third-party submodules from packages/ to deps/

packages/ is reserved for first-party prime-rl subpackages
(packages/prime-rl-configs). Vendored submodules live under deps/.
Ruff extend-exclude switches to deps/ so prime-rl-configs gets linted
again.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(install): apply SSH->HTTPS rewrite in SKIP_CLONE path too

The rewrite was inside the else branch of the clone check, so users
running with SKIP_CLONE=1 without SSH access would hit the same submodule
init failures the rewrite was meant to prevent. Move it after the
clone/skip block so it runs in either path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(docker): copy deps/ and init submodules in release workflow

The submodule move from packages/ to deps/ left the Dockerfile and the
release workflow inconsistent: Dockerfile.cuda only COPYs packages/, and
release.yaml never initialized submodules. Add the deps/ COPY and the
explicit submodule init (matching the test workflows).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: warn against --recursive submodule init, use explicit paths

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: remove note from submodule init step in README

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: pin renderers to v0.1.6 and verifiers to aa428f3

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(verifiers): patch out renderers git source for workspace compat

uv requires workspace members to reference each other as workspace
sources. verifiers@aa428f3 still has renderers as a git source; this
local patch removes it so the workspace resolves.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(verifiers): advance to latest main

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(renderers): advance to latest main (v0.1.8.dev2)

Required by verifiers main which now pins renderers>=0.1.8.dev0.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: revert ruff pre-commit hook to v0.13.0 to match CI

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 23:31:33 -07:00
81f9e9512b fix(ci): fix recurring failures + speedup ci (#2512)
* fix(wandb): respect WANDB_MODE env var in WandbMonitor

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(ci): disable W&B on PR runs to prevent ID collision and missing key crashes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(ci): rename test_rl.py to test_reverse_text.py and split into own CI job

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(ci): reduce reverse-text RL run to 15+5 steps

Reward plateaus at step 8-9 and stays above the 0.65 threshold from
step 8 onward. 20 steps was ~40% wasted compute.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: add average mismatch KL check to reverse-text integration test

Asserts the average mismatch KL across the last 10 trainer steps stays
below 0.01, catching numerical instability early without being brittle
to per-step noise.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(alphabet-sort): add mismatch KL guard, tighten reward threshold, reduce steps

Cut max_steps 10→8 (reward plateaus by step 7 at ~0.22, saves ~16s).
Tighten reward min_threshold 0.05→0.10 to catch regressions earlier.
Add avg mismatch KL check (last 5 steps ≤ 0.15) based on observed ~0.05-0.09
range; 0.15 gives CI headroom while catching numerical instability.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(reverse-text): rename wandb run, reduce mismatch KL check window

Rename W&B run from test-rl to test-reverse-text:{branch} to match the
test file rename. Reduce last_n_steps from 10→3 for the mismatch KL
check to make it less brittle (3 steps is sufficient to catch instability).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: remove unused alphabet_sort_branch CI config

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(tests): update config paths after renames, fix double newline in error output

- configs/ci/integration/rl/ → reverse_text/
- configs/ci/integration/alphabet_sort/start.toml → alphabet_sort.toml
- sep="\n" → sep="" in check_no_error (readlines() lines already end in \n)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(ci): respect WANDB_MODE in shared mode, align lora/alphabet-sort configs

- wandb.py: WANDB_MODE=disabled/offline now bypasses shared mode entirely
  (shared mode requires a server connection and can't work offline)
- reverse_text_lora: reduce steps 20+5 → 15+5 to match reverse_text config
- gpu_tests.yaml: rename rl_lora job → reverse_text_lora, update ignore list
- test_reverse_text_lora.py: use colon separator in wandb run name
- test_alphabet_sort.py: drop rl_output_dir wrapper, use output_dir directly;
  use colon separator in wandb run name

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: rename test_rl_moe → test_reverse_text_moe, split into own CI job

- Rename test file and config dir (rl_moe → reverse_text_moe)
- Add reverse_text_moe as a dedicated CI job; exclude from base
- Update config paths, wandb name (colon separator), output subdirs (hf/custom)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(test): add missing test function to test_reverse_text_moe

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(ci): update config paths for renamed sft/multi-run dirs, tail orch logs

- test_sft.py: sft/ → reverse_text_sft/
- test_sft_lora.py: sft_lora/ → reverse_text_sft_lora/
- test_reverse_text_multi_run.py: rl_multi_run/ → reverse_text_multi_run/
- gpu_tests.yaml: rename rl_multi_run job → reverse_text_multi_run, update
  ignore list to use test_reverse_text_multi_run.py
- rl.py: tail orchestrator.log instead of trainer.log on startup

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(tests): rename CI integration tests and configs to use descriptive names

Rename test files and config directories from generic rl/sft/rl_lora/rl_multi_run
prefixes to descriptive reverse_text/alphabet_sort/reverse_text_sft/etc names.
Flatten alphabet_sort config from a directory to a single file.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(ci): reduce SFT integration test steps from 10+10 to 5+5

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(ci): simplify CI - always offline W&B, drop OPENAI_API_KEY, fix wandb names

- WANDB_MODE hardcoded to offline (removes flaky conditional logic)
- Remove OPENAI_API_KEY (not referenced in code, client defaults to EMPTY)
- Remove WANDB_API_KEY (no longer needed with offline mode)
- Drop -m gpu from integration test args (all integration tests already carry the mark)
- Standardize wandb run names to use colon separator in sft/sft_lora/multi_run tests

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(ci): replace base integration job with explicit sft matrix jobs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: ignore .claude/scheduled_tasks.lock

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: untrack deps/renderers/_version.py, add to gitignore

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(ci): use dynamic matrix to avoid expanded skipped entries on draft PRs

Static matrix jobs get pre-registered by GitHub even when skipped, showing 8
individual "Skipped" entries on draft PRs. A dynamic matrix (output from a prior
job) can't be pre-expanded, so GitHub shows a single entry instead.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Revert "chore(ci): use dynamic matrix to avoid expanded skipped entries on draft PRs"

This reverts commit 0e835ed63ef467f8a33018f809b8ab182ebb2c56.

* chore(ci): disable uv cache on GPU jobs

The post-job cache save tars multi-GB pytorch/CUDA packages, adding 3+ min of
overhead. The save cost exceeds the restore benefit for large GPU dependencies.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: remove deps/renderers/_version.py from gitignore

Handled in a separate PR.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore(ci): run integration tests with -vvs

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* only 5 alphabet sort steps [skip ci]

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 22:25:40 -07:00
d4385029c8 feat(sft): accept tool_defs column alongside tools (#2494)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(sft): accept tool_defs column alongside tools

The verifiers rollout format stores tool definitions under tool_defs
(list[dict] or list[str]); SFT was only reading the OAI tools column
(single JSON string), so rollout-derived datasets trained with an empty
system block — a major training/inference mismatch since vLLM injects
the tool definitions at inference time.

Falls back to tool_defs when tools is absent and parses both shapes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* accept both JSON-encoded and pre-parsed shapes for tools/tool_defs

Either key may now arrive as: a JSON-encoded list string, a list[dict],
or a list[str] of JSON-encoded tool dicts. Result is always list[dict].

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* narrow accepted shapes to str | list[dict]

list[str] (each item a JSON-encoded tool) wasn't a real-world shape; drop it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* simplify tools lookup

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* normalize tool defs to OAI shape before chat template

The orchestrator does this conversion in _convert_tools_to_oai_format
(trajectories.py); SFT was passing the raw verifiers shape directly. That
worked for chat templates that handle both shapes (e.g. NemotronH) but
would silently render an empty <tools> block on most others.

Detects verifiers-shape tools (top-level name/description/parameters) and
wraps them as {type: 'function', function: {...}}. Pre-wrapped OAI tools
pass through unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: hallerite <git@hallerite.com>
2026-05-15 15:27:50 -07:00
samsjaandGitHub c654dc1d4d log masked advantage sign rates (#2481)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-14 19:17:32 -07:00
6ba37c2c21 feat: opt-in renderer-based tokenization for SFT (#2496)
Release / Push CUDA image to Docker (push) Canceled after 0s
Adds `use_renderer` flag to SFTConfig, mirroring the RL path. When enabled,
SFTDataset tokenizes via `renderers.base.build_training_sample` instead of
the incremental Jinja `apply_chat_template` path, fixing multiturn sample
drops and position-dependent template crashes.

Co-authored-by: Eric Botti <ericjbotti@gmail.com>
2026-05-14 23:25:10 +02:00
halleriteandGitHub 458b16ef47 Revert "feat: opt-in renderer-based tokenization for SFT (#2493)" (#2495)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit b5f196a9c5.
2026-05-14 23:14:24 +02:00
halleriteandGitHub b5f196a9c5 feat: opt-in renderer-based tokenization for SFT (#2493)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-14 23:13:00 +02:00
6dda4a1466 chore: tell agents not to edit optimization_dtype / reduce_dtype (#2491)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 10:47:56 -07:00
halleriteandGitHub fa55779272 Fix disagg: thread kv_transfer_params into engine for /inference/v1/generate (#2490)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-14 17:56:28 +02:00
b2ba40b5eb Patch vLLM layerwise reload alias-buffer handling (#2482)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Patch vLLM layerwise alias-buffer reload

* Remove layerwise buffer copy-back guard

* Skip alias buffers during layerwise copy-back

* ruff

* Skip absent buffers during layerwise copy-back

* Precompute layerwise alias storage pointers

* ruff

* simpler fix for layerwise alias buffer reload (#2486)

* meow

* dont think theres a need for this singletoning behavior?

* Simplify layerwise alias-buffer patch to copy-back-only

Drop the capture-time skip and the absent-buffer guard; detect aliasing
at copy-back via parameter storage pointers (recursing into submodules
so views like mixer.conv_weights → mixer.conv1d.weight are caught).
_place_kernel_tensors then restores the original aliased buffer, which
trivially reflects the parameter's freshly-loaded storage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* Apply suggestion from @Jackmin801

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 05:36:14 +08:00
samsjaandGitHub e4330c2d2c add poolside laguna custom model (#2479)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-12 21:13:34 -07:00
4a6b45487f feat(orchestrator): drop groups after max_error_reschedule_attempts (#2459)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): drop groups after max_error_reschedule_attempts

Adds a per-group retry cap to the rollout scheduler. Each `GroupState`
now tracks a `failed_attempts` counter, incremented whenever a batch of
rollouts comes back with at least one errored or empty trajectory. When
the counter reaches `orchestrator.max_error_reschedule_attempts`, the
group is dropped from the current step's batch (cancelling any
in-flight rollouts for that group) and the rest of the batch proceeds.

Default is `None` (retry indefinitely, current behavior). Set a value
to unblock single-example hangs in agent envs (e.g. a sandbox poll
that times out at 60s on every retry — that loop was previously
infinite because the AgentError surfaces as `rollout["error"]`, which
the scheduler treats as a normal "reschedule the group" signal with no
give-up condition).

Minimal local re-implementation of the abandoned PR #2076 — keeps the
retry-cap behavior without the larger GeneratedBatch / variable
group-size / deferred-scoring refactor in that PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(orchestrator): report and clear dropped_groups_by_env in metrics

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(orchestrator): off-by-one in max_error_reschedule_attempts check

failed_attempts is incremented on the initial failure, so >= caused the
group to be dropped without any reschedule. Use > so max_attempts
matches the configured number of retries.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(orchestrator): include last failure reason in drop log

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(orchestrator): count failed rounds, not failed rollouts, for drop cap

For non-group-scoring envs, each individual rollout returns as a
separate task, so a single failed dispatch round could increment
failed_attempts up to rollouts_per_example times and trip the cap before
any retry happened. Tag in-flight requests with a dispatch round and
dedupe failures by round.

Also switch the drop check to `>=` and reword the config description so
the field's semantics match — the group is dropped once this many of
its dispatch rounds have returned errored/empty rollouts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 18:28:13 -07:00
minh hoangandGitHub 024abb2043 bump prime cli to 0.6.4 (#2480)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-12 16:09:18 -07:00
rasdaniandGitHub 5b11b8de33 Fix SLURM cleanup self-kill patterns (#2477)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-12 21:33:51 +02:00
halleriteandGitHub 7c434ec267 feat: unify renderer + teacher endpoints onto vLLM 0.20 /inference/v1/generate (#2408)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-11 19:19:40 +02:00
469a4e6714 chore: bump vllm to 0.20.2 (#2468)
Release / Push CUDA image to Docker (push) Canceled after 0s
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 08:36:40 -07:00
319af10769 Fix: add layerwise as default (#2467)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Fix: add layerwise as default

* Fix; cleanup

* fix(filesystem): apply layerwise reload to filesystem transport

Mirror the same fix as the NCCL path: replace
`model.load_weights + process_weights_after_loading` with
`load_weights_checkpoint_layerwise`. Without it, MoE
+ filesystem transport hits the same
`Current vLLM config is not set` AssertionError at
`worker/filesystem.py` on the first weight update.

Verified end-to-end on Qwen3-30B-A3B-Thinking-2507 + reverse-text:
filesystem broadcast returns 200 OK, orchestrator step 2 consumed
new weights cleanly (off-policy level 1, reward 0.3583), trainer
steady-state at ~29K tok/s, MFU 21%, no NaN, no errors.

---------

Co-authored-by: hallerite <git@hallerite.com>
2026-05-10 16:10:09 +02:00
Matej SirovatkaandGitHub d11fc90469 Fix: third_party to .gitignore (#2463)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-09 15:18:24 -07:00
Matej SirovatkaandGitHub c9a4b3b199 Feat: kv offload for non-PD (#2457)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-09 09:17:44 -07:00
Matej SirovatkaandGitHub a252057978 [Weight Transfer]: Support quantize_in_weight_transfer + EPLB (#2454)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Feat: support EPLB with quantize_in_weight_transfer

* Feat: EPLB+quantize_in_weight_transfer

* Nit: style
2026-05-09 18:07:27 +02:00
Matej SirovatkaandGitHub 429c1bb5e5 Nit: pass hybrid lb for non-pd DP case (#2455)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-09 18:07:17 +02:00
Matej SirovatkaandGitHub efb874b734 [Inference]: vLLM 20 + Prod Run compat (#2456)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Feat: update vllm

* Fix: silu mul patch address overflow (DPEP16)

* Feat: fix weight transfer

* Chore: pin DeepEP DeepGEMM release wheels

* nit: style
2026-05-09 18:07:06 +02:00
Matej SirovatkaandGitHub 2171368063 [FP8]: Upcast addresses to int64 to avoid overflow (#2453)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Fix: upcast to i64

* Fix: 1 more upcast
2026-05-09 08:59:06 -07:00
Jackmin801andGitHub 7b7bde1fa0 drop ampere in fa4 (#2452) 2026-05-08 18:01:22 -07:00
Jackmin801andGitHub 0fe673c23c pin vllm down to cu129 (#2450)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-08 17:28:27 -07:00
minh hoangandGitHub 84ccb9507d fix(inference): make liveness timeout configurable with a 30s default (#2449)
Release / Push CUDA image to Docker (push) Canceled after 0s
* make liveness timeout configurable; set default to 30s

* server config already sets up the default 30s value
2026-05-08 14:27:23 -07:00
samsjaandGitHub 09e403b4a4 Revert "Revert "bump vllm version (#2427)" (#2437)" (#2448)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit bb522cce53.
2026-05-08 12:28:05 -07:00
7da26cd651 fix(trainer): escape dots in FP8 ignore patterns (#2442)
Release / Push CUDA image to Docker (push) Canceled after 0s
`replace_linear_with_fp8_blockwise_linear` uses `re.search(pattern, name)`
to decide which linears to keep in BF16. The default ignore list had
"mlp.gate." which is a regex where `.` matches any character. As a
result, dense MLPs' `mlp.gate_proj` (the trailing `.` matched `_`)
were being skipped from FP8 conversion alongside the MoE router gate.

For FP8 inference checkpoints (e.g. `zai-org/GLM-5-FP8`) where the
dense MLP gate_proj IS quantized to FP8, this leaves the trainer's
copy in BF16 — causing hidden-state divergence in early dense layers
that propagates through the MoE router and inflates trainer↔inference
KL mismatch.

Escape the dots (`mlp\.gate\.`) so the pattern matches only the actual
MoE router gate (`mlp.gate.weight`, `mlp.gate.e_score_correction_bias`)
and not `mlp.gate_proj` / `mlp.gate_up_proj`.

Verified on a 12-node GLM-5.1-FP8 RL run: trainer log now reports
`Replaced 477` (was 474) with `mlp.gate_proj` no longer in the
`first skipped(name)` list.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 22:45:36 -07:00
5f2c004184 feat(inference): fp32 lm_head via native bf16xbf16 -> fp32 mm (#2441)
Release / Push CUDA image to Docker (push) Canceled after 0s
Alternative implementation of fp32 lm_head proposed by @Jackmin801 on
PR #2438: use torch.mm(..., out_dtype=torch.float32) (PyTorch >= 2.10) so
the matmul accumulates and emits fp32 directly without zero-padding the
bf16 operands or maintaining a separate fp32 weight copy.

The win is purely in the epilogue: F.linear(bf16, bf16) accumulates in
fp32 internally on tensor cores but truncates the output to bf16 before
returning. Native out_dtype=fp32 keeps the full mantissa for the
downstream softmax/sample.

Removes the cached fp32 weight + tensor-version invalidation logic from
PR #2438 — not needed when there's no separate fp32 copy.

Wired identically to PR #2438: inference.enable_fp32_lm_head config flag
-> additional_config["fp32_lm_head"] -> captured on LogitsProcessor.__init__
-> per-instance flag read in _get_logits.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 22:44:25 -07:00
c0d896f3f8 fix(gpt-oss): document temperature arg in GptOssForCausalLM.forward (#2439)
Release / Push CUDA image to Docker (push) Canceled after 0s
`temperature` is part of the forward signature but had no docstring entry,
which trips the auto_docstring check. Add a description matching the convention
used in the other model files.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 18:35:55 -07:00
samsjaandGitHub bb522cce53 Revert "bump vllm version (#2427)" (#2437)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit 3b01ce9d48.
2026-05-07 17:12:22 -07:00
95af0118db feat(cp): add ulysses all-to-all CP path alongside ring (#2418)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(cp): add ulysses all-to-all path alongside ring

Adds a `model.cp_style` arg ("ring" default | "ulysses") that selects
between the existing ring CP and a new Ulysses all-to-all variant.

Ulysses redistributes Q/K/V via two seq <-> head all-to-alls and runs
vanilla flash attention on the full sequence with H/cp heads, so the
attention kernel does not need to be CP-aware. Works OOB with FA2/3/4,
linear attention, mamba, etc.

Constraint: cp_size must divide both num_attention_heads and num_kv_heads.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: ruff format ulysses_attn.py

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(cp): refuse cp_style='ring' on linear-attn / Mamba models

Ring CP is a softmax-attention algorithm (sequence ring all-gather of K/V).
It cannot correctly drive non-softmax kernels (Qwen3.5 DeltaNet linear-attn,
NemotronH Mamba). Previously the linear-attn CP setup hooks were called
unconditionally under ring, which silently mixed two different CP layouts
in the same model.

Now:
- Refuse cp_style='ring' at startup if the model has any linear/SSM
  attention layer, with a clear error pointing at cp_style='ulysses'.
- Only call setup_hybrid_cp / setup_nemotron_h_cp under cp_style='ulysses'.
- setup_sparse_mla_cp (still softmax) keeps working under both.

Ulysses' all-to-all is purely on Q/K/V tensors, so the linear/SSM kernel
runs unchanged on a sequence shard — this is the correct CP path for
hybrid models.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 16:05:21 -07:00
d7b3ae203c feat: agentic length-penalty ablations — weighted shaping over tool-response tokens (#2377)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: weighted length shaping over completion + tool-response tokens

Generalize the length_shaping brevity bonus to a weighted combination of
model-completion tokens and tool-response tokens, so the brevity signal
can penalize tool-response token consumption (read from a harness metric
like rlm_total_tool_response_tokens) independently from model output.

- Add `tool_response_lengths` to AdvantageInputs (optional)
- Add `length_shaping_completion_weight` (default 1.0) and
  `length_shaping_tool_response_weight` (default 0.0) to
  DefaultAdvantageConfig — defaults preserve existing behavior.
- effective_lengths = a * completion + b * tool_response, fed to the
  existing correctness-gated brevity bonus.
- Add get_tool_response_len() that pulls *_total_tool_response_tokens
  from rollout metrics and returns 0 if absent (no-op for non-tool envs).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(advantage): guard zero-cost division in efficiency shaping

When `mean_correct_cost == 0` (e.g. tool-only shaping without a harness
metric, or all-zero turn counts), `costs / mean_correct_cost` was 0/0 →
NaN advantages. `clamp(0, 1)` doesn't recover from NaN.

Detect zero mean and zero out the bonus, falling back to plain GRPO for
that group. Also a latent bug for `length_penalty="turns"` if a group
ever had all empty trajectories — same fix covers it.

* fix(advantage): constrain weights to finite non-negative; cast rewards to float

- Config: add `ge=0, allow_inf_nan=False` on both weight fields. Negative
  weights would invert the shaping (reward more tokens); inf/nan poison
  advantages downstream.
- `default_advantage_fn`: cast rewards to float32. The previous
  `dtype=rewards.dtype` for costs truncated fractional weighted sums when
  rollouts emitted integer rewards. Casting also fixes a latent crash on
  int rewards in `_efficiency_shaping`'s `rewards.mean()` (Long unsupported).

* refactor(advantage): discriminated length_penalty sub-config

Replace the scalar `length_penalty: Literal["tokens","turns"] | None` plus
two flat weight fields with a discriminated union on `type`:

  TokensLengthPenaltyConfig(completion_weight, tool_response_weight)
  TurnsLengthPenaltyConfig

Default for the tokens config is (1.0, 1.0), making total-context shaping
the default when token-shaping is enabled. The discriminator pattern
matches the existing AdvantageConfig (default | custom) shape and keeps
weight semantics scoped to the variant they apply to — no cross-field
validator needed.

CHANGELOG entry added.

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 16:04:51 -07:00
229391fa27 Feat: deep-gemm-fp8 (#2166)
Release / Push CUDA image to Docker (push) Canceled after 0s
* Feat: deep-gemm-fp8

* Feat: cleanup

* nit

* Style

* Feat: works now

* Feat: fp8 grouped gemm works

* Fix: skip unaligned + qwen3.5

* chore(deep_gemm): rebuild d30fc36 wheel against torch 2.11 / cu128

The wheel was built against torch 2.10 + cu128; the merge from main bumped
torch to 2.11.0+cu128 / vllm to 0.20.1, breaking ABI compat with the old
build. Rebuilt via scripts/install_deep_gemm.sh --wheel-dir tools/wheels.

Also updates install_deep_gemm.sh:
  - default ref pinned to d30fc36 (was 477618c)
  - script header documents the wheel-dir flow used to refresh tools/wheels/

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deep_gemm): pin to v0.5.0 release URL (uploaded d30fc36 wheel)

The d30fc36 wheel is now hosted on the v0.5.0 GitHub release alongside the
existing 477618c build, so we can drop the local path-based pin.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(fp8): make deep_gemm import optional for CPU-only envs

deep_gemm only ships CUDA wheels; importing prime_rl on a CPU box currently
fails with ImportError before any FP8 path is even touched. Wrap both call
sites in try/except so the import is graceful — actual deep_gemm calls live
inside autograd Function bodies that only run on GPU anyway.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(fp8): wire FP8 grouped GEMM into NemotronH; assert disabled for GPT-OSS

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 16:04:19 -07:00
minh hoangandGitHub 1e9a3e9196 fix: exit early for unsupported platforms on install.sh (#2431)
Release / Push CUDA image to Docker (push) Canceled after 0s
* install: check platform and exit early on unsupported platforms

* handle stripped ansi escape prefix for color output

* Revert "handle stripped ansi escape prefix for color output"

This reverts commit b8850f73893c3189d86848fb3849986275a12963.
2026-05-06 11:51:24 -07:00
3b01ce9d48 bump vllm version (#2427)
Release / Push CUDA image to Docker (push) Canceled after 0s
* bump vllm version

* fix cuda version pin

* correct flash attn

* chore: drop monkey patches now upstream in vLLM 0.20

vLLM 0.20.1 ships fixes for the LoRA+MoE+DP>1 corruption (#40338) and
the OffloadingConnector CPU block-count miscalculation (#39617), so
remove the local monkey patches and the corresponding call site in
transformers_v5_compat. Refresh stale "vLLM 0.16/0.19" comments.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Signed-off-by: Jackmin801 <56836461+Jackmin801@users.noreply.github.com>
Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 11:01:05 -07:00
38b524925d fix(configs): use FutureWarning so config deprecations are visible (#2429)
Release / Push CUDA image to Docker (push) Canceled after 0s
DeprecationWarning is silenced by default outside __main__, so users
never saw notices for max_tokens / [[orchestrator.env]] / [orchestrator.sampling].
FutureWarning is shown under default filters and is the right category
for "will be removed in a future release" notices.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 22:42:03 -07:00
d62c7539e4 feat: split prime-rl-configs into separate workspace package (#2416)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: split prime-rl-configs into separate workspace package

Goal: make `prime_rl.configs.*` pip-installable on its own (~13 deps)
without pulling the full GPU/ML stack (~329 deps).

Layout — uv workspace with two members:
- root `prime-rl` (heavy stack, unchanged location at src/prime_rl/)
- `packages/prime-rl-configs/` (slim wheel, owns prime_rl.configs.*
  and the small slim utils: utils/config.py, utils/logger.py,
  utils/validation.py)

Mechanism — both wheels contribute to a PEP 420 namespace package
`prime_rl/` (no __init__.py at the top level, nor under utils/). Each
wheel ships disjoint files; pip merges them at install time.
- `pip install prime-rl-configs` → schema only
- `pip install prime-rl` → full stack (depends on prime-rl-configs)

Code changes:
- Move src/prime_rl/configs/ → packages/prime-rl-configs/src/prime_rl/configs/
- Move utils/{config,logger,validation}.py → packages/prime-rl-configs/src/prime_rl/utils/
- Move rgetattr/rsetattr from utils/utils.py → utils/config.py (was the
  only heavy import the configs needed; this breaks the dep)
- Replace `Path(prime_rl.__file__).parent / "templates"` (None on a
  namespace package) with `find_package_resource("templates")` which
  iterates `prime_rl.__path__` to locate the heavy wheel's data dir
- Delete src/prime_rl/__init__.py; move its `import _compat` side-effect
  into the actual entrypoint scripts (orchestrator.py, entrypoints/rl.py,
  entrypoints/sft.py — trainer/{rl,sft}/train.py already had it)
- Dockerfile.cuda: also COPY packages/ so the workspace member is
  available during `uv sync`

Verified:
- `uv sync --all-extras` resolves and builds both wheels
- 333 unit tests pass (none touched)
- all 6 entrypoints (rl/sft/trainer/orchestrator/env-server/inference)
  load and print --help
- fresh `pip install ./packages/prime-rl-configs` (no extras) installs
  13 packages, imports all configs, parses examples/.../rl.toml with a
  [slurm] section, and sys.modules contains zero of:
  torch / transformers / vllm / wandb / ring_flash_attn / verifiers /
  prime / datasets / liger_kernel

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* ci: add slim-configs-install job to cpu_tests

Fresh venv → `uv pip install ./packages/prime-rl-configs` → assert that:
- all 6 config modules import
- sys.modules contains zero of: torch, transformers, vllm, wandb,
  ring_flash_attn, verifiers, prime, datasets, liger_kernel
- find_package_resource("templates") returns None (the heavy wheel's
  data dir isn't shipped on slim)
- a real example config with [slurm] parses; template_path stays None

Guards the slim-import contract against future regressions where
something under prime_rl.configs.* might re-introduce a heavy import.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(ruff): mark prime_rl as first-party for isort

Without this, ruff's import sorter classifies prime_rl.configs.* as
third-party (because those files now live under packages/, not src/),
and groups them apart from prime_rl.utils.* / prime_rl.trainer.* etc.

Telling ruff that prime_rl is a single first-party namespace keeps
all prime_rl.* imports in one block, regardless of which workspace
wheel ships the submodule.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(configs): drop logger dep, use stdlib warnings

Configs were doing get_logger().warning(...) at validation time, which
forced loguru into the slim wheel and a logger.py copy alongside it.
None of these warnings need a configured logger — they're config-time
deprecation notices and misconfiguration hints. Stdlib `warnings.warn`
covers the use case without any runtime infrastructure.

- Replace 7 `get_logger().warning(...)` call sites in configs/rl.py and
  configs/orchestrator.py with `warnings.warn(...)`. Deprecation messages
  use `DeprecationWarning`; the rest use the default `UserWarning`.
- Move `prime_rl/utils/logger.py` back to the heavy `prime-rl` wheel
  (`src/prime_rl/utils/`).
- Drop `loguru` from `prime-rl-configs` deps; add it to `prime-rl`.
- Slim CI: stop importing `prime_rl.utils.logger` (it's no longer in the
  slim wheel) and add `loguru` to the forbidden-modules list.

Slim install drops from 13 to 12 packages.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: import _compat in remaining ring_flash_attn entry points

Integration tests like tests/integration/test_sft_lora.py import
prime_rl.trainer.weights, which transitively pulled ring_flash_attn
(via models layer / utils.cp) without prime_rl._compat ever running,
producing the ImportError that failed CI.

Add `import prime_rl._compat` to the two remaining top-level
ring_flash_attn import sites: utils/cp.py and trainer/models/layers/
ring_attn.py. The trainer entrypoints (rl/sft/train.py) already had
this import.

`# ruff: noqa: I001` on both files because ruff's isort, with
known-first-party=prime_rl, sorts the prime_rl._compat first-party
import after the third-party ring_flash_attn import — which defeats
the patch ordering. The shim must run before ring_flash_attn is
imported, so the file order is intentional.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: pin pydantic-config to git fork in slim package

The PyPI package named `pydantic-config` is a different project that
doesn't expose BaseConfig / cli (those are in samsja's fork). Without
this pin, plain `pip install prime-rl-configs` resolves the wrong
package and configs.* imports crash with:

  ImportError: cannot import name 'BaseConfig' from 'pydantic_config'

uv pip install accidentally worked because it reads the root workspace
pyproject.toml's [tool.uv.sources] when installing from a git
subdirectory, which redirected pydantic-config to the fork. Plain pip
doesn't do that — it only sees the leaf pyproject.toml.

PEP 508 direct reference works for both uv and pip.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* ci: install slim wheel from /tmp to bypass workspace source discovery

The previous step did `uv pip install ./packages/prime-rl-configs` from
inside the cloned repo. uv silently reads the root pyproject.toml's
[tool.uv.sources] in that case and applies the pydantic-config git
override — masking the issue an external pip-only user would hit.

Build the wheel into /tmp/slim-wheel and install it from /tmp so uv
can't discover the workspace. This catches dep-resolution bugs that
only show up in a real external install.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: explain dist-name vs import-path in slim package README

Distribution name (`prime-rl-configs`) and import path
(`prime_rl.configs.*`) are different — easy to trip on.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 21:59:37 -07:00
Jackmin801andGitHub edf41113fe Revert "chore: bump vllm 0.20.1 + migrate cu128 → cu130 (#2403)" (#2426)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit bcac552c3f.
2026-05-05 21:12:11 -07:00
bcac552c3f chore: bump vllm 0.20.1 + migrate cu128 → cu130 (#2403)
Release / Push CUDA image to Docker (push) Canceled after 0s
* chore: bump vllm 0.19 → 0.20

vLLM 0.20.0 lands MoE LoRA refactor (#40338) and CPU offloading fix
(#39617) upstream — drop now-redundant prime-rl monkey patches:
monkey_patch_fused_moe_lora_dp and monkey_patch_offloading_connector_
cpu_block_count.

PyPI vllm-0.20.0 is built against CUDA 13 and links libcudart.so.13;
our env is pytorch-cu128 (CUDA 12). Pin vllm to the cu129 wheel from
wheels.vllm.ai (libcudart.so.12) for binary compat. Promote
torchvision/torchaudio to direct deps so [tool.uv.sources] pins them
to pytorch-cu128 (cu13 transitive resolution would break torch ops).

Add vllm = false exemption to the 7-day exclude-newer cooldown since
0.20.0 was published 2026-04-27, inside the window.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: migrate cu128 → cu130

Now that vllm 0.20.0 is the floor and PyPI ships it for CUDA 13
natively, drop our cu129-wheel detour and move the rest of the
GPU stack to cu130:

- pytorch-cu128{,-test} indices → pytorch-cu130{,-test}
  torch/torchvision/torchaudio/flash_attn_3 follow.
- flash-attn extra: bump to v0.9.4 cu130torch2.11 prebuilt wheel.
- Drop the wheels.vllm.ai cu129 URL pin — PyPI vllm 0.20.0 (cu13)
  is now the default.
- override-dependencies: nvidia-cudnn-cu12 → nvidia-cudnn-cu13.

Lockfile pulls torch 2.11.0+cu130, torchvision/torchaudio 0.26.0/2.11.0
+cu130, flash-attn 2.8.3+cu130torch2.11, vllm 0.20.0, and swaps every
nvidia-*-cu12 transitive for its cu13 counterpart.

Not addressed in this change (draft until ready):
- Host driver upgrade: 575.64.03 → ≥580.65.06 required for CUDA 13.
- samsja prebuilt wheels (deep-ep, deep-gemm, nixl-cu12) still
  point at cu12 builds — runtime-incompatible with cu13. Need
  rebuilds before merging.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deps): bump vllm 0.20.0 → 0.20.1

Picks up the DeepSeek V4 patch release and a handful of bug fixes
(CUDA-graph max_num_batched_token, num_gpu_blocks_override, cumem
expandable_segments, structured-output kwargs). Strict patch — none
of the kept/dropped monkey-patches are touched.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deps): ship cu13 disagg wheels, switch nixl to PyPI

deep-ep / deep-gemm: rebuilt against CUDA 13.1, stamped with `.cu13`
local version, uploaded alongside the existing cu12 wheels at v0.5.0.

nixl: dropped the URL pin entirely. PyPI `nixl-cu13` 1.0.1 ships UCX
auditwheel'd with mlx5_ib / rdmacm / cuda transports — verified
end-to-end with a 2-node basic_two_peers.py run that picked rc_mlx5
for inter-node RMA. The custom install_nixl_from_source.sh path is
kept (now generates `nixl-cuMAJOR` per torch's CUDA major) for
clusters that need a vendored UCX, but it's no longer the default.

install_ep_kernels.sh:
- Falls back to /usr/local/cuda-${MAJOR} when torch reports 13.0
  but only cuda-13 (-> 13.1) is installed; rejects toolkit/torch
  major mismatches.
- Exports CPATH=$CUDA_HOME/include/cccl for CUDA 13, where CCCL
  headers (e.g. <cuda/std/tuple>) moved into the cccl/ subdir and
  torch's CUDAExtension doesn't add it on its own.
- Post-build --set-runpath /tmp/deepep_build/nvshmem/lib rewrites
  the DT_RUNPATH on deep_ep_cpp.so to match the cu12 convention the
  existing inference/RL templates already hook (they symlink the
  user's NVSHMEM at that path on each compute node).

install_deep_gemm.sh: post-build cu-suffix stamp.

scripts/wheel_add_cu_suffix.py (new): repacks a wheel with
+...cuXX appended to its local version, optionally stripping or
rewriting DT_RUNPATH on every .so. Keeps METADATA / dist-info /
RECORD / filename consistent.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(templates): fall back to ep_kernels_workspace nvshmem in disagg launchers

inference.sbatch.j2 and multi_node_rl.sbatch.j2 still set up the
/tmp/deepep_build/nvshmem/lib symlink the deep_ep wheel needs at
runtime, but now also try $PROJECT_DIR/ep_kernels_workspace/nvshmem/lib
(where install_ep_kernels.sh actually places NVSHMEM) if
$OUTPUT_DIR/nvshmem isn't staged.

Also adds the same hook to multi_node_rl.sbatch.j2's disagg block
(was previously only in inference.sbatch.j2, despite multi_node_rl
running deep_ep in-process when disagg is enabled).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* style: drop unused shutil import, apply ruff format

Caught by the Style workflow — `shutil` was speculatively imported
when wheel_add_cu_suffix.py was first sketched but never used, and
ruff's formatter wanted a couple of cosmetic tweaks.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(deps): exempt torchvision/torchaudio from exclude-newer cooldown

Both are sourced from the `pytorch-cu130` index alongside `torch` and
`flash_attn_3`. That index doesn't publish upload dates, so any package
pulled from it must be exempt from the 7-day `exclude-newer` cooldown
or `uv lock` may fail to resolve when a new release lands inside the
window.

Caught by bugbot.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(deps): refresh uv.lock metadata under uv 0.11.9

Previous lockfile was generated with uv 0.11.7. After the bugbot
fix added `torchvision`/`torchaudio` to `exclude-newer-package`,
CI (which runs uv 0.11.9) detected a metadata drift and failed
`uv sync --locked`, even though the resolved packages were
identical.

Re-locking with uv 0.11.9 reorders the `exclude-newer-package`
section and normalizes the `exclude-newer` value; no resolution
changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* add cu12 cudart to venv dep

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Jackmin801 <ongjackm@gmail.com>
2026-05-05 20:20:19 -07:00
f7a27f69dd fix(sft): don't divide reported throughput by cp (#2424)
Release / Push CUDA image to Docker (push) Canceled after 0s
The bench reported `num_tokens = batch * seq // cp`, which under-reports
tps and MFU by ~cp× when CP > 1. CP is sequence-sharded data parallelism
(cp ranks split the seq dim of the same `batch × seq` tokens), so the
unique training tokens per step is `batch × seq` regardless of cp —
identical to the convention RL already uses (which excludes cp from the
`dp` mesh used for token counting).

Effect: cp=2 runs no longer look 2× slower than they really are in
SFT bench output; numbers become directly comparable across cp values.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 17:33:39 -07:00
minh hoangandGitHub 31591b7fe8 docker: drop deadsnakes in build stage (#2421)
Release / Push CUDA image to Docker (push) Canceled after 0s
deadsnakes has been pretty flakey during image builds on CI, and afaict
i think uv already installs python so don't think it's actually required
2026-05-05 09:24:40 -07:00
samsjaandGitHub 0deb4abaa9 fix(ring_attn): make FA3 causal/window_size kwargs version-agnostic (#2417)
Release / Push CUDA image to Docker (push) Canceled after 0s
66b277fb hardcoded is_causal + window_size_left/right assuming flash_attn_3
  3.0.0 API, but forward uses causal while backward uses is_causal in the
  installed package. Add _set_fa3_signature_params() that inspects the
  get_default_args() dict to set whichever key is actually present, covering
  both param name variants across FA3 versions.
2026-05-04 19:23:23 -07:00
halleriteandGitHub 4be61bbd68 chore(deps): host disagg wheels on prime-rl release instead of samsja personal repo (#2413)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-05 00:07:16 +02:00
rasdaniandGitHub 0660a9b3cb Pin Triton JIT cache to node-local /tmp per job (#2305)
Release / Push CUDA image to Docker (push) Canceled after 0s
Default TRITON_CACHE_DIR=~/.triton/cache lives on NFS in shared-home
clusters. Concurrent multi-node compiles race on that directory and
some ranks hit `ImportError: cannot stat shared object: Stale file
handle` when reading a .so that another node invalidated. One rank
dies, NCCL watchdog trips after 480s on all other ranks, job hangs.

Point TRITON_CACHE_DIR at /tmp/triton-cache-$USER-$SLURM_JOB_ID so
each node has its own local cache and no job shares state with any
other.
2026-05-03 23:37:04 +02:00
217 changed files with 16595 additions and 11592 deletions
+61 -1
View File
@@ -14,7 +14,11 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
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/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
@@ -38,3 +42,59 @@ jobs:
run: PYTEST_OUTPUT_DIR=/tmp/outputs uv run pytest tests/unit -m "not gpu"
- name: Cleanup output_dir
run: rm -rf /tmp/outputs
slim-configs-install:
name: Slim install (prime-rl-configs only)
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Build the slim wheel
run: uv build --wheel ./packages/prime-rl-configs --out-dir /tmp/slim-wheel
- name: Install slim wheel from a directory with no workspace context
# Build the wheel and install it from /tmp so uv can't discover the
# repo's root pyproject.toml [tool.uv.sources] and silently apply
# them. This mirrors what an external pip-only user gets.
run: |
uv venv --python 3.12 /tmp/slim
cd /tmp && uv pip install --python /tmp/slim/bin/python /tmp/slim-wheel/*.whl
- name: Verify configs import without heavy deps
run: |
/tmp/slim/bin/python - <<'PY'
import sys
from prime_rl.configs.rl import RLConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
from prime_rl.utils.validation import validate_shared_ckpt_config
forbidden = ["torch", "transformers", "vllm", "wandb", "ring_flash_attn",
"verifiers", "prime", "datasets", "liger_kernel", "loguru"]
leaked = [m for m in forbidden if m in sys.modules]
if leaked:
raise SystemExit(f"slim install leaked heavy deps into sys.modules: {leaked}")
# Slim wheel does not ship the templates/ data dir; resolver returns None.
assert find_package_resource("templates") is None, "templates should not be in slim wheel"
print("slim install OK — configs import with no heavy deps loaded")
PY
- name: Verify a real config (with [slurm]) parses on slim install
run: |
/tmp/slim/bin/python - <<'PY'
from pydantic_config import cli
from prime_rl.configs.rl import RLConfig
rl = cli(RLConfig, args=["@", "examples/Intellect-3.1/rl.toml"])
assert rl.slurm is not None, "expected [slurm] in example config"
# On slim, template_path can't be auto-resolved (heavy wheel absent) — must stay None.
assert rl.slurm.template_path is None, f"unexpected template_path on slim: {rl.slurm.template_path}"
print("slim parse OK")
PY
@@ -1,4 +1,4 @@
name: Release
name: Docker Push
on:
push:
@@ -24,6 +24,12 @@ jobs:
- name: Checkout
uses: actions/checkout@v3
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/research-environments deps/pydantic-config
- name: Docker meta
id: meta
uses: crazy-max/ghaction-docker-meta@v2
+36 -27
View File
@@ -28,23 +28,20 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
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/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
- name: Run unit tests
env:
USERNAME_CI: CI_RUNNER
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
# This is to allow running tests on forks without WANDB_API_KEY
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
@@ -63,21 +60,36 @@ jobs:
fail-fast: false
matrix:
include:
- test: base
- test: reverse_text_sft
runner: vm
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py --ignore=tests/integration/test_alphabet_sort.py"
- test: rl_lora
pytest_args: "tests/integration/test_reverse_text_sft.py"
- test: reverse_text_sft_lora
runner: vm
pytest_args: "tests/integration/test_rl_lora.py -m gpu"
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
- test: reverse_text
runner: vm
pytest_args: "tests/integration/test_reverse_text.py"
- test: reverse_text_rl_opd
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_opd.py"
- test: reverse_text_rl_sft
runner: vm
pytest_args: "tests/integration/test_reverse_text_rl_sft.py"
- test: alphabet_sort
runner: vm
pytest_args: "tests/integration/test_alphabet_sort.py -m gpu"
- test: rl_multi_run
pytest_args: "tests/integration/test_alphabet_sort.py"
- test: reverse_text_lora
runner: vm
pytest_args: "tests/integration/test_reverse_text_lora.py"
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: reverse_text_multi_run
runner: 4xa6000
pytest_args: "tests/integration/test_rl_multi_run_lora.py -m gpu"
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py -m gpu"
pytest_args: "tests/integration/test_benchmark_regression.py"
steps:
- name: Install Git
run: |
@@ -87,23 +99,20 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
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/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
- name: Run integration tests
env:
USERNAME_CI: CI_RUNNER
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
# This is to allow running tests on forks without WANDB_API_KEY
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
@@ -111,4 +120,4 @@ jobs:
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest ${{ matrix.pytest_args }}
run: uv run pytest -vvs ${{ matrix.pytest_args }}
+6 -2
View File
@@ -25,7 +25,7 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Build matrix from nightly test files
id: build-matrix
@@ -75,7 +75,11 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
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/research-environments deps/pydantic-config
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
+2 -1
View File
@@ -16,8 +16,9 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
with:
submodules: true
submodules: false
- name: Run ruff
uses: astral-sh/ruff-action@v3
with:
+212
View File
@@ -0,0 +1,212 @@
name: Tag and Release
on:
push:
branches:
- main
tags:
# Stable release tags only. `.dev` tags are created by `devx_tag.yaml`
# via GITHUB_TOKEN (which does not retrigger workflows), so they would
# not arrive here anyway — this exclusion is defensive for manual pushes.
- 'v*'
- '!v*dev*'
workflow_dispatch:
inputs:
tag:
description: 'Existing tag to release (e.g. v0.6.0)'
required: true
type: string
jobs:
auto-tag-on-main:
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
contents: write
outputs:
created: ${{ steps.tag.outputs.created }}
tag: ${{ steps.tag.outputs.tag }}
version: ${{ steps.tag.outputs.version }}
steps:
- name: Checkout main
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect version bump and create tag
id: tag
env:
BEFORE_SHA: ${{ github.event.before }}
GH_TOKEN: ${{ github.token }}
run: |
echo "created=false" >> "$GITHUB_OUTPUT"
if [ "$BEFORE_SHA" = "0000000000000000000000000000000000000000" ]; then
echo "No valid base commit available; skipping auto-tag."
exit 0
fi
OLD_VERSION=$(git show "$BEFORE_SHA:pyproject.toml" | sed -n 's/^version = "\([^"]*\)"$/\1/p' | head -n1)
if [ -z "$OLD_VERSION" ]; then
echo "Could not find version in previous pyproject.toml" >&2
exit 1
fi
NEW_VERSION=$(python - <<'PY'
from pathlib import Path
import re
import sys
match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', Path("pyproject.toml").read_text())
if not match:
sys.exit("Could not find version in current pyproject.toml")
print(match.group(1))
PY
)
if [ "$OLD_VERSION" = "$NEW_VERSION" ]; then
echo "No version change detected in pyproject.toml; skipping auto-tag."
exit 0
fi
TAG="v${NEW_VERSION}"
# A draft GitHub Release must already exist for this tag before we
# bump the version on main. The release skill creates it via
# `gh release create --draft` ahead of the PR merge.
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
echo "No GitHub Release found for $TAG." >&2
echo "Create a draft release first: gh release create --draft $TAG --title $TAG --notes-file <notes>.md" >&2
exit 1
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; skipping auto-tag."
exit 0
fi
TAG_EXISTS_LOCAL=false
TAG_EXISTS_REMOTE=false
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
TAG_EXISTS_LOCAL=true
fi
if git ls-remote --exit-code --tags origin "refs/tags/${TAG}" >/dev/null 2>&1; then
TAG_EXISTS_REMOTE=true
fi
if [ "$TAG_EXISTS_LOCAL" = "true" ] || [ "$TAG_EXISTS_REMOTE" = "true" ]; then
# Tag exists but draft hasn't been published — proceed to publish
# (covers retries after the release-from-auto-tag step failed).
echo "Tag ${TAG} already exists with a draft release; will publish."
echo "created=true" >> "$GITHUB_OUTPUT"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
exit 0
fi
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a "$TAG" -m "Release $TAG"
git push origin "$TAG"
echo "created=true" >> "$GITHUB_OUTPUT"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
release-from-auto-tag:
needs: auto-tag-on-main
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.auto-tag-on-main.outputs.created == 'true'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Publish draft release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.auto-tag-on-main.outputs.tag }}
run: |
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
tag-and-release:
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout tagged release (dispatch)
if: github.event_name == 'workflow_dispatch'
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: refs/tags/${{ inputs.tag }}
- name: Checkout tagged release (push)
if: github.event_name != 'workflow_dispatch'
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Resolve release version
id: release
env:
EVENT_NAME: ${{ github.event_name }}
PUSHED_REF: ${{ github.ref_name }}
INPUT_TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || '' }}
run: |
if [ "$EVENT_NAME" = "workflow_dispatch" ]; then
TAG="$INPUT_TAG"
else
TAG="$PUSHED_REF"
fi
if [ -z "$TAG" ]; then
echo "Unable to determine release tag" >&2
exit 1
fi
case "$TAG" in
v*)
;;
*)
echo "Release tags must be prefixed with 'v' (received '$TAG')" >&2
exit 1
;;
esac
VERSION="${TAG#v}"
FILE_VERSION=$(python - <<'PY'
from pathlib import Path
import re
import sys
match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', Path("pyproject.toml").read_text())
if not match:
sys.exit("Could not find version in pyproject.toml")
print(match.group(1))
PY
)
if [ "$FILE_VERSION" != "$VERSION" ]; then
echo "Version mismatch: tag requests '$VERSION' but pyproject.toml defines '$FILE_VERSION'" >&2
exit 1
fi
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Publish draft release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ steps.release.outputs.tag }}
run: |
STATE=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isDraft --jq '.isDraft' 2>/dev/null || echo "missing")
if [ "$STATE" = "missing" ]; then
echo "No GitHub Release found for $TAG." >&2
echo "Create a draft release first: gh release create --draft $TAG --title $TAG --notes-file <notes>.md" >&2
exit 1
fi
if [ "$STATE" = "false" ]; then
echo "Release $TAG is already published; nothing to do."
exit 0
fi
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
+3
View File
@@ -1,4 +1,5 @@
.vscode/*
.claude/scheduled_tasks.lock
*.ipynb
*.jsonl
configs/endpoints.py
@@ -199,3 +200,5 @@ debug_I2_zero_band
.idea
outputs/
third_party/
+15
View File
@@ -0,0 +1,15 @@
[submodule "verifiers"]
path = deps/verifiers
url = git@github.com:PrimeIntellect-ai/verifiers.git
[submodule "renderers"]
path = deps/renderers
url = git@github.com:PrimeIntellect-ai/renderers.git
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "configs/private"]
path = configs/private
url = git@github.com:PrimeIntellect-ai/research-configs.git
[submodule "pydantic-config"]
path = deps/pydantic-config
url = https://github.com/PrimeIntellect-ai/pydantic-config
+1
View File
@@ -3,6 +3,7 @@
## Writing code
- **Minimal try/except**: let errors propagate — silent failures hide bugs. Only catch exceptions for intentional fault tolerance (retries, robustness).
- **Don't touch `optimization_dtype` / `reduce_dtype`**: never change these model config fields (or their defaults in `trainer.py`) unless the user explicitly asks. They're load-bearing numerical knobs — flipping bfloat16/float32 silently changes training dynamics.
- **Targeted comments**: don't explain your work process or reference old code. Use targeted comments sparingly to clarify ambiguous logic.
- **Zen of Python**: remember the Zen of Python when writing code.
```
+11
View File
@@ -2,6 +2,17 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`AdvantageInputs` / `AdvantageOutputs` are now per-group, and `AdvantageOutputs.advantages` is a plain `list[float]`** (second breaking change to this API in three weeks). `AdvantageInputs.rollouts` is now `list[vf.RolloutOutput]` (a single group) instead of `list[list[vf.RolloutOutput]]`, and `AdvantageOutputs.advantages` is now `list[float]` instead of a 2D `Float[Tensor, "num_examples rollouts_per_example"]`. `compute_advantages` calls `advantage_fn` once per group, which lets partial-group training (groups smaller than `rollouts_per_example` after rollout errors) round-trip without the previous bucket-by-size workaround. Custom advantage functions must drop the outer list dimension and return a list of floats — e.g. `AdvantageOutputs(advantages=(rewards - rewards.mean(dim=1, keepdim=True)).tolist())` becomes `AdvantageOutputs(advantages=[r - mean for r in rewards])` (or `.tolist()` if you keep torch internally). (2026-05-22)
- **`[model.vlm]` requires `orchestrator.use_renderer = true`**: VLMs must go through the renderer path; the `vlm_requires_renderer` validator rejects `use_renderer = false` when `[model.vlm]` is set. The renderer owns the HF processor per-slot and ships generic `mm_kwargs` keyed by the model's forward signature. Since `use_renderer` already defaults to `true`, most VLM configs need no change. (2026-05-19)
- **First-class `training_mode` + batch-driven loss dispatch** (collection of removals/renames). Loss selection is now driven by `TrainingSample.training_mode` (`rl` / `opd` / `sft`), set under `[orchestrator]`. The trainer is mode-agnostic and dispatches per batch.
- **`orchestrator.use_sft_loss` removed**: replaced by `[orchestrator] training_mode = "sft"`. The orchestrator stamps each sample's `training_mode` and the trainer dispatches to `sft_loss_fn` per batch.
- **`orchestrator.teacher_rollout_model` removed (no alias)**: configs must rename to `[orchestrator.teacher]` (`teacher_model` is also accepted as a back-compat alias for `teacher`). Used in both opd and sft modes; the role is determined by `training_mode`.
- **`orchestrator.model` → `orchestrator.student`**: renamed for symmetry with `orchestrator.teacher`. Legacy `[orchestrator.model]` and a flat `[orchestrator.model.lora]`-style layout are aliased via a back-compat shim, so most existing configs still parse. New code should use `[orchestrator.student.*]`.
- **`trainer.loss.type = "sft"` removed (`SFTLossConfig` deleted)**: zero-field discriminator that is now implied by `training_mode = "sft"`. `trainer.loss` collapsed to a `DefaultLossConfig | CustomLossConfig` union. Existing configs setting `[trainer.loss] type = "sft"` must remove that line; the orchestrator-level `training_mode = "sft"` is enough.
- **`trainer.loss.teacher_tau` removed from `DefaultLossConfig`**: the teacher-KL term is now exclusive to `opd_loss_fn` (which inlines `teacher_tau = 1.0`). `default_loss_fn` only handles reward-driven RL and no longer accepts a `teacher_tau`. Configs that set `teacher_tau` on `[trainer.loss]` will fail validation — switch to `[orchestrator] training_mode = "opd"` (which uses `opd_loss_fn` with the value baked in).
- **`trainer.loss` only applies to rl-mode batches**: opd and sft don't read `trainer.loss`. `opd_loss_fn`'s knobs (dppo_mask_*, kl_tau) are inlined as literals; tweak them by editing the function. `CustomLossConfig` overrides the rl-mode loss only — opd and sft always use their dedicated fns. (2026-05-19)
- **`orchestrator.use_token_client` removed**: The server-tokenized TITO path has been deprecated end-to-end. The orchestrator-side config flag (`use_token_client`), the verifiers client_type (`openai_chat_completions_token`), and the inference server's `/v1/chat/completions/tokens` route (along with the `OpenAIServingChatWithTokens` wrapper) are all gone. The orchestrator now picks between renderer-backed TITO (`use_renderer = true`, default) and MITO (`use_renderer = false`, fallback). Existing configs with `use_token_client = true` must migrate to `use_renderer = true` (or `use_renderer = false` for MITO); configs with `use_token_client = false` can simply drop the field. (2026-05-19)
- **`orchestrator.advantage.length_penalty` → discriminated sub-config**: The scalar `length_penalty: Literal["tokens","turns"] | None` is replaced by a `LengthPenaltyConfig | None` discriminated on `type`. Token shaping now takes weighted completion + tool-response token costs. Migration: `length_penalty = "tokens"` becomes `[orchestrator.advantage.length_penalty]\ntype = "tokens"` (default weights `completion_weight = 1.0`, `tool_response_weight = 1.0` — total context). `length_penalty = "turns"` becomes `[orchestrator.advantage.length_penalty]\ntype = "turns"`. (2026-05-06)
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
+3 -7
View File
@@ -12,7 +12,7 @@ RUN echo "LC_ALL=en_US.UTF-8" >> /etc/environment
ENV CUDA_HOME=/usr/local/cuda
ENV PATH=$PATH:/usr/local/cuda/bin
# Install packages (including Python 3.12 and ninja for fast CUDA kernel compilation)
# Install build tooling.
ARG DEBIAN_FRONTEND=noninteractive
ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=Etc/UTC
@@ -22,12 +22,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends --force-yes \
sudo \
git \
ninja-build \
software-properties-common \
&& add-apt-repository ppa:deadsnakes/ppa \
&& apt-get update \
&& apt-get install -y --no-install-recommends python3.12 python3.12-dev python3.12-venv \
&& ln -sf /usr/bin/python3.12 /usr/bin/python3 \
&& ln -sf /usr/bin/python3.12 /usr/bin/python \
&& apt-get clean autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
# Download the latest installer
@@ -48,6 +42,8 @@ COPY pyproject.toml /app/pyproject.toml
COPY uv.lock /app/uv.lock
COPY README.md /app/README.md
COPY src/ /app/src/
COPY packages/ /app/packages/
COPY deps/ /app/deps/
COPY configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
+9 -2
View File
@@ -53,6 +53,7 @@ With `[model] impl = "auto"` (the default), the trainer selects that custom stac
| Qwen3 MoE (`qwen3_moe`) | `Qwen/Qwen3-30B-A3B`, … | yes | ✅ | ✅ |
| Qwen3.5 MoE (`qwen3_5_moe`) | `Qwen/Qwen3.5-35B-A3B`, … | yes | ✅ | ✅ |
| Qwen3 / Qwen3.5 VLMs | [multimodal.md](docs/multimodal.md) (`qwen3_vl`, `qwen3_5`, `qwen3_5_moe`) | MoE only on MoE VLMs | MoE only | ✅ |
| Poolside Laguna (`laguna`) | `poolside/Laguna-XS.2` | yes | ✅ | ✅ |
| MiniMax M2 (`minimax_m2`) | `MiniMax/MiniMax-M2` | yes | ✅ | ✅ |
| Nemotron H (`nemotron_h`) | `nvidia/Nemotron-3-Nano-30B-A3B`, `nvidia/Nemotron-3-Super-120B-A12B`, … | yes | ✅ | ❌ |
| Trinity (`afmoe`) | `arcee-ai/Trinity-Mini`, … | yes | ✅ | ✅ |
@@ -90,14 +91,20 @@ git clone https://github.com/PrimeIntellect-ai/prime-rl.git
cd prime-rl
```
2. Install [uv](https://docs.astral.sh/uv/)
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
```
3. Install [uv](https://docs.astral.sh/uv/)
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
source $HOME/.local/bin/env
```
3. Install dependencies from the lock file
4. Install dependencies from the lock file
```bash
uv sync --all-extras
@@ -15,34 +15,34 @@
"cp": 1,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "83c21ddac",
"timestamp": "2026-02-26T02:07:06+00:00",
"commit_sha": "0b37bc923",
"timestamp": "2026-05-19T01:28:25+00:00",
"success": true,
"error_reason": null,
"time_taken": 276.12556480802596
},
"metrics": {
"mfu": {
"mean": 16.41977165630161,
"std": 0.010586646038388221,
"min": 16.407648988464405,
"max": 16.42719598975201
"mean": 22.77046832707997,
"std": 0.03172890658906481,
"min": 22.750797215697055,
"max": 22.80707156937409
},
"throughput": {
"mean": 1960.9836648020673,
"std": 1.2643440104327244,
"min": 1959.5358764831926,
"max": 1961.8703395331793
"mean": 2719.4358949662887,
"std": 3.7893259921987053,
"min": 2717.086609671837,
"max": 2723.8073540657224
},
"step_time": {
"mean": 65.87,
"std": 0.13,
"min": 65.74,
"max": 66.0
"mean": 48.285218452724315,
"std": 0.06726350421944344,
"min": 48.207625919021666,
"max": 48.327002701349556
},
"peak_memory": {
"gib": 31.806640625,
"pct": 67.03
"gib": 24.248046875,
"pct": 51.15428047554115
}
}
}
@@ -15,34 +15,34 @@
"cp": 1,
"docker_image": null,
"device_name": "NVIDIA RTX A6000",
"commit_sha": "83c21ddac",
"timestamp": "2026-02-26T02:07:06+00:00",
"commit_sha": "0b37bc923",
"timestamp": "2026-05-19T01:32:27+00:00",
"success": true,
"error_reason": null,
"time_taken": 291.91085167229176
},
"metrics": {
"mfu": {
"mean": 15.634260517326164,
"std": 0.009817863071768202,
"min": 15.622927380137481,
"max": 15.640172924064188
"mean": 21.824271379711288,
"std": 0.07444985226850119,
"min": 21.739369034306105,
"max": 21.878404774433935
},
"throughput": {
"mean": 7468.685954343421,
"std": 4.690118598479809,
"min": 7463.271969943842,
"max": 7471.510386564679
"mean": 10425.733211800512,
"std": 35.565645418564436,
"min": 10385.174276894972,
"max": 10451.593425935866
},
"step_time": {
"mean": 68.34095695288852,
"std": 0.16054587555887065,
"min": 68.16114284005016,
"max": 68.46991707291454
"mean": 50.39627862814814,
"std": 0.1756523472528039,
"min": 50.26670710090548,
"max": 50.59620195720345
},
"peak_memory": {
"gib": 23.25390625,
"pct": 49.05701678145735
"gib": 17.490234375,
"pct": 36.897831788841806
}
}
}
}
+6 -1
View File
@@ -45,4 +45,9 @@ rollouts_per_example = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+6 -1
View File
@@ -46,4 +46,9 @@ rollouts_per_example = 32
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
@@ -1,10 +1,10 @@
max_steps = 10
max_steps = 5
seq_len = 2048
[ckpt]
[model]
name = "PrimeIntellect/Qwen3-0.6B"
name = "Qwen/Qwen3-0.6B"
[trainer.optim]
lr = 1e-5
@@ -22,3 +22,8 @@ name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
[inference]
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
preserve_all_thinking = true
@@ -1,29 +0,0 @@
max_steps = 10
seq_len = 2048
[deployment]
type = "single_node"
num_infer_gpus = 1
num_train_gpus = 1
[ckpt]
[model]
name = "Qwen/Qwen3-0.6B"
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
[orchestrator.train.sampling]
max_completion_tokens = 1024
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
[inference]
@@ -2,6 +2,7 @@ max_steps = 20
seq_len = 2048
[ckpt]
resume_step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -19,4 +20,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -1,8 +1,7 @@
max_steps = 25
max_steps = 15
seq_len = 2048
[ckpt]
resume_step = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -20,4 +19,8 @@ max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -2,6 +2,7 @@ max_steps = 20
seq_len = 2048
[ckpt]
resume_step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -30,4 +31,8 @@ id = "reverse-text"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
gpu_memory_utilization = 0.7
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -1,8 +1,7 @@
max_steps = 25
max_steps = 15
seq_len = 2048
[ckpt]
resume_step = 20
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -31,4 +30,8 @@ id = "reverse-text"
[inference]
enable_lora = true
gpu_memory_utilization = 0.7
gpu_memory_utilization = 0.7
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -9,6 +9,9 @@ name = "samsja/mini-glm-moe"
[trainer.optim]
lr = 3e-6
[trainer.model]
impl = "custom"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
@@ -24,3 +27,7 @@ gpu_memory_utilization = 0.7
[inference.model]
max_model_len = 2048
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -20,3 +20,7 @@ id = "reverse-text"
[ckpt]
interval = 10
resume_step = -1
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[renderer]
name = "default"
@@ -0,0 +1,51 @@
# Smoke test for the RL-entrypoint OPD (on-policy distillation) training mode.
# The student inference deployment is launched by the rl entrypoint on GPU 0;
# the teacher inference server is started externally by the test fixture (see
# tests/integration/test_reverse_text_rl_opd.py) on the same GPU. Trainer
# takes GPU 1. Training config mirrors `reverse_text/start.toml`.
max_steps = 5
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-ci"
name = "ci-rl-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
rollouts_per_example = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[inference]
gpu_memory_utilization = 0.4
@@ -0,0 +1,48 @@
# Smoke test for the RL-entrypoint SFT (on-policy hard distillation) training
# mode. The student inference deployment is launched by the rl entrypoint on
# GPU 0; the teacher inference server is started externally by the test
# fixture (see tests/integration/test_reverse_text_rl_sft.py) on the same GPU.
# Trainer takes GPU 1. Training config mirrors `reverse_text/start.toml`.
max_steps = 5
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-ci"
name = "ci-rl-sft"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 16
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 16
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[inference]
gpu_memory_utilization = 0.4
@@ -1,6 +1,7 @@
max_steps = 10
[ckpt]
resume_step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -1,7 +1,6 @@
max_steps = 20
max_steps = 5
[ckpt]
resume_step = 10
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -1,7 +1,7 @@
max_steps = 20
max_steps = 10
[ckpt]
resume_step = 10
resume_step = 5
[ckpt.weights]
save_adapter_separately = true
@@ -1,4 +1,4 @@
max_steps = 10
max_steps = 5
[ckpt]
+6 -1
View File
@@ -28,4 +28,9 @@ args = { dataset_name = "nvidia/AceReason-Math", dataset_subset = "default", que
[trainer]
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+47
View File
@@ -0,0 +1,47 @@
# Training Mode — Debug Configs
Minimal end-to-end configs for the three training modes (`rl` / `opd` / `sft`) against the `reverse-text` env, using `PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT` as the student.
| Config | Mode | Teacher | Notes |
|---|---|---|---|
| `rl.toml` | `rl` | none | |
| `opd.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `opd_lora.toml` | `opd` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | |
| `sft_lora.toml` | `sft` | local vLLM (`Qwen3-0.6B-Reverse-Text-RL`) | trains a LoRA adapter (rank 8) |
| `sft_external.toml` | `sft` | PI inference (`openai/gpt-5-mini`) | external OAI endpoint; no local teacher |
The student inference server is auto-launched on GPU 0 at `http://localhost:8000/v1` with `gpu_memory_utilization=0.5`. The local teacher (used by everything except `rl.toml` and `sft_external.toml`) is **not** auto-launched — start it manually on GPU 1.
## Start the local teacher
Needed for `opd*.toml` and `sft.toml` / `sft_lora.toml`:
```bash
CUDA_VISIBLE_DEVICES=1 uv run inference \
--model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
--server.port 8001 \
--gpu-memory-utilization 0.5 \
--model.enforce-eager
```
## Run the debug configs
```bash
# RL (no teacher)
uv run rl @ configs/debug/training_modes/rl.toml
# OPD (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/opd.toml
uv run rl @ configs/debug/training_modes/opd_lora.toml
# SFT hard distill (needs teacher on port 8001)
uv run rl @ configs/debug/training_modes/sft.toml
uv run rl @ configs/debug/training_modes/sft_lora.toml
# SFT hard distill from openai/gpt-5-mini via PI inference
# (requires PRIME_API_KEY + PRIME_TEAM_ID in env; no local teacher needed)
uv run rl @ configs/debug/training_modes/sft_external.toml
```
See [docs/training_modes.md](../../docs/training_modes.md) for what each mode does.
+54
View File
@@ -0,0 +1,54 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-opd"
[orchestrator]
training_mode = "opd"
batch_size = 128
rollouts_per_example = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -0,0 +1,60 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/opd_lora.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-opd-lora"
[orchestrator]
training_mode = "opd"
batch_size = 128
rollouts_per_example = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+41
View File
@@ -0,0 +1,41 @@
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-rl"
[orchestrator]
training_mode = "rl"
batch_size = 128
rollouts_per_example = 16
[orchestrator.renderer]
name = "qwen3"
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+51
View File
@@ -0,0 +1,51 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 4
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -0,0 +1,55 @@
# SFT from openai/gpt-5-mini via PI inference.
# Requires PRIME_API_KEY + PRIME_TEAM_ID in the environment.
#
# Run with:
# uv run rl @ configs/debug/training_modes/sft_external.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft-external"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 4
[orchestrator.train.sampling]
max_completion_tokens = 2048
extra_body = { reasoning_effort = "minimal" }
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "openai/gpt-5-mini"
[orchestrator.teacher.client]
base_url = ["https://api.pinference.ai/api/v1"]
api_key_var = "PRIME_API_KEY"
[orchestrator.teacher.client.headers_from_env]
X-Prime-Team-ID = "PRIME_TEAM_ID"
[trainer.optim]
lr = 3e-6
[ckpt]
[inference]
gpu_memory_utilization = 0.5
@@ -0,0 +1,57 @@
# Start the teacher inference server first (on a separate GPU):
# CUDA_VISIBLE_DEVICES=1 uv run inference \
# --model.name PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL \
# --server.port 8001 --gpu-memory-utilization 0.5 --model.enforce-eager
# Then:
# uv run rl @ configs/debug/training_modes/sft_lora.toml
max_steps = 20
seq_len = 2048
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
[wandb]
project = "reverse-text-debug"
name = "debug-sft-lora"
[orchestrator]
training_mode = "sft"
batch_size = 128
rollouts_per_example = 4
[orchestrator.train.sampling]
max_completion_tokens = 128
[[orchestrator.train.env]]
id = "reverse-text"
[orchestrator.eval]
interval = 1
num_examples = 128
[orchestrator.eval.sampling]
max_completion_tokens = 128
[[orchestrator.eval.env]]
id = "reverse-text"
[orchestrator.teacher.model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL"
[orchestrator.teacher.client]
base_url = ["http://localhost:8001/v1"]
[trainer.optim]
lr = 1e-4
[trainer.model.lora]
rank = 8
[trainer.ckpt.weights]
save_adapter_separately = true
[ckpt]
[inference]
gpu_memory_utilization = 0.5
+6 -1
View File
@@ -31,4 +31,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+6 -1
View File
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+6 -1
View File
@@ -32,4 +32,9 @@ args = { dataset_name= "agentica-org/DeepScaleR-Preview-Dataset", dataset_subset
[trainer.model.ac]
[inference.parallel]
dp = 6
dp = 6
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+7 -2
View File
@@ -6,7 +6,7 @@ project = "gsm8k-debug"
name = "gsm8k"
[model]
name = "PrimeIntellect/Qwen3-0.6B"
name = "Qwen/Qwen3-0.6B"
[orchestrator]
batch_size = 512
@@ -22,4 +22,9 @@ args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max
[trainer] # Default trainer config
[inference] # Default inference config
[inference] # Default inference config
# Mirror of Qwen/Qwen3-0.6B; PI's template patch always re-emits prior
# <think> blocks. Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
preserve_all_thinking = true
+6 -4
View File
@@ -25,9 +25,6 @@ id = "aime2024"
name = "aime2024"
rollouts_per_example = 16
[trainer.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[trainer.model.ac]
[trainer.model.compile]
@@ -36,4 +33,9 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
max_model_len = 8192
[log]
level = "debug"
level = "debug"
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+5 -1
View File
@@ -52,4 +52,8 @@ temperature = 0.5
[trainer.optim]
lr = 3e-6
[inference] # Default inference config
[inference] # Default inference config
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -12,7 +12,6 @@ language_model_attr = "model.language_model"
batch_size = 256
rollouts_per_example = 16
[orchestrator.train.sampling]
max_completion_tokens = 64
@@ -0,0 +1,99 @@
# 20-step Qwen3-VL-4B RL run on color-codeword using the renderer multimodal path.
#
# Pair with rl_color_codeword_main_mito.toml for an A/B comparison: same env,
# same hyperparameters, same step count — only difference is the inference
# client. The feat-branch run uses the new RendererClient + Qwen3VLRenderer
# (renderers package with multimodal support); the main-branch baseline uses
# the existing TITO chat-completions path through the inference server.
#
# Compare in W&B project ``multimodal-renderer``:
# - ``kl/sampler_vs_trainer`` should be ~0 on this branch (the renderer
# produces byte-identical tokens to what the trainer re-tokenizes) and
# can spike on main when BPE drifts mid-rollout.
# - ``reward`` and ``loss`` should track within noise — same model, same
# env, same hyperparameters.
# - ``bridge_break_rate`` is renderer-only; surfaces multi-turn extension
# failures.
max_steps = 20
seq_len = 4096
output_dir = "outputs/rl_color_codeword_feat_renderer"
clean_output_dir = true
# Pure on-policy: inference can't run ahead of training, so every rollout
# is generated from the latest policy weights. Removes async/off-policy
# drift as a confound for the sampler-vs-trainer KL.
max_async_level = 0
[model]
name = "Qwen/Qwen3-VL-4B-Instruct"
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
[deployment]
num_train_gpus = 1
num_infer_gpus = 1
gpus_per_node = 2
[orchestrator]
batch_size = 16
rollouts_per_example = 8
use_renderer = true
# Track zero-advantage groups but don't drop them — we're validating the
# multimodal renderer path on 20 steps, not optimizing training efficiency.
# Step 0 on Qwen3-VL-4B vs color-codeword is likely uniform (all-correct or
# all-wrong) so enforce=True would crash before any training happens.
[[orchestrator.filters]]
type = "gibberish"
[[orchestrator.filters]]
type = "repetition"
[[orchestrator.filters]]
type = "zero_advantage"
enforce = false
[orchestrator.train.sampling]
max_completion_tokens = 64
[[orchestrator.train.env]]
id = "color-codeword"
args = { images_per_turn = 2, max_turns = 2, num_examples = 100, seed = 42 }
[orchestrator.renderer]
name = "auto"
# 64 concurrent rollouts (batch_size=16 × rollouts_per_example=4) want
# more than one tokenizer slot to avoid serialization queueing. The
# image processor (CPU-bound) dominates for VLMs so returns diminish
# past 4; bump to 4 as the default for multimodal runs.
pool_size = 4
[trainer]
[trainer.model]
optimization_dtype = "bfloat16"
reduce_dtype = "bfloat16"
[trainer.optim]
lr = 3e-6
[inference]
[inference.model]
# Workaround for vLLM 0.20.1 Qwen3-VL deepstack buffer bug: when num_scheduled_tokens
# (188) gets padded up to the next cudagraph_capture_size (192), the model's
# _set_deepstack_input_embeds sizes the buffer to 188 but forward() runs with 192,
# triggering "Requested more deepstack tokens than available in buffer". Eager mode
# skips the padding so num_input_tokens == num_scheduled_tokens.
enforce_eager = true
[inference.parallel]
dp = 1
tp = 1
[wandb]
project = "multimodal-renderer"
name = "feat-renderer-20step-r8-i2-t2-onpolicy"
tags = ["qwen3vl-4b", "color-codeword", "renderer", "feat-branch", "mm-kwargs-generic", "on-policy"]
+1
Submodule configs/private added at 74c1330008
Vendored Submodule
+1
Submodule deps/pydantic-config added at 94d71ecdec
Vendored Submodule
+1
Submodule deps/renderers added at 3ae276c446
Vendored Submodule
+1
Vendored Submodule
+1
Submodule deps/verifiers added at 521d436c55
+10 -11
View File
@@ -70,7 +70,7 @@ kwargs = { clip_eps = 0.2 }
## 2. Custom Advantage Functions
Advantages are computed **per-example** (grouped by `rollouts_per_example`). You provide a function that computes advantages for a batch of examples.
Advantages are computed **per-group** (one example × N rollouts). You provide a function that computes advantages for a single group; the framework calls it once per group and stitches the results back together. Groups may have fewer than `rollouts_per_example` rollouts when some rollouts in the group errored (partial-group training).
### Interface
@@ -86,8 +86,8 @@ def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
```python
@dataclass
class AdvantageInputs:
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
rollouts: list[list[vf.RolloutOutput]]
# All rollouts for a single example (one group).
rollouts: list[vf.RolloutOutput]
```
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
@@ -97,22 +97,21 @@ Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.),
```python
@dataclass
class AdvantageOutputs:
advantages: Float[Tensor, "num_examples rollouts_per_example"]
advantages: list[float] # one entry per rollout in the input group
```
### Example: Normalized Advantage
```python
import torch
import statistics
from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
"""Normalize advantages to zero mean and unit variance per example."""
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
mean = rewards.mean(dim=1, keepdim=True)
std = rewards.std(dim=1, keepdim=True)
advantages = (rewards - mean) / (std + eps)
return AdvantageOutputs(advantages=advantages)
"""Normalize advantages to zero mean and unit variance within the group."""
rewards = [r["reward"] for r in inputs.rollouts]
mean = statistics.fmean(rewards)
std = statistics.pstdev(rewards) if len(rewards) > 1 else 0.0
return AdvantageOutputs(advantages=[(r - mean) / (std + eps) for r in rewards])
```
### Configuration
+2 -2
View File
@@ -8,7 +8,7 @@ Checkpointing is non-standard due to trainer/orchestrator separation and natural
The default checkpoint directory is `checkpoints` and each checkpoint step will live in a step subdirectory, i.e. `checkpoints/step_{step}`.
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronoously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
Checkpointing is configured with the config key `--ckpt`. One can specify the interval (`--ckpt.interval`), whether to save checkpoints asynchronously (`--ckpt.save-async`), how many recent step checkpoints to keep on disk (`--ckpt.keep-last`), and keep checkpoints at every N steps permanently (`--ckpt.keep-interval`). By default, we do not checkpoint to save disk space.
## SFT
@@ -54,4 +54,4 @@ uv run rl \
--orchestrator @ path/to/orch.toml \
--max-steps 20 \
--ckpt.resume-step 10
```
```
+1 -1
View File
@@ -30,4 +30,4 @@ name = "Qwen/Qwen-14B"
PRIME_MODEL__NAME=Qwen/Qwen3-4B uv run ... @ qwen8b.toml @ qwen14b.toml --model.name Qwen/Qwen3-32B
```
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
In this example, the CLI argument `--model.name Qwen/Qwen3-32B` will take precedence and the script will use `Qwen/Qwen3-32B` as the model name. If the CLI argument wasn't set, then the second config file would take precedence and the script would use `Qwen/Qwen-14B` as the model name. If the second config file wasn't set, then the first config file would take precedence and the script would use `Qwen/Qwen3-8B` as the model name. Finally, if the first config file wasn't set, then the environment variable would take precedence and the script would use `Qwen/Qwen3-4B` as the model name. If the environment variable wasn't set, then the default value would be used and the script would use `Qwen/Qwen3-0.6B` as the model name.
+1 -1
View File
@@ -48,7 +48,7 @@ For more details on multi-node deployment options, see the [deployment](deployme
## SFT
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seemless post-training workflow.
We provide a fairly straight-forward SFT trainer which is capable of fine-tuning any conversational model on multi-turn conversation with tool calling. It shares a lot of components with the RL trainer, such as the modeling code, parallelism techniques, checkpoint format, logger, etc. which ensures a seamless post-training workflow.
To start an SFT training, you need to prepare a conversational dataset in either [prompt-completion format](https://huggingface.co/docs/trl/en/dataset_formats#prompt-completion) or raw `messages` format. If `messages` is provided, the trainer interprets the full conversation as a single sample with an empty prompt and applies role-based loss masking across the whole chat. If both `messages` and `prompt` / `completion` are present, `messages` takes precedence. Single-turn fine-tuning should be compatible with the chat templates of most models. However, to properly handle loss masking, we require that the tokenizer's chat template satisfies a prefix property: the tokenization of any conversation prefix must be a prefix of the tokenization of the full conversation. For instance, tokenizing message 1 should yield a token sequence that forms a prefix of tokenizing messages 1 and 2, which in turn should be a prefix of tokenizing messages 1, 2, 3, and so forth. An example of a chat template that *does not* satisfy this property is Qwen3's chat template, as it strips away past think sections.
+3 -1
View File
@@ -7,6 +7,7 @@
"index",
"entrypoints",
"configs",
"training_modes",
"environments",
"async",
"logging",
@@ -15,8 +16,9 @@
"benchmarking",
"deployment",
"kubernetes",
"testing-moe-at-small-scale",
"troubleshooting"
]
}
]
}
}
+4 -6
View File
@@ -47,13 +47,11 @@ To add permanent support for a new model family, add an entry to `VLM_REGISTRY`
## How Multi-Turn VLM RL Training Works
VLM training uses the same `interleave_rollout` path as text-only models. Multi-turn trajectory steps are merged into a single training sample wherever the extension property holds.
VLM rollouts go through the renderer-backed TITO client (`orchestrator.use_renderer = true`, the default and required for VLMs). The renderer owns the HuggingFace processor per-slot and emits multimodal tensors alongside tokens.
Images are handled via a `VLMImageCache` built once per batch:
1. **Extract**: Base64 images are decoded from trajectory step prompts into PIL images.
2. **Preprocess**: Images are processed through the HuggingFace image processor, producing `pixel_values` and `image_grid_thw`.
3. **Attach**: Each training sample receives the cumulative `pixel_values` up to its last merged step.
1. **Render**: For each trajectory step, the renderer tokenizes messages and emits per-image multimodal tensors (e.g. `pixel_values`, `image_grid_thw` for Qwen3-VL) as `multi_modal_data`.
2. **Pack**: `interleave_rollout` concatenates the per-image tensors emitted across a sample's merged step range into a single `mm_kwargs` dict on the `TrainingSample`. Per-token `mm_token_type_ids` (0=text, 1=image, 2=video) come from `renderer.mm_token_type_id_map`.
3. **Forward**: The trainer `**`-unpacks `mm_kwargs` into the model's `forward` signature, so any VLM whose HF processor and forward agree on kwarg names works without touching the transport.
Each multimodal sample becomes its own micro-batch during training (no packing) since image tensor sizes vary.
-117
View File
@@ -1,117 +0,0 @@
# On-Policy Distillation
On-policy distillation uses a teacher model to provide dense token-level feedback during RL training. The student generates rollouts, and the teacher's logprobs guide the student to stay close to stronger behavior while still learning from rewards.
For more details, see [On-Policy Distillation](https://thinkingmachines.ai/blog/on-policy-distillation/) by Thinking Machines.
## Quick Start
Add `num_teacher_gpus` to `[deployment]` and set `teacher_tau > 0`:
```toml
[deployment]
num_teacher_gpus = 2
[trainer.loss]
teacher_tau = 0.5
```
This automatically starts a teacher inference server using the same model as inference. To use a different teacher model:
```toml
[deployment]
num_teacher_gpus = 2
[teacher_inference.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
[trainer.loss]
teacher_tau = 0.5
```
## Using an External Teacher Server
If the teacher is already running elsewhere:
```toml
[trainer.loss]
teacher_tau = 0.5
[orchestrator.teacher_model.client]
base_url = ["http://teacher-server:8000/v1"]
[orchestrator.teacher_model.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B"
```
## Pure Distillation (No Verification)
For agentic environments where verification is expensive (code execution, tool use, multi-turn interactions), you can skip verification entirely and use only the teacher signal:
```toml
[deployment]
num_teacher_gpus = 2
[trainer.loss]
teacher_tau = 1.0
adv_tau = 0.0 # Disable reward-based learning
[orchestrator.verification]
enabled = false # Skip expensive verification
```
This runs pure on-policy distillation: the student learns to match the teacher without needing any reward signal.
## SFT Distillation ("Hard Distillation") From Teacher Rollouts
Use this mode when you want to train from teacher-generated completions directly (hard distillation), without teacher token-level logprobs.
```toml
[trainer.loss]
type = "sft"
[orchestrator]
use_token_client = false
[orchestrator.teacher_rollout_model.client]
base_url = ["https://your-openai-compatible-endpoint/v1"]
skip_model_check = true
[orchestrator.teacher_rollout_model.model]
name = "teacher-model-name"
```
In this mode:
- Rollouts are generated from `orchestrator.teacher_rollout_model`
- The orchestrator uses text-level reconstruction with the student tokenizer
- The RL trainer optimizes masked NLL (`trainer.loss.type = "sft"`)
- Omit `[inference]` (no local inference server required)
### Image Input (VLM) Support
Yes, image input is supported in SFT/hard-distillation mode when the student model is multimodal (VLM).
- Prompts can include OpenAI-style image items in `message.content`, e.g. `{"type": "image_url", "image_url": {"url": "data:image/..."}}`
- The orchestrator extracts and preprocesses images from trajectory prompts and attaches `pixel_values`/`image_grid_thw` to training samples
- No teacher token IDs/logprobs are required; reconstruction still happens from messages
Notes:
- This path currently expects `data:image/...` payloads in message content
- The teacher rollout endpoint still needs to be able to handle the same multimodal prompts during generation
Reference configs:
- `configs/alphabet_sort/sft_distill_hard_qwen4b_lora_prime_teacher.toml`
- `examples/alphabet_sort/sft_distill_hard.toml`
## Parameters
| Parameter | Default | Description |
|-----------|---------|-------------|
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for teacher server. Auto-starts server when set. |
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Set `> 0` to enable. |
| `trainer.loss.adv_tau` | `1.0` | Weight for RL advantage signal. Set `0` for pure distillation. |
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
## Monitoring
The `teacher_kl` metric shows the KL divergence from teacher to student. Lower values mean the student is closer to the teacher.
+39
View File
@@ -0,0 +1,39 @@
# Training Modes
PRIME-RL supports three training modes through our RL trainer, selected via `training_mode`:
- **`rl`** — reinforcement learning: student generates rollouts, no teacher
- **`opd`** — [on-policy distillation](https://thinkingmachines.ai/blog/on-policy-distillation/): students generates rollouts, train to minimize the KL divergence between the student and teacher's logprobs for each token in the rollout
- **`sft`** — supervised fine-tuning on teacher-generated rollouts
> Note: PRIME-RL also has a dedicated `sft` entrypoint for more traditional supervised fine-tuning from a HF dataset. When using the `sft` training mode on the orchestrator, teacher rollouts are generated on-the-fly and used for training.
The mode determines who generates rollouts, what role the teacher plays, and what must be configured.
| Mode | Student | Teacher |
|---|---|---|
| `rl` | required | forbidden |
| `opd` | required | required (local vLLM) |
| `sft` | required | required (any OAI-compatible endpoint) |
**SFT vs OPD teachers** differ in what the orchestrator asks of them. SFT only calls `/v1/chat/completions` to generate rollouts — any OpenAI-compatible endpoint works (PI inference, OpenAI, Anthropic, a local vLLM). OPD additionally needs token-level logprobs scored over the student's tokens, which today only vLLM's `/inference/v1/generate` with `prompt_logprobs` exposes — so the OPD teacher must be a vLLM server.
### Reference configs
Debug-scale configs for all three modes (and LoRA variants) live in [`configs/debug/training_modes/`](../configs/debug/training_modes/):
- `rl.toml` / `opd.toml` / `opd_lora.toml`
- `sft.toml` / `sft_lora.toml` (local vLLM teacher)
- `sft_external.toml` (PI inference teacher)
See [`configs/debug/training_modes/README.md`](../configs/debug/training_modes/README.md) for run commands.
## Parameter reference
| Parameter | Default | Description |
|-----------|---------|-------------|
| `training_mode` | `"rl"` | One of `rl`, `opd`, `sft`. Propagates to `orchestrator.training_mode` and (for sft) `trainer.loss.type`. |
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for the teacher vLLM server. Auto-starts when set. OPD only. |
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Must be `> 0` in OPD. |
| `trainer.loss.adv_tau` | `1.0` | Weight for the RL advantage signal. Set `0` for pure distillation. |
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
+1 -1
View File
@@ -39,7 +39,7 @@ Interleaving enforces a strict invariant:
> The prompt at turn $t$ must be the exact concatenation of prior messages exactly as the LLM originally generated them
We call this the "exact prefix" invariant. For example, at turn 2, the LLM should see U1,A1,U2 as the prompt, where U1 exactly matches the user message in turn 1 and A1 exactly matches the produced assistant message in turn 1. Any violation to this invariant will result in downstream problems when computing the importance sampling ratio during training.
We call this the "exact prefix" invariant. For example, at turn 2, the LLM should see U1,A1,U2 as the prompt, where U1 exactly matches the user message in turn 1 and A1 exactly matches the produced assistant message in turn 1. Any violation of this invariant will result in downstream problems when computing the importance sampling ratio during training.
For example, assume that at turn 2 the prompt is U1,A1',U2 where A1' varies from A1. In this scenario it is not clear whether to add A1 or A1' to the interleaved rollout:
- If we add A1', the logprobs from turn 1 might be off because the inference LLM produced A1 but the trainer LLM is computing logprobs for A1'
+1 -1
View File
@@ -12,7 +12,7 @@ ulimit -n 32000
Assuming this is happening on the RL or SFT trainer, you can try the following:
- Use full activation checkpointing (`--model.ac`)
- Reduce the the micro batch size (`--data.micro-batch-size`) and sequence length (`--data.seq-len`)
- Reduce the micro batch size (`--data.micro-batch-size`) and sequence length (`--data.seq-len`)
- (*Experimental*) Use context parallelism with `--model.cp`
> I cannot pass my TOML config file
+5 -1
View File
@@ -94,4 +94,8 @@ args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200
id = "aime2025"
[inference.parallel]
tp = 8
tp = 8
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
@@ -1,49 +0,0 @@
max_steps = 24
seq_len = 2048
[deployment]
type = "single_node"
gpus_per_node = 2
num_train_gpus = 2
num_infer_gpus = 0
[model]
name = "Qwen/Qwen3-4B-Instruct-2507"
[wandb]
project = "alphabet-sort-sft-distill"
name = "qwen3-4b-hard-distill"
[ckpt]
[trainer.optim]
lr = 1e-5
[trainer.model.lora]
rank = 16
alpha = 32
[trainer.ckpt.weights]
save_adapter_separately = true
[orchestrator]
batch_size = 256
rollouts_per_example = 4
use_token_client = false
use_sft_loss = true
[orchestrator.train.sampling]
max_completion_tokens = 512
temperature = 0.7
[orchestrator.teacher_rollout_model.client]
base_url = ["https://api.pinference.ai/api/v1"]
api_key_var = "PRIME_API_KEY"
[orchestrator.teacher_rollout_model.model]
name = "qwen/qwen3-235b-a22b-instruct-2507"
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
+4 -3
View File
@@ -6,9 +6,6 @@ level = "debug"
[wandb]
project = "glm5-pd-disag"
[model]
name = "zai-org/GLM-5"
[weight_broadcast]
type = "nccl"
port = 29502
@@ -38,6 +35,7 @@ interval = 100
dist_timeout_seconds = 7200
[trainer.model]
name = "zai-org/GLM-5"
impl = "custom"
attn = "flash_attention_2" # dsa is skipping flash attn anyway
fused_lm_head_token_chunk_size = 2048
@@ -68,6 +66,9 @@ rollouts_per_example = 16
oversampling_factor = 3
max_off_policy_steps = 16
[orchestrator.student.model]
name = "zai-org/GLM-5-FP8"
[orchestrator.eval]
interval = 20
+7 -3
View File
@@ -1,5 +1,4 @@
max_steps = 5000
seq_len = 8192
[wandb]
project = "hendrycks-sanity"
@@ -15,6 +14,7 @@ name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
[orchestrator]
batch_size = 512
rollouts_per_example = 8
seq_len = 8192
[[orchestrator.train.env]]
id = "math-env" # included in lock file
@@ -30,8 +30,12 @@ name = "aime2024"
rollouts_per_example = 32
[trainer.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
seq_len = 16384
[inference.model]
max_model_len = 8192
max_model_len = 8192
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
reasoning_parser = "think"
+5 -1
View File
@@ -68,4 +68,8 @@ hard_threshold = 0.0
seed = 42
[inference.parallel]
tp = 8
tp = 8
# PrimeIntellect/MiniMax-M2.5-bf16 — template-identical to MiniMaxAI/MiniMax-M2.5 (mapped).
[orchestrator.renderer]
name = "minimax-m2"
+5 -1
View File
@@ -23,4 +23,8 @@ lr = 3e-6
[ckpt] # Checkpoint at the end of training
[inference]
[inference]
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[orchestrator.renderer]
name = "default"
+7
View File
@@ -29,3 +29,10 @@ max_completion_tokens = 1024
[inference.parallel]
dp = 6
# Qwen3 finetune with the standard PI template patch (byte-identical to
# PrimeIntellect/Qwen3-0.6B base); always re-emits prior <think> blocks.
# Match that with the qwen3 renderer's preserve_all_thinking.
[orchestrator.renderer]
name = "qwen3"
preserve_all_thinking = true
+1 -1
View File
@@ -9,7 +9,7 @@ name = "PrimeIntellect/Qwen3-1.7B"
name = "willcb/V3-wordle"
seq_len = 1024
batch_size = 64
micro-batch-size = 1
micro_batch_size = 1
[optim]
lr = 1e-5
+26
View File
@@ -0,0 +1,26 @@
# prime-rl-configs
Slim config schema for [`prime-rl`](https://github.com/PrimeIntellect-ai/prime-rl), with no GPU or ML deps.
`pip install prime-rl-configs` gives you `prime_rl.configs.*` (RL/SFT/inference/orchestrator/trainer/env-server schemas) without pulling in `torch`, `vllm`, `transformers`, `wandb`, etc. The full training stack lives in `prime-rl`, which depends on this package.
## Install
```sh
pip install git+https://github.com/PrimeIntellect-ai/prime-rl.git#subdirectory=packages/prime-rl-configs
```
## Usage
The pip *distribution name* (`prime-rl-configs`) and the *import path* (`prime_rl.configs.*`) are different on purpose: this package contributes submodules to the shared `prime_rl` namespace.
```python
from pydantic_config import cli
from prime_rl.configs.rl import RLConfig
config = cli(RLConfig, args=["@", "path/to/rl.toml"])
```
Other config classes live alongside `RLConfig` under `prime_rl.configs.*` (`sft`, `inference`, `orchestrator`, `trainer`, `env_server`).
`import prime_rl` on its own succeeds but is empty — it's a [PEP 420](https://peps.python.org/pep-0420/) namespace package with no top-level attributes. Always import a submodule.
+28
View File
@@ -0,0 +1,28 @@
[project]
name = "prime-rl-configs"
version = "0.4.0"
description = "Slim config schema for prime-rl (no GPU/ML deps)."
readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
"prime-pydantic-config>=0.3.0.dev82",
# OrchestratorConfig validates renderer.name='auto' against
# renderers.base.MODEL_RENDERER_MAP. Renderers itself is light; its only
# weighty transitive (transformers) is lazy-imported via the validator,
# so plain `from prime_rl.configs.orchestrator import OrchestratorConfig`
# still doesn't pull it into sys.modules.
"renderers>=0.1.8.dev4",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/prime_rl"]
[tool.hatch.metadata]
allow-direct-references = true
@@ -0,0 +1,25 @@
from pathlib import Path
from pydantic import model_validator
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.utils.config import BaseConfig
class EnvServerConfig(BaseConfig):
env: EnvConfig = EnvConfig()
log: LogConfig = LogConfig()
env_install_prerelease: bool = False
"""Allow pre-release versions when installing environments. Passes ``--prerelease`` to ``prime env install``."""
output_dir: Path = Path("outputs")
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
@model_validator(mode="after")
def validate_num_workers(self):
if self.env.num_workers == "auto":
self.env.num_workers = 1
return self
@@ -0,0 +1,457 @@
from argparse import Namespace
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from pydantic_config import BaseConfig
from prime_rl.configs.shared import BaseModelConfig, SlurmConfig
from prime_rl.utils.config import find_package_resource, rgetattr, rsetattr
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
# TODO: Set thinking/ solution budget
class ServerConfig(BaseConfig):
host: str | None = None
"""Host to bind to."""
port: int = 8000
"""Port to bind to."""
liveness_timeout_seconds: float = Field(30.0, gt=0)
"""Timeout in seconds for the ``/liveness`` endpoint's internal vLLM worker RPC. With Kubernetes liveness probes, keep the probe ``timeoutSeconds`` at least this high."""
class ParallelConfig(BaseConfig):
tp: int = 1
"""Tensor parallel size. Forwarded to vLLM as ``--tensor-parallel-size``."""
dp: int = Field(1, ge=1)
"""Data parallel size. Forwarded to vLLM as ``--data-parallel-size``."""
def __str__(self) -> str:
return f"tp={self.tp} dp={self.dp}"
class ModelConfig(BaseModelConfig):
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html).
Parser fields (``tool_call_parser``, ``reasoning_parser``) default to ``"auto"``,
which resolves to a concrete parser name at validation time from the model name.
Set to ``None`` to disable.
"""
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
"""dtype for model weights and activations. ``auto`` uses FP16 for FP32/FP16 models and BF16 for BF16 models. Forwarded as ``--dtype``."""
max_model_len: int | None = None
"""Maximum model context length. If None, uses the model config's value. Forwarded as ``--max-model-len``."""
enforce_eager: bool = False
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance. Forwarded as ``--enforce-eager``."""
trust_remote_code: bool = False
"""Trust remote code. Forwarded to vLLM engine init."""
chat_template: str | None = None
"""Chat template — a Jinja2 template string or path to a template file. Forwarded as ``--chat-template``. If None, uses the model's default."""
tool_call_parser: str | None = "auto"
"""Tool-call parser. Forwarded as ``--tool-call-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
reasoning_parser: str | None = "auto"
"""Parser for extracting reasoning content from model outputs. Forwarded as ``--reasoning-parser``. Set to ``"auto"`` (default) to detect from the model name, or ``None`` to disable."""
rope_scaling: dict[str, Any] | str | None = None
"""RoPE scaling configuration as a dict (e.g. ``{rope_type="yarn", factor=4.0, original_max_position_embeddings=32768}``). Forwarded as ``--rope-scaling``."""
@model_validator(mode="after")
def auto_resolve_parsers(self):
"""Resolve ``"auto"`` parser values to concrete parser names from the model name.
Runs after ``RLConfig.auto_setup_shared_configs`` (mode=before) has
propagated the shared ``[model] name`` into ``inference.model``, so the
name is set even when only the shared block specifies it.
"""
if self.tool_call_parser == "auto":
self.tool_call_parser = resolve_tool_call_parser(self.name)
if self.reasoning_parser == "auto":
self.reasoning_parser = resolve_reasoning_parser(self.name)
return self
class WeightBroadcastConfig(BaseConfig):
type: Literal["nccl", "filesystem"] = "filesystem"
"""Weight broadcast transport."""
class KVCacheOffloadConfig(BaseConfig):
cpu_bytes: int = Field(1_000_000_000, gt=0)
"""CPU bytes available for KV cache offloading per worker."""
# Valid vLLM max_lora_rank values (from vllm/config/lora.py)
# TODO: on newer vLLM, can import via `get_args(vllm.config.lora.MaxLoRARanks)`
VALID_VLLM_LORA_RANKS = (8, 16, 32, 64, 128, 256, 320, 512)
# vLLM all2all backend options for expert-parallel deployments.
All2AllBackend = Literal[
"allgather_reducescatter",
"deepep_high_throughput",
"deepep_low_latency",
"flashinfer_nvlink_one_sided",
"flashinfer_nvlink_two_sided",
]
class BaseInferenceDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["single_node"] = "single_node"
# Multi-node inference: each node runs an independent vLLM replica.
class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["multi_node"] = "multi_node"
num_nodes: int = Field(2, ge=1)
"""Inference nodes."""
router_port: int = 8000
"""Port for the vllm-router."""
backend_port: int = 8100
"""Port for vLLM backend instances."""
router_policy: str = "consistent_hash"
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
# Disaggregated prefill/decode inference. Each replica is split into separate
# prefill and decode node groups. Requires NIXL for KV transfer and a vllm-router
# for request routing. Multi-replica: set ``num_prefill_replicas`` /
# ``num_decode_replicas`` to run multiple independent vLLM instances within the
# prefill / decode node groups. E.g. ``num_prefill_nodes=4, num_prefill_replicas=2``
# creates two prefill vLLM instances each spanning 2 nodes (EP16 with 8 GPUs/node).
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["disaggregated"] = "disaggregated"
num_prefill_nodes: int = Field(1, ge=1)
"""Total prefill nodes."""
num_decode_nodes: int = Field(1, ge=1)
"""Total decode nodes."""
num_prefill_replicas: int = Field(1, ge=1)
"""Independent prefill vLLM instances. Must evenly divide ``num_prefill_nodes``."""
num_decode_replicas: int = Field(1, ge=1)
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
router_port: int = 8000
"""Port for the vllm-router on each replica."""
prefill_port: int = 8100
"""Port for prefill vLLM instances."""
decode_port: int = 8200
"""Port for decode vLLM instances."""
router_policy: str = "consistent_hash"
"""vllm-router routing policy (e.g. ``consistent_hash``, ``round_robin``)."""
prefill_env_overrides: dict[str, str] = {}
"""Extra environment variables exported only on prefill nodes."""
decode_env_overrides: dict[str, str] = {}
"""Extra environment variables exported only on decode nodes."""
@property
def num_nodes(self) -> int:
return self.num_prefill_nodes + self.num_decode_nodes
@model_validator(mode="after")
def validate_replicas_divide_nodes(self):
if self.num_prefill_nodes % self.num_prefill_replicas != 0:
raise ValueError(
f"num_prefill_replicas ({self.num_prefill_replicas}) must evenly divide "
f"num_prefill_nodes ({self.num_prefill_nodes})"
)
if self.num_decode_nodes % self.num_decode_replicas != 0:
raise ValueError(
f"num_decode_replicas ({self.num_decode_replicas}) must evenly divide "
f"num_decode_nodes ({self.num_decode_nodes})"
)
return self
InferenceDeploymentConfig: TypeAlias = Annotated[
SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig,
Field(discriminator="type"),
]
class InferenceExperimentalConfig(BaseConfig):
pass
class InferenceConfig(BaseConfig):
server: ServerConfig = ServerConfig()
model: ModelConfig = Field(default_factory=ModelConfig)
parallel: ParallelConfig = ParallelConfig()
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
enable_lora: bool = False
"""Enable LoRA. Forwarded as ``--enable-lora``."""
max_loras: int = 8
"""Maximum number of LoRAs. Forwarded as ``--max-loras``."""
# TODO: The default value is very high because our areal impl for lora isn't ideal
# We add a lora with the same name instead of changing weights inplace
# Because we dont cancel requests that are past max_async, these requests could be using a LoRA that gets unloaded which will crash the inference server
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU. Forwarded as ``--max-cpu-loras``."""
max_lora_rank: int | None = None
"""Maximum LoRA rank. Forwarded as ``--max-lora-rank``."""
lora_target_modules: list[str] | None = None
"""LoRA target modules. Forwarded as ``--lora-target-modules``."""
enable_prefix_caching: bool | None = None
"""Enable prefix caching. Forwarded as ``--enable-prefix-caching``."""
gpu_memory_utilization: float = 0.9
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
api_server_count: int = Field(1, ge=0)
"""API servers to run. Forwarded as ``--api-server-count``. Set to 0 for headless mode."""
data_parallel_size_local: int | None = Field(None, ge=1)
"""Data parallel replicas to run on this node. Forwarded as ``--data-parallel-size-local``."""
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
"""RPC port for data parallel communication. Forwarded as ``--data-parallel-rpc-port``."""
seed: int = 0
"""Seed the inference components. Forwarded as ``--seed``."""
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models. Forwarded as ``--enable-expert-parallel``."""
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication. Forwarded as ``--all2all-backend``."""
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB). Forwarded as ``--enable-eplb``."""
enable_dbo: bool = False
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
use_deep_gemm: bool = False
"""Force DeepGEMM FP8 kernels via ``VLLM_USE_DEEP_GEMM=1``. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8)."""
weight_broadcast: WeightBroadcastConfig = WeightBroadcastConfig()
kv_cache_offload: KVCacheOffloadConfig | None = None
"""CPU KV cache offload for inference workers. Standard inference uses vLLM's ``OffloadingConnector``. Disaggregated P/D deployments combine it with NIXL through ``MultiConnector`` in the SLURM launcher."""
enable_return_routed_experts: bool = False
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
enable_fp32_lm_head: bool = False
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""
vllm_extra: dict[str, Any] = {}
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
# Launcher-only fields
deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig()
slurm: SlurmConfig | None = None
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
output_dir: Path = Path("outputs")
"""Directory for SLURM logs and generated scripts."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: InferenceExperimentalConfig = InferenceExperimentalConfig()
@model_validator(mode="after")
def validate_multi_node_requires_slurm(self):
if self.deployment.type == "multi_node" and self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
return self
@model_validator(mode="after")
def auto_setup_kv_cache_offload(self):
if self.kv_cache_offload is not None:
if self.enable_prefix_caching is False:
raise ValueError("KV cache offloading requires inference.enable_prefix_caching to be true.")
if "enable_prefix_caching" not in self.model_fields_set:
self.enable_prefix_caching = True
return self
@model_validator(mode="after")
def auto_setup_disaggregated(self):
"""Auto-configure inference for disaggregated P/D: enable EP and compute DP."""
if self.deployment.type == "disaggregated":
if "enable_expert_parallel" not in self.model_fields_set:
self.enable_expert_parallel = True
if "enable_eplb" not in self.model_fields_set:
self.enable_eplb = False
gpus_per_node = self.deployment.gpus_per_node
tp = self.parallel.tp
dp_per_node = gpus_per_node // tp
if self.data_parallel_size_local is None:
self.data_parallel_size_local = dp_per_node
if self.parallel.dp == 1:
self.parallel.dp = dp_per_node
if self.api_server_count == 1:
self.api_server_count = dp_per_node
return self
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.template_path is None:
templates_dir = find_package_resource("templates")
if templates_dir is not None:
self.slurm.template_path = templates_dir / "inference.sbatch.j2"
return self
@model_validator(mode="after")
def auto_setup_max_lora_rank(self):
"""Auto-setup max_lora_rank by rounding up to the nearest valid vLLM value.
vLLM only accepts specific values for max_lora_rank: (1, 8, 16, 32, 64, 128, 256, 320, 512).
This validator ensures that any configured rank is rounded up to the minimum valid value
that can serve adapters of the requested rank.
"""
if self.max_lora_rank is not None:
original_rank = self.max_lora_rank
for valid_rank in VALID_VLLM_LORA_RANKS:
if valid_rank >= self.max_lora_rank:
self.max_lora_rank = valid_rank
break
else:
raise ValueError(f"max_lora_rank={original_rank} exceeds vLLM maximum of {VALID_VLLM_LORA_RANKS[-1]}")
return self
@model_validator(mode="after")
def auto_setup_api_server_count(self):
"""
Ensures that we have at least as many API servers as data parallel
size. Unless LoRA is enabled, in which case only one API server is
supported (vLLM limitation).
"""
if self.vllm_extra.get("headless", False):
self.api_server_count = 0
return self
if "api_server_count" not in self.model_fields_set:
min_api_server_count = self.data_parallel_size_local or self.parallel.dp
if self.api_server_count < min_api_server_count:
self.api_server_count = min_api_server_count
if self.enable_lora:
self.api_server_count = 1 # LoRA requires only one API server
return self
def to_vllm(self) -> Namespace:
"""Convert InferenceConfig to vLLM-compatible Namespace."""
namespace = Namespace()
to_vllm = {
"server.host": "host",
"server.port": "port",
"server.liveness_timeout_seconds": "liveness_timeout_seconds",
"model.name": "model",
"model.dtype": "dtype",
"model.max_model_len": "max_model_len",
"model.enforce_eager": "enforce_eager",
"model.trust_remote_code": "trust_remote_code",
"model.chat_template": "chat_template",
"model.tool_call_parser": "tool_call_parser",
"model.reasoning_parser": "reasoning_parser",
"model.rope_scaling": "rope_scaling",
"parallel.tp": "tensor_parallel_size",
"parallel.dp": "data_parallel_size",
"data_parallel_size_local": "data_parallel_size_local",
"data_parallel_rpc_port": "data_parallel_rpc_port",
"enable_lora": "enable_lora",
"enable_prefix_caching": "enable_prefix_caching",
"max_loras": "max_loras",
"max_cpu_loras": "max_cpu_loras",
"max_lora_rank": "max_lora_rank",
"lora_target_modules": "lora_target_modules",
"gpu_memory_utilization": "gpu_memory_utilization",
"api_server_count": "api_server_count",
"enable_return_routed_experts": "enable_return_routed_experts",
"enable_expert_parallel": "enable_expert_parallel",
"all2all_backend": "all2all_backend",
"enable_eplb": "enable_eplb",
"enable_dbo": "enable_dbo",
"seed": "seed",
}
for config_key, vllm_key in to_vllm.items():
value = rgetattr(self, config_key.replace("-", "_"))
rsetattr(namespace, vllm_key, value)
# Set `logprobs_mode` to `processed_logprobs` by default
rsetattr(namespace, "logprobs_mode", "processed_logprobs")
if self.kv_cache_offload is not None:
rsetattr(
namespace,
"kv_transfer_config",
{
"kv_connector": "OffloadingConnector",
"kv_role": "kv_both",
"kv_connector_extra_config": {
"cpu_bytes_to_use": int(self.kv_cache_offload.cpu_bytes),
},
},
)
# Pass prime-rl-specific flags through vLLM's additional_config dict;
# workers read these via get_current_vllm_config().additional_config.
if self.enable_fp32_lm_head:
existing = getattr(namespace, "additional_config", None) or {}
existing["fp32_lm_head"] = True
rsetattr(namespace, "additional_config", existing)
# Remove chat_template if not set (vLLM doesn't accept None)
if namespace.chat_template is None:
delattr(namespace, "chat_template")
# Remove tool_call_parser if not set (vLLM doesn't accept None) and gate
# `enable_auto_tool_choice` on its presence.
if namespace.tool_call_parser is None:
delattr(namespace, "tool_call_parser")
namespace.enable_auto_tool_choice = hasattr(namespace, "tool_call_parser")
# Remove reasoning_parser if not set (vLLM doesn't accept None)
if namespace.reasoning_parser is None:
delattr(namespace, "reasoning_parser")
# Remove lora_target_modules if not set (vLLM doesn't accept None)
if hasattr(namespace, "lora_target_modules") and namespace.lora_target_modules is None:
delattr(namespace, "lora_target_modules")
# Remove rope_scaling if not set (vLLM doesn't accept None)
if hasattr(namespace, "rope_scaling"):
if namespace.rope_scaling is None:
delattr(namespace, "rope_scaling")
return namespace
@@ -0,0 +1,960 @@
import math
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import AliasChoices, Field, model_validator
from prime_rl.configs.shared import (
BaseModelConfig,
ClientConfig,
FileSystemTransportConfig,
HeartbeatConfig,
LogConfig,
PrimeMonitorConfig,
RendererConfig,
TransportConfig,
WandbWithExtrasConfig,
)
from prime_rl.configs.trainer import TokenizerConfig
from prime_rl.utils.config import BaseConfig
class OptimizerConfig(BaseConfig):
lr: float = Field(1e-4, ge=0)
"""Learning rate for this run (per-run override for multi-run training)."""
class LoRAConfig(BaseConfig):
name: str | None = None
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
rank: int | None = Field(None, ge=1)
"""LoRA rank for this run. Must be ≤ trainer's max rank. If None, uses the trainer's rank."""
alpha: float | None = Field(None, ge=0)
"""LoRA alpha for this run. If None, uses the trainer's alpha."""
class ModelConfig(BaseModelConfig):
lora: LoRAConfig | None = None
"""Per-run LoRA configuration. If None, LoRA is disabled."""
class TrainSamplingConfig(BaseConfig):
temperature: float = Field(1.0, ge=0)
"""Sampling temperature."""
repetition_penalty: float = Field(1.0, ge=0)
"""Repetition penalty. Values > 1.0 discourage repetition, < 1.0 encourage it, 1.0 disables."""
max_completion_tokens: int | None = Field(
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
)
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
min_tokens: int = Field(0, ge=0)
"""Minimum output tokens per sequence."""
seed: int | None = None
"""Random seed for sampling. If None, no seeding is used."""
# Strictly speaking, extra_body is not a sampling parameter, but it is the
# easiest way to pass arbitrary extra parameters to the server via verifiers
extra_body: dict[str, Any] = {}
"""Extra body forwarded with each request to the inference server."""
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict, omitting None values."""
# Top-level OAI params
args: dict[str, Any] = {
"temperature": self.temperature,
"top_p": 1.0,
"logprobs": True,
}
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
if self.seed is not None:
args["seed"] = self.seed
# vLLM extra_body params
extra_body = dict(self.extra_body)
if self.min_tokens > 0:
extra_body["min_tokens"] = self.min_tokens
if self.repetition_penalty != 1.0:
extra_body["repetition_penalty"] = self.repetition_penalty
if extra_body:
args["extra_body"] = extra_body
return args
@model_validator(mode="before")
@classmethod
def _deprecate_max_tokens(cls, data: Any) -> Any:
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
warnings.warn(
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
return data
class EvalSamplingConfig(BaseConfig):
temperature: float | None = Field(None, ge=0)
"""Sampling temperature. None defers to the inference server default."""
repetition_penalty: float | None = Field(None, ge=0)
"""Repetition penalty. None defers to the inference server default."""
top_p: float | None = None
"""Nucleus sampling threshold. None defers to the inference server default."""
top_k: int | None = None
"""Top-k sampling. None defers to the inference server default."""
min_p: float | None = Field(None, ge=0)
"""Min-p sampling threshold. None defers to the inference server default."""
max_completion_tokens: int | None = Field(
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
)
"""Maximum output tokens per turn. None defers to the inference server default."""
min_tokens: int | None = Field(None, ge=0)
"""Minimum output tokens per sequence. None defers to the inference server default."""
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
"""Reasoning effort constraint for reasoning models."""
seed: int | None = None
"""Random seed for sampling. None means no seeding."""
extra_body: dict[str, Any] = {}
"""Extra body parameters forwarded to the inference server."""
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict. Only includes non-None fields."""
args: dict[str, Any] = {}
if self.temperature is not None:
args["temperature"] = self.temperature
if self.top_p is not None:
args["top_p"] = self.top_p
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
if self.reasoning_effort is not None:
args["reasoning_effort"] = self.reasoning_effort
if self.seed is not None:
args["seed"] = self.seed
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if self.min_p is not None:
extra_body["min_p"] = self.min_p
if self.min_tokens is not None:
extra_body["min_tokens"] = self.min_tokens
if self.repetition_penalty is not None:
extra_body["repetition_penalty"] = self.repetition_penalty
if extra_body:
args["extra_body"] = extra_body
return args
@model_validator(mode="before")
@classmethod
def _deprecate_max_tokens(cls, data: Any) -> Any:
if isinstance(data, dict) and "max_tokens" in data and "max_completion_tokens" not in data:
warnings.warn(
"'max_tokens' is deprecated, use 'max_completion_tokens' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
return data
class EnvConfig(BaseConfig):
id: str = "reverse-text"
"""Registered verifiers environment ID (e.g. ``math-env``, ``primeintellect/math-env``). May include an ``@version`` suffix for installation."""
name: str | None = None
"""Display name for this environment in logs, metrics, and buffer keys. Defaults to the ``id`` without ``@version``. Must be unique across all envs in the same group."""
args: dict = {}
"""Keyword arguments forwarded to ``vf.load_environment``. See the environment's docstring for accepted args."""
extra_env_kwargs: dict[str, Any] = {}
"""Extra kwargs passed to the env (e.g. ``seq_len``, ``max_total_completion_tokens``). Auto-populated by the orchestrator; user overrides are generally discouraged. The main use case is matching ``extra_env_kwargs`` when running an env in an isolated environment server."""
address: str | None = None
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to this server instead of spawning one; when None, a subprocess env server is spawned automatically."""
num_workers: int | Literal["auto"] = "auto"
"""Worker processes for the spawned env server. ``auto`` scales to 1 worker per 256 concurrent rollouts. Ignored when ``address`` is set."""
ratio: float | None = Field(None, gt=0)
"""Sampling weight for this environment in the buffer. When None for all envs, samples uniformly across all available problems. When set, must be set on all envs — values are relative weights normalized to probabilities (e.g. [1, 1] and [0.5, 0.5] are equivalent)."""
max_retries: int = Field(3, ge=0)
"""Times the env server retries a failed rollout before returning an error."""
max_total_completion_tokens: int = -1
"""Maximum total completion tokens across all turns in a multi-turn rollout. ``-1`` disables. Auto-populated into ``extra_env_kwargs``."""
timeout: float | None = Field(None, validation_alias=AliasChoices("timeout", "timeout_seconds"))
"""Per-rollout wall-clock timeout in seconds. None disables."""
state_columns: list[str] = []
"""Extra ``State`` fields to persist into the saved rollout records (in addition to the always-saved ``trajectory`` and ``sampling_args``). Values must be JSON-serializable."""
@property
def stripped_id(self) -> str:
"""Environment ID without the @version suffix."""
return self.id.split("@")[0]
@property
def resolved_name(self) -> str:
return self.name or self.stripped_id
@model_validator(mode="after")
def validate_env_name(self):
if self.resolved_name == "all":
raise ValueError(
'Environment name "all" is reserved for global metric aggregation. Use a different name or id.'
)
return self
@model_validator(mode="after")
def resolve_max_total_completion_tokens(self):
self.extra_env_kwargs["max_total_completion_tokens"] = self.max_total_completion_tokens
return self
@model_validator(mode="after")
def resolve_timeout(self):
if self.timeout is not None:
self.extra_env_kwargs["timeout_seconds"] = self.timeout
return self
class TrainEnvConfig(EnvConfig):
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level train sampling config."""
class EvalEnvConfig(EnvConfig):
sampling: EvalSamplingConfig = EvalSamplingConfig()
"""Per-env sampling overrides. Unset fields inherit from the group-level eval sampling config."""
num_examples: int = -1
"""Eval examples to sample from the dataset. ``-1`` uses all available examples."""
rollouts_per_example: int = Field(1, ge=1)
"""Rollouts generated per example. Used for pass@k estimation (e.g. ``rollouts_per_example=8`` enables pass@1 through pass@8)."""
interval: int = Field(100, ge=1)
"""Per-env eval interval. If unset, inherits from the group-level eval interval."""
class TrainConfig(BaseConfig):
env: list[TrainEnvConfig] = [TrainEnvConfig()]
"""Training environments."""
sampling: TrainSamplingConfig = TrainSamplingConfig()
"""Shared training sampling configuration."""
num_workers: int | Literal["auto"] = "auto"
"""Default worker processes for env servers. Can be overridden per env."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_workers, and max_retries."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
env.sampling = TrainSamplingConfig(**group_sampling)
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = TrainSamplingConfig(**merged)
if "num_workers" not in env.model_fields_set:
env.num_workers = self.num_workers
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
f"Duplicate training environment names: {set(duplicates)}. Each env must have a unique name."
)
return self
@model_validator(mode="after")
def validate_env_ratios(self):
ratios = [env.ratio for env in self.env]
if all(r is None for r in ratios):
return self
if any(r is None for r in ratios):
raise ValueError("Either all envs must have a ratio or none of them. Got a mix of set and unset ratios.")
return self
class EvalConfig(BaseConfig):
env: list[EvalEnvConfig] = [EvalEnvConfig()]
"""Evaluation environments."""
sampling: EvalSamplingConfig = Field(default_factory=EvalSamplingConfig)
"""Shared eval sampling configuration; can differ from training sampling."""
num_examples: int = -1
"""Default eval examples per environment. ``-1`` uses all. Can be overridden per env."""
rollouts_per_example: int = Field(1, ge=1)
"""Default rollouts per example. Can be overridden per env."""
num_workers: int | Literal["auto"] = "auto"
"""Default worker processes for env servers. Can be overridden per env."""
max_retries: int = Field(3, ge=0)
"""Default retries for failed rollouts. Can be overridden per env."""
interval: int = Field(100, ge=1)
"""Step interval at which to evaluate the model."""
@model_validator(mode="after")
def resolve_env_defaults(self):
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, rollouts_per_example, and interval. Then resolve auto num_workers."""
group_sampling = self.sampling.model_dump()
for env in self.env:
if "sampling" not in env.model_fields_set:
env.sampling = EvalSamplingConfig(**group_sampling)
else:
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
env.sampling = EvalSamplingConfig(**merged)
if "num_examples" not in env.model_fields_set:
env.num_examples = self.num_examples
if "rollouts_per_example" not in env.model_fields_set:
env.rollouts_per_example = self.rollouts_per_example
if "interval" not in env.model_fields_set:
env.interval = self.interval
if "num_workers" not in env.model_fields_set:
env.num_workers = self.num_workers
if "max_retries" not in env.model_fields_set:
env.max_retries = self.max_retries
# Resolve auto num_workers now that num_examples and rollouts_per_example are set
if env.num_workers == "auto":
if env.num_examples == -1:
env.num_workers = 4
else:
max_concurrent = env.num_examples * env.rollouts_per_example
env.num_workers = max(1, math.ceil(max_concurrent / 256))
return self
@model_validator(mode="after")
def validate_unique_env_names(self):
env_names = [env.resolved_name for env in self.env]
duplicates = [n for n in env_names if env_names.count(n) > 1]
if duplicates:
raise ValueError(
f"Duplicate evaluation environment names: {set(duplicates)}. Each env must have a unique name."
)
return self
eval_base_model: bool = True
"""Evaluate the base model we are training on."""
skip_eval_on_resume: bool = Field(
True, validation_alias=AliasChoices("skip_eval_on_resume", "skip_eval_on_restart")
)
"""When resuming the orchestrator from a checkpoint, skip the (potentially redundant) online eval that would otherwise run immediately at the resumed step."""
cancel_inflight_rollouts_on_eval: bool = False
"""Cancel in-flight training rollouts before starting online evals. Avoids congestion (no training + eval rollouts at the same time) at the cost of slower training steps as the pipeline has to refill after each eval."""
class CheckpointConfig(BaseConfig):
interval: int | None = Field(None, ge=1)
"""Step interval at which to save the orchestrator checkpoint."""
resume_step: int | None = Field(None, ge=-1)
"""Step to resume the orchestrator from. None starts from scratch; ``-1`` resumes from the latest checkpoint available."""
wait_for_weights_timeout: int | None = Field(None, ge=1)
"""When resuming, wait up to this many seconds for the weight directory to appear. Useful when the orchestrator restarts while the trainer is still saving weights. If None, fail immediately when weights are not found."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
skip_progress: bool = False
"""Skip loading the progress from checkpoint."""
skip_buffer: bool = False
"""Skip loading the buffer from checkpoint."""
class BufferConfig(BaseConfig):
seed: int | None = None
"""Random seed for the buffer. When set, sampling from the buffer is deterministic."""
easy_threshold: float | None = None
"""Average-reward threshold above which a problem is classified ``easy``."""
hard_threshold: float | None = None
"""Average-reward threshold below which a problem is classified ``hard``."""
easy_fraction: float = Field(0.0, ge=0, le=1)
"""Fraction of easy problems to convert to ``normal`` when resuming or starting training. Only problems with difficulty ``normal`` are sampled."""
hard_fraction: float = Field(0.0, ge=0, le=1)
"""Fraction of hard problems to convert to ``normal`` when resuming or starting training. Only problems with difficulty ``normal`` are sampled."""
online_difficulty_filtering: bool = False
"""Filter rollouts based on difficulty. When True, rollouts with average reward 0.0 or 1.0 are not added to the buffer."""
hash_keys: list[str] = Field(["env_name", "prompt"], min_length=1)
"""Keys used to compute example hashes. Used to match examples from buffer checkpoints and determine buffer resume behavior."""
@model_validator(mode="after")
def validate_thresholds(self):
if self.easy_threshold is not None and self.hard_threshold is not None:
assert self.easy_threshold > self.hard_threshold, "easy_threshold must be greater than hard_threshold."
return self
class TokensLengthPenaltyConfig(BaseConfig):
type: Literal["tokens"] = "tokens"
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on model completion tokens. Finite and non-negative."""
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
class TurnsLengthPenaltyConfig(BaseConfig):
type: Literal["turns"] = "turns"
LengthPenaltyConfig: TypeAlias = Annotated[
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
Field(discriminator="type"),
]
class DefaultAdvantageConfig(BaseConfig):
type: Literal["default"] = "default"
length_penalty: LengthPenaltyConfig | None = None
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
class CustomAdvantageConfig(BaseConfig):
type: Literal["custom"] = "custom"
import_path: str
"""Import path to the advantage function (e.g. ``my_module.my_advantage``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the advantage function."""
AdvantageConfig: TypeAlias = Annotated[
DefaultAdvantageConfig | CustomAdvantageConfig,
Field(discriminator="type"),
]
# Flags rare tokens generated at high entropy (Section 5.2, https://arxiv.org/abs/2510.02387).
class GibberishFilterConfig(BaseConfig):
type: Literal["gibberish"] = "gibberish"
enforce: bool = False
"""When True, skip detected rollouts entirely so they are not sent to the trainer. When False, only track detection metrics."""
token_id_threshold: int = 100_000
"""Token IDs above this are candidates for gibberish. BPE tokens are sorted by merge order."""
logprob_offset: float = 2.0
"""Offset from uniform-distribution logprob. Threshold = ``-log(vocab_size) - logprob_offset``."""
# Flags rollouts stuck in a repetition loop: emits high-confidence tokens for an extended stretch.
# Flagged when `window` consecutive tokens are each sampled with probability above `prob_threshold`.
# (Section 3.2, https://arxiv.org/abs/2506.13585)
class RepetitionFilterConfig(BaseConfig):
type: Literal["repetition"] = "repetition"
enforce: bool = False
"""When True, skip detected rollouts entirely so they are not sent to the trainer. When False, only track detection metrics."""
window: int = Field(3_000, ge=1)
"""Consecutive high-probability steps required to flag the rollout."""
prob_threshold: float = Field(0.99, gt=0, le=1)
"""Tokens sampled with probability above this are considered repetitive. Consecutive such tokens count toward the window."""
# Flags rollouts with zero advantage.
class ZeroAdvantageFilterConfig(BaseConfig):
type: Literal["zero_advantage"] = "zero_advantage"
enforce: bool = True
"""When True, skip detected rollouts entirely so they are not sent to the trainer. When False, only track detection metrics."""
FilterConfig: TypeAlias = Annotated[
GibberishFilterConfig | RepetitionFilterConfig | ZeroAdvantageFilterConfig,
Field(discriminator="type"),
]
class FileSystemWeightBroadcastConfig(BaseConfig):
type: Literal["filesystem"] = "filesystem"
class NCCLWeightBroadcastConfig(BaseConfig):
type: Literal["nccl"] = "nccl"
host: str = "localhost"
"""Host for the NCCL broadcast rendezvous."""
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
timeout: int = 1200
"""Timeout in seconds for the NCCL broadcast."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates."""
inference_world_size: int = Field(1, ge=1)
"""Total inference GPUs across all servers. Used by ``init_nccl_broadcast`` to compute per-server rank offsets."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
]
class OrchestratorExperimentalConfig(BaseConfig):
pass
class RolloutModelConfig(BaseConfig):
model: ModelConfig = ModelConfig()
client: ClientConfig = ClientConfig()
class OrchestratorConfig(BaseConfig):
training_mode: Literal["rl", "opd", "sft"] = "rl"
"""Training mode. ``rl``: student generates rollouts, no teacher. ``opd``: student generates rollouts, teacher computes logprobs (teacher_tau > 0). ``sft``: teacher generates rollouts, student inference pool used for evals and weight sync."""
student: RolloutModelConfig = Field(RolloutModelConfig(), validation_alias=AliasChoices("student", "model"))
"""Student rollout participant (model + client) — the model being trained."""
teacher: RolloutModelConfig | None = Field(None, validation_alias=AliasChoices("teacher", "teacher_model"))
"""Teacher rollout participant (model + client). Role depends on ``training_mode``: ``opd`` — teacher computes logprobs; ``sft`` — teacher generates rollouts."""
train: TrainConfig = TrainConfig()
tokenizer: TokenizerConfig = TokenizerConfig()
renderer: RendererConfig = RendererConfig()
"""Client-side renderer configuration. Only consumed when ``use_renderer=true``."""
optim: OptimizerConfig = OptimizerConfig()
"""Per-run optimizer configuration for multi-run training."""
eval: EvalConfig | None = None
"""Evaluation configuration."""
buffer: BufferConfig = BufferConfig()
advantage: AdvantageConfig | None = DefaultAdvantageConfig()
filters: list[FilterConfig] = [GibberishFilterConfig(), RepetitionFilterConfig(), ZeroAdvantageFilterConfig()]
"""Rollout filters. Each filter can ``monitor`` (default) or ``enforce`` (skip rollouts)."""
log: LogConfig = LogConfig()
wandb: WandbWithExtrasConfig | None = None
prime_monitor: PrimeMonitorConfig | None = None
collect_inference_metrics: bool = True
"""Collect inference-server metrics (requires wandb)."""
ckpt: CheckpointConfig | None = None
"""Checkpoint configuration."""
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to receive updated weights from the trainer."""
rollout_transport: TransportConfig = FileSystemTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
output_dir: Path = Path("outputs/run_default")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
tasks_per_minute: int | None = Field(None, ge=1)
"""Rate limit per environment worker, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. With multiple workers, the effective total rate is ``workers × this value``. None disables rate limiting."""
batch_size: int | None = Field(None, ge=1)
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
token_batch_size: int | None = Field(None, ge=1)
"""Tokens to train on per step (token-based batching). Set this OR ``batch_size``."""
oversampling_factor: float | None = Field(None, gt=0)
"""Rollout-mode batching only. Multiplier used to derive ``max_inflight_rollouts`` from ``batch_size`` when ``max_inflight_rollouts`` is unset. Values below 1.0 intentionally cap in-flight rollout capacity below ``batch_size``."""
max_inflight_rollouts: int | None = Field(None, ge=1)
"""Maximum number of rollouts kept in-flight. Required for token-based batching. With ``batch_size`` set, defaults to ``batch_size * oversampling_factor`` (or ``batch_size`` when ``oversampling_factor`` is unset)."""
rollouts_per_example: int = Field(1, ge=1)
"""Output sequences returned per example during training."""
seq_len: int = 2048
"""Training sequence length. Shorter samples are padded; longer samples are truncated."""
# TODO(Mika): This should be automatic from the number of ZMQ connections
num_train_workers: int = Field(1, ge=1)
"""Training workers to use."""
max_steps: int | None = None
"""Maximum training steps. If None, runs indefinitely."""
max_off_policy_steps: int = Field(8, ge=0)
"""Maximum policies allowed to generate a single rollout. Rollouts generated more than ``max_off_policy_steps`` ahead of training are discarded. Higher values yield better throughput at the cost of off-policy noise."""
max_async_level: int = Field(1, ge=0)
"""Maximum steps inference can be ahead of training. ``0`` degenerates to synchronous on-policy RL; ``≥1`` overlaps training and inference."""
strict_async_level: bool = False
"""Strictly enforce ``max_async_level``. When True, the rollout policy is always exactly ``max_async_level`` steps ahead of training. When False, any policy within ``max_async_level`` steps is allowed (always uses the latest available policy)."""
bench: bool = False
"""Benchmark mode. Sets ``max_steps`` to 5, ``max_async_level`` to ~∞, and disables W&B."""
seed: int | None = 42
"""Random seed for the orchestrator."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
use_renderer: bool = True
"""Use the renderer-backed TITO client (client-side tokenization via the ``renderers`` package, served by ``/v1/generate``). When True, the ``[orchestrator.renderer]`` block (name / tool_parser / reasoning_parser / pool_size) applies. Default for both text-only and VLM rollouts; VLMs require it. False falls back to MITO (``openai_chat_completions``)."""
env_install_prerelease: bool = False
"""Allow pre-release versions when installing environments (e.g. ``verifiers>=0.1.12.dev5``). Passes ``--prerelease`` to ``prime env install``."""
experimental: OrchestratorExperimentalConfig = OrchestratorExperimentalConfig()
@model_validator(mode="before")
@classmethod
def fold_student_shortcuts(cls, data: Any) -> Any:
"""Accept top-level ``[orchestrator.model]`` / ``[orchestrator.client]``
as shorthand for the student sub-config. Useful for ergonomic rl configs
where ``[orchestrator.student.*]`` is overkill, and required for
pre-refactor configs that used the flat layout to keep parsing:
- [orchestrator.client.*] -> [orchestrator.student.client.*]
- [orchestrator.model.<k>] -> [orchestrator.student.model.<k>]
(where <k> is any ModelConfig field)
Teacher must always be configured under [orchestrator.teacher.*]
(no equivalent shortcut), because rl mode forbids a teacher and we
don't want the same shortcut to silently route to two different roles.
"""
if not isinstance(data, dict):
return data
def deep_merge(dst: dict, src: dict) -> None:
"""In-place recursive merge of ``src`` into ``dst``. ``src`` wins at the leaf."""
for k, v in src.items():
if isinstance(v, dict) and isinstance(dst.get(k), dict):
deep_merge(dst[k], v)
else:
dst[k] = v
# 1. Re-nest top-level [orchestrator.client] under student.client.
legacy_client = data.pop("client", None)
if isinstance(legacy_client, dict):
student = data.setdefault("student", {})
if isinstance(student, dict):
deep_merge(student.setdefault("client", {}), legacy_client)
else:
# Mismatched types - put it back and let pydantic surface the error.
data["client"] = legacy_client
# 2. Consolidate the legacy `model` alias into `student` so the
# flat-layout fix-up below sees a single target. Deep-merge with the
# legacy keys winning so a CLI `--model.<k>` overrides TOML `student.model.<k>`.
legacy_model = data.pop("model", None)
if legacy_model is not None:
existing = data.get("student")
if existing is None:
data["student"] = legacy_model
elif isinstance(existing, dict) and isinstance(legacy_model, dict):
deep_merge(existing, legacy_model)
else:
# Mismatched types - put it back and let pydantic surface the error.
data["model"] = legacy_model
# 3. Re-nest flat ModelConfig keys under student.model.
model_only_keys = set(ModelConfig.model_fields)
student = data.get("student")
if isinstance(student, dict):
flat = {k: student.pop(k) for k in list(student) if k in model_only_keys}
if flat:
student.setdefault("model", {}).update(flat)
return data
@model_validator(mode="before")
@classmethod
def _env_to_train(cls, data: Any) -> Any:
"""Allow [[env]] and [sampling] as shorthand for [train] with [[train.env]] and [train.sampling]."""
if not isinstance(data, dict):
return data
if "env" in data or "sampling" in data:
train = data.setdefault("train", {})
if isinstance(train, dict):
if "env" in data:
warnings.warn(
"'[[orchestrator.env]]' is deprecated, use '[[orchestrator.train.env]]' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("env", data.pop("env"))
if "sampling" in data:
warnings.warn(
"'[orchestrator.sampling]' is deprecated, use '[orchestrator.train.sampling]' instead. "
"Auto-translating for now, but this will be removed in a future release.",
FutureWarning,
stacklevel=2,
)
train.setdefault("sampling", data.pop("sampling"))
return data
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.student.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.student.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
return self
@model_validator(mode="after")
def auto_setup_prime_monitor_run_name(self):
"""Default ``prime_monitor.run_name`` to the W&B run name when monitoring
is enabled and the user hasn't named the prime-monitor run explicitly."""
if self.prime_monitor is None or self.prime_monitor.run_name is not None:
return self
if self.wandb is not None and self.wandb.name:
self.prime_monitor.run_name = self.wandb.name
return self
@model_validator(mode="after")
def validate_unique_filter_types(self):
types = [f.type for f in self.filters]
if len(types) != len(set(types)):
raise ValueError(f"Duplicate filter types: {types}. Each filter type may only appear once.")
return self
@model_validator(mode="after")
def _force_no_renderer_for_sft(self):
"""SFT rolls out via the teacher's plain chat-completions endpoint; the
renderer client doesn't apply. Force use_renderer=False so the user
doesn't have to remember to set it. Declared before the renderer
validators below so they see the corrected value."""
if self.training_mode == "sft":
self.use_renderer = False
return self
@model_validator(mode="after")
def validate_training_mode(self):
"""Enforce training mode invariants that involve only orchestrator fields."""
has_teacher = self.teacher is not None
if self.training_mode == "rl" and has_teacher:
raise ValueError("orchestrator.teacher must not be set when training_mode = 'rl'.")
if self.training_mode in ("opd", "sft") and not has_teacher:
raise ValueError(f"orchestrator.teacher must be configured when training_mode = '{self.training_mode}'.")
return self
@model_validator(mode="after")
def validate_renderer_args(self):
"""``[orchestrator.renderer]`` knobs are only meaningful when
``use_renderer=True``. Reject otherwise so callers don't silently
pass them and wonder why they're ignored."""
if self.use_renderer:
return self
renderer_args_set = []
if self.renderer.name != "auto":
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
if self.renderer.tool_parser is not None:
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
if self.renderer.reasoning_parser is not None:
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
if self.renderer.pool_size is not None:
renderer_args_set.append(f"renderer.pool_size={self.renderer.pool_size!r}")
if self.renderer.preserve_all_thinking:
renderer_args_set.append(f"renderer.preserve_all_thinking={self.renderer.preserve_all_thinking!r}")
if self.renderer.preserve_thinking_between_tool_calls:
renderer_args_set.append(
f"renderer.preserve_thinking_between_tool_calls={self.renderer.preserve_thinking_between_tool_calls!r}"
)
if renderer_args_set:
raise ValueError(
"Renderer-specific args set without orchestrator.use_renderer=True: "
f"{', '.join(renderer_args_set)}. Either enable the renderer client or remove these knobs."
)
return self
@model_validator(mode="after")
def vlm_requires_renderer(self):
"""VLMs (``[model.vlm]`` block set) must go through the renderer.
The renderer owns the processor per-slot, produces byte-identical
tokens, and ships generic ``mm_kwargs`` keyed by whatever the
model's forward signature expects.
"""
if self.student.model.vlm is not None and not self.use_renderer:
raise ValueError(
"orchestrator.use_renderer must be true when model.vlm is set. "
"VLMs must go through a renderer (e.g. Qwen3VLRenderer) that owns the processor."
)
return self
@model_validator(mode="after")
def validate_renderer_auto_resolves(self):
"""Reject the silent DefaultRenderer fallback at config time.
When ``use_renderer=True`` with ``renderer.name='auto'`` and the
model isn't in ``MODEL_RENDERER_MAP``, ``create_renderer`` would
fall back to ``DefaultRenderer``. That fallback doesn't fix the
position-dependent chat-template bug the renderer client exists to
solve, and rejects envs that pass tools (the rollout dies with
"RendererPool does not support tools") unless
``renderer.tool_parser`` is configured. Surface at config time so
``--dry-run`` reports the error.
"""
if not self.use_renderer or self.renderer.name != "auto":
return self
from renderers.base import MODEL_RENDERER_MAP
model_id = self.tokenizer.name or self.student.model.name
if model_id in MODEL_RENDERER_MAP:
return self
raise ValueError(
f"orchestrator.use_renderer=True with renderer.name='auto' but "
f"{model_id!r} is not in renderers.base.MODEL_RENDERER_MAP, so it "
f"would silently fall back to DefaultRenderer. Pick one: "
f"(a) [orchestrator.renderer] name='default' — for fine-tunes / "
f"vendored mirrors with custom chat templates (DefaultRenderer "
f"calls apply_chat_template); pair with tool_parser=<name> if "
f"the env uses tools. "
f"(b) [orchestrator.renderer] name=<model-specific renderer> — "
f"if {model_id!r} is template-identical to a mapped family "
f"(and ideally also add it upstream to "
f"renderers.base.MODEL_RENDERER_MAP). "
f"(c) orchestrator.use_renderer=false — opt out of the renderer "
f"client entirely."
)
@model_validator(mode="after")
def nccl_max_async_level(self):
if self.weight_broadcast.type == "nccl":
if not self.max_async_level == 1:
raise ValueError("max_async_level must be 1 for NCCL broadcast")
return self
@model_validator(mode="after")
def resolve_batching(self):
has_rollout_batch = self.batch_size is not None
has_token_batch = self.token_batch_size is not None
if has_rollout_batch and has_token_batch:
raise ValueError("Set exactly one of batch_size or token_batch_size")
if not has_rollout_batch and not has_token_batch:
self.batch_size = 128
if has_token_batch:
if self.oversampling_factor is not None:
raise ValueError("oversampling_factor can only be set when batch_size is set")
if self.max_inflight_rollouts is None:
raise ValueError("max_inflight_rollouts must be set when token_batch_size is set")
else:
assert self.batch_size is not None
if self.batch_size % self.rollouts_per_example != 0:
raise ValueError("Batch size must be divisible by the number of samples per problem")
oversampling_factor = self.oversampling_factor if self.oversampling_factor is not None else 1.0
resolved_max_inflight_rollouts = max(
self.rollouts_per_example,
int(self.batch_size * oversampling_factor),
)
if self.max_inflight_rollouts is not None and self.oversampling_factor is not None:
expected_max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_rollouts != expected_max_inflight_rollouts:
raise ValueError("max_inflight_rollouts conflicts with oversampling_factor * batch_size")
if self.max_inflight_rollouts is None:
self.max_inflight_rollouts = resolved_max_inflight_rollouts
if self.max_inflight_rollouts is not None and self.max_inflight_rollouts < self.rollouts_per_example:
raise ValueError("max_inflight_rollouts must be at least the number of rollouts per example")
# Resolve train env num_workers from max_inflight_rollouts
for env_cfg in self.train.env:
if env_cfg.num_workers == "auto":
assert self.max_inflight_rollouts is not None
env_cfg.num_workers = max(1, math.ceil(self.max_inflight_rollouts / 256))
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
self.max_steps = 4 # Run for 1 warmup step + 3 evaluation steps
self.max_async_level = int(1e9) # Never wait for RL weight checkpoints
# Disable evaluation
self.eval = None
if self.wandb:
self.wandb.log_extras = None
if self.prime_monitor:
self.prime_monitor.log_extras = None
return self
@model_validator(mode="after")
def resolve_env_config(self):
"""Populate extra_env_kwargs and vLLM sampling defaults from top-level fields."""
is_vllm = self.training_mode != "sft"
for env in self.train.env:
env.extra_env_kwargs.update(max_seq_len=self.seq_len)
if is_vllm:
env.sampling.extra_body.setdefault("top_k", -1)
env.sampling.extra_body.setdefault("min_p", 0.0)
env.sampling.extra_body.setdefault("return_token_ids", True)
return self
@@ -0,0 +1,698 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.inference import WeightBroadcastConfig as InferenceWeightBroadcastConfig
from prime_rl.configs.orchestrator import (
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
NCCLWeightBroadcastConfig as OrchestratorNCCLWeightBroadcastConfig,
)
from prime_rl.configs.orchestrator import (
OrchestratorConfig,
)
from prime_rl.configs.shared import (
SlurmConfig,
VLMConfig,
)
from prime_rl.configs.trainer import (
BenchConfig,
FakeDataLoaderConfig,
TokenizerConfig,
TrainerConfig,
)
from prime_rl.configs.trainer import (
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
)
from prime_rl.configs.trainer import (
NCCLWeightBroadcastConfig as TrainerNCCLWeightBroadcastConfig,
)
from prime_rl.utils.config import BaseConfig, find_package_resource
from prime_rl.utils.validation import (
propagate_shared_fields,
validate_shared_ckpt_config,
validate_shared_max_async_level,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_output_dir,
validate_shared_seq_len,
validate_shared_tokenizer,
validate_shared_wandb_config,
validate_shared_weight_broadcast,
)
class RLExperimentalConfig(BaseConfig):
pass
class SharedLogConfig(BaseConfig):
level: str | None = None
"""Log level for trainer and orchestrator. When unset, each sub-config's own log level applies (defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``)."""
json_logging: bool = False
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
class SharedWandbConfig(BaseConfig):
project: str | None = "prime-rl"
"""W&B project."""
entity: str | None = None
"""W&B entity."""
name: str | None = None
"""W&B run name."""
group: str | None = None
"""W&B group."""
tags: list[str] | None = None
"""W&B tags attached to the run."""
offline: bool | None = False
"""Run W&B in offline mode."""
shared: bool = True
"""Log trainer and orchestrator metrics to a single shared W&B run. Requires wandb SDK ≥ 0.19.9. Incompatible with offline mode."""
@model_validator(mode="after")
def validate_shared_not_offline(self):
if self.shared and self.offline:
raise ValueError("W&B shared mode requires server connectivity and is incompatible with offline mode")
return self
class SharedCheckpointConfig(BaseConfig):
output_dir: Path | None = None
"""Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir``."""
interval: int | None = None
"""Interval at which to save checkpoints."""
resume_step: int | None = None
"""Step to resume from. If None, does not resume from a checkpoint."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
class SharedModelConfig(BaseConfig):
name: str = "Qwen/Qwen3-0.6B"
"""HF model name or local path."""
vlm: "VLMConfig | None" = None
"""VLM configuration. Set this to enable vision-language model support."""
class SharedWeightBroadcastConfig(BaseConfig):
type: Literal["nccl", "filesystem"] = "filesystem"
"""Weight broadcast transport."""
port: int = 29501
"""Port for NCCL weight broadcast."""
timeout: int = 1200
"""Timeout in seconds for NCCL weight broadcast."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
class BaseDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
type: Literal["single_node"] = "single_node"
num_train_gpus: int = 1
"""GPUs allocated to the trainer."""
num_infer_gpus: int = 1
"""GPUs allocated to inference."""
num_teacher_gpus: int | None = None
"""GPUs allocated to teacher inference (None disables the teacher server)."""
@model_validator(mode="after")
def validate_gpu_count(self):
total = self.num_train_gpus + self.num_infer_gpus + (self.num_teacher_gpus or 0)
if total > self.gpus_per_node:
raise ValueError(
f"Total GPU count ({total} = {self.num_train_gpus} train + {self.num_infer_gpus} infer"
f" + {self.num_teacher_gpus or 0} teacher) exceeds gpus_per_node ({self.gpus_per_node})."
)
return self
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
type: Literal["multi_node"] = "multi_node"
num_train_nodes: int
"""Training nodes."""
num_infer_nodes: int = Field(ge=0)
"""Inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data)."""
num_infer_replicas: int = Field(1, ge=1)
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
num_teacher_nodes: int | None = None
"""Teacher inference nodes."""
nodes_per_fsdp_group: int | None = None
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
@property
def total_infer_nodes(self) -> int:
return self.num_infer_nodes * self.num_infer_replicas
@model_validator(mode="after")
def teacher_inference_not_supported(self):
if self.num_teacher_nodes is not None:
raise ValueError("Teacher inference is not yet supported in multi node deployment.")
return self
DeploymentConfig: TypeAlias = Annotated[
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
]
class RLConfig(BaseConfig):
trainer: TrainerConfig
orchestrator: OrchestratorConfig
inference: InferenceConfig | None = None
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."""
teacher_inference: InferenceConfig | None = None
"""Teacher inference server configuration. If None, falls back to the same config as ``inference`` (or a default). Only used when teacher GPUs/nodes are set."""
output_dir: Path = Path("outputs")
"""Output directory. Should be unique per experiment."""
clean_output_dir: bool = False
"""Delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming."""
### Shared configurations
log: SharedLogConfig = SharedLogConfig()
"""Shared log config. Propagated to trainer and orchestrator."""
ckpt: SharedCheckpointConfig | None = None
"""Shared checkpoint config. If None, falls back to the sub-config checkpoint settings."""
wandb: SharedWandbConfig | None = None
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
model: SharedModelConfig | None = None
"""Shared model config. If None, falls back to the sub-config model settings."""
tokenizer: TokenizerConfig | None = None
"""Shared tokenizer config. Propagated to trainer, orchestrator, and inference. If None, each component uses its own tokenizer config (defaulting to model name)."""
max_steps: int | None = None
"""Shared maximum training steps. If None, falls back to the sub-config ``max_steps``."""
seq_len: int | None = None
"""Shared sequence length. Propagates to ``trainer.model.seq_len`` and ``orchestrator.seq_len`` only when those values were not explicitly set; explicit per-component values always win."""
max_async_level: int | None = None
"""Shared async level. If None, falls back to the sub-config ``max_async_level``."""
weight_broadcast: SharedWeightBroadcastConfig | None = None
bench: bool = False
"""Benchmark mode. Sets trainer and orchestrator to benchmark mode and, when set, suffixes the W&B project with ``-bench``."""
deployment: DeploymentConfig = SingleNodeDeploymentConfig()
slurm: SlurmConfig | None = None
"""SLURM configuration. If None, runs locally."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: RLExperimentalConfig = RLExperimentalConfig()
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="before")
@classmethod
def _stub_orchestrator_teacher_for_auto_setup(cls, data):
"""When `deployment.num_teacher_gpus > 0` and the user didn't write an
`[orchestrator.teacher]` block, inject an empty one so
`OrchestratorConfig.validate_training_mode` (which fires during nested
validation) doesn't reject `training_mode = "opd"` for "missing teacher".
`auto_setup_teacher_inference` (after) then fills in client.base_url and
model.name from the auto-launched teacher_inference server."""
if not isinstance(data, dict):
return data
deployment = data.get("deployment")
if not isinstance(deployment, dict):
return data
if not deployment.get("num_teacher_gpus"):
return data
orch = data.setdefault("orchestrator", {})
if isinstance(orch, dict) and "teacher" not in orch and "teacher_model" not in orch:
orch["teacher"] = {}
return data
@model_validator(mode="after")
def validate_deployment(self):
if self.deployment.type == "multi_node":
if self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
if self.deployment.num_infer_nodes > 0 and not self.inference:
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
if self.deployment.num_infer_nodes == 0 and self.inference:
raise ValueError(
"Cannot configure inference with num_infer_nodes = 0. "
"Either set num_infer_nodes > 0 or remove the inference config."
)
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
raise ValueError(
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
"since no orchestrator or inference server will be running."
)
return self
# TODO: fix this
@model_validator(mode="after")
def validate_no_teacher_in_multinode(self):
if self.deployment.type == "multi_node" and self.teacher_inference is not None:
raise ValueError(
"Teacher inference is not supported in multi-node deployment. "
"The SLURM template only handles inference and training nodes."
)
return self
@model_validator(mode="after")
def validate_enough_devices_for_nccl(self):
if self.deployment.type == "single_node":
if self.trainer.weight_broadcast.type == "nccl":
if self.deployment.num_train_gpus + self.deployment.num_infer_gpus < 2:
raise ValueError(
"NCCL weight broadcast requires at least 2 GPUs to build the broadcast process group."
)
return self
@model_validator(mode="after")
def validate_quantize_in_weight_transfer(self):
if self.weight_broadcast is None or not self.weight_broadcast.quantize_in_weight_transfer:
return self
if self.weight_broadcast.type != "nccl":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires weight_broadcast.type = 'nccl'.")
if self.inference is None:
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires an inference config.")
if self.trainer.model.impl != "custom":
raise ValueError("weight_broadcast.quantize_in_weight_transfer requires trainer.model.impl = 'custom'.")
return self
### Auto-setup shared configs (before sub-config construction)
@model_validator(mode="before")
@classmethod
def auto_setup_shared_configs(cls, data: Any) -> Any:
"""Propagate shared top-level fields into sub-config dicts before sub-configs
are constructed. See ``validation.propagate_shared_fields`` for the full
propagation table, transforms, and the mutex rule.
"""
return propagate_shared_fields(data)
### Validate shared configs (after sub-config construction)
@model_validator(mode="after")
def validate_shared_configs(self):
"""Validate consistency of shared configs across trainer, orchestrator, and inference."""
validate_shared_output_dir(self.trainer, self.orchestrator)
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
validate_shared_max_steps(self.trainer, self.orchestrator)
validate_shared_max_async_level(self.trainer, self.orchestrator)
validate_shared_seq_len(self.trainer, self.orchestrator)
validate_shared_ckpt_config(self.trainer, self.orchestrator)
validate_shared_wandb_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_weight_broadcast(self):
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
if self.weight_broadcast is not None:
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
inference_world_size=inference_world_size,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def validate_eplb_requires_quantized_weight_transfer(self):
if self.inference is None or not self.inference.enable_eplb:
return self
# TODO(matej): check if weight reloading works itself before supporting EPLB without quantized transfer.
trainer_weight_broadcast = self.trainer.weight_broadcast
if trainer_weight_broadcast.type != "nccl" or not trainer_weight_broadcast.quantize_in_weight_transfer:
raise ValueError(
"inference.enable_eplb requires weight_broadcast.type = 'nccl' and "
"weight_broadcast.quantize_in_weight_transfer = true."
)
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench:
self.trainer.bench = BenchConfig()
self.orchestrator.bench = True
self.trainer.data.fake = FakeDataLoaderConfig(
batch_size=self.orchestrator.batch_size or 32,
)
trainer_bench_enabled = self.trainer.bench is not None
if trainer_bench_enabled != self.orchestrator.bench:
raise ValueError(
f"Trainer benchmark mode ({self.trainer.bench}) and orchestrator benchmark mode "
f"({self.orchestrator.bench}) must match. Use the top-level bench = true to set both."
)
return self
@model_validator(mode="after")
def auto_setup_lora(self):
if self.trainer.model.lora is not None:
if self.trainer.weight_broadcast.type == "nccl":
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
if self.orchestrator.student.model.lora is None:
from prime_rl.configs.orchestrator import LoRAConfig
self.orchestrator.student.model.lora = LoRAConfig()
if (
self.orchestrator.student.model.lora.rank is not None
and self.orchestrator.student.model.lora.rank != self.trainer.model.lora.rank
):
raise ValueError(
f"orchestrator.student.model.lora.rank ({self.orchestrator.student.model.lora.rank}) conflicts with "
f"trainer.model.lora.rank ({self.trainer.model.lora.rank}). "
f"Remove orchestrator.student.model.lora.rank to inherit from trainer, or update trainer.model.lora.rank to match."
)
if (
self.orchestrator.student.model.lora.alpha is not None
and self.orchestrator.student.model.lora.alpha != self.trainer.model.lora.alpha
):
raise ValueError(
f"orchestrator.student.model.lora.alpha ({self.orchestrator.student.model.lora.alpha}) conflicts with "
f"trainer.model.lora.alpha ({self.trainer.model.lora.alpha}). "
f"Remove orchestrator.student.model.lora.alpha to inherit from trainer, or update trainer.model.lora.alpha to match."
)
if self.orchestrator.student.model.lora.rank is None:
self.orchestrator.student.model.lora.rank = self.trainer.model.lora.rank
if self.orchestrator.student.model.lora.alpha is None:
self.orchestrator.student.model.lora.alpha = self.trainer.model.lora.alpha
if self.orchestrator.student.model.lora.name is None:
self.orchestrator.student.model.lora.name = (
f"r{self.orchestrator.student.model.lora.rank}-a{self.orchestrator.student.model.lora.alpha}"
)
if self.inference is not None:
self.inference.enable_lora = True
self.inference.max_lora_rank = self.trainer.model.lora.rank
else:
warnings.warn(
"LoRA is enabled, but inference is not configured. When manually starting the inference server, "
"make sure to set --enable_lora and --max-lora-rank.",
stacklevel=2,
)
return self
@model_validator(mode="after")
def auto_setup_router_replay(self):
if self.trainer.enable_router_replay:
if self.inference is not None:
if self.inference.enable_return_routed_experts is False:
warnings.warn(
"Router replay is enabled, but inference.enable_return_routed_experts is False. Setting to True.",
stacklevel=2,
)
self.inference.enable_return_routed_experts = True
else:
warnings.warn(
"Router replay is enabled, but inference is not configured. When manually starting the inference server, make sure to pass `--enable-return-routed-experts` to the vLLM server.",
stacklevel=2,
)
return self
@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
self.trainer.enable_router_replay
and self.inference is not None
and self.inference.kv_cache_offload is not None
):
raise ValueError(
"Router replay with inference.kv_cache_offload is not supported. "
"External KV cache hits do not carry routed-expert decisions."
)
return self
@model_validator(mode="after")
def auto_setup_deployment(self):
if self.deployment.type == "single_node": # single-node
# set num_train_workers to the number of data replicas
non_data_parallel_size = self.trainer.model.cp
if self.deployment.num_train_gpus > 1:
self.orchestrator.num_train_workers = self.deployment.num_train_gpus // non_data_parallel_size
# fill up inference capacity with dp ranks
if self.inference is not None:
num_infer_gpus = self.deployment.num_infer_gpus
if num_infer_gpus != self.inference.parallel.dp * self.inference.parallel.tp:
assert num_infer_gpus % self.inference.parallel.tp == 0, (
"Number of inference GPUs must be divisible by the tensor parallel size"
)
self.inference.parallel.dp = num_infer_gpus // self.inference.parallel.tp
# Ensure api_server_count matches DP so all workers are created.
# Without this, the NCCL broadcast group expects dp*tp workers
# but only api_server_count*tp exist, causing a deadlock.
dp = self.inference.parallel.dp
if self.inference.api_server_count < dp and not self.inference.enable_lora:
self.inference.api_server_count = dp
elif self.deployment.type == "multi_node": # multi-node
self.orchestrator.num_train_workers = self.deployment.num_train_nodes * self.deployment.gpus_per_node
if self.deployment.nodes_per_fsdp_group is not None:
if self.deployment.num_train_nodes % self.deployment.nodes_per_fsdp_group != 0:
raise ValueError(
f"deployment.num_train_nodes ({self.deployment.num_train_nodes}) must be divisible by "
f"deployment.nodes_per_fsdp_group ({self.deployment.nodes_per_fsdp_group})"
)
self.trainer.model.dp_replicate = (
self.deployment.num_train_nodes // self.deployment.nodes_per_fsdp_group
)
if (
self.inference is not None
and self.inference.enable_expert_parallel
and self.inference.deployment.type != "disaggregated"
):
inference_tp = self.inference.parallel.tp
if self.deployment.gpus_per_node % inference_tp != 0:
raise ValueError(
"deployment.gpus_per_node must be divisible by inference.parallel.tp "
"when inference.enable_expert_parallel is enabled in multi-node deployment."
)
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
expected_global_world_size = self.inference.parallel.dp * inference_tp
if expected_global_world_size != total_infer_gpus:
raise ValueError(
"For multi-node expert parallel inference, inference.parallel.dp * inference.parallel.tp "
f"must match total inference GPUs ({total_infer_gpus}), got {expected_global_world_size}."
)
if self.inference.data_parallel_size_local is None:
self.inference.data_parallel_size_local = inferred_dp_local
elif self.inference.data_parallel_size_local != inferred_dp_local:
raise ValueError(
"inference.data_parallel_size_local must equal deployment.gpus_per_node / inference.parallel.tp "
f"({inferred_dp_local}) when inference.enable_expert_parallel is enabled in multi-node deployment."
)
if not self.inference.enable_lora and self.inference.api_server_count == self.inference.parallel.dp:
self.inference.api_server_count = inferred_dp_local
# Auto-infer DP and api_server_count for standard multi-node inference.
# Without EP, vLLM only creates api_server_count * tp workers per node,
# not gpus_per_node workers. If DP isn't set, the broadcast group expects
# more workers than exist, deadlocking NCCL init.
if (
self.inference is not None
and not self.inference.enable_expert_parallel
and self.inference.deployment.type != "disaggregated"
):
dp_per_node = self.deployment.gpus_per_node // self.inference.parallel.tp
if self.inference.parallel.dp == 1 and dp_per_node > 1:
self.inference.parallel.dp = dp_per_node
if self.inference.data_parallel_size_local is None and dp_per_node > 1:
self.inference.data_parallel_size_local = dp_per_node
if self.inference.api_server_count == 1 and dp_per_node > 1:
self.inference.api_server_count = dp_per_node
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
# Compute inference_world_size from actual worker count per server:
# each api_server runs tp workers that participate in collective_rpc.
api_server_count = self.inference.api_server_count if self.inference else 1
tp = self.inference.parallel.tp if self.inference else 1
total_infer_workers = self.deployment.total_infer_nodes * api_server_count * tp
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.host = "0.0.0.0"
self.trainer.weight_broadcast.inference_world_size = total_infer_workers
assert self.orchestrator.weight_broadcast.type == "nccl"
self.orchestrator.weight_broadcast.inference_world_size = total_infer_workers
return self
@model_validator(mode="after")
def auto_setup_disaggregated_inference(self):
"""Auto-setup for disaggregated P/D inference within a multi-node deployment."""
if self.inference is None or self.inference.deployment.type != "disaggregated":
return self
if self.deployment.type != "multi_node":
return self
infer_deploy = self.inference.deployment
expected_infer_nodes = infer_deploy.num_prefill_nodes + infer_deploy.num_decode_nodes
if self.deployment.num_infer_nodes != expected_infer_nodes:
raise ValueError(
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
f"inference.deployment.num_prefill_nodes ({infer_deploy.num_prefill_nodes}) + "
f"inference.deployment.num_decode_nodes ({infer_deploy.num_decode_nodes}) = {expected_infer_nodes}"
)
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
if self.weight_broadcast is not None and self.weight_broadcast.type == "nccl":
assert self.trainer.weight_broadcast.type == "nccl"
self.trainer.weight_broadcast.inference_world_size = total_infer_gpus
assert self.orchestrator.weight_broadcast.type == "nccl"
self.orchestrator.weight_broadcast.inference_world_size = total_infer_gpus
return self
@model_validator(mode="after")
def auto_setup_inference_client(self):
"""Auto-configure orchestrator student client from the inference server config.
For all modes, sets dp_rank_count from inference DP size. For SFT mode,
also sets base_url - rl/opd rely on the ClientConfig default
(``["http://localhost:8000/v1"]``) which already matches the auto-launched
student vLLM at inference.server.port = 8000.
"""
if self.inference is None:
return self
client = self.orchestrator.student.client
if "dp_rank_count" not in client.model_fields_set:
client.dp_rank_count = self.inference.data_parallel_size_local or self.inference.parallel.dp
if self.orchestrator.training_mode == "sft" and "base_url" not in client.model_fields_set:
host = self.inference.server.host or "localhost"
port = self.inference.server.port
client.base_url = [f"http://{host}:{port}/v1"]
return self
@model_validator(mode="after")
def auto_setup_teacher_inference(self):
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
if self.deployment.type != "single_node":
return self
if self.deployment.num_teacher_gpus is None or self.deployment.num_teacher_gpus == 0:
return self
import copy
from prime_rl.configs.orchestrator import RolloutModelConfig
if self.teacher_inference is None:
if self.inference is None:
self.teacher_inference = InferenceConfig()
else:
self.teacher_inference = copy.deepcopy(self.inference)
self.teacher_inference.server.port = (self.inference.server.port if self.inference else 8000) + 1
elif self.inference is not None and self.teacher_inference.server.port == self.inference.server.port:
raise ValueError(
f"teacher_inference.server.port ({self.teacher_inference.server.port}) conflicts with "
f"inference.server.port ({self.inference.server.port}). "
"Either use different ports or let teacher_inference be auto-configured."
)
tp = self.teacher_inference.parallel.tp
num_teacher_gpus = self.deployment.num_teacher_gpus
if num_teacher_gpus != self.teacher_inference.parallel.dp * tp:
assert num_teacher_gpus % tp == 0, "Number of teacher GPUs must be divisible by tensor parallel size"
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
if self.orchestrator.teacher is None:
self.orchestrator.teacher = RolloutModelConfig()
host = self.teacher_inference.server.host or "localhost"
port = self.teacher_inference.server.port
self.orchestrator.teacher.client.base_url = [f"http://{host}:{port}/v1"]
self.orchestrator.teacher.model.name = self.teacher_inference.model.name
return self
@model_validator(mode="after")
def auto_setup_slurm_template(self):
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
if self.slurm is not None and self.slurm.template_path is None:
templates_dir = find_package_resource("templates")
if templates_dir is not None:
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_rl.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_rl.sbatch.j2"
return self
### Warnings
@@ -2,10 +2,11 @@ import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import BaseModel, ConfigDict, Field, model_validator
from pydantic import Field, model_validator
from prime_rl.configs.shared import (
HeartbeatConfig,
RendererConfig,
SlurmConfig,
TrainerLogConfig,
WandbConfig,
@@ -21,16 +22,21 @@ from prime_rl.configs.trainer import (
SchedulerConfig,
TokenizerConfig,
)
from prime_rl.utils.config import BaseConfig
from prime_rl.utils.config import BaseConfig, find_package_resource
class BaseDataConfig(BaseModel):
"""Base config for SFT data."""
class BaseDataConfig(BaseConfig):
batch_size: int = Field(128, ge=1)
"""Global batch size."""
seq_len: int = Field(128, ge=1)
"""Sequence length."""
batch_size: Annotated[int, Field(ge=1)] = 128
seq_len: Annotated[int, Field(ge=1)] = 128
pack_function: Literal["cat", "stack"] = "cat"
micro_batch_size: Annotated[int, Field(ge=1)] = 1
"""Sample packing strategy. ``cat`` concatenates; ``stack`` requires ``seq_len`` divisible by 256."""
micro_batch_size: int = Field(1, ge=1)
"""Per-step micro batch size. ``batch_size`` must be divisible by this."""
@model_validator(mode="after")
def validate_batch_size(self):
@@ -42,50 +48,56 @@ class BaseDataConfig(BaseModel):
class FakeDataConfig(BaseDataConfig):
"""Configures fake data used for debugging."""
type: Literal["fake"] = "fake"
length: Literal["fixed", "variable"] = "fixed"
"""Use fixed-length samples or variable-length samples."""
input_ids: Literal["increasing", "random"] = "increasing"
"""Token id generator: ``increasing`` for deterministic sequences, ``random`` for random ids."""
class LossMaskConfig(BaseConfig):
"""Configures which message types contribute to the loss. If True, the loss_mask will be True and the message type will contribute to the loss."""
system: bool = False
"""System messages contribute to the loss."""
system: Annotated[bool, Field(description="Whether system messages contribute to the loss.")] = False
user: Annotated[bool, Field(description="Whether user messages contribute to the loss.")] = False
assistant: Annotated[bool, Field(description="Whether assistant messages contribute to the loss.")] = True
tool: Annotated[bool, Field(description="Whether tool messages contribute to the loss.")] = False
user: bool = False
"""User messages contribute to the loss."""
assistant: bool = True
"""Assistant messages contribute to the loss."""
tool: bool = False
"""Tool messages contribute to the loss."""
class SFTDataConfig(BaseDataConfig):
"""Configures the data used for training."""
type: Literal["sft"] = "sft"
name: Annotated[str, Field(description="Name or path of the HF dataset to use.")] = (
"PrimeIntellect/Reverse-Text-SFT"
)
subsets: Annotated[list[str] | None, Field(description="Subsets to use from the HF dataset.")] = None
splits: Annotated[list[str] | None, Field(description="Splits to use from the HF dataset.")] = None
probabilities: Annotated[list[float] | None, Field(description="Probabilities to use for each subset/split.")] = (
None
)
stopping_strategy: Annotated[
Literal["first_exhausted", "all_exhausted"],
Field(description=""),
] = "all_exhausted"
shuffle: Annotated[bool, Field(description="Whether to shuffle the dataset at the beginning of each epoch.")] = True
seed: Annotated[
int,
Field(
description="Random seed to use for shuffling the dataset. We also shuffle at the end of each epoch by adding epoch count to the seed."
),
] = 0
name: str = "PrimeIntellect/Reverse-Text-SFT"
"""HF dataset name or path."""
subsets: list[str] | None = None
"""Subsets to load from the HF dataset."""
splits: list[str] | None = None
"""Splits to load from the HF dataset."""
probabilities: list[float] | None = None
"""Sampling probabilities for each subset/split."""
stopping_strategy: Literal["first_exhausted", "all_exhausted"] = "all_exhausted"
"""Stopping strategy when interleaving multiple subsets/splits."""
shuffle: bool = True
"""Shuffle the dataset at the start of each epoch."""
seed: int = 0
"""Random seed for shuffling. Re-shuffled per epoch by adding the epoch count to the seed."""
# Configuring
loss_mask: LossMaskConfig = LossMaskConfig()
"""Which message types contribute to the loss."""
@model_validator(mode="after")
def validate_subsets_and_splits(self):
@@ -109,28 +121,28 @@ class SFTDataConfig(BaseDataConfig):
class SFTValConfig(BaseConfig):
interval: Annotated[int, Field(ge=1, description="Run validation every N training steps.")] = 50
eval_on_start: Annotated[bool, Field(description="Run validation before the first training step.")] = False
interval: int = Field(50, ge=1)
"""Run validation every N training steps."""
eval_on_start: bool = False
"""Run validation before the first training step."""
data: SFTDataConfig
DataConfig: TypeAlias = Annotated[FakeDataConfig | SFTDataConfig, Field(discriminator="type")]
class BaseDeploymentConfig(BaseModel):
"""Base deployment config for SFT."""
model_config = ConfigDict(extra="forbid")
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
class BaseDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
class SingleNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a single-node SFT deployment."""
type: Literal["single_node"] = "single_node"
num_gpus: Annotated[int, Field(description="Number of GPUs.")] = 1
num_gpus: int = 1
"""GPUs to use."""
@model_validator(mode="after")
def validate_gpu_count(self):
@@ -140,18 +152,13 @@ class SingleNodeDeploymentConfig(BaseDeploymentConfig):
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a multi-node SFT deployment."""
type: Literal["multi_node"] = "multi_node"
num_nodes: Annotated[int, Field(description="Number of training nodes.")] = 2
num_nodes: int = 2
"""Training nodes."""
nodes_per_fsdp_group: Annotated[
int | None,
Field(
description="Number of nodes per FSDP island. Auto-sets model.dp_replicate = num_nodes / nodes_per_fsdp_group."
),
] = None
nodes_per_fsdp_group: int | None = None
"""Nodes per FSDP island. Auto-sets ``model.dp_replicate = num_nodes / nodes_per_fsdp_group``."""
SFTDeploymentConfig: TypeAlias = Annotated[
@@ -160,124 +167,77 @@ SFTDeploymentConfig: TypeAlias = Annotated[
class SFTExperimentalConfig(BaseConfig):
"""Experimental features for SFT training."""
pass
class SFTConfig(BaseConfig):
"""Configures the SFT trainer"""
# The model configuration
model: ModelConfig = ModelConfig()
# The tokenizer configuration
tokenizer: TokenizerConfig = TokenizerConfig()
# The data configuration
renderer: RendererConfig = RendererConfig()
"""Client-side renderer configuration. Only consumed when ``use_renderer=true``."""
use_renderer: bool = False
"""Tokenize SFT samples through the ``renderers`` library (single ``render()`` + ``message_indices`` mask) instead of the default ``build_incremental_token_mask`` path. Required for chat templates that render position-dependently (e.g. Qwen3, Qwen3.5)."""
data: DataConfig = SFTDataConfig()
# Optional validation configuration
val: SFTValConfig | None = None
"""Validation configuration. If None, no validation runs."""
# The optimizer configuration
optim: OptimizerConfig = AdamWConfig()
# The learning rate scheduler configuration
scheduler: SchedulerConfig = ConstantSchedulerConfig()
# The checkpoint configuration
ckpt: CheckpointConfig | None = None
# The logging configuration
log: TrainerLogConfig = TrainerLogConfig()
# The wandb configuration
wandb: WandbConfig | None = None
output_dir: Annotated[
Path,
Field(
description="Directory to write outputs to. Will be populated with checkpoints and logs as subdirectories. Should be set to a persistent directory with enough disk space. This value should be distinct across experiments running on a single node. See the README for more details."
),
] = Path("outputs")
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
clean_output_dir: Annotated[
bool,
Field(
description="If true, delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming.",
),
] = False
clean_output_dir: bool = False
"""Delete the output directory before starting training. Required to overwrite an output directory that contains checkpoints from a previous run when not resuming."""
matmul_precision: Annotated[
Literal["highest", "high", "medium"],
Field(
description=(
"Precision for float32 matrix multiplications. "
"Use 'highest' for full FP32 (required on ROCm/AMD GPUs to avoid "
"catastrophic precision loss in softmax over large vocabularies). "
"Use 'high' to enable TF32 on NVIDIA GPUs for a speedup with minor "
"precision tradeoff. See torch.set_float32_matmul_precision docs."
),
),
] = "high"
matmul_precision: Literal["highest", "high", "medium"] = "high"
"""Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``."""
max_steps: Annotated[
int | None,
Field(description="Maximum number of steps to run training for. If None, will run indefinitely."),
] = None
max_steps: int | None = None
"""Maximum training steps. If None, runs indefinitely."""
memory_profiler_path: Annotated[Path | None, Field(description="Path to write memory profile to.")] = None
memory_profiler_path: Path | None = None
"""Path to write the memory profile to."""
bench: Annotated[
BenchConfig | None,
Field(
description="Whether to run in benchmark mode. It will automatically set the maximum number of steps to run to 4 and use fake data.",
),
] = None
bench: BenchConfig | None = None
"""Benchmark-mode configuration. When set, ``max_steps`` is forced to 4 and fake data is used."""
gc: Annotated[
GCConfig | None,
Field(
description="Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior.",
),
] = GCConfig()
gc: GCConfig | None = GCConfig()
"""Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior."""
trace_path: Annotated[Path | None, Field(description="Path to write pytorch profiler trace to.")] = None
trace_path: Path | None = None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds: Annotated[
int,
Field(
description="Timeout in seconds for torch distributed ops. Defaults to 600 seconds.",
),
] = 600
dist_timeout_seconds: int = 600
"""Timeout in seconds for torch distributed ops."""
loss_impl: Annotated[
Literal["liger", "torch", "liger_fused", "quack_fused"],
Field(
description="Implementation of the cross entropy loss function to use. "
"'liger_fused' fuses the lm_head projection with the CE loss to avoid materializing full logits. "
"'quack_fused' uses quack-kernels for chunked linear + CE with CuTe DSL CUDA kernels."
),
] = "torch"
loss_impl: Literal["liger", "torch", "liger_fused", "quack_fused"] = "torch"
"""Cross-entropy loss implementation. ``liger_fused`` fuses the lm_head projection with the CE loss to avoid materializing full logits. ``quack_fused`` uses quack-kernels for chunked linear + CE with CuTe DSL CUDA kernels."""
heartbeat: Annotated[
HeartbeatConfig | None, Field(description="The heartbeat config for monitoring training progress.")
] = None
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
deployment: SFTDeploymentConfig = SingleNodeDeploymentConfig()
slurm: Annotated[
SlurmConfig | None,
Field(
description="SLURM configuration. If set, the run will be submitted as a SLURM job instead of running locally.",
),
] = None
slurm: SlurmConfig | None = None
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
dry_run: Annotated[bool, Field(description="Only validate and dump resolved configs and exit early.")] = False
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
experimental: Annotated[
SFTExperimentalConfig,
Field(description="Experimental features for SFT training."),
] = SFTExperimentalConfig()
experimental: SFTExperimentalConfig = SFTExperimentalConfig()
### Pre-validation normalization
@@ -357,6 +317,61 @@ class SFTConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_renderer_vs_vlm(self):
if self.use_renderer and self.model.vlm is not None:
raise ValueError(
"use_renderer is not supported for VLMs. The renderer tokenizes "
"text-only message dicts client-side and cannot handle image inputs."
)
return self
@model_validator(mode="after")
def validate_renderer_args(self):
# pool_size is orchestrator-only. An in-process renderer pool exists
# to amortize tokenization across concurrent rollouts in the
# orchestrator (many async requests render at once, HF fast
# tokenizers release the GIL during Rust encoding, so a pool of N
# tokenizer copies parallelizes well). SFT has no such concurrency:
# the StatefulDataLoader is constructed with num_workers=0, so the
# main process tokenizes one example at a time, between training
# steps. Across DP, each rank already owns its own renderer — an
# implicit pool of size world_size. Pooling within a rank gives
# nothing on top of that. Reject so callers don't silently set a
# knob that does nothing; if SFT tokenization ever becomes a
# bottleneck the fix is num_workers on the dataloader, not a pool.
if self.renderer.pool_size is not None:
raise ValueError(
f"renderer.pool_size={self.renderer.pool_size!r} is only used by the orchestrator. "
"SFT tokenizes synchronously (num_workers=0) and already gets one renderer per DP "
"rank — an in-process pool adds nothing. If tokenization is a bottleneck, raise "
"num_workers on the dataloader instead."
)
if self.use_renderer:
return self
renderer_args_set = []
if self.renderer.name != "auto":
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
if self.renderer.tool_parser is not None:
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
if self.renderer.reasoning_parser is not None:
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
if self.renderer.preserve_all_thinking:
renderer_args_set.append(f"renderer.preserve_all_thinking={self.renderer.preserve_all_thinking!r}")
if self.renderer.preserve_thinking_between_tool_calls:
renderer_args_set.append(
f"renderer.preserve_thinking_between_tool_calls={self.renderer.preserve_thinking_between_tool_calls!r}"
)
if renderer_args_set:
raise ValueError(
"Renderer-specific args set without use_renderer=True: "
f"{', '.join(renderer_args_set)}. Either enable the renderer or remove these knobs."
)
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
@@ -425,11 +440,10 @@ class SFTConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_slurm_template(self):
if self.slurm is not None and self.slurm.template_path is None:
import prime_rl
templates_dir = Path(prime_rl.__file__).parent / "templates"
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
templates_dir = find_package_resource("templates")
if templates_dir is not None:
if self.deployment.type == "single_node":
self.slurm.template_path = templates_dir / "single_node_sft.sbatch.j2"
else:
self.slurm.template_path = templates_dir / "multi_node_sft.sbatch.j2"
return self
@@ -0,0 +1,277 @@
import os
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import Field, model_validator
from prime_rl.utils.config import BaseConfig
class SlurmConfig(BaseConfig):
job_name: str = "prime-rl"
"""SLURM job name."""
project_dir: Path = Path(".")
"""Path to the project root, used to source .env, activate .venv, and run uv sync."""
template_path: Path | None = None
"""SLURM template file. If None, uses the bundled single-node or multi-node template."""
partition: str = "cluster"
"""SLURM partition (#SBATCH --partition)."""
nodelist: str | None = None
"""Comma-separated list of specific nodes to run on (#SBATCH --nodelist)."""
exclude: str | None = None
"""Comma-separated list of nodes to exclude (#SBATCH --exclude)."""
account: str | None = None
"""SLURM account to charge (#SBATCH --account)."""
time: str | None = None
"""Maximum wall time, e.g. '24:00:00' or '7-00:00:00' (#SBATCH --time)."""
pre_run_command: str | None = None
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
@property
def template_vars(self) -> dict:
"""Common template variables for all SLURM templates."""
return {
"job_name": self.job_name,
"project_dir": self.project_dir,
"partition": self.partition,
"nodelist": self.nodelist,
"exclude": self.exclude,
"account": self.account,
"time": self.time,
"pre_run_command": self.pre_run_command,
}
@model_validator(mode="after")
def resolve_project_dir(self):
self.project_dir = self.project_dir.resolve()
return self
ServerType = Literal["vllm", "openai"]
class VLMConfig(BaseConfig):
vision_encoder_attr: str
"""Dotted attribute path to the vision encoder module (e.g. ``model.visual``)."""
language_model_attr: str
"""Dotted attribute path to the language model module (e.g. ``model.language_model``)."""
freeze_vision_encoder: bool = True
"""Freeze the vision encoder. When False, it is trainable and FSDP-sharded per-block. No effect with LoRA (LoRA freezes all non-adapter parameters)."""
class BaseModelConfig(BaseConfig):
name: str = "Qwen/Qwen3-0.6B"
"""HF model name or local path."""
trust_remote_code: bool = False
"""Trust remote code when initializing the tokenizer."""
vlm: "VLMConfig | None" = None
"""VLM configuration. Setting this enables vision-language model support."""
@property
def is_vlm(self) -> bool:
return self.vlm is not None
class RendererConfig(BaseConfig):
name: str = "auto"
"""Renderer used for chat-template tokenization. One of: ``auto`` (detect from tokenizer), ``qwen3``, ``qwen3_vl``, ``qwen3.5``, ``glm5``, ``glm4.5``, ``minimax-m2``, ``deepseek_v3``, ``kimi_k2``, ``kimi_k25``, ``nemotron3``, ``gpt_oss``, ``default``."""
tool_parser: str | None = None
"""Tool parser from ``renderers.parsers``. Only consumed by DefaultRenderer; model-specific renderers bake their own parsing in. Options: ``qwen3``, ``qwen3.5``, ``glm``, ``deepseek_v3``."""
reasoning_parser: str | None = None
"""Reasoning parser from ``renderers.parsers``. Only consumed by DefaultRenderer. Options: ``think``."""
pool_size: int | None = Field(None, ge=1)
"""Number of renderer slots shared across concurrent rollouts. Bump for long multi-turn prompts where client-side jinja tokenization serializes."""
preserve_all_thinking: bool = False
"""Re-emit every past-assistant turn's ``reasoning_content`` between ``<think>``/``</think>`` (or the model's equivalent), even when the chat template would drop it. Strict superset of preserve_thinking_between_tool_calls."""
preserve_thinking_between_tool_calls: bool = False
"""Preserve past-assistant ``reasoning_content`` only inside the current tool cycle — the contiguous assistant→tool→…→assistant block after the most recent user message, when that block contains at least one tool response. A new user turn closes the block."""
class ElasticConfig(BaseConfig):
hostname: str
"""DNS hostname that resolves to inference server IPs."""
port: int = 8000
"""Port that inference servers listen on."""
sync_interval: float = 5.0
"""Seconds between server discovery checks."""
class ClientConfig(BaseConfig):
timeout: int = 1200
"""Request timeout in seconds."""
connect_timeout: float = 30.0
"""TCP connect timeout in seconds for inference API requests."""
wait_for_ready_timeout: int = 1800
"""Seconds to wait at startup for the inference pool to become ready. Applies to both the static health check and elastic DNS-based discovery."""
base_url: list[str] = ["http://localhost:8000/v1"]
"""Base URLs for the OpenAI API. With more than one URL, the client round-robins (chat) completion requests across all servers. Ignored when ``elastic`` is set."""
api_key_var: str = "VLLM_API_KEY"
"""Environment variable name containing the API key, resolved via ``os.getenv``. Can be any string when the server is not protected by an API key; the same key is used for every URL."""
headers: dict[str, str] = {}
"""Static headers sent with every request."""
headers_from_env: dict[str, str] = {}
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
extra_headers_from_state: dict[str, str] = {}
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "example_id"}`` enables sticky routing at the inference router."""
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
dp_rank_count: int = Field(1, ge=1)
"""Number of data-parallel ranks behind each base URL. When > 1, each URL is expanded into ``dp_rank_count`` logical clients pinned via the ``X-data-parallel-rank`` header, so every request within a rollout hits the same DP engine and reuses KV cache. Auto-set from the inference config when using the RL entrypoint."""
admin_base_url: list[str] | None = None
"""Separate base URLs for admin operations (weight updates, health checks). When set, admin clients bypass routers and hit each server directly — used in disaggregated P/D deployments where the router must not handle admin traffic."""
elastic: ElasticConfig | None = None
"""Elastic inference pool config for DNS-based service discovery. When set, ``base_url`` is ignored and inference servers are discovered dynamically via DNS."""
router_url: str | None = None
"""vllm-router URL for load-aware inference routing. With elastic mode, inference requests go through the router while admin ops still hit discovered pods directly."""
@property
def is_elastic(self) -> bool:
"""Check if elastic mode is enabled."""
return self.elastic is not None
class LogConfig(BaseConfig):
level: str = Field(default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"))
"""Log level for the process. Defaults to ``$PRIME_LOG_LEVEL`` if set, else ``info``."""
vf_level: str = Field(default_factory=lambda: os.environ.get("PRIME_VF_LOG_LEVEL", "info"))
"""Log level for the verifiers package. Defaults to ``$PRIME_VF_LOG_LEVEL`` if set, else ``info``."""
json_logging: bool = False
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
log_data: bool = False
"""Log the first data sample at startup."""
class TrainerLogConfig(LogConfig):
ranks_filter: list[int] = [0]
"""Trainer ranks to show in console output. Passed to ``torchrun --local-ranks-filter``."""
class LogExtrasConfig(BaseConfig):
samples: bool = True
"""Log prompt/response samples."""
distributions: bool = True
"""Log distributions (rewards, advantages, etc.)."""
interval: int = Field(10, ge=1)
"""Step interval between extras logs."""
sample_ratio: float | None = Field(None, ge=0.0, le=1.0)
"""Fraction of rollouts to log per step. The effective cap is ``len(rollouts) * sample_ratio``; 1.0 = all, 0.5 = half, 0.0 = none."""
class WandbConfig(BaseConfig):
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
project: str = "prime-rl"
"""W&B project to log to."""
entity: str | None = None
"""W&B entity to log to."""
name: str | None = None
"""W&B run name."""
group: str | None = None
"""W&B group."""
tags: list[str] | None = None
"""W&B tags attached to the run."""
offline: bool = False
"""Run W&B in offline mode."""
class WandbWithExtrasConfig(WandbConfig):
log_extras: LogExtrasConfig | None = LogExtrasConfig()
"""Extras logging configuration. If None, no extras are logged."""
class PrimeMonitorConfig(BaseConfig):
base_url: str = "https://api.primeintellect.ai/api/v1/rft"
"""Base URL for the Prime Intellect monitoring API."""
api_key_var: str = "PRIME_API_KEY"
"""Environment variable name containing the Prime Intellect API key, resolved via ``os.getenv``."""
log_extras: LogExtrasConfig | None = LogExtrasConfig()
"""Extras logging configuration. If None, no extras are logged."""
run_name: str | None = None
"""Run name shown on the platform. Defaults to the W&B run name when set, otherwise the platform auto-generates one."""
team_id: str | None = None
"""Team ID to associate the run with."""
frontend_url: str | None = None
"""Frontend base URL used for the dashboard link printed after registration. Defaults to the Prime CLI frontend URL when unset."""
class HeartbeatConfig(BaseConfig):
url: str
"""URL to send the heartbeat to."""
class MetricsServerConfig(BaseConfig):
port: int = Field(8000, ge=1, le=65535)
"""Port to expose metrics and health endpoints on."""
host: str = "0.0.0.0"
"""Host to bind the server to."""
class BaseTransportConfig(BaseConfig):
pass
class FileSystemTransportConfig(BaseTransportConfig):
type: Literal["filesystem"] = "filesystem"
class ZMQTransportConfig(BaseTransportConfig):
type: Literal["zmq"] = "zmq"
host: str = "localhost"
"""Host address for ZMQ transport."""
port: int = 5555
"""Base port for ZMQ transport."""
hwm: int = 10
"""High-water mark (max in-flight messages per ZMQ socket)."""
TransportConfig: TypeAlias = Annotated[FileSystemTransportConfig | ZMQTransportConfig, Field(discriminator="type")]
@@ -0,0 +1,673 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import Field, model_validator
from prime_rl.configs.shared import (
BaseModelConfig,
FileSystemTransportConfig,
HeartbeatConfig,
MetricsServerConfig,
TrainerLogConfig,
TransportConfig,
WandbConfig,
)
from prime_rl.utils.config import BaseConfig
# -- Shared trainer configs (used by both SFT and RL trainers) --
AttnImplementation: TypeAlias = Literal["eager", "sdpa", "flash_attention_2", "flash_attention_3", "fa4"]
EPCommBackend: TypeAlias = Literal["torch", "deepep"]
# User-facing name -> internal name. Users set `flash_attention_4` in configs,
# which gets rewritten to `fa4` before pydantic validation.
# We use `fa4` internally because `flash_attention_*` triggers transformers
# to attempt installing a kernel from hub.
_ATTN_ALIASES = {"flash_attention_4": "fa4"}
class GCConfig(BaseConfig):
interval: int = Field(50, ge=1)
"""Run garbage collection every N training steps. Disables Python's automatic GC so every rank collects together and one slow rank can't stall the others."""
class ActivationCheckpointConfig(BaseConfig):
mode: Literal["full", "selective"] = "full"
"""``full`` checkpoints whole transformer blocks; ``selective`` checkpoints only the subcomponents listed in ``targets`` inside supported custom decoder layers."""
freq: int = Field(1, ge=1)
"""Apply activation checkpointing to every N layers."""
targets: list[str] = ["norm"]
"""Selective checkpoint targets. ``norm`` checkpoints every norm module inside selected layers. ``attn_proj`` checkpoints projection-side attention work outside the kernel (input/output projections, attention-local norms, RoPE, gating, model-specific MLA projection helpers). ``mlp`` checkpoints the entire dense MLP forward (not for MoE). ``mla_up_proj`` checkpoints MLA Q/KV up-projection where supported. ``routed_experts`` checkpoints routed expert compute in MoE layers (including LatentMoE). ``linear_attn`` checkpoints non-softmax token mixers (NemotronH Mamba, Qwen3.5-MoE GatedDeltaNet, AFMoE sliding-window attention)."""
@model_validator(mode="after")
def validate_selective_targets(self):
self.targets = list(dict.fromkeys(self.targets))
if self.mode == "selective" and not self.targets:
raise ValueError("Selective activation checkpointing requires at least one target.")
return self
class ActivationOffloadingConfig(BaseConfig):
pin_memory: bool = True
"""Pin offloaded activations to CPU memory."""
max_inflight_activations: int = Field(5, ge=1)
"""Max activations kept in flight while offloading. More activations smooth overlap at the cost of GPU memory."""
class CompileConfig(BaseConfig):
fullgraph: bool = False
"""Compile transformer blocks with ``fullgraph=True``."""
class BenchConfig(BaseConfig):
output_json: Path | None = None
"""Path to write benchmark results as JSON. If unset, results are only printed to the console."""
class LoRAConfig(BaseConfig):
rank: int = Field(16, ge=1)
"""Rank of the low-rank decomposition matrices."""
alpha: float = Field(32.0, ge=0)
"""LoRA scaling parameter."""
dropout: float = Field(0.0, ge=0, le=1)
"""LoRA dropout rate."""
target_modules: list[str] = [
"q_proj",
"k_proj",
"v_proj",
"o_proj",
"gate_proj",
"up_proj",
"down_proj",
"experts",
"fc1_latent_proj",
"fc2_latent_proj",
]
"""Module names or regex patterns to apply LoRA to. Simple names (e.g. ``q_proj``) match any component in the module path; regex patterns match anywhere in the name. Names unknown to the current model are silently ignored, so defaults cover multiple architectures. NemotronH note: ``experts`` matches NonGatedGroupedExperts inside LatentMoE; ``fc1_latent_proj``/``fc2_latent_proj`` adapt the latent up/down projections. Add ``in_proj``/``out_proj`` to also LoRA Mamba."""
modules_to_save: list[str] = []
"""Module names or regex patterns to keep fully trainable (not freeze). Same matching rules as ``target_modules``."""
class DebugModelConfig(BaseConfig):
num_layers: int | None = None
"""Override the number of transformer layers (truncates the model)."""
random_init: bool = False
"""Randomly initialize the model instead of loading weights."""
force_balanced_routing: bool = False
"""Replace MoE token-choice routing with a round-robin assignment so every expert sees an equal share. Intended for fake-data smoke tests where untrained routing would otherwise OOM under severe imbalance. Gating scores are still gathered from the override indices so the forward pass stays consistent."""
class ModelConfig(BaseModelConfig):
seq_len: int = 2048
"""Sequence length the model is trained on."""
attn: AttnImplementation = "flash_attention_2"
"""Attention implementation. With CP enabled, ring attention uses the matching kernel family (FA2/FA3/FA4)."""
compile: CompileConfig | None = None
"""Compile the model with ``torch.compile``."""
ac: ActivationCheckpointConfig | None = None
"""Activation checkpointing configuration. If None, activation checkpointing is disabled."""
ac_offloading: ActivationOffloadingConfig | None = None
"""Activation offloading configuration. If None, activation offloading is disabled."""
fsdp_cpu_offload: bool = False
"""Enable FSDP CPU offloading for parameters, gradients, and optimizer states. Uses pinned memory for efficient CPU↔GPU transfers."""
optim_cpu_offload: bool = False
"""Offload only optimizer states (momentum, variance) to CPU, keeping weights on GPU. Avoids the H2D all-gather overhead of FSDP CPU offload while still saving GPU memory."""
reshard_after_forward: bool = True
"""Reshard the model after each forward pass."""
dp_replicate: int = 1
"""Data parallel dim where model weights are replicated."""
ep: int = 1
"""Expert parallelism degree for MoE layers. 1 disables EP."""
ep_comm_backend: EPCommBackend = "torch"
"""Communication backend for expert parallelism. ``torch`` uses TorchTitan all-to-all collectives; ``deepep`` uses DeepEP custom kernels."""
deepep_num_sms: int = Field(20, ge=1)
"""SMs allocated for DeepEP intranode dispatch/combine kernels. Also determines internode RDMA channel count (``num_channels = num_sms / 2``). Lower values leave more SMs for compute; higher values speed up dispatch/combine. The optimal value depends on EP degree and hardware. Only used when ``ep_comm_backend='deepep'``."""
deepep_token_chunk_size: int | None = Field(None, ge=1)
"""Token chunk size for DeepEP MoE pipelining. When set, DeepEP dispatch for chunk i+1 is launched while experts compute chunk i. Only used when ``ep_comm_backend='deepep'``."""
cp: int = 1
"""Context parallelism degree. 1 disables CP."""
cp_style: Literal["ring", "ulysses"] = "ring"
"""CP communication style. ``ring`` uses ring-attention all-gather/reduce-scatter (requires custom kernels per attention type). ``ulysses`` uses all-to-all to redistribute Q/K/V from sequence-sharded to head-sharded, runs vanilla attention locally on the full sequence, then all-to-all back — works out-of-the-box with any attention kernel (softmax FA, linear attention, mamba, etc.)."""
impl: Literal["hf", "custom", "auto"] = "auto"
"""Model implementation. ``auto`` selects ``custom`` if supported by the model, otherwise ``hf``."""
optimization_dtype: Literal["bfloat16", "float32"] = "float32"
"""dtype for model optimization."""
reduce_dtype: Literal["bfloat16", "float32"] = "float32"
"""dtype for gradient/parameter reductions."""
moe_use_grouped_mm: bool = True
"""Use grouped mm for MoE layers. Requires compute capability ≥ 9.0."""
fp8: bool = False
"""FP8 training via DeepGEMM. Replaces ``nn.Linear`` with FP8 blockwise linear and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and ``model.impl='custom'``."""
freeze_moe_router: bool = False
"""Freeze MoE router parameters during training."""
lora: LoRAConfig | None = None
"""LoRA configuration. If None, LoRA is disabled."""
debug: DebugModelConfig = DebugModelConfig()
"""Debugging knobs for the model and distributed training."""
fused_lm_head_token_chunk_size: int | Literal["auto", "disabled"] = "disabled"
"""Flattened token chunk size for the fused LM head. ``int >= 1`` sets the tokens per LM-head chunk explicitly; ``auto`` auto-enables (RL training picks 8192); ``disabled`` uses the vanilla LM head. Integer values aren't supported for SFT training."""
@model_validator(mode="before")
@classmethod
def _normalize_attn_alias(cls, data):
"""Rewrite user-facing `flash_attention_4` to internal `fa4` before validation."""
if isinstance(data, dict) and data.get("attn") in _ATTN_ALIASES:
data["attn"] = _ATTN_ALIASES[data["attn"]]
return data
@model_validator(mode="after")
def trust_remote_code_only_with_hf(self):
"""Trust remote code only if the model is from HF."""
if self.trust_remote_code:
if self.impl not in ("hf", "auto"):
raise ValueError("Trust remote code is only supported with the HF implementation or auto mode.")
return self
@model_validator(mode="after")
def cp_only_with_flash_attn(self):
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "fa4"]:
raise ValueError("CP is only supported with flash attention 2, flash attention 3, or fa4")
if self.cp > 1 and self.attn in ("flash_attention_3", "fa4") and self.impl != "custom":
# Both ring and ulysses route FA3/FA4 through our custom FlashAttention class:
# ring patches `_compute_attention` with the ring kernel, ulysses patches it with
# the all-to-all wrapper around the FA3/FA4 kernel. The HF path patches
# `_flash_attention_forward` which only wraps FA2.
raise ValueError(
f"CP with {self.attn} requires model.impl='custom' "
"(FA3/FA4 paths are only implemented for the custom model attention class)"
)
return self
@model_validator(mode="after")
def ac_offloading_requires_ac(self):
"""Automatically enable activation checkpointing when activation offloading is enabled."""
if self.ac_offloading is not None and self.ac is None:
self.ac = ActivationCheckpointConfig()
return self
@model_validator(mode="after")
def selective_ac_only_with_custom_impl(self):
if self.ac is not None and self.ac.mode == "selective" and self.impl not in ("custom", "auto"):
raise ValueError("Selective activation checkpointing requires model.impl='custom' or 'auto'")
return self
@model_validator(mode="after")
def cpu_offload_mutual_exclusion(self):
if self.fsdp_cpu_offload and self.optim_cpu_offload:
raise ValueError("Cannot enable both fsdp_cpu_offload and optim_cpu_offload. Use one or the other.")
return self
@model_validator(mode="after")
def flash_attention_4_only_with_custom_impl(self):
if self.attn == "fa4" and self.impl != "custom":
raise ValueError("Flash attention 4 is only supported with the custom implementation")
return self
@model_validator(mode="after")
def fp8_only_with_custom_impl(self):
if self.fp8 and self.impl not in ("custom", "auto"):
raise ValueError("FP8 training is only supported with model.impl='custom' or 'auto'.")
return self
@model_validator(mode="after")
def validate_ep_comm_backend(self):
if self.ep_comm_backend == "torch":
return self
if self.ep <= 1:
raise ValueError(f"model.ep_comm_backend='{self.ep_comm_backend}' requires model.ep > 1.")
return self
class TokenizerConfig(BaseConfig):
name: str | None = None
"""Tokenizer name or path. If None, the model's default tokenizer is used."""
trust_remote_code: bool | None = None
"""Trust remote code when initializing the tokenizer. If None, inherits the model's ``trust_remote_code`` setting."""
chat_template: str | None = None
"""Chat template for the tokenizer. Either a Jinja2 template string or a path to a template file. If None, the tokenizer's default chat template is used."""
class ConstantSchedulerConfig(BaseConfig):
type: Literal["constant"] = "constant"
class LinearSchedulerConfig(BaseConfig):
type: Literal["linear"] = "linear"
warmup_steps: int = Field(10, ge=0)
"""Warmup steps for the learning rate scheduler."""
decay_steps: int = Field(10, ge=0)
"""Steps to decay the learning rate during the final portion of training."""
min_lr: float = Field(0.0, ge=0)
"""Minimum learning rate to converge to."""
class CosineSchedulerConfig(BaseConfig):
type: Literal["cosine"] = "cosine"
warmup_steps: int = Field(10, ge=0)
"""Warmup steps for the learning rate scheduler."""
min_lr: float = Field(0.0, ge=0)
"""Minimum learning rate to converge to."""
SchedulerConfig: TypeAlias = Annotated[
ConstantSchedulerConfig | LinearSchedulerConfig | CosineSchedulerConfig, Field(discriminator="type")
]
class BaseOptimizerConfig(BaseConfig):
lr: float = Field(1e-6, ge=0)
"""Peak learning rate."""
weight_decay: float = Field(0.01, ge=0)
"""L2 weight-decay coefficient."""
max_norm: float | None = Field(1.0, ge=0)
"""Maximum gradient norm to clip to. If None, gradient clipping is disabled."""
class SGDConfig(BaseOptimizerConfig):
type: Literal["sgd"] = "sgd"
nesterov: bool = True
"""Use Nesterov momentum."""
momentum: float = 0.9
"""SGD momentum factor."""
class AdamWConfig(BaseOptimizerConfig):
type: Literal["adamw"] = "adamw"
betas1: float = Field(0.9, ge=0)
"""Adam first-moment (β1) decay."""
betas2: float = Field(0.999, ge=0)
"""Adam second-moment (β2) decay."""
class MuonConfig(BaseOptimizerConfig):
type: Literal["muon"] = "muon"
mu: float = Field(0.95, ge=0)
"""Momentum factor for the Muon algorithm."""
betas1: float = Field(0.9, ge=0)
"""β1 for the AdamW/Lion sub-optimizer used on non-Muon params."""
betas2: float = Field(0.95, ge=0)
"""β2 for the AdamW/Lion sub-optimizer used on non-Muon params."""
class SignSGDConfig(BaseOptimizerConfig):
type: Literal["sign_sgd"] = "sign_sgd"
OptimizerConfig: TypeAlias = Annotated[
SGDConfig | AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")
]
class WeightCheckpointConfig(BaseConfig):
save_sharded: bool = True
"""Save the weight checkpoint in sharded format."""
save_format: Literal["safetensors", "torch"] = "safetensors"
"""Weight checkpoint serialization format."""
save_adapter_separately: bool = False
"""Save LoRA adapters separately before merging into full model weights."""
class CheckpointConfig(BaseConfig):
output_dir: Path | None = None
"""Override directory for checkpoints and weights. If set, checkpoints and weight snapshots are written here instead of under the trainer ``output_dir`` — useful for writing large checkpoints to a separate storage volume."""
interval: int | None = Field(None, ge=1)
"""Interval at which to save the training checkpoint. If None, only checkpoints at the end of training."""
weights: WeightCheckpointConfig | None = WeightCheckpointConfig()
"""Weight-checkpoint sub-configuration. If None, no HF-compatible weight checkpoints are written."""
skip_gather_master_weights: bool = False
"""Skip gathering and saving HF-compatible weight checkpoints. Useful for large models where the gather is expensive and only DCP checkpoints are needed."""
weights_only: bool = False
"""Save only weight checkpoints (no optimizer/scheduler state). Much faster and smaller than full checkpoints, but cannot resume training."""
resume_step: int | None = Field(None, ge=-1)
"""Step to resume training from. None starts from scratch; ``-1`` restarts from the latest checkpoint available."""
keep_last: int | None = Field(None, ge=1)
"""Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency."""
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
skip_progress: bool = False
"""Skip loading the progress from checkpoint."""
skip_scheduler: bool = False
"""Skip loading the scheduler from checkpoint."""
skip_dataloader: bool = False
"""Skip loading the dataloader from checkpoint."""
skip_optimizer: bool = False
"""Skip loading the optimizer state from checkpoint."""
class DefaultLossConfig(BaseConfig):
type: Literal["default"] = "default"
dppo_mask_low: float = Field(0.2, ge=0)
"""Lower DPPO masking threshold."""
dppo_mask_high: float = Field(0.2, ge=0)
"""Upper DPPO masking threshold."""
adv_tau: float = Field(1.0, ge=0)
"""Temperature for the advantage term."""
kl_tau: float = Field(1e-3, ge=0)
"""Temperature for the KL term."""
class CustomLossConfig(BaseConfig):
type: Literal["custom"] = "custom"
import_path: str
"""Import path to the loss function (e.g. ``my_module.my_loss``)."""
kwargs: dict[str, Any] = Field(default_factory=dict)
"""Kwargs forwarded to the loss function."""
LossConfig: TypeAlias = Annotated[DefaultLossConfig | CustomLossConfig, Field(discriminator="type")]
class FakeDataLoaderConfig(BaseConfig):
batch_size: int = Field(2, ge=1)
"""Batch size of the fake data loader."""
generate_samples: bool = False
"""Generate separate samples and pack them into a single micro-batch instead of using random tensors."""
class DataLoaderConfig(BaseConfig):
fake: FakeDataLoaderConfig | None = None
"""Use a fake data loader sampling random micro-batches (for debugging)."""
class BaseWeightBroadcastConfig(BaseConfig):
pass
class FileSystemWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["filesystem"] = "filesystem"
save_sharded: bool = True
"""Save the weight checkpoint in sharded format."""
save_format: Literal["safetensors", "torch"] = "safetensors"
"""Weight checkpoint serialization format."""
class NCCLWeightBroadcastConfig(BaseWeightBroadcastConfig):
type: Literal["nccl"] = "nccl"
host: str = "localhost"
"""Host for the NCCL broadcast rendezvous."""
port: int = 29501
"""Port for the NCCL broadcast rendezvous."""
timeout: int = 1200
"""Timeout in seconds for the NCCL broadcast."""
# TODO: Should not be configurable, but auto-inferred
inference_world_size: int = 1
"""Number of GPUs used for inference."""
quantize_in_weight_transfer: bool = False
"""Use kernel-format FP8 quantized NCCL transfer for weight updates. When disabled, uses default HF checkpoint-format transfer."""
WeightBroadcastConfig: TypeAlias = Annotated[
FileSystemWeightBroadcastConfig | NCCLWeightBroadcastConfig, Field(discriminator="type")
]
class TokenExportConfig(BaseConfig):
"""Configures per-token rollout exports from the RL trainer."""
class TrainerExperimentalConfig(BaseConfig):
token_export: TokenExportConfig | None = None
"""Opt-in per-token JSONL export for rollout debugging. When enabled, writes token ids and aligned trainer metrics after each forward pass."""
class TrainerConfig(BaseConfig):
model: ModelConfig = ModelConfig()
tokenizer: TokenizerConfig = TokenizerConfig()
data: DataLoaderConfig = DataLoaderConfig()
loss: LossConfig = DefaultLossConfig()
"""Loss config for rl-mode batches. opd and sft batches dispatch to their own loss fns unconditionally and do not read this."""
optim: OptimizerConfig = AdamWConfig()
scheduler: SchedulerConfig = ConstantSchedulerConfig()
ckpt: CheckpointConfig | None = None
"""Full training-state checkpoint configuration (model + optimizer + scheduler). If None, no resume-capable checkpoints are written."""
weight_broadcast: WeightBroadcastConfig = FileSystemWeightBroadcastConfig()
"""Transport used to broadcast updated weights from trainer to inference."""
rollout_transport: TransportConfig = FileSystemTransportConfig()
"""Transport used to ship rollouts from orchestrator to trainer."""
log: TrainerLogConfig = TrainerLogConfig()
wandb: WandbConfig | None = None
output_dir: Path = Path("outputs")
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
matmul_precision: Literal["highest", "high", "medium"] = "high"
"""Precision for float32 matrix multiplications. ``highest`` is full FP32 (required on ROCm/AMD GPUs to avoid catastrophic precision loss in softmax over large vocabularies). ``high`` enables TF32 on NVIDIA GPUs for a speedup with minor precision tradeoff. See ``torch.set_float32_matmul_precision``."""
max_steps: int | None = None
"""Maximum number of training steps. If None, runs indefinitely."""
max_async_level: int = Field(1, ge=0)
"""Maximum steps inference can be ahead of training (how off-policy inference can be). Higher values yield better throughput via async execution at the cost of policy lag; ``0`` is fully synchronous."""
enable_router_replay: bool = False
"""Return routed experts in the batch so the trainer can replay routing. Requires ``enable_return_routed_experts=true`` on the vLLM server (or ``--enable-return-routed-experts``) and is only supported for custom models."""
memory_profiler_path: Path | None = None
"""Path to write the memory profile to."""
bench: BenchConfig | None = None
"""Benchmark-mode configuration. When set, ``max_steps`` is forced to 4 and fake data is used."""
gc: GCConfig | None = GCConfig()
"""Garbage collection config. Disables automatic GC and runs deterministic collections every N steps to avoid stragglers. Set to null to use Python's default GC behavior."""
trace_path: Path | None = None
"""Path to write the PyTorch profiler trace to."""
dist_timeout_seconds: int = 600
"""Timeout in seconds for torch distributed ops."""
heartbeat: HeartbeatConfig | None = None
"""BetterStack heartbeat configuration for monitoring training progress."""
metrics_server: MetricsServerConfig | None = None
"""Prometheus metrics server configuration. If set, exposes a ``/metrics`` endpoint for scraping."""
max_concurrent_runs: int = Field(1, ge=1)
"""Maximum number of concurrent runs to allow. If 1, only one run may run at a time."""
experimental: TrainerExperimentalConfig = TrainerExperimentalConfig()
@model_validator(mode="after")
def deepep_disables_grad_clipping(self):
if self.model.ep_comm_backend == "deepep" and self.optim.max_norm is not None:
warnings.warn(
"Gradient clipping is not compatible with DeepEP. "
"Automatically setting optim.max_norm to None (disabled).",
stacklevel=1,
)
self.optim.max_norm = None
return self
@model_validator(mode="after")
def vlms_require_bfloat16(self):
if self.model.vlm is not None and (
self.model.optimization_dtype != "bfloat16" or self.model.reduce_dtype != "bfloat16"
):
raise ValueError(
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
)
return self
@model_validator(mode="after")
def vlm_freeze_incompatible_with_lora(self):
if self.model.vlm is not None and not self.model.vlm.freeze_vision_encoder and self.model.lora is not None:
raise ValueError(
"freeze_vision_encoder=false is incompatible with LoRA. "
"LoRA freezes all non-adapter parameters including the vision encoder."
)
return self
@model_validator(mode="after")
def auto_setup_bench(self):
if self.bench is not None:
self.max_steps = 4 # 1 Warmup + 3 Benchmark
if not self.data.fake:
self.data.fake = FakeDataLoaderConfig()
if self.ckpt: # Do not checkpoint
self.ckpt = None
return self
@model_validator(mode="after")
def dont_do_massive_traces(self):
if self.trace_path:
if self.max_steps is None:
raise ValueError("Must specify max_steps when tracing")
if self.max_steps >= 10:
raise ValueError(
"Tracing more than 10 steps is not recommended as your trace will be massive. Remove this line if you really want to trace more steps."
)
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
lora_enabled = self.model and self.model.lora
if not lora_enabled:
raise ValueError(
"save_adapter_separately=True requires LoRA to be enabled. "
"Set model.lora or disable save_adapter_separately."
)
return self
@model_validator(mode="after")
def validate_weight_broadcast_type(self):
if self.weight_broadcast.type == "nccl" and self.max_async_level != 1:
raise ValueError("NCCL weight broadcast only works with async level 1")
return self
@model_validator(mode="after")
def validate_opt_and_fsdp_offload(self):
if self.optim.type == "muon" and self.model.fsdp_cpu_offload:
raise ValueError("Muon optimizer does not support FSDP CPU offload")
return self
@model_validator(mode="after")
def validate_optim_cpu_offload_single_run(self):
if self.model.optim_cpu_offload and self.max_concurrent_runs > 1:
raise ValueError("Optimizer CPU offload is not supported with max_concurrent_runs > 1")
return self
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
# TODO: Support this
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
if self.tokenizer.name is None:
self.tokenizer.name = self.model.name
if self.tokenizer.trust_remote_code is None:
self.tokenizer.trust_remote_code = self.model.trust_remote_code
return self
@model_validator(mode="after")
def auto_setup_fused_lm_head_token_chunk_size(self):
if self.model.fused_lm_head_token_chunk_size == "auto":
self.model.fused_lm_head_token_chunk_size = 8192
return self
@model_validator(mode="after")
def ep_only_with_custom_impl(self):
if self.model.ep > 1 and self.model.impl not in ("custom", "auto"):
raise ValueError("EP is only supported with the custom implementation or auto mode")
return self
@model_validator(mode="after")
def router_replay_only_with_custom_impl(self):
if self.enable_router_replay and self.model.impl not in ("custom", "auto"):
raise ValueError("Router replay is only supported with the custom implementation or auto mode")
return self
@@ -0,0 +1,56 @@
from pathlib import Path
from typing import Any
from pydantic import BaseModel
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
def find_package_resource(subdir: str) -> Path | None:
"""Find a directory contributed to the `prime_rl` namespace package by any installed wheel.
Returns None if `subdir` is not present in any wheel — e.g. on a slim
`prime-rl-configs`-only install where `prime-rl`'s shipped resources
(templates, etc.) are absent.
"""
import prime_rl
for p in prime_rl.__path__:
candidate = Path(p) / subdir
if candidate.is_dir():
return candidate
return None
def rgetattr(obj: Any, attr_path: str) -> Any:
"""Recursive getattr for dotted paths: rgetattr(cfg, "trainer.model.name")."""
current = obj
for attr in attr_path.split("."):
if not hasattr(current, attr):
raise AttributeError(f"'{type(current).__name__}' object has no attribute '{attr}'")
current = getattr(current, attr)
return current
def rsetattr(obj: Any, attr_path: str, value: Any) -> None:
"""Recursive setattr for dotted paths: rsetattr(cfg, "trainer.model.name", "foo")."""
if "." not in attr_path:
return setattr(obj, attr_path, value)
parent_path, attr = attr_path.rsplit(".", 1)
setattr(rgetattr(obj, parent_path), attr, value)
def get_all_fields(model: BaseModel | type) -> list[str]:
if isinstance(model, BaseModel):
model_cls = model.__class__
else:
model_cls = model
fields = []
for name, field in model_cls.model_fields.items():
field_type = field.annotation
fields.append(name)
if field_type is not None and hasattr(field_type, "model_fields"):
sub_fields = get_all_fields(field_type)
fields.extend(f"{name}.{sub}" for sub in sub_fields)
return fields
@@ -0,0 +1,44 @@
import re
# (regex, parser_name) — first match wins.
TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
(re.compile(r"^zai-org/GLM-4\.7"), "glm47"),
(re.compile(r"^zai-org/GLM-5"), "glm47"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Qwen3.5 and Qwen3-Coder use qwen3_coder — must be before the Qwen3 catch-all.
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3_coder"),
(re.compile(r"^Qwen/Qwen3-Coder"), "qwen3_coder"),
(re.compile(r"^Qwen/Qwen3-"), "hermes"),
]
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
(re.compile(r"^zai-org/GLM-"), "glm45"),
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
# Only Qwen3 Thinking models reason — Instruct/base models do not.
(re.compile(r"^Qwen/Qwen3-.*Thinking"), "deepseek_r1"),
(re.compile(r"^Qwen/Qwen3\.5-"), "qwen3"),
]
def _resolve(model_name: str, patterns: list[tuple[re.Pattern[str], str]]) -> str | None:
for pattern, parser_name in patterns:
if pattern.search(model_name):
return parser_name
return None
def resolve_tool_call_parser(model_name: str) -> str | None:
return _resolve(model_name, TOOL_CALL_PARSER_PATTERNS)
def resolve_reasoning_parser(model_name: str) -> str | None:
return _resolve(model_name, REASONING_PARSER_PATTERNS)
@@ -0,0 +1,329 @@
from __future__ import annotations
from typing import Any, Optional
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.trainer import TrainerConfig
def propagate_shared_fields(data: Any) -> Any:
"""Propagate ``RLConfig``'s shared top-level fields into the matching sub-config
dicts before sub-configs are constructed, so each sub-config's ``mode="after"``
validators see the resolved values at construction time.
Behaviour:
- **Fill-if-absent**: an explicit sub-config value is never overwritten.
The shared block acts as a default, not a stomper.
- **Up-front mutex**: setting the same field at both the shared and
sub-config level raises. Under fill-if-absent the sub would silently
win, and any later CLI override of the shared field would invisibly
no-op.
- **Aliased sub-paths**: ``orchestrator.model.*`` is checked against its
``orchestrator.student.model.*`` alias (and vice versa), so the
conflict fires regardless of which spelling the user wrote.
"""
if not isinstance(data, dict):
return data
def get(path: str) -> Any | None:
node: Any = data
for p in path.split("."):
if not isinstance(node, dict) or p not in node:
return None
node = node[p]
return node
def fill(path: str, value: Any) -> None:
parts = path.split(".")
if parts[0] not in data or not isinstance(data[parts[0]], dict):
return
node = data
for p in parts[:-1]:
if not isinstance(node, dict):
return
node = node.setdefault(p, {})
if isinstance(node, dict) and parts[-1] not in node:
node[parts[-1]] = value
conflicts: list[tuple[str, str]] = []
def propagate(shared_path: str, *targets: str, aliases: tuple[str, ...] = ()) -> None:
"""Verbatim shared → targets. Records overlap (incl. alias spellings)
into ``conflicts`` and fills each target if the shared value is set.
"""
value = get(shared_path)
if value is None:
return
for sub in (*targets, *aliases):
if get(sub) is not None:
conflicts.append((shared_path, sub))
for target in targets:
fill(target, value)
# [model] → trainer / orchestrator (student, via AliasChoices) / inference.
propagate(
"model.name",
"trainer.model.name",
"inference.model.name",
"orchestrator.model.name",
aliases=("orchestrator.student.model.name",),
)
propagate(
"model.vlm",
"trainer.model.vlm",
"inference.model.vlm",
"orchestrator.model.vlm",
aliases=("orchestrator.student.model.vlm",),
)
# [log]
propagate("log.level", "trainer.log.level", "orchestrator.log.level")
propagate("log.json_logging", "trainer.log.json_logging", "orchestrator.log.json_logging")
# [ckpt] leaves. (Bare empty ``[ckpt]`` block enablement is at the end.)
# ``orchestrator.ckpt`` has no ``output_dir`` field — trainer-only.
propagate("ckpt.output_dir", "trainer.ckpt.output_dir")
propagate("ckpt.interval", "trainer.ckpt.interval", "orchestrator.ckpt.interval")
propagate("ckpt.resume_step", "trainer.ckpt.resume_step", "orchestrator.ckpt.resume_step")
propagate("ckpt.keep_last", "trainer.ckpt.keep_last", "orchestrator.ckpt.keep_last")
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval", "orchestrator.ckpt.keep_interval")
# [wandb] leaves. (Bare empty ``[wandb]`` block enablement is at the end.)
propagate("wandb.project", "trainer.wandb.project", "orchestrator.wandb.project")
propagate("wandb.entity", "trainer.wandb.entity", "orchestrator.wandb.entity")
propagate("wandb.group", "trainer.wandb.group", "orchestrator.wandb.group")
propagate("wandb.tags", "trainer.wandb.tags", "orchestrator.wandb.tags")
propagate("wandb.offline", "trainer.wandb.offline", "orchestrator.wandb.offline")
# wandb.name: in non-shared mode the two sub-configs get distinct
# ``-trainer`` / ``-orchestrator`` suffixes so the W&B runs are
# distinguishable. ``OrchestratorConfig.auto_setup_prime_monitor_run_name``
# then defaults prime_monitor.run_name to the (unsuffixed) value.
wandb_name = get("wandb.name")
if wandb_name is not None:
for sub in ("trainer.wandb.name", "orchestrator.wandb.name"):
if get(sub) is not None:
conflicts.append(("wandb.name", sub))
non_shared = get("wandb.shared") is False
fill("trainer.wandb.name", f"{wandb_name}-trainer" if non_shared else wandb_name)
fill("orchestrator.wandb.name", f"{wandb_name}-orchestrator" if non_shared else wandb_name)
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
# differ between sub-configs (auto-derived from model names, which may
# differ for FP8-quantized inference variants).
propagate("tokenizer.name", "trainer.tokenizer.name", "orchestrator.tokenizer.name")
propagate(
"tokenizer.trust_remote_code",
"trainer.tokenizer.trust_remote_code",
"orchestrator.tokenizer.trust_remote_code",
)
propagate(
"tokenizer.chat_template",
"trainer.tokenizer.chat_template",
"orchestrator.tokenizer.chat_template",
"inference.model.chat_template",
)
# Top-level scalars.
propagate("max_steps", "trainer.max_steps", "orchestrator.max_steps")
propagate("max_async_level", "trainer.max_async_level", "orchestrator.max_async_level")
propagate("seq_len", "trainer.model.seq_len", "orchestrator.seq_len")
# output_dir: orchestrator gets a ``/run_default`` subdir so trainer +
# orchestrator nest under the same experiment root without colliding.
output_dir = get("output_dir")
if output_dir is not None:
for sub in ("trainer.output_dir", "orchestrator.output_dir"):
if get(sub) is not None:
conflicts.append(("output_dir", sub))
fill("trainer.output_dir", output_dir)
fill("orchestrator.output_dir", f"{output_dir}/run_default")
# Cascade trainer.tokenizer.chat_template → inference.model.chat_template
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
# propagation above so we cover both:
# - shared ``[tokenizer] chat_template`` (already filled all three above,
# this re-fill is a no-op via fill-if-absent), and
# - ``[trainer.tokenizer] chat_template`` set directly without shared
# (only path that reaches inference; ``validate_shared_tokenizer``
# would otherwise complain about the missing inference value).
trainer_chat_template = get("trainer.tokenizer.chat_template")
if trainer_chat_template is not None:
fill("inference.model.chat_template", trainer_chat_template)
# Bare ``[ckpt]`` / ``[wandb]`` block: presence-only signal that enables
# the section with defaults on both sub-configs. Necessary because
# ``trainer.ckpt`` / ``orchestrator.ckpt`` are Optional[None] by default —
# without this an empty shared block would be a no-op. Leaf-level
# conflicts (e.g. shared ``ckpt.interval`` vs ``trainer.ckpt.interval``)
# are already caught above; the bare block is exempt because
# ``[ckpt]`` + ``[trainer.ckpt] keep_last = 3`` is a legitimate
# "enable + customise per side" pattern.
for key in ("ckpt", "wandb"):
if get(key) is not None:
fill(f"trainer.{key}", {})
fill(f"orchestrator.{key}", {})
if conflicts:
lines = [
"Shared config conflicts with matching sub-config field(s). Pick one place "
"to set each value — duplicating it is ambiguous and the sub-config "
"would silently shadow any later shared-level override (e.g. on the CLI):",
]
for shared, sub in conflicts:
lines.append(f" - [{shared!r}] is set, but [{sub!r}] is also set")
raise ValueError("\n".join(lines))
return data
def validate_shared_ckpt_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.ckpt and not orchestrator.ckpt:
raise ValueError(
"Trainer checkpoint config is specified, but orchestrator checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
)
if orchestrator.ckpt and not trainer.ckpt:
raise ValueError(
"Orchestrator checkpoint config is specified, but trainer checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
)
if trainer.ckpt and orchestrator.ckpt and trainer.ckpt.interval != orchestrator.ckpt.interval:
raise ValueError(
f"Trainer checkpoint interval ({trainer.ckpt.interval}) and orchestrator checkpoint interval ({orchestrator.ckpt.interval}) are not the same. Please specify the same checkpoint interval for both."
)
if trainer.ckpt and orchestrator.ckpt and trainer.ckpt.resume_step != orchestrator.ckpt.resume_step:
raise ValueError(
f"Trainer checkpoint resume step ({trainer.ckpt.resume_step}) and orchestrator checkpoint resume step ({orchestrator.ckpt.resume_step}) are not the same. Please specify the same checkpoint resume step for both."
)
def validate_shared_model_name(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
# Orchestrator must match inference (it queries the inference server)
if inference is not None:
if inference.model.name != orchestrator.student.model.name:
raise ValueError(
f"Inference model name ({inference.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
return
if trainer.model.name != orchestrator.student.model.name:
raise ValueError(
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.student.model.name}) are not the same. Please specify the same model name for both."
)
def validate_shared_output_dir(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.output_dir != orchestrator.output_dir.parent:
raise ValueError(
f"Trainer outputs directory ({trainer.output_dir}) and orchestrator outputs directory parent ({orchestrator.output_dir.parent}) are not the same. Please specify the same outputs directory for both."
)
def validate_shared_wandb_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.wandb and not orchestrator.wandb:
raise ValueError(
"Trainer W&B config is specified, but orchestrator W&B config is not. "
"This means only trainer metrics will be logged. Please specify [orchestrator.wandb] to log orchestrator metrics as well, "
"or use [wandb] to configure both at once."
)
if orchestrator.wandb and not trainer.wandb:
raise ValueError(
"Orchestrator W&B config is specified, but trainer W&B config is not. "
"This means only orchestrator metrics will be logged. Please specify [trainer.wandb] to log trainer metrics as well, "
"or use [wandb] to configure both at once."
)
if trainer.wandb and orchestrator.wandb:
if trainer.wandb.project != orchestrator.wandb.project:
raise ValueError(
f"Trainer W&B project ({trainer.wandb.project}) and orchestrator W&B project ({orchestrator.wandb.project}) are not the same. Please specify the same W&B project for both."
)
def validate_shared_max_steps(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.max_steps != orchestrator.max_steps:
raise ValueError(
f"Trainer max steps ({trainer.max_steps}) and orchestrator max steps ({orchestrator.max_steps}) are not the same. Please specify the same max steps for both."
)
def validate_shared_max_async_level(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.max_async_level != orchestrator.max_async_level:
raise ValueError(
f"Trainer max async level ({trainer.max_async_level}) and orchestrator max async level ({orchestrator.max_async_level}) are not the same. Please specify the same max async level for both."
)
def validate_shared_seq_len(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.model.seq_len < orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({trainer.model.seq_len}) must be >= orchestrator seq_len ({orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
def validate_shared_tokenizer(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
# Validate chat_template is consistent across all components.
# We only check chat_template (not name/trust_remote_code) because those
# are auto-derived from model names which may legitimately differ (e.g.
# when inference uses an FP8 quantized variant of the same model).
if trainer.tokenizer.chat_template != orchestrator.tokenizer.chat_template:
raise ValueError(
f"Trainer chat_template ({trainer.tokenizer.chat_template!r}) and orchestrator "
f"chat_template ({orchestrator.tokenizer.chat_template!r}) do not match. "
f"Use the shared [tokenizer] config to set chat_template for both."
)
if inference is not None:
if trainer.tokenizer.chat_template != inference.model.chat_template:
raise ValueError(
f"Inference chat_template ({inference.model.chat_template!r}) does not match "
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
f"Use the shared [tokenizer] config to set chat_template for all components."
)
def validate_shared_weight_broadcast(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
if (
inference
and trainer.weight_broadcast.type != orchestrator.weight_broadcast.type != inference.weight_broadcast.type
):
raise ValueError(
f"Inference weight broadcast type ({inference.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
elif trainer.weight_broadcast.type != orchestrator.weight_broadcast.type:
raise ValueError(
f"Trainer weight broadcast type ({trainer.weight_broadcast.type}) and orchestrator weight broadcast type ({orchestrator.weight_broadcast.type}) are not the same. Please specify the same weight broadcast type for both."
)
+129 -68
View File
@@ -1,28 +1,27 @@
[project]
name = "prime-rl"
version = "0.4.0"
version = "0.5.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"prime-rl-configs",
"beartype>=0.21.0",
"datasets>=4.0.0",
"jaxtyping>=0.3.2",
"liger-kernel>=0.5.10",
"loguru>=0.7.3",
"pyarrow>=21.0.0",
"pydantic>=1.10.13",
"pydantic-config",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"numpy>=2.2.6",
"torch>=2.9.0",
"torchvision",
"torchaudio",
"torchdata>=0.11.0",
"transformers",
"vllm>=0.19.0",
"vllm>=0.21.0",
"wandb>=0.26.1",
"ring-flash-attn>=0.1.8",
"prime>=0.5.73",
"prime>=0.6.4",
"pyzmq>=27.1.0",
"aiolimiter>=1.2.1",
"tenacity>=8.2.0",
@@ -32,18 +31,20 @@ dependencies = [
"uvloop>=0.21.0",
"torchtitan",
"verifiers",
"renderers",
"dion",
"tilelang>=0.1.8",
"flash-linear-attention",
"nvidia-ml-py>=12.575.51",
"pybase64>=1.4.2",
]
[project.scripts]
rl = "prime_rl.entrypoints.rl:main"
sft = "prime_rl.entrypoints.sft:main"
inference = "prime_rl.entrypoints.inference:main"
trainer = "prime_rl.trainer.rl.train:main"
orchestrator = "prime_rl.orchestrator.orchestrator:main"
trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
env-server = "prime_rl.orchestrator.env_server.env_server:main"
[project.entry-points."vllm.general_plugins"]
@@ -51,7 +52,7 @@ prime_rl = "prime_rl.inference.patches:transformers_v5_compat"
[project.optional-dependencies]
flash-attn = [
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.16/flash_attn-2.8.3+cu128torch2.10-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
"flash-attn @ https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.4/flash_attn-2.8.3+cu128torch2.11-cp312-cp312-linux_x86_64.whl ; platform_machine == 'x86_64'",
]
flash-attn-3 = ["flash_attn_3"]
@@ -59,20 +60,33 @@ flash-attn-cute = [
"flash-attn-4",
]
envs = [
"reverse-text",
"alphabet-sort",
"wiki-search",
"math-python",
"math-env",
"code-env",
"science-env",
"logic-env",
"color-codeword",
"math500",
"aime2024",
"aime2025",
"mini_swe_agent_plus",
"deepdive"
"alphabet-sort",
"code-env",
"color-codeword",
"deepdive",
"gpqa",
"hle",
"ifeval",
"livecodebench",
"logic-env",
"math-env",
"math-python",
"math500",
"mini-swe-agent-plus",
"mini-swe-agent-plus-rlm",
"mmlu-pro",
"opencode-cp",
"opencode-deepdive",
"opencode-math",
"opencode-science",
"opencode-swe",
"reverse-text",
"science-env",
"simpleqa-verified",
"tau2-bench",
"wiki-search",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -85,7 +99,7 @@ gpt-oss = [
"kernels",
]
quack = [
"quack-kernels>=0.3.3",
"quack-kernels>=0.4.1",
]
all = [
"prime-rl[flash-attn]",
@@ -108,6 +122,41 @@ dev = [
]
[tool.uv.workspace]
members = [
"packages/prime-rl-configs",
"deps/pydantic-config",
"deps/verifiers",
"deps/renderers",
"deps/verifiers/environments/alphabet_sort",
"deps/verifiers/environments/math_python",
"deps/verifiers/environments/reverse_text",
"deps/verifiers/environments/wiki_search",
"deps/research-environments/environments/aime2024",
"deps/research-environments/environments/aime2025",
"deps/research-environments/environments/code_env",
"deps/research-environments/environments/color_codeword",
"deps/research-environments/environments/deepdive",
"deps/research-environments/environments/gpqa",
"deps/research-environments/environments/hle",
"deps/research-environments/environments/ifeval",
"deps/research-environments/environments/livecodebench",
"deps/research-environments/environments/logic_env",
"deps/research-environments/environments/math500",
"deps/research-environments/environments/math_env",
"deps/research-environments/environments/mini_swe_agent_plus",
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
"deps/research-environments/environments/mmlu_pro",
"deps/research-environments/environments/opencode_cp",
"deps/research-environments/environments/opencode_deepdive",
"deps/research-environments/environments/opencode_math",
"deps/research-environments/environments/opencode_science",
"deps/research-environments/environments/opencode_swe",
"deps/research-environments/environments/science_env",
"deps/research-environments/environments/simpleqa_verified",
"deps/research-environments/environments/tau2_bench",
]
[tool.uv]
exclude-newer = "7 days"
preview = true
@@ -122,67 +171,75 @@ override-dependencies = [
"nvidia-cudnn-cu12>=9.15",
"nvidia-cutlass-dsl>=4.4.1",
"transformers>=5.1.0.dev0",
"torch>=2.9.0",
"openenv-core",
]
[tool.uv.exclude-newer-package]
# pytorch-cu128 / pytorch-cu128-test indexes don't publish upload dates
torch = false
# we want latest vllm, remove next patch
vllm = false
tokenspeed-mla = false
fastokens = false
flash_attn_3 = false
# Self-vendored packages on our primeintellect index
reverse-text = false
alphabet-sort = false
wiki-search = false
math-python = false
math-env = false
code-env = false
science-env = false
logic-env = false
color-codeword = false
math500 = false
aime2024 = false
aime2025 = false
deepdive = false
mini_swe_agent_plus = false
# PrimeIntellect-published on PyPI (trusted publisher)
prime = false
prime-sandboxes = false
prime-tunnel = false
prime-evals = false
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
verifiers = false
vllm-router = false
dion = false
pydantic-config = false
deep-ep = false
deep-gemm = false
nixl-cu12 = false
[tool.uv.sources]
prime-rl-configs = { workspace = true }
verifiers = { workspace = true }
renderers = { workspace = true }
aime2024 = { workspace = true }
aime2025 = { workspace = true }
alphabet-sort = { workspace = true }
code-env = { workspace = true }
color-codeword = { workspace = true }
deepdive = { workspace = true }
gpqa = { workspace = true }
hle = { workspace = true }
ifeval = { workspace = true }
livecodebench = { workspace = true }
logic-env = { workspace = true }
math-env = { workspace = true }
math-python = { workspace = true }
math500 = { workspace = true }
mini-swe-agent-plus = { workspace = true }
mini-swe-agent-plus-rlm = { workspace = true }
mmlu-pro = { workspace = true }
opencode-cp = { workspace = true }
opencode-deepdive = { workspace = true }
opencode-math = { workspace = true }
opencode-science = { workspace = true }
opencode-swe = { workspace = true }
reverse-text = { workspace = true }
science-env = { workspace = true }
simpleqa-verified = { workspace = true }
tau2-bench = { workspace = true }
wiki-search = { workspace = true }
torch = { index = "pytorch-cu128" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "3b77145" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "a1fdd7e" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
pydantic-config = { git = "https://github.com/samsja/pydantic_config.git", branch = "main" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.22/vllm_router-0.1.22-cp38-abi3-manylinux_2_28_x86_64.whl" }
reverse-text = { index = "primeintellect" }
alphabet-sort = { index = "primeintellect" }
wiki-search = { index = "primeintellect" }
math-python = { index = "primeintellect" }
math-env = { index = "primeintellect" }
code-env = { index = "primeintellect" }
science-env = { index = "primeintellect" }
logic-env = { index = "primeintellect" }
color-codeword = { index = "primeintellect" }
math500 = { index = "primeintellect" }
aime2024 = { index = "primeintellect" }
aime2025 = { index = "primeintellect" }
deepdive = { index = "primeintellect" }
mini_swe_agent_plus = { index = "primeintellect" }
deep-ep = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/deep_ep-1.2.1+73b6ea4-cp312-cp312-linux_x86_64.whl" }
deep-gemm = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/deep_gemm-2.3.0+477618c-cp312-cp312-linux_x86_64.whl" }
nixl-cu12 = { url = "https://github.com/samsja/research-pre-built-wheels/releases/download/v0.2/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
prime-pydantic-config = { workspace = true }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_24_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
flash_attn_3 = { index = "pytorch-cu128-test" }
@@ -194,17 +251,11 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
[[tool.uv.index]]
name = "primeintellect"
url = "https://hub.primeintellect.ai/primeintellect/simple/"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/cu128"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128-test"
url = "https://download.pytorch.org/whl/test/cu128"
@@ -214,8 +265,15 @@ explicit = true
select = ["F", "I"]
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
[tool.ruff.lint.isort]
# `prime_rl` is split across two workspace wheels (prime-rl + prime-rl-configs).
# Without this, ruff classifies prime_rl.configs.* as third-party because it
# doesn't live under src/.
known-first-party = ["prime_rl"]
[tool.ruff]
line-length = 120
extend-exclude = ["deps"]
[tool.pytest.ini_options]
addopts = "--strict-markers"
@@ -228,5 +286,8 @@ markers = [
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["src/prime_rl"]
[tool.hatch.metadata]
allow-direct-references = true
-6
View File
@@ -15,9 +15,3 @@ export FLASH_ATTENTION_SKIP_CUDA_BUILD=FALSE
echo "=== reinstalling flash-attn-cute (flash-attn overwrites it with a stub) ==="
uv pip install --reinstall --no-deps \
"flash-attn-4 @ git+https://github.com/Dao-AILab/flash-attention.git@96bd151#subdirectory=flash_attn/cute"
# TODO: remove once flash-attn gates the ampere_helpers import or cutlass-dsl re-adds it.
echo "=== copying ampere_helpers.py from flashinfer vendor ==="
SITE_PACKAGES=".venv/lib/python3.12/site-packages"
cp "$SITE_PACKAGES/flashinfer/data/cutlass/python/CuTeDSL/cutlass/utils/ampere_helpers.py" \
"$SITE_PACKAGES/nvidia_cutlass_dsl/python_packages/cutlass/utils/ampere_helpers.py"
+115 -53
View File
@@ -4,86 +4,148 @@ set -euo pipefail
# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
REPO_ID="prime-rl"
# Flag defaults (can be overridden via env)
SKIP_CLONE=${SKIP_CLONE:-0}
assert_supported_platform() {
local os arch
os="$(uname -s)"
arch="$(uname -m)"
if [ "$os" != "Linux" ]; then
log_error "Unsupported platform: ${os}/${arch}."
log_error "prime-rl currently supports Linux on x86_64 or aarch64 only."
exit 1
fi
case "$arch" in
x86_64 | aarch64) ;;
*)
log_error "Unsupported architecture: ${arch}."
log_error "prime-rl currently supports Linux on x86_64 or aarch64 only."
exit 1
;;
esac
if ! command -v apt &>/dev/null; then
log_error "Unsupported Linux distribution: apt is required by this installer."
log_error "Use a Debian/Ubuntu-based Linux machine on x86_64 or aarch64, or install manually."
exit 1
fi
}
has_ssh_access() {
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
# We try a quick ls-remote to avoid cloning on failure.
# Disable -e for the probe so the script doesn't exit on a failed test.
set +e
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
rc=$?
set -e
return $rc
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
# We try a quick ls-remote to avoid cloning on failure.
# Disable -e for the probe so the script doesn't exit on a failed test.
set +e
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
rc=$?
set -e
return $rc
}
ensure_known_hosts() {
# Make sure ~/.ssh exists with the right perms, then add GitHub host key.
mkdir -p "${HOME}/.ssh"
chmod 700 "${HOME}/.ssh"
# Use -H to hash hostnames; merge uniquely to avoid dupes.
if command -v ssh-keyscan >/dev/null 2>&1; then
ssh-keyscan -H github.com 2>/dev/null | sort -u \
| tee -a "${HOME}/.ssh/known_hosts" >/dev/null
# Make sure ~/.ssh exists with the right perms, then add GitHub host key.
mkdir -p "${HOME}/.ssh"
chmod 700 "${HOME}/.ssh"
# Use -H to hash hostnames; merge uniquely to avoid dupes.
if command -v ssh-keyscan >/dev/null 2>&1; then
ssh-keyscan -H github.com 2>/dev/null | sort -u |
tee -a "${HOME}/.ssh/known_hosts" >/dev/null
chmod 600 "${HOME}/.ssh/known_hosts"
fi
}
# Initialize each submodule independently so that a missing private repo
# (e.g. configs/private when the user lacks access) does not abort the install.
init_submodules() {
if [ ! -f .gitmodules ]; then
return 0
fi
local paths failures
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
failures=()
for path in $paths; do
log_info "Initializing submodule: ${path}"
if git submodule update --init --recursive -- "$path"; then
:
else
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
failures+=("$path")
fi
done
if [ "${#failures[@]}" -gt 0 ]; then
log_warn "Skipped submodules: ${failures[*]}"
fi
}
main() {
# Ensure sudo exists
if ! command -v sudo &>/dev/null; then
apt update
apt install -y sudo
fi
assert_supported_platform
log_info "Installing base packages..."
sudo apt update && sudo apt install -y build-essential openssh-client curl git tmux htop nvtop
# Ensure sudo exists
if ! command -v sudo &>/dev/null; then
apt update
apt install -y sudo
fi
log_info "Configuring SSH known_hosts for GitHub..."
ensure_known_hosts
log_info "Installing base packages..."
sudo apt update
sudo apt install -y build-essential openssh-client curl git tmux htop nvtop
if [ "$SKIP_CLONE" -eq 1 ]; then
log_info "Skipping clone; assuming we are already inside the repo."
log_info "Configuring SSH known_hosts for GitHub..."
ensure_known_hosts
if [ "$SKIP_CLONE" -eq 1 ]; then
log_info "Skipping clone; assuming we are already inside the repo."
else
log_info "Determining best way to clone (SSH vs HTTPS)..."
if has_ssh_access; then
log_info "SSH access to GitHub works. Cloning via SSH."
git clone git@github.com:PrimeIntellect-ai/${REPO_ID}.git
else
log_info "Determining best way to clone (SSH vs HTTPS)..."
if has_ssh_access; then
log_info "SSH access to GitHub works. Cloning via SSH."
git clone git@github.com:PrimeIntellect-ai/${REPO_ID}.git
else
log_warn "SSH auth to GitHub not available. Cloning via HTTPS."
git clone https://github.com/PrimeIntellect-ai/${REPO_ID}.git
fi
log_info "Entering project directory..."
cd ${REPO_ID}
log_warn "SSH auth to GitHub not available. Cloning via HTTPS."
git clone https://github.com/PrimeIntellect-ai/${REPO_ID}.git
fi
log_info "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh
log_info "Entering project directory..."
cd ${REPO_ID}
fi
log_info "Sourcing uv environment..."
if ! command -v uv &> /dev/null; then
source $HOME/.local/bin/env
fi
if ! has_ssh_access; then
git config url."https://github.com/".insteadOf "git@github.com:"
fi
log_info "Installing prime..."
uv tool install prime
log_info "Initializing submodules..."
init_submodules
log_info "Syncing virtual environment..."
uv sync --all-extras
log_info "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh
log_info "Installing pre-commit hooks..."
uv run pre-commit install
log_info "Sourcing uv environment..."
if ! command -v uv &>/dev/null; then
source $HOME/.local/bin/env
fi
log_info "Installation completed!"
log_info "Installing prime..."
uv tool install prime
log_info "Syncing virtual environment..."
uv sync --all-extras
log_info "Installing pre-commit hooks..."
uv run pre-commit install
log_info "Installation completed!"
}
main
main
+11 -5
View File
@@ -1,14 +1,20 @@
#!/usr/bin/env bash
# Build and install DeepGEMM from source for FP8 MoE inference.
# Build and install DeepGEMM from source for FP8 MoE inference + FP8 training.
#
# Pinned to d30fc36 — the commit our FP8 grouped-GEMM training path requires
# (newer than the 477618c that vLLM 0.17/0.19 used). The matching prebuilt
# wheel lives at tools/wheels/deep_gemm-2.3.0+d30fc36-cp312-cp312-linux_x86_64.whl
# and is what `pyproject.toml` consumes by default; this script is for
# rebuilding when torch / CUDA / vllm bumps invalidate that wheel.
#
# Uses the commit recommended by vLLM for compatibility with vLLM 0.17+.
# Requires CUDA 12.8+ and a Hopper/Blackwell GPU.
#
# Usage:
# bash scripts/install_deep_gemm.sh
# bash scripts/install_deep_gemm.sh # build + install in-place
# bash scripts/install_deep_gemm.sh --wheel-dir tools/wheels # build wheel only
#
# Options:
# --ref REF DeepGEMM commit hash (default: 477618c)
# --ref REF DeepGEMM commit hash (default: d30fc36)
# --wheel-dir DIR Output wheel to DIR instead of installing
set -euo pipefail
@@ -17,7 +23,7 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
DEEPGEMM_GIT_REPO="https://github.com/deepseek-ai/DeepGEMM.git"
DEEPGEMM_GIT_REF="477618cd51baffca09c4b0b87e97c03fe827ef03"
DEEPGEMM_GIT_REF="d30fc36c8f229f4f873b90a492f6e19e6e610923"
WHEEL_DIR=""
while [[ $# -gt 0 ]]; do
+55
View File
@@ -23,6 +23,8 @@ from transformers.models.qwen3_5_moe.modeling_qwen3_5_moe import (
from prime_rl.trainer.models.glm4_moe import Glm4MoeConfig
from prime_rl.trainer.models.glm4_moe import Glm4MoeForCausalLM as PrimeRLGlm4MoeForCausalLM
from prime_rl.trainer.models.laguna import LagunaConfig
from prime_rl.trainer.models.laguna import LagunaForCausalLM as PrimeRLLagunaForCausalLM
from prime_rl.trainer.models.layers.lm_head import inject_prime_lm_head
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2ForCausalLM as PrimeRLMiniMaxM2ForCausalLM
@@ -130,6 +132,59 @@ ARCH_PRESETS = {
"prime_model_class": PrimeRLMiniMaxM2ForCausalLM,
"tokenizer_source": "MiniMaxAI/MiniMax-M2.1",
},
"laguna": {
"config_class": LagunaConfig,
"config_kwargs": dict(
vocab_size=100352,
hidden_size=512,
intermediate_size=2048,
num_hidden_layers=12,
num_attention_heads=8,
num_attention_heads_per_layer=[8] * 12,
num_key_value_heads=4,
head_dim=64,
hidden_act="silu",
max_position_embeddings=4096,
rms_norm_eps=1e-6,
rope_parameters={
"full_attention": {
"rope_type": "yarn",
"rope_theta": 500000.0,
"factor": 4.0,
"original_max_position_embeddings": 1024,
"beta_slow": 1.0,
"beta_fast": 64.0,
"attention_factor": 1.0,
"partial_rotary_factor": 0.5,
},
"sliding_attention": {
"rope_type": "default",
"rope_theta": 10000.0,
"partial_rotary_factor": 1.0,
},
},
layer_types=["full_attention", "sliding_attention", "sliding_attention", "sliding_attention"] * 3,
sliding_window=512,
moe_intermediate_size=128,
shared_expert_intermediate_size=128,
num_experts=8,
num_experts_per_tok=4,
mlp_layer_types=["dense"] + ["sparse"] * 11,
moe_routed_scaling_factor=2.5,
use_grouped_mm=False,
pad_token_id=9,
bos_token_id=2,
eos_token_id=[2, 24],
auto_map={
"AutoConfig": "poolside/Laguna-XS.2--configuration_laguna.LagunaConfig",
"AutoModel": "poolside/Laguna-XS.2--modeling_laguna.LagunaModel",
"AutoModelForCausalLM": "poolside/Laguna-XS.2--modeling_laguna.LagunaForCausalLM",
},
),
"hf_model_class": None, # uses Poolside remote modeling code
"prime_model_class": PrimeRLLagunaForCausalLM,
"tokenizer_source": "poolside/Laguna-XS.2",
},
"qwen3_5_moe_vlm": {
"config_fn": _qwen3_5_moe_vlm_config,
"hf_model_class": HFQwen3_5MoeVLM,
-180
View File
@@ -1,180 +0,0 @@
---
name: config
description: How the prime-rl config system works — TOML files, CLI, config composition, and special patterns. Use when creating configs, debugging config errors, or overriding values via CLI.
---
# Config
prime-rl uses `pydantic_config` (combines `tyro` and `pydantic`) for configuration.
## Use configs
Every entrypoint accepts TOML files via `@` syntax and CLI overrides to configure it.
```bash
# Configure RL training with a TOML file
uv run rl @ examples/reverse_text/rl.toml
# Override specific fields via CLI
uv run rl @ examples/reverse_text/rl.toml --max-steps 50
```
Config resolve in the following order:
1. CLI arguments
2. Config files (merged left-to-right)
3. Class defaults (lowest)
## Compose configs
Multiple config files are merged left-to-right (later files override earlier ones):
```bash
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
```
Nested configs can be loaded for specific sections:
```bash
uv run rl --model @ model.toml --data @ data.toml
```
Mixed composition works too:
```bash
uv run rl @ base.toml --trainer @ trainer_override.toml --trainer.lr 1e-3
```
Merging is deep — unset fields in the override are preserved from the base config.
## Inspect & validate configs
Use `--help` to see all available fields and their defaults. When combined with a config file, defaults reflect the TOML values:
```bash
uv run rl --help # shows class defaults
uv run rl @ examples/reverse_text/rl.toml --help # shows defaults from TOML
```
Use `--dry-run` to validate and dump the fully resolved config:
```bash
uv run rl @ examples/reverse_text/rl.toml --dry-run --output-dir /tmp/test
# Writes resolved TOML to /tmp/test/configs
```
## Naming
CLI uses kebab-case (`--model.max-model-len`), TOML uses snake_case (`max_model_len`). Both refer to the same field.
## General rules
- **Fail early**: incompatible option combinations (e.g. CP requires flash attention, NCCL broadcast requires async level 1) should raise in `model_validator` at config resolution time, not at runtime. When adding new constraints, add a validator to the config class.
- **Deprecation**: when renaming or removing config fields, emit a deprecation warning with a clear migration path (e.g. "field X is deprecated, use Y instead"). Do not silently drop fields — help users update their configs.
## Important patterns
### Boolean fields
```bash
uv run inference --model.enforce-eager # sets to true
uv run inference --model.no-enforce-eager # sets to false
```
In TOML, booleans must be explicit:
```toml
[model]
enforce_eager = true
```
### None fields
TOML has no null type. Use the string `"None"`:
```toml
max_model_len = "None"
```
On the CLI, pass `None` as a plain string:
```bash
uv run inference --model.max-model-len None
```
### List fields
In TOML, use `[[double brackets]]` (array of tables) for lists of objects:
```toml
[[orchestrator.env]]
id = "reverse-text"
[[orchestrator.env]]
id = "math-env"
```
On the CLI, list items are indexed: `--env.0.id reverse-text --env.1.id math-env`.
### Dict fields
In TOML, use a section:
```toml
[vllm_extra]
key1 = "value1"
key2 = 123
```
On the CLI, pass as a JSON string:
```bash
uv run inference --vllm-extra '{"key1": "value1", "key2": 123}'
```
### Discriminated unions
Some config fields use discriminated unions (e.g. loss type, data type). Set the `type` field to select the variant:
```toml
[trainer.loss]
type = "sft"
[data]
type = "fake"
batch_size = 2
```
On the CLI:
```bash
uv run sft --data.type fake --data.batch-size 4
```
If you wish to configure values of the default variant, you don't need to set the `type` field.
### SFT hard distill override
For hosted multi-tenant runs where the trainer image's `trainer.loss.type` is fixed, the orchestrator exposes a per-run override that forces SFT loss on every micro-batch without rebuilding the trainer. Set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; both must be configured together (the orchestrator validator enforces this). The orchestrator stamps each `TrainingSample.sft_loss = True`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch — independent of the trainer's configured default loss.
### Model fields
For `BaseModel | None` fields (like `[ckpt]`, `[wandb]`, `[compile]`), a bare flag enables them with defaults:
```bash
uv run rl @ config.toml --model.compile # enables compilation with defaults (fullgraph = false)
uv run rl @ config.toml --model.compile.fullgraph # enables compilation and sets nested field (fullgraph = true)
```
In TOML, an empty section header does the same:
```toml
[ckpt] # enables checkpointing with defaults
```
## Key files
- `src/prime_rl/utils/config.py` — re-exports `BaseConfig` and `cli` from pydantic_config
- `src/prime_rl/configs/` — all domain-specific config classes
- `configs/debug/` — minimal debug configs for testing
- `examples/` — full example configs for various tasks
+78
View File
@@ -0,0 +1,78 @@
---
name: configs
description: How the prime-rl config system works — TOML files, CLI overrides, composition, and special patterns. Use when creating configs, debugging config errors, or overriding values via CLI.
---
# Configs
prime-rl uses [`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config) — a Pydantic-based TOML + CLI config system (no tyro). Every entrypoint accepts TOML files via `@` and CLI overrides.
## Loading and composition
```bash
uv run rl @ examples/reverse_text/rl.toml # single TOML
uv run rl @ examples/reverse_text/rl.toml --max-steps 50 # CLI override
uv run rl @ base.toml @ overlay.toml # left-to-right merge
uv run rl --model @ model.toml --data @ data.toml # nested section files
uv run rl @ base.toml --trainer @ trainer.toml --trainer.lr 1e-3 # mixed
```
Resolution order: CLI > config files (left-to-right) > class defaults. Merging is deep — unset fields in an overlay are preserved from the base.
Naming: CLI uses kebab-case (`--model.max-model-len`); TOML uses snake_case (`max_model_len`).
## Inspect & validate
```bash
uv run rl --help # all fields and defaults
uv run rl @ rl.toml --dry-run --output-dir /tmp/x # write resolved TOML to /tmp/x/configs
```
## Validators
Incompatible combinations (e.g. CP requires flash attention) must raise in a `model_validator` at resolve time, not at runtime. When renaming a field, emit a deprecation warning with a migration hint — never silently drop.
## Special syntax
**Booleans** — CLI `--flag` / `--no-flag`; TOML must be explicit (`enforce_eager = true`).
**None** — TOML has no null, use the string `"None"` (`max_model_len = "None"`); CLI: `--model.max-model-len None`.
**Lists** — TOML uses array of tables; later config files replace lists wholesale, so overlays must include the full desired list:
```toml
[[orchestrator.env]]
id = "reverse-text"
```
CLI: `--env.0.id reverse-text --env.1.id math-env`.
**Dicts** — TOML uses a section; CLI takes a JSON string: `--vllm-extra '{"key1": "value1"}'`.
**Discriminated unions** — set the `type` field to pick the variant (`[trainer.loss] type = "sft"`). Omit `type` to keep the default variant.
**`BaseModel | None` fields** — bare flag enables defaults; nested override enables and sets:
```bash
--model.compile # enables compile with defaults
--model.compile.fullgraph # enables and sets fullgraph=true
```
In TOML, an empty section header (`[ckpt]`) does the same.
## RL trainer token exports
For rollout debugging, enable trainer-side token export under `trainer.experimental.token_export` (or `experimental.token_export` when running the trainer entrypoint directly). It writes one JSONL record per exported sequence under `output_dir/token_exports/step_<step>/rank_<rank>.jsonl`. Each record stores aligned per-token arrays for token ids, loss mask, advantage, reward, entropy, mismatch KL, inference/trainer logprobs, importance ratios, probability deltas, and masking diagnostics. It does not decode token text in the trainer.
```toml
[trainer.experimental.token_export]
```
Leave it unset for normal training. When enabled, it exports every sequence from each exporting rank.
## Key files
- `packages/prime-rl-configs/src/prime_rl/` — config classes under `configs/`; `utils/config.py` re-exports `BaseConfig` and `cli`
- `configs/debug/` — minimal debug configs
- `configs/private/` — private configs submodule (internal)
- `examples/` — full example configs
-91
View File
@@ -1,91 +0,0 @@
---
name: entrypoints
description: All available prime-rl entrypoints — what they do, how to launch them, and which config class they use. Use when running commands, launching training, or starting servers.
---
# Entrypoints
All entrypoints are run via `uv run <command>` and accept TOML configs via `@ path/to/config.toml` with CLI overrides. See the `config` skill for config system details.
## `rl` — RL training
Orchestrates the complete RL loop: launches inference server, orchestrator, and trainer as subprocesses.
```bash
uv run rl @ examples/reverse_text/rl.toml
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml # with SLURM
uv run rl @ examples/reverse_text/rl.toml --dry-run # generate scripts without running
```
- **Config:** `RLConfig` (`src/prime_rl/configs/rl.py`)
- **Entrypoint:** `src/prime_rl/entrypoints/rl.py`
- **SLURM:** yes — single-node and multi-node
## `sft` — SFT training
Trains a model on labeled data. Uses torchrun for distributed training.
```bash
uv run sft @ examples/reverse_text/sft.toml
uv run sft @ examples/reverse_text/sft.toml --slurm # with SLURM
uv run sft @ examples/reverse_text/sft.toml --dry-run # generate scripts without running
```
The entrypoint launches torchrun internally — no need to call torchrun directly.
- **Config:** `SFTConfig` (`src/prime_rl/configs/sft.py`)
- **Entrypoint:** `src/prime_rl/entrypoints/sft.py`
- **SLURM:** yes — single-node and multi-node
## `inference` — Standalone inference server
Launches a vLLM-based inference server with OpenAI-compatible API.
```bash
uv run inference @ configs/debug/infer.toml
uv run inference --model.name Qwen/Qwen3-0.6B --model.enforce-eager
```
Always use the `inference` entrypoint — never `vllm serve` directly.
Custom endpoints beyond standard OpenAI API:
- `/v1/chat/completions/tokens` — accepts token IDs as prompt input
- `/update_weights` — hot-reload model weights from the trainer
- `/load_lora_adapter` — load LoRA adapters at runtime
- `/init_broadcaster` — initialize weight broadcast for distributed training
Check health with:
```bash
curl http://<ip>:<port>/health
```
Check served models with:
```bash
curl http://<ip>:<port>/v1/models
```
Test chat completions with:
```bash
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hi"}], "max_tokens": 50}'
```
- **Config:** `InferenceConfig` (`src/prime_rl/configs/inference.py`)
- **Entrypoint:** `src/prime_rl/entrypoints/inference.py`
- **SLURM:** yes — single-node, multi-node, and disaggregated deployments
## Summary
| Command | Purpose | SLURM | Typical use |
|---------|---------|-------|-------------|
| `rl` | Full RL pipeline | yes | Production RL training |
| `sft` | Supervised fine-tuning | yes | SFT training |
| `inference` | vLLM server | yes | Standalone inference or debugging |
## Key directories
- `src/prime_rl/entrypoints/` — top-level entrypoints (`rl`, `sft`, `inference`)
- `src/prime_rl/configs/` — all config classes
- `configs/debug/` — minimal configs for quick testing
- `examples/` — full example configs for various tasks
+69
View File
@@ -0,0 +1,69 @@
---
name: install
description: How to install prime-rl and its optional dependencies. Use when setting up the project, installing extras like deep-gemm for FP8 models, or troubleshooting dependency issues.
---
# Install
## Clone + submodules
prime-rl is a monorepo with submodules. Use the install script when bootstrapping a fresh machine:
```bash
bash scripts/install.sh # clones, inits submodules, installs uv, runs `uv sync --all-extras`
```
For an existing clone, init submodules explicitly:
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
```
Do **not** run `git submodule update --init --recursive` without paths — it tries to clone the private `configs/private` submodule and aborts for users without access. `scripts/install.sh` walks submodules one at a time and skips failures, so it works for everyone.
## Sync
```bash
uv sync # core only
uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
```
The `envs` extra installs every env workspace listed in `[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and `[tool.uv.sources]`.
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
## Optional extras
### NemotronH (Mamba SSD kernels)
```bash
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
```
Requires `nvcc`. Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch SSD path, which computes softplus in bf16 and yields ~0.4 KL divergence vs vLLM. Do **not** install `causal-conv1d` unless your GPU arch matches the prebuilt kernels — the code falls back to `nn.Conv1d` when it's absent.
### FP8 inference (GLM-5-FP8, etc.)
```bash
uv sync --group fp8-inference # installs the prebuilt deep-gemm wheel
```
### Trainer DeepEP backend
`scripts/install_ep_kernels.sh` auto-detects the CUDA toolkit matching torch and the GPU arch, builds NVSHMEM + DeepEP from source, and skips if `deep_ep` already imports.
```bash
bash scripts/install_ep_kernels.sh
```
Flags: `--workspace DIR`, `--deepep-ref REF` (default `73b6ea4`), `--nvshmem-ver VER` (default `3.3.24`), `--configure-drivers` (multi-node IBGDA; needs sudo + reboot).
Verify: `uv run python -c 'import deep_ep; print(deep_ep.__file__)'`.
## Key files
- `pyproject.toml` — dependencies, extras, dependency groups
- `uv.lock` — pinned lockfile (refresh with `uv sync --all-extras`)
- `scripts/install.sh` — bootstrap installer
- `scripts/install_ep_kernels.sh` — DeepEP build script
-73
View File
@@ -1,73 +0,0 @@
---
name: installation
description: How to install prime-rl and its optional dependencies. Use when setting up the project, installing extras like deep-gemm for FP8 models, or troubleshooting dependency issues.
---
# Installation
## Basic
```bash
uv sync # core dependencies only
uv sync --group dev # dev tools: pytest, ruff, pre-commit
uv sync --all-extras # recommended: includes flash-attn, flash-attn-cute, etc.
```
## Advanced
### Mamba-SSM (NemotronH models)
For NemotronH (hybrid Mamba-Transformer-MoE) models, install `mamba-ssm` for Triton-based SSD kernels that match vLLM's precision:
```bash
CUDA_HOME=/usr/local/cuda uv pip install mamba-ssm
```
Requires `nvcc` (CUDA toolkit). Without `mamba-ssm`, NemotronH falls back to HF's pure-PyTorch implementation which computes softplus in bf16, causing ~0.4 KL divergence vs vLLM.
Note: do NOT install `causal-conv1d` unless your GPU architecture matches the compiled CUDA kernels. The code automatically falls back to PyTorch nn.Conv1d when it's absent.
### FP8 inference with deep-gemm
For certain models like GLM-5-FP8, you need `deep-gemm`. Install it via the `fp8-inference` dependency group:
```bash
uv sync --group fp8-inference
```
This installs the pre-built `deep-gemm` wheel. No CUDA build step is needed.
## Trainer DeepEP backend
The trainer-side MoE `deepep` backend is optional and requires a local DeepEP build.
Install using the provided script, which auto-detects CUDA toolkit and GPU architecture:
```bash
bash scripts/install_ep_kernels.sh
```
The script downloads NVSHMEM, builds DeepEP from source, and places the wheel in `deps/`. It skips if DeepEP is already installed. Options:
- `--workspace DIR` — build directory (default: `./ep_kernels_workspace`)
- `--deepep-ref REF` — DeepEP commit hash (default: `73b6ea4`)
- `--nvshmem-ver VER` — NVSHMEM version (default: `3.3.24`)
- `--configure-drivers` — configure IBGDA drivers for multi-node (requires sudo + reboot)
Verify the install:
```bash
uv run python -c 'import deep_ep; print(deep_ep.__file__)'
```
## Dev dependencies
```bash
uv sync --group dev
```
Installs pytest, ruff, pre-commit, and other development tools.
## Key files
- `pyproject.toml` — all dependencies, extras, and dependency groups
- `uv.lock` — pinned lockfile (update with `uv sync --all-extras`)
-254
View File
@@ -1,254 +0,0 @@
---
name: monitor-run
description: How to monitor ongoing training runs — find output directories, check logs, diagnose performance, and inspect SLURM jobs. Use when asked to check on a run, debug training issues, or investigate performance.
---
# Monitor RL Run
## Runbook
### On launch
Immediately gather context and write a summary of the run into `{output_dir}/STATUS.md`:
1. Identify the output directory and read the resolved configs to understand the experiment (model, envs, hyperparameters, deployment details).
2. Make sure that the run started successfully and that all processes are alive.
3. Read the logs and note the current training step and health.
### Recurring check-ins
After the initial overview, schedule recurring check-ins. By default, check in every **1 hour** (the researcher can override this).
At each check-in:
1. Check that all processes are alive.
2. Read the logs — look for errors, warnings, hangs, or degraded performance
3. Note the current training step, key metrics, and checkpoint progress.
4. **Append an entry to `{output_dir}/STATUS.md`**:
```markdown
## YYYY-MM-DD HH:MM UTC
**Step**: {current_step} / {max_steps}
**Health**: {Healthy | Degraded | Down}
**Progress**: reward/mean, seq_len, truncation rate, eval scores (if available), notable env-specific metrics.
**Stability**: entropy, mismatch KL, grad norm — flag any spikes or concerning trends.
**Performance**: trainer and orchestrator step times, who is waiting on whom, env server lag, inference pressure.
**Notes**: (anything unusual — errors, restarts, hangs, etc. Omit if nothing notable.)
```
Always append — never overwrite previous entries.
### Restarting a run
**IMPORTANT**: Never restart a run unless you were explicitly instructed by the researcher. If you were given permission, make sure to ask the researcher for the exact command to resume a run and under what conditions a restart is necessary.
**IMPORTANT**: Never run kill or launch commands directly from your shell. Instead, send them to the tmux **Launcher** window so the researcher can see exactly what was executed.
Use `tmux send-keys` to dispatch commands to the Launcher pane:
```bash
# Get your current tmux session name
SESSION=$(tmux display-message -p '#S')
# Send a command to the Launcher window
tmux send-keys -t "$SESSION:Launcher" 'your command here' Enter
```
After a restart, verify that all processes are back up and healthy before resuming periodic check-ins. Check the process tree and tail the logs to confirm the run is making progress again.
---
## Reference
### Output directory and tmux session
The output directory and tmux session name are typically provided by the researcher in the appended system prompt (see `scripts/tmux.sh` — the Claude window is launched with this context). If not provided, **ask the researcher** which output directory to monitor and which tmux session the run is in.
The tmux session contains the **Launcher** window where the researcher runs launch commands — this is where you should send any restart commands (see [Restarting a run](#restarting-a-run)).
Once you have the output directory, the resolved configs are at `{output_dir}/configs/`.
### Configs
The launcher writes resolved configs as TOML files to `{output_dir}/configs/`. Read `rl.toml` to get the full picture of the experiment (model, envs, hyperparameters, wandb, deployment).
### Logs
Logs are usually the most informative place to monitor a run.
```
{output_dir}/logs/
├── trainer.log # trainer stdout (rank 0)
├── orchestrator.log # orchestrator stdout
├── inference.log # vLLM inference server stdout
├── trainer/
│ ├── node_*.log # per-node logs (multi-node only)
│ └── torchrun/ # per-rank stdout/stderr (all ranks)
├── inference/
│ ├── node_*.log # per-node logs (multi-node only)
│ └── router_0.log # vllm-router per replica (multi-node only)
└── envs/
├── train/{env_name}/
│ ├── env_server.log
│ └── env_worker_{id}.log
└── eval/{env_name}/
└── ...
```
Usually it's sufficient to tail `trainer.log`, `orchestrator.log`, and `inference.log`. For debugging, it may be necessary to check the per-node logs (`node_*.log`) or per-rank trainer logs under `torchrun/`.
```bash
tail {output_dir}/logs/trainer.log # training progress — kl mismatch, entropy, grad norm, trainer step time
tail {output_dir}/logs/orchestrator.log # orchestrator — reward, rollouts, env execution, inference step time
tail {output_dir}/logs/inference.log # inference — completed HTTP requests, engine stats, OOM errors
tail {output_dir}/logs/envs/train/*/env_server.log # env server — aggregated stats across its workers (lag, task distribution)
tail {output_dir}/logs/envs/train/*/env_worker_*.log # env workers — individual env logs
```
All logs use loguru with the format `HH:mm:ss LEVEL message`. Log levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`. To scan for problems:
```bash
grep -E "WARNING|ERROR" {output_dir}/logs/trainer.log
grep -E "WARNING|ERROR" {output_dir}/logs/orchestrator.log
grep -E "WARNING|ERROR" {output_dir}/logs/inference.log
grep -E "WARNING|ERROR" {output_dir}/logs/envs/train/*/env_server.log
grep -E "WARNING|ERROR" {output_dir}/logs/envs/train/*/env_worker_*.log
```
### Metrics
All metrics below are logged to the console. The source column indicates which log file to check.
#### Progress
These tell you whether the model is learning and how the run is progressing.
| Metric | Source | Description |
|--------|--------|-------------|
| `reward/{all,env}/mean` | orchestrator | mean training reward |
| `seq_len/{all,env}/mean` | orchestrator | average sequence length in tokens |
| `num_turns/{all,env}/mean` | orchestrator | average turns per rollout (ignore for single-turn envs) |
| `is_truncated/{all,env}/mean` | orchestrator | fraction of truncated rollouts |
| `empty_rollouts/{all,env}` | orchestrator | fraction of empty rollouts |
| `errored_rollouts/{all,env}` | orchestrator | fraction of errored rollouts |
| `metrics/{env}/{metric}` | orchestrator | env-specific metrics (e.g. pass rate for unit tests) |
| `eval/{env}/{avg@k,pass@k}` | orchestrator | eval scores (if eval is configured) |
#### Stability
These tell you whether training is healthy or diverging.
| Metric | Source | Description |
|--------|--------|-------------|
| `mismatch_kl/mean` | trainer | KL divergence between trainer and (old) inference policy |
| `entropy/mean` | trainer | policy entropy |
| `optim/grad_norm` | trainer | gradient norm — spikes may precede divergence |
#### Performance
These tell you how fast the run is and where the bottlenecks are. Trainer and orchestrator step independently — compare their step times to identify who is waiting on whom.
**Trainer** (in `trainer.log`):
| Metric | Description |
|--------|-------------|
| `time/step` | total trainer step time |
| `time/wait_for_batch` | time waiting for orchestrator to deliver a batch — **high = orchestrator is the bottleneck** |
| `time/forward_backward` | forward/backward pass time |
| `time/broadcast_weights` | time broadcasting weights to inference |
| `time/save_ckpt` | checkpoint save time |
| `perf/throughput` | tokens/s throughput |
| `perf/mfu` | model FLOPs utilization % |
**Orchestrator** (in `orchestrator.log`):
| Metric | Description |
|--------|-------------|
| `time/step` | total orchestrator step time |
| `time/generate_completions` | rollout generation time |
| `time/wait_for_ckpt` | time waiting for trainer checkpoint — **high = trainer is the bottleneck** |
| `time/update_weights` | weight update time |
| `scheduler/async_level` | current async level |
| `scheduler/inflight_rollouts` | number of in-flight rollouts |
**Env servers** (in `envs/train/{env_name}/env_server.log`):
| Metric | Description |
|--------|-------------|
| event loop lag (min/mean/p90/p99/max) | server and worker lag stats, logged periodically |
| active task distribution | per-worker and per-env task counts |
**Inference** (in `inference.log`):
vLLM logs completed HTTP requests and occasionally engine stats. For live inference metrics, query the vLLM metrics endpoint directly:
```bash
# Get vLLM Prometheus metrics (num running/queued reqs, KV cache usage, etc.)
curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
```
Key vLLM metrics to watch:
- `vllm:num_requests_running` — requests currently being processed
- `vllm:num_requests_waiting` — requests queued waiting for KV cache space
- `vllm:gpu_cache_usage_perc` — KV cache pressure (approaching 1.0 = requests will queue)
### Rollouts
Plain-text rollouts (`verifiers` format) are saved every step alongside the binary training batch inside the run directory. For single-run (local) runs this is typically `{output_dir}/run_default`.
```
{output_dir}/{run_dir}/rollouts/
└── step_{N}/
├── train_rollouts.jsonl # all train rollouts
├── eval_rollouts.jsonl # all eval rollouts (only present when eval ran)
└── train_rollouts.bin # binary-encoded training batch (consumed by the trainer)
```
Each line in the `.jsonl` files is a JSON-serialized `vf.RolloutOutput` dict with fields like `example_id`, `task`, `prompt`, `completion`, `reward`, `trajectory`, `metrics`, etc. To inspect rollouts for a given step:
```bash
# Count rollouts at a step
wc -l {output_dir}/{run_dir}/rollouts/step_42/train_rollouts.jsonl
# Preview first rollout (pretty-printed)
head -1 {output_dir}/{run_dir}/rollouts/step_42/train_rollouts.jsonl | python -m json.tool
# Extract rewards
jq '.reward' {output_dir}/{run_dir}/rollouts/step_42/train_rollouts.jsonl
```
### Errors and warnings
As part of every check-in, grep all logs for `WARNING` and `ERROR` level messages. Pay special attention to env server and env worker logs — these are the most common source of issues since they run user-provided code.
Common things to look for:
- **Env workers**: exceptions in environment execution, timeouts, sandbox errors, OOM kills
- **Orchestrator**: empty/errored rollout spikes, weight broadcast failures, checkpoint errors
- **Trainer**: NCCL/CUDA errors, OOM, NaN loss or gradients
- **Inference**: NCCL/CUDA errors, OOM, request timeouts
A small number of warnings is normal (e.g. occasional env timeouts). Escalate to the researcher if you see errors that are persistent, increasing, or affect a large fraction of rollouts.
### Processes
All processes have custom process names, making them easy to identify in `ps`, `htop`, and `pstree`. Use this in case you need to debug a process that is not responding or behaving unexpectedly.
```
PRIME-RL::Launcher
├── PRIME-RL::Inference (vLLM server, GPU 0)
├── PRIME-RL::Orchestrator (CPU-only, data/scheduling)
│ ├── Verifiers::EnvServer (ZMQ env server per environment)
│ │ ├── Verifiers::EnvWorker0
│ │ ├── Verifiers::EnvWorker1
│ │ └── ...
│ └── ...
├── torchrun
│ └── PRIME-RL::Trainer (RL trainer, GPU 1+)
└── tail trainer.log
```
For multi-node runs, trainer and inference processes are distributed across separate nodes. Use `srun` or `ssh` to inspect processes on other nodes directly.
+61 -10
View File
@@ -5,14 +5,65 @@ description: How to prepare and publish GitHub releases for prime-rl. Use when d
# Releases
## Preparing release notes
Releases are driven by [`.github/workflows/tag-and-release.yaml`](../../.github/workflows/tag-and-release.yaml). The flow:
1. **Style reference**: check the previous release (`gh release list --limit 1` then `gh release view <tag>`) to match the tone and formatting.
2. **Gather changes**: use `git log <last-tag>..origin/main --oneline --no-merges` to list all commits since the last release.
3. **Check for new commits**: always `git fetch origin main` and re-check right before publishing, since PRs may have been merged while drafting.
4. **Structure**: organize notes into numbered highlight sections (`# 1.`, `# 2.`, ...), then `# Breaking Changes`, `# Bug Fixes`, and `# Misc`.
5. **Highlights**: group related PRs under a single highlight. Use `##` subsections when a highlight contains multiple items (e.g. Performance & Parallelism). Keep the top highlights for the most impactful user-facing features.
6. **Config examples**: when referencing TOML config, verify the exact field names against the actual code or docs — don't guess.
7. **Links**: use clickable links for docs (`[docs/foo.md](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/docs/foo.md)`) and PR references (`[#1234](https://github.com/PrimeIntellect-ai/prime-rl/pull/1234)`).
8. **Contributors**: list all contributors ranked by number of commits, using their GitHub `@username`. Get usernames via the GitHub API, not git author names (which can be inconsistent).
9. **Draft first**: always create releases as `--draft` first, iterate on content, then publish.
1. You create a **draft GitHub Release** with the notes inline (`gh release create --draft`).
2. You open a **draft PR** that bumps `version` in `pyproject.toml`.
3. Maintainer merges. The workflow tags the commit and promotes the draft.
Release notes live on the GitHub Release, not in the repo. Prime-rl is **not** on PyPI. `.dev` tags are handled separately by `devx_tag.yaml`; `tag-and-release.yaml` ignores them.
## 1. Decide the version
```bash
git fetch origin --tags
grep '^version' pyproject.toml
gh release list --repo PrimeIntellect-ai/prime-rl --limit 5
```
SemVer (`MAJOR.MINOR.PATCH`). Confirm with the user before continuing.
## 2. Draft the notes
Match the prior release's structure: numbered highlights (`# 1.`, ...), then `# Breaking Changes`, `# Bug Fixes`, `# Misc`, `# Contributors`. Use `##` subsections inside a highlight when it bundles multiple items.
```bash
PREV=$(gh release list --limit 1 --json tagName --jq '.[0].tagName')
gh release view "$PREV" --json body --jq .body # style reference
git log "$PREV"..origin/main --oneline --no-merges # commits since
gh pr list --base main --state merged --search \
"merged:>=$(gh release view "$PREV" --json publishedAt --jq .publishedAt)" \
--limit 500 --json number,title,author # for PR links + contributors
```
Tips:
- PR refs: `[#1234](https://github.com/PrimeIntellect-ai/prime-rl/pull/1234)`.
- Contributors: order by commit count, use the GH `@username` from the API (not git author names).
- Verify any TOML field names against the actual config classes.
## 3. Create the draft release
```bash
NEW=v0.6.0
gh release create --draft "$NEW" --title "$NEW" --target main --notes-file /tmp/release-notes-$NEW.md
gh release view "$NEW" --json isDraft,tagName --jq '{tagName, isDraft}' # expect isDraft: true
```
Iterate with `gh release edit "$NEW" --notes-file /tmp/release-notes-$NEW.md`.
## 4. Open the version-bump PR
```bash
git switch -c chore/release-$NEW
# bump `version = "..."` in pyproject.toml
git add pyproject.toml
git commit -m "chore: release $NEW"
git push -u origin "chore/release-$NEW"
gh pr create --draft --title "chore: release $NEW" --body "Bumps version to ${NEW#v}. Draft release: https://github.com/PrimeIntellect-ai/prime-rl/releases/tag/$NEW"
```
Stop. Do not tag, push tags, or flip the draft to published — the workflow does that on merge.
## Recovery
If the workflow tagged the commit but failed to promote the draft, the next main push (or `workflow_dispatch` with `tag: v{new}`) re-promotes it.
+13
View File
@@ -0,0 +1,13 @@
---
name: training
description: Launch and monitor prime-rl training runs. Use when starting, supervising, or debugging an RL/SFT run. Routes to `start-run` (entrypoints + how to launch) and `monitor-run` (logs, metrics, check-ins).
---
# Training
Two phases — start the run, then watch it.
- **Start a run** — see `start-run/SKILL.md` for the `rl`, `sft`, and `inference` entrypoints and how to launch them (single-node, SLURM, dry-run).
- **Monitor a run** — see `monitor-run/SKILL.md` for the runbook: how to find the output dir, what to tail, which metrics to watch, and how to restart safely.
Both subskills assume the `configs` skill for config-loading mechanics.
+172
View File
@@ -0,0 +1,172 @@
---
name: monitor-run
description: Monitor an ongoing prime-rl training run — find the output directory, tail logs, check key metrics, inspect SLURM jobs, and restart safely. Use when asked to check on a run, debug training, or investigate performance.
---
# Monitor a run
## Runbook
### On launch
1. Find the output dir and read the resolved configs at `{output_dir}/configs/` (start with `rl.toml`).
2. Confirm all processes are alive and the run is making progress.
3. Write the initial summary into `{output_dir}/STATUS.md`.
### Recurring check-ins
Default cadence: **1 hour** (researcher can override). At each check-in:
1. Confirm processes are alive.
2. Grep logs for errors/warnings; note current step and key metrics.
3. **Append** an entry to `{output_dir}/STATUS.md` (never overwrite):
```markdown
## YYYY-MM-DD HH:MM UTC
**Step**: {current_step} / {max_steps}
**Health**: {Healthy | Degraded | Down}
**Progress**: reward/mean, seq_len, truncation, eval scores, env-specific metrics.
**Stability**: entropy, mismatch_kl, grad_norm — flag spikes.
**Performance**: trainer vs orchestrator step time, env lag, inference pressure.
**Notes**: anything unusual (errors, restarts, hangs). Omit if nothing notable.
```
### Restarting a run
**Never restart unless the researcher explicitly asked.** Confirm the exact restart command and the conditions that warrant one.
**Never** run kill or launch commands from your own shell. Dispatch them to the tmux **Launcher** window so the researcher sees what was executed:
```bash
SESSION=$(tmux display-message -p '#S')
tmux send-keys -t "$SESSION:Launcher" 'your command here' Enter
```
After a restart, verify all processes are back up and progress resumed before the next check-in.
---
## Reference
### Where to find things
- `scripts/tmux.sh` launches the run with a `Launcher` window in the named tmux session. The Claude window receives the output dir and session name in its appended prompt — if either is missing, **ask** rather than guess.
- `{output_dir}/configs/` — resolved TOMLs (`rl.toml` has the full picture).
- `{output_dir}/logs/` — see below.
- `{output_dir}/rollouts/step_N/` — saved rollouts.
### Logs
```
{output_dir}/logs/
├── trainer.log # rank 0 stdout
├── orchestrator.log # orchestrator stdout
├── inference.log # vLLM stdout
├── trainer/
│ ├── node_*.log # per-node (multi-node only)
│ └── torchrun/ # per-rank stdout/stderr
├── inference/
│ ├── node_*.log # per-node (multi-node only)
│ └── router_0.log # vllm-router per replica (multi-node only)
└── envs/{train,eval}/{env_name}/
├── env_server.log
└── env_worker_*.log
```
Usually tailing `trainer.log`, `orchestrator.log`, and `inference.log` is enough. Drop into per-node or per-rank logs only when debugging. All logs are loguru with `HH:mm:ss LEVEL message`; levels: `DEBUG`, `INFO`, `SUCCESS`, `WARNING`, `ERROR`.
Scan for problems:
```bash
grep -E "WARNING|ERROR" {output_dir}/logs/{trainer,orchestrator,inference}.log
grep -E "WARNING|ERROR" {output_dir}/logs/envs/train/*/env_{server,worker_*}.log
```
### Metrics
All metrics print to the console log (and W&B when configured).
**Progress** — orchestrator log:
| Metric | Description |
|--------|-------------|
| `reward/{all,env}/mean` | mean training reward |
| `seq_len/{all,env}/mean` | avg sequence length (tokens) |
| `num_turns/{all,env}/mean` | avg turns per rollout (multi-turn only) |
| `is_truncated/{all,env}/mean` | fraction truncated |
| `empty_rollouts/{all,env}`, `errored_rollouts/{all,env}` | fraction empty/errored |
| `metrics/{env}/{metric}` | env-specific (e.g. pass rate) |
| `eval/{env}/{avg@k,pass@k}` | eval scores when configured |
**Stability** — trainer log:
| Metric | Description |
|--------|-------------|
| `mismatch_kl/{all,env}/{mean,std,max}` | KL between trainer and (old) inference policy over trainable tokens |
| `entropy/{all,env}/{mean,std,max}` | policy entropy over trainable tokens |
| `masked_advantage_{positive,negative}/mean` | fraction of DPPO-masked tokens with +/- advantage |
| `optim/grad_norm` | spikes may precede divergence |
**Performance** — trainer and orchestrator step independently, so comparing step times shows who's waiting on whom.
| Source | Metric | Description |
|--------|--------|-------------|
| trainer | `time/step` | total trainer step |
| trainer | `time/wait_for_batch` | **high → orchestrator is bottleneck** |
| trainer | `time/forward_backward`, `time/broadcast_weights`, `time/save_ckpt` | phase timings |
| trainer | `perf/throughput`, `perf/mfu` | tokens/s and MFU % |
| orchestrator | `time/step`, `time/generate_completions`, `time/update_weights` | phase timings |
| orchestrator | `time/wait_for_ckpt` | **high → trainer is bottleneck** |
| orchestrator | `scheduler/async_level`, `scheduler/inflight_rollouts` | scheduler state |
| env server | event loop lag (min/mean/p90/p99/max), active task distribution | periodic |
For live vLLM stats, query Prometheus directly:
```bash
curl -s http://localhost:8000/metrics | grep -E "num_requests|gpu_cache_usage"
# vllm:num_requests_running, vllm:num_requests_waiting, vllm:gpu_cache_usage_perc (→1.0 = KV cache saturated)
```
### Rollouts
```
{output_dir}/rollouts/step_N/
├── train_rollouts.jsonl # all train rollouts (vf.RolloutOutput, trajectory excluded)
├── eval_rollouts.jsonl # only present when eval ran
└── train_rollouts.bin # binary batch consumed by the trainer
```
```bash
wc -l {output_dir}/rollouts/step_42/train_rollouts.jsonl
head -1 {output_dir}/rollouts/step_42/train_rollouts.jsonl | python -m json.tool
jq '.reward' {output_dir}/rollouts/step_42/train_rollouts.jsonl
```
### Common failure modes
A few warnings are normal. Escalate when errors are persistent, growing, or hit a large fraction of rollouts.
- **Env workers**: exceptions in env code, timeouts, sandbox errors, OOM kills (most common source — runs user code).
- **Orchestrator**: empty/errored rollout spikes, weight-broadcast failures, checkpoint errors.
- **Trainer**: NCCL/CUDA errors, OOM, NaN loss or gradients.
- **Inference**: NCCL/CUDA errors, OOM, request timeouts.
### Process tree
All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
```
PRIME-RL::Launcher
├── PRIME-RL::Inference (vLLM server, GPU 0)
├── PRIME-RL::Orchestrator (CPU-only)
│ └── Verifiers::EnvServer (ZMQ env server per environment)
│ └── Verifiers::EnvWorker0..N
├── torchrun
│ └── PRIME-RL::Trainer (GPU 1+)
└── tail trainer.log
```
For multi-node runs, trainer and inference processes are on separate nodes — use `srun` or `ssh` to inspect them.
+88
View File
@@ -0,0 +1,88 @@
---
name: start-run
description: How to launch prime-rl training runs — the `rl`, `sft`, and `inference` entrypoints, their config classes, and single-node/SLURM/dry-run modes. Use when starting a run or picking the right entrypoint.
---
# Start a run
All entrypoints run via `uv run <command>` and accept TOML configs via `@ path/to.toml` plus CLI overrides.
## Config system at a glance
[`pydantic-config`](https://github.com/PrimeIntellect-ai/pydantic-config) — Pydantic-based TOML + CLI loader. Highlights (see the `configs` skill for full mechanics):
- Config files via `@ path` (TOML / YAML / JSON); CLI args layer on top, deep-merged with class defaults.
- Nested groups via dotted CLI paths — kebab-case on the CLI, snake_case in TOML.
- Bool toggles: bare `--flag` enables, `--no-flag` disables (nested too).
- Lists: space-separated or JSON literal. Dicts: JSON literal, deep-merged with file values.
- Optional sub-configs (`WandbConfig | None`): bare `--wandb` enables defaults; `--wandb @ wandb.toml` enables from a file; `--no-wandb` disables.
- Discriminated unions are switched by the `type` tag (e.g. `--optimizer.type muon`).
- Validation aliases let renamed fields keep working; legacy keys can be remapped in a `model_validator(mode="before")`.
- Auto-generated `--help` panels from `Field(description=...)` or PEP 224 docstrings.
- Friendly errors: required-field boxes, validator errors point at the offending flag, unknown flags get a "did you mean" hint.
## `rl` — RL training
Launches inference server, orchestrator, and trainer as subprocesses.
```bash
uv run rl @ examples/reverse_text/rl.toml
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml # SLURM
uv run rl @ examples/reverse_text/rl.toml --dry-run # write scripts, don't run
```
- Config: `RLConfig` (`packages/prime-rl-configs/src/prime_rl/configs/rl.py`)
- Entrypoint: `src/prime_rl/entrypoints/rl.py`
- SLURM: single- and multi-node
## `sft` — SFT training
Launches torchrun internally — never call torchrun directly.
```bash
uv run sft @ examples/reverse_text/sft.toml
uv run sft @ examples/reverse_text/sft.toml --slurm
uv run sft @ examples/reverse_text/sft.toml --dry-run
```
- Config: `SFTConfig` (`packages/prime-rl-configs/src/prime_rl/configs/sft.py`)
- Entrypoint: `src/prime_rl/entrypoints/sft.py`
- SLURM: single- and multi-node
## `inference` — vLLM server
OpenAI-compatible API plus prime-rl custom endpoints (`/update_weights`, `/load_lora_adapter`, `/init_broadcaster`). Always use this entrypoint — never `vllm serve` directly.
```bash
uv run inference @ configs/debug/infer.toml
uv run inference --model.name Qwen/Qwen3-0.6B --model.enforce-eager
```
Smoke checks:
```bash
curl http://<host>:<port>/health
curl http://<host>:<port>/v1/models
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hi"}], "max_tokens": 50}'
```
- Config: `InferenceConfig` (`packages/prime-rl-configs/src/prime_rl/configs/inference.py`)
- Entrypoint: `src/prime_rl/entrypoints/inference.py`
- SLURM: single-node, multi-node, and disaggregated deployments
## Summary
| Command | Purpose | Typical use |
|---------|---------|-------------|
| `rl` | Full RL pipeline | Production RL training |
| `sft` | Supervised fine-tuning | SFT and hard-distill |
| `inference` | vLLM server | Standalone serving / debugging |
## Key paths
- `src/prime_rl/entrypoints/` — `rl`, `sft`, `inference` (+ `trainer`, `orchestrator` for direct launches)
- `packages/prime-rl-configs/src/prime_rl/configs/` — all config classes
- `configs/debug/` — minimal debug configs
- `examples/` — full example configs (e.g. `reverse_text/`)
-1
View File
@@ -1 +0,0 @@
import prime_rl._compat # noqa: F401 — must run before ring_flash_attn is imported

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