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.

Fix installation resource gating and launcher update recovery (#2)

Bowen Xue90683b3ae834
diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py
index c6a8ee1..fff033d 100644
--- a/freevideo_engine/bootstrap.py
+++ b/freevideo_engine/bootstrap.py
@@ -21,7 +21,7 @@ from urllib.parse import unquote, urlsplit
from .hardware import Hardware, GiB, cgroup_capacity
from . import __version__
-from .policy import choose
+from .policy import resource_budget
from .monitoring import save
from .install_tuning import build_parallelism, required_models, cache_compatible, wheel_key
from .terminal_ui import TerminalUI, LogProgress
@@ -206,11 +206,10 @@ def plan(args, *, local_progress=None):
errors.append('Missing %s. Run ./setup.sh interactively to install basic tools, then review the engine plan.' % name)
if not args.hardware_json and not shutil.which('curl'):
errors.append('Missing curl for bounded downloads and HTTP/SOCKS proxy support. Run ./setup.sh to install it.')
- policy = None
+ resources = None
try:
- policy = choose(hardware, vram_gib=vram_gib, ram_gib=ram_gib,
- available_backends={'sage2', 'torch-flash', 'cudnn'},
- allow_capacity_trial=True).to_dict()
+ resources = resource_budget(hardware, vram_gib=vram_gib, ram_gib=ram_gib)
+ resources['ram_budget_bytes'] = max(0, resources['ram_budget_bytes'])
except ValueError as error:
errors.append(str(error))
model_dir = Path(args.models or saved.get('model_root') or root / 'models' / 'vdn').expanduser().resolve()
@@ -316,10 +315,11 @@ def plan(args, *, local_progress=None):
if error:
errors.append(error)
from .model_transfer import policy as transfer_policy
- build = build_parallelism(policy['ram_budget_bytes'], snapshot.get('cpu_threads') or 1) if policy and not windows_target else None
- transfers = transfer_policy(policy['ram_budget_bytes'], build['estimated_peak_bytes'] if build else 0) if policy else None
+ build = build_parallelism(resources['ram_budget_bytes'], snapshot.get('cpu_threads') or 1) if resources and not windows_target else None
+ transfers = transfer_policy(resources['ram_budget_bytes'], build['estimated_peak_bytes'] if build else 0) if resources else None
from .model_status import inventory as model_inventory
- return {'schema_version': 1, 'engine_version': __version__, 'root': str(root), 'inventory': snapshot, 'policy_estimate': policy,
+ return {'schema_version': 1, 'engine_version': __version__, 'root': str(root), 'inventory': snapshot, 'policy_estimate': None,
+ 'installation_resources': resources,
'storage': storage,
'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'),
@@ -449,12 +449,10 @@ def display_details(value, ui=None):
limits = [value.get(key) for key in ('vram_gib', 'ram_gib')]
rows.append(('Resources', 'Automatic · current available VRAM/RAM' if all(v is None for v in limits)
else 'Capacity limits · VRAM %s / RAM %s' % tuple('auto' if v is None else '%g GiB' % v for v in limits)))
- p = value['policy_estimate']
- if p:
- rows += [('Budgets', 'GPU %.2f GiB / RAM %.2f GiB · system reserves %.2f / %.2f GiB' %
- tuple(p[k]/GiB for k in ('gpu_budget_bytes', 'ram_budget_bytes', 'gpu_system_reserve_bytes', 'ram_system_reserve_bytes'))),
- ('Strategy', '%s · %s · %d resident blocks · %.2f GB pinned weights' %
- (p['engine']['linear_compute'], p['engine']['attention'], p['engine']['resident_blocks'], p['engine']['pin_host_gb']))]
+ resources = value.get('installation_resources') or value.get('policy_estimate')
+ if resources:
+ rows.append(('Installation RAM budget', '%.2f GiB · system growth reserve %.2f GiB' %
+ (resources['ram_budget_bytes']/GiB, resources['ram_system_reserve_bytes']/GiB)))
rows.append(('Install root', value['root']))
rows.append(('Environment', value['environment_layout'] + ' · text encoder exits before video models load'))
rows.append(('Kernel installation', value.get('kernel_install', 'Local Sage2 build')))
@@ -645,6 +643,7 @@ class Installer:
def initialize(self, value, ui):
self.plan = value
+ self.resources = value.get('installation_resources') or value.get('policy_estimate') or {}
self.root = Path(value['root'])
self.layout = value.get('environment_layout', 'unified')
self.system = value['inventory'].get('hardware', {}).get('system', platform.system())
@@ -757,12 +756,12 @@ class Installer:
# sampled. Allow two resamples, while checking the live
# system floor on every attempt. A complete over-budget
# reading and persistent failures still stop the work.
- if available < floor or (used is not None and used > self.plan['policy_estimate']['ram_budget_bytes']):
+ if available < floor or (used is not None and used > self.resources['ram_budget_bytes']):
self.state['resource_guard'] = 'Installation crossed its RAM budget or the %d GiB emergency system floor.' % (floor / GiB)
if row.get('private_commit_bytes') is not None:
self.state['resource_guard'] += (' ' + setup_memory_status(row) +
' · Process budget %.1f GiB (working set; commit is diagnostic).' %
- (self.plan['policy_estimate']['ram_budget_bytes']/GiB))
+ (self.resources['ram_budget_bytes']/GiB))
self.cancel.set()
break
if (used is None and (self.system != 'Windows' or unreadable >= 3)
diff --git a/freevideo_engine/desktop.py b/freevideo_engine/desktop.py
index 1d92e7c..e152266 100644
--- a/freevideo_engine/desktop.py
+++ b/freevideo_engine/desktop.py
@@ -465,14 +465,13 @@ class Desktop:
"""Figures go in tiles; only what a figure cannot say stays as text."""
gib = lambda value: '%.1f GiB' % (value/2**30)
h = self.plan['inventory']['hardware']
- estimate = self.plan['policy_estimate']
+ estimate = self.plan.get('installation_resources') or self.plan.get('policy_estimate')
local = self.plan.get('local_models')
tiles = [(self.t('VRAM free', '空闲显存'), '%s / %s' % (gib(h['vram_free']), gib(h['vram_total']))),
(self.t('RAM available', '可用内存'), '%s / %s' % (gib(h['ram_available']), gib(h['ram_total']))),
(self.t('To download', '需下载'), gib(self.plan['model_download_bytes']))]
if estimate:
- tiles.append((self.t('Work budget · GPU / RAM', '运行预算 · GPU/RAM'), '%.1f / %.1f GiB' % (
- estimate['gpu_budget_bytes']/2**30, estimate['ram_budget_bytes']/2**30)))
+ tiles.append((self.t('Installation RAM budget', '安装内存预算'), gib(estimate['ram_budget_bytes'])))
for disk in self.plan['disks'][:1]:
tiles.append((self.t('Disk needed', '磁盘需求'),
'%s / %s' % (gib(disk['needed_bytes']), gib(disk['free_bytes']))))
diff --git a/freevideo_engine/installation_diagnostics.py b/freevideo_engine/installation_diagnostics.py
index ea859df..d20479d 100644
--- a/freevideo_engine/installation_diagnostics.py
+++ b/freevideo_engine/installation_diagnostics.py
@@ -116,7 +116,8 @@ def enrich(result, value):
result['coverage']['installation_memory'] = bool(result['worker_resources']['ram'] or
result['worker_resources']['ram_samples'])
result['coverage']['worker_memory'] = bool(result['worker_resources']['ram'])
- estimate = d.mapping(d.mapping(state.get('plan')).get('policy_estimate'))
+ plan = d.mapping(state.get('plan'))
+ estimate = d.mapping(plan.get('installation_resources') or plan.get('policy_estimate'))
result['budgets'].update(d.numbers({'ram': estimate.get('ram_budget_bytes')}, ('ram',)))
for row in d.sequence(state.get('steps'))[-32:]:
row = d.mapping(row)
diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py
index 61497db..8db8b19 100644
--- a/freevideo_engine/launcher_session.py
+++ b/freevideo_engine/launcher_session.py
@@ -303,12 +303,17 @@ class Session:
def update(self, token=''):
if not self.updater or self.updater.busy or self.controller.busy or self.importer.busy:
return
- from .launcher_update import launch_download, RELEASE_PAGE
+ from .launcher_update import launch_download, RELEASE_PAGE, DownloadedLauncherUnavailable
from .windows_ux import open_browser
row = self.updater.state
if row['status'] == 'ready':
self.persist()
- launch_download(row['candidate'], self.updater.root, token=self.updater.token)
+ try:
+ launch_download(row['candidate'], self.updater.root, token=self.updater.token)
+ except DownloadedLauncherUnavailable:
+ self.error = ''
+ self.updater.run('download', row['candidate'])
+ return
self.closing = True
elif row.get('candidate'):
if self.updater.current.get('packaging') == 'onedir':
diff --git a/freevideo_engine/launcher_update.py b/freevideo_engine/launcher_update.py
index 1800aee..6d5dff3 100644
--- a/freevideo_engine/launcher_update.py
+++ b/freevideo_engine/launcher_update.py
@@ -189,11 +189,15 @@ def download(candidate, root, token='', *, progress=None, cancel=None):
return target
+class DownloadedLauncherUnavailable(ValueError):
+ """The cached executable needs downloading again before it can be started."""
+
+
def launch_download(candidate, root, *, token='', popen=None):
candidate = manifest(candidate)
path = executable_path(root, candidate)
if not verified(path, candidate['asset']):
- raise ValueError('Downloaded launcher is missing or changed; download again')
+ raise DownloadedLauncherUnavailable('Downloaded launcher is missing or changed; download again')
env = dict(os.environ, FREEVIDEO_LAUNCHER_HOME=str(Path(root).absolute().resolve()))
if token:
env['GITHUB_TOKEN'] = token # Session only; never stored in a receipt or command.
diff --git a/freevideo_engine/launcher_update_ui.py b/freevideo_engine/launcher_update_ui.py
index dc63738..f67c604 100644
--- a/freevideo_engine/launcher_update_ui.py
+++ b/freevideo_engine/launcher_update_ui.py
@@ -3,7 +3,7 @@ import time
import webbrowser
from . import branding
-from .launcher_update import RELEASE_PAGE, launch_download
+from .launcher_update import RELEASE_PAGE, launch_download, DownloadedLauncherUnavailable
class UpdateUI:
@@ -78,6 +78,8 @@ class UpdateUI:
else:
self.client.token = self.token.get().strip()
self.client.run('check')
+ except DownloadedLauncherUnavailable:
+ self.client.run('download', row['candidate'])
except Exception as error:
from .diagnostics import Redactor
self.client.state = dict(status='error', error=Redactor([(self.client.token, '<REDACTED>')]).text(str(error)),
diff --git a/freevideo_engine/model_transfer.py b/freevideo_engine/model_transfer.py
index 87fd802..ca125b7 100644
--- a/freevideo_engine/model_transfer.py
+++ b/freevideo_engine/model_transfer.py
@@ -395,7 +395,8 @@ class TransferSizeError(RuntimeError):
def run_sdk(source, row, path, plan, progress_callback, networking, transfer_complete=None):
from .ram import ProcessMemory
from .hardware import cgroup_capacity
- selected = dict(plan.get('model_transfer') or policy(plan.get('policy_estimate', {}).get('ram_budget_bytes', 16*GiB)))
+ resources = plan.get('installation_resources') or plan.get('policy_estimate') or {}
+ selected = dict(plan.get('model_transfer') or policy(resources.get('ram_budget_bytes', 16*GiB)))
# The compiler and desktop can consume RAM after preflight. Recheck here.
available = system_memory()['available_bytes']
_, group_available = cgroup_capacity()
diff --git a/freevideo_engine/policy.py b/freevideo_engine/policy.py
index 33204d4..18b0af8 100644
--- a/freevideo_engine/policy.py
+++ b/freevideo_engine/policy.py
@@ -385,26 +385,9 @@ class Policy:
policy=self.to_dict())
-def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
- gpu_reserve_gib=None, ram_reserve_gib=None, available_backends=None, canvas=None,
- demonstrated_ram_bytes=None, allow_capacity_trial=False, stage='generation'):
- from .geometry import geometry
- if stage not in ('encoding', 'generation'):
- raise ValueError('Resource planning stage must be encoding or generation')
- if canvas is not None:
- checked = geometry(canvas['width'], canvas['height'], frames=canvas['frames'])
- if any(canvas.get(k) != checked[k] for k in ('width', 'height', 'frames', 'video_tokens')):
- raise ValueError('Resource policy requires aligned, consistent request geometry')
- reference_rows = 0
- if canvas is not None:
- for name in ('reference_video_tokens', 'reference_audio_tokens'):
- count = canvas.get(name, 0)
- if type(count) is not int or count < 0:
- raise ValueError('Reference token counts must be nonnegative integers')
- reference_rows += count
- effective_tokens = canvas['video_tokens'] + reference_rows if canvas is not None else None
- if hardware.capability < (8, 0):
- raise ValueError('This engine targets Ampere and newer NVIDIA GPUs.')
+def resource_budget(hardware: Hardware, *, vram_gib=None, ram_gib=None,
+ gpu_reserve_gib=None, ram_reserve_gib=None):
+ """Live capacity and growth reserves, without admitting a generation request."""
# Saved policies store whole bytes. Validate in that same unit so the
# minimum reserve survives the bytes -> GiB round trip between passes.
if gpu_reserve_gib is not None and (not math.isfinite(gpu_reserve_gib) or
@@ -431,6 +414,46 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
raise ValueError('System RAM headroom must be finite and nonnegative.')
gpu_budget = free_gpu - int(reserve_gpu * GiB)
ram_budget = free_ram - int(reserve_ram * GiB)
+ return dict(gpu_capacity_bytes=gpu_total, ram_capacity_bytes=ram_total,
+ gpu_available_bytes=free_gpu, ram_available_bytes=free_ram,
+ gpu_system_reserve_bytes=int(reserve_gpu * GiB),
+ ram_system_reserve_bytes=int(reserve_ram * GiB),
+ gpu_budget_bytes=gpu_budget, ram_budget_bytes=ram_budget)
+
+
+def decoder_workspace(canvas=None):
+ """Existing offloaded decoder allowance; fixed weights do not shrink with video length."""
+ area = canvas['width'] * canvas['height'] / (1344 * 768) if canvas is not None else 1.
+ return int(3.25 * GiB * max(1., area))
+
+
+def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
+ gpu_reserve_gib=None, ram_reserve_gib=None, available_backends=None, canvas=None,
+ demonstrated_ram_bytes=None, allow_capacity_trial=False, stage='generation'):
+ from .geometry import geometry
+ if stage not in ('encoding', 'generation'):
+ raise ValueError('Resource planning stage must be encoding or generation')
+ if canvas is not None:
+ checked = geometry(canvas['width'], canvas['height'], frames=canvas['frames'])
+ if any(canvas.get(k) != checked[k] for k in ('width', 'height', 'frames', 'video_tokens')):
+ raise ValueError('Resource policy requires aligned, consistent request geometry')
+ reference_rows = 0
+ if canvas is not None:
+ for name in ('reference_video_tokens', 'reference_audio_tokens'):
+ count = canvas.get(name, 0)
+ if type(count) is not int or count < 0:
+ raise ValueError('Reference token counts must be nonnegative integers')
+ reference_rows += count
+ effective_tokens = canvas['video_tokens'] + reference_rows if canvas is not None else None
+ if hardware.capability < (8, 0):
+ raise ValueError('This engine targets Ampere and newer NVIDIA GPUs.')
+ budget = resource_budget(hardware, vram_gib=vram_gib, ram_gib=ram_gib,
+ gpu_reserve_gib=gpu_reserve_gib, ram_reserve_gib=ram_reserve_gib)
+ gpu_total, ram_total = budget['gpu_capacity_bytes'], budget['ram_capacity_bytes']
+ free_gpu, free_ram = budget['gpu_available_bytes'], budget['ram_available_bytes']
+ reserve_gpu, reserve_ram = budget['gpu_system_reserve_bytes']/GiB, budget['ram_system_reserve_bytes']/GiB
+ gpu_budget, ram_budget = budget['gpu_budget_bytes'], budget['ram_budget_bytes']
+ desktop = hardware.system == 'Windows'
# What this machine has actually held, for the weight cache only.
#
# Retaining weights is worth a 20 GB disk read per step, and only while
@@ -459,9 +482,16 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
ram_total - int(reserve_ram * GiB)))
small_adjustment = (int(4.6 * GiB * (effective_tokens / (72 * 1008) - 1.))
if canvas is not None else 0)
- residual_need = max(5 * GiB, RESIDUAL_ACTIVATION_RESERVE + small_adjustment)
+ # Scale the existing activation estimate with output and reference rows.
+ # Keep the decoder's fixed workspace funded; neither weights nor its
+ # temporal tile shrink in proportion to the number of output frames.
+ fixed_workspace = decoder_workspace(canvas)
+ residual_need = max(fixed_workspace, RESIDUAL_ACTIVATION_RESERVE + small_adjustment)
residual_floor = (residual_need if desktop else
- max(5 * GiB, RESIDUAL_ADMISSION_FLOOR + small_adjustment))
+ max(fixed_workspace, RESIDUAL_ADMISSION_FLOOR + small_adjustment))
+ # Preserve the reference-canvas trial boundary while allowing smaller
+ # requests to reach their geometry-aware placement below 5 GiB.
+ gpu_minimum = max(fixed_workspace, min(5 * GiB, residual_floor))
original_reserve_gpu = reserve_gpu
# Let a foreground request spend growth headroom before rejecting it.
# This is live free memory, not the card's nominal capacity: a busy larger
@@ -488,9 +518,10 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# preloaded encoder because the later video stage needs a larger minimum;
# automatic_profile replans generation after conditioning has been saved.
ram_minimum = ENCODER_HOST_BYTES if stage == 'encoding' else 4*GiB
- if gpu_budget < 5 * GiB or ram_budget < ram_minimum:
+ if gpu_budget < gpu_minimum or ram_budget < ram_minimum:
raise ResourceBudgetError(hardware, gpu_total, ram_total, free_gpu, free_ram, reserve_gpu, reserve_ram,
- ram_minimum_bytes=ram_minimum)
+ gpu_minimum_bytes=gpu_minimum, ram_minimum_bytes=ram_minimum,
+ canvas=canvas)
if ram_budget < ENCODER_HOST_BYTES:
# Say so here rather than let a request spend a minute loading a
# 14.6 GiB encoder and die before the first sampling step, which is
@@ -498,7 +529,7 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# this is what the note below offers.
raise ResourceBudgetError(hardware, gpu_total, ram_total, free_gpu, free_ram,
reserve_gpu, reserve_ram, canvas=canvas,
- ram_minimum_bytes=ENCODER_HOST_BYTES,
+ gpu_minimum_bytes=gpu_minimum, ram_minimum_bytes=ENCODER_HOST_BYTES,
ram_requirement='text_encoder_host')
# A foreground generation may try the existing bounded path below a
# measured estimate after reclaiming owned idle caches. This does not add
@@ -994,8 +1025,7 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# these repeatedly-read weights before spending RAM on host copies. At the
# reference canvas a streamed/offloaded clip measured 3.07 GiB whole-GPU;
# 3.25 GiB includes the transfer slot and a small workspace allowance.
- area_ratio = (canvas['width'] * canvas['height'] / (1344 * 768)) if canvas is not None else 1.
- vae_workspace = int(3.25 * GiB * max(1., area_ratio))
+ vae_workspace = decoder_workspace(canvas)
vae_resident = max(0, min(36, int((gpu_budget - vae_workspace) / 268574720))) if decoder_offload else 0
# The bounded decoder loader stores Linear weights in the FP16 dtype that
# autocast would use anyway. This reduces streamed transfer volume and