Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ff21d97e7 | ||
|
|
5e6f7ebae8 | ||
|
|
7d7bd92333 |
@@ -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,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)
|
||||
|
||||
@@ -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)
|
||||
```
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -53,6 +53,7 @@ from prime_rl.trainer.weights import (
|
||||
)
|
||||
from prime_rl.trainer.world import get_world
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
|
||||
@@ -275,9 +276,7 @@ def _patch_qwen3_5_linear_attn_varlen():
|
||||
pids = position_ids
|
||||
if pids.ndim == 3:
|
||||
pids = pids[0]
|
||||
flat = pids.view(-1)
|
||||
seqlens = torch.cat([flat[0:1], flat[:-1][(flat == 0)[1:]] + 1, flat[-1:] + 1])
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, _ = get_cu_seqlens_from_position_ids(pids)
|
||||
kwargs["cu_seqlens"] = cu_seqlens
|
||||
return _text_orig(
|
||||
self,
|
||||
|
||||
@@ -28,6 +28,7 @@ from prime_rl.trainer.models.layers.rotary_emb import (
|
||||
RotaryEmbeddingConfig,
|
||||
apply_rotary_pos_emb,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
try:
|
||||
from flash_attn import flash_attn_varlen_func
|
||||
@@ -489,16 +490,7 @@ class AfmoeModel(AfmoePreTrainedModel):
|
||||
use_flash = self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4")
|
||||
|
||||
if use_flash:
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
causal_mask_mapping = None
|
||||
else:
|
||||
|
||||
@@ -39,6 +39,7 @@ from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.moe import MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
class Glm4MoeDecoderLayer(GradientCheckpointingLayer):
|
||||
@@ -215,16 +216,7 @@ class Glm4MoeModel(Glm4MoePreTrainedModel):
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -40,6 +40,7 @@ from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.mlp import MLP, MLPConfig
|
||||
from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -188,16 +189,7 @@ class LlamaModel(LlamaPreTrainedModel):
|
||||
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -22,6 +22,7 @@ from prime_rl.trainer.models.minimax_m2.converting_minimax_m2 import (
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -176,16 +177,7 @@ class MiniMaxM2Model(MiniMaxM2PreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -30,6 +30,7 @@ from prime_rl.trainer.models.nemotron_h.converting_nemotron_h import (
|
||||
convert_prime_layer_to_hf,
|
||||
convert_prime_to_hf,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -505,16 +506,7 @@ class NemotronHModel(NemotronHPreTrainedModel):
|
||||
|
||||
# Compute cu_seqlens and max_seqlen for flash attention
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -18,6 +18,7 @@ from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
|
||||
from prime_rl.trainer.models.layers.lm_head import PrimeLmOutput
|
||||
from prime_rl.trainer.models.layers.moe import FeedForward, MoE, MoEArgs
|
||||
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig, apply_rotary_pos_emb
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
from .configuration_qwen3_5_moe import Qwen3_5MoeConfig
|
||||
from .converting_qwen3_5_moe import (
|
||||
@@ -763,16 +764,7 @@ class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -40,6 +40,7 @@ from prime_rl.trainer.models.qwen3_moe.converting_qwen3_moe import (
|
||||
convert_tt_layer_to_hf,
|
||||
convert_tt_to_hf_moe,
|
||||
)
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
@@ -216,16 +217,7 @@ class Qwen3MoeModel(Qwen3MoePreTrainedModel):
|
||||
inputs_embeds = self.embed_tokens(input_ids)
|
||||
|
||||
if self.config._attn_implementation in ("flash_attention_2", "flash_attention_3", "fa4"):
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
max_seqlen = seqlens.max().item()
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
torch._dynamo.mark_dynamic(cu_seqlens, 0)
|
||||
else:
|
||||
max_seqlen = None
|
||||
|
||||
@@ -6,6 +6,8 @@ import torch.distributed.nn as dist_nn
|
||||
import torch.nn as nn
|
||||
from ring_flash_attn import update_ring_flash_attn_params
|
||||
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
def setup_hybrid_cp(model: nn.Module, cp_group: dist.ProcessGroup, cp_rank: int, cp_world_size: int) -> None:
|
||||
"""Configure DeltaNet modules in Qwen3.5 hybrid models for native fla CP."""
|
||||
@@ -139,15 +141,7 @@ def get_padding_logit_from_prev_cp_rank(
|
||||
|
||||
|
||||
def _get_cu_seqlens_for_cp(position_ids: torch.Tensor) -> torch.Tensor:
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
seqlens = torch.cat(
|
||||
[
|
||||
flat_position_ids[0:1],
|
||||
flat_position_ids[:-1][(flat_position_ids == 0)[1:]] + 1,
|
||||
flat_position_ids[-1:] + 1,
|
||||
]
|
||||
)
|
||||
cu_seqlens = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
cu_seqlens, _ = get_cu_seqlens_from_position_ids(position_ids)
|
||||
return cu_seqlens
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def get_cu_seqlens_from_position_ids(position_ids: torch.Tensor) -> tuple[torch.Tensor, int]:
|
||||
"""Build local-relative cumulative sequence lengths from packed position ids.
|
||||
|
||||
``position_ids`` may be a full packed sequence or a context-parallel local shard.
|
||||
In the shard case, the first local token can be a continuation with a non-zero
|
||||
position id, so cumulative offsets must be anchored to the local tensor rather
|
||||
than to the absolute position id value.
|
||||
"""
|
||||
flat_position_ids = position_ids.view(-1)
|
||||
total_tokens = flat_position_ids.numel()
|
||||
assert total_tokens > 0, "Cannot build cu_seqlens for an empty position_ids tensor"
|
||||
|
||||
zero_starts = (flat_position_ids == 0).nonzero(as_tuple=True)[0]
|
||||
starts = torch.cat(
|
||||
[torch.zeros(1, dtype=zero_starts.dtype, device=zero_starts.device), zero_starts]
|
||||
).unique_consecutive()
|
||||
|
||||
ends = torch.cat(
|
||||
[
|
||||
starts[1:],
|
||||
torch.tensor([total_tokens], dtype=starts.dtype, device=starts.device),
|
||||
]
|
||||
)
|
||||
seqlens = ends - starts
|
||||
|
||||
cu_seqlens = torch.empty(seqlens.numel() + 1, dtype=torch.int32, device=position_ids.device)
|
||||
cu_seqlens[0] = 0
|
||||
cu_seqlens[1:] = seqlens.cumsum(dim=0, dtype=torch.int32)
|
||||
|
||||
return cu_seqlens, seqlens.max().item()
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from prime_rl.utils.sequence import get_cu_seqlens_from_position_ids
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("position_ids", "expected_cu_seqlens", "expected_max_seqlen"),
|
||||
[
|
||||
(torch.arange(8).unsqueeze(0), [0, 8], 8),
|
||||
(torch.arange(8, 16).unsqueeze(0), [0, 8], 8),
|
||||
(torch.tensor([[0, 1, 2, 3, 0, 1, 2]]), [0, 4, 7], 4),
|
||||
(torch.tensor([[5, 6, 7, 0, 1, 2]]), [0, 3, 6], 3),
|
||||
],
|
||||
)
|
||||
def test_get_cu_seqlens_from_position_ids_is_local_relative(
|
||||
position_ids: torch.Tensor,
|
||||
expected_cu_seqlens: list[int],
|
||||
expected_max_seqlen: int,
|
||||
) -> None:
|
||||
cu_seqlens, max_seqlen = get_cu_seqlens_from_position_ids(position_ids)
|
||||
|
||||
assert cu_seqlens.dtype == torch.int32
|
||||
assert cu_seqlens.tolist() == expected_cu_seqlens
|
||||
assert max_seqlen == expected_max_seqlen
|
||||
Reference in New Issue
Block a user