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.

A request during idle encoder preparation keeps the loaded models

Bowen Xue8d9d19d0e3dc
diff --git a/freevideo_engine/diagnostic_resources.py b/freevideo_engine/diagnostic_resources.py
index 46102be..fdcb190 100644
--- a/freevideo_engine/diagnostic_resources.py
+++ b/freevideo_engine/diagnostic_resources.py
@@ -111,6 +111,10 @@ def encoder_runtime(value):
'cuda_initialized_at_start', 'native_imported_at_start') if type(value.get(key)) is bool}
+PREWARM_FAILURE_KINDS = ('cuda_error', 'worker_stop_unconfirmed', 'cancelled', 'timeout', 'gpu_oom',
+ 'ram_pressure', 'unknown_worker_exit', 'code_error')
+
+
def encoder_prewarm(value):
value = mapping(value)
result = numbers(value, ('elapsed_seconds', 'seconds', 'bytes', 'done_bytes', 'total_bytes',
@@ -122,6 +126,14 @@ def encoder_prewarm(value):
result[key] = value[key]
if value.get('purpose') in ('encoder', 'upscale'):
result['purpose'] = value['purpose']
+ # Why idle preparation stopped, as fixed words only: the receipt's reason
+ # is free text and may name a path. A bare "failed" explained nothing.
+ kind = mapping(value.get('failure')).get('kind', value.get('failure_kind'))
+ if kind in PREWARM_FAILURE_KINDS:
+ result['failure_kind'] = kind
+ error = value.get('error_type')
+ if isinstance(error, str) and len(error) <= 64 and error.isidentifier() and error.isascii():
+ result['error_type'] = error
return result
@@ -673,7 +685,7 @@ def planning(rows):
('capacity_bytes', 'available_bytes', 'reserve_bytes', 'budget_bytes', 'minimum_bytes')))
idle = mapping(row.get('idle_cache'))
item['idle_cache'] = dict(present=bool(idle), **numbers(idle, ('reclaimable_gpu_bytes',
- 'reclaimable_ram_bytes', 'retained_pinned_ram_bytes')))
+ 'reclaimable_ram_bytes', 'reclaimable_commit_bytes', 'retained_pinned_ram_bytes')))
item['idle_cache']['memory'] = numbers(idle.get('memory'), RAM_SAMPLE)
item['idle_cache']['gpu_capacity'] = numbers(idle.get('gpu_capacity'),
('allocator_limit_bytes', 'owned_allocator_reserved_bytes', 'live_free_bytes',
diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.py
index b99614e..2f0a92b 100644
--- a/freevideo_engine/encode_worker.py
+++ b/freevideo_engine/encode_worker.py
@@ -116,6 +116,10 @@ def preload(clip, request, resident):
except (PreloadCancelled, MemoryError, torch.OutOfMemoryError) as error:
resident.drop('encoder', 'Speculative preload interrupted; foreground work wins')
result.update(state='cancelled' if isinstance(error, PreloadCancelled) else 'released', reason=str(error))
+ except Exception:
+ # An unfinished placement left its weights where they were; never keep it.
+ resident.drop('encoder', 'Speculative preload failed; partial placement discarded')
+ raise
result.update(gpu_bytes_after=gpu_bytes(clip), elapsed_seconds=time.perf_counter()-started,
torch_peak_allocated_bytes=torch.cuda.max_memory_allocated(),
torch_peak_reserved_bytes=torch.cuda.max_memory_reserved())
diff --git a/freevideo_engine/idle_encoder.py b/freevideo_engine/idle_encoder.py
index a6db641..f4c8b3f 100644
--- a/freevideo_engine/idle_encoder.py
+++ b/freevideo_engine/idle_encoder.py
@@ -49,6 +49,14 @@ class PreloadCancelled(Exception):
"""A completed video stays successful when speculative work is cancelled."""
+# How long cancelled placement may take to hand the worker back. Past this the
+# worker is stopped, and with it every model it holds: the next request then
+# pays a new process and loads everything again, which costs far more than
+# these seconds. One native transfer in flight cannot be interrupted, and on a
+# slow disk a single large weight takes longer than a second.
+YIELD_SECONDS = 6.
+
+
@contextmanager
def interruptible_load(patcher, check):
"""Yield between native module transfers, with the original loader intact.
@@ -78,6 +86,28 @@ def interruptible_load(patcher, check):
return original_patch(*args, **kwargs)
replace(patcher, 'patch_weight_to_device', patch)
replace(patcher, 'pin_weight_to_device', lambda *args, **kwargs: check())
+ # The native loader answers a failed placement by moving every weight
+ # it already placed back to host memory. Here that is a full
+ # GPU-to-CPU copy, as much new host memory as was placed, before the
+ # worker can yield; under RAM pressure it is the wrong direction too.
+ # The caller discards a model whose placement did not finish, so its
+ # tensors stay where they are. None is unpatch_model's own "do not
+ # move" mode.
+ native_detach = getattr(patcher, 'detach', None)
+ def detach(*args, **kwargs):
+ native_unpatch = patcher.unpatch_model
+ existed, previous = 'unpatch_model' in vars(patcher), vars(patcher).get('unpatch_model')
+ patcher.unpatch_model = lambda device_to=None, unpatch_weights=True: native_unpatch(
+ device_to=None, unpatch_weights=unpatch_weights)
+ try:
+ return native_detach(*args, **kwargs)
+ finally:
+ if existed:
+ patcher.unpatch_model = previous
+ else:
+ del patcher.unpatch_model
+ if callable(native_detach):
+ replace(patcher, 'detach', detach)
yield
finally:
for obj, name, existed, value in reversed(saved):
@@ -104,7 +134,7 @@ class IdleEncoder:
if self.process is not None and self.process.poll() is None:
processes.stop(self.process, grace=1.)
if self.thread is not None:
- self.thread.join(timeout=3.)
+ self.thread.join(timeout=YIELD_SECONDS+2.)
if self.thread.is_alive():
# A blocked disk read/native copy is not indefinitely allowed
# to delay the next prompt. The controller stops the real GPU
@@ -174,7 +204,7 @@ class IdleEncoder:
except Exception as error:
if self.process is not None and self.process.poll() is None:
processes.stop(self.process, grace=1.)
- save(report, dict(state='failed', reason=str(error)))
+ save(report, dict(state='failed', reason=str(error), error_type=type(error).__name__))
self.thread = threading.Thread(target=work, name='FreeVideo idle encoder', daemon=True)
self.thread.start()
@@ -251,7 +281,7 @@ def run(request):
result.update(state='released', reason='Live RAM pressure interrupted speculative loading')
if cancelled.exists():
cancel_started = cancel_started or time.monotonic()
- if time.monotonic()-cancel_started > 1.:
+ if time.monotonic()-cancel_started > YIELD_SECONDS:
raise PreloadCancelled('Preload did not yield promptly; stop the worker before foreground work')
try:
worker.wait(timeout=.1)
@@ -275,7 +305,7 @@ def run(request):
if getattr(error, 'worker_stop_confirmed', None) is False:
failure = classify_failure(error)
result.update(state='cancelled' if failure['outcome'] == 'cancelled' else 'skipped' if isinstance(error, BlockingIOError) else 'failed',
- reason=str(error), failure=failure)
+ reason=str(error), failure=failure, error_type=type(error).__name__)
if attempt is not None:
history.finish(attempt, failure['outcome'], details=result)
finally:
diff --git a/freevideo_engine/input_cache.py b/freevideo_engine/input_cache.py
index 833c393..52a7145 100644
--- a/freevideo_engine/input_cache.py
+++ b/freevideo_engine/input_cache.py
@@ -103,9 +103,13 @@ class InputCache:
checksum = digest(source)
target = self.root / (checksum + '.pt')
if target.exists() and digest(target) != checksum:
- target = self.root / (checksum + '-' + uuid.uuid4().hex + '.pt')
+ target = self.root / (checksum[:31] + '-' + uuid.uuid4().hex + '.pt')
if not target.exists():
- temporary = source if move else target.with_suffix('.partial-' + uuid.uuid4().hex)
+ # Nothing written here has a longer name than the receipt. Windows
+ # refuses a path past 260 characters: a longer staging name left an
+ # installation in a deep folder unable to save an input whose
+ # receipt and file both fit, so every repeat encoded it again.
+ temporary = source if move else self.root / (uuid.uuid4().hex + '.partial')
if not move:
with temporary.open('xb') as output, source.open('rb') as stream:
shutil.copyfileobj(stream, output, length=1024 * 1024)
@@ -117,8 +121,10 @@ class InputCache:
if receipt.exists():
# Keep old receipts too, including malformed ones, for diagnostics.
prior = receipt.read_bytes()
- if not (self.root / (receipt.stem + '-' + hashlib.sha256(prior).hexdigest()[:16] + '.previous.json')).exists():
- (self.root / (receipt.stem + '-' + hashlib.sha256(prior).hexdigest()[:16] + '.previous.json')).write_bytes(prior)
+ previous = self.root / (receipt.stem[:38] + '-' + hashlib.sha256(prior).hexdigest()[:16] + '.previous.json')
+ if not previous.exists():
+ previous.write_bytes(prior)
save(receipt, {'identity': self.identity, 'file': target.name, 'bytes': size,
- 'sha256': checksum, 'metrics': metrics, 'created_epoch': time.time()})
+ 'sha256': checksum, 'metrics': metrics, 'created_epoch': time.time()},
+ staging='receipt.')
return True
diff --git a/freevideo_engine/monitoring.py b/freevideo_engine/monitoring.py
index d68f769..b3d92c0 100644
--- a/freevideo_engine/monitoring.py
+++ b/freevideo_engine/monitoring.py
@@ -12,13 +12,16 @@ from .system import windows
from .long_paths import io_path, plain_data
-def save(path, value):
+def save(path, value, *, staging=None):
path = io_path(path)
path.parent.mkdir(parents=True, exist_ok=True)
# Unique, closed staging file; Windows readers/antivirus may briefly hold
# the destination. Keep the previous good report and the failed staging file.
+ # ``staging`` names it for a caller whose folder cannot take a longer name
+ # than the file itself.
with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', newline='\n',
- prefix=path.name + '.', suffix='.tmp', dir=path.parent, delete=False) as stream:
+ prefix=path.name + '.' if staging is None else staging, suffix='.tmp',
+ dir=path.parent, delete=False) as stream:
temporary = Path(stream.name)
stream.write(json.dumps(plain_data(value), ensure_ascii=False, indent=2) + '\n')
for attempt in range(8):
diff --git a/freevideo_engine/resident_models.py b/freevideo_engine/resident_models.py
index 30aa11d..270a5d9 100644
--- a/freevideo_engine/resident_models.py
+++ b/freevideo_engine/resident_models.py
@@ -43,12 +43,15 @@ def gpu_bytes(model):
return sum(storages.values())
-def pinned_cpu_storages(model):
+def pinned_cpu_storages(model, *, committed=False):
"""Owned, physically backed weights which eviction can actually release.
Mapped/pageable weights are excluded: Linux already credits clean file
cache, and Windows commit is not resident RAM. Count storage once even
when several tensor views (or model entries) share a pinned plane.
+ ``committed`` also leaves out registered read-only checkpoint maps: they
+ are resident while pinned, but file-backed, so releasing them returns no
+ commit.
"""
if hasattr(model, 'transformer'):
model = model.transformer
@@ -56,12 +59,13 @@ def pinned_cpu_storages(model):
model = model.cond_stage_model
if model is None:
return {}
+ from .encoder_checkpoint import owns_readonly_tensor
storages = {}
for tensor in list(model.parameters()) + list(model.buffers()):
if tensor.device.type != 'cpu':
continue
try:
- if tensor.is_pinned():
+ if tensor.is_pinned() and not (committed and owns_readonly_tensor(tensor)):
storage = tensor.untyped_storage()
storages[storage.data_ptr()] = storage.nbytes()
except (NotImplementedError, RuntimeError):
@@ -239,9 +243,14 @@ class ModelBank:
# Keep the existing affordable cache rather than rereading every block
# just to pin one more layer. A lower cap must still release the old
# placement; never silently retain pins beyond a reduced RAM budget.
- retained_pin_gb = getattr(found, 'config', {}).get('pin_host_gb', 0.)
+ # The allowance is a ceiling the load may not have reached, and free
+ # RAM moves it between requests: compare what the cache really pinned.
+ config = getattr(found, 'config', {})
+ retained_pin_gb = config.get('pin_host_gb', 0.)
requested_pin_gb = options.get('pin_host_gb', 0.)
- if found is not None and retained_pin_gb > requested_pin_gb:
+ pinned = config.get('pinned_host_allocated_bytes') or config.get('pinned_model_bytes')
+ held_pin_gb = min(retained_pin_gb, pinned / 1e9) if type(pinned) is int and pinned > 0 else retained_pin_gb
+ if found is not None and held_pin_gb > requested_pin_gb:
self.drop('engine', 'Host weight cache allowance decreased')
found = None
hit = found is not None
@@ -331,9 +340,10 @@ class ModelBank:
uuid = str(getattr(torch.cuda.get_device_properties(0), 'uuid', ''))
if uuid and not uuid.startswith(('GPU-', 'MIG-')):
uuid = 'GPU-' + uuid
- host = {}
+ host, committed = {}, {}
for entry in self.entries.values():
host.update(pinned_cpu_storages(entry['model']))
+ committed.update(pinned_cpu_storages(entry['model'], committed=True))
memory, gpu_capacity = None, None
from .system import windows
if windows():
@@ -347,8 +357,9 @@ class ModelBank:
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,
memory=memory, gpu_capacity=gpu_capacity,
- ram_credit_scope='Owned pinned model storage only; deduplicated, reclaimable on eviction. No mapped-page, commit or swap credit.',
+ ram_credit_scope='Owned pinned model storage only; deduplicated, reclaimable on eviction. No mapped-page or swap credit; commit only for pinned 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/resident_process.py b/freevideo_engine/resident_process.py
index d456407..a16607c 100644
--- a/freevideo_engine/resident_process.py
+++ b/freevideo_engine/resident_process.py
@@ -144,9 +144,17 @@ def credit(hardware, environment=None, *, reuse_encoder=False):
keys = ('effective_available_bytes', 'system_physical_available_bytes',
'system_commit_available_bytes', 'reclaimable_mapped_bytes', 'guard_bytes')
if all(type(memory.get(k)) is int and memory[k] >= 0 for k in keys):
- available = min(hardware.ram_total, memory['system_commit_available_bytes'],
- memory['effective_available_bytes'] + min(ram, memory['guard_bytes']),
- memory['system_physical_available_bytes'] + memory['reclaimable_mapped_bytes'] + min(ram, memory['guard_bytes']))
+ # Pinned private storage of an idle model is memory this worker
+ # already committed: reusing it charges nothing new and evicting it
+ # returns the commit. Commit headroom alone counted it twice, so a
+ # repeat was planned with less RAM than the model it already held.
+ # Pinned read-only checkpoint maps are file-backed and earn none.
+ owned = min(ram, memory['guard_bytes'])
+ committed = state.get('reclaimable_commit_bytes', 0)
+ committed = min(owned, committed) if type(committed) is int and committed > 0 else 0
+ available = min(hardware.ram_total, memory['system_commit_available_bytes'] + committed,
+ memory['effective_available_bytes'] + owned,
+ memory['system_physical_available_bytes'] + memory['reclaimable_mapped_bytes'] + owned)
if (reuse_encoder and memory.get('guard_metric') == 'tree private working set'
and any(model.get('role') == 'encoder' for model in state.get('models', []))):
# The encoder is staying in this same worker. Its measured