Spaces:
Running on Zero
Running on Zero
Commit ·
e4e93b7
1
Parent(s): e10f5f9
Read references on threads
Browse files
inference/cli/minimax_h3_ref2va.py
CHANGED
|
@@ -33,7 +33,7 @@ from diffusers.utils import export_to_video
|
|
| 33 |
|
| 34 |
from codecopsd.attention import BACKENDS, set_attention
|
| 35 |
from codecopsd.configs import load
|
| 36 |
-
from codecopsd.pipelines.minimax_h3_ref2va import load_reference, stage_times
|
| 37 |
|
| 38 |
from ..hardware import announce, cap_gpu_memory, vlm_files_gb
|
| 39 |
from ..load import RESIDENT_GB, build_pipeline, place, vlm_notice, vlm_source
|
|
@@ -155,7 +155,7 @@ def main(argv=None):
|
|
| 155 |
if args.offload == "auto": # every model resident when the GPU holds them all with room (B200: 180 GB), as the demo
|
| 156 |
args.offload = "none" if total >= RESIDENT_GB else "model"
|
| 157 |
vlm_notice(vlm, args.offload)
|
| 158 |
-
references =
|
| 159 |
pipe = build_pipeline("minimax_h3_ref2va", args.model, args.lora, args.lora_weight_name, args.text_encoder,
|
| 160 |
args.sampler, args.sampler_weights, text_encoder_path=vlm["path"])
|
| 161 |
if args.sampler == "flash" and args.vae_encoder == "taeh3": # the extreme path only (inference/extreme.py)
|
|
|
|
| 33 |
|
| 34 |
from codecopsd.attention import BACKENDS, set_attention
|
| 35 |
from codecopsd.configs import load
|
| 36 |
+
from codecopsd.pipelines.minimax_h3_ref2va import load_reference, map_references, stage_times
|
| 37 |
|
| 38 |
from ..hardware import announce, cap_gpu_memory, vlm_files_gb
|
| 39 |
from ..load import RESIDENT_GB, build_pipeline, place, vlm_notice, vlm_source
|
|
|
|
| 155 |
if args.offload == "auto": # every model resident when the GPU holds them all with room (B200: 180 GB), as the demo
|
| 156 |
args.offload = "none" if total >= RESIDENT_GB else "model"
|
| 157 |
vlm_notice(vlm, args.offload)
|
| 158 |
+
references = map_references(load_reference, args.reference) # one thread per reference
|
| 159 |
pipe = build_pipeline("minimax_h3_ref2va", args.model, args.lora, args.lora_weight_name, args.text_encoder,
|
| 160 |
args.sampler, args.sampler_weights, text_encoder_path=vlm["path"])
|
| 161 |
if args.sampler == "flash" and args.vae_encoder == "taeh3": # the extreme path only (inference/extreme.py)
|
inference/demo/requests.py
CHANGED
|
@@ -17,6 +17,7 @@ import time
|
|
| 17 |
from pathlib import Path
|
| 18 |
|
| 19 |
import gradio as gr
|
|
|
|
| 20 |
import torch
|
| 21 |
from diffusers.utils import export_to_video
|
| 22 |
from PIL import ImageOps
|
|
@@ -37,10 +38,12 @@ from .views import draw_references, read_references
|
|
| 37 |
# TODO: Be careful to check whether the teacher (Run: Teacher, every reference token) fits in the 96 GB of an RTX PRO
|
| 38 |
# 6000, our main target GPU, for every sample we choose. If it runs out of memory there, record the teacher as OOM for
|
| 39 |
# that sample.
|
| 40 |
-
def run_one(name, who, report, call, steps_key):
|
| 41 |
"""One model's run of a request, alone on the GPU (other requests may run between the Student and the Teacher).
|
| 42 |
Returns dict(result, denoise, total, calls, refs, drop). On a ZeroGPU Space the GPU part runs in the worker process
|
| 43 |
-
of a GPU that ZeroGPU lends to this run (`zerogpu.run_one`); elsewhere here, after the requests before it.
|
|
|
|
|
|
|
| 44 |
if zerogpu.ON:
|
| 45 |
run = zerogpu.run_one(name, who, report, call, steps_key)
|
| 46 |
else:
|
|
@@ -56,21 +59,40 @@ def run_one(name, who, report, call, steps_key):
|
|
| 56 |
return run
|
| 57 |
STEPS[run["steps_key"]] = run["calls"]
|
| 58 |
seen = run.pop("seen") # the references as the model read them (CPU copies), drawn after the GPU is free
|
| 59 |
-
|
| 60 |
-
report.stage("Finish: drawing the kept tokens")
|
| 61 |
-
t = time.perf_counter()
|
| 62 |
-
refs, share = draw_references(seen)
|
| 63 |
-
drawn = time.perf_counter() - t
|
| 64 |
report.log(f"{WHO[who]}: denoise {run['denoise']:.1f} s, total {run['total']:.1f} s"
|
| 65 |
+ ("" if share is None else f", {1 - share:.0%} of the reference tokens dropped")
|
| 66 |
+ f", GPU memory {run.pop('resident'):.1f} GB resident, peak {run['peak']:.1f} GB; {run.pop('stages')}; "
|
| 67 |
+ "progress counts " + ", ".join(f"{k} {d}/{n}" for k, (d, n) in run.pop("work").items()))
|
| 68 |
-
if
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
| 71 |
return run
|
| 72 |
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
def gpu_part(name, who, report, call, steps_key):
|
| 75 |
"""The GPU part of `run_one`: the pipeline of `name` loaded, the call made with the LoRA on (Ours) or off (the
|
| 76 |
Teacher), its timings read, and CPU copies of the references as the model read them (`seen`). Returns
|
|
@@ -215,6 +237,7 @@ def run_image_raw(prompt, files, size, strategy, picture_motion, picture_residua
|
|
| 215 |
"both" the Teacher first); the last yield holds every result. The results of a request with the inputs of a bundled
|
| 216 |
example are stored for it when it has none yet. `page`: `page_for` of the viewer (None: no page)."""
|
| 217 |
from codecopsd.pipelines.minimax_h3_image.pipeline_minimax_h3_image import reference_size
|
|
|
|
| 218 |
report = report or Report()
|
| 219 |
paths = input_paths(files)
|
| 220 |
report.log(f"image, Run {mode}: {len(paths)} pictures {[Path(p).name for p in paths]}, size {size!r}, seed {seed}, "
|
|
@@ -227,7 +250,7 @@ def run_image_raw(prompt, files, size, strategy, picture_motion, picture_residua
|
|
| 227 |
raise Refused("Add at least one reference picture: this model generates from references.")
|
| 228 |
seed = parse_seed(seed)
|
| 229 |
codec = parse_codec(strategy, None, None, None, picture_motion, picture_residual, vlm, vlm_scale, video=False)
|
| 230 |
-
images =
|
| 231 |
check_tags(prompt, len(images))
|
| 232 |
if str(size).startswith("first"):
|
| 233 |
height, width = reference_size(images[0])
|
|
@@ -306,6 +329,7 @@ def run_video_raw(prompt, files, size, frames, strategy, video_drop, video_motio
|
|
| 306 |
example are stored for it when it has none yet. `page`: `page_for` of the viewer (None: no page). `audio`: the
|
| 307 |
Settings switch, the soundtrack generated with the video and put into the mp4 (part of the request, so a request
|
| 308 |
with audio never shows or stores an example's silent result)."""
|
|
|
|
| 309 |
report = report or Report()
|
| 310 |
paths = input_paths(files)
|
| 311 |
report.log(f"video, Run {mode}: {len(paths)} references {[Path(p).name for p in paths]}, size {size!r}, "
|
|
@@ -332,7 +356,7 @@ def run_video_raw(prompt, files, size, frames, strategy, video_drop, video_motio
|
|
| 332 |
f"{', '.join(map(str, state.PAGE['frames']))}).")
|
| 333 |
codec = parse_codec(strategy, video_drop, video_motion, video_residual, picture_motion, picture_residual, vlm,
|
| 334 |
vlm_scale)
|
| 335 |
-
references =
|
| 336 |
kinds = [r.kind for r in references]
|
| 337 |
check_tags(prompt, kinds.count("image"), kinds.count("video"), video_tab=True)
|
| 338 |
except Refused as e:
|
|
@@ -345,14 +369,14 @@ def run_video_raw(prompt, files, size, frames, strategy, video_drop, video_motio
|
|
| 345 |
seed, audio])))
|
| 346 |
order = ["released", "student"] if mode == "both" else [mode] # Teacher first: the GPU warm-up falls on it
|
| 347 |
runs, page = {}, page if page is not None else new_page()
|
| 348 |
-
sources =
|
| 349 |
asked = re.fullmatch(r"\s*(\d+)\s*[x×X*,]\s*(\d+)\s*", str(size))
|
| 350 |
rounded = [] if (int(asked[1]), int(asked[2])) == (height, width) else [
|
| 351 |
f"Output {asked[1]} x {asked[2]} rounded to {height} x {width} (multiples of 32)."]
|
| 352 |
setting = (f"output {height} x {width}, {frames} frames{', with audio' if audio else ''}", codec["text"])
|
| 353 |
page["running"].update({w: report.id for w in order})
|
| 354 |
-
out = lambda final: finish(state.VIDEO, ex, runs, order, rounded, setting=setting,
|
| 355 |
-
|
| 356 |
|
| 357 |
def call(who):
|
| 358 |
return VideoCall(who, prompt, references, sources, height, width, frames, codec, seed, audio,
|
|
@@ -361,7 +385,7 @@ def run_video_raw(prompt, files, size, frames, strategy, video_drop, video_motio
|
|
| 361 |
try:
|
| 362 |
yield out(False)
|
| 363 |
for who in order:
|
| 364 |
-
run = run_one(state.VIDEO, who, report, call(who), sampler_of)
|
| 365 |
if run.get("oom"): # a run past the GPU memory budget: said under the outputs, the other run stays
|
| 366 |
remember(state.VIDEO, ex, who, run)
|
| 367 |
runs[who] = page["fresh"][who] = run
|
|
@@ -381,9 +405,14 @@ def run_video_raw(prompt, files, size, frames, strategy, video_drop, video_motio
|
|
| 381 |
export_to_video(run["result"], path, fps=24)
|
| 382 |
run["clock"].add("write the video file (mp4)", time.perf_counter() - t)
|
| 383 |
run["result"] = path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
finish_stats(run, state.VIDEO, who, ex)
|
| 385 |
remember(state.VIDEO, ex, who, run)
|
| 386 |
-
runs[who] = page["fresh"][who] = run
|
| 387 |
release(page, who, report.id)
|
| 388 |
report.quiet()
|
| 389 |
yield out(who == order[-1])
|
|
|
|
| 17 |
from pathlib import Path
|
| 18 |
|
| 19 |
import gradio as gr
|
| 20 |
+
import numpy as np
|
| 21 |
import torch
|
| 22 |
from diffusers.utils import export_to_video
|
| 23 |
from PIL import ImageOps
|
|
|
|
| 38 |
# TODO: Be careful to check whether the teacher (Run: Teacher, every reference token) fits in the 96 GB of an RTX PRO
|
| 39 |
# 6000, our main target GPU, for every sample we choose. If it runs out of memory there, record the teacher as OOM for
|
| 40 |
# that sample.
|
| 41 |
+
def run_one(name, who, report, call, steps_key, draw=True):
|
| 42 |
"""One model's run of a request, alone on the GPU (other requests may run between the Student and the Teacher).
|
| 43 |
Returns dict(result, denoise, total, calls, refs, drop). On a ZeroGPU Space the GPU part runs in the worker process
|
| 44 |
+
of a GPU that ZeroGPU lends to this run (`zerogpu.run_one`); elsewhere here, after the requests before it.
|
| 45 |
+
`draw=False`: the views of the kept tokens are not drawn yet (`draw_views` draws them after the result is on the
|
| 46 |
+
page); the run keeps the references as the model read them in "seen"."""
|
| 47 |
if zerogpu.ON:
|
| 48 |
run = zerogpu.run_one(name, who, report, call, steps_key)
|
| 49 |
else:
|
|
|
|
| 59 |
return run
|
| 60 |
STEPS[run["steps_key"]] = run["calls"]
|
| 61 |
seen = run.pop("seen") # the references as the model read them (CPU copies), drawn after the GPU is free
|
| 62 |
+
share = kept_share(seen)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
report.log(f"{WHO[who]}: denoise {run['denoise']:.1f} s, total {run['total']:.1f} s"
|
| 64 |
+ ("" if share is None else f", {1 - share:.0%} of the reference tokens dropped")
|
| 65 |
+ f", GPU memory {run.pop('resident'):.1f} GB resident, peak {run['peak']:.1f} GB; {run.pop('stages')}; "
|
| 66 |
+ "progress counts " + ", ".join(f"{k} {d}/{n}" for k, (d, n) in run.pop("work").items()))
|
| 67 |
+
run.update(refs=[], drop=None if share is None else 1 - share)
|
| 68 |
+
if draw:
|
| 69 |
+
draw_views(run, seen, report)
|
| 70 |
+
else:
|
| 71 |
+
run["seen"] = seen
|
| 72 |
return run
|
| 73 |
|
| 74 |
|
| 75 |
+
def kept_share(seen):
|
| 76 |
+
"""The kept share of all reference tokens of `seen` (`read_references`), counted as `draw_references` counts it;
|
| 77 |
+
None without references."""
|
| 78 |
+
if not seen:
|
| 79 |
+
return None
|
| 80 |
+
masks = [np.asarray(mask, dtype=bool) for _, _, mask, _ in seen]
|
| 81 |
+
return sum(int(m.sum()) for m in masks) / max(sum(m.size for m in masks), 1)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def draw_views(run, seen, report=None):
|
| 85 |
+
"""The views of the kept tokens of the references (`draw_references`, written to outputs/app) into `run["refs"]`,
|
| 86 |
+
timed as a page row of the run. `report`: shows the stage on the progress line (None: the result stays in view)."""
|
| 87 |
+
if not seen:
|
| 88 |
+
return
|
| 89 |
+
if report is not None:
|
| 90 |
+
report.stage("Finish: drawing the kept tokens")
|
| 91 |
+
t = time.perf_counter()
|
| 92 |
+
run["refs"] = draw_references(seen)[0]
|
| 93 |
+
run["clock"].add(PAGE_ROWS[0], time.perf_counter() - t)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
def gpu_part(name, who, report, call, steps_key):
|
| 97 |
"""The GPU part of `run_one`: the pipeline of `name` loaded, the call made with the LoRA on (Ours) or off (the
|
| 98 |
Teacher), its timings read, and CPU copies of the references as the model read them (`seen`). Returns
|
|
|
|
| 237 |
"both" the Teacher first); the last yield holds every result. The results of a request with the inputs of a bundled
|
| 238 |
example are stored for it when it has none yet. `page`: `page_for` of the viewer (None: no page)."""
|
| 239 |
from codecopsd.pipelines.minimax_h3_image.pipeline_minimax_h3_image import reference_size
|
| 240 |
+
from codecopsd.pipelines.minimax_h3_ref2va import map_references
|
| 241 |
report = report or Report()
|
| 242 |
paths = input_paths(files)
|
| 243 |
report.log(f"image, Run {mode}: {len(paths)} pictures {[Path(p).name for p in paths]}, size {size!r}, seed {seed}, "
|
|
|
|
| 250 |
raise Refused("Add at least one reference picture: this model generates from references.")
|
| 251 |
seed = parse_seed(seed)
|
| 252 |
codec = parse_codec(strategy, None, None, None, picture_motion, picture_residual, vlm, vlm_scale, video=False)
|
| 253 |
+
images = map_references(open_picture, paths, range(1, len(paths) + 1)) # one thread per picture
|
| 254 |
check_tags(prompt, len(images))
|
| 255 |
if str(size).startswith("first"):
|
| 256 |
height, width = reference_size(images[0])
|
|
|
|
| 329 |
example are stored for it when it has none yet. `page`: `page_for` of the viewer (None: no page). `audio`: the
|
| 330 |
Settings switch, the soundtrack generated with the video and put into the mp4 (part of the request, so a request
|
| 331 |
with audio never shows or stores an example's silent result)."""
|
| 332 |
+
from codecopsd.pipelines.minimax_h3_ref2va import map_references
|
| 333 |
report = report or Report()
|
| 334 |
paths = input_paths(files)
|
| 335 |
report.log(f"video, Run {mode}: {len(paths)} references {[Path(p).name for p in paths]}, size {size!r}, "
|
|
|
|
| 356 |
f"{', '.join(map(str, state.PAGE['frames']))}).")
|
| 357 |
codec = parse_codec(strategy, video_drop, video_motion, video_residual, picture_motion, picture_residual, vlm,
|
| 358 |
vlm_scale)
|
| 359 |
+
references = map_references(lambda path, i: open_reference(path, i, frames), paths, range(1, len(paths) + 1))
|
| 360 |
kinds = [r.kind for r in references]
|
| 361 |
check_tags(prompt, kinds.count("image"), kinds.count("video"), video_tab=True)
|
| 362 |
except Refused as e:
|
|
|
|
| 369 |
seed, audio])))
|
| 370 |
order = ["released", "student"] if mode == "both" else [mode] # Teacher first: the GPU warm-up falls on it
|
| 371 |
runs, page = {}, page if page is not None else new_page()
|
| 372 |
+
sources = map_references(source_of, paths, references)
|
| 373 |
asked = re.fullmatch(r"\s*(\d+)\s*[x×X*,]\s*(\d+)\s*", str(size))
|
| 374 |
rounded = [] if (int(asked[1]), int(asked[2])) == (height, width) else [
|
| 375 |
f"Output {asked[1]} x {asked[2]} rounded to {height} x {width} (multiples of 32)."]
|
| 376 |
setting = (f"output {height} x {width}, {frames} frames{', with audio' if audio else ''}", codec["text"])
|
| 377 |
page["running"].update({w: report.id for w in order})
|
| 378 |
+
out = lambda final, note=(): finish(state.VIDEO, ex, runs, order, rounded + list(note), setting=setting,
|
| 379 |
+
final=final, page=page, me=report.id)
|
| 380 |
|
| 381 |
def call(who):
|
| 382 |
return VideoCall(who, prompt, references, sources, height, width, frames, codec, seed, audio,
|
|
|
|
| 385 |
try:
|
| 386 |
yield out(False)
|
| 387 |
for who in order:
|
| 388 |
+
run = run_one(state.VIDEO, who, report, call(who), sampler_of, draw=False)
|
| 389 |
if run.get("oom"): # a run past the GPU memory budget: said under the outputs, the other run stays
|
| 390 |
remember(state.VIDEO, ex, who, run)
|
| 391 |
runs[who] = page["fresh"][who] = run
|
|
|
|
| 405 |
export_to_video(run["result"], path, fps=24)
|
| 406 |
run["clock"].add("write the video file (mp4)", time.perf_counter() - t)
|
| 407 |
run["result"] = path
|
| 408 |
+
seen = run.pop("seen", None)
|
| 409 |
+
runs[who] = page["fresh"][who] = run
|
| 410 |
+
if seen: # the video on the page first; the views of the kept tokens drawn while the visitor watches it
|
| 411 |
+
report.quiet()
|
| 412 |
+
yield out(False, ["Drawing the kept tokens of the references ..."])
|
| 413 |
+
draw_views(run, seen) # no progress update: the video stays in view
|
| 414 |
finish_stats(run, state.VIDEO, who, ex)
|
| 415 |
remember(state.VIDEO, ex, who, run)
|
|
|
|
| 416 |
release(page, who, report.id)
|
| 417 |
report.quiet()
|
| 418 |
yield out(who == order[-1])
|
src/codecopsd/pipelines/minimax_h3_image/pipeline_minimax_h3_image.py
CHANGED
|
@@ -34,7 +34,7 @@ from ...models import MiniMaxH3ImageCodecOPSDTransformer2DModel, text_encoder_to
|
|
| 34 |
from ...models.fp8_linear import load_fp8_text_encoder
|
| 35 |
from ...stats import Clock
|
| 36 |
from ..minimax_h3_ref2va import MiniMaxH3CodecOPSDPipeline
|
| 37 |
-
from ..minimax_h3_ref2va.pipeline_minimax_h3_ref2va import vlm_prompt_embeds
|
| 38 |
from ..minimax_h3_ref2va.vlm_drop import drop_vision_rows, vision_token_keep
|
| 39 |
|
| 40 |
CONFIG = load("minimax_h3_image") # src/codecopsd/configs/minimax_h3_image.yaml
|
|
@@ -128,17 +128,20 @@ class MiniMaxH3ImageCodecOPSDPipeline(DiffusionPipeline):
|
|
| 128 |
|
| 129 |
def prepare_references(self, images):
|
| 130 |
"""Each picture upright and RGB, then its two released copies: the VAE's and the text encoder's (a short edge outside
|
| 131 |
-
`vae_short_edge` / `vision_short_edge` is resized to the nearer bound, multiples of 32).
|
| 132 |
-
|
| 133 |
-
|
| 134 |
image = ImageOps.exif_transpose(image).convert("RGB")
|
| 135 |
if min(image.size) < 32:
|
| 136 |
raise ValueError(f"a reference picture needs at least 32 pixels on each side, got {image.size}")
|
| 137 |
-
|
| 138 |
-
|
| 139 |
size = bound_short_edge(*image.size, low, high, CONFIG["canvas"]["multiple"])
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
@torch.no_grad()
|
| 144 |
def encode(self, prompt, images, generator=None, gaze=True, vlm_drop=None, teacher_text=False, gaze_overrides=None):
|
|
|
|
| 34 |
from ...models.fp8_linear import load_fp8_text_encoder
|
| 35 |
from ...stats import Clock
|
| 36 |
from ..minimax_h3_ref2va import MiniMaxH3CodecOPSDPipeline
|
| 37 |
+
from ..minimax_h3_ref2va.pipeline_minimax_h3_ref2va import map_references, vlm_prompt_embeds
|
| 38 |
from ..minimax_h3_ref2va.vlm_drop import drop_vision_rows, vision_token_keep
|
| 39 |
|
| 40 |
CONFIG = load("minimax_h3_image") # src/codecopsd/configs/minimax_h3_image.yaml
|
|
|
|
| 128 |
|
| 129 |
def prepare_references(self, images):
|
| 130 |
"""Each picture upright and RGB, then its two released copies: the VAE's and the text encoder's (a short edge outside
|
| 131 |
+
`vae_short_edge` / `vision_short_edge` is resized to the nearer bound, multiples of 32). One thread per picture
|
| 132 |
+
(`map_references`)."""
|
| 133 |
+
def two_copies(image):
|
| 134 |
image = ImageOps.exif_transpose(image).convert("RGB")
|
| 135 |
if min(image.size) < 32:
|
| 136 |
raise ValueError(f"a reference picture needs at least 32 pixels on each side, got {image.size}")
|
| 137 |
+
copies = []
|
| 138 |
+
for low, high in (CONFIG["references"]["vae_short_edge"], CONFIG["references"]["vision_short_edge"]):
|
| 139 |
size = bound_short_edge(*image.size, low, high, CONFIG["canvas"]["multiple"])
|
| 140 |
+
copies.append(image if image.size == size else self.image_processor.resize(image, size[1], size[0]))
|
| 141 |
+
return copies
|
| 142 |
+
|
| 143 |
+
pairs = map_references(two_copies, images)
|
| 144 |
+
return [vae for vae, _ in pairs], [vision for _, vision in pairs]
|
| 145 |
|
| 146 |
@torch.no_grad()
|
| 147 |
def encode(self, prompt, images, generator=None, gaze=True, vlm_drop=None, teacher_text=False, gaze_overrides=None):
|
src/codecopsd/pipelines/minimax_h3_ref2va/__init__.py
CHANGED
|
@@ -5,5 +5,7 @@ Authors: Boyang Wang, Kevin Blackburn-Matzen, Oindrila Saha, Matheus Gadelha, Ze
|
|
| 5 |
Copyright (c) 2026 The CodecOPSD Authors. All rights reserved.
|
| 6 |
"""
|
| 7 |
|
| 8 |
-
from .pipeline_minimax_h3_ref2va import
|
|
|
|
|
|
|
| 9 |
from .pipeline_output import MiniMaxH3CodecOPSDPipelineOutput
|
|
|
|
| 5 |
Copyright (c) 2026 The CodecOPSD Authors. All rights reserved.
|
| 6 |
"""
|
| 7 |
|
| 8 |
+
from .pipeline_minimax_h3_ref2va import (
|
| 9 |
+
MiniMaxH3CodecOPSDPipeline, add_audio_track, load_reference, map_references, stage_times,
|
| 10 |
+
)
|
| 11 |
from .pipeline_output import MiniMaxH3CodecOPSDPipelineOutput
|
src/codecopsd/pipelines/minimax_h3_ref2va/pipeline_minimax_h3_ref2va.py
CHANGED
|
@@ -22,7 +22,6 @@ from diffusers.modular_pipelines.minimax_h3.before_denoise import (
|
|
| 22 |
MiniMaxH3Ref2VAPrepareLayoutStep,
|
| 23 |
patchify_video_latents,
|
| 24 |
)
|
| 25 |
-
from diffusers.modular_pipelines.minimax_h3.before_encoder import MiniMaxH3Ref2VASetupStep
|
| 26 |
from diffusers.modular_pipelines.minimax_h3.encoders import (
|
| 27 |
MiniMaxH3Ref2VATextEncoderStep,
|
| 28 |
encode_vae_condition,
|
|
@@ -35,6 +34,7 @@ from diffusers.modular_pipelines.minimax_h3.modular_pipeline import (
|
|
| 35 |
MINIMAX_H3_VIDEO_TAG,
|
| 36 |
align_num_frames,
|
| 37 |
audio_latent_num_frames,
|
|
|
|
| 38 |
video_latent_num_frames,
|
| 39 |
)
|
| 40 |
from diffusers.modular_pipelines.minimax_h3.references import MiniMaxH3ImageReference, MiniMaxH3VideoReference
|
|
@@ -75,6 +75,33 @@ def video_tier(height, width):
|
|
| 75 |
smallest of `VIDEO_TIERS` whose short edge reaches the output's, the largest when none does (Pika H3 Flex's rule)."""
|
| 76 |
return next((t for t in VIDEO_TIERS if t[0] >= min(height, width)), VIDEO_TIERS[-1])
|
| 77 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
PICTURES = (".png", ".jpg", ".jpeg", ".webp", ".bmp")
|
| 79 |
|
| 80 |
|
|
@@ -142,6 +169,24 @@ def load_reference(path, num_frames=None):
|
|
| 142 |
return MiniMaxH3VideoReference(frames=np.stack(frames), fps=fps)
|
| 143 |
|
| 144 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
def stage_times(timings):
|
| 146 |
"""One line on where the reference encoding of a request went (`pipe.timings` after a call): preparing the
|
| 147 |
references, the VAE, the text encoder, and the codec gazer, which runs on the CPU while the VAE encodes. Every part is a
|
|
@@ -357,14 +402,16 @@ class MiniMaxH3CodecOPSDPipeline(DiffusionPipeline):
|
|
| 357 |
(references.picture_short_edge; released MiniMax-H3 reads every picture at 2048); a video first resized
|
| 358 |
onto the canvas of its own aspect ratio at the tier of the `height` x `width` output (`video_tier`, Pika H3
|
| 359 |
Flex's rule; without an output size the released 768 canvas), then at 24 fps, cut to `num_frames` and then to
|
| 360 |
-
the longest 17n + 5 frames the VAE encodes. Other sizes: `set_reference_sizes`.
|
|
|
|
|
|
|
| 361 |
sizes = self.reference_sizes or {}
|
| 362 |
short_edge, long_edge = sizes.get("picture_short_edge") or PICTURE_SHORT_EDGE, sizes.get("picture_long_edge")
|
| 363 |
video_edge = sizes.get("video_short_edge")
|
| 364 |
canvas = ((video_edge, video_edge * ((video_edge * 16 // 9 + 31) // 32 * 32)) if video_edge
|
| 365 |
else video_tier(height, width) if height and width else (CANVAS["short_edge"], CANVAS["max_pixels"]))
|
| 366 |
-
|
| 367 |
-
|
| 368 |
if ref.kind == "image":
|
| 369 |
image = ref.image if isinstance(ref.image, Image.Image) else Image.fromarray(np.asarray(ref.image))
|
| 370 |
image = image.convert("RGB")
|
|
@@ -376,19 +423,33 @@ class MiniMaxH3CodecOPSDPipeline(DiffusionPipeline):
|
|
| 376 |
scale = short_edge / min(width, height)
|
| 377 |
if long_edge:
|
| 378 |
scale = min(scale, long_edge / max(width, height))
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
elif ref.kind == "video":
|
| 383 |
-
frames = MiniMaxH3Ref2VASetupStep._normalize_video_condition(
|
| 384 |
-
ref.frames, float(ref.fps), num_frames, CANVAS["canvas_multiple"], *canvas, float(MINIMAX_H3_FPS),
|
| 385 |
-
)
|
| 386 |
if len(frames) < 22:
|
| 387 |
raise ValueError(f"a reference video needs at least 22 frames at 24 fps, got {len(frames)}")
|
| 388 |
-
|
| 389 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
else:
|
| 391 |
-
|
|
|
|
| 392 |
return out
|
| 393 |
|
| 394 |
@torch.no_grad()
|
|
|
|
| 22 |
MiniMaxH3Ref2VAPrepareLayoutStep,
|
| 23 |
patchify_video_latents,
|
| 24 |
)
|
|
|
|
| 25 |
from diffusers.modular_pipelines.minimax_h3.encoders import (
|
| 26 |
MiniMaxH3Ref2VATextEncoderStep,
|
| 27 |
encode_vae_condition,
|
|
|
|
| 34 |
MINIMAX_H3_VIDEO_TAG,
|
| 35 |
align_num_frames,
|
| 36 |
audio_latent_num_frames,
|
| 37 |
+
resolve_canvas_size,
|
| 38 |
video_latent_num_frames,
|
| 39 |
)
|
| 40 |
from diffusers.modular_pipelines.minimax_h3.references import MiniMaxH3ImageReference, MiniMaxH3VideoReference
|
|
|
|
| 75 |
smallest of `VIDEO_TIERS` whose short edge reaches the output's, the largest when none does (Pika H3 Flex's rule)."""
|
| 76 |
return next((t for t in VIDEO_TIERS if t[0] >= min(height, width)), VIDEO_TIERS[-1])
|
| 77 |
|
| 78 |
+
|
| 79 |
+
def video_frames(frames, fps, num_frames, canvas):
|
| 80 |
+
"""A reference video's frames as uint8 [T, H, W, 3] at 24 fps, cut to `num_frames`, and the (height, width) of the
|
| 81 |
+
canvas of its own aspect ratio (`canvas`: short edge, area cap) they go on: the steps of diffusers'
|
| 82 |
+
`MiniMaxH3Ref2VASetupStep._normalize_video_condition` (0.43.0) in the same order, without its final per-frame
|
| 83 |
+
LANCZOS resize, which `normalize_references` runs on threads."""
|
| 84 |
+
if isinstance(frames, list):
|
| 85 |
+
frames = np.stack([np.asarray(frame.convert("RGB")) for frame in frames])
|
| 86 |
+
if isinstance(frames, torch.Tensor):
|
| 87 |
+
frames = frames.movedim(-3, -1).cpu().numpy()
|
| 88 |
+
frames = np.asarray(frames)
|
| 89 |
+
if frames.dtype != np.uint8:
|
| 90 |
+
frames = (frames * 255.0).round().clip(0, 255).astype(np.uint8)
|
| 91 |
+
if frames.ndim != 4 or frames.shape[3] != 3:
|
| 92 |
+
raise ValueError(
|
| 93 |
+
f"A reference video must be `(num_frames, height, width, 3)` RGB frames, got {tuple(frames.shape)}.")
|
| 94 |
+
if fps <= 0:
|
| 95 |
+
raise ValueError(f"A reference video must have a positive frame rate, got {fps}.")
|
| 96 |
+
target_fps = float(MINIMAX_H3_FPS)
|
| 97 |
+
if fps != target_fps: # each frame held until the slot of the next one, as ffmpeg's fps filter does
|
| 98 |
+
scale = target_fps / fps
|
| 99 |
+
slots = np.floor(np.arange(frames.shape[0]) * scale + 0.5).astype(np.int64)
|
| 100 |
+
frames = np.repeat(frames, np.diff(slots, append=math.floor(frames.shape[0] * scale + 0.5)), axis=0)
|
| 101 |
+
frames = frames[:num_frames]
|
| 102 |
+
return frames, resolve_canvas_size(frames.shape[2], frames.shape[1], CANVAS["canvas_multiple"], *canvas)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
PICTURES = (".png", ".jpg", ".jpeg", ".webp", ".bmp")
|
| 106 |
|
| 107 |
|
|
|
|
| 169 |
return MiniMaxH3VideoReference(frames=np.stack(frames), fps=fps)
|
| 170 |
|
| 171 |
|
| 172 |
+
def map_references(fn, *iterables):
|
| 173 |
+
"""`[fn(*args) for args in zip(*iterables)]` on threads, the results in the same order: the reference files are
|
| 174 |
+
read and resized at the same time (PIL and the ffmpeg reader release the interpreter lock), with the same results.
|
| 175 |
+
At most half the CPU cores, since the codec gazer runs x264 and its reader on the CPU right after; it is never
|
| 176 |
+
nested (`normalize_references` runs its resizes as a second flat list), so that caps every thread it starts. One
|
| 177 |
+
after the other with CODECOPSD_SERIAL_REFERENCES=1 in the environment, or when the same object is given twice (PIL
|
| 178 |
+
reads a picture from its file on first use, which two threads must not do at once)."""
|
| 179 |
+
items = list(zip(*iterables))
|
| 180 |
+
cores = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count() or 1
|
| 181 |
+
workers = min(len(items), max(1, cores // 2))
|
| 182 |
+
if (workers < 2 or os.environ.get("CODECOPSD_SERIAL_REFERENCES") == "1"
|
| 183 |
+
or len({id(args[0]) for args in items}) < len(items)):
|
| 184 |
+
return [fn(*args) for args in items]
|
| 185 |
+
with ThreadPoolExecutor(workers, thread_name_prefix="references") as pool:
|
| 186 |
+
futures = [pool.submit(fn, *args) for args in items]
|
| 187 |
+
return [f.result() for f in futures]
|
| 188 |
+
|
| 189 |
+
|
| 190 |
def stage_times(timings):
|
| 191 |
"""One line on where the reference encoding of a request went (`pipe.timings` after a call): preparing the
|
| 192 |
references, the VAE, the text encoder, and the codec gazer, which runs on the CPU while the VAE encodes. Every part is a
|
|
|
|
| 402 |
(references.picture_short_edge; released MiniMax-H3 reads every picture at 2048); a video first resized
|
| 403 |
onto the canvas of its own aspect ratio at the tier of the `height` x `width` output (`video_tier`, Pika H3
|
| 404 |
Flex's rule; without an output size the released 768 canvas), then at 24 fps, cut to `num_frames` and then to
|
| 405 |
+
the longest 17n + 5 frames the VAE encodes. Other sizes: `set_reference_sizes`. On threads (`map_references`):
|
| 406 |
+
first each reference (in order, errors included), then every LANCZOS resize as one job, each picture and each
|
| 407 |
+
video frame."""
|
| 408 |
sizes = self.reference_sizes or {}
|
| 409 |
short_edge, long_edge = sizes.get("picture_short_edge") or PICTURE_SHORT_EDGE, sizes.get("picture_long_edge")
|
| 410 |
video_edge = sizes.get("video_short_edge")
|
| 411 |
canvas = ((video_edge, video_edge * ((video_edge * 16 // 9 + 31) // 32 * 32)) if video_edge
|
| 412 |
else video_tier(height, width) if height and width else (CANVAS["short_edge"], CANVAS["max_pixels"]))
|
| 413 |
+
|
| 414 |
+
def prepare(ref): # (RGB picture or uint8 frames [T, H, W, 3], the (width, height) they are resized to)
|
| 415 |
if ref.kind == "image":
|
| 416 |
image = ref.image if isinstance(ref.image, Image.Image) else Image.fromarray(np.asarray(ref.image))
|
| 417 |
image = image.convert("RGB")
|
|
|
|
| 423 |
scale = short_edge / min(width, height)
|
| 424 |
if long_edge:
|
| 425 |
scale = min(scale, long_edge / max(width, height))
|
| 426 |
+
return image, (max(32, round(width * scale / 32) * 32), max(32, round(height * scale / 32) * 32))
|
| 427 |
+
if ref.kind == "video":
|
| 428 |
+
frames, (height, width) = video_frames(ref.frames, float(ref.fps), num_frames, canvas)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
if len(frames) < 22:
|
| 430 |
raise ValueError(f"a reference video needs at least 22 frames at 24 fps, got {len(frames)}")
|
| 431 |
+
return frames[: (len(frames) - 5) // 17 * 17 + 5], (width, height)
|
| 432 |
+
raise ValueError(f"references are pictures or videos, got {ref.kind!r}")
|
| 433 |
+
|
| 434 |
+
def resize(x, size): # a picture, or a video frame as diffusers resizes it (back as an array)
|
| 435 |
+
if isinstance(x, Image.Image):
|
| 436 |
+
return x.resize(size, Image.LANCZOS)
|
| 437 |
+
return np.asarray(Image.fromarray(x).resize(size, Image.Resampling.LANCZOS))
|
| 438 |
+
|
| 439 |
+
prepared = map_references(prepare, references)
|
| 440 |
+
shape = lambda x: x.size if isinstance(x, Image.Image) else (x.shape[2], x.shape[1])
|
| 441 |
+
jobs = [] # every LANCZOS resize, in reference order: a picture, or each frame of a video
|
| 442 |
+
for x, size in prepared:
|
| 443 |
+
if shape(x) != size:
|
| 444 |
+
jobs += [(x, size)] if isinstance(x, Image.Image) else [(frame, size) for frame in x]
|
| 445 |
+
resized = iter(map_references(resize, *zip(*jobs))) # in the order of `jobs`
|
| 446 |
+
out = []
|
| 447 |
+
for x, size in prepared:
|
| 448 |
+
if isinstance(x, Image.Image):
|
| 449 |
+
out.append(MiniMaxH3ImageReference(image=x if x.size == size else next(resized)))
|
| 450 |
else:
|
| 451 |
+
frames = x if shape(x) == size else np.stack([next(resized) for _ in range(len(x))])
|
| 452 |
+
out.append(MiniMaxH3VideoReference(frames=frames, fps=MINIMAX_H3_FPS))
|
| 453 |
return out
|
| 454 |
|
| 455 |
@torch.no_grad()
|