From 9af88d7f53453689693d53bfc51a1c019853f0e7 Mon Sep 17 00:00:00 2001 From: Shogo Iwano Date: Sat, 21 Nov 2026 03:49:45 +0900 Subject: [PATCH 1/4] feat: support frame-indexed visual and audio guides for MiniMax-H3 --- docs/dgl-builtins.md | 6 +- docs/dgl.md | 5 +- docs/guides/c_api.md | 4 + docs/models/minimax_h3.md | 22 ++++- examples/cli/main.cpp | 55 ++++++++++++ examples/common/common.cpp | 97 ++++++++++++++++++++- examples/common/common.h | 8 ++ examples/server/api.md | 4 +- src/api/generation_h3.cpp | 74 +++++++++++----- src/api/generation_hires.cpp | 3 + src/api/generation_video.cpp | 5 ++ src/api/options.cpp | 4 + src/api/templates/video_h3.dgl | 7 ++ src/api/templates/video_reference.dgl | 2 +- src/config.h | 8 ++ src/dgl/bindings/condition.cpp | 8 +- src/dgl/bindings/latents.cpp | 5 +- src/dgl/bindings/registration.cpp | 2 +- src/dgl/ops/media.cpp | 5 +- src/dgl/ops/media.h | 2 +- src/model/diffusion/minimax_h3.hpp | 120 ++++++++++++++------------ src/model/diffusion/model.hpp | 1 + 22 files changed, 354 insertions(+), 93 deletions(-) diff --git a/docs/dgl-builtins.md b/docs/dgl-builtins.md index 1cedb5b62b..b814553c03 100644 --- a/docs/dgl-builtins.md +++ b/docs/dgl-builtins.md @@ -14,7 +14,7 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn | `audio::save` | `path: string`, `audio: dict`, `format?: string = "f32"` | `void` | | `audio_latent_shape` | `vae: audio_vae`, `frames: int`, `fps: int` | `tensor` | | `audio_vae_decode` | `vae: audio_vae`, `latent: tensor` | `dict`
`sample_rate: int`
`samples: tensor` | -| `audio_vae_encode` | `vae: audio_vae`, `samples: tensor`, `sample_rate: int` | `tensor` | +| `audio_vae_encode` | `vae: audio_vae`, `samples: tensor`, `sample_rate: int`, `max_latents?: int = 0` | `tensor` | | `cache` | `mode?: string = "disabled"`, `reuse_threshold?: number`, `start_percent?: number`, `end_percent?: number`, `error_decay_rate?: number`, `use_relative_threshold?: bool`, `reset_error_on_compute?: bool`, `residual_diff_threshold?: number`, `max_warmup_steps?: int`, `max_cached_steps?: int`, `max_continuous_cached_steps?: int`, `taylorseer_n_derivatives?: int`, `taylorseer_skip_interval?: int`, `scm_mask?: string`, `spectrum_w?: number`, `spectrum_m?: int`, `spectrum_lam?: number`, `spectrum_window_size?: int`, `spectrum_flex_window?: number`, `spectrum_warmup_steps?: int`, `spectrum_stop_percent?: number` | `dict`
`end_percent: number`
`error_decay_rate: number`
`max_cached_steps: int`
`max_continuous_cached_steps: int`
`max_warmup_steps: int`
`mode: string`
`reset_error_on_compute: bool`
`residual_diff_threshold: number`
`reuse_threshold: number`
`scm_mask: string`
`spectrum_flex_window: number`
`spectrum_lam: number`
`spectrum_m: int`
`spectrum_stop_percent: number`
`spectrum_w: number`
`spectrum_warmup_steps: int`
`spectrum_window_size: int`
`start_percent: number`
`taylorseer_n_derivatives: int`
`taylorseer_skip_interval: int`
`use_relative_threshold: bool` | | `cfg` | `positive: predictor`, `negative: predictor`, `scale: number`, `image_only?: predictor`, `image_scale?: number = 1`, `schedule?: list` | `predictor` | | `controlnet::apply` | `condition: dict`, `model: control_net`, `hint: tensor`, `strength?: number = 1`, `start_sigma?: number`, `end_sigma?: number`, `type?: string = "none"` | same type as `condition`
`controls: control_bindings` | @@ -26,7 +26,7 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn | `detections::to_regions` | `image: tensor`, `detections: dict` | `dict`
`boxes: tensor`
`height: int`
`width: int` | | `dit_to_vae_latents` | `vae: vae`, `latent: tensor` | `tensor` | | `encode_audio` | `encoder: audio_encoder`, `samples: tensor`, `sample_rate: int` | `tensor` | -| `encode_prompt` | `encoder: text_encoder`, `text: string`, `width?: int = 512`, `height?: int = 512`, `clip_skip?: int = -1`, `system?: string`, `media?: list`, `image_bindings?: dict`, `raw?: bool = false` | `dict`
`concat: tensor`
`crossattn: tensor`
`extra_crossattn: list`
`image_embed_indices: list`
`image_embeds: list`
`input_ids: tensor`
`position_ids: tensor`
`ref_audios: list`
`ref_images: list`
`reference_blocks: list`
`reference_blocks.audio: int`
`reference_blocks.kind: string`
`reference_blocks.video: int`
`t5_ids: tensor`
`t5_weights: tensor`
`token_types: tensor`
`vector: tensor`
`vinput_mask: tensor` | +| `encode_prompt` | `encoder: text_encoder`, `text: string`, `width?: int = 512`, `height?: int = 512`, `clip_skip?: int = -1`, `system?: string`, `media?: list`, `image_bindings?: dict`, `raw?: bool = false` | `dict`
`concat: tensor`
`crossattn: tensor`
`extra_crossattn: list`
`image_embed_indices: list`
`image_embeds: list`
`input_ids: tensor`
`position_ids: tensor`
`ref_audios: list`
`ref_images: list`
`reference_blocks: list`
`reference_blocks.audio: int`
`reference_blocks.frame_index: int`
`reference_blocks.kind: string`
`reference_blocks.video: int`
`t5_ids: tensor`
`t5_weights: tensor`
`token_types: tensor`
`vector: tensor`
`vinput_mask: tensor` | | `encode_vision` | `encoder: vision_encoder`, `image: tensor`, `pooled?: bool = false`, `clip_skip?: int = -2`, `zero?: bool = false`, `zero_input?: bool = false` | `tensor` | | `image::canny` | `image: tensor`, `high_threshold?: number = 0.08`, `low_threshold?: number = 0.04`, `weak?: number = 0.5`, `strong?: number = 1`, `invert?: bool = false` | `tensor` | | `image::encode` | `image: tensor`, `format?: string = "png"` | `dict`
`data: bytes`
`mime_type: string` | @@ -68,7 +68,7 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn | `media::save` | `path: string`, `media: dict` | `void` | | `photomaker::apply` | `condition: dict`, `photomaker: photomaker`, `tokens: tensor`, `mask: tensor` | same type as `condition`
`crossattn: tensor` | | `photomaker::encode_images` | `photomaker: photomaker`, `images: list`, `id_embedding?: tensor` | `tensor` | -| `photomaker::encode_prompt` | `encoder: text_encoder`, `text: string`, `tokens: tensor`, `width?: int = 1024`, `height?: int = 1024`, `clip_skip?: int = -1` | `dict`
`condition: dict`
`condition.concat: tensor`
`condition.crossattn: tensor`
`condition.extra_crossattn: list`
`condition.image_embed_indices: list`
`condition.image_embeds: list`
`condition.input_ids: tensor`
`condition.position_ids: tensor`
`condition.ref_audios: list`
`condition.ref_images: list`
`condition.reference_blocks: list`
`condition.reference_blocks.audio: int`
`condition.reference_blocks.kind: string`
`condition.reference_blocks.video: int`
`condition.t5_ids: tensor`
`condition.t5_weights: tensor`
`condition.token_types: tensor`
`condition.vector: tensor`
`condition.vinput_mask: tensor`
`mask: tensor`
`plain: dict`
`plain.concat: tensor`
`plain.crossattn: tensor`
`plain.extra_crossattn: list`
`plain.image_embed_indices: list`
`plain.image_embeds: list`
`plain.input_ids: tensor`
`plain.position_ids: tensor`
`plain.ref_audios: list`
`plain.ref_images: list`
`plain.reference_blocks: list`
`plain.reference_blocks.audio: int`
`plain.reference_blocks.kind: string`
`plain.reference_blocks.video: int`
`plain.t5_ids: tensor`
`plain.t5_weights: tensor`
`plain.token_types: tensor`
`plain.vector: tensor`
`plain.vinput_mask: tensor` | +| `photomaker::encode_prompt` | `encoder: text_encoder`, `text: string`, `tokens: tensor`, `width?: int = 1024`, `height?: int = 1024`, `clip_skip?: int = -1` | `dict`
`condition: dict`
`condition.concat: tensor`
`condition.crossattn: tensor`
`condition.extra_crossattn: list`
`condition.image_embed_indices: list`
`condition.image_embeds: list`
`condition.input_ids: tensor`
`condition.position_ids: tensor`
`condition.ref_audios: list`
`condition.ref_images: list`
`condition.reference_blocks: list`
`condition.reference_blocks.audio: int`
`condition.reference_blocks.frame_index: int`
`condition.reference_blocks.kind: string`
`condition.reference_blocks.video: int`
`condition.t5_ids: tensor`
`condition.t5_weights: tensor`
`condition.token_types: tensor`
`condition.vector: tensor`
`condition.vinput_mask: tensor`
`mask: tensor`
`plain: dict`
`plain.concat: tensor`
`plain.crossattn: tensor`
`plain.extra_crossattn: list`
`plain.image_embed_indices: list`
`plain.image_embeds: list`
`plain.input_ids: tensor`
`plain.position_ids: tensor`
`plain.ref_audios: list`
`plain.ref_images: list`
`plain.reference_blocks: list`
`plain.reference_blocks.audio: int`
`plain.reference_blocks.frame_index: int`
`plain.reference_blocks.kind: string`
`plain.reference_blocks.video: int`
`plain.t5_ids: tensor`
`plain.t5_weights: tensor`
`plain.token_types: tensor`
`plain.vector: tensor`
`plain.vinput_mask: tensor` | | `photomaker::load` (resource) | `path: string`, `family?: string = "auto"`, `wtype?: string = "auto"`, `conv_scale?: number = 0`, `linear_scale?: number = 0`, `attn_scale?: number = 0`, `backend?: string = ""`, `params_backend?: string = ""`, `split_mode?: string = ""`, `model_args?: string = ""`, `tensor_type_rules?: string = ""`, `flash_attn_mode?: string = "auto"`, `conv_direct_mode?: string = "auto"`, `sage_attn?: bool = false`, `linear_type?: string = "auto"` | `photomaker` | | `predictor` | `model: denoiser`, `condition: dict`, `prediction?: string = "auto"`, `concat?: tensor`, `ref_latents?: list`, `ref_audios?: list`, `reference_blocks?: list`, `keyframe_indices?: list`, `ref_index_mode?: string = "fixed"`, `force_ref_timestep_zero?: bool = false`, `ref_rope_anchor?: string = "default"`, `guidance?: number = 3.5`, `skip_layers?: list`, `vace_context?: tensor`, `vace_strength?: number = 1`, `audio_embedding?: tensor`, `video_positions?: tensor`, `audio_length?: int = 0`, `fps?: number = 24`, `video_sigma_shift?: number = 12`, `audio_sigma_shift?: number = 3`, `circular_x?: bool = false`, `circular_y?: bool = false`, `transform?: fn`, `transform_args?: dict` | `predictor` | | `preview` | `decoder?: vae`, `circular_x?: bool = false`, `circular_y?: bool = false` | `sampling_observer` | diff --git a/docs/dgl.md b/docs/dgl.md index 0fe7af869c..16286d0637 100644 --- a/docs/dgl.md +++ b/docs/dgl.md @@ -1304,7 +1304,8 @@ video::save("output.avi", video, audio = track) `encode_audio(encoder, samples, sample_rate=...)` and `audio_vae_encode(vae, samples, sample_rate=...)` accept tensors and an explicit -sample rate. Their existing model-specific resampling remains in effect. +sample rate. On MiniMax-H3, pass `max_latents` to `audio_vae_encode` to encode +only the requested prefix. The default, 0, encodes the full input. `audio_vae_decode` reports the decoder's actual output sample rate. ## Regions and masks @@ -1562,6 +1563,8 @@ Each block has a `kind` of `image`, `video`, `audio` or `video_audio`. `image` and `video` require a `video` index into `ref_latents`; `audio` requires an `audio` index into `ref_audios`; `video_audio` requires both. Indices are zero-based nonnegative integers, and list order determines reference order. +Set a block's optional `frame_index` to anchor it to a zero-based output frame. +Blocks without this field precede the output timeline. If `ref_latents` is empty, video indices refer to the condition's `ref_images`. The explicit argument overrides the condition field, including an empty list. Malformed blocks or out-of-range indices fail when constructing the predictor, diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index e456c0050d..6d185369a7 100644 --- a/docs/guides/c_api.md +++ b/docs/guides/c_api.md @@ -422,6 +422,10 @@ For SDXL's bundled VAE (no `vae_path`), generation emits | `flash_attn_mode` | `string` | context | | `force_sdxl_vae_conv_scale` | `bool` | context | | `fps` | `int` | video | +| `guide_audio_indices` | `ints` | video | +| `guide_audios` | `audios` | video | +| `guide_video_indices` | `ints` | video | +| `guide_videos` | `videos` | video | | `height` | `int` | image, video | | `high_noise_diffusion_model_path` | `string` | context | | `image` | `tensor` | upscale | diff --git a/docs/models/minimax_h3.md b/docs/models/minimax_h3.md index 7c2e3bc684..514432e7b1 100644 --- a/docs/models/minimax_h3.md +++ b/docs/models/minimax_h3.md @@ -331,8 +331,24 @@ generation. Reference inputs are presented to Qwen3-VL in image, video, then audio order. Videos are sampled at 2 fps for the Qwen presentation while their full 24 fps latents condition the diffusion transformer. Paired video and audio references -share the same timeline. Ref2VA cannot be combined with `--init-img` or -`--end-img` in one request. +share the same timeline. + +Use repeatable `--guide-image PATH@FRAME` and `--guide-audio WAV@FRAME` to +anchor guides on the target timeline, including in Ref2VA requests. For example, +`--ref-image actor.png --guide-image board.png@0 --guide-audio line.wav@24 --guide-image ending.png@-1` +anchors the dialogue at one second. Negative indices count from the aligned +frame count. `--init-img` and `--end-img` anchor the first and last frames. + +A visual guide accepts one image or a 24 fps frame directory. Clips shorter +than five frames use their first image. Longer clips use the largest prefix of +`17k + 5` frames and must fit at the specified index. Audio guides require +audio VAE encoder weights and are cropped to the remaining target duration. +Frame-indexed guides do not receive prompt tags. Without Ref2VA references, +`--init-img` and `--end-img` retain their legacy Qwen3-VL picture tags. + +C API and `sdcpp` requests pair `guide_videos` and `guide_audios` with +`guide_video_indices` and `guide_audio_indices`, respectively. Use a +single-frame video for an image. A C API video guide can include its own soundtrack. Reference images preserve their aspect ratio and are downscaled only when their pixel area exceeds the generation canvas. Each axis is then snapped to @@ -475,7 +491,7 @@ Notes for this mode: - `--hires-sigmas` can replace `--hires-denoising-strength` when the second stage should resume from an explicit sigma schedule, which is how most two-stage H3 workflows split the sampler. -- Keyframe conditioning (`--init-img` / `--end-img`) is not available together +- Visual guide conditioning (`--guide-image`, `--init-img`, `--end-img`) is not available together with hires yet: those latents are encoded at the first stage resolution and would have to be re-encoded for the hires canvas. Use T2VA or Ref2VA. - The second stage runs at the larger latent, so it is the memory-hungry half; diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp index e3b7202f45..96447350d0 100644 --- a/examples/cli/main.cpp +++ b/examples/cli/main.cpp @@ -320,6 +320,44 @@ void sd_log_cb(enum sd_log_level_t level, const char* log, void* data) { log_print(level, log, cli_params->log_level, cli_params->color, log_stream); } +static bool load_guide_image(const std::string& path, SDImageOwner& image) { + if (!load_sd_image_from_file(image.put(), path.c_str(), 0, 0, 0)) { + return false; + } + normalize_guide_frame_rgb(image.get()); + return true; +} + +static bool load_guide_frames(const fs::path& dir_path, std::vector& images) { + std::vector entries; + for (const auto& entry : fs::directory_iterator(dir_path)) { + if (!entry.is_regular_file()) { + continue; + } + std::string ext = entry.path().extension().u8string(); + std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); + if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".webp") { + entries.push_back(entry); + } + } + + std::sort(entries.begin(), entries.end(), + [](const fs::directory_entry& a, const fs::directory_entry& b) { + return a.path().filename().u8string() < b.path().filename().u8string(); + }); + entries.resize(minimax_h3_guide_frame_count(entries.size())); + for (const auto& entry : entries) { + std::string path = entry.path().u8string(); + LOG_VERBOSE("load image %zu from '%s'", images.size(), path.c_str()); + SDImageOwner image; + if (!load_guide_image(path, image)) { + return false; + } + images.push_back(std::move(image)); + } + return true; +} + std::string format_frame_idx(std::string pattern, int frame_idx) { std::smatch match; std::string result = pattern; @@ -706,6 +744,23 @@ int main(int argc, const char* argv[]) { } } + for (const auto& path : gen_params.guide_video_paths) { + auto& frames = gen_params.guide_videos.emplace_back(); + if (fs::is_directory(fs::u8path(path))) { + if (!load_guide_frames(fs::u8path(path), frames) || frames.empty()) { + return 1; + } + } else if (!load_guide_image(path, frames.emplace_back())) { + LOG_ERROR("failed to load guide image '%s'", path.c_str()); + return 1; + } + } + for (const auto& path : gen_params.guide_audio_paths) { + if (!load_audio(path, gen_params.guide_audios.emplace_back())) { + return 1; + } + } + if (!gen_params.ref_video_paths.empty()) { gen_params.ref_videos.clear(); gen_params.ref_video_audios.clear(); diff --git a/examples/common/common.cpp b/examples/common/common.cpp index cf400eb1a2..b5d4185704 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -2,8 +2,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -1386,6 +1388,27 @@ ArgOptions SDGenerationParams::get_options() { return 1; }; + auto on_guide_arg = [&](int argc, const char** argv, int index) { + bool audio = std::string(argv[index]) == "--guide-audio"; + if (++index >= argc) { + return -1; + } + auto arg = argv_to_utf8(index, argv); + auto at = arg.rfind('@'); + int32_t frame; + if (at == std::string::npos || at == 0) { + return -1; + } + const char* end = arg.data() + arg.size(); + auto parsed = std::from_chars(arg.data() + at + 1, end, frame); + if (parsed.ec != std::errc() || parsed.ptr != end) { + return -1; + } + (audio ? guide_audio_paths : guide_video_paths).push_back(arg.substr(0, at)); + (audio ? guide_audio_indices : guide_video_indices).push_back(frame); + return 1; + }; + auto on_ref_video_arg = [&](int argc, const char** argv, int index) { if (++index >= argc) { return -1; @@ -1581,6 +1604,8 @@ ArgOptions SDGenerationParams::get_options() { "--hires-sigmas", "custom sigma values for the highres fix second pass, comma-separated (e.g., \"0.85,0.725,0.421875,0.0\") or preset: qwen-image-2.1-turbo, p-h3-image, minimax-h3-image, hyperflow-h3-flash-4, hyperflow-h3-flash-6, hyperflow-h3-flash-8.", on_hires_sigmas_arg}, + {"", "--guide-image", "MiniMax-H3 image or frame directory: PATH@FRAME (repeatable)", on_guide_arg}, + {"", "--guide-audio", "MiniMax-H3 WAV guide: PATH@FRAME (repeatable)", on_guide_arg}, {"-r", "--ref-image", "reference image for Flux Kontext or MiniMax-H3 Ref2VA (can be used multiple times)", @@ -1821,10 +1846,24 @@ static bool parse_audio_array_json_field(const json& parent, return true; } +size_t minimax_h3_guide_frame_count(size_t available) { + return available < 5 ? std::min(available, 1) : available - (available - 5) % 17; +} + +void normalize_guide_frame_rgb(SDImage& image) { + if (image.channel == 4) { + for (size_t pixel = 0; pixel < size_t(image.width) * image.height; ++pixel) { + std::memmove(image.data + pixel * 3, image.data + pixel * 4, 3); + } + image.channel = 3; + } +} + /** Parses a JSON array of per-video base64 frame arrays into owned videos. */ static bool parse_video_array_json_field(const json& parent, const char* key, - std::vector>& out_videos) { + std::vector>& out_videos, + bool visual_guide = false) { if (!parent.contains(key)) { return true; } @@ -1842,7 +1881,9 @@ static bool parse_video_array_json_field(const json& parent, return false; } std::vector frames; - for (const auto& frame : video) { + size_t count = visual_guide ? minimax_h3_guide_frame_count(video.size()) : video.size(); + for (size_t i = 0; i < count; ++i) { + const auto& frame = video[i]; if (!frame.is_string()) { return false; } @@ -1850,6 +1891,9 @@ static bool parse_video_array_json_field(const json& parent, if (!decode_base64_image(frame.get(), 0, 0, 0, image)) { return false; } + if (visual_guide) { + normalize_guide_frame_rgb(image.get()); + } frames.push_back(std::move(image)); } out_videos.push_back(std::move(frames)); @@ -2136,7 +2180,31 @@ bool SDGenerationParams::from_json_str( !load_image("ip_adapter_image", 3, ip_adapter_image)) { return false; } - if (!parse_image_array_json_field(j, "ref_images", 0, ref_images) || + auto read_guide_indices = [&](const char* key, std::vector& indices) { + if (!j.contains(key)) { + return true; + } + if (j.at(key).is_null()) { + indices.clear(); + return true; + } + if (!j.at(key).is_array()) { + return false; + } + indices.clear(); + for (const auto& index : j.at(key)) { + if (!index.is_number_integer() || index.get() < INT32_MIN || index.get() > INT32_MAX) { + return false; + } + indices.push_back(index.get()); + } + return true; + }; + if (!parse_video_array_json_field(j, "guide_videos", guide_videos, true) || + !parse_audio_array_json_field(j, "guide_audios", guide_audios) || + !read_guide_indices("guide_video_indices", guide_video_indices) || + !read_guide_indices("guide_audio_indices", guide_audio_indices) || + !parse_image_array_json_field(j, "ref_images", 0, ref_images) || !parse_image_array_json_field(j, "control_frames", 3, control_frames) || !parse_audio_array_json_field(j, "ref_audios", ref_audios) || !parse_audio_array_json_field(j, "ref_video_audios", ref_video_audios) || @@ -2399,7 +2467,12 @@ bool SDGenerationParams::validate(SDMode mode) { return false; } - if (mode != VID_GEN && (!ref_video_paths.empty() || !ref_video_audio_paths.empty() || !ref_audio_paths.empty() || + if (guide_video_indices.size() != guide_video_paths.size() + guide_videos.size() || + guide_audio_indices.size() != guide_audio_paths.size() + guide_audios.size()) { + LOG_ERROR("each guide requires one frame index"); + return false; + } + if (mode != VID_GEN && (!guide_video_indices.empty() || !guide_audio_indices.empty() || !ref_video_paths.empty() || !ref_video_audio_paths.empty() || !ref_audio_paths.empty() || !ref_videos.empty() || !ref_video_audios.empty() || !ref_audios.empty())) { LOG_ERROR("error: reference video and audio inputs require vid_gen mode"); return false; @@ -2650,6 +2723,22 @@ SDOptPtr SDGenerationParams::to_video_opt() { opt.set_bool("circular_y", circular_y); opt.set_loras("loras", lora_vec.data(), lora_vec.size()); opt.set_images("ref_images", ref_image_views.data(), ref_image_views.size()); + std::vector> guide_frames(guide_videos.size()); + std::vector videos; + for (size_t i = 0; i < guide_videos.size(); ++i) { + for (const auto& frame : guide_videos[i]) { + guide_frames[i].push_back(frame.get()); + } + videos.push_back({guide_frames[i].data(), static_cast(guide_frames[i].size()), 24, {}}); + } + std::vector audios; + for (auto& audio : guide_audios) { + audios.push_back(audio.get()); + } + opt.set_videos("guide_videos", videos.data(), videos.size()); + opt.set_audios("guide_audios", audios.data(), audios.size()); + opt.set_ints("guide_video_indices", guide_video_indices.data(), guide_video_indices.size()); + opt.set_ints("guide_audio_indices", guide_audio_indices.data(), guide_audio_indices.size()); opt.set_videos("ref_videos", ref_video_views.data(), ref_video_views.size()); opt.set_audios("ref_audios", ref_audio_views.data(), ref_audio_views.size()); opt.set_frames("control_frames", control_frame_views.data(), control_frame_views.size()); diff --git a/examples/common/common.h b/examples/common/common.h index cddfaf0c88..73796ed1b5 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -17,6 +17,8 @@ // The command-line argument at `index` as UTF-8 (on Windows, read again from // the UTF-16 command line: argv itself is in the ANSI code page). std::string argv_to_utf8(int index, const char** argv); +size_t minimax_h3_guide_frame_count(size_t available); +void normalize_guide_frame_rgb(SDImage& image); #define SAFE_STR(s) ((s) ? (s) : "") #define BOOL_STR(b) ((b) ? "true" : "false") @@ -231,6 +233,12 @@ struct SDGenerationParams { std::optional control_type; std::vector ref_image_paths; std::vector ref_video_paths; + std::vector guide_video_paths; + std::vector guide_audio_paths; + std::vector guide_video_indices; + std::vector guide_audio_indices; + std::vector> guide_videos; + std::vector guide_audios; std::vector ref_video_audio_paths; std::vector ref_audio_paths; std::string control_video_path; diff --git a/examples/server/api.md b/examples/server/api.md index 1c9b15e40e..90ffb40e57 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -1429,6 +1429,8 @@ Compared with `img_gen`, the `vid_gen` request body: - `mask_image`, `control_image`, `control_strength`, `ip_adapter_image`, `ip_adapter_strength`, and `embed_image_metadata` are not part of the request schema - `ref_images` is accepted for MiniMax-H3 Ref2VA conditioning; other video model families currently ignore it - `vid_gen` adds `end_image`, `control_frames`, `high_noise_sample_params`, `video_frames`, `fps`, `moe_boundary`, and `vace_strength` +- `guide_videos` accepts MiniMax-H3 visual guides as arrays of base64 frames. `guide_video_indices` supplies one signed target frame index per guide. +- `guide_audios` accepts MiniMax-H3 audio guides as base64 WAV strings. `guide_audio_indices` supplies one signed target frame index per guide. Example: @@ -1499,7 +1501,7 @@ Example: - `ref_images` contains reference images for MiniMax-H3 Ref2VA conditioning. - Images retain request order and correspond to ``, ``, and so on in the prompt. -- For MiniMax-H3, non-empty `ref_images` cannot be combined with `init_image` or `end_image`. A conflicting API request fails during generation; the WebUI checks this before submission. +- MiniMax-H3 accepts references together with frame-indexed guides, including `init_image` and `end_image`. - MiniMax-H3 does not support `control_frames`; leave that array empty. - Other video model families currently ignore `ref_images`. - `features_by_mode.vid_gen` does not currently advertise `ref_images`; its absence is not an indication that MiniMax-H3 reference images are unsupported. diff --git a/src/api/generation_h3.cpp b/src/api/generation_h3.cpp index 766c2ec956..9df998e720 100644 --- a/src/api/generation_h3.cpp +++ b/src/api/generation_h3.cpp @@ -16,15 +16,12 @@ namespace sd::api { const auto videos = bound_videos(request.options, "ref_videos"); const auto audios = bound_audios(request.options, "ref_audios"); const bool references = !images.empty() || !videos.empty() || !audios.empty(); - const bool audio_references = !audios.empty() || std::any_of(videos.begin(), videos.end(), [](const sd_video_t& video) { return video.audio.data != nullptr; }); - if (audio_references && !request.flags.at("decode_audio").get()) - throw dgl::Error(SD_STATUS_LOAD_FAILED, "MiniMax-H3 audio references require audio VAE weights"); - if (references && (!first.empty() || !last.empty())) - throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "MiniMax-H3 references and start/end keyframes cannot be combined"); - if (!references && first.empty() && last.empty()) + const auto guide_videos = bound_videos(request.options, "guide_videos"); + const auto guide_audios = bound_audios(request.options, "guide_audios"); + if (!references && first.empty() && last.empty() && guide_videos.empty() && guide_audios.empty()) return; auto& prepare = request.fields["references"]; - std::vector visuals, sounds, presentation, blocks, keys; + std::vector visuals, sounds, presentation, blocks; const auto encode_visual = [&](const std::string& pixels, const nlohmann::json& options = nlohmann::json::object()) { const auto name = "h3_visual_" + std::to_string(visuals.size()); nlohmann::json parameters{{"name", name}, {"pixels", pixels}, {"encode_audio", false}, {"resize_video", false}, {"resize_image", false}}; @@ -32,26 +29,63 @@ namespace sd::api { prepare += request.render("video_reference", parameters); visuals.push_back(name); }; - const auto encode_sound = [&](const sd_audio_t& audio) { + const auto encode_sound = [&](const sd_audio_t& audio, int64_t limit = 0) { + if (!request.flags.at("decode_audio").get()) + throw dgl::Error(SD_STATUS_LOAD_FAILED, "MiniMax-H3 audio conditioning requires audio VAE weights"); const auto name = "h3_sound_" + std::to_string(sounds.size()); bind_tensor(request.program, name + "_samples", audio.data); const auto media = "{samples = " + name + "_samples, sample_rate = " + std::to_string(audio.sample_rate) + "}"; - prepare += request.render("video_reference", {{"encode_audio", true}, {"name", name}, {"sample_rate", audio.sample_rate}}); + prepare += request.render("video_reference", {{"encode_audio", true}, {"name", name}, {"sample_rate", audio.sample_rate}, {"limit", limit}}); sounds.push_back(name); - presentation.push_back("{audio = " + media + "}"); + if (!limit) + presentation.push_back("{audio = " + media + "}"); }; - if (!references) { - std::vector key_images; - for (const auto& [pixels, index] : std::vector>{{first, "0"}, {last, "frames - 1"}}) { - if (pixels.empty()) - continue; - encode_visual(pixels); - key_images.push_back(pixels + "[:, :, 0]"); - keys.push_back(index); - } + const int frames = request.values.at("frames").get(); + std::vector key_images; + for (const auto& [pixels, index] : std::vector>{{first, 0}, {last, frames - 1}}) { + if (pixels.empty()) + continue; + blocks.push_back(literal({{"kind", "video"}, {"video", visuals.size()}, {"frame_index", index}})); + encode_visual(pixels); + key_images.push_back(pixels + "[:, :, 0]"); + } + if (!references && !key_images.empty()) { request.fields["prompt_options"] += ", media = " + expression_list(key_images); request.fields["negative_prompt_options"] += ", media = " + expression_list(key_images); } + const auto resolve_index = [&](int index) { + if (index < 0) + index += frames; + if (index < 0 || index >= frames) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "MiniMax-H3 guide frame index outside target"); + return index; + }; + const auto guide_audio = [&](const sd_audio_t& audio, int start) { + blocks.push_back(literal({{"kind", "audio"}, {"audio", sounds.size()}, {"frame_index", start}})); + encode_sound(audio, std::llround(frames * (40.0 / 24)) - (5LL * start + 2) / 3); + }; + for (size_t i = 0; i < guide_videos.size(); ++i) { + const auto& video = guide_videos[i]; + const int start = resolve_index(request.video->guide_video_indices[i]); + const int64_t available = sd_tensor_dim(video.data, 3); + const int64_t count = available < 5 ? 1 : available - (available - 5) % 17; + if (available < 1 || video.fps != 24 || count > frames - start) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "MiniMax-H3 visual guide requires 24 fps frames that fit at the requested index"); + const auto name = "guide_video_" + std::to_string(i); + bind_tensor(request.program, name, video.data); + blocks.push_back(literal({{"kind", "video"}, {"video", visuals.size()}, {"frame_index", start}})); + const auto channels = sd_tensor_dim(video.data, 0) == 2 ? ":1" : ":"; + const auto clip = name + "[" + channels + ", :, :, :" + std::to_string(count) + "]"; + const auto width = request.values.at("width").get(), height = request.values.at("height").get(); + const auto w = sd_tensor_dim(video.data, 1), h = sd_tensor_dim(video.data, 2); + const auto scale = std::max(double(width) / w, double(height) / h); + const auto size = literal({int64_t(std::ceil(w * scale)), int64_t(std::ceil(h * scale))}); + encode_visual("h3_guide_pixels(" + clip + ", width, height, " + size + ")"); + if (video.audio.data) + guide_audio(video.audio, start); + } + for (size_t i = 0; i < guide_audios.size(); ++i) + guide_audio(guide_audios[i], resolve_index(request.video->guide_audio_indices[i])); for (size_t i = 0; i < images.size(); ++i) { const auto name = "h3_image_" + std::to_string(i); bind_tensor(request.program, name, images[i]); @@ -105,8 +139,6 @@ namespace sd::api { options += ", ref_audios = " + expression_list(sounds); if (!blocks.empty()) options += ", reference_blocks = " + expression_list(blocks); - if (!keys.empty()) - options += ", keyframe_indices = " + expression_list(keys); request.fields["predictor_options"] += options; request.fields["negative_predictor_options"] += options; if (!presentation.empty()) { diff --git a/src/api/generation_hires.cpp b/src/api/generation_hires.cpp index 7c11b21dc8..da34295016 100644 --- a/src/api/generation_hires.cpp +++ b/src/api/generation_hires.cpp @@ -23,6 +23,9 @@ namespace sd::api { const bool pixels = !request.video && (model || mode == "lanczos" || mode == "nearest"); const auto version = request.definition.version; const bool ltx = sd_version_is_ltxav(version); + if (request.video && version == VERSION_MINIMAX_H3 && + (bound_tensor(request.options, "init_image") || bound_tensor(request.options, "end_image") || !bound_videos(request.options, "guide_videos").empty())) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "MiniMax-H3 hires does not support visual guides"); if (request.video && !ltx && version != VERSION_MINIMAX_H3) throw dgl::Error(SD_STATUS_UNSUPPORTED, "video hires supports LTX and MiniMax-H3; other workflows can be written in DGL"); if (request.video && (mode == "lanczos" || mode == "nearest")) diff --git a/src/api/generation_video.cpp b/src/api/generation_video.cpp index 8e4a963d55..989b6610d7 100644 --- a/src/api/generation_video.cpp +++ b/src/api/generation_video.cpp @@ -103,6 +103,11 @@ namespace sd::api { const bool frozen = (version == VERSION_WAN2_2_TI2V || sd_version_is_lingbot_video(version)) && (first || last); const bool ltx = sd_version_is_ltxav(version); const bool h3 = version == VERSION_MINIMAX_H3; + if (request.video->guide_videos_count != request.video->guide_video_indices_count || + request.video->guide_audios_count != request.video->guide_audio_indices_count) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "each MiniMax-H3 guide requires one frame index"); + if (!h3 && (request.video->guide_videos_count || request.video->guide_audios_count)) + throw dgl::Error(SD_STATUS_UNSUPPORTED, "frame-indexed guides require MiniMax-H3"); if (!h3 && !bound_videos(request.options, "ref_videos").empty()) throw dgl::Error(SD_STATUS_UNSUPPORTED, "reference videos require MiniMax-H3"); if (!h3 && !s2v && !bound_audios(request.options, "ref_audios").empty()) diff --git a/src/api/options.cpp b/src/api/options.cpp index 4f1970a25e..329d2ef6e4 100644 --- a/src/api/options.cpp +++ b/src/api/options.cpp @@ -369,6 +369,10 @@ static void add_generation_specs(std::vector& specs) { vid.number("moe_boundary", &sd::VideoConfig::moe_boundary, 0, 1); vid.integer("high_noise_sample.steps", &sd::VideoConfig::high_noise_steps, -1, INT32_MAX); vid.array("ref_audios", &sd::VideoConfig::ref_audios, &sd::VideoConfig::ref_audios_count); + vid.array("guide_videos", &sd::VideoConfig::guide_videos, &sd::VideoConfig::guide_videos_count); + vid.array("guide_video_indices", &sd::VideoConfig::guide_video_indices, &sd::VideoConfig::guide_video_indices_count); + vid.array("guide_audios", &sd::VideoConfig::guide_audios, &sd::VideoConfig::guide_audios_count); + vid.array("guide_audio_indices", &sd::VideoConfig::guide_audio_indices, &sd::VideoConfig::guide_audio_indices_count); vid.array("ref_videos", &sd::VideoConfig::ref_videos, &sd::VideoConfig::ref_videos_count); vid.number("vace_strength", &sd::VideoConfig::vace_strength, 0, std::numeric_limits::max()); vid.integer("video_frames", &sd::VideoConfig::video_frames, 1, INT32_MAX); diff --git a/src/api/templates/video_h3.dgl b/src/api/templates/video_h3.dgl index db9a360c03..2fa62b79a4 100644 --- a/src/api/templates/video_h3.dgl +++ b/src/api/templates/video_h3.dgl @@ -6,6 +6,13 @@ var { {% include "video_helpers" %} +fn h3_guide_pixels(clip, width, height, size) { + pixels = image::to_f32(clip, channels = 3) + resized = tensor::interpolate(pixels, size = size, axes = [0, 1], mode = "lanczos") + start = [math::floor((size[0] - width) / 2), math::floor((size[1] - height) / 2)] + return tensor::crop(resized, axes = [0, 1], start = start, size = [width, height]) +} + fn main({{inputs}}) { base_model = load_dit(model_path{{model_options}}) base_text = load_text_encoder(text_path{{text_options}}) diff --git a/src/api/templates/video_reference.dgl b/src/api/templates/video_reference.dgl index 7e295b2b8c..08668307ba 100644 --- a/src/api/templates/video_reference.dgl +++ b/src/api/templates/video_reference.dgl @@ -1,5 +1,5 @@ {% if encode_audio %} - {{name}} = audio_vae_encode(audio_vae, {{name}}_samples, sample_rate = {{sample_rate}}) + {{name}} = audio_vae_encode(audio_vae, {{name}}_samples, sample_rate = {{sample_rate}}, max_latents = {{limit}}) {% else %} {% if resize_video %} {{source}}_pixels = image::to_f32(tensor::interpolate(tensor::index_select({{source}}, axis = 3, indices = {{indices}}), size = [{{width}}, {{height}}], axes = [1, 2]), channels = 3) diff --git a/src/config.h b/src/config.h index c93e84ad19..8434927aea 100644 --- a/src/config.h +++ b/src/config.h @@ -180,6 +180,14 @@ namespace sd { sd::Image end_image{}; sd::Image* ref_images{}; int ref_images_count{}; + sd::ReferenceVideo* guide_videos{}; + int guide_videos_count{}; + int* guide_video_indices{}; + int guide_video_indices_count{}; + sd::Audio* guide_audios{}; + int guide_audios_count{}; + int* guide_audio_indices{}; + int guide_audio_indices_count{}; sd::ReferenceVideo* ref_videos{}; int ref_videos_count{}; sd::Audio* ref_audios{}; diff --git a/src/dgl/bindings/condition.cpp b/src/dgl/bindings/condition.cpp index 7dc9ae5f94..47d2d45cb7 100644 --- a/src/dgl/bindings/condition.cpp +++ b/src/dgl/bindings/condition.cpp @@ -108,6 +108,8 @@ namespace sd::dgl { fields.emplace("video", Value::literal(block.video_index)); if (block.kind == MiniMaxH3ReferenceKind::AUDIO || block.kind == MiniMaxH3ReferenceKind::VIDEO_AUDIO) fields.emplace("audio", Value::literal(block.audio_index)); + if (block.frame_index >= 0) + fields.emplace("frame_index", Value::literal(block.frame_index)); blocks.push_back(Value::dict(std::move(fields))); } return Value::list(std::move(blocks), Kind::Dict); @@ -151,8 +153,10 @@ namespace sd::dgl { }; block.video_index = index("video", block.kind != MiniMaxH3ReferenceKind::AUDIO); block.audio_index = index("audio", block.kind == MiniMaxH3ReferenceKind::AUDIO || block.kind == MiniMaxH3ReferenceKind::VIDEO_AUDIO); + if (fields.count("frame_index")) + block.frame_index = index("frame_index", true); for (const auto& [field, entry] : fields) - if (field != "kind" && field != "video" && field != "audio") + if (field != "kind" && field != "video" && field != "audio" && field != "frame_index") throw std::runtime_error(label + " has unknown field '" + field + "'"); blocks.push_back(block); } @@ -211,7 +215,7 @@ namespace sd::dgl { {"image_embed_indices", {Kind::List, Kind::Tensor}, image_embed_indices}, tensor_list_field<&SDCondition::c_ref_images>("ref_images"), tensor_list_field<&SDCondition::c_ref_audios>("ref_audios"), - {"reference_blocks", {{Kind::List, Kind::Dict}, {{"kind", {Kind::String}}, {"video", {Kind::Integer}}, {"audio", {Kind::Integer}}}}, reference_blocks}, + {"reference_blocks", {{Kind::List, Kind::Dict}, {{"kind", {Kind::String}}, {"video", {Kind::Integer}}, {"audio", {Kind::Integer}}, {"frame_index", {Kind::Integer}}}}, reference_blocks}, }; OutputSignature condition_signature() { diff --git a/src/dgl/bindings/latents.cpp b/src/dgl/bindings/latents.cpp index 12b3572fc7..65e3a36c3b 100644 --- a/src/dgl/bindings/latents.cpp +++ b/src/dgl/bindings/latents.cpp @@ -79,11 +79,14 @@ namespace sd::dgl { auto& engine = *object(args, "vae"); Model::ExecutionScope scope(engine); scope.require_ready(); - auto waveform = sd::dgl::ops::prepare_minimax_h3_reference_waveform(audio, engine.audio_vae_model->input_sample_rate()); + const auto limit = get_int(args, "max_latents"); + auto waveform = sd::dgl::ops::prepare_minimax_h3_reference_waveform(audio, engine.audio_vae_model->input_sample_rate(), limit); auto result = engine.audio_vae_model->encode(engine.n_threads, waveform); if (result.empty()) { throw std::runtime_error("audio VAE encoding failed"); } + if (limit > 0 && result.shape()[0] > limit) + result = sd::ops::slice(result, 0, 0, limit); return tensor_value(std::move(result)); } diff --git a/src/dgl/bindings/registration.cpp b/src/dgl/bindings/registration.cpp index 6624e9907d..2c42a550b4 100644 --- a/src/dgl/bindings/registration.cpp +++ b/src/dgl/bindings/registration.cpp @@ -665,7 +665,7 @@ namespace sd::dgl { {required("upscaler", Kind::LatentUpscaler), required("latent", Kind::Tensor), std::move(width), std::move(height)}, {Kind::Tensor}, upscale_latent); registry["audio_vae_encode"] = make_operation( - {required("vae", Kind::AudioVAE), required("samples", Kind::Tensor), integer("sample_rate", 1000, 384000)}, {Kind::Tensor}, audio_vae_encode); + {required("vae", Kind::AudioVAE), required("samples", Kind::Tensor), integer("sample_rate", 1000, 384000), integer("max_latents", 0, INT32_MAX, 0)}, {Kind::Tensor}, audio_vae_encode); registry["audio_vae_decode"] = make_operation( {required("vae", Kind::AudioVAE), required("latent", Kind::Tensor)}, audio_signature(), audio_vae_decode); } diff --git a/src/dgl/ops/media.cpp b/src/dgl/ops/media.cpp index 2226d3a253..49d28d89c5 100644 --- a/src/dgl/ops/media.cpp +++ b/src/dgl/ops/media.cpp @@ -128,13 +128,16 @@ namespace sd::dgl::ops { } sd::Tensor prepare_minimax_h3_reference_waveform(const sd::Audio& audio, - int target_sample_rate) { + int target_sample_rate, int64_t max_latents) { if (audio.data == nullptr || audio.sample_count == 0 || audio.channels == 0 || audio.sample_rate == 0) { return {}; } uint64_t output_samples = static_cast(std::llround( static_cast(audio.sample_count) * target_sample_rate / audio.sample_rate)); output_samples = std::max(1, output_samples); + // The encoder receptive field for latent i ends at sample 800*i + 9924. + if (max_latents > 0) + output_samples = std::min(output_samples, 800 * (max_latents - 1) + 9925); uint64_t padded_samples = (output_samples + 799) / 800 * 800; // Keep stereo streams planar for the mono-per-stream audio encoder: // [samples, 1, stereo, batch]. This avoids flattening interleaved L/R diff --git a/src/dgl/ops/media.h b/src/dgl/ops/media.h index 5206bcacb8..1d9516134c 100644 --- a/src/dgl/ops/media.h +++ b/src/dgl/ops/media.h @@ -23,7 +23,7 @@ namespace sd::dgl::ops { int temporal_scale, bool causal_temporal_positioning); sd::Tensor prepare_minimax_h3_reference_waveform(const sd::Audio& audio, - int target_sample_rate); + int target_sample_rate, int64_t max_latents); sd::Tensor build_s2v_audio_window(const sd::Tensor& stacked, int64_t batch_frames); } // namespace sd::dgl::ops diff --git a/src/model/diffusion/minimax_h3.hpp b/src/model/diffusion/minimax_h3.hpp index 2f5cb4f7ce..e4a72fc06d 100644 --- a/src/model/diffusion/minimax_h3.hpp +++ b/src/model/diffusion/minimax_h3.hpp @@ -1098,7 +1098,6 @@ namespace MiniMaxH3 { } cursor += video_span(t); } - return cursor; }; auto append_audio_positions = [&](int64_t length, float cursor, @@ -1113,6 +1112,18 @@ namespace MiniMaxH3 { }; float cursor = static_cast(text_len); + auto reference_end = [&](const MiniMaxH3ReferenceBlock& block, float start) { + float end = block.kind == MiniMaxH3ReferenceKind::IMAGE ? start + 1.f : start; + if (block.video_index >= 0 && block.kind != MiniMaxH3ReferenceKind::IMAGE) { + for (int64_t t = 0; t < condition_videos[block.video_index].shape()[2]; ++t) { + end += video_span(t); + } + } + if (block.audio_index >= 0) { + end = std::max(end, start + static_cast(condition_audios[block.audio_index].shape()[0])); + } + return end; + }; if (reference_blocks.empty()) { float video_duration = 0.f; for (int64_t t = 0; t < latent_t; ++t) { @@ -1140,60 +1151,63 @@ namespace MiniMaxH3 { layout.segments.push_back({row, row + count, condition_time_row * 3}); row += count; } - } else { - for (const auto& block : reference_blocks) { - const sd::Tensor* ref_video = nullptr; - const sd::Tensor* ref_audio = nullptr; - if (block.video_index >= 0) { - GGML_ASSERT(block.video_index < static_cast(condition_videos.size())); - ref_video = &condition_videos[static_cast(block.video_index)]; - } - if (block.audio_index >= 0) { - GGML_ASSERT(block.audio_index < static_cast(condition_audios.size())); - ref_audio = &condition_audios[static_cast(block.audio_index)]; - } - - float block_end = cursor; - if (block.kind == MiniMaxH3ReferenceKind::AUDIO || - block.kind == MiniMaxH3ReferenceKind::VIDEO_AUDIO) { - GGML_ASSERT(ref_audio != nullptr); - float w_low = w_axis.front(); - float w_high = w_axis.back(); - if (ref_video != nullptr) { - auto axes = condition_spatial_axes(*ref_video); - w_low = axes.second.front(); - w_high = axes.second.back(); - } - int64_t count = ref_audio->shape()[0] * 2; - append_audio_positions(ref_audio->shape()[0], cursor, w_low, w_high); - layout.sequence_segments.push_back({row, - row + count, - SequenceKind::CONDITION_AUDIO, - block.audio_index}); - layout.segments.push_back({row, - row + count, - audio_condition_time_row * 3 + 2}); - row += count; - block_end = std::max(block_end, cursor + static_cast(ref_audio->shape()[0])); + } + float target_start = cursor; + for (const auto& block : reference_blocks) { + GGML_ASSERT(block.video_index < static_cast(condition_videos.size())); + GGML_ASSERT(block.audio_index < static_cast(condition_audios.size())); + if (block.frame_index < 0) { + target_start = reference_end(block, target_start); + } + } + for (const auto& block : reference_blocks) { + const sd::Tensor* ref_video = nullptr; + const sd::Tensor* ref_audio = nullptr; + if (block.video_index >= 0) { + ref_video = &condition_videos[static_cast(block.video_index)]; + } + if (block.audio_index >= 0) { + ref_audio = &condition_audios[static_cast(block.audio_index)]; + } + + float start = block.frame_index < 0 ? cursor : target_start + FRAME_RESCALE * block.frame_index; + if (block.kind == MiniMaxH3ReferenceKind::AUDIO || + block.kind == MiniMaxH3ReferenceKind::VIDEO_AUDIO) { + GGML_ASSERT(ref_audio != nullptr); + float w_low = w_axis.front(); + float w_high = w_axis.back(); + if (ref_video != nullptr) { + auto axes = condition_spatial_axes(*ref_video); + w_low = axes.second.front(); + w_high = axes.second.back(); } + int64_t count = ref_audio->shape()[0] * 2; + append_audio_positions(ref_audio->shape()[0], start, w_low, w_high); + layout.sequence_segments.push_back({row, + row + count, + SequenceKind::CONDITION_AUDIO, + block.audio_index}); + layout.segments.push_back({row, + row + count, + audio_condition_time_row * 3 + 2}); + row += count; + } - if (block.kind != MiniMaxH3ReferenceKind::AUDIO) { - GGML_ASSERT(ref_video != nullptr); - auto axes = condition_spatial_axes(*ref_video); - int64_t count = ref_video->shape()[2] * - static_cast(axes.first.size() * axes.second.size()); - float video_end = append_video_positions(*ref_video, cursor); - layout.sequence_segments.push_back({row, - row + count, - SequenceKind::CONDITION_VIDEO, - block.video_index}); - layout.segments.push_back({row, row + count, condition_time_row * 3}); - row += count; - block_end = block.kind == MiniMaxH3ReferenceKind::IMAGE - ? std::max(block_end, cursor + 1.f) - : std::max(block_end, video_end); - } - cursor = block_end; + if (block.kind != MiniMaxH3ReferenceKind::AUDIO) { + GGML_ASSERT(ref_video != nullptr); + auto axes = condition_spatial_axes(*ref_video); + int64_t count = ref_video->shape()[2] * + static_cast(axes.first.size() * axes.second.size()); + append_video_positions(*ref_video, start); + layout.sequence_segments.push_back({row, + row + count, + SequenceKind::CONDITION_VIDEO, + block.video_index}); + layout.segments.push_back({row, row + count, condition_time_row * 3}); + row += count; + } + if (block.frame_index < 0) { + cursor = reference_end(block, cursor); } } diff --git a/src/model/diffusion/model.hpp b/src/model/diffusion/model.hpp index 993624b526..12838a456e 100644 --- a/src/model/diffusion/model.hpp +++ b/src/model/diffusion/model.hpp @@ -99,6 +99,7 @@ struct MiniMaxH3ReferenceBlock { MiniMaxH3ReferenceKind kind = MiniMaxH3ReferenceKind::IMAGE; int32_t video_index = -1; int32_t audio_index = -1; + int32_t frame_index = -1; }; struct MiniMaxH3DiffusionExtra { From 6aa32368aba3cf18cebad83374551764db4d573c Mon Sep 17 00:00:00 2001 From: Shogo Iwano Date: Sun, 29 Nov 2026 10:11:46 +0900 Subject: [PATCH 2/4] fix: crop MiniMax-H3 visual guides before resizing --- src/api/generation_h3.cpp | 6 ++++-- src/api/templates/video_h3.dgl | 8 +++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/api/generation_h3.cpp b/src/api/generation_h3.cpp index 9df998e720..b3eb123d46 100644 --- a/src/api/generation_h3.cpp +++ b/src/api/generation_h3.cpp @@ -79,8 +79,10 @@ namespace sd::api { const auto width = request.values.at("width").get(), height = request.values.at("height").get(); const auto w = sd_tensor_dim(video.data, 1), h = sd_tensor_dim(video.data, 2); const auto scale = std::max(double(width) / w, double(height) / h); - const auto size = literal({int64_t(std::ceil(w * scale)), int64_t(std::ceil(h * scale))}); - encode_visual("h3_guide_pixels(" + clip + ", width, height, " + size + ")"); + const auto crop_w = std::min(w, std::max(1, std::llround(width / scale))); + const auto crop_h = std::min(h, std::max(1, std::llround(height / scale))); + const auto crop_start = literal({(w - crop_w) / 2, (h - crop_h) / 2}), size = literal({crop_w, crop_h}); + encode_visual("h3_guide_pixels(" + clip + ", width, height, " + crop_start + ", " + size + ")"); if (video.audio.data) guide_audio(video.audio, start); } diff --git a/src/api/templates/video_h3.dgl b/src/api/templates/video_h3.dgl index 2fa62b79a4..ba4c42bf7f 100644 --- a/src/api/templates/video_h3.dgl +++ b/src/api/templates/video_h3.dgl @@ -6,11 +6,9 @@ var { {% include "video_helpers" %} -fn h3_guide_pixels(clip, width, height, size) { - pixels = image::to_f32(clip, channels = 3) - resized = tensor::interpolate(pixels, size = size, axes = [0, 1], mode = "lanczos") - start = [math::floor((size[0] - width) / 2), math::floor((size[1] - height) / 2)] - return tensor::crop(resized, axes = [0, 1], start = start, size = [width, height]) +fn h3_guide_pixels(clip, width, height, start, size) { + pixels = tensor::crop(image::to_f32(clip, channels = 3), axes = [0, 1], start = start, size = size) + return tensor::interpolate(pixels, size = [width, height], axes = [0, 1], mode = "lanczos") } fn main({{inputs}}) { From ff317970b6533cceb7531fc8d1d61f72557517d7 Mon Sep 17 00:00:00 2001 From: Shogo Iwano Date: Tue, 1 Dec 2026 03:52:43 +0900 Subject: [PATCH 3/4] refactor: scope MiniMax-H3 frame-indexed guides to DGL --- docs/dgl-builtins.md | 2 +- docs/dgl.md | 10 +- docs/dgl/README.md | 2 +- .../minimax-h3-reference-guides.dgl | 127 ++++++++++++++++++ docs/guides/c_api.md | 4 - docs/models/minimax_h3.md | 25 +--- examples/cli/main.cpp | 55 -------- examples/common/common.cpp | 97 +------------ examples/common/common.h | 8 -- examples/server/api.md | 4 +- src/api/generation_h3.cpp | 76 +++-------- src/api/generation_hires.cpp | 3 - src/api/generation_video.cpp | 5 - src/api/options.cpp | 4 - src/api/templates/video_h3.dgl | 5 - src/api/templates/video_reference.dgl | 2 +- src/config.h | 8 -- src/dgl/bindings/latents.cpp | 5 +- src/dgl/bindings/registration.cpp | 2 +- src/dgl/ops/media.cpp | 5 +- src/dgl/ops/media.h | 2 +- 21 files changed, 173 insertions(+), 278 deletions(-) create mode 100644 docs/dgl/minimax_h3/minimax-h3-reference-guides.dgl diff --git a/docs/dgl-builtins.md b/docs/dgl-builtins.md index b814553c03..cb547f224b 100644 --- a/docs/dgl-builtins.md +++ b/docs/dgl-builtins.md @@ -14,7 +14,7 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn | `audio::save` | `path: string`, `audio: dict`, `format?: string = "f32"` | `void` | | `audio_latent_shape` | `vae: audio_vae`, `frames: int`, `fps: int` | `tensor` | | `audio_vae_decode` | `vae: audio_vae`, `latent: tensor` | `dict`
`sample_rate: int`
`samples: tensor` | -| `audio_vae_encode` | `vae: audio_vae`, `samples: tensor`, `sample_rate: int`, `max_latents?: int = 0` | `tensor` | +| `audio_vae_encode` | `vae: audio_vae`, `samples: tensor`, `sample_rate: int` | `tensor` | | `cache` | `mode?: string = "disabled"`, `reuse_threshold?: number`, `start_percent?: number`, `end_percent?: number`, `error_decay_rate?: number`, `use_relative_threshold?: bool`, `reset_error_on_compute?: bool`, `residual_diff_threshold?: number`, `max_warmup_steps?: int`, `max_cached_steps?: int`, `max_continuous_cached_steps?: int`, `taylorseer_n_derivatives?: int`, `taylorseer_skip_interval?: int`, `scm_mask?: string`, `spectrum_w?: number`, `spectrum_m?: int`, `spectrum_lam?: number`, `spectrum_window_size?: int`, `spectrum_flex_window?: number`, `spectrum_warmup_steps?: int`, `spectrum_stop_percent?: number` | `dict`
`end_percent: number`
`error_decay_rate: number`
`max_cached_steps: int`
`max_continuous_cached_steps: int`
`max_warmup_steps: int`
`mode: string`
`reset_error_on_compute: bool`
`residual_diff_threshold: number`
`reuse_threshold: number`
`scm_mask: string`
`spectrum_flex_window: number`
`spectrum_lam: number`
`spectrum_m: int`
`spectrum_stop_percent: number`
`spectrum_w: number`
`spectrum_warmup_steps: int`
`spectrum_window_size: int`
`start_percent: number`
`taylorseer_n_derivatives: int`
`taylorseer_skip_interval: int`
`use_relative_threshold: bool` | | `cfg` | `positive: predictor`, `negative: predictor`, `scale: number`, `image_only?: predictor`, `image_scale?: number = 1`, `schedule?: list` | `predictor` | | `controlnet::apply` | `condition: dict`, `model: control_net`, `hint: tensor`, `strength?: number = 1`, `start_sigma?: number`, `end_sigma?: number`, `type?: string = "none"` | same type as `condition`
`controls: control_bindings` | diff --git a/docs/dgl.md b/docs/dgl.md index 16286d0637..0da0c97bd1 100644 --- a/docs/dgl.md +++ b/docs/dgl.md @@ -1304,8 +1304,7 @@ video::save("output.avi", video, audio = track) `encode_audio(encoder, samples, sample_rate=...)` and `audio_vae_encode(vae, samples, sample_rate=...)` accept tensors and an explicit -sample rate. On MiniMax-H3, pass `max_latents` to `audio_vae_encode` to encode -only the requested prefix. The default, 0, encodes the full input. +sample rate. Their existing model-specific resampling remains in effect. `audio_vae_decode` reports the decoder's actual output sample rate. ## Regions and masks @@ -1564,7 +1563,12 @@ Each block has a `kind` of `image`, `video`, `audio` or `video_audio`. an `audio` index into `ref_audios`; `video_audio` requires both. Indices are zero-based nonnegative integers, and list order determines reference order. Set a block's optional `frame_index` to anchor it to a zero-based output frame. -Blocks without this field precede the output timeline. +Blocks without this field precede the output timeline. Keep `frame_index` +below the aligned output frame count; it is not validated. The +[frame-indexed guide program](dgl/minimax_h3/minimax-h3-reference-guides.dgl) +combines an image reference with first and last frame guides and an audio guide. +It slices the audio latent, 5 latents per 3 output frames, to the duration +left after its anchor frame. If `ref_latents` is empty, video indices refer to the condition's `ref_images`. The explicit argument overrides the condition field, including an empty list. Malformed blocks or out-of-range indices fail when constructing the predictor, diff --git a/docs/dgl/README.md b/docs/dgl/README.md index df8958cc69..2debdd54fe 100644 --- a/docs/dgl/README.md +++ b/docs/dgl/README.md @@ -91,7 +91,7 @@ and [NumPy tensor files](../dgl.md#tensor-files). | [LingBot-Video](../models/lingbot_video.md) | [Dens 1.3B text to video](lingbot_video/lingbot-video-dens-1-3b-txt2video.dgl) | | [LTX-2.3](../models/ltx2.md) | [2.3 text to video](ltx2/ltx-2-3-dev-txt2video.dgl) · [2.3 image to video](ltx2/ltx-2-3-dev-img2video.dgl) · [2.3 first/last frames](ltx2/ltx-2-3-dev-first-last-frame.dgl) · [2.3 spatial latent upscale](ltx2/ltx-2-3-spatial-upscale.dgl) | | [LTX-2.5](../models/ltx2.md) | [2.5 text to video](ltx2/ltx-2-5-dev-txt2video.dgl) · [2.5 image to video](ltx2/ltx-2-5-dev-img2video.dgl) · [2.5 spatial latent upscale](ltx2/ltx-2-5-spatial-upscale.dgl) | -| [MiniMax-H3](../models/minimax_h3.md) | [Text to audio/video](minimax_h3/minimax-h3-text-to-av.dgl) · [First/last-frame conditioning](minimax_h3/minimax-h3-first-last-frame.dgl) · [Reference to audio/video](minimax_h3/minimax-h3-reference-to-av.dgl) · [Interpolated latent hires](minimax_h3/minimax-h3-latent-hires.dgl) · [Learned latent hires](minimax_h3/minimax-h3-learned-hires.dgl) | +| [MiniMax-H3](../models/minimax_h3.md) | [Text to audio/video](minimax_h3/minimax-h3-text-to-av.dgl) · [First/last-frame conditioning](minimax_h3/minimax-h3-first-last-frame.dgl) · [Reference to audio/video](minimax_h3/minimax-h3-reference-to-av.dgl) · [Reference with frame-indexed guides](minimax_h3/minimax-h3-reference-guides.dgl) · [Interpolated latent hires](minimax_h3/minimax-h3-latent-hires.dgl) · [Learned latent hires](minimax_h3/minimax-h3-learned-hires.dgl) | | [Wan 2.1](../models/wan.md) | [Text to video, 1.3B](wan/wan2-1-t2v-1-3b.dgl) · [Text to video, 14B](wan/wan2-1-t2v-14b.dgl) · [Image to video, 14B](wan/wan2-1-i2v-14b.dgl) · [First/last frames, 14B](wan/wan2-1-first-last-frame-14b.dgl) | | [Wan 2.1 VACE 1.3B](../models/wan.md) | [Text to video](wan/wan2-1-vace-1-3b-txt2video.dgl) · [Reference to video](wan/wan2-1-vace-1-3b-ref2video.dgl) · [Video to video](wan/wan2-1-vace-1-3b-video2video.dgl) | | [Wan 2.1 VACE 14B](../models/wan.md) | [Text to video](wan/wan2-1-vace-14b-txt2video.dgl) · [Reference to video](wan/wan2-1-vace-14b-ref2video.dgl) · [Video to video](wan/wan2-1-vace-14b-video2video.dgl) | diff --git a/docs/dgl/minimax_h3/minimax-h3-reference-guides.dgl b/docs/dgl/minimax_h3/minimax-h3-reference-guides.dgl new file mode 100644 index 0000000000..dcbcdcab2e --- /dev/null +++ b/docs/dgl/minimax_h3/minimax-h3-reference-guides.dgl @@ -0,0 +1,127 @@ +# version: 0.0.0 +# docs/models/minimax_h3.md — Reference with frame-indexed guides + +var { + model_path = "../models/diffusion_models/minimax_h3_ref2va_pruned-Q4_K_M.gguf" + text_path = "../models/text_encoders/qwen3vl_32b_minimax_h3-Q4_K_M.gguf" + vae_path = "../models/vae/minimax_h3_video_vae_fp16.safetensors" + audio_vae_path = "../models/vae/minimax_h3_audio_vae_fp32.safetensors" + + reference_path = "../inputs/ernie_image/turbo_example.png" + first_frame_path = "../inputs/start_image.png" + last_frame_path = "../inputs/end_image.png" + guide_audio_path = "../inputs/dialogue.wav" + guide_audio_frame = 24 + output_path = "output.avi" + + prompt = "The cat from looks at the camera, meows, then walks toward the beach." + + seed = 42 + rng_type = "cpu" + width = 864 + height = 480 + frames = 56 + fps = 24 + + steps = 20 + method = "euler" + scheduler = "discrete" + audio_scale = 4 +} + +fn pack_av(video, audio, audio_scale) { + shape = tensor::shape(video) + count = tensor::numel(audio) + tail_channels = math::ceil_div(count, shape[0] * shape[1] * shape[2]) + tail_shape = [shape[0], shape[1], shape[2], tail_channels, 1] + flat = tensor::reshape(tensor::mul(audio, audio_scale), [count]) + padded = tensor::pad(flat, [0, math::product(tail_shape) - count]) + return tensor::concat([video, tensor::reshape(padded, tail_shape)], axis = 3) +} + +fn unpack_audio(packed, channels, audio_shape, audio_scale) { + tail = packed[:, :, :, channels:] + flat = tensor::reshape(tail, [tensor::numel(tail)]) + return tensor::div(tensor::reshape(flat[:math::product(audio_shape)], audio_shape), audio_scale) +} + +fn h3_reference_noise(latent, seed) { + rng = make_rng("cuda", seed = seed) + return tensor::lerp(latent, tensor::randn_like(latent, rng = rng), 0.001) +} + +fn sqrt_step(estimate, index, value) { + return (estimate + value / estimate) / 2 +} + +fn positive_sqrt(value) { + return fold(tensor::to_list(tensor::arange(0, 32)), value + 1.0, process = sqrt_step, value = value) +} + +fn fit_reference_area(input, area, factor, mode) { + shape = tensor::shape(input) + width = positive_sqrt(area * shape[0] / shape[1]) + rounded = [math::round(width / factor) * factor, math::round(width * shape[1] / shape[0] / factor) * factor] + size = tensor::maximum(tensor::vector(rounded, dtype = "i64"), tensor::full([2], factor, dtype = "i64")) + return tensor::interpolate(input, size = size, mode = mode) +} + +fn guide_pixels(image, width, height) { + pixels = image::to_f32(image, channels = 3) + shape = tensor::shape(pixels) + crop_width = math::min(shape[0], math::floor(shape[1] * width / height)) + crop_height = math::min(shape[1], math::floor(shape[0] * height / width)) + start = [math::floor((shape[0] - crop_width) / 2), math::floor((shape[1] - crop_height) / 2)] + cropped = tensor::crop(pixels, axes = [0, 1], start = start, size = [crop_width, crop_height]) + return tensor::unsqueeze(tensor::interpolate(cropped, size = [width, height], axes = [0, 1], mode = "lanczos"), axis = 2) +} + +fn main() { + reference = image::load(reference_path) + first_frame = image::load(first_frame_path) + last_frame = image::load(last_frame_path) + guide_sound = audio::load(guide_audio_path) + + model = load_dit(model_path, family = "minimax_h3", params_backend = "cpu") + text = load_text_encoder(text_path, family = "minimax_h3", params_backend = "cpu") + vae = load_vae(vae_path, family = "minimax_h3", params_backend = "cpu") + + rng = make_rng(rng_type, seed = seed) + # latent_shape rounds the frame count up to 5 + 17k. + aligned_frames = math::ceil_div(frames - 5, 17) * 17 + 5 + video_base = tensor::zeros(latent_shape(vae, width = width, height = height, frames = frames)) + audio_vae = load_audio_vae(audio_vae_path, family = "minimax_h3", params_backend = "cpu") + audio_shape = audio_latent_shape(audio_vae, frames = aligned_frames, fps = fps) + base = pack_av(video_base, tensor::zeros(audio_shape), audio_scale = audio_scale) + + first_guide = h3_reference_noise(vae_to_dit_latents(vae, vae_encode(vae, guide_pixels(first_frame, width, height), rng = rng)), seed) + last_guide = h3_reference_noise(vae_to_dit_latents(vae, vae_encode(vae, guide_pixels(last_frame, width, height), rng = rng)), seed) + + # The model places 5 audio latents per 3 output frames. Keep the part that fits after the anchor frame. + guide_audio_full = audio_vae_encode(audio_vae, guide_sound.samples, sample_rate = guide_sound.sample_rate) + guide_audio = guide_audio_full[:audio_shape[0] - math::round(guide_audio_frame * 5 / 3)] + + reference_original = image::to_f32(reference, channels = 3) + reference_area = math::min(width * height, tensor::shape(reference_original)[0] * tensor::shape(reference_original)[1]) + reference_pixels = fit_reference_area(reference_original, reference_area, 32, mode = "bilinear") + reference_latent = h3_reference_noise(vae_to_dit_latents(vae, vae_encode(vae, reference_pixels, rng = rng)), seed) + + condition = encode_prompt(text, prompt, width = width, height = height, media = [{image = reference_pixels}]) + predict = predictor(model, condition, audio_length = audio_shape[0], + ref_latents = [first_guide, last_guide, reference_latent], ref_audios = [guide_audio], + reference_blocks = [ + {kind = "video", video = 0, frame_index = 0}, + {kind = "video", video = 1, frame_index = aligned_frames - 1}, + {kind = "audio", audio = 0, frame_index = guide_audio_frame}, + {kind = "image", video = 2} + ]) + sigmas = make_sigmas(predict, latent = base, steps = steps, scheduler = scheduler) + start = add_noise(predict, base, tensor::randn_like(base, rng = rng), sigma = sigmas[0]) + latent = sample(start, sigmas, predict = predict, method = method, rng = rng) + video_latent = latent[:, :, :tensor::shape(video_base)[2], :tensor::shape(video_base)[3]] + output_frames = vae_decode(vae, dit_to_vae_latents(vae, video_latent)) + sound_latent = unpack_audio(latent, channels = tensor::shape(video_base)[3], audio_shape = audio_shape, audio_scale = audio_scale) + audio = audio_vae_decode(audio_vae, sound_latent) + video::save(output_path, {frames = output_frames, fps_num = fps, fps_den = 1}, audio = audio) + return {video = {frames = output_frames, fps_num = fps, fps_den = 1}, latent = latent, audio = audio} +} diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md index 6d185369a7..e456c0050d 100644 --- a/docs/guides/c_api.md +++ b/docs/guides/c_api.md @@ -422,10 +422,6 @@ For SDXL's bundled VAE (no `vae_path`), generation emits | `flash_attn_mode` | `string` | context | | `force_sdxl_vae_conv_scale` | `bool` | context | | `fps` | `int` | video | -| `guide_audio_indices` | `ints` | video | -| `guide_audios` | `audios` | video | -| `guide_video_indices` | `ints` | video | -| `guide_videos` | `videos` | video | | `height` | `int` | image, video | | `high_noise_diffusion_model_path` | `string` | context | | `image` | `tensor` | upscale | diff --git a/docs/models/minimax_h3.md b/docs/models/minimax_h3.md index 514432e7b1..4e9070a19a 100644 --- a/docs/models/minimax_h3.md +++ b/docs/models/minimax_h3.md @@ -131,6 +131,7 @@ Select optional components when required by your checkpoint or task. | [Text to audio/video](../dgl/minimax_h3/minimax-h3-text-to-av.dgl) | Generate video and its soundtrack together. | | [First/last-frame conditioning](../dgl/minimax_h3/minimax-h3-first-last-frame.dgl) | Guide the video with endpoint images. | | [Reference to audio/video](../dgl/minimax_h3/minimax-h3-reference-to-av.dgl) | Use image, video and audio references. | +| [Reference with frame-indexed guides](../dgl/minimax_h3/minimax-h3-reference-guides.dgl) | Combine a reference with first/last-frame guides and audio anchored at a frame. | | [Interpolated latent hires](../dgl/minimax_h3/minimax-h3-latent-hires.dgl) | Resize the draft latent, then run a second sampling pass. | | [Learned latent hires](../dgl/minimax_h3/minimax-h3-learned-hires.dgl) | Use a learned latent upscaler between sampling passes. | @@ -331,24 +332,10 @@ generation. Reference inputs are presented to Qwen3-VL in image, video, then audio order. Videos are sampled at 2 fps for the Qwen presentation while their full 24 fps latents condition the diffusion transformer. Paired video and audio references -share the same timeline. - -Use repeatable `--guide-image PATH@FRAME` and `--guide-audio WAV@FRAME` to -anchor guides on the target timeline, including in Ref2VA requests. For example, -`--ref-image actor.png --guide-image board.png@0 --guide-audio line.wav@24 --guide-image ending.png@-1` -anchors the dialogue at one second. Negative indices count from the aligned -frame count. `--init-img` and `--end-img` anchor the first and last frames. - -A visual guide accepts one image or a 24 fps frame directory. Clips shorter -than five frames use their first image. Longer clips use the largest prefix of -`17k + 5` frames and must fit at the specified index. Audio guides require -audio VAE encoder weights and are cropped to the remaining target duration. -Frame-indexed guides do not receive prompt tags. Without Ref2VA references, -`--init-img` and `--end-img` retain their legacy Qwen3-VL picture tags. - -C API and `sdcpp` requests pair `guide_videos` and `guide_audios` with -`guide_video_indices` and `guide_audio_indices`, respectively. Use a -single-frame video for an image. A C API video guide can include its own soundtrack. +share the same timeline. Ref2VA cannot be combined with `--init-img` or +`--end-img` in one request. To combine references with guides anchored at +output frames, use the +[frame-indexed guide DGL program](../dgl/minimax_h3/minimax-h3-reference-guides.dgl). Reference images preserve their aspect ratio and are downscaled only when their pixel area exceeds the generation canvas. Each axis is then snapped to @@ -491,7 +478,7 @@ Notes for this mode: - `--hires-sigmas` can replace `--hires-denoising-strength` when the second stage should resume from an explicit sigma schedule, which is how most two-stage H3 workflows split the sampler. -- Visual guide conditioning (`--guide-image`, `--init-img`, `--end-img`) is not available together +- Keyframe conditioning (`--init-img` / `--end-img`) is not available together with hires yet: those latents are encoded at the first stage resolution and would have to be re-encoded for the hires canvas. Use T2VA or Ref2VA. - The second stage runs at the larger latent, so it is the memory-hungry half; diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp index 96447350d0..e3b7202f45 100644 --- a/examples/cli/main.cpp +++ b/examples/cli/main.cpp @@ -320,44 +320,6 @@ void sd_log_cb(enum sd_log_level_t level, const char* log, void* data) { log_print(level, log, cli_params->log_level, cli_params->color, log_stream); } -static bool load_guide_image(const std::string& path, SDImageOwner& image) { - if (!load_sd_image_from_file(image.put(), path.c_str(), 0, 0, 0)) { - return false; - } - normalize_guide_frame_rgb(image.get()); - return true; -} - -static bool load_guide_frames(const fs::path& dir_path, std::vector& images) { - std::vector entries; - for (const auto& entry : fs::directory_iterator(dir_path)) { - if (!entry.is_regular_file()) { - continue; - } - std::string ext = entry.path().extension().u8string(); - std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); - if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".webp") { - entries.push_back(entry); - } - } - - std::sort(entries.begin(), entries.end(), - [](const fs::directory_entry& a, const fs::directory_entry& b) { - return a.path().filename().u8string() < b.path().filename().u8string(); - }); - entries.resize(minimax_h3_guide_frame_count(entries.size())); - for (const auto& entry : entries) { - std::string path = entry.path().u8string(); - LOG_VERBOSE("load image %zu from '%s'", images.size(), path.c_str()); - SDImageOwner image; - if (!load_guide_image(path, image)) { - return false; - } - images.push_back(std::move(image)); - } - return true; -} - std::string format_frame_idx(std::string pattern, int frame_idx) { std::smatch match; std::string result = pattern; @@ -744,23 +706,6 @@ int main(int argc, const char* argv[]) { } } - for (const auto& path : gen_params.guide_video_paths) { - auto& frames = gen_params.guide_videos.emplace_back(); - if (fs::is_directory(fs::u8path(path))) { - if (!load_guide_frames(fs::u8path(path), frames) || frames.empty()) { - return 1; - } - } else if (!load_guide_image(path, frames.emplace_back())) { - LOG_ERROR("failed to load guide image '%s'", path.c_str()); - return 1; - } - } - for (const auto& path : gen_params.guide_audio_paths) { - if (!load_audio(path, gen_params.guide_audios.emplace_back())) { - return 1; - } - } - if (!gen_params.ref_video_paths.empty()) { gen_params.ref_videos.clear(); gen_params.ref_video_audios.clear(); diff --git a/examples/common/common.cpp b/examples/common/common.cpp index b5d4185704..cf400eb1a2 100644 --- a/examples/common/common.cpp +++ b/examples/common/common.cpp @@ -2,10 +2,8 @@ #include #include -#include #include #include -#include #include #include #include @@ -1388,27 +1386,6 @@ ArgOptions SDGenerationParams::get_options() { return 1; }; - auto on_guide_arg = [&](int argc, const char** argv, int index) { - bool audio = std::string(argv[index]) == "--guide-audio"; - if (++index >= argc) { - return -1; - } - auto arg = argv_to_utf8(index, argv); - auto at = arg.rfind('@'); - int32_t frame; - if (at == std::string::npos || at == 0) { - return -1; - } - const char* end = arg.data() + arg.size(); - auto parsed = std::from_chars(arg.data() + at + 1, end, frame); - if (parsed.ec != std::errc() || parsed.ptr != end) { - return -1; - } - (audio ? guide_audio_paths : guide_video_paths).push_back(arg.substr(0, at)); - (audio ? guide_audio_indices : guide_video_indices).push_back(frame); - return 1; - }; - auto on_ref_video_arg = [&](int argc, const char** argv, int index) { if (++index >= argc) { return -1; @@ -1604,8 +1581,6 @@ ArgOptions SDGenerationParams::get_options() { "--hires-sigmas", "custom sigma values for the highres fix second pass, comma-separated (e.g., \"0.85,0.725,0.421875,0.0\") or preset: qwen-image-2.1-turbo, p-h3-image, minimax-h3-image, hyperflow-h3-flash-4, hyperflow-h3-flash-6, hyperflow-h3-flash-8.", on_hires_sigmas_arg}, - {"", "--guide-image", "MiniMax-H3 image or frame directory: PATH@FRAME (repeatable)", on_guide_arg}, - {"", "--guide-audio", "MiniMax-H3 WAV guide: PATH@FRAME (repeatable)", on_guide_arg}, {"-r", "--ref-image", "reference image for Flux Kontext or MiniMax-H3 Ref2VA (can be used multiple times)", @@ -1846,24 +1821,10 @@ static bool parse_audio_array_json_field(const json& parent, return true; } -size_t minimax_h3_guide_frame_count(size_t available) { - return available < 5 ? std::min(available, 1) : available - (available - 5) % 17; -} - -void normalize_guide_frame_rgb(SDImage& image) { - if (image.channel == 4) { - for (size_t pixel = 0; pixel < size_t(image.width) * image.height; ++pixel) { - std::memmove(image.data + pixel * 3, image.data + pixel * 4, 3); - } - image.channel = 3; - } -} - /** Parses a JSON array of per-video base64 frame arrays into owned videos. */ static bool parse_video_array_json_field(const json& parent, const char* key, - std::vector>& out_videos, - bool visual_guide = false) { + std::vector>& out_videos) { if (!parent.contains(key)) { return true; } @@ -1881,9 +1842,7 @@ static bool parse_video_array_json_field(const json& parent, return false; } std::vector frames; - size_t count = visual_guide ? minimax_h3_guide_frame_count(video.size()) : video.size(); - for (size_t i = 0; i < count; ++i) { - const auto& frame = video[i]; + for (const auto& frame : video) { if (!frame.is_string()) { return false; } @@ -1891,9 +1850,6 @@ static bool parse_video_array_json_field(const json& parent, if (!decode_base64_image(frame.get(), 0, 0, 0, image)) { return false; } - if (visual_guide) { - normalize_guide_frame_rgb(image.get()); - } frames.push_back(std::move(image)); } out_videos.push_back(std::move(frames)); @@ -2180,31 +2136,7 @@ bool SDGenerationParams::from_json_str( !load_image("ip_adapter_image", 3, ip_adapter_image)) { return false; } - auto read_guide_indices = [&](const char* key, std::vector& indices) { - if (!j.contains(key)) { - return true; - } - if (j.at(key).is_null()) { - indices.clear(); - return true; - } - if (!j.at(key).is_array()) { - return false; - } - indices.clear(); - for (const auto& index : j.at(key)) { - if (!index.is_number_integer() || index.get() < INT32_MIN || index.get() > INT32_MAX) { - return false; - } - indices.push_back(index.get()); - } - return true; - }; - if (!parse_video_array_json_field(j, "guide_videos", guide_videos, true) || - !parse_audio_array_json_field(j, "guide_audios", guide_audios) || - !read_guide_indices("guide_video_indices", guide_video_indices) || - !read_guide_indices("guide_audio_indices", guide_audio_indices) || - !parse_image_array_json_field(j, "ref_images", 0, ref_images) || + if (!parse_image_array_json_field(j, "ref_images", 0, ref_images) || !parse_image_array_json_field(j, "control_frames", 3, control_frames) || !parse_audio_array_json_field(j, "ref_audios", ref_audios) || !parse_audio_array_json_field(j, "ref_video_audios", ref_video_audios) || @@ -2467,12 +2399,7 @@ bool SDGenerationParams::validate(SDMode mode) { return false; } - if (guide_video_indices.size() != guide_video_paths.size() + guide_videos.size() || - guide_audio_indices.size() != guide_audio_paths.size() + guide_audios.size()) { - LOG_ERROR("each guide requires one frame index"); - return false; - } - if (mode != VID_GEN && (!guide_video_indices.empty() || !guide_audio_indices.empty() || !ref_video_paths.empty() || !ref_video_audio_paths.empty() || !ref_audio_paths.empty() || + if (mode != VID_GEN && (!ref_video_paths.empty() || !ref_video_audio_paths.empty() || !ref_audio_paths.empty() || !ref_videos.empty() || !ref_video_audios.empty() || !ref_audios.empty())) { LOG_ERROR("error: reference video and audio inputs require vid_gen mode"); return false; @@ -2723,22 +2650,6 @@ SDOptPtr SDGenerationParams::to_video_opt() { opt.set_bool("circular_y", circular_y); opt.set_loras("loras", lora_vec.data(), lora_vec.size()); opt.set_images("ref_images", ref_image_views.data(), ref_image_views.size()); - std::vector> guide_frames(guide_videos.size()); - std::vector videos; - for (size_t i = 0; i < guide_videos.size(); ++i) { - for (const auto& frame : guide_videos[i]) { - guide_frames[i].push_back(frame.get()); - } - videos.push_back({guide_frames[i].data(), static_cast(guide_frames[i].size()), 24, {}}); - } - std::vector audios; - for (auto& audio : guide_audios) { - audios.push_back(audio.get()); - } - opt.set_videos("guide_videos", videos.data(), videos.size()); - opt.set_audios("guide_audios", audios.data(), audios.size()); - opt.set_ints("guide_video_indices", guide_video_indices.data(), guide_video_indices.size()); - opt.set_ints("guide_audio_indices", guide_audio_indices.data(), guide_audio_indices.size()); opt.set_videos("ref_videos", ref_video_views.data(), ref_video_views.size()); opt.set_audios("ref_audios", ref_audio_views.data(), ref_audio_views.size()); opt.set_frames("control_frames", control_frame_views.data(), control_frame_views.size()); diff --git a/examples/common/common.h b/examples/common/common.h index 73796ed1b5..cddfaf0c88 100644 --- a/examples/common/common.h +++ b/examples/common/common.h @@ -17,8 +17,6 @@ // The command-line argument at `index` as UTF-8 (on Windows, read again from // the UTF-16 command line: argv itself is in the ANSI code page). std::string argv_to_utf8(int index, const char** argv); -size_t minimax_h3_guide_frame_count(size_t available); -void normalize_guide_frame_rgb(SDImage& image); #define SAFE_STR(s) ((s) ? (s) : "") #define BOOL_STR(b) ((b) ? "true" : "false") @@ -233,12 +231,6 @@ struct SDGenerationParams { std::optional control_type; std::vector ref_image_paths; std::vector ref_video_paths; - std::vector guide_video_paths; - std::vector guide_audio_paths; - std::vector guide_video_indices; - std::vector guide_audio_indices; - std::vector> guide_videos; - std::vector guide_audios; std::vector ref_video_audio_paths; std::vector ref_audio_paths; std::string control_video_path; diff --git a/examples/server/api.md b/examples/server/api.md index 90ffb40e57..1c9b15e40e 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -1429,8 +1429,6 @@ Compared with `img_gen`, the `vid_gen` request body: - `mask_image`, `control_image`, `control_strength`, `ip_adapter_image`, `ip_adapter_strength`, and `embed_image_metadata` are not part of the request schema - `ref_images` is accepted for MiniMax-H3 Ref2VA conditioning; other video model families currently ignore it - `vid_gen` adds `end_image`, `control_frames`, `high_noise_sample_params`, `video_frames`, `fps`, `moe_boundary`, and `vace_strength` -- `guide_videos` accepts MiniMax-H3 visual guides as arrays of base64 frames. `guide_video_indices` supplies one signed target frame index per guide. -- `guide_audios` accepts MiniMax-H3 audio guides as base64 WAV strings. `guide_audio_indices` supplies one signed target frame index per guide. Example: @@ -1501,7 +1499,7 @@ Example: - `ref_images` contains reference images for MiniMax-H3 Ref2VA conditioning. - Images retain request order and correspond to ``, ``, and so on in the prompt. -- MiniMax-H3 accepts references together with frame-indexed guides, including `init_image` and `end_image`. +- For MiniMax-H3, non-empty `ref_images` cannot be combined with `init_image` or `end_image`. A conflicting API request fails during generation; the WebUI checks this before submission. - MiniMax-H3 does not support `control_frames`; leave that array empty. - Other video model families currently ignore `ref_images`. - `features_by_mode.vid_gen` does not currently advertise `ref_images`; its absence is not an indication that MiniMax-H3 reference images are unsupported. diff --git a/src/api/generation_h3.cpp b/src/api/generation_h3.cpp index b3eb123d46..766c2ec956 100644 --- a/src/api/generation_h3.cpp +++ b/src/api/generation_h3.cpp @@ -16,12 +16,15 @@ namespace sd::api { const auto videos = bound_videos(request.options, "ref_videos"); const auto audios = bound_audios(request.options, "ref_audios"); const bool references = !images.empty() || !videos.empty() || !audios.empty(); - const auto guide_videos = bound_videos(request.options, "guide_videos"); - const auto guide_audios = bound_audios(request.options, "guide_audios"); - if (!references && first.empty() && last.empty() && guide_videos.empty() && guide_audios.empty()) + const bool audio_references = !audios.empty() || std::any_of(videos.begin(), videos.end(), [](const sd_video_t& video) { return video.audio.data != nullptr; }); + if (audio_references && !request.flags.at("decode_audio").get()) + throw dgl::Error(SD_STATUS_LOAD_FAILED, "MiniMax-H3 audio references require audio VAE weights"); + if (references && (!first.empty() || !last.empty())) + throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "MiniMax-H3 references and start/end keyframes cannot be combined"); + if (!references && first.empty() && last.empty()) return; auto& prepare = request.fields["references"]; - std::vector visuals, sounds, presentation, blocks; + std::vector visuals, sounds, presentation, blocks, keys; const auto encode_visual = [&](const std::string& pixels, const nlohmann::json& options = nlohmann::json::object()) { const auto name = "h3_visual_" + std::to_string(visuals.size()); nlohmann::json parameters{{"name", name}, {"pixels", pixels}, {"encode_audio", false}, {"resize_video", false}, {"resize_image", false}}; @@ -29,65 +32,26 @@ namespace sd::api { prepare += request.render("video_reference", parameters); visuals.push_back(name); }; - const auto encode_sound = [&](const sd_audio_t& audio, int64_t limit = 0) { - if (!request.flags.at("decode_audio").get()) - throw dgl::Error(SD_STATUS_LOAD_FAILED, "MiniMax-H3 audio conditioning requires audio VAE weights"); + const auto encode_sound = [&](const sd_audio_t& audio) { const auto name = "h3_sound_" + std::to_string(sounds.size()); bind_tensor(request.program, name + "_samples", audio.data); const auto media = "{samples = " + name + "_samples, sample_rate = " + std::to_string(audio.sample_rate) + "}"; - prepare += request.render("video_reference", {{"encode_audio", true}, {"name", name}, {"sample_rate", audio.sample_rate}, {"limit", limit}}); + prepare += request.render("video_reference", {{"encode_audio", true}, {"name", name}, {"sample_rate", audio.sample_rate}}); sounds.push_back(name); - if (!limit) - presentation.push_back("{audio = " + media + "}"); + presentation.push_back("{audio = " + media + "}"); }; - const int frames = request.values.at("frames").get(); - std::vector key_images; - for (const auto& [pixels, index] : std::vector>{{first, 0}, {last, frames - 1}}) { - if (pixels.empty()) - continue; - blocks.push_back(literal({{"kind", "video"}, {"video", visuals.size()}, {"frame_index", index}})); - encode_visual(pixels); - key_images.push_back(pixels + "[:, :, 0]"); - } - if (!references && !key_images.empty()) { + if (!references) { + std::vector key_images; + for (const auto& [pixels, index] : std::vector>{{first, "0"}, {last, "frames - 1"}}) { + if (pixels.empty()) + continue; + encode_visual(pixels); + key_images.push_back(pixels + "[:, :, 0]"); + keys.push_back(index); + } request.fields["prompt_options"] += ", media = " + expression_list(key_images); request.fields["negative_prompt_options"] += ", media = " + expression_list(key_images); } - const auto resolve_index = [&](int index) { - if (index < 0) - index += frames; - if (index < 0 || index >= frames) - throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "MiniMax-H3 guide frame index outside target"); - return index; - }; - const auto guide_audio = [&](const sd_audio_t& audio, int start) { - blocks.push_back(literal({{"kind", "audio"}, {"audio", sounds.size()}, {"frame_index", start}})); - encode_sound(audio, std::llround(frames * (40.0 / 24)) - (5LL * start + 2) / 3); - }; - for (size_t i = 0; i < guide_videos.size(); ++i) { - const auto& video = guide_videos[i]; - const int start = resolve_index(request.video->guide_video_indices[i]); - const int64_t available = sd_tensor_dim(video.data, 3); - const int64_t count = available < 5 ? 1 : available - (available - 5) % 17; - if (available < 1 || video.fps != 24 || count > frames - start) - throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "MiniMax-H3 visual guide requires 24 fps frames that fit at the requested index"); - const auto name = "guide_video_" + std::to_string(i); - bind_tensor(request.program, name, video.data); - blocks.push_back(literal({{"kind", "video"}, {"video", visuals.size()}, {"frame_index", start}})); - const auto channels = sd_tensor_dim(video.data, 0) == 2 ? ":1" : ":"; - const auto clip = name + "[" + channels + ", :, :, :" + std::to_string(count) + "]"; - const auto width = request.values.at("width").get(), height = request.values.at("height").get(); - const auto w = sd_tensor_dim(video.data, 1), h = sd_tensor_dim(video.data, 2); - const auto scale = std::max(double(width) / w, double(height) / h); - const auto crop_w = std::min(w, std::max(1, std::llround(width / scale))); - const auto crop_h = std::min(h, std::max(1, std::llround(height / scale))); - const auto crop_start = literal({(w - crop_w) / 2, (h - crop_h) / 2}), size = literal({crop_w, crop_h}); - encode_visual("h3_guide_pixels(" + clip + ", width, height, " + crop_start + ", " + size + ")"); - if (video.audio.data) - guide_audio(video.audio, start); - } - for (size_t i = 0; i < guide_audios.size(); ++i) - guide_audio(guide_audios[i], resolve_index(request.video->guide_audio_indices[i])); for (size_t i = 0; i < images.size(); ++i) { const auto name = "h3_image_" + std::to_string(i); bind_tensor(request.program, name, images[i]); @@ -141,6 +105,8 @@ namespace sd::api { options += ", ref_audios = " + expression_list(sounds); if (!blocks.empty()) options += ", reference_blocks = " + expression_list(blocks); + if (!keys.empty()) + options += ", keyframe_indices = " + expression_list(keys); request.fields["predictor_options"] += options; request.fields["negative_predictor_options"] += options; if (!presentation.empty()) { diff --git a/src/api/generation_hires.cpp b/src/api/generation_hires.cpp index da34295016..7c11b21dc8 100644 --- a/src/api/generation_hires.cpp +++ b/src/api/generation_hires.cpp @@ -23,9 +23,6 @@ namespace sd::api { const bool pixels = !request.video && (model || mode == "lanczos" || mode == "nearest"); const auto version = request.definition.version; const bool ltx = sd_version_is_ltxav(version); - if (request.video && version == VERSION_MINIMAX_H3 && - (bound_tensor(request.options, "init_image") || bound_tensor(request.options, "end_image") || !bound_videos(request.options, "guide_videos").empty())) - throw dgl::Error(SD_STATUS_UNSUPPORTED, "MiniMax-H3 hires does not support visual guides"); if (request.video && !ltx && version != VERSION_MINIMAX_H3) throw dgl::Error(SD_STATUS_UNSUPPORTED, "video hires supports LTX and MiniMax-H3; other workflows can be written in DGL"); if (request.video && (mode == "lanczos" || mode == "nearest")) diff --git a/src/api/generation_video.cpp b/src/api/generation_video.cpp index 989b6610d7..8e4a963d55 100644 --- a/src/api/generation_video.cpp +++ b/src/api/generation_video.cpp @@ -103,11 +103,6 @@ namespace sd::api { const bool frozen = (version == VERSION_WAN2_2_TI2V || sd_version_is_lingbot_video(version)) && (first || last); const bool ltx = sd_version_is_ltxav(version); const bool h3 = version == VERSION_MINIMAX_H3; - if (request.video->guide_videos_count != request.video->guide_video_indices_count || - request.video->guide_audios_count != request.video->guide_audio_indices_count) - throw dgl::Error(SD_STATUS_INVALID_ARGUMENT, "each MiniMax-H3 guide requires one frame index"); - if (!h3 && (request.video->guide_videos_count || request.video->guide_audios_count)) - throw dgl::Error(SD_STATUS_UNSUPPORTED, "frame-indexed guides require MiniMax-H3"); if (!h3 && !bound_videos(request.options, "ref_videos").empty()) throw dgl::Error(SD_STATUS_UNSUPPORTED, "reference videos require MiniMax-H3"); if (!h3 && !s2v && !bound_audios(request.options, "ref_audios").empty()) diff --git a/src/api/options.cpp b/src/api/options.cpp index 329d2ef6e4..4f1970a25e 100644 --- a/src/api/options.cpp +++ b/src/api/options.cpp @@ -369,10 +369,6 @@ static void add_generation_specs(std::vector& specs) { vid.number("moe_boundary", &sd::VideoConfig::moe_boundary, 0, 1); vid.integer("high_noise_sample.steps", &sd::VideoConfig::high_noise_steps, -1, INT32_MAX); vid.array("ref_audios", &sd::VideoConfig::ref_audios, &sd::VideoConfig::ref_audios_count); - vid.array("guide_videos", &sd::VideoConfig::guide_videos, &sd::VideoConfig::guide_videos_count); - vid.array("guide_video_indices", &sd::VideoConfig::guide_video_indices, &sd::VideoConfig::guide_video_indices_count); - vid.array("guide_audios", &sd::VideoConfig::guide_audios, &sd::VideoConfig::guide_audios_count); - vid.array("guide_audio_indices", &sd::VideoConfig::guide_audio_indices, &sd::VideoConfig::guide_audio_indices_count); vid.array("ref_videos", &sd::VideoConfig::ref_videos, &sd::VideoConfig::ref_videos_count); vid.number("vace_strength", &sd::VideoConfig::vace_strength, 0, std::numeric_limits::max()); vid.integer("video_frames", &sd::VideoConfig::video_frames, 1, INT32_MAX); diff --git a/src/api/templates/video_h3.dgl b/src/api/templates/video_h3.dgl index ba4c42bf7f..db9a360c03 100644 --- a/src/api/templates/video_h3.dgl +++ b/src/api/templates/video_h3.dgl @@ -6,11 +6,6 @@ var { {% include "video_helpers" %} -fn h3_guide_pixels(clip, width, height, start, size) { - pixels = tensor::crop(image::to_f32(clip, channels = 3), axes = [0, 1], start = start, size = size) - return tensor::interpolate(pixels, size = [width, height], axes = [0, 1], mode = "lanczos") -} - fn main({{inputs}}) { base_model = load_dit(model_path{{model_options}}) base_text = load_text_encoder(text_path{{text_options}}) diff --git a/src/api/templates/video_reference.dgl b/src/api/templates/video_reference.dgl index 08668307ba..7e295b2b8c 100644 --- a/src/api/templates/video_reference.dgl +++ b/src/api/templates/video_reference.dgl @@ -1,5 +1,5 @@ {% if encode_audio %} - {{name}} = audio_vae_encode(audio_vae, {{name}}_samples, sample_rate = {{sample_rate}}, max_latents = {{limit}}) + {{name}} = audio_vae_encode(audio_vae, {{name}}_samples, sample_rate = {{sample_rate}}) {% else %} {% if resize_video %} {{source}}_pixels = image::to_f32(tensor::interpolate(tensor::index_select({{source}}, axis = 3, indices = {{indices}}), size = [{{width}}, {{height}}], axes = [1, 2]), channels = 3) diff --git a/src/config.h b/src/config.h index 8434927aea..c93e84ad19 100644 --- a/src/config.h +++ b/src/config.h @@ -180,14 +180,6 @@ namespace sd { sd::Image end_image{}; sd::Image* ref_images{}; int ref_images_count{}; - sd::ReferenceVideo* guide_videos{}; - int guide_videos_count{}; - int* guide_video_indices{}; - int guide_video_indices_count{}; - sd::Audio* guide_audios{}; - int guide_audios_count{}; - int* guide_audio_indices{}; - int guide_audio_indices_count{}; sd::ReferenceVideo* ref_videos{}; int ref_videos_count{}; sd::Audio* ref_audios{}; diff --git a/src/dgl/bindings/latents.cpp b/src/dgl/bindings/latents.cpp index 65e3a36c3b..12b3572fc7 100644 --- a/src/dgl/bindings/latents.cpp +++ b/src/dgl/bindings/latents.cpp @@ -79,14 +79,11 @@ namespace sd::dgl { auto& engine = *object(args, "vae"); Model::ExecutionScope scope(engine); scope.require_ready(); - const auto limit = get_int(args, "max_latents"); - auto waveform = sd::dgl::ops::prepare_minimax_h3_reference_waveform(audio, engine.audio_vae_model->input_sample_rate(), limit); + auto waveform = sd::dgl::ops::prepare_minimax_h3_reference_waveform(audio, engine.audio_vae_model->input_sample_rate()); auto result = engine.audio_vae_model->encode(engine.n_threads, waveform); if (result.empty()) { throw std::runtime_error("audio VAE encoding failed"); } - if (limit > 0 && result.shape()[0] > limit) - result = sd::ops::slice(result, 0, 0, limit); return tensor_value(std::move(result)); } diff --git a/src/dgl/bindings/registration.cpp b/src/dgl/bindings/registration.cpp index 2c42a550b4..6624e9907d 100644 --- a/src/dgl/bindings/registration.cpp +++ b/src/dgl/bindings/registration.cpp @@ -665,7 +665,7 @@ namespace sd::dgl { {required("upscaler", Kind::LatentUpscaler), required("latent", Kind::Tensor), std::move(width), std::move(height)}, {Kind::Tensor}, upscale_latent); registry["audio_vae_encode"] = make_operation( - {required("vae", Kind::AudioVAE), required("samples", Kind::Tensor), integer("sample_rate", 1000, 384000), integer("max_latents", 0, INT32_MAX, 0)}, {Kind::Tensor}, audio_vae_encode); + {required("vae", Kind::AudioVAE), required("samples", Kind::Tensor), integer("sample_rate", 1000, 384000)}, {Kind::Tensor}, audio_vae_encode); registry["audio_vae_decode"] = make_operation( {required("vae", Kind::AudioVAE), required("latent", Kind::Tensor)}, audio_signature(), audio_vae_decode); } diff --git a/src/dgl/ops/media.cpp b/src/dgl/ops/media.cpp index 49d28d89c5..2226d3a253 100644 --- a/src/dgl/ops/media.cpp +++ b/src/dgl/ops/media.cpp @@ -128,16 +128,13 @@ namespace sd::dgl::ops { } sd::Tensor prepare_minimax_h3_reference_waveform(const sd::Audio& audio, - int target_sample_rate, int64_t max_latents) { + int target_sample_rate) { if (audio.data == nullptr || audio.sample_count == 0 || audio.channels == 0 || audio.sample_rate == 0) { return {}; } uint64_t output_samples = static_cast(std::llround( static_cast(audio.sample_count) * target_sample_rate / audio.sample_rate)); output_samples = std::max(1, output_samples); - // The encoder receptive field for latent i ends at sample 800*i + 9924. - if (max_latents > 0) - output_samples = std::min(output_samples, 800 * (max_latents - 1) + 9925); uint64_t padded_samples = (output_samples + 799) / 800 * 800; // Keep stereo streams planar for the mono-per-stream audio encoder: // [samples, 1, stereo, batch]. This avoids flattening interleaved L/R diff --git a/src/dgl/ops/media.h b/src/dgl/ops/media.h index 1d9516134c..5206bcacb8 100644 --- a/src/dgl/ops/media.h +++ b/src/dgl/ops/media.h @@ -23,7 +23,7 @@ namespace sd::dgl::ops { int temporal_scale, bool causal_temporal_positioning); sd::Tensor prepare_minimax_h3_reference_waveform(const sd::Audio& audio, - int target_sample_rate, int64_t max_latents); + int target_sample_rate); sd::Tensor build_s2v_audio_window(const sd::Tensor& stacked, int64_t batch_frames); } // namespace sd::dgl::ops From bf8ca817f71d51e4a7dfda520704a1a49278c51d Mon Sep 17 00:00:00 2001 From: leejet Date: Tue, 1 Dec 2026 22:13:02 +0800 Subject: [PATCH 4/4] fix: correct audio guide trimming in the MiniMax-H3 DGL example --- docs/dgl/minimax_h3/minimax-h3-reference-guides.dgl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dgl/minimax_h3/minimax-h3-reference-guides.dgl b/docs/dgl/minimax_h3/minimax-h3-reference-guides.dgl index dcbcdcab2e..0d58d41082 100644 --- a/docs/dgl/minimax_h3/minimax-h3-reference-guides.dgl +++ b/docs/dgl/minimax_h3/minimax-h3-reference-guides.dgl @@ -99,7 +99,7 @@ fn main() { # The model places 5 audio latents per 3 output frames. Keep the part that fits after the anchor frame. guide_audio_full = audio_vae_encode(audio_vae, guide_sound.samples, sample_rate = guide_sound.sample_rate) - guide_audio = guide_audio_full[:audio_shape[0] - math::round(guide_audio_frame * 5 / 3)] + guide_audio = guide_audio_full[:audio_shape[0] - math::ceil_div(guide_audio_frame * 5, 3)] reference_original = image::to_f32(reference, channels = 3) reference_area = math::min(width * height, tensor::shape(reference_original)[0] * tensor::shape(reference_original)[1])