From 7125ad94e8758bcc4eac42ab7b27db30bec49c9b Mon Sep 17 00:00:00 2001 From: Ruilin Gao Date: Wed, 25 Nov 2026 03:45:52 -0500 Subject: [PATCH] feat(rm): add CLAP as a built-in reward that scores the soundtrack (--rm-type clap) --- docs/user-guide/cli-reference.md | 7 +- docs/user-guide/rewards.md | 56 ++++- miles/rollout/rm_hub/__init__.py | 12 ++ miles/rollout/rm_hub/clap.py | 139 ++++++++++++ miles/rollout/rm_hub/weighted_mixture_rm.py | 4 +- miles/utils/arguments.py | 40 +++- tests/fast-gpu/test_clap_scorer.py | 82 +++++++ tests/fast/rollout/test_clap_reward.py | 223 ++++++++++++++++++++ 8 files changed, 552 insertions(+), 11 deletions(-) create mode 100644 miles/rollout/rm_hub/clap.py create mode 100644 tests/fast-gpu/test_clap_scorer.py create mode 100644 tests/fast/rollout/test_clap_reward.py diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md index e84db4693..6133867de 100644 --- a/docs/user-guide/cli-reference.md +++ b/docs/user-guide/cli-reference.md @@ -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:` 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. | @@ -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. | diff --git a/docs/user-guide/rewards.md b/docs/user-guide/rewards.md index 064e7cbfb..57118a0e6 100644 --- a/docs/user-guide/rewards.md +++ b/docs/user-guide/rewards.md @@ -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`. @@ -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:` 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` | @@ -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: @@ -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 \ @@ -176,12 +214,12 @@ The example returns a dict per sample (`{"hps": ..., "pickscore": ..., "weighted `rollout/reward/_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 @@ -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: @@ -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. diff --git a/miles/rollout/rm_hub/__init__.py b/miles/rollout/rm_hub/__init__.py index a52ef7f54..e637f03ea 100644 --- a/miles/rollout/rm_hub/__init__.py +++ b/miles/rollout/rm_hub/__init__.py @@ -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 @@ -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 @@ -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 diff --git a/miles/rollout/rm_hub/clap.py b/miles/rollout/rm_hub/clap.py new file mode 100644 index 000000000..a34f4bcc8 --- /dev/null +++ b/miles/rollout/rm_hub/clap.py @@ -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 diff --git a/miles/rollout/rm_hub/weighted_mixture_rm.py b/miles/rollout/rm_hub/weighted_mixture_rm.py index cd682461d..a707fbad3 100644 --- a/miles/rollout/rm_hub/weighted_mixture_rm.py +++ b/miles/rollout/rm_hub/weighted_mixture_rm.py @@ -13,7 +13,7 @@ on. Each named reward scores the whole batch once. Local rewards keep their own placement flags (``---reward-colocate``, ``---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. """ @@ -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 @@ -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, } diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index eb48351e9..516a450d5 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -1544,7 +1544,7 @@ def add_reward_model_arguments(parser): "--rm-type", type=str, default=None, - help="Built-in reward (pickscore / hps / hpsv3 / ocr / openai_api), custom_api for a configurable actor, " + help="Built-in reward (pickscore / hps / hpsv3 / ocr / clap / openai_api), custom_api for a configurable actor, " "or none for a constant 0 when the loss reads no reward; none also has the engine skip decoding " "training rollouts, whose media nothing reads. Ignored when --custom-rm-path is set.", ) @@ -1721,6 +1721,37 @@ def add_reward_model_arguments(parser): default=None, help="Optional local HPSv3.safetensors; otherwise download it from MizzenAI/HPSv3.", ) + parser.add_argument( + "--clap-num-workers", + type=int, + default=1, + help="Number of Ray CLAP actors used when --rm-type clap.", + ) + parser.add_argument( + "--clap-num-gpus-per-worker", + type=float, + default=1.0, + help="GPU resources per CLAP actor when reward is not colocated. " + "Use a fractional value below 1.0 to share a GPU with other reward models.", + ) + parser.add_argument( + "--clap-reward-colocate", + action="store_true", + default=False, + help="Seat CLAP actors on the rollout GPUs, one per placement-group bundle. Requires --colocate.", + ) + parser.add_argument( + "--clap-batch-size", + type=int, + default=8, + help="Batch size per CLAP actor call.", + ) + parser.add_argument( + "--clap-model-path", + type=str, + default="laion/larger_clap_general", + help="CLAP checkpoint (transformers ClapModel) for --rm-type clap: a Hugging Face repo or a local path.", + ) parser.add_argument( "--rm-url", @@ -2452,6 +2483,12 @@ def miles_validate_args(args): raise ValueError(f"--hpsv3-batch-size must be positive, got {args.hpsv3_batch_size}") if args.hpsv3_num_gpus_per_worker < 0: raise ValueError(f"--hpsv3-num-gpus-per-worker must be non-negative, got {args.hpsv3_num_gpus_per_worker}") + if args.clap_num_workers <= 0: + raise ValueError(f"--clap-num-workers must be positive, got {args.clap_num_workers}") + if args.clap_batch_size <= 0: + raise ValueError(f"--clap-batch-size must be positive, got {args.clap_batch_size}") + if args.clap_num_gpus_per_worker < 0: + raise ValueError(f"--clap-num-gpus-per-worker must be non-negative, got {args.clap_num_gpus_per_worker}") colocated_reward_workers = { name: num_workers @@ -2459,6 +2496,7 @@ def miles_validate_args(args): ("pickscore", args.pickscore_reward_colocate, args.pickscore_num_workers), ("hps", args.hps_reward_colocate, args.hps_num_workers), ("hpsv3", args.hpsv3_reward_colocate, args.hpsv3_num_workers), + ("clap", args.clap_reward_colocate, args.clap_num_workers), ) if colocate } diff --git a/tests/fast-gpu/test_clap_scorer.py b/tests/fast-gpu/test_clap_scorer.py new file mode 100644 index 000000000..48543ebe8 --- /dev/null +++ b/tests/fast-gpu/test_clap_scorer.py @@ -0,0 +1,82 @@ +"""The CLAP reward on the real checkpoints: it tells sounds apart, and a clip's score is its own. + +Clips are synthesized here (white noise, a 440 Hz tone), so the test needs no audio files. + +Covered, for an unfused and a fusion checkpoint: each caption scores its own clip above the other (1); a clip +scores the same alone as in a batch, which the fusion extractor's random "longer" mark would break (2); a clip +longer than the 10 s window scores the same on every call, where CLAP's random crop would not (3). +""" + +from tests.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=120, + suite="stage-b-3-gpu-h200", + labels=[], +) + +import sys + +import pytest +import torch + +from miles.rollout.rm_hub.clap import ClapRewardActor, ClapScorer +from miles.utils.types import GeneratedMedia + +_SAMPLE_RATE = 44_100 +_NOISE_CAPTION = "white noise static hiss" +_TONE_CAPTION = "a steady pure sine tone beep" + + +def _clips(seconds: float) -> tuple[torch.Tensor, torch.Tensor]: + generator = torch.Generator().manual_seed(0) + t = torch.arange(int(_SAMPLE_RATE * seconds)) / _SAMPLE_RATE + noise = torch.randn(2, len(t), generator=generator) * 0.2 + tone = (torch.sin(2 * torch.pi * 440 * t) * 0.5).repeat(2, 1) + return noise, tone + + +@pytest.fixture(scope="module", params=["laion/larger_clap_general", "laion/clap-htsat-fused"]) +def actor(request) -> ClapRewardActor: + actor = ClapRewardActor.__new__(ClapRewardActor) + actor.scorer = ClapScorer(device="cuda" if torch.cuda.is_available() else "cpu", model_path=request.param) + actor.windows_per_forward = 8 + return actor + + +def _score(actor: ClapRewardActor, clips: list[torch.Tensor], captions: list[str]) -> list[float]: + outputs = [GeneratedMedia(audio=clip, audio_sample_rate=_SAMPLE_RATE) for clip in clips] + return actor.score_batch(outputs, captions) + + +def test_each_caption_prefers_its_own_clip(actor): + noise, tone = _clips(seconds=4) + + noise_caption = _score(actor, [noise, tone], [_NOISE_CAPTION] * 2) + tone_caption = _score(actor, [noise, tone], [_TONE_CAPTION] * 2) + + assert noise_caption[0] > noise_caption[1] + 0.1 + assert tone_caption[1] > tone_caption[0] + 0.1 + + +def test_a_clip_scores_the_same_alone_and_in_a_batch(actor): + noise, tone = _clips(seconds=4) + + batched = _score(actor, [noise, tone], [_NOISE_CAPTION, _TONE_CAPTION]) + alone = _score(actor, [noise], [_NOISE_CAPTION]) + _score(actor, [tone], [_TONE_CAPTION]) + + torch.testing.assert_close(torch.tensor(batched), torch.tensor(alone), rtol=0, atol=1e-5) + + +def test_a_long_clip_scores_the_same_on_every_call(actor): + noise, tone = _clips(seconds=12.5) + long_clip = torch.cat([noise, tone], dim=1) + + first = _score(actor, [long_clip], [_NOISE_CAPTION]) + second = _score(actor, [long_clip], [_NOISE_CAPTION]) + + assert first == second + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-v"])) diff --git a/tests/fast/rollout/test_clap_reward.py b/tests/fast/rollout/test_clap_reward.py new file mode 100644 index 000000000..73685edf4 --- /dev/null +++ b/tests/fast/rollout/test_clap_reward.py @@ -0,0 +1,223 @@ +"""CLAP reward plumbing that does not need the checkpoint; the real model is tests/fast-gpu/test_clap_scorer.py. + +Mental model (one audio-video sample, 48 kHz model, 10 s window): + + sample.generated_media (audio [C, L] at audio_sample_rate) a StoredTensor with the output store on + -> clap_rm : one GeneratedMedia + prompt per sample to the pool + -> AsyncRewardActorPool : requires audio, sends no video + -> ClapRewardActor.score_batch : mono -> 48 kHz -> windows that cover the clip -> mean over windows + -> ClapScorer : cosine(text embedding, audio embedding) + +Covered: channels are averaged and the clip resampled to the model's rate (1); a clip that fits the window is +scored whole, a longer one on evenly spaced full windows from its start to its end (2); the actor scores each +window with its clip's prompt at the clip's own sample rate and averages them per clip (3); the scorer marks no +window as longer and cuts the prompt at 77 tokens (4); clap_rm hands each sample's media and prompt to its pool +and records its backlog (5); the CLAP pool refuses a sample without a waveform and sends the actor no video (6); +batched_async_rm takes the clap fast path (7); weighted_mixture_rm accepts clap (8); an audio-video command line +parses with the CLAP defaults (9), and colocated CLAP workers are checked like the other pools' (10). +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=[]) + +import shlex +import sys +from argparse import Namespace +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest +import torch + +import miles.rollout.rm_hub.clap as clap_module +import miles.rollout.rm_hub.core as core_module +from miles.rollout.rm_hub import batched_async_rm +from miles.rollout.rm_hub.clap import ClapRewardActor, ClapScorer, split_windows, waveform_to_mono +from miles.rollout.rm_hub.core import AsyncRewardActorPool +from miles.rollout.rm_hub.weighted_mixture_rm import parse_weights +from miles.utils.types import GeneratedMedia, Sample + +_STEREO = torch.stack([torch.ones(24_000), -torch.ones(24_000) * 0.5]) + + +def _actor_with(scorer, *, windows_per_forward: int = 8) -> ClapRewardActor: + actor = ClapRewardActor.__new__(ClapRewardActor) + actor.scorer = scorer + actor.windows_per_forward = windows_per_forward + return actor + + +def test_channels_are_averaged_and_the_clip_resampled(): + """CLAP takes one channel at its own rate; a clip fed at another rate is heard at the wrong pitch.""" + mono = waveform_to_mono(_STEREO, 24_000, 48_000) + + assert mono.shape == (48_000,) + # a constant signal stays constant away from the resampling filter's edges + assert torch.allclose(mono[1_000:-1_000], torch.full((46_000,), 0.25), atol=1e-3) + assert torch.equal(waveform_to_mono(_STEREO[0], 48_000, 48_000), _STEREO[0]) + with pytest.raises(ValueError, match=r"\[C, L\] or \[L\]"): + waveform_to_mono(torch.zeros(1, 2, 8), 48_000, 48_000) + + +def test_a_long_clip_is_covered_by_full_windows(): + """CLAP crops a longer clip at random, so its reward would change from call to call.""" + short = torch.arange(7.0) + long = torch.arange(25.0) + + assert [w.tolist() for w in split_windows(short, 10)] == [short.tolist()] + assert [w.tolist() for w in split_windows(torch.arange(10.0), 10)] == [list(range(10))] + windows = split_windows(long, 10) + assert [(int(w[0]), int(w[-1])) for w in windows] == [(0, 9), (8, 17), (15, 24)] + + +def test_actor_scores_each_window_with_its_prompt_and_averages_per_clip(): + """A clip of several windows must get one reward, and forwards stay within --clap-batch-size.""" + forwards = [] + + def scorer(prompts, windows): + forwards.append([(prompt, len(window)) for prompt, window in zip(prompts, windows, strict=True)]) + return [float(window[0]) for window in windows] + + scorer.sample_rate, scorer.window_samples = 10, 10 + actor = _actor_with(scorer, windows_per_forward=2) + # each clip is heard at its own rate: 3 samples at 5 Hz are 6 at the model's 10 Hz + half_rate = GeneratedMedia(audio=torch.zeros(1, 3), audio_sample_rate=5) + three_windows = GeneratedMedia(audio=torch.arange(25.0).reshape(1, 25), audio_sample_rate=10) + + scores = actor.score_batch([half_rate, three_windows], ["rain", "dog"]) + + # the long clip's windows start at samples 0, 8 and 15 + assert scores == [0.0, pytest.approx((0 + 8 + 15) / 3)] + assert forwards == [[("rain", 6), ("dog", 10)], [("dog", 10), ("dog", 10)]] + + +def test_scorer_marks_no_window_as_longer_and_cuts_the_prompt(): + """A fusion checkpoint's extractor marks a random clip of the batch as longer, which changes its embedding.""" + calls = {} + + def feature_extractor(waveforms, *, sampling_rate, return_tensors): + calls["audio"] = (len(waveforms), sampling_rate) + return {"input_features": torch.zeros(2, 1), "is_longer": torch.tensor([[False], [True]])} + + def tokenizer(prompts, **kwargs): + calls["text"] = kwargs + return {"input_ids": torch.zeros(2, 1, dtype=torch.long)} + + def model(**inputs): + calls["is_longer"] = inputs["is_longer"] + text = torch.tensor([[1.0, 0.0], [0.0, 1.0]]) + audio = torch.tensor([[0.6, 0.8], [0.0, 1.0]]) + return SimpleNamespace(text_embeds=text, audio_embeds=audio) + + scorer = ClapScorer.__new__(ClapScorer) + torch.nn.Module.__init__(scorer) + scorer.device, scorer.sample_rate = torch.device("cpu"), 48_000 + scorer.feature_extractor, scorer.tokenizer, scorer.model = feature_extractor, tokenizer, model + + scores = scorer(["rain", "dog"], [torch.zeros(4), torch.zeros(4)]) + + assert scores == pytest.approx([0.6, 1.0]) + assert not calls["is_longer"].any() + assert calls["audio"] == (2, 48_000) + assert calls["text"]["truncation"] is True and calls["text"]["max_length"] == 77 + + +@pytest.mark.asyncio +async def test_clap_rm_hands_each_samples_media_and_prompt_to_its_pool(monkeypatch): + pool = AsyncMock() + pool.score.return_value = ([0.4], 3) + monkeypatch.setattr(clap_module, "AsyncClapPool", lambda args: pool) + sample = Sample(prompt="rain on a tin roof", generated_audio=_STEREO, audio_sample_rate=24_000) + + assert await clap_module.clap_rm(Namespace(), [sample]) == [0.4] + ((output,), prompts), _ = pool.score.await_args + assert output.audio is _STEREO and output.audio_sample_rate == 24_000 + assert prompts == ["rain on a tin roof"] + assert sample.reward_max_queue_depth == {"clap": 3.0} + + +@pytest.mark.asyncio +async def test_the_clap_pool_refuses_silence_and_sends_no_video(monkeypatch): + """Scoring a sample without audio would train on a constant; sending the video would move it for nothing.""" + ray_actor = Mock() + ray_actor.score_batch.remote.side_effect = lambda outputs, prompts: [0.0] * len(outputs) + ray_actor_cls = Mock() + ray_actor_cls.options.return_value.remote.return_value = ray_actor + monkeypatch.setattr(core_module.ray, "remote", lambda actor_cls: ray_actor_cls) + monkeypatch.setattr(core_module.ray, "get", lambda refs: refs) + pool = AsyncRewardActorPool( + args=Namespace(use_output_store=False), + actor_cls=ClapRewardActor, + actor_kwargs={}, + num_workers=1, + batch_size=8, + num_gpus_per_worker=0, + colocate=False, + name="clap", + ) + video = torch.zeros(3, 2, 4, 4) + + with pytest.raises(ValueError, match="the clap reward requires audio"): + await pool.score([Sample(generated_output=video).generated_media], ["a"]) + ray_actor.score_batch.remote.assert_not_called() + + audio_video = Sample(generated_output=video, generated_audio=_STEREO, audio_sample_rate=24_000) + await pool.score([audio_video.generated_media], ["a"]) + ((sent,), _), _ = ray_actor.score_batch.remote.call_args + assert sent.visual is None and sent.audio is _STEREO and sent.audio_sample_rate == 24_000 + + +@pytest.mark.asyncio +async def test_batched_async_rm_uses_clap_batch_fast_path(monkeypatch): + clap_rm = AsyncMock(return_value=[0.3, 0.1]) + monkeypatch.setattr(clap_module, "clap_rm", clap_rm) + args = Namespace(custom_rm_path=None, rm_type="clap") + samples = [Sample(index=3), Sample(index=1)] + + assert await batched_async_rm(args, samples) == [0.3, 0.1] + clap_rm.assert_awaited_once_with(args, samples) + + +def test_weighted_mixture_accepts_clap(): + assert parse_weights("pickscore=0.5,clap=0.5") == [("pickscore", 0.5), ("clap", 0.5)] + + +def _parse(monkeypatch, reward_args: str) -> Namespace: + from miles.backends.fsdp_utils.arguments import load_fsdp_args + from miles.utils.arguments import get_miles_extra_args_provider, miles_validate_args, set_default_diffusion_args + + argv = ( + "test --hf-checkpoint Lightricks/LTX-2.3 --diffusion-task t2v --prompt-data prompts.jsonl " + "--rollout-batch-size 2 --n-samples-per-prompt 2 --global-batch-size 4 --num-rollout 1 " + "--actor-num-gpus-per-node 2 --rollout-num-gpus 2 --rollout-num-gpus-per-engine 1 " + "--micro-batch-size 1 --rollout-function-path miles.rollout.sglang_diffusion_rollout.generate_rollout " + "--diffusion-sde-type cps --diffusion-guidance-scale 1.0 " + f"--rollout-extra-streams audio --rollout-patch-group ltx_av --rm-type clap {reward_args}" + ) + monkeypatch.setattr(sys, "argv", shlex.split(argv)) + args = load_fsdp_args(extra_args_provider=get_miles_extra_args_provider()) + set_default_diffusion_args(args) + miles_validate_args(args) + return args + + +def test_an_audio_video_command_line_parses_with_the_clap_defaults(monkeypatch): + args = _parse(monkeypatch, "") + + assert args.clap_model_path == "laion/larger_clap_general" + assert (args.clap_num_workers, args.clap_batch_size, args.clap_reward_colocate) == (1, 8, False) + + +@pytest.mark.parametrize( + "reward_args, message", + [ + ("--clap-num-workers 0", "--clap-num-workers must be positive"), + ("--clap-reward-colocate", "--clap-reward-colocate requires --colocate"), + ("--colocate --clap-reward-colocate --clap-num-workers 3", r"workers \(3\) exceed rollout_num_gpus \(2\)"), + ], +) +def test_clap_workers_are_checked_like_the_other_pools(monkeypatch, reward_args, message): + """A colocated pool the slot check does not count would take a GPU slot another reward was given.""" + with pytest.raises(ValueError, match=message): + _parse(monkeypatch, reward_args)