Skip to content

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.

Cap Windows weight pinning at the WDDM non-local budget (#13)

Bowen Xue63f17a98f84b
diff --git a/freevideo_engine/offload.py b/freevideo_engine/offload.py
index a8063dd..9e9712e 100644
--- a/freevideo_engine/offload.py
+++ b/freevideo_engine/offload.py
@@ -40,7 +40,7 @@ def _pin_reservation(sizes):
@torch.no_grad()
-def pin_layer_weights(layers, max_bytes=None, *, headroom_bytes=None):
+def pin_layer_weights(layers, max_bytes=None, *, headroom_bytes=None, nonlocal_reserve_bytes=None):
"""Pack immutable CPU parameters into persistent pinned planes, one per dtype.
This optional mode trades pageable/mapped storage for locked host residency.
@@ -90,6 +90,26 @@ def pin_layer_weights(layers, max_bytes=None, *, headroom_bytes=None):
available = min(available, commit_available)
live_cap = available - headroom_bytes
max_bytes = live_cap if max_bytes is None else min(max_bytes, live_cap)
+ from .system import windows
+ if 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.
+ from .windows_gpu_memory import nonlocal_pin_capacity, NONLOCAL_PIN_RESERVE
+ reserve = NONLOCAL_PIN_RESERVE if nonlocal_reserve_bytes is None else nonlocal_reserve_bytes
+ capacity = nonlocal_pin_capacity(reserve)
+ if capacity is None and memory.get('total_bytes'):
+ # Without a DXGI reading, assume the Windows default of half of RAM.
+ try:
+ pinned = torch.cuda.memory.host_memory_stats()['allocated_bytes.current']
+ except (RuntimeError, KeyError, AttributeError):
+ pinned = 0
+ capacity = max(0, memory['total_bytes'] // 2 - pinned - reserve)
+ if capacity is not None:
+ max_bytes = min(max_bytes, capacity)
groups, sizes, reserved = [], [], 0
for entries in layer_groups:
@@ -229,7 +249,7 @@ def unload_streamed_layer(layer, source, index):
@torch.no_grad()
-def prepare_streamed_layer(layer, source, index, *, pin_budget_bytes, headroom_bytes):
+def prepare_streamed_layer(layer, source, index, *, pin_budget_bytes, headroom_bytes, nonlocal_reserve_bytes=None):
"""Retain one affordable pinned layer or release it before loading the next.
Return logical pinned bytes and the charged allocator reservation. A partial
@@ -242,7 +262,8 @@ def prepare_streamed_layer(layer, source, index, *, pin_budget_bytes, headroom_b
reserved = _pin_reservation(sizes.values())
pinned = 0
if 0 < reserved <= pin_budget_bytes:
- pinned = pin_layer_weights([layer], max_bytes=pin_budget_bytes, headroom_bytes=headroom_bytes)
+ pinned = pin_layer_weights([layer], max_bytes=pin_budget_bytes, headroom_bytes=headroom_bytes,
+ nonlocal_reserve_bytes=nonlocal_reserve_bytes)
if pinned == sum(sizes.values()) and all(value.is_pinned() for _, value in cpu_weights(layer)):
return pinned, reserved
unload_streamed_layer(layer, source, index)
diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.py
index a8f568e..85e9f81 100644
--- a/freevideo_engine/runtime.py
+++ b/freevideo_engine/runtime.py
@@ -123,6 +123,12 @@ class Engine:
varlen_smooth_k=varlen_smooth_k)
model = skeleton(self.base, Path(checkpoint))
validate_catalog(manifest, len(model.transformer_blocks))
+ # 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)
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
@@ -170,7 +176,8 @@ class Engine:
tick = time.perf_counter()
logical, reserved = prepare_streamed_layer(block, streamed_source, index,
pin_budget_bytes=max(0, int(pin_host_gb * 1e9) - prepared_pins['reserved']),
- headroom_bytes=self.weight_cache_headroom_bytes)
+ headroom_bytes=self.weight_cache_headroom_bytes,
+ nonlocal_reserve_bytes=self.nonlocal_reserve_bytes)
prepared_pins['logical'] += logical
prepared_pins['reserved'] += reserved
prepared_pins['seconds'] += time.perf_counter() - tick
@@ -358,12 +365,14 @@ class Engine:
pin_layers = [self.offload_layers[index] for index in interleaved_layer_order(len(self.offload_layers))]
pin_order = 'interleaved'
self.pinned_model_bytes = pin_layer_weights(pin_layers, max_bytes=int(pin_host_gb * 1e9) if pin_host_gb else None,
- headroom_bytes=host_headroom)
+ headroom_bytes=host_headroom,
+ nonlocal_reserve_bytes=self.nonlocal_reserve_bytes)
pin_seconds = time.perf_counter() - pin_start
self.pinned_host_allocated_bytes = torch.cuda.memory.host_memory_stats()['allocated_bytes.current']
print(json.dumps({'event': 'host_weights_pinned', 'seconds': pin_seconds,
'logical_bytes': self.pinned_model_bytes,
'working_headroom_bytes': host_headroom,
+ 'nonlocal_reserve_bytes': self.nonlocal_reserve_bytes,
'pin_order': pin_order,
'host_allocator_bytes': self.pinned_host_allocated_bytes}), flush=True)
if preload_host:
@@ -386,6 +395,7 @@ class Engine:
'resident_upload_submit_seconds': upload_submit_seconds,
'resident_upload_overlaps_block_preparation': True,
'weight_cache_headroom_bytes': self.weight_cache_headroom_bytes,
+ 'nonlocal_reserve_bytes': self.nonlocal_reserve_bytes,
'weight_cache_pin_order': pin_order,
'host_pinning_during_load': incremental_pinning,
'host_preload_seconds': self.host_preload_seconds,
diff --git a/freevideo_engine/system.py b/freevideo_engine/system.py
index 0ecbf65..ff4e128 100644
--- a/freevideo_engine/system.py
+++ b/freevideo_engine/system.py
@@ -88,18 +88,21 @@ def weight_cache_headroom(*, system=None, streamed=False, cpu_outputs=True, canv
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.
- Linux CPU readouts measured 4.56 GiB beyond retained weights in the same
- complete request. Keep 5 GiB at that geometry; larger requests additionally
- reserve 2.5 GiB per reference token volume for their growing host readouts.
- Unknown geometry retains the original allowance. This is a starting
- estimate; complete local observations and runtime RAM guards still apply.
+ CPU readouts measured 4.56 GiB beyond retained weights on Linux.
+ Keep 5 GiB at that geometry there; Windows page-locks the readouts on top
+ of about 4.0 GiB of non-pinned private working set (12/32 Ada laptop) and
+ keeps its 8 GiB. Larger requests additionally reserve 2.5 GiB per reference
+ token volume for their growing host readouts.
+ Unstreamed placements, platforms without a measurement and unknown
+ geometry retain the original allowance. This is a starting estimate;
+ complete local observations and runtime RAM guards still apply.
"""
if system is None:
system = 'Windows' if windows() else 'Linux'
- if system != 'Linux' or not streamed:
+ if system not in ('Linux', 'Windows') or not streamed:
return HOST_WEIGHT_HEADROOM
if not cpu_outputs:
- return int(3.5 * 2**30)
+ return int(3.5 * 2**30) if system == 'Linux' else HOST_WEIGHT_HEADROOM
if canvas is None:
return HOST_WEIGHT_HEADROOM
from .geometry import geometry
@@ -107,7 +110,10 @@ def weight_cache_headroom(*, system=None, streamed=False, cpu_outputs=True, canv
if any(canvas.get(key) != checked[key] for key in ('width', 'height', 'frames', 'video_tokens')):
raise ValueError('Host cache allowance requires consistent request geometry')
growth = max(0., checked['video_tokens'] / (72 * 1008) - 1.)
- return int((5. + 2.5 * growth) * 2**30)
+ # Windows page-locks these readouts on top of the ~4.0 GiB measured there,
+ # so it keeps its original 8 GiB at the measured geometry and grows with it.
+ base = HOST_WEIGHT_HEADROOM / 2**30 if system == 'Windows' else 5.
+ return int((base + 2.5 * growth) * 2**30)
def effective_available():
diff --git a/freevideo_engine/win32.py b/freevideo_engine/win32.py
index 84f2a12..fd3ffc7 100644
--- a/freevideo_engine/win32.py
+++ b/freevideo_engine/win32.py
@@ -215,18 +215,63 @@ def processes():
lib.CloseHandle(snapshot)
+class InaccessibleProcess(PermissionError):
+ """OpenProcess refused even PROCESS_QUERY_LIMITED_INFORMATION for this PID."""
+
+
+def process_names():
+ """Executable names by PID for diagnostics; empty when a snapshot is unavailable."""
+ try:
+ lib = kernel32()
+ snapshot = lib.CreateToolhelp32Snapshot(2, 0)
+ if snapshot == C.c_void_p(-1).value:
+ return {}
+ try:
+ entry = ProcessEntry()
+ entry.dwSize = C.sizeof(entry)
+ names, more = {}, lib.Process32FirstW(snapshot, C.byref(entry))
+ for _ in range(1 << 16):
+ if not more:
+ break
+ names[entry.pid] = entry.exe
+ more = lib.Process32NextW(snapshot, C.byref(entry))
+ return names
+ finally:
+ lib.CloseHandle(snapshot)
+ except (OSError, AttributeError, ValueError):
+ return {}
+
+
def process_memory(pid, *, parent_start_tick=None):
"""Read counters; a tree query also returns identity for old/exited children."""
lib = kernel32()
# Current Windows supports these queries without PROCESS_VM_READ. Keep a
# synchronized handle so exit during a query is checked on this same process,
# not on a potentially recycled PID.
- handle = lib.OpenProcess(0x1000 | 0x100000, False, pid)
+ handle, synchronized = lib.OpenProcess(0x1000 | 0x100000, False, pid), True
if not handle:
- if C.get_last_error() == 87: # PID exited between enumeration and OpenProcess.
+ error = C.get_last_error()
+ if error == 87: # PID exited between enumeration and OpenProcess.
return None
- raise C.WinError(C.get_last_error())
+ if error != 5:
+ raise C.WinError(error)
+ # Another account's process can grant PROCESS_QUERY_LIMITED_INFORMATION
+ # but not SYNCHRONIZE; read it with that right and judge exit by its code.
+ handle, synchronized = lib.OpenProcess(0x1000, False, pid), False
+ if not handle:
+ error = C.get_last_error()
+ if error == 87:
+ return None
+ if error == 5:
+ raise InaccessibleProcess(5, 'Access is denied.', None, 5)
+ raise C.WinError(error)
started = None
+ def signaled():
+ if synchronized:
+ return lib.WaitForSingleObject(handle, 0) == 0
+ code = DWORD()
+ # An exit code equal to STILL_ACTIVE reads as running, never as exited.
+ return bool(lib.GetExitCodeProcess(handle, C.byref(code))) and code.value != 259
def exited_row():
return {'start_tick': started, 'exited': True} if parent_start_tick is not None and started is not None else None
try:
@@ -238,7 +283,7 @@ def process_memory(pid, *, parent_start_tick=None):
# for memory counters (which may be inaccessible for system processes).
if parent_start_tick is not None and started < parent_start_tick:
return {'start_tick': started, 'excluded': 'predates-parent'}
- if lib.WaitForSingleObject(handle, 0) == 0:
+ if signaled():
return exited_row()
memory, io = ProcessCounters(), IoCounters()
memory.cb = C.sizeof(memory)
@@ -252,7 +297,7 @@ def process_memory(pid, *, parent_start_tick=None):
'read_bytes': io.read_bytes if io_ok else 0, 'write_bytes': io.write_bytes if io_ok else 0,
'io_complete': bool(io_ok), 'start_tick': started}
except OSError:
- if lib.WaitForSingleObject(handle, 0) == 0:
+ if signaled():
return exited_row()
raise
finally:
@@ -283,6 +328,7 @@ class ProcessMemory:
pending, visited = [(root_pid, None)], set()
rss = private = resident = count = 0
incomplete, errors, excluded = [], [], []
+ names = None
# Parents first: each edge must agree with the processes' creation times.
for pid, parent_started in pending:
if pid in visited:
@@ -311,12 +357,34 @@ class ProcessMemory:
resident += row['private_working_set_bytes']
self.io[(pid, row['start_tick'])] = (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
+ if parent_started is None:
+ # The request's own worker must stay measurable.
+ incomplete.append(pid)
+ errors.append(dict(pid=pid, parent_pid=parents.get(pid), exe=names.get(pid),
+ error=str(error), winerror=5, exited=None))
+ else:
+ # FreeVideo starts its helpers under the same account, so it
+ # can always open them. A descendant refused even limited
+ # query was started by Windows in another context (a crash
+ # reporter, for one); its pages are not this request's
+ # working set, and the system availability floor still
+ # applies. One such child used to abort a generation.
+ excluded.append(dict(pid=pid, parent_pid=parents.get(pid), exe=names.get(pid),
+ start_tick=None, parent_start_tick=parent_started, reason='inaccessible'))
+ pending.extend((child, parent_started) for child in children.get(pid, []))
+ continue
except OSError as error:
exited = process_exited(pid)
if exited is not True:
+ names = process_names() if names is None else names
incomplete.append(pid)
- errors.append(dict(pid=pid, parent_pid=parents.get(pid),
- error=str(error), winerror=getattr(error, 'winerror', None), exited=exited))
+ error_row = dict(pid=pid, parent_pid=parents.get(pid),
+ error=str(error), winerror=getattr(error, 'winerror', None), exited=exited)
+ if names.get(pid):
+ error_row['exe'] = names[pid]
+ errors.append(error_row)
pending.extend((child, started) for child in children.get(pid, []))
self.errors.extend(errors[:max(0, 16-len(self.errors))])
self.excluded.extend(excluded[:max(0, 16-len(self.excluded))])
diff --git a/freevideo_engine/windows_gpu_memory.py b/freevideo_engine/windows_gpu_memory.py
index fc76ab9..f029ace 100644
--- a/freevideo_engine/windows_gpu_memory.py
+++ b/freevideo_engine/windows_gpu_memory.py
@@ -89,3 +89,46 @@ class AdapterMemory:
if self.adapter:
pointer, self.adapter = self.adapter, c.c_void_p()
method(pointer, 2, c.c_uint32)(pointer)
+
+
+# Page-locked host memory counts against the process's WDDM non-local budget,
+# which Windows sets near half of physical RAM however much RAM is free. An
+# RTX 5060 Ti with 27.98 GiB of RAM reported a 13.24 GiB budget: 30 pinned
+# blocks and two transfer slots used 13.06 GiB and ran; 32 blocks failed with
+# cudaErrorMemoryAllocation at the token refiner's first copy. The transfer
+# slots (0.81 GiB) and the refiner slot (0.36 GiB) are allocated after weight
+# pinning; the rest covers driver allocations and other processes moving the budget.
+NONLOCAL_PIN_RESERVE = 2 * 2**30
+
+
+def nonlocal_readout_bytes(canvas, attention_width, text_rows=1024):
+ """Page-locked attention readouts the CPU-output path allocates after weight pinning.
+
+ One soft-attention readout spans every row and one linear readout every
+ video row, each in BF16, at the full-resolution pass; the half-resolution
+ first pass may still hold its quarter-sized pair in the host cache.
+ """
+ canvas = canvas or {}
+ video = canvas.get('video_tokens', 72576)
+ rows = video + text_rows + canvas.get('reference_video_tokens', 0) + canvas.get('reference_audio_tokens', 0)
+ return int(1.25 * (rows + video) * attention_width * 2)
+
+
+def nonlocal_pin_capacity(reserve=NONLOCAL_PIN_RESERVE):
+ """Bytes this process may still page-lock inside its non-local budget, or None if unreadable."""
+ reader = None
+ try:
+ reader = AdapterMemory()
+ segment = reader.sample()['nonlocal']
+ except (OSError, AttributeError, ValueError, KeyError):
+ return None
+ finally:
+ if reader is not None:
+ try:
+ reader.close()
+ except OSError:
+ pass # The budget was already read; a failed release changes nothing here.
+ budget, usage = segment.get('budget_bytes'), segment.get('usage_bytes')
+ if type(budget) is not int or budget <= 0 or type(usage) is not int or usage < 0:
+ return None
+ return max(0, budget - usage - reserve)