Commit 7c35fe4 for stable-diffusion.cpp

commit 7c35fe40bc3a378777836b3b9533555c7ec6a25d
Author: Shogo Iwano <shiwano@gmail.com>
Date:   Tue Dec 1 23:32:01 2026 +0900

    feat: support frame-indexed visual and audio guides for MiniMax-H3 (#2463)

diff --git a/docs/dgl-builtins.md b/docs/dgl-builtins.md
index 0ce1a7d..b344b0e 100644
--- a/docs/dgl-builtins.md
+++ b/docs/dgl-builtins.md
@@ -26,7 +26,7 @@ Optional parameters are marked with `?`. Default values follow `=`. See [DGL syn
 | `detections::to_regions` | `image: tensor`, `detections: dict` | `dict`<br>`boxes: tensor`<br>`height: int`<br>`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<any>`, `image_bindings?: dict`, `raw?: bool = false` | `dict`<br>`concat: tensor`<br>`crossattn: tensor`<br>`extra_crossattn: list<tensor>`<br>`image_embed_indices: list<tensor>`<br>`image_embeds: list<tensor>`<br>`input_ids: tensor`<br>`position_ids: tensor`<br>`ref_audios: list<tensor>`<br>`ref_images: list<tensor>`<br>`reference_blocks: list<dict>`<br>`reference_blocks.audio: int`<br>`reference_blocks.kind: string`<br>`reference_blocks.video: int`<br>`t5_ids: tensor`<br>`t5_weights: tensor`<br>`token_types: tensor`<br>`vector: tensor`<br>`vinput_mask: tensor` |
+| `encode_prompt` | `encoder: text_encoder`, `text: string`, `width?: int = 512`, `height?: int = 512`, `clip_skip?: int = -1`, `system?: string`, `media?: list<any>`, `image_bindings?: dict`, `raw?: bool = false` | `dict`<br>`concat: tensor`<br>`crossattn: tensor`<br>`extra_crossattn: list<tensor>`<br>`image_embed_indices: list<tensor>`<br>`image_embeds: list<tensor>`<br>`input_ids: tensor`<br>`position_ids: tensor`<br>`ref_audios: list<tensor>`<br>`ref_images: list<tensor>`<br>`reference_blocks: list<dict>`<br>`reference_blocks.audio: int`<br>`reference_blocks.frame_index: int`<br>`reference_blocks.kind: string`<br>`reference_blocks.video: int`<br>`t5_ids: tensor`<br>`t5_weights: tensor`<br>`token_types: tensor`<br>`vector: tensor`<br>`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`<br>`data: bytes`<br>`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`<br>`crossattn: tensor` |
 | `photomaker::encode_images` | `photomaker: photomaker`, `images: list<tensor>`, `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`<br>`condition: dict`<br>`condition.concat: tensor`<br>`condition.crossattn: tensor`<br>`condition.extra_crossattn: list<tensor>`<br>`condition.image_embed_indices: list<tensor>`<br>`condition.image_embeds: list<tensor>`<br>`condition.input_ids: tensor`<br>`condition.position_ids: tensor`<br>`condition.ref_audios: list<tensor>`<br>`condition.ref_images: list<tensor>`<br>`condition.reference_blocks: list<dict>`<br>`condition.reference_blocks.audio: int`<br>`condition.reference_blocks.kind: string`<br>`condition.reference_blocks.video: int`<br>`condition.t5_ids: tensor`<br>`condition.t5_weights: tensor`<br>`condition.token_types: tensor`<br>`condition.vector: tensor`<br>`condition.vinput_mask: tensor`<br>`mask: tensor`<br>`plain: dict`<br>`plain.concat: tensor`<br>`plain.crossattn: tensor`<br>`plain.extra_crossattn: list<tensor>`<br>`plain.image_embed_indices: list<tensor>`<br>`plain.image_embeds: list<tensor>`<br>`plain.input_ids: tensor`<br>`plain.position_ids: tensor`<br>`plain.ref_audios: list<tensor>`<br>`plain.ref_images: list<tensor>`<br>`plain.reference_blocks: list<dict>`<br>`plain.reference_blocks.audio: int`<br>`plain.reference_blocks.kind: string`<br>`plain.reference_blocks.video: int`<br>`plain.t5_ids: tensor`<br>`plain.t5_weights: tensor`<br>`plain.token_types: tensor`<br>`plain.vector: tensor`<br>`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`<br>`condition: dict`<br>`condition.concat: tensor`<br>`condition.crossattn: tensor`<br>`condition.extra_crossattn: list<tensor>`<br>`condition.image_embed_indices: list<tensor>`<br>`condition.image_embeds: list<tensor>`<br>`condition.input_ids: tensor`<br>`condition.position_ids: tensor`<br>`condition.ref_audios: list<tensor>`<br>`condition.ref_images: list<tensor>`<br>`condition.reference_blocks: list<dict>`<br>`condition.reference_blocks.audio: int`<br>`condition.reference_blocks.frame_index: int`<br>`condition.reference_blocks.kind: string`<br>`condition.reference_blocks.video: int`<br>`condition.t5_ids: tensor`<br>`condition.t5_weights: tensor`<br>`condition.token_types: tensor`<br>`condition.vector: tensor`<br>`condition.vinput_mask: tensor`<br>`mask: tensor`<br>`plain: dict`<br>`plain.concat: tensor`<br>`plain.crossattn: tensor`<br>`plain.extra_crossattn: list<tensor>`<br>`plain.image_embed_indices: list<tensor>`<br>`plain.image_embeds: list<tensor>`<br>`plain.input_ids: tensor`<br>`plain.position_ids: tensor`<br>`plain.ref_audios: list<tensor>`<br>`plain.ref_images: list<tensor>`<br>`plain.reference_blocks: list<dict>`<br>`plain.reference_blocks.audio: int`<br>`plain.reference_blocks.frame_index: int`<br>`plain.reference_blocks.kind: string`<br>`plain.reference_blocks.video: int`<br>`plain.t5_ids: tensor`<br>`plain.t5_weights: tensor`<br>`plain.token_types: tensor`<br>`plain.vector: tensor`<br>`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<tensor>`, `ref_audios?: list<tensor>`, `reference_blocks?: list<dict>`, `keyframe_indices?: list<int>`, `ref_index_mode?: string = "fixed"`, `force_ref_timestep_zero?: bool = false`, `ref_rope_anchor?: string = "default"`, `guidance?: number = 3.5`, `skip_layers?: list<int>`, `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 64a5558..a985684 100644
--- a/docs/dgl.md
+++ b/docs/dgl.md
@@ -1562,6 +1562,13 @@ 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. 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 a175ff8..31cd367 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) · [pi-H3 four-step text to audio/video](minimax_h3/pi-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) · [Audio/video continuation](minimax_h3/minimax-h3-av-continuation.dgl) |
+| [MiniMax-H3](../models/minimax_h3.md) | [Text to audio/video](minimax_h3/minimax-h3-text-to-av.dgl) · [pi-H3 four-step text to audio/video](minimax_h3/pi-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) · [Audio/video continuation](minimax_h3/minimax-h3-av-continuation.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 0000000..0d58d41
--- /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 <Picture 1> 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::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])
+    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/models/minimax_h3.md b/docs/models/minimax_h3.md
index 2c410ec..137bc06 100644
--- a/docs/models/minimax_h3.md
+++ b/docs/models/minimax_h3.md
@@ -132,6 +132,7 @@ Select optional components when required by your checkpoint or task.
 | [pi-H3 text to audio/video](../dgl/minimax_h3/pi-h3-text-to-av.dgl) | Generate video and its soundtrack in four Euler steps with the native H3 VAEs. |
 | [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. |
 | [Audio/video continuation](../dgl/minimax_h3/minimax-h3-av-continuation.dgl) | Generate and join two clips with shared audio and video context. |
@@ -359,7 +360,9 @@ 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.
+`--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
diff --git a/src/dgl/bindings/condition.cpp b/src/dgl/bindings/condition.cpp
index 961e3c2..b484f6f 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/model/diffusion/minimax_h3.hpp b/src/model/diffusion/minimax_h3.hpp
index 2f5cb4f..e4a72fc 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<float>(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<float>(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<float>* ref_video = nullptr;
-                const sd::Tensor<float>* ref_audio = nullptr;
-                if (block.video_index >= 0) {
-                    GGML_ASSERT(block.video_index < static_cast<int32_t>(condition_videos.size()));
-                    ref_video = &condition_videos[static_cast<size_t>(block.video_index)];
-                }
-                if (block.audio_index >= 0) {
-                    GGML_ASSERT(block.audio_index < static_cast<int32_t>(condition_audios.size()));
-                    ref_audio = &condition_audios[static_cast<size_t>(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<float>(ref_audio->shape()[0]));
+        }
+        float target_start = cursor;
+        for (const auto& block : reference_blocks) {
+            GGML_ASSERT(block.video_index < static_cast<int32_t>(condition_videos.size()));
+            GGML_ASSERT(block.audio_index < static_cast<int32_t>(condition_audios.size()));
+            if (block.frame_index < 0) {
+                target_start = reference_end(block, target_start);
+            }
+        }
+        for (const auto& block : reference_blocks) {
+            const sd::Tensor<float>* ref_video = nullptr;
+            const sd::Tensor<float>* ref_audio = nullptr;
+            if (block.video_index >= 0) {
+                ref_video = &condition_videos[static_cast<size_t>(block.video_index)];
+            }
+            if (block.audio_index >= 0) {
+                ref_audio = &condition_audios[static_cast<size_t>(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<int64_t>(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<int64_t>(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/minimax_h3_reference.hpp b/src/model/diffusion/minimax_h3_reference.hpp
index a54f7aa..a285a45 100644
--- a/src/model/diffusion/minimax_h3_reference.hpp
+++ b/src/model/diffusion/minimax_h3_reference.hpp
@@ -14,6 +14,7 @@ struct MiniMaxH3ReferenceBlock {
     MiniMaxH3ReferenceKind kind = MiniMaxH3ReferenceKind::IMAGE;
     int32_t video_index         = -1;
     int32_t audio_index         = -1;
+    int32_t frame_index         = -1;
 };

 #endif  // __SD_MODEL_DIFFUSION_MINIMAX_H3_REFERENCE_HPP__