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.
Automatically enable space-saving installation (#6)
Bowen Xue23ffd5f1b215
diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.pyindex b53476a..d61fe3f 100644--- a/freevideo_engine/bootstrap.py+++ b/freevideo_engine/bootstrap.py@@ -277,26 +277,31 @@ def plan(args, *, local_progress=None):local = (local_reuse or {}).get('matches', {}).get(row['repo'] + '/' + row['file'])model_entries.append((row, 'found' if size_matches else 'verified' if local else 'download'))entry['needed_bytes'] += 0 if size_matches or local and local['method'] == 'hardlink' else row['bytes']+ partial = path.with_suffix(path.suffix + '.partial')+ if not size_matches and not local and partial.is_file() and partial.stat().st_size <= row['bytes']:+ # Only the streaming strategy can reuse this contiguous prefix.+ # Its completed content must still pass the pinned hash check.+ entry['resume_bytes'] = entry.get('resume_bytes', 0) + partial.stat().st_size# Stream directly into final FP8 groups. The pinned model occupies ~45.3# GiB; allow 52 GiB including the largest group in progress. Never credit# future source deletion toward the space needed to complete conversion.dependencies = dependency_status(root, layout, hardware.system)environments_ready = all(r['exists'] and not r['missing'] and not r['mismatched'] for r in dependencies.values())extra = (0 if reuse_cache or prepared else 52) + (5 if environments_ready else 30 if layout == 'unified' else 45) + 10- path = existing_parent(root)- entry = groups.setdefault(str(path), {'path': str(path), 'needed_bytes': 0,- 'free_bytes': shutil.disk_usage(path).free})- entry['needed_bytes'] += extra * GiB- # Aggregate paths sharing a filesystem; never count one disk's free space twice.- disks = {}- for entry in groups.values():- key = str(os.stat(entry['path']).st_dev)- merged = disks.setdefault(key, dict(paths=[], needed_bytes=0, free_bytes=entry['free_bytes']))- merged['paths'].append(entry['path'])- merged['needed_bytes'] += entry['needed_bytes']- for disk in disks.values():- if disk['needed_bytes'] > disk['free_bytes']:- errors.append('Insufficient disk space for retained models, environments and caches: ' + ', '.join(disk['paths']))+ frontend = None+ if getattr(args, 'frontend_root', None):+ frontend = dict(root=str(args.frontend_root.expanduser().resolve()),+ separate=args.frontend_separate, download=args.frontend_download)+ from .install_disk import budget as disk_budget+ reviewed = (json.loads(Path(args.approved_plan).read_text(encoding='utf-8'))+ if getattr(args, 'approved_plan', None) else saved)+ disk_plan = disk_budget(groups, root, extra,+ eligible=bool(windows_target and layout == 'unified' and (reuse_cache or prepared)+ and getattr(args, 'model_downloader', 'auto') != 'xet'),+ environments_ready=environments_ready, frontend=frontend,+ keep_extreme=reviewed.get('disk_mode') == 'extreme')+ extra = disk_plan['environment_cache_safety_gib']+ errors.extend(disk_plan['errors'])if reuse_cache and not cache_compatible(reuse_cache, hardware.capability):errors.append('--cache must contain a prepared FP8 cache compatible with this GPU scale format.')from .download_settings import read as download_preferences@@ -317,10 +322,13 @@ def plan(args, *, local_progress=None):from .model_transfer import policy as transfer_policybuild = build_parallelism(resources['ram_budget_bytes'], snapshot.get('cpu_threads') or 1) if resources and not windows_target else Nonetransfers = transfer_policy(resources['ram_budget_bytes'], build['estimated_peak_bytes'] if build else 0) if resources else None+ if disk_plan['mode'] == 'extreme':+ transfers = dict(transfers or {}, file_workers=1, overlap_build=False, mode='streaming-space-saver')from .model_status import inventory as model_inventoryreturn {'schema_version': 1, 'engine_version': __version__, 'root': str(root), 'inventory': snapshot, 'policy_estimate': None,'installation_resources': resources,'storage': storage,+ 'disk_mode': disk_plan['mode'], 'disk_policy': disk_plan, 'frontend': frontend,'storage_preparation': ('Download verified slim FP8 weights and fixed AdaLN tables; no original transformer or local conversion'if prepared else 'Stream CPU merge directly to FP8 groups; no complete BF16 intermediate cache'),'storage_cleanup': ('After cache verification and GPU probes, remove only unchanged conversion-only weights downloaded/copied into this installation; borrowed originals and outputs are retained'@@ -351,7 +359,7 @@ def plan(args, *, local_progress=None):'wheel_cache': str(Path(getattr(args, 'wheel_cache', None) or saved.get('wheel_cache') or root / 'wheels').expanduser().resolve()),'rebuild_sage': getattr(args, 'rebuild_sage', False),'model_download_bytes': sum(r['bytes'] for r in files) - present - (local_reuse or {}).get('reused_bytes', 0),- 'existing_model_bytes_size_matched': present, 'disks': list(disks.values()),+ 'existing_model_bytes_size_matched': present, 'disks': disk_plan['disks'],'additional_environment_cache_safety_gib': extra,'preparation_ram_estimate_gib': ('Bounded hash/header verification; no transformer loaded or converted' if prepared else'4–8 GiB working set plus reclaimable source file cache; measured by setup'),@@ -386,6 +394,8 @@ def display(value, ui=None, *, verbose=False):rows.append((label, value[key]))rows.append(('Model download', '~%.1f GiB; Python / GPU packages are additional' % (value['model_download_bytes']/GiB)if value['model_download_bytes'] else 'No new model files expected · verify existing files'))+ if value.get('disk_mode') == 'extreme':+ rows.append(('Disk mode', 'Automatic space saver · sequential downloads · temporary package cache removed before models'))if value.get('local_models'):local = value['local_models']rows.append(('Reuse models', '%.1f GiB verified · %.1f GiB copied locally · source files kept' %@@ -505,7 +515,7 @@ def confirmed(args, value, ask=input, ui=None):if not args.yes or not args.accept_model_license:raise ValueError('--approved-plan requires explicit plan/license acceptance.')reviewed = json.loads(Path(reviewed_path).read_text(encoding='utf-8'))- keys = ('root', 'engine_version', 'environment_layout', 'model_dir', 'encoder_dir', 'vram_gib', 'ram_gib', 'reuse_cache', 'storage', 'storage_cleanup', 'model_downloader', 'prepared_model', 'model_source')+ keys = ('root', 'engine_version', 'environment_layout', 'model_dir', 'encoder_dir', 'vram_gib', 'ram_gib', 'reuse_cache', 'storage', 'storage_cleanup', 'model_downloader', 'prepared_model', 'model_source', 'disk_mode', 'frontend')changed = any(reviewed.get(key) != value.get(key) for key in keys)changed |= reviewed.get('inventory', {}).get('selected_gpu', {}).get('uuid') != value['inventory']['selected_gpu']['uuid']changed |= value['model_download_bytes'] > reviewed.get('model_download_bytes', -1)@@ -579,6 +589,8 @@ def setup_task(label):key = key[len(prefix):]breaktasks = {+ 'release-package-cache': ('Release installation cache', 'Installed components and models are kept'),+ 'space-saving-comfy': ('Prepare ComfyUI', 'Finish the environment before downloading models'),'python': ('Install Python', 'Download and prepare the private Python runtime'),'python-bootstrap-reuse': ('Use existing Python', 'Check the Python already prepared by the launcher'),'venv': ('Create Python environment', 'Prepare an isolated environment for FreeVideo'),@@ -664,6 +676,7 @@ class Installer:# The former complete configuration is retained in machine.before.json.save(previous, dict(saved, root=str(self.root), ready=False, setup_run=str(self.run_dir),storage=value.get('storage', 'compact'),+ disk_mode=value.get('disk_mode', 'normal'),pending_environment_layout=self.layout, model_root=value['model_dir'],encoder_model_root=value.get('encoder_dir', saved.get('encoder_model_root')),wheel_cache=value.get('wheel_cache', saved.get('wheel_cache')),@@ -690,6 +703,9 @@ class Installer:self.env.update(FREEVIDEO_NETWORK_PLAN=str(self.run_dir / 'plan.json'),FREEVIDEO_NETWORK_EVENTS=str(self.run_dir / 'network.jsonl'))self.env = network.proxy_environment(self.env)+ if value.get('disk_mode') == 'extreme':+ from .install_disk import environment+ self.env = environment(self.root, self.env)self.network = dict(value.get('network', {}), events_path=str(self.run_dir / 'network.jsonl'), quiet=True)self.state = {'status': 'running', 'steps': [], 'plan': value}self.state_lock = threading.Lock()@@ -709,6 +725,14 @@ class Installer:try:with (self.run_dir / 'ram.jsonl').open('w', buffering=1, encoding='utf-8') as stream:while not self.monitor_stop.is_set():+ if self.plan.get('disk_mode') == 'extreme':+ from .install_disk import check_floor+ try:+ check_floor([p for disk in self.plan['disks'] for p in disk['paths']])+ except RuntimeError as error:+ self.state['resource_guard'] = str(error)+ self.cancel.set()+ breaktry:row = memory.sample(os.getpid())except OSError as error:@@ -949,8 +973,29 @@ class Installer:overlap = (self.plan.get('model_transfer') or {}).get('overlap_build', True)task('sage', lambda: self.install_sage(uv, python), ('runtime',) if overlap else ('runtime', 'models'),('environment:' + name,))+ if self.plan.get('disk_mode') == 'extreme':+ # Finish all environments before models occupy most of the disk.+ # In particular retain the uv cache until ComfyUI has reused it.+ tasks['sage']['after'] = ('runtime',)+ prerequisites = tuple(key for key in tasks if key != 'models')+ frontend = self.plan.get('frontend') or {}+ if frontend.get('separate'):+ task('frontend', lambda: self.command('space-saving-comfy',+ [python, '-m', 'freevideo_engine.comfy_host', '--root', self.root,+ '--comfy', frontend['root'], '--setup-plan', self.run_dir / 'plan.json']), prerequisites)+ prerequisites = ('frontend',)+ task('package-cache', lambda: self.release_package_cache(uv), prerequisites)+ tasks['models']['after'] = ('package-cache',)return tasks, pythons, comfy+ def release_package_cache(self, uv):+ cache = self.root / 'downloads' / 'uv-cache'+ if cache.is_symlink() or not cache.resolve().is_relative_to(self.root.resolve()):+ raise ValueError('The installation cache points outside this FreeVideo folder; '+ 'space-saving cleanup stopped without removing it.')+ # Use uv's lock-aware cleanup; never unlink its internal files ourselves.+ return self.command('release-package-cache', [uv, 'cache', 'clean', '--cache-dir', cache])+def clone(self, name, url, commit, sparse=None):return network.clone(self.root / 'vendor' / name, url, commit, sparse=sparse, run=self.command,network=self.network, env=self.env)@@ -1134,14 +1179,16 @@ class Installer:from .install_schedule import runtasks, pythons, comfy = self.component_tasks(uv)total = len(tasks) + 4 # Bootstrap, preparation, checks and final readiness.+ phase = 'Install with space saver' if self.plan.get('disk_mode') == 'extreme' else 'Install components in parallel'def scheduling(name, status, completed, count):with self.state_lock:self.state.setdefault('schedule', {})[name] = dict(status=status, after=tasks[name]['after'],exclusive_writers=tasks[name]['writes'], epoch=time.time())save(self.run_dir / 'status.json', self.state)- self.ui.phase('Install components in parallel', 1 + completed, total)- self.ui.phase('Install components in parallel', 1, total)- results = run(tasks, self.cancel, progress=scheduling)+ self.ui.phase(phase, 1 + completed, total)+ self.ui.phase(phase, 1, total)+ results = run(tasks, self.cancel, progress=scheduling,+ workers=1 if self.plan.get('disk_mode') == 'extreme' else 3)sage_manifest = results['sage']python, encoder_python = self.pythons['engine'], self.pythons['encoder']prepared = self.run_dir / 'prepared.json'@@ -1178,6 +1225,7 @@ class Installer:self.ui.phase('Finish setup', total - 1, total)configuration = {'schema_version': 1, 'root': str(self.root), 'source': str(SOURCE),'storage': self.plan.get('storage', 'compact'),+ 'disk_mode': self.plan.get('disk_mode', 'normal'),'environment_layout': self.layout,'system': self.system, 'engine_version': __version__,'git': self.env.get('FREEVIDEO_GIT') or shutil.which('git', path=self.env['PATH']),@@ -1224,6 +1272,9 @@ def main(argv=None):cache_options.add_argument('--cache', type=Path, help='Verify and reuse an existing FP8 cache')cache_options.add_argument('--rebuild-cache', action='store_true', help='Recreate FP8 from pinned source weights, downloading missing sources; preserve failed caches')parser.add_argument('--storage', choices=('compact', 'retain'), help='Default compact: stream FP8 and remove installer-owned conversion sources after verification; retain keeps sources for re-quantization')+ parser.add_argument('--frontend-root', type=Path, help=argparse.SUPPRESS)+ parser.add_argument('--frontend-separate', action='store_true', help=argparse.SUPPRESS)+ parser.add_argument('--frontend-download', action='store_true', help=argparse.SUPPRESS)parser.add_argument('--verify', choices=('auto', 'full'), default='auto', help='auto reuses unchanged pinned receipts; full rereads every required tensor')parser.add_argument('--wheel-cache', type=Path, help='Reusable local Sage2 wheel cache, keyed by architecture and ABI')parser.add_argument('--rebuild-sage', action='store_true', help='Measure a fresh source build, retaining previous build artifacts')diff --git a/freevideo_engine/comfy_host.py b/freevideo_engine/comfy_host.pyindex 7cf3a83..62f3ce6 100644--- a/freevideo_engine/comfy_host.py+++ b/freevideo_engine/comfy_host.py@@ -26,6 +26,24 @@ def prepare(root, comfy, run=None, download=False):return _prepare(root, comfy, machine, run, download)+def prepare_for_setup(root, comfy, plan_path):+ """Finish the frontend before models, without marking the engine ready."""+ root, comfy, plan_path = Path(root).resolve(), Path(comfy).resolve(), Path(plan_path).resolve()+ setup = json.loads(plan_path.read_text(encoding='utf-8'))+ frontend = setup.get('frontend') or {}+ if (setup.get('disk_mode') != 'extreme' or Path(setup['root']).resolve() != root+ or not frontend.get('separate') or Path(frontend['root']).resolve() != comfy):+ raise ValueError('Frontend does not match the space-saving installation plan')+ from .system import venv_python+ python = venv_python(root / 'envs' / 'unified', setup['inventory']['hardware']['system'])+ if Path(sys.executable).resolve() != python.resolve():+ raise ValueError('Run frontend preparation with the installed engine Python')+ machine = dict(python=str(python), setup_run=str(plan_path.parent), disk_mode='extreme',+ git=os.environ.get('FREEVIDEO_GIT'))+ with runtime_lock(root / 'launcher' / 'host-setup.lock', inherit=False):+ return _prepare(root, comfy, machine, None, frontend.get('download', False))++def _prepare(root, comfy, machine, run, download):source = Path(__file__).resolve().parents[1]env = isolated_environment(root, source)@@ -33,6 +51,9 @@ def _prepare(root, comfy, machine, run, download):env['FREEVIDEO_GIT'] = machine['git']env['PATH'] = str(Path(machine['git']).parent) + os.pathsep + env.get('PATH', '')env.update(UV_LINK_MODE='hardlink', UV_CACHE_DIR=str(root / 'downloads' / 'uv-cache'), PYTHONUNBUFFERED='1')+ if machine.get('disk_mode') == 'extreme':+ from .install_disk import environment+ env = environment(root, env)directory = root / 'launcher' / 'host-runs' / (time.strftime('%Y%m%dT%H%M%S') + '-' + str(time.time_ns()))directory.mkdir(parents=True, exist_ok=False)try:@@ -74,6 +95,9 @@ def _prepare(root, comfy, machine, run, download):stdout=output.stdout, stderr=subprocess.STDOUT, supervise=True, start_new_session=True)output.spawned()while child.poll() is None:+ if machine.get('disk_mode') == 'extreme':+ from .install_disk import check_floor+ check_floor((root, comfy))if output.error is not None:raise RuntimeError('Could not retain ComfyUI package output') from output.errortry:@@ -158,8 +182,12 @@ def main():parser.add_argument('--root', type=Path, required=True)parser.add_argument('--comfy', type=Path, required=True)parser.add_argument('--download-comfy', action='store_true', help='Download the pinned ComfyUI application into a new folder')+ parser.add_argument('--setup-plan', type=Path, help=argparse.SUPPRESS)args = parser.parse_args()- prepare(args.root, args.comfy, download=args.download_comfy)+ if args.setup_plan:+ prepare_for_setup(args.root, args.comfy, args.setup_plan)+ else:+ prepare(args.root, args.comfy, download=args.download_comfy)if __name__ == '__main__':diff --git a/freevideo_engine/comfy_launcher.py b/freevideo_engine/comfy_launcher.pyindex 0900f8b..d0782c3 100644--- a/freevideo_engine/comfy_launcher.py+++ b/freevideo_engine/comfy_launcher.py@@ -595,6 +595,8 @@ class Launcher:plan = row.get('plan', {})hardware = plan.get('inventory', {}).get('hardware', {})summary = []+ if plan.get('disk_mode') == 'extreme':+ summary.append(self.t('Space saver (automatic)', '极限省空间(自动启用)'))if hardware.get('gpu_name'):summary.append(hardware['gpu_name'])if 'model_download_bytes' in plan:diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.pyindex 1146405..fc58f4b 100644--- a/freevideo_engine/comfy_launcher_runtime.py+++ b/freevideo_engine/comfy_launcher_runtime.py@@ -33,6 +33,13 @@ TEMPLATE = 'FreeVideo-All-in-One.json'def disk_review(plan, engine, comfy, *, separate, new_comfy):"""Add frontend costs to the right volume, including cross-drive installs."""+ frontend = plan.get('frontend')+ if frontend and frontend['root'] == str(Path(comfy).resolve()) and frontend['separate'] == separate:+ from .install_disk import existing, errors+ disks = [dict(disk, paths=list(disk['paths']),+ free_bytes=shutil.disk_usage(existing(disk['paths'][0])).free)+ for disk in plan.get('disks', [])]+ return 0, disks, errors(disks) # Already included before automatic mode selection.def existing(path):path = Path(path)while not path.exists() and path != path.parent:@@ -51,9 +58,8 @@ def disk_review(plan, engine, comfy, *, separate, new_comfy):disk['free_bytes'] = shutil.disk_usage(parent).freedisk['needed_bytes'] += amountextra += amount- errors = ['Insufficient disk space for ComfyUI and the engine: ' + ', '.join(d['paths'])- for d in disks.values() if d['needed_bytes'] > d['free_bytes']]- return extra, list(disks.values()), errors+ from .install_disk import errors+ return extra, list(disks.values()), errors(disks.values())def layout(path):@@ -465,13 +471,15 @@ class Controller:if not isinstance(extra, list) or any(not isinstance(p, str) for p in extra):raise ValueError('Model folders must be a list of directory paths')extra = extra + ([values['models']] if values.get('models') else [])- self.setup.inspect(dict(root=str(engine), extra_libraries=extra, copy=False))+ self.setup.inspect(dict(root=str(engine), extra_libraries=extra, copy=False,+ frontend=dict(root=descriptor['root'], separate=descriptor['separate'], download=fresh)))row = self._wait_setup()self.state = dict(self.state, plan=row['plan'])extra_disk, disks, disk_errors = disk_review(self.state.get('plan', {}), engine, descriptor['root'],separate=descriptor['separate'], new_comfy=fresh and not Path(descriptor['root']).exists())errors = list(self.state.get('plan', {}).get('errors', []))- self.state = dict(self.state, status='review', extra_disk_bytes=extra_disk, disks=disks, errors=errors + disk_errors)+ self.state = dict(self.state, status='review', extra_disk_bytes=extra_disk, disks=disks,+ errors=list(dict.fromkeys(errors + disk_errors)))def _install(self, accepted):if not accepted or not self.selection:diff --git a/freevideo_engine/comfy_setup.py b/freevideo_engine/comfy_setup.pyindex 8f88ef0..5b73354 100644--- a/freevideo_engine/comfy_setup.py+++ b/freevideo_engine/comfy_setup.py@@ -223,6 +223,13 @@ class Setup:manifest = self.logs / ('libraries-' + uuid.uuid4().hex + '.json')save(manifest, dict(version=1, roots=libraries))arguments = ['setup', '--reuse-models-manifest', str(manifest)]+ frontend = value.get('frontend')+ if frontend:+ arguments += ['--frontend-root', str(Path(frontend['root']).expanduser().resolve())]+ if frontend.get('separate'):+ arguments.append('--frontend-separate')+ if frontend.get('download'):+ arguments.append('--frontend-download')if value.get('copy'):arguments.append('--copy-existing-models')self.selection = dict(root=str(root), arguments=arguments)diff --git a/freevideo_engine/install_disk.py b/freevideo_engine/install_disk.pynew file mode 100644index 0000000..cedbf97--- /dev/null+++ b/freevideo_engine/install_disk.py@@ -0,0 +1,120 @@+"""Disk estimates and live guards for the automatic Windows space saver."""+from pathlib import Path+import shutil+import hashlib+import json++GiB = 1 << 30+SPACE_FLOOR = 2 * GiB+++def existing(path):+ path = Path(path)+ while not path.exists() and path != path.parent:+ path = path.parent+ return path+++def add(disks, path, amount):+ parent = existing(path)+ disk = disks.setdefault(parent.stat().st_dev,+ dict(paths=[], needed_bytes=0, free_bytes=shutil.disk_usage(parent).free))+ if str(parent) not in disk['paths']:+ disk['paths'].append(str(parent))+ disk['needed_bytes'] += amount+++def errors(disks):+ return [('Insufficient disk space: need %.2f GiB, available %.2f GiB, short %.2f GiB · %s' %+ (d['needed_bytes'] / GiB, d['free_bytes'] / GiB,+ (d['needed_bytes'] - d['free_bytes']) / GiB, ', '.join(d['paths'])))+ for d in disks if d['needed_bytes'] > d['free_bytes']]+++def frontend_ready(root, frontend):+ """An interrupted engine install can already have a completed frontend."""+ try:+ root, comfy = Path(root), Path(frontend['root'])+ record = json.loads((root / 'launcher' / 'comfy-host.json').read_text(encoding='utf-8'))+ identity = record['identity']+ env_root = Path(record['environment'])+ return (env_root.resolve().parent == (root / 'envs').resolve()+ and Path(record['python']).is_file()+ and Path(record['python']).resolve().is_relative_to(env_root.resolve())+ and Path(identity['engine_python']).resolve() == (root / 'envs/unified/Scripts/python.exe').resolve()+ and Path(identity['comfy']).resolve() == comfy.resolve()+ and identity['requirements'] == hashlib.sha256((comfy / 'requirements.txt').read_bytes()).hexdigest()+ and json.loads((env_root / 'freevideo-host.json').read_text(encoding='utf-8')) == identity)+ except (OSError, ValueError, KeyError, TypeError):+ return False+++def budget(groups, root, normal_extra, *, eligible, environments_ready, frontend=None, keep_extreme=False):+ """Estimate each volume for the selected installation strategy."""+ frontend = frontend or {}+ def estimate(extreme):+ disks = {}+ for group in groups.values():+ add(disks, group['path'], group['needed_bytes'] - (group.get('resume_bytes', 0) if extreme else 0))+ extra = (1 if environments_ready else 6) if extreme else normal_extra+ add(disks, root, extra * GiB)+ if frontend.get('separate') and not (extreme and frontend_ready(root, frontend)):+ add(disks, root, (3 if extreme else 12) * GiB)+ if frontend.get('download') and not Path(frontend['root']).exists():+ add(disks, frontend['root'], GiB)+ if extreme:+ for disk in disks.values():+ disk['needed_bytes'] += SPACE_FLOOR+ return list(disks.values()), extra + (2 if extreme else 0)+ normal, extra = estimate(False)+ extreme = eligible and (keep_extreme or bool(errors(normal)))+ disks, extra = estimate(True) if extreme else (normal, extra)+ return dict(mode='extreme' if extreme else 'normal', disks=disks,+ environment_cache_safety_gib=extra, errors=errors(disks),+ ordinary_needed_bytes=sum(d['needed_bytes'] for d in normal),+ safety_bytes_per_volume=SPACE_FLOOR if extreme else 0)+++def environment(root, env):+ """Bound package expansion and keep its temporary files on the chosen disk."""+ temporary = Path(root) / 'downloads' / 'install-temp'+ temporary.mkdir(parents=True, exist_ok=True)+ return dict(env, UV_CONCURRENT_DOWNLOADS='1', UV_CONCURRENT_INSTALLS='1',+ UV_CONCURRENT_BUILDS='1', UV_LINK_MODE='hardlink',+ TMP=str(temporary), TEMP=str(temporary), TMPDIR=str(temporary))+++def check_floor(paths):+ seen = set()+ for path in paths:+ parent = existing(path)+ device = parent.stat().st_dev+ if device in seen:+ continue+ seen.add(device)+ free = shutil.disk_usage(parent).free+ if free < SPACE_FLOOR:+ raise RuntimeError('Space-saving installation paused: less than 2 GiB free on %s '+ '(%.2f GiB available). Free space and resume; downloaded files are retained.' %+ (parent, free / GiB))+++def check_models(entries):+ """Recheck actual free disk AFTER package cleanup, before writing any models."""+ disks = {}+ for row, path, _, local in entries:+ remaining = row['bytes']+ if path.is_file() and path.stat().st_size == remaining:+ remaining = 0 # provision still verifies its pinned content.+ elif local and local.get('method') == 'hardlink':+ remaining = 0+ else:+ partial = path.with_suffix(path.suffix + '.partial')+ if partial.is_file() and partial.stat().st_size <= remaining:+ remaining -= partial.stat().st_size+ add(disks, path.parent, remaining)+ for disk in disks.values():+ disk['needed_bytes'] += SPACE_FLOOR+ problems = errors(disks.values())+ if problems:+ raise RuntimeError('\n'.join(problems) + '\nFree space and resume; installed components and downloaded files are retained.')diff --git a/freevideo_engine/launcher_copy.py b/freevideo_engine/launcher_copy.pyindex e427e8f..c78b01f 100644--- a/freevideo_engine/launcher_copy.py+++ b/freevideo_engine/launcher_copy.py@@ -30,6 +30,8 @@ ZH = dict([('Check build tools', '检查编译工具'), ('Build SageAttention 2', '准备 GPU 加速'),('Install SageAttention 2', '安装 GPU 加速组件'), ('Prepare dependencies', '准备运行组件'),('Install components in parallel', '安装运行组件'),+ ('Install with space saver', '极限省空间安装'),+ ('Release installation cache', '释放安装缓存'),('Install acceleration and download models', '安装加速组件和下载模型'),('Verify installation on your GPU', '检查 GPU 加速'), ('Finish setup', '完成安装'),('Setup complete', '安装完成'), ('Setup interrupted', '安装已暂停'), ('Setup failed', '安装未完成'),diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.pyindex 39f226e..dd15ba5 100644--- a/freevideo_engine/launcher_session.py+++ b/freevideo_engine/launcher_session.py@@ -465,6 +465,8 @@ class Session:source = preferences['source']plan = row.get('plan', {})estimate = []+ if plan.get('disk_mode') == 'extreme':+ estimate.append(self.t('Space saver (automatic)', '极限省空间(自动启用)'))gpu = plan.get('inventory', {}).get('hardware', {}).get('gpu_name')if gpu:estimate.append(gpu)diff --git a/freevideo_engine/model_transfer.py b/freevideo_engine/model_transfer.pyindex ca125b7..879b347 100644--- a/freevideo_engine/model_transfer.py+++ b/freevideo_engine/model_transfer.py@@ -586,6 +586,7 @@ def download(row, path, plan, progress_callback, headers_for, *, transfer_compleif row['bytes'] >= max(MIN_SDK_BYTES, 64 * MiB) and mount_type(path) in ('tmpfs', 'ramfs'):raise ValueError('Model directory is on a RAM-backed filesystem. Choose a disk directory with --models /path/on/disk (and --encoder-models for the encoder). Existing files retained.')selected = plan.get('model_transfer') or policy(16 * GiB)+ space_saver = plan.get('disk_mode') == 'extreme'# A transport-complete notification is intentionally separate from the# function's return: the latter means the pinned hash has been checked.# Keep the notification once per file even when a source/route retry is@@ -605,6 +606,9 @@ def download(row, path, plan, progress_callback, headers_for, *, transfer_complefrom .download_settings import current, SwitchRequestedactive=current(plan.get('network') or {})def resource_check():+ if space_saver:+ from .install_disk import check_floor+ check_floor((path.parent,))selected=current(plan.get('network') or {})if selected.get('switch_id') != active.get('switch_id'):raise SwitchRequested(selected)@@ -613,7 +617,7 @@ def download(row, path, plan, progress_callback, headers_for, *, transfer_complecache.check()networking = dict(plan.get('network', {}), resource_check=resource_check)retained_manual=retained_payload(stage_directory('manual',row,path),row)- if active.get('source') not in (None,'auto') or retained_manual:+ if not space_saver and (active.get('source') not in (None,'auto') or retained_manual):candidates=network.model_urls(networking,row)# On a rerun, honor the user's last explicit switch rather than the# normal affinity ordering intended for automatic recovery.@@ -645,6 +649,10 @@ def download(row, path, plan, progress_callback, headers_for, *, transfer_compleif selected not in [name for name,_ in candidates]:raise RuntimeError('The selected source has no compatible file for '+row['file']+'. Current download stopped; all fragments retained.')networking.update(manual_source_switch=True,manual_source=selected)+ if space_saver:+ # curl resumes the same contiguous prefix across sources.+ # Do not assemble SDK ranges or allocate a second copy.+ continue# run_sdk/curl have joined their workers before this point.# Reuse known byte ranges, including disjoint MS parts.from .transfer_handoff import migrate@@ -668,6 +676,11 @@ def _download(row, path, plan, progress_callback, headers_for, *, transfer_complnetworking = dict(plan.get('network', {}), allow_model_restart=plan.get('allow_model_restart', False))candidates = network.model_urls(networking, row)family = network.model_family(row)+ if plan.get('disk_mode') == 'extreme':+ network.download(candidates, path, row.get('sha256') or row['git_blob'], progress_callback,+ network=dict(networking, allow_model_restart=False), size=row['bytes'], headers_for=headers_for,+ algorithm='sha256' if row.get('sha256') else 'sha1', git_blob=not row.get('sha256'), category=family)+ returnrequire_xet = plan.get('model_downloader') == 'xet' and row['bytes'] >= MIN_SDK_BYTESif require_xet:candidates = network.model_urls(dict(networking, mode='official'), row)diff --git a/freevideo_engine/provision.py b/freevideo_engine/provision.pyindex 995dadc..4077458 100644--- a/freevideo_engine/provision.py+++ b/freevideo_engine/provision.py@@ -85,6 +85,10 @@ def models(plan):local = (plan.get('local_models') or {}).get('matches', {}).get(local_key(row))entry = (row, path, hf_directory, local)(local_files if path.exists() or path.is_symlink() or local else missing).append(entry)+ space_saver = plan.get('disk_mode') == 'extreme'+ if space_saver:+ from .install_disk import check_models+ check_models(local_files + missing)stopped = threading.Event()lock = threading.RLock()failures = []@@ -93,6 +97,9 @@ def models(plan):def check():if stopped.is_set():raise CancelledError('Parallel model preparation stopped; all files retained')+ if space_saver:+ from .install_disk import check_floor+ check_floor((root, model_dir, encoder_dir))def emit(event, **details):with lock:@@ -140,6 +147,7 @@ def models(plan):raise ValueError('Existing model failed pinned integrity check; preserved without overwrite: ' + str(path))elif local:def local_progress(value):+ check()progress(value.get('done_bytes', 0), value.get('total_bytes', row['bytes']))method = import_file(row, path, local, callback=local_progress)complete(row, path, dict(file_identity(path, row), method='verified_local_' + method),@@ -165,6 +173,8 @@ def models(plan):networking['resource_check'] = resource_checkdownload_plan = dict(plan, network=networking)requested_workers = (plan.get('model_transfer') or {}).get('file_workers', 1)+ if space_saver:+ requested_workers = 1try:workers = max(1, min(len(missing), int(requested_workers)))except (TypeError, ValueError):@@ -172,6 +182,8 @@ def models(plan):def download_one(entry, transfer_ready=None):row, path, hf_directory, _ = entrycheck()+ if space_saver:+ check_models(local_files + missing)# A user may copy a file in while setup is active. Do not claim# ownership of, replace, or download over that newly present file.if path.exists() or path.is_symlink():@@ -288,7 +300,9 @@ def models(plan):# downloader. Same-file SDK concurrency and its live RAM guard remain# unchanged; file_workers only overlaps separate files.with ThreadPoolExecutor(max_workers=1, thread_name_prefix='model-verification') as pool:- verification = pool.submit(verify_local) if local_files else None+ if space_saver:+ verify_local() # Local copies must also finish before downloads start.+ verification = pool.submit(verify_local) if local_files and not space_saver else Nonetry:download_missing()if verification is not None: