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.
Retain resident model components by recent requests and keep the usage habit across restarts
Bowen Xue0026f90c911c
diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.pyindex 2ff56df..dcd442e 100644--- a/freevideo_engine/comfy_nodes.py+++ b/freevideo_engine/comfy_nodes.py@@ -4,7 +4,7 @@ from pathlib import Pathfrom comfy_api.latest import ComfyExtension, InputImpl, io, ui-from . import comfy_bridge, workflow_repairs+from . import comfy_bridge, usage_habit, workflow_repairsfrom .comfy_continuation import node_frames, optional_text, part_steps, request_optionsfrom .default_prompt import DEFAULT_PROMPTfrom .original_audio import audio_use_option@@ -397,8 +397,8 @@ class FreeVideoGenerate(io.ComfyNode):gpu = comfy_bridge.installation()[1].get('gpu_uuid')except (OSError, ValueError, KeyError, TypeError):gpu = None- OWNER.finished(next_part=next_part, gpu=gpu, warm=True,- agent=server is not None and str(getattr(server, 'client_id', '') or '').startswith('agent:'))+ kept = OWNER.finished(next_part=next_part, gpu=gpu, warm=True,+ agent=server is not None and str(getattr(server, 'client_id', '') or '').startswith('agent:'))from .comfy_environment import executor_deviceif target and not result_reused[0] and not executor_device():client = server.client_id if server is not None else None@@ -411,12 +411,19 @@ 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 (isinstance(kept, dict) and kept.get('action') == 'kept' and next_part is None+ and usage_habit.dominant((usage_habit.load() or {}).get('recent')) == 'prompt'):+ # Prompts change often: place the encoder on the card while the kept worker+ # idles. It yields to any new task, and only what fits free memory is placed.+ 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)- except (OSError, RuntimeError):+ except (OSError, RuntimeError, ValueError, KeyError, TypeError):pass # A saved video remains successful if idle warming cannot start.return io.NodeOutput(InputImpl.VideoFromFile(str(output)), report, ui=preview)diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.pyindex fc3a534..4ceba4e 100644--- a/freevideo_engine/encode_worker.py+++ b/freevideo_engine/encode_worker.py@@ -576,8 +576,8 @@ def _encode(args, request, resident, trace):save(request['metrics'], {**loading, 'success': False, 'phase': 'keyframe_vae','load_seconds': load_seconds, 'prompt_encode_seconds': prompt_encode_seconds})# Only the encoder is read; the decoder in the shared shards is skipped.- vae, _ = load_video_encoder(request['base'], before_upload=None if resident is None else- lambda model: resident.input_vae_room(model, dict(width=width, height=height)))+ vae = (resident.input_video_encoder(request['base'], dict(width=width, height=height))+ if resident is not None else load_video_encoder(request['base'])[0])torch.cuda.synchronize()keyframe_metrics['keyframe_vae_load_seconds'] = time.perf_counter() - vae_startedvae_started = time.perf_counter()diff --git a/freevideo_engine/media_encoding.py b/freevideo_engine/media_encoding.pyindex c2da401..c3a7a44 100644--- a/freevideo_engine/media_encoding.py+++ b/freevideo_engine/media_encoding.py@@ -351,9 +351,12 @@ def encode_latents(normalized, value, base, canvas, *, resident=None, device='cuon_mps = torch.device(device).type == 'mps'# On MPS the weights stay in the checkpoint mapping and each encoder# stage uploads its own while it runs (bounded_encoder).- vae, _ = load_video_encoder(base, before_upload=None if resident is None else- lambda model: resident.input_vae_room(model, canvas),- device='cpu' if on_mps else device)+ if resident is not None and not on_mps:+ vae = resident.input_video_encoder(base, canvas, device=device)+ else:+ vae, _ = load_video_encoder(base, before_upload=None if resident is None else+ lambda model: resident.input_vae_room(model, canvas),+ device='cpu' if on_mps else device)lifetime = nullcontext()if on_mps:from .backends.mps_vae_encode import bounded_encoder@@ -382,8 +385,9 @@ def encode_latents(normalized, value, base, canvas, *, resident=None, device='cuempty_cache()if any(row.get('audio') for row in normalized):print(json.dumps({'event': 'media_encode_phase', 'phase': 'Encoding reference audio'}), flush=True)- vae, _ = load_audio_vae(base, before_upload=None if resident is None else- lambda model: resident.input_vae_room(model, canvas, audio=True), device=device)+ vae = (resident.input_audio_encoder(base, canvas, device=device)+ if resident is not None and torch.device(device).type != 'mps' else+ load_audio_vae(base, device=device)[0])mean = torch.tensor(vae.config.latents_mean).view(1, 1, -1)std = torch.tensor(vae.config.latents_std).view(1, 1, -1)if vae.config.sampling_rate != 32000:diff --git a/freevideo_engine/resident_models.py b/freevideo_engine/resident_models.pyindex b55c139..7f03200 100644--- a/freevideo_engine/resident_models.py+++ b/freevideo_engine/resident_models.py@@ -1,17 +1,83 @@"""Request-aware model residency inside the isolated interactive GPU worker."""import gc+import hashlibimport jsonfrom pathlib import Pathimport sysimport timeimport torch+from . import usage_habitfrom .torch_compat import empty_host_cache, host_cache_release_supportedfrom .device_index import device_propertiesGiB = 1 << 30# Where a preview's sampling peak is kept, apart from its complete request's.PREVIEW_STAGE = 'engine_preview'+HABIT_WINDOW = 4+++def retention_order(history):+ """Cache roles to evict first; two thirds of recent transitions wins.++ History contains at most four successful requests' digests, never inputs.+ Image changes win ties with prompt changes, then same-prompt reruns. With+ fewer than two successes (or no dominant habit), use the old engine-first+ order. Active stages still use make_room's existing admission rules.+ """+ return eviction_order(usage_habit.dominant(usage_habit.transitions(history)))+++def eviction_order(habit):+ """Eviction order for a habit kind from usage_habit.dominant (None: default)."""+ if habit == 'images':+ keep = ('input_video_vae', 'encoder', 'conditioning', 'engine',+ 'input_audio_vae', 'video_vae', 'audio_vae')+ elif habit == 'prompt':+ keep = ('encoder', 'conditioning', 'engine', 'input_video_vae',+ 'input_audio_vae', 'video_vae', 'audio_vae')+ elif habit == 'rerun':+ keep = ('conditioning', 'engine', 'video_vae', 'audio_vae',+ 'input_video_vae', 'input_audio_vae', 'encoder')+ else:+ return ('engine', 'encoder', 'audio_vae', 'video_vae',+ 'input_audio_vae', 'input_video_vae', 'conditioning')+ return tuple(reversed(keep))+++def _input_digest(value):+ """Hash CPU conditioning without retaining inputs or copying mapped payloads."""+ digest = hashlib.sha256()+ def visit(item):+ if isinstance(item, torch.Tensor):+ tensor = item.detach().cpu().contiguous()+ digest.update(str((str(tensor.dtype), list(tensor.shape))).encode())+ digest.update(memoryview(tensor.reshape(-1).view(torch.uint8).numpy()))+ elif isinstance(item, dict):+ for name in sorted(item):+ visit(name)+ visit(item[name])+ elif isinstance(item, (tuple, list)):+ for child in item:+ visit(child)+ else:+ digest.update(json.dumps(item, sort_keys=True).encode())+ digest.update(b'\0')+ visit(value)+ return digest.hexdigest()+++class ConditioningMemo(torch.nn.Module):+ """The engine's bounded CPU refined-text results, independently evictable."""+ def __init__(self, memo):+ super().__init__()+ self.memo = memo++ def to(self, device):+ if device != 'meta':+ raise ValueError('Conditioning memo stays on the CPU')+ self.memo.clear()+ return selfdef key(value):@@ -156,6 +222,11 @@ class ModelBank:from .streamed_weights import ConvertedStore# Converted decoder layers streamed from the checkpoint; rebuilt on demand.self.converted_store = ConvertedStore()+ self.history = []+ # Transition kinds kept across restarts (see usage_habit); history+ # holds only this process's digests.+ stored = usage_habit.load()+ self.recent = stored['recent'] if stored else []# 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@@ -200,6 +271,11 @@ class ModelBank:import comfy.model_managementencoder_discarded = release_encoder(model, comfy.model_management)elif role == 'engine':+ cached = self.entries.get('conditioning')+ if cached and getattr(model, 'refined_text_memo', None) is cached['model'].memo:+ # Engine.close clears its dictionary; detach the independently+ # owned results so an engine miss need only reload weights.+ model.refined_text_memo = {}model.close()else:model.to('meta')@@ -268,14 +344,15 @@ class ModelBank:(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.+ """Keep as many independent components as the next cold start permits.The RAM guard counts the whole session, so retained engine weightsplus the next encoder's start (about 8 GiB) must stay inside thebudget, and so must the host weights a fresh plan would pin beyond thosethe engine already holds: 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.+ pin and sampling took 95 s instead of 38 s. Evict lower-priority+ components first, checking live RAM again after each release. This does+ not change an engine's layer layout."""# A retained engine's pinned weights are reused by the next request# rather than pinned again, so they count once, in the session's use.@@ -283,8 +360,11 @@ class ModelBank:need = 8*GiB + max(0, int(pinned) - held)if not self.ram_fits(need):self.converted_store.clear()- for role in ('engine', 'encoder'):- if role in self.entries and not self.ram_fits(need):+ order = eviction_order(self.habit())+ for role in (*order, *(role for role in self.entries if role not in order)):+ if self.ram_fits(need):+ break+ if role in self.entries:self.drop(role, 'Retained weights leave no host room for the next request')if role == 'engine':need = 8*GiB + int(pinned)@@ -295,6 +375,37 @@ class ModelBank:except (OSError, AttributeError):pass+ def succeeded(self, request):+ """Observe video successes only, locally; encoding/preloads are not jobs.++ Read the existing conditioning with mmap after generation has returned,+ so failures and cancellations do not train the policy. An unreadable+ or legacy external input leaves the previous habit unchanged.+ """+ path = Path(request['conditioning'])+ value = torch.load(path, map_location='cpu', weights_only=True, mmap=True)+ prompt = value.get('prompt')+ if prompt is None:+ prompt = value['prompt_embeds'][value['text_token_tags'] == 1]+ images = dict(anchors=value.get('keyframe_anchors'), latents=value.get('condition_latents'),+ references=[{k: row[k] for k in ('kind', 'latent') if k in row}+ for row in value.get('references', []) if row['kind'] != 'audio'])+ row = dict(prompt=_input_digest(prompt), images=_input_digest(images),+ run=key(dict(seed=request.get('seed'), options=request.get('engine_options'),+ geometry=request.get('geometry'), sampling=request.get('sampling_plan'))))+ kinds = usage_habit.transition(self.history[-1], row) if self.history else None+ self.history = (self.history + [row])[-HABIT_WINDOW:]+ if kinds is not None:+ self.recent = (self.recent + [kinds])[-(HABIT_WINDOW - 1):]+ try:+ usage_habit.record(kinds)+ except OSError:+ pass # A habit that cannot be saved is only forgotten at restart.++ def habit(self):+ """The dominant kind of change, from stored transitions or this process's digests."""+ return usage_habit.dominant(self.recent or usage_habit.transitions(self.history))+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@@ -311,7 +422,41 @@ class ModelBank:# model's host copy is released unless the live budget covers the# stage as well. Plentiful hosts keep it for reuse.host = weights + (2*GiB if audio else max(8*GiB, 26*GiB*area))- self.make_room('input_audio_vae' if audio else 'input_video_vae', weights + workspace, ram_need=host)+ role = 'input_audio_vae' if audio else 'input_video_vae'+ retained = model if self.entries.get(role, {}).get('model') is model else None+ self.make_room(role, weights + workspace, model=retained, ram_need=host)++ def input_video_encoder(self, base, canvas, *, device='cuda'):+ """Reuse just the image/video encoder; never load the output decoder."""+ from .vae_weights import load_video_encoder+ directory = Path(base) / 'vae'+ identity = key(dict(files=[file_identity(path) for path in+ sorted([directory/'config.json', *directory.glob('*.safetensors')])],+ device=str(device)))+ found = self.take('input_video_vae', identity)+ if found is not None:+ self.input_vae_room(found, canvas)+ return found+ found, _ = load_video_encoder(base, before_upload=lambda model: self.input_vae_room(model, canvas),+ device=device)+ self.put('input_video_vae', identity, found)+ return found++ def input_audio_encoder(self, base, canvas, *, device='cuda'):+ """Reuse the reference-audio VAE the way the image/video encoder is reused."""+ from .vae_weights import load_audio_vae+ directory = Path(base) / 'audio_vae'+ identity = key(dict(files=[file_identity(path) for path in+ sorted([directory/'config.json', *directory.glob('*.safetensors')])],+ device=str(device)))+ found = self.take('input_audio_vae', identity)+ if found is not None:+ self.input_vae_room(found, canvas, audio=True)+ return found+ found, _ = load_audio_vae(base, before_upload=lambda model: self.input_vae_room(model, canvas, audio=True),+ device=device)+ self.put('input_audio_vae', identity, found)+ return founddef device_ceiling(self):"""What this process's allocator can hold before the device itself is full.@@ -450,6 +595,13 @@ class ModelBank:if found is None:found = factory()self.put('engine', identity, found)+ memo = getattr(found, 'refined_text_memo', None)+ if isinstance(memo, dict):+ cached = self.take('conditioning', identity)+ if cached is None:+ cached = ConditioningMemo(memo)+ self.put('conditioning', identity, cached)+ found.refined_text_memo = cached.memoreturn found, hitdef encoder_room(self, clip, tokens, fallback_peak):diff --git a/freevideo_engine/resident_process.py b/freevideo_engine/resident_process.pyindex 6003da8..8337bdc 100644--- a/freevideo_engine/resident_process.py+++ b/freevideo_engine/resident_process.py@@ -23,17 +23,17 @@ from .monitoring import saveENV = 'FREEVIDEO_RESIDENT_SESSION'GiB = 2**30-# A finished request keeps the worker for the next one while host memory is ample-# (for as long as nothing needs the memory, unless KEEP_IDLE_SECONDS sets a limit), and it is given up at once when anything else-# needs the memory: another program's GPU use grows, host memory runs low, an+# A successful request settles individual caches inside the worker, then keeps+# it without an idle limit unless KEEP_IDLE_SECONDS sets one. It gives up the+# worker at once when another program's GPU use grows, host memory runs low, an# image or prompt model starts (those release it themselves), or the agent asks-# for the card back. A request that is not followed by a queued part and fails,-# or a machine without the room, releases it as before; a next part already on-# its way is held for HOLD_SECONDS.+# for the card back. A failed request without a queued part releases it as+# before; a next part already on its way is held for HOLD_SECONDS.HOLD_SECONDS = 90.AGENT_HOLD_SECONDS = 30.KEEP_IDLE_SECONDS = NoneOTHER_GPU_GROWTH = 512 * 2**20+PRELOAD_CONTEXT_BYTES = 1536 * 2**20 # what the preload's process adds beside its weights (context, allocator, staging; measured 1.4 GiB)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.@@ -363,6 +363,7 @@ class SessionOwner:self.identity = Noneself.active = Falseself.prewarm = None+ self.gpu = self.baseline = self.own = Noneself.mutex = threading.RLock()self.generation = 0self.idle_since = None@@ -384,7 +385,7 @@ class SessionOwner:def finished(self, *, next_part=None, agent=False, gpu=None, warm=False):"""Release the idle worker now, or keep it for the next request.- A successful request (warm) keeps it while host memory is ample and the card's use can be read, so+ A successful request (warm) keeps its settled caches above HOST_FLOOR while the card's use can be read, soanother program's growth is seen; a next part on its way keeps it for a short hold. Anything elsegives the memory back now."""@@ -398,6 +399,8 @@ class SessionOwner:warm = Falseif not next_part or (hold is not None and hold <= 0):return self.release('finished' if not next_part else 'no_hold')+ # The worker settles individual caches against its live RAM budget.+ # A small host alone is no reason to discard everything it kept.reason = pressure(gpu, None) or self._tight()if reason:return self.release(reason)@@ -406,21 +409,12 @@ class SessionOwner:baseline = gpu_used(gpu)if warm and baseline is None:return self.release('gpu_unreadable')- threading.Thread(target=self._watch, args=(self.generation, self.idle_since, hold, gpu, baseline),+ self.gpu, self.baseline = gpu, baseline+ self.own = gpu_own(gpu) if warm else None+ threading.Thread(target=self._watch, args=(self.generation, self.idle_since, hold, gpu),name='freevideo-resident-hold', daemon=True).start()return self.record(action='kept', reason=next_part, seconds=hold, pid=self.process.pid)- def release_idle(self, reason='requested'):- """Give the card and host memory back on a caller's request; never touches a running request."""- with self.mutex:- if self.active:- return dict(released=False, reason='busy')- if self.process is None or self.process.poll() is not None:- return dict(released=False, reason='nothing_held')- row = self.release(reason)- return dict(released=True, reason=reason, **{k: v for k, v in (row or {}).items()- if k in ('idle_seconds', 'worker_rss_bytes')})-def _tight(self):from .system import windowsif windows():@@ -436,11 +430,79 @@ class SessionOwner:passreturn None- def _watch(self, generation, since, hold, gpu, baseline):+ def preloading(self):+ return self.prewarm is not None and self.prewarm.thread is not None and self.prewarm.thread.is_alive()++ def warm_encoder(self, output, python, environment, *, busy=None, notify=None):+ """Place the encoder on the card while the kept worker idles, under the worker's own lease.++ Only the models the worker can hold beside what it keeps are placed (it+ sizes that from live free memory), and any new request, queued prompt or+ memory pressure stops it first.+ """+ with self.mutex:+ 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 release_idle(self, reason='requested'):+ """Give the card and host memory back on a caller's request; never touches a running request."""+ with self.mutex:+ if self.active:+ return dict(released=False, reason='busy')+ if self.process is None or self.process.poll() is not None:+ return dict(released=False, reason='nothing_held')+ row = self.release(reason)+ return dict(released=True, reason=reason, **{k: v for k, v in (row or {}).items()+ if k in ('idle_seconds', 'worker_rss_bytes')})++ def placed_bytes(self):+ """Card bytes the last idle preload accounts for: its reported growth, else its budget, plus the context."""+ try:+ report = json.loads(Path(self.prewarm.report).read_text(encoding='utf-8'))+ before, after = report.get('gpu_bytes_before'), report.get('gpu_bytes_after')+ if type(before) is int and type(after) is int:+ known = max(0, after - before)+ else:+ known = max(0, int(report.get('gpu_budget_bytes') or 0))+ except (AttributeError, OSError, TypeError, ValueError):+ known = 0+ return known + PRELOAD_CONTEXT_BYTES++ def _watch(self, generation, since, hold, gpu):+ placing = Falsewhile True:time.sleep(.5)- reason = ('idle' if hold is not None and time.monotonic() - since >= hold- else pressure(gpu, baseline))+ # Our own idle preload grows the card; only another program's growth counts,+ # so the reference is read again once placement has ended.+ unreadable = False+ if self.preloading():+ placing = True+ elif placing:+ placing = False+ used = gpu_used(gpu)+ own = gpu_own(gpu)+ if used is None:+ unreadable = True # Same as at the start of the hold: never keep without a reading.+ elif own is not None and self.own is not None and self.baseline is not None:+ # Only the part this tree added moves the reference; another program's share stays visible.+ self.baseline += max(0, own - self.own)+ self.own = own+ elif self.baseline is not None:+ # No per-process bytes (WDDM): only what the preload reports it placed, plus its+ # context, moves the reference; the rest of the growth is another program's.+ self.baseline += min(max(0, used - self.baseline), self.placed_bytes())+ else:+ self.baseline = used+ reason = ('gpu_unreadable' if unreadable else+ 'idle' if hold is not None and time.monotonic() - since >= hold+ else pressure(gpu, None if placing else self.baseline))with self.mutex:if generation != self.generation or self.active or self.process is None:return@@ -564,6 +626,23 @@ def gpu_used(gpu):return None+def gpu_own(gpu):+ """Card bytes held by this process tree (the kept worker and its leases), or None if not listed."""+ try:+ from .background_room import Gpu, family+ device = Gpu(gpu)+ try:+ rows = device.processes()+ finally:+ device.close()+ if rows is None or any(size is None for size in rows.values()):+ return None+ pids = family(os.getpid())+ return sum(size for pid, size in rows.items() if pid in pids)+ except (OSError, RuntimeError, AttributeError, ValueError, ImportError):+ return None++def pressure(gpu, baseline):"""Why a kept idle worker should go now, or None."""try:diff --git a/freevideo_engine/resident_worker.py b/freevideo_engine/resident_worker.pyindex 1419267..c74521e 100644--- a/freevideo_engine/resident_worker.py+++ b/freevideo_engine/resident_worker.py@@ -68,6 +68,25 @@ def main():from .worker import generatebank.configure(request['gpu_budget_bytes'], request.get('ram_budget_bytes'))generate(request, resident=bank)+ # Only a fully returned video is a success, including its+ # final cleanup. Keep habit data inside this worker.+ try:+ bank.succeeded(request)+ except Exception:+ pass # Optional observations cannot fail a finished video.+ try:+ bank.settle(float(request['engine_options'].get('pin_host_gb') or 0)*1e9)+ except Exception:+ pass # Best-effort trimming cannot fail a finished video.+ if request.get('metrics'):+ try:+ from .monitoring import save+ path = Path(request['metrics'])+ metrics = json.loads(path.read_text(encoding='utf-8'))+ metrics.update(resident_models=bank.snapshot(), resident_admission=list(bank.decisions))+ save(path, metrics)+ except (OSError, ValueError, TypeError):+ passelse:from .encode_worker import encodebank.configure(request['gpu_budget_gb']*1e9, request.get('ram_budget_bytes'))diff --git a/freevideo_engine/usage_habit.py b/freevideo_engine/usage_habit.pynew file mode 100644index 0000000..334a7be--- /dev/null+++ b/freevideo_engine/usage_habit.py@@ -0,0 +1,83 @@+"""Recent usage habit kept across restarts: operation types and counts only.++Nothing derived from a prompt, image or seed is stored. A transition between+two successive successful videos is one of three kinds of change, and the file+keeps the last three transitions (the four-request window) plus running counts.+A file that is missing, unreadable or malformed counts as no habit at all.+"""+import json+import os+from pathlib import Path++WINDOW = 4+KINDS = ('images', 'prompt', 'rerun')+++def path():+ override = os.environ.get('FREEVIDEO_USAGE_HABIT')+ if override:+ return Path(override)+ from .system import install_root+ return install_root() / '.freevideo' / 'usage-habit.json'+++def transition(previous, current):+ """Kinds of change between two requests' digests (never stored)."""+ kinds = []+ if previous['images'] != current['images']:+ kinds.append('images')+ if previous['prompt'] != current['prompt']:+ kinds.append('prompt')+ elif not kinds:+ kinds.append('rerun')+ return kinds+++def transitions(history):+ recent = history[-WINDOW:]+ return [transition(a, b) for a, b in zip(recent, recent[1:])]+++def dominant(recent):+ """The kind that two thirds of the recent transitions share, or None.++ Image changes win ties with prompt changes, then same-prompt reruns.+ """+ if not recent:+ return None+ for kind in KINDS:+ if sum(kind in kinds for kinds in recent) * 3 >= len(recent) * 2:+ return kind+ return None+++def load(file=None):+ """The stored habit, or None when there is nothing trustworthy to read."""+ try:+ value = json.loads(Path(file or path()).read_text(encoding='utf-8'))+ if value['version'] != 1 or value['window'] != WINDOW:+ return None+ recent = value['recent']+ counts = value['counts']+ if (not isinstance(recent, list) or len(recent) > WINDOW - 1+ or any(not isinstance(kinds, list) or any(kind not in KINDS for kind in kinds) for kinds in recent)+ or not isinstance(counts, dict)+ or any(type(counts.get(name)) is not int or counts[name] < 0 for name in (*KINDS, 'requests'))):+ return None+ return dict(version=1, window=WINDOW, recent=[list(kinds) for kinds in recent],+ counts={name: counts[name] for name in (*KINDS, 'requests')})+ except (OSError, ValueError, KeyError, TypeError, AttributeError):+ return None+++def record(kinds, file=None):+ """Append one transition (None for the first request after a restart) and save."""+ from .monitoring import save+ value = load(file) or dict(version=1, window=WINDOW, recent=[], counts=dict.fromkeys((*KINDS, 'requests'), 0))+ value['counts']['requests'] += 1+ if kinds is not None:+ value['recent'] = (value['recent'] + [list(kinds)])[-(WINDOW - 1):]+ for kind in kinds:+ value['counts'][kind] += 1+ save(Path(file or path()), value)+ return valuediff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.pyindex 5a365d5..ea7fa7b 100644--- a/freevideo_engine/worker.py+++ b/freevideo_engine/worker.py@@ -763,12 +763,6 @@ def generate(request, resident=None):resident.device_free, resident.device_reserve = None, 0if 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.- passif resident is not None:metrics['resident_admission'] = list(resident.decisions)from .adaptive import classify_failure