Add support for video references in MiniMax H3 ref2va
This commit is contained in:
1 parent
4900e5e866
commit
97bf49edad
10 files changed
+668
-74
No files matched your search
@@ -62,6 +62,8 @@ from toolkit.util.quantize import get_qtype, quantize, quantize_model
|
||||
from optimum.quanto import freeze
|
||||
|
||||
from .src import packing
|
||||
|
||||
packing_video_exts = [".mp4", ".avi", ".mov", ".webm", ".mkv", ".wmv", ".m4v", ".flv"]
|
||||
from .src.audio_vae import MiniMaxH3AudioVAE, fold_audio_vae_weight_norm
|
||||
from .src.packing import (
|
||||
KEYFRAME_ENCODE_SEED,
|
||||
@@ -75,7 +77,13 @@ from .src.packing import (
|
||||
unpatchify_video_tokens,
|
||||
)
|
||||
from .src.pipeline import MiniMaxH3Pipeline
|
||||
from .src.text_encoder import TEXT_ENCODER_LAYER, encode_minimax_h3_prompt
|
||||
from .src.ref_video_cache import load_ref_video_latent
|
||||
from .src.text_encoder import (
|
||||
TEXT_ENCODER_LAYER,
|
||||
VideoRef,
|
||||
encode_minimax_h3_prompt,
|
||||
load_video_ref,
|
||||
)
|
||||
from .src.transformer import MiniMaxH3Transformer, MiniMaxH3TransformerParams
|
||||
from .src.vae import MiniMaxH3VideoVAE
|
||||
|
||||
@@ -664,6 +672,9 @@ class MinimaxH3Model(BaseModel):
|
||||
pil_images.append(
|
||||
Image.fromarray(arr.permute(1, 2, 0).cpu().numpy())
|
||||
)
|
||||
elif isinstance(img, str):
|
||||
# a control VIDEO path: 2 fps timestamped presentation
|
||||
pil_images.append(load_video_ref(img))
|
||||
else:
|
||||
pil_images.append(img)
|
||||
if len(pil_images) == 1:
|
||||
@@ -824,7 +835,7 @@ class MinimaxH3Model(BaseModel):
|
||||
"""Build the packed sequence's condition segment for one train step.
|
||||
|
||||
``latent_shape`` is the target's ``(t_lat, h_lat, w_lat)``. Returns
|
||||
``(cond_rows, keyframe_anchors, image_ref_shapes)`` where ``cond_rows``
|
||||
``(cond_rows, cond_audio_rows, keyframe_anchors, ref_blocks)`` where ``cond_rows``
|
||||
is ``(B, num_condition_rows, 96)`` or None. The base model implements
|
||||
fl2va: the clip's first frame as a keyframe when the dataset asks for
|
||||
i2v. MinimaxH3Ref2VAModel overrides this with image references from
|
||||
@@ -835,7 +846,7 @@ class MinimaxH3Model(BaseModel):
|
||||
and getattr(batch, "num_frames", 1) > 1
|
||||
)
|
||||
if not do_i2v:
|
||||
return None, (), ()
|
||||
return None, None, (), ()
|
||||
|
||||
if batch.first_frame_latents is not None:
|
||||
first_latents = batch.first_frame_latents.to(device, torch.float32)
|
||||
@@ -857,7 +868,7 @@ class MinimaxH3Model(BaseModel):
|
||||
KEYFRAME_NOISE_AUG_T * first_latents
|
||||
+ (1.0 - KEYFRAME_NOISE_AUG_T) * cond_noise
|
||||
)
|
||||
return patchify_video_latents(first_latents).to(dtype), ("first",), ()
|
||||
return patchify_video_latents(first_latents).to(dtype), None, ("first",), ()
|
||||
|
||||
def get_noise_prediction(
|
||||
self,
|
||||
@@ -896,9 +907,12 @@ class MinimaxH3Model(BaseModel):
|
||||
t_a = 1.0 - sigma_a
|
||||
|
||||
# --- conditioning rows (fl2va keyframe / ref2va references) ----
|
||||
cond_rows, keyframe_anchors, image_ref_shapes = self._build_condition(
|
||||
batch, (t_lat, h_lat, w_lat), device, dtype
|
||||
)
|
||||
(
|
||||
cond_rows,
|
||||
cond_audio_rows,
|
||||
keyframe_anchors,
|
||||
ref_blocks,
|
||||
) = self._build_condition(batch, (t_lat, h_lat, w_lat), device, dtype)
|
||||
|
||||
# --- audio rows -------------------------------------------------
|
||||
if batch is not None and getattr(batch, "num_frames", None):
|
||||
@@ -983,7 +997,7 @@ class MinimaxH3Model(BaseModel):
|
||||
latent_width=w_lat,
|
||||
num_audio_latents=a_lat,
|
||||
keyframe_anchors=keyframe_anchors,
|
||||
image_ref_shapes=image_ref_shapes,
|
||||
ref_blocks=ref_blocks,
|
||||
)
|
||||
)
|
||||
(
|
||||
@@ -995,14 +1009,20 @@ class MinimaxH3Model(BaseModel):
|
||||
_,
|
||||
) = pad_layouts_to_batch(layouts)
|
||||
num_cond = layouts[0].num_condition_video_rows
|
||||
num_cond_audio = layouts[0].num_condition_audio_rows
|
||||
|
||||
# per-row timesteps: text/video rows at t_v, audio rows at t_a,
|
||||
# condition rows pinned at max(t_v, 0.999)
|
||||
# condition rows pinned at max(t_v, 0.999); ref soundtracks clean
|
||||
row_t = t_v.view(-1, 1).expand(-1, token_tags.shape[1]).clone()
|
||||
row_t[:, audio_indices] = t_a.view(-1, 1)
|
||||
if num_cond > 0:
|
||||
cond_t = torch.maximum(t_v, torch.full_like(t_v, KEYFRAME_NOISE_AUG_T))
|
||||
row_t[:, video_indices[:num_cond]] = cond_t.view(-1, 1)
|
||||
if num_cond_audio > 0:
|
||||
row_t[:, audio_indices[:num_cond_audio]] = 1.0
|
||||
audio_rows = torch.cat(
|
||||
[cond_audio_rows.to(audio_rows.dtype), audio_rows], dim=1
|
||||
)
|
||||
|
||||
# pad text embeds to the batch max length
|
||||
max_text = int(text_indices.shape[0])
|
||||
@@ -1034,6 +1054,9 @@ class MinimaxH3Model(BaseModel):
|
||||
text_indices=text_indices.to(device),
|
||||
)
|
||||
|
||||
if num_cond_audio > 0:
|
||||
# reference soundtrack rows are conditioning, not targets
|
||||
audio_pred = audio_pred[:, num_cond_audio:]
|
||||
if batch is not None and batch.audio_target is not None:
|
||||
# flip to ai-toolkit's noise - clean convention
|
||||
if is_primary_pred:
|
||||
@@ -1199,6 +1222,9 @@ class MinimaxH3Ref2VAModel(MinimaxH3Model):
|
||||
# their ORIGINAL size — this model does its own area-matched resize
|
||||
self.has_multiple_control_images = True
|
||||
self.use_raw_control_images = True
|
||||
# control VIDEOS are cached like dataset items and consumed as
|
||||
# multi-frame reference blocks
|
||||
self.supports_video_control_images = True
|
||||
|
||||
def _dit_component(self) -> str:
|
||||
partition = str(
|
||||
@@ -1220,7 +1246,7 @@ class MinimaxH3Ref2VAModel(MinimaxH3Model):
|
||||
# raw-size control tensors in [0, 1]; each is resized to the TARGET's
|
||||
# pixel area with its own aspect kept, then encoded on its own grid
|
||||
if batch is None:
|
||||
return None, (), ()
|
||||
return None, None, (), ()
|
||||
controls_per_item = None
|
||||
if batch.control_tensor_list is not None:
|
||||
controls_per_item = batch.control_tensor_list
|
||||
@@ -1229,7 +1255,11 @@ class MinimaxH3Ref2VAModel(MinimaxH3Model):
|
||||
[batch.control_tensor[b]] for b in range(batch.control_tensor.shape[0])
|
||||
]
|
||||
if not controls_per_item:
|
||||
return None, (), ()
|
||||
controls_per_item = (
|
||||
[[] for _ in batch.file_items] if batch.file_items else []
|
||||
)
|
||||
if not controls_per_item:
|
||||
return None, None, (), ()
|
||||
ref_count = len(controls_per_item[0])
|
||||
if any(len(c) != ref_count for c in controls_per_item):
|
||||
raise ValueError(
|
||||
@@ -1278,7 +1308,151 @@ class MinimaxH3Ref2VAModel(MinimaxH3Model):
|
||||
)
|
||||
ref_shapes.append((ref_latents.shape[3], ref_latents.shape[4]))
|
||||
all_rows.append(patchify_video_latents(ref_latents).to(dtype))
|
||||
return torch.cat(all_rows, dim=1), (), tuple(ref_shapes)
|
||||
|
||||
blocks = [(1, h, w, 0) for h, w in ref_shapes]
|
||||
audio_rows = []
|
||||
self._append_video_ref_blocks(
|
||||
batch, all_rows, audio_rows, blocks, device, dtype
|
||||
)
|
||||
if not all_rows:
|
||||
return None, None, (), ()
|
||||
cond_audio = torch.cat(audio_rows, dim=1) if audio_rows else None
|
||||
return torch.cat(all_rows, dim=1), cond_audio, (), tuple(blocks)
|
||||
|
||||
@torch.no_grad()
|
||||
def _encode_ref_video_for_sampling(self, path: str, gen_config) -> torch.Tensor:
|
||||
"""Decode a reference video, sample it evenly onto the 17n+5 grid
|
||||
(capped at the sample's frame count), area-match it to the target with
|
||||
its own aspect, and encode with the released keyframe recipe. Returns
|
||||
normalized latents (C, T, h, w)."""
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
cap = cv2.VideoCapture(path)
|
||||
if not cap.isOpened():
|
||||
raise ValueError(f"Could not open reference video {path}")
|
||||
total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
n = packing.align_num_frames_down(min(total, max(gen_config.num_frames, 5)))
|
||||
indices = [round(i * (total - 1) / max(n - 1, 1)) for i in range(n)]
|
||||
frames = []
|
||||
for idx in indices:
|
||||
cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
|
||||
ok, frame = cap.read()
|
||||
if not ok:
|
||||
break
|
||||
frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
||||
cap.release()
|
||||
if len(frames) != n:
|
||||
n = packing.align_num_frames_down(max(len(frames), 5))
|
||||
frames = frames[:n]
|
||||
h0, w0 = frames[0].shape[:2]
|
||||
ph, pw = packing.reference_pixel_size(
|
||||
w0, h0, gen_config.height, gen_config.width
|
||||
)
|
||||
pixels = torch.from_numpy(np.stack(frames)).float() / 255.0 * 2.0 - 1.0
|
||||
pixels = pixels.permute(3, 0, 1, 2)[None] # (1, 3, T, H, W)
|
||||
pixels = (
|
||||
torch.nn.functional.interpolate(
|
||||
pixels.reshape(1 * 3, len(frames), h0, w0).transpose(0, 1),
|
||||
size=(ph, pw),
|
||||
mode="bilinear",
|
||||
antialias=True,
|
||||
)
|
||||
.transpose(0, 1)
|
||||
.reshape(1, 3, len(frames), ph, pw)
|
||||
)
|
||||
generator = torch.Generator(device="cpu").manual_seed(KEYFRAME_ENCODE_SEED)
|
||||
latents = self.video_vae.encode(
|
||||
pixels.to(self.vae.device, self.video_vae.dtype),
|
||||
sample=True,
|
||||
generator=generator,
|
||||
fp16_round=True,
|
||||
)
|
||||
# soundtrack rides clean when the clip has one (best effort)
|
||||
audio_rows = None
|
||||
try:
|
||||
import torchaudio
|
||||
|
||||
waveform, sample_rate = torchaudio.load(path)
|
||||
rows = self.encode_audio(
|
||||
[{"waveform": waveform, "sample_rate": sample_rate}]
|
||||
)[0]
|
||||
a_lat = packing.audio_latent_num_frames(n)
|
||||
audio_rows = self._fit_audio_rows(rows.float(), a_lat)
|
||||
except Exception:
|
||||
pass
|
||||
return {"latent": latents[0].float(), "audio_rows": audio_rows}
|
||||
|
||||
def _append_video_ref_blocks(
|
||||
self, batch, all_rows, audio_rows, blocks, device, dtype
|
||||
):
|
||||
# control videos get dataset-identical treatment (frame count, fps,
|
||||
# bucket) and one VAE encode, disk-cached next to the video; the
|
||||
# resulting latents become multi-frame reference blocks packed after
|
||||
# the image references
|
||||
paths_per_item = getattr(batch, "control_video_paths_list", None)
|
||||
if not paths_per_item:
|
||||
return
|
||||
vid_count = len(paths_per_item[0])
|
||||
if any(len(v) != vid_count for v in paths_per_item):
|
||||
raise ValueError(
|
||||
"ref2va: every item in a batch must have the same number of "
|
||||
"reference videos"
|
||||
)
|
||||
for ref_idx in range(vid_count):
|
||||
lats = []
|
||||
auds = []
|
||||
for per_item in paths_per_item:
|
||||
entry = load_ref_video_latent(
|
||||
self, per_item[ref_idx], batch.dataset_config
|
||||
)
|
||||
lats.append(entry["latent"].to(device, torch.float32))
|
||||
auds.append(entry.get("audio_rows"))
|
||||
shapes = {tuple(l.shape) for l in lats}
|
||||
if len(shapes) > 1:
|
||||
raise ValueError(
|
||||
"ref2va: reference video latent shapes must match across a "
|
||||
f"batch (got {sorted(shapes)}); use batch_size 1"
|
||||
)
|
||||
ref_latents = torch.stack(lats) # (B, C, T, h, w)
|
||||
ref_noise = torch.randn_like(ref_latents)
|
||||
ref_latents = (
|
||||
KEYFRAME_NOISE_AUG_T * ref_latents
|
||||
+ (1.0 - KEYFRAME_NOISE_AUG_T) * ref_noise
|
||||
)
|
||||
# soundtrack rows ride clean when every item in the batch has them
|
||||
a_lat = 0
|
||||
if all(a is not None for a in auds):
|
||||
a_lat = packing.audio_latent_num_frames(entry["num_frames"])
|
||||
trimmed = [
|
||||
self._fit_audio_rows(a.to(device, torch.float32), a_lat)
|
||||
for a in auds
|
||||
]
|
||||
if len({t.shape for t in trimmed}) == 1:
|
||||
audio_rows.append(torch.stack(trimmed).to(dtype))
|
||||
else:
|
||||
a_lat = 0
|
||||
blocks.append(
|
||||
(
|
||||
ref_latents.shape[2],
|
||||
ref_latents.shape[3],
|
||||
ref_latents.shape[4],
|
||||
a_lat,
|
||||
)
|
||||
)
|
||||
all_rows.append(patchify_video_latents(ref_latents).to(dtype))
|
||||
|
||||
@staticmethod
|
||||
def _fit_audio_rows(rows: torch.Tensor, a_lat: int) -> torch.Tensor:
|
||||
"""Trim/pad channel-major packed rows (2*T, C) to 2*a_lat rows,
|
||||
per stereo channel."""
|
||||
t = rows.shape[0] // 2
|
||||
per_ch = rows.reshape(2, t, rows.shape[-1])
|
||||
if t > a_lat:
|
||||
per_ch = per_ch[:, :a_lat]
|
||||
elif t < a_lat:
|
||||
per_ch = torch.nn.functional.pad(per_ch, (0, 0, 0, a_lat - t))
|
||||
return per_ch.reshape(2 * a_lat, rows.shape[-1])
|
||||
|
||||
def generate_single_image(
|
||||
self,
|
||||
@@ -1304,8 +1478,9 @@ class MinimaxH3Ref2VAModel(MinimaxH3Model):
|
||||
gen_config.log_image = partial(blank_log_image_function, gen_config)
|
||||
gen_config.output_ext = "mp4"
|
||||
|
||||
# every ctrl image is a REFERENCE (never a first frame): resized to
|
||||
# the target's pixel area with its own aspect kept
|
||||
# every ctrl file is a REFERENCE (never a first frame): images are
|
||||
# resized to the target's pixel area with their own aspect kept;
|
||||
# videos are dataset-style encoded into multi-frame latent blocks
|
||||
ref_images = []
|
||||
for path in (
|
||||
gen_config.ctrl_img,
|
||||
@@ -1313,7 +1488,13 @@ class MinimaxH3Ref2VAModel(MinimaxH3Model):
|
||||
gen_config.ctrl_img_2,
|
||||
gen_config.ctrl_img_3,
|
||||
):
|
||||
if path is not None:
|
||||
if path is None:
|
||||
continue
|
||||
if os.path.splitext(str(path))[1].lower() in packing_video_exts:
|
||||
ref_images.append(
|
||||
self._encode_ref_video_for_sampling(str(path), gen_config)
|
||||
)
|
||||
else:
|
||||
img = Image.open(path).convert("RGB")
|
||||
ref_images.append(
|
||||
packing.prepare_reference_image(
|
||||
|
||||
Reference in new issue
Block a user