Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56a9402953 | ||
|
|
0c0b92f99c | ||
|
|
84ce4d6677 | ||
|
|
01e959596a | ||
|
|
738eb5016a | ||
|
|
06eb91d7c8 | ||
|
|
327f378e07 | ||
|
|
4aeca13870 | ||
|
|
8ab86036b2 | ||
|
|
f0bc8f1fab |
@@ -34,8 +34,42 @@ concurrency:
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
authorize:
|
||||
name: Authorize dispatcher
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Require maintain or admin
|
||||
# Gate MANUAL dispatches only; other events (e.g. release) are
|
||||
# already privileged and pass through. Guard the step, not the job —
|
||||
# a skipped job would skip `prepare` via `needs: authorize`.
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
ACTOR: ${{ github.triggering_actor }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
# Restricted to repo members with maintain or admin. Automated
|
||||
# in-repo dispatches (devx_tag dev-image builds, the release build)
|
||||
# run as github-actions[bot] via GITHUB_TOKEN — allow those through.
|
||||
if [ "$ACTOR" = "github-actions[bot]" ]; then
|
||||
echo "Dispatcher is repo automation ($ACTOR); allowed."
|
||||
exit 0
|
||||
fi
|
||||
role=$(gh api "repos/${REPO}/collaborators/${ACTOR}/permission" --jq '.role_name' 2>/dev/null || true)
|
||||
echo "Dispatcher $ACTOR has repo role: ${role:-<none>}"
|
||||
case "$role" in
|
||||
admin|maintain)
|
||||
echo "Authorized." ;;
|
||||
*)
|
||||
echo "::error::$ACTOR (role: ${role:-none}) is not allowed to trigger image builds; requires maintain or admin." >&2
|
||||
exit 1 ;;
|
||||
esac
|
||||
|
||||
prepare:
|
||||
name: Prepare build
|
||||
needs: authorize
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -81,27 +115,30 @@ jobs:
|
||||
INPUT_TAG: ${{ env.BUILD_TAG }}
|
||||
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
|
||||
run: |
|
||||
case "$INPUT_REF" in
|
||||
main|v[0-9]*|*.dev[0-9]*) ;;
|
||||
*)
|
||||
echo "ref '${INPUT_REF}' not allowed for ghcr publish (must be main, v*, or *.dev*)" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -n "$INPUT_TAG" ] && [ "$INPUT_TAG" != "$INPUT_REF" ] && [ "$INPUT_REF" != "main" ]; then
|
||||
echo "custom 'tag' that differs from 'ref' is only allowed when ref=main; got ref='${INPUT_REF}' tag='${INPUT_TAG}'" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
raw_tag="$INPUT_TAG"
|
||||
if [ -z "$raw_tag" ]; then
|
||||
raw_tag="$INPUT_REF"
|
||||
sanitize() {
|
||||
echo "$1" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//' | cut -c1-50
|
||||
}
|
||||
|
||||
# A ref that is exactly a git tag builds under that tag verbatim;
|
||||
# any other ref (branch / arbitrary commit) is prefixed with
|
||||
# `git describe` so the tag carries the nearest release, commit
|
||||
# distance and short sha (e.g. v0.7.0-42-g1a2b3c4d5-fix-my-branch)
|
||||
# and can't collide with a clean release tag.
|
||||
if [ -n "$INPUT_TAG" ]; then
|
||||
tag=$(sanitize "$INPUT_TAG")
|
||||
elif tag=$(git describe --tags --exact-match 2>/dev/null); then
|
||||
:
|
||||
else
|
||||
tag="$(git describe --tags --always)-$(sanitize "$INPUT_REF")"
|
||||
fi
|
||||
|
||||
tag=$(echo "$raw_tag" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | cut -c1-50 | sed 's/^-//;s/-$//')
|
||||
if [ -z "$tag" ]; then
|
||||
echo "Could not derive a valid image tag from '${raw_tag}'." >&2
|
||||
echo "Could not derive a valid image tag from ref='${INPUT_REF}' tag='${INPUT_TAG}'." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
+3
-2
@@ -8,8 +8,9 @@ Configurations for running prime-rl.
|
||||
Envs: `reverse-text`, `alphabet-sort`, `wiki-search`, `wordle`, `hendrycks-sanity`.
|
||||
- **`ci/`** — integration and nightly configs used by CI.
|
||||
- **`debug/`** — throwaway configs for developing the framework itself: `algo/`
|
||||
(per-algorithm smokes) and `fake/` (fake-data trainer/SFT smokes). Not guaranteed
|
||||
functional or up to date.
|
||||
(per-algorithm smokes), `fake/` (fake-data trainer/SFT smokes), and `multi-env/`
|
||||
(two reverse-text train sources + one eval source, one env server per source). Not
|
||||
guaranteed functional or up to date.
|
||||
|
||||
```bash
|
||||
uv run rl @ configs/basic/<env>/rl.toml
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# Env server for the multi-run RL integration test: one per orchestrator, each bound at
|
||||
# its run's base port (the test passes --serve.address).
|
||||
[env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[env.agent.runtime]
|
||||
type = "subprocess"
|
||||
@@ -0,0 +1,67 @@
|
||||
# Minimal multi-env debug run: two reverse-text train sources + one eval source.
|
||||
# The launcher spawns one env server per source at its derived address
|
||||
# (tcp://127.0.0.1:5000-5002); the orchestrator connects to each.
|
||||
max_steps = 10
|
||||
seq_len = 2048
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-a"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[[orchestrator.train.source]]
|
||||
name = "reverse-text-b"
|
||||
|
||||
[orchestrator.train.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.train.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.train.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
num_examples = 64
|
||||
|
||||
[orchestrator.eval.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.eval.source]]
|
||||
name = "reverse-text"
|
||||
|
||||
[orchestrator.eval.source.env.taskset]
|
||||
id = "reverse-text-v1"
|
||||
|
||||
[orchestrator.eval.source.env.agent.harness]
|
||||
id = "null"
|
||||
|
||||
[orchestrator.eval.source.env.agent.runtime]
|
||||
type = "subprocess"
|
||||
|
||||
[trainer.optim]
|
||||
lr = 3e-6
|
||||
|
||||
[inference]
|
||||
gpu_memory_utilization = 0.5
|
||||
+1
-1
@@ -293,6 +293,6 @@ enable_router_replay = true # this will also auto-set the inference.enable_retur
|
||||
enable_return_routed_experts = true
|
||||
```
|
||||
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env-server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
|
||||
This however is not free, it adds a significant overhead to the HTTP requests as this payload can grow quite large. We reccomend sizing up the env server pool (`orchestrator.*.source.serve.pool`) to allow for more parallelization on the verifiers side.
|
||||
|
||||
Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.
|
||||
|
||||
+4
-5
@@ -36,7 +36,8 @@ This page covers everything you need to launch, observe, checkpoint, and recover
|
||||
| `uv run sft` | Supervised fine-tuning on a HF dataset. | Launches torchrun internally; never call torchrun directly. |
|
||||
| `uv run inference` | vLLM server. | Always use this entrypoint over `vllm serve` — it adds `/update_weights`, `/load_lora_adapter`, and `/init_broadcaster`. |
|
||||
| `uv run trainer` | Standalone trainer process group. | Use only when launching the trainer separately from the orchestrator (e.g. multi-node RL without the `rl` wrapper). |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer + inference. |
|
||||
| `uv run orchestrator` | Standalone orchestrator process. | Pair with a separately-launched trainer, inference, and one `env-server` per source. |
|
||||
| `uv run env-server` | Standalone env server for one environment. | The `rl` launcher starts these automatically (one per train/eval source, at the source's derived `serve.address`); only needed when running the orchestrator standalone. |
|
||||
|
||||
## RL Trainer
|
||||
|
||||
@@ -271,12 +272,10 @@ The launcher tees every process's stdout/stderr into `<output_dir>/logs/`. The f
|
||||
├── inference/
|
||||
│ ├── node_*.log # per-node inference stdout (multi-node only)
|
||||
│ └── router.log # the single global router (multi-node only)
|
||||
└── envs/{train,eval}/<env_name>/
|
||||
├── env_server.log
|
||||
└── env_worker_<id>.log
|
||||
└── envs/{train,eval}/<env_name>.log # one env server process per source (broker + its workers)
|
||||
```
|
||||
|
||||
Env worker logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
Env logs are the first place to look for env-side errors (most user code lives there). Verbosity is controlled by `orchestrator.log.vf_level`. For multi-rank trainer debugging, drop into `logs/trainer/torchrun/<rdzv>/attempt_0/<rank>/{stdout,stderr}.log` — verbose and per-rank.
|
||||
|
||||
Live tailing from a single point (works on the head node for multi-node runs over a shared filesystem):
|
||||
|
||||
|
||||
@@ -1,14 +1,66 @@
|
||||
from pathlib import Path
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import SerializeAsAny, model_validator
|
||||
|
||||
from prime_rl.configs.shared import LogConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
|
||||
|
||||
class EnvServerConfig(BaseConfig):
|
||||
env: EnvConfig
|
||||
"""``uv run env-server``: what to serve (``[env]``, or ``[legacy]`` for a classic v0
|
||||
env) and how it's hosted (``[serve]``). The ``rl`` launcher writes one of these per
|
||||
train/eval source, with ``serve.address`` set to the source's derived address."""
|
||||
|
||||
env: SerializeAsAny[vf.EnvConfig] = vf.SingleAgentEnvConfig()
|
||||
"""The environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
|
||||
serve: vf.ServeConfig = vf.ServeConfig()
|
||||
"""How it's served: the worker pool, the bind address, each worker's episode bound."""
|
||||
|
||||
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
|
||||
"""A classic (v0) environment to serve through the bridge instead of ``env``."""
|
||||
|
||||
log: LogConfig = LogConfig()
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — logs and any generated artifacts are written as subdirectories."""
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _resolve_env(cls, data):
|
||||
"""Narrow ``env`` to the selected env's config class."""
|
||||
return vf.resolve_env_field(data, vf.narrowed_env_annotation(cls))
|
||||
|
||||
@property
|
||||
def is_legacy(self) -> bool:
|
||||
"""Whether this serves the v0 bridge: a legacy id and no v1 taskset."""
|
||||
return self.legacy.id is not None and not self.env.taskset.id
|
||||
|
||||
@property
|
||||
def env_id(self) -> str:
|
||||
"""The served env's identifier: the v1 env's, else the v0 env id."""
|
||||
return self.env.env_id or self.legacy.id or ""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_env(self):
|
||||
# A v0 id next to any v1 env identity leaves one of the two going nowhere, and
|
||||
# which one depends on `is_legacy`: a taskset makes it False, so the v0 env never
|
||||
# loads; a bare `env.id` leaves it True, so the v0 env runs under the v1 name.
|
||||
if self.legacy.id is not None and self.env.env_id:
|
||||
if self.env.taskset.id:
|
||||
raise ValueError(
|
||||
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with "
|
||||
f"the v1 taskset {self.env.taskset.id!r}. Pairing a reusable env with a taskset "
|
||||
f"is env.id = {self.legacy.id!r}; to run the v0 env instead, drop the taskset."
|
||||
)
|
||||
raise ValueError(
|
||||
f"legacy.id {self.legacy.id!r} is a classic (v0) env and can't combine with the "
|
||||
f"v1 env.id {self.env.id!r}: the v0 env is what would run, stamped with the v1 "
|
||||
"env's name. Keep whichever one you meant to run."
|
||||
)
|
||||
if not self.env_id:
|
||||
raise ValueError(
|
||||
'no env configured — set env = { taskset = { id = "<id>" } } (v1) or legacy = { id = "<id>" } (v0)'
|
||||
)
|
||||
return self
|
||||
|
||||
@@ -4,6 +4,7 @@ from typing import Annotated, Any, Literal, TypeAlias
|
||||
import verifiers.v1 as vf
|
||||
from pydantic import Field, SerializeAsAny, model_validator
|
||||
from renderers import AutoRendererConfig, RendererConfig
|
||||
from verifiers.v1.configs.serve import PoolConfig
|
||||
|
||||
from prime_rl.configs.algorithm import (
|
||||
AlgoConfig,
|
||||
@@ -122,15 +123,19 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return args
|
||||
|
||||
|
||||
class ServeConfig(vf.ServeConfig):
|
||||
"""Verifiers' serve block with ``address`` back to optional. Verifiers defaults it
|
||||
to a fixed local bind address; here the question is whether to spawn a server or
|
||||
connect to one already running, and that answer has to survive the resolved config
|
||||
being written to a file and read back — so it must be a *value* (``None``), not
|
||||
field-set metadata, which a round-trip drops."""
|
||||
class ServeConfig(BaseConfig):
|
||||
"""The subset of verifiers' ``ServeConfig`` a source configures — the worker pool
|
||||
and the per-worker bound. The launcher materializes it into the env server's full
|
||||
``[serve]`` block, filling in the source's derived address
|
||||
(``OrchestratorConfig.env_addresses``)."""
|
||||
|
||||
address: str | None = None
|
||||
"""ZMQ address of an external env server (e.g. ``tcp://host:5000``). When set, the orchestrator connects to that server instead of spawning one; when None, it spawns a subprocess env server on a free port. ``pool`` sizes the spawned server."""
|
||||
pool: PoolConfig = Field(default_factory=vf.ElasticPoolConfig)
|
||||
"""Worker-pool sizing. ``elastic`` (default) starts at one worker and scales up on
|
||||
demand; ``static`` pre-spawns a fixed ``num_workers``."""
|
||||
|
||||
max_concurrent: int | None = Field(None, ge=1)
|
||||
"""Episodes in flight per worker (None = unbounded; the dispatcher's
|
||||
``max_inflight_episodes`` is the run's bound)."""
|
||||
|
||||
|
||||
class EnvConfig(BaseConfig):
|
||||
@@ -142,7 +147,7 @@ class EnvConfig(BaseConfig):
|
||||
"""The verifiers environment — which env, its seed taskset, each agent, its knobs. Narrowed to the selected env's config class by the env id, else the taskset id."""
|
||||
|
||||
serve: ServeConfig = ServeConfig()
|
||||
"""How the env server is run: ``serve.pool`` sizes the spawned server, ``serve.address`` points at an external one instead, and ``serve.max_concurrent`` bounds one worker's episodes in flight (unset = unbounded; the dispatcher's ``max_inflight_episodes`` is the run's bound)."""
|
||||
"""How this source's env server is sized. Consumed by the launcher (which writes each source's env-server config), not by the orchestrator — the orchestrator only connects."""
|
||||
|
||||
legacy: vf.LegacyEnvConfig = vf.LegacyEnvConfig()
|
||||
"""A classic (v0) environment to run through the bridge instead of ``env``."""
|
||||
@@ -296,6 +301,11 @@ class EvalConfig(BaseConfig):
|
||||
"""If True, skip the startup eval that otherwise runs before any
|
||||
train rollouts."""
|
||||
|
||||
retrigger_on_resume: bool = False
|
||||
"""If True, re-trigger evals at the checkpoint step on resume (e.g. after a
|
||||
crash that left in-flight evals unfinished). By default, assumes a clean
|
||||
exit where all evals already completed."""
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_examples,
|
||||
@@ -524,6 +534,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Rate limit per environment worker, in tasks per minute. Recommended for sandbox-backed environments to prevent sandbox-not-ready errors during autoscaling. With multiple workers, the effective total rate is ``workers × this value``. None disables rate limiting."""
|
||||
|
||||
env_server_base_port: int = Field(5000, ge=1, le=65535)
|
||||
"""First port of the env-server port range: the source at position ``i`` (train, then eval) is served at ``tcp://127.0.0.1:<base + i>``. Give concurrent runs on one host distinct bases (e.g. one per multi-run orchestrator)."""
|
||||
|
||||
batch_size: int | None = Field(None, ge=1)
|
||||
"""Samples to train on per step (rollout-based batching). Set this OR ``token_batch_size``."""
|
||||
|
||||
@@ -720,3 +733,24 @@ class OrchestratorConfig(BaseConfig):
|
||||
# bridge applies legacy.extra_env_kwargs via env.set_kwargs).
|
||||
env.legacy.extra_env_kwargs["max_seq_len"] = self.seq_len
|
||||
return self
|
||||
|
||||
@property
|
||||
def env_sources(self) -> list[tuple[str, EnvConfig]]:
|
||||
"""Every ``(split, source)`` this run pulls from, train first then eval — the
|
||||
order that fixes each source's deterministic env-server port."""
|
||||
sources: list[tuple[str, EnvConfig]] = [("train", source) for source in self.train.source]
|
||||
if self.eval is not None:
|
||||
sources += [("eval", source) for source in self.eval.source]
|
||||
return sources
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str]:
|
||||
"""Where each source's env server lives, keyed by ``(split, resolved_name)``:
|
||||
``tcp://127.0.0.1:<port>`` with ports from ``env_server_base_port`` in
|
||||
``env_sources`` order. The launcher binds env servers at exactly these addresses
|
||||
and the orchestrator connects to them, so both sides agree from the config
|
||||
alone."""
|
||||
return {
|
||||
(split, source.resolved_name): f"tcp://127.0.0.1:{self.env_server_base_port + index}"
|
||||
for index, (split, source) in enumerate(self.env_sources)
|
||||
}
|
||||
|
||||
@@ -2,12 +2,17 @@ import re
|
||||
|
||||
# (regex, parser_name) — first match wins.
|
||||
TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
# Trinity-Large-Thinking uses the Qwen3-Coder tool format; the rest of the family is Hermes.
|
||||
(re.compile(r"^arcee-ai/Trinity-Large-Thinking"), "qwen3_coder"),
|
||||
(re.compile(r"^arcee-ai/Trinity-"), "hermes"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.2"), "deepseek_v32"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.1"), "deepseek_v31"),
|
||||
(re.compile(r"^zai-org/GLM-4\.5"), "glm45"),
|
||||
(re.compile(r"^zai-org/GLM-4\.7"), "glm47"),
|
||||
(re.compile(r"^zai-org/GLM-5"), "glm47"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2"),
|
||||
(re.compile(r"^openai/gpt-oss"), "openai"),
|
||||
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "qwen3_coder"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3"), "qwen3_coder"),
|
||||
(re.compile(r"^stepfun-ai/Step-3\.5"), "step3p5"),
|
||||
@@ -18,9 +23,13 @@ TOOL_CALL_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
]
|
||||
|
||||
REASONING_PARSER_PATTERNS: list[tuple[re.Pattern[str], str]] = [
|
||||
# Trinity-Large-Preview doesn't reason; the Thinking/Mini/Nano variants do.
|
||||
(re.compile(r"^arcee-ai/Trinity-(Large-Thinking|Mini|Nano)"), "deepseek_r1"),
|
||||
(re.compile(r"^deepseek-ai/DeepSeek-V3\.[12]"), "deepseek_r1"),
|
||||
(re.compile(r"^zai-org/GLM-"), "glm45"),
|
||||
(re.compile(r"^MiniMaxAI/MiniMax-M2"), "minimax_m2_append_think"),
|
||||
# openai/gpt-oss has no entry here — vLLM's harmony serving path splits reasoning natively.
|
||||
(re.compile(r"^poolside/Laguna"), "poolside_v1"),
|
||||
(re.compile(r"^PrimeIntellect/INTELLECT-3"), "deepseek_r1"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Super"), "nemotron_v3"),
|
||||
(re.compile(r"^nvidia/NVIDIA-Nemotron-3-Nano"), "nano_v3"),
|
||||
|
||||
+10
-3
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "prime-rl"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
description = "Async RL Training at Scale"
|
||||
readme = "README.md"
|
||||
requires-python = "~=3.12.0"
|
||||
@@ -53,7 +53,7 @@ sft = "prime_rl.entrypoints.sft:main"
|
||||
inference = "prime_rl.entrypoints.inference:main"
|
||||
trainer = "prime_rl.entrypoints.trainer:main"
|
||||
orchestrator = "prime_rl.entrypoints.orchestrator:main"
|
||||
env-server = "prime_rl.orchestrator.env_server.env_server:main"
|
||||
env-server = "prime_rl.entrypoints.env_server:main"
|
||||
|
||||
[project.entry-points."vllm.general_plugins"]
|
||||
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
|
||||
@@ -235,7 +235,14 @@ explicit = true
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["F", "I"]
|
||||
ignore = ["F722", "F821"] # Need to ignore for jaxtyping (https://docs.kidger.site/jaxtyping/faq/)
|
||||
|
||||
# jaxtyping writes shapes as string annotations (`Int[Tensor, "batch seq"]`), which ruff reads as
|
||||
# forward references and reports as syntax errors / undefined names.
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"src/prime_rl/trainer/model.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/rl/data.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/rl/loss.py" = ["F722", "F821"]
|
||||
"src/prime_rl/trainer/sft/data.py" = ["F722", "F821"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
# `prime_rl` is split across two editable wheels (prime-rl + prime-rl-configs).
|
||||
|
||||
@@ -180,9 +180,9 @@ All processes use `setproctitle` so they're visible in `ps`/`htop`/`pstree`:
|
||||
```
|
||||
PRIME-RL::Launcher
|
||||
├── PRIME-RL::Inference (vLLM server, GPU 0)
|
||||
├── PRIME-RL::Orchestrator (CPU-only)
|
||||
│ └── Verifiers::EnvServer (ZMQ env server per environment)
|
||||
│ └── Verifiers::EnvWorker0..N
|
||||
├── PRIME-RL::EnvServer (verifiers' ZMQ env server, run in-process; one per train/eval source)
|
||||
│ └── Verifiers::EnvWorker0..N
|
||||
├── PRIME-RL::Orchestrator (CPU-only; connects to each env server)
|
||||
├── torchrun
|
||||
│ └── PRIME-RL::Trainer (GPU 1+)
|
||||
└── tail trainer.log
|
||||
|
||||
+8
-10
@@ -12,28 +12,26 @@ from prime_rl.utils.utils import clean_exit
|
||||
|
||||
@clean_exit
|
||||
def run_server(config: EnvServerConfig):
|
||||
env = config.env
|
||||
address = env.serve.address or "tcp://127.0.0.1:5000"
|
||||
# The env's ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
|
||||
# ``serve.pool`` (static or elastic) sizes the server; a v0/legacy env runs through
|
||||
# the bridge, a v1 env is a native env block — both speak the same serve protocol,
|
||||
# so the orchestrator is agnostic. serve_env applies the logging setup in this process
|
||||
# and in every spawned worker.
|
||||
server_kwargs = (
|
||||
{"env_id": env.env_id, "env_args": env.legacy.args, "extra_env_kwargs": env.legacy.extra_env_kwargs}
|
||||
if env.is_legacy
|
||||
else {"config_data": env_config_data(env.env), "max_concurrent": env.serve.max_concurrent}
|
||||
{"env_id": config.env_id, "env_args": config.legacy.args, "extra_env_kwargs": config.legacy.extra_env_kwargs}
|
||||
if config.is_legacy
|
||||
else {"config_data": env_config_data(config.env), "max_concurrent": config.serve.max_concurrent}
|
||||
)
|
||||
serve_env(
|
||||
**pool_serve_kwargs(env.serve.pool),
|
||||
legacy=env.is_legacy,
|
||||
address=address,
|
||||
**pool_serve_kwargs(config.serve.pool),
|
||||
legacy=config.is_legacy,
|
||||
address=config.serve.address,
|
||||
log_setup=partial(setup_env_server_logging, config.log.level, config.log.json_logging),
|
||||
**server_kwargs,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
"""Main entry-point for env-server. Run using `uv run env-server`"""
|
||||
"""Main entry-point for the env server. Run using `uv run env-server`"""
|
||||
set_proc_title("EnvServer")
|
||||
run_server(cli(EnvServerConfig))
|
||||
|
||||
@@ -8,12 +8,14 @@ import uuid
|
||||
from pathlib import Path
|
||||
from subprocess import Popen
|
||||
from threading import Event, Thread
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import pynvml
|
||||
import tomli_w
|
||||
|
||||
from prime_rl.configs.algorithm import FrozenModelConfig
|
||||
from prime_rl.configs.inference import VllmRouterConfig
|
||||
from prime_rl.configs.orchestrator import EnvConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
from prime_rl.entrypoints.inference import vllm_overrides_fragment
|
||||
from prime_rl.utils.config import cli, to_toml_dict
|
||||
@@ -43,6 +45,17 @@ TRAINER_TOML = "trainer.toml"
|
||||
ORCHESTRATOR_TOML = "orchestrator.toml"
|
||||
INFERENCE_TOML = "inference.toml"
|
||||
|
||||
ENVS_DIR = "envs"
|
||||
|
||||
|
||||
def env_servers(config: RLConfig) -> list[tuple[str, EnvConfig, str]]:
|
||||
"""``(split, source, address)`` for every train/eval source. The launcher runs one
|
||||
env server per source at its deterministic address; the orchestrator connects there."""
|
||||
addresses = config.orchestrator.env_addresses
|
||||
return [
|
||||
(split, source, addresses[(split, source.resolved_name)]) for split, source in config.orchestrator.env_sources
|
||||
]
|
||||
|
||||
|
||||
def get_physical_gpu_ids() -> list[int]:
|
||||
"""Return physical GPU IDs visible to the launcher."""
|
||||
@@ -80,6 +93,22 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
|
||||
with open(output_dir / INFERENCE_TOML, "wb") as f:
|
||||
tomli_w.dump(inference_dict, f)
|
||||
|
||||
# One EnvServerConfig TOML per source: `env-server @ <path>` binds at the source's
|
||||
# deterministic address, where the orchestrator connects. The source's env/serve/legacy
|
||||
# blocks carry over; its other knobs (sampling, algo, name, ...) are orchestrator-side.
|
||||
for split, source, address in env_servers(config):
|
||||
env_dir = output_dir / ENVS_DIR / split
|
||||
env_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_dict = to_toml_dict(source)
|
||||
env_server_dict = {
|
||||
"env": source_dict["env"],
|
||||
"serve": {**source_dict.get("serve", {}), "address": address},
|
||||
"legacy": source_dict.get("legacy", {}),
|
||||
"log": {"level": config.orchestrator.log.vf_level, "json_logging": config.orchestrator.log.json_logging},
|
||||
}
|
||||
with open(env_dir / f"{source.resolved_name}.toml", "wb") as f:
|
||||
tomli_w.dump(env_server_dict, f)
|
||||
|
||||
|
||||
def rl_local(config: RLConfig):
|
||||
assert config.deployment.type == "single_node"
|
||||
@@ -131,8 +160,6 @@ def rl_local(config: RLConfig):
|
||||
|
||||
# Validate client port matches inference server port
|
||||
if config.inference is not None and not config.orchestrator.model.client.is_elastic:
|
||||
from urllib.parse import urlparse
|
||||
|
||||
base_url = config.orchestrator.model.client.base_url[0]
|
||||
parsed = urlparse(base_url)
|
||||
client_port = parsed.port
|
||||
@@ -219,6 +246,41 @@ def rl_local(config: RLConfig):
|
||||
"otherwise rollouts will hang."
|
||||
)
|
||||
|
||||
# Start one env server per source. The orchestrator connects to each source's
|
||||
# deterministic address, polling until the server is up, so the servers and the
|
||||
# orchestrator start in parallel.
|
||||
for split, source, address in env_servers(config):
|
||||
name = source.resolved_name
|
||||
env_server_cmd = ["env-server", "@", (config_dir / ENVS_DIR / split / f"{name}.toml").as_posix()]
|
||||
logger.info(f"Starting {split} env server {name} at {address}")
|
||||
logger.debug(f"Env server start command: {' '.join(env_server_cmd)}")
|
||||
env_server_log = log_dir / ENVS_DIR / split / f"{name}.log"
|
||||
env_server_log.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(env_server_log, "w") as log_file:
|
||||
env_server_process = Popen(
|
||||
env_server_cmd,
|
||||
env={
|
||||
**os.environ,
|
||||
**DEFAULT_COMMON_ENV_VARS,
|
||||
**config.env_vars,
|
||||
**config.orchestrator.env_vars,
|
||||
},
|
||||
stdout=log_file,
|
||||
stderr=log_file,
|
||||
)
|
||||
processes.append(env_server_process)
|
||||
|
||||
# Start monitoring thread
|
||||
stop_event = Event()
|
||||
stop_events[f"env/{split}/{name}"] = stop_event
|
||||
monitor_thread = Thread(
|
||||
target=monitor_process,
|
||||
args=(env_server_process, stop_event, error_queue, f"{split} env server {name}"),
|
||||
daemon=True,
|
||||
)
|
||||
monitor_thread.start()
|
||||
monitor_threads.append(monitor_thread)
|
||||
|
||||
orchestrator_cmd = ["orchestrator", "@", (config_dir / ORCHESTRATOR_TOML).as_posix()]
|
||||
logger.info("Starting orchestrator process")
|
||||
logger.debug(f"Orchestrator start command: {' '.join(orchestrator_cmd)}")
|
||||
@@ -391,6 +453,11 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
else {}
|
||||
)
|
||||
|
||||
# Env servers launch next to the orchestrator, one per train/eval source.
|
||||
sources = config.orchestrator.env_sources
|
||||
train_env_names = [source.resolved_name for split, source in sources if split == "train"]
|
||||
eval_env_names = [source.resolved_name for split, source in sources if split == "eval"]
|
||||
|
||||
if config.deployment.type == "single_node":
|
||||
script = template.render(
|
||||
**config.slurm.template_vars,
|
||||
@@ -438,6 +505,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
use_zmq_transport=config.rollout_transport is not None and config.rollout_transport.type == "zmq",
|
||||
ranks_filter=",".join(map(str, config.trainer.log.ranks_filter)),
|
||||
orchestrator_on_inference=config.deployment.orchestrator_on_inference,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
)
|
||||
else:
|
||||
script = template.render(
|
||||
@@ -467,6 +536,8 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
|
||||
trainer_env_vars=trainer_env_vars,
|
||||
orchestrator_env_vars=orchestrator_env_vars,
|
||||
inference_env_vars=inference_env_vars,
|
||||
train_env_names=train_env_names,
|
||||
eval_env_names=eval_env_names,
|
||||
)
|
||||
|
||||
script_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import torch
|
||||
|
||||
from prime_rl.inference.vllm.padded_input_scrub import monkey_patch_vllm_padded_input_scrub
|
||||
|
||||
|
||||
def apply_shared_vllm_patches():
|
||||
"""vLLM general plugin: prime-rl patches that must run in every vLLM process.
|
||||
@@ -16,7 +14,6 @@ def apply_shared_vllm_patches():
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
monkey_patch_qwen3_coder_param_newline_trim()
|
||||
monkey_patch_minimax_m2_think_end_passthrough()
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
monkey_patch_return_routed_experts_with_nixl_connector()
|
||||
monkey_patch_kv_xfer_finished_tolerate_freed()
|
||||
monkey_patch_online_fp8_parameter_cast()
|
||||
|
||||
@@ -10,14 +10,10 @@ def setup_vllm_env(config: InferenceConfig):
|
||||
# spawn is more robust in vLLM nightlies and Qwen3-VL (fork can deadlock with multithreaded processes)
|
||||
os.environ.setdefault("VLLM_WORKER_MULTIPROC_METHOD", "spawn")
|
||||
|
||||
# Force the V1 GPU model runner. vLLM 0.24.0 routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe; the 0.23 MoE/quantized guard was removed) to the
|
||||
# V2 runner, which has no `_preprocess` hook for our padded-input scrub (see
|
||||
# inference/vllm/padded_input_scrub.py) and doesn't zero the padded decode tail
|
||||
# itself; that stale tail poisons CUDA-graph replay as NaN logits (reproduced on
|
||||
# Nemotron-Nano SWE, PR #2506; upstream fix vllm#42779 is still unmerged). V1 keeps
|
||||
# the scrub effective for every model and is also required for routed-experts capture
|
||||
# (the NIXL PD path rejects V2). setdefault so it stays overridable.
|
||||
# Force the V1 GPU model runner. vLLM routes Llama/Mistral/Qwen3 plus MoE archs
|
||||
# (DeepseekV2, Qwen2Moe, GraniteMoe) to the V2 runner by default, but V2 doesn't
|
||||
# support routed-experts capture (the NIXL PD path rejects it). setdefault so it
|
||||
# stays overridable.
|
||||
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
|
||||
|
||||
# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_INSTALL_LOCK = threading.Lock()
|
||||
_INSTALLED = False
|
||||
|
||||
|
||||
def monkey_patch_vllm_padded_input_scrub() -> None:
|
||||
"""Zero vLLM's padded model inputs before graph replay.
|
||||
|
||||
vLLM pads decode batches up to CUDA graph capture sizes. Some kernels read
|
||||
model-input tensors past the scheduled-token prefix, so stale values in the
|
||||
padded tail can affect replayed decode graphs. Keep this shim until the
|
||||
vLLM-side fix is available in the pinned runtime.
|
||||
|
||||
Remove this patch once https://github.com/vllm-project/vllm/pull/42779 is
|
||||
included in the vLLM release we pin/use.
|
||||
"""
|
||||
global _INSTALLED
|
||||
with _INSTALL_LOCK:
|
||||
if _INSTALLED:
|
||||
return
|
||||
|
||||
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
|
||||
|
||||
if getattr(GPUModelRunner, "_prime_rl_padded_input_scrub", False):
|
||||
_INSTALLED = True
|
||||
return
|
||||
|
||||
original_preprocess = GPUModelRunner._preprocess
|
||||
|
||||
def _patched_preprocess(
|
||||
self: Any,
|
||||
scheduler_output: Any,
|
||||
num_input_tokens: int,
|
||||
intermediate_tensors: Any | None = None,
|
||||
) -> tuple[Any, ...]:
|
||||
result = original_preprocess(
|
||||
self,
|
||||
scheduler_output,
|
||||
num_input_tokens,
|
||||
intermediate_tensors,
|
||||
)
|
||||
|
||||
num_scheduled_tokens = int(scheduler_output.total_num_scheduled_tokens)
|
||||
_zero_padded_model_inputs(
|
||||
result,
|
||||
num_scheduled_tokens,
|
||||
int(num_input_tokens),
|
||||
)
|
||||
return result
|
||||
|
||||
GPUModelRunner._preprocess = _patched_preprocess
|
||||
GPUModelRunner._prime_rl_padded_input_scrub = True
|
||||
_INSTALLED = True
|
||||
|
||||
logger.warning("Enabled vLLM padded model-input scrub.")
|
||||
|
||||
|
||||
def _zero_padded_model_inputs(
|
||||
preprocess_result: Sequence[Any],
|
||||
num_scheduled_tokens: int,
|
||||
num_input_tokens: int,
|
||||
) -> None:
|
||||
"""Zero the model-input tail beyond scheduled tokens in-place."""
|
||||
if num_input_tokens <= num_scheduled_tokens:
|
||||
return
|
||||
|
||||
input_ids = preprocess_result[0]
|
||||
inputs_embeds = preprocess_result[1]
|
||||
positions = preprocess_result[2]
|
||||
pad_slice = slice(num_scheduled_tokens, num_input_tokens)
|
||||
|
||||
if input_ids is not None:
|
||||
input_ids[pad_slice].zero_()
|
||||
if inputs_embeds is not None:
|
||||
inputs_embeds[pad_slice].zero_()
|
||||
if positions is not None:
|
||||
if positions.ndim == 1:
|
||||
positions[pad_slice].zero_()
|
||||
else:
|
||||
positions[..., pad_slice].zero_()
|
||||
@@ -25,7 +25,6 @@ from prime_rl.inference.patches import (
|
||||
monkey_patch_nano_v3_reasoning_parser,
|
||||
monkey_patch_strip_routed_experts_from_chat,
|
||||
monkey_patch_tokenize_params_validation,
|
||||
monkey_patch_vllm_padded_input_scrub,
|
||||
)
|
||||
|
||||
# NOTE: Fix harmony stop token propagation for GPT-OSS models
|
||||
@@ -37,9 +36,6 @@ monkey_patch_tokenize_params_validation()
|
||||
# NOTE: Register Nano V3 reasoning parser so configs can use
|
||||
# `reasoning_parser = "nano_v3"` without a vLLM plugin file.
|
||||
monkey_patch_nano_v3_reasoning_parser()
|
||||
# NOTE: Optional mitigation for vLLM padded decode inputs until the native fix
|
||||
# is available in our pinned runtime.
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
# NOTE: routed_experts are consumed only via the serialized /generate path (router
|
||||
# replay). The chat-completions path encodes them as a base64 np.save string the PD
|
||||
# router cannot merge, which fails eval rollouts (they use chat completions). Strip
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"""Env wrappers over a v1 env server.
|
||||
|
||||
Each ``Env`` owns a v1 ``EnvServer`` (spawned as a child process, or an
|
||||
external one pinned by ``config.serve.address``) and an ``EnvClient`` to drive it. The
|
||||
Each ``Env`` is an ``EnvClient`` onto its source's env server. Each server's address
|
||||
is derived from the source's position in the config
|
||||
(``OrchestratorConfig.env_addresses``); the launcher runs the servers at
|
||||
exactly those addresses, and the orchestrator connects. The
|
||||
orchestrator never *runs* an environment — the agents and their runtimes live only
|
||||
in the server — but it does own the *taskset*: a v1 env's tasks are loaded here,
|
||||
once, and each dispatched episode ships its task's data on the request
|
||||
@@ -20,19 +22,12 @@ keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import atexit
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import queue
|
||||
import sys
|
||||
from collections.abc import Iterator, Sequence
|
||||
from itertools import islice
|
||||
from multiprocessing.process import BaseProcess
|
||||
from pathlib import Path
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
import verifiers.v1 as vf
|
||||
from verifiers.v1.serve import EnvClient, env_config_data
|
||||
from verifiers.v1.serve import EnvClient
|
||||
|
||||
from prime_rl.configs.orchestrator import EnvConfig, EvalSourceConfig, TrainSourceConfig
|
||||
from prime_rl.orchestrator.algo import Algorithm, build_algorithm
|
||||
@@ -45,48 +40,19 @@ from prime_rl.utils.logger import get_logger
|
||||
# task.idx + task.model_dump).
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
|
||||
|
||||
# Max wait for a spawned env server to bind and report its address. A legacy
|
||||
# child loads its dataset before reporting, so this is generous.
|
||||
ENV_SERVER_SPAWN_TIMEOUT = 600.0
|
||||
|
||||
|
||||
def _run_env_server(
|
||||
*,
|
||||
log_file: str,
|
||||
log_level: str,
|
||||
json_logging: bool,
|
||||
legacy: bool = False,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
"""Spawned-process entry point: redirect this process's output to ``log_file`` (the
|
||||
server's logging + any subprocess-runtime output), then serve via ``serve_env``. The
|
||||
worker-pool sizing arrives in ``kwargs`` (``max_workers`` / ``multiplex`` / ``elastic``
|
||||
from the env's ``pool``). ``serve_env`` applies ``log_setup`` here and in every spawned
|
||||
worker; a worker inherits this process's redirected stdout/stderr, so its per-rollout
|
||||
logs reach ``log_file`` too. Top-level so it stays picklable for the ``spawn`` start
|
||||
method. ``legacy`` picks the v0 bridge."""
|
||||
from functools import partial
|
||||
|
||||
from verifiers.v1.serve import serve_env
|
||||
|
||||
from prime_rl.orchestrator.utils import setup_env_server_logging
|
||||
|
||||
fh = open(log_file, "w", buffering=1)
|
||||
os.dup2(fh.fileno(), sys.stdout.fileno())
|
||||
os.dup2(fh.fileno(), sys.stderr.fileno())
|
||||
serve_env(
|
||||
legacy=legacy,
|
||||
log_setup=partial(setup_env_server_logging, log_level, json_logging),
|
||||
**kwargs,
|
||||
)
|
||||
# Max wait for the env server to answer health. Generous because the launcher spawns
|
||||
# servers concurrently with the orchestrator, and a legacy server loads its dataset
|
||||
# before serving.
|
||||
ENV_SERVER_STARTUP_TIMEOUT = 600.0
|
||||
|
||||
|
||||
class Env:
|
||||
"""Wraps a v1 env server + client. The orchestrator owns the taskset (loaded once,
|
||||
"""Client onto a v1 env server. The orchestrator owns the taskset (loaded once,
|
||||
client-side); the server owns agent/harness execution."""
|
||||
|
||||
def __init__(self, config: EnvConfig):
|
||||
def __init__(self, config: EnvConfig, address: str):
|
||||
self.config = config
|
||||
self.address = address
|
||||
self.sampling_args: dict = {}
|
||||
self.num_tasks: int | None = 0
|
||||
"""Task count; ``None`` means the taskset is infinite."""
|
||||
@@ -97,7 +63,6 @@ class Env:
|
||||
count) and iterated from there; an infinite one streams off its generator.
|
||||
Consumed once — by ``TrainSource`` (train) or ``EvalEnv.start`` (eval)."""
|
||||
self._env_client: EnvClient | None = None
|
||||
self._env_server_process: BaseProcess | None = None
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
@@ -109,17 +74,14 @@ class Env:
|
||||
raise RuntimeError(f"Env {self.name} not started — call start() first.")
|
||||
return self._env_client
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
"""Spawn the env server (if needed), connect, and load the taskset client-side
|
||||
(legacy instead asks the server for ``info`` — its dataset is server-side)."""
|
||||
external = self.config.serve.address is not None
|
||||
address = self.config.serve.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
|
||||
get_logger().debug(f"Connecting {self.name} to env server {address}")
|
||||
self._env_client = EnvClient(address=address)
|
||||
# A spawned server already reported its address *after* binding, so it's up. An
|
||||
# external server has no such handshake, so poll until it answers.
|
||||
if external:
|
||||
await self.env_client.wait_for_server_startup()
|
||||
async def start(self) -> None:
|
||||
"""Connect to the env server and load the taskset client-side (legacy instead
|
||||
asks the server for ``info`` — its dataset is server-side)."""
|
||||
get_logger().debug(f"Connecting {self.name} to env server {self.address}")
|
||||
self._env_client = EnvClient(address=self.address)
|
||||
# The server may still be coming up (the launcher spawns it concurrently with
|
||||
# the orchestrator), so poll until it answers.
|
||||
await self.env_client.wait_for_server_startup(timeout=ENV_SERVER_STARTUP_TIMEOUT)
|
||||
if self.config.is_legacy:
|
||||
info = await self.env_client.info()
|
||||
self.num_tasks = info.num_tasks
|
||||
@@ -137,59 +99,6 @@ class Env:
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
|
||||
|
||||
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
|
||||
"""Spawn a v1 EnvServer child process (it runs the agents; the tasks come from
|
||||
us). The server binds an OS-assigned port (``:0``) and reports the concrete
|
||||
address back over a queue — no free-port guess, no TOCTOU race. Its output
|
||||
goes to ``<log_dir>/<name>.log`` (``log_dir`` is already the train/eval-split
|
||||
``.../logs/envs/{train,eval}`` the orchestrator passes in)."""
|
||||
ctx = mp.get_context("spawn")
|
||||
address_queue: mp.Queue = ctx.Queue()
|
||||
log_file = log_dir / f"{self.name}.log"
|
||||
log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
get_logger().debug(f"Spawning env server {self.name} (id={self.config.env_id}, log={log_file})")
|
||||
server_kwargs = (
|
||||
dict(
|
||||
legacy=True,
|
||||
env_id=self.config.env_id,
|
||||
env_args=self.config.legacy.args,
|
||||
extra_env_kwargs=self.config.legacy.extra_env_kwargs,
|
||||
)
|
||||
if self.config.is_legacy
|
||||
# Picklable dict — the narrowed config class doesn't survive the spawn.
|
||||
# ``max_concurrent`` bounds this worker's episodes in flight — usually unset,
|
||||
# since the dispatcher's ``max_inflight_episodes`` is the run's bound.
|
||||
else dict(
|
||||
legacy=False,
|
||||
config_data=env_config_data(self.config.env),
|
||||
max_concurrent=self.config.serve.max_concurrent,
|
||||
)
|
||||
)
|
||||
process = ctx.Process(
|
||||
target=_run_env_server,
|
||||
kwargs=dict(
|
||||
log_file=str(log_file),
|
||||
log_level=log_level,
|
||||
json_logging=json_logging,
|
||||
**vf.pool_serve_kwargs(self.config.serve.pool),
|
||||
address="tcp://127.0.0.1:0",
|
||||
address_queue=address_queue,
|
||||
**server_kwargs,
|
||||
),
|
||||
daemon=False,
|
||||
)
|
||||
process.start()
|
||||
self._env_server_process = process
|
||||
try:
|
||||
address = await asyncio.to_thread(address_queue.get, timeout=ENV_SERVER_SPAWN_TIMEOUT)
|
||||
except queue.Empty:
|
||||
raise RuntimeError(f"Env server {self.name} did not report its address within {ENV_SERVER_SPAWN_TIMEOUT}s")
|
||||
finally:
|
||||
address_queue.close()
|
||||
address_queue.join_thread()
|
||||
get_logger().debug(f"Env server {self.name} bound at {address}")
|
||||
return address
|
||||
|
||||
def _sampling(self, cache_salt: str | None) -> vf.SamplingConfig:
|
||||
sampling = {**self.sampling_args}
|
||||
if cache_salt is not None:
|
||||
@@ -244,18 +153,12 @@ class Env:
|
||||
)
|
||||
return [ROLLOUT_TYPE.model_construct(**dict(wire)) for wire in wires]
|
||||
|
||||
def shutdown(self) -> None:
|
||||
if self._env_server_process is None:
|
||||
return
|
||||
self._env_server_process.terminate()
|
||||
self._env_server_process = None
|
||||
|
||||
|
||||
class TrainEnv(Env):
|
||||
config: TrainSourceConfig
|
||||
|
||||
def __init__(self, config: TrainSourceConfig, sampler: Sampler, algorithm: Algorithm):
|
||||
super().__init__(config)
|
||||
def __init__(self, config: TrainSourceConfig, address: str, sampler: Sampler, algorithm: Algorithm):
|
||||
super().__init__(config, address)
|
||||
self.sampler = sampler
|
||||
self.algorithm = algorithm
|
||||
self.sampling_args = sampler.sampling_args(config.sampling.to_sampling_args())
|
||||
@@ -264,13 +167,13 @@ class TrainEnv(Env):
|
||||
class EvalEnv(Env):
|
||||
config: EvalSourceConfig
|
||||
|
||||
def __init__(self, config: EvalSourceConfig):
|
||||
super().__init__(config)
|
||||
def __init__(self, config: EvalSourceConfig, address: str):
|
||||
super().__init__(config, address)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
self.examples: list[dict] = []
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
async def start(self) -> None:
|
||||
await super().start()
|
||||
n = self.config.num_examples
|
||||
if self.tasks is None: # legacy: the dataset lives on the server — address it by row
|
||||
count = self.num_tasks if n < 0 else min(n, self.num_tasks)
|
||||
@@ -308,30 +211,10 @@ class Envs(Generic[EnvT]):
|
||||
def __len__(self) -> int:
|
||||
return len(self._envs)
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
"""Spawn env servers (where needed) and connect, one at a time. Each server
|
||||
binds an OS-assigned port and reports it back, so there's no port race."""
|
||||
for env in self:
|
||||
await env.start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
atexit.register(self.shutdown)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Terminate all spawned env server processes."""
|
||||
processes = [env._env_server_process for env in self if env._env_server_process is not None]
|
||||
if not processes:
|
||||
return
|
||||
logger = get_logger()
|
||||
logger.debug(f"Shutting down {len(processes)} env server(s)")
|
||||
for p in processes:
|
||||
p.terminate()
|
||||
for p in processes:
|
||||
p.join(timeout=25)
|
||||
if p.is_alive():
|
||||
logger.warning(f"Env server {p.pid} did not exit after 25s, force killing")
|
||||
p.kill()
|
||||
p.join(timeout=5)
|
||||
for env in self:
|
||||
env._env_server_process = None
|
||||
async def start(self) -> None:
|
||||
"""Connect to all env servers in parallel — every address is known up front,
|
||||
so there's nothing to serialize on."""
|
||||
await asyncio.gather(*(env.start() for env in self))
|
||||
|
||||
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
@@ -339,12 +222,20 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
:class:`Sampler` and runtime :class:`Algorithm`, built from the env's
|
||||
resolved algorithm config."""
|
||||
|
||||
def __init__(self, configs: Sequence[TrainSourceConfig], *, policy_pool, renderer_config=None):
|
||||
def __init__(
|
||||
self,
|
||||
configs: Sequence[TrainSourceConfig],
|
||||
addresses: dict[tuple[str, str], str],
|
||||
*,
|
||||
policy_pool,
|
||||
renderer_config=None,
|
||||
):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
assert config.algo is not None, "TrainSourceConfig.algo must be resolved before env construction"
|
||||
env = TrainEnv(
|
||||
config,
|
||||
addresses[("train", config.resolved_name)],
|
||||
Sampler(config.algo.sampling, policy_pool, renderer_config),
|
||||
build_algorithm(config.algo, policy_pool),
|
||||
)
|
||||
@@ -354,8 +245,8 @@ class TrainEnvs(Envs[TrainEnv]):
|
||||
class EvalEnvs(Envs[EvalEnv]):
|
||||
"""Collection of evaluation environments."""
|
||||
|
||||
def __init__(self, configs: Sequence[EvalSourceConfig]):
|
||||
def __init__(self, configs: Sequence[EvalSourceConfig], addresses: dict[tuple[str, str], str]):
|
||||
self._envs: dict[str, EvalEnv] = {}
|
||||
for config in configs:
|
||||
env = EvalEnv(config)
|
||||
env = EvalEnv(config, addresses[("eval", config.resolved_name)])
|
||||
self._envs[env.name] = env
|
||||
|
||||
@@ -81,7 +81,7 @@ from prime_rl.utils.config import to_toml_dict
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
from prime_rl.utils.pathing import get_log_dir, get_trace_path
|
||||
from prime_rl.utils.pathing import get_trace_path
|
||||
from prime_rl.utils.usage_reporter import UsageReporter
|
||||
from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
@@ -260,27 +260,22 @@ class Orchestrator:
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(
|
||||
config.train.source, policy_pool=self.policy_inference, renderer_config=config.renderer
|
||||
config.train.source,
|
||||
config.env_addresses,
|
||||
policy_pool=self.policy_inference,
|
||||
renderer_config=config.renderer,
|
||||
)
|
||||
get_logger().debug(
|
||||
f"Loaded {len(self.train_envs)} training environment(s) ({', '.join(self.train_envs.names)})"
|
||||
)
|
||||
await self.train_envs.start(
|
||||
log_dir=get_log_dir(config.output_dir.parent) / "envs" / "train",
|
||||
log_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
await self.train_envs.start()
|
||||
get_logger().success("Train environment(s) ready")
|
||||
|
||||
if config.eval is not None:
|
||||
get_logger().info("Loading eval environment(s)")
|
||||
self.eval_envs = EvalEnvs(config.eval.source)
|
||||
self.eval_envs = EvalEnvs(config.eval.source, config.env_addresses)
|
||||
get_logger().debug(f"Loaded {len(self.eval_envs)} eval environment(s) ({', '.join(self.eval_envs.names)})")
|
||||
await self.eval_envs.start(
|
||||
log_dir=get_log_dir(config.output_dir.parent) / "envs" / "eval",
|
||||
log_level=config.log.vf_level,
|
||||
json_logging=config.log.json_logging,
|
||||
)
|
||||
await self.eval_envs.start()
|
||||
get_logger().success("Eval environment(s) ready")
|
||||
|
||||
if config.ckpt is not None and config.ckpt.resume_step is not None and self.ckpt_manager is not None:
|
||||
@@ -475,7 +470,11 @@ class Orchestrator:
|
||||
]
|
||||
|
||||
# Base-model eval (policy v0) — fires before any train rollouts, logged at the first
|
||||
# step, unless ``eval.skip_first_step=True`` (or this is a resume)
|
||||
# step, unless ``eval.skip_first_step=True``. On resume, defaults to assuming a clean
|
||||
# exit (evals already completed); set ``eval.retrigger_on_resume=True`` to also re-fire
|
||||
# interval-aligned evals at the checkpoint step (e.g. after a crash).
|
||||
if config.eval is not None and config.eval.retrigger_on_resume and self.resume_step is not None:
|
||||
self.maybe_trigger_eval(self.resume_step)
|
||||
self.maybe_trigger_eval(self.progress.step)
|
||||
|
||||
# Anchor step-time clock so the first step measures startup → first batch
|
||||
@@ -984,9 +983,6 @@ class Orchestrator:
|
||||
for env in self.train_envs:
|
||||
for pool in (*env.sampler.connected_pools, *env.algorithm.connected_pools):
|
||||
await pool.stop()
|
||||
self.train_envs.shutdown()
|
||||
if self.eval_envs is not None:
|
||||
self.eval_envs.shutdown()
|
||||
if self.usage_reporter is not None:
|
||||
self.usage_reporter.close()
|
||||
|
||||
|
||||
@@ -320,10 +320,14 @@ srun --kill-on-bad-exit=1 bash -c '
|
||||
for ((d=0; d<DP_PER_NODE; d++)); do
|
||||
RANK_GPUS=$(seq -s, $((d * TP)) $((d * TP + TP - 1)))
|
||||
RANK_LOG=$(rank_log "$INFER_NODE_RANK" "$d")
|
||||
if [ "$EP" -eq 1 ]; then
|
||||
if [ "$EP" -eq 1 ] && [ "$DP_PER_NODE" -gt 1 ]; then
|
||||
RANK_EXTRA="{\"data_parallel_rank\": $d, \"data_parallel_address\": \"$LOCAL_IP\"}"
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" "$DP_PER_NODE" "$RPC_PORT" "$RANK_EXTRA" "" "$RANK_LOG"
|
||||
else
|
||||
# Dense or single-DP-rank EP (dp=1, e.g. EP within one tp=8 group):
|
||||
# independent single-engine servers. vLLM rejects the external-LB DP
|
||||
# args when data_parallel_size == 1; enable_expert_parallel in the
|
||||
# inference config alone shards experts across the TP group.
|
||||
launch_inference_rank "$((BACKEND_PORT + d))" "$RANK_GPUS" 1 "" "" "" "$RANK_LOG"
|
||||
fi
|
||||
done
|
||||
|
||||
@@ -409,6 +409,26 @@ if [ "$SLURM_PROCID" -eq "$ORCH_PROCID" ]; then
|
||||
export {{ key }}="{{ value }}"
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
{%- if train_env_names or eval_env_names %}
|
||||
|
||||
# Launch one env server per source next to the orchestrator, which connects to each
|
||||
# source at its deterministic loopback address (so this node), polling until they are
|
||||
# up — the servers and the orchestrator start in parallel.
|
||||
# NOTE: keep this block free of single quotes. The whole srun body is one
|
||||
# single-quoted bash -c string, so a stray quote closes it early and the rest of
|
||||
# the script fails to parse.
|
||||
{%- for name in train_env_names %}
|
||||
mkdir -p $OUTPUT_DIR/logs/envs/train
|
||||
uv run env-server @ $CONFIG_DIR/envs/train/{{ name }}.toml \
|
||||
> $OUTPUT_DIR/logs/envs/train/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- for name in eval_env_names %}
|
||||
mkdir -p $OUTPUT_DIR/logs/envs/eval
|
||||
uv run env-server @ $CONFIG_DIR/envs/eval/{{ name }}.toml \
|
||||
> $OUTPUT_DIR/logs/envs/eval/{{ name }}.log 2>&1 &
|
||||
{%- endfor %}
|
||||
{%- endif %}
|
||||
|
||||
{% if use_nccl_broadcast %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --weight_broadcast.host $MASTER_ADDR"
|
||||
{% endif %}{% if use_zmq_transport %}ORCHESTRATOR_ARGS="$ORCHESTRATOR_ARGS --rollout_transport.host $MASTER_ADDR"
|
||||
{% endif %}WANDB_SHARED_LABEL=orchestrator uv run orchestrator $ORCHESTRATOR_ARGS \
|
||||
|
||||
@@ -207,10 +207,17 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
|
||||
position_ids: Optional[torch.LongTensor] = None,
|
||||
inputs_embeds: Optional[torch.FloatTensor] = None,
|
||||
routed_experts: Optional[torch.LongTensor] = None,
|
||||
*,
|
||||
seq_lens: Optional[torch.LongTensor] = None,
|
||||
seq_lens_are_pre_shard: bool = False,
|
||||
) -> BaseModelOutputWithPast:
|
||||
"""
|
||||
routed_experts (`torch.LongTensor` of shape `(batch_size, sequence_length, num_hidden_layers, num_experts_per_tok)`, *optional*):
|
||||
Routed experts for each token in the sequence. Only used for router replay.
|
||||
seq_lens (`torch.LongTensor` of shape `(num_documents,)`, *optional*):
|
||||
Per-document lengths of the packed row (PrimeRL packed-batch contract). Unused.
|
||||
seq_lens_are_pre_shard (`bool`, *optional*, defaults to `False`):
|
||||
Whether `seq_lens` holds pre-CP-shard (global) document boundaries. Unused.
|
||||
"""
|
||||
if (input_ids is None) ^ (inputs_embeds is not None):
|
||||
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
||||
|
||||
@@ -16,45 +16,8 @@ from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
|
||||
def _build_seq_idx(boundaries: list[int], seq_len: int, device: torch.device) -> torch.Tensor:
|
||||
"""Return the packed-document id for each token in a full CP sequence."""
|
||||
if boundaries[0] != 0 or boundaries[-1] != seq_len:
|
||||
raise ValueError(f"cu_seqlens must span the full sequence length {seq_len}, got {boundaries}")
|
||||
|
||||
seq_idx = torch.empty(seq_len, dtype=torch.int32, device=device)
|
||||
for sequence_id, (start, end) in enumerate(zip(boundaries[:-1], boundaries[1:])):
|
||||
if end <= start:
|
||||
raise ValueError(f"cu_seqlens must be strictly increasing, got {boundaries}")
|
||||
seq_idx[start:end] = sequence_id
|
||||
return seq_idx.unsqueeze(0)
|
||||
|
||||
|
||||
def _causal_conv1d_varlen(
|
||||
hidden_states: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
boundaries: list[int],
|
||||
) -> torch.Tensor:
|
||||
"""Apply a depthwise causal convolution independently to packed documents."""
|
||||
batch_size, _, channels = hidden_states.shape
|
||||
if batch_size != 1:
|
||||
raise ValueError(f"packed CP Mamba expects batch_size=1, got {batch_size}")
|
||||
|
||||
inputs = hidden_states.transpose(1, 2)
|
||||
outputs = []
|
||||
for start, end in zip(boundaries[:-1], boundaries[1:]):
|
||||
convolved = torch.nn.functional.conv1d(
|
||||
inputs[:, :, start:end],
|
||||
weight,
|
||||
bias,
|
||||
groups=channels,
|
||||
padding=weight.shape[2] - 1,
|
||||
)
|
||||
outputs.append(convolved[:, :, : end - start])
|
||||
|
||||
return torch.cat(outputs, dim=-1).transpose(1, 2)
|
||||
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
|
||||
from fla.ops.utils import prepare_sequence_ids
|
||||
|
||||
|
||||
class _SeqToHeadParallel(torch.autograd.Function):
|
||||
@@ -180,8 +143,7 @@ def mamba_cp_forward(
|
||||
hidden_states_B_C = torch.cat([x_part, B_part, C_part], dim=-1)
|
||||
|
||||
full_seq_len = hidden_states_B_C.shape[1] # S (full sequence)
|
||||
boundaries = cu_seqlens.tolist()
|
||||
seq_idx = _build_seq_idx(boundaries, full_seq_len, hidden_states.device)
|
||||
seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
|
||||
|
||||
# ── 3. Local head dimensions ──
|
||||
local_num_heads = mixer.num_heads // cp_size
|
||||
@@ -216,9 +178,15 @@ def mamba_cp_forward(
|
||||
local_conv_weight = mixer.conv1d.weight[conv_indices]
|
||||
local_conv_bias = mixer.conv1d.bias[conv_indices] if mixer.conv1d.bias is not None else None
|
||||
|
||||
# ── 4. Conv1d on each packed document, local heads ──
|
||||
hidden_states_B_C = torch.nn.functional.silu(
|
||||
_causal_conv1d_varlen(hidden_states_B_C, local_conv_weight, local_conv_bias, boundaries)
|
||||
# ── 4. Causal conv1d on the full sequence, local heads ──
|
||||
# Must reset at sequence boundaries for packed batches, otherwise the
|
||||
# kernel-1 left pad leaks state across sequences.
|
||||
hidden_states_B_C, _ = fla_causal_conv1d(
|
||||
x=hidden_states_B_C,
|
||||
weight=local_conv_weight.squeeze(1),
|
||||
bias=local_conv_bias,
|
||||
activation=mixer.activation,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
|
||||
local_groups_time_state_size = local_n_groups * mixer.ssm_state_size
|
||||
|
||||
@@ -3,11 +3,12 @@ from typing import Optional
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers.configuration_utils import PretrainedConfig
|
||||
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
||||
|
||||
|
||||
def _compute_default_rope_parameters(
|
||||
config: Optional["PreTrainedConfig"] = None,
|
||||
config: Optional["PretrainedConfig"] = None,
|
||||
device: Optional["torch.device"] = None,
|
||||
seq_len: int | None = None,
|
||||
layer_type: str | None = None,
|
||||
|
||||
@@ -10,6 +10,8 @@ from typing import Optional
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from fla.modules.conv import causal_conv1d as fla_causal_conv1d
|
||||
from fla.ops.utils import prepare_sequence_ids
|
||||
from torch import Tensor, nn
|
||||
from transformers.generation import GenerationMixin
|
||||
from transformers.modeling_layers import GradientCheckpointingLayer
|
||||
@@ -40,10 +42,8 @@ def _patch_mamba2_use_triton_ssd():
|
||||
Triton kernels and mamba_ssm use fp32. This causes ~0.4 KL divergence.
|
||||
|
||||
This patch makes the mixer use mamba_chunk_scan_combined (Triton, fp32
|
||||
softplus) for the SSD computation, with PyTorch nn.Conv1d for convolution.
|
||||
Requires mamba_ssm installed; causal_conv1d should NOT be installed (it
|
||||
needs arch-specific CUDA compilation). The HF cuda_kernels_forward
|
||||
already falls back to PyTorch nn.Conv1d when causal_conv1d is absent.
|
||||
softplus) for the SSD computation, with fla's Triton causal_conv1d for
|
||||
convolution. Requires mamba_ssm installed.
|
||||
"""
|
||||
global _patch_applied
|
||||
if _patch_applied:
|
||||
@@ -68,7 +68,7 @@ def _patch_mamba2_use_triton_ssd():
|
||||
def _varlen_mamba_forward(self, hidden_states, cu_seqlens):
|
||||
"""Varlen-aware mamba forward. `cu_seqlens` is required: shape [num_seq+1],
|
||||
e.g. [0, s1, s1+s2, ...]. Handles packed batches by:
|
||||
- applying conv1d per-sequence (with kernel-1 leading zeros)
|
||||
- passing cu_seqlens to causal_conv1d (conv state resets at boundaries)
|
||||
- passing seq_idx to mamba_chunk_scan_combined (SSM state resets at boundaries)
|
||||
"""
|
||||
batch_size, seq_len, _ = hidden_states.shape
|
||||
@@ -86,20 +86,15 @@ def _patch_mamba2_use_triton_ssd():
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# 2. Per-sequence causal conv1d. self.conv1d already has padding=kernel-1 so
|
||||
# applying it to each segment independently gives the correct causal output
|
||||
# without cross-sequence history.
|
||||
hbc_t = hidden_states_B_C.transpose(1, 2) # (1, C, L)
|
||||
cu = cu_seqlens.tolist()
|
||||
conv_outs = []
|
||||
for i in range(len(cu) - 1):
|
||||
s, e = cu[i], cu[i + 1]
|
||||
if s == e:
|
||||
continue
|
||||
seg = hbc_t[:, :, s:e]
|
||||
conv_out = self.conv1d(seg)[:, :, : e - s]
|
||||
conv_outs.append(conv_out)
|
||||
hidden_states_B_C = self.act(torch.cat(conv_outs, dim=-1).transpose(1, 2))
|
||||
# 2. Causal conv1d — must reset at sequence boundaries for packed batches,
|
||||
# otherwise the kernel-1 left pad leaks state across sequences.
|
||||
hidden_states_B_C, _ = fla_causal_conv1d(
|
||||
x=hidden_states_B_C,
|
||||
weight=self.conv1d.weight.squeeze(1),
|
||||
bias=self.conv1d.bias,
|
||||
activation=self.activation,
|
||||
cu_seqlens=cu_seqlens,
|
||||
)
|
||||
|
||||
hidden_states, B, C = torch.split(
|
||||
hidden_states_B_C,
|
||||
@@ -108,12 +103,7 @@ def _patch_mamba2_use_triton_ssd():
|
||||
)
|
||||
|
||||
# 3. SSM with seq_idx so state resets at sequence boundaries
|
||||
seq_idx = torch.zeros(seq_len, dtype=torch.int32, device=hidden_states.device)
|
||||
for i in range(len(cu) - 1):
|
||||
s, e = cu[i], cu[i + 1]
|
||||
if e > s:
|
||||
seq_idx[s:e] = i
|
||||
seq_idx = seq_idx.unsqueeze(0) # (1, L)
|
||||
seq_idx = prepare_sequence_ids(cu_seqlens).to(torch.int32).unsqueeze(0)
|
||||
|
||||
scan_output = _mamba_chunk_scan_combined(
|
||||
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
|
||||
|
||||
@@ -106,6 +106,32 @@ def wandb_name(branch_name: str) -> str:
|
||||
INFERENCE_PORTS = [8000, 8001]
|
||||
INFERENCE_BASE_URLS = [f"http://localhost:{port}/v1" for port in INFERENCE_PORTS]
|
||||
|
||||
# One env server per run (1:1 with its orchestrator), at that run's base port. A resumed
|
||||
# run keeps its port, so it reconnects to the same server.
|
||||
ENV_SERVER_PORTS = {name: 5000 + i for i, name in enumerate(ORCHESTRATOR_NAMES)}
|
||||
ENV_SERVER_PORTS["alpha_resume"] = ENV_SERVER_PORTS["alpha"]
|
||||
ENV_SERVER_PORTS["beta_resume"] = ENV_SERVER_PORTS["beta"]
|
||||
|
||||
|
||||
def start_env_server(log_dir: Path, name: str) -> subprocess.Popen:
|
||||
"""Start one env server for orchestrator `name`, which derives the same address and
|
||||
connects, polling until the server is up — no readiness wait needed here."""
|
||||
env_server_log = log_dir / f"env_server_{name}.log"
|
||||
with open(env_server_log, "w") as f:
|
||||
return subprocess.Popen(
|
||||
[
|
||||
"uv",
|
||||
"run",
|
||||
"env-server",
|
||||
"@",
|
||||
"configs/ci/integration/reverse-text-multi-run/env.toml",
|
||||
"--serve.address",
|
||||
f"tcp://127.0.0.1:{ENV_SERVER_PORTS[name]}",
|
||||
],
|
||||
stdout=f,
|
||||
stderr=f,
|
||||
)
|
||||
|
||||
|
||||
def start_inference_and_trainer(
|
||||
log_dir: Path, output_dir: Path, wandb_project: str, wandb_name: str
|
||||
@@ -219,6 +245,8 @@ def start_orchestrator(
|
||||
str(max_steps),
|
||||
"--model.lora.name",
|
||||
name,
|
||||
"--env-server-base-port",
|
||||
str(ENV_SERVER_PORTS[name]),
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
@@ -249,6 +277,9 @@ def multi_run_result(
|
||||
|
||||
processes: list[subprocess.Popen] = []
|
||||
|
||||
for name in ORCHESTRATOR_NAMES:
|
||||
processes.append(start_env_server(log_dir, name))
|
||||
|
||||
trainer_proc, inference_procs = start_inference_and_trainer(log_dir, output_dir, wandb_project, wandb_name)
|
||||
processes.append(trainer_proc)
|
||||
processes.extend(inference_procs)
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import torch
|
||||
|
||||
import prime_rl.inference.vllm.padded_input_scrub as padded_input_scrub
|
||||
from prime_rl.inference.vllm.padded_input_scrub import (
|
||||
_zero_padded_model_inputs,
|
||||
monkey_patch_vllm_padded_input_scrub,
|
||||
)
|
||||
|
||||
|
||||
def test_monkey_patch_preprocess_matches_vllm_preprocess_signature(monkeypatch):
|
||||
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
|
||||
|
||||
calls = {}
|
||||
|
||||
def fake_preprocess(
|
||||
self,
|
||||
scheduler_output,
|
||||
num_input_tokens,
|
||||
intermediate_tensors=None,
|
||||
):
|
||||
calls["args"] = (
|
||||
self,
|
||||
scheduler_output,
|
||||
num_input_tokens,
|
||||
intermediate_tensors,
|
||||
)
|
||||
return (
|
||||
torch.tensor([10, 11, 12, 991, 992]),
|
||||
None,
|
||||
torch.tensor([0, 1, 2, 991, 992]),
|
||||
intermediate_tensors,
|
||||
{},
|
||||
None,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(padded_input_scrub, "_INSTALLED", False)
|
||||
monkeypatch.setattr(GPUModelRunner, "_preprocess", fake_preprocess)
|
||||
monkeypatch.setattr(
|
||||
GPUModelRunner,
|
||||
"_prime_rl_padded_input_scrub",
|
||||
False,
|
||||
raising=False,
|
||||
)
|
||||
|
||||
monkey_patch_vllm_padded_input_scrub()
|
||||
|
||||
self = object()
|
||||
scheduler_output = SimpleNamespace(total_num_scheduled_tokens=3)
|
||||
intermediate_tensors = object()
|
||||
result = GPUModelRunner._preprocess(self, scheduler_output, 5, intermediate_tensors)
|
||||
|
||||
assert calls["args"] == (
|
||||
self,
|
||||
scheduler_output,
|
||||
5,
|
||||
intermediate_tensors,
|
||||
)
|
||||
assert result[0].tolist() == [10, 11, 12, 0, 0]
|
||||
assert result[2].tolist() == [0, 1, 2, 0, 0]
|
||||
|
||||
|
||||
def test_zero_padded_model_inputs_leaves_scheduled_prefix_intact():
|
||||
input_ids = torch.tensor([10, 11, 12, 991, 992])
|
||||
positions = torch.tensor([0, 1, 2, 991, 992])
|
||||
preprocess_result = (input_ids, None, positions, None, {}, None)
|
||||
|
||||
_zero_padded_model_inputs(
|
||||
preprocess_result,
|
||||
num_scheduled_tokens=3,
|
||||
num_input_tokens=5,
|
||||
)
|
||||
|
||||
assert input_ids.tolist() == [10, 11, 12, 0, 0]
|
||||
assert positions.tolist() == [0, 1, 2, 0, 0]
|
||||
|
||||
|
||||
def test_zero_padded_model_inputs_zeroes_embeddings_and_mrope_positions():
|
||||
inputs_embeds = torch.ones((5, 4))
|
||||
inputs_embeds[3:] = 7
|
||||
positions = torch.tensor(
|
||||
[
|
||||
[0, 1, 2, 991, 992],
|
||||
[0, 1, 2, 993, 994],
|
||||
[0, 1, 2, 995, 996],
|
||||
]
|
||||
)
|
||||
preprocess_result = (None, inputs_embeds, positions, None, {}, None)
|
||||
|
||||
_zero_padded_model_inputs(
|
||||
preprocess_result,
|
||||
num_scheduled_tokens=3,
|
||||
num_input_tokens=5,
|
||||
)
|
||||
|
||||
torch.testing.assert_close(inputs_embeds[:3], torch.ones((3, 4)))
|
||||
torch.testing.assert_close(inputs_embeds[3:], torch.zeros((2, 4)))
|
||||
assert positions.tolist() == [
|
||||
[0, 1, 2, 0, 0],
|
||||
[0, 1, 2, 0, 0],
|
||||
[0, 1, 2, 0, 0],
|
||||
]
|
||||
|
||||
|
||||
def test_zero_padded_model_inputs_noops_without_padding():
|
||||
input_ids = torch.tensor([10, 11, 12])
|
||||
positions = torch.tensor([0, 1, 2])
|
||||
preprocess_result = (input_ids, None, positions, None, {}, None)
|
||||
|
||||
_zero_padded_model_inputs(
|
||||
preprocess_result,
|
||||
num_scheduled_tokens=3,
|
||||
num_input_tokens=3,
|
||||
)
|
||||
|
||||
assert input_ids.tolist() == [10, 11, 12]
|
||||
assert positions.tolist() == [0, 1, 2]
|
||||
@@ -6,6 +6,7 @@ import tomli_w
|
||||
from pydantic import BaseModel, Field, ValidationError
|
||||
from pydantic_config import ConfigFileError
|
||||
|
||||
from prime_rl.configs.env_server import EnvServerConfig
|
||||
from prime_rl.configs.inference import InferenceConfig
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.rl import RLConfig
|
||||
@@ -21,6 +22,7 @@ CONFIG_CLASSES = [
|
||||
SFTConfig,
|
||||
OrchestratorConfig,
|
||||
InferenceConfig,
|
||||
EnvServerConfig,
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -5,6 +5,11 @@ from prime_rl.utils.parsers import resolve_reasoning_parser, resolve_tool_call_p
|
||||
|
||||
# (model_name, expected_tool_call_parser, expected_reasoning_parser)
|
||||
EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
|
||||
# Arcee Trinity
|
||||
("arcee-ai/Trinity-Large-Thinking", "qwen3_coder", "deepseek_r1"),
|
||||
("arcee-ai/Trinity-Large-Preview", "hermes", None),
|
||||
("arcee-ai/Trinity-Mini", "hermes", "deepseek_r1"),
|
||||
("arcee-ai/Trinity-Nano-Preview", "hermes", "deepseek_r1"),
|
||||
# DeepSeek
|
||||
("deepseek-ai/DeepSeek-V3.2", "deepseek_v32", "deepseek_r1"),
|
||||
("deepseek-ai/DeepSeek-V3.2-Exp", "deepseek_v32", "deepseek_r1"),
|
||||
@@ -33,6 +38,14 @@ EXPECTED_PARSERS: list[tuple[str, str | None, str | None]] = [
|
||||
("MiniMaxAI/MiniMax-M2", "minimax_m2", "minimax_m2_append_think"),
|
||||
("MiniMaxAI/MiniMax-M2.1", "minimax_m2", "minimax_m2_append_think"),
|
||||
("MiniMaxAI/MiniMax-M2.5", "minimax_m2", "minimax_m2_append_think"),
|
||||
# gpt-oss (reasoning handled natively by vLLM's harmony path)
|
||||
("openai/gpt-oss-20b", "openai", None),
|
||||
("openai/gpt-oss-120b", "openai", None),
|
||||
# Poolside Laguna
|
||||
("poolside/Laguna-S-2.1", "poolside_v1", "poolside_v1"),
|
||||
("poolside/Laguna-S-2.1-FP8", "poolside_v1", "poolside_v1"),
|
||||
("poolside/Laguna-XS-2.1", "poolside_v1", "poolside_v1"),
|
||||
("poolside/Laguna-M.1", "poolside_v1", "poolside_v1"),
|
||||
# INTELLECT-3
|
||||
("PrimeIntellect/INTELLECT-3", "qwen3_coder", "deepseek_r1"),
|
||||
("PrimeIntellect/INTELLECT-3-FP8", "qwen3_coder", "deepseek_r1"),
|
||||
|
||||
@@ -6,6 +6,8 @@ import torch
|
||||
|
||||
from prime_rl.trainer.models.layers import cp_mamba
|
||||
|
||||
pytestmark = [pytest.mark.gpu]
|
||||
|
||||
|
||||
class _FakeMixer(torch.nn.Module):
|
||||
def __init__(self):
|
||||
@@ -19,6 +21,7 @@ class _FakeMixer(torch.nn.Module):
|
||||
self.chunk_size = 1
|
||||
self.time_step_limit = None
|
||||
self.variance_epsilon = 1e-5
|
||||
self.activation = "silu"
|
||||
|
||||
self.in_proj = torch.nn.Linear(1, 5, bias=False)
|
||||
self.in_proj.weight.data.copy_(torch.tensor([[1.0], [1.0], [1.0], [1.0], [1.0]]))
|
||||
@@ -27,7 +30,9 @@ class _FakeMixer(torch.nn.Module):
|
||||
self.dt_bias = torch.nn.Parameter(torch.zeros(1))
|
||||
self.conv1d = torch.nn.Conv1d(3, 3, kernel_size=2, groups=3, bias=False)
|
||||
self.conv1d.weight.data.fill_(1.0)
|
||||
self.norm = types.SimpleNamespace(weight=torch.ones(1), variance_epsilon=self.variance_epsilon, group_size=1)
|
||||
self.norm = types.SimpleNamespace(
|
||||
weight=torch.ones(1, device="cuda"), variance_epsilon=self.variance_epsilon, group_size=1
|
||||
)
|
||||
self.out_proj = torch.nn.Identity()
|
||||
|
||||
|
||||
@@ -52,20 +57,29 @@ def test_mamba_cp_forward_resets_conv_and_scan_at_packed_boundaries(monkeypatch)
|
||||
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
|
||||
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
|
||||
|
||||
mixer = _FakeMixer()
|
||||
cu_seqlens = torch.tensor([0, 2, 4], dtype=torch.int32)
|
||||
first = torch.tensor([[[1.0], [2.0], [3.0], [4.0]]])
|
||||
mixer = _FakeMixer().cuda()
|
||||
cu_seqlens = torch.tensor([0, 2, 4], dtype=torch.int32, device="cuda")
|
||||
first = torch.tensor([[[1.0], [2.0], [3.0], [4.0]]], device="cuda")
|
||||
second = first.clone()
|
||||
second[0, 1, 0] = 200.0
|
||||
|
||||
first_out = cp_mamba.mamba_cp_forward(mixer, first, None, 0, 1, cu_seqlens)
|
||||
second_out = cp_mamba.mamba_cp_forward(mixer, second, None, 0, 1, cu_seqlens)
|
||||
|
||||
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 0, 1, 1]], dtype=torch.int32))
|
||||
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 0, 1, 1]], dtype=torch.int32, device="cuda"))
|
||||
assert torch.equal(seen_seq_idx[1], seen_seq_idx[0])
|
||||
torch.testing.assert_close(first_out[:, 2:], second_out[:, 2:])
|
||||
|
||||
|
||||
def test_mamba_cp_forward_rejects_local_boundaries():
|
||||
with pytest.raises(ValueError, match="full sequence length 4"):
|
||||
cp_mamba._build_seq_idx([0, 2], 4, torch.device("cpu"))
|
||||
def test_mamba_cp_forward_builds_seq_idx_for_uneven_packs(monkeypatch):
|
||||
seen_seq_idx: list[torch.Tensor] = []
|
||||
_install_fake_scan(monkeypatch, seen_seq_idx)
|
||||
monkeypatch.setattr(cp_mamba, "seq_to_head_parallel", lambda value, *_: value)
|
||||
monkeypatch.setattr(cp_mamba, "head_to_seq_parallel", lambda value, *_: value)
|
||||
|
||||
cu_seqlens = torch.tensor([0, 1, 4, 6], dtype=torch.int32, device="cuda")
|
||||
hidden_states = torch.arange(6, dtype=torch.float32, device="cuda").reshape(1, 6, 1)
|
||||
|
||||
cp_mamba.mamba_cp_forward(_FakeMixer().cuda(), hidden_states, None, 0, 1, cu_seqlens)
|
||||
|
||||
assert torch.equal(seen_seq_idx[0], torch.tensor([[0, 1, 1, 1, 2, 2]], dtype=torch.int32, device="cuda"))
|
||||
|
||||
Reference in New Issue
Block a user