Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
137f8f49c8 | ||
|
|
f04c8d988c | ||
|
|
4d361adacc | ||
|
|
7f77713886 | ||
|
|
efeddae6bb |
@@ -2,6 +2,7 @@
|
||||
|
||||
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
|
||||
|
||||
- **`orchestrator.advantage` length-penalty overhaul + length-weighted baseline**: `length_penalty` is now a single shape — a linear penalty that subtracts `coef * pass_rate * (model completion tokens / orchestrator.seq_len)` from each reward before the baseline subtraction (`pass_rate` = group mean reward, so solved-often problems get the strongest concision pressure and never-solved groups get none), with an optional `gate_by_correctness` flag (default `false`) that restricts the penalty to correct rollouts (`reward == 1`). The previous discriminated `type = "tokens" | "turns"` efficiency-shaping variants and the per-penalty `max_length` field have been removed — configure `[orchestrator.advantage.length_penalty]` with `coef` (and optionally `gate_by_correctness`) instead; the denominator is always `orchestrator.seq_len`. Also adds `orchestrator.advantage.length_weighted_baseline` (default `false`): when enabled, the GRPO baseline is the token-length-weighted mean reward (`sum(len_i * reward_i) / sum(len_i)`) instead of the plain mean. (2026-06-03)
|
||||
- **`trainer.experimental.token_export` removed → `trainer.enable_token_export`**: `TrainerExperimentalConfig` and the `[trainer.experimental] token_export = true` setting have been removed with no migration alias. Existing trainer configs must delete the `[trainer.experimental]` block and set the new top-level trainer flag instead: `enable_token_export = true` in a trainer config file, or `trainer.enable_token_export = true` when nested under `[trainer]` in an RL config. The trainer entrypoint CLI flag is `--enable-token-export`. (2026-06-10)
|
||||
- **`inference.kv_cache_offload.cpu_bytes` removed → discriminated `type` config**: The flat `[inference.kv_cache_offload]` block with a single `cpu_bytes` field is replaced by a backend-discriminated union with composable `cpu`/`disk` tiers. Migrate native CPU offload from `[inference.kv_cache_offload]\ncpu_bytes = N` to `[inference.kv_cache_offload]\ntype = "native"` plus `[inference.kv_cache_offload.cpu]\nnum_bytes = N`. A `type = "mooncake"` backend (per-node distributed store; multi-node/SLURM only) and an optional `[inference.kv_cache_offload.disk]\npath = "..."` tier (layered behind cpu) are also available. `extra="forbid"` rejects the old `cpu_bytes` key, so existing configs must migrate. (2026-06-02)
|
||||
- **Orchestrator async-pipeline rewrite** (collection of removals/renames). The orchestrator was rewritten to overlap train/eval rollouts on a shared concurrency limiter; several config fields were removed or renamed.
|
||||
|
||||
+13
-3
@@ -136,10 +136,20 @@ The default advantage is per-group reward minus per-group baseline (DR-GRPO with
|
||||
|
||||
This is intentionally simple — it does the right thing for most envs. Switch to a [custom advantage](#custom-advantage) when you need group-aware shaping that depends on trajectory metadata (sub-agent rollouts, relative-rank shaping, …).
|
||||
|
||||
Two built-in **length penalties** can be layered on top of any advantage to discourage rambling:
|
||||
A **length penalty** can be layered on top of the default advantage to discourage rambling. Configured under `[orchestrator.advantage.length_penalty]`, it subtracts a `coef * pass_rate * (completion tokens / orchestrator.seq_len)` term from every reward before the baseline subtraction, where `pass_rate` is the problem's mean reward across the group. The pass-rate factor means problems the model already solves reliably get the strongest push toward concise outputs, while rarely-solved problems are barely penalized (a never-solved group, mean reward 0, gets none). Set `gate_by_correctness = true` to apply the penalty only to correct rollouts (`reward == 1`), leaving incorrect ones untouched:
|
||||
|
||||
- `[orchestrator.length_penalty] type = "tokens"` — penalizes long completions in tokens, with configurable target and slope.
|
||||
- `[orchestrator.length_penalty] type = "turns"` — penalizes long multi-turn rollouts by turn count.
|
||||
```toml
|
||||
[orchestrator.advantage.length_penalty]
|
||||
coef = 0.25 # effective penalty is coef * pass_rate * (completion_tokens / seq_len)
|
||||
gate_by_correctness = false # when true, only penalize rollouts with reward == 1
|
||||
```
|
||||
|
||||
By default the baseline is the plain group mean reward. Set `length_weighted_baseline = true` to instead use the token-length-weighted mean — `sum(len_i * reward_i) / sum(len_i)` — which centers advantages by per-token expected reward when rollouts vary a lot in length:
|
||||
|
||||
```toml
|
||||
[orchestrator.advantage]
|
||||
length_weighted_baseline = true
|
||||
```
|
||||
|
||||
|
||||
### Custom Advantage
|
||||
|
||||
@@ -143,31 +143,22 @@ class EvalSamplingConfig(BaseConfig):
|
||||
return data
|
||||
|
||||
|
||||
class TokensLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["tokens"] = "tokens"
|
||||
class LinearLengthPenaltyConfig(BaseConfig):
|
||||
coef: float = Field(0.25, ge=0, allow_inf_nan=False)
|
||||
"""Scale on the linear length penalty. Each reward is reduced by ``coef * pass_rate * (model completion tokens / orchestrator.seq_len)`` — where ``pass_rate`` is the group's mean reward — before the GRPO baseline subtraction. Finite and non-negative."""
|
||||
|
||||
completion_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on model completion tokens. Finite and non-negative."""
|
||||
|
||||
tool_response_weight: float = Field(1.0, ge=0, allow_inf_nan=False)
|
||||
"""Weight on tool-response tokens (read from the rollout's ``*_total_tool_response_tokens`` harness metric; 0 if absent). Finite and non-negative."""
|
||||
|
||||
|
||||
class TurnsLengthPenaltyConfig(BaseConfig):
|
||||
type: Literal["turns"] = "turns"
|
||||
|
||||
|
||||
LengthPenaltyConfig: TypeAlias = Annotated[
|
||||
TokensLengthPenaltyConfig | TurnsLengthPenaltyConfig,
|
||||
Field(discriminator="type"),
|
||||
]
|
||||
gate_by_correctness: bool = False
|
||||
"""When True, scale each rollout's penalty by its reward (``penalty * reward``), so correct rollouts (``reward == 1``) are penalized and incorrect ones (``reward == 0``) are not. When False, every rollout is penalized equally."""
|
||||
|
||||
|
||||
class DefaultAdvantageConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
length_penalty: LengthPenaltyConfig | None = None
|
||||
"""Correctness-gated length penalty. ``tokens`` shapes by weighted token cost; ``turns`` shapes by trajectory turn count; None disables shaping. In mixed groups, lower-cost correct rollouts get amplified advantage (up to 2x), higher-cost correct rollouts are unchanged, incorrect untouched. In all-correct groups, below-average-cost rollouts get advantage in [0, 1], others get 0."""
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None
|
||||
"""Length penalty applied during advantage computation. Subtracts a ``coef * pass_rate * (completion tokens / orchestrator.seq_len)`` term from each reward (``pass_rate`` = group mean reward) before the baseline subtraction, so solved-often problems get the strongest concision pressure and never-solved groups get none. None disables the penalty."""
|
||||
|
||||
length_weighted_baseline: bool = False
|
||||
"""When True, the GRPO baseline is the token-length-weighted mean reward (``sum(len_i * reward_i) / sum(len_i)``) instead of the plain group mean, centering advantages by per-token expected reward."""
|
||||
|
||||
|
||||
class CustomAdvantageConfig(BaseConfig):
|
||||
|
||||
@@ -88,6 +88,7 @@ envs = [
|
||||
"reverse-text",
|
||||
"rlm-swe",
|
||||
"rlm-search",
|
||||
"rlm-uuid-ctf",
|
||||
"science-env",
|
||||
"simpleqa-verified",
|
||||
"tau2-bench",
|
||||
@@ -228,6 +229,7 @@ opencode-swe = { path = "deps/research-environments/environments/opencode_swe",
|
||||
reverse-text = { path = "deps/verifiers/environments/reverse_text", editable = true }
|
||||
rlm-swe = { path = "deps/research-environments/environments/rlm_swe", editable = true }
|
||||
rlm-search = { path = "deps/research-environments/environments/rlm_search", editable = true }
|
||||
rlm-uuid-ctf = { path = "deps/research-environments/environments/rlm_uuid_ctf", editable = true }
|
||||
science-env = { path = "deps/research-environments/environments/science_env", editable = true }
|
||||
simpleqa-verified = { path = "deps/research-environments/environments/simpleqa_verified", editable = true }
|
||||
tau2-bench = { path = "deps/research-environments/environments/tau2_bench", editable = true }
|
||||
|
||||
@@ -27,7 +27,7 @@ uv sync --group dev # + pytest, ruff, pre-commit
|
||||
uv sync --all-extras # recommended: envs, flash-attn, flash-attn-cute, etc.
|
||||
```
|
||||
|
||||
The `envs` extra installs every env workspace listed in `[tool.uv.workspace]`. Adding a new env means adding it to `members`, the `envs` extra, and `[tool.uv.sources]`.
|
||||
The `envs` extra installs environments listed under `[project.optional-dependencies].envs`, resolved through `[tool.uv.sources]`. Adding a new env means adding its package name to `envs` and its editable source path to `[tool.uv.sources]`.
|
||||
|
||||
When bumping a package past the workspace-wide `exclude-newer = "7 days"` window, add it (and any newly-required transitives) to `[tool.uv.exclude-newer-package]` before refreshing `uv.lock`.
|
||||
|
||||
|
||||
@@ -5,8 +5,6 @@ from typing import TYPE_CHECKING, Callable
|
||||
|
||||
import torch
|
||||
import verifiers as vf
|
||||
from jaxtyping import Float
|
||||
from torch import Tensor
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
@@ -14,11 +12,9 @@ if TYPE_CHECKING:
|
||||
from prime_rl.configs.orchestrator import (
|
||||
AdvantageConfig,
|
||||
CustomAdvantageConfig,
|
||||
LengthPenaltyConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.utils import get_model_completion_len, get_tool_response_len
|
||||
from prime_rl.orchestrator.utils import get_model_completion_len
|
||||
from prime_rl.utils.utils import import_object
|
||||
|
||||
|
||||
@@ -50,68 +46,36 @@ entry per rollout. `assign_advantages` calls it on one already-grouped cohort.
|
||||
|
||||
def default_advantage_fn(
|
||||
inputs: AdvantageInputs,
|
||||
length_penalty: LengthPenaltyConfig | None = None,
|
||||
length_penalty: LinearLengthPenaltyConfig | None = None,
|
||||
max_seq_len: int | None = None,
|
||||
length_weighted_baseline: bool = False,
|
||||
) -> AdvantageOutputs:
|
||||
"""Default GRPO advantage for a single group: reward minus per-group baseline.
|
||||
|
||||
`length_penalty` enables correctness-gated efficiency shaping over a per-rollout
|
||||
cost: tokens (weighted completion + tool-response) or trajectory turn count.
|
||||
``length_penalty`` subtracts ``coef * pass_rate * (completion tokens / max_seq_len)``
|
||||
from each reward (``pass_rate`` = group mean reward), optionally gated to correct
|
||||
(``reward == 1``) rollouts. ``length_weighted_baseline`` uses the token-length-weighted
|
||||
mean reward as the baseline instead of the plain mean.
|
||||
"""
|
||||
rewards = torch.tensor([r["reward"] for r in inputs.rollouts], dtype=torch.float32)
|
||||
lengths = torch.tensor([get_model_completion_len(r) for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
|
||||
if isinstance(length_penalty, TokensLengthPenaltyConfig):
|
||||
w_c = length_penalty.completion_weight
|
||||
w_t = length_penalty.tool_response_weight
|
||||
costs = torch.tensor(
|
||||
[w_c * get_model_completion_len(r) + w_t * get_tool_response_len(r) for r in inputs.rollouts],
|
||||
dtype=rewards.dtype,
|
||||
)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if isinstance(length_penalty, TurnsLengthPenaltyConfig):
|
||||
costs = torch.tensor([len(r["trajectory"]) for r in inputs.rollouts], dtype=rewards.dtype)
|
||||
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs).tolist())
|
||||
if length_penalty is not None:
|
||||
if max_seq_len is None:
|
||||
raise ValueError("max_seq_len is required when length_penalty is enabled")
|
||||
penalty = length_penalty.coef * rewards.mean() * (lengths / max_seq_len)
|
||||
if length_penalty.gate_by_correctness:
|
||||
penalty = penalty * rewards
|
||||
rewards = rewards - penalty
|
||||
|
||||
return AdvantageOutputs(advantages=(rewards - rewards.mean()).tolist())
|
||||
if length_weighted_baseline:
|
||||
baseline = (lengths * rewards).sum() / lengths.sum()
|
||||
else:
|
||||
baseline = rewards.mean()
|
||||
return AdvantageOutputs(advantages=(rewards - baseline).tolist())
|
||||
|
||||
|
||||
def _efficiency_shaping(
|
||||
rewards: Float[Tensor, "group_size"],
|
||||
costs: Float[Tensor, "group_size"],
|
||||
) -> Float[Tensor, "group_size"]:
|
||||
"""Correctness-gated efficiency shaping with bounded advantages.
|
||||
|
||||
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
|
||||
preserving zero-mean advantages within the group. `costs` is a per-rollout cost
|
||||
(e.g., completion length in tokens or number of turns).
|
||||
|
||||
Correct rollouts get reward amplified by up to 2x based on relative efficiency.
|
||||
Incorrect rollouts are untouched. Lower-cost correct rollouts get higher advantage.
|
||||
"""
|
||||
max_reward = rewards.max()
|
||||
correct_mask = rewards >= max_reward
|
||||
num_correct = correct_mask.sum()
|
||||
|
||||
# No shaping when max reward is 0 — no correct rollouts to differentiate
|
||||
if max_reward <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
# Mean cost of correct rollouts
|
||||
mean_correct_cost = (costs * correct_mask).sum() / num_correct.clamp(min=1)
|
||||
|
||||
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above.
|
||||
# When mean_correct_cost is 0 (e.g. tool-only shaping with no harness metric, or
|
||||
# all-zero turn counts), no rollouts can be differentiated — fall back to no bonus.
|
||||
if mean_correct_cost <= 0:
|
||||
return rewards - rewards.mean()
|
||||
|
||||
bonus = (1 - costs / mean_correct_cost).clamp(0, 1)
|
||||
|
||||
# Shape rewards: correct rollouts amplified by up to 2x, incorrect untouched
|
||||
shaped_rewards = rewards * (1 + bonus * correct_mask)
|
||||
return shaped_rewards - shaped_rewards.mean()
|
||||
|
||||
|
||||
def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
def setup_advantage_fn(config: AdvantageConfig, max_seq_len: int | None = None) -> AdvantageFn:
|
||||
"""Setup advantage function from config."""
|
||||
if isinstance(config, CustomAdvantageConfig):
|
||||
custom_fn = import_object(config.import_path)
|
||||
@@ -123,7 +87,12 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
|
||||
return advantage_fn
|
||||
|
||||
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
|
||||
return default_advantage_fn(inputs, length_penalty=config.length_penalty)
|
||||
return default_advantage_fn(
|
||||
inputs,
|
||||
length_penalty=config.length_penalty,
|
||||
max_seq_len=max_seq_len,
|
||||
length_weighted_baseline=config.length_weighted_baseline,
|
||||
)
|
||||
|
||||
return advantage_fn
|
||||
|
||||
|
||||
@@ -11,8 +11,9 @@
|
||||
schedule next. Transitions are level-triggered (driven by the eval
|
||||
source's emptiness), so in-flight rollouts of the opposite kind drain
|
||||
naturally on either side of an eval boundary.
|
||||
- ``on_new_version`` (called by the watcher) bumps ``off_policy_steps`` on
|
||||
in-flight train rollouts and drops groups past ``max_off_policy_steps``.
|
||||
- ``on_version_pending`` (called by the watcher before the engines pause for
|
||||
the weight update) bumps ``off_policy_steps`` on in-flight train rollouts and
|
||||
drops groups past ``max_off_policy_steps``.
|
||||
Eval rollouts are measurements for the policy version they started with,
|
||||
so they are allowed to finish even if training advances.
|
||||
Cancellations surface as synthetic ``Cancelled`` markers so the sink's
|
||||
@@ -116,7 +117,7 @@ class RolloutDispatcher:
|
||||
"""``await dispatcher.start()`` runs the dispatch loop until ``stop()``.
|
||||
Pulls examples from ``TrainSource`` / ``EvalSource``, schedules
|
||||
rollouts under shared capacity, and emits ``FinishedRollout``\\ s to
|
||||
``out_q``. The watcher drives ``on_new_version`` for off-policy
|
||||
``out_q``. The watcher drives ``on_version_pending`` for off-policy
|
||||
cancellation; the orchestrator triggers eval epochs."""
|
||||
|
||||
def __init__(
|
||||
@@ -263,11 +264,16 @@ class RolloutDispatcher:
|
||||
await safe_cancel(self.task)
|
||||
self.task = None
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""Bump off-policy counters and drop groups past
|
||||
``max_off_policy_steps`` (drop_group emits ``Cancelled`` markers so
|
||||
the sink still finalizes the partial group). Eval rollouts are not
|
||||
aged because they are tied to their start-time policy version."""
|
||||
aged because they are tied to their start-time policy version.
|
||||
|
||||
Runs *before* the inference engines are paused for the weight update so
|
||||
the resulting aborts are processed while the engine is still stepping —
|
||||
otherwise the orphaned KV transfers crash the decode engine on resume
|
||||
(see ``WeightWatcher.apply_policy_update``)."""
|
||||
stale_groups: set[uuid.UUID] = set()
|
||||
cancelled = 0
|
||||
for meta in self.inflight.values():
|
||||
@@ -287,6 +293,9 @@ class RolloutDispatcher:
|
||||
"Consider increasing it to avoid this."
|
||||
)
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""No-op: the dispatcher drains in ``on_version_pending`` (pre-pause)."""
|
||||
|
||||
async def fill_inflight(self) -> None:
|
||||
"""Schedule new rollouts up to ``max_inflight``, honoring
|
||||
``self.mode``. Eval scheduling ignores the orchestrator's dispatch
|
||||
@@ -602,7 +611,7 @@ class RolloutDispatcher:
|
||||
# markers for those too so the sink hits ``target_rollouts``
|
||||
#
|
||||
# ``last_meta`` can be ``None`` if the only inflight task for this
|
||||
# group completed naturally between ``on_new_version``'s snapshot
|
||||
# group completed naturally between ``on_version_pending``'s snapshot
|
||||
# and us reaching it — synthesize a stand-in from the group state
|
||||
unscheduled_cancelled = 0
|
||||
if group is not None and group.rollouts_to_schedule > 0:
|
||||
|
||||
@@ -162,13 +162,13 @@ class Env:
|
||||
class TrainEnv(Env):
|
||||
config: TrainEnvConfig
|
||||
|
||||
def __init__(self, config: TrainEnvConfig):
|
||||
def __init__(self, config: TrainEnvConfig, max_seq_len: int):
|
||||
super().__init__(config)
|
||||
self.sampling_args = config.sampling.to_sampling_args()
|
||||
# Built once — custom advantage funcs do an ``import_object`` we don't
|
||||
# want to pay per group. ``None`` = reward-only path.
|
||||
self.advantage_fn: AdvantageFn | None = (
|
||||
setup_advantage_fn(config.advantage) if config.advantage is not None else None
|
||||
setup_advantage_fn(config.advantage, max_seq_len=max_seq_len) if config.advantage is not None else None
|
||||
)
|
||||
|
||||
def get_dataset(self, seed: int | None = None):
|
||||
@@ -246,10 +246,10 @@ class Envs(Generic[EnvT]):
|
||||
class TrainEnvs(Envs[TrainEnv]):
|
||||
"""Collection of training environments."""
|
||||
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig]):
|
||||
def __init__(self, configs: Sequence[TrainEnvConfig], max_seq_len: int):
|
||||
self._envs: dict[str, TrainEnv] = {}
|
||||
for config in configs:
|
||||
env = TrainEnv(config)
|
||||
env = TrainEnv(config, max_seq_len=max_seq_len)
|
||||
self._envs[env.name] = env
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ in ``setup()`` and drives them from ``main_loop()``.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import ctypes
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
@@ -72,6 +71,7 @@ from prime_rl.orchestrator.utils import (
|
||||
save_rollouts,
|
||||
set_default_executor,
|
||||
setup_student_inference_pool,
|
||||
trim_process_memory,
|
||||
)
|
||||
from prime_rl.orchestrator.watcher import WeightWatcher
|
||||
from prime_rl.trainer.model import setup_tokenizer
|
||||
@@ -268,7 +268,7 @@ class Orchestrator:
|
||||
post_filters = setup_filters(config.post_batch_filters, vocab_size=self.tokenizer.vocab_size, kind="post-batch")
|
||||
|
||||
get_logger().info("Loading training environments")
|
||||
self.train_envs = TrainEnvs(config.train.env)
|
||||
self.train_envs = TrainEnvs(config.train.env, max_seq_len=config.seq_len)
|
||||
if config.training_mode == "sft":
|
||||
for env in self.train_envs:
|
||||
env.sampling_args.pop("logprobs", None)
|
||||
@@ -482,10 +482,7 @@ class Orchestrator:
|
||||
get_logger().success("Orchestrator finished.")
|
||||
else:
|
||||
get_logger().warning("Orchestrator cleanup complete (forced).")
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except Exception as e:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {e}")
|
||||
trim_process_memory()
|
||||
|
||||
async def main_loop(self) -> None:
|
||||
"""Consume ``FinishedRollout``\\ s from the dispatcher and route them
|
||||
@@ -614,6 +611,7 @@ class Orchestrator:
|
||||
|
||||
await self.sender.send(TrainingBatch(examples=batch.samples, step=step))
|
||||
self.update_dispatch_gate()
|
||||
trim_process_memory()
|
||||
|
||||
metrics = self.metrics.build(
|
||||
step=step,
|
||||
@@ -876,6 +874,10 @@ class Orchestrator:
|
||||
get_logger().info("Resuming dispatcher")
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""No-op: the dispatch gate is re-evaluated in ``on_new_version`` once
|
||||
the new policy version is live."""
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
|
||||
@@ -202,7 +202,12 @@ class EvalBatch:
|
||||
|
||||
|
||||
class VersionObserver(Protocol):
|
||||
"""Notified after each policy update; walked by the watcher after it
|
||||
mutates ``Policy``."""
|
||||
"""Notified around each policy update; walked by the watcher.
|
||||
|
||||
``on_version_pending`` fires *before* the inference engines are paused for
|
||||
the weight update; ``on_new_version`` fires *after* the new weights are live
|
||||
and ``Policy`` has been mutated."""
|
||||
|
||||
async def on_version_pending(self, step: int) -> None: ...
|
||||
|
||||
async def on_new_version(self, step: int) -> None: ...
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import asyncio
|
||||
import ctypes
|
||||
import gc
|
||||
import logging
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
@@ -96,6 +98,15 @@ def set_default_executor(max_workers: int = 64) -> None:
|
||||
asyncio.get_event_loop().set_default_executor(ThreadPoolExecutor(max_workers=max_workers))
|
||||
|
||||
|
||||
def trim_process_memory() -> None:
|
||||
"""Return freed heap pages to the OS on glibc systems."""
|
||||
gc.collect()
|
||||
try:
|
||||
ctypes.CDLL("libc.so.6").malloc_trim(0)
|
||||
except Exception as exc:
|
||||
get_logger().debug(f"malloc_trim(0) failed: {exc!r}")
|
||||
|
||||
|
||||
async def compute_teacher_logprobs(
|
||||
clients: list[vf.ClientConfig],
|
||||
model_name: str,
|
||||
|
||||
@@ -92,6 +92,24 @@ class WeightWatcher:
|
||||
f"Orchestrator resumed: checkpoint {next_step} ready (after {format_time(self.last_wait_for_ckpt_time)})"
|
||||
)
|
||||
|
||||
# Drain off-policy rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
# ``_reqs_not_processed``), which is only propagated to the workers
|
||||
# while the engine is stepping. If we drain after resume instead,
|
||||
# the aborts race with the flush of KV transfers that completed
|
||||
# during the pause and trip ``assert req_id in self.requests`` in
|
||||
# the decode scheduler's ``_update_from_kv_xfer_finished`` — killing
|
||||
# the engine and cascading to every DP rank. Draining first lets the
|
||||
# aborts settle under normal stepping. ``on_new_version`` (below)
|
||||
# still runs post-update for observers that need the live version.
|
||||
for observer in self.observers:
|
||||
try:
|
||||
await observer.on_version_pending(next_step)
|
||||
except Exception as exc:
|
||||
get_logger().warning(
|
||||
f"Observer {type(observer).__name__}.on_version_pending({next_step}) raised: {exc!r}"
|
||||
)
|
||||
|
||||
get_logger().debug(f"Updating weights to step {next_step}")
|
||||
t1 = time.perf_counter()
|
||||
await self.inference.update_weights(weights_path, lora_name=self.lora_name, step=next_step)
|
||||
|
||||
@@ -8,6 +8,7 @@ import torch.nn as nn
|
||||
from torch import Tensor
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.vlm import get_final_logit_softcapping
|
||||
|
||||
FUSED_CE_IGNORE_INDEX = -100
|
||||
|
||||
@@ -299,8 +300,8 @@ def inject_prime_lm_head(
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
# Check for Gemma-style softcapping - dispatch to specialized implementation
|
||||
final_logit_softcapping = getattr(model.config, "final_logit_softcapping", None)
|
||||
# Check for Gemma-style softcapping - dispatch to specialized implementation.
|
||||
final_logit_softcapping = get_final_logit_softcapping(model.config)
|
||||
if final_logit_softcapping:
|
||||
if fused_cross_entropy == "quack":
|
||||
raise ValueError(
|
||||
|
||||
@@ -29,6 +29,7 @@ VLM_REGISTRY: dict[str, VLMModelInfo] = {
|
||||
"qwen3_5": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_5_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"qwen3_vl_moe": VLMModelInfo(vision_encoder_attr="model.visual", language_model_attr="model.language_model"),
|
||||
"gemma4": VLMModelInfo(vision_encoder_attr="model.vision_tower", language_model_attr="model.language_model"),
|
||||
}
|
||||
|
||||
# Text-only default
|
||||
@@ -86,6 +87,16 @@ def is_vlm_architecture(model_config: PretrainedConfig) -> bool:
|
||||
return _get_model_info_from_config(model_config) is not None
|
||||
|
||||
|
||||
def get_final_logit_softcapping(model_config: PretrainedConfig) -> float | None:
|
||||
"""Read ``final_logit_softcapping`` from the text config.
|
||||
|
||||
For composite VLM configs (e.g. Gemma) the value lives under ``text_config``;
|
||||
``get_text_config()`` returns that for VLMs and the config itself for text-only
|
||||
models, so a plain top-level ``getattr`` would miss it and silently drop softcapping.
|
||||
"""
|
||||
return getattr(model_config.get_text_config(), "final_logit_softcapping", None)
|
||||
|
||||
|
||||
def get_layer_prefix(model_config: PretrainedConfig, override: str | None = None) -> str:
|
||||
"""Return the weight key prefix for language model layers.
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import math
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
@@ -6,8 +5,8 @@ import pytest
|
||||
from prime_rl.configs.orchestrator import (
|
||||
CustomAdvantageConfig,
|
||||
DefaultAdvantageConfig,
|
||||
TokensLengthPenaltyConfig,
|
||||
TurnsLengthPenaltyConfig,
|
||||
LinearLengthPenaltyConfig,
|
||||
OrchestratorConfig,
|
||||
)
|
||||
from prime_rl.orchestrator.advantage import (
|
||||
AdvantageInputs,
|
||||
@@ -16,48 +15,29 @@ from prime_rl.orchestrator.advantage import (
|
||||
default_advantage_fn,
|
||||
setup_advantage_fn,
|
||||
)
|
||||
from prime_rl.orchestrator.envs import Env, TrainEnv
|
||||
from prime_rl.orchestrator.types import TrainRollout
|
||||
|
||||
|
||||
def _make_rollout(
|
||||
reward: float,
|
||||
completion_len: int = 0,
|
||||
num_turns: int = 1,
|
||||
env_name: str = "test",
|
||||
example_id: int = 0,
|
||||
) -> dict:
|
||||
"""Create a minimal rollout dict for advantage testing.
|
||||
|
||||
`completion_len` tokens are split across `num_turns` trajectory steps.
|
||||
"""
|
||||
per_turn, rem = divmod(completion_len, max(num_turns, 1))
|
||||
trajectory = [
|
||||
{"tokens": {"prompt_ids": [0], "completion_ids": list(range(per_turn + (rem if i == 0 else 0)))}}
|
||||
for i in range(num_turns)
|
||||
]
|
||||
def _make_rollout(reward: float, completion_len: int = 0) -> dict:
|
||||
"""Minimal single-turn rollout dict with ``completion_len`` completion tokens."""
|
||||
return {
|
||||
"reward": reward,
|
||||
"trajectory": trajectory,
|
||||
"env_name": env_name,
|
||||
"example_id": example_id,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(completion_len))}}],
|
||||
"env_name": "test",
|
||||
"example_id": 0,
|
||||
}
|
||||
|
||||
|
||||
def _make_group(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
|
||||
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths/turns."""
|
||||
def _make_group(rewards, completion_lengths=None) -> AdvantageInputs:
|
||||
"""Build single-group AdvantageInputs from 1D arrays of rewards/lengths."""
|
||||
rollouts = []
|
||||
for i, reward in enumerate(rewards):
|
||||
cl = int(completion_lengths[i]) if completion_lengths is not None else 0
|
||||
nt = int(num_turns[i]) if num_turns is not None else 1
|
||||
rollouts.append(_make_rollout(float(reward), cl, nt))
|
||||
rollouts.append(_make_rollout(float(reward), cl))
|
||||
return AdvantageInputs(rollouts=rollouts)
|
||||
|
||||
|
||||
# Helper aliases for readability — completion-only and tool-only token shaping.
|
||||
_TOKENS_COMPLETION = TokensLengthPenaltyConfig(completion_weight=1.0, tool_response_weight=0.0)
|
||||
_TOKENS_TOOL_ONLY = TokensLengthPenaltyConfig(completion_weight=0.0, tool_response_weight=1.0)
|
||||
|
||||
|
||||
def test_default_advantage_fn_simple_mean():
|
||||
inputs = _make_group(rewards=[1.0, 0.5, 0.8], completion_lengths=[10, 12, 8])
|
||||
result = default_advantage_fn(inputs)
|
||||
@@ -66,187 +46,141 @@ def test_default_advantage_fn_simple_mean():
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_mixed_group():
|
||||
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_linear_length_penalty_scales_by_pass_rate():
|
||||
"""Linear penalty subtracts coef * pass_rate * (completion tokens / max_seq_len), then mean-centers.
|
||||
|
||||
# mean_correct_len = (10+30+20)/3 = 20
|
||||
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
|
||||
# shaped_rewards = R * (1 + bonus * correct_mask) = [1.5, 1, 0, 1]
|
||||
# baseline = mean(shaped_rewards) = 0.875
|
||||
# A = shaped_rewards - baseline = [0.625, 0.125, -0.875, 0.125]
|
||||
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
``pass_rate`` is the group's mean reward, so a half-solved group scales the penalty by 0.5.
|
||||
"""
|
||||
rewards = [1.0, 1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
|
||||
result = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=2.0), max_seq_len=100)
|
||||
|
||||
# Zero-mean per group
|
||||
pass_rate = sum(rewards) / len(rewards) # 0.5
|
||||
penalized = [r - 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
# Zero-mean per group, and within each reward tier shorter output → higher advantage
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
# All correct rollouts have positive advantage
|
||||
for rollout, adv in zip(inputs.rollouts, result.advantages):
|
||||
if rollout["reward"] >= 1.0:
|
||||
assert adv > 0
|
||||
assert result.advantages[0] > result.advantages[1]
|
||||
assert result.advantages[2] > result.advantages[3]
|
||||
|
||||
|
||||
def test_efficiency_all_correct_group():
|
||||
"""All-correct group: zero-mean, shorter gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 1.0], completion_lengths=[10, 20, 40])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
|
||||
# mean_len = 70/3 ≈ 23.33
|
||||
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
|
||||
# shaped_rewards = [1+4/7, 1+1/7, 1] = [11/7, 8/7, 1]
|
||||
shaped = [11.0 / 7, 8.0 / 7, 1.0]
|
||||
mean_shaped = sum(shaped) / len(shaped)
|
||||
expected = [s - mean_shaped for s in shaped]
|
||||
assert result.advantages == pytest.approx(expected, abs=1e-6)
|
||||
|
||||
# Zero-mean
|
||||
assert sum(result.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
# Shortest has highest advantage
|
||||
assert result.advantages[0] > result.advantages[1] > result.advantages[2]
|
||||
def test_linear_length_penalty_zero_pass_rate_disables_penalty():
|
||||
"""A never-solved group (mean reward 0) gets no length pressure — falls back to plain GRPO."""
|
||||
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 50, 200])
|
||||
penalized = default_advantage_fn(inputs, length_penalty=LinearLengthPenaltyConfig(coef=5.0), max_seq_len=100)
|
||||
plain = default_advantage_fn(inputs)
|
||||
assert penalized.advantages == pytest.approx(plain.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_all_zero_rewards():
|
||||
"""When all rewards are 0, no length shaping — falls back to standard GRPO."""
|
||||
inputs = _make_group(rewards=[0.0, 0.0, 0.0], completion_lengths=[10, 20, 15])
|
||||
result_with = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
result_without = default_advantage_fn(inputs)
|
||||
def test_linear_length_penalty_gate_by_correctness():
|
||||
"""Gating scales each rollout's penalty by its reward, so reward-0 rollouts are untouched."""
|
||||
rewards = [1.0, 1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 20, 30, 40])
|
||||
cfg = LinearLengthPenaltyConfig(coef=2.0, gate_by_correctness=True)
|
||||
result = default_advantage_fn(inputs, length_penalty=cfg, max_seq_len=100)
|
||||
|
||||
assert result_with.advantages == pytest.approx(result_without.advantages, abs=1e-6)
|
||||
pass_rate = sum(rewards) / len(rewards) # 0.5
|
||||
penalized = [r - r * 2.0 * pass_rate * (length / 100) for r, length in zip(rewards, (10, 20, 30, 40))]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_single_correct():
|
||||
"""Single correct rollout: bonus=0 (at its own mean), same as standard GRPO."""
|
||||
inputs = _make_group(rewards=[1.0, 0.0, 0.0, 0.0], completion_lengths=[100, 50, 200, 150])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_setup_advantage_fn_threads_max_seq_len():
|
||||
"""``setup_advantage_fn`` threads ``max_seq_len`` into the linear penalty denominator."""
|
||||
rewards = [1.0, 1.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30])
|
||||
fn = setup_advantage_fn(DefaultAdvantageConfig(length_penalty=LinearLengthPenaltyConfig(coef=1.0)), max_seq_len=100)
|
||||
result = fn(inputs)
|
||||
|
||||
assert result.advantages == pytest.approx([0.75, -0.25, -0.25, -0.25], abs=1e-6)
|
||||
pass_rate = sum(rewards) / len(rewards) # 1.0
|
||||
penalized = [1.0 - 1.0 * pass_rate * (length / 100) for length in (10, 30)]
|
||||
mean = sum(penalized) / len(penalized)
|
||||
assert result.advantages == pytest.approx([p - mean for p in penalized], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_shorter_correct_higher_advantage():
|
||||
"""Among correct rollouts in a mixed group, shorter always gets higher advantage."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 1.0, 0.0, 0.0], completion_lengths=[50, 100, 200, 80, 120])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
def test_train_env_threads_max_seq_len_into_advantage_fn(monkeypatch):
|
||||
"""TrainEnv-built advantage funcs use orchestrator seq_len for length penalties."""
|
||||
|
||||
advs = result.advantages
|
||||
assert advs[0] > advs[1] > advs[2]
|
||||
assert all(a > 0 for a in advs[:3])
|
||||
assert all(a < 0 for a in advs[3:])
|
||||
def fake_env_init(self, config):
|
||||
self.config = config
|
||||
self._env = None
|
||||
self._env_client = None
|
||||
self._env_server_process = None
|
||||
|
||||
|
||||
def test_efficiency_zero_mean_per_group():
|
||||
"""Reward shaping preserves zero-mean advantages within each group."""
|
||||
mixed = default_advantage_fn(
|
||||
_make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20]),
|
||||
length_penalty=_TOKENS_COMPLETION,
|
||||
)
|
||||
all_correct = default_advantage_fn(
|
||||
_make_group(rewards=[1.0, 1.0, 1.0, 1.0], completion_lengths=[10, 20, 40, 80]),
|
||||
length_penalty=_TOKENS_COMPLETION,
|
||||
monkeypatch.setattr(Env, "__init__", fake_env_init)
|
||||
config = OrchestratorConfig(
|
||||
seq_len=100,
|
||||
advantage={"type": "default", "length_penalty": {"coef": 1.0}},
|
||||
)
|
||||
|
||||
assert sum(mixed.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
assert sum(all_correct.advantages) == pytest.approx(0.0, abs=1e-6)
|
||||
env = TrainEnv(config.train.env[0], max_seq_len=config.seq_len)
|
||||
assert env.advantage_fn is not None
|
||||
result = env.advantage_fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
|
||||
|
||||
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_amplification_bounded():
|
||||
"""Even with extreme length outliers, reward amplification is capped at 2x."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0], completion_lengths=[1, 10000, 5000])
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
|
||||
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
|
||||
# Standard reward = 1, so amplification ≈ 2x
|
||||
# shaped_rewards ≈ [2, 1, 0], baseline ≈ 1, max advantage ≈ 1
|
||||
assert result.advantages[0] < 1.0 + 1e-3
|
||||
|
||||
|
||||
def test_efficiency_tokens_with_tool_response_weight():
|
||||
"""`tool_response_weight` shifts shaping onto tool-response tokens read from rollout metrics."""
|
||||
rollouts = [
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 200},
|
||||
def test_per_env_linear_advantage_uses_runtime_schema():
|
||||
config = OrchestratorConfig(
|
||||
seq_len=100,
|
||||
train={
|
||||
"env": [
|
||||
{
|
||||
"advantage": {
|
||||
"type": "default",
|
||||
"length_penalty": {"coef": 1.0},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 0},
|
||||
},
|
||||
{
|
||||
"reward": 1.0,
|
||||
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}],
|
||||
"metrics": {"rlm_total_tool_response_tokens": 100},
|
||||
},
|
||||
]
|
||||
inputs = AdvantageInputs(rollouts=rollouts)
|
||||
|
||||
# completion tokens identical (10 each) → completion-only shaping is a no-op
|
||||
result_completion_only = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
assert result_completion_only.advantages == pytest.approx([0.0, 0.0, 0.0], abs=1e-6)
|
||||
|
||||
# tool-response only: costs are [200, 0, 100], mean=100, bonus is one-sided
|
||||
# so only the below-mean rollout (idx 1) gets amplified; the at/above-mean tie.
|
||||
result_tool_only = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
|
||||
advs = result_tool_only.advantages
|
||||
assert advs[1] > advs[0]
|
||||
assert advs[1] > advs[2]
|
||||
assert advs[0] == pytest.approx(advs[2], abs=1e-6)
|
||||
assert sum(advs) == pytest.approx(0.0, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_fractional_weight_with_int_rewards():
|
||||
"""Fractional weights must not truncate when rollout rewards are emitted as ints."""
|
||||
rollouts_int = [
|
||||
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(7))}}]},
|
||||
{"reward": 1, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(11))}}]},
|
||||
{"reward": 0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(13))}}]},
|
||||
]
|
||||
rollouts_float = [{**r, "reward": float(r["reward"])} for r in rollouts_int]
|
||||
|
||||
fractional = TokensLengthPenaltyConfig(completion_weight=0.3, tool_response_weight=0.0)
|
||||
int_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_int), length_penalty=fractional)
|
||||
float_result = default_advantage_fn(AdvantageInputs(rollouts=rollouts_float), length_penalty=fractional)
|
||||
assert int_result.advantages == pytest.approx(float_result.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_zero_costs_falls_back_to_plain_grpo():
|
||||
"""When all effective costs are zero, shaping is a no-op (no NaNs from div-by-zero)."""
|
||||
# tool-only weights but no harness metric → all costs == 0
|
||||
rollouts = [
|
||||
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
{"reward": 1.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
{"reward": 0.0, "trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(10))}}]},
|
||||
]
|
||||
inputs = AdvantageInputs(rollouts=rollouts)
|
||||
result = default_advantage_fn(inputs, length_penalty=_TOKENS_TOOL_ONLY)
|
||||
expected = default_advantage_fn(inputs) # plain GRPO
|
||||
assert not any(math.isnan(a) for a in result.advantages)
|
||||
assert result.advantages == pytest.approx(expected.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_tokens_default_weights_match_completion_when_no_metric():
|
||||
"""Default TokensLengthPenaltyConfig (1,1) reduces to completion-only when rollouts lack the metric."""
|
||||
inputs = _make_group(rewards=[1.0, 1.0, 0.0, 1.0], completion_lengths=[10, 30, 20, 20])
|
||||
result_default = default_advantage_fn(inputs, length_penalty=TokensLengthPenaltyConfig())
|
||||
result_completion = default_advantage_fn(inputs, length_penalty=_TOKENS_COMPLETION)
|
||||
assert result_default.advantages == pytest.approx(result_completion.advantages, abs=1e-6)
|
||||
|
||||
|
||||
def test_efficiency_turns_penalty():
|
||||
"""`TurnsLengthPenaltyConfig` shapes by trajectory turn count rather than token count."""
|
||||
inputs = _make_group(
|
||||
rewards=[1.0, 1.0, 0.0, 1.0],
|
||||
# token counts identical, but turns differ — turns penalty should still differentiate
|
||||
completion_lengths=[100, 100, 100, 100],
|
||||
num_turns=[1, 3, 2, 2],
|
||||
)
|
||||
result = default_advantage_fn(inputs, length_penalty=TurnsLengthPenaltyConfig())
|
||||
|
||||
# mean_correct_turns = (1+3+2)/3 = 2
|
||||
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
|
||||
assert result.advantages == pytest.approx([0.625, 0.125, -0.875, 0.125], abs=1e-6)
|
||||
advantage = config.train.env[0].advantage
|
||||
assert isinstance(advantage, DefaultAdvantageConfig)
|
||||
assert isinstance(advantage.length_penalty, LinearLengthPenaltyConfig)
|
||||
|
||||
fn = setup_advantage_fn(advantage, max_seq_len=config.seq_len)
|
||||
result = fn(_make_group(rewards=[1.0, 1.0], completion_lengths=[10, 30]))
|
||||
|
||||
assert result.advantages == pytest.approx([0.1, -0.1], abs=1e-6)
|
||||
|
||||
|
||||
def test_per_env_custom_advantage_uses_runtime_schema():
|
||||
config = OrchestratorConfig(
|
||||
train={
|
||||
"env": [
|
||||
{
|
||||
"advantage": {
|
||||
"type": "custom",
|
||||
"import_path": "tests.unit.orchestrator.test_advantage._dummy_custom_advantage",
|
||||
"kwargs": {"scale": 3.0},
|
||||
},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
advantage = config.train.env[0].advantage
|
||||
assert isinstance(advantage, CustomAdvantageConfig)
|
||||
|
||||
fn = setup_advantage_fn(advantage)
|
||||
result = fn(_make_group(rewards=[1.0, 0.5], completion_lengths=[10, 20]))
|
||||
|
||||
assert result.advantages == pytest.approx([3.0, 1.5], abs=1e-6)
|
||||
|
||||
|
||||
def test_length_weighted_baseline():
|
||||
"""Length-weighted baseline uses sum(len_i * reward_i) / sum(len_i) instead of the plain mean."""
|
||||
rewards = [1.0, 0.0, 0.0]
|
||||
inputs = _make_group(rewards=rewards, completion_lengths=[10, 30, 60])
|
||||
result = default_advantage_fn(inputs, length_weighted_baseline=True)
|
||||
|
||||
baseline = (10 * 1.0 + 30 * 0.0 + 60 * 0.0) / (10 + 30 + 60) # 0.1
|
||||
assert result.advantages == pytest.approx([r - baseline for r in rewards], abs=1e-6)
|
||||
# Token-weighted mean of advantages is zero
|
||||
assert sum(length * adv for length, adv in zip((10, 30, 60), result.advantages)) == pytest.approx(0.0, abs=1e-5)
|
||||
|
||||
|
||||
def _train_rollouts(rewards: list[float]) -> list[TrainRollout]:
|
||||
|
||||
@@ -11,7 +11,7 @@ supported-markers = [
|
||||
]
|
||||
|
||||
[options]
|
||||
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
|
||||
exclude-newer = "2026-06-10T23:37:49.383138959Z"
|
||||
exclude-newer-span = "P7D"
|
||||
|
||||
[options.exclude-newer-package]
|
||||
@@ -4016,6 +4016,7 @@ envs = [
|
||||
{ name = "reverse-text", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "rlm-search", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "rlm-swe", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "rlm-uuid-ctf", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "science-env", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "simpleqa-verified", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "tau2-bench", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
@@ -4118,6 +4119,7 @@ requires-dist = [
|
||||
{ name = "ring-flash-attn", specifier = ">=0.1.8" },
|
||||
{ name = "rlm-search", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_search" },
|
||||
{ name = "rlm-swe", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_swe" },
|
||||
{ name = "rlm-uuid-ctf", marker = "extra == 'envs'", editable = "deps/research-environments/environments/rlm_uuid_ctf" },
|
||||
{ name = "science-env", marker = "extra == 'envs'", editable = "deps/research-environments/environments/science_env" },
|
||||
{ name = "setproctitle", specifier = ">=1.3.0" },
|
||||
{ name = "simpleqa-verified", marker = "extra == 'envs'", editable = "deps/research-environments/environments/simpleqa_verified" },
|
||||
@@ -4964,6 +4966,23 @@ requires-dist = [
|
||||
{ name = "verifiers", extras = ["packages"], specifier = ">=0.1.15.dev17,<0.1.15.dev156" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rlm-uuid-ctf"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/research-environments/environments/rlm_uuid_ctf" }
|
||||
dependencies = [
|
||||
{ name = "datasets", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "prime-sandboxes", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
{ name = "verifiers", extra = ["packages"], marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "datasets", specifier = ">=4.0.0" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.21" },
|
||||
{ name = "verifiers", extras = ["packages"], specifier = ">=0.1.15.dev17" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rpds-py"
|
||||
version = "0.30.0"
|
||||
|
||||
Reference in New Issue
Block a user