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.
Continue in pageable memory when a copy through a locked residual or attention readout buffer is...
Bowen Xue7d50461950f7
diff --git a/freevideo_engine/activation_staging.py b/freevideo_engine/activation_staging.pyindex 9d2f2cd..48c8c09 100644--- a/freevideo_engine/activation_staging.py+++ b/freevideo_engine/activation_staging.py@@ -1,6 +1,75 @@"""Contiguous D2H head groups with double-buffered CPU projection tiles."""+import collectionsimport torch+# Every refused locked-page copy of this process, residual stream and head+# readouts alike, so a report shows whether the fallback fired, which copy was+# refused and what CUDA said. The newest entries are kept; the count is exact.+_REFUSED = collections.deque(maxlen=32)+_refused_total = 0+++def record_refusal(source, copy, error):+ global _refused_total+ lines = str(error).strip().splitlines()+ _REFUSED.append(dict(source=source, copy=copy, error=(lines[0] if lines else '')[:200]))+ _refused_total += 1+++def refusals_mark():+ return _refused_total+++def refusals_since(mark):+ """Refusals recorded after `mark`, as plain dicts for the sampling metrics."""+ count = min(_refused_total - mark, len(_REFUSED))+ return [dict(row) for row in list(_REFUSED)[len(_REFUSED) - count:]] if count > 0 else []+++class LockedCopies:+ """Asynchronous copies through page-locked buffers that continue in pageable memory.++ Windows can refuse a queued copy with "invalid argument" when the system+ takes locked pages back. The queued work is finished first, so a sticky+ error is raised as itself rather than hidden by the retry. The copy then+ goes through a pageable temporary, which holds the same bytes, and the+ remaining copies of these buffers skip the locked path. A failed device+ allocation is not a refusal: it is raised for the caller to recover from,+ and the buffers stay locked.+ """++ def __init__(self):+ self.locked = True+ self.fallbacks = 0++ def _leave(self, device, copy, error):+ record_refusal('readout', copy, error)+ if device.type == 'cuda':+ torch.cuda.synchronize(device)+ self.locked = False+ self.fallbacks += 1++ def to_host(self, destination, source):+ if self.locked:+ try:+ destination.copy_(source, non_blocking=True)+ return+ except torch.cuda.OutOfMemoryError:+ raise+ except RuntimeError as error:+ self._leave(source.device, 'to_host', error)+ destination.copy_(source.to('cpu'))++ def to_device(self, source, device):+ if self.locked:+ try:+ return source.to(device, non_blocking=True)+ except torch.cuda.OutOfMemoryError:+ raise+ except RuntimeError as error:+ self._leave(torch.device(device), 'to_device', error)+ return source.clone().to(device)+class HeadReadouts:def __init__(self, rows, head_widths, dtype, tile_rows):@@ -11,6 +80,7 @@ class HeadReadouts:self.groups = [torch.empty((self.capacity, width), dtype=dtype, pin_memory=True) for width in head_widths]self.tiles = [torch.empty((tile_rows, sum(head_widths)), dtype=dtype, pin_memory=True) for _ in range(2)]self.events = [None, None]+ self.copies = LockedCopies()def supports(self, rows, head_widths, dtype, tile_rows):return rows <= self.capacity and tuple(head_widths) == self.widths and dtype == self.dtype and tile_rows == self.tile_rows@@ -18,7 +88,7 @@ class HeadReadouts:def store(self, group, values):if values.shape[1] != self.widths[group] or not values.is_contiguous():raise ValueError('Head readouts must be contiguous [rows, head channels]')- self.groups[group][:len(values)].copy_(values, non_blocking=True)+ self.copies.to_host(self.groups[group][:len(values)], values)def project(self, module, output, rows):# The caller synchronizes once after all D2H groups have been written.@@ -33,7 +103,7 @@ class HeadReadouts:for group, width in zip(self.groups, self.widths):tile[:, offset:offset + width].copy_(group[start:start + count])offset += width- device_values = tile.to(output.device, non_blocking=True)+ device_values = self.copies.to_device(tile, output.device)done = torch.cuda.Event()done.record(stream)self.events[slot] = donediff --git a/freevideo_engine/decode_resume.py b/freevideo_engine/decode_resume.pyindex 635497f..1f2eeeb 100644--- a/freevideo_engine/decode_resume.py+++ b/freevideo_engine/decode_resume.py@@ -20,7 +20,7 @@ DECODER_PLACEMENT = frozenset(('offload', 'prefetch', 'preload', 'pin_weights',COMPUTE_PARTITION = frozenset(('head_chunk', 'window_batch', 'ff_chunk', 'projection_chunk', 'head_parallelism','attention_cpu_outputs', 'grouped_attention_outputs', 'fp8_ff_recompute', 'residual_offload', 'query_chunk'))SAMPLE_FIELDS = ('config', 'sample_seconds', 'step_seconds', 'finite_latents', 'geometry',- 'conditioning_info', 'conditioning_shape', 'offload', 'residual_offload_steps',+ 'conditioning_info', 'conditioning_shape', 'offload', 'residual_offload_steps', 'locked_copy_refusals','attention_backend_calls', 'head_execution', 'text_refinement', 'sampling_memory','load_seconds', 'load_breakdown', 'load_peak_allocated_bytes', 'load_peak_reserved_bytes','torch_peak_allocated_bytes', 'torch_peak_reserved_bytes', 'latent_save_seconds', 'sample_metrics_scope',diff --git a/freevideo_engine/head_chunk.py b/freevideo_engine/head_chunk.pyindex ccf61b8..246a06b 100644--- a/freevideo_engine/head_chunk.py+++ b/freevideo_engine/head_chunk.py@@ -59,7 +59,7 @@ def release_readouts(policy):a 16 GiB machine failed cudaHostAlloc at the refine pass's first layer."""held = [getattr(policy, name, None) for name in ('group_readouts', 'host_outputs')]- for name in ('group_readouts', 'host_outputs', 'host_output_key'):+ for name in ('group_readouts', 'host_outputs', 'host_output_key', 'host_copies'):if hasattr(policy, name):delattr(policy, name)if any(value is not None for value in held):@@ -135,12 +135,14 @@ def install_head_chunks(transformer, policy, chunk, cpu_outputs=False, projectiofor rows in (len(x), linear_shape[0]))soft, linear = policy.group_readoutselif cpu_outputs:+ from .activation_staging import LockedCopieskey = (soft_shape, linear_shape, x.dtype)if getattr(policy, 'host_output_key', None) != key:release_readouts(policy)policy.host_outputs = (torch.empty(soft_shape, dtype=x.dtype, pin_memory=True),torch.empty(linear_shape, dtype=x.dtype, pin_memory=True))policy.host_output_key = key+ policy.host_copies = LockedCopies()soft, linear = policy.host_outputselif reuses_input(attn, x, projections):# Measured second-pass peak: the head groups, with x, both output planes,@@ -201,8 +203,10 @@ def install_head_chunks(transformer, policy, chunk, cpu_outputs=False, projectiosoft.store(start // chunk, attended.flatten(1))elif taken:soft.write(channels, attended.flatten(1))+ elif cpu_outputs:+ policy.host_copies.to_host(soft[:, channels], attended.flatten(1))else:- soft[:, channels].copy_(attended.flatten(1), non_blocking=cpu_outputs)+ soft[:, channels].copy_(attended.flatten(1))del attendedif not taken:beta = torch.sigmoid(F.linear(x[video], branch.beta_proj.weight[heads]))@@ -221,8 +225,10 @@ def install_head_chunks(transformer, policy, chunk, cpu_outputs=False, projectiolinear_scale.update(readout)if grouped_outputs:linear.store(start // chunk, readout.contiguous())+ elif cpu_outputs:+ policy.host_copies.to_host(linear[:, linear_channels], readout)else:- linear[:, linear_channels].copy_(readout, non_blocking=cpu_outputs)+ linear[:, linear_channels].copy_(readout)del raw, readout, gate, beta, text_beta# Keep the exact projection/head/window shapes. Merely widening the@@ -293,13 +299,13 @@ def install_head_chunks(transformer, policy, chunk, cpu_outputs=False, projectioout = x.new_empty((len(x), output_width))for row in range(0, len(x), projection_chunk):rows = slice(row, row + projection_chunk)- part = soft[rows].to(x.device, non_blocking=True)+ part = policy.host_copies.to_device(soft[rows], x.device)scale = row_scale(soft_scale, rows) if soft_scale is not None else Noneout[rows] = orig.to_out[1](project_with_scale(orig.to_out[0], part, scale))del partfor row in range(0, len(linear), projection_chunk):rows = slice(row, row + projection_chunk)- part = linear[rows].to(x.device, non_blocking=True)+ part = policy.host_copies.to_device(linear[rows], x.device)scale = row_scale(linear_scale, rows) if linear_scale is not None else Noneout[video][rows].add_(project_with_scale(attn.to_out_linear, part, scale))del partdiff --git a/freevideo_engine/pass_configuration.py b/freevideo_engine/pass_configuration.pyindex 1785e6b..191bf53 100644--- a/freevideo_engine/pass_configuration.py+++ b/freevideo_engine/pass_configuration.py@@ -1,4 +1,5 @@"""Change pass-local compute tiling while preserving loaded model weights."""+import sysfrom contextlib import contextmanager@@ -62,6 +63,20 @@ def configuration(engine, selected):attention.current_plan = attention.offsets = attention.batches = None# Canvas-specific host buffers must not survive alongside the next# pass's differently shaped buffers. Immutable weights remain untouched.- for name in ('host_outputs', 'host_output_key', 'group_readouts'):- if hasattr(attention, name):- delattr(attention, name)+ # Dropping them here without waiting for the device returned locked+ # blocks that the pass's last copies could still be using, and the+ # next pass's release then found nothing left to wait for.+ try:+ from .head_chunk import release_readouts+ except ModuleNotFoundError:+ # No torch, so no page-locked readouts can exist to return.+ def release_readouts(policy):+ for name in ('group_readouts', 'host_outputs', 'host_output_key', 'host_copies'):+ if hasattr(policy, name):+ delattr(policy, name)+ pending = sys.exc_info()[0]+ try:+ release_readouts(attention)+ except RuntimeError:+ if pending is None:+ raisediff --git a/freevideo_engine/residual.py b/freevideo_engine/residual.pyindex 17cc9a1..64b2ac5 100644--- a/freevideo_engine/residual.py+++ b/freevideo_engine/residual.py@@ -21,6 +21,7 @@ class ResidualState:self.stored = Falseself.closed = Falseself.copies = {'to_host': 0, 'to_device': 0}+ self.pinned_fallbacks = 0self.copy_wall_seconds = 0.# Set by the block loop: collect reference cycles once this block has# dropped its input (packing.install_streamed_forward).@@ -43,7 +44,15 @@ class ResidualState:tick = time.perf_counter()if self.host is None:self.host = self._allocate()- self.host.copy_(tensor, non_blocking=self.pinned)+ try:+ self.host.copy_(tensor, non_blocking=self.pinned)+ except torch.cuda.OutOfMemoryError:+ raise+ except RuntimeError as error:+ if not self.pinned:+ raise+ self._leave_locked_pages(keep=False, error=error)+ self.host.copy_(tensor)self.stored = Trueself.copies['to_host'] += 1self.copy_wall_seconds += time.perf_counter()-tick@@ -70,12 +79,36 @@ class ResidualState:return hostreturn torch.empty(self.shape, dtype=self.dtype, device='cpu')+ def _leave_locked_pages(self, keep, error):+ # A copy through the locked buffer was refused (Windows can fail a+ # queued copy with "invalid argument" when the system takes pages back).+ # Finish the queued work first, so a sticky error is raised as itself+ # rather than hidden by the retry, then continue in pageable memory,+ # which holds the same bytes and is read back unchanged.+ from .activation_staging import record_refusal+ record_refusal('residual', 'to_device' if keep else 'to_host', error)+ if self.device.type == 'cuda':+ torch.cuda.synchronize(self.device)+ host = torch.empty(self.shape, dtype=self.dtype, device='cpu')+ if keep:+ host.copy_(self.host)+ self.host, self.pinned = host, False+ self.pinned_fallbacks += 1+def restore(self):if self.closed or not self.stored:raise RuntimeError('No complete host residual is available')tick = time.perf_counter()# copy=True also makes CPU contract checks use independent storage.- tensor = self.host.to(self.device, copy=True, non_blocking=self.pinned)+ try:+ tensor = self.host.to(self.device, copy=True, non_blocking=self.pinned)+ except torch.cuda.OutOfMemoryError:+ raise+ except RuntimeError as error:+ if not self.pinned:+ raise+ self._leave_locked_pages(keep=True, error=error)+ tensor = self.host.to(self.device, copy=True)self.copies['to_device'] += 1self.copy_wall_seconds += time.perf_counter()-tickreturn tensor@@ -89,7 +122,7 @@ class ResidualState:def stats(self):host_bytes = self.host.numel()*self.host.element_size() if self.host is not None else 0return dict(host_buffer_bytes=host_bytes, pinned_host_bytes=host_bytes if self.pinned else 0,- copies=dict(self.copies), blocking_copy_wall_seconds=self.copy_wall_seconds,+ copies=dict(self.copies), pinned_fallbacks=self.pinned_fallbacks, blocking_copy_wall_seconds=self.copy_wall_seconds,timing_scope=('Locked-page copies are queued asynchronously; this is the time spent issuing them.'if self.pinned else'Blocking copy calls can include waiting for prior compute; not pure PCIe transfer time.'))diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.pyindex 44bb57a..34f796e 100644--- a/freevideo_engine/runtime.py+++ b/freevideo_engine/runtime.py@@ -809,6 +809,8 @@ class Engine:pass_cache = dict(gpu_budget_bytes=pass_cache_budget_bytes, admitted_bytes=0,requested_resident_blocks=pass_resident_blocks)residual_steps = []+ from .activation_staging import refusals_mark, refusals_since+ refusals_before = refusals_mark()attention_before = dict(self.attention.backend_calls) if self.attention is not None else Nonegemm_before = Noneif self.config.get('fp8_gemm'):@@ -880,6 +882,7 @@ class Engine:# weights through VAE loading. Reports own plain numbers only.sampled = {'sample_seconds': time.perf_counter() - started, 'step_seconds': list(step_seconds),'offload': stats, 'residual_offload_steps': residual_steps,+ 'locked_copy_refusals': refusals_since(refusals_before),'pass_cache_admission': pass_cache,'compute_configuration': {key: planned.get(key) for key in('head_chunk', 'window_batch', 'ff_chunk', 'projection_chunk', 'prefetch',diff --git a/freevideo_engine/two_pass_metrics.py b/freevideo_engine/two_pass_metrics.pyindex a9ff1eb..daa7074 100644--- a/freevideo_engine/two_pass_metrics.py+++ b/freevideo_engine/two_pass_metrics.py@@ -29,6 +29,7 @@ def combine(first, second, upscale, sampling_plan):result[key] = ({name: sum(row.get(name, 0) for row in rows)for name in set().union(*(row.keys() for row in rows))} if rows else None)result['residual_offload_steps'] = list(first.get('residual_offload_steps', [])) + list(second.get('residual_offload_steps', []))+ result['locked_copy_refusals'] = list(first.get('locked_copy_refusals', [])) + list(second.get('locked_copy_refusals', []))if first.get('head_execution') and second.get('head_execution'):result['head_execution'] = dict(second['head_execution'])for name in ('parallel_head_calls', 'parallel_head_warmups'):