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
7 changes: 6 additions & 1 deletion docs/user-guide/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ See [Dtype Control](../advanced/dtype-control.md).

| Flag | Type | Default | Notes |
|---|---|---|---|
| `--rm-type` | str | – | `pickscore` / `hps` / `hpsv3` / `ocr` / `openai_api` / `custom_api`, or `none` (constant 0, for a loss that reads no reward such as `dmd2`; training rollouts then skip the engine's VAE decode, which needs an engine with `rollout_return_generated_output`, while eval still decodes). Overridable per sample via `metadata.rm_type`. Ignored when `--custom-rm-path` is set. |
| `--rm-type` | str | – | `pickscore` / `hps` / `hpsv3` / `ocr` / `clap` / `openai_api` / `custom_api`, or `none` (constant 0, for a loss that reads no reward such as `dmd2`; training rollouts then skip the engine's VAE decode, which needs an engine with `rollout_return_generated_output`, while eval still decodes). Overridable per sample via `metadata.rm_type`. Ignored when `--custom-rm-path` is set. |
| `--custom-api-rm-config` | str | – | Required for `--rm-type custom_api`: a YAML file or inline `base64:<payload>` with `actor_class`, `actor_kwargs`, `max_concurrency`. A flat mapping configures the default OpenAI-compatible image actor. |
| `--openai-api-rm-config` | str | – | Required for `--rm-type openai_api`; same format as `--custom-api-rm-config`. |
| `--group-rm` | flag | off | Score a whole prompt group at once. |
Expand All @@ -327,6 +327,11 @@ See [Dtype Control](../advanced/dtype-control.md).
| `--hpsv3-reward-colocate` | flag | off | Seats `--hpsv3-num-workers` actors on the rollout GPUs, one per placement-group bundle, sharing them with the train actor and rollout engine. Requires `--colocate`. |
| `--hpsv3-batch-size` | int | `8` | |
| `--hpsv3-checkpoint-path` | str | – | Local `HPSv3.safetensors`; unset downloads from `MizzenAI/HPSv3`. |
| `--clap-num-workers` | int | `1` | |
| `--clap-num-gpus-per-worker` | float | `1.0` | Standalone workers only; fractional values allowed. |
| `--clap-reward-colocate` | flag | off | Seats `--clap-num-workers` actors on the rollout GPUs, one per placement-group bundle, sharing them with the train actor and rollout engine. Requires `--colocate`. |
| `--clap-batch-size` | int | `8` | |
| `--clap-model-path` | str | `laion/larger_clap_general` | CLAP checkpoint (transformers `ClapModel`) for `--rm-type clap`, which scores the rollout's waveform against its prompt. |
| `--ocr-num-workers` | int | `4` | |
| `--rollout-parser-num-workers` | int | `1` | Ray actors deserializing rollout responses. Raise when trajectory tensors are large. |
| `--rollout-fetch-in-parser` | flag | off | Parser actors pick the least-loaded engine through the miles router, then fetch and parse its response in place, skipping the router's data plane and the manager's event loop. Requires `--use-miles-router` and at least as many parser workers as concurrency slots. |
Expand Down
56 changes: 48 additions & 8 deletions docs/user-guide/rewards.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
---
title: Rewards
description: Built-in reward models (PickScore, HPS, HPSv3, OCR, API rewards), rm_hub dispatch, and prompt data format.
description: Built-in reward models (PickScore, HPS, HPSv3, OCR, CLAP, API rewards), rm_hub dispatch, and prompt data format.
---
Miles-diffusion scores generated images (or video frames) after each rollout
Miles-diffusion scores generated images (or video frames, or the soundtrack) after each rollout
microgroup. Reward computation lives in `miles/rollout/rm_hub/` and is invoked
from `sglang_diffusion_rollout.generate_and_rm_microgroup`.

Expand All @@ -13,7 +13,7 @@ For `--custom-rm-path`, `--custom-reward-post-process-path`, and other

| Stage | Flag | Role |
|---|---|---|
| Reward type | `--rm-type` | Selects built-in scorer (`pickscore`, `hps`, `hpsv3`, `ocr`, `openai_api`, `custom_api`), or `none` for a constant 0 when the loss reads no reward (DMD2), which also skips decoding training rollouts; ignored when `--custom-rm-path` is set |
| Reward type | `--rm-type` | Selects built-in scorer (`pickscore`, `hps`, `hpsv3`, `ocr`, `clap`, `openai_api`, `custom_api`), or `none` for a constant 0 when the loss reads no reward (DMD2), which also skips decoding training rollouts; ignored when `--custom-rm-path` is set |
| API reward config | `--openai-api-rm-config`, `--custom-api-rm-config` | YAML file or inline `base64:<payload>` for the two API rewards |
| Per-sample override | `metadata.rm_type` in JSONL | Overrides global `--rm-type` |
| Custom reward / norm | see [Customization](customization.md) | `--custom-rm-path`, `--custom-reward-post-process-path` |
Expand Down Expand Up @@ -141,6 +141,44 @@ Example from `scripts/run_diffusion_grpo_sd3_hpsv3_sglang.py`:
--hpsv3-reward-colocate
```

### CLAP (`--rm-type clap`)

Implementation: `miles/rollout/rm_hub/clap.py`.

[CLAP](https://github.com/LAION-AI/CLAP) scores how well a rollout's **soundtrack** matches its prompt, for
models that return a waveform with the video (LTX audio-video, MiniMax H3 t2va). The other built-in rewards
only see frames; mixed with one of them (see [Combining rewards](#combining-rewards)) it gives the audio
stream a reward of its own.

- Model: `--clap-model-path`, a transformers `ClapModel` checkpoint (default `laion/larger_clap_general`)

Scoring formula:

```
score = cos(text_emb, audio_emb) # in [-1, 1]
```

The waveform is averaged to mono and resampled to the model's 48 kHz. A clip longer than the model's 10 s
window is scored on evenly spaced windows that cover it, averaged; CLAP's own handling of a long clip is a
random crop, which would make a sample's reward change from call to call. The prompt is cut at 77 tokens,
the length CLAP's text tower was trained with. A sample without a waveform is an error (its pool requires `audio`), so the reward
cannot be used with a model that returns no audio. `tests/fast-gpu/test_clap_scorer.py` runs the real checkpoints.

| Flag | Default | Description |
|---|---|---|
| `--clap-num-workers` | 1 | Ray actor count |
| `--clap-num-gpus-per-worker` | 1.0 | GPU per worker (non-colocate) |
| `--clap-batch-size` | 8 | Batch size per actor call |
| `--clap-model-path` | `laion/larger_clap_general` | Hugging Face repo or local path of the CLAP checkpoint |
| `--clap-reward-colocate` | False | Seat the `--clap-num-workers` actors on rollout GPUs, one per placement-group bundle (requires `--colocate`) |

Example, PickScore on the frames plus CLAP on the soundtrack:

```bash
--custom-rm-path miles.rollout.rm_hub.weighted_mixture_rm.weighted_mixture_rm \
--custom-rm-args "pickscore=1.0,clap=1.0" --reward-key weighted
```

### Reward placement

Every GPU reward pool is placed one of two ways:
Expand All @@ -161,7 +199,7 @@ built on first use.
directly; `--custom-rm-args` is an opaque string the framework hands to that function
through `args`, so the function owns its own config grammar. The shipped example
`miles/rollout/rm_hub/weighted_mixture_rm.py` reads `name=weight,name=weight`, with names
from `hps`, `hpsv3`, `pickscore`, `ocr`, `custom_api`, `openai_api`:
from `hps`, `hpsv3`, `pickscore`, `ocr`, `clap`, `custom_api`, `openai_api`:

```bash
--custom-rm-path miles.rollout.rm_hub.weighted_mixture_rm.weighted_mixture_rm \
Expand All @@ -176,12 +214,12 @@ The example returns a dict per sample (`{"hps": ..., "pickscore": ..., "weighted
`rollout/reward/<name>_mean` panel, so the components stay visible while the sum is optimized.

Weights apply to raw scores (HPSv2.1 ≈ 0.25–0.35, HPSv3 μ unbounded and roughly −10 to +16,
PickScore/26 ≈ 0.8–0.9, OCR ∈ [0, 1], default OpenAI API rubric ∈ [0, 4]), so pick them with the
PickScore/26 ≈ 0.8–0.9, OCR ∈ [0, 1], CLAP cosine ∈ [−1, 1], default OpenAI API rubric ∈ [0, 4]), so pick them with the
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 each sample's `GeneratedMedia` (see § 3), and every reward actor
quantises its `visual` to uint8 on its own terms.
quantises its `visual` to uint8 on its own terms; CLAP scores its `audio` instead.

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 @@ -250,10 +288,11 @@ generate_and_rm_microgroup()
→ all pickscore? pickscore_rm (batched)
→ all hps? hps_rm (batched)
→ all hpsv3? hpsv3_rm (batched)
→ all clap? clap_rm (batched, scores the waveform)
→ all ocr? ocr_rm (batched, one image per actor call)
→ all custom_api? custom_api_rm (batched, one request per actor call)
→ all openai_api? openai_api_rm (batched, one request per actor call)
→ else per-sample async_rm → ocr / pickscore / hps / hpsv3 / custom_api / openai_api / NotImplementedError
→ else per-sample async_rm → ocr / pickscore / hps / hpsv3 / clap / custom_api / openai_api / NotImplementedError
→ sample.reward = score

# after the rollout, in the RolloutManager Ray actor:
Expand All @@ -263,7 +302,8 @@ RolloutManager._convert_samples_to_train_data()

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
class declares `required_media`, e.g. `frozenset({"visual"})` for the image rewards and
`frozenset({"audio"})` for CLAP; 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.

Expand Down
12 changes: 12 additions & 0 deletions miles/rollout/rm_hub/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ async def async_rm(args, sample: Sample, **kwargs):
from .hpsv3 import hpsv3_rm

return (await hpsv3_rm(args, [sample]))[0]
elif rm_type == "clap":
from .clap import clap_rm

return (await clap_rm(args, [sample]))[0]
elif rm_type == "custom_api":
from .api import custom_api_rm

Expand Down Expand Up @@ -57,6 +61,10 @@ def create_colocated_reward_pools(args, placement_group, slots) -> list:
from .hpsv3 import AsyncHPSv3Pool

pools.append(AsyncHPSv3Pool(args, placement_group=placement_group, slots=slots))
if args.clap_reward_colocate:
from .clap import AsyncClapPool

pools.append(AsyncClapPool(args, placement_group=placement_group, slots=slots))
return pools


Expand Down Expand Up @@ -85,6 +93,10 @@ async def batched_async_rm(
from .hpsv3 import hpsv3_rm

return await hpsv3_rm(args, samples)
if all(rm_type == "clap" for rm_type in rm_types):
from .clap import clap_rm

return await clap_rm(args, samples)
if all(rm_type == "ocr" for rm_type in rm_types):
from .ocr import ocr_rm

Expand Down
139 changes: 139 additions & 0 deletions miles/rollout/rm_hub/clap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
"""CLAP reward: text-audio similarity for rollouts that return a waveform (LTX audio-video, H3 t2va).

The score is the cosine similarity between CLAP's prompt and audio embeddings, the usual "CLAP score". It is
the audio counterpart of PickScore: the video rewards only see frames, so with them alone the audio stream's
advantage comes from the picture.
"""

from __future__ import annotations

import math
from collections.abc import Sequence

import numpy as np
import ray
import torch
import torchaudio

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

from .core import AsyncRewardActorPool, record_reward_queue_depth

# CLAP's text tower was trained on captions cut at 77 tokens (laion_clap's tokenizer call).
_MAX_TEXT_TOKENS = 77


def waveform_to_mono(waveform: torch.Tensor, sample_rate: int, target_sample_rate: int) -> torch.Tensor:
"""A ``[C, L]`` (or ``[L]``) waveform as mono float32 ``[L']`` at ``target_sample_rate``."""
if waveform.ndim not in (1, 2):
raise ValueError(f"a waveform is [C, L] or [L], got shape {tuple(waveform.shape)}")
mono = waveform.float().reshape(-1, waveform.shape[-1]).mean(dim=0)
if sample_rate != target_sample_rate:
mono = torchaudio.functional.resample(mono, sample_rate, target_sample_rate)
return mono


def split_windows(mono: torch.Tensor, window_samples: int) -> list[torch.Tensor]:
"""The clip itself when it fits one model window, else evenly spaced full windows that cover it.

CLAP's own handling of a longer clip is a random crop, which would make the reward of a sample depend on
the draw; every window given to the model here fits, so nothing is cropped.
"""
length = mono.shape[0]
if length <= window_samples:
return [mono]
num_windows = math.ceil(length / window_samples)
starts = np.linspace(0, length - window_samples, num_windows).round().astype(int)
return [mono[start : start + window_samples] for start in starts]


class ClapScorer(torch.nn.Module):
"""CLAP cosine similarity for (prompt, waveform window) pairs, in [-1, 1]."""

def __init__(self, *, device: str = "cuda", model_path: str) -> None:
super().__init__()
from transformers import ClapModel, ClapProcessor

self.device = torch.device(device)
processor = ClapProcessor.from_pretrained(model_path)
self.tokenizer = processor.tokenizer
self.feature_extractor = processor.feature_extractor
self.model = ClapModel.from_pretrained(model_path).eval().to(device=self.device, dtype=torch.float32)
self.sample_rate: int = self.feature_extractor.sampling_rate
self.window_samples: int = self.feature_extractor.nb_max_samples

@torch.no_grad()
def forward(self, prompts: Sequence[str], windows: Sequence[torch.Tensor]) -> list[float]:
"""``windows`` are mono waveforms at ``sample_rate``, each at most ``window_samples`` long."""
audio_inputs = self.feature_extractor(
[window.numpy() for window in windows], sampling_rate=self.sample_rate, return_tensors="pt"
)
if "is_longer" in audio_inputs:
# A fusion checkpoint's extractor marks one random clip of a batch of short clips as longer, and the
# model then fuses that clip's (identical) crops; no window here is longer, so none is marked.
audio_inputs["is_longer"] = torch.zeros_like(audio_inputs["is_longer"])
text_inputs = self.tokenizer(
list(prompts), padding=True, truncation=True, max_length=_MAX_TEXT_TOKENS, return_tensors="pt"
)
inputs = {k: v.to(self.device) for k, v in (audio_inputs | text_inputs).items()}
outputs = self.model(**inputs)
# both come out of the model L2-normalized
scores = (outputs.text_embeds * outputs.audio_embeds).sum(dim=-1)
return [float(score) for score in scores.float().cpu()]


class ClapRewardActor:
required_media = frozenset({"audio"})

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

def score_batch(self, outputs: list[GeneratedMedia], prompts: list[str]) -> list[float]:
# a clip longer than the model's window is scored on windows that cover it, averaged
windows, window_counts = [], []
for output in outputs:
mono = waveform_to_mono(output.audio, output.audio_sample_rate, self.scorer.sample_rate)
clip_windows = split_windows(mono, self.scorer.window_samples)
windows.extend(clip_windows)
window_counts.append(len(clip_windows))
flat_prompts = [p for p, n in zip(prompts, window_counts, strict=True) for _ in range(n)]
flat_scores = []
for start in range(0, len(windows), self.windows_per_forward):
end = start + self.windows_per_forward
flat_scores.extend(self.scorer(flat_prompts[start:end], windows[start:end]))
scores, offset = [], 0
for count in window_counts:
scores.append(float(sum(flat_scores[offset : offset + count]) / count))
offset += count
return scores


class AsyncClapPool(AsyncRewardActorPool, metaclass=SingletonMeta):
"""Ray actor pool for CLAP reward inference."""

def __init__(self, args, placement_group=None, slots=None) -> None:
super().__init__(
args=args,
actor_cls=ClapRewardActor,
actor_kwargs={"model_path": args.clap_model_path, "windows_per_forward": args.clap_batch_size},
num_workers=args.clap_num_workers,
batch_size=args.clap_batch_size,
num_gpus_per_worker=args.clap_num_gpus_per_worker,
colocate=args.clap_reward_colocate,
name="clap",
placement_group=placement_group,
slots=slots,
)


async def clap_rm(args, samples: Sequence[Sample]) -> list[float]:
pool = AsyncClapPool(args)
# the pool refuses a sample without a waveform, so a model that returns no audio fails here
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, "clap", max_queue_depth)
return scores
4 changes: 3 additions & 1 deletion miles/rollout/rm_hub/weighted_mixture_rm.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
on. Each named reward scores the whole batch once. Local rewards keep their own placement flags
(``--<rm>-reward-colocate``, ``--<rm>-num-gpus-per-worker``). Weights apply to raw scores,
whose scales differ: HPSv2.1 ~0.3, HPSv3 mu unbounded (roughly -10..16), PickScore/26 ~0.85, OCR in [0, 1],
default OpenAI API rubric in [0, 4].
CLAP cosine in [-1, 1], default OpenAI API rubric in [0, 4].
API rewards use their YAML settings and do not consume local GPU reward slots.
"""

Expand All @@ -23,6 +23,7 @@
from miles.utils.types import Sample

from .api import custom_api_rm
from .clap import clap_rm
from .hps import hps_rm
from .hpsv3 import hpsv3_rm
from .ocr import ocr_rm
Expand All @@ -34,6 +35,7 @@
"hpsv3": hpsv3_rm,
"pickscore": pickscore_rm,
"ocr": ocr_rm,
"clap": clap_rm,
"custom_api": custom_api_rm,
"openai_api": openai_api_rm,
}
Expand Down
Loading