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.

An engine whose GPU memory did not free is released without copying back first

Bowen Xue3172802e73fe
diff --git a/freevideo_engine/background_room.py b/freevideo_engine/background_room.py
index d696e90..d054a75 100644
--- a/freevideo_engine/background_room.py
+++ b/freevideo_engine/background_room.py
@@ -1,8 +1,8 @@
"""Whether the user's other programs leave room for a background compile.
-The compile loads the model as a request would, so it needs the host memory a
-request needs and the whole GPU. It starts only when the system has a recent
-request's host peak plus RAM_MARGIN available, the GPU has been nearly idle
+The compile covers only the first sampling block and one decode clip. It
+starts only with its own measured host peak plus RAM_MARGIN available, using
+a measured baseline until a matching compile has completed. The GPU must be nearly idle
and other programs hold little of its memory. While it runs it gives way when
availability falls under RAM_FLOOR, or when another program starts using the
GPU, grows its memory there or keeps its cores busy. Measured on the machine,
@@ -24,11 +24,13 @@ import sys
import time
GiB = 2**30
-RAM_MARGIN = 4 * GiB
+RAM_MARGIN = 2 * GiB
RAM_FLOOR = 2 * GiB
-# A request's host peak when this machine has measured none: the private
-# working set of a 1344x768 request on a 12 GB Windows laptop was 4.0 GiB.
-DEFAULT_RAM_NEED = 8 * GiB
+# Cold 1344x768/243-frame, two-pass precompile: 5.22 GiB working PSS for
+# supervisor + workers on Linux, under a 12 GiB/no-swap cgroup, with no host
+# weight retention and one compiler. Round up; Windows needs physical checks.
+# RAM_MARGIN keeps the existing running floor available beyond this peak.
+DEFAULT_RAM_NEED = 6 * GiB
GPU_IDLE_PERCENT = 10
GPU_SAMPLES = 5
GPU_OTHER_SHARE = .2
@@ -178,14 +180,24 @@ def available_memory(sample=None):
return min(available, group) if group is not None else available
-def recent_need(history):
- """The largest host peak of this machine's recent requests, or DEFAULT_RAM_NEED."""
- try:
- peaks = [row['observation'].get('ram_peak_bytes') for row in history.observations(limit=16, include_details=False)]
- except Exception:
- peaks = []
- peaks = [peak for peak in peaks if type(peak) is int and peak > 0]
- return max(peaks) if peaks else DEFAULT_RAM_NEED
+def compile_need(previous, *, identity, requested, inputs):
+ """Own completed compile peak for the same workload, never a generation peak.
+
+ Changed code, packages, device, placement inputs or shapes use the baseline;
+ an incomplete sample cannot establish a smaller memory requirement.
+ """
+ if (not isinstance(previous, dict) or identity is None or previous.get('success') is not True
+ or previous.get('identity') != identity or previous.get('requested') != requested
+ or previous.get('inputs') != inputs):
+ return DEFAULT_RAM_NEED
+ memory = previous.get('host_memory')
+ if not isinstance(memory, dict) or memory.get('complete') is not True:
+ return DEFAULT_RAM_NEED
+ metric = 'tree private working set' if sys.platform == 'win32' else 'inference working PSS'
+ peak = memory.get('peak_bytes')
+ if memory.get('metric') != metric or type(peak) is not int or peak <= 0:
+ return DEFAULT_RAM_NEED
+ return max(DEFAULT_RAM_NEED, peak)
class Room:
@@ -208,6 +220,9 @@ class Room:
self.sampled = int(time.time() * 1e6)
self.started = self.sampled / 1e6
self.trace = collections.deque(maxlen=TRACE_SAMPLES)
+ self.host_peak = 0
+ self.host_samples = 0
+ self.host_complete = True
def refresh(self):
"""Our processes now: this one, its descendants and the owner.
@@ -258,6 +273,14 @@ class Room:
def run_reason(self, sample=None):
"""Why a running compile should give way now, or None. Call it often; the GPU is read once a second."""
+ if sample is not None:
+ from .system import inference_memory_sample
+ peak = inference_memory_sample(sample)
+ self.host_samples += 1
+ if type(peak) is int and peak >= 0:
+ self.host_peak = max(self.host_peak, peak)
+ else:
+ self.host_complete = False
available = available_memory(sample)
if available < RAM_FLOOR:
return 'memory: %.1f GiB available' % (available / GiB)
@@ -298,6 +321,12 @@ class Room:
return 'gpu: another program keeps it busy'
return None
+ def memory_result(self):
+ """The supervisor and every worker/compiler, excluding reclaimable mapped pages."""
+ return dict(peak_bytes=self.host_peak, samples=self.host_samples,
+ complete=self.host_complete and self.host_samples > 0,
+ metric='tree private working set' if sys.platform == 'win32' else 'inference working PSS')
+
def samples(self):
"""Other programs' samples for the log: [seconds since this room started,
pid, % of cores, seconds after the first sample's own stamp]."""
diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py
index f60466c..1363e97 100644
--- a/freevideo_engine/bootstrap.py
+++ b/freevideo_engine/bootstrap.py
@@ -229,6 +229,12 @@ def torch_stack(name):
return name in ('torch', 'torchvision', 'torchaudio') or name.startswith(('nvidia-', 'cuda-'))
+def environment_seeded(folder):
+ """An environment uv seeded with pip: the folder has one, as `uv venv --seed` leaves it."""
+ folder = Path(folder)
+ return any(folder.glob('Lib/site-packages/pip')) or any(folder.glob('lib/python*/site-packages/pip'))
+
+
def environment_in_place(row, python_version):
"""An existing environment that only lacks ordinary packages: setup adds them beside the rest."""
if not row.get('exists') or row.get('error'):
@@ -1333,8 +1339,9 @@ class Installer:
self.ui.end(key, success=success, detail=(getattr(progress, 'last_notice', None) or 'Log: ' + str(log))
if self.ui.verbose or not success else 'Ready')
if child.returncode:
- from .failure_details import setup_command_failure
- raise RuntimeError(setup_command_failure(label, log, child.returncode))
+ from .failure_details import setup_command_failure, environment_python_removed
+ raise RuntimeError(environment_python_removed(args, getattr(self, 'pythons', {}).values())
+ + setup_command_failure(label, log, child.returncode))
return log
def component_tasks(self, uv):
@@ -1359,8 +1366,25 @@ class Installer:
pythons[name] = python
writer = ('environment:' + name,)
def environment(folder=venv, executable=python, label=name):
- if not executable.exists():
- return self.packages(label + '-venv', [uv, 'venv', '--seed', '--python', self.versions['python'], folder])
+ if executable.exists() and environment_seeded(folder):
+ return None
+ command = [uv, 'venv', '--seed', '--python', self.versions['python']]
+ # The Python file came back (restored from quarantine) without
+ # the seed packages: keep it and add them. Without the file, the
+ # folder is a leftover that uv replaces.
+ if executable.exists():
+ command.append('--allow-existing')
+ elif folder.exists():
+ command.append('--clear')
+ try:
+ return self.packages(label + '-venv', [*command, folder])
+ except RuntimeError as error:
+ from .failure_details import environment_python_removed
+ # uv failed while the new interpreter was disappearing.
+ removed = '' if executable.exists() else environment_python_removed([executable], [executable])
+ if not removed:
+ raise
+ raise RuntimeError(removed + str(error)) from error
task(name + '-venv', environment, ('python',), writer)
command = [uv, 'pip', 'install', '--python', python, *spec['torch'], '-c', constraints_file(name, self.system)]
family = 'torch-' + spec['cuda'] + '-' + spec['torch'][0].split('==')[1]
diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py
index bb2d15b..0d93d7c 100644
--- a/freevideo_engine/failure_details.py
+++ b/freevideo_engine/failure_details.py
@@ -77,6 +77,20 @@ def setup_command_failure(label, log, exit_code):
return '\n'.join(lines) + STEP_OUTPUT + output
+# Leads the error of a step that needed an environment's Python file after it
+# disappeared, e.g. while security software was holding it in quarantine.
+ENVIRONMENT_PYTHON_REMOVED = 'The Python file of the FreeVideo environment is missing'
+
+
+def environment_python_removed(args, pythons):
+ """The line that opens a failed step's error when it used an environment Python that is gone, or ''."""
+ used = {str(value) for value in args}
+ for python in pythons:
+ if str(python) in used and not io_path(python).exists():
+ return '%s: %s\n' % (ENVIRONMENT_PYTHON_REMOVED, python)
+ return ''
+
+
# Checked before free space: freeing space cannot fix a disk that cannot hold the installation.
PLACE_RULES = (
(r'The installation folder is on a FAT32 disk', 'disk-format',
@@ -195,6 +209,26 @@ def _stopped_on_missing_module(text):
and not any('for custom nodes' in line for line in lines[errors[-1] + 1:])
+def _without_ready_curl_diagnostics(text):
+ """Ignore successful tool checks only when matching failure guidance.
+
+ Candidate failures can be normal (e.g. Sysnative from a 64-bit process).
+ The complete diagnostics stay in the caller's retained and copied output.
+ """
+ lines = []
+ for line in text.splitlines(keepends=True):
+ if line.lstrip().startswith('{'):
+ try:
+ report = json.loads(line)
+ except ValueError:
+ pass
+ else:
+ if isinstance(report, dict) and report.get('event') == 'curl_diagnostic' and report.get('status') == 'ready':
+ continue
+ lines.append(line)
+ return ''.join(lines)
+
+
def launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_repair=False, repairs_comfy=False,
unavailable='none'):
"""Short guidance for known failures; callers retain the full error separately.
@@ -207,11 +241,11 @@ def launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_rep
"""
if not value:
return dict(title='', detail='', action='', kind='')
+ text = _without_ready_curl_diagnostics(str(value))
from .offline_errors import alias_failure, guidance
- if alias_failure(value):
+ if alias_failure(text):
return dict(title=guidance('title', zh), detail=guidance('runtime-alias', zh),
action='', kind='runtime-alias')
- text = str(value)
summary = text.partition(STEP_OUTPUT)[0]
from .comfy_launcher_runtime import OlderLauncher
# Controller and offline Importer retain strings; direct callers keep the exception.
@@ -342,6 +376,11 @@ def launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_rep
('The browser has not opened FreeVideo', '浏览器还没有打开 FreeVideo'),
('Click “Open FreeVideo”. If the page stays blank or keeps loading, open it in a current Chrome or Edge.',
'请点击“打开 FreeVideo”。如果页面空白或一直在加载,请用最新版 Chrome 或 Edge 打开。')),
+ (r'NVIDIA driver/nvidia-smi is missing\.', 'gpu-driver-missing',
+ ('No NVIDIA driver was found', '未找到 NVIDIA 显卡驱动'),
+ ('If this computer has an NVIDIA graphics card, install NVIDIA driver 580 or newer, '
+ 'restart the computer, then click Retry installation.',
+ '如果这台电脑有 NVIDIA 显卡,请安装 580 或更新版本的 NVIDIA 显卡驱动,重启电脑后点击“重试安装”。')),
(r'CUDA_ARCH_UNSUPPORTED', 'gpu-architecture',
('This GPU lacks the required compute support', '这张显卡不满足当前计算要求'),
('The detected GPU and compute capability are shown below. The CUDA runtime requires native BF16 computation (SM80 or newer). Use a compatible GPU; changing the driver does not change its hardware capability.',
@@ -394,6 +433,11 @@ def launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_rep
_joined(CHANGED_WHY['files'], CHANGED_REPAIR)),
(r'The installation plan changed\. Detect configuration again', 'plan-changed', CHANGED_TITLE,
_joined(CHANGED_WHY['other'], CHANGED_REPAIR)),
+ (ENVIRONMENT_PYTHON_REMOVED, 'environment-python-removed',
+ ('A Python file is missing', '一个 Python 文件不见了'),
+ ('It may have been quarantined by security software. Restore the file or allow the FreeVideo folder, '
+ 'then click Retry installation.',
+ '可能被安全软件隔离了。恢复这个文件或允许 FreeVideo 所在的文件夹后,点“重试安装”。')),
(r'PermissionError|Access is denied|Permission denied|WinError 5\b', 'permission',
('This folder is not writable', '无法写入这个目录'),
('Choose an installation folder you can write to, then retry.', '选择有写入权限的安装目录后重试。')),
diff --git a/freevideo_engine/gpu_budget.py b/freevideo_engine/gpu_budget.py
index 4ed6ddc..efb1bc4 100644
--- a/freevideo_engine/gpu_budget.py
+++ b/freevideo_engine/gpu_budget.py
@@ -268,6 +268,16 @@ class LiveGPUBudget:
return None
return max(0, total - used)
+ def device_free(self):
+ """Physical device memory no process holds right now, or None if unread."""
+ self.device_memory = None
+ if self.device is not None:
+ try:
+ self.device_memory = self.device.sample()
+ except (OSError, RuntimeError, AttributeError, ValueError) as error:
+ self._error(error)
+ return self.device_headroom()
+
def _settle(self, workspace):
"""Wait for a driver budget that again covers `workspace` twice in a row."""
deadline = self.clock() + self.settle_seconds
diff --git a/freevideo_engine/precompile.py b/freevideo_engine/precompile.py
index d81eca9..f12f8a3 100644
--- a/freevideo_engine/precompile.py
+++ b/freevideo_engine/precompile.py
@@ -201,9 +201,10 @@ def run(machine, *, environment=None, timeout=TIMEOUT_SECONDS, background=False,
checkpoint()
room = None
if background:
- from .background_room import DEFAULT_RAM_NEED, Room, recent_need
+ from .background_room import Room, compile_need
room = Room(machine.get('gpu_uuid'), owner=owner,
- need_bytes=recent_need(history) if history is not None else DEFAULT_RAM_NEED)
+ need_bytes=compile_need(previous, identity=identity,
+ requested=json.loads(json.dumps(shapes)), inputs=receipt['inputs']))
reason = room.start_reason()
if reason:
room.close()
@@ -353,6 +354,8 @@ def compile_shapes(machine, shapes, history, identity, receipt, environment, tim
# receipt records it, so the next start does not compile it again.
receipt['success'] = all(row.get('returncode') == 0 for row in receipt['shapes'])
receipt['seconds'] = time.time() - receipt['started']
+ if room is not None:
+ receipt['host_memory'] = room.memory_result()
if receipt['success']:
mark(receipt['caches'], receipt['started'])
save(root / 'precompile.json', receipt)
@@ -371,6 +374,10 @@ def compile_plan(receipt, shape, request, profile, index, folder, environment, d
path = folder / ('request-%d.json' % index)
save(path, request)
env = inference_environment(environment, profile['inference_ram_budget_gb'] * 1e9)
+ if room is not None:
+ # Background work must not grow a pool of compiler heaps even
+ # when the generation profile has a generous RAM budget.
+ env['TORCHINDUCTOR_COMPILE_THREADS'] = '1'
env.update(PYTORCH_ALLOC_CONF=profile['allocator_config'], PYTORCH_CUDA_ALLOC_CONF=profile['allocator_config'])
log = folder / ('worker-%d.log' % index)
returncode = watch_worker([sys.executable, '-m', 'freevideo_engine.precompile_worker', '--request', str(path)],
@@ -441,7 +448,9 @@ def watch_worker(command, env, descriptor, log, timeout, room):
deadline = time.monotonic() + timeout
try:
while process.poll() is None:
- checkpoint(room, memory.sample(process.pid) if room is not None else None)
+ # Include this supervisor's torch/conditioning heap and probe children,
+ # not just the active worker. This also credits only our mapped pages.
+ checkpoint(room, memory.sample(os.getpid()) if room is not None else None)
if time.monotonic() > deadline:
raise subprocess.TimeoutExpired(command, timeout)
try:
@@ -454,6 +463,15 @@ def watch_worker(command, env, descriptor, log, timeout, room):
return process.returncode
+def worker_options(options):
+ """No host weight retention for blocks that a compile never executes.
+
+ Keep every compute shape, GPU placement and arithmetic option. Streaming
+ profiles can then bind offloaded weights without a load-all/pinning pass.
+ """
+ return dict(options, pin_host_gb=0., pin_host_weights=False, preload_host=False)
+
+
def zero_conditioning(folder, tokens):
"""A text-to-video prompt of `tokens` rows; only its length reaches a kernel."""
import torch
diff --git a/freevideo_engine/precompile_worker.py b/freevideo_engine/precompile_worker.py
index 686e4a7..1512918 100644
--- a/freevideo_engine/precompile_worker.py
+++ b/freevideo_engine/precompile_worker.py
@@ -111,6 +111,7 @@ def first_pass(engine, conditioning, request):
def compile_request(request):
from .runtime import Engine
from .worker import device_memory_report, prefetch_compiler_keys
+ from .precompile import worker_options
torch.set_num_threads(8)
prefetch_compiler_keys()
receipt = dict(success=False, geometry=request['geometry'], passes=[])
@@ -122,7 +123,7 @@ def compile_request(request):
# A missing sampling table becomes zeros of its shape: it is installed by
# the request that uses it, never by setup.
engine = Engine(request['cache'], gpu_allocation_bytes=int(allocation), fetch_tables=False,
- **dict(request['engine_options'], canvas=request['geometry']))
+ **dict(worker_options(request['engine_options']), canvas=request['geometry']))
receipt['load_seconds'] = time.perf_counter() - tick
plan = request['sampling_plan']
channels, base = engine.transformer.config.in_channels, engine.base
diff --git a/freevideo_engine/resident_models.py b/freevideo_engine/resident_models.py
index 270a5d9..4beeae5 100644
--- a/freevideo_engine/resident_models.py
+++ b/freevideo_engine/resident_models.py
@@ -8,6 +8,8 @@ import torch
from .torch_compat import empty_host_cache, host_cache_release_supported
GiB = 1 << 30
+# Where a preview's sampling peak is kept, apart from its complete request's.
+PREVIEW_STAGE = 'engine_preview'
def key(value):
@@ -74,6 +76,24 @@ def pinned_cpu_storages(model, *, committed=False):
return storages
+def is_parked(model):
+ """Whether an engine handed its GPU weights to host memory with park()."""
+ return type(getattr(model, 'parked', None)) is list
+
+
+def parked_bytes(model):
+ """Host bytes of weights an engine moved off the GPU with park()."""
+ if not is_parked(model):
+ return 0
+ records = model.parked
+ total = 0
+ for module, kind, name in records:
+ tensor = getattr(module, kind).get(name)
+ if tensor is not None:
+ total += tensor.numel() * tensor.element_size()
+ return total
+
+
def release_encoder(clip, manager):
"""Discard our Windows mapped encoder without a full GPU-to-CPU copy.
@@ -129,6 +149,12 @@ class ModelBank:
self.gpu_reserve = 0
self.ram_budget = None
self.decisions = []
+ # Set by a request that can read the whole device: bytes no process
+ # holds, and the growth reserve that request keeps out of them. The
+ # planning budget already excludes that reserve; the device reading
+ # does not.
+ self.device_free = None
+ self.device_reserve = 0
def configure(self, gpu_budget, ram_budget=None, *, gpu_reserve=0):
self.gpu_budget = int(gpu_budget)
@@ -179,6 +205,38 @@ class ModelBank:
host_cache_released=host_cache_released,
released_gpu_bytes=max(0, before - torch.cuda.memory_allocated())))
+ def park(self, role, reason, ram_need=2*GiB):
+ """Release only an idle engine's GPU weights and keep its host side.
+
+ Only when live RAM also covers the parked copy beside the next stage's
+ own need; otherwise the caller releases the whole model as before.
+ """
+ entry = self.entries.get(role)
+ model = entry['model'] if entry else None
+ if role != 'engine' or not callable(getattr(model, 'park', None)) or is_parked(model):
+ return False
+ held = gpu_bytes(model)
+ def declined(why):
+ self.decisions.append(dict(action='keep_declined', role=role, reason=why, gpu_bytes=held))
+ return False
+ if not self.ram_fits(ram_need + held):
+ return declined('Host memory does not cover the parked weights beside the next stage')
+ started = time.perf_counter()
+ before = torch.cuda.memory_allocated()
+ moved = model.park()
+ if moved is None:
+ return declined('Weights share storage; a per-tensor copy would duplicate it')
+ torch.cuda.empty_cache()
+ released = max(0, before - torch.cuda.memory_allocated())
+ if released < .9 * moved:
+ # Something outside the registered tensors still holds these
+ # weights, so parking would keep two copies. The caller releases
+ # the model as before; copying back first could itself not fit.
+ return declined('GPU weights are still referenced elsewhere')
+ self.decisions.append(dict(action='park', role=role, reason=reason, parked_bytes=moved,
+ released_gpu_bytes=released, seconds=time.perf_counter() - started))
+ return True
+
def clear(self, reason='Request failed or session configuration changed'):
for role in list(self.entries):
self.drop(role, reason)
@@ -210,24 +268,66 @@ class ModelBank:
workspace = 2*GiB if audio else max(2*GiB, 6*GiB*area)
self.make_room('input_audio_vae' if audio else 'input_video_vae', weights + workspace)
- def make_room(self, role, peak, *, model=None, ram_need=2*GiB):
+ def device_ceiling(self):
+ """What this process's allocator can hold before the device itself is full.
+
+ Its own pool plus what no process holds. Under Windows neither CUDA's
+ free memory nor the allocator budget counts other applications until
+ the device is already full. None when the device cannot be read.
+ """
+ read = self.device_free
+ if not callable(read):
+ return None
+ try:
+ free = read()
+ except (OSError, RuntimeError, AttributeError, ValueError):
+ return None
+ if type(free) is not int or free < 0:
+ return None
+ return free + torch.cuda.memory_reserved()
+
+ def make_room(self, role, peak, *, model=None, ram_need=2*GiB, device=False):
retained = gpu_bytes(model) if model is not None else 0
extra = max(0, int(peak) - retained)
- before = self.available()
+ # Read once: releasing a model moves its bytes from this pool to the
+ # device's free memory and leaves their sum where it was.
+ ceiling = self.device_ceiling() if device else None
+ reserve = max(self.gpu_reserve, self.device_reserve)
+ budgeted = self.available
+ def available():
+ room = budgeted()
+ if ceiling is not None:
+ room = min(room, max(0, ceiling - torch.cuda.memory_allocated() - reserve))
+ return room
+ before = available()
# Once conditioning is ready the current video cannot use the encoder
# again. Reclaim its speculative weights before a VAE needed later in
# this very request, regardless of how recently preloading touched it.
def eviction_order(item):
return (0 if item == 'encoder' and role != 'encoder' else 1, self.entries[item]['used'])
for other in sorted(self.entries, key=eviction_order):
- if self.available() >= extra and self.ram_fits(ram_need):
+ if available() >= extra and self.ram_fits(ram_need):
break
- if other != role:
- self.drop(other, 'Next %s stage needs memory; cached weights are reclaimable' % role)
+ if other == role:
+ continue
+ if is_parked(self.entries[other]['model']):
+ # A parked engine holds no GPU memory; only RAM releases it.
+ if self.ram_fits(ram_need):
+ continue
+ elif self.available() < extra and self.park(
+ other, 'Next %s stage needs GPU memory; host copy kept for the next request' % role, ram_need):
+ continue
+ self.drop(other, 'Next %s stage needs memory; cached weights are reclaimable' % role)
self.decisions.append(dict(action='admit', role=role, estimated_peak_bytes=int(peak),
reused_model_bytes=retained, additional_bytes=extra, available_before_bytes=before,
- available_after_bytes=self.available(), budget_bytes=self.gpu_budget,
+ available_after_bytes=available(), budget_bytes=self.gpu_budget,
reason='Keep idle models when live resources cover the next stage; estimates do not certify capacity'))
+ if ceiling is not None:
+ self.decisions[-1]['device_ceiling_bytes'] = ceiling
+
+ def engine_on_gpu(self):
+ entry = self.entries.get('engine')
+ return entry is not None and not is_parked(entry['model'])
def engine_key(self, request):
return key(dict(cache=file_identity(Path(request['cache'])/'manifest.json'),
@@ -273,14 +373,30 @@ class ModelBank:
max(0, activation_bytes(head, rows) - activation_bytes(8, rows)))
source = 'windows_gpu_output_workspace'
estimate = int(options.get('resident_blocks', 0)*BLOCK_BYTES + workspace)
- observed = self.peaks.get(('engine', identity))
+ # A preview samples the first pass alone, under the key of the request
+ # it previews. Its peak is evidence for another preview only: an
+ # upscale of it runs the second pass, whose workspace is about twice
+ # as large, and an idle audio decoder admitted on the preview's figure
+ # stayed on the card through that pass. A complete request's peak
+ # covers a preview too.
+ preview = request.get('preview') is True
+ observed = self.peaks.get((PREVIEW_STAGE if preview else 'engine', identity))
+ if observed is None and preview:
+ observed = self.peaks.get(('engine', identity))
peak = estimate if observed is None else observed
- self.make_room('engine', peak, model=found)
+ # Sampling is the long stage: an idle model stays through it only where
+ # the device still holds both beside every other application.
+ self.make_room('engine', peak, model=found, device=True)
self.decisions[-1]['evidence'] = dict(source=source if observed is None else 'complete_local_stage_peak',
cold_estimate_bytes=estimate, observed_peak_bytes=observed, video_and_reference_tokens=rows,
head_chunk=options.get('head_chunk', 8), window_batch=options.get('window_batch', 1),
requested_pin_host_gb=requested_pin_gb,
retained_pin_host_gb=retained_pin_gb if hit else None)
+ if found is not None and is_parked(found):
+ started = time.perf_counter()
+ moved = found.unpark()
+ self.decisions.append(dict(action='unpark', role='engine', moved_bytes=moved,
+ seconds=time.perf_counter() - started))
if found is None:
found = factory()
self.put('engine', identity, found)
@@ -344,6 +460,8 @@ class ModelBank:
for entry in self.entries.values():
host.update(pinned_cpu_storages(entry['model']))
committed.update(pinned_cpu_storages(entry['model'], committed=True))
+ # Parked engine weights: private host copies, freed with the model.
+ parked = sum(parked_bytes(entry['model']) for entry in self.entries.values())
memory, gpu_capacity = None, None
from .system import windows
if windows():
@@ -356,10 +474,11 @@ class ModelBank:
gpu_capacity = owned_pool_capacity(torch)
can_release_host = host_cache_release_supported(torch)
return dict(reclaimable_gpu_bytes=torch.cuda.memory_reserved(),
- reclaimable_ram_bytes=sum(host.values()) if can_release_host else 0,
- reclaimable_commit_bytes=sum(committed.values()) if can_release_host else 0,
- retained_pinned_ram_bytes=sum(host.values()), host_cache_release_supported=can_release_host,
+ reclaimable_ram_bytes=(sum(host.values()) if can_release_host else 0) + parked,
+ reclaimable_commit_bytes=(sum(committed.values()) if can_release_host else 0) + parked,
+ retained_pinned_ram_bytes=sum(host.values()), parked_ram_bytes=parked,
+ host_cache_release_supported=can_release_host,
memory=memory, gpu_capacity=gpu_capacity,
- ram_credit_scope='Owned pinned model storage only; deduplicated, reclaimable on eviction. No mapped-page or swap credit; commit only for pinned private storage.',
+ ram_credit_scope='Owned pinned model storage and parked engine weights; deduplicated, reclaimable on eviction. No mapped-page or swap credit; commit only for private storage.',
gpu_uuid=uuid, models=[dict(role=role, gpu_bytes=gpu_bytes(entry['model']))
for role, entry in self.entries.items()], decisions=self.decisions)
diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.py
index 5f92cae..b3feeee 100644
--- a/freevideo_engine/runtime.py
+++ b/freevideo_engine/runtime.py
@@ -120,6 +120,8 @@ class Engine:
self.cache = Path(cache)
self.input_cache_dir = input_cache_dir
self.closed = False
+ # (module, '_parameters' or '_buffers', name) moved to host by park().
+ self.parked = None
self.offloader = None
self.stream_weight_source = None
self.stream_refiner_count = 0
@@ -889,9 +891,71 @@ class Engine:
return {'seconds': time.perf_counter() - started, 'shape': list(text.shape),
'refiner_weights_released': True, 'offload': stats, 'cache_hit': False, 'cache_saved': saved, 'cache_note': note}
+ def device_tensors(self):
+ """The registered tensors this engine keeps on the GPU, or None.
+
+ None when two of them share storage or one is a view of a larger
+ storage: a per-tensor copy would duplicate that storage on its way back.
+ """
+ found, storages = [], set()
+ device = torch.device(self.device_backend.device).type
+ for module in self.transformer.modules():
+ for kind in ('_parameters', '_buffers'):
+ for name, tensor in getattr(module, kind).items():
+ if tensor is None or tensor.device.type != device:
+ continue
+ storage = tensor.untyped_storage()
+ if storage.data_ptr() in storages or storage.nbytes() != tensor.numel() * tensor.element_size():
+ return None
+ storages.add(storage.data_ptr())
+ found.append((module, kind, name))
+ return found
+
+ @torch.no_grad()
+ def park(self):
+ """Move the weights this engine keeps on the GPU to ordinary host memory.
+
+ Streamed, pinned and mapped weights stay where they are, so the next
+ request with the same plan copies only these back instead of reading,
+ binding and pinning every block again. Copies are exact, so the output
+ is unchanged. Returns the bytes moved, or None when this engine cannot
+ be parked; the caller then releases it as before.
+ """
+ if self.closed or self.parked is not None:
+ return None
+ found = self.device_tensors()
+ if found is None:
+ return None
+ moved = 0
+ for module, kind, name in found:
+ tensor = getattr(module, kind)[name]
+ moved += tensor.numel() * tensor.element_size()
+ # .data keeps every reference to this tensor object valid, as
+ # Module.to does for parameters.
+ tensor.data = tensor.data.to('cpu')
+ self.parked = found
+ gc.collect()
+ self.device_backend.empty_cache()
+ return moved
+
+ @torch.no_grad()
+ def unpark(self):
+ """Copy parked weights back to the GPU; returns the bytes moved."""
+ if self.parked is None:
+ return 0
+ moved = 0
+ for module, kind, name in self.parked:
+ tensor = getattr(module, kind)[name]
+ moved += tensor.numel() * tensor.element_size()
+ tensor.data = tensor.data.to(self.device_backend.device)
+ self.parked = None
+ self.device_backend.synchronize()
+ return moved
+
def close(self):
if self.closed:
return
+ self.parked = None
if self.schedule_hook is not None:
self.schedule_hook.remove()
self.transformer = None
diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.py
index de41b90..0c0e363 100644
--- a/freevideo_engine/worker.py
+++ b/freevideo_engine/worker.py
@@ -65,6 +65,9 @@ def device_memory_report(budget_bytes, allocator_limit_bytes=None, *, reserve_by
def generate(request, resident=None):
+ def released(engine):
+ # A parked engine (ModelBank.park) holds no GPU weights either.
+ return engine.closed or type(getattr(engine, 'parked', None)) is list
torch.set_num_threads(8)
started = time.perf_counter()
prefetch_compiler_keys()
@@ -136,6 +139,10 @@ def generate(request, resident=None):
# The pass cache grows only into memory no other process holds.
refresh_budget.device_headroom = live_budget.device_headroom
if resident is not None:
+ # Idle models stay beside sampling only where the device holds both,
+ # with this request's growth reserve left over.
+ resident.device_free = live_budget.device_free if live_budget is not None else None
+ resident.device_reserve = request.get('gpu_reserve_bytes', 0) if live_budget is not None else 0
limit = metrics['device_memory'].get('effective_allocator_limit_bytes')
if limit is not None:
resident.gpu_budget = min(resident.gpu_budget, limit)
@@ -227,7 +234,7 @@ def generate(request, resident=None):
resident.decoder_room(decoder, canvas)
latents, audio = latents.to('cuda'), audio.to('cuda')
metrics['latent_reload_seconds'] = time.perf_counter() - tick
- metrics['transformer_released_before_decode'] = resident is None or 'engine' not in resident.entries
+ metrics['transformer_released_before_decode'] = resident is None or not resident.engine_on_gpu()
else:
tick = time.perf_counter()
# Windows charges the allocator room still to be reserved to commit;
@@ -420,7 +427,7 @@ def generate(request, resident=None):
lift_canvas['width'], lift_canvas['height'], **kwargs)
except Exception as error:
from .adaptive import classify_failure
- if classify_failure(error)['kind'] != 'gpu_oom' or (engine.closed and memory_saving):
+ if classify_failure(error)['kind'] != 'gpu_oom' or (released(engine) and memory_saving):
raise
from .diagnostic_resources import error_details
upscale_failures.append(error_details(error))
@@ -429,7 +436,7 @@ def generate(request, resident=None):
# Leave the failed call's traceback before retrying so
# its tensors no longer occupy the allocator. Do not
# sample again or change the temporal normalization.
- if not engine.closed:
+ if not released(engine):
if resident is not None:
resident.drop('engine', 'Latent upscale allocation needs additional workspace')
else:
@@ -455,9 +462,10 @@ def generate(request, resident=None):
allocation_failures=upscale_failures,
torch_peak_allocated_bytes=torch.cuda.max_memory_allocated(),
torch_peak_reserved_bytes=torch.cuda.max_memory_reserved(),
- transformer_reloaded=engine.closed)
+ transformer_reloaded=released(engine))
metrics['latent_upscale'] = lifted
- if engine.closed:
+ # A parked engine is reacquired too: its GPU weights come back.
+ if released(engine):
tick = time.perf_counter()
engine, _ = resident.engine(request, factory) if resident is not None else (factory(), False)
reload_seconds = time.perf_counter() - tick
@@ -535,7 +543,7 @@ def generate(request, resident=None):
resident.decoder_room(decoder, canvas)
else:
engine.close()
- metrics['transformer_released_before_decode'] = engine.closed
+ metrics['transformer_released_before_decode'] = released(engine)
# Keep the bounded file reader alive through transformer teardown.
# Releasing DiT mappings is independent of the decoder checkpoint,
# so both operations can run concurrently and give slow storage
@@ -552,7 +560,7 @@ def generate(request, resident=None):
if live_budget is not None:
refresh_budget('decode')
if engine is not None:
- metrics['transformer_released_before_decode'] = engine.closed
+ metrics['transformer_released_before_decode'] = released(engine)
if resident is not None:
metrics['resident_admission'] = list(resident.decisions)
save(request['metrics'], metrics)
@@ -601,8 +609,9 @@ def generate(request, resident=None):
from .resident_models import key
if not resume:
from .two_pass_metrics import sampling_workspace_peak
- resident.observe_peak('engine', resident.engine_key(request),
- sampling_workspace_peak(sampled) - foreign_sample_bytes)
+ # A preview's first pass is kept apart from the complete request's peak.
+ resident.observe_peak('engine_preview' if request.get('preview') is True else 'engine',
+ resident.engine_key(request), sampling_workspace_peak(sampled) - foreign_sample_bytes)
resident.observe_peak('decode', key(dict(options=decoder, canvas=canvas)), torch.cuda.max_memory_allocated() - foreign_decode_bytes)
metrics['resident_models'] = resident.snapshot()
except BaseException as error:
@@ -627,6 +636,8 @@ def generate(request, resident=None):
save(request['metrics'], metrics)
raise
finally:
+ if resident is not None:
+ resident.device_free, resident.device_reserve = None, 0
if live_budget is not None:
live_budget.close()
if resident is not None: