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.

Text conditioning cache keyed by encoder content and prompt, with LRU eviction

Bowen Xuee1cbe61ae407
diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py
index fc585f5..dbc8452 100644
--- a/freevideo_engine/generate.py
+++ b/freevideo_engine/generate.py
@@ -797,13 +797,14 @@ def _run(args):
and (args.comfy_root or comfy_root()).resolve() == Path(machine['comfy_root']).resolve()
and args.model_paths and args.model_paths.resolve() == Path(machine['model_paths']).resolve())
if same_inputs:
+ # The text cache needs only the encoder and its code: no git, no video models.
+ from .input_cache import InputCache
+ input_cache = InputCache(tuning.text_identity(machine, hardware))
+ report['input_cache'].update(enabled=True, directory=str(input_cache.root))
identity = tuning.identity(machine, hardware)
state, reason = tuning.load_state(identity)
if active_loras:
state, reason = None, 'LoRA uses its own model history; encoder cache remains reusable'
- from .input_cache import InputCache
- input_cache = InputCache(identity)
- report['input_cache'].update(enabled=True, directory=str(input_cache.root))
report['tuning']['note'] = reason
else:
report['tuning']['note'] = 'Explicit model/encoder paths differ from the optimized installation'
diff --git a/freevideo_engine/input_cache.py b/freevideo_engine/input_cache.py
index 52a7145..a7c0c4f 100644
--- a/freevideo_engine/input_cache.py
+++ b/freevideo_engine/input_cache.py
@@ -6,6 +6,7 @@ on disk; a miss never deletes user artifacts or substitutes a finished video.
import copy
import hashlib
import json
+import os
from pathlib import Path
import shutil
import time
@@ -25,7 +26,7 @@ def digest(path):
class InputCache:
- """One receipt per input: no global index, eviction, or RAM-sized cache."""
+ """One receipt per input; a hit refreshes its receipt and `prune` evicts the least recently used ones."""
def __init__(self, identity, *, root=None, kind='conditioning'):
encoded = json.dumps(identity, sort_keys=True, separators=(',', ':')).encode()
self.identity = hashlib.sha256(encoded).hexdigest()
@@ -74,6 +75,10 @@ class InputCache:
return None
from .file_ops import publish
publish(temporary, destination)
+ try:
+ os.utime(self.receipt(key))
+ except OSError:
+ pass
result = copy.deepcopy(entry['metrics'])
# A receipt describes the original encoding. Keep its timings as
# provenance, not work performed by this cache-hit request.
@@ -127,4 +132,35 @@ class InputCache:
save(receipt, {'identity': self.identity, 'file': target.name, 'bytes': size,
'sha256': checksum, 'metrics': metrics, 'created_epoch': time.time()},
staging='receipt.')
+ self.prune()
return True
+
+ def prune(self, max_bytes=1 << 30, max_entries=4096):
+ """Drop the least recently used receipts of this kind, across identities, until under both limits.
+
+ Only files this cache wrote are removed; unreadable receipts are left in place."""
+ kind = self.root.parent
+ rows, owners = [], {}
+ try:
+ for receipt in kind.glob('*/*.json'):
+ try:
+ entry = json.loads(receipt.read_text(encoding='utf-8'))
+ if not isinstance(entry['file'], str) or Path(entry['file']).name != entry['file']:
+ continue
+ data = receipt.parent / entry['file']
+ rows.append((receipt.stat().st_mtime, receipt, data))
+ owners[data] = owners.get(data, 0) + 1
+ except (OSError, ValueError, KeyError, TypeError):
+ continue
+ total = sum({data: data.stat().st_size for _, _, data in rows if data.exists()}.values())
+ for _, receipt, data in sorted(rows, key=lambda row: row[0]):
+ if total <= max_bytes and len(rows) <= max_entries:
+ break
+ receipt.unlink()
+ rows = [row for row in rows if row[1] != receipt]
+ owners[data] -= 1
+ if not owners[data] and data.exists():
+ total -= data.stat().st_size
+ data.unlink()
+ except OSError as error:
+ self.note = type(error).__name__ + ': input cache pruning skipped'
diff --git a/freevideo_engine/tuning.py b/freevideo_engine/tuning.py
index 8c6f9a6..6489c6b 100644
--- a/freevideo_engine/tuning.py
+++ b/freevideo_engine/tuning.py
@@ -116,6 +116,54 @@ def identity(machine, hardware):
'encoder': machine['encoder'], 'model_revision': machine['model_revision']}
+TEXT_SCHEMA = 1
+TEXT_FILES = ('encode_worker.py', 'encoder_lowmem.py', 'encoder_precision.py', 'encoder_checkpoint.py',
+ 'encoder_pinning.py', 'encoder_workspace.py', 'encoder_memory.py', 'adaptive.py',
+ 'conditioning.py', 'media_request.py')
+TEXT_PACKAGES = ('torch', 'transformers', 'tokenizers', 'comfy-kitchen', 'safetensors', 'numpy')
+
+
+def encoder_content(path, catalog):
+ """Cheap content identity of the encoder file: catalog hash and size, plus its header and sampled blocks.
+
+ A same-size edit that touches none of the sampled bytes is not seen; a full 15 GB hash on every run would
+ cost more than the encode it avoids."""
+ size = path.stat().st_size
+ expected = next((row for row in catalog if row['file'].endswith('/' + path.name)), None)
+ value = hashlib.sha256()
+ with path.open('rb') as stream:
+ head = stream.read(8)
+ value.update(head)
+ value.update(stream.read(int.from_bytes(head, 'little') if int.from_bytes(head, 'little') < 2**26 else 0))
+ for index in range(16):
+ stream.seek(size * index // 16)
+ value.update(stream.read(65536))
+ return {'size': size, 'catalog_sha256': expected and expected['sha256'],
+ 'catalog_bytes': expected and expected['bytes'], 'sampled_sha256': value.hexdigest()}
+
+
+def text_identity(machine, hardware):
+ """What the text conditioning of a prompt depends on: encoder content, its code and arithmetic, nothing else.
+
+ No git, no timestamps, no video models, no GPU serial number: an unrelated update or a copied folder without
+ .git keeps the cache; a different encoder file, library, source or GPU architecture does not."""
+ package = Path(__file__).parent
+ catalog = json.loads((package / 'model_files.json').read_text(encoding='utf-8'))
+ catalog = catalog['files'] if isinstance(catalog, dict) else catalog
+ encoder = Path(machine['encoder_model_root']) / 'text_encoders' / machine['encoder']
+ specs = json.loads((package / 'dependencies.json').read_text(encoding='utf-8'))
+ texts = Path(machine['comfy_root']) / 'comfy' / 'text_encoders'
+ assets = {str(p.relative_to(texts)): digest(p) for p in sorted(texts.rglob('*'))
+ if p.is_file() and p.suffix in ('.py', '.json', '.txt', '.model')}
+ versions = package_versions(machine['comfy_python'])
+ return {'schema': TEXT_SCHEMA, 'kind': 'text-conditioning', 'system': hardware.system,
+ 'gpu': [hardware.gpu_name, list(hardware.capability), hardware.driver_version],
+ 'encoder': encoder_content(encoder, catalog),
+ 'encoder_packages': {k: v for k, v in versions.items() if k in TEXT_PACKAGES},
+ 'comfy_commit': specs['encoder']['comfy_commit'], 'comfy_text_encoders': assets,
+ 'source_sha256': {name: digest(package / name) for name in TEXT_FILES}}
+
+
def report_identity_errors(inventory, expected):
errors = []
if expected.get('system') and inventory.get('hardware', {}).get('system') != expected['system']: