diff --git a/deps/renderers b/deps/renderers index 9b47901de1e..f91c3e7061c 160000 --- a/deps/renderers +++ b/deps/renderers @@ -1 +1 @@ -Subproject commit 9b47901de1eab70cedf8aeedf21408ac98785d30 +Subproject commit f91c3e7061ce50ea405cdf54fd419a45cb51a152 diff --git a/deps/verifiers b/deps/verifiers index d4a217794fc..3ed6ef7c2cd 160000 --- a/deps/verifiers +++ b/deps/verifiers @@ -1 +1 @@ -Subproject commit d4a217794fc0bfd70369a8230e56653c193da8ce +Subproject commit 3ed6ef7c2cd4b08c3ddca426b4ea11a01c28d5b4 diff --git a/docs/inference.md b/docs/inference.md index 5f9e91e25a5..c494c131ec4 100644 --- a/docs/inference.md +++ b/docs/inference.md @@ -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] @@ -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`. diff --git a/packages/prime-rl-configs/src/prime_rl/configs/inference.py b/packages/prime-rl-configs/src/prime_rl/configs/inference.py index c561acbf223..b09107d0aad 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/inference.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/inference.py @@ -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 + """Return per-token sampling masks (``sampling_mask``) on ``/inference/v1/generate`` responses via vLLM's native ``--return-sampling-mask`` (>= 0.28). The ``rl`` entrypoint enables this field for truncated policy sampling. Standalone inference must set it explicitly because no orchestrator sampling config is available. The field persists into per-node configs and selects the V2 model runner before vLLM starts. Capture is engine-wide: vLLM rejects requests with ``temperature <= 0`` or without ``top_k > 0`` while it is on.""" + 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.""" @@ -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.""" @@ -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 diff --git a/packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py b/packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py index 4816d982270..54cea8de9de 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/orchestrator.py @@ -1,3 +1,4 @@ +import warnings from pathlib import Path from typing import Annotated, Any, Literal, TypeAlias @@ -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.""" @@ -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 @@ -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 @@ -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.""" @@ -646,6 +743,23 @@ def resolve_env_config(self): env.sampling.extra_body.setdefault("return_token_ids", True) return self + @model_validator(mode="after") + def validate_policy_top_k_consistency(self): + """Require one top-k capture mode across the live policy server.""" + policy_sources = [ + env for env in self.train.source if env.algo is not None and env.algo.sampling.source == "policy" + ] + enabled = [env for env in policy_sources if env.sampling.top_k is not None] + disabled = [env for env in policy_sources if env.sampling.top_k is None] + if enabled and disabled: + names = ", ".join(env.resolved_name for env in disabled) + raise ValueError( + "Live-policy train sources cannot mix top_k > 0 and top_k = -1 because " + "sampling-mask capture is engine-wide. Set top_k > 0 for these sources: " + f"{names}." + ) + return self + @property def env_sources(self) -> list[tuple[str, EnvConfig]]: """Every ``(split, source)`` this run pulls from, train first then eval — the diff --git a/packages/prime-rl-configs/src/prime_rl/configs/rl.py b/packages/prime-rl-configs/src/prime_rl/configs/rl.py index 4a7ce753ef8..a5e89f886a9 100644 --- a/packages/prime-rl-configs/src/prime_rl/configs/rl.py +++ b/packages/prime-rl-configs/src/prime_rl/configs/rl.py @@ -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 + + @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 ( diff --git a/pyproject.toml b/pyproject.toml index 9d77038a88e..fe6157e26c9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", diff --git a/src/prime_rl/inference/patches.py b/src/prime_rl/inference/patches.py index cf879eb91b0..e6c5ec3a1fc 100644 --- a/src/prime_rl/inference/patches.py +++ b/src/prime_rl/inference/patches.py @@ -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 diff --git a/src/prime_rl/inference/server.py b/src/prime_rl/inference/server.py index 635776bae02..685945ac604 100644 --- a/src/prime_rl/inference/server.py +++ b/src/prime_rl/inference/server.py @@ -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") + # Standard deployments use V2 for both capture modes. NIXL P/D also uses V2 + # for sampling-mask capture, but router replay remains on V1 because vLLM + # rejects routed-expert capture with KV connectors and prime-rl's stitching + # patch is V1-only. setdefault keeps an explicit env-var 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") # vLLM 0.24.0 flipped VLLM_ENFORCE_STRICT_TOOL_CALLING's default to True, which # grammar-constrains generation (xgrammar structural tags) for tool_choice diff --git a/src/prime_rl/orchestrator/envs.py b/src/prime_rl/orchestrator/envs.py index 40c13ca41e0..bb26fe5324a 100644 --- a/src/prime_rl/orchestrator/envs.py +++ b/src/prime_rl/orchestrator/envs.py @@ -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): diff --git a/src/prime_rl/orchestrator/train_sink.py b/src/prime_rl/orchestrator/train_sink.py index 21bf0ddfed8..4b9eff127b0 100644 --- a/src/prime_rl/orchestrator/train_sink.py +++ b/src/prime_rl/orchestrator/train_sink.py @@ -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 diff --git a/src/prime_rl/orchestrator/trajectories.py b/src/prime_rl/orchestrator/trajectories.py index 84f27467cca..3d3f9c9b1f6 100644 --- a/src/prime_rl/orchestrator/trajectories.py +++ b/src/prime_rl/orchestrator/trajectories.py @@ -21,7 +21,7 @@ import verifiers.v1 as vf from prime_rl.transports.batch import TrainingSample -from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts +from prime_rl.transports.batch.types import EncodedTensor, RoutedExperts, SamplingMask from prime_rl.utils.logger import get_logger @@ -66,6 +66,28 @@ def _encode_routed_experts(arr: np.ndarray | None, num_tokens: int) -> RoutedExp return RoutedExperts(data=arr.tobytes(), shape=list(arr.shape), dtype=str(arr.dtype)) +def _encode_sampling_mask(mask: vf.SamplingMask | None, num_tokens: int) -> SamplingMask | None: + """Encode a branch sampling mask for a fixed token count. + + The mask stores row sizes in `counts` and concatenates every row in `ids`. + For example, `counts=[2, 1]` and `ids=[4, 7, 9]` become `counts=[2]` and + `ids=[4, 7]` for one token. For three tokens, they become + `counts=[2, 1, 0]` with unchanged ids. Zero-count rows disable replay. + """ + if mask is None: + return None + ids, counts = mask.ids, mask.counts + if len(counts) > num_tokens: + counts = counts[:num_tokens] + ids = ids[: int(counts.sum())] + elif len(counts) < num_tokens: + counts = np.concatenate([counts, np.zeros(num_tokens - len(counts), dtype=np.int32)]) + return SamplingMask( + ids=np.ascontiguousarray(ids, dtype=np.int32).tobytes(), + counts=np.ascontiguousarray(counts, dtype=np.int32).tobytes(), + ) + + def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]: """Yield each branch that yields a training sample, with its trainable-token mask. @@ -143,6 +165,7 @@ def trace_to_samples(trace: vf.Trace, *, env_name: str = "") -> list[TrainingSam ce_weights=_loss_weights(branch, "ce", trained_loss_nodes["ce"]), ref_kl_weights=_loss_weights(branch, "ref_kl", trained_loss_nodes["ref_kl"]), advantages=branch.advantages, + sampling_mask=_encode_sampling_mask(branch.sampling_mask, len(token_ids)), ) ) if not samples: diff --git a/src/prime_rl/trainer/batch.py b/src/prime_rl/trainer/batch.py index 31a70dd7a85..2483de7e107 100644 --- a/src/prime_rl/trainer/batch.py +++ b/src/prime_rl/trainer/batch.py @@ -6,7 +6,7 @@ import numpy as np -from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, TrainingSample +from prime_rl.transports.batch.types import EncodedTensor, MicroBatch, RoutedExperts, SamplingMask, TrainingSample # Backfill value per component weight stream when a packed sample doesn't # carry it: absent rl means weight 1.0 on the loss mask, absent ce/ref_kl @@ -278,6 +278,31 @@ def _pad_routed_experts(micro_batch: MicroBatch, padding_size: int) -> None: routed_experts.shape[0] += padding_size +_SAMPLING_MASK_ITEMSIZE = np.dtype(np.int32).itemsize + + +def _empty_sampling_mask(num_tokens: int) -> SamplingMask: + return SamplingMask(ids=b"", counts=b"\0" * (num_tokens * _SAMPLING_MASK_ITEMSIZE)) + + +def _slice_sampling_mask(sampling_mask: SamplingMask, seq_len: int) -> SamplingMask: + counts = np.frombuffer(sampling_mask.counts, dtype=np.int32)[:seq_len] + return SamplingMask( + ids=sampling_mask.ids[: int(counts.sum()) * _SAMPLING_MASK_ITEMSIZE], + counts=counts.tobytes(), + ) + + +def _pad_sampling_mask(micro_batch: MicroBatch, padding_size: int) -> None: + """Add zero-count mask rows for sequence-padding tokens. + + Padding adds token positions but no eligible token ids, so only `counts` grows. + """ + sampling_mask = micro_batch.sampling_mask + assert sampling_mask is not None + sampling_mask.counts += b"\0" * (padding_size * _SAMPLING_MASK_ITEMSIZE) + + def _slice_encoded(tensor: EncodedTensor, n_rows: int) -> EncodedTensor: """First `n_rows` rows of a dim-0-stacked encoded tensor (e.g. pixel_values, image_grid_thw).""" row = int(np.prod(tensor.shape[1:])) if len(tensor.shape) > 1 else 1 @@ -383,6 +408,9 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch routed_experts = ( _copy_routed_experts(training_example.routed_experts) if training_example.routed_experts is not None else None ) + # No copy needed: SamplingMask holds immutable bytes, and _pad_sampling_mask only + # ever mutates _materialize_bin's own accumulator. + sampling_mask = training_example.sampling_mask if len(input_ids) > seq_len: # Multimodal: never split an image's placeholder block — cut to a whole-image boundary @@ -406,6 +434,8 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch ref_kl_weights = ref_kl_weights[:cut] if routed_experts is not None: routed_experts = _slice_routed_experts(routed_experts, cut) + if sampling_mask is not None: + sampling_mask = _slice_sampling_mask(sampling_mask, cut) if mm_token_type_ids is not None: mm_token_type_ids = mm_token_type_ids[:cut] env_names = env_names[:cut] @@ -436,6 +466,13 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch ) assert len(routed_experts.data) == len(input_ids) * _routed_experts_row_size(routed_experts) + if sampling_mask is not None: + mask_counts = np.frombuffer(sampling_mask.counts, dtype=np.int32) + assert len(mask_counts) == len(input_ids), ( + f"sampling_mask counts: {len(mask_counts)}, input_ids: {len(input_ids)}" + ) + assert len(sampling_mask.ids) == int(mask_counts.sum()) * _SAMPLING_MASK_ITEMSIZE + assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}" return MicroBatch( @@ -448,6 +485,7 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch ref_logprobs=ref_logprobs, temperatures=temperatures, routed_experts=routed_experts, + sampling_mask=sampling_mask, mm_token_type_ids=mm_token_type_ids, env_names=env_names, mm_kwargs=mm_kwargs, @@ -541,6 +579,9 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch: # A weight stream materializes as soon as one packed sample carries it; the # samples that lack it get the stream's identity fill (STREAM_FILL). has_stream = {name: any(getattr(s, name) is not None for s in bin_content.samples) for name in STREAM_FILL} + # Sampling masks are per-token optional (unlike routed_experts): samples + # without them get zero-count backfill instead of constraining packing. + has_sampling_mask = any(sample.sampling_mask is not None for sample in bin_content.samples) input_ids: list[int] = [] loss_mask: list[bool] = [] @@ -555,6 +596,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch: streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL} seq_lens: list[int] = [] routed_experts: RoutedExperts | None = None + sampling_mask: SamplingMask | None = SamplingMask(ids=b"", counts=b"") if has_sampling_mask else None for sample in bin_content.samples: sample_len = len(sample.input_ids) @@ -592,6 +634,10 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch: mm_kwargs[key].data += sample.mm_kwargs[key].data mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0] seq_lens.extend(sample.seq_lens) + if sampling_mask is not None: + sample_mask = sample.sampling_mask if sample.sampling_mask is not None else _empty_sampling_mask(sample_len) + sampling_mask.ids += sample_mask.ids + sampling_mask.counts += sample_mask.counts sequence_lengths = [len(sample.input_ids) for sample in bin_content.samples] assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids)) @@ -607,6 +653,7 @@ def _materialize_bin(bin_content: _MicroBatchBin) -> MicroBatch: ref_logprobs=ref_logprobs, temperatures=temperatures, routed_experts=routed_experts, + sampling_mask=sampling_mask, mm_token_type_ids=mm_token_type_ids, env_names=env_names, mm_kwargs=mm_kwargs, @@ -733,6 +780,8 @@ def pad_micro_batch(micro_batch: MicroBatch, pad_to_multiple_of: int) -> MicroBa micro_batch.mm_token_type_ids.extend([0] * padding_size) if micro_batch.routed_experts is not None: _pad_routed_experts(micro_batch, padding_size) + if micro_batch.sampling_mask is not None: + _pad_sampling_mask(micro_batch, padding_size) micro_batch.env_names.extend([""] * padding_size) return micro_batch @@ -769,6 +818,15 @@ def _assert_token_arrays_aligned(micro_batch: MicroBatch) -> None: assert micro_batch.routed_experts.shape[0] == num_tokens, ( f"routed_experts misaligned after packing: {micro_batch.routed_experts.shape[0]} != {num_tokens} tokens" ) + if micro_batch.sampling_mask is not None: + mask_counts = np.frombuffer(micro_batch.sampling_mask.counts, dtype=np.int32) + assert len(mask_counts) == num_tokens, ( + f"sampling_mask misaligned after packing: {len(mask_counts)} != {num_tokens} tokens" + ) + assert len(micro_batch.sampling_mask.ids) == int(mask_counts.sum()) * _SAMPLING_MASK_ITEMSIZE, ( + f"sampling_mask ids/counts inconsistent after packing: " + f"{len(micro_batch.sampling_mask.ids)} bytes != {int(mask_counts.sum())} ids" + ) def _make_dummy_batch(source: MicroBatch) -> MicroBatch: @@ -781,6 +839,8 @@ def _make_dummy_batch(source: MicroBatch) -> MicroBatch: dummy.rl_weights = None dummy.ce_weights = None dummy.ref_kl_weights = None + # Fully loss-masked, so replaying sampling masks would be pure wasted work. + dummy.sampling_mask = None return dummy diff --git a/src/prime_rl/trainer/model.py b/src/prime_rl/trainer/model.py index 095795b8438..e9afd538afc 100644 --- a/src/prime_rl/trainer/model.py +++ b/src/prime_rl/trainer/model.py @@ -1328,6 +1328,7 @@ def forward( labels: Int[Tensor, "batch seq"] | None = None, temperature: Tensor | None = None, routed_experts: Int[Tensor, "batch seq layers topk"] | None = None, + sampling_mask: Int[Tensor, "batch seq mask"] | None = None, # Generic multimodal kwargs (e.g. {"pixel_values": ..., # "image_grid_thw": ...} for Qwen3-VL; just {"pixel_values": ...} # for Gemma3). Passed straight through to ``model(**kwargs)`` so @@ -1345,6 +1346,11 @@ def forward( "temperature": temperature, } + # Sampling masks are consumed by the injected prime lm_head; HF + # forwards don't know the kwarg, so only pass it when present. + if sampling_mask is not None: + kwargs["sampling_mask"] = sampling_mask + if mm_kwargs: # Forward the per-model multimodal tensors verbatim, plus the # renderer-supplied ``mm_token_type_ids`` (renderer owns the diff --git a/src/prime_rl/trainer/models/layers/lm_head.py b/src/prime_rl/trainer/models/layers/lm_head.py index 9896d32570c..e981ff16e59 100644 --- a/src/prime_rl/trainer/models/layers/lm_head.py +++ b/src/prime_rl/trainer/models/layers/lm_head.py @@ -44,6 +44,7 @@ def forward( hidden_states: torch.Tensor, labels: torch.Tensor | None = None, temperature: Tensor | None = None, + sampling_mask: Tensor | None = None, ) -> PrimeLmOutput: assert labels is not None, "FusedOutputLinear requires labels for chunked logprob computation" assert temperature is not None, "FusedOutputLinear requires per-token temperatures" @@ -52,9 +53,11 @@ def forward( hidden_states = hidden_states.reshape(b * s, h).contiguous() labels = labels.reshape(b * s).contiguous() inv_t = 1.0 / temperature.reshape(b * s).contiguous() # [N] + if sampling_mask is not None: + sampling_mask = sampling_mask.reshape(b * s, sampling_mask.shape[-1]).contiguous() logprobs, entropy = _SequenceChunkedLogProbEntropyFn.apply( - hidden_states, self.weight, labels, inv_t, self.chunk_size + hidden_states, self.weight, labels, inv_t, self.chunk_size, sampling_mask ) logprobs = logprobs.reshape(b, s) @@ -67,9 +70,14 @@ def __init__(self, in_features: int, out_features: int): super().__init__(in_features, out_features, bias=False) def forward( - self, hidden_states: torch.Tensor, labels: torch.Tensor | None = None, temperature: Tensor | None = None + self, + hidden_states: torch.Tensor, + labels: torch.Tensor | None = None, + temperature: Tensor | None = None, + sampling_mask: Tensor | None = None, ) -> PrimeLmOutput: - # VanillaOutputLinear just returns logits - temperature scaling is done externally in train.py + # VanillaOutputLinear just returns logits. train.py applies temperature + # scaling and sampling-mask replay. return PrimeLmOutput(logits=super().forward(hidden_states)) @@ -86,6 +94,23 @@ def _online_logsumexp_and_weighted_update( return m_new, s_new, t_new +def sampling_replay_mask(sampling_mask: torch.Tensor, labels: torch.Tensor) -> torch.Tensor: + """Positions replayable against their sampling mask: non-empty (-1 is padding) + and containing the label (a label outside its mask means misaligned data — + fall back to full-vocab rather than emit a corrupt logprob).""" + return (sampling_mask >= 0).any(dim=-1) & (sampling_mask == labels.unsqueeze(-1)).any(dim=-1) + + +def _sampling_mask_local_indices( + mask_chunk: torch.Tensor, vocab_start: int, vocab_end: int +) -> tuple[torch.Tensor, torch.Tensor]: + """Sampling-mask ids mapped into a vocab chunk as clamped local indices + plus the in-chunk validity mask (-1 entries are padding).""" + in_range = (mask_chunk >= vocab_start) & (mask_chunk < vocab_end) + local = (mask_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1) + return local, in_range + + class _SequenceChunkedLogProbEntropyFn(torch.autograd.Function): @staticmethod def forward( # type: ignore[override] @@ -95,9 +120,15 @@ def forward( # type: ignore[override] labels: torch.Tensor, # [N] inv_temperature: torch.Tensor, # [N] chunk_size: int, + sampling_mask: torch.Tensor | None = None, # [N, K] int32, -1-padded ) -> tuple[torch.Tensor, torch.Tensor]: """ Returns per-token logprobs and entropy by chunking over flattened sequence tokens. + + Positions with a usable ``sampling_mask`` (see ``sampling_replay_mask``) are + renormalized over that mask: ``logprob = scaled_logits[label] - + logsumexp(scaled_logits[mask])``. Other positions — and entropy, a + full-distribution diagnostic — keep full-vocab normalization. """ assert hidden.dim() == 2, f"expected hidden [N,H], got {tuple(hidden.shape)}" assert weight.dim() == 2, f"expected weight [V,H], got {tuple(weight.shape)}" @@ -107,6 +138,10 @@ def forward( # type: ignore[override] assert hidden.shape[1] == weight.shape[1], "hidden/weight H mismatch" assert hidden.shape[0] == inv_temperature.shape[0], "hidden/inv_temperature N mismatch" assert chunk_size > 0 + if sampling_mask is not None: + assert sampling_mask.dim() == 2 and sampling_mask.shape[0] == hidden.shape[0], ( + f"expected sampling_mask [N,K], got {tuple(sampling_mask.shape)}" + ) device = hidden.device n = hidden.shape[0] @@ -115,6 +150,7 @@ def forward( # type: ignore[override] logprobs = torch.empty((n,), device=device, dtype=torch.float32) entropy = torch.empty((n,), device=device, dtype=torch.float32) logz = torch.empty((n,), device=device, dtype=torch.float32) + replay = torch.zeros((n,), device=device, dtype=torch.bool) if sampling_mask is not None else None for start in range(0, n, chunk_size): end = min(start + chunk_size, n) @@ -128,6 +164,13 @@ def forward( # type: ignore[override] t = torch.zeros((token_count,), device=device, dtype=torch.float32) target_logits = torch.zeros((token_count,), device=device, dtype=torch.float32) + mask_chunk = sampling_mask[start:end].to(torch.long) if sampling_mask is not None else None + if mask_chunk is not None: + replay_chunk = sampling_replay_mask(mask_chunk, labels_chunk) + # Each mask id lives in exactly one vocab chunk; collect its logit + # into a [tokens, K] buffer and logsumexp once after the loop. + mask_logits = torch.full_like(mask_chunk, float("-inf"), dtype=torch.float32) + for vocab_start in range(0, vocab, vocab_chunk_size): vocab_end = min(vocab_start + vocab_chunk_size, vocab) weight_chunk = weight[vocab_start:vocab_end] @@ -136,21 +179,30 @@ def forward( # type: ignore[override] m, s, t = _online_logsumexp_and_weighted_update(m, s, t, scaled_logits) + if mask_chunk is not None: + mask_local, mask_in_range = _sampling_mask_local_indices(mask_chunk, vocab_start, vocab_end) + mask_logits = torch.where(mask_in_range, scaled_logits.gather(1, mask_local), mask_logits) + # Branchless target extraction - we don't want to stall the GPU here (because: if torch.any()) calls bool(Tensor) calls Tensor.items() <- sync here we don't want in_range = (labels_chunk >= vocab_start) & (labels_chunk < vocab_end) local_idx = (labels_chunk - vocab_start).clamp(0, vocab_end - vocab_start - 1).to(torch.int64) chunk_target = scaled_logits.gather(1, local_idx.unsqueeze(1)).squeeze(1) target_logits = torch.where(in_range, chunk_target, target_logits) - logz_chunk = m + torch.log(s) + logz_full = m + torch.log(s) + if mask_chunk is not None: + logz_chunk = torch.where(replay_chunk, torch.logsumexp(mask_logits, dim=-1), logz_full) + replay[start:end] = replay_chunk + else: + logz_chunk = logz_full logz[start:end] = logz_chunk logprobs[start:end] = target_logits - logz_chunk - entropy[start:end] = logz_chunk - (t / s) + entropy[start:end] = logz_full - (t / s) ctx.set_materialize_grads( False ) # Without materialized grads unused outputs get grad None instead of zeros and backward can reject them without a sync - ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz) + ctx.save_for_backward(hidden, weight, labels, inv_temperature, logz, sampling_mask, replay) ctx.chunk_size = chunk_size return logprobs, entropy @@ -161,7 +213,7 @@ def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor | None assert grad_entropy is None, "Backward through entropy is not implemented in FusedOutputLinear" assert grad_logprobs is not None, "FusedOutputLinear backward requires logprobs gradients" - hidden, weight, labels, inv_temperature, logz = ctx.saved_tensors + hidden, weight, labels, inv_temperature, logz, sampling_mask, replay = ctx.saved_tensors chunk_size: int = ctx.chunk_size n, _ = hidden.shape @@ -179,12 +231,24 @@ def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor | None grad_chunk = grad_logprobs[start:end].to(torch.float32) inv_t_chunk = inv_temperature[start:end].unsqueeze(-1) logz_chunk = logz[start:end] + mask_chunk = sampling_mask[start:end].to(torch.long) if sampling_mask is not None else None + replay_chunk = replay[start:end] if replay is not None else None for vocab_start in range(0, vocab, vocab_chunk_size): vocab_end = min(vocab_start + vocab_chunk_size, vocab) weight_chunk = weight[vocab_start:vocab_end] logits_chunk = hidden_chunk @ weight_chunk.t() scaled_logits = logits_chunk.to(torch.float32) * inv_t_chunk + + if mask_chunk is not None: + # Replayed rows get softmax gradient only on mask ids. Set masked-out + # logits to -inf before exp: a masked-out logit above the sampling-mask + # logZ would overflow exp() to inf (and inf * 0 = NaN in the grads). + local, in_range = _sampling_mask_local_indices(mask_chunk, vocab_start, vocab_end) + mask_indicator = torch.zeros(scaled_logits.shape, dtype=torch.int8, device=scaled_logits.device) + mask_indicator.scatter_add_(1, local, in_range.to(torch.int8)) + masked_out = replay_chunk.unsqueeze(-1) & (mask_indicator == 0) + scaled_logits.masked_fill_(masked_out, float("-inf")) probs = torch.exp(scaled_logits - logz_chunk.unsqueeze(-1)) grad_logits = (-grad_chunk).unsqueeze(-1) * probs @@ -199,7 +263,7 @@ def backward(ctx, grad_logprobs: torch.Tensor, grad_entropy: torch.Tensor | None if needs_weight: grad_weight[vocab_start:vocab_end].add_(grad_logits.to(weight.dtype).t() @ hidden_chunk) - return grad_hidden, grad_weight, None, None, None + return grad_hidden, grad_weight, None, None, None, None def inject_prime_lm_head( @@ -262,6 +326,7 @@ def new_forward( labels: torch.Tensor | None = None, logits_to_keep: int = 0, temperature: torch.Tensor | None = None, + sampling_mask: torch.Tensor | None = None, **kwargs: object, ) -> PrimeLmOutput: # For VLM with images, don't create position_ids - let model compute MRoPE internally @@ -285,6 +350,7 @@ def new_forward( hidden_states[:, slice_indices, :], labels[:, slice_indices] if labels is not None else None, temperature=temperature[:, slice_indices] if temperature is not None else None, + sampling_mask=sampling_mask[:, slice_indices] if sampling_mask is not None else None, ) # Bind the new forward to the model diff --git a/src/prime_rl/trainer/models/layers/lm_head_gemma.py b/src/prime_rl/trainer/models/layers/lm_head_gemma.py index 7fee1a8d87f..27da7021391 100644 --- a/src/prime_rl/trainer/models/layers/lm_head_gemma.py +++ b/src/prime_rl/trainer/models/layers/lm_head_gemma.py @@ -23,9 +23,11 @@ def forward( hidden_states: torch.Tensor, labels: torch.Tensor | None = None, temperature: Tensor | None = None, + sampling_mask: Tensor | None = None, ) -> PrimeLmOutput: assert labels is not None, "GemmaFusedOutputLinear requires labels for chunked logprob computation" assert temperature is not None, "GemmaFusedOutputLinear requires per-token temperatures" + assert sampling_mask is None, "sampling-mask replay is not supported with Gemma softcapped lm_heads" b, s, h = hidden_states.shape hidden_states = hidden_states.reshape(b * s, h).contiguous() @@ -47,7 +49,11 @@ def __init__(self, in_features: int, out_features: int, softcap: float): self.softcap = softcap def forward( - self, hidden_states: torch.Tensor, labels: torch.Tensor | None = None, temperature: Tensor | None = None + self, + hidden_states: torch.Tensor, + labels: torch.Tensor | None = None, + temperature: Tensor | None = None, + sampling_mask: Tensor | None = None, ) -> PrimeLmOutput: logits = super().forward(hidden_states) logits = self.softcap * torch.tanh(logits / self.softcap) diff --git a/src/prime_rl/trainer/rl/data.py b/src/prime_rl/trainer/rl/data.py index 308541e70e6..884f2f6e032 100644 --- a/src/prime_rl/trainer/rl/data.py +++ b/src/prime_rl/trainer/rl/data.py @@ -1,6 +1,7 @@ from pathlib import Path from typing import TypedDict +import numpy as np import torch from jaxtyping import Bool, Float, Int from torch import Tensor @@ -36,6 +37,10 @@ class TensorMicroBatch(TypedDict): # MoE router replay routed_experts: Int[Tensor, "batch seq layers topk"] | None + # Sampling-mask token ids per position, padded with -1 to the micro batch's + # maximum mask size. A row containing only -1 has no mask. + sampling_mask: Int[Tensor, "batch seq mask"] | None + # Generic multimodal kwargs — flat dict matching the model's forward # signature (e.g. ``{"pixel_values": ..., "image_grid_thw": ...}`` for # Qwen3-VL; ``{"pixel_values": ...}`` for Gemma3-VL). The trainer @@ -122,6 +127,7 @@ def _get_sample_micro_batch(self, generator: torch.Generator) -> TensorMicroBatc "lora_num_tokens": torch.tensor([input_ids.shape[0]], dtype=torch.int32), "seq_lens": torch.tensor(sequence_lengths, dtype=torch.long), "routed_experts": None, + "sampling_mask": None, "mm_kwargs": None, "mm_token_type_ids": None, "rl_weights": None, @@ -151,6 +157,7 @@ def _get_micro_batch(self, generator: torch.Generator) -> TensorMicroBatch: "lora_num_tokens": torch.tensor([self.seq_len], dtype=torch.int32), "seq_lens": torch.tensor([self.seq_len], dtype=torch.long), "routed_experts": None, + "sampling_mask": None, "mm_kwargs": None, "mm_token_type_ids": None, "rl_weights": None, @@ -206,6 +213,16 @@ def _micro_batch_to_tensor(self, micro_batch: MicroBatch) -> TensorMicroBatch: .to(torch.int32) .unsqueeze(0) ) + sampling_mask = None + packed_sampling_mask = micro_batch.sampling_mask + if packed_sampling_mask is not None: + counts = np.frombuffer(packed_sampling_mask.counts, dtype=np.int32) + ids = np.frombuffer(packed_sampling_mask.ids, dtype=np.int32) + # Boolean assignment fills row-major, matching the flat concat order. + max_mask_size = max(int(counts.max()), 1) if counts.size else 1 + padded = np.full((len(counts), max_mask_size), -1, dtype=np.int32) + padded[np.arange(max_mask_size)[None, :] < counts[:, None]] = ids + sampling_mask = torch.from_numpy(padded).unsqueeze(0) return TensorMicroBatch( input_ids=torch.tensor(micro_batch.input_ids, dtype=torch.long).unsqueeze(0), position_ids=torch.tensor(micro_batch.position_ids, dtype=torch.long).unsqueeze(0), @@ -226,6 +243,7 @@ def _micro_batch_to_tensor(self, micro_batch: MicroBatch) -> TensorMicroBatch: if micro_batch.mm_token_type_ids is not None else None, routed_experts=routed_experts, + sampling_mask=sampling_mask, rl_weights=torch.tensor(micro_batch.rl_weights, dtype=torch.float).unsqueeze(0) if micro_batch.rl_weights is not None else None, diff --git a/src/prime_rl/trainer/rl/loss.py b/src/prime_rl/trainer/rl/loss.py index c4b63770d95..126c6671330 100644 --- a/src/prime_rl/trainer/rl/loss.py +++ b/src/prime_rl/trainer/rl/loss.py @@ -7,6 +7,7 @@ from torch import Tensor from prime_rl.configs.trainer import CustomLossConfig, IPOLossConfig, LossConfig +from prime_rl.trainer.models.layers.lm_head import sampling_replay_mask from prime_rl.utils.utils import import_object @@ -54,6 +55,27 @@ def selective_log_softmax( return torch.gather(logprobs, dim=-1, index=index.unsqueeze(-1)).squeeze(-1) +@jaxtyped(typechecker=typechecker) +def selective_log_softmax_with_sampling_mask( + logits: Float[Tensor, "batch seq vocab"], + index: Int[Tensor, "batch seq"], + sampling_mask: Int[Tensor, "batch seq mask"], +) -> Float[Tensor, "batch seq"]: + """Per-token logprobs with sampling-mask replay: positions with a usable + mask (see ``sampling_replay_mask``) get ``logits[index] - + logsumexp(logits[mask])``, others full-vocab. Non-replayed rows are zeroed + before the logsumexp so the unselected ``where`` branch can't emit NaN grads. + """ + full_logprobs = selective_log_softmax(logits, index) + replay = sampling_replay_mask(sampling_mask, index) + mask_logits = torch.gather(logits, -1, sampling_mask.clamp_min(0).long()) + mask_logits = torch.where(sampling_mask >= 0, mask_logits, float("-inf")) + mask_logits = torch.where(replay.unsqueeze(-1), mask_logits, 0.0) + logz_masked = torch.logsumexp(mask_logits, dim=-1) + target_logits = torch.gather(logits, -1, index.unsqueeze(-1)).squeeze(-1) + return torch.where(replay, target_logits - logz_masked, full_logprobs) + + @jaxtyped(typechecker=typechecker) @torch.compile(dynamic=True) def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[Tensor, "batch seq"]: @@ -63,14 +85,15 @@ def compute_entropy(shifted_logits: Float[Tensor, "batch seq vocab"]) -> Float[T return entropy -def shift_tensor_left(t: Float[Tensor, "batch seq"]) -> Float[Tensor, "batch seq"]: - """Shifts the tensor one token to the left. +def shift_tensor_left(t: Tensor, pad_value: float = 0.0) -> Tensor: + """Shifts the tensor one position to the left along dim 1. - Used to create labels from input_ids: labels[i] = input_ids[i+1]. - The last position is padded with 0 (a valid token index) since this value - will be shifted off by shift_tensor_right and never used. + Used to create labels from input_ids: labels[i] = input_ids[i+1]. The last + position is padded with ``pad_value`` (0 is a valid token index but gets + shifted off by shift_tensor_right and never used). Works for [batch, seq] + labels and label-aligned [batch, seq, ...] fields like sampling_mask. """ - return torch.cat([t[:, 1:], torch.full((t.shape[0], 1), 0, device=t.device, dtype=t.dtype)], dim=1) + return torch.cat([t[:, 1:], torch.full_like(t[:, :1], pad_value)], dim=1) def shift_tensor_right(t: Float[Tensor, "batch seq"], pad_value: float | None = None) -> Float[Tensor, "batch seq"]: diff --git a/src/prime_rl/trainer/rl/train.py b/src/prime_rl/trainer/rl/train.py index ef387113ec4..6ed15aac18a 100644 --- a/src/prime_rl/trainer/rl/train.py +++ b/src/prime_rl/trainer/rl/train.py @@ -31,6 +31,7 @@ compute_loss, compute_importance_ratio_and_mismatch_kl, selective_log_softmax, + selective_log_softmax_with_sampling_mask, setup_rl_loss_fn, shift_tensor_left, shift_tensor_right, @@ -377,6 +378,10 @@ def train(config: TrainerConfig): # we could've gotten routed experts from the inference server, but we didn't enable router replay routed_experts = None + sampling_mask = ( + micro_batch["sampling_mask"].to("cuda") if micro_batch["sampling_mask"] is not None else None + ) + # Multimodal kwargs are an opaque per-model dict (e.g. # {"pixel_values": ..., "image_grid_thw": ...} for Qwen3-VL, # just {"pixel_values": ...} for Gemma3-VL) — we move every @@ -397,6 +402,10 @@ def train(config: TrainerConfig): seq_lens = micro_batch["seq_lens"].to("cuda") labels = shift_tensor_left(input_ids) + if sampling_mask is not None: + # Sampling masks ride at the sampled token's own position (like inference + # logprobs); shift to align with the label each position predicts. + sampling_mask = shift_tensor_left(sampling_mask, pad_value=-1) seq_lens_are_pre_shard = False @@ -417,6 +426,10 @@ def train(config: TrainerConfig): labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size) if routed_experts is not None and not defer_vlm_cp_to_model: routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size) + if sampling_mask is not None: + # The LM head consumes masks after any deferred VLM sharding, so + # they must follow the label shard rather than the input shard. + sampling_mask = shard_for_cp(sampling_mask, cp_rank=cp_rank, cp_world_size=cp_size) if config.model.lora: lora_num_tokens = micro_batch["lora_num_tokens"].to("cuda") @@ -436,6 +449,12 @@ def train(config: TrainerConfig): if cp_enabled: temperatures = shard_for_cp(temperatures, cp_rank=cp_rank, cp_world_size=cp_size) + if sampling_mask is not None: + assert sampling_mask.shape[:2] == labels.shape, ( + f"sampling_mask shape {tuple(sampling_mask.shape)} is not aligned with " + f"labels shape {tuple(labels.shape)}" + ) + # Forward pass with per-token temperatures with maybe_record_function("forward"), maybe_activation_offloading(config.model.ac_offloading): out = forward( @@ -449,6 +468,7 @@ def train(config: TrainerConfig): seq_lens=seq_lens, seq_lens_are_pre_shard=seq_lens_are_pre_shard, routed_experts=routed_experts, + sampling_mask=sampling_mask, ) if out.get("logprobs") is None: @@ -457,7 +477,10 @@ def train(config: TrainerConfig): logits = out["logits"] # Per-token temperature scaling: temperatures is [batch, seq], logits is [batch, seq, vocab] scaled_logits = logits / temperatures.unsqueeze(-1) - out["logprobs"] = selective_log_softmax(scaled_logits, labels) + if sampling_mask is not None: + out["logprobs"] = selective_log_softmax_with_sampling_mask(scaled_logits, labels, sampling_mask) + else: + out["logprobs"] = selective_log_softmax(scaled_logits, labels) out["entropy"] = compute_entropy(scaled_logits) # else: FusedOutputLinear was used - logprobs already computed with per-token temperatures diff --git a/src/prime_rl/transports/batch/__init__.py b/src/prime_rl/transports/batch/__init__.py index 07e7e6314f0..922cd96886a 100644 --- a/src/prime_rl/transports/batch/__init__.py +++ b/src/prime_rl/transports/batch/__init__.py @@ -9,6 +9,7 @@ from prime_rl.transports.batch.types import ( MicroBatch, RoutedExperts, + SamplingMask, TrainingSample, ) from prime_rl.transports.batch.zmq import ( @@ -48,6 +49,7 @@ def setup_batch_receiver( "BatchSender", "TrainingSample", "MicroBatch", + "SamplingMask", "RoutedExperts", "setup_batch_sender", "setup_batch_receiver", diff --git a/src/prime_rl/transports/batch/types.py b/src/prime_rl/transports/batch/types.py index 21fe63f810c..53831ac3e7b 100644 --- a/src/prime_rl/transports/batch/types.py +++ b/src/prime_rl/transports/batch/types.py @@ -18,6 +18,13 @@ class RoutedExperts(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tru dtype: str +# Sampling masks for top-p/top-k replay: flat int32 token-id bytes plus an +# int32 count per token position (0 = no mask); len(ids) == 4 * counts.sum(). +class SamplingMask(msgspec.Struct, array_like=True, gc=False, omit_defaults=True): + ids: bytes + counts: bytes + + # Produced by the orchestrator's train sink; consumed in-process by # ``prepare_batch``, which packs samples into per-rank ``MicroBatch``es. class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=True): @@ -69,6 +76,10 @@ class TrainingSample(msgspec.Struct, array_like=True, gc=False, omit_defaults=Tr # samples without live rl member tokens (the trainer raises otherwise). advantages: list[float] | None = None + # Last field on purpose: array_like structs encode positionally, so appending + # keeps the wire layout of earlier fields stable across versions. + sampling_mask: SamplingMask | None = None + # Orchestrator -> Trainer class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True): @@ -97,3 +108,6 @@ class MicroBatch(msgspec.Struct, array_like=True, gc=False, omit_defaults=True): rl_weights: list[float] | None = None ce_weights: list[float] | None = None ref_kl_weights: list[float] | None = None + + # See TrainingSample.sampling_mask; appended last for wire-layout stability. + sampling_mask: SamplingMask | None = None diff --git a/tests/unit/test_configs.py b/tests/unit/test_configs.py index 16a30885c39..a54ca921870 100644 --- a/tests/unit/test_configs.py +++ b/tests/unit/test_configs.py @@ -1,3 +1,4 @@ +import os from pathlib import Path from typing import Annotated, Literal @@ -356,6 +357,54 @@ def test_env_algo_overrides_top_level(): ) +def test_policy_sources_accept_different_top_p_values(): + with pytest.warns(UserWarning, match="defaulting top_k"): + config = OrchestratorConfig.model_validate( + { + "renderer": {"name": "qwen3"}, + "train": { + "source": [ + { + "name": "top-p-95", + "env": {"taskset": {"id": "reverse-text"}}, + "sampling": {"top_p": 0.95}, + }, + { + "name": "top-p-97", + "env": {"taskset": {"id": "reverse-text"}}, + "sampling": {"top_p": 0.97}, + }, + ] + }, + } + ) + + assert [source.sampling.top_k for source in config.train.source] == [512, 512] + + +def test_policy_sources_reject_mixed_top_k_capture(): + with pytest.warns(UserWarning, match="defaulting top_k"): + with pytest.raises(ValidationError, match="cannot mix top_k > 0 and top_k = -1"): + OrchestratorConfig.model_validate( + { + "renderer": {"name": "qwen3"}, + "train": { + "source": [ + { + "name": "truncated", + "env": {"taskset": {"id": "reverse-text"}}, + "sampling": {"top_p": 0.95}, + }, + { + "name": "untruncated", + "env": {"taskset": {"id": "reverse-text"}}, + }, + ] + }, + } + ) + + def test_trainer_enable_token_export_cli_flag(): assert not cli(TrainerConfig, args=[]).enable_token_export assert cli(TrainerConfig, args=["--enable-token-export"]).enable_token_export @@ -827,3 +876,19 @@ def test_explicit_inference_parser_wins_over_auto(): ) assert config.inference is not None assert config.inference.vllm.tool_call_parser == "hermes" + + +def test_combined_replay_uses_v2_runner(monkeypatch): + from prime_rl.inference.server import setup_vllm_env + + monkeypatch.delenv("VLLM_USE_V2_MODEL_RUNNER", raising=False) + config = InferenceConfig( + enable_return_sampling_mask=True, + vllm={"enable_return_routed_experts": True}, + ) + + setup_vllm_env(config) + + assert config.enable_return_sampling_mask is True + assert config.vllm.enable_return_routed_experts is True + assert os.environ["VLLM_USE_V2_MODEL_RUNNER"] == "1" diff --git a/uv.lock b/uv.lock index 59e79d92bbc..545a8c68b71 100644 --- a/uv.lock +++ b/uv.lock @@ -310,21 +310,20 @@ wheels = [ [[package]] name = "anthropic" -version = "0.104.1" +version = "1.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "anyio" }, - { name = "distro" }, { name = "docstring-parser" }, - { name = "httpx" }, + { name = "httpx2" }, { name = "jiter" }, { name = "pydantic" }, { name = "sniffio" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/22/c7/7a655b948916f777354648ce979f68b94d5b8dbdb5f61fed1f37fad9378c/anthropic-0.104.1.tar.gz", hash = "sha256:17362b6c45f527afcc9b0fdf62011ffd359726ab2ebcb1978ea0cc41bd8d8d40", size = 850081, upload-time = "2026-05-22T15:36:57.432Z" } +sdist = { url = "https://files.pythonhosted.org/packages/25/aa/4978e58035bd6c638c7b483450a68b7ef2d732ab78885e27bb9db0cff1a2/anthropic-1.0.0.tar.gz", hash = "sha256:42be3c97604af7252c5898413aee076ace6c46e9bca0d0d90ceb77c7d3719027", size = 1077769, upload-time = "2026-08-20T19:59:00.565Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b8/12/d9ab42790494d7c428391a46cd28492395566a6a8ccb138d681978594455/anthropic-0.104.1-py3-none-any.whl", hash = "sha256:35c8cb456f5a4405aafe1f10f03f6fcc54fa51fa8ec01d655cc4b437d120e9b7", size = 832996, upload-time = "2026-05-22T15:36:59.519Z" }, + { url = "https://files.pythonhosted.org/packages/ad/5b/db4a854aebf5d33a5ab714c46af6eb85ee44f390ed29b7b325c00b9f11ed/anthropic-1.0.0-py3-none-any.whl", hash = "sha256:32dd52e9e1d774393b27182f451398ba4262287a4d0eab30887f89f1481b3ae4", size = 1171725, upload-time = "2026-08-20T19:58:58.725Z" }, ] [[package]] @@ -7677,7 +7676,6 @@ source = { editable = "deps/verifiers" } dependencies = [ { name = "aiohttp" }, { name = "anthropic" }, - { name = "datasets" }, { name = "gepa" }, { name = "httpx" }, { name = "loguru" }, @@ -7696,7 +7694,6 @@ dependencies = [ { name = "tenacity" }, { name = "tomli-w" }, { name = "typing-extensions" }, - { name = "uvloop", marker = "platform_python_implementation != 'PyPy'" }, ] [package.optional-dependencies] @@ -7711,8 +7708,8 @@ ta = [ [package.metadata] requires-dist = [ { name = "aiohttp", specifier = ">=3.14.1" }, - { name = "anthropic", specifier = ">=0.78.0" }, - { name = "datasets", specifier = ">=3.3.0,<6.0.0" }, + { name = "anthropic", specifier = ">=1.0.0" }, + { name = "datasets", marker = "extra == 'lean'", specifier = ">=3.3.0,<6.0.0" }, { name = "gepa", specifier = ">=0.0.6" }, { name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.21.0" }, { name = "httpx", specifier = ">=0.27.0" }, @@ -7723,22 +7720,21 @@ requires-dist = [ { name = "msgpack", specifier = ">=1.1.2" }, { name = "nltk", marker = "extra == 'ta'", specifier = ">=3.9.2" }, { name = "numpy", specifier = ">=2.1.0" }, - { name = "openai", specifier = ">=2.9.0" }, + { name = "openai", specifier = ">=2.54.0,<3.0.0" }, { name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" }, { name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" }, { name = "prime-sandboxes", specifier = ">=0.2.39" }, { name = "prime-tunnel", specifier = ">=0.1.8" }, { name = "pydantic", specifier = ">=2.12.3" }, { name = "pyzmq", specifier = ">=27.1.0" }, - { name = "renderers", extras = ["multimodal"], specifier = ">=0.1.11" }, + { name = "renderers", extras = ["multimodal"], specifier = ">=0.1.12.dev2" }, { name = "rich", specifier = ">=11.0.0" }, { name = "tenacity", specifier = ">=8.5.0" }, { name = "textarena", marker = "extra == 'ta'", specifier = "==0.7.4" }, { name = "tomli-w", specifier = ">=1.0.0" }, { name = "typing-extensions", specifier = ">=4.12.2" }, - { name = "uvloop", marker = "platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'", specifier = ">=0.21.0" }, ] -provides-extras = ["harbor", "modal", "openenv", "ta"] +provides-extras = ["harbor", "lean", "modal", "openenv", "ta"] [package.metadata.requires-dev] dev = [