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.
Use spare RAM for streamed Windows weights (#17)
Bowen Xue555d5e74e3c9
diff --git a/freevideo_engine/offload.py b/freevideo_engine/offload.pyindex 9e9712e..e077bd1 100644--- a/freevideo_engine/offload.py+++ b/freevideo_engine/offload.py@@ -93,11 +93,10 @@ def pin_layer_weights(layers, max_bytes=None, *, headroom_bytes=None, nonlocal_rfrom .system import windowsif windows():# Free RAM does not bound locked pages on Windows: the WDDM non-local- # budget does. A 20 s request on a 27.98 GiB machine pinned 9.67 GiB;- # its CPU readouts then took non-local usage to 13.14 of 13.24 GiB and- # cudaHostAlloc failed with 10.68 GiB of VRAM free. The reserve covers- # locked buffers allocated after the weights; the caller adds its- # request's CPU attention readouts to the default.+ # budget does. A 3.5 GiB working allowance on a 27.98 GiB machine pinned+ # past it on the second request, and every retry failed the same way.+ # The reserve covers locked buffers allocated after the weights; the+ # caller adds its request's CPU attention readouts to the default.from .windows_gpu_memory import nonlocal_pin_capacity, NONLOCAL_PIN_RESERVEreserve = NONLOCAL_PIN_RESERVE if nonlocal_reserve_bytes is None else nonlocal_reserve_bytescapacity = nonlocal_pin_capacity(reserve)@@ -361,6 +360,9 @@ class LayerOffloader:self.prefetch_wait_seconds = 0.self.direct_read_layers = 0self.direct_read_bytes = 0+ # The weight source outlives this pass; report only this pass's view hits.+ self.host_view_hits_start = getattr(weight_source, 'host_view_hits', 0)+ self.host_view_hit_bytes_start = getattr(weight_source, 'host_view_hit_bytes', 0)self.hooks = []self.expected = 0self.closed = False@@ -428,7 +430,9 @@ class LayerOffloader:raise RuntimeError('Pass cache admission requires an idle step boundary')remaining = self.cache_budget_bytes = max(0, int(max_bytes))candidates = set()- for index in sorted(range(len(self.layers)), key=lambda i: self.pinned_layers[i]):+ # Disk reads cost most, then copies from RAM-resident views, then pinned H2D.+ views = getattr(self.weight_source, 'host_views', None) or {}+ for index in sorted(range(len(self.layers)), key=lambda i: (self.pinned_layers[i], i in views)):if not allow_growth and index not in self.cached:continueif max_layers is not None and len(candidates) >= max_layers:@@ -660,6 +664,11 @@ class LayerOffloader:'h2d_seconds': sum(row[2].elapsed_time(row[3]) for row in self.transfers) / 1000,'direct_read_layers': self.direct_read_layers,'direct_read_bytes': self.direct_read_bytes,+ 'host_view_layers': len(getattr(self.weight_source, 'host_views', None) or {}),+ 'host_view_bytes': getattr(self.weight_source, 'host_view_bytes', 0),+ 'host_view_hits': getattr(self.weight_source, 'host_view_hits', 0) - self.host_view_hits_start,+ 'host_view_hit_bytes': getattr(self.weight_source, 'host_view_hit_bytes', 0) - self.host_view_hit_bytes_start,+ 'host_view_released': getattr(self.weight_source, 'host_view_released', 0),'host_prefetch': self.host_prefetch,'host_prefetch_reads': self.host_prefetch_reads,'host_prefetch_wait_seconds': self.host_prefetch_wait_seconds,diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.pyindex 85e9f81..55600f9 100644--- a/freevideo_engine/runtime.py+++ b/freevideo_engine/runtime.py@@ -126,9 +126,15 @@ class Engine:# Locked buffers allocated after the weights must also fit the Windows# non-local budget: CPU attention readouts grow with this request's rows.from .windows_gpu_memory import NONLOCAL_PIN_RESERVE, nonlocal_readout_bytes- self.nonlocal_reserve_bytes = NONLOCAL_PIN_RESERVE + (nonlocal_readout_bytes(- self.canvas, model.config.num_attention_heads * model.config.attention_head_dim)- if attention_cpu_outputs else 0)+ readouts = (nonlocal_readout_bytes(self.canvas, model.config.num_attention_heads * model.config.attention_head_dim)+ if attention_cpu_outputs else 0)+ self.nonlocal_reserve_bytes = NONLOCAL_PIN_RESERVE + readouts+ # RAM views fill during the first pass; leave what the refine pass will+ # still allocate. A 20 s request that let views take that room drove+ # physical availability to 0.01 GiB when its full-size readouts arrived.+ from .streamed_weights import HOST_VIEW_RESERVE+ self.host_view_reserve_bytes = HOST_VIEW_RESERVE + readouts + (+ residual_host_headroom(self.canvas) if residual_offload else 0)if resident_blocks > len(model.transformer_blocks):raise ValueError('More resident blocks requested than the model contains')# Build the streamed source before binding transformer blocks. The@@ -166,7 +172,8 @@ class Engine:streamed_paths += [self.cache / f'adaln/{index:02d}.safetensors'for index in range(resident_blocks, len(model.transformer_blocks))]if streamed_prefixes:- streamed_source = SafetensorLayers(streamed_paths + lora_paths, streamed_prefixes)+ streamed_source = SafetensorLayers(streamed_paths + lora_paths, streamed_prefixes, host_views=True,+ host_view_reserve=self.host_view_reserve_bytes)self.stream_weight_source = streamed_source# Only source-backed placeholders may remain empty between# refinement requests; pinned groups keep their own storage.@@ -349,7 +356,8 @@ class Engine:paths += [self.cache / f'blocks/{index:02d}.safetensors' for index in range(resident_blocks, len(model.transformer_blocks))]if not adaln_cache:paths += [self.cache / f'adaln/{index:02d}.safetensors' for index in range(resident_blocks, len(model.transformer_blocks))]- self.stream_weight_source = SafetensorLayers(paths + lora_paths, prefixes)+ self.stream_weight_source = SafetensorLayers(paths + lora_paths, prefixes, host_views=True,+ host_view_reserve=self.host_view_reserve_bytes)self.host_preload_seconds = 0.self.pinned_model_bytes = prepared_pins['logical']self.pinned_host_allocated_bytes = 0@@ -396,6 +404,7 @@ class Engine:'resident_upload_overlaps_block_preparation': True,'weight_cache_headroom_bytes': self.weight_cache_headroom_bytes,'nonlocal_reserve_bytes': self.nonlocal_reserve_bytes,+ 'host_view_reserve_bytes': self.host_view_reserve_bytes,'weight_cache_pin_order': pin_order,'host_pinning_during_load': incremental_pinning,'host_preload_seconds': self.host_preload_seconds,@@ -748,6 +757,8 @@ class Engine:self.schedule_hook.remove()self.transformer = Noneself.offload_layers = []+ if self.stream_weight_source is not None:+ self.stream_weight_source.release_host_views()self.stream_weight_source = Noneself.attention = Noneself.closed = Truediff --git a/freevideo_engine/streamed_weights.py b/freevideo_engine/streamed_weights.pyindex 5814b27..43b18f3 100644--- a/freevideo_engine/streamed_weights.py+++ b/freevideo_engine/streamed_weights.py@@ -251,8 +251,34 @@ class LayerReadAhead:self.pending_bytes = 0+# Streamed layers kept in RAM as read-only file views must leave this much+# physical memory free. A 27.98 GiB Windows machine started sampling at+# 7.31 GiB available and ran the refine pass at 6.98 GiB: 0.35 GiB of later+# growth, plus a 2 GiB floor for the rest of the system.+HOST_VIEW_RESERVE = int(2.5 * 2**30)+# Below this much available memory, views are handed back one layer per use,+# so a request that grows (a larger refine pass, readouts, another program)+# trades them for disk reads instead of pushing Windows toward its floor.+HOST_VIEW_SHED = int(1.5 * 2**30)+++def host_view_fits(size, reserve=HOST_VIEW_RESERVE):+ """Whether one more layer may stay in RAM as a read-only file view.++ Read-only views charge no commit (a 412 MiB block mapped and touched moved+ Windows commit by 1 MiB; a private copy moved it by 415 MiB), and Windows+ can drop their clean pages without writing the pagefile. Only physical+ memory bounds them.+ """+ from .system import system_memory+ memory = system_memory()+ available = memory.get('physical_available_bytes') or memory['available_bytes']+ return available - size >= reserve++class SafetensorLayers:- def __init__(self, paths, prefixes, *, intermediate_dtype=None, direct_read=None):+ def __init__(self, paths, prefixes, *, intermediate_dtype=None, direct_read=None, host_views=False,+ host_view_reserve=HOST_VIEW_RESERVE):from .system import windowsself.direct_read = windows() if direct_read is None else direct_readself.prefixes = tuple(prefixes)@@ -261,6 +287,14 @@ class SafetensorLayers:self.handle_files = {}self.keys = {}self.byte_ranges = {}+ # Layers that pinning could not hold but RAM can: read-only views of+ # their checkpoint bytes, adopted right after the first direct read.+ self.host_views = {} if host_views and self.direct_read else None+ self.host_view_reserve = host_view_reserve+ self.host_view_bytes = 0+ self.host_view_hits = 0+ self.host_view_hit_bytes = 0+ self.host_view_released = 0for path in sorted(set(Path(p).resolve() for p in paths)):self.files[path] = self.identity(path)with _open_safetensors(path, framework='np') as handle:@@ -338,12 +372,28 @@ class SafetensorLayers:or size != count * plane.element_size()):raise ValueError('Invalid streamed destination: ' + key)reads.setdefault(self.keys[key], []).append((start, size, dtype, offset))+ for path in reads:+ self.check(path)+ entry = self.host_views.get(index) if self.host_views is not None else None+ if entry is not None:+ views, _, size = entry+ # torch copies release the GIL, so the inference thread keeps launching.+ try:+ for source, dtype, begin, length in views:+ planes[dtype].detach().view(torch.uint8)[begin:begin + length].copy_(source)+ finally:+ for path in reads:+ self.check(path)+ self.host_view_hits += 1+ self.host_view_hit_bytes += size+ del entry, views+ if not host_view_fits(0, HOST_VIEW_SHED):+ self._release(index)+ return True# numpy exposes a writable byte view of CPU/pinned storage without# copying, including BF16/FP8 planes that numpy cannot represent directly.buffers = {dtype: memoryview(plane.detach().view(torch.uint8).numpy()).cast('B')for dtype, plane in planes.items()}- for path in reads:- self.check(path)try:for path, entries in reads.items():with path.open('rb', buffering=0) as stream:@@ -360,11 +410,64 @@ class SafetensorLayers:if not count:raise ValueError('Incomplete streamed checkpoint: ' + str(path))done += count+ if self.host_views is not None:+ size = sum(row[1] for entries in reads.values() for row in entries)+ if host_view_fits(size, self.host_view_reserve):+ self._adopt(index, reads, planes, size)finally:for path in reads:self.check(path)return True+ def _adopt(self, index, reads, planes, size):+ """Keep the layer just read resident as read-only views of its checkpoint."""+ import mmap+ import os+ import warnings+ import torch+ views, mappings = [], []+ for path, entries in reads.items():+ with path.open('rb', buffering=0) as stream:+ observed = _file_identity(os.fstat(stream.fileno()))+ if observed != self.handle_files[path]:+ raise CheckpointChangedError(path, 'handle', self.handle_files[path], observed)+ try:+ mapping = mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ)+ except OSError:+ # Address space or mapping refused: this layer keeps its direct reads.+ for opened in mappings:+ opened.close()+ return+ mappings.append(mapping)+ with warnings.catch_warnings():+ # Read-only checkpoint bytes; these tensors are only ever copy sources.+ warnings.simplefilter('ignore', UserWarning)+ data = torch.frombuffer(mapping, dtype=torch.uint8)+ for start, length, dtype, offset in entries:+ views.append((data[start:start + length], dtype, offset * planes[dtype].element_size(), length))+ # The direct read just left these pages in the file cache. Touch every+ # page now, so they join this process's working set before the next+ # streamed reads recycle the standby list.+ for source, *_ in views:+ source[::mmap.PAGESIZE].sum()+ self.host_views[index] = (views, mappings, size)+ self.host_view_bytes += size++ def _release(self, index):+ views, mappings, size = self.host_views.pop(index)+ del views+ for mapping in mappings:+ try:+ mapping.close()+ except BufferError:+ pass # A tensor view is still referenced; the mapping closes when it is collected.+ self.host_view_bytes -= size+ self.host_view_released += 1++ def release_host_views(self):+ for index in list(self.host_views or ()):+ self._release(index)+def read_ahead(self, layouts, pinned):from .system import windows# Windows uses the commit-safe safetensors ``pread`` backend. Adiff --git a/freevideo_engine/system.py b/freevideo_engine/system.pyindex ff4e128..d73191b 100644--- a/freevideo_engine/system.py+++ b/freevideo_engine/system.py@@ -84,11 +84,13 @@ def residual_host_headroom(canvas=None):def weight_cache_headroom(*, system=None, streamed=False, cpu_outputs=True, canvas=None):"""Separate host work from weight caching, without counting swap as RAM.- The 8 GiB Windows allowance covers its measured private working set and- host attention outputs. Linux streaming with GPU attention outputs measured- 2.56 GiB non-weight working memory in a complete 768p/243-frame request.- 3.5 GiB leaves growth/staging room inside the already OS-reserved budget.- CPU readouts measured 4.56 GiB beyond retained weights on Linux.+ Streaming with GPU attention outputs measured 2.56 GiB of non-weight+ working memory in a complete 768p/243-frame Linux request, and 2.63 GiB on+ Windows (RTX 4060 Ti 16 GiB: 10.69 GiB peak private working set holding+ 8.06 GiB of pinned weights). 3.5 GiB leaves growth/staging room inside the+ already OS-reserved budget on both platforms; Windows previously kept 8 GiB+ here, sized for host attention outputs, and streamed weights it had room+ to retain. CPU readouts measured 4.56 GiB beyond retained weights on Linux.Keep 5 GiB at that geometry there; Windows page-locks the readouts on topof about 4.0 GiB of non-pinned private working set (12/32 Ada laptop) andkeeps its 8 GiB. Larger requests additionally reserve 2.5 GiB per reference@@ -102,7 +104,7 @@ def weight_cache_headroom(*, system=None, streamed=False, cpu_outputs=True, canvif system not in ('Linux', 'Windows') or not streamed:return HOST_WEIGHT_HEADROOMif not cpu_outputs:- return int(3.5 * 2**30) if system == 'Linux' else HOST_WEIGHT_HEADROOM+ return int(3.5 * 2**30)if canvas is None:return HOST_WEIGHT_HEADROOMfrom .geometry import geometry