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.
Read less from disk when loading the model on Windows with little RAM (0.3.18) (#132)
Bowen Xue5815b23369c8
diff --git a/freevideo_engine/offload.py b/freevideo_engine/offload.pyindex 61c29b6..46293e1 100644--- a/freevideo_engine/offload.py+++ b/freevideo_engine/offload.py@@ -39,33 +39,8 @@ def _pin_reservation(sizes):return sum((1 << (size - 1).bit_length()) if 0 < size <= threshold else size for size in sizes)[email protected]_grad()-def pin_layer_weights(layers, max_bytes=None, *, headroom_bytes=None, nonlocal_reserve_bytes=None,- commit_reserve_bytes=0):- """Pack immutable CPU parameters into persistent pinned planes, one per dtype.-- This optional mode trades pageable/mapped storage for locked host residency.- Rebinding preserves parameter values and permits direct asynchronous H2D.- """- if type(commit_reserve_bytes) is not int or commit_reserve_bytes < 0:- raise ValueError('Commit reserve must be a nonnegative byte count')- layers = list(layers)- layer_groups = []- for layer in layers:- by_dtype = {}- for name, parameter in cpu_weights(layer):- if not isinstance(parameter, torch.nn.Parameter) and parameter._base is not None:- # safetensors buffers are views. Reassigning their .data alone- # keeps the old view base (and mapped FP8 file) alive alongside- # the pinned copy. Detach the registered buffer first; this- # shares the bytes without retaining view metadata.- parent, _, leaf = name.rpartition('.')- owner = layer.get_submodule(parent) if parent else layer- parameter = parameter.detach()- setattr(owner, leaf, parameter)- by_dtype.setdefault(parameter.dtype, []).append(parameter)- layer_groups.append(list(by_dtype.items()))-+def live_pin_capacity(*, headroom_bytes=None, nonlocal_reserve_bytes=None, commit_reserve_bytes=0):+ """Bytes that page-locking may take now, beyond the working headroom."""# Charge free physical memory only. Effective availability credits this# tree's reclaimable mapped pages, which is right for measuring pressure# but wrong for deciding how much to lock: locked pages cannot be@@ -98,8 +73,7 @@ def pin_layer_weights(layers, max_bytes=None, *, headroom_bytes=None, nonlocal_r# the step cache for the rest of the request. The caller passes that# unreserved allocator room; physical RAM is not charged for it.available = min(available, commit_available - commit_reserve_bytes)- live_cap = available - headroom_bytes- max_bytes = live_cap if max_bytes is None else min(max_bytes, live_cap)+ cap = available - headroom_bytesfrom .system import windowsif windows():# Free RAM does not bound locked pages on Windows: the WDDM non-local@@ -118,7 +92,40 @@ def pin_layer_weights(layers, max_bytes=None, *, headroom_bytes=None, nonlocal_rpinned = 0capacity = max(0, memory['total_bytes'] // 2 - pinned - reserve)if capacity is not None:- max_bytes = min(max_bytes, capacity)+ cap = min(cap, capacity)+ return cap++[email protected]_grad()+def pin_layer_weights(layers, max_bytes=None, *, headroom_bytes=None, nonlocal_reserve_bytes=None,+ commit_reserve_bytes=0):+ """Pack immutable CPU parameters into persistent pinned planes, one per dtype.++ This optional mode trades pageable/mapped storage for locked host residency.+ Rebinding preserves parameter values and permits direct asynchronous H2D.+ """+ if type(commit_reserve_bytes) is not int or commit_reserve_bytes < 0:+ raise ValueError('Commit reserve must be a nonnegative byte count')+ layers = list(layers)+ layer_groups = []+ for layer in layers:+ by_dtype = {}+ for name, parameter in cpu_weights(layer):+ if not isinstance(parameter, torch.nn.Parameter) and parameter._base is not None:+ # safetensors buffers are views. Reassigning their .data alone+ # keeps the old view base (and mapped FP8 file) alive alongside+ # the pinned copy. Detach the registered buffer first; this+ # shares the bytes without retaining view metadata.+ parent, _, leaf = name.rpartition('.')+ owner = layer.get_submodule(parent) if parent else layer+ parameter = parameter.detach()+ setattr(owner, leaf, parameter)+ by_dtype.setdefault(parameter.dtype, []).append(parameter)+ layer_groups.append(list(by_dtype.items()))++ cap = live_pin_capacity(headroom_bytes=headroom_bytes, nonlocal_reserve_bytes=nonlocal_reserve_bytes,+ commit_reserve_bytes=commit_reserve_bytes)+ max_bytes = cap if max_bytes is None else min(max_bytes, cap)groups, sizes, reserved = [], [], 0for entries in layer_groups:@@ -299,6 +306,24 @@ def prepare_streamed_layer(layer, source, index, *, pin_budget_bytes, headroom_breturn 0, 0+def loading_retains(source, index, *, pin_budget_bytes, **pin_options):+ """Whether preparing a streamed layer may keep what loading reads: a pin or a view.++ The checks of prepare_streamed_layer (planned budget, then the live cap of+ pin_layer_weights, with pin_options) and of SafetensorLayers.adopt, made on+ checkpoint header sizes, which equal the bound tensors, before the layer is+ read. pin_layer_weights measures with the layer already read into private+ memory, so the live cap here is charged its size as well.+ """+ sizes = source.layer_bytes(index)+ size = sum(sizes.values())+ reservation = _pin_reservation(sizes.values())+ if 0 < reservation <= pin_budget_bytes and reservation <= live_pin_capacity(**pin_options) - size:+ return True+ from .streamed_weights import host_view_fits+ return source.host_views is not None and host_view_fits(size, source.host_view_reserve)++class LayerOffloader:"""Keep CPU weights and stream a sequential layer list through one or two slots.diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.jsonindex 2b1a8bb..d4fe68a 100644--- a/freevideo_engine/release_notes.json+++ b/freevideo_engine/release_notes.json@@ -1,19 +1,34 @@{"schema": 1,- "product_version": "0.3.17",+ "product_version": "0.3.18","en": {- "summary": "On Windows, GPUs with 12 to 20 GB of memory sample a little faster: attention runs 16 heads at a time where memory allows.",+ "summary": "On Windows computers with little RAM, loading the video model reads much less from the disk.","changes": [- "On Windows, attention now runs 16 heads at a time instead of 8 whenever the GPU memory budget leaves room for it. This covers the first pass on 12 to 20 GB GPUs and the second pass on most 16 and 20 GB GPUs. On a 16 GB GPU, a 10-second 1344×768 video took about 6% less time per first-pass step and about 2% less per second-pass step, without using more video memory. FP8 models, requests with a LoRA, Linux and GPUs below 12 GB keep their current settings. The same seed can give a slightly different video than before, as it already does between GPUs with different memory."+ "On Windows, when RAM cannot hold the whole video model, loading no longer reads the model layers that sampling streams from the disk anyway; each is read when sampling first needs it. With 16 GB of RAM, that is about 13 GB less to read every time the model loads: on an RTX 5060 Ti test machine limited to the RAM of a 16 GB computer, loading took 7 seconds instead of 11, and on a slower drive the saving is a few minutes. Videos are unchanged. Computers that keep the whole model in RAM, Linux and Mac load as before."]},"zh": {- "summary": "在 Windows 上,12–20 GB 显存的显卡采样稍快一些:显存允许时,注意力每次计算 16 个头。",+ "summary": "在内存较小的 Windows 电脑上,加载视频模型时从硬盘读取的数据少了很多。","changes": [- "在 Windows 上,只要显存预算有余量,注意力改为每次计算 16 个头(原来每次 8 个)。12–20 GB 显卡的第一遍,以及大多数 16 GB 和 20 GB 显卡的第二遍都会用上。在 16 GB 显卡上生成 10 秒 1344×768 视频,第一遍每步缩短约 6%,第二遍每步缩短约 2%,显存占用没有增加。FP8 模型、使用 LoRA 的生成、Linux 和 12 GB 以下的显卡保持现有设置。同一个种子生成的视频可能与以前略有不同,就像在显存不同的显卡上本来就会有差异一样。"+ "在 Windows 上,内存放不下整个视频模型时,加载阶段不再预先读取那些采样时本来就要从硬盘读取的模型层,改为采样第一次用到时再读。16 GB 内存的电脑每次加载模型可少读约 13 GB:在按 16 GB 电脑的内存条件运行的 RTX 5060 Ti 测试机上,加载从 11 秒缩短到 7 秒;硬盘较慢时可节省几分钟。生成的视频不变。内存能放下整个模型的电脑、Linux 和 Mac 的加载方式不变。"]},"history": [+ {+ "product_version": "0.3.17",+ "en": {+ "summary": "On Windows, GPUs with 12 to 20 GB of memory sample a little faster: attention runs 16 heads at a time where memory allows.",+ "changes": [+ "On Windows, attention now runs 16 heads at a time instead of 8 whenever the GPU memory budget leaves room for it. This covers the first pass on 12 to 20 GB GPUs and the second pass on most 16 and 20 GB GPUs. On a 16 GB GPU, a 10-second 1344×768 video took about 6% less time per first-pass step and about 2% less per second-pass step, without using more video memory. FP8 models, requests with a LoRA, Linux and GPUs below 12 GB keep their current settings. The same seed can give a slightly different video than before, as it already does between GPUs with different memory."+ ]+ },+ "zh": {+ "summary": "在 Windows 上,12–20 GB 显存的显卡采样稍快一些:显存允许时,注意力每次计算 16 个头。",+ "changes": [+ "在 Windows 上,只要显存预算有余量,注意力改为每次计算 16 个头(原来每次 8 个)。12–20 GB 显卡的第一遍,以及大多数 16 GB 和 20 GB 显卡的第二遍都会用上。在 16 GB 显卡上生成 10 秒 1344×768 视频,第一遍每步缩短约 6%,第二遍每步缩短约 2%,显存占用没有增加。FP8 模型、使用 LoRA 的生成、Linux 和 12 GB 以下的显卡保持现有设置。同一个种子生成的视频可能与以前略有不同,就像在显存不同的显卡上本来就会有差异一样。"+ ]+ }+ },{"product_version": "0.3.16","en": {diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.pyindex 7e6be6f..d3ecd02 100644--- a/freevideo_engine/runtime.py+++ b/freevideo_engine/runtime.py@@ -166,7 +166,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., views=0)+ prepared_pins = dict(logical=0, reserved=0, seconds=0., views=0, unread=0, unread_bytes=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:@@ -195,8 +195,35 @@ class Engine:# Only source-backed placeholders may remain empty between# refinement requests; pinned groups keep their own storage.self.stream_refiner_count = streamed_refiner_count- def prepare_streamed(block, index):+ def unread_weights(index):+ """Layout-only tensors for a streamed block that loading cannot keep.++ A block is read here only for a pinned group or a view. Otherwise+ its values are dropped, and where RAM is that short the file cache+ cannot hold them until the first step either.+ """+ if streamed_source is None or not streamed_source.direct_read or index < resident_blocks:+ return None+ from .offload import loading_retains+ layer = streamed_refiner_count + index - resident_blocks+ budget = max(0, int(pin_host_gb * 1e9) - prepared_pins['reserved']) if incremental_pinning else 0+ if loading_retains(streamed_source, layer, pin_budget_bytes=budget,+ headroom_bytes=self.weight_cache_headroom_bytes,+ nonlocal_reserve_bytes=self.nonlocal_reserve_bytes,+ commit_reserve_bytes=self.gpu_commit_reserve()):+ return None+ tensors = streamed_source.placeholders(layer, self.cache / f'blocks/{index:02d}.safetensors')+ if tensors is not None:+ prepared_pins['unread'] += 1+ prepared_pins['unread_bytes'] += sum(streamed_source.layer_bytes(layer).values())+ return tensors+ def prepare_streamed(block, index, unread=False):logical = 0+ if unread:+ # Placeholder values: never pin or view them. The first direct+ # read in sampling adopts a view if RAM allows by then.+ self.device_backend.unload_streamed_layer(block, streamed_source, index)+ returnif incremental_pinning:tick = time.perf_counter()logical, reserved = self.device_backend.prepare_streamed_layer(block, streamed_source, index,@@ -271,8 +298,11 @@ class Engine:del table, adalnadaln_prepare_seconds += time.perf_counter() - adaln_startedbind_started = time.perf_counter()- weights = {name.removeprefix(prefix): value for name, value in- _load_safetensors(self.cache / f'blocks/{index:02d}.safetensors').items()}+ weights = unread_weights(index)+ unread = weights is not None+ if not unread:+ weights = _load_safetensors(self.cache / f'blocks/{index:02d}.safetensors')+ weights = {name.removeprefix(prefix): value for name, value in weights.items()}if not adaln_cache:weights.update(adaln)result = block.load_state_dict(weights, strict=False, assign=True)@@ -302,7 +332,7 @@ class Engine:# Keep only the bounded pinned subset or metadata. Immutable# unpinned bytes are reopened by SafetensorLayers on demand,# rather than accumulating until the first sampling step.- prepare_streamed(block, streamed_refiner_count + index - resident_blocks)+ prepare_streamed(block, streamed_refiner_count + index - resident_blocks, unread)if (index + 1) % 5 == 0:print(json.dumps({'event': 'prepared_blocks', 'blocks': index + 1,'adaln_cache': adaln_cache, 'adaln_reused_blocks': table_cache_hits,@@ -411,6 +441,8 @@ class Engine:'weight_cache_pin_order': pin_order,'host_pinning_during_load': incremental_pinning,'host_views_adopted_during_load': prepared_pins['views'],+ 'streamed_blocks_unread_during_load': prepared_pins['unread'],+ 'streamed_bytes_unread_during_load': prepared_pins['unread_bytes'],'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 fbb487a..ad84903 100644--- a/freevideo_engine/streamed_weights.py+++ b/freevideo_engine/streamed_weights.py@@ -427,6 +427,42 @@ class SafetensorLayers:self.check(path)return True+ def layer_bytes(self, index):+ """Checkpoint bytes of one layer by stored dtype, from the headers alone."""+ prefix = self.prefixes[index]+ sizes = {}+ for key, (_, size, stored, _) in self.byte_ranges.items():+ if key.startswith(prefix):+ sizes[stored] = sizes.get(stored, 0) + size+ return sizes++ def placeholders(self, index, path):+ """Tensors with one file's stored dtypes and shapes for a layer, read from nothing.++ Model loading binds a streamed layer only to record its layout, then+ drops the values. When the layer will be neither pinned nor kept as a+ view, reading it first is wasted: the first step reads it again. With+ the RAM of a 16 GB machine, 31 of 45 offloaded blocks (13.4 GB) were+ such layers; on the RTX 5060 Ti test machine loading took 7.1 s instead+ of 11.3 s, with identical output, and slower drives save far more.+ Each placeholder is one element expanded to the checkpoint shape.+ Return None for a dtype torch lacks.+ """+ import torch+ prefix = self.prefixes[index]+ path = Path(path).resolve()+ tensors = {}+ for key, owner in self.keys.items():+ if owner != path or not key.startswith(prefix):+ continue+ _, _, stored, shape = self.byte_ranges[key]+ dtype = getattr(torch, _TORCH_DTYPES.get(stored, ''), None)+ if dtype is None:+ return None+ tensors[key] = (torch.empty((1,) * len(shape), dtype=dtype).expand(shape) if all(shape)+ else torch.empty(shape, dtype=dtype))+ return tensors+def adopt(self, index):"""Keep a layer that loading just read as views, so its first pass reads no disk.