Compare commits

...
Author SHA1 Message Date
Matej SirovatkaandGitHub 618de8a511 Feat: retry/logging (#2673)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-30 19:52:27 -07:00
eead822cb3 chore(security): extend cooldown exempt list with first-party deps (#2668)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
prime-rl already had exclude-newer = "7 days" and a partial exempt list
for prime/prime-sandboxes/prime-tunnel/prime-evals. This PR extends the
exempt list with the other PrimeIntellect packages now in prime-rl's
`uv tree` closure: verifiers, renderers, prime-pydantic-config.

The exempt entries are scoped to packages actually in this project's
dep graph — the resolver ignores entries for packages it never sees.

Pins `required-version = ">=0.11.1"` so older uvs fail loudly instead
of silently parsing "7 days" as an RFC 3339 date and proceeding
*without* the cooldown — see uv#17908.

Lock regenerated. Five third-party env packages were rolled back by the
existing cooldown (opencode-cp/math/science/swe and mini-swe-agent-plus
each released in the past 7 days), confirming the cooldown is doing
real protection work, not just sitting as config.

Part 1 of 3 in a coordinated supply-chain hardening across PI repos.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-31 00:27:36 +02:00
Matej SirovatkaandGitHub aeaf4c44f1 Update BUGBOT.md with custom model requirements (#2672)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Added requirements for new custom models in PRs.

Signed-off-by: Matej Sirovatka <54212263+S1ro1@users.noreply.github.com>
2026-05-30 00:58:24 +02:00
241d8e931e feat: configurable grace period for SLURM multinode (#2670)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat: configurable grace period for SLURM cleanup

Add slurm.cleanup_grace_period_seconds (default 3600) so that when a
component exits — completion, crash, or SIGTERM — the multi-node RL and
inference sbatch teardown sends SIGTERM and then waits up to the grace
period for the remaining processes to exit before force-killing and
releasing the allocation. This gives in-flight work, notably trainer
checkpoint writes, a bounded window to flush. The wait ends as soon as
all processes exit, so it is only an upper bound; set to 0 for the
previous immediate force-kill behavior.

Closes #2664

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: rename cleanup_grace_period_seconds to cleanup_grace_period

Drop the _seconds suffix; the unit is documented in the field docstring.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: drop CHANGELOG entry for cleanup_grace_period

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: make cleanup grace actually cover cross-node teardown

The previous SIGTERM-then-wait approach didn't help the target case
(inference dies while the trainer is mid-checkpoint on another node):
that teardown is driven by `srun --kill-on-bad-exit=1`, which reaps the
trainer task via SLURM's own KillWait path and never runs our in-task
grace loop.

Instead, on a non-zero exit the failing node now stays alive (signalling
nothing) for the grace period before propagating the exit. Because
--kill-on-bad-exit only fires when a task exits, holding the failing
task keeps peer nodes' checkpointing trainers running untouched until
they flush. Clean (zero-exit) completion is unaffected.

Scope to multi_node_rl only; the inference-only template has no trainer
checkpoints to protect, so it reverts to immediate teardown.

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs: note cleanup_grace_period is multi-node RL only

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs: minimize cleanup_grace_period docstring

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 15:15:32 -07:00
rasdaniandGitHub f510ef62cb Fix multi-run checkpoint dispatch (#2661)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-28 14:27:10 -07:00
26cdf2ee1d chore(deps): bump renderers (offset-tokenizer config-build fallback for Laguna) (#2663)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bumps the deps/renderers submodule 89ab3f0 (v0.1.8.dev35) -> 35c2407
(v0.1.8.dev37), pulling in PrimeIntellect-ai/renderers#75: apply the
config-build fallback to ``_get_offset_tokenizer`` too.

#72 only wired the fallback into ``load_tokenizer``;
``_get_offset_tokenizer`` still called ``AutoTokenizer.from_pretrained``
directly to avoid the fastokens shim and so kept hitting HF's RoPE
validator on Laguna-family models. Every rollout through a hand-coded
renderer (LagunaXS2, Qwen35, ...) crashed with the same KeyError #72
was supposed to fix.

Verified end-to-end against poolside/Laguna-XS.2 with reverse-text:
two RL steps complete cleanly (reward 0.36 / 0.31, ~100 tok/sample);
the run then hits an unrelated single-GPU FSDP OOM on the 256-expert
trainer, which is a config-sizing issue, not the renderers bug.

Also pulls in renderers#74 (``message_tool_names`` field for per-message
tool attribution).

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 13:05:51 -07:00
Matej SirovatkaandGitHub ae748fd69d Support delta-only routed experts replay (#2632)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Support delta-only routed experts replay

* Pin routed experts replay dependencies

* fix(orchestrator): match longest active prefix in interleave_rollout
2026-05-28 03:00:20 +02:00
083127fe32 chore(config): remove unused sampling args (min_tokens, repetition_penalty, seed) (#2656)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Drop `min_tokens`, `repetition_penalty`, and `seed` from `TrainSamplingConfig`
and `EvalSamplingConfig`. They distorted the on-policy sampling distribution
(min_tokens suppressed natural EOS, repetition_penalty introduced
train/serve mismatch) or weren't pulling their weight (seed). Hard
deprecation — no migration window.

Closes #2655

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-27 16:50:50 -07:00
Varun SinghandGitHub b90aca4221 prevent path where expert biases are not loaded for afmoe (#2658)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* prevent path where expert biases are not loaded

* address bugbot
2026-05-27 16:11:45 -07:00
d3727060cb chore(deps): bump renderers (tokenizer config-build fallback for Laguna) (#2657)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Bumps the deps/renderers submodule 2ec28a8 (v0.1.8.dev28) -> 89ab3f0
(v0.1.8.dev35), pulling in PrimeIntellect-ai/renderers#72: when
AutoTokenizer.from_pretrained fails while building the model config
(e.g. HF RoPE validation rejecting nested rope_parameters for
poolside/Laguna-XS.2), fall back to loading the repo's self-contained
tokenizer.json directly. Fixes the tokenizer load crash for the Laguna
model series; loads under the fastokens fast path.

Re-locks uv.lock: renderers now floors openai-harmony at >=0.0.4 (renderers#69).

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 00:44:47 +02:00
1891771201 chore(config): remove wandb.shared shim; fix --no-wandb / --no-ckpt (#2654)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(config): remove wandb.shared deprecation shim

The ``SharedWandbConfig.deprecate_shared_field`` ``model_validator(mode="before")``
introduced in #2649 popped ``wandb.shared`` from input dicts with a
``FutureWarning`` so older configs that still set ``shared = true`` (or
``false``) kept loading.

The ``rl`` entrypoint always uses shared W&B mode now, the legacy split with
``-trainer`` / ``-orchestrator`` suffixes is gone, and the in-tree configs no
longer set ``shared``. Drop the shim so configs that still carry the field
fail loudly via the default ``extra = "forbid"`` instead of silently warning.

Docs and CHANGELOG updated.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(config): honor --no-wandb / --no-ckpt across shared and sub-configs

pydantic-config's CLI negation (``--no-wandb`` / ``--no-ckpt``) writes the
string ``"None"`` into the override dict, which only becomes real ``None``
later via ``BaseConfig._none_str_to_none``. ``RLConfig``'s subclass
``mode="before"`` validators run *before* that conversion, so the bare-block
enablement in ``propagate_shared_fields`` used to see the string and
re-enable ``trainer.wandb`` / ``orchestrator.wandb`` (or the ``ckpt`` pair)
with defaults — silently undoing the CLI's intent.

Tighten the bare-block check from ``get(key) is not None`` to
``isinstance(get(key), dict)``. A bare ``[wandb]`` block in TOML is ``{}``
(dict, still enables); ``--no-wandb`` produces ``"None"`` (string, now
correctly skipped). Same logic applies to ``ckpt``.

Verified end-to-end with ``cli(RLConfig, args=[..., "--no-wandb"])``:
``cfg.wandb``, ``cfg.trainer.wandb``, ``cfg.orchestrator.wandb`` are all
``None``. ``--wandb None`` and ``--no-ckpt`` behave the same. Bare
``[wandb] {}`` / ``[ckpt] {}`` blocks still enable the sub-configs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(changelog): drop --no-wandb fix entry

It's a bug fix, not a breaking config change, so it doesn't belong in
CHANGELOG.md (which documents breaking config changes only).

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(comment): trim bare-block enablement comment

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(wandb): drop legacy-mode reference; add AGENTS rule

``docs/`` should describe the current state of the codebase, not its
history. Strip the "the legacy split has been removed" sentence from
``docs/training.md`` — readers on ``main`` don't care that there used to
be a non-shared mode — and add a ``## Docs`` rule to ``AGENTS.md`` to
codify it.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(agents): trim docs rule

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-27 10:23:18 -07:00
10bc02c6dc fix(config): round-trip materialized RLConfig; deprecate wandb.shared (#2649)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(rl-config): accept matching shared/sub duplicates so materialized config round-trips

The single-node SLURM launcher (``rl_slurm`` for
``deployment.type == "single_node"``) dumps the fully-resolved ``RLConfig`` to
``<output_dir>/configs/rl.toml`` and the sbatch script re-runs
``uv run rl @ rl.toml``. ``propagate_shared_fields`` writes both shared keys
(``output_dir``, ``wandb.project``, ...) *and* the matching sub-config keys
(``trainer.output_dir``, ``orchestrator.wandb.project``, ...) during the
first-load propagation; ``model_dump`` preserves both. On re-load the
``if sub_set: conflict`` check fired even though both keys had the same
value — treating a no-op round-trip as ambiguity.

Tighten the check to ``if sub_set and sub != shared_value``: genuine
conflicts still raise (a CLI-shared override silently no-opping against
an inconsistent sub-config value still surfaces), but matching values are
accepted so the materialized config re-loads cleanly. ``output_dir`` and
``wandb.name`` compare against their *transformed* sub-config values
(``output_dir → /run_default`` and ``-trainer``/``-orchestrator``
suffixes in non-shared mode).

Verified end-to-end on the hendrycks-sanity example for all three RL
deployments: local dry-run, single-node SLURM (submitted job 21902 from the
materialized rl.toml — config re-loaded, all three subprocesses spawned,
wandb shared run id preserved across trainer + orchestrator), multi-node
SLURM dry-run (write_subconfigs path).

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(rl): deprecate wandb.shared, hardcode shared W&B mode

Shared W&B mode (single run for trainer + orchestrator) has been the default
on the rl entrypoint since #1330 and is the only mode anyone uses. The
non-shared mode — two separate runs suffixed ``-trainer`` /
``-orchestrator``, gated on ``wandb.shared = false`` — was kept around as
the legacy fallback and as the reason the validator's ``wandb.name``
propagation needed custom asymmetric ``expected``/conflict logic.

Drop the non-shared path:

* ``SharedWandbConfig.shared`` is removed from the schema. A
  ``mode="before"`` validator pops the field from input dicts with a
  ``FutureWarning`` so existing configs that still set ``shared = true``
  (or ``false``) keep loading.
* ``validate_shared_not_offline`` becomes ``validate_not_offline``:
  ``wandb.offline = true`` at the shared level is rejected because shared
  mode is always on and needs server connectivity. The escape hatch is to
  set ``offline`` per sub-config (``[trainer.wandb] offline = true``,
  ``[orchestrator.wandb] offline = true``).
* ``propagate_shared_fields`` collapses the ``wandb.name`` block into a
  plain ``propagate("wandb.name", "trainer.wandb.name",
  "orchestrator.wandb.name")``. The ``expected``/conflict-against-
  transformed-value machinery is gone; only ``output_dir`` still needs the
  custom block because of its asymmetric ``/run_default`` suffix.
* ``rl_local`` always sets ``WANDB_SHARED_MODE`` / ``WANDB_SHARED_RUN_ID``
  for subprocesses (no ``if config.wandb and config.wandb.shared`` gate).
* The multi-node SLURM template (``multi_node_rl.sbatch.j2``) drops the
  ``{% if wandb_shared %}`` gates and always exports the shared env vars
  + ``WANDB_SHARED_LABEL``. The ``wandb_shared`` template variable is
  removed from both call sites in ``rl_slurm``.
* Configs that still set ``shared = true`` (``configs/nemotron_debug``,
  ``configs/nemotron_4node``) are cleaned up.
* Docs + the runtime info log are updated.

Verified end-to-end on hendrycks-sanity (job 21919, single-node SLURM): the
materialized rl.toml round-trips through the validator, both trainer and
orchestrator log ``Using shared W&B mode (label=…, primary=…)``, and the
W&B run name is the verbatim shared name (no ``-trainer``/``-orchestrator``
suffix). 234 config-related unit tests pass.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-26 22:18:26 -07:00
28 changed files with 553 additions and 154 deletions
+2
View File
@@ -15,3 +15,5 @@ Config files live in:
- `src/prime_rl/configs/`
If breaking changes are detected without a corresponding `CHANGELOG.md` update, request that the author add an entry.
Any PR that introduces a new custom model must also provide a table showing mean KL mismatch across 20 steps on math environment on this new model with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not present, request the author to add such a table.
+4
View File
@@ -35,6 +35,10 @@ Namespaces are one honking great idea -- let's do more of those!
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
## Docs
- **Docs reflect `main`, not history**: `docs/` describes the current state of the codebase only. Don't mention removed/legacy fields, migration paths, or "this used to be X" anecdotes.
## Skills
Skills live in `skills/` and are symlinked to `.claude/skills/`. They teach agents how to handle specific workflows (e.g. starting the inference server, writing configs). When you make changes to the codebase, check if any skills need to be updated to stay accurate.
+2
View File
@@ -2,6 +2,8 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`sampling.min_tokens`, `sampling.repetition_penalty`, `sampling.seed` removed**: Dropped from both `TrainSamplingConfig` and `EvalSamplingConfig` (group-level `[orchestrator.train.sampling]` / `[orchestrator.eval.sampling]` and per-env `[[orchestrator.train.env.sampling]]` / `[[orchestrator.eval.env.sampling]]`). `min_tokens` suppressed natural EOS, `repetition_penalty` distorts the on-policy sampling distribution, and `seed` wasn't pulling its weight — none belonged on the supported config surface. Existing configs setting any of these must delete the field. Hard-deprecation, no migration window. (2026-05-27)
- **`wandb.shared` removed**: The deprecation shim that popped `wandb.shared` from input dicts with a `FutureWarning` (introduced in #2649) is gone. The `rl` entrypoint always uses shared W&B mode now, and existing configs that still set `wandb.shared = true` (or `false`) will fail validation. Drop the field from your config. (2026-05-27)
- **`max_async_level` and `strict_async_level` removed**: The async-execution semantics between trainer and orchestrator are now design invariants, not config knobs. The trainer always runs exactly one step ahead of inference, and the orchestrator always adopts the freshest checkpoint that doesn't violate the one-step barrier. The shared top-level `max_async_level`, the per-sub-config `trainer.max_async_level` / `orchestrator.max_async_level`, and `orchestrator.strict_async_level` have all been removed. Existing configs setting any of these must drop the field; the previous defaults (`max_async_level = 1`, `strict_async_level = false`) match the new hardcoded behavior. Bench mode no longer bypasses the weight-ckpt wait (the `int(1e9)` workaround is gone) and `multimodal/rl_color_codeword_feat_renderer.toml`'s prior `max_async_level = 0` (fully synchronous on-policy) is no longer expressible. (2026-05-25)
- **`teacher_inference` removed from RL entrypoint**: The `[teacher_inference]` config block and the `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` fields have been removed. The `rl` entrypoint now only manages the student-policy inference server. External teachers (used by OPD and local-vLLM SFT) must be started manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001 ...`) and pointed at via `[orchestrator.teacher.client]`. Existing configs using `[teacher_inference]` or `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` must drop those fields and bring up the teacher out-of-band. (2026-05-25)
- **`rollouts_per_example` → `group_size`**: The orchestrator-level field, the group-level `[orchestrator.eval]` field, and the per-env `[[orchestrator.eval.env]]` field have all been renamed. The old name still parses as a validation alias (in both TOML and CLI), so existing configs keep working without changes; new configs should prefer `group_size`. (2026-05-22)
-1
View File
@@ -18,7 +18,6 @@ level = "debug"
[wandb]
project = "sami_debug_nemotron"
name = "nemotron-120b-math"
shared = true
[weight_broadcast]
type = "nccl"
-1
View File
@@ -17,7 +17,6 @@ level = "debug"
[wandb]
project = "nemotron_sami_debug"
name = "nemotron-120b-math"
shared = true
[weight_broadcast]
type = "nccl"
+1 -1
+1 -1
+2 -1
View File
@@ -289,9 +289,10 @@ W&B is off by default. Enable with `--wandb`:
```bash
uv run rl @ rl.toml --wandb # default project, random name
uv run rl @ rl.toml --wandb.project my-proj --wandb.name run-42
uv run rl @ rl.toml --no-wandb # force-disable even if the TOML enables it
```
By default (`wandb.shared = true`) the trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Set `wandb.shared = false` (or pass `--no-wandb.shared`) to fall back to the legacy split — two runs suffixed `-trainer` and `-orchestrator`. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `wandb.offline = true`.
The trainer and orchestrator log into a **single shared W&B run**, so all metrics from both processes land in one place. Shared mode requires the W&B SDK ≥ 0.19.9 and is incompatible with `wandb.offline = true`.
By default, every 10 steps each process also logs a sample of prompts/completions (with rewards and advantages) and reward/advantage/entropy distributions as W&B tables. Tune via `--wandb.log-extras.interval` and `--wandb.log-extras.sample-ratio`, or disable subsets:
@@ -46,20 +46,11 @@ class TrainSamplingConfig(BaseConfig):
temperature: float = Field(1.0, ge=0)
"""Sampling temperature."""
repetition_penalty: float = Field(1.0, ge=0)
"""Repetition penalty. Values > 1.0 discourage repetition, < 1.0 encourage it, 1.0 disables."""
max_completion_tokens: int | None = Field(
None, validation_alias=AliasChoices("max_completion_tokens", "max_tokens")
)
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""
min_tokens: int = Field(0, ge=0)
"""Minimum output tokens per sequence."""
seed: int | None = None
"""Random seed for sampling. If None, no seeding is used."""
# Strictly speaking, extra_body is not a sampling parameter, but it is the
# easiest way to pass arbitrary extra parameters to the server via verifiers
extra_body: dict[str, Any] = {}
@@ -67,7 +58,6 @@ class TrainSamplingConfig(BaseConfig):
def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict, omitting None values."""
# Top-level OAI params
args: dict[str, Any] = {
"temperature": self.temperature,
"top_p": 1.0,
@@ -75,17 +65,9 @@ class TrainSamplingConfig(BaseConfig):
}
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens
if self.seed is not None:
args["seed"] = self.seed
# vLLM extra_body params
extra_body = dict(self.extra_body)
if self.min_tokens > 0:
extra_body["min_tokens"] = self.min_tokens
if self.repetition_penalty != 1.0:
extra_body["repetition_penalty"] = self.repetition_penalty
if extra_body:
args["extra_body"] = extra_body
if self.extra_body:
args["extra_body"] = dict(self.extra_body)
return args
@@ -106,9 +88,6 @@ class EvalSamplingConfig(BaseConfig):
temperature: float | None = Field(None, ge=0)
"""Sampling temperature. None defers to the inference server default."""
repetition_penalty: float | None = Field(None, ge=0)
"""Repetition penalty. None defers to the inference server default."""
top_p: float | None = None
"""Nucleus sampling threshold. None defers to the inference server default."""
@@ -123,15 +102,9 @@ class EvalSamplingConfig(BaseConfig):
)
"""Maximum output tokens per turn. None defers to the inference server default."""
min_tokens: int | None = Field(None, ge=0)
"""Minimum output tokens per sequence. None defers to the inference server default."""
reasoning_effort: Literal["minimal", "low", "medium", "high"] | None = None
"""Reasoning effort constraint for reasoning models."""
seed: int | None = None
"""Random seed for sampling. None means no seeding."""
extra_body: dict[str, Any] = {}
"""Extra body parameters forwarded to the inference server."""
@@ -146,18 +119,12 @@ class EvalSamplingConfig(BaseConfig):
args["max_completion_tokens"] = self.max_completion_tokens
if self.reasoning_effort is not None:
args["reasoning_effort"] = self.reasoning_effort
if self.seed is not None:
args["seed"] = self.seed
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if self.min_p is not None:
extra_body["min_p"] = self.min_p
if self.min_tokens is not None:
extra_body["min_tokens"] = self.min_tokens
if self.repetition_penalty is not None:
extra_body["repetition_penalty"] = self.repetition_penalty
if extra_body:
args["extra_body"] = extra_body
@@ -74,15 +74,17 @@ class SharedWandbConfig(BaseConfig):
"""W&B tags attached to the run."""
offline: bool | None = False
"""Run W&B in offline mode."""
shared: bool = True
"""Log trainer and orchestrator metrics to a single shared W&B run. Requires wandb SDK ≥ 0.19.9. Incompatible with offline mode."""
"""Run W&B in offline mode. Incompatible with shared mode, which is always on for the ``rl`` entrypoint."""
@model_validator(mode="after")
def validate_shared_not_offline(self):
if self.shared and self.offline:
raise ValueError("W&B shared mode requires server connectivity and is incompatible with offline mode")
def validate_not_offline(self):
if self.offline:
raise ValueError(
"W&B shared mode is always on for the rl entrypoint and requires server "
"connectivity; wandb.offline = true is not supported. Use offline mode "
"via the sub-config wandb blocks (trainer.wandb.offline, "
"orchestrator.wandb.offline) if you really need it per-process."
)
return self
@@ -35,6 +35,9 @@ class SlurmConfig(BaseConfig):
pre_run_command: str | None = None
"""Shell command to run on the head node after cd, .env sourcing, and venv activation. Useful for cleanup like ``sudo pkill -f vllm``; wrap with ``srun bash -c '...'`` to fan out to all nodes."""
cleanup_grace_period: int = Field(3600, ge=0)
"""Seconds to wait before tearing down a multi-node RL job that hit a non-zero exit, letting in-flight checkpoints flush. Set to 0 to tear down immediately."""
@property
def template_vars(self) -> dict:
"""Common template variables for all SLURM templates."""
@@ -47,6 +50,7 @@ class SlurmConfig(BaseConfig):
"account": self.account,
"time": self.time,
"pre_run_command": self.pre_run_command,
"cleanup_grace_period": self.cleanup_grace_period,
}
@model_validator(mode="after")
@@ -15,10 +15,13 @@ def propagate_shared_fields(data: Any) -> Any:
Behaviour:
- **Fill-if-absent**: an explicit sub-config value is never overwritten.
The shared block acts as a default, not a stomper.
- **Up-front mutex**: setting the same field at both the shared and
sub-config level raises. Under fill-if-absent the sub would silently
win, and any later CLI override of the shared field would invisibly
no-op.
- **Consistency mutex**: setting the same field at both the shared and
sub-config level only raises when the values *disagree*. Matching
values are accepted as a harmless no-op so that the materialized
config (``model_dump`` writes both copies) round-trips through re-load.
The original footgun the mutex was designed to catch — a sub-config
value silently winning over a later CLI shared override — is still
caught because that scenario produces *different* values.
- **Aliased sub-paths**: ``orchestrator.model.*`` is checked against its
``orchestrator.student.model.*`` alias (and vice versa), so the
conflict fires regardless of which spelling the user wrote.
@@ -49,14 +52,17 @@ def propagate_shared_fields(data: Any) -> Any:
conflicts: list[tuple[str, str]] = []
def propagate(shared_path: str, *targets: str, aliases: tuple[str, ...] = ()) -> None:
"""Verbatim shared → targets. Records overlap (incl. alias spellings)
into ``conflicts`` and fills each target if the shared value is set.
"""Verbatim shared → targets. Records *disagreeing* overlap (incl. alias
spellings) into ``conflicts`` and fills each target if the shared value
is set. Matching values are silently accepted so the materialized
config round-trips through re-load.
"""
value = get(shared_path)
if value is None:
return
for sub in (*targets, *aliases):
if get(sub) is not None:
sub_value = get(sub)
if sub_value is not None and sub_value != value:
conflicts.append((shared_path, sub))
for target in targets:
fill(target, value)
@@ -90,25 +96,16 @@ def propagate_shared_fields(data: Any) -> Any:
propagate("ckpt.keep_interval", "trainer.ckpt.keep_interval", "orchestrator.ckpt.keep_interval")
# [wandb] leaves. (Bare empty ``[wandb]`` block enablement is at the end.)
# ``wandb.name`` flows verbatim to both sub-configs — shared W&B mode is
# always on for the rl entrypoint, so the legacy ``-trainer`` /
# ``-orchestrator`` suffix split is gone.
propagate("wandb.project", "trainer.wandb.project", "orchestrator.wandb.project")
propagate("wandb.entity", "trainer.wandb.entity", "orchestrator.wandb.entity")
propagate("wandb.name", "trainer.wandb.name", "orchestrator.wandb.name")
propagate("wandb.group", "trainer.wandb.group", "orchestrator.wandb.group")
propagate("wandb.tags", "trainer.wandb.tags", "orchestrator.wandb.tags")
propagate("wandb.offline", "trainer.wandb.offline", "orchestrator.wandb.offline")
# wandb.name: in non-shared mode the two sub-configs get distinct
# ``-trainer`` / ``-orchestrator`` suffixes so the W&B runs are
# distinguishable. ``OrchestratorConfig.auto_setup_prime_monitor_run_name``
# then defaults prime_monitor.run_name to the (unsuffixed) value.
wandb_name = get("wandb.name")
if wandb_name is not None:
for sub in ("trainer.wandb.name", "orchestrator.wandb.name"):
if get(sub) is not None:
conflicts.append(("wandb.name", sub))
non_shared = get("wandb.shared") is False
fill("trainer.wandb.name", f"{wandb_name}-trainer" if non_shared else wandb_name)
fill("orchestrator.wandb.name", f"{wandb_name}-orchestrator" if non_shared else wandb_name)
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
# differ between sub-configs (auto-derived from model names, which may
@@ -132,13 +129,19 @@ def propagate_shared_fields(data: Any) -> Any:
# output_dir: orchestrator gets a ``/run_default`` subdir so trainer +
# orchestrator nest under the same experiment root without colliding.
# Conflicts are reported against the *transformed* sub-config value, not
# the raw shared path, so the materialized config round-trips cleanly.
output_dir = get("output_dir")
if output_dir is not None:
for sub in ("trainer.output_dir", "orchestrator.output_dir"):
if get(sub) is not None:
expected = {
"trainer.output_dir": output_dir,
"orchestrator.output_dir": f"{output_dir}/run_default",
}
for sub, expected_value in expected.items():
sub_value = get(sub)
if sub_value is not None and sub_value != expected_value:
conflicts.append(("output_dir", sub))
fill("trainer.output_dir", output_dir)
fill("orchestrator.output_dir", f"{output_dir}/run_default")
fill(sub, expected_value)
# Cascade trainer.tokenizer.chat_template → inference.model.chat_template
# (vLLM ``--chat-template``). Read trainer's value *after* the shared
@@ -159,9 +162,12 @@ def propagate_shared_fields(data: Any) -> Any:
# conflicts (e.g. shared ``ckpt.interval`` vs ``trainer.ckpt.interval``)
# are already caught above; the bare block is exempt because
# ``[ckpt]`` + ``[trainer.ckpt] keep_last = 3`` is a legitimate
# "enable + customise per side" pattern.
# "enable + customise per side" pattern. The ``isinstance(dict)`` check
# (not ``is not None``) is what makes CLI ``--no-wandb`` / ``--no-ckpt``
# work — those land as the *string* ``"None"`` until ``BaseConfig``'s
# parent-class validator converts it, which happens after this one.
for key in ("ckpt", "wandb"):
if get(key) is not None:
if isinstance(get(key), dict):
fill(f"trainer.{key}", {})
fill(f"orchestrator.{key}", {})
+13 -2
View File
@@ -164,6 +164,11 @@ members = [
]
[tool.uv]
# Enforce a uv version that supports the friendly-duration form
# (`"7 days"`) in the static pyproject parser. Older uvs silently parse
# the value as an RFC 3339 date, emit a TOML parse warning, and proceed
# *without* the cooldown — bypassing this security policy.
required-version = ">=0.11.1"
exclude-newer = "7 days"
preview = true
no-build-isolation-package = ["flash-attn"]
@@ -203,11 +208,17 @@ vllm = false
tokenspeed-mla = false
fastokens = false
flash_attn_3 = false
# PrimeIntellect-published on PyPI (trusted publisher)
# PrimeIntellect-published packages in this project's dependency closure —
# fast-track so first-party releases can land same-day. Only packages that
# appear in `uv tree` need to be listed; the resolver ignores entries for
# packages it never sees.
prime = false
prime-sandboxes = false
prime-tunnel = false
prime-evals = false
verifiers = false
renderers = false
prime-pydantic-config = false
# Trusted git/URL sources pinned by rev or wheel URL (defensive: belt-and-suspenders)
vllm-router = false
dion = false
@@ -255,7 +266,7 @@ dion = { git = "https://github.com/samsja/dion.git", rev = "d891eeb" }
transformers = { git = "https://github.com/huggingface/transformers.git", rev = "c1c3424" }
flash-attn-4 = { git = "https://github.com/Dao-AILab/flash-attention.git", subdirectory = "flash_attn/cute", rev = "96bd151" }
prime-pydantic-config = { workspace = true }
vllm-router = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl" }
vllm-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 = [
{ url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl", marker = "platform_machine == 'x86_64'" },
{ url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl", marker = "platform_machine == 'aarch64'" },
+7 -7
View File
@@ -107,11 +107,13 @@ def rl_local(config: RLConfig):
logger.info("Starting RL run")
logger.debug(f"RL start command: {' '.join(start_command)}")
# Build shared W&B env vars for subprocesses
wandb_shared_env: dict[str, str] = {}
if config.wandb and config.wandb.shared:
wandb_shared_env["WANDB_SHARED_MODE"] = "1"
wandb_shared_env["WANDB_SHARED_RUN_ID"] = os.environ.get("WANDB_SHARED_RUN_ID", uuid.uuid4().hex)
# Build shared W&B env vars for subprocesses. Shared mode is always on for
# the rl entrypoint — trainer and orchestrator log to a single W&B run.
# The monitor short-circuits when WANDB_MODE=disabled/offline is also set.
wandb_shared_env: dict[str, str] = {
"WANDB_SHARED_MODE": "1",
"WANDB_SHARED_RUN_ID": os.environ.get("WANDB_SHARED_RUN_ID", uuid.uuid4().hex),
}
# Validate client port matches inference server port
if config.inference is not None and not config.orchestrator.student.client.is_elastic:
@@ -378,7 +380,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
if config.inference.kv_cache_offload
else 0,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
wandb_shared=config.wandb is not None and config.wandb.shared,
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
)
else:
@@ -401,7 +402,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
dp_per_node=(config.deployment.gpus_per_node // config.inference.parallel.tp) if config.inference else 1,
kv_offload=config.inference is not None and config.inference.kv_cache_offload is not None,
use_nccl_broadcast=config.weight_broadcast is not None and config.weight_broadcast.type == "nccl",
wandb_shared=config.wandb is not None and config.wandb.shared,
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
)
@@ -8,7 +8,7 @@ import pybase64
from vllm.outputs import RequestOutput
def serialize_routed_experts(routed_experts: Any) -> dict[str, Any] | None:
def serialize_routed_experts(routed_experts: Any, start: int = 0) -> dict[str, Any] | None:
if routed_experts is None:
return None
@@ -23,18 +23,20 @@ def serialize_routed_experts(routed_experts: Any) -> dict[str, Any] | None:
return {
"data": pybase64.b64encode(memoryview(compact)).decode("ascii"),
"shape": list(compact.shape),
"start": start,
}
class RoutedExpertsCapture:
def __init__(self, generator: AsyncIterator[RequestOutput]):
def __init__(self, generator: AsyncIterator[RequestOutput], start: int = 0):
self._generator = generator
self._start = start
self.routed_experts: dict[int, dict[str, Any]] = {}
async def __aiter__(self):
async for request_output in self._generator:
for output in request_output.outputs:
encoded = serialize_routed_experts(getattr(output, "routed_experts", None))
encoded = serialize_routed_experts(getattr(output, "routed_experts", None), start=self._start)
if encoded is not None:
self.routed_experts[output.index] = encoded
yield request_output
+1
View File
@@ -61,6 +61,7 @@ WORKER_EXTENSION_CLS = {
@router.post("/pause")
async def pause(request: Request):
logger.debug("Received /pause request (mode=keep, clear_cache=False)")
await engine_client(request).pause_generation(mode="keep", clear_cache=False)
return {"status": "paused"}
@@ -266,7 +266,11 @@ class PrimeRlServingTokens(ServingTokens):
# experts surface in the JSON.
capture: _GenerateRoutedExpertsCapture | None = None
if self.model_config.enable_return_routed_experts:
capture = _GenerateRoutedExpertsCapture(result_generator)
start = request.sampling_params.routed_experts_prompt_start
capture = _GenerateRoutedExpertsCapture(
result_generator,
start=start,
)
result_generator = capture
response = await super().serve_tokens_full_generator(
+111 -25
View File
@@ -244,11 +244,13 @@ def interleave_rollout(
if tokens is not None:
routed_experts_payload = tokens.get("routed_experts")
routed_experts = None
routed_experts_start = None
if routed_experts_payload is not None:
decoded_routed_experts = pybase64.b64decode_as_bytearray(routed_experts_payload["data"])
routed_experts = np.frombuffer(decoded_routed_experts, dtype=np.uint8).reshape(
routed_experts_payload["shape"]
)
routed_experts_start = routed_experts_payload["start"]
return {
"prompt_ids": list(tokens["prompt_ids"]),
@@ -257,6 +259,7 @@ def interleave_rollout(
"completion_mask": list(map(bool, tokens["completion_mask"])),
"completion_logprobs": list(tokens["completion_logprobs"]),
"routed_experts": routed_experts,
"routed_experts_start": routed_experts_start,
# Renderer-emitted multimodal sidecar (placeholders + per-item
# processed tensors). Populated when the rollout went through
# a multimodal-aware renderer (e.g. Qwen3VLRenderer); absent
@@ -277,8 +280,14 @@ def interleave_rollout(
# Deferred routed_experts state per sample: O(N) chunk list concatenated
# once at finalize, replacing the prior O(N²) per-extension unpack/repack.
sample_routed_state: dict[int, dict[str, Any]] = {}
routed_prefix_states: dict[int, list[tuple[list[int], list[int], dict[str, Any]]]] = {}
def make_sample(tokens: dict[str, Any]) -> TrainingSample:
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
# is the explicit list of prepared_steps positions merged into this sample —
# non-contiguous when other agents' steps interleave.
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
def make_sample(tokens: dict[str, Any], step_idx: int) -> TrainingSample:
"""Create a new TrainingSample from a trajectory step."""
if has_error:
completion_mask = [False] * len(tokens["completion_mask"])
@@ -306,9 +315,50 @@ def interleave_rollout(
# each extension is a no-op append rather than a destructive write.
step_routed = tokens.get("routed_experts")
if step_routed is not None:
routed_start = tokens["routed_experts_start"]
assert routed_start is not None, f"Missing routed_experts_start for step {step_idx}"
chunks: list[np.ndarray] = []
running_len = 0
if routed_start > 0:
source_len = routed_start + 1
assert source_len in routed_prefix_states, (
f"Missing routed prefix state for step {step_idx}: "
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
)
source_state = None
for prompt_ids, completion_ids, candidate_state in routed_prefix_states[source_len]:
prompt_len = len(prompt_ids)
if (
tokens["prompt_ids"][:prompt_len] == prompt_ids
and tokens["prompt_ids"][prompt_len:source_len] == completion_ids
):
source_state = candidate_state
break
assert source_state is not None, (
f"No matching routed prefix for step {step_idx}: "
f"routed_start={routed_start}, prompt_len={len(tokens['prompt_ids'])}"
)
assert source_state["running_len"] >= routed_start, (
f"Routed prefix too short for step {step_idx}: "
f"running_len={source_state['running_len']}, routed_start={routed_start}"
)
remaining = routed_start
for chunk in source_state["chunks"]:
if remaining == 0:
break
take = min(remaining, int(chunk.shape[0]))
chunks.append(chunk[:take])
remaining -= take
assert remaining == 0, (
f"Could not reconstruct routed prefix for step {step_idx}: "
f"remaining={remaining}, routed_start={routed_start}"
)
running_len = routed_start
chunks.append(step_routed)
running_len += int(step_routed.shape[0])
sample_routed_state[id(sample)] = {
"chunks": [step_routed],
"running_len": int(step_routed.shape[0]),
"chunks": chunks,
"running_len": running_len,
}
return sample
@@ -339,51 +389,82 @@ def interleave_rollout(
step_routed = tokens.get("routed_experts")
state = sample_routed_state.get(id(sample))
if step_routed is not None and state is not None:
# vLLM doesn't capture a routing decision for the *last* token of any
# request, so the previous step left no entry for token at index
# (prefix_len - 1). The next step's forward pass *did* process that
# token (as part of its prompt) and produced step_routed[prefix_len-1].
# Append that single boundary entry as its own chunk, then append the
# genuinely new entries from this step. No prior bytes touched.
if prefix_len > 0 and prefix_len <= step_routed.shape[0]:
boundary_chunk = step_routed[prefix_len - 1 : prefix_len]
if state is not None:
assert step_routed is not None, f"Missing routed experts for routed sample extension at step {step_idx}"
if step_routed is not None:
assert state is not None, f"Unexpected routed experts for unrouted sample at step {step_idx}"
assert tokens["routed_experts_start"] == prefix_len - 1, (
f"Routed experts delta start mismatch at step {step_idx}: "
f"start={tokens['routed_experts_start']}, expected={prefix_len - 1}, prefix_len={prefix_len}"
)
# Delta payloads start at prefix_len - 1. Row 0 fills the boundary
# token missing from the previous request; the rest is the new suffix.
if prefix_len > 0:
boundary_chunk = step_routed[:1]
state["chunks"].append(boundary_chunk)
state["running_len"] += 1
new_chunk = step_routed[prefix_len:]
step_routed = step_routed[1:]
new_chunk = step_routed
state["chunks"].append(new_chunk)
state["running_len"] += int(new_chunk.shape[0])
# Track (prefix_tokens, sample, step_indices) per active sample. step_indices
# is the explicit list of prepared_steps positions merged into this sample —
# non-contiguous when other agents' steps interleave.
active_samples: list[tuple[list[int], TrainingSample, list[int]]] = []
first_tokens = prepared_steps[0]
first_prefix = first_tokens["prompt_ids"] + first_tokens["completion_ids"]
first_sample = make_sample(first_tokens)
first_sample = make_sample(first_tokens, step_idx=0)
active_samples.append((first_prefix, first_sample, [0]))
first_routed_state = sample_routed_state.get(id(first_sample))
if first_routed_state is not None:
routed_prefix_states.setdefault(len(first_prefix), []).append(
(first_tokens["prompt_ids"], first_tokens["completion_ids"], first_routed_state)
)
for step_idx, _step in enumerate(trajectory[1:], start=1):
tokens = prepared_steps[step_idx]
step_prompt_ids = tokens["prompt_ids"]
# Check if this step extends ANY active prefix
# Pick the *longest* matching active prefix. With compaction/rollback,
# one active sample's prefix can be a strict prefix of another (e.g. a
# later sample re-generated tokens that overlap an earlier sample's
# prefix). Both would satisfy the slice check; the shorter would
# silently absorb the longer sample's generated tokens as user input.
matched_idx = None
matched_len = -1
matching_prefix_lens: list[int] = []
for idx, (prefix_tokens, _, _) in enumerate(active_samples):
if step_prompt_ids[: len(prefix_tokens)] == prefix_tokens:
matched_idx = idx
break
pl = len(prefix_tokens)
if step_prompt_ids[:pl] == prefix_tokens:
matching_prefix_lens.append(pl)
if pl > matched_len:
matched_idx = idx
matched_len = pl
if len(matching_prefix_lens) > 1:
# Ambiguous extension: rare, but reachable via compaction/rollback
# where a new sample's prefix happens to start with an older
# sample's prefix. Longest-match is the correct choice; surface
# the ambiguity so we can audit if it shows up in real rollouts.
logger.warning(
f"Ambiguous prefix match at step {step_idx} for example {output['example_id']}: "
f"{len(matching_prefix_lens)} of {len(active_samples)} active prefixes match "
f"(lens={sorted(matching_prefix_lens)}, step_prompt_len={len(step_prompt_ids)}). "
f"Extending the longest (len={matched_len})."
)
if matched_idx is not None:
# Extension holds - merge into matched sample
prefix_tokens, sample, step_indices = active_samples[matched_idx]
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
active_samples[matched_idx] = (
tokens["prompt_ids"] + tokens["completion_ids"],
new_prefix,
sample,
step_indices + [step_idx],
)
routed_state = sample_routed_state.get(id(sample))
if routed_state is not None:
routed_prefix_states.setdefault(len(new_prefix), []).append(
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
)
else:
# No prefix matches - start a new sample
logger.debug(
@@ -391,8 +472,13 @@ def interleave_rollout(
f"Starting new sample (active_prefixes={len(active_samples)}, step_prompt_len={len(step_prompt_ids)})."
)
new_prefix = tokens["prompt_ids"] + tokens["completion_ids"]
sample = make_sample(tokens)
sample = make_sample(tokens, step_idx=step_idx)
active_samples.append((new_prefix, sample, [step_idx]))
routed_state = sample_routed_state.get(id(sample))
if routed_state is not None:
routed_prefix_states.setdefault(len(new_prefix), []).append(
(tokens["prompt_ids"], tokens["completion_ids"], routed_state)
)
# Finalize routed_experts for each sample. One concat per sample (O(N) byte
# work) replaces the previous per-step unpack/concat/repack (O(N²)). The
+18 -6
View File
@@ -72,10 +72,8 @@ export PYTHONUNBUFFERED=1
export OMP_NUM_THREADS=1
export TRITON_CACHE_DIR=/tmp/triton-cache-$USER-$SLURM_JOB_ID
{% if wandb_shared -%}
export WANDB_SHARED_MODE=1
export WANDB_SHARED_RUN_ID=$(python3 -c "import uuid; print(uuid.uuid4().hex)")
{%- endif %}
# Networking
HOSTNAMES=( $( scontrol show hostnames $SLURM_JOB_NODELIST ) )
@@ -384,7 +382,7 @@ else
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.base-url $INFER_URLS"
ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --student.client.admin-base-url $ADMIN_URLS"
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
{% endif %}{% if wandb_shared %}WANDB_SHARED_LABEL=orchestrator {% endif %}uv run orchestrator $ORCHESTRATOR_ARGS \
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
2>&1 | tee $OUTPUT_DIR/logs/orchestrator.log &
fi
{%- else %}
@@ -398,7 +396,7 @@ else
echo $HOSTNAMES_STR | tee $OUTPUT_DIR/logs/trainer/node_${TRAIN_NODE_RANK}.log
{% if wandb_shared %}WANDB_SHARED_LABEL=trainer {% endif %}uv run torchrun \
WANDB_SHARED_LABEL=trainer uv run torchrun \
--role=trainer \
--nnodes=$NUM_TRAIN_NODES \
--nproc-per-node=$GPUS_PER_NODE \
@@ -420,8 +418,22 @@ else
# tears down instead of leaving zombies holding the allocation.
wait -n
EXIT_CODE=$?
echo "[$(hostname)] component exited with code $EXIT_CODE - terminating remaining processes"
for pid in $(jobs -p); do
REMAINING_PIDS=$(jobs -p)
{%- if cleanup_grace_period %}
# Cross-node teardown is driven by `srun --kill-on-bad-exit=1`, which reaps peer
# tasks only once a task *exits* non-zero. So on a non-zero exit (crash, SIGTERM,
# wall-time) we stay alive for the grace period and signal nothing: this lets an
# in-flight trainer checkpoint on this node finish, and — because the task has
# not exited yet — keeps --kill-on-bad-exit from reaping checkpointing trainers
# on peer nodes. We then propagate the exit code so the allocation tears down. A
# clean (zero) exit can't trip --kill-on-bad-exit, so we tear down immediately.
if [ "$EXIT_CODE" -ne 0 ]; then
echo "[$(hostname)] component exited with code $EXIT_CODE - waiting up to {{ cleanup_grace_period }}s for in-flight checkpoints to flush before teardown"
sleep {{ cleanup_grace_period }}
fi
{%- endif %}
echo "[$(hostname)] tearing down (exit code $EXIT_CODE) - terminating remaining processes"
for pid in $REMAINING_PIDS; do
kill -TERM $pid 2>/dev/null || true
done
exit $EXIT_CODE
@@ -43,7 +43,7 @@ class AfmoeConfig(PretrainedConfig):
route_norm=True,
route_scale=1.0,
score_before_experts: bool = False,
load_balance_coeff: float | None = None,
load_balance_coeff: float = 5e-4,
use_grouped_mm: bool = True,
global_attn_every_n_layers=4,
sliding_window=1024,
@@ -352,7 +352,7 @@ class AfmoeDecoderLayer(GradientCheckpointingLayer):
score_before_experts=getattr(config, "score_before_experts", False),
top_k=config.num_experts_per_tok,
use_grouped_mm=getattr(config, "use_grouped_mm", True),
load_balance_coeff=getattr(config, "load_balance_coeff", None),
load_balance_coeff=config.load_balance_coeff,
fp8=getattr(config, "fp8", False),
)
if self.moe_enabled:
+9 -7
View File
@@ -286,7 +286,15 @@ def train(config: TrainerConfig):
for idx in multi_run_manager.used_idxs:
multi_run_manager.ready_to_update[idx] = False
if (
if config.max_concurrent_runs > 1:
# Multi-run: Save per-run checkpoints using each run's orchestrator config.
# Trainer-level ckpt config can be set by the combined rl entrypoint,
# but MultiCheckpointManager has a different save signature.
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(optimizer, scheduler)
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
ckpt_manager.maybe_clean()
elif (
ckpt_manager is not None
and (config.ckpt and config.ckpt.interval)
and not (is_first_step or is_last_step)
@@ -310,12 +318,6 @@ def train(config: TrainerConfig):
weight_ckpt_manager.save(progress.step, model, tokenizer)
save_ckpt_time += time.perf_counter() - save_ckpt_start_time
weight_ckpt_manager.maybe_clean()
elif config.max_concurrent_runs > 1:
# Multi-run: Save per-run checkpoints (each run has its own interval from orchestrator config)
save_ckpt_start_time = time.perf_counter()
ckpt_manager.save(optimizer, scheduler)
save_ckpt_time = time.perf_counter() - save_ckpt_start_time
ckpt_manager.maybe_clean()
else:
save_ckpt_time = 0
+34 -1
View File
@@ -278,13 +278,46 @@ async def check_health(
NCCL_READY_MARKER = "NCCL_READY"
def _is_retryable_pause_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for pausing engines."""
if isinstance(exception, httpx.HTTPStatusError):
# Retry on transient server errors (5xx, e.g. engine briefly unresponsive);
# client errors (4xx) won't fix themselves on retry.
return exception.response.status_code >= 500
# Retry on transport-level failures (timeouts, connection resets, etc.) so the
# per-attempt read timeout below turns a stuck server into a bounded retry loop
# instead of hanging forever on the global timeout=None admin client.
if isinstance(exception, (httpx.TimeoutException, httpx.TransportError)):
return True
return False
# Per-attempt and total bounds for `/pause`. Pausing drains in-flight requests
# (mode="keep"), so a single attempt can legitimately take a while, but the global
# admin AsyncClient uses `timeout=None`, so a stuck server would hang the weight
# update forever. `_READ_TIMEOUT` converts a hang into a TimeoutException so
# tenacity retries; `_TOTAL` is the wall-clock budget across all retries.
PAUSE_READ_TIMEOUT_S = 120.0
PAUSE_TOTAL_TIMEOUT_S = 300.0
async def _pause_engines(admin_clients: list[AsyncClient]) -> None:
"""Pause all inference engines, waiting for in-flight requests to drain."""
logger = get_logger()
logger.info("Pausing inference engines for weight update")
@retry(
retry=retry_if_exception(_is_retryable_pause_error),
stop=stop_after_delay(PAUSE_TOTAL_TIMEOUT_S) | stop_after_attempt(10),
wait=wait_exponential(multiplier=1, min=1, max=10),
reraise=True,
)
async def _pause(client: AsyncClient) -> None:
response = await client.post("/pause", params={"mode": "keep", "clear_cache": "false"})
response = await client.post(
"/pause",
params={"mode": "keep", "clear_cache": "false"},
timeout=httpx.Timeout(connect=10.0, read=PAUSE_READ_TIMEOUT_S, write=60.0, pool=10.0),
)
response.raise_for_status()
await asyncio.gather(*[_pause(client) for client in admin_clients])
+1 -4
View File
@@ -61,10 +61,7 @@ class WandbMonitor(Monitor):
x_primary=primary,
x_update_finish_state=primary,
)
self.logger.info(
f"Using shared W&B mode ({label=}, {primary=}). "
"This is an experimental feature. Disable with --wandb.shared False"
)
self.logger.info(f"Using shared W&B mode ({label=}, {primary=})")
else:
run_id = None
primary = False
+1 -1
View File
@@ -73,7 +73,7 @@ def test_serialize_routed_experts_uses_compact_raw_payload():
def test_generate_response_post_process_replaces_upstream_routed_experts():
compact_routed_experts = {"data": "AQID", "shape": [1, 1, 3]}
compact_routed_experts = {"data": "AQID", "shape": [1, 1, 3], "start": 0}
capture = _GenerateRoutedExpertsCapture(_empty_request_outputs())
capture.routed_experts[0] = compact_routed_experts
response = GenerateResponse(
+266 -5
View File
@@ -31,11 +31,12 @@ def _decode_mm_thw(sample) -> list:
return np.frombuffer(g.data, dtype=np.dtype(g.dtype)).reshape(g.shape).tolist()
def _routed_experts_payload(data) -> dict:
def _routed_experts_payload(data, start: int = 0) -> dict:
arr = np.asarray(data, dtype=np.uint8)
return {
"data": pybase64.b64encode(memoryview(np.ascontiguousarray(arr))).decode("ascii"),
"shape": list(arr.shape),
"start": start,
}
@@ -748,6 +749,140 @@ def test_interleave_rollout_interleaved_agents(interleaved_agents_trajectory):
assert agent2_sample.completion_logprobs == [-0.5, -0.6]
@pytest.fixture
def prefix_of_prefix_trajectory():
"""
Trajectory where one active sample's prefix is a strict prefix of another's.
Construction:
- step 0: prompt=[1,2], completion=[3,4] -> sample A, P_A=[1,2,3,4]
- step 1: extends A. prompt=[1,2,3,4,5], completion=[6] -> P_A=[1,2,3,4,5,6]
- step 2: rollback/regenerate. prompt=[1,2] (shorter than P_A so no match),
completion=[3,4,5,6,7] -> sample B, P_B=[1,2,3,4,5,6,7]
P_B starts with P_A.
- step 3: extends B. prompt=[1,2,3,4,5,6,7,8], completion=[9]
Both P_A and P_B are token-prefixes of the step's prompt.
The correct match is the longer P_B. First-match-wins picks P_A and silently
folds B's generated tokens into A as user-input tokens (mask=False).
"""
output = vf.RolloutOutput(
example_id=2,
task="test",
trajectory=[
vf.TrajectoryStep(
prompt="step 0",
completion="completion 0",
response=None,
tokens=vf.TrajectoryStepTokens(
prompt_ids=[1, 2],
prompt_mask=[0, 0],
completion_ids=[3, 4],
completion_mask=[1, 1],
completion_logprobs=[-0.1, -0.2],
overlong_prompt=False,
is_truncated=False,
),
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="traj_A",
extras={},
),
vf.TrajectoryStep(
prompt="step 1",
completion="completion 1",
response=None,
tokens=vf.TrajectoryStepTokens(
prompt_ids=[1, 2, 3, 4, 5],
prompt_mask=[0, 0, 0, 0, 0],
completion_ids=[6],
completion_mask=[1],
completion_logprobs=[-0.3],
overlong_prompt=False,
is_truncated=False,
),
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="traj_A",
extras={},
),
vf.TrajectoryStep(
prompt="step 2 (rollback)",
completion="completion 2",
response=None,
tokens=vf.TrajectoryStepTokens(
prompt_ids=[1, 2],
prompt_mask=[0, 0],
completion_ids=[3, 4, 5, 6, 7],
completion_mask=[1, 1, 1, 1, 1],
completion_logprobs=[-0.4, -0.5, -0.6, -0.7, -0.8],
overlong_prompt=False,
is_truncated=False,
),
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="traj_B",
extras={},
),
vf.TrajectoryStep(
prompt="step 3 (extends B)",
completion="completion 3",
response=None,
tokens=vf.TrajectoryStepTokens(
prompt_ids=[1, 2, 3, 4, 5, 6, 7, 8],
prompt_mask=[0, 0, 0, 0, 0, 0, 0, 0],
completion_ids=[9],
completion_mask=[1],
completion_logprobs=[-0.9],
overlong_prompt=False,
is_truncated=False,
),
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="traj_B",
extras={},
),
],
sampling_args={"temperature": 1.0},
error=None,
)
return output
def test_interleave_rollout_picks_longest_matching_prefix(prefix_of_prefix_trajectory):
"""
When two active samples both match (one's prefix is a strict prefix of the
other's), the longer prefix is the correct extension. Previously the first-
match-wins loop folded the longer sample's generated tokens into the shorter
sample as user input (mask=False) and left the longer sample stale.
"""
rollouts = interleave_rollout(prefix_of_prefix_trajectory)
assert rollouts is not None
assert len(rollouts) == 2
# Sample A: steps 0 and 1 only. Step 3 must NOT have been folded in here.
sample_a = rollouts[0]
assert sample_a.prompt_ids == [1, 2]
# step 0 completion [3,4] + step 1 new prompt [5] + step 1 completion [6]
assert sample_a.completion_ids == [3, 4, 5, 6]
assert sample_a.completion_mask == [True, True, False, True]
assert sample_a.completion_logprobs == [-0.1, -0.2, 0.0, -0.3]
# Sample B: steps 2 and 3 merged. The token 7 (from step 2's completion)
# must remain masked as a generated token, not silently re-classified.
sample_b = rollouts[1]
assert sample_b.prompt_ids == [1, 2]
# step 2 completion [3,4,5,6,7] + step 3 new prompt [8] + step 3 completion [9]
assert sample_b.completion_ids == [3, 4, 5, 6, 7, 8, 9]
assert sample_b.completion_mask == [True, True, True, True, True, False, True]
assert sample_b.completion_logprobs == [-0.4, -0.5, -0.6, -0.7, -0.8, 0.0, -0.9]
def test_interleave_rollout_empty_trajectory():
"""Empty trajectory returns None."""
output = vf.RolloutOutput(
@@ -910,8 +1045,9 @@ def test_interleave_rollout_multi_step_with_routed_experts():
"""Routed experts are extended and aligned across multi-step trajectories."""
# Step 1: prompt=[1,2], completion=[3,4] -> 4 tokens, vLLM returns 3
step1_experts = np.asarray([[[1, 2]], [[3, 4]], [[5, 6]]], dtype=np.uint8)
# Step 2: prompt=[1,2,3,4,5,6], completion=[7,8] -> 8 tokens, vLLM returns 7
step2_experts = np.asarray([[[1, 0]], [[2, 0]], [[3, 0]], [[4, 0]], [[5, 0]], [[6, 0]], [[7, 0]]], dtype=np.uint8)
# Step 2: prompt=[1,2,3,4,5,6], completion=[7,8], bridged from prefix len 4.
# vLLM returns routed experts starting at row 3: boundary token 4, then 5, 6, 7.
step2_experts = np.asarray([[[40, 41]], [[50, 51]], [[60, 61]], [[70, 71]]], dtype=np.uint8)
output = vf.RolloutOutput(
example_id=0,
@@ -952,7 +1088,7 @@ def test_interleave_rollout_multi_step_with_routed_experts():
completion_logprobs=[-0.3, -0.4],
overlong_prompt=False,
is_truncated=False,
routed_experts=_routed_experts_payload(step2_experts),
routed_experts=_routed_experts_payload(step2_experts, start=3),
),
reward=None,
advantage=None,
@@ -973,7 +1109,132 @@ def test_interleave_rollout_multi_step_with_routed_experts():
# Merged sample: prompt=[1,2], completion=[3,4,5,6,7,8] -> 8 tokens total
assert len(sample.prompt_ids) + len(sample.completion_ids) == 8
assert sample.routed_experts is not None
assert _sample_routed_experts(sample).shape == (8, 1, 2)
routed_experts = _sample_routed_experts(sample)
assert routed_experts.shape == (8, 1, 2)
np.testing.assert_array_equal(
routed_experts,
np.asarray(
[
[[1, 2]],
[[3, 4]],
[[5, 6]],
[[40, 41]],
[[50, 51]],
[[60, 61]],
[[70, 71]],
[[0, 0]],
],
dtype=np.uint8,
),
)
def test_interleave_rollout_branch_delta_uses_prior_routed_prefix():
step1_experts = np.asarray([[[1, 2]], [[3, 4]], [[5, 6]]], dtype=np.uint8)
step2_experts = np.asarray([[[40, 41]], [[50, 51]], [[60, 61]], [[70, 71]]], dtype=np.uint8)
step3_experts = np.asarray([[[80, 81]], [[90, 91]], [[100, 101]], [[110, 111]]], dtype=np.uint8)
output = vf.RolloutOutput(
example_id=0,
trajectory=[
vf.TrajectoryStep(
prompt=[{"role": "user", "content": "U1"}],
completion=[{"role": "assistant", "content": "A1"}],
response=MagicMock(),
tokens=vf.TrajectoryStepTokens(
prompt_ids=[1, 2],
prompt_mask=[0, 0],
completion_ids=[3, 4],
completion_mask=[1, 1],
completion_logprobs=[-0.1, -0.2],
overlong_prompt=False,
is_truncated=False,
routed_experts=_routed_experts_payload(step1_experts),
),
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
),
vf.TrajectoryStep(
prompt=[
{"role": "user", "content": "U1"},
{"role": "assistant", "content": "A1"},
{"role": "user", "content": "U2"},
],
completion=[{"role": "assistant", "content": "A2"}],
response=MagicMock(),
tokens=vf.TrajectoryStepTokens(
prompt_ids=[1, 2, 3, 4, 5, 6],
prompt_mask=[0, 0, 0, 0, 0, 0],
completion_ids=[7, 8],
completion_mask=[1, 1],
completion_logprobs=[-0.3, -0.4],
overlong_prompt=False,
is_truncated=False,
routed_experts=_routed_experts_payload(step2_experts, start=3),
),
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
),
vf.TrajectoryStep(
prompt=[
{"role": "user", "content": "U1"},
{"role": "assistant", "content": "A1"},
{"role": "user", "content": "branch"},
],
completion=[{"role": "assistant", "content": "A3"}],
response=MagicMock(),
tokens=vf.TrajectoryStepTokens(
prompt_ids=[1, 2, 3, 4, 9, 10],
prompt_mask=[0, 0, 0, 0, 0, 0],
completion_ids=[11, 12],
completion_mask=[1, 1],
completion_logprobs=[-0.5, -0.6],
overlong_prompt=False,
is_truncated=False,
routed_experts=_routed_experts_payload(step3_experts, start=3),
),
reward=None,
advantage=None,
is_truncated=False,
trajectory_id="1",
extras={},
),
],
sampling_args={"temperature": 1.0},
error=None,
)
rollouts = interleave_rollout(output)
assert rollouts is not None
assert len(rollouts) == 2
branched = rollouts[1]
assert branched.prompt_ids == [1, 2, 3, 4, 9, 10]
assert branched.completion_ids == [11, 12]
routed_experts = _sample_routed_experts(branched)
assert routed_experts.shape == (8, 1, 2)
np.testing.assert_array_equal(
routed_experts,
np.asarray(
[
[[1, 2]],
[[3, 4]],
[[5, 6]],
[[80, 81]],
[[90, 91]],
[[100, 101]],
[[110, 111]],
[[0, 0]],
],
dtype=np.uint8,
),
)
def test_interleave_rollout_none_routed_experts_stays_none():
+7 -6
View File
@@ -381,19 +381,19 @@ def test_trainer_chat_template_cascades_to_inference():
def test_shared_wandb_fields_propagate_to_subconfigs():
"""Every ``SharedWandbConfig`` leaf (project, entity, group, tags, offline)
propagates to both trainer.wandb and orchestrator.wandb, not just project
and offline. Regression for a miss in the inline propagator."""
"""Every ``SharedWandbConfig`` leaf (project, entity, name, group, tags,
offline) propagates to both trainer.wandb and orchestrator.wandb. Regression
for a miss in the inline propagator."""
config = RLConfig.model_validate(
{
"model": {"name": "Qwen/Qwen3-0.6B"},
"wandb": {
"project": "shared-proj",
"entity": "shared-entity",
"name": "shared-name",
"group": "shared-group",
"tags": ["a", "b"],
"shared": False,
"offline": True,
"offline": False,
},
"trainer": {},
"orchestrator": {"renderer": None},
@@ -403,9 +403,10 @@ def test_shared_wandb_fields_propagate_to_subconfigs():
assert component is not None
assert component.project == "shared-proj"
assert component.entity == "shared-entity"
assert component.name == "shared-name"
assert component.group == "shared-group"
assert component.tags == ["a", "b"]
assert component.offline is True
assert component.offline is False
def test_empty_shared_ckpt_block_does_not_conflict_with_subconfig_ckpt():
Generated
+14 -11
View File
@@ -15,23 +15,26 @@ conflicts = [[
]]
[options]
exclude-newer = "2026-05-18T23:20:22.611873892Z"
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer-span = "P7D"
[options.exclude-newer-package]
vllm = false
verifiers = false
prime-pydantic-config = false
vllm-router = false
dion = false
tokenspeed-mla = false
prime = false
nixl-cu12 = false
deep-ep = false
fastokens = false
flash-attn-3 = false
prime-sandboxes = false
prime-tunnel = false
deep-gemm = false
prime-evals = false
fastokens = false
tokenspeed-mla = false
deep-ep = false
prime-sandboxes = false
renderers = false
prime = false
[manifest]
members = [
@@ -4144,7 +4147,7 @@ requires-dist = [
{ name = "vllm", marker = "platform_machine != 'aarch64' and platform_machine != 'x86_64'", specifier = ">=0.21.0" },
{ name = "vllm", marker = "platform_machine == 'aarch64'", url = "https://github.com/vllm-project/vllm/releases/download/v0.21.0/vllm-0.21.0+cu129-cp38-abi3-manylinux_2_34_aarch64.whl" },
{ name = "vllm", marker = "platform_machine == 'x86_64'", url = "https://github.com/PrimeIntellect-ai/prime-rl/releases/download/v0.5.0/vllm-0.21.0+cu129.r42434.pr39568.a106aa6-cp38-abi3-manylinux_2_34_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl" },
{ name = "vllm-router", marker = "platform_machine == 'x86_64' and extra == 'disagg'", 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" },
{ name = "wandb", specifier = ">=0.26.1" },
{ name = "wiki-search", marker = "extra == 'envs'", editable = "deps/verifiers/environments/wiki_search" },
]
@@ -4833,7 +4836,7 @@ requires-dist = [
{ name = "jinja2" },
{ name = "numpy" },
{ name = "openai", specifier = ">=1.108.1" },
{ name = "openai-harmony", specifier = ">=0.0.8" },
{ name = "openai-harmony", specifier = ">=0.0.4" },
{ name = "prime-pydantic-config", editable = "deps/pydantic-config" },
{ name = "tiktoken" },
{ name = "transformers", git = "https://github.com/huggingface/transformers.git?rev=c1c3424" },
@@ -6482,8 +6485,8 @@ provides-extras = ["zen", "bench", "tensorizer", "fastsafetensors", "instanttens
[[package]]
name = "vllm-router"
version = "0.1.25"
source = { url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl" }
version = "0.1.26"
source = { 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" }
dependencies = [
{ name = "aiohttp", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "fastapi", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
@@ -6493,7 +6496,7 @@ dependencies = [
{ name = "uvicorn", marker = "(platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
]
wheels = [
{ url = "https://github.com/PrimeIntellect-ai/router/releases/download/v0.1.25/vllm_router-0.1.25-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:e84e731a0779f820bfe3cf4ce78cea2d09993c0a6501c63bcda93826bcd21fd0" },
{ 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", hash = "sha256:db0c9410a4c130da8ffeea22f569faca7c85c58c5e183be1ebf758076361a6ec" },
]
[package.metadata]