Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4df5b6229f | ||
|
|
ae1461e7a1 | ||
|
|
7e8355003a | ||
|
|
81822debb6 | ||
|
|
8e978063b4 |
+1
-1
Submodule configs/private updated: 74c1330008...894caa0047
Vendored
+1
-1
Submodule deps/verifiers updated: 521d436c55...04651bec3e
+12
-13
@@ -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
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
@@ -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
@@ -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..."
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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)))
|
||||
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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" },
|
||||
|
||||
Reference in New Issue
Block a user