Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
618de8a511 | ||
|
|
eead822cb3 | ||
|
|
aeaf4c44f1 | ||
|
|
241d8e931e | ||
|
|
f510ef62cb | ||
|
|
26cdf2ee1d | ||
|
|
ae748fd69d | ||
|
|
083127fe32 | ||
|
|
b90aca4221 | ||
|
|
d3727060cb | ||
|
|
1891771201 | ||
|
|
10bc02c6dc |
@@ -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.
|
||||
|
||||
@@ -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,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)
|
||||
|
||||
@@ -18,7 +18,6 @@ level = "debug"
|
||||
[wandb]
|
||||
project = "sami_debug_nemotron"
|
||||
name = "nemotron-120b-math"
|
||||
shared = true
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
@@ -17,7 +17,6 @@ level = "debug"
|
||||
[wandb]
|
||||
project = "nemotron_sami_debug"
|
||||
name = "nemotron-120b-math"
|
||||
shared = true
|
||||
|
||||
[weight_broadcast]
|
||||
type = "nccl"
|
||||
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: 2ec28a8543...35c2407e92
Vendored
+1
-1
Submodule deps/verifiers updated: f9c68eb28c...43016ea6e4
+2
-1
@@ -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
@@ -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'" },
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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])
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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]
|
||||
|
||||
Reference in New Issue
Block a user