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.
Stream Windows offloaded layers with load-time views; restart the resident worker after CUDA errors (#21)
Bowen Xue47927c82f023
diff --git a/freevideo_engine/adaptive.py b/freevideo_engine/adaptive.pyindex 7d2966c..f73e2d0 100644--- a/freevideo_engine/adaptive.py+++ b/freevideo_engine/adaptive.py@@ -23,6 +23,19 @@ class WorkerExit(RuntimeError):(code, log, self.log.read_text(encoding='utf-8', errors='replace')[-4000:]))+def cuda_runtime_error(error):+ """A CUDA runtime error other than an allocation failure anywhere in the+ exception chain, whether or not it is a known sticky error."""+ seen = set()+ while error is not None and id(error) not in seen:+ seen.add(id(error))+ text = str(error).lower()+ if 'cuda error' in text and 'out of memory' not in text:+ return True+ error = error.__cause__ or error.__context__+ return False++def classify_failure(error, metrics=None):"""Only positively identified resource failures are retriable.diff --git a/freevideo_engine/policy.py b/freevideo_engine/policy.pyindex f1e7f6c..1dd4e43 100644--- a/freevideo_engine/policy.py+++ b/freevideo_engine/policy.py@@ -912,7 +912,15 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',ram_wants = max(0, 50 - max(0, int(host_room // block_bytes)))if not small:resident = min(resident, max(RESIDENT_TARGET, ram_wants))- streamed_weights = (50 - resident) * block_bytes + host_activation + 2 * GiB > retention_budget+ # Windows reads non-streamed offloaded blocks into private memory (pread;+ # a section view would be charged to commit in full). The RAM guard counts+ # it, it cannot be reclaimed, and pins planned after that load-all pass find+ # no room: after a 20 s request, 27.98 GiB RTX 5060 Ti, the next 768p plan+ # crossed this threshold and sampled with 21.2 GiB private, nothing pinned+ # and 2.5 GiB available. Streaming pins a bounded subset block by block and+ # keeps read-only views of the rest, which avoid rereads while RAM allows.+ streamed_weights = ((hardware.system == 'Windows' and resident < 50)+ or (50 - resident) * block_bytes + host_activation + 2 * GiB > retention_budget)if streamed_weights:# When the remaining weights exceed RAM, a bounded retained subset# prevents rereading those bytes every step. This addresses disk I/O,@@ -1013,7 +1021,10 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',if residual_offload:notes.append('The original small path exceeds the live VRAM budget: stage residuals in one reusable CPU buffer, preserving kernel shapes, dtype and every requested row. Host weight caching leaves an additional %.2f GiB for this buffer. Extra transfers cost time; this is a capacity route, not a claimed speedup.' % (residual_host / GiB))if streamed_weights:- notes.append('Live RAM cannot retain all offloaded mappings: keep at most %.3f GB pinned, reopen only remaining layers per transfer; no arithmetic or attention change.' % pin)+ if hardware.system == 'Windows':+ notes.append('Windows streams offloaded layers: keep at most %.3f GB pinned and read-only views of the rest while RAM allows, reopening a layer only after its view is shed; no arithmetic or attention change.' % pin)+ else:+ notes.append('Live RAM cannot retain all offloaded mappings: keep at most %.3f GB pinned, reopen only remaining layers per transfer; no arithmetic or attention change.' % pin)notes.append('Host weight cache keeps %.2f GiB for this path\'s working memory, inside the separate OS growth reserve; the runtime rechecks available RAM.' % (host_headroom / GiB))if hardware.architecture == 'ampere':notes.append('Ampere keeps FP8 weight storage and uses bounded BF16 compute; no native FP8 tensor-core claim.')diff --git a/freevideo_engine/resident_worker.py b/freevideo_engine/resident_worker.pyindex 8b47cdc..44d4b81 100644--- a/freevideo_engine/resident_worker.py+++ b/freevideo_engine/resident_worker.py@@ -74,7 +74,7 @@ def main():if diagnostics is not None:diagnostics.finish(False)traceback.print_exc()- from .adaptive import classify_failure+ from .adaptive import classify_failure, cuda_runtime_errorfailure = classify_failure(error)if request.get('metrics'):from .monitoring import save@@ -96,7 +96,12 @@ def main():retained.update(failure_resources(sys.modules['torch'], query_cuda=failure['kind'] != 'cuda_error'))metrics['gpu'] = retained['gpu']save(path, metrics)- if failure['kind'] == 'cuda_error':+ # Any CUDA runtime error except an allocation failure can leave+ # this context unusable, not only the known sticky ones. After+ # 1080p failed with "CUDA error: invalid argument" on an H2D+ # copy, the next request's text encoder in this same process+ # failed with the same error. A fresh worker costs a reload.+ if failure['kind'] == 'cuda_error' or cuda_runtime_error(error):log.flush()import osos._exit(74)diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.pyindex 55600f9..7ae533a 100644--- a/freevideo_engine/runtime.py+++ b/freevideo_engine/runtime.py@@ -149,7 +149,7 @@ class Engine:streamed_source = Nonefrom .system import windowsincremental_pinning = stream_weights and bool(pin_host_gb) and windows()- prepared_pins = dict(logical=0, reserved=0, seconds=0.)+ prepared_pins = dict(logical=0, reserved=0, seconds=0., views=0)streamed_refiner_count = (len(model.token_refiner.refiner_blocks)if stream_weights and offload_refiner and not cache_refined_text else 0)if stream_weights and not adaln_cache:@@ -179,6 +179,7 @@ class Engine:# refinement requests; pinned groups keep their own storage.self.stream_refiner_count = streamed_refiner_countdef prepare_streamed(block, index):+ logical = 0if incremental_pinning:tick = time.perf_counter()logical, reserved = prepare_streamed_layer(block, streamed_source, index,@@ -190,6 +191,9 @@ class Engine:prepared_pins['seconds'] += time.perf_counter() - tickelse:unload_streamed_layer(block, streamed_source, index)+ if not logical:+ # Its bytes are still in the file cache; later pins would evict them.+ prepared_pins['views'] += int(streamed_source.adopt(index))precision = manifest.get('precision', 'bf16')actual_fp8_gemm = Noneif precision == 'fp8':@@ -407,6 +411,7 @@ class Engine:'host_view_reserve_bytes': self.host_view_reserve_bytes,'weight_cache_pin_order': pin_order,'host_pinning_during_load': incremental_pinning,+ 'host_views_adopted_during_load': prepared_pins['views'],'host_preload_seconds': self.host_preload_seconds,'remaining_load_seconds': self.load_seconds - adaln_prepare_seconds - pin_seconds - self.host_preload_seconds,'scope': 'Host wall time within model load; AdaLN includes table reads or computation and writes.'}diff --git a/freevideo_engine/streamed_weights.py b/freevideo_engine/streamed_weights.pyindex 43b18f3..fbb487a 100644--- a/freevideo_engine/streamed_weights.py+++ b/freevideo_engine/streamed_weights.py@@ -371,16 +371,24 @@ class SafetensorLayers:or offset < 0 or count < 0 or offset + count > plane.numel()or size != count * plane.element_size()):raise ValueError('Invalid streamed destination: ' + key)- reads.setdefault(self.keys[key], []).append((start, size, dtype, offset))+ reads.setdefault(self.keys[key], []).append((start, size, dtype, offset, name))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 and any(name not in entry[0] or entry[0][name].numel() != size+ for entries in reads.values() for _, size, _, _, name in entries):+ # Views are kept by tensor name. One that cannot serve this layout+ # is dropped rather than copied to a guessed plane offset.+ self._release(index)+ entry = Noneif 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)+ for entries in reads.values():+ for _, length, dtype, offset, name in entries:+ begin = offset * planes[dtype].element_size()+ planes[dtype].detach().view(torch.uint8)[begin:begin + length].copy_(views[name])finally:for path in reads:self.check(path)@@ -400,7 +408,7 @@ class SafetensorLayers:observed = _file_identity(os.fstat(stream.fileno()))if observed != self.handle_files[path]:raise CheckpointChangedError(path, 'handle', self.handle_files[path], observed)- for start, size, dtype, offset in sorted(entries, key=lambda row: row[0]):+ for start, size, dtype, offset, _ in sorted(entries, key=lambda row: row[0]):stream.seek(start)begin = offset * planes[dtype].element_size()target = buffers[dtype][begin:begin + size]@@ -413,19 +421,43 @@ class SafetensorLayers: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)+ self._adopt(index, reads, size)finally:for path in reads:self.check(path)return True- def _adopt(self, index, reads, planes, size):+ def adopt(self, index):+ """Keep a layer that loading just read as views, so its first pass reads no disk.++ Pinned groups admitted after it consume the RAM that cached these+ pages: a 768p request after a 20 s one read its 16 GiB of unpinned+ layers again during the first step. Admission and shedding are the+ same as for a layer adopted after its first direct read.+ """+ if self.host_views is None or index in self.host_views:+ return False+ prefix = self.prefixes[index]+ reads = {}+ for key, path in self.keys.items():+ if key.startswith(prefix):+ start, size, _, _ = self.byte_ranges[key]+ reads.setdefault(path, []).append((start, size, None, None, key[len(prefix):]))+ size = sum(row[1] for entries in reads.values() for row in entries)+ if not reads or not host_view_fits(size, self.host_view_reserve):+ return False+ for path in reads:+ self.check(path)+ self._adopt(index, reads, size)+ return index in self.host_views++ def _adopt(self, index, reads, size):"""Keep the layer just read resident as read-only views of its checkpoint."""import mmapimport osimport warningsimport torch- views, mappings = [], []+ views, mappings = {}, []for path, entries in reads.items():with path.open('rb', buffering=0) as stream:observed = _file_identity(os.fstat(stream.fileno()))@@ -443,12 +475,12 @@ class SafetensorLayers:# 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))+ for start, length, _, _, name in entries:+ views[name] = data[start:start + 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:+ for source in views.values():source[::mmap.PAGESIZE].sum()self.host_views[index] = (views, mappings, size)self.host_view_bytes += sizediff --git a/freevideo_engine/win32.py b/freevideo_engine/win32.pyindex 3781ab5..d3b8cd5 100644--- a/freevideo_engine/win32.py+++ b/freevideo_engine/win32.py@@ -2,6 +2,7 @@import ctypes as Cfrom functools import lru_cacheimport os+import timeDWORD, BOOL, HANDLE, SIZE_T = C.c_uint32, C.c_int32, C.c_void_p, C.c_size_tQWORD = C.c_uint64@@ -354,6 +355,10 @@ class ProcessMemory:self.minimum_effective = Noneself.complete = self.io_complete = Trueself.io = {}+ self.io_baseline = {}+ # Process creation times are FILETIMEs. A process created before this+ # observation (a resident worker) already counts earlier requests.+ self.started_tick = int((time.time() + 11644473600) * 10**7)self.errors = []self.excluded = []@@ -392,7 +397,11 @@ class ProcessMemory:rss += row['rss_bytes']private += row['private_commit_bytes']resident += row['private_working_set_bytes']- self.io[(pid, row['start_tick'])] = (row['read_bytes'], row['write_bytes'])+ key = (pid, row['start_tick'])+ if key not in self.io_baseline:+ self.io_baseline[key] = ((row['read_bytes'], row['write_bytes'])+ if row['start_tick'] < self.started_tick else (0, 0))+ self.io[key] = (row['read_bytes'], row['write_bytes'])self.io_complete &= row['io_complete']except InaccessibleProcess as error:names = process_names() if names is None else names@@ -487,10 +496,10 @@ class ProcessMemory:'system_min_commit_available_bytes': self.minimum_commit,'effective_min_available_bytes': self.minimum_effective,'ram_observation_samples': self.samples,- 'process_tree_disk_read_bytes': sum(v[0] for v in self.io.values()),- 'process_tree_disk_write_bytes': sum(v[1] for v in self.io.values()),- 'process_tree_io_complete': self.io_complete, 'process_tree_io_version': 3,- 'process_tree_io_scope': 'Windows per-process transfer counters, retained by PID/creation time; includes cached I/O, not physical disk traffic.',+ 'process_tree_disk_read_bytes': sum(max(0, v[0] - self.io_baseline[k][0]) for k, v in self.io.items()),+ 'process_tree_disk_write_bytes': sum(max(0, v[1] - self.io_baseline[k][1]) for k, v in self.io.items()),+ 'process_tree_io_complete': self.io_complete, 'process_tree_io_version': 4,+ 'process_tree_io_scope': 'Windows per-process transfer counters, retained by PID/creation time and counted from this observation: a process created earlier (a resident worker) contributes only transfers after its first sample. Includes cached I/O, not physical disk traffic.','ram_observation_scope': 'RAM guard is the summed private working set (ProcessVmCounters): resident private bytes, excluding mapped files and nonresident commit. PSS unavailable; this is not PSS and does not apportion shared pages. Working set and private commit are retained for diagnosis only and must not be compared against a RAM budget: the working set counts resident mapped file pages, which grow with free RAM, and WDDM charges GPU allocations to PrivateUsage without residency while per-PID VRAM attribution is unavailable. Effective availability adds back this tree own resident non-private pages, which are clean mapped weight pages the kernel can drop, because GlobalMemoryStatusEx counts only free and standby pages unlike Linux MemAvailable; it stays bounded by commit headroom and total RAM and never credits system-wide cache. Pagefile not added to physical RAM.'}