Skip to content
Open
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
17 changes: 13 additions & 4 deletions slime/data/batch_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
)
from slime.utils.data import get_source
from slime.utils.dp_schedule import build_dp_schedule
from slime.utils.misc import Box, load_function
from slime.utils.misc import Box, group_by, load_function
from slime.utils.types import Sample

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -446,10 +446,9 @@ def split_by_dp(self, data):
"""Build a schedule over one immutable conversion, without per-rank writes."""
transport = self.args.rollout_data_transport
if transport == "straw":
# Scheduling needs lengths and rollout identity only. In particular,
# replay must not read the full token or R3 payload on the manager.
# Read only the metadata needed for scheduling and reward reporting.
reference = data if isinstance(data, DiskPayloadRef) else self.publish_converted(data)
data = reference.load(selection={"total_lengths": None, "rollout_ids": None})
data = reference.load(selection={"total_lengths": None, "rollout_ids": None, "raw_reward": None})
total_lengths = data.get("total_lengths")
if total_lengths is None:
total_lengths = [len(tokens) for tokens in data["tokens"]]
Expand All @@ -461,6 +460,14 @@ def split_by_dp(self, data):
global_batch_size=self.args.global_batch_size,
rollout_indices=data["rollout_ids"],
)
raw_reward_mean = None
if raw_rewards := data.get("raw_reward"):
# An episode can span multiple DP ranks. Average its rows while
# the whole batch is available, then weight each episode equally.
rewards_by_rollout = group_by(zip(data["rollout_ids"], raw_rewards, strict=True), lambda pair: pair[0])
raw_reward_mean = sum(
sum(reward for _, reward in rows) / len(rows) for rows in rewards_by_rollout.values()
) / len(rewards_by_rollout)
fields = [
"tokens",
"multimodal_train_inputs",
Expand Down Expand Up @@ -502,6 +509,8 @@ def split_by_dp(self, data):
"num_microbatches": num_microbatches,
"micro_batch_indices": micro_batch_indices[rank],
}
if raw_reward_mean is not None:
schedule["raw_reward_mean"] = raw_reward_mean
if transport == "straw":
selection = {key: partition for key in fields}
# Training's pass-rate and load metrics use the global arrays;
Expand Down
5 changes: 5 additions & 0 deletions slime/observability/train_metric_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ def log_rollout_data(
"micro_batch_indices",
"source_names",
"local_raw_reward",
"raw_reward_mean",
}
per_rollout_mean_keys = {
"log_probs",
Expand All @@ -192,6 +193,10 @@ def log_rollout_data(
for key, value in rollout_data.items():
if key in ignored_keys:
continue
if key == "raw_reward" and "raw_reward_mean" in rollout_data:
# Each rank carries the same mean over the full rollout batch.
log_dict[key] = rollout_data["raw_reward_mean"]
continue
if isinstance(value, (list, tuple)):
count = len(value)
if isinstance(value[0], torch.Tensor):
Expand Down
70 changes: 70 additions & 0 deletions tests/test_metric_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,76 @@
NUM_GPUS = 0


@pytest.mark.parametrize("split", [False, True], ids=["whole-rollouts", "segments-across-ranks"])
def test_raw_reward_mean_counts_each_rollout_once(monkeypatch, split):
from types import SimpleNamespace

import ray
from megatron.core import mpu

from slime.data.batch_builder import BatchBuilder
from slime.observability import train_metric_utils
from slime.utils.data import process_rollout_data

monkeypatch.setattr(ray, "put", lambda value: value)
monkeypatch.setattr(ray, "get", lambda value: value)
monkeypatch.setattr(mpu, "get_tensor_model_parallel_rank", lambda: 0, raising=False)
monkeypatch.setattr(mpu, "is_pipeline_last_stage", lambda: True, raising=False)
monkeypatch.setattr(mpu, "get_data_parallel_world_size", lambda **kwargs: 2, raising=False)
reported = []
monkeypatch.setattr(
train_metric_utils, "gather_log_data", lambda name, args, step, metrics: reported.append(metrics)
)

args = SimpleNamespace(
custom_reward_post_process_path=None,
custom_convert_samples_to_train_data_path=None,
rollout_data_transport="object-store",
global_batch_size=4,
micro_batch_size=1,
use_dynamic_batch_size=False,
balance_by_flops=False,
balance_data=False,
ci_test=False,
log_multi_turn=False,
log_passrate=False,
log_correct_samples=False,
)
builder = BatchBuilder(args)
builder.train_parallel_config = {
"dp_size": 2,
"cp_size": 1,
"vpp_size": 1,
"microbatch_group_size_per_vp_stage": 1,
}
rollout_ids = [10, 10, 20, 30, 40, 40] if split else [10, 20, 30, 40]
raw_rewards = [float(rollout_id == 10) for rollout_id in rollout_ids]
refs = builder.split_by_dp(
{
"tokens": [[1, 2] for _ in rollout_ids],
"response_lengths": [1] * len(rollout_ids),
"loss_masks": [[1] for _ in rollout_ids],
"rollout_ids": rollout_ids,
"raw_reward": raw_rewards,
}
)

for rank in range(2):
shard = process_rollout_data(refs, rank, 2)
if split:
assert 10 in shard["rollout_ids"]
assert shard["raw_reward"] == raw_rewards
train_metric_utils.log_rollout_data(0, args, shard)

def gather_object(value, output, **kwargs):
output[:] = reported

monkeypatch.setattr(train_metric_utils.dist, "get_rank", lambda: 0)
monkeypatch.setattr(train_metric_utils.dist, "gather_object", gather_object)
reduced = train_metric_utils.gather_and_reduce_log_dict(reported[0], dp_size=2, dp_src_rank=0, dp_group=None)
assert reduced["raw_reward"] == 0.25


def test_truncation_fraction_is_reported_once_for_all_rollout_sources(monkeypatch):
from types import SimpleNamespace

Expand Down
1 change: 1 addition & 0 deletions tests/test_rollout_straw_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,7 @@ def put(value, **kwargs):
assert batch["loss_masks"][0].tolist() == [0, 1]
assert batch["total_lengths"] == [3]
assert batch["local_raw_reward"] == [2.0]
assert batch["raw_reward_mean"] == 1.5
assert batch["rollout_top_p_token_offsets"][0].tolist() == [0, 1, 2]
torch.testing.assert_close(batch["rollout_top_p_log_probs"][0], torch.tensor([-0.3, -0.4]))
assert batch["multimodal_train_inputs"][0]["pixel_values"].shape == (3, 20, 20)
Expand Down
Loading