Compare commits

...
Author SHA1 Message Date
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
67 changed files with 3615 additions and 5346 deletions
@@ -1,4 +1,4 @@
name: Release
name: Docker Push
on:
push:
+6
View File
@@ -69,6 +69,12 @@ jobs:
- 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"
+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
+1
View File
@@ -2,6 +2,7 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`[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`.
@@ -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
@@ -16,7 +16,6 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
use_renderer = false
[orchestrator.train.sampling]
max_completion_tokens = 64
-3
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]
@@ -11,8 +11,6 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 256
rollouts_per_example = 16
use_renderer = false
[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"]
@@ -12,7 +12,6 @@ language_model_attr = "model.language_model"
[orchestrator]
batch_size = 16
rollouts_per_example = 2
use_renderer = false
[orchestrator.train.sampling]
max_completion_tokens = 32
+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.
+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
+1 -2
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,7 +30,6 @@ name = "aime2024"
rollouts_per_example = 32
[trainer.model]
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
seq_len = 16384
[inference.model]
+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
+1 -4
View File
@@ -6,10 +6,7 @@ readme = "README.md"
requires-python = "~=3.12.0"
dependencies = [
"pydantic>=1.10.13",
# The PyPI package named `pydantic-config` is a different project that
# doesn't expose `BaseConfig` / `cli`. Pin to samsja's fork so plain
# `pip install prime-rl-configs` (no uv workspace context) resolves it.
"pydantic-config @ git+https://github.com/samsja/pydantic_config.git",
"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,
@@ -1,7 +1,6 @@
from pathlib import Path
from typing import Annotated
from pydantic import Field, model_validator
from pydantic import model_validator
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.shared import LogConfig
@@ -9,18 +8,15 @@ from prime_rl.utils.config import BaseConfig
class EnvServerConfig(BaseConfig):
"""Configures an environment server."""
env: EnvConfig = EnvConfig()
log: LogConfig = LogConfig()
env_install_prerelease: bool = False
output_dir: Annotated[
Path,
Field(
description="Directory to write outputs to. Will be populated with checkpoints, weights, rollouts 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")
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):
@@ -2,132 +2,93 @@ from argparse import Namespace
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import BaseModel, ConfigDict, Field, model_validator
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):
"""Configures the inference server."""
host: str | None = None
"""Host to bind to."""
host: Annotated[str | None, Field(description="The host to bind to.")] = None
port: Annotated[int, Field(description="The port to bind to.")] = 8000
liveness_timeout_seconds: Annotated[
float,
Field(
gt=0,
description=(
"Timeout in seconds for the /liveness endpoint's internal vLLM worker RPC. "
"If Kubernetes liveness probes are enabled, keep the probe timeoutSeconds at least this high."
),
),
] = 30.0
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):
"""Configures multi-node and multi-GPU setups through different types of parallelism (TP, DP, PP)."""
tp: int = 1
"""Tensor parallel size. Forwarded to vLLM as ``--tensor-parallel-size``."""
tp: Annotated[
int,
Field(
description="The tensor parallel size. It is passed to vLLM as `--tensor-parallel-size`",
),
] = 1
dp: Annotated[
int,
Field(
ge=1,
description="The data parallel size. It is passed to vLLM as `--data-parallel-size`",
),
] = 1
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)."""
"""Configures the inference model. Most arguments are passed directly to the vLLM LLM class (https://docs.vllm.ai/en/latest/api/vllm.LLM.html).
dtype: Annotated[
Literal["auto", "float16", "bfloat16", "float32"],
Field(
description="Data type for model weights and activations. If 'auto' will use FP16 precision for FP32 and FP16 models, and BF16 precision for BF16 models. Passed to vLLM as `--dtype`",
),
] = "auto"
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.
"""
max_model_len: Annotated[
int | None,
Field(
description="Maximum model context length. If None, will use the maximum context length from model config. Passed to vLLM as `--max-model-len`",
),
] = None
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``."""
enforce_eager: Annotated[
bool,
Field(
description="Whether to enforce eager mode. If False, will use PyTorch eager and cuda graphs in hybrid for maximal performance. Passed to vLLM as `--enforce-eager`",
),
] = False
max_model_len: int | None = None
"""Maximum model context length. If None, uses the model config's value. Forwarded as ``--max-model-len``."""
trust_remote_code: Annotated[
bool,
Field(
description="Whether to trust remote code. Passed to vLLM engine init",
),
] = False
enforce_eager: bool = False
"""Enforce eager mode. When False, PyTorch eager and cuda graphs run hybrid for maximum performance. Forwarded as ``--enforce-eager``."""
chat_template: Annotated[
str | None,
Field(
description="Chat template to use. Can be a Jinja2 template string or a path to a template file. "
"Passed to vLLM as `--chat-template`. If None, uses the model's default.",
),
] = None
trust_remote_code: bool = False
"""Trust remote code. Forwarded to vLLM engine init."""
tool_call_parser: Annotated[
str | None,
Field(
description="The tool call parser to use. Passed to vLLM as `--tool-call-parser`. "
'Set to "auto" to infer from the model name.',
),
] = "auto"
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."""
reasoning_parser: Annotated[
str | None,
Field(
description="Parser for extracting reasoning content from model outputs. Passed to vLLM as `--reasoning-parser`. Setting this enables reasoning mode.",
),
] = None
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."""
rope_scaling: Annotated[
dict[str, Any] | str | None,
Field(
description='RoPE scaling configuration as a dict. For YaRN, use: {rope_type="yarn", factor=4.0, original_max_position_embeddings=32768} or. Passed to vLLM as `--rope-scaling`.',
),
] = None
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):
"""Configures weight broadcast settings."""
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
"filesystem"
)
type: Literal["nccl", "filesystem"] = "filesystem"
"""Weight broadcast transport."""
class KVCacheOffloadConfig(BaseModel):
"""CPU KV cache offloading for vLLM inference workers."""
model_config = ConfigDict(extra="forbid")
cpu_bytes: Annotated[int, Field(gt=0, description="CPU bytes available for KV cache offloading per worker.")] = (
1_000_000_000
)
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)
@@ -144,81 +105,70 @@ All2AllBackend = Literal[
]
class BaseInferenceDeploymentConfig(BaseModel):
"""Base deployment config for inference."""
model_config = ConfigDict(extra="forbid")
gpus_per_node: Annotated[int, Field(description="Number of GPUs per node.")] = 8
class BaseInferenceDeploymentConfig(BaseConfig):
gpus_per_node: int = 8
"""GPUs per node."""
class SingleNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
"""Configures a single-node inference deployment."""
type: Literal["single_node"] = "single_node"
# Multi-node inference: each node runs an independent vLLM replica.
class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
"""Configures a multi-node inference deployment. Each node runs an independent vLLM replica."""
type: Literal["multi_node"] = "multi_node"
num_nodes: Annotated[int, Field(ge=1, description="Number of inference nodes.")] = 2
num_nodes: int = Field(2, ge=1)
"""Inference nodes."""
router_port: Annotated[int, Field(description="Port for the vllm-router.")] = 8000
backend_port: Annotated[int, Field(description="Port for vLLM backend instances.")] = 8100
router_policy: Annotated[
str, Field(description="Routing policy for the vllm-router (e.g. 'consistent_hash', 'round_robin').")
] = "consistent_hash"
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):
"""Configures a disaggregated prefill/decode inference deployment.
Each inference replica is split into separate prefill and decode node groups.
Requires NIXL for KV transfer and a vllm-router for request routing.
Multi-replica support: set ``num_prefill_replicas`` / ``num_decode_replicas``
to run multiple independent vLLM instances within the prefill / decode node
groups. For example, ``num_prefill_nodes=4, num_prefill_replicas=2`` creates
two prefill vLLM instances each spanning 2 nodes (EP16 with 8 GPUs/node).
"""
type: Literal["disaggregated"] = "disaggregated"
num_prefill_nodes: Annotated[int, Field(ge=1, description="Total number of prefill nodes.")] = 1
num_decode_nodes: Annotated[int, Field(ge=1, description="Total number of decode nodes.")] = 1
num_prefill_nodes: int = Field(1, ge=1)
"""Total prefill nodes."""
num_prefill_replicas: Annotated[
int,
Field(
ge=1,
description="Number of independent prefill vLLM instances. Must evenly divide num_prefill_nodes.",
),
] = 1
num_decode_replicas: Annotated[
int,
Field(
ge=1,
description="Number of independent decode vLLM instances. Must evenly divide num_decode_nodes.",
),
] = 1
num_decode_nodes: int = Field(1, ge=1)
"""Total decode nodes."""
router_port: Annotated[int, Field(description="Port for the vllm-router on each replica.")] = 8000
prefill_port: Annotated[int, Field(description="Port for prefill vLLM instances.")] = 8100
decode_port: Annotated[int, Field(description="Port for decode vLLM instances.")] = 8200
router_policy: Annotated[
str, Field(description="Routing policy for the vllm-router (e.g. 'consistent_hash', 'round_robin').")
] = "consistent_hash"
num_prefill_replicas: int = Field(1, ge=1)
"""Independent prefill vLLM instances. Must evenly divide ``num_prefill_nodes``."""
prefill_env_overrides: Annotated[
dict[str, str],
Field(description="Extra environment variables exported only on prefill nodes."),
] = {}
decode_env_overrides: Annotated[
dict[str, str],
Field(description="Extra environment variables exported only on decode 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:
@@ -246,200 +196,96 @@ InferenceDeploymentConfig: TypeAlias = Annotated[
class InferenceExperimentalConfig(BaseConfig):
"""Experimental features for inference."""
pass
class InferenceConfig(BaseConfig):
"""Configures inference."""
# The server configuration
server: ServerConfig = ServerConfig()
# The model configuration
model: ModelConfig = Field(default_factory=ModelConfig)
# The parallel configuration
parallel: ParallelConfig = ParallelConfig()
"""Multi-node and multi-GPU parallelism (TP, DP, PP)."""
enable_lora: Annotated[
bool,
Field(
description="Whether to enable LORA. Passed to vLLM as `--enable-lora`",
),
] = False
enable_lora: bool = False
"""Enable LoRA. Forwarded as ``--enable-lora``."""
max_loras: Annotated[
int,
Field(
description="The maximum number of LoRAs to use. Passed to vLLM as `--max-loras`",
),
] = 8
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: Annotated[
int,
Field(
description="The maximum number of LoRAs to use on CPU. Passed to vLLM as `--max-cpu-loras`",
),
] = 100
max_cpu_loras: int = 100
"""Maximum number of LoRAs on CPU. Forwarded as ``--max-cpu-loras``."""
max_lora_rank: Annotated[
int | None,
Field(
description="The maximum LoRA rank to use. Passed to vLLM as `--max-lora-rank`",
),
] = None
max_lora_rank: int | None = None
"""Maximum LoRA rank. Forwarded as ``--max-lora-rank``."""
lora_target_modules: Annotated[
list[str] | None,
Field(
description="The target modules for LoRA. Passed to vLLM as `--lora-target-modules`.",
),
] = None
lora_target_modules: list[str] | None = None
"""LoRA target modules. Forwarded as ``--lora-target-modules``."""
enable_prefix_caching: Annotated[
bool | None,
Field(
description="Whether to enable prefix caching. Passed to vLLM as `--enable-prefix-caching`",
),
] = None
enable_prefix_caching: bool | None = None
"""Enable prefix caching. Forwarded as ``--enable-prefix-caching``."""
gpu_memory_utilization: Annotated[
float,
Field(
description="The GPU memory utilization to use. Passed to vLLM as `--gpu-memory-utilization`",
),
] = 0.9
gpu_memory_utilization: float = 0.9
"""GPU memory utilization. Forwarded as ``--gpu-memory-utilization``."""
api_server_count: Annotated[
int,
Field(
ge=0,
description="The number of API servers to use. Passed to vLLM as `--api-server-count`. Set to 0 for headless mode.",
),
] = 1
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: Annotated[
int | None,
Field(
ge=1,
description="Number of data parallel replicas to run on this node. Passed to vLLM as `--data-parallel-size-local`.",
),
] = None
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: Annotated[
int,
Field(
ge=1,
le=65535,
description="RPC port for data parallel communication. Passed to vLLM as `--data-parallel-rpc-port`.",
),
] = 13345
data_parallel_rpc_port: int = Field(13345, ge=1, le=65535)
"""RPC port for data parallel communication. Forwarded as ``--data-parallel-rpc-port``."""
seed: Annotated[
int,
Field(
description="Seed the inference components. Passed to vLLM as `--seed`",
),
] = 0
seed: int = 0
"""Seed the inference components. Forwarded as ``--seed``."""
enable_expert_parallel: Annotated[
bool,
Field(
description="Enable expert parallelism for MoE models. Passed to vLLM as `--enable-expert-parallel`.",
),
] = False
enable_expert_parallel: bool = False
"""Enable expert parallelism for MoE models. Forwarded as ``--enable-expert-parallel``."""
all2all_backend: Annotated[
All2AllBackend,
Field(
description="All-to-all backend for expert parallel communication. Passed to vLLM as `--all2all-backend`.",
),
] = "allgather_reducescatter"
all2all_backend: All2AllBackend = "allgather_reducescatter"
"""All-to-all backend for expert-parallel communication. Forwarded as ``--all2all-backend``."""
enable_eplb: Annotated[
bool,
Field(
description="Enable expert parallel load balancer (EPLB). Passed to vLLM as `--enable-eplb`.",
),
] = False
enable_eplb: bool = False
"""Enable expert parallel load balancer (EPLB). Forwarded as ``--enable-eplb``."""
enable_dbo: Annotated[
bool,
Field(
description="Enable dual batch overlap (DBO). Passed to vLLM as `--enable-dbo`.",
),
] = False
enable_dbo: bool = False
"""Enable dual batch overlap (DBO). Forwarded as ``--enable-dbo``."""
use_deep_gemm: Annotated[
bool,
Field(
description="Force DeepGEMM FP8 kernels via VLLM_USE_DEEP_GEMM=1. Only works with per-tensor FP8 quantization (e.g. GLM-5-FP8).",
),
] = False
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: Annotated[WeightBroadcastConfig, Field(description="The weight broadcast config.")] = (
WeightBroadcastConfig()
)
weight_broadcast: WeightBroadcastConfig = WeightBroadcastConfig()
kv_cache_offload: Annotated[
KVCacheOffloadConfig | None,
Field(
description=(
"CPU KV cache offload config for inference workers. Standard inference uses vLLM's "
"OffloadingConnector. Disaggregated P/D deployments combine it with NIXL through "
"MultiConnector in the SLURM launcher."
),
),
] = None
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: Annotated[
bool,
Field(
description="Whether to enable return routed experts. Passed to vLLM as `--enable-return-routed-experts`",
),
] = False
enable_return_routed_experts: bool = False
"""Return routed experts in responses. Forwarded as ``--enable-return-routed-experts``."""
enable_fp32_lm_head: Annotated[
bool,
Field(
description="Run the lm_head projection in fp32 via a native bf16xbf16 -> 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.",
),
] = False
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: Annotated[
dict[str, Any],
Field(
description="Extra arguments to pass to vLLM. These are applied as attributes on the vLLM namespace after config translation.",
),
] = {}
vllm_extra: dict[str, Any] = {}
"""Extra arguments forwarded to vLLM. Applied as attributes on the vLLM namespace after config translation."""
# Launcher-only fields
deployment: Annotated[
InferenceDeploymentConfig,
Field(
description="Deployment configuration for inference.",
),
] = SingleNodeInferenceDeploymentConfig()
deployment: InferenceDeploymentConfig = SingleNodeInferenceDeploymentConfig()
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."""
output_dir: Annotated[Path, Field(description="Directory for SLURM logs and generated scripts.")] = Path("outputs")
output_dir: Path = Path("outputs")
"""Directory for SLURM logs and generated scripts."""
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[
InferenceExperimentalConfig,
Field(description="Experimental features for inference."),
] = InferenceExperimentalConfig()
experimental: InferenceExperimentalConfig = InferenceExperimentalConfig()
@model_validator(mode="after")
def validate_multi_node_requires_slurm(self):
@@ -589,6 +435,12 @@ class InferenceConfig(BaseConfig):
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")
File diff suppressed because it is too large Load Diff
@@ -1,14 +1,11 @@
import warnings
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from typing import Annotated, Any, Literal, TypeAlias
from pydantic import BaseModel, ConfigDict, Field, model_validator
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 (
CheckpointConfig as OrchestratorCheckpointConfig,
)
from prime_rl.configs.orchestrator import (
FileSystemWeightBroadcastConfig as OrchestratorFileSystemWeightBroadcastConfig,
)
@@ -21,8 +18,6 @@ from prime_rl.configs.orchestrator import (
from prime_rl.configs.shared import (
SlurmConfig,
VLMConfig,
WandbConfig,
WandbWithExtrasConfig,
)
from prime_rl.configs.trainer import (
BenchConfig,
@@ -30,9 +25,6 @@ from prime_rl.configs.trainer import (
TokenizerConfig,
TrainerConfig,
)
from prime_rl.configs.trainer import (
CheckpointConfig as TrainerCheckpointConfig,
)
from prime_rl.configs.trainer import (
FileSystemWeightBroadcastConfig as TrainerFileSystemWeightBroadcastConfig,
)
@@ -41,11 +33,13 @@ from prime_rl.configs.trainer import (
)
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,
@@ -53,47 +47,38 @@ from prime_rl.utils.validation import (
class RLExperimentalConfig(BaseConfig):
"""Experimental features for RL training."""
pass
class SharedLogConfig(BaseConfig):
"""Configures shared logging."""
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``)."""
level: Annotated[
str | None,
Field(
description="The log level to use. When unset, the trainer and orchestrator log levels are used as-is (which themselves default to the PRIME_LOG_LEVEL env var if set, else 'info').",
),
] = None
json_logging: Annotated[
bool,
Field(description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.)."),
] = False
json_logging: bool = False
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
class SharedWandbConfig(BaseConfig):
"""Configures shared W&B configs."""
project: str | None = "prime-rl"
"""W&B project."""
project: Annotated[str | None, Field(description="The W&B project to use.")] = "prime-rl"
entity: str | None = None
"""W&B entity."""
entity: Annotated[str | None, Field(description="The W&B entity to use.")] = None
name: str | None = None
"""W&B run name."""
name: Annotated[str | None, Field(description="The W&B run name to use.")] = None
group: str | None = None
"""W&B group."""
group: Annotated[str | None, Field(description="The W&B group to use.")] = None
tags: list[str] | None = None
"""W&B tags attached to the run."""
tags: Annotated[list[str] | None, Field(description="The W&B tags to attach to the run.")] = None
offline: bool | None = False
"""Run W&B in offline mode."""
offline: Annotated[bool | None, Field(description="Whether to run W&B in offline mode.")] = False
shared: Annotated[
bool,
Field(
description="Use shared W&B mode to log trainer and orchestrator metrics to a single run. "
"Requires wandb SDK >= 0.19.9. Incompatible with offline mode.",
),
] = True
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):
@@ -103,88 +88,60 @@ class SharedWandbConfig(BaseConfig):
class SharedCheckpointConfig(BaseConfig):
"""Configures shared checkpoint configs."""
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``."""
output_dir: Annotated[
Path | None,
Field(
description="Override directory for checkpoints and weights. When set, checkpoints and weight snapshots are written here instead of under the trainer output_dir.",
),
] = None
interval: int | None = None
"""Interval at which to save checkpoints."""
interval: Annotated[int | None, Field(description="The interval at which to save checkpoints.")] = None
resume_step: int | None = None
"""Step to resume from. If None, does not resume from a checkpoint."""
resume_step: Annotated[
int | None, Field(description="The step to resume from. If None, will not resume from a checkpoint.")
] = None
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_last: Annotated[
int | None,
Field(
ge=1,
description="Keep at most this many recent step checkpoints on disk. If None, never clean old checkpoints based on recency.",
),
] = None
keep_interval: Annotated[
int | None,
Field(
ge=1,
description="Keep checkpoints at every N steps permanently (e.g., keep_interval=100 keeps step 100, 200, ...). If None, no interval-based keeping.",
),
] = None
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):
"""Configures shared model settings."""
name: str = "Qwen/Qwen3-0.6B"
"""HF model name or local path."""
name: Annotated[
str,
Field(description="The name of the model to use."),
] = "Qwen/Qwen3-0.6B"
vlm: Annotated[
"VLMConfig | None",
Field(description="VLM configuration. Set to enable vision-language model support."),
] = None
vlm: "VLMConfig | None" = None
"""VLM configuration. Set this to enable vision-language model support."""
class SharedWeightBroadcastConfig(BaseConfig):
"""Configures shared weight broadcast settings."""
type: Literal["nccl", "filesystem"] = "filesystem"
"""Weight broadcast transport."""
type: Annotated[Literal["nccl", "filesystem"], Field(description="The type of weight broadcast to use.")] = (
"filesystem"
)
port: int = 29501
"""Port for NCCL weight broadcast."""
port: Annotated[int, Field(description="The port to use for NCCL weight broadcast.")] = 29501
timeout: Annotated[int, Field(description="The timeout in seconds for NCCL weight broadcast.")] = 1200
quantize_in_weight_transfer: Annotated[
bool,
Field(
description=(
"Use kernel-format FP8 quantized NCCL transfer for weight updates. "
"When disabled, uses default HF checkpoint-format transfer."
),
),
] = False
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(BaseModel):
"""Configures a base deployment."""
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 deployment."""
type: Literal["single_node"] = "single_node"
num_train_gpus: Annotated[int, Field(description="Number of training GPUs")] = 1
num_infer_gpus: Annotated[int, Field(description="Number of inference GPUs")] = 1
num_teacher_gpus: Annotated[int | None, Field(description="Number of teacher inference GPUs")] = None
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):
@@ -198,33 +155,22 @@ class SingleNodeDeploymentConfig(BaseDeploymentConfig):
class MultiNodeDeploymentConfig(BaseDeploymentConfig):
"""Configures a multi node deployment."""
type: Literal["multi_node"] = "multi_node"
num_train_nodes: Annotated[int, Field(description="Number of training nodes.")]
num_infer_nodes: Annotated[
int,
Field(
ge=0,
description="Number of inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data).",
),
]
num_infer_replicas: Annotated[
int,
Field(
ge=1,
description="Number of independent inference replicas. Total inference nodes = num_infer_nodes * num_infer_replicas.",
),
] = 1
num_teacher_nodes: Annotated[int | None, Field(description="Number of teacher inference nodes.")] = None
num_train_nodes: int
"""Training nodes."""
nodes_per_fsdp_group: Annotated[
int | None,
Field(
description="Number of training nodes per FSDP island. Auto-sets trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group."
),
] = None
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:
@@ -243,127 +189,62 @@ DeploymentConfig: TypeAlias = Annotated[
class RLConfig(BaseConfig):
"""Configures an RL training run."""
trainer: TrainerConfig
orchestrator: OrchestratorConfig
inference: Annotated[
InferenceConfig | None,
Field(
description="The inference config. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."
),
] = None
teacher_inference: Annotated[
InferenceConfig | None,
Field(
description="Teacher inference config. If None, will use the same config as inference or a default config. Only used when teacher GPUs or nodes are set."
),
] = None
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)."""
output_dir: Annotated[
Path,
Field(
description="The directory to store the outputs. Should be set to a unique directory identifying the experiment."
),
] = Path("outputs")
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."""
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
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: Annotated[
SharedLogConfig,
Field(
description="Shared log configs. If None, will fallback to the log configs specified on submodule configs."
),
] = SharedLogConfig()
log: SharedLogConfig = SharedLogConfig()
"""Shared log config. Propagated to trainer and orchestrator."""
ckpt: Annotated[
SharedCheckpointConfig | None,
Field(
description="Shared checkpoint configs. If None, will fallback to the checkpoint configs specified on submodule configs."
),
] = None
ckpt: SharedCheckpointConfig | None = None
"""Shared checkpoint config. If None, falls back to the sub-config checkpoint settings."""
wandb: Annotated[
SharedWandbConfig | None,
Field(
description="Shared W&B configs. If None, will fallback to the W&B configs specified on submodule configs."
),
] = None
wandb: SharedWandbConfig | None = None
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
model: Annotated[
SharedModelConfig | None,
Field(
description="Shared model configs. If None, will fallback to the model configs specified on submodule configs."
),
] = None
model: SharedModelConfig | None = None
"""Shared model config. If None, falls back to the sub-config model settings."""
tokenizer: Annotated[
TokenizerConfig | None,
Field(
description="Shared tokenizer config. Propagated to trainer, orchestrator, and inference. "
"If None, each component uses its own tokenizer config (defaulting to model name).",
),
] = None
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: Annotated[
int | None,
Field(
description="The maximum number of steps to train for. If None, will fallback to the max steps specified on submodule configs."
),
] = None
max_steps: int | None = None
"""Shared maximum training steps. If None, falls back to the sub-config ``max_steps``."""
max_model_len: Annotated[
int | None,
Field(
description="The maximum model length to use. If None, will fallback to the max model length specified on submodule configs."
),
] = None
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."""
seq_len: Annotated[
int | None,
Field(
description="Shared sequence length. Propagates to trainer.model.seq_len and orchestrator.seq_len, "
"but only for those not explicitly set in the config. "
"Explicitly set per-component values always take precedence."
),
] = None
max_async_level: int | None = None
"""Shared async level. If None, falls back to the sub-config ``max_async_level``."""
max_async_level: Annotated[
int | None,
Field(
description="The async level to use. If None, will fallback to the async level specified on submodule configs."
),
] = None
weight_broadcast: SharedWeightBroadcastConfig | None = None
weight_broadcast: Annotated[
SharedWeightBroadcastConfig | None, Field(description="The weight broadcast config.")
] = None
bench: Annotated[
bool,
Field(
description="Whether to run in benchmark mode. Automatically sets the trainer and orchestrator to benchmark mode and, if present, suffixes the W&B project with `-bench`.",
),
] = False
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: Annotated[SlurmConfig | None, Field(description="SLURM configuration. If None, will run locally.")] = None
slurm: SlurmConfig | None = None
"""SLURM configuration. If None, runs 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[
RLExperimentalConfig,
Field(description="Experimental features for RL training."),
] = RLExperimentalConfig()
experimental: RLExperimentalConfig = RLExperimentalConfig()
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@@ -443,211 +324,30 @@ class RLConfig(BaseConfig):
return self
### Auto-setup and validate shared configs
### Auto-setup shared configs (before sub-config construction)
@model_validator(mode="after")
def auto_setup_output_dir(self):
"""Auto-setup shared output directory for trainer and orchestrator."""
self.trainer.output_dir = self.output_dir
self.orchestrator.output_dir = self.output_dir / "run_default"
validate_shared_output_dir(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_logs(self):
"""Auto-setup shared log config for trainer and orchestrator."""
if self.log is not None:
if self.log.level is not None:
self.trainer.log.level = self.log.level
self.orchestrator.log.level = self.log.level
self.trainer.log.json_logging = self.log.json_logging
self.orchestrator.log.json_logging = self.log.json_logging
return self
@model_validator(mode="after")
def auto_setup_ckpt(self):
"""Auto-setup shared checkpoint config for trainer and orchestrator."""
if self.ckpt is not None:
# Create checkpoint configs if not specified
if self.trainer.ckpt is None:
self.trainer.ckpt = TrainerCheckpointConfig()
if self.orchestrator.ckpt is None:
self.orchestrator.ckpt = OrchestratorCheckpointConfig()
# If specified, override checkpoint output directory
if self.ckpt.output_dir is not None:
self.trainer.ckpt.output_dir = self.ckpt.output_dir
# If specified, use the same ckpt interval
if self.ckpt.interval is not None:
self.trainer.ckpt.interval = self.ckpt.interval
self.orchestrator.ckpt.interval = self.ckpt.interval
# If resuming training, ensure orchestrator resume from the same step
if self.ckpt.resume_step is not None:
self.trainer.ckpt.resume_step = self.ckpt.resume_step
self.orchestrator.ckpt.resume_step = self.ckpt.resume_step
# If specified, propagate keep policy
if self.ckpt.keep_last is not None:
self.trainer.ckpt.keep_last = self.ckpt.keep_last
self.orchestrator.ckpt.keep_last = self.ckpt.keep_last
if self.ckpt.keep_interval is not None:
self.trainer.ckpt.keep_interval = self.ckpt.keep_interval
self.orchestrator.ckpt.keep_interval = self.ckpt.keep_interval
validate_shared_ckpt_config(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_wandb(self):
"""Auto-setup shared W&B config for trainer and orchestrator."""
if self.wandb is not None:
if not self.trainer.wandb:
self.trainer.wandb = WandbConfig()
if not self.orchestrator.wandb:
self.orchestrator.wandb = WandbWithExtrasConfig()
if self.wandb.project:
self.trainer.wandb.project = self.wandb.project
self.orchestrator.wandb.project = self.wandb.project
if self.wandb.entity:
self.trainer.wandb.entity = self.wandb.entity
self.orchestrator.wandb.entity = self.wandb.entity
if self.wandb.shared:
if self.wandb.name:
self.trainer.wandb.name = self.wandb.name
self.orchestrator.wandb.name = self.wandb.name
else:
if self.wandb.name:
self.trainer.wandb.name = f"{self.wandb.name}-trainer"
self.orchestrator.wandb.name = f"{self.wandb.name}-orchestrator"
if self.wandb.group:
self.trainer.wandb.group = self.wandb.group
self.orchestrator.wandb.group = self.wandb.group
if self.wandb.tags:
self.trainer.wandb.tags = self.wandb.tags.copy()
self.orchestrator.wandb.tags = self.wandb.tags.copy()
if self.wandb.offline:
self.trainer.wandb.offline = self.wandb.offline
self.orchestrator.wandb.offline = self.wandb.offline
validate_shared_wandb_config(self.trainer, self.orchestrator)
if self.orchestrator.prime_monitor is not None and self.orchestrator.prime_monitor.run_name is None:
if self.wandb and self.wandb.name:
self.orchestrator.prime_monitor.run_name = self.wandb.name
return self
@model_validator(mode="after")
def auto_setup_model(self):
"""Auto-setup shared model config for trainer, orchestrator, and inference."""
if self.model is not None:
self.trainer.model.name = self.model.name
if self.inference is not None:
inference_model_explicitly_set = "name" in self.inference.model.model_fields_set
if not inference_model_explicitly_set:
self.inference.model.name = self.model.name
self.orchestrator.student.model.name = self.inference.model.name
else:
self.orchestrator.student.model.name = self.model.name
if self.model.vlm is not None:
self.trainer.model.vlm = self.model.vlm
self.orchestrator.student.model.vlm = self.model.vlm
if self.inference is not None:
self.inference.model.vlm = self.model.vlm
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_tokenizer(self):
"""Auto-setup shared tokenizer config for trainer, orchestrator, and inference."""
if self.tokenizer is not None:
# Shared tokenizer config: propagate to all components, then fill
# in name/trust_remote_code from model config where still unset.
self.trainer.tokenizer = self.tokenizer.model_copy()
self.orchestrator.tokenizer = self.tokenizer.model_copy()
if self.trainer.tokenizer.name is None:
self.trainer.tokenizer.name = self.trainer.model.name
if self.trainer.tokenizer.trust_remote_code is None:
self.trainer.tokenizer.trust_remote_code = self.trainer.model.trust_remote_code
if self.orchestrator.tokenizer.name is None:
self.orchestrator.tokenizer.name = self.orchestrator.student.model.name
if self.orchestrator.tokenizer.trust_remote_code is None:
self.orchestrator.tokenizer.trust_remote_code = self.orchestrator.student.model.trust_remote_code
else:
# No shared tokenizer: re-derive from (now-correct) model names,
# since auto_setup_tokenizer on sub-configs already ran with defaults.
self.trainer.tokenizer.name = self.trainer.model.name
self.trainer.tokenizer.trust_remote_code = self.trainer.model.trust_remote_code
self.orchestrator.tokenizer.name = self.orchestrator.student.model.name
self.orchestrator.tokenizer.trust_remote_code = self.orchestrator.student.model.trust_remote_code
# Propagate chat_template to inference (vLLM --chat-template)
if self.inference is not None:
chat_template = self.trainer.tokenizer.chat_template
if chat_template is not None and self.inference.model.chat_template is None:
self.inference.model.chat_template = chat_template
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
return self
@model_validator(mode="after")
def auto_setup_max_steps(self):
"""Auto-setup shared max steps for trainer and orchestrator."""
if self.max_steps is not None:
self.trainer.max_steps = self.max_steps
self.orchestrator.max_steps = self.max_steps
validate_shared_max_steps(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_async_level(self):
"""Auto-setup shared async level for trainer and orchestrator."""
if self.max_async_level is not None:
self.trainer.max_async_level = self.max_async_level
self.orchestrator.max_async_level = self.max_async_level
validate_shared_max_async_level(self.trainer, self.orchestrator)
return self
@model_validator(mode="after")
def auto_setup_seq_len(self):
"""Auto-setup shared seq_len for trainer and orchestrator.
Only propagates to components that weren't explicitly set in the config.
Uses model_fields_set to detect explicit assignment.
@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.
"""
if self.seq_len is not None:
if "seq_len" not in self.trainer.model.model_fields_set:
self.trainer.model.seq_len = self.seq_len
if "seq_len" not in self.orchestrator.model_fields_set:
self.orchestrator.seq_len = self.seq_len
return propagate_shared_fields(data)
if self.trainer.model.seq_len < self.orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({self.trainer.model.seq_len}) must be >= orchestrator seq_len ({self.orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
### 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")
@@ -767,12 +467,6 @@ class RLConfig(BaseConfig):
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.orchestrator.student.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
return self
@model_validator(mode="after")
def auto_setup_router_replay(self):
if self.trainer.enable_router_replay:
@@ -2,7 +2,7 @@ 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,
@@ -25,13 +25,18 @@ from prime_rl.configs.trainer import (
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):
@@ -43,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):
@@ -110,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):
@@ -141,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[
@@ -161,139 +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 renderer configuration (only used when use_renderer=True)
renderer: RendererConfig = RendererConfig()
"""Client-side renderer configuration. Only consumed when ``use_renderer=true``."""
use_renderer: Annotated[
bool,
Field(
description=(
"If True, 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)."
),
),
] = False
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)."""
# The data configuration
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
@@ -2,61 +2,38 @@ import os
from pathlib import Path
from typing import Annotated, Literal, TypeAlias
from pydantic import BaseModel, Field, model_validator
from pydantic import Field, model_validator
from prime_rl.utils.config import BaseConfig
class SlurmConfig(BaseConfig):
"""Configures SLURM scheduling."""
job_name: str = "prime-rl"
"""SLURM job name."""
job_name: Annotated[str, Field(description="The SLURM job name.")] = "prime-rl"
project_dir: Path = Path(".")
"""Path to the project root, used to source .env, activate .venv, and run uv sync."""
project_dir: Annotated[
Path,
Field(description="Path to the project root. Used to source .env, activate .venv, and run uv sync."),
] = Path(".")
template_path: Path | None = None
"""SLURM template file. If None, uses the bundled single-node or multi-node template."""
template_path: Annotated[
Path | None,
Field(
description="The path to the SLURM template file. If None, will use the default single-node/multi-node template."
),
] = None
partition: str = "cluster"
"""SLURM partition (#SBATCH --partition)."""
partition: Annotated[
str, Field(description="The SLURM partition to use. Will be passed as #SBATCH --partition.")
] = "cluster"
nodelist: str | None = None
"""Comma-separated list of specific nodes to run on (#SBATCH --nodelist)."""
nodelist: Annotated[
str | None,
Field(description="Comma-separated list of specific nodes to run on. Passed as #SBATCH --nodelist."),
] = None
exclude: str | None = None
"""Comma-separated list of nodes to exclude (#SBATCH --exclude)."""
exclude: Annotated[
str | None,
Field(description="Comma-separated list of nodes to exclude. Passed as #SBATCH --exclude."),
] = None
account: str | None = None
"""SLURM account to charge (#SBATCH --account)."""
account: Annotated[
str | None,
Field(description="SLURM account to charge. Passed as #SBATCH --account."),
] = None
time: str | None = None
"""Maximum wall time, e.g. '24:00:00' or '7-00:00:00' (#SBATCH --time)."""
time: Annotated[
str | None,
Field(description="Maximum wall time (e.g. '24:00:00', '7-00:00:00'). Passed as #SBATCH --time."),
] = None
pre_run_command: Annotated[
str | None,
Field(
description="Shell command to run on the head node before starting the job. "
"Runs after cd into project dir, .env sourcing, and venv activation. "
"Useful for cleanup routines like 'sudo pkill -f vllm'. "
"To run on all nodes, wrap with srun: 'srun bash -c \"pkill -f vllm || true\"'.",
),
] = None
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:
@@ -82,54 +59,25 @@ ServerType = Literal["vllm", "openai"]
class VLMConfig(BaseConfig):
"""Configures vision-language model support.
vision_encoder_attr: str
"""Dotted attribute path to the vision encoder module (e.g. ``model.visual``)."""
Presence of this config enables VLM mode. You must specify where the
vision encoder and language model live on the model object.
language_model_attr: str
"""Dotted attribute path to the language model module (e.g. ``model.language_model``)."""
Usage:
[model.vlm]
vision_encoder_attr = "model.visual"
language_model_attr = "model.language_model"
"""
vision_encoder_attr: Annotated[
str,
Field(description="Dotted attribute path to the vision encoder module (e.g. 'model.visual')."),
]
language_model_attr: Annotated[
str,
Field(description="Dotted attribute path to the language model module (e.g. 'model.language_model')."),
]
freeze_vision_encoder: Annotated[
bool,
Field(
description="Whether to freeze the vision encoder. When False, the vision encoder is trainable "
"and FSDP-sharded per-block. Has no effect with LoRA (LoRA freezes all non-adapter parameters).",
),
] = True
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):
"""Configures the model."""
name: str = "Qwen/Qwen3-0.6B"
"""HF model name or local path."""
name: Annotated[str, Field(description="Name or path of the HF model to use.")] = "Qwen/Qwen3-0.6B"
trust_remote_code: bool = False
"""Trust remote code when initializing the tokenizer."""
trust_remote_code: Annotated[
bool,
Field(
description="Whether to trust remote code for tokenizer initialization.",
),
] = False
vlm: Annotated[
"VLMConfig | None",
Field(
description="VLM configuration. Set this to enable vision-language model support.",
),
] = None
vlm: "VLMConfig | None" = None
"""VLM configuration. Setting this enables vision-language model support."""
@property
def is_vlm(self) -> bool:
@@ -137,234 +85,75 @@ class BaseModelConfig(BaseConfig):
class RendererConfig(BaseConfig):
"""Configures the client-side renderer (chat-template + response parsing).
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``."""
Consumed when ``use_renderer = true``. The renderer
owns both directions: render messages → token ids on the client, and
parse model output tokens → structured ``content`` / ``reasoning_content``
/ ``tool_calls``.
"""
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``."""
name: Annotated[
str,
Field(
description=(
"Renderer to use for chat template tokenization. "
"Options: 'auto' (detect from tokenizer), 'qwen3', 'qwen3_vl', "
"'qwen3.5', 'glm5', 'glm4.5', 'minimax-m2', 'deepseek_v3', "
"'kimi_k2', 'kimi_k25', 'nemotron3', 'gpt_oss', 'default'."
),
),
] = "auto"
reasoning_parser: str | None = None
"""Reasoning parser from ``renderers.parsers``. Only consumed by DefaultRenderer. Options: ``think``."""
tool_parser: Annotated[
str | None,
Field(
description=(
"Name of a tool parser in renderers.parsers. Only consumed by "
"DefaultRenderer (model-specific renderers bake their own parsing "
"in). Options today: 'qwen3', 'qwen3.5', 'glm', 'deepseek_v3'."
),
),
] = None
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."""
reasoning_parser: Annotated[
str | None,
Field(
description=(
"Name of a reasoning parser in renderers.parsers. Only consumed "
"by DefaultRenderer. Options today: 'think'."
),
),
] = None
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."""
pool_size: Annotated[
int | None,
Field(
ge=1,
description=(
"Number of renderer slots shared across concurrent rollouts. "
"None keeps the verifiers default (1). Bump for long multi-turn "
"prompts where client-side jinja tokenization serializes."
),
),
] = None
preserve_all_thinking: Annotated[
bool,
Field(
description=(
"Override flag forwarded to the renderer at construction. When "
"True, every past-assistant turn's ``reasoning_content`` is "
"re-emitted between ``<think>``/``</think>`` (or the model's "
"equivalent), even if the underlying chat template would drop "
"it. Off by default — preserves byte-identical output to the "
"stock template. Strict superset of "
"``preserve_thinking_between_tool_calls``."
),
),
] = False
preserve_thinking_between_tool_calls: Annotated[
bool,
Field(
description=(
"Override flag forwarded to the renderer at construction. When "
"True, preserves 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; older blocks fall back to "
"the template default (typically dropped). Use "
"``preserve_all_thinking`` to keep older blocks too."
),
),
] = False
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):
"""Configures elastic inference pool with DNS-based service discovery.
hostname: str
"""DNS hostname that resolves to inference server IPs."""
Works with any DNS hostname that resolves to multiple IP addresses.
"""
port: int = 8000
"""Port that inference servers listen on."""
hostname: Annotated[
str,
Field(
description="DNS hostname that resolves to inference server IPs.",
),
]
port: Annotated[
int,
Field(
description="Port that inference servers listen on.",
),
] = 8000
sync_interval: Annotated[
float,
Field(
description="Interval in seconds between server discovery checks.",
),
] = 5.0
sync_interval: float = 5.0
"""Seconds between server discovery checks."""
class ClientConfig(BaseConfig):
"""Configures the OAI client.
timeout: int = 1200
"""Request timeout in seconds."""
Supports two modes:
- Static mode (default): Uses fixed base_url list
- Elastic mode: Uses DNS-based service discovery via hostname
connect_timeout: float = 30.0
"""TCP connect timeout in seconds for inference API requests."""
If elastic config is provided, base_url is ignored and servers are discovered dynamically.
"""
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."""
timeout: Annotated[
int,
Field(
description="Timeout in seconds. By default, it is set to 1200 seconds.",
),
] = 1200
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."""
connect_timeout: Annotated[
float,
Field(
description="TCP connect timeout in seconds for inference API requests.",
),
] = 30.0
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."""
wait_for_ready_timeout: Annotated[
int,
Field(
description="Timeout in seconds for waiting for the inference pool to become ready at startup. "
"Applies to both the static health check and elastic DNS-based discovery. Defaults to 1800 seconds.",
),
] = 1800
headers: dict[str, str] = {}
"""Static headers sent with every request."""
base_url: Annotated[
list[str],
Field(
description="Base URLs to use for the OpenAI API. By default, it is set to a single server on localhost at port 8000 which matches the default local vLLM server configuration. If you specify more than one URL, the client will round-robin (chat) completion requests across all servers. Ignored if elastic config is provided.",
),
] = ["http://localhost:8000/v1"]
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"}``."""
api_key_var: Annotated[
str,
Field(
description="Name of environment variable containing the API key to use for the inference API. Will parse using `os.getenv(client_config.api_key_var)`. Can be set to an arbitrary string if the inference server is not protected by an API key. If multiple URLs are specified, the same API key will be used for all servers.",
),
] = "VLLM_API_KEY"
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."""
headers: Annotated[
dict[str, str],
Field(
description="Headers to use for the OpenAI API. By default, it is set to an empty dictionary.",
),
] = {}
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``."""
headers_from_env: Annotated[
dict[str, str],
Field(
description='Maps HTTP header names to environment variable names. At runtime each entry is resolved via os.getenv and merged into the request headers. e.g. {"X-Prime-Team-ID": "PRIME_TEAM_ID"}.',
),
] = {}
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."""
extra_headers_from_state: Annotated[
dict[str, str],
Field(
description="Maps HTTP header names to state field names. For each inference request, "
"the header value is dynamically read from the rollout state dict. "
'e.g. {"X-Session-ID": "example_id"} enables sticky routing at the inference router.',
),
] = {}
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."""
skip_model_check: Annotated[
bool,
Field(
description="Whether to skip checking if the model is available in the inference pool. Useful for external APIs or API Keys that don't support the /models endpoint.",
),
] = False
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."""
dp_rank_count: Annotated[
int,
Field(
ge=1,
description=(
"Number of data-parallel ranks behind each base URL. When > 1, "
"each URL is expanded into dp_rank_count logical clients, each "
"pinned to a specific DP rank via the X-data-parallel-rank header. "
"This ensures all requests within a multi-turn rollout hit the same "
"DP engine, maximizing KV cache reuse. Auto-set from "
"inference.data_parallel_size_local (or inference.parallel.dp) "
"when using the RL entrypoint."
),
),
] = 1
admin_base_url: Annotated[
list[str] | None,
Field(
description="Separate base URLs for admin operations (weight updates, health checks). "
"When set, admin clients use these URLs instead of base_url, allowing weight "
"updates to bypass routers and hit each server directly. Used in disaggregated "
"P/D deployments where the inference router should not handle admin traffic.",
),
] = None
elastic: Annotated[
ElasticConfig | None,
Field(
description="Elastic inference pool configuration for DNS-based service discovery. If provided, base_url is ignored and inference servers are discovered dynamically via DNS.",
),
] = None
router_url: Annotated[
str | None,
Field(
description="URL of a vllm-router for load-aware inference routing. When set with elastic mode, inference requests go through the router while admin operations (weight updates, LoRA loading) still go directly to discovered pods.",
),
] = None
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:
@@ -373,225 +162,116 @@ class ClientConfig(BaseConfig):
class LogConfig(BaseConfig):
"""Configures the logger."""
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``."""
level: Annotated[
str,
Field(
default_factory=lambda: os.environ.get("PRIME_LOG_LEVEL", "info"),
description="Logging level for the process. Will determine the logging verbosity and format. Defaults to the PRIME_LOG_LEVEL env var 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``."""
vf_level: Annotated[
str,
Field(
default_factory=lambda: os.environ.get("PRIME_VF_LOG_LEVEL", "info"),
description="Logging level for the verifiers package. Will determine the logging verbosity and format. Defaults to the PRIME_VF_LOG_LEVEL env var if set, else 'info'.",
),
]
json_logging: bool = False
"""Emit newline-delimited JSON logs for aggregation (Loki, Grafana, etc.)."""
json_logging: Annotated[
bool,
Field(
description="Emit JSON logs (newline-delimited) for log aggregation (Loki, Grafana, etc.).",
),
] = False
log_data: Annotated[
bool,
Field(
description="Whether to log the first data sample to the logger.",
),
] = False
log_data: bool = False
"""Log the first data sample at startup."""
class TrainerLogConfig(LogConfig):
"""Trainer-specific log config."""
ranks_filter: Annotated[
list[int],
Field(description="Which trainer ranks to show in console output. Passed to torchrun's --local-ranks-filter."),
] = [0]
ranks_filter: list[int] = [0]
"""Trainer ranks to show in console output. Passed to ``torchrun --local-ranks-filter``."""
class LogExtrasConfig(BaseConfig):
"""Configures extra logging for monitoring platforms."""
samples: bool = True
"""Log prompt/response samples."""
samples: Annotated[
bool,
Field(
description="Whether to log prompt/response samples.",
),
] = True
distributions: bool = True
"""Log distributions (rewards, advantages, etc.)."""
distributions: Annotated[
bool,
Field(
description="Whether to log distributions (like rewards, advantages, etc.).",
),
] = True
interval: int = Field(10, ge=1)
"""Step interval between extras logs."""
interval: Annotated[
int,
Field(
ge=1,
description="Step interval at which to log extras.",
),
] = 10
sample_ratio: Annotated[
float | None,
Field(
ge=0.0,
le=1.0,
description="Fraction of rollouts to log per step (0.0–1.0). "
"When set, the effective sample cap is len(rollouts) * sample_ratio. "
"1.0 = all rollouts, 0.5 = half, 0.0 = none. "
"None (default)",
),
] = None
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):
"""Configures logging to Weights and Biases."""
# Shared configs (May be overwritten by WandbConfig from `rl.py`)
project: Annotated[str, Field(description="The W&B project to log to.")] = "prime-rl"
project: str = "prime-rl"
"""W&B project to log to."""
entity: Annotated[
str | None,
Field(
description="The W&B entity to log to.",
),
] = None
entity: str | None = None
"""W&B entity to log to."""
name: Annotated[
str | None,
Field(
description="The W&B name to to use for logging.",
),
] = None
name: str | None = None
"""W&B run name."""
group: Annotated[
str | None,
Field(
description="The W&B group to use for logging.",
),
] = None
group: str | None = None
"""W&B group."""
tags: Annotated[
list[str] | None,
Field(
description="The W&B tags to attach to the run.",
),
] = None
tags: list[str] | None = None
"""W&B tags attached to the run."""
offline: Annotated[bool, Field(description="Whether to run W&B in offline mode.")] = False
offline: bool = False
"""Run W&B in offline mode."""
class WandbWithExtrasConfig(WandbConfig):
"""Configures logging to Weights and Biases with extras."""
log_extras: Annotated[
LogExtrasConfig | None,
Field(
description="Configuration for logging extras. If None, no extras are logged.",
),
] = LogExtrasConfig()
log_extras: LogExtrasConfig | None = LogExtrasConfig()
"""Extras logging configuration. If None, no extras are logged."""
class PrimeMonitorConfig(BaseConfig):
"""Configures logging to Prime Intellect API."""
base_url: str = "https://api.primeintellect.ai/api/v1/rft"
"""Base URL for the Prime Intellect monitoring API."""
base_url: Annotated[
str,
Field(
description="The base URL for Prime Intellect monitoring API.",
),
] = "https://api.primeintellect.ai/api/v1/rft"
api_key_var: str = "PRIME_API_KEY"
"""Environment variable name containing the Prime Intellect API key, resolved via ``os.getenv``."""
api_key_var: Annotated[
str,
Field(
description="Name of environment variable containing the API key for Prime Intellect API. Will parse using `os.getenv(config.api_key_var)`.",
),
] = "PRIME_API_KEY"
log_extras: LogExtrasConfig | None = LogExtrasConfig()
"""Extras logging configuration. If None, no extras are logged."""
log_extras: Annotated[
LogExtrasConfig | None,
Field(
description="Configuration for logging extras. If None, no extras are logged.",
),
] = LogExtrasConfig()
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."""
run_name: Annotated[
str | None,
Field(
description="Name for the run shown on the platform. Defaults to the W&B run name if set, otherwise auto-generated by the platform.",
),
] = None
team_id: str | None = None
"""Team ID to associate the run with."""
team_id: Annotated[
str | None,
Field(
description="Team ID to associate the run with.",
),
] = None
frontend_url: Annotated[
str | None,
Field(
description="Frontend base URL used for the dashboard link shown after registration. Defaults to the Prime CLI frontend URL when unset.",
),
] = None
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):
"""Configures the heartbeat for BetterStack."""
url: Annotated[str, Field(description="The URL to send the heartbeat to.")]
url: str
"""URL to send the heartbeat to."""
class MetricsServerConfig(BaseConfig):
"""Configures the Prometheus metrics server for trainer observability."""
port: int = Field(8000, ge=1, le=65535)
"""Port to expose metrics and health endpoints on."""
port: Annotated[
int,
Field(
ge=1,
le=65535,
description="Port to expose metrics and health endpoints. Defaults to 8000.",
),
] = 8000
host: Annotated[
str,
Field(
description="Host to bind the server to. Defaults to 0.0.0.0.",
),
] = "0.0.0.0"
host: str = "0.0.0.0"
"""Host to bind the server to."""
class BaseTransportConfig(BaseModel):
"""Base configuration for transport."""
class BaseTransportConfig(BaseConfig):
pass
class FileSystemTransportConfig(BaseTransportConfig):
"""Configures filesystem-based transport for training examples."""
type: Literal["filesystem"] = "filesystem"
class ZMQTransportConfig(BaseTransportConfig):
"""Configures ZMQ-based transport for training examples."""
type: Literal["zmq"] = "zmq"
host: Annotated[str, Field(description="The host address for ZMQ transport.")] = "localhost"
port: Annotated[int, Field(description="The base port for ZMQ transport.")] = 5555
hwm: Annotated[int, Field(description="High water mark (max messages in queue) for ZMQ sockets.")] = 10
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")]
File diff suppressed because it is too large Load Diff
@@ -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)
@@ -1,12 +1,184 @@
from __future__ import annotations
from typing import Optional
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,
@@ -104,6 +276,17 @@ def validate_shared_max_async_level(
)
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,
+5 -5
View File
@@ -1,6 +1,6 @@
[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"
@@ -42,8 +42,8 @@ dependencies = [
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"]
@@ -124,6 +124,7 @@ dev = [
[tool.uv.workspace]
members = [
"packages/prime-rl-configs",
"deps/pydantic-config",
"deps/verifiers",
"deps/renderers",
"deps/verifiers/environments/alphabet_sort",
@@ -186,7 +187,6 @@ prime-evals = false
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
vllm-router = false
dion = false
pydantic-config = false
deep-ep = false
deep-gemm = false
nixl-cu12 = false
@@ -229,7 +229,7 @@ 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" }
prime-pydantic-config = { workspace = true }
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" }
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
-195
View File
@@ -1,195 +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`.
When composing multiple TOML files, list fields are replaced wholesale by the later file. To change one
`orchestrator.filters` entry in an overlay, include the full desired filter list in that overlay.
For quick KL smoke runs with very small rollout batches, enforced `zero_advantage` filtering can remove
every rollout and stop the orchestrator. If the goal is only trainer/inference mismatch KL, keep the
filter present but set `enforce = false` in a temporary overlay and call out that the run is not a reward
learning validation.
### 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
Set `orchestrator.training_mode = "sft"` (or top-level `training_mode = "sft"`, which auto-propagates) and configure `orchestrator.teacher` with the teacher endpoint. The orchestrator stamps each `TrainingSample.sft_loss = True` and the shared `training_mode` validator sets `trainer.loss.type = "sft"`, which the trainer's `compute_loss` honors by dispatching to `sft_loss_fn` per batch.
`[inference]` is required (same as rl/opd) — it starts the student inference server and auto-configures `orchestrator.student.client.base_url`. The student pool is used for online evals and policy weight sync. For externally started student inference, set `orchestrator.student.client.base_url` explicitly instead.
### RL rollout client defaults
For text-only RL rollouts, the orchestrator defaults to renderer-backed TITO (`use_renderer = true`). VLM configs must explicitly fall back to MITO (`use_renderer = false`) so image preprocessing and chat templating stay server-side. External teacher rollouts must also set `use_renderer = false`.
### 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
- `configs/private/` — private configs via git submodule (internal only)
- `examples/` — full example configs for various tasks
+68
View File
@@ -0,0 +1,68 @@
---
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.
## 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:
- `/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
- `configs/private/` — private configs submodule (if access granted)
- `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
-99
View File
@@ -1,99 +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
## Cloning
prime-rl is a monorepo with submodules. Clone the repo first, then initialize submodules explicitly:
```bash
git clone git@github.com:PrimeIntellect-ai/prime-rl.git
cd prime-rl
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
```
For an existing clone, initialize the public submodules by passing explicit paths:
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments deps/pydantic-config
```
Do **not** use `git submodule update --init --recursive` without explicit paths — it will also attempt to clone `configs/private` (a private submodule) and fail with "Repository not found" for users without access. Git will retry the clone once internally before aborting, which is expected behavior.
The public submodules live under `deps/`: `deps/verifiers/`, `deps/renderers/`, `deps/research-environments/`, and `deps/pydantic-config/`. The uv workspace members among them apply source edits to the prime-rl venv without re-sync.
The install script (`scripts/install.sh`) handles the private submodule gracefully — it iterates each submodule individually so a failed `configs/private` init does not abort the rest.
## Basic
```bash
uv sync # core dependencies only
uv sync --group dev # dev tools: pytest, ruff, pre-commit
uv sync --all-extras # recommended: includes envs, flash-attn, flash-attn-cute, etc.
```
The `envs` extra installs the env packages listed in `pyproject.toml > [tool.uv.workspace] members`. Adding a new env means adding it there, in the `envs` extra, and in `[tool.uv.sources]`.
When intentionally bumping a package to a release newer than the workspace-wide `exclude-newer = "7 days"` window, add that package and any newly required transitive packages to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
## 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`)
-255
View File
@@ -1,255 +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/{all,env}/{mean,std,max}` | trainer | KL divergence between trainer and (old) inference policy over trainable tokens (W&B) |
| `entropy/{all,env}/{mean,std,max}` | trainer | policy entropy over trainable tokens (W&B) |
| `masked_advantage_positive/mean` | trainer | fraction of DPPO-masked trainable tokens with positive advantage (W&B) |
| `masked_advantage_negative/mean` | trainer | fraction of DPPO-masked trainable tokens with negative advantage (W&B) |
| `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/`)
+28
View File
@@ -0,0 +1,28 @@
"""Lightweight launcher for the orchestrator.
Defers heavy ML imports (verifiers, transformers, pandas, prime_rl.trainer.*)
until after ``cli()`` parses CLI args, so ``orchestrator --help`` short-circuits
in ``cli()`` and returns in ~0.5 s instead of ~9 s.
The actual orchestrator implementation lives in
``prime_rl.orchestrator.orchestrator``, which is also runnable as
``python -m prime_rl.orchestrator.orchestrator``.
"""
import asyncio
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Orchestrator")
config = cli(OrchestratorConfig)
from prime_rl.orchestrator.orchestrator import orchestrate
asyncio.run(orchestrate(config))
if __name__ == "__main__":
main()
+5 -6
View File
@@ -12,23 +12,18 @@ from threading import Event, Thread
import pynvml
import tomli_w
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
from prime_rl.configs.rl import RLConfig
from prime_rl.trainer.model import pre_download_model
from prime_rl.utils.config import cli
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
format_log_message,
get_ckpt_dir,
get_log_dir,
resolve_latest_ckpt_step,
validate_output_dir,
)
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process, set_proc_title
from prime_rl.utils.utils import (
get_free_port,
get_log_dir,
)
RL_TOML = "rl.toml"
RL_SBATCH = "rl.sbatch"
@@ -275,6 +270,8 @@ def rl_local(config: RLConfig):
monitor_threads.append(monitor_thread)
# Start training process
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
@@ -544,6 +541,8 @@ def rl(config: RLConfig):
clean_future_steps(config.output_dir, -1)
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
pre_download_model(config.trainer.model.name)
if config.slurm is not None:
+4 -3
View File
@@ -8,14 +8,11 @@ from threading import Event, Thread
import tomli_w
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
from prime_rl.configs.sft import SFTConfig
from prime_rl.trainer.model import pre_download_model
from prime_rl.utils.config import cli
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir, validate_output_dir
from prime_rl.utils.process import cleanup_processes, cleanup_threads, monitor_process, set_proc_title
from prime_rl.utils.utils import get_free_port
SFT_TOML = "sft.toml"
SFT_SBATCH = "sft.sbatch"
@@ -115,6 +112,8 @@ def sft_local(config: SFTConfig):
log_dir = config.output_dir / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
from prime_rl.utils.utils import get_free_port
trainer_cmd = [
"torchrun",
"--role=trainer",
@@ -199,6 +198,8 @@ def sft(config: SFTConfig):
config.output_dir.mkdir(parents=True, exist_ok=True)
if not config.dry_run:
from prime_rl.trainer.model import pre_download_model
pre_download_model(config.model.name)
if config.slurm is not None:
+26
View File
@@ -0,0 +1,26 @@
"""Lightweight launcher for the RL trainer.
Defers heavy ML imports (torch, transformers, torchtitan, ring_flash_attn,
prime_rl.trainer.*) until after ``cli()`` parses CLI args, so ``trainer --help``
short-circuits in ``cli()`` and returns in ~0.5 s instead of ~10 s.
The actual training implementation lives in ``prime_rl.trainer.rl.train``,
which is also runnable as ``python -m prime_rl.trainer.rl.train`` (used by
the ``rl`` launcher under torchrun).
"""
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.utils.config import cli
from prime_rl.utils.process import set_proc_title
def main():
set_proc_title("Trainer")
config = cli(TrainerConfig)
from prime_rl.trainer.rl.train import train
train(config)
if __name__ == "__main__":
main()
-116
View File
@@ -18,117 +18,6 @@ from vllm.utils.argparse_utils import FlexibleArgumentParser
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.logger import get_logger
MODEL_TOOL_CALL_PARSER: dict[str, str] = {
# GLM-4.5
"zai-org/GLM-4.5": "glm45",
"zai-org/GLM-4.5-FP8": "glm45",
"zai-org/GLM-4.5-Base": "glm45",
"zai-org/GLM-4.5-Air": "glm45",
"zai-org/GLM-4.5-Air-FP8": "glm45",
"zai-org/GLM-4.5-Air-Base": "glm45",
"zai-org/GLM-4.5V": "glm45",
"zai-org/GLM-4.5V-FP8": "glm45",
# GLM-4.7
"zai-org/GLM-4.7": "glm47",
"zai-org/GLM-4.7-FP8": "glm47",
"zai-org/GLM-4.7-Flash": "glm47",
# GLM-5
"zai-org/GLM-5": "glm47",
"zai-org/GLM-5-FP8": "glm47",
# GLM-5.1
"zai-org/GLM-5.1": "glm47",
"zai-org/GLM-5.1-FP8": "glm47",
# MiniMax M2
"MiniMaxAI/MiniMax-M2": "minimax_m2",
"MiniMaxAI/MiniMax-M2.1": "minimax_m2",
"MiniMaxAI/MiniMax-M2.5": "minimax_m2",
# INTELLECT-3
"PrimeIntellect/INTELLECT-3": "hermes",
"PrimeIntellect/INTELLECT-3-FP8": "hermes",
"PrimeIntellect/INTELLECT-3.1": "hermes",
# Qwen3 dense
"Qwen/Qwen3-0.6B": "hermes",
"Qwen/Qwen3-0.6B-Base": "hermes",
"Qwen/Qwen3-0.6B-FP8": "hermes",
"Qwen/Qwen3-1.7B": "hermes",
"Qwen/Qwen3-1.7B-Base": "hermes",
"Qwen/Qwen3-1.7B-FP8": "hermes",
"Qwen/Qwen3-4B": "hermes",
"Qwen/Qwen3-4B-Base": "hermes",
"Qwen/Qwen3-4B-FP8": "hermes",
"Qwen/Qwen3-8B": "hermes",
"Qwen/Qwen3-8B-Base": "hermes",
"Qwen/Qwen3-8B-FP8": "hermes",
"Qwen/Qwen3-14B": "hermes",
"Qwen/Qwen3-14B-Base": "hermes",
"Qwen/Qwen3-14B-FP8": "hermes",
"Qwen/Qwen3-32B": "hermes",
"Qwen/Qwen3-32B-FP8": "hermes",
# Qwen3 MoE
"Qwen/Qwen3-30B-A3B": "hermes",
"Qwen/Qwen3-30B-A3B-Base": "hermes",
"Qwen/Qwen3-30B-A3B-FP8": "hermes",
"Qwen/Qwen3-235B-A22B": "hermes",
"Qwen/Qwen3-235B-A22B-FP8": "hermes",
# Qwen3 2507
"Qwen/Qwen3-4B-Instruct-2507": "hermes",
"Qwen/Qwen3-4B-Thinking-2507": "hermes",
"Qwen/Qwen3-4B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-4B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507": "hermes",
"Qwen/Qwen3-30B-A3B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-30B-A3B-Thinking-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507": "hermes",
"Qwen/Qwen3-235B-A22B-Instruct-2507-FP8": "hermes",
"Qwen/Qwen3-235B-A22B-Thinking-2507-FP8": "hermes",
# Qwen3-Next
"Qwen/Qwen3-Next-80B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Next-80B-A3B-Thinking-FP8": "hermes",
# Qwen3-Coder
"Qwen/Qwen3-Coder-480B-A35B-Instruct": "hermes",
"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct": "hermes",
"Qwen/Qwen3-Coder-30B-A3B-Instruct-FP8": "hermes",
# Qwen3-Coder-Next
"Qwen/Qwen3-Coder-Next": "hermes",
"Qwen/Qwen3-Coder-Next-Base": "hermes",
"Qwen/Qwen3-Coder-Next-FP8": "hermes",
# Qwen3.5 dense (uses qwen3_coder tool format, not hermes)
"Qwen/Qwen3.5-0.8B": "qwen3_coder",
"Qwen/Qwen3.5-0.8B-Base": "qwen3_coder",
"Qwen/Qwen3.5-2B": "qwen3_coder",
"Qwen/Qwen3.5-2B-Base": "qwen3_coder",
"Qwen/Qwen3.5-4B": "qwen3_coder",
"Qwen/Qwen3.5-4B-Base": "qwen3_coder",
"Qwen/Qwen3.5-9B": "qwen3_coder",
"Qwen/Qwen3.5-9B-Base": "qwen3_coder",
"Qwen/Qwen3.5-27B": "qwen3_coder",
"Qwen/Qwen3.5-27B-FP8": "qwen3_coder",
# Qwen3.5 MoE (uses qwen3_coder tool format, not hermes)
"Qwen/Qwen3.5-35B-A3B": "qwen3_coder",
"Qwen/Qwen3.5-35B-A3B-Base": "qwen3_coder",
"Qwen/Qwen3.5-35B-A3B-FP8": "qwen3_coder",
"Qwen/Qwen3.5-122B-A10B": "qwen3_coder",
"Qwen/Qwen3.5-122B-A10B-FP8": "qwen3_coder",
"Qwen/Qwen3.5-397B-A17B": "qwen3_coder",
"Qwen/Qwen3.5-397B-A17B-FP8": "qwen3_coder",
# NemotronH
"nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16": "qwen3_coder",
"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16": "qwen3_coder",
}
def resolve_tool_call_parser(model_name: str, tool_call_parser: str | None) -> str | None:
"""Resolve tool_call_parser from model name if set to "auto"."""
if tool_call_parser == "auto":
return MODEL_TOOL_CALL_PARSER.get(model_name)
return tool_call_parser
logger = get_logger()
from prime_rl.inference.patches import (
monkey_patch_harmony_stop_token_propagation,
@@ -313,11 +202,6 @@ def server(config: InferenceConfig, vllm_extra: dict[str, Any] | None = None):
assert args is not None
validate_parsed_serve_args(args)
args.tool_call_parser = resolve_tool_call_parser(args.model, args.tool_call_parser)
args.enable_auto_tool_choice = args.tool_call_parser is not None
if args.tool_call_parser is not None:
logger.info(f"Using tool_call_parser='{args.tool_call_parser}' for model '{args.model}'")
# Set the worker extension class based on the broadcast backend
args.worker_extension_cls = WORKER_EXTENSION_CLS[config.weight_broadcast.type]
+40 -68
View File
@@ -13,7 +13,6 @@ from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
from prime_rl.orchestrator.trajectories import (
build_vlm_image_cache,
interleave_rollout,
offload_images_to_disk,
pretokenize_rollout_trajectory,
@@ -34,7 +33,6 @@ monkey_patch_chat_completion_logprobs()
import pandas as pd
import verifiers as vf
from renderers.base import create_renderer
from transformers import AutoProcessor
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.buffer import Buffer
@@ -118,17 +116,9 @@ async def orchestrate(config: OrchestratorConfig):
for env_id in env_ids_to_install:
install_env(env_id, prerelease=config.env_install_prerelease)
# Load tokenizer and processor (processor only for VLM models)
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
processor = None
if config.student.model.is_vlm:
logger.info(f"Loading VLM processor for {config.student.model.name}")
processor = AutoProcessor.from_pretrained(
config.student.model.name, trust_remote_code=config.student.model.trust_remote_code, use_fast=True
)
# Set up student inference pool (required for all training modes).
logger.info(
f"Initializing student inference pool (base_url={', '.join(config.student.client.base_url)}, "
@@ -140,6 +130,18 @@ async def orchestrate(config: OrchestratorConfig):
logger=logger,
)
# Token-id → modality marker (1 = image patch, 2 = video patch) used
# to build ``mm_token_type_ids`` per sample. The renderer is the
# single source of truth — it already knows its own special-token
# IDs (``<|image_pad|>`` etc.) from the tokenizer it owns, so the
# orchestrator never needs to load a separate ``AutoProcessor``.
# Text-only renderers expose an empty map (or no attribute).
mm_token_type_ids_mapping: dict[int, int] | None = (
getattr(renderer, "mm_token_type_id_map", None) if renderer is not None else None
)
if mm_token_type_ids_mapping == {}:
mm_token_type_ids_mapping = None
# Set up teacher inference pool (configured for opd or sft). Always MITO for
# simplicity - this also keeps external OAI-compatible teachers (PI inference,
# OpenAI) working as drop-in endpoints.
@@ -468,69 +470,41 @@ async def orchestrate(config: OrchestratorConfig):
save_rollouts, train_rollouts, step_path / "train_rollouts.jsonl", exclude_keys={"trajectory"}
)
# VLM: offload base64 images to disk immediately to free memory
if config.student.model.is_vlm:
offload_start = time.perf_counter()
num_offloaded = offload_images_to_disk(train_rollouts, config.output_dir)
if num_offloaded:
logger.info(
f"VLM offloaded {num_offloaded} unique images to disk in {time.perf_counter() - offload_start:.2f}s"
)
# Offload base64 images to disk to free memory. No-op for text-only
# rollouts (no ``data:image`` URLs to find); cheap to call always.
offload_start = time.perf_counter()
num_offloaded = offload_images_to_disk(train_rollouts, config.output_dir)
if num_offloaded:
logger.info(
f"Offloaded {num_offloaded} unique images to disk in {time.perf_counter() - offload_start:.2f}s"
)
# Convert rollouts to training samples
parallel_preprocess_start = time.perf_counter()
# Stage 1: pretokenize + (for VLM) build image cache concurrently.
# Pretokenize is a no-op when the renderer client already populated
# `tokens` on each trajectory step, but the fallback-tokenizer path
# and image-cache build are both CPU-heavy. Running them on threads
# and awaiting a single gather lets whichever finishes first free
# the event loop immediately and, with max_async_level >= 2, overlaps
# this whole stage with inference for the next batch.
async def _pretokenize_all() -> None:
await asyncio.gather(
*(
asyncio.to_thread(
pretokenize_rollout_trajectory,
rollout,
tokenizer,
processor=processor,
renderer=renderer,
)
for rollout in train_rollouts
# ``tokens`` on each trajectory step (renderer path); the fallback
# tokenizer-only branch handles text-only rollouts whose tokens
# were not pre-rendered. Run on threads so CPU work overlaps with
# inference for the next batch (via max_async_level >= 2).
await asyncio.gather(
*(
asyncio.to_thread(
pretokenize_rollout_trajectory,
rollout,
tokenizer,
renderer=renderer,
)
for rollout in train_rollouts
)
if config.student.model.is_vlm:
mm_token_type_ids_mapping = {}
if hasattr(processor, "image_token_id") and processor.image_token_id is not None:
mm_token_type_ids_mapping[processor.image_token_id] = 1
if hasattr(processor, "video_token_id") and processor.video_token_id is not None:
mm_token_type_ids_mapping[processor.video_token_id] = 2
_, vlm_cache = await asyncio.gather(
_pretokenize_all(),
asyncio.to_thread(build_vlm_image_cache, train_rollouts, processor),
)
logger.info(
f"VLM timing: extract={vlm_cache.extract_time:.2f}s, preprocess={vlm_cache.preprocess_time:.2f}s "
f"({vlm_cache.num_unique_images} unique images from {vlm_cache.num_unique_examples} examples)"
)
else:
await _pretokenize_all()
vlm_cache = None
mm_token_type_ids_mapping = None
)
# Process rollouts in parallel
def process_rollout(rollout: vf.RolloutOutput, rollout_idx: int) -> list[TrainingSample] | None:
return interleave_rollout(
rollout,
vlm_cache=vlm_cache,
cache_key=rollout_idx,
mm_token_type_ids_mapping=mm_token_type_ids_mapping,
)
results = await asyncio.gather(
*(asyncio.to_thread(process_rollout, r, rollout_idx) for rollout_idx, r in enumerate(train_rollouts))
*(
asyncio.to_thread(interleave_rollout, r, mm_token_type_ids_mapping=mm_token_type_ids_mapping)
for r in train_rollouts
)
)
# Collect results and assign advantages. Metrics are computed over all
@@ -793,7 +767,7 @@ async def orchestrate(config: OrchestratorConfig):
is_first_step = False
# Free large per-step objects to prevent memory accumulation
del train_rollouts, train_examples, training_batch, vlm_cache
del train_rollouts, train_examples, training_batch
del results_df, metrics_df
gc.collect()
# Return free glibc heap pages to the OS. numpy/pandas allocate array data
@@ -903,10 +877,8 @@ async def setup_student_inference_pool(
Routing policy is driven by ``config.use_renderer``:
- ``use_renderer=True`` → renderer-backed TITO client (``/v1/generate``).
Default for text-only rollouts. Not allowed for VLMs (validated at
config time).
- ``use_renderer=False`` → MITO (``openai_chat_completions``). VLMs
land here too.
Default for both text-only and VLM rollouts; required for VLMs.
- ``use_renderer=False`` → MITO (``openai_chat_completions``).
Eval clients always use MITO. In sft mode ``use_renderer`` is forced off
by a config validator, so the student pool is plain MITO end-to-end.
+124 -460
View File
@@ -1,14 +1,10 @@
import base64
import hashlib
import time
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from pathlib import Path
from typing import Any
import torch
import verifiers as vf
from PIL import Image
from transformers.tokenization_utils import PreTrainedTokenizer
from prime_rl.transport import TrainingSample
@@ -22,7 +18,7 @@ from prime_rl.utils.chat_template import (
from prime_rl.utils.logger import get_logger
# We use list() instead of deepcopy() for flat lists (token IDs, logprobs) - safe because
# primitives are immutable. pixel_values/image_grid_thw are not mutated after creation.
# primitives are immutable. mm_kwargs payloads are not mutated after creation.
def _align_routed_experts(
@@ -67,62 +63,19 @@ def _render_messages(
messages: list[dict[str, Any]],
add_generation_prompt: bool = False,
tools: list[dict[str, Any]] | None = None,
processor=None,
) -> list[int]:
return render_messages(
tokenizer,
messages,
add_generation_prompt=add_generation_prompt,
tools=tools,
processor=processor,
)
def _prepare_messages_for_processor(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Convert messages to the format expected by the VLM processor.
- Converts image_url items to image items with loaded PIL Images
- Strips extra fields (e.g. image_url on text items) that confuse the processor
- Ensures all message content is in list format (processor requires this)
"""
prepared = []
for msg in messages:
content = msg.get("content")
if isinstance(content, str):
prepared.append({**msg, "content": [{"type": "text", "text": content}]})
continue
if not isinstance(content, list):
prepared.append(msg)
continue
new_content = []
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith(_FILE_URL_PREFIX):
img = _load_file_image(url)
elif url.startswith("data:image"):
b64_data = url.split(",", 1)[1]
img = Image.open(BytesIO(base64.b64decode(b64_data)))
else:
new_content.append(item)
continue
new_content.append({"type": "image", "image": img})
elif item.get("type") == "text":
new_content.append({"type": "text", "text": item.get("text", "")})
else:
new_content.append(item)
prepared.append({**msg, "content": new_content})
return prepared
def _tokenize_step_from_messages(
step: vf.TrajectoryStep,
tokenizer: PreTrainedTokenizer,
tools: list[dict[str, Any]] | None = None,
processor=None,
) -> dict[str, Any]:
prompt = _normalize_messages(step.get("prompt"), default_role="user")
completion = _normalize_messages(step.get("completion"), default_role="assistant")
@@ -135,10 +88,6 @@ def _tokenize_step_from_messages(
f"got roles: {[m.get('role') for m in completion]}"
)
if processor is not None:
prompt = _prepare_messages_for_processor(prompt)
completion = _prepare_messages_for_processor(completion)
all_messages = prompt + completion
prompt_has_assistant_completion = len(completion) > 0 and completion[0].get("role") == "assistant"
prompt_ids = _render_messages(
@@ -146,13 +95,11 @@ def _tokenize_step_from_messages(
prompt,
add_generation_prompt=prompt_has_assistant_completion,
tools=tools,
processor=processor,
)
full_ids = _render_messages(
tokenizer,
all_messages,
tools=tools,
processor=processor,
)
split_idx = _common_prefix_len(prompt_ids, full_ids)
@@ -217,7 +164,6 @@ def _tokenize_step_with_renderer(
def pretokenize_rollout_trajectory(
output: vf.RolloutOutput,
tokenizer: PreTrainedTokenizer,
processor=None,
renderer=None,
) -> bool:
"""Populate missing step tokens from prompt/completion messages.
@@ -235,7 +181,7 @@ def pretokenize_rollout_trajectory(
if renderer is not None:
step["tokens"] = _tokenize_step_with_renderer(step, renderer, tools=tools)
else:
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools, processor=processor)
reconstructed = _tokenize_step_from_messages(step, tokenizer, tools=tools)
if reconstructed["prompt_prefix_len"] < reconstructed["original_prompt_len"]:
logger.debug(
f"Prompt tokenization was non-prefix for example {output['example_id']} step {step_idx}. "
@@ -251,8 +197,6 @@ def pretokenize_rollout_trajectory(
def interleave_rollout(
output: vf.RolloutOutput,
vlm_cache: "VLMImageCache | None" = None,
cache_key: int | None = None,
mm_token_type_ids_mapping: dict[int, int] | None = None,
) -> list[TrainingSample] | None:
"""
@@ -270,13 +214,9 @@ def interleave_rollout(
Returns a list of samples - could be 1 (extension always held) or up to T
(extension never held).
For VLM models, pass vlm_cache to attach cumulative pixel_values per sample.
Each sample gets the images accumulated up to its last merged step.
Args:
output: vf.RolloutOutput containing trajectory data
vlm_cache: Pre-computed VLM image cache for multimodal training
cache_key: Cache key to use when retrieving images from the VLM cache
For VLM models, each renderer-produced trajectory step carries its
per-image processed tensors inline on ``multi_modal_data``; the last
merged step's sidecar covers every image in the sample.
"""
logger = get_logger()
@@ -303,6 +243,11 @@ def interleave_rollout(
"completion_mask": [bool(i) for i in tokens["completion_mask"]],
"completion_logprobs": list(tokens["completion_logprobs"]),
"routed_experts": tokens.get("routed_experts"),
# Renderer-emitted multimodal sidecar (placeholders + per-item
# processed tensors). Populated when the rollout went through
# a multimodal-aware renderer (e.g. Qwen3VLRenderer); absent
# for text-only rollouts.
"multi_modal_data": tokens.get("multi_modal_data"),
}
logger.warning(f"Missing rollout tokens for example {output['example_id']} step {step_idx}.")
@@ -375,12 +320,14 @@ def interleave_rollout(
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
sample.routed_experts = _align_routed_experts(sample.routed_experts, expected_len)
# Track [prefix_tokens, sample, last_step_idx] per active sample
active_samples: list[tuple[list[int], TrainingSample, int]] = []
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
# is the explicit list of prepared_steps positions merged into this sample —
# non-contiguous when other agents' steps interleave.
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
first_tokens = prepared_steps[0]
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
active_samples.append((first_prefix, make_sample(first_tokens), 0))
active_samples.append((first_prefix, make_sample(first_tokens), [0]))
for step_idx, _step in enumerate(trajectory[1:], start=1):
tokens = prepared_steps[step_idx]
@@ -395,9 +342,13 @@ def interleave_rollout(
if matched_idx is not None:
# Extension holds - merge into matched sample
prefix_tokens, sample, _ = active_samples[matched_idx]
prefix_tokens, sample, step_indices = active_samples[matched_idx]
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
active_samples[matched_idx] = (tokens["prompt_ids"] + tokens["completion_ids"], sample, step_idx)
active_samples[matched_idx] = (
tokens["prompt_ids"] + tokens["completion_ids"],
sample,
step_indices + [step_idx],
)
else:
# No prefix matches - start a new sample
logger.debug(
@@ -405,31 +356,114 @@ def interleave_rollout(
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
active_samples.append((new_prefix, make_sample(tokens), step_idx))
active_samples.append((new_prefix, make_sample(tokens), [step_idx]))
# Attach images once per sample using only the last merged step. Prompt
# tokens already contain fully expanded <|image_pad|> placeholders because
# VLMs go through MITO (chat completions), which runs apply_chat_template
# server-side; the orchestrator re-tokenizes via the same processor in the
# fallback path so features and tokens stay 1:1.
if vlm_cache is not None:
key = output["example_id"] if cache_key is None else cache_key
for _, sample, last_step_idx in active_samples:
pv, shape, grids = vlm_cache.get_for_step(key, last_step_idx)
sample.pixel_values = pv
sample.pixel_values_shape = shape
sample.image_grid_thw = grids
if mm_token_type_ids_mapping is not None:
sample.mm_token_type_ids = [
mm_token_type_ids_mapping.get(token_id, 0) for token_id in sample.prompt_ids + sample.completion_ids
]
# Attach images by concatenating mm_items across every step the
# sample covers. verifiers' ``state_to_output`` ships per-step
# *delta* mm_data (each step contains only items not present in the
# prior step's cumulative set, with multiset-aware dedup), so
# reading the last step alone would miss every earlier-turn image.
# Concat in step order recovers the per-sample cumulative set;
# deduping again here would drop legitimate duplicate placeholders.
for _, sample, step_indices in active_samples:
renderer_mm = _union_step_mm_data(prepared_steps, step_indices)
if renderer_mm is not None:
mm_kwargs = _pack_mm_kwargs_from_renderer(renderer_mm)
if mm_kwargs is not None:
sample.mm_kwargs = mm_kwargs
# ``mm_token_type_ids``: 1 for image-placeholder tokens, 2
# for video, 0 otherwise. Renderer-supplied via
# ``mm_token_type_id_map`` (single source of truth).
if mm_token_type_ids_mapping is not None:
sample.mm_token_type_ids = [
mm_token_type_ids_mapping.get(token_id, 0)
for token_id in sample.prompt_ids + sample.completion_ids
]
return [sample for _, sample, _ in active_samples]
# =============================================================================
# VLM-specific functions
# =============================================================================
def _union_step_mm_data(
prepared_steps: list[dict[str, Any]],
step_indices: list[int],
) -> "dict[str, Any] | None":
"""Concatenate renderer-emitted mm_items across this sample's owned steps.
``step_indices`` lists exactly the ``prepared_steps`` positions merged into
the sample — explicit, not a range, so interleaved-agent trajectories skip
steps owned by other agents.
Verifiers ≥ c7731bbb ships per-step *delta* mm_data instead of
cumulative — see ``verifiers/utils/save_utils.py::_delta_intermediate_mm_data``.
The cross-step dedup is already done there with multiset semantics
(preserving multiplicity for an image that appears in multiple
placeholder runs in the token stream). We just concatenate in step
order to recover the per-sample cumulative; deduping again here
would drop legitimate duplicate placeholders.
"""
union_items: dict[str, list] = {}
union_hashes: dict[str, list] = {}
has_any = False
for i in step_indices:
mm = prepared_steps[i].get("multi_modal_data")
if mm is None:
continue
items = mm.mm_items if hasattr(mm, "mm_items") else (mm or {}).get("mm_items") or {}
hashes = mm.mm_hashes if hasattr(mm, "mm_hashes") else (mm or {}).get("mm_hashes") or {}
for modality, item_lst in items.items():
hash_lst = hashes.get(modality, []) or []
for j, item in enumerate(item_lst or []):
h = hash_lst[j] if j < len(hash_lst) else None
union_items.setdefault(modality, []).append(item)
union_hashes.setdefault(modality, []).append(h)
has_any = True
if not has_any:
return None
return {"mm_items": union_items, "mm_hashes": union_hashes}
def _pack_mm_kwargs_from_renderer(mm_data: Any) -> "dict[str, Any] | None":
"""Batch the renderer's per-image ``mm_items`` into model-agnostic
forward kwargs.
``mm_data`` may arrive as a ``MultiModalData`` instance (in-process
for tests) or as a plain dict (after msgpack round-trip from the
env-worker). Each item is a dict keyed by the names the model's
``forward`` expects (``pixel_values`` + ``image_grid_thw`` for
Qwen3-VL, just ``pixel_values`` for Gemma3-VL, etc.). We batch by
``torch.cat(..., dim=0)`` per key — generic because every HF VLM
processor emits a leading batch/patch dimension, and the renderer
always processes one image per call.
Returns a dict of ``EncodedTensor`` payloads keyed by kwarg name,
or ``None`` when no multimodal data is present.
"""
from verifiers.utils.serve_utils import decode_tensor_payload
from prime_rl.transport.types import EncodedTensor
mm_items = mm_data.mm_items if hasattr(mm_data, "mm_items") else (mm_data or {}).get("mm_items") or {}
# Flatten across modalities into one kwarg dict — the model's
# forward signature is the schema. ``mm_items`` is typically
# ``{"image": [...], "video": [...]}`` but each modality's keys
# don't collide for any HF VLM we ship today.
per_kwarg: dict[str, list] = {}
for _modality, items in mm_items.items():
for item in items or []:
for key, payload in item.items():
per_kwarg.setdefault(key, []).append(decode_tensor_payload(payload))
if not per_kwarg:
return None
out: dict[str, EncodedTensor] = {}
for key, tensors in per_kwarg.items():
cat = torch.cat(tensors, dim=0).contiguous()
arr = cat.detach().cpu().numpy()
out[key] = EncodedTensor(
dtype=str(arr.dtype),
shape=list(arr.shape),
data=arr.tobytes(),
)
return out
_FILE_URL_PREFIX = "file://"
@@ -475,373 +509,3 @@ def offload_images_to_disk(rollouts: list[vf.RolloutOutput], output_dir: Path) -
item["image_url"]["url"] = f"{_FILE_URL_PREFIX}{path}"
return len(written)
def _load_file_image(path_str: str) -> Image.Image:
"""Load an image from a file:// path."""
return Image.open(path_str.removeprefix(_FILE_URL_PREFIX))
def _extract_images_from_messages(messages: list) -> list[tuple[Image.Image, str]]:
"""Extract (image, key) pairs from OpenAI-style chat messages.
Handles both base64 data URLs and file:// paths from disk offloading.
"""
images = []
if not messages or not isinstance(messages, list):
return images
for msg in messages:
content = msg.get("content", [])
if isinstance(content, list):
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith(_FILE_URL_PREFIX):
img = _load_file_image(url)
images.append((img, url))
elif url.startswith("data:image"):
b64_data = url.split(",", 1)[1]
img_bytes = base64.b64decode(b64_data)
img = Image.open(BytesIO(img_bytes))
images.append((img, b64_data))
return images
def _collect_image_keys_from_messages(messages: list) -> list[str]:
"""Extract image keys from OpenAI-style chat messages without decoding.
Handles both base64 data URLs and file:// paths from disk offloading.
"""
keys = []
if not messages or not isinstance(messages, list):
return keys
for msg in messages:
content = msg.get("content", [])
if isinstance(content, list):
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image"):
keys.append(url.split(",", 1)[1])
elif url.startswith(_FILE_URL_PREFIX):
keys.append(url)
return keys
def _decode_image(key: str) -> Image.Image:
"""Decode an image from a base64 string or load from a file:// path."""
if key.startswith(_FILE_URL_PREFIX):
return _load_file_image(key)
return Image.open(BytesIO(base64.b64decode(key)))
_PARALLEL_DECODE_THRESHOLD = 4
_IMAGE_STRIPPED_PLACEHOLDER = "[preprocessed image]"
def strip_base64_images(examples: list[tuple[int, vf.RolloutOutput]]) -> None:
"""Strip image data from rollout prompts to free memory.
Handles both base64 data URLs and file:// paths from disk offloading.
The images have been decoded and indexed; the original data is no longer needed.
"""
for _, output in examples:
for step in output.get("trajectory", []):
prompt = step.get("prompt")
if not prompt or not isinstance(prompt, list):
continue
for msg in prompt:
content = msg.get("content", [])
if isinstance(content, list):
for item in content:
if item.get("type") == "image_url":
url = item.get("image_url", {}).get("url", "")
if url.startswith("data:image") or url.startswith(_FILE_URL_PREFIX):
item["image_url"]["url"] = _IMAGE_STRIPPED_PLACEHOLDER
def _extract_images_from_examples(
examples: list[tuple[int, vf.RolloutOutput]],
) -> tuple[list[Image.Image], dict[int, list[list[int]]]]:
"""
Extract images from all trajectory steps of each example.
Two-pass approach: first collects unique base64 keys (fast, string-only),
then decodes unique images in parallel via ThreadPoolExecutor.
Args:
examples: List of (cache_key, output) tuples where output contains a "trajectory"
list with steps that have "prompt" messages in OpenAI chat format.
Returns:
Tuple of (all_images, step_image_indices_per_example)
- all_images: deduplicated flat list of decoded PIL images
- step_image_indices_per_example: dict mapping cache_key to per-step lists of
indices into all_images (e.g., [[0], [0, 1], [1]] for the decreasing-images case)
"""
# Pass 1: collect unique b64 keys and build step indices
unique_keys: list[str] = []
key_to_index: dict[str, int] = {}
step_image_indices_per_example: dict[int, list[list[int]]] = {}
for eid, output in examples:
trajectory = output.get("trajectory", [])
if not trajectory:
step_image_indices_per_example[eid] = []
continue
step_image_indices = []
for step in trajectory:
prompt = step.get("prompt")
image_keys = _collect_image_keys_from_messages(prompt)
indices = []
for key in image_keys:
if key not in key_to_index:
key_to_index[key] = len(unique_keys)
unique_keys.append(key)
indices.append(key_to_index[key])
step_image_indices.append(indices)
step_image_indices_per_example[eid] = step_image_indices
# Pass 2: decode unique images (parallel when worthwhile)
if len(unique_keys) > _PARALLEL_DECODE_THRESHOLD:
with ThreadPoolExecutor(max_workers=min(len(unique_keys), 16)) as pool:
all_images = list(pool.map(_decode_image, unique_keys))
else:
all_images = [_decode_image(k) for k in unique_keys]
del unique_keys, key_to_index
strip_base64_images(examples)
return all_images, step_image_indices_per_example
_DEFAULT_IMAGE_CHUNK_SIZE = 32
class _ImageStore:
"""Holds per-unique-image data, assembled lazily on demand.
Instead of duplicating pixel bytes for every step that references an image,
we store each image's bytes once and assemble the concatenation at retrieval time.
"""
def __init__(
self,
image_bytes: list[bytes],
image_num_patches: list[int],
patch_dim: int,
image_grids: list[list[int]],
):
self.image_bytes = image_bytes
self.image_num_patches = image_num_patches
self.patch_dim = patch_dim
self.image_grids = image_grids
self._cache: dict[tuple[int, ...], tuple[bytes, list[int], list[list[int]]]] = {}
def assemble(self, indices: list[int]) -> tuple[bytes, list[int], list[list[int]]]:
"""Assemble pixel bytes, shape, and grids for a set of image indices.
Results are cached by index tuple — multi-turn rollouts with the same
cumulative image set (common across rollouts of the same example) hit
the cache and skip the join.
"""
cache_key = tuple(indices)
cached = self._cache.get(cache_key)
if cached is not None:
return cached
total_patches = sum(self.image_num_patches[i] for i in indices)
pixel_bytes = b"".join(self.image_bytes[i] for i in indices)
shape = [total_patches, self.patch_dim]
grids = [self.image_grids[i] for i in indices]
result = (pixel_bytes, shape, grids)
self._cache[cache_key] = result
return result
def _preprocess_images_batched(
images: list[Image.Image],
step_image_indices_per_example: dict[int, list[list[int]]],
processor,
chunk_size: int = _DEFAULT_IMAGE_CHUNK_SIZE,
) -> tuple["_ImageStore | None", dict[int, list[list[int]]]]:
"""
Preprocess all images in chunked batches, returning an _ImageStore and step indices.
Images are processed in chunks to avoid OOM on large batches. Per-image bytes are
stored once in the _ImageStore and assembled lazily at retrieval time.
Returns:
Tuple of (_ImageStore or None, step_image_indices_per_example).
The store is None when there are no images or no processor.
"""
if not images or processor is None:
return None, step_image_indices_per_example
logger = get_logger()
image_sizes = [(img.width, img.height) for img in images]
# Process images in chunks to avoid OOM, parallelized across threads
# (PIL/numpy release the GIL so threads give real concurrency here)
chunks = [images[i : i + chunk_size] for i in range(0, len(images), chunk_size)]
def _process_chunk(chunk: list[Image.Image]) -> tuple[torch.Tensor, torch.Tensor]:
processed = processor.image_processor(images=chunk, return_tensors="pt")
return processed["pixel_values"], processed["image_grid_thw"]
if len(chunks) > 1:
with ThreadPoolExecutor(max_workers=min(len(chunks), 8)) as pool:
results = list(pool.map(_process_chunk, chunks))
else:
results = [_process_chunk(chunks[0])]
# Free PIL images now that preprocessing is done
del chunks
images.clear()
all_pixel_values_list = [r[0] for r in results]
all_grid_thw_list = [r[1] for r in results]
all_pixel_values = torch.cat(all_pixel_values_list, dim=0)
all_grid_thw = torch.cat(all_grid_thw_list, dim=0)
del all_pixel_values_list, all_grid_thw_list, results
logger.debug(
f"VLM image processing: {len(image_sizes)} images, sizes={image_sizes}, "
f"pixel_values={all_pixel_values.shape}, grid_thw={all_grid_thw.tolist()}"
)
# Pre-compute patch start offset for each image
patch_starts = [0]
for g in all_grid_thw:
patch_starts.append(patch_starts[-1] + int(g[0] * g[1] * g[2]))
patch_dim = all_pixel_values.shape[1]
# Convert to bytes per-image and free the tensor immediately after
image_bytes_list: list[bytes] = []
image_num_patches_list: list[int] = []
image_grids_list: list[list[int]] = []
for i in range(len(image_sizes)):
img_slice = all_pixel_values[patch_starts[i] : patch_starts[i + 1]]
image_bytes_list.append(img_slice.numpy().tobytes())
image_num_patches_list.append(img_slice.shape[0])
image_grids_list.append(all_grid_thw[i].tolist())
del all_pixel_values, all_grid_thw
store = _ImageStore(
image_bytes=image_bytes_list,
image_num_patches=image_num_patches_list,
patch_dim=patch_dim,
image_grids=image_grids_list,
)
return store, step_image_indices_per_example
class VLMImageCache:
"""Result of building VLM image cache with per-step image data."""
def __init__(
self,
cache: dict[int, list[tuple[bytes | None, list[int] | None, list[list[int]] | None]]],
num_unique_examples: int,
extract_time: float,
preprocess_time: float,
):
self._store: _ImageStore | None = None
self._step_indices: dict[int, list[list[int]]] | None = None
self.cache = cache
self.num_unique_examples = num_unique_examples
self.num_unique_images = 0
self.extract_time = extract_time
self.preprocess_time = preprocess_time
@classmethod
def from_store(
cls,
store: _ImageStore | None,
step_indices: dict[int, list[list[int]]],
num_unique_examples: int,
num_unique_images: int,
extract_time: float,
preprocess_time: float,
) -> "VLMImageCache":
"""Create a store-backed cache that assembles bytes lazily."""
obj = cls.__new__(cls)
obj._store = store
obj._step_indices = step_indices
obj.cache = {}
obj.num_unique_examples = num_unique_examples
obj.num_unique_images = num_unique_images
obj.extract_time = extract_time
obj.preprocess_time = preprocess_time
return obj
def _assemble(self, indices: list[int]) -> tuple[bytes | None, list[int] | None, list[list[int]] | None]:
if not indices:
return (None, None, None)
return self._store.assemble(indices)
def get_for_step(
self, cache_key: int, step_idx: int
) -> tuple[bytes | None, list[int] | None, list[list[int]] | None]:
"""Get cumulative images up to and including the given step."""
if self._store is not None:
steps = self._step_indices.get(cache_key, [])
if not steps or step_idx >= len(steps):
return (None, None, None)
return self._assemble(steps[step_idx])
steps = self.cache.get(cache_key, [])
if not steps or step_idx >= len(steps):
return (None, None, None)
return steps[step_idx]
def get_all(self, cache_key: int) -> tuple[bytes | None, list[int] | None, list[list[int]] | None]:
"""Get all images for the cache key (last step's cumulative images)."""
if self._store is not None:
steps = self._step_indices.get(cache_key, [])
if not steps:
return (None, None, None)
return self._assemble(steps[-1])
steps = self.cache.get(cache_key, [])
if not steps:
return (None, None, None)
return steps[-1]
def build_vlm_image_cache(rollouts: list[vf.RolloutOutput], processor) -> VLMImageCache:
"""
Build image cache for VLM training by extracting and preprocessing images.
Caches per rollout to keep images aligned with divergent multi-turn trajectories.
"""
examples = [(idx, rollout) for idx, rollout in enumerate(rollouts)]
unique_example_ids = {(rollout.get("env_name"), rollout["example_id"]) for rollout in rollouts}
# Extract images (also strips base64 data from rollout prompts to free memory)
extract_start = time.perf_counter()
all_images, images_per_example = _extract_images_from_examples(examples)
num_unique_images = len(all_images)
extract_time = time.perf_counter() - extract_start
# Preprocess images (clears PIL image list when done)
preprocess_start = time.perf_counter()
store, step_indices = _preprocess_images_batched(all_images, images_per_example, processor)
preprocess_time = time.perf_counter() - preprocess_start
return VLMImageCache.from_store(
store=store,
step_indices=step_indices,
num_unique_examples=len(unique_example_ids),
num_unique_images=num_unique_images,
extract_time=extract_time,
preprocess_time=preprocess_time,
)
+28 -4
View File
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
set -e
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
@@ -130,7 +134,15 @@ srun bash -c '
'
# Run inference
srun bash -c '
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed router/engine terminates the SLURM job instead of leaving
# the surviving ranks holding nodes.
srun --kill-on-bad-exit=1 bash -c '
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
# wait/cleanup block at the end of this script surfaces background
# process crashes (router) as task failures.
set -o pipefail
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
@@ -262,7 +274,7 @@ srun bash -c '
--parallel.dp $EP \
--data-parallel-rpc-port $RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
{%- elif num_nodes > 1 %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" \
| tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
@@ -289,7 +301,7 @@ srun bash -c '
@ $CONFIG_PATH \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
{%- else %}
echo "INFER_NODE_RANK=${INFER_NODE_RANK}, LOCAL_IP=${LOCAL_IP}" | tee $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
# Required for graph compilation to work
@@ -297,6 +309,18 @@ srun bash -c '
uv run inference \
@ $CONFIG_PATH \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
{%- endif %}
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (router) into task failures that
# --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job tears
# down instead of leaving zombies holding the allocation.
wait -n
EXIT_CODE=$?
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
for pid in $(jobs -p); do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
'
+29 -5
View File
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately on any failed command so a crash anywhere releases the
# allocation instead of leaving zombie processes holding nodes.
set -e
# Configs
export NUM_TRAIN_NODES={{ num_train_nodes }}
export NUM_INFER_NODES={{ num_infer_nodes }}
@@ -174,7 +178,15 @@ srun bash -c '
'
# Run RL
srun bash -c '
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a crashed component terminates the SLURM job instead of leaving the
# surviving ranks holding nodes.
srun --kill-on-bad-exit=1 bash -c '
# pipefail ensures `cmd | tee log` propagates `cmd` failures, and the
# wait/cleanup block at the end of this script surfaces background
# process crashes (router, orchestrator) as task failures.
set -o pipefail
# Source environment
cd $PROJECT_DIR
[ -f .env ] && source .env
@@ -313,7 +325,7 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
--parallel.dp $DP \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
{%- else -%}
# Start vllm-router on the first node of each replica
if [ "$RANK_IN_REPLICA" -eq 0 ]; then
@@ -349,13 +361,13 @@ if [ "$SLURM_PROCID" -lt "$NUM_INFER_NODES" ]; then
--server.port $BACKEND_PORT \
--data-parallel-rpc-port $INFERENCE_DATA_PARALLEL_RPC_PORT \
--vllm-extra "$VLLM_EXTRA" \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
else
uv run inference \
@ $CONFIG_DIR/inference.toml \
--server.host 0.0.0.0 \
--server.port $BACKEND_PORT \
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log
2>&1 | tee -a $OUTPUT_DIR/logs/inference/node_${INFER_NODE_RANK}.log &
fi
{%- endif %}
@@ -394,6 +406,18 @@ else
--local-ranks-filter={{ ranks_filter }} \
-m prime_rl.trainer.rl.train \
@ $CONFIG_DIR/trainer.toml \
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
2>&1 | sed -u 's/^\[[a-zA-Z]*[0-9]*\]://' | tee -a $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log &
{% if num_infer_nodes > 0 %} fi{% endif %}
# Wait for the first background job to exit and propagate its exit code. This
# turns background process crashes (router, orchestrator) into task failures
# that --kill-on-bad-exit=1 can broadcast to the other nodes so the whole job
# tears down instead of leaving zombies holding the allocation.
wait -n
EXIT_CODE=$?
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
for pid in $(jobs -p); do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
'
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately on any failed command so a crash on any node releases the
# allocation instead of leaving zombie processes holding nodes.
set -e
# Configs
export NUM_NODES={{ num_nodes }}
export GPUS_PER_NODE={{ gpus_per_node }}
@@ -81,7 +85,12 @@ srun bash -c '
'
# Run SFT
srun bash -c '
# --kill-on-bad-exit=1 propagates a non-zero exit on any node to all other
# tasks so a single trainer crash terminates the entire SLURM job instead of
# leaving the surviving ranks (and their nodes) idle.
srun --kill-on-bad-exit=1 bash -c '
set -o pipefail
# Setup environment
[ -f $PROJECT_DIR/.env ] && source $PROJECT_DIR/.env
source $PROJECT_DIR/.venv/bin/activate
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately if any setup command or the launcher fails so the SLURM job
# releases its allocation instead of holding nodes after a crash.
set -e
export PROJECT_DIR={{ project_dir }}
# Setup environment
@@ -21,6 +21,10 @@
#SBATCH --output={{ output_dir }}/job_%j.log
#SBATCH --error={{ output_dir }}/job_%j.log
# Exit immediately if any setup command or the launcher fails so the SLURM job
# releases its allocation instead of holding nodes after a crash.
set -e
export PROJECT_DIR={{ project_dir }}
# Setup environment
+3 -6
View File
@@ -77,17 +77,14 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
routed_experts=routed_experts,
mm_token_type_ids=mm_token_type_ids,
env_names=env_names,
# Multimodal fields (Qwen3-VL) - passed through without modification
pixel_values=training_example.pixel_values,
pixel_values_shape=training_example.pixel_values_shape,
image_grid_thw=training_example.image_grid_thw,
mm_kwargs=training_example.mm_kwargs,
training_mode=training_example.training_mode,
)
def _is_multimodal_sample(sample: MicroBatch) -> bool:
"""Check if a sample contains multimodal data (images)."""
return sample.pixel_values is not None
return sample.mm_kwargs is not None
def packed_samples_into_micro_bs(
@@ -98,7 +95,7 @@ def packed_samples_into_micro_bs(
We follow the First Fit Decreasing algorithm to pack the samples into bins and minimize potential padding while never truncating.
With per-token temperatures, samples can be packed together regardless of their temperature values.
NOTE: Multimodal samples (with pixel_values) are NOT packed together as they have variable-sized
NOTE: Multimodal samples (with mm_kwargs) are NOT packed together as they have variable-sized
vision data that doesn't pack well. Each multimodal sample becomes its own micro batch.
"""
# Sort by (lora_idx, -length) for packing efficiency
+19 -31
View File
@@ -12,9 +12,8 @@ os.environ.setdefault("USE_HUB_KERNELS", "NO")
import torch
import torch._dynamo
import torch.nn as nn
from beartype import beartype as typechecker
from huggingface_hub import snapshot_download
from jaxtyping import Float, Int, jaxtyped
from jaxtyping import Int
from torch import Tensor
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper
from torch.distributed.checkpoint.hf_storage import HuggingFaceStorageReader
@@ -1100,25 +1099,6 @@ def setup_model(
return model
def _get_qwen3_vl_mm_token_type_ids(model: nn.Module, input_ids: Tensor) -> Tensor | None:
config = getattr(model, "config", None)
if getattr(config, "model_type", None) != "qwen3_vl":
return None
mm_token_type_ids = torch.zeros_like(input_ids)
image_token_id = getattr(config, "image_token_id", None)
if image_token_id is not None:
mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == image_token_id, 1)
video_token_id = getattr(config, "video_token_id", None)
if video_token_id is not None:
mm_token_type_ids = mm_token_type_ids.masked_fill(input_ids == video_token_id, 2)
return mm_token_type_ids
@jaxtyped(typechecker=typechecker)
def forward(
model: nn.Module,
input_ids: Int[Tensor, "batch seq"],
@@ -1126,9 +1106,13 @@ def forward(
labels: Int[Tensor, "batch seq"] | None = None,
temperature: Tensor | None = None,
routed_experts: Int[Tensor, "batch seq layers topk"] | None = None,
# Multimodal fields (Qwen3-VL)
pixel_values: Float[Tensor, "num_patches patch_dim"] | None = None,
image_grid_thw: Int[Tensor, "num_images 3"] | None = None,
# Generic multimodal kwargs (e.g. {"pixel_values": ...,
# "image_grid_thw": ...} for Qwen3-VL; just {"pixel_values": ...}
# for Gemma3). Passed straight through to ``model(**kwargs)`` so
# the model's HF forward signature is the schema. ``mm_token_type_ids``
# is split out because it's prime-rl-computed (from token ids),
# not a renderer/processor output.
mm_kwargs: dict[str, Tensor] | None = None,
mm_token_type_ids: Int[Tensor, "batch seq"] | None = None,
) -> PrimeLmOutput:
# Build kwargs for model forward
@@ -1138,15 +1122,19 @@ def forward(
"temperature": temperature,
}
# For multimodal (VLM), don't pass position_ids - let the model compute MRoPE internally
# using image_grid_thw. Qwen3-VL only computes proper MRoPE when position_ids is None.
if pixel_values is not None:
assert image_grid_thw is not None, "pixel_values requires image_grid_thw for MRoPE computation"
kwargs["pixel_values"] = pixel_values
kwargs["image_grid_thw"] = image_grid_thw
mm_token_type_ids = _get_qwen3_vl_mm_token_type_ids(model, input_ids)
if mm_kwargs:
# Forward the per-model multimodal tensors verbatim, plus the
# renderer-supplied ``mm_token_type_ids`` (renderer owns the
# token→modality mapping via ``mm_token_type_id_map``).
kwargs.update(mm_kwargs)
if mm_token_type_ids is not None:
kwargs["mm_token_type_ids"] = mm_token_type_ids
# ``position_ids`` for MRoPE families: Qwen3-VL's HF forward
# recomputes 3D positions from ``image_grid_thw`` and breaks if
# given the trainer's pre-computed 1D ``position_ids``. Detect
# via the mm_kwargs shape so we don't enumerate model_types.
if "image_grid_thw" not in mm_kwargs:
kwargs["position_ids"] = position_ids
else:
kwargs["position_ids"] = position_ids
+30 -18
View File
@@ -32,11 +32,12 @@ class TensorMicroBatch(TypedDict):
# MoE router replay
routed_experts: Int[Tensor, "batch seq layers topk"] | None
# Multimodal fields (Qwen3-VL)
# pixel_values: flattened image patches [num_patches, patch_dim] where patch_dim=1176 for Qwen3-VL
pixel_values: Float[Tensor, "num_patches patch_dim"] | None
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
image_grid_thw: Int[Tensor, "num_images 3"] | None
# Generic multimodal kwargs — flat dict matching the model's forward
# signature (e.g. ``{"pixel_values": ..., "image_grid_thw": ...}`` for
# Qwen3-VL; ``{"pixel_values": ...}`` for Gemma3-VL). The trainer
# ``**`` -unpacks this into the forward call, so any HF VLM whose
# processor and forward agree on kwarg names works out of the box.
mm_kwargs: dict[str, Tensor] | None
# mm_token_type_ids: token type per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: Int[Tensor, "batch seq"] | None
@@ -114,8 +115,7 @@ class FakeDataLoader:
"loss_mask": loss_mask.unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
"pixel_values": None,
"image_grid_thw": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
}
@@ -142,8 +142,7 @@ class FakeDataLoader:
"loss_mask": torch.ones(self.seq_len, dtype=torch.bool).unsqueeze(0),
"lora_num_tokens": lora_num_tokens,
"routed_experts": None,
"pixel_values": None,
"image_grid_thw": None,
"mm_kwargs": None,
"mm_token_type_ids": None,
"training_mode": "rl",
}
@@ -199,6 +198,15 @@ class DataLoader:
if micro_batch.lora_num_tokens is None:
micro_batch.lora_num_tokens = [0] * self.multi_run_manager.max_runs
micro_batch.lora_num_tokens[0] = len(micro_batch.input_ids)
mm_kwargs: dict[str, Tensor] | None = None
if micro_batch.mm_kwargs:
# Each value is an EncodedTensor (dtype, shape, raw bytes).
# No batch dim — the orchestrator concatenates per-image along
# dim=0 generically, matching what each HF VLM's forward expects.
mm_kwargs = {
key: torch.frombuffer(bytearray(payload.data), dtype=_torch_dtype(payload.dtype)).reshape(payload.shape)
for key, payload in micro_batch.mm_kwargs.items()
}
return TensorMicroBatch(
input_ids=torch.tensor(micro_batch.input_ids, dtype=torch.long).unsqueeze(0),
position_ids=torch.tensor(micro_batch.position_ids, dtype=torch.long).unsqueeze(0),
@@ -211,15 +219,7 @@ class DataLoader:
temperatures=torch.tensor(micro_batch.temperatures, dtype=torch.float).unsqueeze(0),
env_names=micro_batch.env_names,
lora_num_tokens=torch.tensor(micro_batch.lora_num_tokens, dtype=torch.int32),
# Multimodal fields - no batch dimension for these as they are variable-sized
pixel_values=torch.frombuffer(bytearray(micro_batch.pixel_values), dtype=torch.float32).reshape(
micro_batch.pixel_values_shape
)
if micro_batch.pixel_values is not None
else None,
image_grid_thw=torch.tensor(micro_batch.image_grid_thw, dtype=torch.long)
if micro_batch.image_grid_thw is not None
else None,
mm_kwargs=mm_kwargs,
mm_token_type_ids=torch.tensor(micro_batch.mm_token_type_ids, dtype=torch.long).unsqueeze(0)
if micro_batch.mm_token_type_ids is not None
else None,
@@ -230,3 +230,15 @@ class DataLoader:
else None,
training_mode=micro_batch.training_mode,
)
def _torch_dtype(name: str) -> torch.dtype:
"""Resolve a numpy/torch dtype name (e.g. ``"float32"``) to torch.dtype."""
# Strip the ``numpy.`` prefix some dtype reprs carry.
name = name.replace("numpy.", "")
if hasattr(torch, name):
return getattr(torch, name)
# numpy ↔ torch alias mismatches (rare but possible) — fall back via numpy.
import numpy as np
return torch.from_numpy(np.zeros(1, dtype=np.dtype(name))).dtype
+23 -13
View File
@@ -338,9 +338,15 @@ def train(config: TrainerConfig):
forward_backward_start_time = time.perf_counter()
seq_len = micro_batches[0]["input_ids"].shape[1]
# Normalize by the local number of unmasked tokens in the batch (per-batch length normalization)
loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
loss_scale = max(loss_scale, 1)
# Normalize by the global (dp_cp) number of unmasked tokens in the batch, so every rank
# divides by the same denominator. With a per-rank denominator, ranks with fewer loss
# tokens implicitly upweight their per-token gradient contribution after FSDP averaging.
# FSDP's per-rank divide is undone after the microbatch loop via fsdp_gradient_divide_factor.
local_loss_scale = sum(micro_batch["loss_mask"].sum().item() for micro_batch in micro_batches)
global_loss_scale = torch.tensor(local_loss_scale, dtype=torch.int64, device="cuda")
dp_cp_group = parallel_dims.get_mesh("dp_cp").get_group()
dist.all_reduce(global_loss_scale, op=dist.ReduceOp.SUM, group=dp_cp_group)
loss_scale = max(global_loss_scale.item(), 1)
logger.debug(f"Starting forward and backward pass ({batch_size=})")
tensors = Tensors() # Used to accumulate tensor statistics across micro-batches and ranks for logging
@@ -371,13 +377,12 @@ def train(config: TrainerConfig):
# we could've gotten routed experts from the inference server, but we didn't enable router replay
routed_experts = None
# Multimodal fields (Qwen3-VL) - only present for VLM training
pixel_values = (
micro_batch["pixel_values"].to("cuda") if micro_batch.get("pixel_values") is not None else None
)
image_grid_thw = (
micro_batch["image_grid_thw"].to("cuda") if micro_batch.get("image_grid_thw") is not None else None
)
# Multimodal kwargs are an opaque per-model dict (e.g.
# {"pixel_values": ..., "image_grid_thw": ...} for Qwen3-VL,
# just {"pixel_values": ...} for Gemma3-VL) — we move every
# tensor to CUDA and let the model's forward sort them.
mm_kwargs_raw = micro_batch.get("mm_kwargs")
mm_kwargs = {k: v.to("cuda") for k, v in mm_kwargs_raw.items()} if mm_kwargs_raw else None
mm_token_type_ids = (
micro_batch["mm_token_type_ids"].to("cuda")
if micro_batch.get("mm_token_type_ids") is not None
@@ -387,7 +392,7 @@ def train(config: TrainerConfig):
labels = shift_tensor_left(input_ids)
# VLM + CP is not supported: MRoPE requires global positions but CP shards the sequence
if cp_enabled and pixel_values is not None:
if cp_enabled and mm_kwargs is not None:
raise NotImplementedError("Context parallelism is not supported with VLM/multimodal training")
if cp_enabled:
@@ -426,8 +431,7 @@ def train(config: TrainerConfig):
forward_position_ids,
labels=labels,
temperature=temperatures,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
mm_kwargs=mm_kwargs,
mm_token_type_ids=mm_token_type_ids,
routed_experts=routed_experts,
)
@@ -514,6 +518,12 @@ def train(config: TrainerConfig):
micro_step_message += f" | Max Vio: {tensors['max_vio'][-1].mean().item():.4f}"
logger.debug(micro_step_message)
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
# across dp_cp so the final gradient is the true per-token mean over the global batch.
for param in model.parameters():
if param.grad is not None:
param.grad.mul_(parallel_dims.fsdp_gradient_divide_factor)
# Optionally, clip the gradients
grad_norm: torch.Tensor | None = None
if config.optim.max_norm is not None:
+20 -10
View File
@@ -5,6 +5,15 @@ import msgspec
TrainingMode = Literal["rl", "opd", "sft"]
# Encoded tensor: {dtype: "float32", shape: [...], data: <bytes>}.
# Mirrors verifiers.utils.serve_utils.msgpack_encoder so the same wire
# shape is used end-to-end from renderer → orchestrator → trainer.
class EncodedTensor(msgspec.Struct, array_like=True, gc=False):
dtype: str
shape: list[int]
data: bytes
# Orchestrator -> Packer
class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
"""A single training example."""
@@ -20,11 +29,15 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr
advantage: float | None = None
reward: float | None = None
# Multimodal fields (Qwen3-VL) — pixel_values stored as raw float32 bytes for efficient serialization
pixel_values: bytes | None = None
pixel_values_shape: list[int] | None = None # [num_patches, patch_dim]
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
image_grid_thw: list[list[int]] | None = None
# Generic multimodal kwargs: flat dict keyed by the kwarg names the
# model's forward expects (e.g. {"pixel_values": ..., "image_grid_thw":
# ...} for Qwen3-VL; just {"pixel_values": ...} for Gemma3). The
# orchestrator batches per-image renderer items by torch.cat along
# dim=0 generically — no model-specific knowledge in prime-rl. The
# trainer ``**`` -unpacks this into the model forward, so any VLM
# whose HF processor / forward agree on kwarg names works without
# touching this transport.
mm_kwargs: dict[str, EncodedTensor] | None = None
routed_experts: list[list[list[int]]] | None = None # [seq_len, layers, topk]
@@ -59,11 +72,8 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True):
lora_num_tokens: list[int] | None = None
routed_experts: list[list[list[int]]] | None = None
# Multimodal fields (Qwen3-VL) — pixel_values stored as raw float32 bytes for efficient serialization
pixel_values: bytes | None = None
pixel_values_shape: list[int] | None = None # [num_patches, patch_dim]
# image_grid_thw: grid dimensions [num_images, 3] where each entry is [temporal, height, width]
image_grid_thw: list[list[int]] | None = None
# See TrainingSample.mm_kwargs.
mm_kwargs: dict[str, EncodedTensor] | None = None
# mm_token_type_ids: token type ids per token [batch seq], int64 (0=text, 1=image, 2=video)
mm_token_type_ids: list[int] | None = None
+10 -1
View File
@@ -9,6 +9,7 @@ import verifiers as vf
import wandb
from transformers.tokenization_utils import PreTrainedTokenizer
from wandb.errors import CommError
from wandb.sdk.mailbox.mailbox_handle import ServerResponseError
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
from prime_rl.utils.chat_template import deserialize_tool_calls
@@ -70,11 +71,14 @@ class WandbMonitor(Monitor):
mode = os.environ.get("WANDB_MODE", "offline" if config.offline else "online")
settings = wandb.Settings(mode=mode)
retryable_errors = (CommError, ServerResponseError) if shared_mode else (CommError,)
def init_wandb(max_retries: int):
for attempt in range(max_retries):
try:
return wandb.init(
id=run_id,
resume="allow" if run_id else None,
project=config.project,
entity=config.entity,
name=config.name,
@@ -84,7 +88,7 @@ class WandbMonitor(Monitor):
config=run_config.model_dump() if run_config else None,
settings=settings,
)
except CommError as e:
except retryable_errors as e:
if attempt + 1 == max_retries:
raise
if shared_mode and not primary:
@@ -94,6 +98,11 @@ class WandbMonitor(Monitor):
else:
msg = f"Transient W&B init error ({e}) - retrying in 10s ({attempt + 1}/{max_retries})"
self.logger.info(msg)
# A failed wandb.init leaves the run_id registered in the local
# wandb-core StreamMux, causing the next attempt to fail with
# "run ID ... is in use". Tear down the service so the retry
# starts from a clean state.
wandb.teardown()
time.sleep(10)
# Non-primary processes in shared mode wait for the primary to create the run.
@@ -20,7 +20,7 @@ pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 15 * 60 # 15 minutes
# Note: I would prefer 5% but massed compute A600s seem to be slower than hyperstack A600s (which is the baseline)
METRIC_TOLERANCE = 0.1 # 10% tolerance for mfu, throughput, step_time
METRIC_TOLERANCE = 0.15 # 15% tolerance for mfu, throughput, step_time
MEMORY_TOLERANCE = 0.01 # 1% tolerance for peak memory
TOKEN_CHUNK_SIZE = "1024"
@@ -205,14 +205,14 @@ def start_orchestrator(
run_dir.as_posix(),
"--max-steps",
str(max_steps),
"--student.model.lora.name",
"--model.lora.name",
name,
"--wandb.project",
wandb_project,
"--wandb.name",
f"{wandb_name}-{proc_name}",
]
cmd.append("--student.client.base-url")
cmd.append("--model.client.base-url")
cmd.extend(INFERENCE_BASE_URLS)
with open(orch_log_dir / "orchestrator.log", "w") as f:
@@ -0,0 +1,113 @@
import os
import signal
import subprocess
import time
from pathlib import Path
from typing import Callable, Generator
import httpx
import pytest
from prime_rl.utils.process import cleanup_process
from tests.conftest import ProcessResult
from tests.utils import check_eval_avg_goes_up, check_no_error, strip_escape_codes
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 600 # 10 minutes
TEACHER_PORT = 8001
TEACHER_READY_TIMEOUT_S = 300
def _wait_for_teacher(port: int, timeout_s: int) -> None:
"""Block until the teacher inference server's /v1/models endpoint is reachable."""
url = f"http://localhost:{port}/v1/models"
deadline = time.time() + timeout_s
while time.time() < deadline:
try:
r = httpx.get(url, timeout=2.0)
if r.status_code == 200:
return
except (httpx.ConnectError, httpx.ReadTimeout):
pass
time.sleep(1.0)
raise TimeoutError(f"Teacher inference server at {url} did not become ready within {timeout_s}s")
@pytest.fixture(scope="module")
def teacher_inference(output_dir: Path) -> Generator[subprocess.Popen, None, None]:
"""Spawn a `uv run inference` teacher on GPU 0 (shared with the rl-launched
student) at 40% gpu_memory_utilization. Tears down at module scope.
"""
# The rl entrypoint's --clean-output-dir wipes the rl output_dir on start,
# so park the teacher log next to it instead of inside it.
teacher_log_dir = output_dir.parent / f"{output_dir.name}_teacher"
teacher_log_dir.mkdir(parents=True, exist_ok=True)
log_path = teacher_log_dir / "teacher_inference.log"
cmd = [
"uv",
"run",
"inference",
"--model.name",
"PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL",
"--server.port",
str(TEACHER_PORT),
"--gpu-memory-utilization",
"0.4",
]
env = {**os.environ, "CUDA_VISIBLE_DEVICES": "0"}
with open(log_path, "w") as log_file:
proc = subprocess.Popen(cmd, env=env, stdout=log_file, stderr=log_file)
try:
_wait_for_teacher(TEACHER_PORT, TEACHER_READY_TIMEOUT_S)
yield proc
finally:
cleanup_process(proc.pid, signal.SIGTERM)
try:
proc.wait(timeout=30)
except subprocess.TimeoutExpired:
cleanup_process(proc.pid, signal.SIGKILL)
proc.wait()
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
return f"test-reverse-text-rl-opd:{branch_name}"
@pytest.fixture(scope="module")
def rl_opd_process(
teacher_inference,
run_process: Callable[..., ProcessResult],
output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
"""Run the RL entrypoint with training_mode = "opd"; teacher_inference is
a fixture-managed external vLLM at http://localhost:8001/v1."""
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/integration/reverse_text_rl_opd/start.toml",
"--clean-output-dir",
"--wandb.project",
wandb_project,
"--wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def test_no_error(rl_opd_process: ProcessResult, output_dir: Path):
check_no_error(rl_opd_process, output_dir)
def test_eval_avg_goes_up(rl_opd_process: ProcessResult, test_no_error, output_dir: Path):
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_eval_avg_goes_up(orchestrator_stdout, env_name="reverse-text")
@@ -0,0 +1,113 @@
import os
import signal
import subprocess
import time
from pathlib import Path
from typing import Callable, Generator
import httpx
import pytest
from prime_rl.utils.process import cleanup_process
from tests.conftest import ProcessResult
from tests.utils import check_eval_avg_goes_up, check_no_error, strip_escape_codes
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 600 # 10 minutes
TEACHER_PORT = 8001
TEACHER_READY_TIMEOUT_S = 300
def _wait_for_teacher(port: int, timeout_s: int) -> None:
"""Block until the teacher inference server's /v1/models endpoint is reachable."""
url = f"http://localhost:{port}/v1/models"
deadline = time.time() + timeout_s
while time.time() < deadline:
try:
r = httpx.get(url, timeout=2.0)
if r.status_code == 200:
return
except (httpx.ConnectError, httpx.ReadTimeout):
pass
time.sleep(1.0)
raise TimeoutError(f"Teacher inference server at {url} did not become ready within {timeout_s}s")
@pytest.fixture(scope="module")
def teacher_inference(output_dir: Path) -> Generator[subprocess.Popen, None, None]:
"""Spawn a `uv run inference` teacher on GPU 0 (shared with the rl-launched
student) at 40% gpu_memory_utilization. Tears down at module scope.
"""
# The rl entrypoint's --clean-output-dir wipes the rl output_dir on start,
# so park the teacher log next to it instead of inside it.
teacher_log_dir = output_dir.parent / f"{output_dir.name}_teacher"
teacher_log_dir.mkdir(parents=True, exist_ok=True)
log_path = teacher_log_dir / "teacher_inference.log"
cmd = [
"uv",
"run",
"inference",
"--model.name",
"PrimeIntellect/Qwen3-0.6B-Reverse-Text-RL",
"--server.port",
str(TEACHER_PORT),
"--gpu-memory-utilization",
"0.4",
]
env = {**os.environ, "CUDA_VISIBLE_DEVICES": "0"}
with open(log_path, "w") as log_file:
proc = subprocess.Popen(cmd, env=env, stdout=log_file, stderr=log_file)
try:
_wait_for_teacher(TEACHER_PORT, TEACHER_READY_TIMEOUT_S)
yield proc
finally:
cleanup_process(proc.pid, signal.SIGTERM)
try:
proc.wait(timeout=30)
except subprocess.TimeoutExpired:
cleanup_process(proc.pid, signal.SIGKILL)
proc.wait()
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
return f"test-reverse-text-rl-sft:{branch_name}"
@pytest.fixture(scope="module")
def rl_sft_process(
teacher_inference,
run_process: Callable[..., ProcessResult],
output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
"""Run the RL entrypoint with training_mode = "sft"; teacher_inference is
a fixture-managed external vLLM at http://localhost:8001/v1."""
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/integration/reverse_text_rl_sft/start.toml",
"--clean-output-dir",
"--wandb.project",
wandb_project,
"--wandb.name",
wandb_name,
"--output-dir",
output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def test_no_error(rl_sft_process: ProcessResult, output_dir: Path):
check_no_error(rl_sft_process, output_dir)
def test_eval_avg_goes_up(rl_sft_process: ProcessResult, test_no_error, output_dir: Path):
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_eval_avg_goes_up(orchestrator_stdout, env_name="reverse-text")
@@ -0,0 +1,187 @@
"""End-to-end integration test for the Qwen3-VL renderer path.
Walks a multimodal request through the full client stack — RendererClient
→ renderers.client.generate → /inference/v1/generate features payload —
with the HTTP layer mocked, and verifies that vLLM can deserialize the
features back into engine inputs identical to what its own server-side
processor would have produced for the same messages.
This is the strongest end-to-end check we can run without a GPU. The
remaining missing piece (vLLM actually consuming the engine input,
sampling tokens, and returning them) is exercised in real rollouts.
"""
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock
import pytest
_HF_CACHE = Path("~/.cache/huggingface/hub").expanduser()
_MODEL = "Qwen/Qwen3-VL-4B-Instruct"
def _model_cached() -> bool:
safe = "models--" + _MODEL.replace("/", "--")
snapshots = _HF_CACHE / safe / "snapshots"
if not snapshots.is_dir():
return False
return any(p.is_dir() for p in snapshots.iterdir())
pytestmark = pytest.mark.skipif(
not _model_cached(),
reason=f"{_MODEL}: HF snapshot not cached locally",
)
class _FakeOpenAI:
"""Minimal AsyncOpenAI stand-in that captures POST bodies.
The renderer client calls ``client.post(absolute_url, body=...)``;
we capture the body for assertions and return a canned generate
response so the parse-side of the flow runs.
"""
def __init__(self):
self.calls: list[dict[str, Any]] = []
self.base_url = "http://fake-host:8000/v1"
async def post(self, path, *, cast_to=dict, body=None, options=None):
self.calls.append({"path": path, "body": body, "options": options})
# Reply with two sampled tokens + <|im_end|>. The renderer's
# parse_response slices the content tokens.
return {
"request_id": "qwen-vl-e2e",
"choices": [
{
"index": 0,
"token_ids": [50, 60, 151645],
"logprobs": {
"content": [
{"token": "t1", "logprob": -0.1},
{"token": "t2", "logprob": -0.2},
{"token": "t3", "logprob": -0.3},
]
},
"finish_reason": "stop",
},
],
}
def test_renderer_client_qwen3_vl_e2e_features_payload_roundtrips_through_vllm():
"""Walk a Qwen3-VL multimodal turn through the renderer client and
verify the resulting ``/inference/v1/generate`` body has a valid
``features`` payload that:
1. parses through vLLM's ``GenerateRequest`` pydantic model,
2. decodes back to ``MultiModalKwargsItem`` instances carrying
``pixel_values`` + ``image_grid_thw`` of the right shapes,
3. has placeholder ranges that exactly cover the ``<|image_pad|>``
runs in the prompt token sequence.
"""
from PIL import Image
from renderers.base import load_tokenizer
from renderers.qwen3_vl import Qwen3VLRenderer
from transformers import AutoProcessor
from verifiers.clients.renderer_client import RendererClient
from verifiers.types import (
ClientConfig,
UserMessage,
)
from vllm.entrypoints.serve.disagg.mm_serde import decode_mm_kwargs_item
from vllm.entrypoints.serve.disagg.protocol import GenerateRequest
# ── Build a real Qwen3VLRenderer with a real processor. ─────────────
tokenizer = load_tokenizer(_MODEL)
processor = AutoProcessor.from_pretrained(_MODEL)
renderer = Qwen3VLRenderer(tokenizer, processor=processor)
image_pad_id = tokenizer.convert_tokens_to_ids("<|image_pad|>")
# ── Manually wire a RendererClient bypassing the pool factory. ──────
client_cfg = ClientConfig(client_type="renderer", base_url="http://fake-host:8000/v1")
rc = object.__new__(RendererClient)
rc._config = client_cfg
rc._renderer = renderer
rc._pool_size = 1
rc._client = _FakeOpenAI()
rc.logger = MagicMock()
# ── Build a verifiers-shaped user message with an image. ────────────
img = Image.new("RGB", (224, 224), color=(64, 128, 255))
# The renderer accepts the OpenAI ``image_url`` content-part shape —
# the same shape verifiers' UserMessage carries through.
user = UserMessage(
content=[
{"type": "text", "text": "What's in this picture?"},
# Embed the PIL image directly. The verifiers→renderer message
# converter forwards content unchanged for our purposes.
{"type": "image", "image": img},
]
)
# to_native_prompt converts to renderer-shaped messages.
prompt, _ = asyncio.run(rc.to_native_prompt([user]))
sampling = {"max_tokens": 16}
response = asyncio.run(
rc.get_native_response(
prompt=prompt,
model=_MODEL,
sampling_args=sampling,
tools=None,
)
)
# ── The HTTP body should carry a features payload. ──────────────────
fake = rc.client
assert isinstance(fake, _FakeOpenAI)
assert len(fake.calls) == 1
body = fake.calls[0]["body"]
assert "features" in body, "RendererClient should ship features for image content"
features = body["features"]
# ── Pydantic-roundtrip through vLLM's GenerateRequest model. ────────
gen_req = GenerateRequest(
token_ids=body["token_ids"],
features=features,
sampling_params=body["sampling_params"],
)
assert gen_req.features is not None
assert "image" in gen_req.features.mm_hashes
assert len(gen_req.features.mm_hashes["image"]) == 1
# ── Placeholder anchoring: the offset/length in features must land
# exactly on a run of <|image_pad|> ids in the prompt. ───────────
placeholders = gen_req.features.mm_placeholders["image"]
assert len(placeholders) == 1
ph = placeholders[0]
pad_slice = body["token_ids"][ph.offset : ph.offset + ph.length]
assert all(t == image_pad_id for t in pad_slice), (
f"placeholder span ({ph.offset}, {ph.length}) does not cover image_pad tokens; slice={pad_slice[:8]}..."
)
# ── kwargs_data decodes to MultiModalKwargsItem with the right keys. ─
assert gen_req.features.kwargs_data is not None
encoded_items = gen_req.features.kwargs_data["image"]
assert len(encoded_items) == 1
item = decode_mm_kwargs_item(encoded_items[0])
assert set(item.keys()) == {"pixel_values", "image_grid_thw"}
# The image_grid_thw must match what the HF processor would have
# produced for the same PIL image — strongest signal that the engine
# sees the same image features the trainer will.
direct_proc_out = processor.image_processor(images=[img], return_tensors="pt")
expected_grid = direct_proc_out["image_grid_thw"][0].tolist()
assert item["image_grid_thw"].data.tolist() == expected_grid
# ── Response parsed through renderer's parse_response. ──────────────
assert response["completion_ids"] == [50, 60, 151645]
# multi_modal_data surfaces on the result so the caller can persist it.
assert response["multi_modal_data"] is not None
assert len(response["multi_modal_data"].mm_items["image"]) == 1
File diff suppressed because it is too large Load Diff
+291 -7
View File
@@ -157,18 +157,20 @@ def test_removed_fused_lm_head_chunk_size_field_is_rejected():
TrainerModelConfig.model_validate({"fused_lm_head_chunk_size": "auto"})
def test_orchestrator_vlm_configs_must_disable_renderer():
with pytest.raises(ValidationError, match="orchestrator.use_renderer is not supported for VLMs"):
def test_orchestrator_vlm_requires_renderer():
with pytest.raises(ValidationError, match="orchestrator.use_renderer must be true when model.vlm is set"):
OrchestratorConfig.model_validate(
{
"student": {
"model": {
"name": "Qwen/Qwen3-VL-4B-Instruct",
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
}
},
}
}
},
"use_renderer": False,
}
)
@@ -176,17 +178,17 @@ def test_orchestrator_vlm_configs_must_disable_renderer():
{
"student": {
"model": {
"name": "Qwen/Qwen3-VL-4B-Instruct",
"vlm": {
"vision_encoder_attr": "model.visual",
"language_model_attr": "model.language_model",
}
},
}
},
"use_renderer": False,
}
)
assert config.use_renderer is False
assert config.use_renderer is True
def test_selective_activation_checkpointing_requires_custom_impl():
@@ -194,6 +196,255 @@ def test_selective_activation_checkpointing_requires_custom_impl():
TrainerModelConfig.model_validate({"impl": "hf", "ac": {"mode": "selective"}})
def test_shared_model_name_propagates_to_subconfigs():
model_name = "PrimeIntellect/test-model"
config = RLConfig.model_validate(
{
"model": {"name": model_name},
"trainer": {},
"orchestrator": {"use_renderer": False},
"inference": {},
}
)
assert config.trainer.model.name == model_name
assert config.orchestrator.student.model.name == model_name
assert config.inference is not None and config.inference.model.name == model_name
assert config.trainer.tokenizer.name == model_name
assert config.orchestrator.tokenizer.name == model_name
def test_shared_tokenizer_propagates_when_subconfigs_unset():
config = RLConfig.model_validate(
{
"model": {"name": "my-model"},
"tokenizer": {"name": "my-tokenizer"},
"trainer": {},
"orchestrator": {"use_renderer": False},
}
)
assert config.trainer.tokenizer.name == "my-tokenizer"
assert config.orchestrator.tokenizer.name == "my-tokenizer"
def test_shared_and_sub_tokenizer_name_conflict_raises():
"""Setting tokenizer.name in both [tokenizer] and [trainer.tokenizer]
is a config conflict — the sub-config would silently win, and any later
CLI override of [tokenizer].name would silently no-op for the trainer."""
with pytest.raises(ValidationError, match=r"tokenizer.name.*trainer.tokenizer.name"):
RLConfig.model_validate(
{
"model": {"name": "my-model"},
"tokenizer": {"name": "shared-tok"},
"trainer": {"tokenizer": {"name": "trainer-tok"}},
"orchestrator": {"use_renderer": False},
}
)
def test_tokenizer_name_falls_back_to_model_name_when_unset():
config = RLConfig.model_validate(
{
"model": {"name": "my-model"},
"tokenizer": {"trust_remote_code": True},
"trainer": {},
"orchestrator": {"use_renderer": False},
}
)
assert config.trainer.tokenizer.name == "my-model"
assert config.orchestrator.tokenizer.name == "my-model"
assert config.trainer.tokenizer.trust_remote_code is True
assert config.orchestrator.tokenizer.trust_remote_code is True
def test_explicit_subconfig_tokenizer_name_survives_shared_model_propagation():
"""Regression: shared ``[model] name = "M"`` must propagate model names but
must NOT clobber an explicit ``[orchestrator.tokenizer] name = "T"``.
This is the case that the old RL-level ``auto_setup_tokenizer`` fix-up got
wrong: it unconditionally re-derived ``orchestrator.tokenizer.name`` from
``orchestrator.student.model.name`` after propagation, silently overriding
the user's explicit value. The ``mode="before"`` ``auto_setup_shared_configs``
propagator fixes this because it propagates the model name into the raw
dict before sub-configs are built, so ``OrchestratorConfig``'s own
``auto_setup_tokenizer`` (mode=after) sees the resolved name *and* the
explicit user-set tokenizer name, and the ``fill``-if-absent semantic
leaves the explicit value alone.
"""
config = RLConfig.model_validate(
{
"model": {"name": "M"},
"trainer": {},
"orchestrator": {
"use_renderer": False,
"tokenizer": {"name": "explicit-orch-tok"},
},
}
)
# Shared model.name reached every sub-config that didn't override it.
assert config.trainer.model.name == "M"
assert config.orchestrator.student.model.name == "M"
# Trainer didn't specify a tokenizer, so it falls back to the propagated model name.
assert config.trainer.tokenizer.name == "M"
# Orchestrator's explicit tokenizer name survived.
assert config.orchestrator.tokenizer.name == "explicit-orch-tok"
def test_tokenizer_chat_template_mismatch_raises():
with pytest.raises(ValidationError, match="chat_template"):
RLConfig.model_validate(
{
"trainer": {"tokenizer": {"chat_template": "A"}},
"orchestrator": {"use_renderer": False, "tokenizer": {"chat_template": "B"}},
}
)
def test_shared_seq_len_propagates_to_subconfigs():
config = RLConfig.model_validate(
{
"seq_len": 4096,
"trainer": {},
"orchestrator": {"use_renderer": False},
}
)
assert config.trainer.model.seq_len == 4096
assert config.orchestrator.seq_len == 4096
def test_shared_and_sub_seq_len_conflict_raises():
"""Setting seq_len at the shared level and on a sub-config is a conflict —
forces the user to pick one place to express the value rather than
relying on the silent 'sub wins' rule."""
with pytest.raises(ValidationError, match=r"seq_len.*trainer.model.seq_len"):
RLConfig.model_validate(
{
"seq_len": 4096,
"trainer": {"model": {"seq_len": 8192}},
"orchestrator": {"use_renderer": False},
}
)
def test_shared_and_sub_model_name_conflict_raises():
"""Setting model.name at the shared level and on a sub-config is a conflict."""
with pytest.raises(ValidationError, match=r"model.name.*trainer.model.name"):
RLConfig.model_validate(
{
"model": {"name": "X"},
"trainer": {"model": {"name": "Y"}},
"orchestrator": {"use_renderer": False},
}
)
def test_shared_and_sub_max_steps_conflict_raises():
"""Top-level scalar shared fields also participate in the mutex check."""
with pytest.raises(ValidationError, match=r"max_steps.*orchestrator.max_steps"):
RLConfig.model_validate(
{
"max_steps": 100,
"trainer": {},
"orchestrator": {"use_renderer": False, "max_steps": 200},
}
)
def test_trainer_chat_template_cascades_to_inference():
"""``[trainer.tokenizer] chat_template`` set directly (no shared
``[tokenizer] chat_template``) must still reach
``inference.model.chat_template`` so vLLM's ``--chat-template`` is wired
up. Regression: the original ``auto_setup_tokenizer`` cascaded this; the
refactored propagator must keep doing it."""
config = RLConfig.model_validate(
{
"model": {"name": "Qwen/Qwen3-0.6B"},
"trainer": {"tokenizer": {"chat_template": "TPL"}},
"orchestrator": {"use_renderer": False, "tokenizer": {"chat_template": "TPL"}},
"inference": {},
}
)
assert config.trainer.tokenizer.chat_template == "TPL"
assert config.orchestrator.tokenizer.chat_template == "TPL"
assert config.inference is not None
assert config.inference.model.chat_template == "TPL"
def test_shared_wandb_fields_propagate_to_subconfigs():
"""Every ``SharedWandbConfig`` leaf (project, entity, group, tags, offline)
propagates to both trainer.wandb and orchestrator.wandb, not just project
and offline. Regression for a miss in the inline propagator."""
config = RLConfig.model_validate(
{
"model": {"name": "Qwen/Qwen3-0.6B"},
"wandb": {
"project": "shared-proj",
"entity": "shared-entity",
"group": "shared-group",
"tags": ["a", "b"],
"shared": False,
"offline": True,
},
"trainer": {},
"orchestrator": {"use_renderer": False},
}
)
for component in (config.trainer.wandb, config.orchestrator.wandb):
assert component is not None
assert component.project == "shared-proj"
assert component.entity == "shared-entity"
assert component.group == "shared-group"
assert component.tags == ["a", "b"]
assert component.offline is True
def test_empty_shared_ckpt_block_does_not_conflict_with_subconfig_ckpt():
"""An empty shared [ckpt] block is a presence-only signal, not a field
setting — it should not conflict with a non-empty [trainer.ckpt]."""
config = RLConfig.model_validate(
{
"ckpt": {}, # empty block, no field set
"trainer": {"ckpt": {"interval": 50}},
"orchestrator": {"use_renderer": False, "ckpt": {"interval": 50}},
}
)
assert config.trainer.ckpt is not None
assert config.trainer.ckpt.interval == 50
def test_shared_and_subconfig_disjoint_fields_coexist():
"""Per-field mutex only forbids conflicts on the SAME field — disjoint
fields in [model] vs [trainer.model] are fine."""
config = RLConfig.model_validate(
{
"model": {"name": "Qwen/Qwen3-0.6B"},
"trainer": {"model": {"impl": "custom"}},
"orchestrator": {"use_renderer": False},
}
)
assert config.trainer.model.name == "Qwen/Qwen3-0.6B"
assert config.trainer.model.impl == "custom"
def test_shared_output_dir_propagates_through_cli(tmp_path):
"""Shared output_dir from CLI reaches sub-configs even when tyro constructs sub-configs before the before-validator."""
toml_path = tmp_path / "cfg.toml"
write_toml(
toml_path,
{
"max_steps": 1,
"seq_len": 128,
"model": {"name": "Qwen/Qwen3-0.6B"},
"trainer": {},
"orchestrator": {"batch_size": 16, "rollouts_per_example": 1},
"inference": {},
},
)
shared_out = tmp_path / "shared"
config = cli(RLConfig, args=["@", str(toml_path), "--output-dir", str(shared_out)])
assert config.trainer.output_dir == shared_out
assert config.orchestrator.output_dir == shared_out / "run_default"
def test_orchestrator_renderer_auto_rejects_unmapped_model():
"""use_renderer=True with renderer.name='auto' must reject models not in MODEL_RENDERER_MAP."""
with pytest.raises(ValidationError, match="silently fall back to DefaultRenderer"):
@@ -239,3 +490,36 @@ def test_orchestrator_explicit_default_renderer_with_unmapped_model():
)
assert config.renderer.name == "default"
assert config.renderer.tool_parser == "qwen3"
def test_shared_model_name_resolves_inference_parsers():
"""Shared [model] name must reach inference.model BEFORE ModelConfig's after-validator
runs auto_resolve_parsers — i.e. the parsers resolve from the propagated name, not
from an empty default.
"""
config = RLConfig.model_validate(
{
"model": {"name": "Qwen/Qwen3-Coder-30B-A3B-Instruct"},
"trainer": {},
"orchestrator": {"use_renderer": False},
"inference": {},
}
)
assert config.inference is not None
assert config.inference.model.name == "Qwen/Qwen3-Coder-30B-A3B-Instruct"
assert config.inference.model.tool_call_parser == "qwen3_coder"
def test_explicit_inference_parser_wins_over_auto():
"""Explicit inference.model.tool_call_parser is preserved even when the shared model
name would otherwise auto-resolve to something else."""
config = RLConfig.model_validate(
{
"model": {"name": "Qwen/Qwen3-Coder-30B-A3B-Instruct"},
"trainer": {},
"orchestrator": {"use_renderer": False},
"inference": {"model": {"tool_call_parser": "hermes"}},
}
)
assert config.inference is not None
assert config.inference.model.tool_call_parser == "hermes"
+136
View File
@@ -0,0 +1,136 @@
import pytest
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_parser
# (model_name, expected_tool_call_parser, expected_reasoning_parser)
EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
# DeepSeek
("deepseek-ai/DeepSeek-V3.2", "deepseek_v32", "deepseek_r1"),
("deepseek-ai/DeepSeek-V3.2-Exp", "deepseek_v32", "deepseek_r1"),
("deepseek-ai/DeepSeek-V3.1", "deepseek_v31", "deepseek_r1"),
("deepseek-ai/DeepSeek-V3.1-FP8", "deepseek_v31", "deepseek_r1"),
# GLM-4.5
("zai-org/GLM-4.5", "glm45", "glm45"),
("zai-org/GLM-4.5-FP8", "glm45", "glm45"),
("zai-org/GLM-4.5-Base", "glm45", "glm45"),
("zai-org/GLM-4.5-Air", "glm45", "glm45"),
("zai-org/GLM-4.5-Air-FP8", "glm45", "glm45"),
("zai-org/GLM-4.5-Air-Base", "glm45", "glm45"),
("zai-org/GLM-4.5V", "glm45", "glm45"),
("zai-org/GLM-4.5V-FP8", "glm45", "glm45"),
# GLM-4.7
("zai-org/GLM-4.7", "glm47", "glm45"),
("zai-org/GLM-4.7-FP8", "glm47", "glm45"),
("zai-org/GLM-4.7-Flash", "glm47", "glm45"),
# GLM-5
("zai-org/GLM-5", "glm47", "glm45"),
("zai-org/GLM-5-FP8", "glm47", "glm45"),
# GLM-5.1
("zai-org/GLM-5.1", "glm47", "glm45"),
("zai-org/GLM-5.1-FP8", "glm47", "glm45"),
# MiniMax M2
("MiniMaxAI/MiniMax-M2", "minimax_m2", "minimax_m2_append_think"),
("MiniMaxAI/MiniMax-M2.1", "minimax_m2", "minimax_m2_append_think"),
("MiniMaxAI/MiniMax-M2.5", "minimax_m2", "minimax_m2_append_think"),
# INTELLECT-3
("PrimeIntellect/INTELLECT-3", "qwen3_coder", "deepseek_r1"),
("PrimeIntellect/INTELLECT-3-FP8", "qwen3_coder", "deepseek_r1"),
("PrimeIntellect/INTELLECT-3.1", "qwen3_coder", "deepseek_r1"),
# NemotronH
("nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16", "qwen3_coder", None),
("nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16", "qwen3_coder", None),
# StepFun
("stepfun-ai/Step-3.5-Flash", "step3p5", "step3p5"),
# Qwen3 dense
("Qwen/Qwen3-0.6B", "hermes", None),
("Qwen/Qwen3-0.6B-Base", "hermes", None),
("Qwen/Qwen3-0.6B-FP8", "hermes", None),
("Qwen/Qwen3-1.7B", "hermes", None),
("Qwen/Qwen3-4B", "hermes", None),
("Qwen/Qwen3-8B", "hermes", None),
("Qwen/Qwen3-14B", "hermes", None),
("Qwen/Qwen3-32B", "hermes", None),
# Qwen3 MoE
("Qwen/Qwen3-30B-A3B", "hermes", None),
("Qwen/Qwen3-235B-A22B", "hermes", None),
# Qwen3 2507
("Qwen/Qwen3-4B-Instruct-2507", "hermes", None),
("Qwen/Qwen3-4B-Thinking-2507", "hermes", "deepseek_r1"),
("Qwen/Qwen3-30B-A3B-Thinking-2507", "hermes", "deepseek_r1"),
("Qwen/Qwen3-235B-A22B-Instruct-2507", "hermes", None),
("Qwen/Qwen3-235B-A22B-Thinking-2507", "hermes", "deepseek_r1"),
# Qwen3-Next
("Qwen/Qwen3-Next-80B-A3B-Instruct", "hermes", None),
("Qwen/Qwen3-Next-80B-A3B-Thinking", "hermes", "deepseek_r1"),
# Qwen3-Coder
("Qwen/Qwen3-Coder-480B-A35B-Instruct", "qwen3_coder", None),
("Qwen/Qwen3-Coder-30B-A3B-Instruct", "qwen3_coder", None),
("Qwen/Qwen3-Coder-Next", "qwen3_coder", None),
# Qwen3.5 dense
("Qwen/Qwen3.5-0.8B", "qwen3_coder", "qwen3"),
("Qwen/Qwen3.5-9B", "qwen3_coder", "qwen3"),
("Qwen/Qwen3.5-27B", "qwen3_coder", "qwen3"),
# Qwen3.5 MoE
("Qwen/Qwen3.5-35B-A3B", "qwen3_coder", "qwen3"),
("Qwen/Qwen3.5-122B-A10B", "qwen3_coder", "qwen3"),
("Qwen/Qwen3.5-397B-A17B", "qwen3_coder", "qwen3"),
# Unknown model
("some/unknown-model", None, None),
]
@pytest.mark.parametrize("model_name,expected_tool_call,expected_reasoning", EXPECTED_PARSERS)
def test_resolve_tool_call_parser(model_name: str, expected_tool_call: str | None, expected_reasoning: str | None):
assert resolve_tool_call_parser(model_name) == expected_tool_call
@pytest.mark.parametrize("model_name,expected_tool_call,expected_reasoning", EXPECTED_PARSERS)
def test_resolve_reasoning_parser(model_name: str, expected_tool_call: str | None, expected_reasoning: str | None):
assert resolve_reasoning_parser(model_name) == expected_reasoning
def test_inference_config_resolves_parsers_from_model_name():
"""InferenceConfig.ModelConfig.auto_resolve_parsers fires when parsers default to 'auto'."""
config = InferenceConfig(model={"name": "deepseek-ai/DeepSeek-V3.2"})
assert config.model.tool_call_parser == "deepseek_v32"
assert config.model.reasoning_parser == "deepseek_r1"
def test_inference_config_explicit_parser_not_overridden():
config = InferenceConfig(model={"name": "Qwen/Qwen3-4B", "tool_call_parser": "my_parser"})
assert config.model.tool_call_parser == "my_parser"
def test_inference_config_none_disables_parser():
config = InferenceConfig(
model={"name": "Qwen/Qwen3-4B", "tool_call_parser": None, "reasoning_parser": None},
)
assert config.model.tool_call_parser is None
assert config.model.reasoning_parser is None
def test_to_vllm_resolves_parsers():
config = InferenceConfig(model={"name": "deepseek-ai/DeepSeek-V3.2"})
ns = config.to_vllm()
assert ns.tool_call_parser == "deepseek_v32"
assert ns.reasoning_parser == "deepseek_r1"
assert ns.enable_auto_tool_choice is True
def test_to_vllm_none_strips_parser_attrs_from_namespace():
"""vLLM doesn't accept None for these — they must be removed, not passed through."""
config = InferenceConfig(
model={"name": "Qwen/Qwen3-4B", "tool_call_parser": None, "reasoning_parser": None},
)
ns = config.to_vllm()
assert not hasattr(ns, "tool_call_parser")
assert not hasattr(ns, "reasoning_parser")
assert ns.enable_auto_tool_choice is False
def test_to_vllm_unknown_model_disables_auto_tool_choice():
config = InferenceConfig(model={"name": "some/unknown-model"})
ns = config.to_vllm()
assert not hasattr(ns, "tool_call_parser")
assert ns.enable_auto_tool_choice is False
-49
View File
@@ -1,49 +0,0 @@
import pytest
from prime_rl.inference.vllm.server import resolve_tool_call_parser
@pytest.mark.parametrize(
"model_name,expected_parser",
[
# GLM-4.5
("zai-org/GLM-4.5", "glm45"),
("zai-org/GLM-4.5-Air", "glm45"),
("zai-org/GLM-4.5V", "glm45"),
# GLM-4.7
("zai-org/GLM-4.7", "glm47"),
("zai-org/GLM-4.7-Flash", "glm47"),
# GLM-5.1
("zai-org/GLM-5.1", "glm47"),
# MiniMax
("MiniMaxAI/MiniMax-M2", "minimax_m2"),
("MiniMaxAI/MiniMax-M2.1", "minimax_m2"),
("MiniMaxAI/MiniMax-M2.5", "minimax_m2"),
# INTELLECT
("PrimeIntellect/INTELLECT-3", "hermes"),
("PrimeIntellect/INTELLECT-3-FP8", "hermes"),
("PrimeIntellect/INTELLECT-3.1", "hermes"),
# Qwen3
("Qwen/Qwen3-0.6B", "hermes"),
("Qwen/Qwen3-32B", "hermes"),
("Qwen/Qwen3-235B-A22B", "hermes"),
("Qwen/Qwen3-4B-Instruct-2507", "hermes"),
("Qwen/Qwen3-Coder-480B-A35B-Instruct", "hermes"),
("Qwen/Qwen3-Next-80B-A3B-Instruct", "hermes"),
("Qwen/Qwen3.5-397B-A17B", "qwen3_coder"),
],
)
def test_auto_detect_tool_call_parser(model_name: str, expected_parser: str):
assert resolve_tool_call_parser(model_name, "auto") == expected_parser
def test_explicit_parser_not_overridden():
assert resolve_tool_call_parser("Qwen/Qwen3-4B-Instruct-2507", "qwen3_xml") == "qwen3_xml"
def test_auto_unknown_model():
assert resolve_tool_call_parser("some/unknown-model", "auto") is None
def test_none_skips_resolution():
assert resolve_tool_call_parser("Qwen/Qwen3-0.6B", None) is None
+45 -12
View File
@@ -18,33 +18,66 @@ class _CaptureModel(nn.Module):
return {"logits": torch.zeros(*input_ids.shape, 4)}
def test_forward_adds_qwen3_vl_mm_token_type_ids():
image_token_id = 10
video_token_id = 20
model = _CaptureModel(
SimpleNamespace(model_type="qwen3_vl", image_token_id=image_token_id, video_token_id=video_token_id)
)
input_ids = torch.tensor([[1, image_token_id, image_token_id, 2, video_token_id]])
def test_forward_passes_renderer_mm_token_type_ids_through():
"""``forward()`` forwards renderer-supplied ``mm_token_type_ids``
verbatim — the trainer no longer auto-computes from the model
config, since the renderer is the source of truth."""
model = _CaptureModel(SimpleNamespace(model_type="qwen3_vl"))
input_ids = torch.tensor([[1, 10, 10, 2, 20]])
position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0)
pixel_values = torch.ones(2, 3)
image_grid_thw = torch.tensor([[1, 1, 2]])
mm_token_type_ids = torch.tensor([[0, 1, 1, 0, 2]])
forward(model, input_ids, position_ids, pixel_values=pixel_values, image_grid_thw=image_grid_thw)
forward(
model,
input_ids,
position_ids,
mm_kwargs={"pixel_values": pixel_values, "image_grid_thw": image_grid_thw},
mm_token_type_ids=mm_token_type_ids,
)
assert model.kwargs is not None
# MRoPE families (image_grid_thw present) get position_ids stripped.
assert "position_ids" not in model.kwargs
torch.testing.assert_close(model.kwargs["pixel_values"], pixel_values)
torch.testing.assert_close(model.kwargs["image_grid_thw"], image_grid_thw)
torch.testing.assert_close(model.kwargs["mm_token_type_ids"], torch.tensor([[0, 1, 1, 0, 2]]))
torch.testing.assert_close(model.kwargs["mm_token_type_ids"], mm_token_type_ids)
def test_forward_skips_mm_token_type_ids_for_other_vlm_models():
model = _CaptureModel(SimpleNamespace(model_type="qwen3_5_moe", image_token_id=10))
def test_forward_omits_mm_token_type_ids_when_renderer_does_not_supply():
"""When the renderer doesn't ship ``mm_token_type_ids`` (text-only
or a family without modality markers), ``forward()`` doesn't
fabricate one."""
model = _CaptureModel(SimpleNamespace(model_type="qwen3_vl"))
input_ids = torch.tensor([[1, 10, 10, 2]])
position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0)
forward(model, input_ids, position_ids, pixel_values=torch.ones(2, 3), image_grid_thw=torch.tensor([[1, 1, 2]]))
forward(
model,
input_ids,
position_ids,
mm_kwargs={"pixel_values": torch.ones(2, 3), "image_grid_thw": torch.tensor([[1, 1, 2]])},
)
assert model.kwargs is not None
assert "position_ids" not in model.kwargs
assert "mm_token_type_ids" not in model.kwargs
def test_forward_keeps_position_ids_for_non_mrope_vlm():
"""Non-MRoPE VLM families (no ``image_grid_thw``) keep the trainer's
pre-computed ``position_ids``."""
model = _CaptureModel(SimpleNamespace(model_type="gemma3"))
input_ids = torch.tensor([[1, 10, 10, 2]])
position_ids = torch.arange(input_ids.shape[1]).unsqueeze(0)
forward(
model,
input_ids,
position_ids,
mm_kwargs={"pixel_values": torch.ones(2, 3)},
)
assert model.kwargs is not None
torch.testing.assert_close(model.kwargs["position_ids"], position_ids)
+15
View File
@@ -107,6 +107,21 @@ def check_loss_goes_down(lines: list[str]):
return check_number_goes_up_or_down(lines, go_up=False, pattern=r"Loss:\s*(\d+\.\d{4})")
def check_eval_avg_goes_up(lines: list[str], env_name: str):
"""Assert that the last `Evaluated {env_name} ... Avg@K=X.XXXX` line reports a
higher score than the first one. Use for smoke tests with `interval = 1`
evals."""
pattern = rf"Evaluated {re.escape(env_name)} .*Avg@\d+=(\d+\.\d{{4}})"
eval_lines = [line for line in lines if "SUCCESS" in line and re.search(pattern, line)]
assert len(eval_lines) >= 2, f"Need at least 2 eval lines for {env_name!r}, found {len(eval_lines)}"
start = float(re.search(pattern, eval_lines[0]).group(1))
end = float(re.search(pattern, eval_lines[-1]).group(1))
assert end > start, (
f"Eval avg for {env_name!r} did not go up: first={start} last={end}\n"
f"first line: {eval_lines[0]}\nlast line: {eval_lines[-1]}"
)
def check_reward_in_range(
lines: list[str],
step: int = -1,
Generated
+51 -14
View File
@@ -15,7 +15,7 @@ conflicts = [[
]]
[options]
exclude-newer = "2026-05-11T22:34:17.526963383Z"
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer-span = "P7D"
[options.exclude-newer-package]
@@ -28,7 +28,6 @@ deep-ep = false
flash-attn-3 = false
prime-sandboxes = false
prime-tunnel = false
pydantic-config = false
deep-gemm = false
prime-evals = false
prime = false
@@ -57,6 +56,7 @@ members = [
"opencode-math",
"opencode-science",
"opencode-swe",
"prime-pydantic-config",
"prime-rl",
"prime-rl-configs",
"renderers",
@@ -3838,9 +3838,55 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/79/54/f3da8112d6ccb12c9662a5ab3de6b1495ca28ea2f889e15fe01ca538d636/prime_evals-0.2.2-py3-none-any.whl", hash = "sha256:f8f058d81819c1815203217a0c1c05defb3f8fe7f4eeb3befd2881251459f343", size = 13414, upload-time = "2026-05-14T23:07:50.351Z" },
]
[[package]]
name = "prime-pydantic-config"
version = "0.3.0"
source = { editable = "deps/pydantic-config" }
dependencies = [
{ name = "pydantic", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
[package.optional-dependencies]
all = [
{ name = "pyyaml", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tomli", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
toml = [
{ name = "tomli", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
yaml = [
{ name = "pyyaml", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
[package.dev-dependencies]
dev = [
{ name = "pre-commit", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "pytest", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "rich", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "ruff", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
[package.metadata]
requires-dist = [
{ name = "pydantic", specifier = ">=2.0.0" },
{ name = "pyyaml", marker = "extra == 'all'" },
{ name = "pyyaml", marker = "extra == 'yaml'" },
{ name = "tomli", marker = "extra == 'all'" },
{ name = "tomli", marker = "extra == 'toml'" },
]
provides-extras = ["yaml", "toml", "all"]
[package.metadata.requires-dev]
dev = [
{ name = "pre-commit", specifier = ">=3.0.0" },
{ name = "pytest", specifier = ">=9.0.3" },
{ name = "rich", specifier = ">=15.0.0" },
{ name = "ruff", specifier = ">=0.12.1" },
]
[[package]]
name = "prime-rl"
version = "0.4.0"
version = "0.5.0"
source = { editable = "." }
dependencies = [
{ name = "aiolimiter", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
@@ -4048,8 +4094,8 @@ name = "prime-rl-configs"
version = "0.4.0"
source = { editable = "packages/prime-rl-configs" }
dependencies = [
{ name = "prime-pydantic-config", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "pydantic", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "pydantic-config", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "renderers", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tomli", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tomli-w", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
@@ -4057,8 +4103,8 @@ dependencies = [
[package.metadata]
requires-dist = [
{ name = "prime-pydantic-config", editable = "deps/pydantic-config" },
{ name = "pydantic", specifier = ">=1.10.13" },
{ name = "pydantic-config", git = "https://github.com/samsja/pydantic_config.git?branch=main" },
{ name = "renderers", editable = "deps/renderers" },
{ name = "tomli", specifier = ">=2.2.1" },
{ name = "tomli-w", specifier = ">=1.2.0" },
@@ -4315,15 +4361,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/be/14/9ee71e3a183f76ff93e46b36157d6ddbf29ec2547b7d2c57931cd5d3aecc/pydantic_argparse-0.10.0-py3-none-any.whl", hash = "sha256:e317f001208d77a5600ece6f7ac78d768d8221a7d64a958980705e9630c2e299", size = 25265, upload-time = "2025-02-09T08:18:27.671Z" },
]
[[package]]
name = "pydantic-config"
version = "0.3.0"
source = { git = "https://github.com/samsja/pydantic_config.git?branch=main#73c1d84f7c359fa5fa3b7cfb946272352866efb7" }
dependencies = [
{ name = "pydantic", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tyro", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
[[package]]
name = "pydantic-core"
version = "2.46.4"