Compare commits

...
Author SHA1 Message Date
JannikStandGitHub 4df5b6229f fix: probe github ssh auth directly in install.sh (#2613)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: probe github ssh auth directly in install.sh

The previous `has_ssh_access` probe ran `git ls-remote` against the
public prime-rl repo, which can return success under SSH connection
multiplexing, cached creds, or other states without the local key
actually being registered with a GitHub user. When that happens, the
HTTPS `insteadOf` rewrite is never applied and private-submodule
clones fail with "Permission denied (publickey)".

Use `ssh -T git@github.com` and grep for the canonical
"successfully authenticated" string instead. This is a direct check
of the precondition (your key is registered with a GitHub user) and
matches the pattern git itself recommends.

* fix: capture ssh output to var so pipefail doesn't mask success

`ssh -T git@github.com` always exits 1 (GitHub denies shell access
after authenticating), and install.sh has `set -o pipefail` at the
top, so the previous pipeline made has_ssh_access return failure even
for developers with valid keys. Capture stdout/stderr into a variable
first, then grep — keeps pipefail intact for the rest of the script.

* fix: use universal ssh options in github auth probe

`StrictHostKeyChecking=accept-new` requires OpenSSH 7.6+ (Sep 2017).
On older systems ssh errors with 'Bad configuration option' and the
probe wrongly reports no SSH auth, forcing HTTPS even when SSH would
have worked.

Use `StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null`
instead, which works on all OpenSSH versions. Safe for a probe-only
flow: no key material is exchanged, and a hostile MITM at worst
makes the probe wrongly report 'no SSH', causing HTTPS fallback for
public repos.

* fix: rely on ensure_known_hosts and default ssh host key checking

Previous commit disabled `StrictHostKeyChecking` and `UserKnownHostsFile`
to side-step OpenSSH version requirements, but that made the auth probe
trust any host that returns the "successfully authenticated" string —
a MITM could steer the script into using their SSH for submodule
clones.

`ensure_known_hosts` already runs (line 116) before any
`has_ssh_access` call and populates github.com via ssh-keyscan, so
default host key checking is both safe and sufficient. Drop the
options entirely; keep `BatchMode=yes` to suppress prompts.

* fix: propagate insteadOf to submodule clones via GIT_CONFIG_* env

`git submodule--helper clone` spawns fresh `git clone` processes
that read only ~/.gitconfig and env vars — not the parent repo's
local .git/config. So setting `url..insteadOf` locally never reached
the submodule clones, and they kept attempting SSH despite the probe
correctly reporting no auth.

Use `GIT_CONFIG_COUNT`/`GIT_CONFIG_KEY_0`/`GIT_CONFIG_VALUE_0` which
propagate the rewrite to every child git process for the duration of
this script, with no persistent state in ~/.gitconfig.
2026-05-24 04:58:21 +02:00
Mika SenghaasandGitHub ae1461e7a1 docs: fix stale slurm config examples and references (#2619)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The docs and a couple of example READMEs described slurm usage that
no longer matches the real config system - users following them would
hit validation errors.

- docs/slurm.md: drop bogus `toml_files = [...]` (not a pydantic-config
  feature) and document the real `@ base.toml @ overlay.toml` compose
  syntax. Rename `[orchestrator.sampling]` and `[[orchestrator.env]]`
  to the current `train`-scoped paths, swap `max_tokens` for
  `max_completion_tokens`, repoint dead `examples/hendrycks_math/`
  links to `examples/multinode/`, fix the inference example filename
  and `--dry-run` flag usage
- examples/hendrycks_sanity/README.md: the slurm command was invoking
  the overlay alone (which fails validation), compose base + overlay
- examples/wiki_search/README.md: stale `[[orchestrator.env]]` path
2026-05-23 19:56:41 -07:00
7e8355003a chore(orchestrator): backfill rollout tokens only when needed (#2610)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore(orchestrator): gate pretokenize_rollout_trajectory on SFT mode

Only call the pretokenize fallback in sft mode. The renderer-backed and
MITO rollout clients populate step["tokens"] from vLLM's prompt_token_ids
and token_ids extensions, so the call is a no-op there. sft from an
external teacher (e.g. openai/gpt-5-mini via PI inference) does still
need the fallback because external APIs return no token IDs.

Verified on examples/reverse_text/rl.toml @ 5 steps:
- renderer (default):                  reward 0.11 → 0.24
- MITO (--no-orchestrator.use-renderer): reward 0.11 → 0.20
- sft external (configs/debug/training_modes/sft_external.toml): reward ~0.92, all 5 steps complete

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

* chore(orchestrator): gate pretokenize on tokens-missing, log when it runs

Replace the training_mode == "sft" gate with a behavioral check on
step["tokens"] is None. This skips the 256-way to_thread fanout for
SFT against a local vLLM teacher too (vLLM populates tokens via
prompt_token_ids/token_ids), not just RL/OPD. Only the external teacher
API path (OpenAI/etc.) actually needs the fallback. Log inside the
guard so it's visible when the work runs.

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

* refactor(orchestrator): rename pretokenize_rollout_trajectory -> backfill_rollout_tokens

"Pretokenize" was misleading - the function is a backfill that fills in
step["tokens"] for any step where it's None, run only when the rollout
source (e.g. external teacher API) didn't return token IDs.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 19:18:14 -07:00
81822debb6 feat(orchestrator): default X-Session-ID header to trajectory_id (#2615)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* feat(orchestrator): default X-Session-ID header to trajectory_id

Switch the auto-injected `X-Session-ID` sticky-routing header from
`example_id` to `trajectory_id` so each rollout (rather than each
dataset example) pins to a single inference engine.

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

* chore: bump configs/private submodule

Pin to the research-configs branch dropping the explicit
`X-Session-ID = example_id` override on `rlm5/{prod,glm5-swe}`
so they pick up the new `trajectory_id` default.

See: PrimeIntellect-ai/research-configs#2

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 19:18:07 -07:00
8e978063b4 perf(orchestrator): reduce event-loop lag (#2609)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* perf(transport): offload TrainingBatch send to a worker thread

Make FileSystemTrainingBatchSender.send async and run the msgspec encode
+ disk write in asyncio.to_thread. Keeps the orch event loop responsive
during step transitions when the batch payload is large.

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

* perf(orchestrator): await async sender; to_thread advantages+filters+uvloop

- await training_batch_sender.send(training_batch) since sender is async (O1+O2)
- compute_advantages and apply_filters wrapped in asyncio.to_thread (O3+O4):
  both iterate ~2k rollouts in pure Python and release the GIL on every
  bytecode tick, so threading actually helps unlike the C-extension encode
- main() installs uvloop (O7) — lower scheduler overhead matters when the
  orchestrator is juggling many concurrent rollouts + the HTTP client to
  inference; measurably reduces tail latency.

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

* perf(orchestrator): log p99 event-loop lag in metrics + busy-loop warning

p90 alone undersells the long tail we see at step boundaries. p99 is the
metric we actually compare across runs, so surface it in the wandb dict
(`event_loop_lag/p99`) and in the busy-loop warning line.

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

* perf(orchestrator): defer routed_experts concat in interleave_rollout

extend_sample's previous implementation unpacked the accumulated
routed_experts bytes, mutated one boundary entry, np.concatenated the new
step's routings, then re-packed to bytes — every extension. For an N-turn
rollout reaching seq_len 60k, the accumulated buffer reached ~23 MB and was
fully read+written N times, giving O(N²) byte work (~2.3 GB of memcpy per
rollout). At 256 rollouts/step this dominated the orch's step-boundary
event-loop stalls more than the encode path we'd already fixed.

Defer the concat: track per-sample `chunks: list[np.ndarray]` during the
extension loop and finalize once at the end. The "boundary token" entry
that vLLM omits for each request is appended as its own one-entry chunk
between consecutive steps' contributions, so the final concat is a
straight join — no destructive writes to prior chunks.

Verified byte-exact against the old implementation on a 50-step extension
chain. Per-rollout work drops from O(N²) → O(N): ~100× less memcpy in the
realistic regime.

This makes use_process_pool unnecessary for the residual orch lag: each
rollout's process_rollout cost drops below the IPC pickle cost, so the
threaded path is strictly better.

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

* perf(orchestrator): orjson save_rollouts + dedup bool conversion

- save_rollouts: json.dump -> orjson.dumps + bytes write. The pure-Python
  serializer held the GIL for the whole save phase (multi-second spikes
  on big steps); orjson serializes in C and releases the GIL.
- prepare/make/extend mask handling: [bool(i) for i in mask] was the
  remaining per-turn GIL-held Python loop. make_sample/extend_sample
  swapped to list(...) / direct extend; prepare_step_tokens uses
  list(map(bool, ...)). Together drops gather wallclock 5-10% on
  long-tail rollouts.

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

* perf(orchestrator): skip pretokenize fanout when nothing needs work; 10Hz lag monitor

- Pretokenize was a no-op for router-replay (every step already has
  tokens populated by the renderer client), but the 256-way to_thread
  fanout starved the loop for ~2 s per step. Short-circuit when no
  rollout's trajectory has unpopulated tokens. Offline attribution:
  pretokenize lag drops 2050 ms → 11 ms.
- EventLoopLagMonitor sampling 1 Hz → 10 Hz (mirrors verifiers'
  monitor). 1 Hz was missing sub-second spikes that show up clearly
  at 10 Hz.

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

* chore(deps): bump verifiers submodule to a930f2e5 (post-1453 main)

Pulls in the env_worker / env_router event-loop lag fixes that just
landed on verifiers main via PR 1453 — required for the orch-side
gains in this PR to surface under realistic 256-rollout concurrency.

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

---------

Co-authored-by: Sami <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 18:34:42 -07:00
17 changed files with 166 additions and 116 deletions
+1 -1
+12 -13
View File
@@ -8,16 +8,14 @@ The `rl`, `sft`, and `inference` entrypoints all have built-in SLURM support. Ad
# Local run
uv run rl @ examples/reverse_text/rl.toml
# SLURM run (same entrypoint, just add [slurm] to the config)
uv run rl @ examples/reverse_text/slurm_rl.toml
# SLURM run — overlay slurm_rl.toml on top of the base config
uv run rl @ examples/reverse_text/rl.toml @ examples/reverse_text/slurm_rl.toml
```
The SLURM config is a thin overlay that inherits from a base config and adds `[slurm]` + `[deployment]` sections:
The SLURM config is a thin overlay that adds `[slurm]` (and optionally `[deployment]`) on top of a base config. Configs are composed left-to-right via the `@` CLI syntax — see [`configs.md`](configs.md) for details.
```toml
# examples/reverse_text/slurm_rl.toml
toml_files = ["rl.toml"]
output_dir = "outputs/reverse-text-rl"
[slurm]
@@ -140,10 +138,10 @@ freq = 1
batch_size = 512
group_size = 16
[orchestrator.sampling]
max_tokens = 2048
[orchestrator.train.sampling]
max_completion_tokens = 2048
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "math-env"
name = "hendrycks-math"
args = { dataset_name = "PrimeIntellect/Hendrycks-Math", dataset_subset = "default" }
@@ -153,7 +151,7 @@ tp = 4
dp = 2
```
See [`examples/hendrycks_math/rl.toml`](../examples/hendrycks_math/rl.toml) for the full example.
See [`examples/multinode/rl.toml`](../examples/multinode/rl.toml) for the full example.
---
@@ -202,7 +200,7 @@ batch_size = 128
seq_len = 8192
```
See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) for the full example.
See [`examples/multinode/sft.toml`](../examples/multinode/sft.toml) for the full example.
---
@@ -213,6 +211,7 @@ See [`examples/hendrycks_math/sft.toml`](../examples/hendrycks_math/sft.toml) fo
Run a vLLM server on a single allocated node:
```toml
# my_inference.toml
output_dir = "/shared/outputs/my-inference"
[model]
@@ -226,7 +225,7 @@ job_name = "my-inference"
```
```bash
uv run inference @ inference_slurm.toml
uv run inference @ my_inference.toml
```
### Multi-node SLURM
@@ -255,10 +254,10 @@ After submission, the SLURM template prints the inference URLs for all nodes (on
### Dry run
Use `dry_run = true` to generate the sbatch script without submitting:
Use `--dry-run` (or `dry_run = true` in TOML) to generate the sbatch script without submitting:
```bash
uv run inference @ config.toml --dry-run true
uv run inference @ config.toml --dry-run
```
---
+1 -1
View File
@@ -19,7 +19,7 @@ uv run rl @ examples/hendrycks_sanity/rl.toml \
Or schedule the same training via SLURM
```bash
uv run rl @ examples/hendrycks_sanity/slurm_rl.toml \
uv run rl @ examples/hendrycks_sanity/rl.toml @ examples/hendrycks_sanity/slurm_rl.toml \
--wandb.project your-project \
--wandb.name your-run
```
+1 -1
View File
@@ -155,7 +155,7 @@ The wiki-search environment supports several configuration options:
You can pass these via the `--env-args` flag in `vf-eval` or configure them in your `rl.toml`:
```toml
[[orchestrator.env]]
[[orchestrator.train.env]]
id = "primeintellect/wiki-search"
args = { max_turns = 5, judge_model = "gpt-4.1" }
```
@@ -760,7 +760,7 @@ class OrchestratorConfig(BaseConfig):
@model_validator(mode="after")
def auto_setup_session_headers(self):
"""Ensure X-Session-ID header is always set for sticky DP-aware routing at the inference router."""
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "example_id")
self.student.client.extra_headers_from_state.setdefault("X-Session-ID", "trajectory_id")
return self
@model_validator(mode="after")
@@ -138,7 +138,7 @@ class ClientConfig(BaseConfig):
"""Maps HTTP header names to environment variable names; each entry is resolved via ``os.getenv`` and merged into request headers. e.g. ``{"X-Prime-Team-ID": "PRIME_TEAM_ID"}``."""
extra_headers_from_state: dict[str, str] = {}
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "example_id"}`` enables sticky routing at the inference router."""
"""Maps HTTP header names to rollout-state field names. The header value is read from the rollout state dict on every request. e.g. ``{"X-Session-ID": "trajectory_id"}`` enables sticky routing at the inference router."""
skip_model_check: bool = False
"""Skip checking that the model is available in the inference pool. Useful for external APIs or keys that do not expose ``/models``."""
+19 -5
View File
@@ -44,11 +44,19 @@ assert_supported_platform() {
}
has_ssh_access() {
# Probe SSH auth to GitHub without prompting; treat any nonzero as "no ssh"
# We try a quick ls-remote to avoid cloning on failure.
# Disable -e for the probe so the script doesn't exit on a failed test.
# Probe GitHub SSH auth directly. `ssh -T git@github.com` returns
# "successfully authenticated" only when the local key is registered
# with a GitHub user, which is the precondition for cloning private
# submodules over SSH. The previous `git ls-remote` probe could
# spuriously succeed (cached creds, public-repo edge cases) and
# leave submodule clones to fail later.
#
# Note: ssh -T git@github.com always exits 1 (GitHub denies shell
# access after authenticating), so we capture stdout/stderr to a var
# first and grep the var. Piping directly would trigger pipefail.
set +e
timeout 5s git ls-remote --heads git@github.com:PrimeIntellect-ai/${REPO_ID}.git >/dev/null 2>&1
out=$(timeout 5s ssh -o BatchMode=yes -T git@github.com 2>&1)
echo "$out" | grep -q "successfully authenticated"
rc=$?
set -e
return $rc
@@ -122,7 +130,13 @@ main() {
fi
if ! has_ssh_access; then
git config url."https://github.com/".insteadOf "git@github.com:"
# Propagate the rewrite via env vars so it reaches `git submodule--helper clone`,
# which spawns fresh `git clone` processes that do not read the parent repo's
# local `.git/config`. Local `git config url..insteadOf` is invisible to them.
log_info "Routing git@github.com: SSH URLs to HTTPS for this run."
export GIT_CONFIG_COUNT=1
export GIT_CONFIG_KEY_0="url.https://github.com/.insteadOf"
export GIT_CONFIG_VALUE_0="git@github.com:"
fi
log_info "Initializing submodules..."
+12 -10
View File
@@ -11,24 +11,24 @@ class EventLoopLagMonitor:
def __init__(
self,
interval: float = 1.0,
interval: float = 0.1,
max_window_size: int = 10000,
warn_med_lag_threshold: float = 0.5,
warn_p90_lag_threshold: float = 1.0,
warn_max_lag_threshold: float = 5.0,
warn_p99_lag_threshold: float = 5.0,
warn_max_lag_threshold: float = 30.0,
):
assert (
interval > 0
and max_window_size > 0
and warn_max_lag_threshold > 0
and warn_med_lag_threshold > 0
and warn_p90_lag_threshold > 0
and warn_p99_lag_threshold > 0
and warn_max_lag_threshold > 0
)
self.interval = interval
self.max_window_size = max_window_size
self.warn_max_lag_threshold = warn_max_lag_threshold
self.warn_med_lag_threshold = warn_med_lag_threshold
self.warn_p90_lag_threshold = warn_p90_lag_threshold
self.warn_p99_lag_threshold = warn_p99_lag_threshold
self.warn_max_lag_threshold = warn_max_lag_threshold
self.logger = get_logger()
self.lags = []
@@ -61,15 +61,16 @@ class EventLoopLagMonitor:
mean_lag = float(np.mean(last_lags))
med_lag = float(np.median(last_lags))
p90_lag = float(np.percentile(last_lags, 90))
p99_lag = float(np.percentile(last_lags, 99))
min_lag = float(np.min(last_lags))
max_lag = float(np.max(last_lags))
if (
med_lag > self.warn_med_lag_threshold
or p90_lag > self.warn_p90_lag_threshold
p90_lag > self.warn_p90_lag_threshold
or p99_lag > self.warn_p99_lag_threshold
or max_lag > self.warn_max_lag_threshold
):
self.logger.warning(
f"Detected busy event loop. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
f"Detected busy event loop. Measured {mean_lag:.1f}s (min={min_lag:.1f}s, med={med_lag:.1f}s, p90={p90_lag:.1f}s, p99={p99_lag:.1f}s, max={max_lag:.1f}s) event loop lag over the last {len(last_lags)} measurement(s)"
)
return {
@@ -77,5 +78,6 @@ class EventLoopLagMonitor:
"event_loop_lag/mean": mean_lag,
"event_loop_lag/med": med_lag,
"event_loop_lag/p90": p90_lag,
"event_loop_lag/p99": p99_lag,
"event_loop_lag/max": max_lag,
}
+27 -18
View File
@@ -13,9 +13,9 @@ from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
from prime_rl.orchestrator.trajectories import (
backfill_rollout_tokens,
interleave_rollout,
offload_images_to_disk,
pretokenize_rollout_trajectory,
)
from prime_rl.transport import TrainingBatch, TrainingSample, setup_training_batch_sender
from prime_rl.utils.pathing import get_log_dir, get_rollout_dir, get_step_path
@@ -428,10 +428,10 @@ async def orchestrate(config: OrchestratorConfig):
# Compute advantages (in-place)
num_rollouts = len(train_rollouts)
num_unique_examples = len({(r["env_name"], r["example_id"]) for r in train_rollouts})
compute_advantages(train_rollouts, config.advantage)
await asyncio.to_thread(compute_advantages, train_rollouts, config.advantage)
# Apply rollout filters — sets rollout["filters"] and rollout["is_filtered"]
apply_filters(rollout_filters, train_rollouts)
await asyncio.to_thread(apply_filters, rollout_filters, train_rollouts)
n_trainable = sum(1 for r in train_rollouts if not r["is_filtered"])
if n_trainable > 0:
@@ -482,22 +482,28 @@ async def orchestrate(config: OrchestratorConfig):
# Convert rollouts to training samples
parallel_preprocess_start = time.perf_counter()
# Pretokenize is a no-op when the renderer client already populated
# ``tokens`` on each trajectory step (renderer path); the fallback
# tokenizer-only branch handles text-only rollouts whose tokens
# were not pre-rendered. Run on threads so CPU work overlaps with
# inference for the next batch (via max_async_level >= 2).
await asyncio.gather(
*(
asyncio.to_thread(
pretokenize_rollout_trajectory,
rollout,
tokenizer,
renderer=renderer,
# We only expect to backfill tokens for training_mode=sft against an
# external teacher API (OpenAI/etc.), which returns no token IDs —
# reconstruct via tokenizer/renderer. The vLLM-served paths (RL/OPD
# renderer + MITO, and training_mode=sft against a local vLLM teacher)
# already populate tokens via prompt_token_ids/token_ids, so we
# short-circuit the 256-way fanout.
needs_backfill = any(step["tokens"] is None for rollout in train_rollouts for step in rollout["trajectory"])
if needs_backfill:
logger.info(
"Backfilling tokens for rollout trajectories (expected for training_mode=sft against an external teacher API)"
)
await asyncio.gather(
*(
asyncio.to_thread(
backfill_rollout_tokens,
rollout,
tokenizer,
renderer=renderer,
)
for rollout in train_rollouts
)
for rollout in train_rollouts
)
)
# Process rollouts in parallel
results = await asyncio.gather(
@@ -564,7 +570,7 @@ async def orchestrate(config: OrchestratorConfig):
step=progress.step,
)
training_batch_sender.send(training_batch)
await training_batch_sender.send(training_batch)
step_time = time.perf_counter() - step_start_time
@@ -863,6 +869,9 @@ async def orchestrate(config: OrchestratorConfig):
def main():
"""Main entry-point for orchestrator. Run using `uv run orchestrator`"""
set_proc_title("Orchestrator")
import uvloop
uvloop.install()
asyncio.run(orchestrate(cli(OrchestratorConfig)))
+72 -52
View File
@@ -164,7 +164,7 @@ def _tokenize_step_with_renderer(
return build_trajectory_step(renderer, prompt, completion, tools=tools)
def pretokenize_rollout_trajectory(
def backfill_rollout_tokens(
output: vf.RolloutOutput,
tokenizer: PreTrainedTokenizer,
renderer=None,
@@ -174,6 +174,9 @@ def pretokenize_rollout_trajectory(
When a renderer is provided, uses it for tokenization (faster, deterministic).
Otherwise falls back to the tokenizer + apply_chat_template path.
"""
if all(step["tokens"] is not None for step in output["trajectory"]):
return True
logger = get_logger()
tools = _convert_tools_to_oai_format(output.get("tool_defs", []))
@@ -249,9 +252,9 @@ def interleave_rollout(
return {
"prompt_ids": list(tokens["prompt_ids"]),
"prompt_mask": [bool(i) for i in tokens["prompt_mask"]],
"prompt_mask": list(map(bool, tokens["prompt_mask"])),
"completion_ids": list(tokens["completion_ids"]),
"completion_mask": [bool(i) for i in tokens["completion_mask"]],
"completion_mask": list(map(bool, tokens["completion_mask"])),
"completion_logprobs": list(tokens["completion_logprobs"]),
"routed_experts": routed_experts,
# Renderer-emitted multimodal sidecar (placeholders + per-item
@@ -271,31 +274,22 @@ def interleave_rollout(
return None
prepared_steps.append(prepared)
# 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]] = {}
def make_sample(tokens: dict[str, Any]) -> TrainingSample:
"""Create a new TrainingSample from a trajectory step."""
if has_error:
completion_mask = [False] * len(tokens["completion_mask"])
else:
completion_mask = [bool(i) for i in tokens["completion_mask"]]
completion_mask = list(tokens["completion_mask"])
completion_ids = list(tokens["completion_ids"])
routed_experts = align_routed_experts(
tokens.get("routed_experts"),
len(tokens["prompt_ids"]) + len(tokens["completion_ids"]),
)
packed_routed_experts = None
if routed_experts is not None:
routed_experts = np.ascontiguousarray(routed_experts)
packed_routed_experts = RoutedExperts(
data=routed_experts.tobytes(),
shape=list(routed_experts.shape),
dtype=str(routed_experts.dtype),
)
prompt_ids = list(tokens["prompt_ids"])
sample = TrainingSample(
prompt_ids=prompt_ids,
prompt_mask=[bool(i) for i in tokens["prompt_mask"]],
prompt_mask=list(tokens["prompt_mask"]),
completion_ids=completion_ids,
completion_mask=completion_mask,
completion_logprobs=list(tokens["completion_logprobs"]),
@@ -304,16 +298,25 @@ def interleave_rollout(
advantage=None,
env_name=output["env_name"],
mm_token_type_ids=None,
routed_experts=packed_routed_experts,
routed_experts=None, # deferred — finalized at end of interleave_rollout
)
return sample, routed_experts
# Initialize routed-experts state for this sample. First chunk is the
# raw step routed_experts (no pad, no copy). running_len is the
# cumulative count across chunks; tracked so the boundary fix-up at
# each extension is a no-op append rather than a destructive write.
step_routed = tokens.get("routed_experts")
if step_routed is not None:
sample_routed_state[id(sample)] = {
"chunks": [step_routed],
"running_len": int(step_routed.shape[0]),
}
return sample
def extend_sample(
sample: TrainingSample,
sample_routed_experts: np.ndarray | None,
prefix_len: int,
step_idx: int,
) -> np.ndarray | None:
) -> None:
"""Extend an existing sample with a new trajectory step (extension property holds)."""
tokens = prepared_steps[step_idx]
@@ -330,39 +333,36 @@ def interleave_rollout(
if has_error:
sample.completion_mask.extend([False] * len(tokens["completion_mask"]))
else:
sample.completion_mask.extend(bool(i) for i in tokens["completion_mask"])
sample.completion_mask.extend(tokens["completion_mask"])
sample.completion_logprobs.extend(tokens["completion_logprobs"])
sample.completion_temperatures.extend([temperature] * len(completion_ids))
if tokens.get("routed_experts") is not None and sample_routed_experts is not None:
step_routed = tokens["routed_experts"]
# The previous step's last routing entry was zero-padded by align_routed_experts
# (vLLM only captures num_tokens-1 routings per request). This step actually
# processed that boundary token as part of its prompt, so replace the zero-fill
# with the real routing decision before appending new entries.
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]:
sample_routed_experts[prefix_len - 1] = step_routed[prefix_len - 1]
sample_routed_experts = np.concatenate((sample_routed_experts, step_routed[prefix_len:]), axis=0)
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
sample_routed_experts = align_routed_experts(sample_routed_experts, expected_len)
sample_routed_experts = np.ascontiguousarray(sample_routed_experts)
packed_routed_experts = RoutedExperts(
data=sample_routed_experts.tobytes(),
shape=list(sample_routed_experts.shape),
dtype=str(sample_routed_experts.dtype),
)
sample.routed_experts = packed_routed_experts
return sample_routed_experts
boundary_chunk = step_routed[prefix_len - 1 : prefix_len]
state["chunks"].append(boundary_chunk)
state["running_len"] += 1
new_chunk = step_routed[prefix_len:]
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], np.ndarray | None]] = []
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, first_routed_experts = make_sample(first_tokens)
active_samples.append((first_prefix, first_sample, [0], first_routed_experts))
first_sample = make_sample(first_tokens)
active_samples.append((first_prefix, first_sample, [0]))
for step_idx, _step in enumerate(trajectory[1:], start=1):
tokens = prepared_steps[step_idx]
@@ -370,20 +370,19 @@ def interleave_rollout(
# Check if this step extends ANY active prefix
matched_idx = None
for idx, (prefix_tokens, _, _, _) in enumerate(active_samples):
for idx, (prefix_tokens, _, _) in enumerate(active_samples):
if step_prompt_ids[: len(prefix_tokens)] == prefix_tokens:
matched_idx = idx
break
if matched_idx is not None:
# Extension holds - merge into matched sample
prefix_tokens, sample, step_indices, sample_routed_experts = active_samples[matched_idx]
sample_routed_experts = extend_sample(sample, sample_routed_experts, len(prefix_tokens), step_idx=step_idx)
prefix_tokens, sample, step_indices = active_samples[matched_idx]
extend_sample(sample, len(prefix_tokens), step_idx=step_idx)
active_samples[matched_idx] = (
tokens["prompt_ids"] + tokens["completion_ids"],
sample,
step_indices + [step_idx],
sample_routed_experts,
)
else:
# No prefix matches - start a new sample
@@ -392,8 +391,29 @@ 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, routed_experts = make_sample(tokens)
active_samples.append((new_prefix, sample, [step_idx], routed_experts))
sample = make_sample(tokens)
active_samples.append((new_prefix, sample, [step_idx]))
# 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
# boundary entries between steps were already inserted as one-entry chunks
# during extend_sample, so a straight concat is correct.
for _, sample, _ in active_samples:
state = sample_routed_state.get(id(sample))
if state is None:
continue
chunks = state["chunks"]
if not chunks:
continue
combined = np.concatenate(chunks, axis=0) if len(chunks) > 1 else np.ascontiguousarray(chunks[0])
expected_len = len(sample.prompt_ids) + len(sample.completion_ids)
combined = align_routed_experts(combined, expected_len)
combined = np.ascontiguousarray(combined)
sample.routed_experts = RoutedExperts(
data=combined.tobytes(),
shape=list(combined.shape),
dtype=str(combined.dtype),
)
# Attach images by concatenating mm_items across every step the
# sample covers. verifiers' ``state_to_output`` ships per-step
@@ -402,7 +422,7 @@ def interleave_rollout(
# reading the last step alone would miss every earlier-turn image.
# Concat in step order recovers the per-sample cumulative set;
# deduping again here would drop legitimate duplicate placeholders.
for _, sample, step_indices, _ in active_samples:
for _, sample, step_indices in active_samples:
renderer_mm = _union_step_mm_data(prepared_steps, step_indices)
if renderer_mm is not None:
mm_kwargs = _pack_mm_kwargs_from_renderer(renderer_mm)
@@ -417,7 +437,7 @@ def interleave_rollout(
for token_id in sample.prompt_ids + sample.completion_ids
]
return [sample for _, sample, _, _ in active_samples]
return [sample for _, sample, _ in active_samples]
def _union_step_mm_data(
+4 -4
View File
@@ -1,7 +1,7 @@
import json
import logging
from pathlib import Path
import orjson
import verifiers as vf
from verifiers.utils.save_utils import make_serializable
@@ -82,11 +82,11 @@ def get_tool_response_len(output: vf.RolloutOutput) -> int:
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
"""Save rollouts to a JSONL file using verifiers serialization."""
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w") as f:
opts = orjson.OPT_APPEND_NEWLINE | orjson.OPT_SERIALIZE_NUMPY
with open(path, "wb") as f:
for rollout in rollouts:
row = {k: v for k, v in rollout.items() if k not in exclude_keys} if exclude_keys else rollout
json.dump(row, f, default=make_serializable)
f.write("\n")
f.write(orjson.dumps(row, default=make_serializable, option=opts))
def intercept_vf_logging(logger: str = "verifiers", level: str = "DEBUG", prefix: str | None = None):
+1 -1
View File
@@ -16,7 +16,7 @@ class TrainingBatchSender(ABC):
self.output_dir = output_dir
@abstractmethod
def send(self, batch: TrainingBatch) -> None:
async def send(self, batch: TrainingBatch) -> None:
"""Send a batch of training examples to the trainer(s).
Args:
+6 -2
View File
@@ -1,3 +1,4 @@
import asyncio
from pathlib import Path
from time import time
@@ -18,11 +19,14 @@ class FileSystemTrainingBatchSender(TrainingBatchSender):
super().__init__(output_dir)
self.rollout_dir = get_rollout_dir(output_dir)
def send(self, batch: TrainingBatch) -> None:
"""Send a batch by writing it to disk"""
async def send(self, batch: TrainingBatch) -> None:
"""Send a batch by writing it to disk. Encode + write run in a worker
thread so the orch event loop stays responsive during step transitions."""
step_path = get_step_path(self.rollout_dir, batch.step)
step_path.mkdir(parents=True, exist_ok=True)
await asyncio.to_thread(self._encode_and_write, batch, step_path)
def _encode_and_write(self, batch: TrainingBatch, step_path: Path) -> None:
buffer = self.encoder.encode(batch)
tmp_path = step_path / BATCH_FILE_TMP_NAME
with open(tmp_path, "wb") as f:
+1 -1
View File
@@ -32,7 +32,7 @@ class ZMQTrainingBatchSender(TrainingBatchSender):
f"endpoint=tcp://{transport.host}:{transport.port} hwm={transport.hwm}"
)
def send(self, batch: TrainingBatch) -> None:
async def send(self, batch: TrainingBatch) -> None:
payload = self.encoder.encode(batch)
self.logger.debug(f"Sending batch {batch.step} to {self.sender_id}")
self.socket.send_multipart([self.sender_id, payload], copy=False)
@@ -2,7 +2,7 @@ from unittest.mock import MagicMock
import verifiers as vf
from prime_rl.orchestrator.trajectories import interleave_rollout, pretokenize_rollout_trajectory
from prime_rl.orchestrator.trajectories import backfill_rollout_tokens, interleave_rollout
class SimpleChatTokenizer:
@@ -56,7 +56,7 @@ def test_interleave_rollout_missing_tokens_returns_none():
assert interleave_rollout(output) is None
def test_pretokenize_rollout_trajectory_for_sft():
def test_backfill_rollout_tokens_for_sft():
tokenizer = SimpleChatTokenizer()
output = vf.RolloutOutput(
example_id=42,
@@ -93,7 +93,7 @@ def test_pretokenize_rollout_trajectory_for_sft():
error=None,
)
pretokenize_rollout_trajectory(output, tokenizer)
backfill_rollout_tokens(output, tokenizer)
rollouts = interleave_rollout(output)
assert rollouts is not None
Generated
+3 -1
View File
@@ -15,7 +15,7 @@ conflicts = [[
]]
[options]
exclude-newer = "2026-05-14T14:58:09.755544055Z"
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]
@@ -5907,6 +5907,7 @@ dependencies = [
{ name = "setproctitle", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "tenacity", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "textual", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy')" },
{ name = "uvloop", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'aarch64' and platform_python_implementation != 'PyPy' and sys_platform == 'linux') or (platform_machine == 'x86_64' and platform_python_implementation != 'PyPy' and sys_platform == 'linux') or (platform_machine == 'aarch64' and platform_python_implementation == 'PyPy' and extra == 'extra-9-verifiers-openenv' and extra == 'group-9-verifiers-policy') or (platform_machine == 'x86_64' and platform_python_implementation == 'PyPy' 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')" },
]
[package.optional-dependencies]
@@ -6010,6 +6011,7 @@ requires-dist = [
{ name = "torch", marker = "extra == 'rl'", specifier = ">=2.8.0,<2.9.0", index = "https://download.pytorch.org/whl/cu128" },
{ name = "transformers", marker = "extra == 'rl'", git = "https://github.com/huggingface/transformers.git?rev=c1c3424" },
{ name = "typing-extensions", marker = "python_full_version < '3.12'" },
{ name = "uvloop", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'", specifier = ">=0.21.0" },
{ name = "vllm", marker = "platform_machine == 'aarch64' and extra == 'rl'", 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 != 'aarch64' and platform_machine != 'x86_64' and extra == 'rl'", specifier = ">=0.10.0,<0.11.0" },
{ name = "vllm", marker = "platform_machine == 'x86_64' and extra == 'rl'", 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" },