Compare commits

...
Author SHA1 Message Date
961c11f4cf feat(orchestrator): support infinite tasksets (#2993)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): support infinite tasksets

An env server may now report num_tasks=None (verifiers#1969: an
infinite, procedurally generated taskset). TrainSource streams a
monotonic task_idx for such an env - the server generates tasks on
demand, so every pull is a fresh task and there are no epochs to
shuffle - while finite envs keep their shuffled index table. An eval
env with an infinite taskset must set num_examples explicitly.

Dormant until the verifiers pin includes #1969: a finite taskset still
reports an int count and takes the existing paths.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers to main (infinite tasksets) + relock

Activates the orchestrator's infinite-taskset support: verifiers main
now includes #1969, so the procedural v1 tasksets report
num_tasks=None. The color-codeword-v1 configs drop their num_examples
taskset field (the knob no longer exists - the taskset is
unconditionally infinite and the train env streams); CHANGELOG entry
for the removed size knobs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop CHANGELOG entry

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 19:05:55 -07:00
Sebastian MüllerandGitHub b7b1f874b5 fix(trainer): skip unneeded gradients in fused LM-head backward (#3011)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
_SequenceChunkedLogProbEntropyFn.backward unconditionally allocated and
accumulated both grad_hidden and grad_weight, ignoring
ctx.needs_input_grad. With a frozen output head (e.g. LoRA without head
adaptation) this allocated a full vocab-size gradient buffer and ran the
weight-gradient matmuls for a result autograd discards. Allocate and
accumulate each gradient only when required; return None otherwise.
2026-07-14 03:25:41 +02:00
d334ea5294 chore: release v0.7.0 (#2998)
Tag and Release / auto-tag-on-main (push) Canceled after 0s
Tag and Release / release-from-auto-tag (push) Canceled after 0s
Tag and Release / tag-and-release (push) Canceled after 0s
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: release v0.7.0

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

* chore: sync uv.lock to 0.7.0

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 18:22:09 -07:00
57d2b84330 feat(config): allow prime-rl conversions to be stored separately from model (#3023)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(config): allow prime-rl conversions to be stored separately from model

Add primerl_conversion_dir config field to decouple converted weight
storage from the (potentially immutable) model snapshot directory. When
set, HF<->PrimeRL format conversions are written there instead of inside
the model directory. Defaults to None (existing behavior).

Also fixes load_state_dict to always read from the original source_path
instead of the converted snapshot path's parent.

Signed-off-by: Sami Jaghouar <sami.jaghouar@gmail.com>

* chore: rename primerl_conversion_dir to conversion_dir

Address review: shorter field name and clarify the docstring that converted
weights land in a prime/hf subdirectory. Keep the /prime subdir layout.

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

---------

Signed-off-by: Sami Jaghouar <sami.jaghouar@gmail.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 18:13:32 -07:00
Matej SirovatkaandGitHub 4f5e06fcb6 fix: install vllm-router on aarch64 (#3025)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-14 02:20:25 +02:00
Matej SirovatkaandGitHub 390dfdc556 fix: support DeepGEMM FP8 training on SM100 (#3022)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: support DeepGEMM grouped GEMM on SM100

* Remove FP8 inference instructions

Remove FP8 inference section from SKILL.md.

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>

* refactor: inline DeepGEMM scale mode

* fix: support FP8 linears on SM100

---------

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-07-14 02:19:24 +02:00
2fdffa7d3d fix(trainer): broadcast resumed policy weights before training loop (#3004)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(trainer): broadcast resumed policy weights before training loop

On resume, the orchestrator advances to v{checkpoint_step} and pauses
inference to receive those weights over NCCL. Since #2896 moved the
in-loop weight broadcast to the END of a step, the trainer would start
step {checkpoint_step+1} first — which blocks on rollouts the paused
inference engines cannot produce until they get v{checkpoint_step}.
Both sides then wait forever (confirmed on GLM-5.2 resume: orchestrator
"Created NCCL_READY marker" then silent, trainer stuck "Looking for
batches" for the next step).

Restore the pre-#2896 top-of-loop sync with a one-shot broadcast right
after checkpoint load. Runs are only registered during batch collection
(packer.discover_runs), so discover run 0 first (mirroring optim.py's
wait-for-run-0 pattern) to populate used_idxs before broadcasting.

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

* refactor(resume): broadcast startup weights on the first step (fresh or resume)

Address review: instead of a resume-only pre-loop broadcast, always sync
inference to the incoming policy on the first training step.

- trainer: broadcast v{step-1} at the top of the loop's first iteration
  (fresh -> v0, resume -> v{checkpoint_step}), replacing the pre-loop block.
- orchestrator: always pause + sync inference at startup (previously
  resume-only), so it rendezvouses with the trainer's first-step broadcast
  in both cases and startup is symmetric.
- factor the "wait for run 0 to be discovered" loop into
  MultiRunManager.wait_for_run(); reuse it in optim.py (dedupes the
  copy that lived there) and the first-step broadcast.

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

* fix(orchestrator): wait for startup broadcast on fresh start

The unconditional startup weight sync fell back to wait_timeout=None when
there was no ckpt block (from-scratch run). With filesystem weight broadcast
(check_exists=True), get_weight_dir then raised FileNotFoundError immediately
instead of waiting for the trainer to write broadcasts/step_0/STABLE.

Fall back to a default timeout so the orchestrator waits for the trainer's
startup broadcast, which is always coming.

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

* fix(config): reject NCCL weight broadcast with LoRA

LoRA adapters are transferred via the filesystem (loaded from disk by the
inference servers); NCCL broadcast only writes a STABLE marker. The now
unconditional startup weight sync makes a fresh LoRA + NCCL run try to load an
adapter from a disk path NCCL never populates, hanging/failing during setup
(and LoRA over NCCL is broken for training-time updates too).

The auto weight-broadcast setup already falls back to filesystem for LoRA when
unset; enforce the same invariant for an explicitly configured NCCL broadcast
instead of failing at runtime.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 17:00:52 -07:00
7cbc77a27f fix: respect packed document boundaries in Qwen3.5 DeltaNet CP (#3003)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Under Ulysses CP the DeltaNet layer built its fla CP context from a
fabricated single-sequence cu_seqlens, so the gated delta rule carried
state across packed documents. The causal conv used shard-local
cu_seqlens, resetting mid-document at every shard boundary even for
unpacked rows.

Build the CP context from the full pre-shard cu_seqlens published by
setup_cp_params (fla derives per-rank boundaries and document-aware
state passing from them) and run the convolution through fla's CP conv,
which resets at true document boundaries and exchanges tail tokens
across ranks for straddling documents.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-07-13 16:06:13 -07:00
21c072a8f9 fix: reset Nemotron-H CP state at packed boundaries (#3001)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: reset Nemotron-H CP state at packed boundaries

* chore: simplify packed-boundary plumbing in CP mamba

- read ULYSSES_PARAMS["cu_seqlens"] directly via a module-level import,
  matching the ulysses attention path (no try/except wrapper)
- convert cu_seqlens to a boundary list once per forward and share it
  between the conv and seq_idx helpers (one host sync instead of four)
- import cp_mamba as a normal package module in the test

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: drop unused final states from CP mamba scan

return_final_states=True computed and returned states the CP path
discards; return_final_states=False matches the non-CP varlen path
and skips the dfinal_states backward work. Flagged by Cursor Bugbot
(its assert/mishandling claim does not reproduce against mamba_ssm
2.3.1 — outputs and grads verified bit-identical on GPU either way).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: hallerite <git@hallerite.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: samsja <55492238+samsja@users.noreply.github.com>
2026-07-13 16:05:36 -07:00
cb43db2ad1 feat: make all envs uv workspace members, drop the envs extra (#3019)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: make research-environment envs uv workspace members

Research envs under deps/research-environments/environments/*/* are now
auto-discovered uv workspace members instead of being hand-registered in
the `envs` extra + [tool.uv.sources]. Adding a new research env needs no
pyproject.toml change - the glob picks it up and it's locked automatically.

They are opt-in: `uv sync` / `--all-extras` no longer install them; use
`uv sync --all-packages`. Env-running sites (sbatch training templates,
gpu/nightly CI, Docker image + entrypoint, nemotron config, example
READMEs) gain --all-packages; dev quickstart and cpu unit tests stay lean.

tau2-synth-v1 and tau3-bench-v1 are excluded - they pin `tau2` forks/revs
that conflict with the canonical tau2-bench-v1 in the workspace's shared lock.

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

* feat: make verifiers envs workspace members, drop the envs extra

Extends the workspace glob to deps/verifiers/environments/*, so verifiers-repo
envs are auto-discovered members alongside the research envs. Removes the
now-empty `envs` optional-dependency and all its [tool.uv.sources] entries, and
drops the defunct `--extra envs` from cpu_tests, Dockerfile.cuda, and
docker-entrypoint.sh (env members install via --all-packages instead).

All 94 env members (66 research + 28 verifiers) lock, install, and import.

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

* fix(ci): install all env packages in cpu_tests

test_load_configs parses every config, and parsing a v1-taskset config makes
verifiers import the env package to derive its taskset config type. With envs
now workspace members, the lean `uv sync --extra flash-attn` left them
uninstalled, so 28 config tests failed with ModuleNotFoundError. Add
--all-packages so the referenced env packages are importable.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 15:46:33 -07:00
Sebastian MüllerandGitHub 2c6ac2bd47 fix(orchestrator): scope the train batch observation window to finalized groups (#3013)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
TrainSink filled the observation window (TrainBatch.rollouts) on arrival,
so a ready overflow batch triggered by the first rollout of a new,
incomplete group claimed that rollout in its window; the window then
reset, leaving the rollout missing from the window of the batch its own
group eventually shipped in. Metrics and persisted per-step traces could
therefore describe rollouts that belong to a different batch.

Window membership now follows group finalization: arrivals accumulate in
pending_groups only, a finalized group moves all its rollouts (errored,
filtered, and survivors) into the window, and batches only ship at
finalization points. Every rollout lands in exactly one batch's window.
2026-07-13 14:07:48 -07:00
Sebastian MüllerandGitHub 4d64d38a60 fix(orchestrator): count token batches by shipped sample payload (#3010)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Token-batched TrainSink accounting used Trace.num_total_tokens, which sums
over all branches — but trace_to_samples skips branches left with no
trainable tokens after fork dedup, so forked traces overcounted vs the
actual trainer payload. Count sum(len(sample.token_ids)) at both accounting
sites (accumulation and batch cut) instead. Linear traces are unchanged.

Zero-payload survivors (no trainable samples) fall back to the trace total
so they still advance the readiness check; a degenerate all-zero-payload
stream then ships empty batches and hits the orchestrator's
consecutive-empty-batch abort rather than stalling batching.
2026-07-13 14:07:10 -07:00
samsjaandGitHub d3fe2a8044 ci: use filesystem weight broadcast for RL integration tests (#3020)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The RL integration tests (reverse_text, alphabet_sort, reverse_text_moe,
reverse_text_rl_opd, reverse_text_rl_sft) currently fail on the GPU CI
runners: the trainer subprocess exits with code 1 right at NCCL weight
broadcast init (orchestrator logs "Initializing NCCL broadcast", then
~5s later "Trainer failed with exit code 1"). SFT-only and unit tests
are unaffected because they don't use the trainer<->inference NCCL
weight-transfer path.

As a temporary workaround to get main CI green, switch these RL configs
to the already-supported `filesystem` weight-broadcast transport (the
same transport reverse_text_multi_run already uses and which passes).
The NCCL path itself will be fixed separately.
2026-07-13 13:09:55 -07:00
df5f991bf4 fix: preserve explicit None config overrides across config write/re-parse (#2981)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Launcher-written TOMLs (slurm rl.toml/subconfigs, sft, inference, and the
orchestrator's control/orch.toml) were dumped with exclude_none=True, so a
field explicitly overridden to None (e.g. --trainer.model.compile None) was
dropped and silently reverted to its non-None default when the file was
re-parsed by the sbatch job.

Add to_toml_dict(), which drops unset None fields as before but encodes
explicitly-set ones as the string "None" — the config system's TOML null
convention, converted back by BaseConfig on load. Serializing all Nones
would instead trip RLConfig's shared-vs-subconfig conflict validator
(shared defaults like log.level=None disagree with sub-config defaults),
hence the model_fields_set distinction.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 11:01:15 -07:00
Florian BrandandGitHub 546fd69709 fix: flush env server exception logs (#3005)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-13 19:28:23 +02:00
321c8aa825 chore: bump research-environments to latest main (#2999)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: drop v0 logic-env and math-env deps

These v0 environments are being removed from research-environments in favor of
their v1 tasksets (logic-env -> i3_logic_v1, math-env -> math-env-v1, the latter
already wired here). Remove the v0 editable path deps + relock so the build
doesn't break when deps/research-environments is re-pinned past their deletion.

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

* chore: migrate standalone math configs off v0 math-env to v1 tasksets

Move the training configs that used the v0 math-env on an explicit dataset to
v1 env sections: gsm8k -> gsm8k-v1 (verifiers), and the Hendrycks/sanity configs
-> math-env-v1 (task-facing math_verify_timeout preserved where set). All use the
`null` harness + subprocess runtime. Drops the v0-only math_verify_max_workers.

qwen30b_math and examples/Intellect-3.1 use the v0 math-env DEFAULT (INTELLECT-3-RL
math), so they migrate to i3_math_v1 instead — deferred to the submodule bump.

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

* chore: bump research-environments to latest main and fix moved env paths

Bump deps/research-environments 504bd2620 -> 54f30788f, which includes the
v0->v1 migration (#653), the environment grouping reorg (#655), frontierscience
v1 (#656), and swebench deprecation (#651). The reorg moved every env into a
category subdir (math/, knowledge/, search/, tool_use/, long_context/, code/,
reasoning/, science/, if/, terminal/), so update all 44 editable path deps in
[tool.uv.sources] accordingly, and relock.

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

* chore: re-bump to research-environments with i3_math_v1; migrate qwen30b_math

Re-bump deps/research-environments 54f30788f -> 06232831f (adds i3_math_v1, #660).
Wire i3-math-v1 (INTELLECT-3-RL math) and i3-logic-v1 (INTELLECT-3-RL logic) as
editable path deps, and migrate examples/qwen30b_math (v0 math-env's INTELLECT-3-RL
default) to the i3_math_v1 v1 taskset. Relock.

examples/Intellect-3.1 is left on v0 for a dedicated recipe pass (it mixes 6 v0
envs — mini-swe-agent-plus/deepdive/math-env/logic-env/code-env/aime2025 — several
without a clean 1:1 v1 mapping); it still validates (v0 sections aren't imported).

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

* chore: migrate remaining config/example env refs to installed v1 envs

Sweep every configs/ + examples/ env reference so all resolve to installed envs
(no Environments-Hub downloads, no removed v0 envs):

- mini-swe-agent-plus -> r2e-gym-v1 (default harness, prime runtime): Intellect-3.1,
  qwen30b_swe, minimax_m2.5_swe, glm5_pd_disag
- Intellect-3.1 recipe fully to v1: deepdive->deepdive-v1 (rlm+search), math-env->
  i3_math_v1, logic-env->i3_logic_v1 (filter max 0.874), code-env->i3_code_v1,
  aime2025->aime25-v1
- aime2025->aime25-v1 (qwen30b_math eval)
- de-Hub primeintellect/*: wordle->wordle, alphabet-sort->alphabet-sort,
  wiki-search->wiki-search, aime2024->aime24-v1 (hendrycks_sanity eval)
- general-agent-solver-rlm -> general-agent-v1 taskset (colocated tools; configs/general_agent/*)

All target envs are already in the `envs` extra (no lock change). All configs parse
under the schema; audit shows 0 unresolved env references.

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

* chore: SWE eval -> swebench-verified-v1; lowercase Intellect-3.1 dir

- Point the SWE *eval* env at swebench-verified-v1 (train stays r2e-gym-v1) in
  Intellect-3.1, qwen30b_swe, minimax_m2.5_swe, glm5_pd_disag.
- Rename examples/Intellect-3.1 -> examples/intellect-3.1 (lowercase) and update
  the docs/configuration.md link.

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

* chore: drop "-quick" from SWE eval name (now full swebench-verified-v1)

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

* chore: runtime labels use the run name, not the env name

Set the prime-runtime sandbox labels to each config's run identifier (its wandb
project) instead of per-env tags like ["deepdive"] / ["mini-swe-agent-plus"].

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

* chore: prime-runtime labels = [run name, env name]

Convention: tag prime sandboxes with both the run identifier (wandb project) and
the env name, e.g. ["intellect-3.1", "swe"] / ["intellect-3.1", "deepdive"].

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

* ci: slim install parses an SFT [slurm] config (RL configs are now v1)

The slim "parse a real config" step parsed examples/Intellect-3.1/rl.toml, which
(a) was renamed to lowercase and (b) is now a v1 recipe — v1 env sections resolve/
import their taskset at parse (vf.EnvServerConfig), and those env packages aren't
installed in the slim (prime-rl-configs-only) env. Point it at an SFT [slurm]
config (no env sections) so it still verifies slurm/template_path handling.

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

* ci: slim install also parses the reverse_text RL config (v0 env, [slurm] compose)

Cover both paths on the slim install: the SFT [slurm] config and the reverse_text
RL recipe (rl.toml @ slurm_rl.toml). The RL one parses because reverse-text is a
v0 env id (resolved lazily, not imported at parse), so no env package is needed.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 14:10:10 -07:00
Anirudh RavichandranandGitHub 84b413fd73 feat(scripts): export verifiers v1 traces.jsonl as an SFT dataset (#2989)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bridge a finished verifiers eval run to 'uv run sft': one row per branch
with a messages column (OpenAI chat wire shape) and a tools column
(Trace.tools, JSON-encoded) — the shape trainer/sft/data.py consumes.
Generation-errored traces always drop (scoring-only errors keep their
finished transcript); --min-reward / --drop-truncated select further.
Writes <run>/sft/train.parquet (data.name-ready) or pushes with --push.

Moved here from PrimeIntellect-ai/verifiers#1964 per review; requires the
verifiers release carrying Trace.tools (verifiers#1963).
2026-07-10 16:21:32 -07:00
Mika SenghaasandGitHub 9e0d242cd0 chore: bump research-environments and verifiers to 0.2.0 (#2995)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-10 14:40:53 -07:00
samsjaandGitHub b127f0375b fix(orchestrator): use atomic writes for checkpoint saves (#2992)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Write checkpoints to a temp file then atomically rename into place, so a
killed process can't leave a corrupt progress.pt that breaks restarts.

Signed-off-by: Sami Jaghouar <sami.jaghouar@gmail.com>
2026-07-10 12:15:53 -07:00
4bbf967a57 feat: adapt to verifiers task-centric Task/TaskData split (#2987)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: adapt to verifiers task-centric Task/TaskData split

Companion to PrimeIntellect-ai/verifiers#1948: Trace is now generic over
TaskData (DataT), the wire task type is WireTaskData, and vf.Task is the
behavior class — placeholder wire tasks construct vf.TaskData. Taskset
knobs that moved onto TaskConfig nest under taskset.task in configs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (from_trace is an opt-in hook)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/research-environments to the task-centric port

All v1 envs in research-environments now speak the task-centric API
(PrimeIntellect-ai/research-environments#650); general_agent's tools
placement knob nests under taskset.task like the other moved knobs.
Full unit suite green against the pinned branch.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: adapt to the nested trace.task carrier

Companion to verifiers recording the producing task class on the trace
(trace.task -> {type, data}): dispatcher placeholders wrap their rows in
vf.TraceTask (type="Task" — no behavior class ever ran), readers nest
(.task.idx -> .task.data.idx), and the wandb sample tables keep showing
the row. Bumps both submodule pins.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (compact harness nested-task fix)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (simplify-API merge + review fixes)

Compat-audited: every surface prime-rl imports is unchanged or already
adapted; unit suite green (544) and 10-step reverse_text/gsm8k debug
runs healthy against the pinned tip.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(configs): glm45air search judges nest under taskset.task

main's new search config predates the task-centric knob move: plugged
judges live at taskset.task.judges and browsecomp's judge endpoint at
taskset.task.judge.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump submodule pins (codex feature-tool disable, sandbox version fix)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (replay recomputes from scratch)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers to main (task-centric tasks merged)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/research-environments (verifiers dev443 floors)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/research-environments (python floor + prerelease test fix)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/research-environments (port changelogs)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/research-environments (swe taskset ports)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/research-environments (stale comment)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/research-environments to main (v1 ports merged) + relock

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 12:11:43 -07:00
samsjaandGitHub cdb1480c66 fix(trainer): reduce filesystem churn in nccl weight broadcast (#2991)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Only the master rank polls the filesystem for NCCL_READY markers; all
other ranks wait on a dist.barrier() instead. This eliminates redundant
filesystem polling across trainer ranks on multi-node setups.

Signed-off-by: Sami Jaghouar <sami.jaghouar@gmail.com>
2026-07-10 12:10:43 -07:00
samsjaandGitHub f34efdbf49 fix(orchestrator): allow final nccl batch through dispatch gate (#2990)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The trainer skips the final NCCL weight broadcast (nccl_broadcast_unused
in train.py: step >= max_steps - 1) because the inference NCCL group is
torn down before that broadcast lands. As a result policy.version never
reaches the final step.

The orchestrator's dispatch gate (update_dispatch_gate) was unaware of
this: it pauses dispatch when lead > TARGET_LAG, waiting for a policy
version the trainer will never publish. Once the rollout buffer can't
cover the last batch on its own, the run deadlocks.

This mirrors the trainer's nccl_broadcast_unused condition in the gate:
when building the final batch under NCCL, let it through regardless of
lead. The last batch is meant to build on the penultimate policy anyway.

Signed-off-by: Sami Jaghouar <sami.jaghouar@gmail.com>
2026-07-10 11:49:35 -07:00
9b47b777aa feat(models): dense Qwen3.5 custom attention (#2984)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Implement dense Qwen3.5 (Qwen3_5ForCausalLM / Qwen3_5Model) on the
PrimeRL attention modules, reusing the Qwen3.5-MoE building blocks
(GatedDeltaNet, gated SDPA/flash attention, RMSNorm, rotary embedding)
so ring/ulysses CP substitution patches the dense and MoE models
consistently:

- New models/qwen3_5 package: decoder layer dispatching on
  layer_types (linear_attention / full_attention), flash varlen
  cu_seqlens from position_ids, identity state-dict conversion
  (dense HF layout matches PrimeRL layout).
- Shared normalize_qwen3_5_attn_implementation on the MoE module
  (eager→sdpa, kernels-community/vllm-flash-attn3→flash_attention_3),
  consumed by both models' attention factories and
  _check_and_adjust_attn_implementation.
- Register Qwen3_5TextConfig / Qwen3_5ForCausalLM in AutoConfig and
  the custom causal-LM mapping; hook dense Qwen3_5GatedFlashAttention
  into substitute_ring_attn / substitute_ulysses_attn.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 18:55:35 -07:00
1877714656 exp: search + terminal ablations (#2915)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* exp: GLM-4.5-Air RL configs for the search + terminal env domains

Two self-contained 2-train + 4-infer-node configs (configs/glm45air_search_terminal/) mirroring
configs/debug/v1/glm45air_scaleswe.toml (glm4_moe router replay, glm-4.5 renderer, cp=8 ulysses,
muon, LM-head chunking, AC/offload), with GRPO + linear length penalty, the rlm harness, and the
prime runtime for every env under a single per-run label:

- search.toml (label glm45air-search): rlm `search` skill; train deepdive-v1 / papersearchqa-v1
  (split=train) / wideseek-v1 (split=hybrid), eval browsecomp-v1 / openseeker-v1 / redsearcher-v1.
- terminal.toml (label glm45air-terminal): rlm ipython; train scaleswe-v1 / r2e-gym-v1, eval
  swebench-verified-v1 (use_prime_registry) / swebench-pro-v1 / terminal-bench-2-v1.

Both validate via RLConfig.model_validate.

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

* exp: correct search/terminal env sets

- search: openseeker-v1 + redsearcher-v1 are train sources (move from eval); deepdive stays train
  (qa_rl; no held-out eval split). Eval is browsecomp-v1.
- terminal: SWE (scaleswe/r2e-gym) is a separate domain — train on the terminal sets instead
  (openthoughts-tblite-v1 = terminal-bench-lite, uuid-ctf-v1 = synthetic forensic CTF). Keep the
  sandbox-benchmark evals (terminal-bench-2-v1 primary; swebench-verified/pro as references).

Both pass RLConfig.model_validate; all env ids are locked in pyproject.

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

* exp: full eval at avg@1 (drop num_examples/group_size caps); terminal evals tb2 only

Eval blocks now use the defaults (num_examples=-1 → all, group_size=1 → avg@1). Terminal evals on
terminal-bench-2-v1 only for now (dropped the swebench-verified/pro cross-domain evals).

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

* exp: bump verifiers to forward_env; forward SERPER_API_KEY on search envs

Bump deps/verifiers 62ba2212 -> 842f6b18 (verifiers main incl. forward_env on
HarnessConfig) and set forward_env = ["SERPER_API_KEY"] on every search harness,
so the rlm search skill gets the key inside the prime sandbox. SERPER_API_KEY must
be exported in the launch environment.

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

* exp: consolidate glm45air configs under configs/glm45air/; 131k ctx, node-local caches

Move search/terminal configs into configs/glm45air/ alongside swe.toml (rebased
from exp/scaleswe-lp). All three: seq_len/max_model_len -> 131072; drop default
inference args (gpu_memory_utilization, enable_prefix_caching) and eval
skip_first_step; node-local caches (/tmp/.{vllm,triton,flashinfer}-cache-$(whoami)).
search/terminal get the linear length penalty at 0.1 on all three terms.

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

* exp: terminal-lego train env + Qwen3-235B judge for search envs

- terminal.toml: train env -> terminal-lego-v1 (drops openthoughts-tblite + uuid-ctf);
  eval stays terminal-bench-2-v1 only.
- research-environments submodule -> feat/terminal-lego-v1-port (adds terminal-lego-v1);
  registered in pyproject envs extra + tool.uv.sources; uv.lock updated.
- search.toml: judge -> Qwen/Qwen3-235B-A22B-Instruct-2507 (temperature 0) on all six
  search envs (judge client already defaults to PI inference).

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

* exp: add papersearchqa held-out test eval, cap large evals at 500, drop default project_dir

- search.toml: add papersearchqa `test` split as an eval env (held-out signal);
  cap browsecomp (1266) and papersearchqa-test (5000) evals at num_examples=500.
- drop `project_dir = "."` from all three configs (it is the SlurmConfig default).

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

* exp: split wandb projects (search-ablations / terminal-ablations); drop stale length-penalty comment

- search.toml -> wandb project "search-ablations"; terminal.toml -> "terminal-ablations".
- remove the stale "GRPO + linear length penalty (... default weights)" comment (weights are 0.1).

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

* exp: static node-local cache dirs (drop $(whoami))

inference.env_vars are passed literally to vLLM (not shell-expanded), so
"$(whoami)" landed verbatim in the FlashInfer ninja build path and broke it
("bad $-escape"), disabling the allreduce-norm fusion. Nodes are exclusive, so
per-user suffixes are unnecessary: use static /tmp/.{vllm,triton,flashinfer}-cache.

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

* exp: search judge uses default sampling (drop temperature=0 override)

Remove sampling={temperature=0} from the Qwen3-235B judge on all search envs;
keep the model override, let the judge use its default sampling.

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

* exp: search+terminal batch_size 256->512, max_inflight 512->768

Raise per-step batch (256->512 groups) and inflight-rollout concurrency
cap (512->768) for both glm45air search and terminal ablations. The
prior 512 cap sat ~42% utilized under the weight-sync barrier, so lift
concurrency and grow the batch to keep inference busier per step.

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

* exp: search v2 run — job/wandb name glm45air-search-v2

Fresh search ablation from step 0 on the pulled branch (vLLM 0.24 +
dispatch-gate fixes) with the new 512 batch / 768 inflight config.

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

* exp: hardcode prime sandbox cleanup label in glm45air configs

Decouple pre_run_command's sandbox-delete label from $SLURM_JOB_NAME and
pin it to each run's harness label. Fixes search.toml, where job_name
(glm45air-search-v2) diverged from the harness label (glm45air-search),
so pre-run cleanup targeted a label no sandbox carried.

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

* exp: search v2 — train openseeker+redsearcher, eval browsecomp, batch 256 / concurrency 512

Trim search train set to openseeker + redsearcher and eval to browsecomp
only. Drop orchestrator batch_size 512->256 and max_inflight_rollouts
768->512 to match the swe runs (was over-driving inference).

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

* exp: search v3 — rlm auto-compaction (train draw 65536-131072 per task, eval fixed 98304)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* exp: terminal train on tmax-v1; eval swebench-verified + terminal-bench-2

- swap terminal train env terminal-lego -> tmax-v1 (TMax Harbor taskset)
- eval both swebench-verified and terminal-bench-2 every 20 steps
- bump research-environments to latest main (adds the tmax-v1 taskset)
- bump verifiers to origin/main (dev422), required by latest research-envs
  (browsecomp-v1 + others now pin verifiers>=0.1.15.dev422)
- register tmax-v1 in pyproject envs + sources; relock

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

* exp: search v3 — migrate judge config to plugged judges list (post vf-bump schema)

openseeker/redsearcher: taskset.judge is gone; declare [[taskset.judges]] reference
entries (reward key 'correct', A/B verdicts, Qwen3-235B judge model). Note the
taskset-plugged BC-style prompt is replaced by the reference judge's stock prompt.
browsecomp keeps its taskset.judge field (still valid on BrowseCompConfig).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* exp: terminal v2 — bump job + wandb name to glm45air-terminal-v2

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* exp: keep base run names in configs — version suffix goes on the launch CLI

(--slurm.job-name / --wandb.name, e.g. glm45air-search-v3)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* exp(glm45air): terminal + search ablation config updates

terminal:
- terminal-bench-2 eval at avg@4 (group_size=4)
- add weight-0 rlm + swe rubric monitors (GLM-5.2 judge) on train + eval envs
- drop length penalty on output tokens (input/turns kept)
- run prime runtime as micro-VM (vm=true)

search:
- add weight-0 rlm rubric monitor (GLM-5.2 judge) on train + eval envs
- drop length penalty on turns + output tokens (input kept)
- run prime runtime as micro-VM (vm=true)

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

* exp(glm45air): trim header comment blocks from search + terminal configs

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

* exp(glm45air): drop tmax taskset inline comment

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

* exp(glm45air): disable idle_timeout on vm prime runtimes

The Prime API rejects idle_timeout_minutes for VM sandboxes (HTTP 422),
and the prime runtime defaults idle_timeout to 1h. A debug eval rollout on
scaleswe-v1 + swebench-verified-v1 (vm=true, use_prime_registry) failed at
provisioning until idle_timeout was cleared. Set idle_timeout = "None" on
every vm=true prime runtime (coerced to None; VM lifetime stays bounded by
timeout_minutes). Re-ran both envs: VM provisions, image pulls from the
prime registry, rollout runs to the 10-turn cap.

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

* exp(glm45air): run swe config on prime micro-VM

Match the terminal/search ablations: run scaleswe train + swebench-verified
eval on vm=true prime runtimes with idle_timeout = "None" (the Prime API
rejects idle_timeout_minutes for VM sandboxes). Also set use_prime_registry
on the scaleswe taskset so its image resolves from the Prime platform
registry (pullable on the VM), matching swebench-verified.

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

* exp(glm45air): comment out rlm/swe rubric monitors (vm-only test)

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

* fix: register tmax-v1 taskset in pyproject

The terminal ablation config references the tmax-v1 taskset, but the
package was never added to the envs extra, so config loading failed
with ModuleNotFoundError.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* exp: align swe/terminal ablation configs with search

- swe: length penalty on input tokens + turns only (drop output-token
  term), matching terminal
- terminal: batch_size 256 / max_inflight_rollouts 512, matching
  swe and search
- swe + terminal: rlm auto-compaction like search — train draws a
  per-task threshold in [65536, 131072], eval compacts at 98304

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 17:26:59 -07:00
samsjaandGitHub 77766bb59c feat: make NCCL the default weight broadcast transport (#2982)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Change the default weight_broadcast type from 'filesystem' to 'nccl' in
RLConfig. When no weight_broadcast is explicitly configured:

- Default to NCCL broadcast (in-memory GPU-to-GPU transfer)
- Fall back to filesystem when LoRA is enabled (not yet supported with NCCL)
- Fall back to filesystem when no inference server is configured

Sub-config defaults (TrainerConfig, OrchestratorConfig, InferenceConfig)
remain filesystem since they are always overridden by RLConfig propagation
in the rl entrypoint, and standalone usage shouldn't default to NCCL.

Pin explicit filesystem broadcast in the multi-run integration test configs
that use standalone entrypoints with LoRA.

Update docs to reflect the new default.
2026-07-09 15:42:53 -07:00
1caebf8a1b feat: save all rollouts, not just the effective ones (#2983)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(deps): bump verifiers to fab50d51

Picks up feat: record runtime info on the trace (verifiers#1959) — every
trace now carries its runtime's full config plus the provisioned resource
id — and the results.jsonl -> traces.jsonl rename (verifiers#1956).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(orchestrator): save all rollouts, not just the batched ones

Rollout traces move from rollouts/step_N/{train,eval}_rollouts*.jsonl to
traces/{train,eval}/{all,effective}/:

- all/traces.jsonl is a flat run-level stream appended the moment each
  rollout completes — errored, filtered, and never-batched rollouts
  included — so it is durable across crashes and drains.
- effective/step_N/traces.jsonl is written on batch finalize as before,
  but now holds only the clean subset that shipped to the trainer (eval:
  the non-errored epoch cohort; multiple eval envs share the step file).

Rollout.to_record() now includes the orchestration metadata (kind,
env_name, group_id, policy_version, eval_step) so records in the flat
all stream can be placed without relying on the file path. Together with
the verifiers bump, each record also carries the runtime info (config +
sandbox id), so sandbox errors can be correlated from the all stream.

The all streams have no per-step layout, so resume can't rewind them;
they are wiped on fresh runs only. The per-step effective files rewind
past the resume step exactly like the rollout dirs.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(orchestrator): nest trace files under per-step directories

traces/{train,eval}/... -> traces/step_N/{train,eval}/{all,effective}/
traces.jsonl. Train arrivals attribute to the batch window currently
collecting (progress.step), eval arrivals to their eval trigger step, so
the all files stay append-per-rollout. Per-step layout also lets resume
rewind traces past the resume step exactly like rollouts and broadcasts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(orchestrator): nest trace files under the rollout dir

traces/step_N/{train,eval}/... -> rollouts/{train,eval}/step_N/
{all,effective}/traces.jsonl. No separate traces/ top-level dir; the
per-kind subtrees coexist with the trainer-bound rollouts/step_N/*.bin
transport files and rewind on resume like the other step directories.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor(orchestrator): order trace files step-first under the rollout dir

rollouts/{train,eval}/step_N/... -> rollouts/step_N/{train,eval}/
{all,effective}/traces.jsonl, next to the step's train_rollouts.bin.
The existing per-step rewind on the rollout dirs covers the traces
again, so clean_future_steps needs no extra entries.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 15:40:51 -07:00
samsjaandGitHub db04385acf fix(examples): update disaggregated configs to use prefill/decode_nodes_per_replica (#2980)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(examples): update disaggregated configs to use prefill/decode_nodes_per_replica

The derive inference node counts PR (#2959) renamed num_prefill_nodes →
prefill_nodes_per_replica and num_decode_nodes → decode_nodes_per_replica
in the config schema, and made deployment.num_infer_nodes auto-derive
from inference.deployment.num_nodes. The configs/ and docs/ were updated
but examples/ was missed.

- glm5_llmd/rl.toml: num_prefill_nodes=8 → prefill_nodes_per_replica=2
  (8 ÷ 4 replicas), num_decode_nodes=8 → decode_nodes_per_replica=8,
  remove num_infer_nodes (auto-derives to 16)
- glm5_pd_disag/rl.toml: num_prefill_nodes=4 → prefill_nodes_per_replica=4,
  num_decode_nodes=4 → decode_nodes_per_replica=4, remove num_infer_nodes
  (auto-derives to 8)

* refactor: remove backward-compat shim for old disaggregated node field names

The normalize_node_counts before-validator silently accepted the old
num_prefill_nodes / num_decode_nodes field names and converted them to
prefill_nodes_per_replica / decode_nodes_per_replica. This made it
impossible for CI to detect stale configs still using the old names —
parsing succeeded silently instead of failing with a validation error.

Now that all in-repo configs and examples have been updated to use the
new field names, remove the shim so old names are rejected as
extra_forbidden by pydantic, turning future regressions into CI failures.
2026-07-09 11:21:46 -07:00
2bc136cf85 refactor: share trace_to_sample with verifiers in the prime monitor (#2974)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* refactor: share trace_to_sample with verifiers in the prime monitor

Replace the monitor's hand-rolled v1-trace -> sample conversion in
`_rollouts_to_parquet_bytes` with `verifiers.v1.samples.trace_to_sample`, the same
canonical converter verifiers' eval `uv run eval --push` uses. Both producers now emit
one identically-shaped sample record; the RFT-only parquet columns (run/step/advantage/
problem_id/env_name) are layered on here. Behavior-preserving: the parquet schema and all
column values are unchanged (verified against the existing monitor unit tests).

Bumps the deps/verifiers submodule to the verifiers PR that adds `trace_to_sample`.

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

* chore: bump deps/verifiers (drop trace_to_sample unit test)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (run-metrics aggregation + main merge)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (inline push run-metrics)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (drop URL from push log)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (platform sample/metric shape fixes)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (compute_metrics docstring)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (per-rollout reward columns)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (crash-safe --push upload)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (drop trajectory reward + reward-name suffixing)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (num_examples in push metadata)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: bump deps/verifiers (trace_to_sample folded into push.py)

samples.py was dropped on the verifiers branch - trace_to_sample now
lives in verifiers.v1.push

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 17:10:42 -07:00
6bfbd64aef chore(deps): bump verifiers + research-environments to latest main (#2976)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bump both submodules to their current upstream main:
- verifiers:              50883f16 -> a497ee52
- research-environments:  404f0fa8 -> 3e3b5ac3

Reconcile pyproject/uv.lock with upstream changes:
- research-environments moved the SWE tasksets under environments/swe/,
  so repath r2e-gym-v1, scaleswe-v1, swebench-pro-v1, swebench-verified-v1
  and swelego-v1 to environments/swe/<name>.
- research-environments removed the v0 general_agent and rlm_search envs
  (#646), so drop general-agent and rlm-search from the `envs` extra and
  [tool.uv.sources]. general-agent-v1 is unaffected.

verifiers is consumed only via the verifiers.v1 namespace; the removed
verifiers.rl / verifiers-rl code and the RolloutContext->ModelContext
rename do not touch prime-rl. Verified `uv sync --extra envs` resolves,
all 64 env dists install, the moved SWE envs import, and prime-rl's
verifiers.v1 imports (incl. EnvConfig(vf.EnvServerConfig)) still work.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 14:39:52 -07:00
Sebastian MüllerandGitHub b453f40d8c fix(orchestrator): train shared sampled nodes exactly once across branches (#2975)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(orchestrator): train shared sampled nodes exactly once across branches

trace_to_samples built one sample per branch using branch.sampled_mask
directly, so a sampled node lying on N branches (a mid-trajectory fork)
was mask-True in N samples and received N x the gradient weight. Grant
each sampled node its mask only in the first branch containing it; later
branches carry its tokens as context (mask False). No behavior change
for traces whose branches share only input nodes.

* fix(orchestrator): keep echo branch/sample zip aligned under fork dedup

Extract the dedup'd branch selection into iter_trainable_branches and use
it in both trace_to_samples and EchoAlgorithm._weight_observations. When
a later branch's only sampled tokens are on an already-trained shared
node, it yields no sample; echo's old any(branch.sampled_mask) filter
would still count it, shifting the zip with rollout.samples on forked
traces.
2026-07-08 19:11:54 +02:00
samsjaandGitHub 1b028ca1d1 bump depsj (#2967)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-07 09:10:48 -07:00
samsjaandGitHub e96bbae2dd feat: derive inference node counts (#2959)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-06 10:03:29 -07:00
samsjaandGitHub df2acf4874 bump vf (#2956)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-03 20:31:12 -07:00
samsjaandGitHub 5ff9abd8b5 bump re (#2955)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-07-03 20:23:40 -07:00
117 changed files with 3615 additions and 1305 deletions
+16 -6
View File
@@ -25,7 +25,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --extra flash-attn --extra envs --locked
run: uv sync --extra flash-attn --all-packages --locked
- name: Run tests
env:
USERNAME_CI: CI_RUNNER
@@ -90,14 +90,24 @@ jobs:
assert find_package_resource("templates") is None, "templates should not be in slim wheel"
print("slim install OK — configs import with no heavy deps loaded")
PY
- name: Verify a real config (with [slurm]) parses on slim install
- name: Verify real configs (with [slurm]) parse on slim install
run: |
/tmp/slim/bin/python - <<'PY'
from pydantic_config import cli
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.rl import RLConfig
rl = cli(RLConfig, args=["@", "examples/Intellect-3.1/rl.toml"])
assert rl.slurm is not None, "expected [slurm] in example config"
# On slim, template_path can't be auto-resolved (heavy wheel absent) — must stay None.
assert rl.slurm.template_path is None, f"unexpected template_path on slim: {rl.slurm.template_path}"
# Configs that don't pull in a v1 env package parse on the slim
# (prime-rl-configs-only) install: the SFT config has no env sections, and the
# reverse_text RL recipe uses a v0 env id (resolved lazily, not imported at parse).
# RL configs on a v1 taskset can't parse here because vf.EnvServerConfig imports the
# (uninstalled) env package at parse time.
for cfg_cls, args in [
(SFTConfig, ["@", "examples/reverse_text/slurm_sft.toml"]),
(RLConfig, ["@", "examples/reverse_text/rl.toml", "@", "examples/reverse_text/slurm_rl.toml"]),
]:
cfg = cli(cfg_cls, args=args)
assert cfg.slurm is not None, f"expected [slurm] in {args}"
# On slim, template_path can't be auto-resolved (heavy wheel absent) — must stay None.
assert cfg.slurm.template_path is None, f"unexpected template_path on slim: {cfg.slurm.template_path}"
print("slim parse OK")
PY
+2 -2
View File
@@ -36,7 +36,7 @@ jobs:
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Install dependencies
run: uv sync --all-extras --locked
run: uv sync --all-extras --all-packages --locked
- name: Run unit tests
env:
USERNAME_CI: CI_RUNNER
@@ -107,7 +107,7 @@ jobs:
- name: Install uv
uses: astral-sh/setup-uv@v5
- name: Install dependencies
run: uv sync --all-extras --locked
run: uv sync --all-extras --all-packages --locked
- name: Run integration tests
env:
USERNAME_CI: CI_RUNNER
+1 -1
View File
@@ -86,7 +86,7 @@ jobs:
enable-cache: true
cache-dependency-glob: "uv.lock"
- name: Install dependencies
run: uv sync --all-extras --locked
run: uv sync --all-extras --all-packages --locked
- name: Run experiment
env:
USERNAME_CI: CI_RUNNER
+1 -1
View File
@@ -111,7 +111,7 @@ RUN --mount=type=cache,target=/app/.cache/uv \
&& \
EXTRA_DISAGG_FLAG=""; if [ "$INCLUDE_DISAGG_EXTRAS" = "1" ]; then EXTRA_DISAGG_FLAG="--extra disagg"; fi \
&& \
uv sync --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra envs --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
uv sync --all-packages --extra flash-attn --extra flash-attn-3 --extra flash-attn-cute --extra gpt-oss --extra modelexpress $EXTRA_DISAGG_FLAG --group mamba-ssm --locked --no-dev
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
+2
View File
@@ -111,6 +111,8 @@ source $HOME/.local/bin/env
uv sync --all-extras
```
> *NOTE*: Environments are opt-in uv workspace members — `uv sync --all-extras` does not install them. To train on them, install all with `uv sync --all-extras --all-packages`, or a subset with `uv sync --package prime-rl --package <env>`.
4.1. On aarch64 hosts: build flash-attn from source for your GPU
> *NOTE*: aarch64 has no prebuilt flash-attn wheel. This step compiles the CUDA extension for your local GPU (~20-30 minutes). Compute capability is auto-detected from `nvidia-smi`; override with `TORCH_CUDA_ARCH_LIST=9.0` (Hopper) / `10.0` (Blackwell) if needed.
@@ -1,6 +1,12 @@
max_steps = 10
seq_len = 2048
[weight_broadcast]
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
# path is fixed. See CI RL integration test failures on main.
type = "filesystem"
[ckpt]
[model]
@@ -1,6 +1,12 @@
max_steps = 20
seq_len = 2048
[weight_broadcast]
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
# path is fixed. See CI RL integration test failures on main.
type = "filesystem"
[ckpt]
resume_step = 15
@@ -1,6 +1,12 @@
max_steps = 15
seq_len = 2048
[weight_broadcast]
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
# path is fixed. See CI RL integration test failures on main.
type = "filesystem"
[ckpt]
[model]
@@ -1,6 +1,12 @@
max_steps = 20
seq_len = 2048
[weight_broadcast]
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
# path is fixed. See CI RL integration test failures on main.
type = "filesystem"
[ckpt]
[model]
@@ -8,3 +8,6 @@ gpu_memory_utilization = 0.7
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
max_model_len = 2048
[weight_broadcast]
type = "filesystem"
@@ -21,6 +21,9 @@ id = "reverse-text"
interval = 10
resume_step = -1
[weight_broadcast]
type = "filesystem"
# Model not in MODEL_RENDERER_MAP — opt into DefaultRenderer (apply_chat_template).
[renderer]
name = "default"
@@ -16,3 +16,6 @@ freq = 1
[model.compile]
fullgraph = false
[weight_broadcast]
type = "filesystem"
@@ -7,6 +7,12 @@
max_steps = 15
seq_len = 2048
[weight_broadcast]
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
# path is fixed. See CI RL integration test failures on main.
type = "filesystem"
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -7,6 +7,12 @@
max_steps = 15
seq_len = 2048
[weight_broadcast]
# TEMP: NCCL weight broadcast currently crashes the trainer on CI GPU runners
# (trainer exits during NCCL init). Use filesystem transport until the NCCL
# path is fixed. See CI RL integration test failures on main.
type = "filesystem"
[model]
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
@@ -22,7 +22,7 @@ max_completion_tokens = 64
[[orchestrator.train.env]]
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer]
+2 -2
View File
@@ -14,9 +14,9 @@ max_inflight_rollouts = 512
group_size = 8
[[orchestrator.train.env]]
id = "math-env"
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 50
+1 -1
View File
@@ -41,7 +41,7 @@ max_completion_tokens = 64
[[orchestrator.train.env]]
name = "color-codeword"
taskset = { id = "color-codeword-v1", images_per_turn = 1, num_examples = 1000 }
taskset = { id = "color-codeword-v1", images_per_turn = 1 }
harness = { id = "null", runtime = { type = "subprocess" } }
# Default renderer (AutoRendererConfig) resolves Qwen3-VL-4B-Instruct from
+1 -1
View File
@@ -36,7 +36,7 @@ max_completion_tokens = 768
[[orchestrator.train.env]]
name = "alphabet-sort"
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, power_per_turn = false }
taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference] # Default inference config
+1 -1
View File
@@ -41,7 +41,7 @@ name = "qwen3"
[[orchestrator.train.env]]
# v1 general-agent solver taskset; the tool server is colocated in the harness's modal sandbox.
taskset = { id = "general-agent-v1", tools = { colocated = true } }
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
harness = { id = "null", runtime = { type = "modal" } }
[inference]
+2 -1
View File
@@ -16,7 +16,8 @@ rollouts_per_example = 4
max_completion_tokens = 4096
[[orchestrator.train.env]]
id = "general-agent-solver-rlm"
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
harness = { id = "null", runtime = { type = "modal" } }
[trainer]
+2 -1
View File
@@ -36,7 +36,8 @@ rollouts_per_example = 16
max_off_policy_steps = 32
[[orchestrator.train.env]]
id = "general-agent-solver-rlm"
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
harness = { id = "null", runtime = { type = "modal" } }
[orchestrator.train.env.args]
min_tier = 1
+2 -1
View File
@@ -32,7 +32,8 @@ rollouts_per_example = 8
max_off_policy_steps = 32
[[orchestrator.train.env]]
id = "general-agent-solver-rlm"
taskset = { id = "general-agent-v1", task = { tools = { colocated = true } } }
harness = { id = "null", runtime = { type = "modal" } }
[inference]
gpu_memory_utilization = 0.85
+177
View File
@@ -0,0 +1,177 @@
# exp: GLM-4.5-Air (100B MoE) RL across our v1 SEARCH-domain envs — bring-your-own-search QA, run
# through the rlm harness (its built-in `search` skill) on a prime sandbox. GRPO + linear length
# penalty. 2 train + 4 infer nodes. Single run label (glm45air-search) for all envs.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-search"
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-search" -y || true'
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
project = "search-ablations"
name = "glm45air-search"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[model]
name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 8
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
type = "muon"
# --- Orchestrator ---
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[orchestrator.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.0
[orchestrator.prime_monitor]
# --- Train: the search envs with usable training data (rlm `search` skill, prime sandbox) ---
# openseeker/redsearcher pre-plug a `reference` judge; declaring `judges` here replaces that
# entry wholesale (keep `name`/`question_field`/`choices` in sync with the taskset defaults —
# the plugged BC-style prompt is replaced by the reference judge's stock prompt).
[[orchestrator.train.env]]
name = "openseeker"
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[orchestrator.train.env.taskset]
id = "openseeker-v1"
[[orchestrator.train.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.train.env]]
name = "redsearcher"
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
[orchestrator.train.env.taskset]
id = "redsearcher-v1" # optional `difficulty` filter (easy/medium/hard)
[[orchestrator.train.env.taskset.task.judges]]
id = "reference"
name = "correct"
model = "Qwen/Qwen3-235B-A22B-Instruct-2507"
question_field = "question"
choices = ["A", "B"]
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.train.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# --- Eval: BrowseComp held-out test, every 20 steps (incl. step 0) ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
name = "browsecomp"
num_examples = 500 # full set is 1266; cap eval at 500
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-search"] } }
timeout = { rollout = 3600 }
[orchestrator.eval.env.taskset]
id = "browsecomp-v1"
task = { judge = { model = "Qwen/Qwen3-235B-A22B-Instruct-2507" } }
# # Metric-only monitor (weight 0): rlm harness-mechanics rubric, judged by GLM-5.2.
# [[orchestrator.eval.env.taskset.task.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
max_model_len = 131072
[inference.parallel]
tp = 8
+15 -19
View File
@@ -3,9 +3,9 @@
# the routed-expert decisions returned by inference via enable_return_routed_experts) — GLM-4.5-Air is
# a glm4_moe model, which supports routed_experts.
#
# GRPO uses the linear length penalty with the output-token, input-token, and turns coefficients all
# set to 0.1. Each term is pass_rate-scaled and normalized by the group's own max before the GRPO
# baseline subtraction.
# GRPO uses the linear length penalty with the input-token and turns coefficients set to 0.1. Each
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
# subtraction.
#
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
@@ -14,19 +14,18 @@
# configs/debug/v1/scaleswe.toml + GLM-4.5-Air model settings from the int5 opencode configs.
max_steps = 1000
seq_len = 65536
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid
# slow/contended shared-FS caches and FS lock deadlocks.
[env_vars]
TRITON_CACHE_DIR = "/tmp/triton-cache-$USER-$SLURM_JOB_ID"
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-swe"
project_dir = "."
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (label == SLURM job name).
pre_run_command = 'timeout 120 prime sandbox delete --label "$SLURM_JOB_NAME" -y || true'
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-swe" -y || true'
[deployment]
type = "multi_node"
@@ -89,9 +88,9 @@ max_inflight_rollouts = 512
[orchestrator.algo]
type = "grpo"
# Linear length penalty at coef 0.1 on all three terms (output tokens, input tokens, turns).
[orchestrator.algo.length_penalty]
num_output_tokens_weight = 0.1
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
@@ -101,8 +100,8 @@ thinking_retention = "all"
[[orchestrator.train.env]]
name = "scaleswe"
taskset = { id = "scaleswe-v1" }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
taskset = { id = "scaleswe-v1", use_prime_registry = true }
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
[orchestrator.prime_monitor]
@@ -110,28 +109,25 @@ harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] }
[orchestrator.eval]
interval = 20
skip_first_step = false
[[orchestrator.eval.env]]
name = "swebench-verified"
taskset = { id = "swebench-verified-v1", use_prime_registry = true }
harness = { id = "rlm", runtime = { type = "prime", labels = ["glm45air-swe"] } }
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-swe"] } }
timeout = { rollout = 3600 }
# --- Inference ---
[inference]
gpu_memory_utilization = 0.85
enable_prefix_caching = true
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp (see [env_vars]).
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm_cache_$(whoami)"
FLASHINFER_WORKSPACE_BASE = "/tmp/flashinfer-$(whoami)"
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
max_model_len = 65536
max_model_len = 131072
[inference.parallel]
tp = 8
+181
View File
@@ -0,0 +1,181 @@
# exp: GLM-4.5-Air (100B MoE) RL across our v1 TERMINAL-domain envs — agentic shell/sandbox tasks
# run through the rlm harness (ipython-only) on a prime sandbox. Each task ships its own Docker image
# (NEEDS_CONTAINER) injected into the sandbox; grading is host-side inside the container. GRPO +
# linear length penalty. 2 train + 4 infer nodes. Single run label (glm45air-terminal) for all envs.
max_steps = 1000
seq_len = 131072
# Redirect compile/JIT caches to node-local /tmp (per user + job) to avoid contended shared-FS caches.
[env_vars]
TRITON_CACHE_DIR = "/tmp/.triton-cache"
[slurm]
job_name = "glm45air-terminal"
partition = "all"
# Clean up this run's orphaned prime sandboxes before launch (hardcoded label, matches the harness labels below).
pre_run_command = 'timeout 120 prime sandbox delete --label "glm45air-terminal" -y || true'
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
num_infer_replicas = 4
[wandb]
project = "terminal-ablations"
name = "glm45air-terminal"
[weight_broadcast]
type = "nccl"
timeout = 3600
[ckpt]
interval = 50
keep_last = 1
resume_step = -1
[model]
name = "zai-org/GLM-4.5-Air"
# --- Trainer ---
[trainer]
dist_timeout_seconds = 3600
enable_router_replay = true
[trainer.model]
impl = "custom"
attn = "flash_attention_3"
cp = 8
cp_style = "ulysses"
fused_lm_head_token_chunk_size = 1024
optim_cpu_offload = true
[trainer.model.ac]
[trainer.model.ac_offloading]
max_inflight_activations = 1
[trainer.model.compile]
[trainer.ckpt]
skip_gather_master_weights = true
skip_optimizer = true
[trainer.optim]
type = "muon"
# --- Orchestrator ---
[orchestrator]
batch_size = 256
group_size = 16
max_off_policy_steps = 32
max_inflight_rollouts = 512
[orchestrator.renderer]
name = "glm-4.5"
thinking_retention = "all"
[orchestrator.algo]
type = "grpo"
[orchestrator.algo.length_penalty]
type = "linear"
num_output_tokens_weight = 0.0
num_input_tokens_weight = 0.1
num_turns_weight = 0.1
[orchestrator.prime_monitor]
# --- Train: tmax (per-task Docker image in a prime sandbox, rlm ipython) ---
[[orchestrator.train.env]]
name = "tmax"
harness = { id = "rlm", summarize_at_tokens = [65536, 131072], runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
[orchestrator.train.env.taskset]
id = "tmax-v1"
# # Metric-only monitors (weight 0): rlm harness-mechanics + swe code-usage rubrics, judged by GLM-5.2.
# [[orchestrator.train.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.train.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# --- Eval: swebench-verified (avg@1) + terminal-bench-2 (full, avg@4) every 20 steps, incl. step 0 ---
[orchestrator.eval]
interval = 20
[[orchestrator.eval.env]]
name = "swebench-verified"
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
timeout = { rollout = 3600 }
[orchestrator.eval.env.taskset]
id = "swebench-verified-v1"
use_prime_registry = true
# [[orchestrator.eval.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
[[orchestrator.eval.env]]
name = "terminal-bench-2"
group_size = 4 # avg@4
harness = { id = "rlm", summarize_at_tokens = 98304, runtime = { type = "prime", vm = true, idle_timeout = "None", labels = ["glm45air-terminal"] } }
timeout = { rollout = 3600 }
[orchestrator.eval.env.taskset]
id = "terminal-bench-2-v1"
# [[orchestrator.eval.env.taskset.judges]]
# id = "rubric"
# name = "rlm"
# path = "deps/research-environments/rubrics/rlm.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# [[orchestrator.eval.env.taskset.judges]]
# id = "rubric"
# name = "swe"
# path = "deps/research-environments/rubrics/swe.toml"
# model = "zai-org/GLM-5.2"
# weight = 0.0
# --- Inference ---
[inference]
enable_return_routed_experts = true
# vLLM + FlashInfer caches on node-local /tmp.
[inference.env_vars]
VLLM_CACHE_ROOT = "/tmp/.vllm-cache"
FLASHINFER_WORKSPACE_BASE = "/tmp/.flashinfer-cache"
[inference.model]
max_model_len = 131072
[inference.parallel]
tp = 8
+2 -2
View File
@@ -31,9 +31,9 @@ num_bytes = 1_000_000_000_000
[deployment]
type = "disaggregated"
num_prefill_nodes = 8
prefill_nodes_per_replica = 2
num_prefill_replicas = 4
num_decode_nodes = 8
decode_nodes_per_replica = 8
num_decode_replicas = 1
prefill_env_vars = {"VLLM_ENABLE_MOE_DP_CHUNK"="0", "VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
decode_env_vars = {"VLLM_DEEP_GEMM_WARMUP"="skip", "UCX_RCACHE_MAX_UNRELEASED"="1024"}
+2 -2
View File
@@ -10,8 +10,8 @@ reasoning_parser = "glm45"
[deployment]
type = "disaggregated"
num_prefill_nodes = 4
num_decode_nodes = 2
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 2
gpus_per_node = 8
[slurm]
+2 -2
View File
@@ -16,9 +16,9 @@ group_size = 16
max_completion_tokens = 2048
[[orchestrator.train.env]]
id = "math-env"
name = "gsm8k"
args = { dataset_name = "openai/gsm8k", dataset_subset = "main", math_verify_max_workers = 128, math_verify_timeout = 60 }
taskset = { id = "gsm8k-v1", split = "train" }
harness = { id = "null", runtime = { type = "subprocess" } }
[trainer] # Default trainer config
+2 -2
View File
@@ -16,9 +16,9 @@ group_size = 16
max_completion_tokens = 2048
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 10
+3 -3
View File
@@ -5,7 +5,7 @@ seq_len = 2048
[slurm]
job_name = "nemotron-4node"
pre_run_command = "uv sync --all-extras --group mamba-ssm"
pre_run_command = "uv sync --all-extras --all-packages --group mamba-ssm"
[deployment]
type = "multi_node"
@@ -51,9 +51,9 @@ group_size = 8
max_completion_tokens = 2048
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 10
+2 -2
View File
@@ -50,9 +50,9 @@ group_size = 16
max_completion_tokens = 4096
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 10
+1 -1
View File
@@ -23,7 +23,7 @@ batch_size = 128
group_size = 8
[[orchestrator.train.env]]
id = "primeintellect/wordle"
id = "wordle"
name = "wordle"
[orchestrator.train.sampling]
+1 -1
+1 -1
View File
@@ -106,7 +106,7 @@ dropout = 0.0
`target_modules` defaults to a reasonable cross-family set (`q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`, `experts`, plus a few latent-projection names for Nemotron). Unknown names are silently ignored, so the defaults work across architectures. Add architecture-specific names to extend coverage (e.g. `in_proj` / `out_proj` for Mamba).
LoRA is supported across SFT and RL. For RL, `weight_broadcast.type = "nccl"` is **not** supported with LoRA — use the default filesystem transport. To save the raw adapter alongside the merged HF weights:
LoRA is supported across SFT and RL. For RL, NCCL weight broadcast is **not** supported with LoRA — the default NCCL transport automatically falls back to filesystem when LoRA is enabled. To save the raw adapter alongside the merged HF weights:
```toml
[ckpt.weights]
+1 -1
View File
@@ -218,7 +218,7 @@ The shipped end-to-end examples in [`examples/`](https://github.com/PrimeIntelle
- [**Qwen 3 30B – A3B Math**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_math) — `Qwen3-30B-A3B` on hard math.
- [**Qwen 3 30B – A3B SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/qwen30b_swe) — `Qwen3-30B-A3B` on hard SWE.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/Intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**INTELLECT-3.1**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/intellect-3.1) — reproduces our INTELLECT-3.1 training run.
- [**MiniMax-M2.5 SWE**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/minimax_m2.5_swe) — `MiniMax-M2.5` on agentic SWE.
- [**High-throughput GLM-5**](https://github.com/PrimeIntellect-ai/prime-rl/tree/main/examples/glm5_pd_disag) — `GLM-5` with P/D disaggregation and FP8 inference.
+9 -11
View File
@@ -128,41 +128,39 @@ This configuration will run 2 vLLM processes, each with `data_parallel_size_loca
This is the most advanced deployment shape. It allows you to disaggregate the prefill and decode stages, with KV cache flowing between them. This is useful for large scale deployments, where there are high requirements on latency, such as agentic workflows spanning 100s of turns.
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and `inference.deployment.num_prefill_nodes` and `inference.deployment.num_decode_nodes` to the number of nodes you want to run the prefill and decode stages on.
This deployment shape is defined by setting `inference.deployment.type = "disaggregated"` and choosing how many nodes each prefill and decode replica spans.
```toml
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 2
num_decode_nodes = 2
prefill_nodes_per_replica = 2
decode_nodes_per_replica = 2
```
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode node groups. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of replicas you want to run.
Sometimes, you may want to run multiple independent vLLM instances within the prefill and decode stages. You can do this by setting `inference.deployment.num_prefill_replicas` and `inference.deployment.num_decode_replicas` to the number of role replicas you want to run.
```toml
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 2
num_decode_nodes = 2
prefill_nodes_per_replica = 2
num_prefill_replicas = 2
decode_nodes_per_replica = 2
num_decode_replicas = 1
```
Now the total deployment will span 6 nodes - 2x2 for prefill and 1x2 for decode. 2 prefill replicas will run on 2 nodes each - total of 4 nodes for prefill. 1 decode replica will run on 2 nodes for decode.
Now each prefill replica spans 2 nodes and each decode replica spans 2 nodes. With 2 prefill replicas and 1 decode replica, one inference island spans 6 nodes.
We also allow you to configure the total amount of inference replicas - this is useful if you'd like to multiply the above configuration by a factor of `k`, each running behind a separate `vllm-router` instance.
For RL runs, the top-level deployment can multiply that whole inference island by setting `deployment.num_infer_replicas`. `deployment.num_infer_nodes` is inferred from the nested inference deployment when you omit it.
```toml
[deployment] # this is a top-level RL deployment, not inference.deployment!!
type = "multi_node"
num_train_nodes = 4
num_infer_nodes = 6 # this is per-replica
num_infer_replicas = 3
```
This will run 3 inference replicas, each running on 6 nodes. Each replica will run on 2x2 nodes for prefill and 1x2 nodes for decode. The total deployment will span 18 nodes. This will also spin-up 3 separate `vllm-router` instances.
This will run 3 inference islands, each running on 6 nodes. The total inference deployment will span 18 nodes and start 3 separate router instances.
## Router
+1 -1
View File
@@ -12,7 +12,7 @@ A `prime-rl` RL run is three cooperating processes:
- **Orchestrator** — Lightweight CPU process that owns the data plane across many [`verifiers`](https://github.com/PrimeIntellect-ai/verifiers) training and eval environments. Each env runs in an isolated subprocess with a variable-size pool of env workers for scalability. The orchestrator drives multi-turn rollouts against the inference fleet (tool use, browsers, sandboxes, long horizons) without re-tokenizing across turns, computes advantages, packs the rollouts into training batches, and relays new weights from trainer to inference.
- **Trainer** — FSDP2 process group that consumes packed rollouts and steps the optimizer. We ship optimized custom modeling code for many MoE / dense / VLM families that unlocks advanced trainer parallelism — expert parallelism (EP, with DeepEP kernels) and context parallelism (CP) for long-sequence training — plus selective activation checkpointing, FP8 training on Hopper+, LoRA, and multi-tenant training (many concurrent LoRA tenants sharing one trainer + inference deployment). You can read more in the dedicated [training documentation](training.md).
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses the filesystem (or NCCL for synchronous setups). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
The three processes communicate through configurable transports — by default the trainer↔orchestrator rollout link uses the local filesystem, and weight broadcast uses NCCL for synchronous in-memory transfer (falling back to filesystem when LoRA is enabled or no inference server is configured). Swap to ZMQ for multi-host setups without shared storage. See [Scaling](scaling.md) for the deployment options.
## Installation
+2 -2
View File
@@ -179,7 +179,7 @@ The defaults already cover: fused LM head chunking (`1024`), `torch.compile` (fu
The `rl`, `sft`, and `inference` entrypoints all submit to SLURM when a `[slurm]` table is present — there's no separate entrypoint.
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
> **The prime-rl checkout and its `uv` venv must live on a shared filesystem** visible to every node. The generated sbatch script runs a single `uv sync --all-extras --all-packages` on the batch node (not once per node), so all ranks share that one environment — a node-local venv would leave the other nodes stale.
### Activation
@@ -208,7 +208,7 @@ uv run rl @ base_rl.toml @ my_slurm.toml --dry-run # writes the sbatch script
[deployment]
type = "multi_node"
num_train_nodes = 2
num_infer_nodes = 1
num_infer_nodes = 1 # optional when inference.deployment defines the node topology
gpus_per_node = 8 # default
nodes_per_fsdp_group = 1 # optional — controls FSDP island size
```
+1 -1
View File
@@ -32,7 +32,7 @@ group_size = 8
max_completion_tokens = 768
[[orchestrator.train.env]]
id = "primeintellect/alphabet-sort"
id = "alphabet-sort"
name = "alphabet-sort"
args = { min_turns = 3, max_turns = 5, power_per_turn = false }
+1 -1
View File
@@ -13,7 +13,7 @@ You also need prime-rl cloned on your cluster into the shared filesystem.
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
### Install llm-d
+2 -3
View File
@@ -19,15 +19,14 @@ quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
num_infer_nodes = 16
gpus_per_node = 8
num_infer_replicas = 1
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 8
prefill_nodes_per_replica = 2
num_prefill_replicas = 4
num_decode_nodes = 8
decode_nodes_per_replica = 8
num_decode_replicas = 1
# skip warmup for faster start in cost of some jit overhead early
# ucx needs to be set else random segfaults, vllm can't autoset before importing for some reason
+1 -1
View File
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
+5 -6
View File
@@ -15,14 +15,13 @@ quantize_in_weight_transfer = true
[deployment]
type = "multi_node"
num_train_nodes = 16
num_infer_nodes = 8
gpus_per_node = 8
num_infer_replicas = 2
[inference.deployment]
type = "disaggregated"
num_prefill_nodes = 4
num_decode_nodes = 4
prefill_nodes_per_replica = 4
decode_nodes_per_replica = 4
[slurm]
job_name = "glm5-pd-disag"
@@ -73,9 +72,9 @@ name = "zai-org/GLM-5-FP8"
interval = 20
[[orchestrator.eval.env]]
id = "mini-swe-agent-plus"
name = "swe-bench-verified-quick"
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
name = "swe-bench-verified"
taskset = { id = "swebench-verified-v1" }
harness = { id = "default", runtime = { type = "prime", labels = ["glm5-pd-disag", "swe-bench-verified"] } }
[[orchestrator.post_batch_filters]]
type = "gibberish"
+4 -3
View File
@@ -17,16 +17,17 @@ group_size = 8
seq_len = 8192
[[orchestrator.train.env]]
id = "math-env" # included in lock file
args = { dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
name = "hendrycks-math"
taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 50
[[orchestrator.eval.env]]
id = "primeintellect/aime2024"
name = "aime2024"
taskset = { id = "aime24-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
group_size = 32
[trainer.model]
@@ -15,7 +15,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
@@ -48,34 +48,34 @@ batch_size = 2048
oversampling_factor = 2
[[orchestrator.train.env]]
id = "mini-swe-agent-plus"
name = "swe"
ratio = 0.3
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
taskset = { id = "r2e-gym-v1" }
harness = { id = "default", runtime = { type = "prime", labels = ["intellect-3.1", "swe"] } }
[[orchestrator.train.env]]
id = "deepdive"
name = "deepdive"
ratio = 0.2
args = { finish_with_tool = true, open_max_workers = 128, cache_dir = "/tmp/i3_deepdive_cache_train" }
taskset = { id = "deepdive-v1" }
harness = { id = "rlm", skills = ["search"], forward_env = ["SERPER_API_KEY"], runtime = { type = "prime", labels = ["intellect-3.1", "deepdive"] } }
[[orchestrator.train.env]]
id = "math-env"
name = "math"
ratio = 0.3
args = { min_avg_reward = 0.0, max_avg_reward = 0.874}
taskset = { id = "i3_math_v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
id = "logic-env"
name = "logic"
ratio = 0.2
args = { min_avg_reward = 0.0, max_avg_reward = 0.874 }
taskset = { id = "i3_logic_v1", filter = { max = 0.874 } }
harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.train.env]]
id = "code-env"
name = "code"
ratio = 0.2
args = { pool_size = 512 }
taskset = { id = "i3_code_v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[[orchestrator.pre_batch_filters]]
type = "zero_advantage"
@@ -85,12 +85,14 @@ enforce = true
interval = 25
[[orchestrator.eval.env]]
id = "mini-swe-agent-plus"
name = "swe-bench-verified-quick"
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
name = "swe-bench-verified"
taskset = { id = "swebench-verified-v1" }
harness = { id = "default", runtime = { type = "prime", labels = ["intellect-3.1", "swe-bench-verified"] } }
[[orchestrator.eval.env]]
id = "aime2025"
name = "aime2025"
taskset = { id = "aime25-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference.parallel]
tp = 8
+1 -1
View File
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
+5 -5
View File
@@ -50,17 +50,17 @@ max_off_policy_steps = 16
[[orchestrator.train.env]]
id = "mini-swe-agent-plus"
name = "swe"
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
taskset = { id = "r2e-gym-v1" }
harness = { id = "default", runtime = { type = "prime", labels = ["minimax-swe", "swe"] } }
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
id = "mini-swe-agent-plus"
name = "swe-bench-verified-quick"
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
name = "swe-bench-verified"
taskset = { id = "swebench-verified-v1" }
harness = { id = "default", runtime = { type = "prime", labels = ["minimax-swe", "swe-bench-verified"] } }
[inference.parallel]
tp = 8
+2 -2
View File
@@ -42,9 +42,9 @@ group_size = 16
max_completion_tokens = 2048
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", math_verify_max_workers = 128, math_verify_timeout = 60 }
taskset = { id = "math-env-v1", dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default", task = { math_verify_timeout = 60 } }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference.parallel]
tp = 4
+1 -1
View File
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
+5 -2
View File
@@ -49,14 +49,17 @@ max_off_policy_steps = 8
max_completion_tokens = 32768
[[orchestrator.train.env]]
id = "math-env"
name = "math"
taskset = { id = "i3_math_v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
id = "aime2025"
name = "aime2025"
taskset = { id = "aime25-v1" }
harness = { id = "null", runtime = { type = "subprocess" } }
[inference.parallel]
tp = 8
+1 -1
View File
@@ -11,7 +11,7 @@ You also need to have prime-rl cloned on your cluster into the shared filesystem
```bash
git clone https://github.com/PrimeIntellect-ai/prime-rl.git /shared/prime-rl
cd /shared/prime-rl
uv sync --all-extras
uv sync --all-extras --all-packages
```
You might also want to create a `.env` file inside the prime-rl directory to store environment variables used during training like W&B and Hugging Face tokens. The `.env` file is automatically sourced during training.
+5 -5
View File
@@ -47,17 +47,17 @@ oversampling_factor = 2
max_off_policy_steps = 16
[[orchestrator.train.env]]
id = "mini-swe-agent-plus"
name = "swe"
args = { max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
taskset = { id = "r2e-gym-v1" }
harness = { id = "default", runtime = { type = "prime", labels = ["qwen30b-swe", "swe"] } }
[orchestrator.eval]
interval = 25
[[orchestrator.eval.env]]
id = "mini-swe-agent-plus"
name = "swe-bench-verified-quick"
args = { dataset_name="PrimeIntellect/SWE-Bench-Verified-Quick", max_turns = 200, cpu_cores = 2, memory_gb = 4, disk_size_gb = 4, labels = ["mini-swe-agent-plus"], total_timeout_minutes = 720, sandbox_client_max_workers = 256, max_command_timeouts = 3, sandbox_command_timeout = 30}
name = "swe-bench-verified"
taskset = { id = "swebench-verified-v1" }
harness = { id = "default", runtime = { type = "prime", labels = ["qwen30b-swe", "swe-bench-verified"] } }
[inference.parallel]
tp = 8
+1 -1
View File
@@ -45,7 +45,7 @@ type = "zero_advantage"
enforce = true
[[orchestrator.train.env]]
id = "primeintellect/wiki-search"
id = "wiki-search"
[ckpt] # Checkpoint at the end of training
+1 -1
View File
@@ -19,7 +19,7 @@ batch_size = 1024
group_size = 16
[[orchestrator.train.env]]
id = "primeintellect/wordle"
id = "wordle"
name = "wordle"
[orchestrator.train.sampling]
+1 -1
View File
@@ -10,7 +10,7 @@ dependencies = [
"renderers>=0.1.8.dev28",
"tomli>=2.2.1",
"tomli-w>=1.2.0",
"verifiers>=0.1.15.dev390",
"verifiers>=0.2.0",
]
[build-system]
@@ -274,25 +274,22 @@ class MultiNodeInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
# 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).
# prefill and decode node groups. Requires NIXL for KV transfer and a router for
# request routing.
class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
type: Literal["disaggregated"] = "disaggregated"
num_prefill_nodes: int = Field(1, ge=1)
"""Total prefill nodes."""
prefill_nodes_per_replica: int = Field(1, ge=1)
"""Nodes in each prefill vLLM instance."""
num_decode_nodes: int = Field(1, ge=1)
"""Total decode nodes."""
decode_nodes_per_replica: int = Field(1, ge=1)
"""Nodes in each decode vLLM instance."""
num_prefill_replicas: int = Field(1, ge=1)
"""Independent prefill vLLM instances. Must evenly divide ``num_prefill_nodes``."""
"""Independent prefill vLLM instances."""
num_decode_replicas: int = Field(1, ge=1)
"""Independent decode vLLM instances. Must evenly divide ``num_decode_nodes``."""
"""Independent decode vLLM instances."""
prefill_port: int = 8100
"""Port for prefill vLLM instances."""
@@ -312,24 +309,18 @@ class DisaggregatedInferenceDeploymentConfig(BaseInferenceDeploymentConfig):
decode_vllm_overrides: dict[str, Any] = {}
"""Extra vLLM config options merged into --vllm-extra only for decode ranks (SLURM only)."""
@property
def num_prefill_nodes(self) -> int:
return self.prefill_nodes_per_replica * self.num_prefill_replicas
@property
def num_decode_nodes(self) -> int:
return self.decode_nodes_per_replica * self.num_decode_replicas
@property
def num_nodes(self) -> int:
return self.num_prefill_nodes + self.num_decode_nodes
@model_validator(mode="after")
def validate_replicas_divide_nodes(self):
if self.num_prefill_nodes % self.num_prefill_replicas != 0:
raise ValueError(
f"num_prefill_replicas ({self.num_prefill_replicas}) must evenly divide "
f"num_prefill_nodes ({self.num_prefill_nodes})"
)
if self.num_decode_nodes % self.num_decode_replicas != 0:
raise ValueError(
f"num_decode_replicas ({self.num_decode_replicas}) must evenly divide "
f"num_decode_nodes ({self.num_decode_nodes})"
)
return self
InferenceDeploymentConfig: TypeAlias = Annotated[
SingleNodeInferenceDeploymentConfig | MultiNodeInferenceDeploymentConfig | DisaggregatedInferenceDeploymentConfig,
@@ -111,7 +111,7 @@ class SharedModelConfig(BaseConfig):
class SharedWeightBroadcastConfig(BaseConfig):
type: Literal["nccl", "filesystem"] = "filesystem"
type: Literal["nccl", "filesystem"] = "nccl"
"""Weight broadcast transport."""
port: int = 29501
@@ -155,8 +155,8 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
num_train_nodes: int
"""Training nodes."""
num_infer_nodes: int = Field(ge=0)
"""Inference nodes per replica. Set to 0 to skip inference and orchestrator (requires fake data)."""
num_infer_nodes: int | None = Field(None, ge=0)
"""Inference nodes per replica. If unset, inferred from ``inference.deployment``. 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``."""
@@ -167,9 +167,13 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
orchestrator_on_inference: bool = False
"""Run the orchestrator on the last inference node instead of trainer rank 0 (frees host RAM on the trainer node)."""
@property
def infer_nodes_per_replica(self) -> int:
return self.num_infer_nodes or 0
@property
def total_infer_nodes(self) -> int:
return self.num_infer_nodes * self.num_infer_replicas
return self.infer_nodes_per_replica * self.num_infer_replicas
DeploymentConfig: TypeAlias = Annotated[
@@ -232,19 +236,47 @@ class RLConfig(BaseConfig):
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="after")
def auto_setup_infer_nodes(self):
if self.deployment.type != "multi_node":
return self
if self.inference is None:
inferred_nodes = 0
elif self.inference.deployment.type == "multi_node":
inferred_nodes = self.inference.deployment.num_nodes
elif self.inference.deployment.type == "disaggregated":
inferred_nodes = self.inference.deployment.num_nodes
else:
inferred_nodes = 1
if self.deployment.num_infer_nodes is None:
self.deployment.num_infer_nodes = inferred_nodes
elif (
self.inference is not None
and self.inference.deployment.type == "multi_node"
and self.deployment.num_infer_nodes != inferred_nodes
):
raise ValueError(
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
f"inference.deployment.num_nodes ({inferred_nodes}) for multi-node inference."
)
return self
@model_validator(mode="after")
def validate_deployment(self):
if self.deployment.type == "multi_node":
if self.slurm is None:
raise ValueError("Must use SLURM for multi-node deployment.")
if self.deployment.num_infer_nodes > 0 and not self.inference:
num_infer_nodes = self.deployment.infer_nodes_per_replica
if num_infer_nodes > 0 and not self.inference:
raise ValueError("Must configure inference when using multi-node deployment with inference nodes.")
if self.deployment.num_infer_nodes == 0 and self.inference:
if num_infer_nodes == 0 and self.inference:
raise ValueError(
"Cannot configure inference with num_infer_nodes = 0. "
"Either set num_infer_nodes > 0 or remove the inference config."
)
if self.deployment.num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
if num_infer_nodes == 0 and not self.trainer.data.fake and not self.bench:
raise ValueError(
"Must use fake data (trainer.data.fake or bench = true) when num_infer_nodes = 0, "
"since no orchestrator or inference server will be running."
@@ -304,29 +336,46 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_weight_broadcast(self):
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference."""
if self.weight_broadcast is not None:
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
inference_world_size=inference_world_size,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
"""Auto-setup shared weight broadcast config for trainer, orchestrator, and inference.
Defaults to NCCL broadcast when no ``weight_broadcast`` is configured. Falls back to
filesystem when LoRA is enabled (not yet supported with NCCL) or when no inference
server is configured (NCCL requires a running inference pool).
"""
if self.weight_broadcast is None:
if self.trainer.model.lora is not None or self.inference is None:
self.weight_broadcast = SharedWeightBroadcastConfig(type="filesystem")
else:
self.weight_broadcast = SharedWeightBroadcastConfig()
if self.weight_broadcast.type == "nccl" and self.trainer.model.lora is not None:
# LoRA adapters are transferred via the filesystem (loaded from disk by the inference
# servers); NCCL broadcast only writes a STABLE marker, so LoRA over NCCL cannot transfer
# an adapter and would hang/fail on the startup weight sync.
raise ValueError(
"LoRA training is not yet supported with NCCL weight broadcast. "
"Set weight_broadcast.type = 'filesystem'."
)
if self.weight_broadcast.type == "nccl":
inference_world_size = self.inference.parallel.dp * self.inference.parallel.tp if self.inference else 1
self.trainer.weight_broadcast = TrainerNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
inference_world_size=inference_world_size,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
self.orchestrator.weight_broadcast = OrchestratorNCCLWeightBroadcastConfig(
type=self.weight_broadcast.type,
port=self.weight_broadcast.port,
timeout=self.weight_broadcast.timeout,
inference_world_size=inference_world_size,
quantize_in_weight_transfer=self.weight_broadcast.quantize_in_weight_transfer,
)
elif self.weight_broadcast.type == "filesystem":
self.trainer.weight_broadcast = TrainerFileSystemWeightBroadcastConfig()
self.orchestrator.weight_broadcast = OrchestratorFileSystemWeightBroadcastConfig()
if self.inference is not None:
self.inference.weight_broadcast = InferenceWeightBroadcastConfig(type=self.weight_broadcast.type)
validate_shared_weight_broadcast(self.trainer, self.orchestrator, self.inference)
@@ -531,7 +580,7 @@ class RLConfig(BaseConfig):
)
inferred_dp_local = self.deployment.gpus_per_node // inference_tp
total_infer_gpus = self.deployment.num_infer_nodes * self.deployment.gpus_per_node
total_infer_gpus = self.deployment.infer_nodes_per_replica * self.deployment.gpus_per_node
expected_global_world_size = self.inference.parallel.dp * inference_tp
if expected_global_world_size != total_infer_gpus:
raise ValueError(
@@ -593,12 +642,11 @@ class RLConfig(BaseConfig):
return self
infer_deploy = self.inference.deployment
expected_infer_nodes = infer_deploy.num_prefill_nodes + infer_deploy.num_decode_nodes
if self.deployment.num_infer_nodes != expected_infer_nodes:
expected_infer_nodes = infer_deploy.num_nodes
if self.deployment.infer_nodes_per_replica != expected_infer_nodes:
raise ValueError(
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal "
f"inference.deployment.num_prefill_nodes ({infer_deploy.num_prefill_nodes}) + "
f"inference.deployment.num_decode_nodes ({infer_deploy.num_decode_nodes}) = {expected_infer_nodes}"
f"deployment.num_infer_nodes ({self.deployment.num_infer_nodes}) must equal the derived "
f"disaggregated inference nodes per replica ({expected_infer_nodes})."
)
total_infer_gpus = self.deployment.total_infer_nodes * self.deployment.gpus_per_node
@@ -117,6 +117,9 @@ class DebugModelConfig(BaseConfig):
class ModelConfig(BaseModelConfig):
conversion_dir: Path | None = None
"""Directory for the auto-converted weights (written to a `prime`/`hf` subdirectory). If not set, we write into the model snapshot directory."""
seq_len: int = 2048
"""Sequence length the model is trained on."""
@@ -652,7 +655,7 @@ class TrainerConfig(BaseConfig):
@model_validator(mode="after")
def validate_lora_broadcast(self):
if self.model.lora is not None and self.weight_broadcast.type == "nccl":
# TODO: Support this
# TODO: Support NCCL broadcast with LoRA
raise ValueError("NCCL weight broadcast does not support LoRA yet.")
return self
@@ -1,10 +1,45 @@
from pathlib import Path
from typing import Any
from pydantic import BaseModel
from pydantic_config import BaseConfig as BaseConfig # noqa: F401
from pydantic_config import cli # noqa: F401
def to_toml_dict(config: BaseModel, exclude: set[str] | None = None) -> dict:
"""Dump a config to a TOML-serializable dict.
TOML cannot represent null, so None fields left at their default are dropped
(they re-resolve identically on re-parse) while explicitly-set None fields
are encoded as the string ``"None"``, which ``BaseConfig`` converts back to
``None``. Dropping those too would silently revert explicit None overrides
(e.g. ``--trainer.model.compile None``) to their non-None defaults when the
written config is re-parsed.
"""
return _encode_model(config, config.model_dump(exclude=exclude, mode="json"))
def _encode_model(model: BaseModel, dumped: dict) -> dict:
encoded = {}
for name, value in dumped.items():
if value is None:
if name in model.model_fields_set:
encoded[name] = "None"
continue
encoded[name] = _encode_value(getattr(model, name), value)
return encoded
def _encode_value(attr: Any, value: Any) -> Any:
if isinstance(attr, BaseModel) and isinstance(value, dict):
return _encode_model(attr, value)
if isinstance(value, list) and isinstance(attr, (list, tuple)):
return [_encode_value(a, v) for a, v in zip(attr, value)]
if isinstance(value, dict) and isinstance(attr, dict):
return {k: _encode_value(a, v) for (k, v), a in zip(value.items(), attr.values())}
return "None" if value is None else value
def find_package_resource(subdir: str) -> Path | None:
"""Find a directory contributed to the `prime_rl` namespace package by any installed wheel.
+27 -140
View File
@@ -1,6 +1,6 @@
[project]
name = "prime-rl"
version = "0.6.0"
version = "0.7.0"
description = "Async RL Training at Scale"
readme = "README.md"
requires-python = "~=3.12.0"
@@ -34,7 +34,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"torchtitan",
"verifiers[harbor]>=0.1.15.dev411",
"verifiers[harbor]>=0.2.0",
"renderers",
"dion",
"tilelang>=0.1.8",
@@ -66,80 +66,12 @@ flash-attn-3 = ["flash_attn_3"]
flash-attn-cute = [
"flash-attn-4",
]
envs = [
"aime24-v1",
"aime25-v1",
"aime26-v1",
"alphabet-sort",
"alphabet-sort-v1",
"apex-shortlist-v1",
"arxivmath-v1",
"browsecomp-v1",
"code-golf-v1",
"color-codeword-v1",
"deepdive-v1",
"deepwiki-v1",
"forth-lang-v1",
"general-agent",
"general-agent-v1",
"glossary-v1",
"gpqa-v1",
"graphwalks-v1",
"gsm8k-v1",
"i3-code-v1",
"i3-science-v1",
"ifbench-v1",
"ifeval-v1",
"lean-v1",
"livecodebench-v1",
"logic-env",
"longcot-mini-v1",
"longcot-v1",
"longpdfs-v1",
"math-env",
"math-env-v1",
"math-python",
"math500-v1",
"mmlu-pro-v1",
"mrcr-v2-v1",
"oolong-pairs-v1",
"oolong-real-v1",
"oolong-synth-v1",
"openseeker-v1",
"openthoughts-tblite-v1",
"papersearchqa-v1",
"patterned-needle-in-haystack-v1",
"prolog-v1",
"r2e-gym-v1",
"redsearcher-v1",
"reverse-text",
"reverse-text-v1",
"rlm-search",
"s1-deepresearch-v1",
"scaleswe-v1",
"simpleqa-v1",
"simpleqa-verified-v1",
"swebench-pro-v1",
"swebench-verified-v1",
"swelego-v1",
"tau2-bench-v1",
"terminal-bench-2-v1",
"unscramble-v1",
"uuid-ctf-v1",
"verbatim-copy-v1",
"wideseek-v1",
"wiki-search",
"wiki-search-v1",
"wikispeedia-v1",
"wordle",
"wordle-v1",
]
disagg = [
"deep-ep ; platform_machine == 'x86_64'",
"deep-gemm ; platform_machine == 'x86_64'",
"deep-gemm",
"nixl",
"nixl-cu12 ; platform_machine == 'x86_64'",
"vllm-router ; platform_machine == 'x86_64'",
"vllm-router",
]
gpt-oss = [
"kernels",
@@ -193,6 +125,21 @@ override-dependencies = [
"openenv-core",
]
# Environment packages (research-environments + verifiers) are auto-discovered as
# workspace members, so new envs need no per-package registration. Install them
# with `uv sync --all-packages`.
[tool.uv.workspace]
members = [
"deps/research-environments/environments/*/*",
"deps/verifiers/environments/*",
]
# tau2-synth-v1 and tau3-bench-v1 pin `tau2` forks/revs that conflict with the
# canonical tau2-bench-v1; a workspace shares one lock, so these can't coexist.
exclude = [
"deps/research-environments/environments/tool_use/tau2_synth_v1",
"deps/research-environments/environments/tool_use/tau3_bench_v1",
]
# ModelExpress 0.3.0 publishes protobuf<6 metadata, but its generated proto is
# compatible with protobuf 6. prime-sandboxes requires protobuf>=6.31.1; keep
# this capped to the validated protobuf major.
@@ -242,85 +189,25 @@ prime-rl-configs = { path = "packages/prime-rl-configs", editable = true }
verifiers = { path = "deps/verifiers", editable = true }
renderers = { path = "deps/renderers", editable = true }
prime-pydantic-config = { path = "deps/pydantic-config", editable = true }
aime24-v1 = { path = "deps/research-environments/environments/aime24_v1", editable = true }
aime25-v1 = { path = "deps/research-environments/environments/aime25_v1", editable = true }
aime26-v1 = { path = "deps/research-environments/environments/aime26_v1", editable = true }
alphabet-sort = { path = "deps/verifiers/environments/alphabet_sort", editable = true }
alphabet-sort-v1 = { path = "deps/verifiers/environments/alphabet_sort_v1", editable = true }
apex-shortlist-v1 = { path = "deps/research-environments/environments/apex_shortlist_v1", editable = true }
arxivmath-v1 = { path = "deps/research-environments/environments/arxivmath_v1", editable = true }
browsecomp-v1 = { path = "deps/research-environments/environments/browsecomp_v1", editable = true }
code-golf-v1 = { path = "deps/verifiers/environments/code_golf_v1", editable = true }
color-codeword-v1 = { path = "deps/verifiers/environments/color_codeword_v1", editable = true }
deepdive-v1 = { path = "deps/research-environments/environments/deepdive_v1", editable = true }
deepwiki-v1 = { path = "deps/verifiers/environments/deepwiki_v1", editable = true }
forth-lang-v1 = { path = "deps/research-environments/environments/forth_lang_v1", editable = true }
general-agent = { path = "deps/research-environments/environments/general_agent", editable = true }
general-agent-v1 = { path = "deps/research-environments/environments/general_agent_v1", editable = true }
glossary-v1 = { path = "deps/verifiers/environments/glossary_v1", editable = true }
gpqa-v1 = { path = "deps/research-environments/environments/gpqa_v1", editable = true }
graphwalks-v1 = { path = "deps/research-environments/environments/graphwalks_v1", editable = true }
gsm8k-v1 = { path = "deps/verifiers/environments/gsm8k_v1", editable = true }
i3-code-v1 = { path = "deps/research-environments/environments/i3_code_v1", editable = true }
i3-science-v1 = { path = "deps/research-environments/environments/i3_science_v1", editable = true }
ifbench-v1 = { path = "deps/research-environments/environments/ifbench_v1", editable = true }
ifeval-v1 = { path = "deps/research-environments/environments/ifeval_v1", editable = true }
lean-v1 = { path = "deps/research-environments/environments/lean_v1", editable = true }
livecodebench-v1 = { path = "deps/research-environments/environments/livecodebench_v1", editable = true }
logic-env = { path = "deps/research-environments/environments/logic_env", editable = true }
longcot-mini-v1 = { path = "deps/research-environments/environments/longcot_mini_v1", editable = true }
longcot-v1 = { path = "deps/research-environments/environments/longcot_v1", editable = true }
longpdfs-v1 = { path = "deps/research-environments/environments/longpdfs_v1", editable = true }
math-env = { path = "deps/research-environments/environments/math_env", editable = true }
math-env-v1 = { path = "deps/research-environments/environments/math_env_v1", editable = true }
math-python = { path = "deps/verifiers/environments/math_python", editable = true }
math500-v1 = { path = "deps/research-environments/environments/math500_v1", editable = true }
mmlu-pro-v1 = { path = "deps/research-environments/environments/mmlu_pro_v1", editable = true }
mrcr-v2-v1 = { path = "deps/research-environments/environments/mrcr_v2_v1", editable = true }
oolong-pairs-v1 = { path = "deps/research-environments/environments/oolong_pairs_v1", editable = true }
oolong-real-v1 = { path = "deps/research-environments/environments/oolong_real_v1", editable = true }
oolong-synth-v1 = { path = "deps/research-environments/environments/oolong_synth_v1", editable = true }
openseeker-v1 = { path = "deps/research-environments/environments/openseeker_v1", editable = true }
openthoughts-tblite-v1 = { path = "deps/research-environments/environments/openthoughts_tblite_v1", editable = true }
papersearchqa-v1 = { path = "deps/research-environments/environments/papersearchqa_v1", editable = true }
patterned-needle-in-haystack-v1 = { path = "deps/research-environments/environments/patterned_needle_in_haystack_v1", editable = true }
prolog-v1 = { path = "deps/research-environments/environments/prolog_v1", editable = true }
r2e-gym-v1 = { path = "deps/research-environments/environments/r2e_gym_v1", editable = true }
redsearcher-v1 = { path = "deps/research-environments/environments/redsearcher_v1", editable = true }
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
reverse-text-v1 = { path = "deps/verifiers/environments/reverse_text_v1", editable = true }
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
s1-deepresearch-v1 = { path = "deps/research-environments/environments/s1_deepresearch_v1", editable = true }
scaleswe-v1 = { path = "deps/research-environments/environments/scaleswe_v1", editable = true }
simpleqa-v1 = { path = "deps/research-environments/environments/simpleqa_v1", editable = true }
simpleqa-verified-v1 = { path = "deps/research-environments/environments/simpleqa_verified_v1", editable = true }
swebench-pro-v1 = { path = "deps/research-environments/environments/swebench_pro_v1", editable = true }
swebench-verified-v1 = { path = "deps/research-environments/environments/swebench_verified_v1", editable = true }
swelego-v1 = { path = "deps/research-environments/environments/swelego_v1", editable = true }
tau2-bench-v1 = { path = "deps/research-environments/environments/tau2_bench_v1", editable = true }
terminal-bench-2-v1 = { path = "deps/research-environments/environments/terminal_bench_2_v1", editable = true }
unscramble-v1 = { path = "deps/research-environments/environments/unscramble_v1", editable = true }
uuid-ctf-v1 = { path = "deps/research-environments/environments/uuid_ctf_v1", editable = true }
verbatim-copy-v1 = { path = "deps/research-environments/environments/verbatim_copy_v1", editable = true }
wideseek-v1 = { path = "deps/research-environments/environments/wideseek_v1", editable = true }
wiki-search = { path = "deps/verifiers/environments/wiki_search", editable = true }
wiki-search-v1 = { path = "deps/verifiers/environments/wiki_search_v1", editable = true }
wikispeedia-v1 = { path = "deps/research-environments/environments/wikispeedia_v1", editable = true }
wordle = { path = "deps/verifiers/environments/wordle", editable = true }
wordle-v1 = { path = "deps/verifiers/environments/wordle_v1", editable = true }
torch = { index = "pytorch-cu128" }
torchvision = { index = "pytorch-cu128" }
torchaudio = { index = "pytorch-cu128" }
torchtitan = { git = "https://github.com/pytorch/torchtitan", rev = "23e4dfc" }
dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm-router = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.26/vllm_router-0.1.26-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
vllm = [
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.24.0/vllm-0.24.0+cu129-cp38-abi3-manylinux_2_28_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
deep-ep = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_ep-1.2.1+29d31c0-cp312-cp312-linux_x86_64.whl" }
deep-gemm = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_x86_64.whl" }
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", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/deep_gemm-2.5.0+891d57b-cp312-cp312-linux_aarch64.whl", marker = "platform_machine == 'aarch64'" },
]
nixl-cu12 = { url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/nixl_cu12-0.10.1-cp312-cp312-linux_x86_64.whl" }
flash-linear-attention = { git = "https://github.com/fla-org/flash-linear-attention" }
flash_attn_3 = { index = "pytorch-cu128-test" }
+2 -2
View File
@@ -59,9 +59,9 @@ if [ -n "$PRIME_RL_REF" ]; then
# startup. --inexact keeps the seeded venv's pre-built wheels
# (flash-attn-3, mamba-ssm) in place; uv only rebuilds them if the
# override's lockfile pins different versions.
( cd "$DEST" && uv sync --inexact --no-dev \
( cd "$DEST" && uv sync --inexact --no-dev --all-packages \
--extra flash-attn --extra flash-attn-3 --extra flash-attn-cute \
--extra envs --extra gpt-oss --extra modelexpress \
--extra gpt-oss --extra modelexpress \
--group mamba-ssm )
export VIRTUAL_ENV="$DEST/.venv"
export PATH="$DEST/.venv/bin:$PATH"
+94
View File
@@ -0,0 +1,94 @@
"""Export a verifiers v1 eval run (traces.jsonl) as an SFT dataset for `uv run sft`.
Reads a finished run's saved traces and reshapes them into the dataset shape the SFT trainer
consumes directly (see `prime_rl.trainer.sft.data`): a `messages` column (OpenAI chat wire
shape) plus a `tools` column (the tools the model was shown, from `Trace.tools`,
JSON-encoded — heterogeneous JSON-schema dicts don't fit a fixed Arrow schema). One row per
branch: a linear rollout contributes one sample, a compacted/subagent rollout one per branch
(one training sample is built per branch).
Selection: generation-errored traces (`stop_condition == "error"`) always drop — a broken
transcript is not a sample. A scoring-only error keeps the generation outcome as its stop
condition and a complete conversation, so it stays; its reward may be partial/zero, which
`--min-reward` handles.
Usage (from the prime-rl repo):
uv run python scripts/export_sft.py <run-dir> [--min-reward 1.0] [--drop-truncated]
[-o OUT_DIR] [--push HF_REPO_ID]
Writes `<run-dir>/sft/train.parquet` by default — point the trainer at it with
`--data.name <run-dir>/sft`. Requires a verifiers release carrying `Trace.tools`
(PrimeIntellect-ai/verifiers#1963).
"""
import argparse
import json
from pathlib import Path
from datasets import Dataset
from verifiers.v1 import Trace, WireTrace
from verifiers.v1.dialects.chat import message_to_wire
def sft_rows(trace: Trace) -> list[dict]:
"""A trace's SFT rows — one per branch: the branch's conversation as OpenAI chat wire
dicts plus the trace's advertised tools, JSON-encoded."""
tools = json.dumps([t.model_dump(mode="json", exclude_none=True) for t in trace.tools or []])
return [
{
"messages": [message_to_wire(m) for m in branch.messages],
"tools": tools,
}
for branch in trace.branches
if branch.messages
]
def keep(trace: Trace, min_reward: float | None, drop_truncated: bool) -> bool:
"""Whether a trace is worth training on (see module docstring for the error semantics)."""
if trace.stop_condition == "error":
return False
if drop_truncated and trace.is_truncated:
return False
return min_reward is None or trace.reward >= min_reward
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("run_dir", type=Path, help="the eval run dir (holds traces.jsonl)")
parser.add_argument("--min-reward", type=float, default=None, help="keep traces with reward >= this")
parser.add_argument("--drop-truncated", action="store_true", help="drop budget-cut traces")
parser.add_argument("-o", "--output-dir", type=Path, default=None, help="default: <run-dir>/sft")
parser.add_argument("--push", default=None, help="HF repo id to push to instead of writing parquet")
args = parser.parse_args()
traces_path = args.run_dir / "traces.jsonl"
if not traces_path.exists():
raise SystemExit(f"no traces.jsonl in {args.run_dir}")
total, rows = 0, []
with traces_path.open(encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
total += 1
trace = WireTrace.model_validate(json.loads(line))
if keep(trace, args.min_reward, args.drop_truncated):
rows.extend(sft_rows(trace))
print(f"export-sft: {total} trace(s) -> {len(rows)} row(s)")
if not rows:
raise SystemExit("export-sft: no rows to export after selection")
dataset = Dataset.from_list(rows)
if args.push:
dataset.push_to_hub(args.push)
print(f"export-sft: pushed to {args.push}")
return
out = args.output_dir or args.run_dir / "sft"
out.mkdir(parents=True, exist_ok=True)
dataset.to_parquet(str(out / "train.parquet"))
print(f"export-sft: wrote {out / 'train.parquet'} -> train with --data.name {out}")
if __name__ == "__main__":
main()
+6 -10
View File
@@ -22,12 +22,14 @@ git submodule update --init --recursive
## 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.
uv sync # core only
uv sync --group dev # + pytest, ruff, pre-commit
uv sync --all-extras # + extras (flash-attn, flash-attn-cute, …)
uv sync --all-extras --all-packages # + all env packages (needed to train on them)
uv sync --package prime-rl --package gsm8k-v1 # core + just one env
```
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
Environment packages under `deps/research-environments/environments/*/*` and `deps/verifiers/environments/*` are uv **workspace members**, auto-discovered — adding a new env needs no `pyproject.toml` change. They are opt-in: a plain `uv sync` / `--all-extras` does not install them (and would remove them if already present — re-run with `--all-packages`, or `--inexact` to keep them). Install all with `--all-packages`, or a subset with repeated `--package <env>` (include `--package prime-rl` to keep the core). If two envs pin conflicting transitive versions (all members share one lock), add the loser to `[tool.uv.workspace].exclude`.
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`.
@@ -41,12 +43,6 @@ 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.
+16 -9
View File
@@ -58,7 +58,7 @@ After a restart, verify all processes are back up and progress resumed before th
- `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.
- `{output_dir}/rollouts/step_N/{train,eval}/` — saved rollout traces (see Traces below).
### Logs
@@ -130,21 +130,28 @@ 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
### Traces
```
{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
{output_dir}/rollouts/step_N/{train,eval}/all/traces.jsonl # appended per rollout as it completes
{output_dir}/rollouts/step_N/{train,eval}/effective/traces.jsonl # written per finalized batch / eval epoch
```
JSONL files of `vf.Trace` records (training tensors excluded). `all` gets every completed
rollout the moment it arrives — errored, filtered, and never-batched ones included — so it's
crash-durable; `effective` gets the clean subset that went into the step's train batch (eval:
the non-errored epoch cohort; multiple eval envs share the step file). Each record carries
`kind`, `env_name`, `group_id`, `policy_version`, and `eval_step`, plus `runtime` (config +
provisioned resource id, e.g. the sandbox id).
```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
wc -l {output_dir}/rollouts/step_42/train/{all,effective}/traces.jsonl
jq '.rewards' {output_dir}/rollouts/step_42/train/effective/traces.jsonl
jq 'select(.errors != []) | {id, env_name, runtime}' {output_dir}/rollouts/step_*/train/all/traces.jsonl
```
The binary batches consumed by the trainer still live at `{output_dir}/rollouts/step_N/train_rollouts.bin`, next to the trace subtrees.
### Common failure modes
A few warnings are normal. Escalate when errors are persistent, growing, or hit a large fraction of rollouts.
+4 -3
View File
@@ -37,9 +37,10 @@ uv run rl @ examples/reverse_text/rl.toml --dry-run
- Environment packages: before launching a config with a non-core verifier env id,
verify the package imports under `uv run` (for example
`uv run python -c "import importlib.util; print(importlib.util.find_spec('r2e_gym_v1'))"`).
If a local env exists under `deps/research-environments/environments/` but does not
import, add it to the root `pyproject.toml` env extra, workspace members, and
`[tool.uv.sources]`, then run `uv sync --all-extras`.
If a local env exists under `deps/research-environments/environments/` or
`deps/verifiers/environments/` but does not import, install the env workspace
members with `uv sync --all-packages` (all) or `uv sync --package prime-rl
--package <env>` (one) — they're auto-discovered, no `pyproject.toml` edit needed.
## `sft` — SFT training
+4 -2
View File
@@ -8,7 +8,7 @@ from typing import Any
import tomli_w
from prime_rl.configs.inference import InferenceConfig
from prime_rl.utils.config import cli
from prime_rl.utils.config import cli, to_toml_dict
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import format_log_message, get_config_dir, get_log_dir
from prime_rl.utils.process import DEFAULT_COMMON_ENV_VARS, DEFAULT_INFERENCE_ENV_VARS, set_proc_title
@@ -33,7 +33,7 @@ def write_config(config: InferenceConfig, output_dir: Path, exclude: set[str] |
output_dir.mkdir(parents=True, exist_ok=True)
config_path = output_dir / INFERENCE_TOML
with open(config_path, "wb") as f:
tomli_w.dump(config.model_dump(exclude=exclude, exclude_none=True, mode="json"), f)
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
return config_path
@@ -76,6 +76,8 @@ def write_slurm_script(config: InferenceConfig, config_path: Path, script_path:
template_vars.update(
num_prefill_nodes=config.deployment.num_prefill_nodes,
num_decode_nodes=config.deployment.num_decode_nodes,
prefill_nodes_per_replica=config.deployment.prefill_nodes_per_replica,
decode_nodes_per_replica=config.deployment.decode_nodes_per_replica,
num_prefill_replicas=config.deployment.num_prefill_replicas,
num_decode_replicas=config.deployment.num_decode_replicas,
prefill_port=config.deployment.prefill_port,
+10 -9
View File
@@ -16,7 +16,7 @@ from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli
from prime_rl.utils.config import cli, to_toml_dict
from prime_rl.utils.logger import get_logger, setup_logger
from prime_rl.utils.pathing import (
clean_future_steps,
@@ -56,9 +56,8 @@ def get_physical_gpu_ids() -> list[int]:
def write_config(config: RLConfig, output_dir: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
output_dir.mkdir(parents=True, exist_ok=True)
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
with open(output_dir / RL_TOML, "wb") as f:
tomli_w.dump(config_dict, f)
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
@@ -66,16 +65,16 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
output_dir.mkdir(parents=True, exist_ok=True)
with open(output_dir / TRAINER_TOML, "wb") as f:
tomli_w.dump(config.trainer.model_dump(exclude_none=True, mode="json"), f)
tomli_w.dump(to_toml_dict(config.trainer), f)
with open(output_dir / ORCHESTRATOR_TOML, "wb") as f:
tomli_w.dump(config.orchestrator.model_dump(exclude_none=True, mode="json"), f)
tomli_w.dump(to_toml_dict(config.orchestrator), f)
if config.inference is not None:
# Exclude launcher-only fields that are not needed by the vLLM server
exclude_inference = {"deployment", "slurm", "output_dir", "dry_run"}
with open(output_dir / INFERENCE_TOML, "wb") as f:
tomli_w.dump(config.inference.model_dump(exclude=exclude_inference, exclude_none=True, mode="json"), f)
tomli_w.dump(to_toml_dict(config.inference, exclude=exclude_inference), f)
def rl_local(config: RLConfig):
@@ -410,6 +409,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_infer_replicas=config.deployment.num_infer_replicas,
num_prefill_nodes=infer_deploy.num_prefill_nodes,
num_decode_nodes=infer_deploy.num_decode_nodes,
prefill_nodes_per_replica=infer_deploy.prefill_nodes_per_replica,
decode_nodes_per_replica=infer_deploy.decode_nodes_per_replica,
num_prefill_replicas=infer_deploy.num_prefill_replicas,
num_decode_replicas=infer_deploy.num_decode_replicas,
gpus_per_node=config.deployment.gpus_per_node,
@@ -441,11 +442,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
orchestrator_output_dir=config.orchestrator.output_dir,
num_train_nodes=config.deployment.num_train_nodes,
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.num_infer_nodes,
nodes_per_infer_replica=config.deployment.infer_nodes_per_replica,
num_infer_replicas=config.deployment.num_infer_replicas,
gpus_per_node=config.deployment.gpus_per_node,
router=config.inference.deployment.router if config.inference else VllmRouterConfig(),
infer_nodes_per_replica=config.deployment.num_infer_nodes,
infer_nodes_per_replica=config.deployment.infer_nodes_per_replica,
backend_port=config.inference.deployment.backend_port if config.inference else 8100,
inference_tp=config.inference.parallel.tp if config.inference else 1,
inference_enable_expert_parallel=config.inference.enable_expert_parallel if config.inference else False,
@@ -496,7 +497,7 @@ def rl_slurm(config: RLConfig):
train_env_names = [env.resolved_name for env in config.orchestrator.train.env]
eval_env_names = [env.resolved_name for env in config.orchestrator.eval.env] if config.orchestrator.eval else []
has_infer = config.deployment.num_infer_nodes > 0
has_infer = config.deployment.infer_nodes_per_replica > 0
log_message = format_log_message(
log_dir=log_dir,
trainer=True,
+2 -3
View File
@@ -9,7 +9,7 @@ from threading import Event, Thread
import tomli_w
from prime_rl.configs.sft import SFTConfig
from prime_rl.utils.config import cli
from prime_rl.utils.config import cli, to_toml_dict
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 (
@@ -28,9 +28,8 @@ SFT_SBATCH = "sft.sbatch"
def write_config(config: SFTConfig, config_path: Path, exclude: set[str] | None = None) -> None:
"""Write resolved config to disk, excluding launcher-only fields."""
config_path.parent.mkdir(parents=True, exist_ok=True)
config_dict = config.model_dump(exclude=exclude, exclude_none=True, mode="json")
with open(config_path, "wb") as f:
tomli_w.dump(config_dict, f)
tomli_w.dump(to_toml_dict(config, exclude=exclude), f)
def write_slurm_script(config: SFTConfig, config_path: Path, script_path: Path) -> None:
+4 -1
View File
@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Callable
from prime_rl.configs.algorithm import EchoAlgoConfig
from prime_rl.orchestrator.algo.grpo import GRPOAlgorithm
from prime_rl.orchestrator.trajectories import iter_trainable_branches
from prime_rl.utils.utils import import_object
if TYPE_CHECKING:
@@ -55,7 +56,9 @@ class EchoAlgorithm(GRPOAlgorithm):
(role tags, separators, tool-response wraps) is excluded. Nodes without
attribution (the default renderer, or relay turns with no token ids)
fall back to weighting the whole non-sampled span."""
trainable_branches = [branch for branch in rollout.branches if any(branch.sampled_mask)]
# Same branch selection as ``trace_to_samples``, so the zip with ``rollout.samples``
# stays aligned when fork dedup drops a branch.
trainable_branches = [branch for branch, _ in iter_trainable_branches(rollout)]
filter_masks = self._filter_masks(rollout, trainable_branches) if self.filter_fn is not None else None
for sample_idx, (sample, branch) in enumerate(zip(rollout.samples, trainable_branches)):
weights = [0.0] * len(sample.token_ids)
+2 -2
View File
@@ -53,11 +53,11 @@ class OPSDAlgorithm(Algorithm):
def _demonstration(self, rollout: Rollout) -> str:
demonstration = rollout.info.get(self.demo_key)
if demonstration is None:
demonstration = getattr(rollout.task, self.demo_key, None)
demonstration = getattr(rollout.task.data, self.demo_key, None)
if demonstration is None:
raise ValueError(
f"opsd requires '{self.demo_key}' in the trace info dict or on the task "
f"(env '{rollout.env_name}', task {rollout.task.idx})."
f"(env '{rollout.env_name}', task {rollout.task.data.idx})."
)
return demonstration
+14 -2
View File
@@ -3,6 +3,9 @@
from __future__ import annotations
import contextlib
import os
import tempfile
import time
from dataclasses import asdict
from pathlib import Path
@@ -27,8 +30,17 @@ class CheckpointManager:
ckpt_path = self.get_ckpt_path(step)
ckpt_path.mkdir(parents=True, exist_ok=True)
start = time.perf_counter()
with open(ckpt_path / "progress.pt", "wb") as f:
torch.save({"progress": progress}, f)
# Save to a temporary file and do an atomic rename, to avoid corrupting the last
# file if the process gets killed while writing
fd, tmp_name = tempfile.mkstemp(dir=ckpt_path, prefix="progress.pt.", suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
torch.save({"progress": progress}, f)
os.replace(tmp_name, ckpt_path / "progress.pt")
except BaseException:
with contextlib.suppress(OSError):
os.unlink(tmp_name)
raise
get_logger().debug(
f"Orchestrator checkpoint saved to {ckpt_path} in {format_time(time.perf_counter() - start)}"
)
+6 -3
View File
@@ -506,7 +506,10 @@ class RolloutDispatcher:
except Exception as exc:
get_logger().warning(f"Rollout task failed in group {meta.group_id} ({meta.env_name}): {exc!r}")
task_idx = group.task_idx if group is not None else -1
rollouts = [Rollout(task=vf.Task(idx=task_idx, prompt=None)) for _ in range(meta.rollout_count)]
rollouts = [
Rollout(task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)))
for _ in range(meta.rollout_count)
]
for r in rollouts:
r.capture_error(exc)
is_synth_exception = True
@@ -574,7 +577,7 @@ class RolloutDispatcher:
for _, meta in claimed:
for _ in range(meta.rollout_count):
trace = Rollout(
task=vf.Task(idx=task_idx, prompt=None),
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
@@ -600,7 +603,7 @@ class RolloutDispatcher:
unscheduled_cancelled = group.rollouts_to_schedule
for _ in range(unscheduled_cancelled):
trace = Rollout(
task=vf.Task(idx=task_idx, prompt=None),
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=task_idx, prompt=None)),
errors=[vf.Error(type="Cancelled", message="Off-policy cancel")],
stop_condition="error",
)
+15 -10
View File
@@ -5,12 +5,12 @@ external one given by ``config.address``) and an ``EnvClient`` to drive it. The
orchestrator never *runs* an environment: it asks the server for ``info``
(``num_tasks`` + whether group scoring is needed), then runs rollouts purely by
**task index**. The server returns a ``Trace`` (a plain ``model_dump`` — derived values are
properties, not serialized) which we validate into a ``Trace[WireTask]`` — a real ``vf.Trace``
properties, not serialized) which we validate into a ``Trace[WireTaskData]`` — a real ``vf.Trace``
(never a loose dict) whose task keeps the env's
task-specific fields as extras (``WireTask`` allows them). The orchestrator never imports the
task-specific fields as extras (``WireTaskData`` allows them). The orchestrator never imports the
env package: the env's *type* and *runtime* both live only in the server, and the orchestrator
drives it purely by task index. (Nothing here reads typed env task fields — only ``task.idx``
and a full ``task.model_dump``, both of which ``WireTask`` preserves.)
and a full ``task.model_dump``, both of which ``WireTaskData`` preserves.)
"""
from __future__ import annotations
@@ -35,10 +35,10 @@ from prime_rl.orchestrator.sampler import Sampler
from prime_rl.orchestrator.types import Rollout
from prime_rl.utils.logger import get_logger
# Every wire trace validates into this type. WireTask (extra="allow") keeps the env's task
# Every wire trace validates into this type. WireTaskData (extra="allow") keeps the env's task
# fields without importing the env package — the orchestrator never reads them typed (only
# task.idx + task.model_dump).
ROLLOUT_TYPE = Rollout[vf.WireTask]
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
# Max wait for a spawned env server to bind and report its address. The child
# loads the taskset (possibly downloading a dataset) before reporting, so this
@@ -83,7 +83,8 @@ class Env:
def __init__(self, config: EnvConfig):
self.config = config
self.sampling_args: dict = {}
self.num_tasks: int = 0
self.num_tasks: int | None = 0
"""Task count reported by the server; ``None`` means the taskset is infinite."""
self.requires_group_scoring: bool = False
self._env_client: EnvClient | None = None
self._env_server_process: BaseProcess | None = None
@@ -112,9 +113,8 @@ class Env:
info = await self.env_client.info()
self.num_tasks = info.num_tasks
self.requires_group_scoring = info.requires_group_scoring
get_logger().info(
f"Env {self.name} ready: num_tasks={self.num_tasks} group_scoring={self.requires_group_scoring}"
)
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
"""Spawn a v1 EnvServer child process (it loads the env; we never do).
@@ -220,7 +220,12 @@ class EvalEnv(Env):
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
if self.num_tasks is None:
if self.config.num_examples < 0:
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
n = self.config.num_examples
else:
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
self.examples = [{"task_idx": i} for i in range(n)]
+1 -1
View File
@@ -96,7 +96,7 @@ class EvalSink:
if not group:
return
env_name = group[0].env_name
task_idx = group[0].task.idx
task_idx = group[0].task.data.idx
eval_step = group[0].eval_step
bucket = self.pending_batches[(env_name, eval_step)]
bucket.extend(group)
+63 -25
View File
@@ -72,10 +72,11 @@ from prime_rl.trainer.model import setup_tokenizer
from prime_rl.transport import TrainingBatch, setup_training_batch_sender
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
from prime_rl.utils.client import init_nccl_broadcast
from prime_rl.utils.config import to_toml_dict
from prime_rl.utils.heartbeat import Heartbeat
from prime_rl.utils.logger import format_time, get_logger, setup_logger
from prime_rl.utils.monitor import setup_monitor
from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
from prime_rl.utils.pathing import get_log_dir, get_trace_path
from prime_rl.utils.usage_reporter import UsageReporter
from prime_rl.utils.utils import (
clean_exit,
@@ -100,6 +101,11 @@ MAX_CONSECUTIVE_EMPTY_BATCHES = 10
# resumed when the watcher advances ``policy.version``.
TARGET_LAG = 1
# Default wait for the trainer's startup weight broadcast when no ckpt block
# configures ``wait_for_weights_timeout`` (e.g. a from-scratch run). The
# broadcast is always coming, so wait rather than fail immediately.
STARTUP_WEIGHT_WAIT_TIMEOUT_S = 1200
class Orchestrator:
# Set in ``__init__``
@@ -195,7 +201,7 @@ class Orchestrator:
config_dir = config.output_dir / "control"
config_dir.mkdir(parents=True, exist_ok=True)
with open(config_dir / "orch.toml", "wb") as f:
tomli_w.dump(config.model_dump(exclude_none=True, mode="json"), f)
tomli_w.dump(to_toml_dict(config), f)
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
self.tokenizer = setup_tokenizer(config.tokenizer)
@@ -314,19 +320,29 @@ class Orchestrator:
# trainer even when ``ckpt.skip_progress`` left the counter unrestored.
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming orchestrator from checkpoint step {self.resume_step}")
check_exists = config.weight_broadcast.type != "nccl"
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else None
weights_path = get_weight_dir(
config.output_dir, self.resume_step, check_exists=check_exists, wait_timeout=wait_timeout
)
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=self.resume_step)
if self.lora_name is not None:
self.policy_inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
self.policy.version = self.resume_step
else:
get_logger().info("Training from scratch")
# Sync inference to the incoming policy before the first step, whether fresh (v0 = base) or
# resumed (v{resume_step}). This pauses inference and rendezvouses with the trainer's
# first-step broadcast (train.py), so inference serves the correct policy from step 1. Keeping
# it unconditional makes trainer/orchestrator startup symmetric and avoids the resume deadlock
# where inference waited for weights the trainer only sent at the end of a step.
sync_version = self.resume_step if self.resume_step is not None else 0
check_exists = config.weight_broadcast.type != "nccl"
# Wait for the trainer's startup broadcast to land. On a fresh start there is no ckpt block,
# so fall back to a default timeout instead of not waiting at all (which would raise before
# broadcasts/step_0/STABLE is written when using filesystem weight broadcast).
wait_timeout = config.ckpt.wait_for_weights_timeout if config.ckpt else STARTUP_WEIGHT_WAIT_TIMEOUT_S
weights_path = get_weight_dir(
config.output_dir, sync_version, check_exists=check_exists, wait_timeout=wait_timeout
)
await self.policy_inference.update_weights(weights_path, lora_name=self.lora_name, step=sync_version)
if self.lora_name is not None:
self.policy_inference.update_model_name(self.lora_name)
self.policy.model_name = self.lora_name
self.policy.version = sync_version
self.train_source = TrainSource(self.train_envs, seed=42)
self.eval_source: EvalSource | None = (
EvalSource(
@@ -465,6 +481,18 @@ class Orchestrator:
except asyncio.TimeoutError:
continue
# Every completed rollout — errored, filtered, or never batched — lands in the
# ``all`` trace file the moment it arrives, so it survives crashes and drains.
# Train rollouts belong to the batch window currently collecting (``progress.step``),
# eval rollouts to the step whose eval triggered them.
step = rollout.eval_step if rollout.kind == "eval" else self.progress.step
assert step is not None
await asyncio.to_thread(
save_rollouts,
[rollout.to_record()],
get_trace_path(self.config.output_dir, step, rollout.kind, "all"),
)
if rollout.kind == "eval":
assert self.eval_sink is not None # eval rollouts only emitted when eval is configured
eval_batch = self.eval_sink.add(rollout)
@@ -524,12 +552,13 @@ class Orchestrator:
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
)
# Serialize the typed Trace at the I/O boundary (disk + wandb sample tables); to_record
# drops the per-node training tensors — they're for training, not the rollout record, and
# can't round-trip json (raw numpy bytes).
rollout_dicts = [r.to_record() for r in batch.rollouts]
step_path = get_step_path(get_rollout_dir(config.output_dir), step)
await asyncio.to_thread(save_rollouts, rollout_dicts, step_path / "train_rollouts.jsonl")
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
# at ship time; the full arrival window already streamed into ``all`` on arrival.
# to_record drops the per-node training tensors — they're for training, not the rollout
# record, and can't round-trip json (raw numpy bytes).
effective = batch.rollouts.effective
records = [r.to_record() for r in effective]
await asyncio.to_thread(save_rollouts, records, get_trace_path(config.output_dir, step, "train", "effective"))
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
self.progress.step += 1
@@ -540,7 +569,6 @@ class Orchestrator:
# Rollout metrics over the {agg,<env>} × {all,effective} matrix. ``batch.rollouts`` is the
# full arrival window (errored + filtered included); ``.effective`` is the clean subset.
effective = batch.rollouts.effective
metrics: dict[str, float] = {}
for subset, pool in (("all", batch.rollouts), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix="train/agg", subset=subset)
@@ -740,12 +768,13 @@ class Orchestrator:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no rollouts returned, skipping log")
return
rollout_dicts = [r.to_record() for r in batch.rollouts]
step_path = get_step_path(get_rollout_dir(self.config.output_dir), batch.step)
# The non-errored subset lands in the per-step ``effective`` trace file on epoch
# completion (multiple eval envs share the step file — each epoch appends its cohort
# once, and every record carries ``env_name``); the full returned cohort already
# streamed into ``all`` on arrival.
records = [r.to_record() for r in batch.rollouts.effective]
await asyncio.to_thread(
save_rollouts,
rollout_dicts,
step_path / f"eval_rollouts_{batch.env_name}.jsonl",
save_rollouts, records, get_trace_path(self.config.output_dir, batch.step, "eval", "effective")
)
self.monitor.log_eval_samples(batch.rollouts, env_name=batch.env_name, step=batch.step)
policy_versions = {r.policy_version for r in batch.rollouts}
@@ -801,9 +830,18 @@ class Orchestrator:
are 1-indexed while policy versions stay 0-indexed, so the shipped-batch
count is ``progress.step - 1``."""
lead = (self.progress.step - 1) - self.policy.version
# The trainer skips the final NCCL weight broadcast (inference group is
# torn down), so policy.version never reaches the last step. Without this
# the gate deadlocks waiting for a version that will never be published.
# The last batch uses the penultimate policy anyway, so let it through.
building_final_batch_nccl = (
self.config.weight_broadcast.type == "nccl"
and self.config.max_steps is not None
and self.progress.step >= self.config.max_steps - 1
)
gate = self.dispatcher.dispatch_allowed
was_set = gate.is_set()
if lead > TARGET_LAG:
if lead > TARGET_LAG and not building_final_batch_nccl:
if was_set:
get_logger().info(
"Pausing dispatcher to prevent orchestrator from racing from trainer. Waiting for new policy..."
+44 -16
View File
@@ -30,6 +30,19 @@ from prime_rl.transport import TrainingSample
from prime_rl.utils.logger import get_logger
def payload_tokens(rollout: Rollout) -> int:
"""Token cost of the rollout's trainer-bound payload — the samples built by
``process_rollout``. This is what actually ships: forked traces can drop
branches with no trainable tokens, so ``Trace.num_total_tokens`` (which sums
over all branches) may overcount. For linear traces the two agree.
Zero-payload rollouts (no trainable samples at all) fall back to the trace
total so they still advance token batching — a degenerate all-zero-payload
stream then ships empty batches and trips the orchestrator's
consecutive-empty-batch abort instead of stalling the readiness check."""
return sum(len(sample.token_ids) for sample in rollout.samples) or rollout.num_total_tokens
class TrainSink:
"""Three-level train sink. Constructed once, fed via ``add(rollout)``."""
@@ -57,15 +70,18 @@ class TrainSink:
self.pre_filters = pre_filters
self.post_filters = post_filters
# Observation window for the next shipped batch: rollouts of groups
# finalized since the last ship (errored + filtered + survivors).
# In-progress groups stay out until they finalize.
self.pending_rollouts: TrainRollouts = TrainRollouts()
# Keyed by the dispatcher's group UUID. ``(env_name, task_idx)``
# isn't unique — the same task can be re-sampled while an
# earlier group is still in flight
self.pending_rollouts: TrainRollouts = TrainRollouts()
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
self.pending_batch: list[Rollout] = []
# Running token total of ``pending_batch`` (token-batched runs), kept in
# sync on append/pop so the readiness check never re-walks the uncached
# ``Trace.num_total_tokens`` graph property per arrival.
# Running payload-token total of ``pending_batch`` (token-batched
# runs), kept in sync on append/pop so the readiness check never
# re-sums per arrival.
self.pending_tokens: int = 0
# Reset by the orchestrator after each ship via ``reset_pre_filter_stats``
@@ -117,13 +133,18 @@ class TrainSink:
async def add(self, rollout: Rollout) -> TrainBatch | None:
"""Process one arrival; finalize the group on the ``group_size``-th
arrival; return a ``TrainBatch`` if the batch threshold is met."""
arrival; return a ``TrainBatch`` if the finalization pushed (or left)
the batch over its threshold. Arrivals into still-incomplete groups
never ship a batch."""
await self.process_rollout(rollout)
env_name = rollout.env_name
self.pending_rollouts.append(rollout)
self.pending_groups[rollout.group_id].append(rollout)
if len(self.pending_groups[rollout.group_id]) >= self.group_size_for(env_name):
await self.process_group(rollout.group_id)
if len(self.pending_groups[rollout.group_id]) < self.group_size_for(env_name):
return None
await self.process_group(rollout.group_id)
# ``pending_batch`` only grows on group finalization, so readiness is
# only re-checked here — the window of a shipped batch then always
# contains at least the group that finalized it.
ready = (
len(self.pending_batch) >= self.batch_size
if self.batch_size is not None
@@ -159,8 +180,14 @@ class TrainSink:
group = self.pending_groups.pop(group_id, [])
if not group:
return
# Window membership follows group finalization, not arrival: a rollout
# only becomes observable (metrics / persistence) once its whole group
# is finalized, so a batch's window never claims rollouts of a group
# that ships later. Dropped groups still land here — they were observed.
for r in group:
self.pending_rollouts.append(r)
env_name = group[0].env_name
task_idx = group[0].task.idx
task_idx = group[0].task.data.idx
survivors = [r for r in group if not r.has_error]
num_errored = len(group) - len(survivors)
@@ -211,7 +238,7 @@ class TrainSink:
r.is_filtered = False
self.pending_batch.append(r)
if self.token_batch_size is not None:
self.pending_tokens += r.num_total_tokens
self.pending_tokens += payload_tokens(r)
# Per-group summary. One line per finalized group; per-filter
# detection breakdown lives at debug level in ``apply_filters``
@@ -238,7 +265,7 @@ class TrainSink:
cut = 0
running = 0
for i, r in enumerate(self.pending_batch):
running += r.num_total_tokens
running += payload_tokens(r)
cut = i + 1
if running >= self.token_batch_size:
break
@@ -253,11 +280,12 @@ class TrainSink:
# advantage stream and loss routing on each sample. Filtered rollouts don't ship.
samples: list[TrainingSample] = [sample for r in cohort if not r.is_filtered for sample in r.samples]
# ``rollouts`` is the whole arrival window (errored + filtered + survivors); ``samples`` is
# the shipped cohort's trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive
# the clean subset + metric views on demand. Reset the window only when the batch actually
# ships (non-empty samples) — an empty batch is dropped unlogged by the orchestrator, so keep
# accumulating its arrivals (and any overflow) into the next shipped batch's window.
# ``rollouts`` is the observation window — every rollout of every group finalized since the
# last ship (errored + filtered + survivors) — while ``samples`` is the shipped cohort's
# trainable payload. ``rollouts.effective`` / ``rollouts.metrics`` derive the clean subset +
# metric views on demand. Reset the window only when the batch actually ships (non-empty
# samples) — an empty batch is dropped unlogged by the orchestrator, so keep accumulating its
# finalized groups (and any overflow) into the next shipped batch's window.
rollouts = self.pending_rollouts
if samples:
self.pending_rollouts = TrainRollouts()
+17 -6
View File
@@ -1,7 +1,10 @@
"""TrainSource: weighted round-robin across train envs, infinite pull.
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
per env). ``next_example`` reshuffles on cursor exhaustion."""
per env). A finite env serves a shuffled task-index table, reshuffled on
cursor exhaustion; an infinite env (``num_tasks is None``) streams a
monotonic ``task_idx`` — the server generates tasks on demand, so every
pull is a fresh task and there are no epochs to shuffle."""
from __future__ import annotations
@@ -22,17 +25,22 @@ class TrainSource:
if not self.envs:
raise ValueError("TrainSource needs at least one train env")
self.examples: dict[str, list[dict]] = {}
# A finite env's shuffled index table; ``None`` for an infinite env,
# whose cursor alone is the (monotonic) task_idx stream.
self.examples: dict[str, list[dict] | None] = {}
self.cursors: dict[str, int] = {}
# Group-scoring envs reserve ``group_size`` permits up front;
# per-rollout envs need 1
self.env_costs: dict[str, int] = {}
for env in self.envs:
# The orchestrator never loads the env: sample over the task-index
# range the server reported via info() (num_tasks).
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
self.rng.shuffle(rows)
self.examples[env.name] = rows
# range the server reported via info() (num_tasks; None = infinite).
if env.num_tasks is None:
self.examples[env.name] = None
else:
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
self.rng.shuffle(rows)
self.examples[env.name] = rows
self.cursors[env.name] = 0
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
@@ -45,6 +53,9 @@ class TrainSource:
return None
rows = self.examples[env_name]
cursor = self.cursors[env_name]
if rows is None: # infinite env: the cursor is the task_idx
self.cursors[env_name] = cursor + 1
return {"task_idx": cursor, "env_name": env_name}
if cursor >= len(rows):
self.rng.shuffle(rows)
cursor = 0
+26 -4
View File
@@ -15,6 +15,8 @@ the images it introduced (`branch.multi_modal_data`), rebuilt here into the flat
from __future__ import annotations
from collections.abc import Iterator
import numpy as np
import verifiers.v1 as vf
@@ -64,6 +66,29 @@ def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExp
return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype))
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
"""Yield each branch that yields a training sample, with its trainable-token mask.
The mask is `branch.sampled_mask` except that a sampled node shared by several branches
(a mid-trajectory fork) is trainable only in the first branch containing it; later
branches carry its tokens as context (mask False). Branches left with no trainable
tokens are skipped, so consumers pairing branches with `trace_to_samples` output
(e.g. echo's observation weighting) must filter through here to stay aligned.
"""
trained_nodes: set[int] = set()
for branch in trace.branches:
mask: list[bool] = []
for node in branch.nodes:
if node.sampled and any(node.mask) and id(node) in trained_nodes:
mask.extend([False] * len(node.mask))
else:
if node.sampled and any(node.mask):
trained_nodes.add(id(node))
mask.extend(node.mask)
if any(mask):
yield branch, mask
def trace_to_samples(
trace: vf.Trace,
*,
@@ -82,10 +107,7 @@ def trace_to_samples(
yield nothing.
"""
samples: list[TrainingSample] = []
for branch in trace.branches:
mask = branch.sampled_mask
if not any(mask):
continue
for branch, mask in iter_trainable_branches(trace):
token_ids = branch.token_ids
mm_kwargs: dict[str, EncodedTensor] | None = None
mm_token_type_ids: list[int] | None = None
+23 -9
View File
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Generic, Literal, Protocol
import verifiers.v1 as vf
from pydantic import ConfigDict, Field
from verifiers.v1.task import TaskT
from verifiers.v1.task import DataT
from prime_rl.transport import TrainingSample
@@ -69,12 +69,12 @@ class GroupState:
policy_version_at_start: int = 0
class Rollout(vf.Trace[TaskT], Generic[TaskT]):
class Rollout(vf.Trace[DataT], Generic[DataT]):
"""A completed rollout: the env's typed ``vf.Trace`` *is* the rollout — prime-rl's
orchestration metadata lives on it directly (set by the dispatcher once the rollout
returns), so there's no wrapper. Train vs eval is the ``kind`` discriminator. All metadata
fields are ``exclude=True``, so dumping a Rollout yields a plain trace — the on-disk
``results.jsonl`` is unchanged.
fields are ``exclude=True``, so dumping a Rollout yields a plain trace on the wire;
:meth:`to_record` adds the small metadata fields back for the on-disk trace files.
It is also the single currency the scoring hooks receive: a hook reads the trace
directly (``rollout.reward``, ``rollout.nodes``, ``rollout.num_turns``) and writes
@@ -98,6 +98,19 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
filter_results: dict[str, bool] = Field(default_factory=dict, exclude=True)
eval_step: int | None = Field(default=None, exclude=True)
def to_record(self) -> dict:
"""The plain trace record plus the orchestration metadata (excluded from the pydantic
dump), so a record stays fully placeable — kind, env, policy — even when trace files
are merged or read away from their paths. ``eval_step`` is the eval trigger step (None
for train rollouts)."""
return super().to_record() | {
"kind": self.kind,
"env_name": self.env_name,
"group_id": str(self.group_id),
"policy_version": self.policy_version,
"eval_step": self.eval_step,
}
def assign_advantages(self, values: float | list[float]) -> None:
"""Write the rl advantage stream: a scalar broadcast over the
rollout's trainable (mask-True) tokens (0.0 elsewhere), or a per-token
@@ -134,11 +147,12 @@ class Rollout(vf.Trace[TaskT], Generic[TaskT]):
@dataclass
class TrainBatch:
"""``rollouts`` is the full arrival window since the last ship (errored + filtered included; its
``.effective`` / ``.metrics`` views drive logging). ``samples`` is the trainer-bound payload (the
shipped cohort's post-filter survivors) — an empty list means nothing ships, which would stall the
trainer. Trainable counts derive from ``rollouts`` (``r.is_trainable``) and token totals from
``samples``, so neither is carried as a field."""
"""``rollouts`` is the observation window since the last ship — every rollout of every group
finalized in that span (errored + filtered included; rollouts of still-incomplete groups wait
for a later window). Its ``.effective`` / ``.metrics`` views drive logging. ``samples`` is the
trainer-bound payload (the shipped cohort's post-filter survivors) — an empty list means nothing
ships, which would stall the trainer. Trainable counts derive from ``rollouts``
(``r.is_trainable``) and token totals from ``samples``, so neither is carried as a field."""
rollouts: TrainRollouts
samples: list[TrainingSample]
+4 -2
View File
@@ -51,10 +51,12 @@ async def setup_policy_inference_pool(*, config: OrchestratorConfig, tokenizer):
def save_rollouts(rollouts: list[dict], path: Path) -> None:
"""Save rollouts (Trace dicts, already JSON-serializable) to a JSONL file."""
"""Append rollouts (Trace record dicts, already JSON-serializable) to a JSONL file.
The trace streams are append-only: ``all`` grows one rollout at a time as they
complete, ``effective`` one batch at a time on finalize."""
path.parent.mkdir(parents=True, exist_ok=True)
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "wb") as f:
with open(path, "ab") as f:
for rollout in rollouts:
f.write(orjson.dumps(rollout, default=str, option=opts))
+4 -4
View File
@@ -34,8 +34,8 @@ export NUM_DECODE_NODES={{ num_decode_nodes }}
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
export NODES_PER_REPLICA=$((NUM_PREFILL_NODES + NUM_DECODE_NODES))
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
export ROUTER_PORT={{ router.port }}
@@ -67,10 +67,10 @@ source .venv/bin/activate
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras
uv sync --all-extras --all-packages
{% endif %}
# Print inference URLs
@@ -41,8 +41,8 @@ export NUM_PREFILL_NODES={{ num_prefill_nodes }}
export NUM_DECODE_NODES={{ num_decode_nodes }}
export NUM_PREFILL_REPLICAS={{ num_prefill_replicas }}
export NUM_DECODE_REPLICAS={{ num_decode_replicas }}
export NODES_PER_PREFILL_REPLICA=$((NUM_PREFILL_NODES / NUM_PREFILL_REPLICAS))
export NODES_PER_DECODE_REPLICA=$((NUM_DECODE_NODES / NUM_DECODE_REPLICAS))
export NODES_PER_PREFILL_REPLICA={{ prefill_nodes_per_replica }}
export NODES_PER_DECODE_REPLICA={{ decode_nodes_per_replica }}
export PREFILL_PORT={{ prefill_port }}
export DECODE_PORT={{ decode_port }}
{%- if router.type == "llm-d" %}
@@ -150,10 +150,10 @@ source .venv/bin/activate
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
uv sync --all-extras
uv sync --all-extras --all-packages
{% endif %}
{% if pre_run_command %}
@@ -54,10 +54,10 @@ source $PROJECT_DIR/.venv/bin/activate
# all finish. `set -e` above aborts the job if any node's sync fails. Re-source .env
# inside the task because unexported vars in .env don't cross srun even with normal
# SLURM env propagation; otherwise uv would silently fall back to the shared .venv.
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras'
srun --ntasks-per-node=1 bash -c 'cd $PROJECT_DIR && { [ -f .env ] && source .env || true; } && uv sync --all-extras --all-packages'
{% else %}
# Shared (NFS) venv: one sync on the batch node populates it for all nodes.
cd $PROJECT_DIR && uv sync --all-extras
cd $PROJECT_DIR && uv sync --all-extras --all-packages
{% endif %}
@@ -31,7 +31,7 @@ export PROJECT_DIR={{ project_dir }}
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
uv sync --all-extras --all-packages
{% if pre_run_command %}
# Pre-run command
@@ -31,7 +31,7 @@ export PROJECT_DIR={{ project_dir }}
cd $PROJECT_DIR
[ -f .env ] && source .env
source .venv/bin/activate
uv sync --all-extras
uv sync --all-extras --all-packages
{% if pre_run_command %}
# Pre-run command
+7 -5
View File
@@ -834,19 +834,21 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
# All ranks read just the key names (cheap) to determine the path independently.
# Only master loads the full state dict when conversion is actually needed.
if isinstance(model, PreTrainedModelPrimeRL):
snapshot_keys = dict.fromkeys(load_state_dict_keys(snapshot_path))
source_path = snapshot_path
convert_dir = config.conversion_dir or source_path
snapshot_keys = dict.fromkeys(load_state_dict_keys(source_path))
model_keys = dict.fromkeys(model.state_dict().keys())
if model.is_hf_state_dict(snapshot_keys) and model.is_prime_state_dict(model_keys):
logger.warning(
"Found HF weight format in snapshot state dict and PrimeRL weight format in model state dict. Trying to auto-convert..."
)
snapshot_path = snapshot_path / "prime"
snapshot_path = convert_dir / "prime"
if not snapshot_path.exists() and get_world().is_master:
logger.debug(
f"Converting snapshot state dict to PrimeRL format and saving to {snapshot_path} on master rank. This is a one-time operation."
)
snapshot_state_dict = load_state_dict(snapshot_path.parent)
snapshot_state_dict = load_state_dict(source_path)
model.convert_to_prime(snapshot_state_dict)
save_state_dict(snapshot_state_dict, snapshot_path)
del snapshot_state_dict
@@ -855,12 +857,12 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
logger.warning(
"Found PrimeRL weight format in snapshot state dict and HF weight format in model state dict. Trying to auto-convert..."
)
snapshot_path = snapshot_path / "hf"
snapshot_path = convert_dir / "hf"
if not snapshot_path.exists() and get_world().is_master:
logger.debug(
f"Converting snapshot state dict to HF format and saving to {snapshot_path} on master rank. This is a one-time operation."
)
snapshot_state_dict = load_state_dict(snapshot_path.parent)
snapshot_state_dict = load_state_dict(source_path)
model.convert_to_hf(snapshot_state_dict)
save_state_dict(snapshot_state_dict, snapshot_path)
del snapshot_state_dict
+4
View File
@@ -8,6 +8,7 @@ from transformers.models.auto.auto_factory import _BaseAutoModelClass, _LazyAuto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES
from transformers.models.llama.configuration_llama import LlamaConfig
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
from prime_rl.trainer.models.afmoe import AfmoeConfig, AfmoeForCausalLM
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
@@ -20,6 +21,7 @@ from prime_rl.trainer.models.llama import LlamaForCausalLM
from prime_rl.trainer.models.minimax_m2 import MiniMaxM2Config, MiniMaxM2ForCausalLM
from prime_rl.trainer.models.nemotron_h import NemotronHConfig, NemotronHForCausalLM
from prime_rl.trainer.models.qwen3 import Qwen3ForCausalLM
from prime_rl.trainer.models.qwen3_5 import Qwen3_5ForCausalLM
from prime_rl.trainer.models.qwen3_5_moe import Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM
from prime_rl.trainer.models.qwen3_moe import Qwen3MoeConfig, Qwen3MoeForCausalLM
@@ -31,6 +33,7 @@ AutoConfig.register("laguna", LagunaConfig, exist_ok=True)
AutoConfig.register("minimax_m2", MiniMaxM2Config, exist_ok=True)
AutoConfig.register("nemotron_h", NemotronHConfig, exist_ok=True)
AutoConfig.register("qwen3_moe", Qwen3MoeConfig, exist_ok=True)
AutoConfig.register("qwen3_5_text", Qwen3_5TextConfig, exist_ok=True)
AutoConfig.register("qwen3_5_moe_text", Qwen3_5MoeConfig, exist_ok=True)
# GptOssConfig is just HF's class - already registered by transformers, no override needed.
@@ -44,6 +47,7 @@ _CUSTOM_CAUSAL_LM_MAPPING.register(LagunaConfig, LagunaForCausalLM, exist_ok=Tru
_CUSTOM_CAUSAL_LM_MAPPING.register(MiniMaxM2Config, MiniMaxM2ForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(NemotronHConfig, NemotronHForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3MoeConfig, Qwen3MoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5TextConfig, Qwen3_5ForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(Qwen3_5MoeConfig, Qwen3_5MoeForCausalLM, exist_ok=True)
_CUSTOM_CAUSAL_LM_MAPPING.register(GptOssConfig, GptOssForCausalLM, exist_ok=True)
@@ -249,7 +249,7 @@ def _grouped_per_token_fp8_kernel(
@triton.jit
def _grouped_per_channel_fp8_sm90_kmajor_kernel(
def _grouped_per_channel_fp8_kernel(
x_ptr,
block_to_group_ptr,
starts_ptr,
@@ -264,6 +264,7 @@ def _grouped_per_channel_fp8_sm90_kmajor_kernel(
stride_sf0,
stride_sf1,
USE_UE8M0: tl.constexpr,
K_MAJOR: tl.constexpr,
BLOCK_K: tl.constexpr,
BLOCK_N: tl.constexpr,
):
@@ -293,8 +294,20 @@ def _grouped_per_channel_fp8_sm90_kmajor_kernel(
scale = tl.exp2(tl.ceil(tl.log2(scale)))
y = x / scale[None, :]
flat_base = block_start.to(tl.int64) * BLOCK_K * cols
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
tl.store(out_ptrs, tl.trans(y).to(tl.float8e4nv), mask=valid_cols[:, None] & (row_offsets[None, :] < aligned_m))
if K_MAJOR:
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
tl.store(
out_ptrs,
tl.trans(y).to(tl.float8e4nv),
mask=valid_cols[:, None] & (row_offsets[None, :] < aligned_m),
)
else:
out_ptrs = out_ptr + flat_base + row_offsets_i64[:, None] * cols + col_offsets_i64[None, :]
tl.store(
out_ptrs,
y.to(tl.float8e4nv),
mask=(row_offsets[:, None] < aligned_m) & valid_cols[None, :],
)
tl.store(
sf_ptr + pid_blk * stride_sf0 + col_offsets_i64 * stride_sf1,
scale,
@@ -477,7 +490,7 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
if block_to_group.numel() == 0:
return out, sf.T
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
_grouped_per_channel_fp8_sm90_kmajor_kernel[grid](
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
starts_tensor,
@@ -492,6 +505,7 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
K_MAJOR=True,
BLOCK_K=gran_k,
BLOCK_N=128,
num_warps=4,
@@ -499,6 +513,48 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
return out, sf.T
def grouped_per_channel_cast_to_fp8_rowmajor_triton(
x: torch.Tensor,
padded_total_m: int,
block_to_group: torch.Tensor,
starts_tensor: torch.Tensor,
actual_ms_tensor: torch.Tensor,
ks_tensor: torch.Tensor,
block_starts_tensor: torch.Tensor,
use_ue8m0: bool,
gran_k: int = GROUP_ALIGNMENT,
) -> Tuple[torch.Tensor, torch.Tensor]:
assert x.dim() == 2
assert gran_k == GROUP_ALIGNMENT
out = torch.empty((padded_total_m, x.size(1)), device=x.device, dtype=torch.float8_e4m3fn)
total_blocks = padded_total_m // gran_k
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
if block_to_group.numel() == 0:
return out, sf
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
_grouped_per_channel_fp8_kernel[grid](
x,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
out,
sf,
x.size(1),
x.stride(0),
x.stride(1),
sf.stride(0),
sf.stride(1),
USE_UE8M0=use_ue8m0,
K_MAJOR=False,
BLOCK_K=gran_k,
BLOCK_N=128,
num_warps=4,
)
return out, sf
def grouped_per_block_cast_to_fp8_triton(
x: torch.Tensor, use_ue8m0: bool, gran_k: int = GROUP_ALIGNMENT
) -> Tuple[torch.Tensor, torch.Tensor]:
@@ -340,3 +340,7 @@ def substitute_ring_attn(
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import Qwen3_5MoeGatedFlashAttention
Qwen3_5MoeGatedFlashAttention._compute_attention = _ring_compute_attention
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
Qwen3_5GatedFlashAttention._compute_attention = _ring_compute_attention
+54 -13
View File
@@ -18,6 +18,45 @@ import torch
import torch.distributed as dist
def _build_seq_idx(boundaries: list[int], seq_len: int, device: torch.device) -> torch.Tensor:
"""Return the packed-document id for each token in a full CP sequence."""
if boundaries[0] != 0 or boundaries[-1] != seq_len:
raise ValueError(f"cu_seqlens must span the full sequence length {seq_len}, got {boundaries}")
seq_idx = torch.empty(seq_len, dtype=torch.int32, device=device)
for sequence_id, (start, end) in enumerate(zip(boundaries[:-1], boundaries[1:])):
if end <= start:
raise ValueError(f"cu_seqlens must be strictly increasing, got {boundaries}")
seq_idx[start:end] = sequence_id
return seq_idx.unsqueeze(0)
def _causal_conv1d_varlen(
hidden_states: torch.Tensor,
weight: torch.Tensor,
bias: torch.Tensor | None,
boundaries: list[int],
) -> torch.Tensor:
"""Apply a depthwise causal convolution independently to packed documents."""
batch_size, _, channels = hidden_states.shape
if batch_size != 1:
raise ValueError(f"packed CP Mamba expects batch_size=1, got {batch_size}")
inputs = hidden_states.transpose(1, 2)
outputs = []
for start, end in zip(boundaries[:-1], boundaries[1:]):
convolved = torch.nn.functional.conv1d(
inputs[:, :, start:end],
weight,
bias,
groups=channels,
padding=weight.shape[2] - 1,
)
outputs.append(convolved[:, :, : end - start])
return torch.cat(outputs, dim=-1).transpose(1, 2)
class _SeqToHeadParallel(torch.autograd.Function):
"""[B, S/cp, D] -> [B, S, D/cp] via all-to-all."""
@@ -93,7 +132,14 @@ def head_to_seq_parallel(x: torch.Tensor, cp_group: dist.ProcessGroup, cp_size:
return _HeadToSeqParallel.apply(x, cp_group, cp_size)
def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessGroup, cp_rank: int, cp_size: int):
def mamba_cp_forward(
mixer,
hidden_states: torch.Tensor,
cp_group: dist.ProcessGroup,
cp_rank: int,
cp_size: int,
cu_seqlens: torch.Tensor,
):
"""CP-aware Mamba-2 forward: in_proj -> all-to-all -> conv+SSM(local heads) -> all-to-all -> out_proj.
Replaces the mixer's cuda_kernels_forward when CP > 1. Parameters are
@@ -134,6 +180,8 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
hidden_states_B_C = torch.cat([x_part, B_part, C_part], dim=-1)
full_seq_len = hidden_states_B_C.shape[1] # S (full sequence)
boundaries = cu_seqlens.tolist()
seq_idx = _build_seq_idx(boundaries, full_seq_len, hidden_states.device)
# ── 3. Local head dimensions ──
local_num_heads = mixer.num_heads // cp_size
@@ -151,7 +199,6 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
# Slice conv1d weight/bias for local channels
# conv1d channels = intermediate_size + 2 * ngroups * dstate (same as conv_dim)
# After all-to-all, we have local channels: local_intermediate + 2 * local_ngroups * dstate
local_conv_dim = local_intermediate_size + 2 * local_n_groups * mixer.ssm_state_size
conv_x_start = cp_rank * local_intermediate_size
conv_x_end = conv_x_start + local_intermediate_size
conv_b_start = mixer.intermediate_size + cp_rank * local_n_groups * mixer.ssm_state_size
@@ -169,15 +216,9 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
local_conv_weight = mixer.conv1d.weight[conv_indices]
local_conv_bias = mixer.conv1d.bias[conv_indices] if mixer.conv1d.bias is not None else None
# ── 4. Conv1d on full sequence, local heads ──
# ── 4. Conv1d on each packed document, local heads ──
hidden_states_B_C = torch.nn.functional.silu(
torch.nn.functional.conv1d(
hidden_states_B_C.transpose(1, 2),
local_conv_weight,
local_conv_bias,
groups=local_conv_dim,
padding=mixer.conv1d.weight.shape[2] - 1,
).transpose(1, 2)[:, :full_seq_len]
_causal_conv1d_varlen(hidden_states_B_C, local_conv_weight, local_conv_bias, boundaries)
)
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
@@ -190,7 +231,7 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
# ── 5. SSM scan on full sequence, local heads ──
dt_limit_kwargs = {} if mixer.time_step_limit is None else {"dt_limit": mixer.time_step_limit}
scan_output, _ = mamba_chunk_scan_combined(
scan_output = mamba_chunk_scan_combined(
hidden_states_local.view(batch_size, full_seq_len, local_num_heads, mixer.head_dim),
time_step,
local_A,
@@ -199,8 +240,8 @@ def mamba_cp_forward(mixer, hidden_states: torch.Tensor, cp_group: dist.ProcessG
chunk_size=mixer.chunk_size,
D=local_D,
z=None,
seq_idx=None,
return_final_states=True,
seq_idx=seq_idx,
return_final_states=False,
dt_bias=local_dt_bias,
dt_softplus=True,
**dt_limit_kwargs,
@@ -1,17 +1,19 @@
from __future__ import annotations
import torch
try:
import deep_gemm
except ImportError:
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
# are GPU-only at runtime, so leaving the symbol None is safe — only the
# autograd Function bodies below actually call into it.
import torch
from prime_rl.trainer.models.kernels.fp8_utils import (
GROUP_ALIGNMENT,
build_grouped_layout,
grouped_per_block_cast_to_fp8_triton,
grouped_per_channel_cast_to_fp8_rowmajor_triton,
grouped_per_channel_cast_to_fp8_sm90_kmajor_triton,
grouped_per_token_cast_to_fp8_triton,
unpack_rows_triton,
@@ -30,32 +32,60 @@ def _compute_grad_weight(
block_starts_tensor: torch.Tensor,
aligned_ms: list[int],
) -> torch.Tensor:
x_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
x,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
False,
GROUP_ALIGNMENT,
)
dy_k_major = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
False,
GROUP_ALIGNMENT,
)
is_sm100 = torch.cuda.get_device_capability(x.device)[0] >= 10
if is_sm100:
x_fp8 = grouped_per_channel_cast_to_fp8_rowmajor_triton(
x,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
GROUP_ALIGNMENT,
)
dy_fp8 = grouped_per_channel_cast_to_fp8_rowmajor_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
GROUP_ALIGNMENT,
)
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_tn_contiguous
else:
x_fp8 = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
x,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
GROUP_ALIGNMENT,
)
dy_fp8 = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
grad_output,
padded_total_m,
block_to_group,
starts_tensor,
actual_ms_tensor,
ks_tensor,
block_starts_tensor,
True,
GROUP_ALIGNMENT,
)
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_nt_contiguous
grad_weight = torch.zeros(weight_shape, device=x.device, dtype=torch.float32)
deep_gemm.k_grouped_fp8_gemm_nt_contiguous(
x_k_major,
dy_k_major,
grouped_weight_grad(
x_fp8,
dy_fp8,
grad_weight,
aligned_ms,
ks_tensor,
@@ -90,12 +120,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
False,
True,
GROUP_ALIGNMENT,
)
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
weight.transpose(1, 2),
False,
True,
GROUP_ALIGNMENT,
)
@@ -174,12 +204,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
starts_tensor,
actual_ms_tensor,
block_starts_tensor,
False,
True,
GROUP_ALIGNMENT,
)
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
weight,
False,
True,
GROUP_ALIGNMENT,
)
grad_x_padded = torch.empty(
@@ -2,14 +2,15 @@ from __future__ import annotations
import re
import torch
from torch import nn
try:
import deep_gemm
except ImportError:
deep_gemm = None # CPU-only environments don't ship deep_gemm; FP8 paths
# are GPU-only at runtime, so leaving the symbol None is safe — only the
# autograd Function bodies below actually call into it.
import torch
from torch import nn
from prime_rl.trainer.models.kernels.fp8_utils import (
per_block_cast_to_fp8_tp_triton,
@@ -25,8 +26,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
x_shape = x.shape
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
x_fp8 = per_token_cast_to_fp8_triton(x_2d, False, block_size)
weight_fp8 = per_block_cast_to_fp8_triton(weight, False, block_size)
x_fp8 = per_token_cast_to_fp8_triton(x_2d, True, block_size)
weight_fp8 = per_block_cast_to_fp8_triton(weight, True, block_size)
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
@@ -44,8 +45,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
grad_x = grad_weight = None
if ctx.needs_input_grad[0]:
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, False, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, False, block_size)
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, True, block_size)
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, True, block_size)
grad_x_2d = torch.empty_like(x_2d)
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
grad_x = grad_x_2d.reshape(ctx.x_shape)
@@ -63,8 +64,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
else:
grad_output_2d_padded = grad_output_2d
x_2d_padded = x_2d
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, False, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, False, block_size)
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, True, block_size)
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, True, block_size)
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
deep_gemm.fp8_gemm_nt(
grad_output_t_fp8,
@@ -82,7 +83,7 @@ class Float8BlockwiseLinear(nn.Linear):
"""nn.Linear replacement that uses FP8 blockwise matmul via DeepGEMM.
Requires:
- SM90 (Hopper) GPU
- SM90 (Hopper) or SM100 (Blackwell) GPU
- bfloat16 inputs/weights
- No bias
- in_features and out_features divisible by 128
@@ -238,8 +238,9 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
vocab = weight.shape[0]
vocab_chunk_size = min(vocab, 8192)
grad_hidden = torch.zeros_like(hidden)
grad_weight = torch.zeros_like(weight)
needs_hidden, needs_weight = ctx.needs_input_grad[0], ctx.needs_input_grad[1]
grad_hidden = torch.zeros_like(hidden) if needs_hidden else None
grad_weight = torch.zeros_like(weight) if needs_weight else None
for start in range(0, n, chunk_size):
end = min(start + chunk_size, n)
@@ -263,8 +264,10 @@ class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function):
grad_logits[mask, idx] += grad_chunk[mask]
grad_logits = grad_logits * inv_t_chunk
grad_hidden[start:end].add_(grad_logits.to(hidden.dtype) @ weight_chunk)
grad_weight[vocab_start:vocab_end].add_(grad_logits.to(weight.dtype).t() @ hidden_chunk)
if needs_hidden:
grad_hidden[start:end].add_(grad_logits.to(hidden.dtype) @ weight_chunk)
if needs_weight:
grad_weight[vocab_start:vocab_end].add_(grad_logits.to(weight.dtype).t() @ hidden_chunk)
return grad_hidden, grad_weight, None, None, None
@@ -189,6 +189,10 @@ def substitute_ulysses_attn(
Qwen3_5MoeGatedFlashAttention._compute_attention = _ulysses_compute_attention
from prime_rl.trainer.models.qwen3_5.modeling_qwen3_5 import Qwen3_5GatedFlashAttention
Qwen3_5GatedFlashAttention._compute_attention = _ulysses_compute_attention
def substitute_hf_ulysses_attn(process_group: dist.ProcessGroup) -> None:
"""Patch HF's `_flash_attention_forward` to use Ulysses all-to-all + local FA2.
@@ -23,6 +23,7 @@ from prime_rl.trainer.models.layers.cp_mamba import mamba_cp_forward
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import LatentMoE, NemotronHRouter, NonGatedGroupedExperts
from prime_rl.trainer.models.layers.rms_norm import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
from prime_rl.trainer.models.nemotron_h.configuration_nemotron_h import NemotronHConfig
from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import (
convert_hf_layer_to_prime,
@@ -229,9 +230,15 @@ class NemotronHMambaLayer(GradientCheckpointingLayer):
hidden_states = self.norm(hidden_states)
if self.cp_enabled:
# TODO: This path doesnt support cu_seqlens so packing makes it wrong
# The local cu_seqlens cover only this shard; conv/scan need the full
# pre-shard document boundaries published by setup_cp_params.
hidden_states = mamba_cp_forward(
self.mamba, hidden_states, self._cp_group, self._cp_rank, self._cp_world_size
self.mamba,
hidden_states,
self._cp_group,
self._cp_rank,
self._cp_world_size,
ULYSSES_PARAMS["cu_seqlens"],
)
else:
hidden_states = self.mamba(hidden_states, cu_seqlens=cu_seqlens)
@@ -0,0 +1,3 @@
from .modeling_qwen3_5 import Qwen3_5ForCausalLM, Qwen3_5Model, Qwen3_5PreTrainedModel
__all__ = ["Qwen3_5ForCausalLM", "Qwen3_5Model", "Qwen3_5PreTrainedModel"]
@@ -0,0 +1,305 @@
import functools
from typing import Optional, Union
import torch
from torch import Tensor, nn
from transformers.cache_utils import Cache
from transformers.generation import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutputWithPast
from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfig
from transformers.models.qwen3_5.modeling_qwen3_5 import (
Qwen3_5PreTrainedModel as HFQwen3_5PreTrainedModel,
)
from transformers.processing_utils import Unpack
from transformers.utils import TransformersKwargs
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
from prime_rl.trainer.models.qwen3_5_moe.modeling_qwen3_5_moe import (
Qwen3_5MoeGatedAttentionConfig,
Qwen3_5MoeGatedDeltaNet,
Qwen3_5MoeGatedFlashAttention,
Qwen3_5MoeGatedSDPAAttention,
Qwen3_5MoeRMSNorm,
Qwen3_5MoeRotaryEmbedding,
normalize_qwen3_5_attn_implementation,
)
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
class Qwen3_5GatedSDPAAttention(Qwen3_5MoeGatedSDPAAttention):
pass
class Qwen3_5GatedFlashAttention(Qwen3_5MoeGatedFlashAttention):
pass
QWEN35_ATTN_IMPL2CLASS = {
"sdpa": Qwen3_5GatedSDPAAttention,
"flash_attention_2": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=2),
"flash_attention_3": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=3),
"fa4": functools.partial(Qwen3_5GatedFlashAttention, flash_attn_version=4),
}
def _get_gated_attention(config: Qwen3_5TextConfig) -> nn.Module:
attn_config = Qwen3_5MoeGatedAttentionConfig(
hidden_size=config.hidden_size,
head_dim=config.head_dim,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
rms_norm_eps=config.rms_norm_eps,
attention_bias=config.attention_bias,
attention_dropout=config.attention_dropout,
)
attn_impl = normalize_qwen3_5_attn_implementation(config._attn_implementation)
config._attn_implementation = attn_impl
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
raise ValueError(
f"Qwen3.5 attention does not support '{config._attn_implementation}'. "
f"Supported implementations: {supported}."
)
return QWEN35_ATTN_IMPL2CLASS[attn_impl](attn_config)
def _create_rotary_emb(config: Qwen3_5TextConfig) -> Qwen3_5MoeRotaryEmbedding:
return Qwen3_5MoeRotaryEmbedding(config)
class Qwen3_5DecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: Qwen3_5TextConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.layer_type = config.layer_types[layer_idx]
if self.layer_type == "linear_attention":
self.linear_attn = Qwen3_5MoeGatedDeltaNet(config)
elif self.layer_type == "full_attention":
self.self_attn = _get_gated_attention(config)
else:
raise ValueError(f"Unsupported Qwen3.5 layer type: {self.layer_type}")
mlp_config = MLPConfig(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
gate_act=config.hidden_act,
bias=False,
)
self.mlp = MLP(mlp_config)
self.input_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
cu_seqlens: torch.LongTensor | None = None,
max_seqlen: int | None = None,
) -> torch.FloatTensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
if self.layer_type == "linear_attention":
hidden_states = self.linear_attn(hidden_states, cu_seqlens=cu_seqlens)
else:
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
return residual + hidden_states
class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
config_class = Qwen3_5TextConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen3_5DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = False
_supports_attention_backend = True
_can_compile_fullgraph = False
_can_record_outputs = {
"hidden_states": Qwen3_5DecoderLayer,
}
def _check_and_adjust_attn_implementation(
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
) -> str:
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
if attn_impl not in QWEN35_ATTN_IMPL2CLASS:
supported = list(QWEN35_ATTN_IMPL2CLASS.keys())
raise ValueError(
f"Qwen3.5 attention does not support '{attn_implementation}'. Supported implementations: {supported}."
)
return attn_impl
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
@classmethod
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return True
@classmethod
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_to_prime(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_hf(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
@classmethod
def convert_layer_to_prime(cls, state_dict: dict[str, Tensor], layer_idx: int) -> dict[str, Tensor]:
return state_dict
class Qwen3_5Model(Qwen3_5PreTrainedModel):
def __init__(self, config: Qwen3_5TextConfig):
config._attn_implementation = normalize_qwen3_5_attn_implementation(config._attn_implementation)
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[Qwen3_5DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = Qwen3_5MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = _create_rotary_emb(config)
self.gradient_checkpointing = False
self.post_init()
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
if position_ids is None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
flash_attn_enabled = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
if flash_attn_enabled:
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
torch._dynamo.mark_dynamic(cu_seqlens, 0)
else:
cu_seqlens = None
max_seqlen = None
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
for decoder_layer in self.layers:
hidden_states = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_checkpoint_conversion_mapping = {}
_tp_plan = {"lm_head": "colwise_gather_output"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config, **kwargs):
super().__init__(config, **kwargs)
self.model = Qwen3_5Model(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self):
return self.model.embed_tokens
def set_input_embeddings(self, value):
self.model.embed_tokens = value
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
temperature: Union[torch.Tensor, None] = None,
**kwargs: Unpack[TransformersKwargs],
) -> PrimeLmOutput:
assert use_cache is None, "use_cache is not supported for custom qwen3_5 for now"
assert past_key_values is None, "past_key_values is not supported for custom qwen3_5 for now"
if position_ids is None:
if inputs_embeds is not None:
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device).unsqueeze(0)
elif input_ids is not None:
position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
outputs = self.model(
input_ids=input_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
)
hidden_states = outputs.last_hidden_state
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
return self.lm_head(
hidden_states[:, slice_indices, :],
labels[:, slice_indices] if labels is not None else None,
temperature=temperature,
)
def init_buffers_post_meta(self):
lm_rope = self.model.rotary_emb
if hasattr(lm_rope, "rope_init_fn"):
inv_freq, lm_rope.attention_scaling = lm_rope.rope_init_fn(lm_rope.config, lm_rope.inv_freq.device)
lm_rope.inv_freq.copy_(inv_freq)
__all__ = [
"Qwen3_5ForCausalLM",
"Qwen3_5GatedFlashAttention",
"Qwen3_5Model",
"Qwen3_5PreTrainedModel",
]
@@ -24,6 +24,7 @@ from prime_rl.trainer.models.layers.attn import (
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
from prime_rl.trainer.models.layers.rotary_emb import apply_rotary_pos_emb
from prime_rl.trainer.models.layers.ulysses_attn import ULYSSES_PARAMS
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids, get_cu_seqlens_from_seq_lens
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
@@ -43,6 +44,7 @@ except ImportError:
try:
from fla.modules import FusedRMSNormGated
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
from fla.ops.cp import FLACPContext, build_cp_context
from fla.ops.gated_delta_rule import chunk_gated_delta_rule
except ImportError:
@@ -50,6 +52,7 @@ except ImportError:
FusedRMSNormGated = None # type: ignore
FLACPContext = None # type: ignore
build_cp_context = None # type: ignore
fla_causal_conv1d = None # type: ignore
logger = logging.get_logger(__name__)
@@ -233,16 +236,16 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
self._causal_conv1d_fn = causal_conv1d_fn
self._chunk_gated_delta_rule = chunk_gated_delta_rule or torch_chunk_gated_delta_rule
def _build_cp_context(self, local_seq_len: int, device: torch.device) -> "FLACPContext | None":
"""Build fla CP context from the local (sharded) sequence length."""
def _build_cp_context(self) -> "FLACPContext | None":
"""Build fla CP context from the full pre-shard document boundaries."""
cp_group = getattr(self, "cp_group", None)
if cp_group is None or build_cp_context is None:
return None
# Reconstruct global cu_seqlens: single contiguous sequence across all CP ranks
global_seq_len = local_seq_len * self.cp_world_size
global_cu_seqlens = torch.tensor([0, global_seq_len], dtype=torch.int32, device=device)
# Local cu_seqlens cannot describe documents straddling shard boundaries;
# use the full (un-sharded) cu_seqlens published by setup_cp_params. fla
# derives per-rank boundaries and document-aware state passing from them.
return build_cp_context(
cu_seqlens=global_cu_seqlens,
cu_seqlens=ULYSSES_PARAMS["cu_seqlens"],
group=cp_group,
conv1d_kernel_size=self.conv_kernel_size,
)
@@ -259,9 +262,23 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
b = self.in_proj_b(hidden_states)
a = self.in_proj_a(hidden_states)
cp_context = self._build_cp_context()
# Causal conv1d — must reset at sequence boundaries for packed batches,
# otherwise the kernel-1 left pad leaks state across sequences.
if self._causal_conv1d_fn is not None:
if cp_context is not None:
# fla's CP conv resets at the true document boundaries and exchanges
# tail tokens with the previous rank for documents straddling the
# shard boundary; the local cu_seqlens can express neither.
conv_out, _ = fla_causal_conv1d(
x=mixed_qkv.transpose(1, 2),
weight=self.conv1d.weight.squeeze(1),
bias=self.conv1d.bias,
activation=self.activation,
cp_context=cp_context,
)
mixed_qkv = conv_out.transpose(1, 2)
elif self._causal_conv1d_fn is not None:
seq_idx = None
if cu_seqlens is not None:
seg_lens = cu_seqlens[1:] - cu_seqlens[:-1]
@@ -303,7 +320,6 @@ class Qwen3_5MoeGatedDeltaNet(nn.Module):
key = key.repeat_interleave(self.num_v_heads // self.num_k_heads, dim=2)
# Use fla's native CP when available, otherwise fall back to PyTorch kernel
cp_context = self._build_cp_context(seq_len, hidden_states.device)
if cp_context is not None:
cu_seqlens = cp_context.cu_seqlens
core_attn_out, _ = self._chunk_gated_delta_rule(
@@ -551,6 +567,14 @@ QWEN35MOE_ATTN_IMPL2CLASS = {
}
def normalize_qwen3_5_attn_implementation(attn_impl: str) -> str:
if attn_impl == "eager":
return "sdpa"
if attn_impl == "kernels-community/vllm-flash-attn3":
return "flash_attention_3"
return attn_impl
# ---------------------------------------------------------------------------
# Decoder layer
# ---------------------------------------------------------------------------
@@ -567,9 +591,8 @@ def _get_gated_attention(config: Qwen3_5MoeConfig) -> nn.Module:
attention_dropout=config.attention_dropout,
)
attn_impl = config._attn_implementation
if attn_impl == "eager":
attn_impl = "sdpa"
attn_impl = normalize_qwen3_5_attn_implementation(config._attn_implementation)
config._attn_implementation = attn_impl
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
@@ -783,6 +806,17 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
"hidden_states": Qwen3_5MoeDecoderLayer,
}
def _check_and_adjust_attn_implementation(
self, attn_implementation: str | None, is_init_check: bool = False, allow_all_kernels: bool = False
) -> str:
attn_impl = normalize_qwen3_5_attn_implementation(attn_implementation or "sdpa")
if attn_impl not in QWEN35MOE_ATTN_IMPL2CLASS:
supported = list(QWEN35MOE_ATTN_IMPL2CLASS.keys())
raise ValueError(
f"Qwen3.5-MoE attention does not support '{attn_implementation}'. Supported implementations: {supported}."
)
return attn_impl
@classmethod
def is_hf_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
return any(
@@ -819,6 +853,7 @@ class Qwen3_5MoePreTrainedModel(PreTrainedModelPrimeRL):
class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
def __init__(self, config: Qwen3_5MoeConfig):
config._attn_implementation = normalize_qwen3_5_attn_implementation(config._attn_implementation)
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size

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