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.

Keep resident encoder/engine models across requests without costing low-memory hosts

Bowen Xued70120aa94e5
diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.py
index af34634..a8c0c37 100644
--- a/freevideo_engine/encode_worker.py
+++ b/freevideo_engine/encode_worker.py
@@ -293,6 +293,10 @@ def _encode(args, request, resident, trace):
import torch
torch.set_num_threads(8)
torch.set_grad_enabled(False)
+ if resident is not None and not idle:
+ # The guard counts the whole session, retained engine weights included,
+ # from the first sample; free host room before CUDA setup, not after.
+ resident.make_room('encoder', 0, ram_need=8*2**30)
phase('encoder_cuda_setup')
if idle:
from .idle_encoder import gpu_preload_budget
@@ -392,7 +396,9 @@ def _encode(args, request, resident, trace):
clip = resident.take('encoder', encoder_key)
estimated = Path(path).stat().st_size * 1.4 + 2*2**30
if not idle and clip is None:
- resident.make_room('encoder', min(resident.gpu_budget, estimated), model=clip, ram_need=2*2**30)
+ # Measured: a cold encoder load peaks near 8 GiB of guarded host memory
+ # (7.7 GiB PSS); retained engine weights must make room for that.
+ resident.make_room('encoder', min(resident.gpu_budget, estimated), model=clip, ram_need=8*2**30)
elif idle and (Path(request['cancel']).exists() or not resident.ram_fits() or resident.available() < 2*2**30):
return dict(state='skipped', reason='No spare live memory, or a foreground request arrived')
import comfy.model_management
diff --git a/freevideo_engine/resident_models.py b/freevideo_engine/resident_models.py
index c6fb185..ac67535 100644
--- a/freevideo_engine/resident_models.py
+++ b/freevideo_engine/resident_models.py
@@ -262,6 +262,25 @@ class ModelBank:
return (used is not None and inference_headroom(sample) >= need + 2*GiB and
(self.ram_budget is None or used + need <= self.ram_budget))
+ def settle(self, pinned=0):
+ """End of a request: keep the engine and encoder only if the next cold encoder still fits.
+
+ The RAM guard counts the whole session, so retained engine weights
+ plus the next encoder's start (about 8 GiB) must stay inside the
+ budget, and so must the host weights a fresh plan would pin: measured,
+ a retained copy left no room to pin and sampling took 95 s instead of
+ 38 s. Otherwise the engine goes as it did with one worker per request.
+ """
+ for role in ('engine', 'encoder'):
+ if role in self.entries and not self.ram_fits(8*GiB + int(pinned)):
+ self.drop(role, 'Retained weights leave no host room for the next request')
+ gc.collect()
+ try:
+ import ctypes
+ ctypes.CDLL('libc.so.6').malloc_trim(0)
+ except (OSError, AttributeError):
+ pass
+
def input_vae_room(self, model, canvas, *, audio=False):
# Input encoding has its own live workspace; it cannot assume an output
# decoder's memory footprint. Charge actual retained CPU model tensors
@@ -401,7 +420,7 @@ class ModelBank:
peak = estimate if observed is None else observed
# 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.make_room('engine', peak, model=found, device=True, ram_need=8*GiB)
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),
@@ -446,7 +465,11 @@ class ModelBank:
peak = max(weights, gpu_bytes(clip)) + max(2*GiB, workspace)
else:
source = 'encoder_checkpoint_estimate'
- self.make_room('encoder', min(self.gpu_budget, peak), model=clip, ram_need=2*GiB)
+ # Measured: a reused encoder grew the whole session's guarded working
+ # set by 4 GiB beside 21.5 GiB of retained engine weights, passing a
+ # 25 GiB budget that a 2 GiB admission had accepted. Charge 4 GiB so
+ # the retained host copy is parked first on tight machines.
+ self.make_room('encoder', min(self.gpu_budget, peak), model=clip, ram_need=4*GiB)
self.decisions[-1]['evidence'] = dict(source=source, cold_estimate_bytes=int(fallback_peak),
requested_peak_bytes=int(peak))
diff --git a/freevideo_engine/resident_process.py b/freevideo_engine/resident_process.py
index e95fd23..cb21171 100644
--- a/freevideo_engine/resident_process.py
+++ b/freevideo_engine/resident_process.py
@@ -31,6 +31,9 @@ HOLD_SECONDS = 90.
AGENT_HOLD_SECONDS = 30.
OTHER_GPU_GROWTH = 512 * 2**20
HOST_FLOOR = 4 * GiB
+# Below this much host memory (free plus the idle worker's own), a kept worker's
+# base leaves the next part less room than a fresh one; measured on 16 GiB.
+KEEP_MIN_HOST = 24 * GiB
RELEASE_LOG = 20
@@ -382,7 +385,7 @@ class SessionOwner:
hold = min(HOLD_SECONDS, AGENT_HOLD_SECONDS) if agent else HOLD_SECONDS
if not next_part or hold <= 0:
return self.release('finished' if not next_part else 'no_hold')
- reason = pressure(gpu, None)
+ reason = pressure(gpu, None) or self._tight()
if reason:
return self.release(reason)
self.generation += 1
@@ -392,6 +395,21 @@ class SessionOwner:
name='freevideo-resident-hold', daemon=True).start()
return self.record(action='kept', reason=next_part, seconds=hold, pid=self.process.pid)
+ def _tight(self):
+ from .system import windows
+ if windows():
+ # Windows keeps its earlier behaviour: the available-memory reading
+ # here has not been checked against its commit accounting.
+ return None
+ try:
+ from .background_room import available_memory
+ own = worker_memory(self.process.pid).get('worker_rss_bytes', 0)
+ if available_memory() + own < KEEP_MIN_HOST:
+ return 'host_memory_tight'
+ except (OSError, RuntimeError, AttributeError, ValueError, ImportError):
+ pass
+ return None
+
def _watch(self, generation, since, hold, gpu, baseline):
while True:
time.sleep(.5)
diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.py
index b7e1269..9b6950f 100644
--- a/freevideo_engine/worker.py
+++ b/freevideo_engine/worker.py
@@ -733,6 +733,12 @@ def generate(request, resident=None):
resident.device_free, resident.device_reserve = None, 0
if live_budget is not None:
live_budget.close()
+ if resident is not None and metrics['success'] and engine is not None:
+ try:
+ resident.settle(float(request['engine_options'].get('pin_host_gb') or 0)*1e9)
+ except Exception:
+ # Trimming is best effort; it must not turn a finished request into a failure.
+ pass
if resident is not None:
metrics['resident_admission'] = list(resident.decisions)
from .adaptive import classify_failure