Compare commits

...
Author SHA1 Message Date
Matej SirovatkaandGitHub c935497d71 fix sparse MLA backward tilelang pass (#2520)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-16 22:10:12 +02:00
halleriteandGitHub cd2f3daeb2 chore(renderers): advance to latest main (PR #38) (#2518)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-16 17:40:39 +02:00
897b935cae feat: turn prime-rl into a monorepo (#2507)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat: turn prime-rl into a monorepo with submodules

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

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

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

* chore: scope ruff to prime-rl source only

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* refactor: scope workspace members to installed envs only

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

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

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

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

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

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

* chore: strip noisy comments

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* docs: remove note from submodule init step in README

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

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

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

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

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

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

* chore(verifiers): advance to latest main

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore: remove unused alphabet_sort_branch CI config

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* chore: ignore .claude/scheduled_tasks.lock

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

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

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

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

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

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

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

This reverts commit 0e835ed63ef467f8a33018f809b8ab182ebb2c56.

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

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

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

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

Handled in a separate PR.

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

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

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

* only 5 alphabet sort steps [skip ci]

---------

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

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

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

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

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

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

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

* narrow accepted shapes to str | list[dict]

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

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

* simplify tools lookup

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

* normalize tool defs to OAI shape before chat template

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

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

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

---------

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

Co-authored-by: Eric Botti <ericjbotti@gmail.com>
2026-05-14 23:25:10 +02:00
halleriteandGitHub 458b16ef47 Revert "feat: opt-in renderer-based tokenization for SFT (#2493)" (#2495)
Release / Push CUDA image to Docker (push) Canceled after 0s
This reverts commit b5f196a9c5.
2026-05-14 23:14:24 +02:00
halleriteandGitHub b5f196a9c5 feat: opt-in renderer-based tokenization for SFT (#2493)
Release / Push CUDA image to Docker (push) Canceled after 0s
2026-05-14 23:13:00 +02:00
52 changed files with 3978 additions and 1933 deletions
+5 -1
View File
@@ -14,7 +14,11 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
+30 -27
View File
@@ -28,23 +28,20 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
- name: Run unit tests
env:
USERNAME_CI: CI_RUNNER
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
# This is to allow running tests on forks without WANDB_API_KEY
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
GITHUB_REF_NAME: ${{ github.ref_name }}
GITHUB_HEAD_REF: ${{ github.head_ref }}
@@ -63,21 +60,30 @@ jobs:
fail-fast: false
matrix:
include:
- test: base
- test: reverse_text_sft
runner: vm
pytest_args: "tests/integration -m gpu --ignore=tests/integration/test_rl_lora.py --ignore=tests/integration/test_rl_multi_run_lora.py --ignore=tests/integration/test_benchmark_regression.py --ignore=tests/integration/test_alphabet_sort.py"
- test: rl_lora
pytest_args: "tests/integration/test_reverse_text_sft.py"
- test: reverse_text_sft_lora
runner: vm
pytest_args: "tests/integration/test_rl_lora.py -m gpu"
pytest_args: "tests/integration/test_reverse_text_sft_lora.py"
- test: reverse_text
runner: vm
pytest_args: "tests/integration/test_reverse_text.py"
- test: alphabet_sort
runner: vm
pytest_args: "tests/integration/test_alphabet_sort.py -m gpu"
- test: rl_multi_run
pytest_args: "tests/integration/test_alphabet_sort.py"
- test: reverse_text_lora
runner: vm
pytest_args: "tests/integration/test_reverse_text_lora.py"
- test: reverse_text_moe
runner: vm
pytest_args: "tests/integration/test_reverse_text_moe.py"
- test: reverse_text_multi_run
runner: 4xa6000
pytest_args: "tests/integration/test_rl_multi_run_lora.py -m gpu"
pytest_args: "tests/integration/test_reverse_text_multi_run.py"
- test: benchmark_regression
runner: 4xa6000
pytest_args: "tests/integration/test_benchmark_regression.py -m gpu"
pytest_args: "tests/integration/test_benchmark_regression.py"
steps:
- name: Install Git
run: |
@@ -87,23 +93,20 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
- name: Run integration tests
env:
USERNAME_CI: CI_RUNNER
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
# Set WANDB_MODE to online only if WANDB_API_KEY is available, otherwise set to offline
# This is to allow running tests on forks without WANDB_API_KEY
WANDB_MODE: ${{ secrets.WANDB_API_KEY && 'online' || 'offline' }}
WANDB_MODE: offline
HF_TOKEN: ${{ secrets.HF_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
PRIME_API_KEY: ${{ secrets.PRIME_API_KEY }}
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
PRIME_TEAM_ID: ${{ secrets.PRIME_TEAM_ID }}
@@ -111,4 +114,4 @@ jobs:
GITHUB_HEAD_REF: ${{ github.head_ref }}
PYTEST_OUTPUT_DIR: /tmp/outputs
VLLM_WORKER_MULTIPROC_METHOD: spawn
run: uv run pytest ${{ matrix.pytest_args }}
run: uv run pytest -vvs ${{ matrix.pytest_args }}
+6 -2
View File
@@ -25,7 +25,7 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Build matrix from nightly test files
id: build-matrix
@@ -75,7 +75,11 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
with:
submodules: true
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
+6
View File
@@ -24,6 +24,12 @@ jobs:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: false
- name: Init public submodules
run: |
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/verifiers deps/renderers deps/research-environments
- name: Docker meta
id: meta
uses: crazy-max/ghaction-docker-meta@v2
+2 -1
View File
@@ -16,8 +16,9 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
# Submodules are excluded from ruff via pyproject.toml; no need to fetch them.
with:
submodules: true
submodules: false
- name: Run ruff
uses: astral-sh/ruff-action@v3
with:
+2 -1
View File
@@ -1,4 +1,5 @@
.vscode/*
.claude/scheduled_tasks.lock
*.ipynb
*.jsonl
configs/endpoints.py
@@ -200,4 +201,4 @@ debug_I2_zero_band
outputs/
third_party/
third_party/
+12
View File
@@ -0,0 +1,12 @@
[submodule "verifiers"]
path = deps/verifiers
url = git@github.com:PrimeIntellect-ai/verifiers.git
[submodule "renderers"]
path = deps/renderers
url = git@github.com:PrimeIntellect-ai/renderers.git
[submodule "research-environments"]
path = deps/research-environments
url = git@github.com:PrimeIntellect-ai/research-environments.git
[submodule "configs/private"]
path = configs/private
url = git@github.com:PrimeIntellect-ai/research-configs.git
+1
View File
@@ -43,6 +43,7 @@ COPY uv.lock /app/uv.lock
COPY README.md /app/README.md
COPY src/ /app/src/
COPY packages/ /app/packages/
COPY deps/ /app/deps/
COPY configs /app/configs
COPY examples /app/examples
COPY benchmarks/scripts /app/benchmarks/scripts
+8 -2
View File
@@ -91,14 +91,20 @@ git clone https://github.com/PrimeIntellect-ai/prime-rl.git
cd prime-rl
```
2. Install [uv](https://docs.astral.sh/uv/)
2. Initialize submodules
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
```
3. Install [uv](https://docs.astral.sh/uv/)
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
source $HOME/.local/bin/env
```
3. Install dependencies from the lock file
4. Install dependencies from the lock file
```bash
uv sync --all-extras
@@ -1,4 +1,4 @@
max_steps = 10
max_steps = 5
seq_len = 2048
[ckpt]
@@ -1,29 +0,0 @@
max_steps = 10
seq_len = 2048
[deployment]
type = "single_node"
num_infer_gpus = 1
num_train_gpus = 1
[ckpt]
[model]
name = "Qwen/Qwen3-0.6B"
[trainer.optim]
lr = 1e-5
[orchestrator]
batch_size = 128
rollouts_per_example = 8
[orchestrator.train.sampling]
max_completion_tokens = 1024
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 2, max_turns = 2, min_names_per_turn = 1, max_names_per_turn = 3, similarity_power = 4, power_per_turn = false }
[inference]
@@ -1,8 +1,8 @@
max_steps = 25
max_steps = 20
seq_len = 2048
[ckpt]
resume_step = 20
resume_step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -1,4 +1,4 @@
max_steps = 20
max_steps = 15
seq_len = 2048
[ckpt]
@@ -1,8 +1,8 @@
max_steps = 25
max_steps = 20
seq_len = 2048
[ckpt]
resume_step = 20
resume_step = 15
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -1,4 +1,4 @@
max_steps = 20
max_steps = 15
seq_len = 2048
[ckpt]
@@ -9,6 +9,9 @@ name = "samsja/mini-glm-moe"
[trainer.optim]
lr = 3e-6
[trainer.model]
impl = "custom"
[orchestrator]
batch_size = 128
rollouts_per_example = 16
@@ -1,6 +1,7 @@
max_steps = 10
[ckpt]
resume_step = 5
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -1,7 +1,6 @@
max_steps = 20
max_steps = 5
[ckpt]
resume_step = 10
[model]
name = "PrimeIntellect/Qwen3-0.6B"
@@ -1,7 +1,7 @@
max_steps = 20
max_steps = 10
[ckpt]
resume_step = 10
resume_step = 5
[ckpt.weights]
save_adapter_separately = true
@@ -1,4 +1,4 @@
max_steps = 10
max_steps = 5
[ckpt]
+1
Submodule configs/private added at 74c1330008
Vendored Submodule
+1
Submodule deps/renderers added at 17d0584f87
Vendored Submodule
+1
Vendored Submodule
+1
Submodule deps/verifiers added at 711a7c705e
@@ -6,6 +6,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
from prime_rl.configs.shared import (
HeartbeatConfig,
RendererConfig,
SlurmConfig,
TrainerLogConfig,
WandbConfig,
@@ -172,6 +173,21 @@ class SFTConfig(BaseConfig):
# The tokenizer configuration
tokenizer: TokenizerConfig = TokenizerConfig()
# The renderer configuration (only used when use_renderer=True)
renderer: RendererConfig = RendererConfig()
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
# The data configuration
data: DataConfig = SFTDataConfig()
@@ -357,6 +373,55 @@ class SFTConfig(BaseConfig):
)
return self
@model_validator(mode="after")
def validate_renderer_vs_vlm(self):
if self.use_renderer and self.model.vlm is not None:
raise ValueError(
"use_renderer is not supported for VLMs. The renderer tokenizes "
"text-only message dicts client-side and cannot handle image inputs."
)
return self
@model_validator(mode="after")
def validate_renderer_args(self):
# pool_size is orchestrator-only. An in-process renderer pool exists
# to amortize tokenization across concurrent rollouts in the
# orchestrator (many async requests render at once, HF fast
# tokenizers release the GIL during Rust encoding, so a pool of N
# tokenizer copies parallelizes well). SFT has no such concurrency:
# the StatefulDataLoader is constructed with num_workers=0, so the
# main process tokenizes one example at a time, between training
# steps. Across DP, each rank already owns its own renderer — an
# implicit pool of size world_size. Pooling within a rank gives
# nothing on top of that. Reject so callers don't silently set a
# knob that does nothing; if SFT tokenization ever becomes a
# bottleneck the fix is num_workers on the dataloader, not a pool.
if self.renderer.pool_size is not None:
raise ValueError(
f"renderer.pool_size={self.renderer.pool_size!r} is only used by the orchestrator. "
"SFT tokenizes synchronously (num_workers=0) and already gets one renderer per DP "
"rank — an in-process pool adds nothing. If tokenization is a bottleneck, raise "
"num_workers on the dataloader instead."
)
if self.use_renderer:
return self
renderer_args_set = []
if self.renderer.name != "auto":
renderer_args_set.append(f"renderer.name={self.renderer.name!r}")
if self.renderer.tool_parser is not None:
renderer_args_set.append(f"renderer.tool_parser={self.renderer.tool_parser!r}")
if self.renderer.reasoning_parser is not None:
renderer_args_set.append(f"renderer.reasoning_parser={self.renderer.reasoning_parser!r}")
if renderer_args_set:
raise ValueError(
"Renderer-specific args set without use_renderer=True: "
f"{', '.join(renderer_args_set)}. Either enable the renderer or remove these knobs."
)
return self
@model_validator(mode="after")
def validate_lora_adapter_saving(self):
if self.ckpt and self.ckpt.weights and self.ckpt.weights.save_adapter_separately:
+90 -52
View File
@@ -31,7 +31,7 @@ dependencies = [
"uvloop>=0.21.0",
"torchtitan",
"verifiers",
"renderers==0.1.6",
"renderers",
"dion",
"tilelang>=0.1.8",
"flash-linear-attention",
@@ -59,20 +59,33 @@ flash-attn-cute = [
"flash-attn-4",
]
envs = [
"reverse-text",
"alphabet-sort",
"wiki-search",
"math-python",
"math-env",
"code-env",
"science-env",
"logic-env",
"color-codeword",
"math500",
"aime2024",
"aime2025",
"mini_swe_agent_plus",
"deepdive"
"alphabet-sort",
"code-env",
"color-codeword",
"deepdive",
"gpqa",
"hle",
"ifeval",
"livecodebench",
"logic-env",
"math-env",
"math-python",
"math500",
"mini-swe-agent-plus",
"mini-swe-agent-plus-rlm",
"mmlu-pro",
"opencode-cp",
"opencode-deepdive",
"opencode-math",
"opencode-science",
"opencode-swe",
"reverse-text",
"science-env",
"simpleqa-verified",
"tau2-bench",
"wiki-search",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
@@ -109,7 +122,38 @@ dev = [
[tool.uv.workspace]
members = ["packages/*"]
members = [
"packages/prime-rl-configs",
"deps/verifiers",
"deps/renderers",
"deps/verifiers/environments/alphabet_sort",
"deps/verifiers/environments/math_python",
"deps/verifiers/environments/reverse_text",
"deps/verifiers/environments/wiki_search",
"deps/research-environments/environments/aime2024",
"deps/research-environments/environments/aime2025",
"deps/research-environments/environments/code_env",
"deps/research-environments/environments/color_codeword",
"deps/research-environments/environments/deepdive",
"deps/research-environments/environments/gpqa",
"deps/research-environments/environments/hle",
"deps/research-environments/environments/ifeval",
"deps/research-environments/environments/livecodebench",
"deps/research-environments/environments/logic_env",
"deps/research-environments/environments/math500",
"deps/research-environments/environments/math_env",
"deps/research-environments/environments/mini_swe_agent_plus",
"deps/research-environments/environments/mini_swe_agent_plus_rlm",
"deps/research-environments/environments/mmlu_pro",
"deps/research-environments/environments/opencode_cp",
"deps/research-environments/environments/opencode_deepdive",
"deps/research-environments/environments/opencode_math",
"deps/research-environments/environments/opencode_science",
"deps/research-environments/environments/opencode_swe",
"deps/research-environments/environments/science_env",
"deps/research-environments/environments/simpleqa_verified",
"deps/research-environments/environments/tau2_bench",
]
[tool.uv]
exclude-newer = "7 days"
@@ -125,35 +169,20 @@ override-dependencies = [
"nvidia-cudnn-cu12>=9.15",
"nvidia-cutlass-dsl>=4.4.1",
"transformers>=5.1.0.dev0",
"torch>=2.9.0",
"openenv-core",
]
[tool.uv.exclude-newer-package]
# we want latest vllm, remove next patch
vllm = false
flash_attn_3 = false
# Self-vendored packages on our primeintellect index
reverse-text = false
alphabet-sort = false
wiki-search = false
math-python = false
math-env = false
code-env = false
science-env = false
logic-env = false
color-codeword = false
math500 = false
aime2024 = false
aime2025 = false
deepdive = false
mini_swe_agent_plus = false
# PrimeIntellect-published on PyPI (trusted publisher)
prime = false
prime-sandboxes = false
prime-tunnel = false
prime-evals = false
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
verifiers = false
renderers = false
vllm-router = false
dion = false
pydantic-config = false
@@ -163,10 +192,38 @@ nixl-cu12 = false
[tool.uv.sources]
prime-rl-configs = { workspace = true }
verifiers = { workspace = true }
renderers = { workspace = true }
aime2024 = { workspace = true }
aime2025 = { workspace = true }
alphabet-sort = { workspace = true }
code-env = { workspace = true }
color-codeword = { workspace = true }
deepdive = { workspace = true }
gpqa = { workspace = true }
hle = { workspace = true }
ifeval = { workspace = true }
livecodebench = { workspace = true }
logic-env = { workspace = true }
math-env = { workspace = true }
math-python = { workspace = true }
math500 = { workspace = true }
mini-swe-agent-plus = { workspace = true }
mini-swe-agent-plus-rlm = { workspace = true }
mmlu-pro = { workspace = true }
opencode-cp = { workspace = true }
opencode-deepdive = { workspace = true }
opencode-math = { workspace = true }
opencode-science = { workspace = true }
opencode-swe = { workspace = true }
reverse-text = { workspace = true }
science-env = { workspace = true }
simpleqa-verified = { workspace = true }
tau2-bench = { workspace = true }
wiki-search = { workspace = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
verifiers = { git = "https://github.com/PrimeIntellect-ai/verifiers.git", rev = "aa428f3" }
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" }
@@ -177,20 +234,6 @@ vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.20.2/vllm-0.20.2+cu129-cp38-abi3-manylinux_2_31_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
reverse-text = { index = "primeintellect" }
alphabet-sort = { index = "primeintellect" }
wiki-search = { index = "primeintellect" }
math-python = { index = "primeintellect" }
math-env = { index = "primeintellect" }
code-env = { index = "primeintellect" }
science-env = { index = "primeintellect" }
logic-env = { index = "primeintellect" }
color-codeword = { index = "primeintellect" }
math500 = { index = "primeintellect" }
aime2024 = { index = "primeintellect" }
aime2025 = { index = "primeintellect" }
deepdive = { index = "primeintellect" }
mini_swe_agent_plus = { index = "primeintellect" }
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
@@ -205,17 +248,11 @@ mamba-ssm = [{ requirement = "torch", match-runtime = true }]
[tool.uv.extra-build-variables]
flash-attn = { FLASH_ATTENTION_SKIP_CUDA_BUILD = "TRUE" }
[[tool.uv.index]]
name = "primeintellect"
url = "https://hub.primeintellect.ai/primeintellect/simple/"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128"
url = "https://download.pytorch.org/whl/cu128"
explicit = true
[[tool.uv.index]]
name = "pytorch-cu128-test"
url = "https://download.pytorch.org/whl/test/cu128"
@@ -233,6 +270,7 @@ known-first-party = ["prime_rl"]
[tool.ruff]
line-length = 120
extend-exclude = ["deps"]
[tool.pytest.ini_options]
addopts = "--strict-markers"
+30
View File
@@ -66,6 +66,29 @@ ensure_known_hosts() {
fi
}
# Initialize each submodule independently so that a missing private repo
# (e.g. configs/private when the user lacks access) does not abort the install.
init_submodules() {
if [ ! -f .gitmodules ]; then
return 0
fi
local paths failures
paths=$(git config -f .gitmodules --get-regexp '^submodule\..*\.path$' | awk '{print $2}')
failures=()
for path in $paths; do
log_info "Initializing submodule: ${path}"
if git submodule update --init --recursive -- "$path"; then
:
else
log_warn "Could not initialize submodule '${path}' (likely no access). Continuing without it."
failures+=("$path")
fi
done
if [ "${#failures[@]}" -gt 0 ]; then
log_warn "Skipped submodules: ${failures[*]}"
fi
}
main() {
assert_supported_platform
@@ -98,6 +121,13 @@ main() {
cd ${REPO_ID}
fi
if ! has_ssh_access; then
git config url."https://github.com/".insteadOf "git@github.com:"
fi
log_info "Initializing submodules..."
init_submodules
log_info "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh
+1
View File
@@ -177,4 +177,5 @@ In TOML, an empty section header does the same:
- `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
+1
View File
@@ -88,4 +88,5 @@ curl http://localhost:8000/v1/chat/completions \
- `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
+25 -1
View File
@@ -5,13 +5,37 @@ description: How to install prime-rl and its optional dependencies. Use when set
# 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
```
For an existing clone, initialize the public submodules by passing explicit paths:
```bash
git submodule update --init -- deps/verifiers deps/renderers deps/research-environments
```
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/`, and `deps/research-environments/`. Each is also a uv workspace member, so source edits inside them apply 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 flash-attn, flash-attn-cute, etc.
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]`.
## Advanced
### Mamba-SSM (NemotronH models)
+2
View File
@@ -145,6 +145,8 @@ These tell you whether training is healthy or diverging.
|--------|--------|-------------|
| `mismatch_kl/mean` | trainer | KL divergence between trainer and (old) inference policy |
| `entropy/mean` | trainer | policy entropy |
| `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
+2 -2
View File
@@ -349,10 +349,10 @@ def rl_local(config: RLConfig):
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing trainer logs...")
logger.success("Startup complete. Showing orchestrator logs...")
tail_process = Popen(
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
f"tail -F '{log_dir / 'orchestrator.log'}'",
shell=True,
)
processes.append(tail_process)
@@ -91,7 +91,8 @@ def postprocess(
pass_configs={
tilelang.PassConfigKey.TL_DISABLE_TMA_LOWER: True,
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: True,
# Avoid TileLang MLA backward NaNs: https://github.com/tile-ai/tilelang/issues/2199
tilelang.PassConfigKey.TL_ENABLE_AGGRESSIVE_SHARED_MEMORY_MERGE: False,
},
)
def bwd(
+8 -3
View File
@@ -127,11 +127,14 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
probs_diff = trainer_probs - inference_probs
dppo_invalid_mask_high = probs_diff > loss_config.dppo_mask_high
dppo_invalid_mask_low = probs_diff < -loss_config.dppo_mask_low
dppo_invalid_mask = torch.where(advantages > 0, dppo_invalid_mask_high, dppo_invalid_mask_low)
positive_advantages = advantages > 0
negative_advantages = advantages < 0
dppo_invalid_mask = torch.where(positive_advantages, dppo_invalid_mask_high, dppo_invalid_mask_low)
is_masked = dppo_invalid_mask
is_masked_high = (advantages > 0) & dppo_invalid_mask_high
is_masked_low = (advantages < 0) & dppo_invalid_mask_low
is_masked_high = positive_advantages & dppo_invalid_mask_high
is_masked_low = negative_advantages & dppo_invalid_mask_low
drop_mask = loss_mask & is_masked
keep_mask = loss_mask & ~is_masked
log_importance_ratio = trainer_logprobs - inference_logprobs
@@ -156,6 +159,8 @@ def default_loss_fn(inputs: LossInputs, loss_config: DefaultLossConfig) -> LossO
"is_masked": _safe_mean(is_masked, loss_mask),
"is_masked_low": _safe_mean(is_masked_low, loss_mask),
"is_masked_high": _safe_mean(is_masked_high, loss_mask),
"masked_advantage_positive": _safe_mean(positive_advantages, drop_mask),
"masked_advantage_negative": _safe_mean(negative_advantages, drop_mask),
}
if teacher_kl is not None:
metrics["teacher_kl"] = _safe_mean(teacher_kl, loss_mask)
+55 -9
View File
@@ -6,6 +6,7 @@ from typing import Literal, TypedDict, cast
import torch
from datasets import Dataset, interleave_datasets, load_dataset
from jaxtyping import Bool, Int
from renderers.base import Renderer, build_training_sample
from torch import Tensor
from torch.distributed.checkpoint.stateful import Stateful
from torch.utils.data import IterableDataset, get_worker_info
@@ -127,6 +128,7 @@ class SFTDataset(StatefulIterableDataset):
loss_mask_config: LossMaskConfig = LossMaskConfig(),
max_examples: int | None = None,
max_epochs: int | None = None,
renderer: Renderer | None = None,
):
super().__init__()
self.logger = get_logger()
@@ -139,6 +141,8 @@ class SFTDataset(StatefulIterableDataset):
self.loss_mask_config = loss_mask_config
self.max_examples = max_examples
self.max_epochs = max_epochs
self.renderer = renderer
self._warned_chat_template_kwargs = False
if self.tokenizer is None:
self.logger.warning("No tokenizer provided, will not process examples")
@@ -190,7 +194,30 @@ class SFTDataset(StatefulIterableDataset):
# Parse available tools, if present - assumes OAI format
# Reference: https://platform.openai.com/docs/guides/function-calling#function-tool-example
tools = json.loads(example.get("tools") or "[]")
# Accepts either `tools` or `tool_defs` (the verifiers rollout format),
# as either a JSON-encoded string of a list or a list of dicts. Tools
# arriving in the verifiers shape are converted to OAI form so any
# downstream chat template can consume them.
raw_tools = example.get("tools", example.get("tool_defs"))
if not raw_tools:
tools = []
else:
if isinstance(raw_tools, str):
raw_tools = json.loads(raw_tools)
tools = [
t
if isinstance(t, dict) and t.get("type") == "function" and "function" in t
else {
"type": "function",
"function": {
"name": t.get("name"),
"description": t.get("description"),
"parameters": t.get("parameters"),
**({} if t.get("strict") is None else {"strict": t["strict"]}),
},
}
for t in raw_tools
]
def should_mask(message: dict) -> bool:
assert "role" in message, "Message must have a role"
@@ -206,18 +233,35 @@ class SFTDataset(StatefulIterableDataset):
case _:
raise ValueError(f"Invalid message role: {message['role']}")
try:
input_ids, loss_mask = build_incremental_token_mask(
self.tokenizer,
if self.renderer is not None:
if example.get("chat_template_kwargs") and not self._warned_chat_template_kwargs:
self.logger.warning(
"Example carries chat_template_kwargs but use_renderer=True; "
"renderers don't forward chat_template_kwargs (model-specific "
"renderers bake their template behavior in). These kwargs will "
"be ignored. Further warnings suppressed for this dataset."
)
self._warned_chat_template_kwargs = True
input_ids, loss_mask = build_training_sample(
self.renderer,
messages,
role_to_mask=should_mask,
tools=tools,
chat_template_kwargs=example.get("chat_template_kwargs", {}),
collapse_consecutive_tool_messages=True,
)
except IncrementalTokenizationError as e:
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
return None
else:
try:
input_ids, loss_mask = build_incremental_token_mask(
self.tokenizer,
messages,
role_to_mask=should_mask,
tools=tools,
chat_template_kwargs=example.get("chat_template_kwargs", {}),
collapse_consecutive_tool_messages=True,
)
except IncrementalTokenizationError as e:
self.logger.warning(f"Skipping example {example.get('__index', '')}: {e}")
return None
# If EOS token is not found, manually append it
if not self.tokenizer.eos_token_id in input_ids:
@@ -537,6 +581,7 @@ def setup_dataset(
*,
max_epochs: int | None = None,
raw_dataset: Dataset | None = None,
renderer: Renderer | None = None,
) -> StatefulIterableDataset:
if config.type == "fake":
return FakeDataset(
@@ -554,6 +599,7 @@ def setup_dataset(
loss_mask_config=config.loss_mask,
non_dp_size=non_dp_size,
max_epochs=max_epochs,
renderer=renderer,
)
else:
raise ValueError(f"Invalid dataset type: {config.type}")
+27 -2
View File
@@ -4,6 +4,8 @@ import time
from contextlib import nullcontext
from datetime import timedelta
from renderers.base import create_renderer
from renderers.default import DefaultRenderer
from ring_flash_attn import substitute_hf_flash_attn
from torch.nn import CrossEntropyLoss
@@ -157,6 +159,24 @@ def train(config: SFTConfig):
logger.info(f"Initializing tokenizer ({config.tokenizer})")
tokenizer = setup_tokenizer(config.tokenizer)
renderer = None
if config.use_renderer:
renderer = create_renderer(
tokenizer,
renderer=config.renderer.name,
tool_parser=config.renderer.tool_parser,
reasoning_parser=config.renderer.reasoning_parser,
)
if isinstance(renderer, DefaultRenderer):
raise ValueError(
f"use_renderer=True for {config.tokenizer.name!r} resolved to DefaultRenderer. "
"DefaultRenderer falls back to incremental apply_chat_template and does NOT "
"fix position-dependent chat templates — the bug use_renderer is meant to solve. "
"Either use a model with a hand-coded renderer (see renderers.base.MODEL_RENDERER_MAP), "
"set [renderer] name=<hand-coded renderer> explicitly, or set use_renderer=false."
)
logger.info(f"Initialized {type(renderer).__name__} for {config.tokenizer.name}")
# Set up the optimizer
logger.info(f"Initializing optimizer ({config.optim})")
optimizer = setup_optimizer(
@@ -175,7 +195,7 @@ def train(config: SFTConfig):
# Set up the dataset and dataloader
logger.info(f"Initializing data ({config.data})")
dataset = setup_dataset(tokenizer, config.data, config.model.cp)
dataset = setup_dataset(tokenizer, config.data, config.model.cp, renderer=renderer)
dataloader = setup_dataloader(dataset, config.data)
dataiter = iter(dataloader)
@@ -283,7 +303,12 @@ def train(config: SFTConfig):
def run_validation(step: int) -> None:
val_dataset = setup_dataset(
tokenizer, config.val.data, config.model.cp, max_epochs=1, raw_dataset=val_raw_dataset
tokenizer,
config.val.data,
config.model.cp,
max_epochs=1,
raw_dataset=val_raw_dataset,
renderer=renderer,
)
val_dataloader = setup_dataloader(val_dataset, config.val.data)
+2
View File
@@ -389,6 +389,8 @@ def filter_rl_trainer_tensor_stats_for_wandb(metrics: dict[str, float | int]) ->
"is_masked/",
"is_masked_low/",
"is_masked_high/",
"masked_advantage_positive/",
"masked_advantage_negative/",
"mismatch_kl/",
"masked_mismatch_kl/",
"unmasked_mismatch_kl/",
+6 -4
View File
@@ -47,7 +47,10 @@ class WandbMonitor(Monitor):
self.logger.info(f"Initializing {self.__class__.__name__} ({config})")
self._maybe_overwrite_wandb_command()
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1"
# WANDB_MODE=disabled/offline takes precedence over shared mode — shared mode
# requires a server connection and can't work offline.
_wandb_mode = os.environ.get("WANDB_MODE")
shared_mode = os.environ.get("WANDB_SHARED_MODE") == "1" and _wandb_mode not in ("disabled", "offline")
if shared_mode:
run_id = os.environ.get("WANDB_SHARED_RUN_ID")
label = os.environ.get("WANDB_SHARED_LABEL")
@@ -65,9 +68,8 @@ class WandbMonitor(Monitor):
else:
run_id = None
primary = False
settings = wandb.Settings(
mode="offline" if config.offline else "online",
)
mode = os.environ.get("WANDB_MODE", "offline" if config.offline else "online")
settings = wandb.Settings(mode=mode)
def init_wandb(max_retries: int):
for attempt in range(max_retries):
+25 -19
View File
@@ -4,7 +4,13 @@ from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.utils import check_no_error, check_reward_goes_up, check_reward_in_range, strip_escape_codes
from tests.utils import (
check_avg_mismatch_kl_in_range,
check_no_error,
check_reward_goes_up,
check_reward_in_range,
strip_escape_codes,
)
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
@@ -12,23 +18,16 @@ pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 900 # 15 minutes
@pytest.fixture(scope="module")
def rl_output_dir(output_dir: Path) -> Path:
rl_dir = output_dir / "alphabet_sort_start"
rl_dir.mkdir(parents=True, exist_ok=True)
return rl_dir
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for alphabet sort RL CI integration tests."""
return f"test-alphabet-sort-{branch_name}"
return f"test-alphabet-sort:{branch_name}"
@pytest.fixture(scope="module")
def rl_process(
run_process: Callable[..., ProcessResult],
rl_output_dir: Path,
output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
@@ -37,32 +36,39 @@ def rl_process(
"run",
"rl",
"@",
"configs/ci/integration/alphabet_sort/start.toml",
"configs/ci/integration/alphabet_sort.toml",
"--wandb.project",
wandb_project,
"--wandb.name",
wandb_name,
"--output-dir",
rl_output_dir.as_posix(),
output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def test_no_error(rl_process: ProcessResult, rl_output_dir: Path):
def test_no_error(rl_process: ProcessResult, output_dir: Path):
"""Tests that the RL process does not fail."""
check_no_error(rl_process, rl_output_dir)
check_no_error(rl_process, output_dir)
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, rl_output_dir: Path):
def test_reward_goes_up(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that the reward goes up in the RL process."""
with open(rl_output_dir / "logs" / "orchestrator.log", "r") as f:
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_reward_goes_up(orchestrator_stdout)
def test_reward_in_range(rl_process: ProcessResult, test_no_error, rl_output_dir: Path):
def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that the reward is in range in the RL process."""
with open(rl_output_dir / "logs" / "orchestrator.log", "r") as f:
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
orchestrator_stdout = strip_escape_codes(f.read()).splitlines()
check_reward_in_range(orchestrator_stdout, min_threshold=0.05)
check_reward_in_range(orchestrator_stdout, min_threshold=0.10)
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that the average mismatch KL is below 0.15 across the last 5 steps."""
with open(output_dir / "logs" / "trainer.log", "r") as f:
trainer_stdout = strip_escape_codes(f.read()).splitlines()
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=5, max_threshold=0.15)
@@ -4,7 +4,13 @@ from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.utils import check_no_error, check_reward_goes_up, check_reward_in_range, strip_escape_codes
from tests.utils import (
check_avg_mismatch_kl_in_range,
check_no_error,
check_reward_goes_up,
check_reward_in_range,
strip_escape_codes,
)
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
@@ -15,7 +21,7 @@ TIMEOUT = 600 # 10 minutes
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for RL CI integration tests."""
return f"test-rl-{branch_name}"
return f"test-reverse-text:{branch_name}"
@pytest.fixture(scope="module")
@@ -30,7 +36,7 @@ def rl_process(
"run",
"rl",
"@",
"configs/ci/integration/rl/start.toml",
"configs/ci/integration/reverse_text/start.toml",
"--clean-output-dir",
"--wandb.project",
wandb_project,
@@ -58,7 +64,7 @@ def rl_resume_process(
"run",
"rl",
"@",
"configs/ci/integration/rl/resume.toml",
"configs/ci/integration/reverse_text/resume.toml",
"--wandb.project",
wandb_project,
"--wandb.name",
@@ -90,6 +96,13 @@ def test_reward_in_range(rl_process: ProcessResult, test_no_error, output_dir: P
check_reward_in_range(orchestrator_stdout, min_threshold=0.65)
def test_mismatch_kl_in_range(rl_process: ProcessResult, test_no_error, output_dir: Path):
"""Tests that the average mismatch KL is below 0.01 across all steps"""
with open(output_dir / "logs" / "trainer.log", "r") as f:
trainer_stdout = strip_escape_codes(f.read()).splitlines()
check_avg_mismatch_kl_in_range(trainer_stdout, last_n_steps=3, max_threshold=0.01)
@pytest.fixture(scope="module")
def test_no_error_resume(rl_resume_process: ProcessResult, output_dir: Path):
"""Tests that the RL resume process does not fail."""
@@ -15,7 +15,7 @@ TIMEOUT = 600 # 10 minutes
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for RL CI integration tests."""
return f"test-rl-lora-{branch_name}"
return f"test-reverse-text-lora:{branch_name}"
@pytest.fixture(scope="module")
@@ -30,7 +30,7 @@ def rl_process(
"run",
"rl",
"@",
"configs/ci/integration/rl_lora/start.toml",
"configs/ci/integration/reverse_text_lora/start.toml",
"--clean-output-dir",
"--wandb.project",
wandb_project,
@@ -58,7 +58,7 @@ def rl_resume_process(
"run",
"rl",
"@",
"configs/ci/integration/rl_lora/resume.toml",
"configs/ci/integration/reverse_text_lora/resume.toml",
"--wandb.project",
wandb_project,
"--wandb.name",
@@ -0,0 +1,50 @@
from pathlib import Path
from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.utils import check_no_error
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 900 # 15 minutes
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
return f"test-reverse-text-moe:{branch_name}"
@pytest.fixture(scope="module")
def rl_process(
run_process: Callable[..., ProcessResult],
wandb_project: str,
wandb_name: str,
output_dir: Path,
) -> ProcessResult:
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/integration/reverse_text_moe/start.toml",
"--trainer.model.impl",
"custom",
"--wandb.project",
wandb_project,
"--wandb.name",
f"{wandb_name}-custom",
"--output-dir",
output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def test_no_error(rl_process: ProcessResult, output_dir: Path):
check_no_error(rl_process, output_dir)
def test_moe_runs(rl_process: ProcessResult, test_no_error):
"""MoE RL with custom model impl completes without error."""
@@ -88,7 +88,7 @@ def wait_for_log(
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for multi-run RL CI integration tests."""
return f"test-rl-multi-run-{branch_name}"
return f"test-reverse-text-multi-run:{branch_name}"
INFERENCE_PORTS = [8000, 8001]
@@ -111,7 +111,7 @@ def start_inference_and_trainer(
"run",
"inference",
"@",
"configs/ci/integration/rl_multi_run/inference.toml",
"configs/ci/integration/reverse_text_multi_run/inference.toml",
"--server.port",
str(port),
],
@@ -134,7 +134,7 @@ def start_inference_and_trainer(
"-m",
"prime_rl.trainer.rl.train",
"@",
"configs/ci/integration/rl_multi_run/trainer.toml",
"configs/ci/integration/reverse_text_multi_run/trainer.toml",
"--output-dir",
output_dir.as_posix(),
"--wandb.project",
@@ -200,7 +200,7 @@ def start_orchestrator(
"run",
"orchestrator",
"@",
"configs/ci/integration/rl_multi_run/orchestrator.toml",
"configs/ci/integration/reverse_text_multi_run/orchestrator.toml",
"--output-dir",
run_dir.as_posix(),
"--max-steps",
@@ -14,7 +14,7 @@ TIMEOUT = 300 # 5 minutes
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for SFT CI integration tests."""
return f"test-sft-{branch_name}"
return f"test-reverse-text-sft:{branch_name}"
@pytest.fixture(scope="module")
@@ -30,7 +30,7 @@ def sft_process(
"run",
"sft",
"@",
"configs/ci/integration/sft/start.toml",
"configs/ci/integration/reverse_text_sft/start.toml",
"--deployment.num-gpus",
"2",
"--clean-output-dir",
@@ -60,7 +60,7 @@ def sft_resume_process(
"run",
"sft",
"@",
"configs/ci/integration/sft/resume.toml",
"configs/ci/integration/reverse_text_sft/resume.toml",
"--deployment.num-gpus",
"2",
"--wandb.project",
@@ -24,7 +24,7 @@ def assert_adapter_checkpoint(adapter_dir: Path) -> None:
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
"""Fixture for W&B name for SFT LoRA CI integration tests."""
return f"test-sft-lora-{branch_name}"
return f"test-reverse-text-sft-lora:{branch_name}"
@pytest.fixture(scope="module")
@@ -40,7 +40,7 @@ def sft_lora_process(
"run",
"sft",
"@",
"configs/ci/integration/sft_lora/start.toml",
"configs/ci/integration/reverse_text_sft_lora/start.toml",
"--deployment.num-gpus",
"2",
"--clean-output-dir",
@@ -70,7 +70,7 @@ def sft_lora_resume_process(
"run",
"sft",
"@",
"configs/ci/integration/sft_lora/resume.toml",
"configs/ci/integration/reverse_text_sft_lora/resume.toml",
"--deployment.num-gpus",
"2",
"--wandb.project",
@@ -100,7 +100,7 @@ def test_loss_goes_down(sft_lora_process: ProcessResult, output_dir: Path):
def test_adapter_checkpoint_written(sft_lora_process: ProcessResult, output_dir: Path):
"""Tests that the adapter checkpoint is written with valid PEFT-compatible keys."""
adapter_dir = output_dir / "weights" / "step_10" / "lora_adapters"
adapter_dir = output_dir / "weights" / "step_5" / "lora_adapters"
assert_adapter_checkpoint(adapter_dir)
@@ -120,5 +120,5 @@ def test_loss_goes_down_resume(sft_lora_resume_process: ProcessResult, output_di
def test_adapter_checkpoint_written_resume(sft_lora_resume_process: ProcessResult, output_dir: Path):
"""Tests that the adapter checkpoint is written after resuming with valid PEFT-compatible keys."""
adapter_dir = output_dir / "weights" / "step_20" / "lora_adapters"
adapter_dir = output_dir / "weights" / "step_10" / "lora_adapters"
assert_adapter_checkpoint(adapter_dir)
-104
View File
@@ -1,104 +0,0 @@
from pathlib import Path
from typing import Callable
import pytest
from tests.conftest import ProcessResult
from tests.utils import check_no_error
pytestmark = [pytest.mark.gpu, pytest.mark.slow]
TIMEOUT = 900 # 15 minutes
@pytest.fixture(scope="module")
def wandb_name(branch_name: str) -> str:
return f"test-rl-moe-{branch_name}"
# --- MoE with HF impl (default) ---
@pytest.fixture(scope="module")
def moe_hf_output_dir(output_dir: Path) -> Path:
d = output_dir / "rl_moe_hf"
d.mkdir(parents=True, exist_ok=True)
return d
@pytest.fixture(scope="module")
def moe_hf_process(
run_process: Callable[..., ProcessResult],
moe_hf_output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/integration/rl_moe/start.toml",
"--trainer.model.impl",
"hf",
"--wandb.project",
wandb_project,
"--wandb.name",
f"{wandb_name}-hf",
"--output-dir",
moe_hf_output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def test_no_error_hf(moe_hf_process: ProcessResult, moe_hf_output_dir: Path):
check_no_error(moe_hf_process, moe_hf_output_dir)
def test_moe_hf_runs(moe_hf_process: ProcessResult, test_no_error_hf):
"""MoE RL with HF model impl completes without error."""
# --- MoE with custom impl ---
@pytest.fixture(scope="module")
def moe_custom_output_dir(output_dir: Path) -> Path:
d = output_dir / "rl_moe_custom"
d.mkdir(parents=True, exist_ok=True)
return d
@pytest.fixture(scope="module")
def moe_custom_process(
run_process: Callable[..., ProcessResult],
moe_custom_output_dir: Path,
wandb_project: str,
wandb_name: str,
) -> ProcessResult:
cmd = [
"uv",
"run",
"rl",
"@",
"configs/ci/integration/rl_moe/start.toml",
"--trainer.model.impl",
"custom",
"--wandb.project",
wandb_project,
"--wandb.name",
f"{wandb_name}-custom",
"--output-dir",
moe_custom_output_dir.as_posix(),
]
return run_process(cmd, timeout=TIMEOUT)
@pytest.fixture(scope="module")
def test_no_error_custom(moe_custom_process: ProcessResult, moe_custom_output_dir: Path):
check_no_error(moe_custom_process, moe_custom_output_dir)
def test_moe_custom_runs(moe_custom_process: ProcessResult, test_no_error_custom):
"""MoE RL with custom model impl completes without error."""
+3 -2
View File
@@ -25,8 +25,9 @@ CONFIG_CLASSES = [
def get_config_files() -> list[Path]:
"""Any TOML file inside `configs/` or `examples/`"""
config_files = list(Path("configs").rglob("*.toml"))
"""Any TOML file inside `configs/` or `examples/` (skips the configs/private/ submodule)."""
private = Path("configs/private")
config_files = [p for p in Path("configs").rglob("*.toml") if private not in p.parents]
example_files = list(Path("examples").rglob("*.toml"))
return config_files + example_files
+35 -2
View File
@@ -14,10 +14,10 @@ def check_no_error(process: ProcessResult, output_dir: Path) -> None:
if process.returncode != 0:
print("=== Inference Outputs ===")
with open(output_dir / "logs" / "inference.log", "r") as f:
print(*f.readlines()[-100:], sep="\n")
print(*f.readlines()[-100:], sep="")
print("=== Orchestrator Outputs ===")
with open(output_dir / "logs" / "orchestrator.log", "r") as f:
print(*f.readlines()[-1000:], sep="\n")
print(*f.readlines()[-1000:], sep="")
assert process.returncode == 0, f"Process has non-zero return code ({process})"
@@ -157,6 +157,39 @@ def check_avg_reward_in_range(
)
def check_avg_mismatch_kl_in_range(
lines: list[str],
last_n_steps: int,
min_threshold: float | None = None,
max_threshold: float | None = None,
):
"""Helper to assert that the average mismatch KL over the last N steps is within a threshold"""
pattern = r"Mismatch KL:\s*(\d+\.\d{4})"
step_lines = [line for line in lines if "SUCCESS" in line and "Step" in line and re.search(pattern, line)]
assert len(step_lines) >= last_n_steps, (
f"Not enough step lines found. Expected at least {last_n_steps}, got {len(step_lines)}"
)
recent_lines = step_lines[-last_n_steps:]
kl_values = []
for line in recent_lines:
match = re.search(pattern, line)
assert match is not None, f"Could not find Mismatch KL in line: {line}"
kl_values.append(float(match.group(1)))
avg_kl = sum(kl_values) / len(kl_values)
if min_threshold is not None:
assert avg_kl >= min_threshold, (
f"Average mismatch KL over last {last_n_steps} steps did not reach minimum threshold. "
f"Found avg_kl={avg_kl:.4f} < {min_threshold} (kl_values={kl_values})"
)
if max_threshold is not None:
assert avg_kl <= max_threshold, (
f"Average mismatch KL over last {last_n_steps} steps exceeded maximum threshold. "
f"Found avg_kl={avg_kl:.4f} > {max_threshold} (kl_values={kl_values})"
)
def check_mismatch_kl_in_range(
lines: list[str],
step: int = -1,
Generated
+3426 -1638
View File
File diff suppressed because it is too large Load Diff