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.
Video models are released after each generation unless the next part is on its way
Bowen Xuea96d1157dd7d
diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.pyindex 4598e5d..fa843f4 100644--- a/freevideo_engine/comfy_bridge.py+++ b/freevideo_engine/comfy_bridge.py@@ -1416,6 +1416,8 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,state['encoder_prewarm'] = prewarm_summary(encoder_prewarm)if machine.get('device_backend') != 'mps' and (source/'freevideo_engine'/'resident_worker.py').is_file():from .resident_process import OWNER, ENV+ # Whether the models were kept for this request or released, and why.+ state['resident_since_last'] = OWNER.take_decisions()if environment.get('FREEVIDEO_KEEP_MODELS', 'auto').lower() in ('0', 'off', 'false'):OWNER.close()environment.pop(ENV, None)@@ -1529,7 +1531,7 @@ def generate(prompt, width, height, seconds, seed, output_directory, *,# request's process tree. Confirm it exits too before offering# another generation; cancellation should release its memory.from .resident_process import OWNER- OWNER.close()+ OWNER.release('cancelled')raisefinally:from .resident_process import OWNERdiff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.pyindex e11d77f..eacab22 100644--- a/freevideo_engine/comfy_nodes.py+++ b/freevideo_engine/comfy_nodes.py@@ -233,6 +233,8 @@ class FreeVideoGenerate(io.ComfyNode):preview['freevideo_summary'][0]['continuation']['requested_frames'] = options['frames']preview['freevideo_summary'][0]['result_cache_hit'] = result_reused[0]except BaseException as error:+ from .resident_process import OWNER+ OWNER.finished()cancelled = isinstance(error, KeyboardInterrupt) or type(error).__name__ in ('InterruptProcessingException', 'CancelledError')phase = 'cancelled' if cancelled else 'failed'publish(PromptServer.instance, node_id, {'label': 'Generation cancelled' if cancelled else 'Generation stopped',@@ -244,11 +246,32 @@ class FreeVideoGenerate(io.ComfyNode):from .encoder_prewarm import warm_targettarget = warm_target(measured)from .resident_process import OWNER+ server = PromptServer.instance+ def busy():+ return server is not None and server.prompt_queue.get_tasks_remaining() > 0+ # Keep the models only while the next part is on its way; otherwise give+ # the memory back now and let the file cache make the next load quick.+ try:+ # The running prompt is this one; only prompts still waiting are a next part.+ queued = server is not None and bool(server.prompt_queue.get_current_queue()[1])+ except (AttributeError, TypeError, ValueError, IndexError):+ queued = False+ try:+ # Agent videos wait in the agent's own list until the running one ends.+ queued = queued or any(row['kind'] == 'generate' and row['status'] == 'waiting'+ for row in server._freevideo_agent.active())+ except (AttributeError, TypeError, KeyError):+ pass+ next_part = 'queued' if queued else ('continuing' if chain is not None and chain.get('index', 0) + 1 < chain.get('count', 0)+ or chain is None and options.get('continue_from') else None)+ try:+ gpu = comfy_bridge.installation()[1].get('gpu_uuid')+ except (OSError, ValueError, KeyError, TypeError):+ gpu = None+ OWNER.finished(next_part=next_part, gpu=gpu,+ agent=server is not None and str(getattr(server, 'client_id', '') or '').startswith('agent:'))if target and not result_reused[0]:- server = PromptServer.instanceclient = server.client_id if server is not None else None- def busy():- return server is not None and server.prompt_queue.get_tasks_remaining() > 0def warmed(value):if server is not None:server.send_sync('freevideo_prewarm', dict(value, node=node_id), sid=client)@@ -258,12 +281,8 @@ class FreeVideoGenerate(io.ComfyNode):IDLE.schedule(path, output.with_suffix('.prewarm.json'),ram_budget=measured.get('profile', {}).get('inference_ram_budget_gb', 0) * 1e9,busy=busy, notify=warmed, purpose='upscale')- elif OWNER.process is not None:- root, machine = comfy_bridge.installation()- environment = comfy_bridge.engine_environment(root, comfy_bridge.source_root())- environment.update(FREEVIDEO_HOME=str(root), PYTHONPATH=str(comfy_bridge.source_root()))- OWNER.warm_encoder(output, machine['python'], environment, busy=busy, notify=warmed)else:+ # File cache only: a kept worker must not grow on the card while it waits.IDLE.schedule(path, output.with_suffix('.prewarm.json'),ram_budget=measured.get('profile', {}).get('inference_ram_budget_gb', 0) * 1e9,busy=busy, notify=warmed)diff --git a/freevideo_engine/comfy_residency.py b/freevideo_engine/comfy_residency.pyindex c9062d9..b2ee815 100644--- a/freevideo_engine/comfy_residency.py+++ b/freevideo_engine/comfy_residency.py@@ -31,7 +31,7 @@ def install(memory):if (not getattr(_local, 'keep', False) and not OWNER.active andOWNER.process is not None and OWNER.process.poll() is None):if device is None or memory_required > memory.get_free_memory(device):- OWNER.close()+ OWNER.release('comfy_model')return original(memory_required, device, *args, **kwargs)free_memory._freevideo_resident_cooperation = Truediff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.pyindex 2e6d55b..c3727d7 100644--- a/freevideo_engine/image_gen/service.py+++ b/freevideo_engine/image_gen/service.py@@ -309,6 +309,7 @@ class Service:env[resident_process.ENV] = str(owner.endpoint)try:resident_process.release_idle_cache(env, descriptor)+ resident_process.OWNER.record(action='released', reason='image_model')except resident_process.SessionRestarted:passenv.pop(resident_process.ENV, None)diff --git a/freevideo_engine/prompt_vlm/service.py b/freevideo_engine/prompt_vlm/service.pyindex 49e69da..fc64c89 100644--- a/freevideo_engine/prompt_vlm/service.py+++ b/freevideo_engine/prompt_vlm/service.py@@ -448,6 +448,7 @@ class Service:if env.get(resident_process.ENV) and Path(env[resident_process.ENV]).is_file():try:resident_process.release_idle_cache(env, descriptor)+ resident_process.OWNER.record(action='released', reason='prompt_model')except resident_process.SessionRestarted:pass # That worker already exited, which is the release we need.env.pop(resident_process.ENV, None)diff --git a/freevideo_engine/resident_process.py b/freevideo_engine/resident_process.pyindex e76366b..e95fd23 100644--- a/freevideo_engine/resident_process.py+++ b/freevideo_engine/resident_process.py@@ -22,6 +22,16 @@ from . import processesfrom .monitoring import saveENV = 'FREEVIDEO_RESIDENT_SESSION'+GiB = 2**30+# A finished request releases the worker unless its next part is already on the+# way. Then it is kept briefly, and given up at once when anything else needs+# the memory: another program's GPU use grows, host memory runs low, or an+# image or prompt model starts (those release it themselves).+HOLD_SECONDS = 90.+AGENT_HOLD_SECONDS = 30.+OTHER_GPU_GROWTH = 512 * 2**20+HOST_FLOOR = 4 * GiB+RELEASE_LOG = 20class SessionRestarted(RuntimeError):@@ -346,9 +356,76 @@ class SessionOwner:self.identity = Noneself.active = Falseself.prewarm = None+ self.mutex = threading.RLock()+ self.generation = 0+ self.idle_since = None+ self.decisions = []atexit.register(self.close)+ def record(self, **row):+ row.setdefault('at', time.time())+ with self.mutex:+ self.decisions = (self.decisions + [row])[-RELEASE_LOG:]+ return row++ def take_decisions(self):+ """Keep or release decisions since the previous request, for its report."""+ with self.mutex:+ rows, self.decisions = self.decisions, []+ return rows++ def finished(self, *, next_part=None, agent=False, gpu=None):+ """Release the idle worker now, or keep it while a next part is on its way."""+ with self.mutex:+ if self.active or self.process is None or self.process.poll() is not None:+ return None+ 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)+ if reason:+ return self.release(reason)+ self.generation += 1+ self.idle_since = time.monotonic()+ baseline = gpu_used(gpu)+ threading.Thread(target=self._watch, args=(self.generation, self.idle_since, hold, gpu, baseline),+ name='freevideo-resident-hold', daemon=True).start()+ return self.record(action='kept', reason=next_part, seconds=hold, pid=self.process.pid)++ def _watch(self, generation, since, hold, gpu, baseline):+ while True:+ time.sleep(.5)+ reason = ('idle' if time.monotonic() - since >= hold+ else pressure(gpu, baseline))+ with self.mutex:+ if generation != self.generation or self.active or self.process is None:+ return+ if self.process.poll() is not None:+ return # The image or prompt model released it and recorded why.+ if reason:+ self.release(reason)+ return++ def release(self, reason):+ with self.mutex:+ if self.process is None or self.process.poll() is not None:+ self.close()+ return None+ row = dict(action='released', reason=reason, pid=self.process.pid,+ idle_seconds=None if self.idle_since is None else round(time.monotonic() - self.idle_since, 1),+ **worker_memory(self.process.pid))+ self.generation += 1+ self.idle_since = None+ self.close()+ return self.record(**row)+def start(self, root, source, python, environment):+ with self.mutex:+ self.generation += 1+ self.idle_since = None+ return self._start(root, source, python, environment)++ def _start(self, root, source, python, environment):import hashlibimport psutilfrom .triton_compat import COMPILER_ENVIRONMENT_KEYS, environment as compiler_environment@@ -419,17 +496,6 @@ class SessionOwner:receipt['worker_released'] = Truereturn receipt- def warm_encoder(self, output, python, environment, *, busy=None, notify=None):- if (self.process is None or self.process.poll() is not None or self.active or- environment.get('FREEVIDEO_ENCODER_PREWARM', 'auto').lower() in ('0', 'off', 'false')):- return False- self.stop_prewarm()- if self.process is None:- return False- from .idle_encoder import IdleEncoder- self.prewarm = IdleEncoder()- return self.prewarm.schedule(self.endpoint, output, python, environment, busy=busy, notify=notify)-def close(self):self.stop_prewarm()if self.process is not None:@@ -437,6 +503,50 @@ class SessionOwner:self.process = None+def gpu_used(gpu):+ try:+ from .background_room import Gpu+ device = Gpu(gpu)+ try:+ memory = device.memory()+ finally:+ device.close()+ return memory[0] if memory else None+ except (OSError, RuntimeError, AttributeError, ValueError, ImportError):+ return None+++def pressure(gpu, baseline):+ """Why a kept idle worker should go now, or None."""+ try:+ from .background_room import available_memory+ if available_memory() < HOST_FLOOR:+ return 'host_memory_low'+ except (OSError, RuntimeError, AttributeError, ValueError, ImportError):+ pass+ if baseline is not None:+ # The idle worker does not allocate, so growth on the card is another program's.+ used = gpu_used(gpu)+ if used is not None and used - baseline >= OTHER_GPU_GROWTH:+ return 'other_program_gpu'+ return None+++def worker_memory(pid):+ """Host memory the release returns, from the worker tree."""+ try:+ import psutil+ from .background_room import family+ rss = private = 0+ for member in family(pid):+ info = psutil.Process(member).memory_info()+ rss += info.rss+ private += getattr(info, 'private', 0) or getattr(info, 'rss', 0) - getattr(info, 'shared', 0)+ return dict(worker_rss_bytes=rss, worker_private_bytes=private)+ except Exception:+ return {}++OWNER = SessionOwner()