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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/examples/infra-features/score-centering.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions examples/infra_features/score_centering/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Add these arguments to an existing text-only GRPO training recipe:
--calculate-per-token-loss
```

For session-server rollouts using more than 20 candidates, also set `--use-miles-router`.
Unfiltered session-server rollouts with more than 20 candidates, and filtered rollouts, need a compatible SGLang router build; see [Rollout and data contract](#rollout-and-data-contract).

Keep reward mean subtraction enabled. Disabling standard-deviation normalization gives the paper's group-centered rewards. This is a separate REINFORCE-style loss: PPO clipping parameters do not apply. Existing batch size and update scheduling still control how many updates consume a rollout batch; choose them explicitly when reproducing an experiment.

Expand Down Expand Up @@ -82,7 +82,7 @@ Native SGLang generation, the legacy rollout path, and both session-server versi

Evaluation requests skip this collection and may use independent sampling settings, including greedy decoding. The built-in agentic producer marks evaluation sessions when creating them; custom session clients should create them with `POST /sessions` with JSON body `{"evaluation": true}`.

For unfiltered session rollouts, more than 20 candidates require `--use-miles-router`. The SGLang Rust router caps OpenAI `top_logprobs` at 20, while MilesRouter forwards a larger request to SGLang unchanged. To use the SGLang router for unfiltered session rollouts, set `--rollout-top-logprobs-num 20` or less. Filtered rollouts request support probabilities instead of `top_logprobs` and do not use that cap. Native `/generate` rollouts support either router.
Unfiltered session rollouts with more than 20 candidates need an SGLang router build that accepts the requested OpenAI `top_logprobs` value and preserves `input_ids` and `return_meta_info`. Older builds cap `top_logprobs` at 20. Verify a chat request through the installed router before launching; for `--rollout-top-logprobs-num 128`, confirm that 128 candidate log probabilities reach the session server. Native `/generate` requests use `top_logprobs_num` and do not share that chat validation limit. Filtered rollouts request support probabilities through `sampling_logprobs_mode` instead of `top_logprobs`, so that cap does not apply, but the router must forward `sampling_logprobs_mode` on chat and `/generate` requests.

Unused candidate slots and non-trained observation rows contain token ID `-1` and log probability `-inf`. Tool-observation masks, multi-turn merging, retries, trailing-token trimming, and truncation preserve row alignment. Session serialization retains both arrays. For score centering in support mode, training batches share the recorded support IDs when every sample has exactly the same candidate order and prefix padding. A per-row candidate count preserves observation rows and masked generated rows; any mismatch keeps the original arrays for the whole batch. The trainer reconstructs only its context-parallel rows. The source Samples and session payloads still retain both representations.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ def __post_init__(self) -> None:
or self.head_mask.shape != self.train_head_log_probs.shape
):
raise ValueError("Score-centering sample tensors must be [tokens] and head tensors [tokens, candidates]")
if not torch.isfinite(self.advantages).all():
raise ValueError("Score-centering advantages must be finite")


@dataclass(frozen=True)
Expand Down Expand Up @@ -86,10 +84,8 @@ def score_centering_loss(inputs: ScoreCenteringInputs) -> tuple[torch.Tensor, Sc
weight = sampling.sample_weight(
drop_inactive_nan(inputs.train_log_probs - inputs.rollout_log_probs, active, 0.0)
)
correction = (residual * scored_log_probs(train_head, residual, active)).sum(-1)
loss = -inputs.advantages.detach() * (
weight * scored_log_probs(inputs.train_log_probs, weight, active) - correction
)
correction = (residual * scored_log_probs(train_head, residual)).sum(-1)
loss = -inputs.advantages.detach() * (weight * scored_log_probs(inputs.train_log_probs, weight) - correction)
return loss, ScoreCenteringMetrics(
correction=correction.detach(),
train_head_mass=p_mass,
Expand Down
15 changes: 5 additions & 10 deletions miles/backends/training_utils/loss/hub/score_centering/masks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@

Candidate slots outside ``head_mask`` are padding: their log-probability is a
finite placeholder and their probability is zero, so padding never contributes
and never trips the non-finite checks. NaN is tolerated only on inactive
(zero-advantage) tokens, where it becomes zero mass; on an active token it is an
error. ``-inf`` is valid data (zero probability) and is rejected only where an
active token gives it a nonzero coefficient.
to the loss. NaN on inactive (zero-advantage) tokens becomes zero mass.
``-inf`` represents zero probability; scored terms mask non-finite values
before multiplication.
"""

import torch
Expand All @@ -17,14 +16,12 @@ def _token_mask(active: torch.Tensor, values: torch.Tensor) -> torch.Tensor:


def drop_inactive_nan(values: torch.Tensor, active: torch.Tensor, fill: float) -> torch.Tensor:
"""Replace NaN on inactive tokens with ``fill``; NaN on active tokens is kept for the caller to reject."""
"""Replace NaN on inactive tokens with ``fill``; preserve values on active tokens."""
return torch.where(~_token_mask(active, values) & torch.isnan(values), fill, values)


def sanitize_head_log_probs(log_probs: torch.Tensor, head_mask: torch.Tensor, active: torch.Tensor) -> torch.Tensor:
"""Head log-probabilities with inactive NaN mapped to ``-inf`` and padding to the placeholder 0."""
if (_token_mask(active, log_probs) & head_mask & torch.isnan(log_probs)).any():
raise ValueError("Score centering has a NaN candidate log-probability on an active token")
return torch.where(head_mask, drop_inactive_nan(log_probs, active, -torch.inf), 0.0)


Expand All @@ -33,13 +30,11 @@ def head_probs(log_probs: torch.Tensor, head_mask: torch.Tensor) -> torch.Tensor
return log_probs.exp().masked_fill(~head_mask, 0.0)


def scored_log_probs(log_probs: torch.Tensor, coefficient: torch.Tensor, active: torch.Tensor) -> torch.Tensor:
def scored_log_probs(log_probs: torch.Tensor, coefficient: torch.Tensor) -> torch.Tensor:
"""Log-probabilities that enter the loss, zeroed wherever the coefficient is zero.

Masking before the multiply keeps ``0 * -inf`` from turning the loss into NaN.
"""
finite = torch.isfinite(log_probs)
scored = coefficient != 0
if (_token_mask(active, log_probs) & scored & ~finite).any():
raise ValueError("Score centering has a non-finite log-probability with nonzero gradient weight")
return torch.where(scored & finite, log_probs, 0.0)
7 changes: 3 additions & 4 deletions miles/ray/specs/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,8 +414,7 @@ def compute_inference_engine_env_vars(args) -> dict[str, str]:
from miles.utils import dumper_utils

env_vars.update(dumper_utils.get_sglang_env(args))
if getattr(args, "loss_type", None) == "score_centering":
# Candidate and sampled logprobs must describe the temperature-scaled
# distribution used to draw tokens, including on remote workers.
env_vars["SGLANG_RETURN_ORIGINAL_LOGPROB"] = "0"
# Match the trainer's temperature-scaled logprobs on every worker,
# overriding inherited environment and dumper settings.
env_vars["SGLANG_RETURN_ORIGINAL_LOGPROB"] = "0"
return env_vars
11 changes: 0 additions & 11 deletions miles/utils/score_centering.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,5 @@ def validate_score_centering_args(args: Namespace) -> None:
for option, reason in incompatible.items():
if getattr(args, option, None):
raise ValueError(f"Score centering is incompatible with --{option.replace('_', '-')}: {reason}")
if (
args.rollout_top_logprobs_num > 20
and args.rollout_top_p == 1.0
and args.rollout_top_k == -1
and getattr(args, "use_session_server", None)
and not getattr(args, "use_miles_router", False)
):
raise ValueError(
"Score-centering session rollouts with more than 20 candidates require --use-miles-router: "
"the SGLang Rust router caps OpenAI top_logprobs at 20"
)
if os.environ.get("SGLANG_RETURN_ORIGINAL_LOGPROB", "").lower() in ("1", "true"):
raise ValueError("Score centering requires SGLANG_RETURN_ORIGINAL_LOGPROB=0 on rollout servers")
46 changes: 0 additions & 46 deletions tests/fast/backends/training_utils/test_score_centering.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,35 +114,6 @@ def test_zero_advantage_ignores_nan_head_candidate(mode: str, bad_side: str) ->
assert all(torch.isfinite(value).all() for value in metrics.as_log_dict().values())


def test_active_nan_head_candidate_fails_clearly() -> None:
with pytest.raises(ValueError, match="NaN candidate"):
score_centering_loss(
ScoreCenteringInputs(
train_log_probs=torch.tensor([-1.0]),
train_head_log_probs=torch.tensor([[float("nan")]]),
rollout_log_probs=torch.tensor([-1.0]),
rollout_head_log_probs=torch.tensor([[-1.0]]),
head_mask=torch.tensor([[True]]),
advantages=torch.ones(1),
),
)


@pytest.mark.parametrize("advantage", [float("nan"), float("inf"), float("-inf")])
def test_nonfinite_advantage_fails_clearly(advantage: float) -> None:
with pytest.raises(ValueError, match="advantages must be finite"):
score_centering_loss(
ScoreCenteringInputs(
train_log_probs=torch.tensor([-1.0]),
train_head_log_probs=torch.tensor([[-1.0]]),
rollout_log_probs=torch.tensor([-1.0]),
rollout_head_log_probs=torch.tensor([[-1.0]]),
head_mask=torch.tensor([[True]]),
advantages=torch.tensor([advantage]),
),
)


@pytest.mark.parametrize("bad_index", [1, 2, 3, 4, 5])
def test_score_centering_loss_rejects_broadcastable_shapes(bad_index: int) -> None:
values = [
Expand Down Expand Up @@ -192,23 +163,6 @@ def test_zero_weight_negative_infinity_has_finite_loss_and_gradient(mode: str, n
torch.testing.assert_close(head.grad, torch.zeros_like(head.grad))


@pytest.mark.parametrize("nonfinite", ["sample", "head"])
def test_unweighted_nonfinite_positive_weight_fails_clearly(nonfinite: str) -> None:
sample = torch.tensor([float("-inf") if nonfinite == "sample" else -1.0])
head = torch.tensor([[float("-inf") if nonfinite == "head" else -1.0]])
with pytest.raises(ValueError, match="non-finite log-probability"):
score_centering_loss(
ScoreCenteringInputs(
train_log_probs=sample,
train_head_log_probs=head,
rollout_log_probs=torch.tensor([-1.0]),
rollout_head_log_probs=torch.tensor([[-1.0]]),
head_mask=torch.tensor([[True]]),
advantages=torch.ones(1),
),
)


@pytest.mark.parametrize("mode", ["none", "tis", "mis"])
def test_zero_advantage_skips_nonfinite_log_probabilities(mode: str) -> None:
loss, _ = score_centering_loss(
Expand Down
13 changes: 10 additions & 3 deletions tests/fast/ray/specs/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,11 @@ def test_an_enabled_dumper_resolves_the_sglang_environment(self, monkeypatch) ->

def get_sglang_env(call_args: Namespace) -> dict[str, str]:
get_sglang_env_calls.append(call_args)
return {"DUMPER_SERVER_PORT": "reuse", "DUMPER_NON_INTRUSIVE_MODE": "all"}
return {
"DUMPER_SERVER_PORT": "reuse",
"DUMPER_NON_INTRUSIVE_MODE": "all",
"SGLANG_RETURN_ORIGINAL_LOGPROB": "1",
}

fake_dumper_utils = SimpleNamespace(get_sglang_env=get_sglang_env)
import miles.utils as miles_utils
Expand All @@ -486,9 +490,12 @@ def get_sglang_env(call_args: Namespace) -> dict[str, str]:
assert get_sglang_env_calls == [args]
assert envs["DUMPER_SERVER_PORT"] == "reuse"
assert envs["DUMPER_NON_INTRUSIVE_MODE"] == "all"
assert envs["SGLANG_RETURN_ORIGINAL_LOGPROB"] == "0"

def test_score_centering_requests_sampler_logprobs_on_workers(self):
envs = compute_inference_engine_env_vars(make_args(loss_type="score_centering"))
@pytest.mark.parametrize("loss_type", ["policy_loss", "score_centering"])
def test_training_enforces_sampler_logprobs_on_workers(self, monkeypatch, loss_type):
monkeypatch.setenv("SGLANG_RETURN_ORIGINAL_LOGPROB", "1")
envs = compute_inference_engine_env_vars(make_args(loss_type=loss_type))
assert envs["SGLANG_RETURN_ORIGINAL_LOGPROB"] == "0"

def test_a_process_level_override_wins_over_the_built_in_default(self, monkeypatch):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,10 @@ def test_invalid_options_fail_early(field: str, value: object) -> None:

@pytest.mark.parametrize("session", ["v1", "v2"])
@pytest.mark.parametrize("top_k", [21, 128])
def test_large_session_heads_require_miles_router(session: str, top_k: int) -> None:
args = _args(use_session_server=session, rollout_top_logprobs_num=top_k, use_miles_router=False)
with pytest.raises(ValueError, match="require --use-miles-router"):
validate_score_centering_args(args)

args.use_miles_router = True
validate_score_centering_args(args)
def test_large_session_heads_can_use_sglang_router(session: str, top_k: int) -> None:
validate_score_centering_args(
_args(use_session_server=session, rollout_top_logprobs_num=top_k, use_miles_router=False)
)


@pytest.mark.parametrize("session", ["v1", "v2"])
Expand Down
2 changes: 2 additions & 0 deletions tests/snapshots/charts/miles-run/typical-values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ run:
SGLANG_JIT_DEEPGEMM_PRECOMPILE: 'false'
SGLANG_MEMORY_SAVER_CUDA_GRAPH: 'true'
SGLANG_OPT_USE_CUSTOM_ALL_REDUCE_V2: '1'
SGLANG_RETURN_ORIGINAL_LOGPROB: '0'
meta:
gpu_ids: 0,1,2,3,4,5,6,7
name: inference-engine-all-0-0
Expand Down Expand Up @@ -172,6 +173,7 @@ run:
SGLANG_JIT_DEEPGEMM_PRECOMPILE: 'false'
SGLANG_MEMORY_SAVER_CUDA_GRAPH: 'true'
SGLANG_OPT_USE_CUSTOM_ALL_REDUCE_V2: '1'
SGLANG_RETURN_ORIGINAL_LOGPROB: '0'
meta:
gpu_ids: 0,1,2,3,4,5,6,7
name: inference-engine-all-0-1
Expand Down
4 changes: 4 additions & 0 deletions tests/snapshots/charts/miles-run/typical.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1320,6 +1320,8 @@ spec:
value: "true"
- name: "SGLANG_OPT_USE_CUSTOM_ALL_REDUCE_V2"
value: "1"
- name: "SGLANG_RETURN_ORIGINAL_LOGPROB"
value: "0"
ports:
- name: "primary"
containerPort: 8000
Expand Down Expand Up @@ -1523,6 +1525,8 @@ spec:
value: "true"
- name: "SGLANG_OPT_USE_CUSTOM_ALL_REDUCE_V2"
value: "1"
- name: "SGLANG_RETURN_ORIGINAL_LOGPROB"
value: "0"
ports:
- name: "primary"
containerPort: 8000
Expand Down
Loading