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.

Continuation: optional first-frame reference to reduce drift

Bowen Xue432fa04f840c
diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.py
index 9a9a813..39402c8 100644
--- a/freevideo_engine/agent/guide.py
+++ b/freevideo_engine/agent/guide.py
@@ -65,6 +65,11 @@ GUIDE = {
'Continuing (longer than 15 s, or continue_from) needs two-pass text generation: quality "light" '
'or sampling.two_pass=true, no preview and no media. '
'Multi-block output is cut to the planned duration. POST /plan shows the chain plan.',
+ 'first_frame_reference (default false) reduces drift in a continued video: each continuing part also '
+ 'sees the first frame of the whole video. Set it when one scene with the same people runs over several '
+ 'parts and framing, colour or the person may wander. Leave it off for camera moves, big action or a '
+ 'scene that should change: it holds framing and motion close to the first frame. Continuing parts take '
+ 'somewhat longer with it; a single-part video is unaffected.',
'Keep the described timeline inside the duration. 4-15 s is the tested range; longer is experimental.',
'Width and height are multiples of 32. For a size the user names that is not, use the nearest multiple '
'on each side (1000x560 -> 992x544 or 992x576); a rejected request names them.',
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index cb4ff62..76adf72 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -154,10 +154,14 @@ def generate(*, local=False):
preview={'type': 'boolean', 'default': False},
refine_from=nullable({'oneOf': [JOB, SAVED]}), force_regenerate={'type': 'boolean', 'default': False},
continue_from={'oneOf': [obj({'from_job': JOB}, ('from_job',)), obj({'library': SAVED}, ('library',))]},
+ first_frame_reference={'type': 'boolean', 'default': False, 'description':
+ 'Reduces drift over a continued video: every continuing part also sees the first frame of the whole '
+ 'video. It holds framing and motion close to that frame.'},
takes=number(1, 8, integer=True, default=1), **common()),
allOf=[{'if': {'required': ['refine_from'], 'properties': {'refine_from': {'type': 'string'}}},
'then': {'properties': {k: False for k in ('prompt', 'width', 'height', 'aspect', 'megapixels',
- 'seconds', 'seed', 'quality', 'sampling', 'media', 'loras', 'preview', 'continue_from')}},
+ 'seconds', 'seed', 'quality', 'sampling', 'media', 'loras', 'preview', 'continue_from',
+ 'first_frame_reference')}},
'else': {'required': ['prompt']}},
{'if': {'anyOf': [{'required': [k]} for k in ('aspect', 'megapixels')]},
'then': {'not': {'anyOf': [{'required': [k]} for k in ('width', 'height')]}}},
diff --git a/freevideo_engine/agent/spec.py b/freevideo_engine/agent/spec.py
index 352982f..d2f75c6 100644
--- a/freevideo_engine/agent/spec.py
+++ b/freevideo_engine/agent/spec.py
@@ -188,6 +188,8 @@ def normalize(value):
result['task'] = task(result['media'])
if value.get('continue_from'):
result['continue_from'] = dict(value['continue_from'])
+ if value['first_frame_reference']:
+ result['first_frame_reference'] = True
result['loras'] = [dict(name=row, strength=1.) if isinstance(row, str) else {'strength': 1., **row}
for row in value['loras']]
elif kind == 'assemble':
@@ -225,6 +227,9 @@ def comfy_prompt(spec, node, *, prompt, assets, refine_from=''):
seed=spec['seed'], two_pass=spec['two_pass'], base_steps=spec['base_steps'],
refine_steps=spec['refine_steps'], force_regenerate=spec['force_regenerate'],
preview=spec['preview'], refine_from=refine_from)
+ if spec.get('first_frame_reference'):
+ # Every part of the video carries it; the part that continues nothing ignores it.
+ inputs['first_frame_reference'] = True
graph = {node: {'class_type': 'FreeVideoGenerate', 'inputs': inputs,
'_meta': {'title': 'FreeVideo · ' + (spec.get('label') or 'Agent job')}}}
if assets:
diff --git a/freevideo_engine/cli.py b/freevideo_engine/cli.py
index 732dd5d..8da891a 100644
--- a/freevideo_engine/cli.py
+++ b/freevideo_engine/cli.py
@@ -93,6 +93,12 @@ def main():
generate.add_argument('--task', choices=TASKS, help='Input task; inferred when --media is provided')
generate.add_argument('--media', type=Path, help='Versioned keyframe/reference/LoRA request JSON; local files only')
generate.add_argument('--continue-from', type=Path, help='Continue an existing MP4 using its absolute path')
+ generate.add_argument('--first-frame-reference', action='store_true',
+ help='With --continue-from: also give the model the first frame of the whole film as a '
+ 'reference picture. Reduces drift over many parts; holds framing and motion close to '
+ 'the opening, so leave it off when later parts should move away from it')
+ generate.add_argument('--continue-anchor', type=Path, metavar='IMAGE',
+ help='Experimental: a reference picture of your own for a continuation, with no prompt note')
generate.add_argument('--allocator-limit-gib', type=float,
help='Explicit benchmark cap on PyTorch CUDA allocations; not a whole-device memory limit')
generate.add_argument('--no-history-placement', action='store_true', help='Keep the starting placement for a matched baseline; still record measurements')
@@ -136,10 +142,13 @@ def main():
args = parser.parse_args()
if args.command == 'generate':
from .continuation import validate_frames, validate_route
+ if args.continue_anchor is not None and args.continue_from is None:
+ raise ValueError('--continue-anchor requires --continue-from')
if args.continue_from is not None:
if args.frames is not None:
validate_frames(args.frames)
- validate_route(task=args.task or 't2va', two_pass=args.two_pass, preview=args.preview,
+ validate_route(task=args.task or ('ref2va' if args.continue_anchor else 't2va'),
+ anchor=args.continue_anchor is not None, two_pass=args.two_pass, preview=args.preview,
refine_from=args.refine_from)
if sys.platform == 'darwin' and args.command in ('plan', 'generate', 'encode', 'doctor'):
from .macos_generate import dispatch
diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py
index 53bd31f..cddb66c 100644
--- a/freevideo_engine/comfy_bridge.py
+++ b/freevideo_engine/comfy_bridge.py
@@ -591,7 +591,9 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
release_models=None, export_inputs=None, two_pass=True, encoder_prewarm=None,
force_regenerate=False, base_steps=8, refine_steps=3, comfy_metadata=None,
prompt_rewrite_report=None, preview=False, refine_from=None, report_extra=None,
- continue_from=None, frames=None):
+ continue_from=None, frames=None, first_frame_reference=False):
+ if type(first_frame_reference) is not bool:
+ raise ValueError('First-frame reference must be a boolean')
if continue_from is not None:
from .continuation import validate_route
validate_route(two_pass=two_pass, preview=preview, refine_from=refine_from)
@@ -629,6 +631,14 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
# A continuation takes no media or preview, so its sampled size is known here; the snapshot
# of the previous segment was written for that canvas, not for the requested size.
continuation = prepare(continue_from, sampling_canvas(canvas)[0], directory=root / 'continuations')
+ # The engine decides the same way from the same record: whether the film's first frame is there to use.
+ anchored = False
+ if continue_from is not None and first_frame_reference:
+ from .continuation import chain_first_frame
+ try:
+ anchored = chain_first_frame(continuation, continue_from) is not None
+ except ValueError:
+ pass
environment = engine_environment(root, source, environ)
environment.update(FREEVIDEO_HOME=str(root), PYTHONPATH=str(source), PYTHONUNBUFFERED='1',
PYTHONUTF8='1', PYTHONIOENCODING='utf-8', NO_COLOR='1', FREEVIDEO_UI_EVENTS='1')
@@ -657,6 +667,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
command[position:position + 2] = ['--frames', str(frames)]
if continue_from is not None:
command += ['--continue-from', str(continue_from)]
+ if first_frame_reference:
+ command.append('--first-frame-reference')
from .continuation import persist_snapshot
continuation = persist_snapshot(continuation, run / 'continuation-source.safetensors')
command += ['--continuation-snapshot', continuation['snapshot'],
@@ -734,11 +746,12 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
# The engine samples this canvas; results, cache keys and labels keep the requested size.
sampled, output_size = sampling_canvas(canvas, staged=bool(preview or upscale), media=extra.get('media'),
conditioned=bool(extra.get('conditioning')))
- planned = plan(sampled, two_pass, task_for(extra.get('media', {})), base_steps=base_steps, refine_steps=refine_steps,
- staged=bool(preview or upscale))
+ planned = plan(sampled, two_pass, 'ref2va' if anchored else task_for(extra.get('media', {})),
+ base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale))
if continue_from is not None:
- from .continuation import ADALN_TASK, validate_snapshot, summary
- validate_route(task=task_for(extra.get('media', {})), media=extra.get('media'))
+ from .continuation import ADALN_TASK, ANCHOR_ADALN_TASK, validate_snapshot, summary
+ validate_route(task='ref2va' if anchored else task_for(extra.get('media', {})), anchor=anchored,
+ media=extra.get('media'))
continuation = validate_snapshot(continuation, sampled, sampling_plan=planned)
state['continuation'] = summary(continuation)
# A preview is its own result; an upscale is always run from its preview.
@@ -773,7 +786,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
preparation_started = time.monotonic()
try:
# Reference audio selects its own tables; match the encoder's choice.
- asset_task = ADALN_TASK if continue_from is not None else engine_task(extra.get('media', {}), media_base)
+ asset_task = ((ANCHOR_ADALN_TASK if anchored else ADALN_TASK) if continue_from is not None
+ else engine_task(extra.get('media', {}), media_base))
preparation = prepare_sampling_assets(root, machine, planned, asset_task,
progress=asset_progress, interrupted=interrupted, environ=environment)
except BaseException:
diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.py
index aa6518c..10f5181 100644
--- a/freevideo_engine/comfy_nodes.py
+++ b/freevideo_engine/comfy_nodes.py
@@ -62,6 +62,8 @@ class FreeVideoGenerate(io.ComfyNode):
io.Int.Input('frames', display_name='Total frames', default=0, min=0, max=2**31-1, optional=True, advanced=True,
tooltip='For long videos generated in segments: 0 uses Duration; otherwise use 5 + 17n, at least 39. '
'Includes the 22 overlap frames when continuing; the saved MP4 contains only new frames.'),
+ io.Boolean.Input('first_frame_reference', display_name='First-frame reference', default=False,
+ optional=True, advanced=True, tooltip='Reduces drift.'),
],
outputs=[io.Video.Output('video'), io.String.Output('report', display_name='Report JSON')],
hidden=[io.Hidden.unique_id, io.Hidden.prompt, io.Hidden.extra_pnginfo],
@@ -107,7 +109,7 @@ class FreeVideoGenerate(io.ComfyNode):
def execute(cls, text, width, height, seconds, seed, first=None, last=None,
references=None, loras=None, conditioning=None, media=None, two_pass=True,
force_regenerate=False, base_steps=8, refine_steps=3, preview=False, refine_from='',
- continue_from='', frames=0):
+ continue_from='', frames=0, first_frame_reference=False):
from server import PromptServer
from .comfy_chain import block_context, block_finished, report_fields
node_id = cls.hidden.unique_id
@@ -212,6 +214,8 @@ class FreeVideoGenerate(io.ComfyNode):
export_inputs=lambda run, canvas: export(run, canvas, first=first, last=last,
references=references, loras=loras, conditioning=conditioning, assets=media),
**options,
+ # Only a part that continues another can use it; other requests keep the existing bridge call.
+ **({'first_frame_reference': True} if first_frame_reference is True and options.get('continue_from') else {}),
**({'report_extra': {'chain': report_fields(chain)}} if chain is not None else {}))
relative = output.relative_to(output_root)
report = output.with_suffix('.request.json').read_text(encoding='utf-8')
diff --git a/freevideo_engine/continuation.py b/freevideo_engine/continuation.py
index 20171cf..594a6de 100644
--- a/freevideo_engine/continuation.py
+++ b/freevideo_engine/continuation.py
@@ -16,6 +16,12 @@ LEAD_IN_RATE = 32000
CLEAN_T = 1.
AUDIO_CONTEXT_DEFAULT = 'clean'
ADALN_TASK = 'ref2va_audio'
+ANCHOR_ADALN_TASK = 'ref2va_av' # visual reference clock + CLEAN_T (no reference audio)
+# Told to the model when the first frame of the whole film is its reference picture.
+FIRST_FRAME_NOTE = ('The reference image is the very first frame of this whole film: keep the same person, clothing, '
+ 'location, framing and colour tone as in that image throughout.')
+FIRST_FRAME_MAX_BYTES = 8 * 1024 * 1024
+FIRST_FRAME_MAX_SIDE = 4096
VERSION = 1
MISSING = 'The previous video has no usable continuation data. Generate it again with this version of FreeVideo.'
@@ -58,14 +64,99 @@ def validate_frames(frames):
def validate_route(*, task='t2va', two_pass=True, preview=False, refine_from=None,
- media=None, backend=None):
+ media=None, backend=None, anchor=False):
media = media or {}
- if (not supported()[0] or backend not in (None, 'cuda') or task != 't2va'
+ references = media.get('references')
+ valid_reference = (anchor and isinstance(references, list) and len(references) == 1
+ and isinstance(references[0], dict)
+ and references[0].get('kind') == 'image')
+ if (not supported()[0] or backend not in (None, 'cuda') or task != ('ref2va' if anchor else 't2va')
or not two_pass or preview or refine_from
- or any(media.get(key) for key in ('first', 'last', 'references', 'conditioning_info'))):
+ or any(media.get(key) for key in ('first', 'last', 'conditioning_info'))
+ or (references and not valid_reference)):
raise ValueError(UNSUPPORTED)
+def anchor_media(media, path):
+ """Add exactly one explicit global first-frame reference through the media encoder."""
+ if any(media.get(key) for key in ('first', 'last', 'references', 'conditioning_info')):
+ raise ValueError('--continue-anchor cannot be combined with other media conditioning')
+ from .media_request import digest
+ source = Path(path).expanduser().resolve(strict=True)
+ if not source.is_file() or not source.stat().st_size:
+ raise ValueError('--continue-anchor requires a nonempty image file')
+ return dict(media, version=1, references=[dict(kind='image', path=str(source),
+ sha256=digest(source), bytes=source.stat().st_size)])
+
+
+def first_frame_prompt(text):
+ """The prompt with the note about the reference picture, inside the picture's own field when it has fields."""
+ import re
+ field = re.search(r'(?m)^[ \t]*integrated_multimodal_description[ \t]*:[ \t]*', text)
+ position = field.end() if field else 0
+ return text[:position] + FIRST_FRAME_NOTE + ' ' + text[position:]
+
+
+def first_frame_png(video_path):
+ """The first picture of a finished video."""
+ import io
+ import av
+ with av.open(str(video_path)) as container:
+ image = next(container.decode(video=0)).to_image()
+ target = io.BytesIO()
+ image.convert('RGB').save(target, format='PNG')
+ return target.getvalue()
+
+
+def pack_first_frame(raw):
+ """A PNG as continuation record metadata; every continuation of the film carries the same value."""
+ import io
+ from PIL import Image
+ if not isinstance(raw, bytes) or not raw.startswith(b'\x89PNG\r\n\x1a\n') or len(raw) > FIRST_FRAME_MAX_BYTES:
+ raise ValueError('Invalid first frame')
+ try:
+ with Image.open(io.BytesIO(raw)) as image:
+ width, height = image.size
+ if not (32 <= width <= FIRST_FRAME_MAX_SIDE and 32 <= height <= FIRST_FRAME_MAX_SIDE):
+ raise ValueError('Invalid first frame size')
+ image.load() # A cut-off file opens; it does not decode.
+ except (OSError, SyntaxError, Image.DecompressionBombError):
+ raise ValueError('Invalid first frame') from None
+ return dict(format='png', width=width, height=height, data=base64.b64encode(raw).decode('ascii'))
+
+
+def unpack_first_frame(value):
+ """The PNG a record carries, checked again: a record is a file anyone can replace."""
+ try:
+ if value['format'] != 'png' or len(value['data']) > (FIRST_FRAME_MAX_BYTES + 2) // 3 * 4:
+ raise ValueError('Invalid first frame')
+ raw = base64.b64decode(value['data'], validate=True)
+ if pack_first_frame(raw) != value:
+ raise ValueError('Invalid first frame')
+ return raw
+ except (KeyError, TypeError, ValueError, OSError):
+ raise ValueError('Invalid first frame') from None
+
+
+def chain_first_frame(request, video_path=None):
+ """The first frame of the whole film `request` continues, as record metadata; None when nothing has it.
+
+ A continued video's record carries it from its own source. The first part of a film never
+ stored one: its saved video starts with that frame. A continued part made before records
+ carried the frame has no way back to it.
+ """
+ metadata = _snapshot_value(request)['metadata']
+ if metadata.get('first_frame') is not None:
+ unpack_first_frame(metadata['first_frame'])
+ return metadata['first_frame']
+ if metadata['chain']['segment'] != 1 or video_path is None:
+ return None
+ from .continuation_store import video_id
+ if video_id(video_path) != request.get('source_id'):
+ raise ValueError(MISSING)
+ return pack_first_frame(first_frame_png(video_path))
+
+
def validate_path(video_path):
path = Path(video_path)
if not path.is_absolute() or path.suffix.lower() != '.mp4' or not path.is_file():
@@ -192,6 +283,7 @@ def load(request, stage):
# Each pass receives writable tensors of its own; sampling cannot mutate
# the immutable snapshot used by the next pass or retry.
return dict(audio_context=validate_audio_context(request.get('audio_context', AUDIO_CONTEXT_DEFAULT)),
+ **({'anchor': request['anchor']} if request.get('anchor') else {}),
video=torch.from_numpy(value['video_lo' if stage == 'first' else 'video_hi'].copy()),
audio=torch.from_numpy(value['audio'].copy()))
@@ -242,10 +334,13 @@ class Prefix:
update. Audio is either kept clean or re-noised at each call, and restored
on return. Only re-noising owns an independent RNG.
"""
- def __init__(self, transformer, data, seed, device):
+ def __init__(self, transformer, data, seed, device, *, video_offset=0):
import torch
from diffusers.modular_pipelines.minimax_h3.before_denoise import patchify_video_latents
self.audio_context = validate_audio_context(data.get('audio_context', AUDIO_CONTEXT_DEFAULT))
+ if type(video_offset) is not int or video_offset < 0:
+ raise ValueError('Invalid continuation reference row offset')
+ self.video_offset = video_offset
self.video = data['video'].to(device=device, dtype=torch.float32)
self.audio = data['audio'].to(device=device, dtype=torch.float32)
if (self.video.ndim != 5 or self.video.shape[:3] != (1, transformer.config.in_channels, LATENT_FRAMES)
@@ -264,7 +359,7 @@ class Prefix:
import torch
video, audio = kwargs['hidden_states'][0], kwargs['audio_hidden_states'][0]
count, ticks = self.video_rows.shape[0], self.audio.shape[2]
- if video.shape[0] <= count or audio.shape[0] // 2 < ticks:
+ if video.shape[0] <= self.video_offset + count or audio.shape[0] // 2 < ticks:
raise ValueError(MISSING)
self.current_video = video
self.restore_video()
@@ -278,13 +373,13 @@ class Prefix:
audio_t = row_times[kwargs['audio_indices'][0]]
# scale_noise uses H3's clean-at-one convention, not a standard DDPM clock.
audio[audio_rows] = self.scheduler.scale_noise(self.audio_rows, audio_t, self.noise)
- row_times[kwargs['video_indices'][:count]] = CLEAN_T
+ row_times[kwargs['video_indices'][self.video_offset:self.video_offset + count]] = CLEAN_T
kwargs['timestep'], kwargs['timestep_indices'] = torch.unique(row_times, sorted=True, return_inverse=True)
return args, kwargs
def restore_video(self):
if self.current_video is not None:
- self.current_video[:self.video_rows.shape[0]] = self.video_rows
+ self.current_video[self.video_offset:self.video_offset + self.video_rows.shape[0]] = self.video_rows
def finish(self, video, audio):
video[:, :, :LATENT_FRAMES] = self.video
@@ -293,11 +388,12 @@ class Prefix:
@contextmanager
-def sampling(transformer, data, seed, device):
+def sampling(transformer, data, seed, device, *, video_offset=0):
if data is None:
yield None
return
- prefix = Prefix(transformer, data, seed, device)
+ # Keep the legacy constructor call identical for existing continuations.
+ prefix = Prefix(transformer, data, seed, device, **({'video_offset': video_offset} if video_offset else {}))
handle = transformer.register_forward_pre_hook(prefix.before, with_kwargs=True, prepend=True)
try:
yield prefix
diff --git a/freevideo_engine/decode_resume.py b/freevideo_engine/decode_resume.py
index ff764dc..eff5581 100644
--- a/freevideo_engine/decode_resume.py
+++ b/freevideo_engine/decode_resume.py
@@ -98,7 +98,7 @@ def sampling_provenance(request):
# A retry's identity binds the accepted bytes, without embedding the
# snapshot again or making a relocation change computation identity.
result['continuation'] = {key: value for key, value in request['continuation'].items()
- if key not in ('snapshot', 'snapshot_data')}
+ if key not in ('snapshot', 'snapshot_data', 'source_video')}
return result
diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py
index ae15914..93decbe 100644
--- a/freevideo_engine/generate.py
+++ b/freevideo_engine/generate.py
@@ -347,6 +347,15 @@ def _run(args):
audio_context)
frames = getattr(args, 'frames', None)
continue_from = getattr(args, 'continue_from', None)
+ continue_anchor = getattr(args, 'continue_anchor', None)
+ if continue_anchor is not None and continue_from is None:
+ raise ValueError('--continue-anchor requires --continue-from')
+ # Every part of a long video is asked alike; only a part that continues another can use it.
+ first_frame = None
+ if getattr(args, 'first_frame_reference', False) and continue_from is not None:
+ if continue_anchor is not None:
+ raise ValueError('Choose --first-frame-reference or --continue-anchor, not both')
+ first_frame = dict(requested=True, used=False)
if continue_from is not None and frames is not None:
validate_frames(frames)
canvas = geometry(getattr(args, 'width', 1344), getattr(args, 'height', 768),
@@ -366,13 +375,17 @@ def _run(args):
canvas['steps'] = requested_steps
from .media_request import read as read_media, task_for, cache_key
media = read_media(getattr(args, 'media', None))
+ if continue_anchor is not None:
+ from .continuation import anchor_media
+ media = anchor_media(media, continue_anchor)
# Too small to sample cleanly: render larger, scale the picture down. Decided before anything
# compares or stores the canvas, so every later check sees the size that is sampled.
from .two_pass import sampling_canvas
canvas, output_size = sampling_canvas(canvas, staged=bool(preview or refine_source), media=media,
conditioned=bool(args.conditioning))
if continue_from is not None:
- validate_route(task=getattr(args, 'task', None) or 't2va', two_pass=two_pass,
+ validate_route(task=getattr(args, 'task', None) or ('ref2va' if continue_anchor else 't2va'),
+ anchor=continue_anchor is not None, two_pass=two_pass,
preview=preview, refine_from=getattr(args, 'refine_from', None), media=media)
# Reject absent/mismatched context before text encoding or model loading.
if getattr(args, 'continuation_snapshot', None):
@@ -380,7 +393,29 @@ def _run(args):
getattr(args, 'continuation_snapshot_sha256', None), canvas)
else:
continuation = prepare_continuation(continue_from, canvas)
- continuation = dict(continuation, audio_context=audio_context())
+ continuation = dict(continuation, audio_context=audio_context(), source_video=str(continue_from))
+ if first_frame is not None:
+ from .continuation import anchor_media, chain_first_frame, unpack_first_frame
+ try:
+ kept = chain_first_frame(continuation, continue_from)
+ except ValueError:
+ kept = None
+ first_frame['reason'] = 'unreadable'
+ if kept is None:
+ # Optional help: the part is made as an ordinary continuation and the report says why.
+ first_frame.setdefault('reason', 'source_predates')
+ else:
+ if args.out.resolve().exists():
+ raise FileExistsError(args.out.resolve())
+ args.out.resolve().parent.mkdir(parents=True, exist_ok=True)
+ continue_anchor = args.out.resolve().with_suffix('.first-frame.png')
+ continue_anchor.write_bytes(unpack_first_frame(kept))
+ media = anchor_media(media, continue_anchor)
+ validate_route(task=getattr(args, 'task', None) or 'ref2va', anchor=True, two_pass=two_pass,
+ preview=preview, refine_from=getattr(args, 'refine_from', None), media=media)
+ first_frame.update(used=True, width=kept['width'], height=kept['height'])
+ if continue_anchor is not None:
+ continuation['anchor'] = media['references'][0]
active_loras = [row for row in media.get('loras', []) if row['strength'] != 0]
if media:
inferred_task = task_for(media)
@@ -427,7 +462,7 @@ def _run(args):
manifest = json.loads((args.cache / 'manifest.json').read_text(encoding='utf-8'))
if continuation is not None:
from .two_pass import plan as continuation_plan
- validate_route(task=profile['engine'].get('task', 't2va'))
+ validate_route(task=profile['engine'].get('task', 't2va'), anchor=continue_anchor is not None)
continuation = validate_snapshot(continuation, canvas, None if active_loras else manifest,
continuation_plan(canvas, two_pass, base_steps=base_steps, refine_steps=refine_steps))
if manifest.get('precision') not in ('fp8', 'int8', 'bf16'): # BF16: the unquantized reference
@@ -456,6 +491,10 @@ def _run(args):
if continuation is not None:
report['continuation'] = continuation_summary(continuation)
report['audio_context'] = continuation['audio_context']
+ if continue_anchor is not None:
+ report['continue_anchor'] = continuation['anchor']
+ if first_frame is not None:
+ report['first_frame_reference'] = first_frame
from .support_report import code_identity, write as write_debug
report['runtime_hardware'] = hardware.to_dict()
report['runtime_code'] = code_identity()
@@ -542,7 +581,12 @@ def _run(args):
elif args.conditioning:
shutil.copyfile(args.conditioning, condition)
if args.prompt_file and not refine_source:
- encoding = {'prompt': args.prompt_file.read_text(encoding='utf-8'), 'encoder': args.encoder,
+ prompt_text = args.prompt_file.read_text(encoding='utf-8')
+ if first_frame is not None and first_frame['used']:
+ # The saved prompt stays the user's own; the model is also told what the picture is.
+ from .continuation import first_frame_prompt
+ prompt_text = first_frame_prompt(prompt_text)
+ encoding = {'prompt': prompt_text, 'encoder': args.encoder,
'comfy_root': str(args.comfy_root or comfy_root()),
'model_paths': str(args.model_paths.resolve()) if args.model_paths else None,
'output': str(condition), 'gpu_budget_gb': profile['gpu_budget_gb'],
@@ -640,7 +684,7 @@ def _run(args):
staged=bool(preview or refine_source))
report['sampling_plan'] = sampling_plan
if continuation is not None:
- validate_route(task=profile['engine'].get('task', 't2va'))
+ validate_route(task=profile['engine'].get('task', 't2va'), anchor=continue_anchor is not None)
continuation = validate_snapshot(continuation, canvas,
json.loads((args.cache / 'manifest.json').read_text(encoding='utf-8')), sampling_plan)
if preview:
@@ -759,8 +803,9 @@ def _run(args):
nonlocal preview_pass
selected_env = inference_environment(engine_env, selected['inference_ram_budget_gb'] * 1e9)
if continuation is not None:
- from .continuation import ADALN_TASK
- selected['engine'] = dict(selected['engine'], adaln_task=ADALN_TASK)
+ from .continuation import ADALN_TASK, ANCHOR_ADALN_TASK
+ selected['engine'] = dict(selected['engine'],
+ adaln_task=ANCHOR_ADALN_TASK if continue_anchor is not None else ADALN_TASK)
request.update(engine_options=selected['engine'], decoder_options=selected['decoder'],
ram_budget_bytes=round(selected['inference_ram_budget_gb'] * 1e9),
ram_budget_is_estimate=ram_budget_is_estimate(args),
diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.py
index b3feeee..4b24f8e 100644
--- a/freevideo_engine/runtime.py
+++ b/freevideo_engine/runtime.py
@@ -72,7 +72,7 @@ class Engine:
if task not in TASKS:
raise ValueError('Unsupported Engine task: ' + str(task))
self.task = task
- if adaln_task not in (None, task, 'ref2va_audio'):
+ if adaln_task not in (None, task, 'ref2va_audio') and not (task == 'ref2va' and adaln_task == 'ref2va_av'):
raise ValueError('Unsupported continuation modulation schedule')
self.adaln_task = adaln_task or task
if type(residual_offload) is not bool:
@@ -547,7 +547,7 @@ class Engine:
refining = initial_latents is not None
if continuation is not None:
from .continuation import validate_route
- validate_route(task=self.task)
+ validate_route(task=self.task, anchor=bool(continuation.get('anchor')))
if tuple(continuation['video'].shape[-2:]) != (height // 16, width // 16):
from .continuation import SIZE_MISMATCH
raise ValueError(SIZE_MISMATCH)
@@ -581,6 +581,7 @@ class Engine:
progress = SamplingProgress(active_steps, len(self.transformer.transformer_blocks),
offset=progress_offset, total=progress_total)
progress.start()
+ continuation_offset = 0
if self.task.startswith('ref2va'):
from .media_conditioning import describe
value = torch.load(conditioning, map_location='cpu', weights_only=True)
@@ -588,6 +589,13 @@ class Engine:
if info['task'] != self.task:
raise ValueError('Reference modalities changed the precomputed schedule')
conditions = value['references']
+ if continuation is not None:
+ if len(conditions) != 1 or conditions[0]['kind'] != 'image' or conditions[0].get('audio_latent') is not None:
+ raise ValueError('Continuation anchor requires exactly one image reference without audio')
+ # Ref2VA packs independent-size references before generated
+ # video rows in both passes. Their latents do not need the
+ # keyframe resize used by first/last-frame conditioning.
+ continuation_offset = info['reference_video_tokens']
prompt, tags = value['prompt_embeds'].to(self.device_backend.device, torch.bfloat16), value['text_token_tags']
else:
prompt, tags, conditions = load_prompt(str(conditioning), self.device_backend.device)
@@ -747,7 +755,8 @@ class Engine:
try:
with progress.layers(self.transformer.transformer_blocks), self.device_backend.make_offloader(
self.offload_layers, prefetch=self.prefetch, weight_source=self.stream_weight_source) as offloader, sampling(
- self.transformer, continuation, seed, self.device_backend.device) as prefix:
+ self.transformer, continuation, seed, self.device_backend.device,
+ **({'video_offset': continuation_offset} if continuation_offset else {})) as prefix:
latents, audio = generate_latents(self.transformer, prompt, tags, frames,
self.steps, seed, self.device_backend.device, step_seconds=step_seconds,
conditions=conditions)
diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.py
index 0c0e363..c98667f 100644
--- a/freevideo_engine/worker.py
+++ b/freevideo_engine/worker.py
@@ -97,12 +97,13 @@ def generate(request, resident=None):
metrics['sampling_plan'] = expected
continuation = request.get('continuation')
if continuation is not None:
- from .continuation import (validate_route, summary, ADALN_TASK, UNSUPPORTED,
+ from .continuation import (validate_route, summary, ADALN_TASK, ANCHOR_ADALN_TASK, UNSUPPORTED,
validate_audio_context, AUDIO_CONTEXT_DEFAULT)
# A plan that fell back to one pass on a small canvas still has
# the two-pass flag set and keeps its continuation; an explicit
# single-pass request does not.
validate_route(task=request['engine_options'].get('task', 't2va'),
+ anchor=bool(continuation.get('anchor')),
two_pass=bool(request.get('sampling_plan', {}).get('requested')),
preview=request.get('preview', False), refine_from=request.get('resume_first_pass'))
if isinstance(getattr(torch.version, 'hip', None), str):
@@ -110,7 +111,8 @@ def generate(request, resident=None):
continuation = dict(continuation,
audio_context=validate_audio_context(continuation.get('audio_context', AUDIO_CONTEXT_DEFAULT)))
request['continuation'] = continuation
- request['engine_options'] = dict(request['engine_options'], adaln_task=ADALN_TASK)
+ request['engine_options'] = dict(request['engine_options'],
+ adaln_task=ANCHOR_ADALN_TASK if continuation.get('anchor') else ADALN_TASK)
metrics['continuation'] = summary(continuation)
metrics['audio_context'] = continuation['audio_context']
metrics['device_memory'] = device_memory_report(request['gpu_budget_bytes'], request.get('allocator_limit_bytes'),
@@ -190,7 +192,8 @@ def generate(request, resident=None):
# serves both stages. An explicit single-pass request keeps nothing.
plan_flags = request.get('sampling_plan') or {}
continuable = (bool(plan_flags.get('enabled') or plan_flags.get('requested'))
- and options.get('task', 't2va') == 't2va' and not request.get('preview'))
+ and (options.get('task', 't2va') == 't2va' or bool(continuation and continuation.get('anchor')))
+ and not request.get('preview'))
first_tail = continuation_data = None
def tail_failure(error):
from .adaptive import classify_failure
@@ -591,6 +594,19 @@ def generate(request, resident=None):
if continuation is not None and continuation_data is not None else {}),
model_cache=resident, phase_callback=decode_phase, output_size=output_size, **decoder))
if continuable and continuation_data is not None:
+ if continuation is not None:
+ # Every continuation of a film carries its first frame on, used or not: a later
+ # part may ask for it. Without one this part is saved as before.
+ try:
+ from .continuation import chain_first_frame
+ frame = chain_first_frame(continuation, continuation.get('source_video'))
+ if frame is not None:
+ continuation_data['metadata']['first_frame'] = frame
+ except Exception as error:
+ if isinstance(error, MemoryError) or type(error).__name__ in (
+ 'OutOfMemoryError', 'CancelledError', 'InterruptProcessingException'):
+ raise
+ metrics['first_frame_kept'] = dict(saved=False, error=type(error).__name__)
try:
from .continuation_store import save as save_continuation
metrics['continuation_store'] = dict(save_continuation(request['output'], continuation_data), saved=True)