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.

Reference media: the estimate counts the prepared references, and video encoding reports each...

Bowen Xuecf14be1d826b
diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py
index 3ef5f0c..6f3dbcd 100644
--- a/freevideo_engine/comfy_bridge.py
+++ b/freevideo_engine/comfy_bridge.py
@@ -301,7 +301,7 @@ class WholeVideoProgress:
vars(self).clear()
vars(self).update(saved)
- def configure(self, *, plan=None, media=None, conditioning=False, placement=None, sampled=None):
+ def configure(self, *, plan=None, media=None, conditioning=False, placement=None, sampled=None, reference=None):
"""Use facts already obtained by the bridge; never inspect media/models."""
self._late_history()
from .media_request import task_for
@@ -346,6 +346,14 @@ class WholeVideoProgress:
sum(bool(media.get(k)) for k in ('first', 'last')))
if conditioning:
self.cold_flags['encode_cached'] = True
+ if reference:
+ # The prepared references: their rows enlarge every sampling step
+ # and their length sets the encoding time, neither known from the request.
+ rows, seconds = reference.get('reference_video_tokens'), reference.get('reference_seconds')
+ if type(rows) is int and rows > 0:
+ self.request['reference_video_tokens'] = rows
+ if type(seconds) in (int, float) and math.isfinite(seconds) and seconds > 0:
+ self.request['reference_seconds'] = float(seconds)
self._reforecast()
def _reforecast(self, *, reset_source=False):
@@ -542,6 +550,14 @@ class WholeVideoProgress:
# LoRA groups describe a substage, not completion of the whole load.
if type(done) is int and type(total) is int and total > 0 and message.get('unit') != 'bytes':
self._set_count(done, total)
+ elif phase == 'encode' and message.get('stage') == 'media':
+ # Reference video encoding costs far more than the stage's fixed
+ # estimate on a modest GPU; once a chunk is done its rate gives the
+ # rest. Only the stage under way is rescaled.
+ elapsed = _timing_seconds(message.get('elapsed_seconds'))
+ if type(done) is int and type(total) is int and 0 < done <= total and elapsed:
+ self._set_count(done, total)
+ self.weights[phase] = now - self.phase_started + elapsed * (total - done) / done
elif phase == 'decode_save' and message.get('stage') == 'video':
elapsed = _timing_seconds(message.get('elapsed_seconds'))
if type(done) is int and type(total) is int and 0 <= done <= total and total > 0:
@@ -764,6 +780,8 @@ class WholeVideoProgress:
self._retry({}, now)
if event.get('event') in ('video_start', 'decode_resume'):
self.configure(placement=event)
+ if event.get('event') == 'reference_media':
+ self.configure(reference=event)
phase = self._phase_for(message, event)
if phase:
self._enter(phase, now)
@@ -1105,6 +1123,13 @@ def progress_message(event):
elapsed_seconds=event.get('elapsed_seconds'))
if name == 'media_encode_phase':
return {'label': str(event.get('phase', 'Encoding input media')), 'timing_phase': 'encoding'}
+ if name == 'media_encode_progress':
+ done, total = event.get('done'), event.get('total')
+ result = dict(label='Encoding image/video references', timing_phase='encoding')
+ if type(done) is int and type(total) is int and 0 <= done <= total and total > 0:
+ result.update(phase='encoding', stage='media', done=done, total=total, unit='frames',
+ elapsed_seconds=event.get('elapsed_seconds'))
+ return result
if name == 'reference_trimmed':
return {'label': 'Preparing reference media', 'timing_phase': 'encoding',
'reference_trimmed': {key: event.get(key) for key in ('kind', 'number', 'seconds', 'used_seconds')}}
diff --git a/freevideo_engine/media_encoding.py b/freevideo_engine/media_encoding.py
index e1d5a1d..58ba90c 100644
--- a/freevideo_engine/media_encoding.py
+++ b/freevideo_engine/media_encoding.py
@@ -34,11 +34,12 @@ def reference_size(width, height, canvas):
return max(32, round(width * scale / 32) * 32), max(32, round(height * scale / 32) * 32)
-def encode_visual(vae, pixels, *, device='cuda', posterior='sample'):
+def encode_visual(vae, pixels, *, device='cuda', posterior='sample', progress=None):
"""The pinned VAE chunk/padding/posterior recipe with one live pixel chunk.
Posterior sampling still occurs once on the original device with seed 42;
sampling separately per chunk would change the conditioning noise.
+ `progress(frames_done)` is told after each temporal chunk; it never touches the tensors.
"""
import numpy as np
import torch
@@ -55,6 +56,8 @@ def encode_visual(vae, pixels, *, device='cuda', posterior='sample'):
current = torch.cat([current, current[:, :, -1:].repeat(1, 1, clip - current.shape[2], 1, 1)], dim=2)
moments.append(vae._encode_clip(current).cpu())
del current
+ if progress is not None:
+ progress(min(len(pixels), begin + clip))
moments = torch.cat(moments, dim=2).to(device)
if len(pixels) > 1 and vae.config.token_drop:
moments = moments[:, :, :-vae.config.token_drop]
@@ -131,6 +134,25 @@ def _audio(path, destination, seconds):
return str(destination), count > limit + 1600, length
+def reference_load(rows):
+ """(packed video rows, encoding seconds) the visual references add, as capabilities.admit counts them.
+
+ A still is one patch grid and five legacy encoding seconds; a clip adds five
+ rows of patches per 17 frames plus two, and its own length.
+ """
+ video, seconds = 0, 0.
+ for row in rows:
+ if row.get('kind') not in ('image', 'video') or not row.get('pixels'):
+ continue
+ patches = (int(row.get('height', 0)) // 32) * (int(row.get('width', 0)) // 32)
+ frames = int(row.get('frames', 1))
+ if frames == 1:
+ video, seconds = video + patches, seconds + 5.
+ else:
+ video, seconds = video + max(0, (frames - 5) // 17 * 5 + 2) * patches, seconds + frames / 24.
+ return video, seconds
+
+
def prepare(media, canvas, directory):
import numpy as np
import torch
@@ -259,6 +281,12 @@ def prepare(media, canvas, directory):
print(json.dumps(dict(event='reference_trimmed', **ref['trimmed'])), flush=True)
result.append(ref)
(directory / 'normalization.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
+ rows, seconds = reference_load(result)
+ if rows:
+ # Known long before the first encoded chunk, and what the time estimate
+ # needs: reference rows enlarge every sampling step.
+ print(json.dumps({'event': 'reference_media', 'reference_video_tokens': rows,
+ 'reference_seconds': seconds}), flush=True)
return result, {'images': key_images} if key_images else {'minimax_ref_items': ref_items} if ref_items else {}
@@ -478,6 +506,36 @@ def _remember_latent(cache, key, latent, directory=None):
path.unlink(missing_ok=True)
+class _encode_progress:
+ """Tells the caller how many reference frames are encoded, once per temporal chunk.
+
+ Reference video encoding is the longest silent stage of a request on a
+ modest GPU, so each finished chunk prints one `media_encode_progress` row
+ with the elapsed time, from which the remaining time follows. The count only
+ moves forward, also when a stage is retried.
+ """
+
+ def __init__(self, rows, clock=None):
+ import time
+ self.total = sum(int(frames) for frames in rows)
+ self.clock = clock or time.perf_counter
+ self.started = self.clock()
+ self.before = self.done = 0
+
+ def __call__(self, frames):
+ done = min(self.total, self.before + int(frames))
+ if done <= self.done or not self.total:
+ return
+ self.done = done
+ print(json.dumps({'event': 'media_encode_progress', 'done': done, 'total': self.total,
+ 'elapsed_seconds': round(self.clock() - self.started, 3)}), flush=True)
+
+ def finish(self, frames):
+ """One reference is complete: the next one counts on top of it."""
+ self.before += int(frames)
+ self.done = max(self.done, min(self.total, self.before))
+
+
def encode_latents(normalized, value, base, canvas, *, resident=None, device='cuda', cache_root=None):
import gc
import numpy as np
@@ -538,6 +596,8 @@ def encode_latents(normalized, value, base, canvas, *, resident=None, device='cu
if on_mps:
from .backends.mps_vae_encode import bounded_encoder
lifetime = bounded_encoder(vae, device=device)
+ report = _encode_progress([row['frames'] for index, row in enumerate(normalized)
+ if row.get('pixels') and index not in hits])
with lifetime as memory:
for index, (row, ref) in enumerate(zip(normalized, refs)):
if row.get('pixels') and index not in hits:
@@ -547,9 +607,12 @@ def encode_latents(normalized, value, base, canvas, *, resident=None, device='cu
ref['latent'] = _retry_in_host_memory(memory, lambda: encode_vae_condition(
vae, pixels, PIXEL_MEAN, PIXEL_STD, 42)).cpu()
del pixels
+ report(1)
else:
ref['latent'] = _retry_in_host_memory(
- memory, lambda: encode_visual(vae, mapped[:row['frames']], device=device))
+ memory, lambda: encode_visual(vae, mapped[:row['frames']], device=device,
+ progress=report))
+ report.finish(row['frames'])
del mapped
if cache is not None and index in keys:
_remember_latent(cache, keys[index], ref['latent'], Path(row['pixels']).parent)