Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion deps/renderers
18 changes: 17 additions & 1 deletion docs/inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ On the CLI the same keys are available as `--inference.vllm.max-num-seqs 256` (o

Router replay works by capturing the expert routing decisions into a buffer. This buffer then gets sent to the trainer, which can use it instead of re-computing the routing. This lowers the trainer↔inference mismatch by an order of magnitude, resulting in more stable training.

To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`.
To enable router replay, you can set `inference.vllm.enable_return_routed_experts = true`. vLLM 0.28 uses the V2 model runner for standard deployments. Disaggregated P/D remains on V1 because NIXL routed-expert stitching is V1-only.

```toml
[trainer]
Expand All @@ -298,3 +298,19 @@ 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.

Currently this feature is also not supported with CPU KV cache offload, which can have negative impact on the inference throughput.

### Sampling Replay

Truncated sampling (`top_p < 1`, `top_k`) renormalizes the sampling distribution over a sampling mask of surviving token ids. The rollout logprobs reflect that (`logprobs_mode = "processed_logprobs"`), so the trainer must renormalize over the same mask — otherwise every importance ratio is biased and training collapses (DeepSeek V3.2's "Keep Sampling Mask", [arXiv:2512.02556](https://arxiv.org/abs/2512.02556) §3.1; Cognition's [SWE-1.7 post](https://cognition.com/blog/swe-1-7)). prime-rl handles this automatically: vLLM records the sampling mask at sampling time (`--return-sampling-mask`, native since vLLM 0.28) and the trainer renormalizes its logprobs over it.

```toml
[orchestrator.train.sampling]
top_p = 0.95
top_k = 512 # optional, defaults to 512 under truncation (bounds each sampling mask)
```

That's all — there are no replay flags. Truncated train sampling makes the inference server return sampling masks (`inference.enable_return_sampling_mask`, auto-enabled), and the trainer replays them. Train-sampling `top_k` above 512 is rejected: the trainer pads each micro batch to its largest sampling mask, so the bound caps trainer memory. Configs that would break under renormalized logprobs are rejected: `opd`/`opsd` and truncation knobs smuggled via `extra_body`; Gemma-family (softcapped) lm_heads fail loudly. Frozen-source envs are exempt.

Capture runs on vLLM's V2 model runner (forced automatically) and is engine-wide. It can run with router replay on standard deployments. The combination is not supported with disaggregated P/D because NIXL routed-expert capture uses V1. While sampling capture is on, vLLM rejects any request with `temperature <= 0` or without an effective `top_k > 0` — eval sampling against the training server must set `top_k` (the model's generation config often supplies one) and a non-zero temperature.

When launching the inference server standalone, set `inference.enable_return_sampling_mask = true` yourself; clients must sample with `0 < top_k <= 512`.
20 changes: 20 additions & 0 deletions packages/prime-rl-configs/src/prime_rl/configs/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,9 @@ class InferenceConfig(BaseConfig):
use_pd_kv_transfer: bool = False
"""Auto-set for disaggregated P/D: emit the NIXL transfer connector. Persisted into the per-node config (which drops ``deployment``) so the connector is still built per worker. Not meant to be set by hand."""

enable_return_sampling_mask: bool = False
"""Auto-set for sampling replay: return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on, and it requires the V2 model runner (the launcher forces ``VLLM_USE_V2_MODEL_RUNNER=1``). Auto-enabled by the ``rl`` entrypoint under truncated train sampling and persisted into the per-node config; set by hand only for standalone-launched servers."""
Comment thread
mikasenghaas marked this conversation as resolved.
Resolved

enable_fp32_lm_head: bool = True
"""Run the lm_head projection in fp32 via a native bf16×bf16 → fp32 GEMM (``torch.mm`` with ``out_dtype=torch.float32``). Stabilizes logprob precision under FP8/bf16 inference, matching SGLang's ``--enable-fp32-lm-head``. Implemented as a monkey-patch over vLLM's LogitsProcessor, activated by setting ``additional_config["fp32_lm_head"] = True`` on the vLLM config."""

Expand Down Expand Up @@ -494,6 +497,20 @@ def validate_llmd_no_routed_experts(self):
)
return self

@model_validator(mode="after")
def validate_disaggregated_combined_replay(self):
"""NIXL routed-expert capture uses the V1 runner, while sampling replay needs V2."""
if (
self.deployment.type == "disaggregated"
and self.enable_return_sampling_mask
and self.vllm.enable_return_routed_experts
):
raise ValueError(
"Combined router and sampling replay is not supported with disaggregated P/D: "
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
)
return self

@model_validator(mode="after")
def validate_router_deployment(self):
"""The llm-d router (EPP + Envoy) is launched by the SLURM templates only; multi-node deployments need a router to front the per-rank engines."""
Expand Down Expand Up @@ -619,6 +636,9 @@ def to_namespace(self) -> Namespace:
hf_overrides.setdefault("moe_router_dtype", "float32")
namespace.hf_overrides = hf_overrides

if self.enable_return_sampling_mask:
namespace.return_sampling_mask = True

kv_transfer_config = self.build_kv_transfer_config()
if kv_transfer_config is not None:
namespace.kv_transfer_config = kv_transfer_config
Expand Down
103 changes: 100 additions & 3 deletions packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import warnings
from pathlib import Path
from typing import Annotated, Any, Literal, TypeAlias

Expand Down Expand Up @@ -45,6 +46,16 @@ class TrainSamplingConfig(BaseConfig):
temperature: float = Field(1.0, ge=0, le=2.0)
"""Sampling temperature."""

top_p: float = Field(1.0, gt=0, le=1.0)
"""Nucleus (top-p) sampling for train rollouts. Values below 1.0 truncate the sampling
distribution; the ``rl`` entrypoint auto-enables sampling replay so trainer and
rollout distributions stay consistent — see docs/inference.md (Sampling Replay)."""

top_k: int | None = Field(None, ge=1)
"""Top-k sampling for train rollouts. Truncation triggers sampling replay, and
a default top-k is injected when only top-p truncates so sampling masks stay
bounded — see docs/inference.md (Sampling Replay)."""

max_completion_tokens: int | None = None
"""Maximum output tokens per turn. If None, generates until max context length or EOS."""

Expand All @@ -53,18 +64,46 @@ class TrainSamplingConfig(BaseConfig):
extra_body: dict[str, Any] = {}
"""Extra body forwarded with each request to the inference server."""

def truncates_distribution(self) -> bool:
return self.top_p < 1.0 or self.top_k is not None

@model_validator(mode="after")
def validate_no_extra_body_truncation(self):
"""Truncating values must come from the typed fields — the replay policy reads
them. Disabled values pass so resolved configs (where ``resolve_env_config``
stamped the ``top_k = -1`` / ``min_p = 0.0`` sentinels) re-validate cleanly."""
smuggled = [
key
for key, truncates in (
("top_p", self.extra_body.get("top_p", 1.0) < 1.0),
("top_k", self.extra_body.get("top_k") not in (None, -1, 0)),
("min_p", self.extra_body.get("min_p", 0.0) > 0.0),
)
if truncates
]
if smuggled:
raise ValueError(
f"extra_body carries truncating {smuggled}; set them as fields on the train "
"sampling config instead (they drive sampling replay)."
)
return self

def to_sampling_args(self) -> dict[str, Any]:
"""Convert to OAI-compatible sampling args dict, omitting None values."""
args: dict[str, Any] = {
"temperature": self.temperature,
"top_p": 1.0,
"top_p": self.top_p,
"logprobs": True,
}
if self.max_completion_tokens is not None:
args["max_completion_tokens"] = self.max_completion_tokens

if self.extra_body:
args["extra_body"] = dict(self.extra_body)
# top_k rides extra_body (like EvalSamplingConfig), overriding the sentinel.
extra_body = dict(self.extra_body)
if self.top_k is not None:
extra_body["top_k"] = self.top_k
if extra_body:
args["extra_body"] = extra_body

return args

Expand Down Expand Up @@ -442,6 +481,15 @@ def validate_bounds(self):
return self


# Top-k injected on truncated policy sampling that has none, and the hard upper
# bound for explicit top-k. vLLM's native sampling-mask capture requires a
# per-request top_k > 0 to bound mask sizes, and the trainer pads each micro
# batch's masks to the largest sampling mask, so the bound also caps trainer
# mask tensors. Large enough that a 0.95-0.99 nucleus rarely reaches it (the
# sampling policy is essentially unchanged).
TRAIN_TOP_K_BOUND = 512


class OrchestratorConfig(BaseConfig):
algo: AlgoConfig = GRPOAlgoConfig()
"""Training algorithm: sampling plus the per-token training signal (credit
Expand Down Expand Up @@ -568,6 +616,55 @@ def validate_env_algorithms(self):
env_cfg.algo.validate_env(env_cfg.env)
return self

@model_validator(mode="after")
def setup_truncated_sampling(self):
"""Truncated policy sampling trains with sampling replay (rollout
logprobs are renormalized — see docs/inference.md, Sampling Replay).
Owned here: every truncating config gets a top-k bound (bounds the sampling
masks); opd/opsd is rejected (full-vocab prefill refs would mix
normalizations). Frozen-source envs sample externally and are exempt."""
policy_samplings = [
env.sampling for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy"
] or ([self.train.sampling] if not self.train.source else [])
truncating = [sampling for sampling in policy_samplings if sampling.truncates_distribution()]
if not truncating:
return self

if any(sampling.temperature == 0 for sampling in truncating):
raise ValueError(
"Truncated train sampling (top_p/top_k) requires temperature > 0: greedy sampling has "
"no truncated distribution to replay, and the inference server rejects such requests "
"while sampling-mask capture is on."
)

oversized = [sampling.top_k for sampling in truncating if (sampling.top_k or 0) > TRAIN_TOP_K_BOUND]
if oversized:
raise ValueError(
f"Truncated train sampling with top_k = {max(oversized)} exceeds the sampling-replay "
f"bound ({TRAIN_TOP_K_BOUND}): the trainer pads each micro batch's masks to the largest "
f"sampling mask, so unbounded masks blow up trainer memory. Use top_k <= {TRAIN_TOP_K_BOUND}."
)

unbounded = [sampling for sampling in truncating if sampling.top_k is None]
if unbounded:
warnings.warn(
f"Truncated train sampling: defaulting top_k = {TRAIN_TOP_K_BOUND} so every sampling mask is "
"bounded and sampling replay stays exact. Set top_k explicitly to override.",
stacklevel=2,
)
for sampling in unbounded:
sampling.top_k = TRAIN_TOP_K_BOUND

algos = [env.algo for env in self.train.source if env.algo is not None] or [self.algo]
if any(algo.type in ("opd", "opsd") for algo in algos):
raise ValueError(
"opd/opsd is not supported with truncated train sampling: reference logprobs are full-vocab "
"prefill scores while trainer logprobs are renormalized over the sampling mask, biasing the "
"ref_kl term. Remove the truncation (top_p/top_k) or the opd/opsd algo."
)

return self

@property
def any_policy_sourced(self) -> bool:
"""True when at least one train env samples rollouts from the live policy."""
Expand Down
47 changes: 47 additions & 0 deletions packages/prime-rl-configs/src/prime_rl/configs/rl.py
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,53 @@ def validate_multi_node_requires_router(self):
raise ValueError("Multi-node deployments require inference.router to front the per-rank engines.")
return self

@model_validator(mode="after")
def auto_setup_sampling_mask_capture(self):
"""Truncated train sampling needs the inference server to return the sampling
masks the trainer replays (OrchestratorConfig guarantees truncating
configs are bounded by TRAIN_TOP_K_BOUND). Capture is engine-wide: while it is
on, vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0``,
so eval sampling against the same server must set both."""
policy_samplings = [
env.sampling
for env in self.orchestrator.train.source
if env.algo is not None and env.algo.sampling.source == "policy"
] or ([self.orchestrator.train.sampling] if not self.orchestrator.train.source else [])
if not any(sampling.truncates_distribution() for sampling in policy_samplings):
return self
if self.inference is None:
warnings.warn(
"Truncated train sampling with no managed inference server: set "
"`enable_return_sampling_mask = true` on the standalone server's config so it "
"returns the sampling masks the trainer replays.",
stacklevel=2,
)
return self
self.inference.enable_return_sampling_mask = True
if self.orchestrator.eval is not None:
warnings.warn(
"Sampling-mask capture is engine-wide: eval requests without top_k > 0 (from the "
"eval sampling config or the model's generation config) or with temperature 0 are "
"rejected by the inference server while truncated train sampling is on.",
stacklevel=2,
)
return self
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

@model_validator(mode="after")
def validate_disaggregated_combined_replay(self):
inference = self.inference
if (
inference is not None
and inference.deployment.type == "disaggregated"
and inference.enable_return_sampling_mask
and inference.vllm.enable_return_routed_experts
):
raise ValueError(
"Combined router and sampling replay is not supported with disaggregated P/D: "
"NIXL routed-expert capture uses the V1 model runner, while sampling replay needs V2."
)
return self

@model_validator(mode="after")
def validate_router_replay_without_kv_offload(self):
if (
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ dependencies = [
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
"verifiers[harbor]>=0.3.1",
"renderers[multimodal]>=0.1.11",
"renderers[multimodal]>=0.1.12.dev2",
"pybase64>=1.4.2",
"orjson>=3.10",
"pandas>=2.0",
Expand Down
3 changes: 1 addition & 2 deletions src/prime_rl/inference/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,8 +234,7 @@ def _post_init(config: VllmConfig):
raise ValueError("--enable-return-routed-experts is incompatible with pipeline parallelism (PP > 1).")
if config.use_v2_model_runner:
raise ValueError(
"The V2 model runner does not support routed experts capture - "
"set VLLM_USE_V2_MODEL_RUNNER=0 (the prime-rl launcher does this automatically)."
"Routed-expert capture with NIXL requires the V1 model runner. Set VLLM_USE_V2_MODEL_RUNNER=0."
)

# vLLM rejects every KV connector, but our P/D path uses NIXL and
Expand Down
14 changes: 9 additions & 5 deletions src/prime_rl/inference/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,15 @@ 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")

# Router replay needs the V1 GPU model runner: V2 silently never captures
# routed experts. Everything else follows vLLM's own V1/V2 resolution.
# setdefault so it stays overridable.
if config.vllm.enable_return_routed_experts:
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "0")
# vLLM 0.28 supports both replay captures on V2. NIXL P/D remains on V1:
# vLLM rejects routed-expert capture with KV connectors, and prime-rl's
# prefill/decode stitching patch is V1-only. setdefault keeps an explicit
# [inference.env_vars] choice authoritative.
if config.enable_return_sampling_mask:
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1")
elif config.vllm.enable_return_routed_experts:
use_v2_runner = config.deployment.type != "disaggregated"
os.environ.setdefault("VLLM_USE_V2_MODEL_RUNNER", "1" if use_v2_runner else "0")
Comment thread
mikasenghaas marked this conversation as resolved.
Resolved

# vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which
# grammar-constrains generation (xgrammar structural tags) for tool_choice
Expand Down
6 changes: 6 additions & 0 deletions src/prime_rl/orchestrator/envs.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,12 @@ def __init__(
self.generation_source = generation_source
self.algorithm = algorithm
self.sampling_args = generation_source.sampling_args(config.sampling.to_sampling_args())
# Truncated policy sampling must ship the sampling masks the trainer replays.
self.requires_sampling_masks = (
config.sampling.truncates_distribution()
and config.algo is not None
and config.algo.sampling.source == "policy"
)


class EvalEnv(Env):
Expand Down
9 changes: 9 additions & 0 deletions src/prime_rl/orchestrator/train_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,15 @@ async def process_group(self, group_id: str) -> None:
samples = await asyncio.to_thread(trace_to_samples, trace, env_name=env_name)
for sample in samples:
sample.temperatures = [temperature] * len(sample.token_ids)
if env.requires_sampling_masks and sample.sampling_mask is None:
# Rollout logprobs are mask-renormalized; training without the masks
# silently biases every importance ratio.
raise RuntimeError(
f"env '{env_name}' samples with truncation (top_p/top_k) but its rollouts "
"carry no sampling masks. Set `enable_return_sampling_mask = true` on "
"the inference server config (the rl entrypoint does this automatically) - "
"it requires vLLM's native sampling-mask capture (>= 0.28)."
)
stamp_loss_routing(sample, env.algorithm.action_loss_type)
if samples:
samples_by_trace[trace.id] = samples
Expand Down
Loading
Loading