diff --git a/docs/user-guide/rewards.md b/docs/user-guide/rewards.md index 064e7cbfb..fd5897cf6 100644 --- a/docs/user-guide/rewards.md +++ b/docs/user-guide/rewards.md @@ -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`, `openai_api`, `custom_api`, `videoalign`), 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,66 @@ Example from `scripts/run_diffusion_grpo_sd3_hpsv3_sglang.py`: --hpsv3-reward-colocate ``` +### VideoAlign (`--rm-type videoalign`) + +Implementation: `miles/rollout/rm_hub/videoalign.py`. + +VideoAlign / [VideoReward](https://github.com/KwaiVGI/VideoAlign) scores a whole generated video against its prompt with a Qwen2-VL-2B-Instruct fine-tuned as a preference model: + +- Model: `Qwen/Qwen2-VL-2B-Instruct` + a linear `rm_head` read at three added reward tokens `<|VQ_reward|>` / `<|MQ_reward|>` / `<|TA_reward|>` +- Checkpoint: `--videoalign-checkpoint-path` (optional; defaults to `KwaiVGI/VideoReward`, downloaded on first use) + +One forward returns three raw scores — Visual Quality, Motion Quality, Text Alignment. With the +published `KwaiVGI/VideoReward` normalisation constants (`--videoalign-no-normalize` turns it off), each sample's +reward is a dict: + +``` +{"vq": ..., "mq": ..., "ta": ..., "overall": vq + mq + ta} +``` + +`--reward-key` picks the entry GRPO trains on (e.g. `--reward-key overall`, or `--reward-key ta` for +text-alignment only); every key also gets its own `rollout/reward/_mean` panel. The actor scores +`--videoalign-num-frames` evenly spaced frames per video (None = every frame). + +| Flag | Default | Description | +|---|---|---| +| `--videoalign-num-workers` | 1 | Ray actor count | +| `--videoalign-num-gpus-per-worker` | 1.0 | GPU per worker (non-colocate) | +| `--videoalign-batch-size` | 4 | Batch size per actor call | +| `--videoalign-checkpoint-path` | None | `KwaiVGI/VideoReward` repo id or local dir with `checkpoint-11352/model.pth` | +| `--videoalign-model-path` | None | Qwen2-VL-2B base model (defaults to `Qwen/Qwen2-VL-2B-Instruct`) | +| `--videoalign-num-frames` | None | Evenly spaced frames scored per video (None = every frame) | +| `--videoalign-max-pixels` | 200704 | Max pixels per frame for the visual encoder | +| `--videoalign-no-normalize` | False | Return raw VQ/MQ/TA instead of the checkpoint's normalisation | +| `--videoalign-reward-colocate` | False | Seat actors on rollout GPUs, one per placement-group bundle (requires `--colocate`) | + +#### LTX-2.3 Flow-GRPO smoke recipe + +`scripts/run_diffusion_grpo_ltx23_videoalign_sglang.py` keeps the existing LTX-2.3 +PickScore recipe's generator and optimizer settings, but selects VideoAlign: + +- Four colocated train/rollout GPUs plus one dedicated reward GPU. +- Text-only prompts from `rockdu/miles-diffusion-datasets`, `flowgrpo_pickscore/train.jsonl`. +- 8 prompts × 8 samples = 64 videos per rollout, at 768×512, 57 frames, 24 FPS and 24 denoising steps. +- VideoAlign jointly scores 8 uniformly sampled frames, batch size 4. +- `--reward-key overall` optimizes the sum of normalized VQ, MQ and TA. +- Defaults to two rollouts (128 videos); this is an integration test configuration, not a verified training curve. + +A local two-rollout run completes end-to-end: both rollouts return finite `overall` +rewards (raw mean ≈ -3.54 / -3.64; early LTX-2.3 videos score negatively on temporal/ +text alignment), four optimizer steps execute, and checkpoints are written. Training +metrics match the registered LTX-2.3 PickScore e2e: `log_prob_new_idx_0` / `log_prob_old_idx_0` +agree to ~5-6 decimal places and `grad_norm` stays in the baseline ~1e-5 range. Two +rollouts are not enough to show reward improvement; treat this as a reward-integration +smoke gate, not a convergence curve. + +The GPU alignment tests compare input IDs, video grids, pixel hashes and bf16 scores +against upstream revision `219ab9db64c045e5181a2202d11f686439351292`, including a padded batch. +They do not establish fp32 parity, training convergence or output-store integration. + +Like other example scripts, the launcher uses `execute_train`, which performs machine-wide +process cleanup. Run it only on a dedicated allocation; do not use it unchanged on a shared host. + ### Reward placement Every GPU reward pool is placed one of two ways: diff --git a/miles/rollout/rm_hub/__init__.py b/miles/rollout/rm_hub/__init__.py index a52ef7f54..413d5c50e 100644 --- a/miles/rollout/rm_hub/__init__.py +++ b/miles/rollout/rm_hub/__init__.py @@ -38,6 +38,10 @@ async def async_rm(args, sample: Sample, **kwargs): from .openai_api import openai_api_rm return (await openai_api_rm(args, [sample]))[0] + elif rm_type == "videoalign": + from .videoalign import videoalign_rm + + return (await videoalign_rm(args, [sample]))[0] else: raise NotImplementedError(f"Rule-based RM for {rm_type!r} is not implemented.") @@ -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.videoalign_reward_colocate: + from .videoalign import AsyncVideoAlignPool + + pools.append(AsyncVideoAlignPool(args, placement_group=placement_group, slots=slots)) return pools @@ -97,6 +105,10 @@ async def batched_async_rm( from .openai_api import openai_api_rm return await openai_api_rm(args, samples) + if all(rm_type == "videoalign" for rm_type in rm_types): + from .videoalign import videoalign_rm + + return await videoalign_rm(args, samples) tasks = [async_rm(args, sample, **kwargs) for sample in samples] rewards = await asyncio.gather(*tasks) diff --git a/miles/rollout/rm_hub/core.py b/miles/rollout/rm_hub/core.py index 068c25cf3..5bafde4ac 100644 --- a/miles/rollout/rm_hub/core.py +++ b/miles/rollout/rm_hub/core.py @@ -93,7 +93,7 @@ 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[GeneratedMedia], prompts: list[str]) -> list[float]: + def score_batch(self, outputs: list[GeneratedMedia], prompts: list[str]) -> list[float | dict[str, float]]: # eval outputs arrive inline stored_visuals = [output.visual for output in outputs if isinstance(output.visual, StoredTensor)] if stored_visuals: @@ -189,7 +189,7 @@ def _next_actor_idx(self) -> int: self._round_robin_index += 1 return i - async def score(self, outputs: list[GeneratedMedia], prompts: list[str]) -> tuple[list[float], int]: + async def score(self, outputs: list[GeneratedMedia], prompts: list[str]) -> tuple[list[float | dict[str, 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 @@ -207,17 +207,6 @@ async def score(self, outputs: list[GeneratedMedia], prompts: list[str]) -> tupl finally: 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, - ) + return [ + score if isinstance(score, dict) else float(score) for chunk in chunked_scores for score in chunk + ], max_queue_depth diff --git a/miles/rollout/rm_hub/videoalign.py b/miles/rollout/rm_hub/videoalign.py new file mode 100644 index 000000000..b1d108e4e --- /dev/null +++ b/miles/rollout/rm_hub/videoalign.py @@ -0,0 +1,459 @@ +"""VideoAlign / VideoReward (KwaiVGI/VideoReward): Qwen2-VL-2B-Instruct video-text reward. + +The model is a Qwen2-VL-2B-Instruct with a linear 'rm_head' (hidden_size -> 1, no bias) on top of +the hidden state of three added special tokens <|VQ_reward|> / <|MQ_reward|> / <|TA_reward|>, +fine-tuned with a LoRA adapter. Each token ends a section of a fixed rubric, so one forward +returns three raw scores (Visual Quality, Motion Quality, Text Alignment). videoalign_rm returns +a dict per sample {"vq", "mq", "ta", "overall"}; overall = vq_weight*vq + mq_weight*mq + ta_weight*ta, and --reward-key picks the +entry GRPO trains on (every key also gets its own rollout/reward/_mean panel). + +The official implementation normalises each dimension with the means/stds shipped in the +checkpoint's model_config.json (inference_config) before summing the overall score; the port matches +it. tests/fast-gpu/test_videoalign_alignment.py checks the port against the official package. +""" + +from __future__ import annotations + +import math +import types +from collections.abc import Sequence + +import ray +import torch +from PIL import Image + +from miles.utils.misc import SingletonMeta +from miles.utils.output_store import StoredTensor +from miles.utils.processing_utils import generated_output_to_rgb_hwc_uint8_frames, sample_frame_indices +from miles.utils.types import Sample + +from .core import AsyncRewardActorPool, record_reward_queue_depth + +# checkpoint repo and base model (model_config.json: model_name_or_path) +_VIDEOALIGN_REPO = "KwaiVGI/VideoReward" +_BASE_MODEL = "Qwen/Qwen2-VL-2B-Instruct" + +# model_config.json: use_special_tokens + the rubric's three reward tokens +_SPECIAL_TOKENS = ["<|VQ_reward|>", "<|MQ_reward|>", "<|TA_reward|>"] +_DIMENSIONS = ("vq", "mq", "ta") + +# model_config.json inference_config: per-dimension (mean, std), applied when --videoalign-normalize +_NORM = { + "vq": (3.6757, 2.2476), + "mq": (1.1646, 1.3811), + "ta": (2.8105, 2.5121), +} + +# model_config.json data_config: max_frame_pixels +_DEFAULT_MAX_PIXELS = 200704 + +# Verbatim DETAILED_PROMPT_WITH_SPECIAL_TOKEN from the official prompt_template.py. Exact +# whitespace matters for bit-exact scores; the alignment test re-checks this against the official +# string loaded from the overlay, so keep it byte-identical. +_RUBRIC = """ +You are tasked with evaluating a generated video based on three distinct criteria: Visual Quality, Motion Quality, and Text Alignment. Please provide a rating from 0 to 10 for each of the three categories, with 0 being the worst and 10 being the best. Each evaluation should be independent of the others. + +**Visual Quality:** +Evaluate the overall visual quality of the video, with a focus on static factors. The following sub-dimensions should be considered: +- **Reasonableness:** The video should not contain any significant biological or logical errors, such as abnormal body structures or nonsensical environmental setups. +- **Clarity:** Evaluate the sharpness and visibility of the video. The image should be clear and easy to interpret, with no blurring or indistinct areas. +- **Detail Richness:** Consider the level of detail in textures, materials, lighting, and other visual elements (e.g., hair, clothing, shadows). +- **Aesthetic and Creativity:** Assess the artistic aspects of the video, including the color scheme, composition, atmosphere, depth of field, and the overall creative appeal. The scene should convey a sense of harmony and balance. +- **Safety:** The video should not contain harmful or inappropriate content, such as political, violent, or adult material. If such content is present, the image quality and satisfaction score should be the lowest possible. + +Please provide the ratings of Visual Quality: <|VQ_reward|> +END + +**Motion Quality:** +Assess the dynamic aspects of the video, with a focus on dynamic factors. Consider the following sub-dimensions: +- **Stability:** Evaluate the continuity and stability between frames. There should be no sudden, unnatural jumps, and the video should maintain stable attributes (e.g., no fluctuating colors, textures, or missing body parts). +- **Naturalness:** The movement should align with physical laws and be realistic. For example, clothing should flow naturally with motion, and facial expressions should change appropriately (e.g., blinking, mouth movements). +- **Aesthetic Quality:** The movement should be smooth and fluid. The transitions between different motions or camera angles should be seamless, and the overall dynamic feel should be visually pleasing. +- **Fusion:** Ensure that elements in motion (e.g., edges of the subject, hair, clothing) blend naturally with the background, without obvious artifacts or the feeling of cut-and-paste effects. +- **Clarity of Motion:** The video should be clear and smooth in motion. Pay attention to any areas where the video might have blurry or unsteady sections that hinder visual continuity. +- **Amplitude:** If the video is largely static or has little movement, assign a low score for motion quality. + +Please provide the ratings of Motion Quality: <|MQ_reward|> +END + +**Text Alignment:** +Assess how well the video matches the textual prompt across the following sub-dimensions: +- **Subject Relevance** Evaluate how accurately the subject(s) in the video (e.g., person, animal, object) align with the textual description. The subject should match the description in terms of number, appearance, and behavior. +- **Motion Relevance:** Evaluate if the dynamic actions (e.g., gestures, posture, facial expressions like talking or blinking) align with the described prompt. The motion should match the prompt in terms of type, scale, and direction. +- **Environment Relevance:** Assess whether the background and scene fit the prompt. This includes checking if real-world locations or scenes are accurately represented, though some stylistic adaptation is acceptable. +- **Style Relevance:** If the prompt specifies a particular artistic or stylistic style, evaluate how well the video adheres to this style. +- **Camera Movement Relevance:** Check if the camera movements (e.g., following the subject, focus shifts) are consistent with the expected behavior from the prompt. + +Textual prompt - {text_prompt} +Please provide the ratings of Text Alignment: <|TA_reward|> +END +""" + + +_IMAGE_FACTOR = 28 +_MIN_PIXELS = 4 * 28 * 28 +_MAX_RATIO = 200 + + +def _round_by_factor(number: int, factor: int) -> int: + return round(number / factor) * factor + + +def _ceil_by_factor(number: int, factor: int) -> int: + return math.ceil(number / factor) * factor + + +def _floor_by_factor(number: int, factor: int) -> int: + return math.floor(number / factor) * factor + + +def _smart_resize(height: int, width: int, max_pixels: int) -> tuple[int, int]: + """Port of the official smart_resize (vision_process.py) used to size each video frame.""" + if max(height, width) / min(height, width) > _MAX_RATIO: + raise ValueError( + f"absolute aspect ratio must be smaller than {_MAX_RATIO}, got {max(height, width) / min(height, width)}" + ) + h_bar = max(_IMAGE_FACTOR, _round_by_factor(height, _IMAGE_FACTOR)) + w_bar = max(_IMAGE_FACTOR, _round_by_factor(width, _IMAGE_FACTOR)) + if h_bar * w_bar > max_pixels: + beta = math.sqrt((height * width) / max_pixels) + h_bar = _floor_by_factor(height / beta, _IMAGE_FACTOR) + w_bar = _floor_by_factor(width / beta, _IMAGE_FACTOR) + elif h_bar * w_bar < _MIN_PIXELS: + beta = math.sqrt(_MIN_PIXELS / (height * width)) + h_bar = _ceil_by_factor(height * beta, _IMAGE_FACTOR) + w_bar = _ceil_by_factor(width * beta, _IMAGE_FACTOR) + return h_bar, w_bar + + +def _preprocess_frame(frame: Image.Image, max_pixels: int) -> Image.Image: + """Port of the official fetch_image for a video frame: RGB + smart_resize + PIL resize.""" + image = frame.convert("RGB") + width, height = image.size + resized_height, resized_width = _smart_resize(height, width, max_pixels) + return image.resize((resized_width, resized_height)) + + +def _remap_checkpoint_state_dict(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: + """Map the checkpoint (saved with transformers 4.45 + peft 0.10) onto the current naming. + + Three drifts happened since the checkpoint was written: + * the text model moved from ``Qwen2VLModel.model`` to ``Qwen2VLModel.language_model``; + * the vision tower moved from the top level to ``Qwen2VLModel.visual``; + * peft 0.18 stores the original weight of a LoRA-wrapped linear under ``module.base_layer.*``. + """ + prefix = "base_model.model." + lora_modules = {key.split(".lora_A.default.weight")[0] for key in state_dict if ".lora_A." in key} + + def remap(key: str) -> str: + rest = key[len(prefix) :] + if rest.startswith("visual."): + rest = "model." + rest + elif rest.startswith("model."): + rest = "model.language_model." + rest[len("model.") :] + return prefix + rest + + remapped: dict[str, torch.Tensor] = {} + for key, value in state_dict.items(): + new_key = remap(key) + for module in lora_modules: + if key == module + ".weight": + new_key = remap(module) + ".base_layer.weight" + break + if key == module + ".bias": + new_key = remap(module) + ".base_layer.bias" + break + remapped[new_key] = value + return remapped + + +def _find_target_linear_names(model, lora_namespan_exclude: Sequence[str]) -> list[str]: + """Linear/embedding modules that get LoRA adapters; the official excludes lm_head/rm_head/embed_tokens/visual.""" + linear_cls = torch.nn.Linear + embedding_cls = torch.nn.Embedding + names = [] + for name, module in model.named_modules(): + if any(excluded in name for excluded in lora_namespan_exclude): + continue + if isinstance(module, (linear_cls, embedding_cls)): + names.append(name) + return names + + +def _official_vision_attention(self, hidden_states, cu_seqlens, position_embeddings=None, **kwargs): + """Qwen2-VL vision attention as the official implementation computes it: one sdpa over every + frame's patches with a block-diagonal mask. transformers 5 instead calls sdpa per frame without a + mask, which picks a different kernel and moves bf16 scores; this keeps the port bit-exact with the + checkpoint's reference scores (same patch as hpsv3.py).""" + from transformers.models.qwen2_vl.modeling_qwen2_vl import apply_rotary_pos_emb_vision + + seq_length = hidden_states.shape[0] + q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0) + q, k = apply_rotary_pos_emb_vision(q, k, *position_embeddings) + mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool) + for i in range(1, len(cu_seqlens)): + mask[..., cu_seqlens[i - 1] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = True + out = torch.nn.functional.scaled_dot_product_attention( + q.transpose(0, 1), k.transpose(0, 1), v.transpose(0, 1), mask, dropout_p=0.0 + ) + return self.proj(out.transpose(0, 1).reshape(seq_length, -1)) + + +# subclassing needs the parent at class-definition time; videoalign is only imported lazily by rm_hub +from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLForConditionalGeneration + + +class _Qwen2VLRewardModel(Qwen2VLForConditionalGeneration): + """Ported Qwen2VLRewardModelBT: Qwen2-VL-2B plus a scalar head read at the reward tokens. + + Subclasses Qwen2VLForConditionalGeneration so the checkpoint's PeftModel state dict keys match; + rm_head is Linear(hidden_size, 1, bias=False) and forward returns {"logits": [B, 3]} (VQ, MQ, TA + in order), read at the three special tokens. + """ + + def __init__(self, config) -> None: + super().__init__(config) + self.output_dim = 1 + self.rm_head = torch.nn.Linear(config.text_config.hidden_size, self.output_dim, bias=False) + self.reward_token = "special" + self.special_token_ids: list[int] = [] + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: torch.Tensor = None, + position_ids: torch.LongTensor = None, + past_key_values=None, + inputs_embeds: torch.FloatTensor = None, + labels=None, + use_cache: bool = None, + output_attentions: bool = None, + output_hidden_states: bool = None, + return_dict: bool = None, + pixel_values: torch.Tensor = None, + pixel_values_videos: torch.FloatTensor = None, + image_grid_thw: torch.LongTensor = None, + video_grid_thw: torch.LongTensor = None, + **kwargs, + ) -> dict: + # The reference calls the text model directly: all three rotary axes use sequential positions. + if position_ids is None: + position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).view(1, 1, -1) + position_ids = position_ids.expand(3, input_ids.shape[0], -1) + outputs = self.model( + input_ids=input_ids, + pixel_values=pixel_values, + pixel_values_videos=pixel_values_videos, + image_grid_thw=image_grid_thw, + video_grid_thw=video_grid_thw, + position_ids=position_ids, + attention_mask=attention_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=True, + **kwargs, + ) + hidden_states = outputs.last_hidden_state # [B, L, D] + logits = self.rm_head(hidden_states) # [B, L, 1] + + batch_size = input_ids.shape[0] + special_token_mask = torch.zeros_like(input_ids, dtype=torch.bool) + for token_id in self.special_token_ids: + special_token_mask = special_token_mask | (input_ids == token_id) + pooled = logits[special_token_mask, ...] # [B * 3, 1] + pooled = pooled.view(batch_size, 3, self.output_dim) # [B, 3, 1] + pooled = pooled.view(batch_size, -1) # [B, 3] (VQ, MQ, TA) + return {"logits": pooled} + + +class VideoAlignScorer(torch.nn.Module): + """VideoAlign scorer for aligned (prompt, video-frames) batches; returns one dict per sample.""" + + def __init__( + self, + *, + device: str = "cuda", + model_path: str = _BASE_MODEL, + checkpoint_path: str | None = None, + max_pixels: int = _DEFAULT_MAX_PIXELS, + normalize: bool = True, + vq_weight: float = 1.0, + mq_weight: float = 1.0, + ta_weight: float = 1.0, + ) -> None: + super().__init__() + from pathlib import Path + + import huggingface_hub + from peft import LoraConfig, get_peft_model + from transformers import AutoConfig, AutoProcessor + from transformers.models.qwen2_vl.image_processing_pil_qwen2_vl import Qwen2VLImageProcessorPil + + self.device = torch.device(device) + self.max_pixels = max_pixels + self.normalize = normalize + self.vq_weight = vq_weight + self.mq_weight = mq_weight + self.ta_weight = ta_weight + repo = checkpoint_path or _VIDEOALIGN_REPO + + # tokenizer/processor from the base model + the three added reward tokens, as the official does + self.processor = AutoProcessor.from_pretrained(model_path, padding_side="right") + self.processor.image_processor = Qwen2VLImageProcessorPil.from_pretrained(model_path) + self.processor.tokenizer.add_special_tokens({"additional_special_tokens": _SPECIAL_TOKENS}) + special_token_ids = self.processor.tokenizer.convert_tokens_to_ids(_SPECIAL_TOKENS) + + # The reward checkpoint contains every weight, so only the base configuration is needed. + config = AutoConfig.from_pretrained(model_path) + config._attn_implementation = "sdpa" + model = _Qwen2VLRewardModel(config) + model.special_token_ids = list(special_token_ids) + model.resize_token_embeddings(len(self.processor.tokenizer)) + # match the checkpoint's reference scores: use the official block-diagonal vision attention + for block in model.model.visual.blocks: + block.attn.forward = types.MethodType(_official_vision_attention, block.attn) + + # the checkpoint is a full PeftModel state dict (base + LoRA deltas), so rebuild the same + # LoRA structure before loading it; r/alpha/dropout and the excluded namespaces come from + # model_config.json peft_lora_config / lora_namespan_exclude. + target_modules = _find_target_linear_names(model, ["lm_head", "rm_head", "embed_tokens", "visual"]) + peft_config = LoraConfig( + target_modules=target_modules, + r=64, + lora_alpha=128, + lora_dropout=0.05, + task_type="CAUSAL_LM", + use_rslora=False, + bias="none", + ) + self.model = get_peft_model(model, peft_config) + + if Path(repo).is_dir(): + model_pth = Path(repo) / "checkpoint-11352" / "model.pth" + if not model_pth.is_file(): + raise FileNotFoundError(f"VideoAlign checkpoint not found at {model_pth}") + else: + model_pth = huggingface_hub.hf_hub_download(repo, "checkpoint-11352/model.pth") + state_dict = _remap_checkpoint_state_dict(torch.load(model_pth, map_location="cpu", weights_only=True)) + missing, unexpected = self.model.load_state_dict(state_dict, strict=False) + if unexpected: + raise RuntimeError(f"unexpected VideoAlign checkpoint keys: {unexpected[:5]} ...") + if missing: + raise RuntimeError(f"missing VideoAlign checkpoint keys: {missing[:5]} ...") + + self.model.to(self.device, dtype=torch.bfloat16) + self.model.eval() + + def build_inputs(self, prompts: Sequence[str], videos: Sequence[list[Image.Image]]): + resized = [[_preprocess_frame(frame, self.max_pixels) for frame in frames] for frames in videos] + conversations = [] + for prompt, frames in zip(prompts, videos, strict=True): + text = _RUBRIC.format(text_prompt=prompt) + conversations.append( + [{"role": "user", "content": [{"type": "video", "video": frames}, {"type": "text", "text": text}]}] + ) + texts = self.processor.apply_chat_template(conversations, tokenize=False, add_generation_prompt=True) + pixels, grids = [], [] + image_processor = self.processor.image_processor + patch = image_processor.patch_size + temporal = image_processor.temporal_patch_size + for i, frames in enumerate(resized): + # The PIL processor duplicates each image across the temporal patch. Repack the + # first copy from consecutive frames to reproduce the reference video processor. + frames = frames + [frames[-1]] * (-len(frames) % temporal) + images = image_processor(images=frames, return_tensors="pt") + _, grid_h, grid_w = images["image_grid_thw"][0].tolist() + frame_pixels = images["pixel_values"].reshape(len(frames), grid_h * grid_w, 3, temporal, patch, patch) + video_pixels = frame_pixels[:, :, :, 0].reshape(-1, temporal, grid_h * grid_w, 3, patch, patch) + video_pixels = video_pixels.permute(0, 2, 3, 1, 4, 5).reshape(-1, 3 * temporal * patch * patch) + grid = [len(frames) // temporal, grid_h, grid_w] + pixels.append(video_pixels) + grids.append(grid) + token_count = math.prod(grid) // image_processor.merge_size**2 + texts[i] = texts[i].replace("<|video_pad|>", "<|video_pad|>" * token_count, 1) + inputs = self.processor.tokenizer(texts, padding=True, return_tensors="pt") + for token_id in self.processor.tokenizer.convert_tokens_to_ids(_SPECIAL_TOKENS): + if not torch.all((inputs["input_ids"] == token_id).sum(dim=1) == 1): + raise ValueError("Each VideoAlign input must contain exactly one of each reward token") + inputs["pixel_values_videos"] = torch.cat(pixels) + inputs["video_grid_thw"] = torch.tensor(grids) + return inputs + + @torch.no_grad() + def forward(self, prompts: Sequence[str], videos: Sequence[list[Image.Image]]) -> list[dict[str, float]]: + inputs = self.build_inputs(prompts, videos) + inputs = {k: v.to(self.device) for k, v in inputs.items() if isinstance(v, torch.Tensor)} + logits = self.model(**inputs)["logits"] # [B, 3] + rewards = [] + for row in logits.detach().float().cpu().tolist(): + dims = dict(zip(_DIMENSIONS, row, strict=True)) + if self.normalize: + for dim in _DIMENSIONS: + mean, std = _NORM[dim] + dims[dim] = (dims[dim] - mean) / std + dims["overall"] = self.vq_weight * dims["vq"] + self.mq_weight * dims["mq"] + self.ta_weight * dims["ta"] + rewards.append(dims) + return rewards + + +class VideoAlignRewardActor: + def __init__(self, *, num_frames: int | None, **scorer_kwargs) -> None: + self.num_frames = num_frames + use_cuda = bool(ray.get_gpu_ids()) and torch.cuda.is_available() + if use_cuda: + torch.cuda.set_device(0) + self.scorer = VideoAlignScorer(device="cuda" if use_cuda else "cpu", **scorer_kwargs) + + def score_batch(self, outputs: list[torch.Tensor], prompts: list[str]) -> list[dict[str, float]]: + videos = [] + for output in outputs: + frames = generated_output_to_rgb_hwc_uint8_frames(output, self.num_frames) + videos.append([Image.fromarray(frame) for frame in frames]) + return self.scorer(prompts, videos) + + +class AsyncVideoAlignPool(AsyncRewardActorPool, metaclass=SingletonMeta): + """Ray actor pool for VideoAlign reward inference.""" + + def __init__(self, args, placement_group=None, slots=None) -> None: + super().__init__( + args=args, + actor_cls=VideoAlignRewardActor, + actor_kwargs={ + "num_frames": args.videoalign_num_frames, + "model_path": args.videoalign_model_path or _BASE_MODEL, + "checkpoint_path": args.videoalign_checkpoint_path, + "max_pixels": args.videoalign_max_pixels, + "normalize": not args.videoalign_no_normalize, + "vq_weight": args.videoalign_vq_weight, + "mq_weight": args.videoalign_mq_weight, + "ta_weight": args.videoalign_ta_weight, + }, + num_workers=args.videoalign_num_workers, + batch_size=args.videoalign_batch_size, + num_gpus_per_worker=args.videoalign_num_gpus_per_worker, + colocate=args.videoalign_reward_colocate, + name="videoalign", + placement_group=placement_group, + slots=slots, + ) + + +async def videoalign_rm(args, samples: Sequence[Sample]) -> list[dict[str, float]]: + pool = AsyncVideoAlignPool(args) + # pick --videoalign-num-frames here so only the scored frames cross the object store; a stored + # output is not here to pick from, so its actor picks them + outputs = [ + ( + output + if isinstance(output, StoredTensor) + else output[:, sample_frame_indices(output.shape[1], args.videoalign_num_frames)] + ) + for output in (s.generated_output for s in samples) + ] + scores, max_queue_depth = await pool.score(outputs, [s.prompt for s in samples]) + record_reward_queue_depth(samples, "videoalign", max_queue_depth) + return scores diff --git a/miles/rollout/sglang_diffusion_rollout.py b/miles/rollout/sglang_diffusion_rollout.py index c0584ef93..a5d7750fb 100644 --- a/miles/rollout/sglang_diffusion_rollout.py +++ b/miles/rollout/sglang_diffusion_rollout.py @@ -40,13 +40,16 @@ def build_rollout_sampling_params( neg = args.diffusion_negative_prompt eval_steps = args.diffusion_eval_num_steps num_steps = eval_steps if evaluation and eval_steps is not None else args.diffusion_num_steps + guidance_scale = args.diffusion_guidance_scale + if evaluation and args.diffusion_eval_guidance_scale is not None: + guidance_scale = args.diffusion_eval_guidance_scale sampling_params: dict[str, Any] = { "generator_device": args.diffusion_generator_device, "width": args.diffusion_width, "height": args.diffusion_height, "num_inference_steps": num_steps, - "guidance_scale": args.diffusion_guidance_scale, + "guidance_scale": guidance_scale, "true_cfg_scale": args.diffusion_true_cfg_scale, "rollout_video_dtype": args.rollout_video_dtype, } diff --git a/miles/utils/arguments.py b/miles/utils/arguments.py index eb48351e9..ea89cf31b 100644 --- a/miles/utils/arguments.py +++ b/miles/utils/arguments.py @@ -962,6 +962,16 @@ def add_eval_arguments(parser): default=None, help="Number of diffusion inference steps for eval rollout. Defaults to diffusion-num-steps.", ) + parser.add_argument( + "--diffusion-eval-guidance-scale", + type=float, + default=None, + help=( + "Classifier-free guidance scale for eval rollout. Defaults to " + "--diffusion-guidance-scale. LTX-2.3 eval uses the embedded CFG guider, " + "which needs > 1.0 so the negative prompt gets encoded." + ), + ) return parser def add_algo_arguments(parser): @@ -1544,7 +1554,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 / openai_api / videoalign), 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 +1731,88 @@ def add_reward_model_arguments(parser): default=None, help="Optional local HPSv3.safetensors; otherwise download it from MizzenAI/HPSv3.", ) + parser.add_argument( + "--videoalign-num-workers", + type=int, + default=1, + help="Number of Ray VideoAlign actors used when --rm-type videoalign.", + ) + parser.add_argument( + "--videoalign-num-gpus-per-worker", + type=float, + default=1.0, + help="GPU resources per VideoAlign actor when reward is not colocated.", + ) + parser.add_argument( + "--videoalign-reward-colocate", + action="store_true", + default=False, + help="Seat VideoAlign actors on the rollout GPUs, one per placement-group bundle. Requires --colocate.", + ) + parser.add_argument( + "--videoalign-batch-size", + type=int, + default=4, + help="Batch size per VideoAlign actor call.", + ) + parser.add_argument( + "--videoalign-model-path", + type=str, + default=None, + help="Qwen2-VL-2B base model for VideoAlign; defaults to Qwen/Qwen2-VL-2B-Instruct.", + ) + parser.add_argument( + "--videoalign-checkpoint-path", + type=str, + default=None, + help="KwaiVGI/VideoReward repo id or local dir holding checkpoint-11352/model.pth.", + ) + parser.add_argument( + "--videoalign-num-frames", + type=int, + default=None, + help="Evenly spaced frames to score per video (None = every frame).", + ) + parser.add_argument( + "--videoalign-max-pixels", + type=int, + default=200704, + help="Max pixels per frame for the VideoAlign visual encoder.", + ) + parser.add_argument( + "--videoalign-no-normalize", + action="store_true", + default=False, + help="Return raw (un-normalised) VQ/MQ/TA instead of the checkpoint's inference_config normalisation.", + ) + parser.add_argument( + "--videoalign-vq-weight", + type=float, + default=1.0, + help=( + "Weight applied to the visual-quality (VQ) head inside the summed " + "`overall` reward: overall = vq_weight*vq + mq_weight*mq + ta_weight*ta." + ), + ) + parser.add_argument( + "--videoalign-mq-weight", + type=float, + default=1.0, + help=( + "Weight applied to the motion-quality (MQ) head inside the summed " + "`overall` reward: overall = vq_weight*vq + mq_weight*mq + ta_weight*ta." + ), + ) + parser.add_argument( + "--videoalign-ta-weight", + type=float, + default=1.0, + help=( + "Weight applied to the text-alignment (TA) head inside the summed " + "`overall` reward: overall = vq_weight*vq + mq_weight*mq + ta_weight*ta. " + "Raise above 1 to discourage prompt-mismatch reward hacking." + ), + ) parser.add_argument( "--rm-url", @@ -2452,6 +2544,14 @@ 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.videoalign_num_workers <= 0: + raise ValueError(f"--videoalign-num-workers must be positive, got {args.videoalign_num_workers}") + if args.videoalign_batch_size <= 0: + raise ValueError(f"--videoalign-batch-size must be positive, got {args.videoalign_batch_size}") + if args.videoalign_num_gpus_per_worker < 0: + raise ValueError( + f"--videoalign-num-gpus-per-worker must be non-negative, got {args.videoalign_num_gpus_per_worker}" + ) colocated_reward_workers = { name: num_workers @@ -2459,6 +2559,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), + ("videoalign", args.videoalign_reward_colocate, args.videoalign_num_workers), ) if colocate } diff --git a/scripts/run_diffusion_grpo_ltx23_videoalign_sglang.py b/scripts/run_diffusion_grpo_ltx23_videoalign_sglang.py new file mode 100644 index 000000000..e92a02d7f --- /dev/null +++ b/scripts/run_diffusion_grpo_ltx23_videoalign_sglang.py @@ -0,0 +1,182 @@ +"""LTX-2.3 video VideoAlign GRPO: 4-GPU FSDP train + sglang rollout colocate, 1 reward GPU. + +57-frame 512x768 video at 24 fps, 24 denoising steps, CPS-SDE with 3 trainable steps drawn +per epoch from candidate steps 0-9. Everything runs bf16 end to end — master, reduce, +forward and the sgl-d engine — on the sdpa_math attention backend. + +VideoAlign scores 8 uniformly sampled frames per clip. The optimized scalar is the sum +of normalized VQ, MQ and TA; each head is also logged separately. The default two +rollouts are an integration smoke test, not a verified training curve. + +Video rollouts take minutes per request, so the health checker gets a far longer interval +and failure budget than the image recipes. + +Usage: + python3 scripts/run_diffusion_grpo_ltx23_videoalign_sglang.py +""" + +from dataclasses import dataclass +from pathlib import Path + +import typer + +import miles.utils.external_utils.command_utils as U + +MODEL = "Lightricks/LTX-2.3" +DATASET = "rockdu/miles-diffusion-datasets" +DATASET_SUBSET = "flowgrpo_pickscore" +WANDB_PROJECT = "miles-diffusion-grpo" + +EVAL_SUBSET_SIZE = 64 +EVAL_SUBSET_SEED = 0 + + +@dataclass +class ScriptArgs(U.ExecuteTrainConfig): + num_rollout: int = 2 + data_dir: str = "/root/datasets" + extra_args: str = "" + + +def _write_eval_subset(subset_dir: str) -> str: + """Sample a fixed eval subset from test.jsonl with a deterministic seed. + + The same held-out prompts are used for every eval, so reward curves stay + comparable across checkpoints. + """ + import random + + src = Path(subset_dir) / "test.jsonl" + out = src.with_name(f"test_eval_{EVAL_SUBSET_SIZE}.jsonl") + if out.exists(): + return str(out) + lines = src.read_text(encoding="utf-8").splitlines() + chosen = random.Random(EVAL_SUBSET_SEED).sample(lines, EVAL_SUBSET_SIZE) + out.write_text("\n".join(chosen) + "\n", encoding="utf-8") + return str(out) + + +def prepare(args: ScriptArgs) -> str: + local_dir = U.hf_download_dataset(DATASET, include=f"{DATASET_SUBSET}/**", data_dir=args.data_dir) + subset_dir = f"{local_dir}/{DATASET_SUBSET}" + _write_eval_subset(subset_dir) + return subset_dir + + +def execute(args: ScriptArgs, data_dir: str) -> None: + run_name = f"diffusion_grpo_ltx23_videoalign_{U.create_run_id()}" + + ckpt_args = ( + f"--hf-checkpoint {MODEL} --diffusion-task t2v --save {args.output_dir}/{run_name}/ckpt --save-interval 10 " + ) + + rollout_args = ( + "--rollout-function-path miles.rollout.sglang_diffusion_rollout.generate_rollout " + f"--prompt-data {data_dir}/train.jsonl " + "--input-key input " + "--rollout-batch-size 8 " + "--n-samples-per-prompt 8 " + f"--num-rollout {args.num_rollout} " + "--num-steps-per-rollout 2 " + "--rollout-microgroup-size 1 " + "--train-dp-split-mode stride " + "--diffusion-train-iter-order sample_major " + "--rollout-patch-group ltx " + "--diffusion-num-steps 24 " + "--diffusion-output-num-frames 57 " + "--diffusion-fps 24 " + "--diffusion-guidance-scale 1.0 " + "--diffusion-noise-level 0.8 " + "--diffusion-height 512 " + "--diffusion-width 768 " + "--diffusion-sde-type cps " + "--diffusion-step-strategy-path miles.rollout.step_strategy_hub.epoch_global_random_choice " + "--diffusion-num-sde-steps 3 " + "--diffusion-sde-candidate-steps 0,1,2,3,4,5,6,7,8,9 " + ) + + grpo_args = ( + "--advantage-estimator grpo --globalize-reward-std --diffusion-clip-range 1e-5 --diffusion-kl-beta 0.0 " + ) + + optimizer_args = "--lr 2e-4 --adam-beta2 0.999 --weight-decay 1e-4 " + + lora_args = "--use-lora --lora-rank 64 --lora-alpha 128 --lora-init-weights gaussian " + + reward_args = ( + "--rm-type videoalign " + "--reward-key overall " + "--videoalign-num-frames 8 " + "--videoalign-num-gpus-per-worker 1.0 " + "--videoalign-num-workers 1 " + "--videoalign-batch-size 4 " + ) + + eval_args = ( + "--eval-interval 20 " + f"--eval-prompt-data test {data_dir}/test_eval_{EVAL_SUBSET_SIZE}.jsonl " + "--eval-reward-key overall " + "--diffusion-eval-guidance-scale 3.0 " + ) + + wandb_args = U.get_default_wandb_args( + __file__, run_id=run_name, project=WANDB_PROJECT, wandb_log_num_images=4, wandb_log_image_interval=10 + ) + + sglang_args = ( + "--use-miles-router " + "--rollout-fetch-in-parser " + "--sglang-server-concurrency 4 " + "--sglang-lora-merge-mode merge " + "--sglang-attention-backend torch_sdpa " + "--sglang-dit-precision bf16 " + "--update-weight-buffer-size 2147483648 " + ) + + train_backend_args = ( + "--train-backend fsdp " + "--fsdp-master-dtype bf16 " + "--fsdp-reduce-dtype bf16 " + "--diffusion-forward-dtype bf16 " + "--fsdp-attention-backend sdpa_math " + ) + + perf_args = ( + "--gradient-checkpointing " + "--micro-batch-size-sample 1 " + "--micro-batch-size-tstep 1 " + "--rollout-parser-num-workers 16 " + ) + + misc_args = ( + "--actor-num-nodes 1 " + "--actor-num-gpus-per-node 4 " + "--rollout-num-gpus 4 " + "--rollout-num-gpus-per-engine 1 " + "--num-gpus-per-node 4 " + "--colocate " + "--deterministic-mode " + "--rollout-health-check-interval 120 " + "--miles-router-health-check-failure-threshold 30 " + ) + + U.execute_train( + train_args=( + f"{ckpt_args} {rollout_args} {grpo_args} {optimizer_args} {lora_args} " + f"{reward_args} {eval_args} {wandb_args} {sglang_args} {train_backend_args} {perf_args} {misc_args} " + f"{args.extra_args}" + ), + num_gpus_per_node=5, + config=args, + extra_env_vars={"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}, + ) + + +@U.dataclass_cli +def main(args: ScriptArgs) -> None: + data_dir = prepare(args) + execute(args, data_dir) + + +if __name__ == "__main__": + typer.run(main) diff --git a/tests/fast-gpu/test_videoalign_alignment.py b/tests/fast-gpu/test_videoalign_alignment.py new file mode 100644 index 000000000..ab8c28e01 --- /dev/null +++ b/tests/fast-gpu/test_videoalign_alignment.py @@ -0,0 +1,146 @@ +"""Compare bf16 VideoAlign inputs and scores against a commit-pinned upstream SDPA reference. + +The reference runs in a subprocess with its original Transformers/PEFT versions. +Individual and padded mixed-resolution batches must match exactly. +""" + +from tests.ci.ci_register import register_cuda_ci + +register_cuda_ci( + est_time=600, + suite="stage-b-3-gpu-h200", + labels=[], +) + +import hashlib +import importlib.util +import json +import os +import platform +import subprocess +import sys +from pathlib import Path + +import pytest + +from miles.rollout.rm_hub.videoalign import VideoAlignScorer + +_FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" +_OFFICIAL_SCRIPT = _FIXTURES / "videoalign_official_scores.py" +_spec = importlib.util.spec_from_file_location("videoalign_official_scores", _OFFICIAL_SCRIPT) +_official = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_official) + +# the official pins live in a per-machine overlay (transformers/peft/trl for the 4.45-era checkpoint) +OFFICIAL_PINS = [ + "transformers==4.45.2", + "tokenizers==0.20.3", + "huggingface_hub==0.25.2", + "trl==0.12.2", + "peft==0.10.0", +] +_OVERLAY_KEY = hashlib.sha256( + " ".join([*OFFICIAL_PINS, sys.implementation.cache_tag, platform.machine()]).encode() +).hexdigest()[:12] +_OVERLAY = Path.home() / ".cache" / "miles" / f"videoalign_official_{_OVERLAY_KEY}" + + +def _paths(): + # machine-specific locations; skip unless the checkpoint/repo/base model are present + checkpoint = os.environ.get("VIDEOALIGN_CHECKPOINT_DIR") + model = os.environ.get("VIDEOALIGN_MODEL_PATH") + repo = os.environ.get("VIDEOALIGN_REPO_DIR") + if not (checkpoint and model and repo): + pytest.skip("set VIDEOALIGN_CHECKPOINT_DIR / VIDEOALIGN_MODEL_PATH / VIDEOALIGN_REPO_DIR to run the alignment") + return checkpoint, model, repo + + +def _install_overlay() -> Path: + if not _OVERLAY.is_dir(): + subprocess.run( + [ + sys.executable, + "-m", + "pip", + "install", + "--quiet", + "--no-deps", + "--target", + str(_OVERLAY), + *OFFICIAL_PINS, + ], + check=True, + ) + return _OVERLAY + + +@pytest.fixture(scope="module") +def official_scores(tmp_path_factory): + checkpoint, model, repo = _paths() + overlay = _install_overlay() + out = tmp_path_factory.mktemp("videoalign_official") / "scores.json" + env = {**os.environ, "PYTHONPATH": os.pathsep.join(filter(None, [str(overlay), os.environ.get("PYTHONPATH")]))} + subprocess.run( + [ + sys.executable, + str(_OFFICIAL_SCRIPT), + "--repo-dir", + repo, + "--checkpoint-dir", + checkpoint, + "--model-path", + model, + "--output", + str(out), + ], + env=env, + check=True, + ) + return json.loads(out.read_text()) + + +def _frames(sample): + return _official.make_video(sample["width"], sample["height"], sample["frames"], sample["offset"]) + + +@pytest.fixture(scope="module") +def scorer(official_scores): + checkpoint, model, _ = _paths() + return VideoAlignScorer(device="cuda", model_path=model, checkpoint_path=checkpoint, normalize=False) + + +def test_inputs_match_official(official_scores, scorer): + for sample in official_scores["samples"]: + inputs = scorer.build_inputs([sample["prompt"]], [_frames(sample)]) + assert inputs["input_ids"][0].tolist() == sample["input_ids"] + assert inputs["video_grid_thw"][0].tolist() == sample["video_grid_thw"] + assert list(inputs["pixel_values_videos"].shape) == sample["pixel_values_videos_shape"] + assert _official._sha256(inputs["pixel_values_videos"]) == sample["pixel_values_videos_sha256"] + + +def test_scores_match_official(official_scores, scorer): + for sample in official_scores["samples"]: + (result,) = scorer([sample["prompt"]], [_frames(sample)]) + assert [result[key] for key in ("vq", "mq", "ta")] == [sample[key] for key in ("VQ", "MQ", "TA")] + + +def test_padded_batch_scores_match_official(official_scores, scorer): + samples = official_scores["samples"] + results = scorer([s["prompt"] for s in samples], [_frames(s) for s in samples]) + assert [[r[k] for k in ("vq", "mq", "ta")] for r in results] == official_scores["batch_scores"] + + +def test_normalization_and_overall(official_scores, scorer): + from miles.rollout.rm_hub.videoalign import _NORM + + samples = official_scores["samples"] + scorer.normalize = True + try: + results = scorer([s["prompt"] for s in samples], [_frames(s) for s in samples]) + finally: + scorer.normalize = False + for result, raw in zip(results, official_scores["batch_scores"], strict=True): + expected = { + key: (score - _NORM[key][0]) / _NORM[key][1] for key, score in zip(("vq", "mq", "ta"), raw, strict=True) + } + assert result == {**expected, "overall": sum(expected.values())} diff --git a/tests/fast/rollout/test_rollout_negative_prompt.py b/tests/fast/rollout/test_rollout_negative_prompt.py index d02942323..d5d766b25 100644 --- a/tests/fast/rollout/test_rollout_negative_prompt.py +++ b/tests/fast/rollout/test_rollout_negative_prompt.py @@ -23,6 +23,7 @@ def _args(**overrides): diffusion_width=832, diffusion_height=480, diffusion_guidance_scale=4.0, + diffusion_eval_guidance_scale=None, diffusion_guidance_scale_2=None, diffusion_true_cfg_scale=None, diffusion_output_num_frames=None, diff --git a/tests/fast/rollout/test_rollout_payload_media.py b/tests/fast/rollout/test_rollout_payload_media.py index eadc89a37..ba6ca5c63 100644 --- a/tests/fast/rollout/test_rollout_payload_media.py +++ b/tests/fast/rollout/test_rollout_payload_media.py @@ -21,6 +21,7 @@ def _args(**overrides): diffusion_width=832, diffusion_height=480, diffusion_guidance_scale=1.0, + diffusion_eval_guidance_scale=None, diffusion_guidance_scale_2=None, diffusion_true_cfg_scale=None, diffusion_output_num_frames=None, diff --git a/tests/fast/rollout/test_videoalign_reward.py b/tests/fast/rollout/test_videoalign_reward.py new file mode 100644 index 000000000..4170e05ce --- /dev/null +++ b/tests/fast/rollout/test_videoalign_reward.py @@ -0,0 +1,155 @@ +"""VideoAlign reward: dict-per-sample contract and the rm_hub dispatch fast path. + +Mental model (one video scored by VideoAlign): + + sample.generated_output (float CFHW, T frames) + -> VideoAlignRewardActor.score_batch : truncate -> uint8 frames -> VideoAlignScorer + -> videoalign_rm ships only --videoalign-num-frames frames across the object store + -> reward is a dict {"vq", "mq", "ta", "overall"} per sample (--reward-key picks the scalar) + +Covered: the actor decodes every frame and returns one dict per sample (1); videoalign_rm hands the +raw tensor to its pool and records its own queue depth (2); videoalign_rm selects frames before +shipping (3); batched_async_rm takes the videoalign fast path (4) and preserves sample order for +mixed rm_types (5). +""" + +from tests.ci.ci_register import register_cpu_ci + +register_cpu_ci(est_time=10, suite="stage-a-cpu", labels=[]) + +from argparse import Namespace +from unittest.mock import AsyncMock + +import numpy as np +import pytest +import torch + +import miles.rollout.rm_hub.videoalign as videoalign_module +from miles.rollout.rm_hub import batched_async_rm +from miles.rollout.rm_hub.videoalign import VideoAlignRewardActor +from miles.utils.types import Sample + +# one pixel row [0, 0.5, 1] per channel; truncation gives 127 in the middle (the actor truncates) +_ROW = torch.tensor([0.0, 0.5, 1.0]).reshape(1, 1, 1, 3).repeat(3, 1, 1, 1) + + +def _sample_reward() -> dict[str, float]: + return {"vq": 1.0, "mq": 2.0, "ta": 3.0, "overall": 6.0} + + +def test_videoalign_actor_decodes_every_frame_and_returns_one_dict_per_sample(): + actor = VideoAlignRewardActor.__new__(VideoAlignRewardActor) + actor.num_frames = None + decoded = {} + + def scorer(prompts, videos): + for prompt, frames in zip(prompts, videos, strict=True): + decoded[prompt] = [np.asarray(frame).shape for frame in frames] + return [_sample_reward() for _ in prompts] + + actor.scorer = scorer + two_frames = torch.cat([_ROW, _ROW], dim=1) + + assert actor.score_batch([two_frames], ["prompt"]) == [_sample_reward()] + assert len(decoded["prompt"]) == 2 # both frames decoded and handed to the scorer + + +@pytest.mark.asyncio +async def test_videoalign_rm_hands_the_raw_tensor_to_its_pool(monkeypatch): + pool = AsyncMock() + pool.score.return_value = ([_sample_reward()], 2) + monkeypatch.setattr(videoalign_module, "AsyncVideoAlignPool", lambda args: pool) + sample = Sample(prompt="prompt", generated_output=_ROW) + + assert await videoalign_module.videoalign_rm(Namespace(videoalign_num_frames=None), [sample]) == [_sample_reward()] + + (shipped,), prompts = pool.score.await_args.args + assert torch.equal(shipped, _ROW) + assert prompts == ["prompt"] + assert sample.reward_max_queue_depth == {"videoalign": 2.0} + + +@pytest.mark.asyncio +async def test_videoalign_rm_selects_frames_before_shipping(monkeypatch): + """Only the --videoalign-num-frames frames should cross the object store, not the whole video.""" + pool = AsyncMock() + pool.score.return_value = ([_sample_reward()], 0) + monkeypatch.setattr(videoalign_module, "AsyncVideoAlignPool", lambda args: pool) + video = torch.cat([_ROW * 0.0, _ROW, _ROW * 0.0], dim=1) + + await videoalign_module.videoalign_rm( + Namespace(videoalign_num_frames=1), [Sample(prompt="p", generated_output=video)] + ) + + (shipped,), _ = pool.score.await_args.args + assert shipped.shape[1] == 1 and torch.equal(shipped[:, 0], _ROW[:, 0]) + + +@pytest.mark.asyncio +async def test_batched_async_rm_uses_videoalign_batch_fast_path(monkeypatch): + videoalign_rm = AsyncMock(return_value=[_sample_reward(), _sample_reward()]) + monkeypatch.setattr(videoalign_module, "videoalign_rm", videoalign_rm) + args = Namespace(custom_rm_path=None, rm_type="videoalign") + samples = [Sample(index=3), Sample(index=1)] + + assert await batched_async_rm(args, samples) == [_sample_reward(), _sample_reward()] + videoalign_rm.assert_awaited_once_with(args, samples) + + +@pytest.mark.asyncio +async def test_batched_async_rm_preserves_order_for_mixed_reward_types(monkeypatch): + monkeypatch.setattr(videoalign_module, "videoalign_rm", AsyncMock(return_value=[_sample_reward()])) + from miles.rollout.rm_hub import hps as hps_module + + monkeypatch.setattr(hps_module, "hps_rm", AsyncMock(return_value=[10.0])) + args = Namespace(custom_rm_path=None, rm_type=None) + samples = [ + Sample(metadata={"rm_type": "videoalign"}), + Sample(metadata={"rm_type": "hps"}), + ] + + assert await batched_async_rm(args, samples) == [_sample_reward(), 10.0] + + +@pytest.mark.asyncio +async def test_shared_pool_preserves_dict_rewards_and_scalar_conversion(monkeypatch): + from miles.rollout.rm_hub import core + + pool = core.AsyncRewardActorPool.__new__(core.AsyncRewardActorPool) + rewards = [_sample_reward(), np.float32(2.5), {**_sample_reward(), "mq": 4.0}] + pool._actors = [Namespace(score_batch=Namespace(remote=lambda outputs, prompts: [rewards[i] for i in outputs]))] + pool._batch_size = 2 + pool._round_robin_index = 0 + pool._inflight = [0] + monkeypatch.setattr(core.ray, "get", lambda refs: refs) + + scores, depth = await pool.score([0, 1, 2], ["a", "b", "c"]) + assert scores == rewards + assert isinstance(scores[1], float) + assert depth == 1 + assert pool._inflight == [0] + + +def test_videoalign_pool_uses_default_model_when_cli_path_is_none(monkeypatch): + captured = {} + monkeypatch.setattr( + videoalign_module.AsyncRewardActorPool, "__init__", lambda self, **kwargs: captured.update(kwargs) + ) + pool = videoalign_module.AsyncVideoAlignPool.__new__(videoalign_module.AsyncVideoAlignPool) + pool.__init__( + Namespace( + videoalign_num_frames=8, + videoalign_model_path=None, + videoalign_checkpoint_path=None, + videoalign_max_pixels=200704, + videoalign_no_normalize=False, + videoalign_vq_weight=1.0, + videoalign_mq_weight=1.0, + videoalign_ta_weight=1.0, + videoalign_num_workers=1, + videoalign_batch_size=1, + videoalign_num_gpus_per_worker=1, + videoalign_reward_colocate=False, + ) + ) + assert captured["actor_kwargs"]["model_path"] == videoalign_module._BASE_MODEL diff --git a/tests/fixtures/videoalign_official_scores.py b/tests/fixtures/videoalign_official_scores.py new file mode 100644 index 000000000..908f6a92f --- /dev/null +++ b/tests/fixtures/videoalign_official_scores.py @@ -0,0 +1,149 @@ +"""Run the OFFICIAL VideoReward (old transformers/peft, in the overlay) on frame lists. + +Used by the videoalign alignment test. Run in a subprocess with the overlay first on PYTHONPATH so +the official repo + its pinned transformers/peft shadow the main environment; torch and CUDA come +from the main env. Writes the official scores and input tensors (hashes) to --output for the test +to compare against the port. +""" + +import argparse +import json +import subprocess +import sys +from pathlib import Path + +import numpy as np +from PIL import Image + +OFFICIAL_REVISION = "219ab9db64c045e5181a2202d11f686439351292" + +SAMPLES = [ + ((256, 256, 8), 17, "a red ball bouncing on a wooden floor"), + ((512, 512, 4), 53, "a slow camera pan across a mountain lake at sunrise"), + ((768, 512, 8), 91, "a dog runs across a grassy field as the camera follows it"), +] + + +def make_video(width, height, frames, offset): + video = [] + for t in range(frames): + y, x = np.indices((height, width)) + rgb = np.empty((height, width, 3), dtype=np.uint8) + rgb[..., 0] = (3 * x + y + offset + 17 * t) % 256 + rgb[..., 1] = (x + 5 * y + 2 * offset + 13 * t) % 256 + rgb[..., 2] = (7 * x + 11 * y + 3 * offset + 7 * t) % 256 + video.append(Image.fromarray(rgb)) + return video + + +def _sha256(tensor): + import hashlib + + return hashlib.sha256(tensor.detach().float().cpu().contiguous().numpy().tobytes()).hexdigest() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--repo-dir", required=True) + parser.add_argument("--checkpoint-dir", required=True) + parser.add_argument("--model-path", required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + + sys.path.insert(0, args.repo_dir) + + import torch + + revision = subprocess.check_output(["git", "-C", args.repo_dir, "rev-parse", "HEAD"], text=True).strip() + if revision != OFFICIAL_REVISION: + raise ValueError(f"Expected VideoAlign revision {OFFICIAL_REVISION}, got {revision}") + + import inference + from prompt_template import build_prompt + from vision_process import process_vision_info + + original_create = inference.create_model_and_processor + + def create_local_model(*, model_config, peft_lora_config, training_args): + model_config.model_name_or_path = args.model_path + training_args.disable_flash_attn2 = True + return original_create( + model_config=model_config, peft_lora_config=peft_lora_config, training_args=training_args + ) + + inference.create_model_and_processor = create_local_model + inferencer = inference.VideoVLMRewardInference( + load_from_pretrained=args.checkpoint_dir, device="cuda", dtype=torch.bfloat16 + ) + processor = inferencer.processor + model = inferencer.model + data_config = inferencer.data_config + + samples = [] + chats = [] + for (w, h, f), offset, prompt in SAMPLES: + frames = make_video(w, h, f, offset) + chat = [ + [ + { + "role": "user", + "content": [ + { + "type": "video", + "video": frames, + "max_pixels": data_config.max_frame_pixels, + "fps": data_config.fps, + "sample_type": data_config.sample_type, + }, + { + "type": "text", + "text": build_prompt(prompt, data_config.eval_dim, data_config.prompt_template_type), + }, + ], + } + ] + ] + chats.extend(chat) + image_inputs, video_inputs = process_vision_info(chat) + texts = processor.apply_chat_template(chat, tokenize=False, add_generation_prompt=True) + batch = processor( + text=texts, + images=image_inputs, + videos=video_inputs, + padding=True, + return_tensors="pt", + videos_kwargs={"do_rescale": True}, + ) + batch = {k: (v.to("cuda") if torch.is_tensor(v) else v) for k, v in batch.items()} + with torch.no_grad(): + logits = model(return_dict=True, **batch)["logits"] # [1, 3] + samples.append( + { + "width": w, + "height": h, + "frames": f, + "offset": offset, + "prompt": prompt, + "VQ": float(logits[0][0]), + "MQ": float(logits[0][1]), + "TA": float(logits[0][2]), + "input_ids": batch["input_ids"][0].tolist(), + "video_grid_thw": batch["video_grid_thw"][0].tolist(), + "pixel_values_videos_shape": list(batch["pixel_values_videos"].shape), + "pixel_values_videos_sha256": _sha256(batch["pixel_values_videos"]), + } + ) + + image_inputs, video_inputs = process_vision_info(chats) + texts = processor.apply_chat_template(chats, tokenize=False, add_generation_prompt=True) + batch = processor(text=texts, images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt") + batch = {k: v.to("cuda") for k, v in batch.items()} + with torch.no_grad(): + batch_scores = model(return_dict=True, **batch)["logits"].float().cpu().tolist() + Path(args.output).write_text( + json.dumps({"revision": revision, "samples": samples, "batch_scores": batch_scores}, indent=1) + "\n" + ) + + +if __name__ == "__main__": + main()