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.
Online LoRA folders: release the old model they pin, and prune stale ones
Bowen Xuebffb45155395
diff --git a/freevideo_engine/lora_online_cache.py b/freevideo_engine/lora_online_cache.pyindex c00096f..733cc08 100644--- a/freevideo_engine/lora_online_cache.py+++ b/freevideo_engine/lora_online_cache.py@@ -13,6 +13,7 @@ from safetensors.torch import save_filefrom .lora_cache import INT8_UNMERGEABLE, MODULATION, _targets, index_adapter, prepare as prepare_fusedfrom .media_request import digest, verify_filesfrom .monitoring import save+from . import online_lora_foldersfrom .storage import fingerprintfrom .tensor_io import open_tensors@@ -33,6 +34,17 @@ def _supported(adapters, linears, skip_modulation=False):return True+def _tidy(output, identity):+ """Record the use, then drop folders nothing can select again or nobody has used for long."""+ online_lora_folders.touch(output)+ current = {key: identity[key] for key in ('source_manifest_sha256', 'implementation_sha256', 'index_sha256', 'names_sha256')}+ try:+ for folder, reason, freed in online_lora_folders.prune(output.parent, current, keep=output):+ print(json.dumps(dict(event='lora_folder_removed', folder=Path(folder).name, reason=reason, bytes=freed)), flush=True)+ except OSError:+ pass++@torch.no_grad()def prepare(cache, adapters, output_root=None):cache = Path(cache).resolve()@@ -80,6 +92,7 @@ def prepare(cache, adapters, output_root=None):# Another combination can change a shared inode's link count/ctime.# Recheck it once, rather than rehashing the model on every use.save(marker, saved)+ _tidy(output, identity)return output, dict(enabled=True, mode='online', cache_hit=True, **saved['online_lora']['summary'])targets = {name: dict(shape=spec['weight_shape']) for name, spec in manifest['linears'].items()}groups, skipped = {}, []@@ -153,5 +166,6 @@ def prepare(cache, adapters, output_root=None):save(marker, dict(manifest, source_id=key, groups=records, online_lora=online,lora_identity=identity, lora_file_stamps={r['file']: fingerprint(output / r['file']) for r in records},total_bytes=manifest['total_bytes'] + sum(r['bytes'] for r in records if r['group'].startswith('lora/'))))+ _tidy(output, identity)return output, dict(enabled=True, mode='online', cache_hit=False,prepare_seconds=time.perf_counter() - started, **summary)diff --git a/freevideo_engine/online_lora_folders.py b/freevideo_engine/online_lora_folders.pynew file mode 100644index 0000000..0df7fdb--- /dev/null+++ b/freevideo_engine/online_lora_folders.py@@ -0,0 +1,190 @@+"""The online LoRA folders this installer builds beside a prepared model, and when they can go.++prepare() in lora_online_cache names a folder after the digest of its identity+(model manifest, the code that builds it, every adapter and strength), so each+new combination, strength or code update leaves another folder. Each holds the+adapter factors it built and hard links to the model's unchanged groups.++A folder is ours only when its name is the digest it was built under, its+manifest names it, and every file is regular and listed by that manifest.+Removal takes exactly those files: a link only drops its count, so the model+it points at is never touched, and unknown files stay.++A folder is stale once nothing can select it again - its model manifest or+the code that built it has changed - or nobody has used it for a long time.+Use is recorded as the manifest's modification time.+"""+import json+import os+from pathlib import Path+import re+import stat+import time++from .long_paths import io_path, plain, plain_errors++NAME = re.compile(r'vdn-online-lora-[0-9a-f]{24}')+LORA_FILE = re.compile(r'lora/(root|\d{2})\.(safetensors|partial)')+ADALN_FILE = re.compile(r'adaln-tables-v2-[0-9a-f]{24}/(identity|producer)\.json|adaln-tables-v2-[0-9a-f]{24}/\d{2}\.(safetensors|json)')+MARKER = 'manifest.json'+MARKER_LIMIT = 64 << 20+IDLE_DAYS = 30+EXPIRED_IDLE_DAYS = 1+REPARSE_POINT = 0x400+++def redirected(info):+ return stat.S_ISLNK(info.st_mode) or bool(getattr(info, 'st_file_attributes', 0) & REPARSE_POINT)+++def safe_relative(value):+ return (isinstance(value, str) and value and '\\' not in value and ':' not in value+ and not value.startswith('/') and all(part not in ('', '.', '..') for part in value.split('/')))+++@plain_errors+def listing(beside):+ """Real folders of this naming below beside, never through a link."""+ beside = io_path(beside)+ try:+ found = sorted(path for path in beside.iterdir() if NAME.fullmatch(path.name))+ except OSError:+ return []+ return [Path(plain(path)) for path in found if not redirected(path.lstat()) and path.is_dir()]+++@plain_errors+def manifest(folder):+ """The folder's manifest when it names this folder as its own, else None."""+ marker = io_path(folder) / MARKER+ try:+ info = marker.lstat()+ if redirected(info) or not stat.S_ISREG(info.st_mode) or info.st_size > MARKER_LIMIT:+ return None+ value = json.loads(marker.read_text(encoding='utf-8'))+ except (OSError, ValueError):+ return None+ if (not isinstance(value, dict) or not isinstance(value.get('lora_identity'), dict)+ or not isinstance(value.get('online_lora'), dict)+ or str(value.get('source_id', ''))[:24] != Path(folder).name[len('vdn-online-lora-'):]):+ return None+ return value+++def listed_names(value):+ """Relative names the manifest of a folder lists: groups, shared AdaLN tables and itself."""+ names = {MARKER}+ for group in value.get('groups', []):+ if isinstance(group, dict) and safe_relative(group.get('file')):+ names.add(group['file'])+ for table in value.get('adaln_tables', []):+ for row in table.get('files', []) if isinstance(table, dict) else []:+ if isinstance(row, dict) and safe_relative(row.get('file')):+ names.add(row['file'])+ return names+++@plain_errors+def owned_files(folder):+ """Regular files of one folder that are ours, or [] when the folder is not ours."""+ value = manifest(folder)+ if value is None:+ return []+ names = listed_names(value)+ folder = io_path(folder)+ found = []+ for current, directories, files in os.walk(folder, followlinks=False):+ for name in list(directories):+ if redirected((Path(current) / name).lstat()):+ directories.remove(name)+ for name in files:+ path = Path(current) / name+ relative = path.relative_to(folder).as_posix()+ try:+ info = path.lstat()+ except OSError:+ continue+ if redirected(info) or not stat.S_ISREG(info.st_mode):+ continue+ if relative in names or LORA_FILE.fullmatch(relative):+ found.append(Path(plain(path)))+ return found+++def permitted(relative, group_names):+ """A planned name below an online folder: its manifest, an adapter file, a model group or an AdaLN table."""+ return (relative == MARKER or LORA_FILE.fullmatch(relative) is not None+ or ADALN_FILE.fullmatch(relative) is not None or relative in group_names)+++def home(path):+ """The online folder a path lies in, or None."""+ return next((parent for parent in Path(path).parents if NAME.fullmatch(parent.name)), None)+++def last_used(folder):+ try:+ return (io_path(folder) / MARKER).stat().st_mtime+ except OSError:+ return None+++def touch(folder):+ """Record a use; never an error."""+ try:+ os.utime(io_path(folder) / MARKER)+ except OSError:+ pass+++def stale(folder, current, now=None):+ """Why this folder can go, or None. current holds the digests a folder built today would carry."""+ value = manifest(folder)+ used = last_used(folder)+ if value is None or used is None:+ return None+ idle = ((now if now is not None else time.time()) - used) / 86400+ identity = value['lora_identity']+ expired = any(identity.get(key) != digest for key, digest in current.items())+ if expired and idle >= EXPIRED_IDLE_DAYS:+ return 'code or model changed'+ if idle >= IDLE_DAYS:+ return 'unused for %d days' % IDLE_DAYS+ return None+++@plain_errors+def remove(folder):+ """Remove one owned folder's files, then its empty directories. Bytes released by files that had no other link."""+ folder = io_path(folder)+ freed, left = 0, False+ # The manifest is what makes the folder ours, so it goes last, and only when every other file went.+ for path in sorted(owned_files(folder), key=lambda p: p.relative_to(Path(plain(folder))).as_posix() == MARKER):+ if path.name == MARKER and path.parent == Path(plain(folder)) and left:+ continue+ try:+ info = io_path(path).lstat()+ io_path(path).unlink()+ except OSError:+ left = True+ continue+ freed += info.st_size if info.st_nlink == 1 else 0+ for current, directories, files in os.walk(folder, topdown=False, followlinks=False):+ try:+ Path(current).rmdir()+ except OSError:+ pass+ return freed+++@plain_errors+def prune(beside, current, keep=None, now=None):+ """Remove stale folders beside a prepared model, except keep. Returns (folder, reason, bytes) rows."""+ removed = []+ for folder in listing(beside):+ if keep is not None and Path(plain(folder)) == Path(plain(keep)):+ continue+ reason = stale(folder, current, now)+ if reason:+ removed.append((plain(folder), reason, remove(folder)))+ return removeddiff --git a/freevideo_engine/variant_cleanup.py b/freevideo_engine/variant_cleanup.pyindex 19b0a7c..5b0f844 100644--- a/freevideo_engine/variant_cleanup.py+++ b/freevideo_engine/variant_cleanup.py@@ -14,6 +14,10 @@ placed there, one file at a time:the folder's name is the digest of its identity marker and it holds nothingbut table files.+* the online LoRA folders beside its cache that this installer built (see+ online_lora_folders): they hardlink the model's groups, so they are removed+ first and the model files then count only their own link;+A variant with fused LoRA variants beside its cache is kept whole: int8 cannotmerge those adapters yet, so the old model is still the only way to use them.@@ -32,6 +36,7 @@ import statimport timefrom .long_paths import io_path, plain, plain_errors+from . import online_lora_foldersfrom .locking import runtime_lockfrom .storage import fingerprintfrom .runtime_alias import checked_real_path, AliasUnavailable@@ -70,7 +75,8 @@ def inside(base, path):@plain_errors-def unshared_file(path):+def unshared_file(path, links=1):+ """The file's stat when it is a regular file with exactly this many links (its own, by default)."""path = io_path(path)if '.replaced-' in path.name:return None@@ -78,7 +84,7 @@ def unshared_file(path):info = path.lstat()except OSError:return None- if redirected(info) or not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:+ if redirected(info) or not stat.S_ISREG(info.st_mode) or info.st_nlink != links:return Nonereturn info@@ -162,17 +168,18 @@ def _stage(folder, prepared, stage):@plain_errors-def _generated_tables(prepared, table):+def _generated_tables(prepared, table, links=None):"""Files of one engine-generated AdaLN table folder, or None unless it is bound to its identity."""from .adaln_assets import FORMAT, directoryprepared, table = io_path(prepared), io_path(table)if not ADALN_DIRECTORY.fullmatch(table.name) or not inside(prepared, table) or not table.is_dir():return Noneentries = list(table.iterdir())- if any(not ADALN_FILE.fullmatch(entry.name) or unshared_file(entry) is None for entry in entries):+ links = links or (lambda path: 1)+ if any(not ADALN_FILE.fullmatch(entry.name) or unshared_file(entry, links(entry)) is None for entry in entries):return Nonemarker = table / 'identity.json'- info = unshared_file(marker)+ info = unshared_file(marker, links(marker))if info is None or info.st_size > ADALN_IDENTITY_LIMIT:return Nonetry:@@ -185,9 +192,29 @@ def _generated_tables(prepared, table):@plain_errors-def _plan_file(path, kind, entries):+def _regular(path):+ try:+ info = io_path(path).lstat()+ except OSError:+ return False+ return not redirected(info) and stat.S_ISREG(info.st_mode)+++@plain_errors+def _plan_file(path, kind, entries, linked=False):path = io_path(path)entries.append(dict(path=plain(path), kind=kind, bytes=path.lstat().st_size, stamp=fingerprint(path)))+ if linked:+ entries[-1]['linked'] = True+++def _same(entry, now):+ """The file is as planned. Removing another link to the same data changes its change time, which a linked file may do."""+ if not entry.get('linked'):+ return now == entry['stamp']+ ignored = ('ctime_ns', 'change_time_ns')+ return ({k: v for k, v in now.items() if k not in ignored}+ == {k: v for k, v in entry['stamp'].items() if k not in ignored})@plain_errors@@ -201,12 +228,43 @@ def retire(root, catalog, name):return dict(variant=name, folder=plain(folder), files=entries, kept=kept, bytes=0, kept_bytes=0,stage_directories=stage_directories, present=folder.exists() or folder.is_symlink())stages = folder / STAGES+ # Online LoRA folders go first; each hard link they hold on a model file is+ # one more link that file may carry and still count as unshared.+ peers = {}+ beside = (folder / catalog['variants'][name]['cache_prefix']).parent+ online_files = []+ if inside(prepared, beside):+ for online in online_lora_folders.listing(beside):+ for path in online_lora_folders.owned_files(online):+ try:+ info = io_path(path).lstat()+ except OSError:+ continue+ if info.st_ino:+ peers[(info.st_dev, info.st_ino)] = peers.get((info.st_dev, info.st_ino), 0) + 1+ online_files.append((path, info))+ # Each folder's manifest last: it is what makes the folder ours, so it must outlive any file that stays.+ online_files.sort(key=lambda row: (str(online_lora_folders.home(row[0])), row[0] == online_lora_folders.home(row[0]) / online_lora_folders.MARKER))+ for path, info in online_files:+ _plan_file(path, 'online-lora', entries, linked=True)+ # A link to a model file frees nothing of its own: the model file is counted once, under its own name.+ if info.st_ino and info.st_nlink > peers[(info.st_dev, info.st_ino)]:+ entries[-1]['bytes'] = 0+ planned.add(io_path(path))++ def links(path):+ """Links a file may carry: its own, plus the planned online LoRA links to the same data."""+ try:+ info = io_path(path).lstat()+ except OSError:+ return 1+ return 1 + peers.get((info.st_dev, info.st_ino), 0) if info.st_ino else 1for row in catalog['variants'][name]['files']:path = folder / row['file']if path.exists() or path.is_symlink():- info = unshared_file(path)+ info = unshared_file(path, links(path))if info is not None and info.st_size == row['bytes'] and inside(prepared, path):- _plan_file(path, 'catalog', entries)+ _plan_file(path, 'catalog', entries, linked=links(path) > 1)planned.add(path)sidecar = path.with_name(path.name + SIDECAR)if sidecar.exists() and inside(prepared, sidecar) and _sidecar_matches(sidecar, row):@@ -238,11 +296,11 @@ def retire(root, catalog, name):cache = folder / catalog['variants'][name]['cache_prefix']if cache.is_dir() and inside(prepared, cache):for table in sorted(cache.iterdir()):- found = _generated_tables(prepared, table)+ found = _generated_tables(prepared, table, links)for path in found or ():path = io_path(path)if path not in planned:- _plan_file(path, 'adaln', entries)+ _plan_file(path, 'adaln', entries, linked=links(path) > 1)planned.add(path)kept_bytes = 0for current, names, files in os.walk(folder, followlinks=False):@@ -358,6 +416,19 @@ def permitted(path, kind, folder, rows, cache_prefix=None):if row_kind == 'catalog' and key.startswith(name) and PARTIAL.fullmatch(key[len(name):]):return Path(name).parent == path.parentreturn False+ if kind == 'online-lora':+ if cache_prefix is None:+ return False+ beside = folder / Path(cache_prefix).parent+ try:+ relative = path.relative_to(beside)+ except ValueError:+ return False+ parts = relative.parts+ groups = {row_file[len(cache_prefix) + 1:] for row_file in (r['file'] for _, r in rows.values())+ if row_file.startswith(cache_prefix + '/')}+ return (len(parts) >= 2 and online_lora_folders.NAME.fullmatch(parts[0]) is not None+ and online_lora_folders.permitted('/'.join(parts[1:]), groups))if kind == 'adaln':if cache_prefix is None:return False@@ -437,26 +508,37 @@ def clean(plan, catalog=None, receipt=None):if plain(folder) != plain(retired['folder']) or folder == variant_folder(root, catalog, active):raise ValueError('Retired model folder changed; check storage again.')directories = set()+ held = set()for entry in retired['files']:path = Path(entry['path'])reason = None- if not permitted(path, entry['kind'], Path(plain(folder)), rows, catalog['variants'][name]['cache_prefix']):+ if entry['kind'] == 'online-lora' and online_lora_folders.home(path) in held and path == online_lora_folders.home(path) / online_lora_folders.MARKER:+ reason = 'folder still holds files'+ elif not permitted(path, entry['kind'], Path(plain(folder)), rows, catalog['variants'][name]['cache_prefix']):reason = 'not a planned name'- elif not inside(prepared, path) or unshared_file(path) is None:+ elif entry['kind'] == 'online-lora' and not inside(prepared, path):+ reason = 'link, junction, shared or missing'+ elif entry['kind'] == 'online-lora' and not _regular(path):+ reason = 'link, junction, shared or missing'+ elif entry['kind'] != 'online-lora' and (not inside(prepared, path) or unshared_file(path) is None):reason = 'link, junction, shared or missing'else:try:- if fingerprint(path) != entry['stamp']:+ if not _same(entry, fingerprint(path)):reason = 'changed since the scan'except OSError:reason = 'missing'if reason:skipped.append(dict(path=plain(path), reason=reason))+ if entry['kind'] == 'online-lora':+ held.add(online_lora_folders.home(path))continuetry:io_path(path).unlink()except OSError as error:skipped.append(dict(path=plain(path), reason=type(error).__name__))+ if entry['kind'] == 'online-lora':+ held.add(online_lora_folders.home(path))continueremoved.append(dict(path=plain(path), bytes=entry['bytes'], kind=entry['kind']))released += entry['bytes']