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.

Show frame previews while a video is being generated

Bowen Xuea10c21ee5934
diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py
index c87f6b4..e820671 100644
--- a/freevideo_engine/comfy_bridge.py
+++ b/freevideo_engine/comfy_bridge.py
@@ -908,6 +908,21 @@ class EventTail:
return result
+def preview_state(event):
+ """The few facts the page needs to show the newest frame preview, or None."""
+ values = {key: event.get(key) for key in ('serial', 'step', 'total', 'frames', 'frame_width', 'frame_height')}
+ if any(type(value) is not int or value < 1 or value > 100000 for value in values.values()) or values['frames'] > 8:
+ return None
+ return values
+
+
+def preview_update(current, event):
+ """The page's frame picture after a frame_preview / frame_preview_clear event."""
+ if event.get('event') == 'frame_preview_clear':
+ return None
+ return preview_state(event) or current
+
+
def progress_message(event):
from .sampling_progress import progress_message as sampling_message
sampling = sampling_message(event)
@@ -1295,9 +1310,15 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
whole_progress = _SafeProgress(whole_progress)
from .comfy_progress import REPORTS
report_id = REPORTS.register(output)
+ frame_state = [None]
def send_progress(message, event=None):
if progress:
- progress(whole_progress.annotate(dict(message, report_id=report_id), event=event))
+ value = whole_progress.annotate(dict(message, report_id=report_id), event=event)
+ if message.get('phase') in ('sample_finalize', 'decode') or message.get('timing_phase') in ('decode', 'encoding'):
+ frame_state[0] = None
+ if frame_state[0] is not None:
+ value = dict(value, frame_preview=frame_state[0])
+ progress(value)
process = None
from .result_cache import ResultCache, request_key, inspect_bounded
cache = ResultCache(output_directory)
@@ -1310,6 +1331,9 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,
for event in tail.events():
if index == 0 and event.get('event') == 'resource_retry':
tails[2].reset()
+ if event.get('event') in ('frame_preview', 'frame_preview_clear'):
+ frame_state[0] = preview_update(frame_state[0], event)
+ continue
message = progress_message(event)
if message:
send_progress(message, event)
diff --git a/freevideo_engine/comfy_progress.py b/freevideo_engine/comfy_progress.py
index 12b49a0..2a016c3 100644
--- a/freevideo_engine/comfy_progress.py
+++ b/freevideo_engine/comfy_progress.py
@@ -72,7 +72,8 @@ class ProgressState:
'sampling_plan', 'bytes_per_second', 'block', 'blocks', 'elapsed_seconds', 'step_elapsed_seconds',
'estimated_step_seconds', 'remaining_seconds', 'display_fraction',
'estimated', 'uniform_remaining_steps', 'overall', 'retry', 'warning', 'kernel_cache_note',
- 'new_request', 'reset', 'result', 'report_id', 'compatibility', 'memory_tight', 'references', 'chain')
+ 'new_request', 'reset', 'result', 'report_id', 'compatibility', 'memory_tight', 'references', 'chain',
+ 'frame_preview')
value = deepcopy({key: message[key] for key in keys if key in message})
if isinstance(message.get('prediction'), dict):
# The UI only needs a history marker, not the resource forecast.
@@ -198,6 +199,24 @@ class ReportDownloads:
return path.read_bytes()
+ def preview(self, token):
+ """The newest frame preview picture of a registered run, or KeyError."""
+ from .frame_preview import FILE
+ from .diagnostics import is_link
+ with self.lock:
+ output = self.runs.get(token)
+ if output is None:
+ raise KeyError('Unknown run')
+ path = output.parent / FILE
+ if is_link(output.parent) or path.is_symlink() or not path.is_file():
+ raise KeyError('No preview')
+ with path.open('rb') as stream:
+ data = stream.read(2 * 1024 * 1024 + 1)
+ if not data or len(data) > 2 * 1024 * 1024:
+ raise KeyError('No preview')
+ return data
+
+
REPORTS = ReportDownloads()
@@ -290,6 +309,15 @@ def register():
'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
'Content-Disposition': 'attachment; filename="FreeVideo-report-%s.json"' % time.strftime('%Y%m%d-%H%M%S')})
+ @server.routes.get('/freevideo/frame-preview/{report_id}')
+ async def frame_preview(request):
+ try:
+ data = await asyncio.to_thread(REPORTS.preview, request.match_info['report_id'])
+ except (KeyError, OSError):
+ raise web.HTTPNotFound(text='') from None
+ return web.Response(body=data, content_type='image/jpeg', headers={
+ 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'})
+
@server.routes.get('/freevideo/progress')
async def progress(request):
return web.json_response({'progress': STATE.snapshot()},
diff --git a/freevideo_engine/frame_preview.py b/freevideo_engine/frame_preview.py
new file mode 100644
index 0000000..76fb5e9
--- /dev/null
+++ b/freevideo_engine/frame_preview.py
@@ -0,0 +1,182 @@
+"""Coarse frame previews of the video being sampled.
+
+At each step the scheduler already holds the model's prediction of the clean
+latents. A fixed per-pixel affine map from the 24 latent channels to RGB turns
+four of those latent frames into a small picture without running the VAE. The
+observer only reads tensors the sampler already produced and never writes to
+them, so the sampled latents are identical with it on or off. Any failure
+silently turns it off for the rest of the request.
+"""
+from contextlib import contextmanager
+import json
+import os
+from pathlib import Path
+
+WEIGHTS = Path(__file__).with_name('frame_preview_weights.json')
+FILE = 'frame-preview.jpg'
+ENV = 'FREEVIDEO_FRAME_PREVIEW'
+FIRST_STEP = 3
+FRAMES = 4
+QUALITY = 82
+MAX_FRAME_WIDTH = 336
+CHANNELS = 24
+ROW_WIDTH = CHANNELS * 4 # 24 channels x a (1, 2, 2) patch
+
+_sink = None
+_active = None
+_weights = None
+_failed = False # request-level: one failure turns previews off for every later pass
+_serial = 0 # request-level: numbers pictures across passes so the page never mistakes a new one for the old
+
+
+def disabled(environ=None):
+ value = (os.environ if environ is None else environ).get(ENV, '')
+ return value.strip().lower() in ('0', 'off', 'false', 'no')
+
+
+def load_weights(path=WEIGHTS):
+ """(k, weight[24, 3k^2], bias[3k^2]) as lists; ValueError when malformed."""
+ value = json.loads(Path(path).read_text(encoding='utf-8'))
+ k, weight, bias = value['k'], value['weight'], value['bias']
+ outputs = 3 * k * k
+ if (value.get('version') != 1 or type(k) is not int or not 1 <= k <= 8 or value.get('channels') != CHANNELS
+ or len(weight) != CHANNELS or any(len(row) != outputs for row in weight) or len(bias) != outputs):
+ raise ValueError('Unsupported frame preview weights')
+ return k, weight, bias
+
+
+def configure(directory, emit=None, *, weights=None):
+ """Turn previews on for this process; returns whether they are active.
+
+ `directory` receives the picture; `emit(event)` reports each new one.
+ """
+ global _sink, _weights, _failed, _serial
+ _sink = _weights = None
+ _failed, _serial = False, 0
+ if disabled():
+ return False
+ try:
+ k, weight, bias = load_weights(WEIGHTS if weights is None else weights)
+ if emit is None:
+ from .sampling_progress import emit_event as emit
+ _weights = (k, weight, bias)
+ _sink = (Path(directory), emit)
+ except Exception:
+ _sink = _weights = None
+ return _sink is not None
+
+
+def _remove(directory):
+ for name in (FILE, FILE + '.tmp'):
+ try:
+ (directory / name).unlink()
+ except OSError:
+ pass
+
+
+def clear():
+ """Forget the sink and remove the last picture."""
+ global _sink, _weights
+ sink, _sink, _weights = _sink, None, None
+ if sink is not None:
+ _remove(sink[0])
+
+
+def _fail():
+ """Previews stay off for the rest of the request: drop the picture and tell the page to do the same."""
+ global _sink, _weights, _failed
+ sink, _sink, _weights, _failed = _sink, None, None, True
+ if sink is None:
+ return
+ _remove(sink[0])
+ try:
+ sink[1](dict(event='frame_preview_clear'))
+ except Exception:
+ pass
+
+
+class _Preview:
+ def __init__(self, latent_frames, frame_h, frame_w, step_offset, total):
+ self.rows = latent_frames * frame_h * frame_w
+ self.shape = (latent_frames, frame_h, frame_w)
+ self.step_offset, self.total = step_offset, total
+ self.calls = 0
+ count = min(FRAMES, latent_frames)
+ self.indices = sorted({round(i * (latent_frames - 1) / max(1, count - 1)) for i in range(count)})
+ self.tensors = None
+
+ def render(self, model_output, timestep, sample):
+ """The preview strip as uint8 (height, frames * width, 3), from the predicted clean latents."""
+ import torch
+ k, weight, bias = _weights
+ t, fh, fw = self.shape
+ if self.tensors is None or self.tensors[0].device != sample.device:
+ self.tensors = (torch.tensor(weight, dtype=torch.float32, device=sample.device),
+ torch.tensor(bias, dtype=torch.float32, device=sample.device))
+ matrix, offset = self.tensors
+ index = torch.tensor(self.indices, device=sample.device)
+ with torch.no_grad():
+ seen = sample.detach().reshape(t, fh, fw, ROW_WIDTH)[index].float()
+ velocity = model_output.detach().reshape(t, fh, fw, ROW_WIDTH)[index].float()
+ x0 = seen + (1. - float(timestep)) * velocity
+ n = len(self.indices)
+ # (n, fh, fw, C, 1, 2, 2) -> (n, fh*2, fw*2, C)
+ x0 = x0.reshape(n, fh, fw, CHANNELS, 2, 2).permute(0, 1, 4, 2, 5, 3).reshape(n, fh * 2, fw * 2, CHANNELS)
+ out = torch.addmm(offset, x0.reshape(-1, CHANNELS), matrix)
+ out = out.reshape(n, fh * 2, fw * 2, 3, k, k).permute(0, 3, 1, 4, 2, 5)
+ out = out.reshape(n, 3, fh * 2 * k, fw * 2 * k)
+ if out.shape[-1] > MAX_FRAME_WIDTH:
+ size = (max(1, round(out.shape[-2] * MAX_FRAME_WIDTH / out.shape[-1])), MAX_FRAME_WIDTH)
+ out = torch.nn.functional.interpolate(out, size=size, mode='area')
+ picture = out.clamp(0., 1.).mul(255.).round().to(torch.uint8)
+ return picture.permute(2, 0, 3, 1).reshape(picture.shape[2], n * picture.shape[3], 3).cpu().numpy()
+
+ def observe(self, model_output, timestep, sample):
+ global _serial
+ if sample.ndim != 2 or tuple(sample.shape) != (self.rows, ROW_WIDTH):
+ return
+ self.calls += 1
+ step = self.step_offset + self.calls
+ if step < FIRST_STEP:
+ return
+ from PIL import Image
+ directory, emit = _sink
+ strip = self.render(model_output, timestep, sample)
+ target = directory / FILE
+ temporary = directory / (FILE + '.tmp')
+ Image.fromarray(strip).save(temporary, 'JPEG', quality=QUALITY)
+ os.replace(temporary, target)
+ # Never repeats within a request, also when the second pass runs in another process.
+ _serial = max(_serial + 1, step)
+ n = len(self.indices)
+ emit(dict(event='frame_preview', step=step, total=self.total, serial=_serial, frames=n,
+ frame_width=strip.shape[1] // n, frame_height=strip.shape[0]))
+
+
+@contextmanager
+def observing(*, latent_frames, frame_h, frame_w, step_offset=0, total=None):
+ """Observe the video scheduler of one sampling pass; no-op unless configured."""
+ global _active
+ previous = _active
+ _active = None
+ if _sink is not None and not _failed:
+ try:
+ _active = _Preview(latent_frames, frame_h, frame_w, step_offset, total)
+ except Exception:
+ _active = None
+ _fail()
+ try:
+ yield
+ finally:
+ _active = previous
+
+
+def observe(model_output, timestep, sample):
+ """Called by the scheduler before its step; never raises, never changes tensors."""
+ active = _active
+ if active is None or _sink is None:
+ return
+ try:
+ active.observe(model_output, timestep, sample)
+ except Exception:
+ _fail()
diff --git a/freevideo_engine/frame_preview_weights.json b/freevideo_engine/frame_preview_weights.json
new file mode 100644
index 0000000..0cac62f
--- /dev/null
+++ b/freevideo_engine/frame_preview_weights.json
@@ -0,0 +1,362 @@
+{
+ "version": 1,
+ "k": 2,
+ "channels": 24,
+ "weight": [
+ [
+ -0.07370627671480179,
+ -0.021120745688676834,
+ -0.05977412313222885,
+ 0.002065332606434822,
+ -0.11622072011232376,
+ -0.061420608311891556,
+ -0.09455660730600357,
+ -0.02990889362990856,
+ -0.1248912438750267,
+ -0.07796724885702133,
+ -0.09502269327640533,
+ -0.03627718612551689
+ ],
+ [
+ 0.05719200149178505,
+ 0.024717874825000763,
+ 0.07708700746297836,
+ 0.026475833728909492,
+ 0.09218078851699829,
+ 0.05613788962364197,
+ 0.10515830665826797,
+ 0.05108590051531792,
+ 0.06971317529678345,
+ 0.038094718009233475,
+ 0.07261519879102707,
+ 0.022622162476181984
+ ],
+ [
+ 0.08109177649021149,
+ 0.09804833680391312,
+ 0.14805379509925842,
+ 0.13475139439105988,
+ 0.025631869211792946,
+ 0.0450613871216774,
+ 0.09009499102830887,
+ 0.08030437678098679,
+ -0.05549245700240135,
+ -0.04084412008523941,
+ 0.0034296857193112373,
+ -0.00573814008384943
+ ],
+ [
+ 0.09352066367864609,
+ 0.15001873672008514,
+ 0.09000030159950256,
+ 0.10285761207342148,
+ 0.035335153341293335,
+ 0.0922073945403099,
+ 0.018523549661040306,
+ 0.03119659051299095,
+ -0.09246083348989487,
+ -0.037830889225006104,
+ -0.12320800125598907,
+ -0.11105380952358246
+ ],
+ [
+ 0.03231861814856529,
+ 0.11165520548820496,
+ 0.03146477788686752,
+ 0.07725152373313904,
+ 0.07171043008565903,
+ 0.15221165120601654,
+ 0.058880098164081573,
+ 0.10495589673519135,
+ -0.0184634942561388,
+ 0.05710931867361069,
+ -0.043597739189863205,
+ -0.0011704942444339395
+ ],
+ [
+ 0.0628710612654686,
+ 0.1295747607946396,
+ 0.06014357507228851,
+ 0.08755858987569809,
+ 0.06231307238340378,
+ 0.13062003254890442,
+ 0.048115186393260956,
+ 0.0769951343536377,
+ 0.01481440756469965,
+ 0.07980957627296448,
+ -0.01146664097905159,
+ 0.015781186521053314
+ ],
+ [
+ 0.02746896632015705,
+ 0.018691735342144966,
+ 0.058608051389455795,
+ 0.06494835019111633,
+ 0.033147819340229034,
+ 0.021264400333166122,
+ 0.05459044873714447,
+ 0.05657658353447914,
+ 0.048656463623046875,
+ 0.03601812943816185,
+ 0.05913423374295235,
+ 0.05801016837358475
+ ],
+ [
+ 0.06031710281968117,
+ 0.015661295503377914,
+ 0.0678071454167366,
+ 0.05112661421298981,
+ 0.07517538219690323,
+ 0.03120845928788185,
+ 0.07400444895029068,
+ 0.05606979876756668,
+ 0.06921479851007462,
+ 0.029630688950419426,
+ 0.05848361551761627,
+ 0.041103530675172806
+ ],
+ [
+ 0.007075945846736431,
+ -0.007481235079467297,
+ 0.03803469240665436,
+ 0.054172102361917496,
+ 0.016573188826441765,
+ 0.002055448479950428,
+ 0.04110046848654747,
+ 0.056071650236845016,
+ 0.02539006806910038,
+ 0.012152970768511295,
+ 0.041547320783138275,
+ 0.0540786050260067
+ ],
+ [
+ 0.2169901579618454,
+ 0.19573576748371124,
+ 0.13506031036376953,
+ 0.171769917011261,
+ 0.1917288899421692,
+ 0.1700759083032608,
+ 0.11401035636663437,
+ 0.1476142406463623,
+ 0.2088213711977005,
+ 0.19070301949977875,
+ 0.138901025056839,
+ 0.1696886271238327
+ ],
+ [
+ -0.06730172038078308,
+ -0.01871911622583866,
+ -0.08471912145614624,
+ -0.06451212614774704,
+ -0.07660456746816635,
+ -0.026556527242064476,
+ -0.08240856975317001,
+ -0.059063296765089035,
+ -0.0586005374789238,
+ -0.011851834133267403,
+ -0.05294238403439522,
+ -0.028783956542611122
+ ],
+ [
+ -0.06594467163085938,
+ -0.04023434594273567,
+ -0.05397477746009827,
+ -0.040913719683885574,
+ -0.06208707019686699,
+ -0.03515097498893738,
+ -0.04517729952931404,
+ -0.02980121225118637,
+ -0.03832818195223808,
+ -0.012012233026325703,
+ -0.016248520463705063,
+ 0.0003055122506339103
+ ],
+ [
+ -0.00596569525077939,
+ 0.02090793289244175,
+ 0.00036170310340821743,
+ 0.02729453705251217,
+ -0.007709733210504055,
+ 0.01476181112229824,
+ -0.00327357673086226,
+ 0.019488535821437836,
+ 0.012850006110966206,
+ 0.029879936948418617,
+ 0.01460183784365654,
+ 0.03194494917988777
+ ],
+ [
+ -0.0015697324415668845,
+ -0.010920536704361439,
+ 0.011231125332415104,
+ -0.002971336478367448,
+ 0.012953057885169983,
+ 0.005338781513273716,
+ 0.02214047685265541,
+ 0.009154734201729298,
+ 0.010011233389377594,
+ 0.006098836660385132,
+ 0.014581647701561451,
+ 0.005372623447328806
+ ],
+ [
+ -0.012854021042585373,
+ 0.011863038875162601,
+ -0.0013875107979401946,
+ 0.03760281205177307,
+ 0.002505701268091798,
+ 0.023245319724082947,
+ 0.009420841000974178,
+ 0.043354474008083344,
+ 0.024566134437918663,
+ 0.04130033403635025,
+ 0.02450460009276867,
+ 0.051814280450344086
+ ],
+ [
+ 0.011988434009253979,
+ -0.010387538932263851,
+ 0.0002953045768663287,
+ -0.035757459700107574,
+ -0.0006189378909766674,
+ -0.01957632601261139,
+ -0.007361074909567833,
+ -0.03877578675746918,
+ -0.021378973498940468,
+ -0.037113092839717865,
+ -0.021142682060599327,
+ -0.046845436096191406
+ ],
+ [
+ 0.004361477680504322,
+ -0.001813434762880206,
+ 0.0003060020972043276,
+ -0.008216618560254574,
+ 0.003170188283547759,
+ -0.0016546652186661959,
+ 0.0014298983151093125,
+ -0.005871111992746592,
+ -0.0031278706155717373,
+ -0.006494482979178429,
+ -0.0022530308924615383,
+ -0.007610456086695194
+ ],
+ [
+ -0.015650618821382523,
+ -0.008374091237783432,
+ -0.020761262625455856,
+ -0.006753834895789623,
+ -0.010561833158135414,
+ -0.004759455565363169,
+ -0.017140844836831093,
+ -0.003961571492254734,
+ 0.0030405947472900152,
+ 0.008226056583225727,
+ -0.003792162984609604,
+ 0.007954205386340618
+ ],
+ [
+ -0.0036287603434175253,
+ -0.0057984585873782635,
+ -0.013128946535289288,
+ -0.015605788677930832,
+ -0.005019020289182663,
+ -0.006660441402345896,
+ -0.014211004599928856,
+ -0.016038373112678528,
+ -0.00843373965471983,
+ -0.009481443092226982,
+ -0.015925738960504532,
+ -0.017341813072562218
+ ],
+ [
+ 0.024799451231956482,
+ 0.03786415979266167,
+ 0.043592777103185654,
+ 0.044505417346954346,
+ 0.025305960327386856,
+ 0.036301422864198685,
+ 0.04276954010128975,
+ 0.04161131754517555,
+ 0.035451315343379974,
+ 0.04379434511065483,
+ 0.04869825765490532,
+ 0.04650479927659035
+ ],
+ [
+ 0.0010156224016100168,
+ -0.003605668665841222,
+ 0.002793652005493641,
+ -0.0060002971440553665,
+ 0.001485956134274602,
+ 0.0016110967844724655,
+ 0.00487983925268054,
+ 0.0010655251098796725,
+ 0.002363154198974371,
+ 0.006159558892250061,
+ 0.006894534919410944,
+ 0.00761735625565052
+ ],
+ [
+ -0.00989028625190258,
+ -0.007693048566579819,
+ -0.005013972986489534,
+ -0.004166752099990845,
+ -0.011340857483446598,
+ -0.009838343597948551,
+ -0.0070527661591768265,
+ -0.00656382879242301,
+ -0.006510042119771242,
+ -0.0062386454083025455,
+ -0.004144312348216772,
+ -0.0045488919131457806
+ ],
+ [
+ 0.0007720825960859656,
+ -0.0050218538381159306,
+ -0.0010583248222246766,
+ -0.006029705051332712,
+ 0.008309479802846909,
+ 0.0034250589087605476,
+ 0.006893445737659931,
+ 0.003156658262014389,
+ 0.007973856292665005,
+ 0.004382360260933638,
+ 0.008171267807483673,
+ 0.005685930605977774
+ ],
+ [
+ -0.0033922994043678045,
+ 0.004595596343278885,
+ -0.0029562979470938444,
+ 0.0036109904758632183,
+ 0.0010521572548896074,
+ 0.006223274394869804,
+ 0.0015403894940391183,
+ 0.005569476634263992,
+ 0.009277775883674622,
+ 0.011203019879758358,
+ 0.009717206470668316,
+ 0.010944867506623268
+ ]
+ ],
+ "bias": [
+ 0.5390540361404419,
+ 0.5248196721076965,
+ 0.5133297443389893,
+ 0.5151060819625854,
+ 0.4978678226470947,
+ 0.4825141429901123,
+ 0.4765666127204895,
+ 0.47454312443733215,
+ 0.4710156321525574,
+ 0.45429182052612305,
+ 0.45320016145706177,
+ 0.4500283896923065
+ ],
+ "weight_layout": "weight[c][j]: 24 rows x (3*k*k) columns",
+ "output_layout": "j=rgb*k*k+dy*k+dx; out[h*k+dy,w*k+dx,rgb]=sum_c v[c]*weight[c][j]+bias[j]",
+ "input": "normalized H3 latents, no extra mean/std transform",
+ "output": "RGB [0,1], clip after affine projection",
+ "precision": "float32 values serialized as round-trippable JSON numbers"
+}
diff --git a/freevideo_engine/macos_runtime.py b/freevideo_engine/macos_runtime.py
index bb9277c..618e5a1 100644
--- a/freevideo_engine/macos_runtime.py
+++ b/freevideo_engine/macos_runtime.py
@@ -12,6 +12,7 @@ from pathlib import Path
import os
import time
+from . import frame_preview
from .macos_conditions import BLOCK_SECONDS_SCOPE, runtime_conditions
from .sampling_progress import SamplingProgress
@@ -555,7 +556,10 @@ class Engine:
sampling_specs = [row for row in self.specs
if not row[2].startswith('token_refiner.refiner_blocks.')]
with self._sampling_weights(sampling_specs, retention) as residency, \
- progress.layers(self.model.transformer_blocks):
+ progress.layers(self.model.transformer_blocks), \
+ frame_preview.observing(latent_frames=canvas['latent_frames'], frame_h=height // 32,
+ frame_w=width // 32, step_offset=progress_offset,
+ total=progress_total if progress_total is not None else active_steps):
self.residency = residency
video, audio = sampler(self.model, prompt, tags, canvas['frames'], self.steps,
seed, 'mps', step_seconds=durations,
diff --git a/freevideo_engine/macos_stages.py b/freevideo_engine/macos_stages.py
index 94501a8..facbfea 100644
--- a/freevideo_engine/macos_stages.py
+++ b/freevideo_engine/macos_stages.py
@@ -327,6 +327,9 @@ def worker(value):
sampling_lifetime(resource)
if phase in ('first-pass', 'refinement'):
from .macos_runtime import Engine
+ from . import frame_preview
+ # The picture goes next to the video, where the page's report link reads it.
+ frame_preview.configure(Path(value['output']).parent)
refining = phase == 'refinement'
if refining and not sampling['enabled']:
raise ValueError('Refinement is absent from this sampling plan')
@@ -436,6 +439,9 @@ def worker(value):
result.update(error_type=type(error).__name__, error_message=str(error), exception=traceback.format_exc())
raise
finally:
+ if phase in ('first-pass', 'refinement'):
+ from . import frame_preview
+ frame_preview.clear()
if phase == 'decode':
result['conditions'].append(runtime_conditions())
if isinstance(result.get('decode'), dict):
diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.py
index c1f43d2..ea2a00f 100644
--- a/freevideo_engine/runtime.py
+++ b/freevideo_engine/runtime.py
@@ -547,6 +547,7 @@ class Engine:
budget_refresh=None, continuation=None):
from src.inference.render import load_prompt, generate_latents
from .geometry import geometry, sampler_for_canvas
+ from . import frame_preview
refining = initial_latents is not None
if continuation is not None:
from .continuation import validate_route
@@ -828,7 +829,10 @@ class Engine:
self.transformer, continuation, seed, self.device_backend.device,
**({'video_offset': continuation_offset} if continuation_offset else {}),
**({'audio_offset': continuation_audio_offset} if continuation_audio_offset else {})) as prefix, \
- (watch.layers(self.transformer.transformer_blocks) if watch is not None else nullcontext()):
+ (watch.layers(self.transformer.transformer_blocks) if watch is not None else nullcontext()), \
+ frame_preview.observing(latent_frames=canvas['latent_frames'], frame_h=height // 32,
+ frame_w=width // 32, step_offset=progress_offset,
+ total=progress_total if progress_total is not None else active_steps):
latents, audio = generate_latents(self.transformer, prompt, tags, frames,
self.steps, seed, self.device_backend.device, step_seconds=step_seconds,
conditions=conditions, **sampling_kwargs)
diff --git a/freevideo_engine/step_grid.py b/freevideo_engine/step_grid.py
index a748276..a7babfc 100644
--- a/freevideo_engine/step_grid.py
+++ b/freevideo_engine/step_grid.py
@@ -44,6 +44,13 @@ def _scheduler_class():
sigmas = self._shift * base / (1 + (self._shift - 1) * base)
super().set_timesteps(num_inference_steps, device=device, sigmas=sigmas)
+ def step(self, model_output, timestep, sample, return_dict=True):
+ # Read-only: the frame preview looks at the prediction, then the
+ # upstream update runs exactly as before.
+ from .frame_preview import observe
+ observe(model_output, timestep, sample)
+ return super().step(model_output, timestep, sample, return_dict=return_dict)
+
return Scheduler
diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.py
index fb30a15..0e509a6 100644
--- a/freevideo_engine/worker.py
+++ b/freevideo_engine/worker.py
@@ -305,6 +305,9 @@ def generate(request, resident=None):
decode_read_ahead.start(drive_idle=getattr(engine, 'drive_idle', False) is True)
from .sampling_memory import SamplingMemory
memory_diagnostics = SamplingMemory(torch, Path(request['output']).with_suffix('.sampling-memory.json')).start()
+ from . import frame_preview
+ if not request.get('capacity_trial', False):
+ frame_preview.configure(Path(request['output']).parent)
def sample_finalize_phase(name):
metrics.update(phase='sample_finalize', sample_finalize_phase=name)
save(request['metrics'], metrics)
@@ -586,6 +589,7 @@ def generate(request, resident=None):
gpu_reserve_bytes=request.get('gpu_reserve_bytes', 0),
budget_refresh=refresh_budget if live_budget is not None else None)
finally:
+ frame_preview.clear()
metrics['sampling_memory'] = memory_diagnostics.close()
metrics.update(sampled)
metrics.pop('sample_metrics_scope', None)
diff --git a/pyproject.toml b/pyproject.toml
index 78fdd3f..530629b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -33,4 +33,4 @@ include = ["freevideo_engine*"]
[tool.setuptools.package-data]
"freevideo_engine.prompt_vlm" = ["model.json"]
"freevideo_engine.image_gen" = ["image_models.json", "licenses/NOTICE.txt"]
-freevideo_engine = ["stage_estimate_params.json", "build-version.txt", "build-identity.json", "release_notes.json", "dependencies.json", "model_files.json", "model_shares.json", "prepared_models.json", "macos_reference_catalog.json", "superseded_tables.json", "bootstrap_versions.json", "curl_windows.json", "git_linux.json", "gcc_linux.json", "uv_downloads.json", "torch_downloads.json", "test_prompts.json", "windows_bootstrap.ps1", "assets/*.png", "assets/*.ico", "launcher/*.qml", "launcher/licenses/*.txt", "licenses/*.txt", "licenses/runtime/*.txt", "subtitle_pack.json"]
+freevideo_engine = ["stage_estimate_params.json", "build-version.txt", "build-identity.json", "release_notes.json", "dependencies.json", "model_files.json", "model_shares.json", "prepared_models.json", "macos_reference_catalog.json", "superseded_tables.json", "bootstrap_versions.json", "curl_windows.json", "git_linux.json", "gcc_linux.json", "uv_downloads.json", "torch_downloads.json", "test_prompts.json", "windows_bootstrap.ps1", "assets/*.png", "assets/*.ico", "launcher/*.qml", "launcher/licenses/*.txt", "licenses/*.txt", "licenses/runtime/*.txt", "subtitle_pack.json", "frame_preview_weights.json"]
diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs
index f6eeaaa..3c170a7 100644
--- a/scripts/test_freevideo_entry.mjs
+++ b/scripts/test_freevideo_entry.mjs
@@ -361,9 +361,9 @@ test('main browser entry registers both views and preserves node hooks', async t
removalNode = new GenerateNode(); removalNode.id = 10; removalNode.onNodeCreated();
removalNode.freevideoShowProgress({phase: 'load', received_at: 0});
const progress = progressView;
- assert.deepEqual(progress.element.children.slice(0, 8).map(child => child.className), [
+ assert.deepEqual(progress.element.children.slice(0, 9).map(child => child.className), [
'fv-generation-heading', 'fv-generation-track', 'fv-generation-label',
- 'fv-generation-mini', 'fv-generation-times', 'fv-generation-compatibility', 'fv-generation-status', 'fv-generation-live']);
+ 'fv-generation-mini', 'fv-generation-frames', 'fv-generation-times', 'fv-generation-compatibility', 'fv-generation-status', 'fv-generation-live']);
const activity = progress.snapshot().label;
removalNode.freevideoShowProgress({compatibility: {level: 2, name_en: 'Compatible', name_zh: '兼容'}});
assert.equal(progress.snapshot().label, activity, 'The node must not replace the activity for settings-only events');
diff --git a/web/generation_progress.css b/web/generation_progress.css
index c180731..8d2de7d 100644
--- a/web/generation_progress.css
+++ b/web/generation_progress.css
@@ -24,6 +24,11 @@
.fv-generation-status{box-sizing:border-box;width:100%;flex:none;margin-top:10px;font-size:12px;line-height:18px;color:var(--fv-muted,#a2abba);text-align:center;text-wrap:balance}
.fv-generation-compatibility{box-sizing:border-box;width:100%;flex:none;margin-top:10px;font-size:12px;line-height:18px;color:var(--fv-ink,#e8edf5);text-align:center;text-wrap:balance}
.fv-generation-compatibility[hidden]{display:none!important}
+.fv-generation-frames{display:block;box-sizing:border-box;width:auto;max-width:100%;max-height:min(30vh,200px);margin:12px auto 0;border-radius:var(--fv-r-sm,6px);object-fit:contain;background:var(--fv-raised,#212a37)}
+.fv-studio .fv-stage .fv-generation-frames{width:auto;height:auto}
+.fv-generation-frames[data-wide=true],.fv-studio .fv-stage .fv-generation-frames[data-wide=true]{height:64px}
+.fv-generation-frames[hidden]{display:none!important}
+.fv-studio .fv-stage[data-short=true] .fv-generation-frames{display:none!important}
.fv-generation-live{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}
/* Studio shows progress with the preview's rising wave, so its bar stays
hidden (studio.css); the node view keeps the bar under the percentage. */
diff --git a/web/generation_progress.js b/web/generation_progress.js
index 38d1c67..5d2b23f 100644
--- a/web/generation_progress.js
+++ b/web/generation_progress.js
@@ -418,6 +418,9 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
heading.append(count);
const track = el('div', 'fv-generation-track'), fill = el('div', 'fv-generation-fill');
track.setAttribute('role', 'progressbar'); track.setAttribute('aria-valuemin', '0'); track.append(fill);
+ // The sampler's newest coarse frames; decorative, so it carries no text.
+ const frames = el('img', 'fv-generation-frames'); frames.alt = ''; frames.hidden = true;
+ frames.decoding = 'async'; frames.setAttribute('aria-hidden', 'true'); frames.draggable = false;
const times = el('div', 'fv-generation-times');
const elapsed = el('span', ''), eta = el('span', ''); times.append(elapsed, eta);
const status = el('div', 'fv-generation-status'); status.hidden = true;
@@ -428,7 +431,7 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
stall.setAttribute('role', 'status');
const stallText = el('span', ''); stall.append(stallText);
const trims = new Map();
- element.append(heading, track, label, mini, times, compatibilityNote, status, live);
+ element.append(heading, track, label, mini, frames, times, compatibilityNote, status, live);
let recovery = '', lowMemory = false, compatibility = null, samplingPlan = {}, secondPass = false, references = false, splitFailed = null;
let hasHeartbeat = false;
// Mac: the unified-memory notice of this request, and whether its first pass has ended.
@@ -481,6 +484,47 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
|| (message.reset === true && !message.phase);
const diagnostic = createDiagnosticReportControl(t, {api});
const {report, updateReport, fetchReport, downloadReport} = diagnostic;
+ // The newest frame picture. Any failure leaves the page as it was without one.
+ // `framesToken` changes whenever a pending fetch stops being wanted, so a late answer is dropped.
+ let framesKey = '', framesUrl = null, framesLoading = null, framesToken = 0;
+ function clearFrames() {
+ framesKey = ''; framesLoading = null; framesToken++; frames.hidden = true;
+ if (framesUrl) { URL.revokeObjectURL(framesUrl); framesUrl = null; }
+ frames.removeAttribute('src');
+ }
+ // In a wide column each frame is 64 px high; a narrow one keeps the picture's own size.
+ function fitFrames() {
+ const width = (element.parentElement || element).clientWidth;
+ frames.dataset.wide = width > 480 ? 'true' : 'false';
+ }
+ function updateFrames(message, id) {
+ const value = message.frame_preview;
+ fitFrames();
+ const usable = value && typeof value === 'object' && Number.isInteger(value.serial) && value.serial > 0
+ && Number.isInteger(value.frames) && value.frames > 0 && value.frames <= 8;
+ if (!usable || !id || ['complete', 'failed', 'cancelled'].includes(message.phase)) { if (framesKey || framesLoading) clearFrames(); return; }
+ const key = `${id}:${value.serial}`;
+ if (key === framesKey || key === framesLoading) return;
+ framesLoading = key;
+ const token = ++framesToken;
+ const path = `/freevideo/frame-preview/${id}`;
+ (async () => {
+ try {
+ const response = await (api ? api.fetchApi(path) : fetch(path));
+ if (!response.ok) throw new Error('No picture');
+ const blob = await response.blob();
+ if (framesToken !== token) return;
+ const url = URL.createObjectURL(blob);
+ const old = framesUrl;
+ frames.onload = () => { fitFrames(); if (framesUrl === url) frames.hidden = false; try { onLayout?.(); } catch {} };
+ frames.onerror = () => { if (framesUrl === url) clearFrames(); };
+ framesUrl = url; framesKey = key; frames.src = url;
+ if (old) URL.revokeObjectURL(old);
+ } catch {
+ if (framesToken === token) clearFrames();
+ }
+ })();
+ }
const hasCount = value => Number.isInteger(value.total) && value.total > 0 && Number.isInteger(value.done)
&& value.done >= 0 && value.done <= value.total;
@@ -830,7 +874,7 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
// A finished first-pass preview is not the finished video.
const savedText = () => state.label === 'Preview saved' ? t('Preview saved', '预览已保存') : t('Video saved', '视频已保存');
function update(message) {
- updateReport(message);
+ updateFrames(message, updateReport(message));
// Older servers may still forward this diagnostic-only event. It is
// not a stage change or something the user needs to act on.
if (message.warning === 'ram_budget_warning' && !message.phase) return;
@@ -988,6 +1032,7 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
tick(); if (timer === null) timer = setInterval(tick, 250);
}
function hide() {
+ clearFrames();
element.hidden = true; status.hidden = true; recovery = ''; placeholder = false; elapsedLead = 0; trims.clear(); lowMemory = false; compatibility = null; references = false; hasHeartbeat = false; splitFailed = null;
compatibilityNote.hidden = true; compatibilityNote.textContent = '';
memoryTight = null; firstPassOver = false;