Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Support guide clips with character reference images

Bowen Xuee6af26da0b33
diff --git a/freevideo_engine/capabilities.py b/freevideo_engine/capabilities.py
index e732328..a2c027d 100644
--- a/freevideo_engine/capabilities.py
+++ b/freevideo_engine/capabilities.py
@@ -55,7 +55,7 @@ def normalize_references(task, references=None):
kind = row.get('kind')
allowed = {'kind', 'seconds'} if kind == 'audio' else {'kind', 'width', 'height'}
if kind == 'video':
- allowed |= {'seconds', 'audio_seconds'}
+ allowed |= {'seconds', 'audio_seconds', 'guide'}
if kind not in ('image', 'video', 'audio') or set(row) - allowed:
raise ValueError('Unsupported reference metadata.')
width = height = seconds = audio = None
@@ -71,6 +71,12 @@ def normalize_references(task, references=None):
raise ValueError('Reference audio is empty after normalization.')
if kind == 'video' and math.ceil(min(seconds, 15.) * 24) < 22:
raise ValueError('The reference video needs at least 22 normalized frames.')
+ if 'guide' in row:
+ # A guide clip is packed as a silent video reference (same rows and
+ # patches; only the time coordinates differ), so it keeps the plain
+ # video tuple and history matching counts it as reference video tokens.
+ if type(row['guide']) is not bool or 'audio_seconds' in row:
+ raise ValueError('A guide clip is a silent video reference.')
if 'audio_seconds' in row:
audio = row['audio_seconds']
if not positive(audio):
diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.py
index 8d4f8a7..0ed3b95 100644
--- a/freevideo_engine/comfy_assets.py
+++ b/freevideo_engine/comfy_assets.py
@@ -75,7 +75,7 @@ def resolve_assets(serialized, input_directory):
root = Path(input_directory).resolve()
result = {}
for row in rows:
- if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound'}:
+ if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound', 'guide'}:
raise ValueError('Invalid media item')
# The character an @ mention added the row for; a continued part keeps one picture per character.
if 'cast' in row and (set(row['cast'] if isinstance(row['cast'], dict) else ('?',)) != {'id'}
@@ -117,6 +117,11 @@ def resolve_assets(serialized, input_directory):
validate_sound(dict(row, kind=kind))
if not row['sound']:
reference['sound'] = False
+ if 'guide' in row:
+ from .media_request import validate_guide
+ validate_guide(dict(row, kind=kind))
+ if row['guide']:
+ reference['guide'] = True
result.setdefault('references', []).append(reference)
else:
raise ValueError('Media role must be first, last or reference')
diff --git a/freevideo_engine/guide_layout.py b/freevideo_engine/guide_layout.py
new file mode 100644
index 0000000..d7b2be5
--- /dev/null
+++ b/freevideo_engine/guide_layout.py
@@ -0,0 +1,46 @@
+"""Guide layout: a guide clip shares the generated clip's time origin.
+
+The native H3 AddGuide node packs [text | guide rows | references | target] with the guide rows
+at time origin cursor + 5/3 * frame_index, the same origin as the target rows. The Ref2VA layout
+builder gives every video reference its own time slot instead. This wrapper builds the ordinary
+Ref2VA layout with the guides as the LAST references, then rewinds the target rows' time
+coordinate by the slot the first guide occupied so that guides and target share one origin.
+Guides after the first are moved onto the same origin, and a guide with a frame index is offset
+by 5/3 per frame (the native frame-to-time rescale).
+
+Requests without a guide return the builder's layout object unchanged.
+"""
+
+FRAME_RESCALE = 5. / 3.
+
+
+def build(builder, text_token_tags, references, condition_latents, audio_conditions, *args):
+ layout = builder(text_token_tags, references, condition_latents, audio_conditions, *args)
+ guides = [i for i, ref in enumerate(references) if getattr(ref, 'guide', False)]
+ if not guides:
+ return layout
+ count = len(guides)
+ if guides != list(range(len(references) - count, len(references))):
+ raise ValueError('Guide clips must come after all other references')
+ positions, tags, video_ids, audio_ids, text_ids, rows, audio_rows = layout
+ patch_h, patch_w = args[-4][1], args[-4][2]
+ # Guides are silent, so their latents are the last `count` entries of condition_latents.
+ sizes = []
+ for latent in condition_latents[-count:]:
+ sizes.append(latent.shape[2] * (latent.shape[3] // patch_h) * (latent.shape[4] // patch_w))
+ end = rows
+ spans = []
+ for n in reversed(sizes):
+ spans.append(video_ids[:end][-n:])
+ end -= n
+ spans.reverse()
+ audio_start = int(audio_ids[audio_rows:].min())
+ first = float(positions[int(spans[0][0]), 0])
+ shift = float(positions[int(video_ids[rows]), 0]) - first
+ positions[audio_start:, 0] -= shift
+ for span, reference in zip(spans, references[-count:]):
+ offset = first - float(positions[int(span[0]), 0])
+ index = getattr(reference, 'guide_index', 0)
+ if offset or index:
+ positions[span, 0] += offset + FRAME_RESCALE * index
+ return positions, tags, video_ids, audio_ids, text_ids, rows, audio_rows
diff --git a/freevideo_engine/media_conditioning.py b/freevideo_engine/media_conditioning.py
index 09e60cb..2a067f2 100644
--- a/freevideo_engine/media_conditioning.py
+++ b/freevideo_engine/media_conditioning.py
@@ -98,9 +98,22 @@ def _describe(value, width, height, frames):
raise ValueError('Ref2VA needs reference latents and no keyframe anchors')
# Reuse the shared prompt/token validation without pretending references are anchors.
to_cache([[prompt[None], {'minimax_token_tags': tags}]], task='ref2va')
- video_rows = audio_rows = 0
+ video_rows = audio_rows = seen_rows = 0
+ guides = 0
for ref in refs:
kind = ref.get('kind')
+ if ref.get('guide'):
+ # A guide is an ordinary silent video latent whose rows only differ in
+ # time coordinates (guide_layout), so the shape checks below apply
+ # unchanged. It must come after the other references and has no audio.
+ if kind not in ('image', 'video') or ref.get('audio_latent') is not None or 'early_steps' in ref:
+ raise ValueError('A guide must be a silent video or still with no early_steps')
+ guides += 1
+ index = ref.get('guide_index', 0)
+ if type(index) is not int or not 0 <= index < frames:
+ raise ValueError('Guide frame index is outside the clip')
+ elif guides:
+ raise ValueError('Guide references must come after all other references')
if 'early_steps' in ref:
from .media_request import validate_early_steps
validate_early_steps(ref)
@@ -111,12 +124,16 @@ def _describe(value, width, height, frames):
if latent.shape[2] < 1 or any(n < 2 or n % 2 for n in latent.shape[-2:]):
raise ValueError('Reference latent dimensions must fit H3 patches')
video_rows += math.prod(latent.shape[2:]) // 4
+ if not ref.get('guide'):
+ seen_rows += math.prod(latent.shape[2:]) // 4
if kind == 'audio' or ref.get('audio_latent') is not None:
audio = _tensor(ref.get('audio_latent'), (None, 32), 'reference audio rows')
if audio.shape[0] % 2:
raise ValueError('Reference audio must contain both channels')
audio_rows += audio.shape[0]
- if video_rows and not bool((tags == 0).any()):
+ # Guide rows are never shown to the vision-language encoder, so only the
+ # other visual references need jointly encoded vision tokens.
+ if seen_rows and not bool((tags == 0).any()):
raise ValueError('Visual references need jointly encoded vision tokens')
task = 'ref2va_av' if video_rows and audio_rows else 'ref2va_audio' if audio_rows else 'ref2va'
value['task'] = task
@@ -134,11 +151,19 @@ def from_comfy(conditioning, width, height, frames):
if unknown:
raise ValueError('Unsupported conditioning modifiers: ' + ', '.join(sorted(unknown)))
keyframes, refs = extra.get('minimax_keyframes', []), extra.get('minimax_refs', [])
- if keyframes and refs:
- raise ValueError('Combined keyframe/reference conditioning is not an official VDN layout')
anchors = []
+ guides = []
for item in keyframes:
index = item.get('resolved_frame_index')
+ if refs:
+ # Keyframes next to references are packed as guides that share the clip's
+ # time origin (same as the native AddGuide node), so any in-clip index
+ # is a valid position; the latent shape guard in describe() still applies.
+ if type(index) is not int or not 0 <= index < frames:
+ raise ValueError('Guide frame index is outside the clip')
+ guides.append(dict(kind='video', guide=True, guide_index=index,
+ latent=_tensor(item.get('latent'), (1, 24, None, None, None), 'guide video')))
+ continue
if index not in (0, frames - 1):
raise ValueError('Only first and last keyframe anchors are supported')
anchors.append('first' if index == 0 else 'last')
@@ -160,4 +185,5 @@ def from_comfy(conditioning, width, height, frames):
audio = _tensor(row.get('audio_latent'), (1, 32, 2, None), 'native reference audio')
ref['audio_latent'] = audio[0].permute(1, 2, 0).reshape(-1, 32).contiguous()
value['references'].append(ref)
+ value['references'].extend(guides)
return value, describe(value, width, height, frames)
diff --git a/freevideo_engine/media_encoding.py b/freevideo_engine/media_encoding.py
index 4544a68..cacccd8 100644
--- a/freevideo_engine/media_encoding.py
+++ b/freevideo_engine/media_encoding.py
@@ -135,6 +135,8 @@ def prepare(media, canvas, directory):
ref = {'kind': kind}
if 'early_steps' in row:
ref['early_steps'] = row['early_steps']
+ if row.get('guide'):
+ ref['guide'] = True
numbers[kind] += 1
longer, length, used = False, None, limit / 24.
target = directory / ('reference-%02d.npy' % index)
@@ -183,7 +185,7 @@ def prepare(media, canvas, directory):
ref.update(pixels=str(target), frames=count, normalized_fps=24)
used = count / 24.
# The clip's own sound is a reference too, unless the request turned it off.
- soundtrack, longer_audio, _ = (None, False, None) if row.get('sound') is False else \
+ soundtrack, longer_audio, _ = (None, False, None) if row.get('sound') is False or row.get('guide') else \
_audio(path, directory / ('reference-%02d-audio.npy' % index), limit / 24.)
longer = longer or longer_audio
if soundtrack:
@@ -191,7 +193,10 @@ def prepare(media, canvas, directory):
ref_items.append({'type': 'audio'})
selected = list(range(0, count, 12))
sampled = torch.from_numpy(np.array(pixels[selected])).float().div_(255)
- ref_items.append({'type': 'video', 'data': sampled, 'timestamps': [i / 2. for i in range(len(selected))]})
+ if not row.get('guide'):
+ # A guide only supplies motion latents; it is not described to the
+ # vision-language encoder, like the native AddGuide node.
+ ref_items.append({'type': 'video', 'data': sampled, 'timestamps': [i / 2. for i in range(len(selected))]})
del pixels
else:
ref['audio'], longer, length = _audio(path, target, limit / 24.)
@@ -212,7 +217,7 @@ def reference_options(normalized, options, step):
"""Filter whole references, including a video's optional audio presentation."""
items, offset = [], 0
for row in normalized:
- count = 1 + int(row['kind'] == 'video' and bool(row.get('audio')))
+ count = 0 if row.get('guide') else 1 + int(row['kind'] == 'video' and bool(row.get('audio')))
if 'early_steps' not in row or step < row['early_steps']:
items.extend(options['minimax_ref_items'][offset:offset + count])
offset += count
@@ -289,7 +294,7 @@ def encode_latents(normalized, value, base, canvas, *, resident=None, device='cu
if torch.device(device).type not in ('cuda', 'mps'):
raise ValueError('Media encoding requires a CUDA or MPS device')
empty_cache = torch.mps.empty_cache if torch.device(device).type == 'mps' else torch.cuda.empty_cache
- refs = [{key: row[key] for key in ('kind', 'early_steps') if key in row} for row in normalized]
+ refs = [{key: row[key] for key in ('kind', 'early_steps', 'guide') if key in row} for row in normalized]
keys, cache, hits = {}, None, set()
if cache_root and any(row.get('pixels') for row in normalized):
# The same picture or clip with another prompt reuses its latent and may skip loading the encoder.
diff --git a/freevideo_engine/media_request.py b/freevideo_engine/media_request.py
index be8d0ec..f28aa6d 100644
--- a/freevideo_engine/media_request.py
+++ b/freevideo_engine/media_request.py
@@ -55,7 +55,7 @@ def read(path):
raise ValueError('Invalid ' + field + ' entry')
if field != 'references' and 'early_steps' in entry:
raise ValueError('early_steps is only allowed on video references')
- allowed = {'path', 'kind', 'early_steps', 'sound'} if field == 'references' else {'path', 'strength', 'alpha'}
+ allowed = {'path', 'kind', 'early_steps', 'sound', 'guide'} if field == 'references' else {'path', 'strength', 'alpha'}
if set(entry) - allowed:
raise ValueError('Unknown ' + field + ' fields')
row = file_info(entry.get('path'))
@@ -70,6 +70,12 @@ def read(path):
validate_sound(entry)
if not entry['sound']:
row['sound'] = False
+ if 'guide' in entry:
+ validate_guide(entry)
+ # A false marker is not stored, so requests without a guide
+ # keep exactly the same rows and cache key as before.
+ if entry['guide']:
+ row['guide'] = True
else:
if Path(row['path']).suffix.lower() != '.safetensors':
raise ValueError('LoRA requires safetensors; pickle adapters are not loaded')
@@ -81,7 +87,13 @@ def read(path):
row[name] = number
result[field].append(row)
if result['references'] and any(result.get(k) for k in ('first', 'last')):
- raise ValueError('Reference and keyframe layouts cannot be mixed; use separate requests')
+ raise ValueError('Reference and first/last keyframe layouts cannot be mixed in one request; '
+ 'mark the clip that carries the motion with "guide": true instead')
+ guides = [row for row in result['references'] if row.get('guide')]
+ if len(guides) > 1:
+ raise ValueError('At most one guide clip per request')
+ # The packed layout needs the guide after the other references.
+ result['references'].sort(key=lambda row: bool(row.get('guide')))
if value.get('conditioning_info') is not None:
info = value['conditioning_info']
if not isinstance(info, dict) or info.get('task') not in TASKS:
@@ -114,6 +126,20 @@ def validate_sound(row):
raise ValueError('Video reference sound must be true or false')
+def validate_guide(row):
+ """A guide is a video reference that shares the generated clip's time origin.
+
+ It is encoded like a silent video reference, so it cannot carry its own
+ audio or a delayed start.
+ """
+ if row.get('kind') != 'video':
+ raise ValueError('guide is only allowed on video references')
+ if type(row['guide']) is not bool:
+ raise ValueError('Video reference guide must be true or false')
+ if row['guide'] and 'early_steps' in row:
+ raise ValueError('A guide clip cannot use early_steps')
+
+
def reference_stages(media):
"""Active references at each boundary; zero-step inputs never reach an encoder."""
refs = media.get('references', [])
diff --git a/freevideo_engine/reference_sampler.py b/freevideo_engine/reference_sampler.py
index 6a011f7..30c2fee 100644
--- a/freevideo_engine/reference_sampler.py
+++ b/freevideo_engine/reference_sampler.py
@@ -20,7 +20,7 @@ from src.models.sequence_layout import layout_from_indices
from src.inference.render import KEYFRAME_NOISE_AUG
from src.models.hybrid_transform import iter_hybrids, set_layout
-from . import step_grid
+from . import guide_layout, step_grid
# Rebound per Engine request by sampler_for_canvas.
LATENT_H, LATENT_W = 48, 84
@@ -45,14 +45,15 @@ def generate_latents(transformer, prompt_embeds, text_token_tags, num_frames, nu
raise ValueError('Ref2VA requires references')
condition_latents = [row['latent'].to(device) for row in refs if row['kind'] in ('image', 'video')]
audio_conditions = [row['audio_latent'].to(device) for row in refs if row.get('audio_latent') is not None]
- references = [SimpleNamespace(kind=row['kind'], has_audio=row.get('audio_latent') is not None) for row in refs]
+ references = [SimpleNamespace(kind=row['kind'], has_audio=row.get('audio_latent') is not None,
+ guide=bool(row.get('guide')), guide_index=row.get('guide_index', 0)) for row in refs]
patch = tuple(transformer.config.patch_size) # (1, 2, 2)
channels = transformer.config.in_channels # 24
frame_h, frame_w = LATENT_H // patch[1], LATENT_W // patch[2]
def make_layout(text_token_tags, references, condition_latents, audio_conditions):
position_ids, token_tags, video_indices, audio_indices, text_indices, num_condition_rows, num_audio_condition_rows = (
- MiniMaxH3Ref2VAPrepareLayoutStep.build_ref2va_packed_sequence(
+ guide_layout.build(MiniMaxH3Ref2VAPrepareLayoutStep.build_ref2va_packed_sequence,
text_token_tags, references, condition_latents, audio_conditions, num_latent_frames, LATENT_H, LATENT_W, num_audio_latents,
patch, AUDIO_CHANNELS, AUDIO_TAG, VIDEO_TAG,
)
@@ -134,7 +135,8 @@ def generate_latents(transformer, prompt_embeds, text_token_tags, num_frames, nu
generated_audio = audio_rows[num_audio_condition_rows:]
keep_video = [i for i, row in enumerate(visual_refs) if row.get('early_steps', step + 1) > step]
keep_audio = [i for i, row in enumerate(audio_refs) if row.get('early_steps', step + 1) > step]
- references = [SimpleNamespace(kind=row['kind'], has_audio=row.get('audio_latent') is not None)
+ references = [SimpleNamespace(kind=row['kind'], has_audio=row.get('audio_latent') is not None,
+ guide=bool(row.get('guide')), guide_index=row.get('guide_index', 0))
for row in value.get('references', [])]
prompt_embeds = value['prompt_embeds'].to(device=device, dtype=prompt_embeds.dtype)
previous_audio_condition_rows = num_audio_condition_rows
diff --git a/freevideo_engine/refine.py b/freevideo_engine/refine.py
index ee9373d..f535d3f 100644
--- a/freevideo_engine/refine.py
+++ b/freevideo_engine/refine.py
@@ -61,8 +61,10 @@ def generate_latents(transformer, prompt_embeds, text_token_tags, num_frames, nu
refs = conditions
condition_latents = [row['latent'].to(device) for row in refs if row['kind'] in ('image', 'video')]
audio_conditions = [row['audio_latent'].to(device) for row in refs if row.get('audio_latent') is not None]
- references = [SimpleNamespace(kind=row['kind'], has_audio=row.get('audio_latent') is not None) for row in refs]
- layout = MiniMaxH3Ref2VAPrepareLayoutStep.build_ref2va_packed_sequence(
+ references = [SimpleNamespace(kind=row['kind'], has_audio=row.get('audio_latent') is not None,
+ guide=bool(row.get('guide')), guide_index=row.get('guide_index', 0)) for row in refs]
+ from . import guide_layout
+ layout = guide_layout.build(MiniMaxH3Ref2VAPrepareLayoutStep.build_ref2va_packed_sequence,
text_token_tags, references, condition_latents, audio_conditions,
latent_frames, LATENT_H, LATENT_W, audio_frames, patch, AUDIO_CHANNELS, AUDIO_TAG, VIDEO_TAG)
else:
diff --git a/freevideo_engine/sampling_assets.py b/freevideo_engine/sampling_assets.py
index 0f96f9a..4911f5a 100644
--- a/freevideo_engine/sampling_assets.py
+++ b/freevideo_engine/sampling_assets.py
@@ -187,7 +187,7 @@ def engine_task(media, base=None):
for ref in media.get('references', []):
visual |= ref['kind'] in ('image', 'video')
audio |= ref['kind'] == 'audio'
- if ref['kind'] == 'video' and not audio and ref.get('sound') is not False:
+ if ref['kind'] == 'video' and not audio and ref.get('sound') is not False and not ref.get('guide'):
path = Path(ref['path'])
if base is not None and not path.is_absolute():
path = Path(base) / path
diff --git a/freevideo_engine/tuning.py b/freevideo_engine/tuning.py
index dc20659..8c6f9a6 100644
--- a/freevideo_engine/tuning.py
+++ b/freevideo_engine/tuning.py
@@ -22,7 +22,7 @@ from .paths import data_root
SCHEMA = 1
COMPUTE_FILES = ('activation_staging.py', 'residual.py', 'adaln.py', 'adaln_assets.py', 'attention.py', 'blocks.py',
- 'keyframes.py', 'media_request.py', 'media_conditioning.py', 'media_encoding.py', 'reference_sampler.py', 'lora_cache.py',
+ 'keyframes.py', 'guide_layout.py', 'media_request.py', 'media_conditioning.py', 'media_encoding.py', 'reference_sampler.py', 'lora_cache.py',
'conditioning.py', 'decode.py', 'decode_prefetch.py', 'resident_models.py', 'decode_stream.py', 'streamed_weights.py', 'encode_worker.py', 'idle_encoder.py', 'media_encoding.py', 'fp8.py', 'fp8_ops.py', 'fp8_gemm.py', 'int8_ops.py',
'encoder_precision.py', 'encoder_lowmem.py',
'kernel_capabilities.py', 'gpu_budget.py', 'worker.py', 'resident_worker.py', 'failure_cleanup.py',