Compare commits

..
Author SHA1 Message Date
samsjaandGitHub 2ff21d97e7 chore(agents): forbid editing .venv/ (#2400)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(skills): add dotvenv skill warning against editing .venv/

* feat(agents): forbid editing .venv in AGENTS.md instead of skill

Replaces the dotvenv skill with a one-line rule under 'Running code'
in AGENTS.md, since AGENTS.md is always loaded and a 'never do X' rule
fits better there than as an on-demand skill.
2026-05-02 18:36:19 -07:00
5e6f7ebae8 feat(advantage): add num_turns option to efficiency shaping (#2384)
Release / Push CUDA image to Docker (push) Canceled after 0s
* feat(advantage): add num_turns option to efficiency shaping

Replaces `length_shaping: bool` with `shaping_metric: Literal["length", "num_turns"] | None`
so the same correctness-gated efficiency shaping can score rollouts by trajectory
turn count instead of completion-token count. Generalizes the helper to operate
on a per-rollout cost tensor; both metrics are plumbed through `AdvantageInputs`.

* fix(advantage): remove extra blank line for ruff I001

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(advantage): rename shaping_metric -> length_penalty

Per review feedback, use clearer name and shorter literal values:
shaping_metric: Literal["length", "num_turns"] -> length_penalty: Literal["tokens", "turns"]

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(advantage): pass full rollouts through AdvantageInputs

AdvantageInputs now holds list[list[vf.RolloutOutput]] grouped by problem
instead of separate rewards/completion_lengths/num_turns tensors. Custom
advantage fns can read any rollout metadata; inputs.rewards is kept as a
convenience property for the common case.

Per @mikasenghaas review.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(advantage): drop AdvantageInputs.rewards convenience property

Per @samsja review: with rollouts as the single source of truth, the
rewards property was a partial holdover. Custom advantages now extract
rewards directly from rollouts, matching how all other metadata is read.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(advantage): regression test for per-problem advantage isolation

Two-problem case with very different reward scales — catches cross-group
leakage, slicing/transpose bugs, and out-of-order assignment in the
flat -> grouped -> flat round-trip through compute_advantages.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 16:06:31 -07:00
7 changed files with 180 additions and 107 deletions
+1
View File
@@ -32,6 +32,7 @@ Namespaces are one honking great idea -- let's do more of those!
- **Always use uv**: run code with `uv run` or `uv run <command>`, never raw `python`.
- **Adding dependencies**: add to `pyproject.toml` and run `uv sync --all-extras` to install and lock them.
- **Git dependency pins**: when pinning git dependencies in `pyproject.toml`, always use a small (7-char) commit hash for the `rev` field.
- **Never edit `.venv/`**: the local virtual env is read-only. Edits there are silently overwritten by the next `uv sync` and don't propagate to teammates or CI. Reading files under `.venv/` to understand library behavior is fine; writing is not. To fix a dependency issue, update `pyproject.toml` (pin a fork via 7-char commit hash if needed), vendor the code into `src/`, or patch upstream.
## Skills
+2
View File
@@ -2,6 +2,8 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`orchestrator.advantage.length_shaping` → `orchestrator.advantage.length_penalty`**: The boolean `length_shaping` flag has been replaced by `length_penalty: Literal["tokens", "turns"] | None` (default: `None`). `length_shaping = true` becomes `length_penalty = "tokens"`; `length_shaping = false` becomes `length_penalty = None`. The new `"turns"` option applies the same correctness-gated efficiency shaping using trajectory turn count instead of completion-token count. (2026-05-01)
- **`AdvantageInputs` API**: Replaced the `rewards`/`completion_lengths`/`num_turns` tensor fields with a single `rollouts: list[list[vf.RolloutOutput]]` (grouped by problem). Custom advantage functions can now access any rollout metadata. Existing custom advantages must update their signatures and extract per-rollout fields directly (e.g. `torch.tensor([[r["reward"] for r in g] for g in inputs.rollouts])`). (2026-05-01)
- **`orchestrator.teacher_rollout_model` now requires `orchestrator.use_sft_loss = true`**: External teacher rollout configs no longer rely on `trainer.loss.type = "sft"` to select SFT loss. Existing hard-distill configs must set `orchestrator.use_sft_loss = true` alongside `orchestrator.teacher_rollout_model`; the orchestrator validates the pair and stamps training samples with the per-batch SFT loss bool. (2026-04-26)
- **`model.attn = "eager"` (NEW option)**: Added `eager` as a valid value for the `model.attn` field. Required for GPT-OSS models on non-Hopper GPUs, since the only flash attention kernel GPT-OSS supports (`kernels-community/vllm-flash-attn3`) is Hopper-only. A clear error message is raised at model load time if GPT-OSS is used without `eager` on unsupported hardware. Also added `kernels` as a core dependency. (2026-04-05)
- **`[[orchestrator.env]]` → `[[orchestrator.train.env]]`**: Training environments and sampling are now configured under `[orchestrator.train]`. The old `[[orchestrator.env]]` and `[orchestrator.sampling]` paths are auto-translated with a deprecation warning and will be removed in a future release. (2026-04-09)
+8 -5
View File
@@ -86,10 +86,12 @@ def my_custom_advantage(inputs: AdvantageInputs, **kwargs) -> AdvantageOutputs:
```python
@dataclass
class AdvantageInputs:
rewards: Float[Tensor, "num_examples rollouts_per_example"]
completion_lengths: Int[Tensor, "num_examples rollouts_per_example"]
# Rollouts grouped by problem: rollouts[i][j] is the j-th rollout for problem i.
rollouts: list[list[vf.RolloutOutput]]
```
Each `vf.RolloutOutput` carries the full rollout (`reward`, `trajectory`, etc.), so custom advantages can read any metadata they need (e.g. completion-token counts, turn counts, tool calls).
#### AdvantageOutputs
```python
@@ -106,9 +108,10 @@ from prime_rl.orchestrator.advantage import AdvantageInputs, AdvantageOutputs
def normalized_advantage(inputs: AdvantageInputs, eps: float = 1e-8) -> AdvantageOutputs:
"""Normalize advantages to zero mean and unit variance per example."""
mean = inputs.rewards.mean(dim=1, keepdim=True)
std = inputs.rewards.std(dim=1, keepdim=True)
advantages = (inputs.rewards - mean) / (std + eps)
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
mean = rewards.mean(dim=1, keepdim=True)
std = rewards.std(dim=1, keepdim=True)
advantages = (rewards - mean) / (std + eps)
return AdvantageOutputs(advantages=advantages)
```
+8 -6
View File
@@ -691,16 +691,18 @@ class DefaultAdvantageConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
type: Literal["default"] = "default"
length_shaping: Annotated[
bool,
length_penalty: Annotated[
Literal["tokens", "turns"] | None,
Field(
description=(
"Enable correctness-gated length shaping. In mixed groups, shorter correct rollouts get "
"amplified advantage (up to 2x), longer correct rollouts are unchanged, incorrect untouched. "
"In all-correct groups, below-average-length rollouts get advantage in [0, 1], others get 0."
"Cost metric for correctness-gated length penalty. `tokens` shapes by completion-token "
"count, `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."
)
),
] = False
] = None
class CustomAdvantageConfig(BaseModel):
+41 -30
View File
@@ -1,22 +1,27 @@
from dataclasses import dataclass
from typing import Callable
from typing import Callable, Literal
import torch
import verifiers as vf
from jaxtyping import Float, Int
from jaxtyping import Float
from torch import Tensor
from prime_rl.configs.orchestrator import AdvantageConfig, CustomAdvantageConfig
from prime_rl.orchestrator.vf_utils import get_model_completion_len
from prime_rl.orchestrator.vf_utils import get_model_completion_len, get_num_turns
from prime_rl.utils.utils import import_object
LengthPenalty = Literal["tokens", "turns"]
@dataclass
class AdvantageInputs:
"""Inputs for advantage computation."""
"""Inputs for advantage computation.
rewards: Float[Tensor, "num_problems rollouts_per_example"]
completion_lengths: Int[Tensor, "num_problems rollouts_per_example"]
`rollouts` is grouped by problem: `rollouts[i][j]` is the j-th rollout for problem i,
so `len(rollouts) == num_problems` and `len(rollouts[0]) == rollouts_per_example`.
"""
rollouts: list[list[vf.RolloutOutput]]
@dataclass
@@ -37,30 +42,40 @@ Expected signature:
def default_advantage_fn(
inputs: AdvantageInputs,
length_shaping: bool = False,
length_penalty: LengthPenalty | None = None,
) -> AdvantageOutputs:
"""Default GRPO advantage: reward minus per-problem baseline."""
rewards = inputs.rewards
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
if length_shaping:
completion_lengths = inputs.completion_lengths.to(dtype=rewards.dtype)
return AdvantageOutputs(advantages=_efficiency_length_shaping(rewards, completion_lengths))
if length_penalty == "tokens":
costs = torch.tensor(
[[get_model_completion_len(r) for r in group] for group in inputs.rollouts],
dtype=rewards.dtype,
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
if length_penalty == "turns":
costs = torch.tensor(
[[get_num_turns(r) for r in group] for group in inputs.rollouts],
dtype=rewards.dtype,
)
return AdvantageOutputs(advantages=_efficiency_shaping(rewards, costs))
baseline = rewards.mean(dim=1, keepdim=True)
return AdvantageOutputs(advantages=rewards - baseline)
def _efficiency_length_shaping(
def _efficiency_shaping(
rewards: Float[Tensor, "num_problems rollouts_per_example"],
completion_lengths: Float[Tensor, "num_problems rollouts_per_example"],
costs: Float[Tensor, "num_problems rollouts_per_example"],
) -> Float[Tensor, "num_problems rollouts_per_example"]:
"""Correctness-gated length shaping with bounded advantages.
"""Correctness-gated efficiency shaping with bounded advantages.
Shapes rewards with a bounded brevity bonus before standard GRPO subtraction,
preserving zero-mean advantages per group.
Shapes rewards with a bounded efficiency bonus before standard GRPO subtraction,
preserving zero-mean advantages per 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 brevity.
Incorrect rollouts are untouched. Shorter correct rollouts get higher advantage.
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(dim=1, keepdim=True).values
correct_mask = rewards >= max_reward
@@ -69,12 +84,12 @@ def _efficiency_length_shaping(
# No shaping when max reward is 0 — no correct rollouts to differentiate
has_correct = max_reward > 0
# Mean length of correct rollouts per problem
correct_lengths = completion_lengths * correct_mask
mean_correct_len = correct_lengths.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
# Mean cost of correct rollouts per problem
correct_costs = costs * correct_mask
mean_correct_cost = correct_costs.sum(dim=1, keepdim=True) / num_correct.clamp(min=1)
# Bounded brevity bonus: [0, 1], positive for below-average length, zero for above
bonus = (1 - completion_lengths / mean_correct_len).clamp(0, 1)
# Bounded efficiency bonus: [0, 1], positive for below-average cost, zero for above
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)
@@ -99,7 +114,7 @@ def setup_advantage_fn(config: AdvantageConfig) -> AdvantageFn:
def advantage_fn(inputs: AdvantageInputs) -> AdvantageOutputs:
return default_advantage_fn(
inputs,
length_shaping=config.length_shaping,
length_penalty=config.length_penalty,
)
return advantage_fn
@@ -127,12 +142,8 @@ def compute_advantages(
return
advantage_fn = setup_advantage_fn(advantage_config)
completion_lengths = [get_model_completion_len(r) for r in rollouts]
inputs = AdvantageInputs(
rewards=torch.tensor(rewards).view(-1, samples_per_problem),
completion_lengths=torch.tensor(completion_lengths).view(-1, samples_per_problem),
)
grouped = [rollouts[i : i + samples_per_problem] for i in range(0, len(rollouts), samples_per_problem)]
inputs = AdvantageInputs(rollouts=grouped)
result = advantage_fn(inputs)
advantages = result.advantages.flatten().tolist()
+5
View File
@@ -59,6 +59,11 @@ def get_model_completion_len(output: vf.RolloutOutput) -> int:
return sum(len(step["tokens"]["completion_ids"]) for step in output["trajectory"] if step.get("tokens"))
def get_num_turns(output: vf.RolloutOutput) -> int:
"""Number of turns (trajectory steps) in a rollout."""
return len(output["trajectory"])
def save_rollouts(rollouts: list[vf.RolloutOutput], path: Path, exclude_keys: set[str] | None = None) -> None:
"""Save rollouts to a JSONL file using verifiers serialization."""
path.parent.mkdir(parents=True, exist_ok=True)
+115 -66
View File
@@ -10,10 +10,38 @@ from prime_rl.orchestrator.advantage import (
)
def _make_rollout(reward: float, completion_len: int = 0, num_turns: int = 1) -> 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)
]
return {"reward": reward, "trajectory": trajectory}
def _make_inputs(rewards, completion_lengths=None, num_turns=None) -> AdvantageInputs:
"""Build AdvantageInputs from 2D arrays of rewards/lengths/turns."""
rewards_t = torch.as_tensor(rewards, dtype=torch.float32)
num_problems, rollouts_per_example = rewards_t.shape
rollouts = []
for i in range(num_problems):
group = []
for j in range(rollouts_per_example):
cl = int(completion_lengths[i][j]) if completion_lengths is not None else 0
nt = int(num_turns[i][j]) if num_turns is not None else 1
group.append(_make_rollout(float(rewards_t[i, j]), cl, nt))
rollouts.append(group)
return AdvantageInputs(rollouts=rollouts)
def test_default_advantage_fn_simple_mean():
inputs = AdvantageInputs(
rewards=torch.tensor([[1.0, 0.5, 0.8], [0.2, 0.9, 0.1]]),
completion_lengths=torch.tensor([[10, 12, 8], [15, 11, 9]]),
inputs = _make_inputs(
rewards=[[1.0, 0.5, 0.8], [0.2, 0.9, 0.1]],
completion_lengths=[[10, 12, 8], [15, 11, 9]],
)
result = default_advantage_fn(inputs)
@@ -24,11 +52,11 @@ def test_default_advantage_fn_simple_mean():
def test_efficiency_mixed_group():
"""Mixed group: reward shaping preserves zero-mean, shorter correct gets higher advantage."""
inputs = AdvantageInputs(
rewards=torch.tensor([[1.0, 1.0, 0.0, 1.0]]),
completion_lengths=torch.tensor([[10, 30, 20, 20]]),
inputs = _make_inputs(
rewards=[[1.0, 1.0, 0.0, 1.0]],
completion_lengths=[[10, 30, 20, 20]],
)
result = default_advantage_fn(inputs, length_shaping=True)
result = default_advantage_fn(inputs, length_penalty="tokens")
# mean_correct_len = (10+30+20)/3 = 20
# bonus = clamp(1 - [10,30,20,20]/20, 0, 1) = [0.5, 0, 0, 0]
@@ -42,17 +70,18 @@ def test_efficiency_mixed_group():
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(1), atol=1e-6)
# All correct rollouts have positive advantage
correct_mask = inputs.rewards[0] >= 1.0
rewards = torch.tensor([r["reward"] for r in inputs.rollouts[0]])
correct_mask = rewards >= 1.0
assert (result.advantages[0][correct_mask] > 0).all()
def test_efficiency_all_correct_group():
"""All-correct group: zero-mean, shorter gets higher advantage."""
inputs = AdvantageInputs(
rewards=torch.tensor([[1.0, 1.0, 1.0]]),
completion_lengths=torch.tensor([[10, 20, 40]]),
inputs = _make_inputs(
rewards=[[1.0, 1.0, 1.0]],
completion_lengths=[[10, 20, 40]],
)
result = default_advantage_fn(inputs, length_shaping=True)
result = default_advantage_fn(inputs, length_penalty="tokens")
# mean_len = 70/3 ≈ 23.33
# bonus = clamp(1 - [10, 20, 40] / (70/3), 0, 1) = [4/7, 1/7, 0]
@@ -73,11 +102,11 @@ def test_efficiency_all_correct_group():
def test_efficiency_all_zero_rewards():
"""When all rewards are 0, no length shaping — falls back to standard GRPO."""
inputs = AdvantageInputs(
rewards=torch.tensor([[0.0, 0.0, 0.0]]),
completion_lengths=torch.tensor([[10, 20, 15]]),
inputs = _make_inputs(
rewards=[[0.0, 0.0, 0.0]],
completion_lengths=[[10, 20, 15]],
)
result_with = default_advantage_fn(inputs, length_shaping=True)
result_with = default_advantage_fn(inputs, length_penalty="tokens")
result_without = default_advantage_fn(inputs)
assert torch.allclose(result_with.advantages, result_without.advantages, atol=1e-6)
@@ -85,11 +114,11 @@ def test_efficiency_all_zero_rewards():
def test_efficiency_single_correct():
"""Single correct rollout: bonus=0 (at its own mean), same as standard GRPO."""
inputs = AdvantageInputs(
rewards=torch.tensor([[1.0, 0.0, 0.0, 0.0]]),
completion_lengths=torch.tensor([[100, 50, 200, 150]]),
inputs = _make_inputs(
rewards=[[1.0, 0.0, 0.0, 0.0]],
completion_lengths=[[100, 50, 200, 150]],
)
result = default_advantage_fn(inputs, length_shaping=True)
result = default_advantage_fn(inputs, length_penalty="tokens")
expected = torch.tensor([[0.75, -0.25, -0.25, -0.25]])
assert torch.allclose(result.advantages, expected, atol=1e-6)
@@ -97,11 +126,11 @@ def test_efficiency_single_correct():
def test_efficiency_shorter_correct_higher_advantage():
"""Among correct rollouts in a mixed group, shorter always gets higher advantage."""
inputs = AdvantageInputs(
rewards=torch.tensor([[1.0, 1.0, 1.0, 0.0, 0.0]]),
completion_lengths=torch.tensor([[50, 100, 200, 80, 120]]),
inputs = _make_inputs(
rewards=[[1.0, 1.0, 1.0, 0.0, 0.0]],
completion_lengths=[[50, 100, 200, 80, 120]],
)
result = default_advantage_fn(inputs, length_shaping=True)
result = default_advantage_fn(inputs, length_penalty="tokens")
advs = result.advantages[0]
assert advs[0] > advs[1] > advs[2]
@@ -111,32 +140,28 @@ def test_efficiency_shorter_correct_higher_advantage():
def test_efficiency_zero_mean_per_group():
"""Reward shaping preserves zero-mean advantages per group."""
inputs = AdvantageInputs(
rewards=torch.tensor(
[
[1.0, 1.0, 0.0, 1.0], # mixed
[1.0, 1.0, 1.0, 1.0], # all correct
]
),
completion_lengths=torch.tensor(
[
[10, 30, 20, 20],
[10, 20, 40, 80],
]
),
inputs = _make_inputs(
rewards=[
[1.0, 1.0, 0.0, 1.0], # mixed
[1.0, 1.0, 1.0, 1.0], # all correct
],
completion_lengths=[
[10, 30, 20, 20],
[10, 20, 40, 80],
],
)
result = default_advantage_fn(inputs, length_shaping=True)
result = default_advantage_fn(inputs, length_penalty="tokens")
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
def test_efficiency_amplification_bounded():
"""Even with extreme length outliers, reward amplification is capped at 2x."""
inputs = AdvantageInputs(
rewards=torch.tensor([[1.0, 1.0, 0.0]]),
completion_lengths=torch.tensor([[1, 10000, 5000]]),
inputs = _make_inputs(
rewards=[[1.0, 1.0, 0.0]],
completion_lengths=[[1, 10000, 5000]],
)
result = default_advantage_fn(inputs, length_shaping=True)
result = default_advantage_fn(inputs, length_penalty="tokens")
# Shortest correct gets bonus ≈ 1, so shaped_reward ≈ 2
# Standard reward = 1, so amplification ≈ 2x
@@ -146,21 +171,17 @@ def test_efficiency_amplification_bounded():
def test_efficiency_multiple_problems():
"""Handles multiple problems independently."""
inputs = AdvantageInputs(
rewards=torch.tensor(
[
[1.0, 1.0, 0.0], # mixed
[1.0, 1.0, 1.0], # all correct
]
),
completion_lengths=torch.tensor(
[
[10, 20, 15],
[10, 20, 40],
]
),
inputs = _make_inputs(
rewards=[
[1.0, 1.0, 0.0], # mixed
[1.0, 1.0, 1.0], # all correct
],
completion_lengths=[
[10, 20, 15],
[10, 20, 40],
],
)
result = default_advantage_fn(inputs, length_shaping=True)
result = default_advantage_fn(inputs, length_penalty="tokens")
# Row 0: mixed group — shorter correct > longer correct
assert result.advantages[0, 0] > result.advantages[0, 1]
@@ -174,12 +195,20 @@ def test_efficiency_multiple_problems():
assert torch.allclose(result.advantages.mean(dim=1), torch.zeros(2), atol=1e-6)
def _make_rollout(reward: float, completion_len: int) -> dict:
"""Create a minimal rollout dict for advantage testing."""
return {
"reward": reward,
"trajectory": [{"tokens": {"prompt_ids": [0], "completion_ids": list(range(completion_len))}}],
}
def test_efficiency_turns_penalty():
"""`length_penalty='turns'` shapes by trajectory turn count rather than token count."""
inputs = _make_inputs(
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="turns")
# mean_correct_turns = (1+3+2)/3 = 2
# bonus = clamp(1 - [1,3,2,2]/2, 0, 1) = [0.5, 0, 0, 0]
expected = torch.tensor([[0.625, 0.125, -0.875, 0.125]])
assert torch.allclose(result.advantages, expected, atol=1e-6)
def test_compute_advantages_with_config():
@@ -195,6 +224,25 @@ def test_compute_advantages_with_config():
assert abs(sum(advantages[3:])) < 1e-5
def test_compute_advantages_no_cross_group_leakage():
"""Per-problem grouping: each problem must be centered against its own mean, in-order.
Two problems with very different reward scales — cross-group leakage would pull the
small-scale group's advantages toward the large-scale group's mean (and vice versa).
Distinct positional values also catch slicing/transpose bugs in the flat→grouped→flat
round-trip.
"""
rewards = [10.0, 20.0, 30.0, 0.0, 0.1, 0.2]
rollouts = [_make_rollout(r) for r in rewards]
compute_advantages(rollouts, samples_per_problem=3, advantage_config=DefaultAdvantageConfig())
advantages = [r["advantage"] for r in rollouts]
expected = [-10.0, 0.0, 10.0, -0.1, 0.0, 0.1]
for got, want in zip(advantages, expected):
assert abs(got - want) < 1e-5, (advantages, expected)
def test_compute_advantages_without_config():
rewards = [1.0, 0.5, 0.8]
lengths = [10, 12, 8]
@@ -213,9 +261,9 @@ def test_setup_advantage_fn_with_custom_config():
)
advantage_fn = setup_advantage_fn(config)
inputs = AdvantageInputs(
rewards=torch.tensor([[1.0, 0.5, 0.8]]),
completion_lengths=torch.tensor([[10, 12, 8]]),
inputs = _make_inputs(
rewards=[[1.0, 0.5, 0.8]],
completion_lengths=[[10, 12, 8]],
)
result = advantage_fn(inputs)
@@ -225,4 +273,5 @@ def test_setup_advantage_fn_with_custom_config():
def _dummy_custom_advantage(inputs: AdvantageInputs, scale: float = 1.0) -> AdvantageOutputs:
"""A simple custom advantage for testing."""
return AdvantageOutputs(advantages=inputs.rewards * scale)
rewards = torch.tensor([[r["reward"] for r in group] for group in inputs.rollouts])
return AdvantageOutputs(advantages=rewards * scale)