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.
Mac: a first pass stopped by Metal or memory continues after its last completed step
Bowen Xuef8fd10c1d7b8
diff --git a/freevideo_engine/geometry.py b/freevideo_engine/geometry.pyindex a1014d6..e51d49f 100644--- a/freevideo_engine/geometry.py+++ b/freevideo_engine/geometry.py@@ -24,7 +24,7 @@ def geometry(width=1344, height=768, frames=None, seconds=None):alignment='Pinned H3 VAE: round up to 17*n+5 frames; no resampling or hidden resolution reduction.')-def sampler_for_canvas(sampler, width, height):+def sampler_for_canvas(sampler, width, height, scheduler=None):"""Bind canvas constants in an isolated globals dict, preserving upstream code.Engine.sample supplies no_grad. Never edit the upstream file or mutate its@@ -32,7 +32,10 @@ def sampler_for_canvas(sampler, width, height):The upstream sampler builds its schedulers by name; it gets the engine's,whose step grid is the one the modulation tables were made with."""- from .step_grid import scheduler+ from .step_grid import scheduler as engine_scheduler+ # A caller may supply a factory that adds a start step or an observer to the+ # same engine scheduler; the default is that scheduler itself.+ scheduler = scheduler or engine_scheduleroriginal = inspect.unwrap(sampler)bound = types.FunctionType(original.__code__,dict(original.__globals__, LATENT_H=height // 16, LATENT_W=width // 16,diff --git a/freevideo_engine/macos_runtime.py b/freevideo_engine/macos_runtime.pyindex 694e5a0..19a4185 100644--- a/freevideo_engine/macos_runtime.py+++ b/freevideo_engine/macos_runtime.py@@ -495,7 +495,7 @@ class Engine:return resultdef _sample(self, conditioning, seed, *, width, height, frames, progress_offset=0, progress_total=None,- initial_latents=None, refine_steps=None, refine_schedule=None, continuation=None):+ initial_latents=None, refine_steps=None, refine_schedule=None, continuation=None, step_state=None):import torchfrom .geometry import geometry, sampler_for_canvasfrom .system import system_memory@@ -531,9 +531,19 @@ class Engine:from .reference_sampler import generate_latentsactive_steps = refine_steps if refining else self.stepscanvas = geometry(width, height, frames=frames)- sampler = sampler_for_canvas(generate_latents, width, height)- progress = MacSamplingProgress(active_steps, len(self.model.transformer_blocks),- offset=progress_offset, total=progress_total)+ # Only the plain first pass without a step cache saves its steps; a retry+ # of it continues after the last saved one.+ resumable = (step_state is not None and not refining and self.task == 't2va'+ and continuation is None and not self.step_cache)+ resumed = step_state.load() if resumable else None+ start = step_state.start if resumed else 0+ sampler = sampler_for_canvas(generate_latents, width, height,+ scheduler=step_state.scheduler if resumable else None)+ progress = MacSamplingProgress(active_steps - start, len(self.model.transformer_blocks),+ offset=progress_offset + start,+ total=progress_total if progress_total is not None else active_steps + progress_offset)+ if start:+ print(json.dumps(dict(event='step_resume', completed_steps=start, total=active_steps)), flush=True)prefix = Noneclass StepTimes(list):def append(owner, duration):@@ -541,6 +551,8 @@ class Engine:prefix.restore_video()super().append(duration)progress.complete(duration)+ if resumable:+ step_state.completed(duration)durations = StepTimes()previous_calls = dict(self.attention.backend_calls)previous_kernel_calls = {name: dict(counts) for name, counts in@@ -568,7 +580,7 @@ class Engine:+ 2 * continuation['audio'].shape[2])self._plan_compute(canvas, prompt.shape[0])previous_block_calls = self._block_metrics()- self.cursor.reset(self.steps - refine_steps if refining and refine_schedule is None else 0)+ self.cursor.reset(self.steps - refine_steps if refining and refine_schedule is None else start)progress.start()resident = getattr(self, 'resident_bytes', 0)retention = (dict(resident_bytes=resident, working_reserve_bytes=self.reserve_bytes)@@ -589,7 +601,7 @@ class Engine:audio_offset=canvas.get('reference_audio_tokens', 0)) as prefix, \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,+ frame_w=width // 32, step_offset=progress_offset + start,total=progress_total if progress_total is not None else active_steps):self.residency = residencyfrom .step_cache import begin_pass, end_pass@@ -597,12 +609,16 @@ class Engine:if not refining and self.step_cache:begin_pass(self.model, active_steps, self.step_cache)try:+ if resumable:+ step_state.attach(self.model, self.backend.device)video, audio = sampler(self.model, prompt, tags, canvas['frames'], self.steps,seed, self.backend.device, step_seconds=durations,**(dict(conditions=conditions) if conditions else {}),**(dict(initial_latents=initial_latents, refine_steps=refine_steps, refine_schedule=refine_schedule)if refining else {}))finally:+ if resumable:+ step_state.detach()step_cache = end_pass(self.model)if prefix is not None:video, audio = prefix.finish(video, audio)@@ -628,7 +644,8 @@ class Engine:max_bytes=max(self.allocator_limits)),attention_calls={name: value - previous_calls[name]for name, value in self.attention.backend_calls.items()},- step_seconds=list(durations), step_cache=step_cache,+ step_seconds=list(step_state.previous_seconds if resumable else durations), step_cache=step_cache,+ **(dict(resumed_from_step=start) if start else {}),block_seconds=progress.block_seconds, block_seconds_scope=BLOCK_SECONDS_SCOPE,conditions=progress.conditions,load_seconds=self.load_seconds, residency=self._residency_metrics(residency, previous_residency),diff --git a/freevideo_engine/macos_stages.py b/freevideo_engine/macos_stages.pyindex b5df0c9..43b1328 100644--- a/freevideo_engine/macos_stages.py+++ b/freevideo_engine/macos_stages.py@@ -12,7 +12,7 @@ import sysimport timeimport traceback-from . import processes+from . import processes, step_resumefrom .locking import LOCK_ENV, runtime_lockfrom .monitoring import save@@ -182,6 +182,9 @@ def run(value):continueresult['phase'] = stagesave(path, result)+ if stage == 'first-pass':+ # Steps saved by an earlier request's pass must never be resumed.+ step_resume.discard(artifacts)request = artifacts / (stage + '-request.json')receipt = artifacts / (stage + '-result.json')while True:@@ -198,6 +201,13 @@ def run(value):pass_fds=(descriptor,), check=True)except subprocess.CalledProcessError:failed = read_receipt(receipt)+ if failed.get('error_type') == 'ResumeRejected' and (artifacts / 'first-pass-step.pt').is_file():+ # The saved step did not reach the sampler. Start the pass+ # over without spending the retry.+ step_resume.discard(artifacts)+ result.setdefault('resume_rejections', []).append(failed.get('error_message'))+ receipt.unlink(missing_ok=True)+ continueif not memory_exhausted(stage, failed):raisemetal = METAL_FAILURE in str(failed.get('error_message', ''))@@ -246,6 +256,8 @@ def run(value):if stage in ('first-pass', 'refinement'):# A later pass's failure is not a consecutive failed retry.metal_retry = False+ if stage == 'first-pass':+ step_resume.discard(artifacts)breakif stage == 'first-pass' and retained_joined:continue@@ -440,6 +452,14 @@ def worker(value):# A memory retry keeps each pass in its own process.admission = (joined_admission(engine, value) if not refining and not retryand value.get('preview') is not True else dict(selected=False))+ # A first pass saves each step so that a retry can continue after the last one.+ step_state = None+ if not refining and not admission['selected']:+ try:+ step_state = step_resume.StepState(step_resume.step_path(artifacts),+ first_pass_identity(value), sampling['base_steps'])+ except (OSError, KeyError, ValueError):+ step_state = Noneresult['sampling_admission'] = admissionif admission['selected']:result.update(joined_sampling=True, sampling_passes=[], latent_save_seconds=0.)@@ -471,6 +491,7 @@ def worker(value):else:video, audio, measured = engine.sample(value['conditioning'],value['seed'] + (sampling['restart_seed_offset'] if refining else 0),+ **(dict(step_state=step_state) if step_state is not None else {}),**sampling['second' if refining else 'first'],**(dict(continuation=chain.load(continuation, 'final' if refining else 'first'))if continuation is not None else {}),diff --git a/freevideo_engine/step_grid.py b/freevideo_engine/step_grid.pyindex a7babfc..ab2f919 100644--- a/freevideo_engine/step_grid.py+++ b/freevideo_engine/step_grid.py@@ -37,23 +37,46 @@ def _scheduler_class():from diffusers import MiniMaxH3Schedulerclass Scheduler(MiniMaxH3Scheduler):+ # A request resuming after step `start` iterates only the steps still to+ # run, on the unchanged sigma grid; `observer` sees every update.+ start = 0+ observer = None+def set_timesteps(self, num_inference_steps=None, device=None, sigmas=None):if sigmas is None and type(num_inference_steps) is int and num_inference_steps >= 1:base = uniform(num_inference_steps)# The scheduler's own shift, applied to a grid it did not build.sigmas = self._shift * base / (1 + (self._shift - 1) * base)super().set_timesteps(num_inference_steps, device=device, sigmas=sigmas)+ if self.start:+ if not 0 < self.start < len(self.timesteps):+ raise ValueError('A resumed schedule must start inside its steps')+ # The step index then comes from this begin index; the sigmas keep+ # their original positions.+ self.timesteps = self.timesteps[self.start:]+ self.set_begin_index(self.start)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 observeobserve(model_output, timestep, sample)- return super().step(model_output, timestep, sample, return_dict=return_dict)+ result = super().step(model_output, timestep, sample, return_dict=return_dict)+ if self.observer is not None:+ self.observer(self, sample, result[0] if isinstance(result, tuple) else result.prev_sample)+ return resultreturn Scheduler-def scheduler(shift=12.):- """A MiniMaxH3Scheduler whose step grid is `uniform`; explicit sigmas pass through."""- return _scheduler_class()(shift=shift)+def scheduler(shift=12., *, start=0, observer=None):+ """A MiniMaxH3Scheduler whose step grid is `uniform`; explicit sigmas pass through.++ `start` resumes a schedule after that many completed steps; `observer(scheduler,+ sample, updated)` is called after each update."""+ made = _scheduler_class()(shift=shift)+ if start:+ made.start = start+ if observer is not None:+ made.observer = observer+ return madediff --git a/freevideo_engine/step_resume.py b/freevideo_engine/step_resume.pynew file mode 100644index 0000000..0d1680c--- /dev/null+++ b/freevideo_engine/step_resume.py@@ -0,0 +1,142 @@+"""Resume a native first pass from its last completed sampling step.++A sampling pass that Metal or the unified-memory allocator stops is attempted+again in a fresh process. Without a saved state that attempt repeats every+completed step, which on a slow Mac is most of the lost time. This module saves+the generated video and audio rows after every step of the plain first pass and+lets the retry continue from them.++The vendored sampler is not changed. It is bound to the engine's scheduler, so+a resumed scheduler iterates only the remaining steps on the original sigma grid+(the step index comes from the begin index), the scheduler's observer keeps the+rows each update returns, and a one-shot forward hook writes the saved rows into+the sampler's input tensors before the first resumed forward. That first update+then verifies that the saved rows are what the sampler stepped from; if the+sampler no longer shares those tensors the pass stops with `ResumeRejected` and+the controller starts the pass over.++Only the plain text-to-video pass without a step cache or continuation is+resumable. Every other pass behaves as before.+"""+import os+from pathlib import Path++VERSION = 1+VIDEO_SHIFT, AUDIO_SHIFT = 12., 3. # the vendored sampler's defaults+++class ResumeRejected(RuntimeError):+ """The saved step could not be applied; the pass must start from step one."""+++class StepState:+ """Saves the rows after each step, and applies a matching saved step once."""++ def __init__(self, path, identity, steps):+ self.path, self.identity, self.steps = Path(path), identity, steps+ self.saved = self.resume = None+ self.start = 0+ self.previous_seconds = []+ self.finished = 0+ self._rows = {}+ self._hook = None+ self._verified = set()+ self.failed = None++ def load(self):+ """The saved state when it belongs to this pass, else None."""+ import torch+ try:+ saved = torch.load(self.path, map_location='cpu', weights_only=True)+ except Exception:+ # A missing, truncated or foreign file is just no saved step.+ return None+ if not isinstance(saved, dict):+ return None+ done = saved.get('completed')+ if (saved.get('version') != VERSION or saved.get('identity') != self.identity+ or saved.get('steps') != self.steps or type(done) is not int+ or not 0 < done < self.steps or len(saved.get('step_seconds', ())) != done+ or not all(isinstance(saved.get(key), torch.Tensor) and bool(saved[key].isfinite().all())+ for key in ('video', 'audio'))):+ return None+ self.resume, self.start = saved, done+ self.previous_seconds = [float(seconds) for seconds in saved['step_seconds']]+ self.finished = done+ return saved++ def scheduler(self, shift=12., **options):+ """The engine scheduler for the sampler: resumed, and observed."""+ from .step_grid import scheduler+ return scheduler(shift, start=self.start, observer=self._observe, **options)++ def _observe(self, scheduler, sample, updated):+ kind = {VIDEO_SHIFT: 'video', AUDIO_SHIFT: 'audio'}.get(scheduler.shift)+ if kind is None:+ self.failed = 'unknown schedule'+ return+ if self.resume is not None and kind not in self._verified:+ import torch+ # `sample` is the sampler's own tensor, overwritten right after this+ # update; compare it now, before the sampler stores the result.+ if not torch.equal(sample.detach().cpu(), self.resume[kind]):+ raise ResumeRejected('The saved ' + kind + ' rows were not the sampler input')+ self._verified.add(kind)+ self._rows[kind] = updated++ def attach(self, model, device):+ """Write the saved rows into the first forward's inputs; no-op without a saved step."""+ if self.resume is None:+ return+ def inject(module, args, kwargs):+ self._hook.remove()+ for name, key in (('hidden_states', 'video'), ('audio_hidden_states', 'audio')):+ target, rows = kwargs[name][0], self.resume[key]+ if tuple(target.shape) != tuple(rows.shape):+ raise ResumeRejected('The saved rows do not fit the sampler input')+ target.copy_(rows.to(device=target.device, dtype=target.dtype))+ self._hook = model.register_forward_pre_hook(inject, with_kwargs=True)++ def detach(self):+ if self._hook is not None:+ self._hook.remove()+ self._hook = None++ def completed(self, seconds):+ """A step finished: keep its rows so a retry can continue after it."""+ import torch+ self.finished += 1+ self.previous_seconds.append(float(seconds))+ if self.failed or self.finished >= self.steps or set(self._rows) != {'video', 'audio'}:+ return+ temporary = self.path.with_name(self.path.name + '.partial')+ try:+ torch.save(dict(version=VERSION, identity=self.identity, steps=self.steps, completed=self.finished,+ step_seconds=list(self.previous_seconds),+ video=self._rows['video'].detach().cpu(), audio=self._rows['audio'].detach().cpu()),+ temporary)+ os.replace(temporary, self.path)+ except Exception as error:+ # Saving is an optimization: without it a retry starts over. A failed+ # write is an OSError from the rename but a RuntimeError from torch.save.+ self.failed = str(error) or type(error).__name__+ try:+ temporary.unlink(missing_ok=True)+ except OSError:+ pass+ self._rows = {}++ def clear(self):+ for path in (self.path, self.path.with_name(self.path.name + '.partial')):+ path.unlink(missing_ok=True)+++def step_path(artifacts):+ return Path(artifacts) / 'first-pass-step.pt'+++def discard(artifacts):+ """Remove a pass's saved step; a new pass must never meet an older one's."""+ path = step_path(artifacts)+ for stale in (path, path.with_name(path.name + '.partial')):+ stale.unlink(missing_ok=True)