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
7 changes: 5 additions & 2 deletions docs/user-guide/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,8 @@ Built-in scorers (`--rm-type pickscore` / `hps` / `ocr` / `custom_api` / `openai
replaces the normalization that runs after scoring.

With `--use-output-store`, the rollout process does not read a training rollout's output. There,
`sample.generated_output` is a `StoredTensor`, and the actors of a reward pool read it when they score it. A
`sample.generated_output` (and `sample.generated_audio`, when the engine returns audio) is a `StoredTensor`, and the
actors of a reward pool read it when they score it. A
`--custom-rm-path` function therefore scores through a pool, a built-in `*_rm` or its own `AsyncRewardActorPool`, and
does not read the tensor itself. Once a sample is scored its output is `None`; the first `--wandb-log-num-images`
scored samples of a rollout that logs media keep it as a tensor, so a rollout whose first groups a filter drops logs
Expand Down Expand Up @@ -193,7 +194,9 @@ async def api_rm(args, samples: list[Sample], **kwargs) -> list[float]:
```

With `--use-output-store` this function cannot read the output. Send it through `--custom-api-rm-config`, whose
`ApiRewardActor` reads it in the actor, or through your own `AsyncRewardActorPool(args=args, ...)`.
`ApiRewardActor` reads it in the actor, or through your own `AsyncRewardActorPool(args=args, ...)`, whose actor class
declares `required_media` and implements `score_batch(outputs: list[GeneratedMedia], prompts)` (see
[Rewards](rewards.md) § 3).

### `--custom-reward-post-process-path`

Expand Down
14 changes: 12 additions & 2 deletions docs/user-guide/rewards.md
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ PickScore/26 ≈ 0.8–0.9, OCR ∈ [0, 1], default OpenAI API rubric ∈ [0, 4]
scales in mind. A zero weight keeps a reward as a monitor only, e.g.
`--custom-rm-args "hpsv3=1.0,hps=0,pickscore=0" --reward-key hpsv3` trains on HPSv3 and plots the
other two to catch reward hacking. Colocated pools share one slot ledger, so several rewards
can colocate without overlapping. Rewards receive `generated_output` itself, and every reward actor
quantises it to uint8 on its own terms.
can colocate without overlapping. Rewards receive each sample's `GeneratedMedia` (see § 3), and every reward actor
quantises its `visual` to uint8 on its own terms.

A shipped recipe uses it: `scripts/run_diffusion_grpo_sd3_ocr_pickscore_sglang.py` trains SD3.5 on
0.8 OCR + 0.2 PickScore with `--rollout-shuffle`; see [SD3](../models/sd3/sd3.md) § 5.4 for the
Expand Down Expand Up @@ -230,6 +230,10 @@ for a JSON `score`. Its kwargs are `model` and `api_key_env` (required), `base_u
built-in 0–4 rubric is used), `score_min` / `score_max` (default 0 / 4), and `timeout_s`; scores outside that range
raise. It accepts image outputs only (one frame).

An `ApiRewardActor` subclass declares `required_media`, the `GeneratedMedia` fields its requests use
(`OpenAIImageRewardActor`: `frozenset({"visual"})`), and its `build_request(output, prompt)` receives only those; a pool
rejects a subclass that declares none.

### Remote RM (`--rm-type remote_rm`)

The CLI exposes `--rm-url` for a remote reward service, but **`rm_hub` does not
Expand Down Expand Up @@ -257,6 +261,12 @@ RolloutManager._convert_samples_to_train_data()
→ _post_process_rewards() # GRPO advantage normalization
```

Every built-in reward hands its pool one `GeneratedMedia` per sample (`miles/utils/types.py`): `visual` is
`generated_output` (`[C, F, H, W]`), `audio` is `generated_audio` (`[C, L]`) with its `audio_sample_rate`. The scorer
class declares `required_media`, e.g. `frozenset({"visual"})` for the image rewards; the pool rejects a sample that
lacks one of them and sends no other tensor field, so an image reward never moves or reads a waveform. With
`--use-output-store` the fields are `StoredTensor`s, which the reward actor reads.

After rollout, `RolloutManager._post_process_rewards` subtracts the mean and
optionally divides by std to produce normalized advantages for training.
Override that path with `--custom-reward-post-process-path` — see
Expand Down
15 changes: 7 additions & 8 deletions miles/rollout/rm_hub/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,21 @@
from numbers import Real
from typing import Any

import torch

from miles.utils.misc import SingletonMeta, load_function
from miles.utils.types import Sample
from miles.utils.types import GeneratedMedia, Sample

from .core import AsyncRewardActorPool, record_reward_queue_depth


class ApiRewardActor(ABC):
"""Build, send, and parse one request per output using backend-specific hooks.

Hooks may run concurrently on the same actor and must keep per-request state
A subclass declares ``required_media``, the `GeneratedMedia` fields its requests use, e.g.
``frozenset({"visual"})``. Hooks may run concurrently on the same actor and must keep per-request state
local. The transport owns retries and timeouts; exceptions propagate to the caller.
"""

def score_batch(self, outputs: list[torch.Tensor], prompts: list[str]) -> list[float]:
def score_batch(self, outputs: list[GeneratedMedia], prompts: list[str]) -> list[float]:
if len(outputs) != len(prompts):
raise ValueError("API reward requires one prompt per output")
scores = []
Expand All @@ -37,8 +36,8 @@ def score_batch(self, outputs: list[torch.Tensor], prompts: list[str]) -> list[f
return scores

@abstractmethod
def build_request(self, output: torch.Tensor, prompt: str) -> Any:
"""Build a backend request from one raw CFHW tensor and its prompt."""
def build_request(self, output: GeneratedMedia, prompt: str) -> Any:
"""Build a backend request from one sample's output and its prompt; only its ``required_media`` fields are set."""
raise NotImplementedError

@abstractmethod
Expand Down Expand Up @@ -80,6 +79,6 @@ def __init__(self, args) -> None:

async def custom_api_rm(args, samples: Sequence[Sample], **kwargs) -> list[float]:
pool = AsyncApiRewardPool(args)
scores, max_queue_depth = await pool.score([s.generated_output for s in samples], [s.prompt for s in samples])
scores, max_queue_depth = await pool.score([s.generated_media for s in samples], [s.prompt for s in samples])
record_reward_queue_depth(samples, "custom_api", max_queue_depth)
return scores
52 changes: 44 additions & 8 deletions miles/rollout/rm_hub/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import asyncio
import logging
from dataclasses import replace

import ray
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
Expand All @@ -12,6 +13,7 @@
from miles.utils.diffusion_rollout_response import read_generated_outputs
from miles.utils.logging_utils import configure_logger
from miles.utils.output_store import StoredTensor, StoredTensorReader, connect_output_store
from miles.utils.types import GeneratedMedia

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -91,20 +93,32 @@ def __init__(self, *, scorer_cls, scorer_kwargs: dict, args) -> None:
self._scorer = scorer_cls(**scorer_kwargs)
self._reader = StoredTensorReader(connect_output_store(args))

def score_batch(self, outputs: list, prompts: list[str]) -> list[float]:
def score_batch(self, outputs: list[GeneratedMedia], prompts: list[str]) -> list[float]:
# eval outputs arrive inline
stored_outputs = [output for output in outputs if isinstance(output, StoredTensor)]
if stored_outputs:
read_outputs = iter(read_generated_outputs(self._reader, stored_outputs))
outputs = [next(read_outputs) if isinstance(output, StoredTensor) else output for output in outputs]
stored_visuals = [output.visual for output in outputs if isinstance(output.visual, StoredTensor)]
if stored_visuals:
visuals = iter(read_generated_outputs(self._reader, stored_visuals))
outputs = [
replace(output, visual=next(visuals)) if isinstance(output.visual, StoredTensor) else output
for output in outputs
]
stored_audios = [output.audio for output in outputs if isinstance(output.audio, StoredTensor)]
if stored_audios:
# not read_generated_outputs: a waveform has no video layout to normalize
audios = iter(self._reader.read(stored_audios))
outputs = [
replace(output, audio=next(audios)) if isinstance(output.audio, StoredTensor) else output
for output in outputs
]
return self._scorer.score_batch(outputs, prompts)


class AsyncRewardActorPool:
"""Round-robin pool for Ray reward actors exposing ``score_batch(outputs, prompts)``.

Actors receive the float ``generated_output`` tensors and quantise to uint8 themselves. With the output store
on they are given stored outputs and read them first.
The actor class declares ``required_media``, the `GeneratedMedia` fields it scores; the pool checks each sample
has them and sends no other field. Actors receive float tensors and quantise to uint8 themselves. With the output
store on they are given stored tensors and read them first.
Colocated pools take one slot per rollout bundle from the manager's
``slots``; standalone pools are default-scheduled at ``num_gpus_per_worker``, which
only lands on GPUs outside every placement group.
Expand Down Expand Up @@ -136,6 +150,14 @@ def __init__(
num_gpus_per_worker = COLOCATED_REWARD_GPU
else:
strategies = ["DEFAULT"] * num_workers
required_media = actor_cls.required_media
if not required_media or not required_media <= {"visual", "audio"}:
raise TypeError(
f"{actor_cls.__name__}.required_media must name visual, audio or both; got {set(required_media)}"
)
self._requires_visual = "visual" in required_media
self._requires_audio = "audio" in required_media
self._name = name
if args.use_output_store:
actor_kwargs = {"scorer_cls": actor_cls, "scorer_kwargs": actor_kwargs, "args": args}
actor_cls = _StoredOutputRewardActor
Expand Down Expand Up @@ -167,8 +189,9 @@ def _next_actor_idx(self) -> int:
self._round_robin_index += 1
return i

async def score(self, outputs: list, prompts: list[str]) -> tuple[list[float], int]:
async def score(self, outputs: list[GeneratedMedia], prompts: list[str]) -> tuple[list[float], int]:
"""Score samples in batches; also report the deepest dispatch-time backlog this call saw."""
outputs = [self._only_required_fields(output) for output in outputs]
refs, idxs, max_queue_depth = [], [], 0
for start in range(0, len(outputs), self._batch_size):
end = start + self._batch_size
Expand All @@ -185,3 +208,16 @@ async def score(self, outputs: list, prompts: list[str]) -> tuple[list[float], i
for i in idxs:
self._inflight[i] -= 1
return [float(score) for chunk in chunked_scores for score in chunk], max_queue_depth

def _only_required_fields(self, output: GeneratedMedia) -> GeneratedMedia:
"""``output`` without the fields this pool's scorer does not require, so they neither cross Ray nor are read
from the store."""
if self._requires_visual and output.visual is None:
raise ValueError(f"the {self._name} reward requires visual, but a sample generated none")
if self._requires_audio and output.audio is None:
raise ValueError(f"the {self._name} reward requires audio, but a sample generated none")
return replace(
output,
visual=output.visual if self._requires_visual else None,
audio=output.audio if self._requires_audio else None,
)
10 changes: 6 additions & 4 deletions miles/rollout/rm_hub/hps.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from miles.utils.misc import SingletonMeta
from miles.utils.processing_utils import generated_output_to_rgb_hwc_uint8_frames
from miles.utils.types import Sample
from miles.utils.types import GeneratedMedia, Sample

from .core import AsyncRewardActorPool, record_reward_queue_depth

Expand Down Expand Up @@ -104,6 +104,8 @@ def forward(self, prompts: Sequence[str], images: Sequence[Image.Image]) -> list


class HPSRewardActor:
required_media = frozenset({"visual"})

def __init__(self, *, hps_version: str, checkpoint_path: str | None = None) -> None:
use_cuda = bool(ray.get_gpu_ids()) and torch.cuda.is_available()
if use_cuda:
Expand All @@ -114,11 +116,11 @@ def __init__(self, *, hps_version: str, checkpoint_path: str | None = None) -> N
checkpoint_path=checkpoint_path,
)

def score_batch(self, outputs: list[torch.Tensor], prompts: list[str]) -> list[float]:
def score_batch(self, outputs: list[GeneratedMedia], prompts: list[str]) -> list[float]:
# HPSv2 rounds when quantising to uint8; matching it keeps scores comparable with the reference
images = []
for output in outputs:
(image,) = generated_output_to_rgb_hwc_uint8_frames(output, None, round_normalized=True)
(image,) = generated_output_to_rgb_hwc_uint8_frames(output.visual, None, round_normalized=True)
images.append(Image.fromarray(image))
return self.scorer(prompts, images)

Expand Down Expand Up @@ -146,6 +148,6 @@ def __init__(self, args, placement_group=None, slots=None) -> None:

async def hps_rm(args, samples: Sequence[Sample]) -> list[float]:
pool = AsyncHPSPool(args)
scores, max_queue_depth = await pool.score([s.generated_output for s in samples], [s.prompt for s in samples])
scores, max_queue_depth = await pool.score([s.generated_media for s in samples], [s.prompt for s in samples])
record_reward_queue_depth(samples, "hps", max_queue_depth)
return scores
14 changes: 8 additions & 6 deletions miles/rollout/rm_hub/hpsv3.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from miles.utils.misc import SingletonMeta
from miles.utils.processing_utils import generated_output_to_rgb_hwc_uint8_frames
from miles.utils.types import Sample
from miles.utils.types import GeneratedMedia, Sample

from .core import AsyncRewardActorPool, record_reward_queue_depth

Expand Down Expand Up @@ -212,18 +212,20 @@ def forward(self, prompts: Sequence[str], images: Sequence[Image.Image]) -> list


class HPSv3RewardActor:
required_media = frozenset({"visual"})

def __init__(self, **scorer_kwargs) -> None:
use_cuda = bool(ray.get_gpu_ids()) and torch.cuda.is_available()
if use_cuda:
torch.cuda.set_device(0)
self.scorer = HPSv3Scorer(device="cuda" if use_cuda else "cpu", **scorer_kwargs)

def score_batch(self, outputs: list[torch.Tensor], prompts: list[str]) -> list[float]:
def score_batch(self, outputs: list[GeneratedMedia], prompts: list[str]) -> list[float]:
images = []
for output in outputs:
if output.shape[1] != 1:
raise ValueError(f"HPSv3 scores images only, got {output.shape[1]} frames")
(image,) = generated_output_to_rgb_hwc_uint8_frames(output, None, round_normalized=True)
if output.visual.shape[1] != 1:
raise ValueError(f"HPSv3 scores images only, got {output.visual.shape[1]} frames")
(image,) = generated_output_to_rgb_hwc_uint8_frames(output.visual, None, round_normalized=True)
images.append(Image.fromarray(image))
return self.scorer(prompts, images)

Expand All @@ -248,6 +250,6 @@ def __init__(self, args, placement_group=None, slots=None) -> None:

async def hpsv3_rm(args, samples: Sequence[Sample]) -> list[float]:
pool = AsyncHPSv3Pool(args)
scores, max_queue_depth = await pool.score([s.generated_output for s in samples], [s.prompt for s in samples])
scores, max_queue_depth = await pool.score([s.generated_media for s in samples], [s.prompt for s in samples])
record_reward_queue_depth(samples, "hpsv3", max_queue_depth)
return scores
10 changes: 6 additions & 4 deletions miles/rollout/rm_hub/ocr.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from miles.utils.misc import SingletonMeta
from miles.utils.processing_utils import generated_output_to_rgb_hwc_uint8_frames
from miles.utils.types import Sample
from miles.utils.types import GeneratedMedia, Sample

from .core import AsyncRewardActorPool, record_reward_queue_depth

Expand Down Expand Up @@ -84,13 +84,15 @@ def __call__(self, images: list[Image.Image] | list[np.ndarray], prompts: list[s


class OcrRewardActor:
required_media = frozenset({"visual"})

def __init__(self, use_gpu: bool = False):
self.scorer = OcrScorer(use_gpu=use_gpu)

def score_batch(self, outputs: list[torch.Tensor], prompts: list[str]) -> list[float]:
def score_batch(self, outputs: list[GeneratedMedia], prompts: list[str]) -> list[float]:
assert len(outputs) == 1, f"OCR scores one image per call, got {len(outputs)}"
# flow_grpo feeds PaddleOCR rounded RGB (not BGR) uint8; matching it keeps the reward bit-identical
(image,) = generated_output_to_rgb_hwc_uint8_frames(outputs[0], None, round_normalized=True)
(image,) = generated_output_to_rgb_hwc_uint8_frames(outputs[0].visual, None, round_normalized=True)
return self.scorer([image], prompts)


Expand All @@ -112,6 +114,6 @@ def __init__(self, args) -> None:

async def ocr_rm(args, samples: Sequence[Sample]) -> list[float]:
pool = AsyncOcrPool(args)
scores, max_queue_depth = await pool.score([s.generated_output for s in samples], [s.prompt for s in samples])
scores, max_queue_depth = await pool.score([s.generated_media for s in samples], [s.prompt for s in samples])
record_reward_queue_depth(samples, "ocr", max_queue_depth)
return scores
11 changes: 6 additions & 5 deletions miles/rollout/rm_hub/openai_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any

import torch
from PIL import Image

from miles.utils.api_rm_config import OpenAIImageRewardConfig
from miles.utils.processing_utils import encode_image_as_png_data_url, generated_output_to_rgb_hwc_uint8_frames
from miles.utils.types import Sample
from miles.utils.types import GeneratedMedia, Sample

from .api import ApiRewardActor, AsyncApiRewardPool
from .core import record_reward_queue_depth
Expand All @@ -40,6 +39,8 @@
class OpenAIImageRewardActor(ApiRewardActor):
"""Score prompt/image pairs using the OpenAI-compatible Chat Completions API."""

required_media = frozenset({"visual"})

def __init__(self, **kwargs) -> None:
from openai import OpenAI

Expand All @@ -51,8 +52,8 @@ def __init__(self, **kwargs) -> None:
max_retries=2,
)

def build_request(self, output: torch.Tensor, prompt: str) -> dict[str, Any]:
(frame,) = generated_output_to_rgb_hwc_uint8_frames(output, None, round_normalized=True)
def build_request(self, output: GeneratedMedia, prompt: str) -> dict[str, Any]:
(frame,) = generated_output_to_rgb_hwc_uint8_frames(output.visual, None, round_normalized=True)
image = Image.fromarray(frame)
return {
"model": self.config.model,
Expand Down Expand Up @@ -90,6 +91,6 @@ class AsyncOpenAIPool(AsyncApiRewardPool):

async def openai_api_rm(args, samples: Sequence[Sample], **kwargs) -> list[float]:
pool = AsyncOpenAIPool(args)
scores, max_queue_depth = await pool.score([s.generated_output for s in samples], [s.prompt for s in samples])
scores, max_queue_depth = await pool.score([s.generated_media for s in samples], [s.prompt for s in samples])
record_reward_queue_depth(samples, "openai_api", max_queue_depth)
return scores
Loading
Loading