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.

int8 on 6 GB cards, in-place feed-forward output, int8 offline packs (0.3.3) (#88)

Bowen Xue7c3536a999e2
diff --git a/freevideo_engine/blocks.py b/freevideo_engine/blocks.py
index 2f1af53..437ebf9 100644
--- a/freevideo_engine/blocks.py
+++ b/freevideo_engine/blocks.py
@@ -8,6 +8,25 @@ def _post_into_branch(residual, gate, indices, branch):
return branch
+def chunked_ff(original, chunk):
+ """Run a row-wise FF over tiles of `chunk` rows.
+
+ Each tile's output may replace that tile's input once it is computed. The
+ bounded blocks own their normalized FF input and drop it right after the
+ call, so for them the output goes back into it instead of into a full-size
+ buffer allocated for every block. On Windows, without expandable segments,
+ that allocation is where staging ran out of memory: an RTX 5060 at
+ 1344x768x362 asked for 1.12 GiB with 1.06 GiB free in pieces, and an RTX
+ 3090 capped at a 6 GiB laptop's 4.76 GiB asked for 0.57 with 0.60 free.
+ """
+ def forward(ff, hidden, *args, **kwargs):
+ output = hidden if getattr(ff, '_freevideo_owns_input', False) else torch.empty_like(hidden)
+ for start in range(0, hidden.shape[-2], chunk):
+ output[..., start:start + chunk, :] = original(hidden[..., start:start + chunk, :], *args, **kwargs)
+ return output
+ return forward
+
+
def install_bounded_blocks(model, residual_offload=False):
from src.models.ops.fused_block import _compiled, _pre_ref
pre = _compiled('pre', _pre_ref)
@@ -37,3 +56,5 @@ def install_bounded_blocks(model, residual_offload=False):
forward = residual_forward(pre, post)
for block in model.transformer_blocks:
block.forward = types.MethodType(forward, block)
+ # Both forwards drop the normalized FF input right after the call.
+ block.ff._freevideo_owns_input = True
diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.py
index 6609856..3f3d1be 100644
--- a/freevideo_engine/comfy_assets.py
+++ b/freevideo_engine/comfy_assets.py
@@ -152,6 +152,7 @@ def output_summary(report, relative_video):
gpu_total_bytes=report.get('profile', {}).get('policy', {}).get('hardware', {}).get('vram_total'),
geometry=report.get('geometry', {}),
sampling_plan=report.get('sampling_plan'),
+ low_memory=bool(report.get('low_memory_mode')),
reference_trims=report.get('encoding', {}).get('reference_trims') or [],
preview=bool(report.get('preview')), upscaled_preview=bool(report.get('upscaled_preview')),
video=relative_video.as_posix(), report=relative_video.with_suffix(
diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py
index 07a3072..83ead9e 100644
--- a/freevideo_engine/comfy_bridge.py
+++ b/freevideo_engine/comfy_bridge.py
@@ -386,6 +386,9 @@ def progress_message(event):
uniform_remaining_steps=False)
if name == 'preview_mismatch':
return dict(label='The preview no longer matches; sampling its first pass again', stage='preview_mismatch')
+ if name == 'low_memory_mode':
+ return dict(label='Low-memory mode for this GPU', timing_phase='load',
+ low_memory=dict(staging=bool(event.get('staging')), host_outputs=bool(event.get('host_outputs'))))
if name == 'latent_upscale':
done, total = event.get('completed_steps', 8), event.get('total', 10)
return dict(label='Upscaling before the second pass', phase='sampling', stage='latent_upscale',
diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py
index f1e486d..379abfb 100644
--- a/freevideo_engine/generate.py
+++ b/freevideo_engine/generate.py
@@ -125,6 +125,33 @@ def main():
cli()
+def suggest_alternatives(error, hardware, options):
+ """Name smaller requests this GPU can run now, when only VRAM refused this one.
+
+ A request with a new prompt is first planned for its text encoder, which
+ already applies the video stage's VRAM floor, so that is where most
+ refusals happen. Suggestions are planned for the video stage either way.
+ """
+ if error.details.get('insufficient') != ['gpu'] or not options.get('canvas'):
+ return
+ from .policy import describe_alternatives, feasible_alternatives
+ try:
+ rows = feasible_alternatives(hardware, options['canvas'],
+ **{key: value for key, value in options.items() if key not in ('canvas', 'stage')})
+ except Exception: # A suggestion is advisory; the refusal stands as planned.
+ return
+ if rows:
+ error.details['alternatives'] = rows
+ error.args = (str(error) + '\n' + describe_alternatives(rows),)
+
+
+def low_memory_mode(engine):
+ """The placements that trade speed for a smaller GPU working set, if this plan uses them."""
+ if engine.get('residual_offload') or engine.get('attention_cpu_outputs'):
+ return dict(staging=bool(engine.get('residual_offload')), host_outputs=bool(engine.get('attention_cpu_outputs')))
+ return None
+
+
def automatic_profile(args, canvas, *, stage, evidence, descriptor=None, environment=None):
"""Plan with idle-cache accounting; reclaim once if it prevents admission."""
from .hardware import detect
@@ -254,6 +281,7 @@ def automatic_profile(args, canvas, *, stage, evidence, descriptor=None, environ
impossible_capacity = any(error.details[name+'_capacity_bytes'] - error.details[name+'_reserve_bytes']
< error.details[name+'_minimum_bytes'] for name in error.details['insufficient'])
if attempt or impossible_capacity or not state or not environment.get(ENV):
+ suggest_alternatives(error, hardware, options)
raise
print(json.dumps(dict(event='release_idle_cache', stage=stage,
reason='Cached models prevent next-stage loading; releasing them and measuring again',
@@ -571,6 +599,10 @@ def _run(args):
live['engine'].update({k: profile['engine'][k] for k in ('base', 'checkpoint', 'task', 'steps') if k in profile['engine']})
profile = live
report['profile'] = profile
+ report['low_memory_mode'] = low_memory_mode(profile['engine'])
+ if report['low_memory_mode']:
+ # Slower than usual but bounded; the panel says so while it runs.
+ print(json.dumps(dict(event='low_memory_mode', **report['low_memory_mode'])), flush=True)
from .prediction import predict
from .prediction_ui import show as show_prediction, errors as prediction_errors
condition_hash = tuning.digest(condition)
diff --git a/freevideo_engine/model_guidance.py b/freevideo_engine/model_guidance.py
index 26020de..4d1af6e 100644
--- a/freevideo_engine/model_guidance.py
+++ b/freevideo_engine/model_guidance.py
@@ -13,12 +13,12 @@ def package_instructions(new_comfy, zh=False):
"""Describe the payloads this host can actually import."""
if sys.platform == 'darwin':
return (
- 'Get Common models and the RTX 30/40 model pack; these model files also work on Mac. '
+ 'Get the four model packs (video model, text encoder, video & audio decoder, sampling caches); they also work on Mac. '
'The installer downloads the Mac environment automatically. Do not download the Windows Environment package.',
- '下载「公用模型」和「30/40 系模型包」,其中的模型文件也适用于 Mac。'
+ '下载「视频模型」「文本编码器」「视频与音频解码器」「采样缓存」四个模型包,Mac 同样适用。'
'Mac 运行环境由安装器自动下载,无需下载 Windows「运行环境」包。')[bool(zh)]
- text = ('Get Common models and the pack for your GPU (RTX 30/40 or RTX 50).',
- '下载「公用模型」和对应显卡包(30/40 系或 50 系)。')[bool(zh)]
+ text = ('Get the four model packs: video model, text encoder, video & audio decoder, and sampling caches.',
+ '下载「视频模型」「文本编码器」「视频与音频解码器」「采样缓存」四个模型包。')[bool(zh)]
if new_comfy:
text += '\n' + ('For a new installation, also get the Environment package.',
'全新安装还需「运行环境」包。')[bool(zh)]
@@ -27,8 +27,8 @@ def package_instructions(new_comfy, zh=False):
def video_instructions(zh=False):
if sys.platform == 'darwin':
- return ('For Mac, choose the RTX 30/40 model files and keep their folder structure.',
- 'Mac 请选择 30/40 系模型文件,并保留下载的目录结构。')[bool(zh)]
+ return ('For Mac, choose the int8 model files and keep their folder structure.',
+ 'Mac 请选择 int8 模型文件,并保留下载的目录结构。')[bool(zh)]
return ('Choose your GPU variant on the model page and keep its folder structure.',
'按模型页说明选择显卡版本,保留下载的目录结构。')[bool(zh)]
diff --git a/freevideo_engine/offline_packages.py b/freevideo_engine/offline_packages.py
index e68a76a..6570a2f 100644
--- a/freevideo_engine/offline_packages.py
+++ b/freevideo_engine/offline_packages.py
@@ -13,6 +13,21 @@ from .portable import inside
PREFIX = 'FreeVideo-Windows/'
MAX_BYTES = 300 * 2**30
+# Model packs without their own inventory are "common": the shared pack of the
+# earlier FP8 delivery, or the text encoder, decoder and sampling cache packs
+# since 0.3.0, when the int8 video model pack carries the inventory for GeForce
+# cards and Macs.
+MODEL_VARIANTS = ('common', 'rowwise', 'per_tensor', 'int8_convrot')
+
+
+def pack_name(path):
+ """The download pack a model file belongs to, as the delivery note names it."""
+ parts = path.replace('\\', '/').split('/')
+ if 'sampling-cache' in parts:
+ return '采样缓存'
+ if path.startswith('models/encoder/') or 'latent_upscaler' in parts:
+ return '文本编码器'
+ return '视频与音频解码器' if any(p in ('vae', 'audio_vae', 'vocoder') for p in parts) else '视频模型'
def dependency_id():
@@ -57,7 +72,7 @@ def inspect_archive(path):
marker = next((name for name in ('offline-package.json', 'runtime.json')
if PREFIX + name in names), None)
if marker is None:
- raise ValueError('不是 FreeVideo 离线包,请选择公用模型、显卡模型或运行环境 ZIP。')
+ raise ValueError('不是 FreeVideo 离线包,请选择模型或运行环境 ZIP。')
info = archive.getinfo(PREFIX + marker)
if info.file_size > 16 * 2**20:
raise ValueError('Oversized offline inventory')
@@ -68,11 +83,12 @@ def inspect_archive(path):
if value.get('schema_version') != 2 or value.get('dependency_id') != dependency_id():
raise ValueError('运行环境包版本不匹配,请从下载页面获取配套的运行环境包。')
value = dict(value, kind='runtime', variant=None)
- elif value.get('schema_version') != 1 or value.get('kind') != 'models' or value.get('variant') not in ('common', 'rowwise', 'per_tensor'):
+ elif value.get('schema_version') != 1 or value.get('kind') != 'models' or value.get('variant') not in MODEL_VARIANTS:
raise ValueError('Invalid model package')
import sys
- if sys.platform == 'darwin' and value.get('variant') == 'per_tensor':
- raise ValueError('Mac 请使用「30/40 系模型包」;「公用模型」包可以通用。此处无需导入 50 系模型包。')
+ if sys.platform == 'darwin' and value.get('variant') in ('rowwise', 'per_tensor'):
+ # Macs run the int8 model; FP8 packs only serve Windows workstation cards.
+ raise ValueError('Mac 请使用「视频模型」包(int8),此 FP8 模型包不适用于 Mac。')
rows = value['files']
if not isinstance(rows, list) or not rows:
raise ValueError('Empty offline package')
@@ -160,9 +176,9 @@ def assemble(runtime, models, source):
candidates.append((Path(root), json.loads(path.read_text(encoding='utf-8'))))
variants = {value['variant'] for _, value in candidates}
if not candidates:
- raise ValueError('还需导入公用模型包和对应显卡的模型包。')
+ raise ValueError('还需导入「视频模型」包。')
if len(variants) != 1:
- raise ValueError('请只导入本机对应的一个显卡模型包;无需同时导入两种。')
+ raise ValueError('请只导入一个「视频模型」包。')
model = candidates[0][1]
inventory(model['files'])
if any(not r['path'].startswith('models/') for r in model['files']):
@@ -174,7 +190,7 @@ def assemble(runtime, models, source):
src = next((p for p in sources if p.is_file() and p.stat().st_size == row['bytes']
and hash_file(p) == row['sha256']), None)
if src is None:
- raise ValueError('还缺少公用模型或显卡模型包中的文件:' + row['path'])
+ raise ValueError('还需导入「%s」包,缺少文件:%s' % (pack_name(row['path']), row['path']))
if target.exists():
if hash_file(target) != row['sha256']:
raise ValueError('离线安装已有不同模型,未覆盖:' + str(target))
@@ -186,9 +202,10 @@ def assemble(runtime, models, source):
shutil.copyfile(src, target)
code = materialize_source(source, runtime / 'engine/launcher/source')
variant = model['variant']
+ from .prepared_model import catalog
value = dict(config['configuration'], schema_version=1, variant=variant,
source=str(code.relative_to(runtime).as_posix()),
- source_commit=code.name, cache='models/edge/' + ('rowwise/cache' if variant == 'rowwise' else 'cache'),
+ source_commit=code.name, cache='models/edge/' + catalog()['variants'][variant]['cache_prefix'],
files=config['files'] + model['files'])
inventory(value['files'])
save(runtime / 'portable.json', value)
diff --git a/freevideo_engine/pass_configuration.py b/freevideo_engine/pass_configuration.py
index aa67abf..1785e6b 100644
--- a/freevideo_engine/pass_configuration.py
+++ b/freevideo_engine/pass_configuration.py
@@ -41,16 +41,10 @@ def configuration(engine, selected):
# Ampere keeps its existing weight-only arithmetic. Replace
# the outer row tiling without nesting the old tiling wrapper.
import types
- import torch
- chunk = values['ff_chunk']
+ from .blocks import chunked_ff
for block in model.transformer_blocks:
- original = block.ff._freevideo_unchunked_forward
- def forward(self, hidden, *args, original=original, **kwargs):
- output = torch.empty_like(hidden)
- for start in range(0, hidden.shape[-2], chunk):
- output[..., start:start + chunk, :] = original(hidden[..., start:start + chunk, :], *args, **kwargs)
- return output
- block.ff.forward = types.MethodType(forward, block.ff)
+ block.ff.forward = types.MethodType(chunked_ff(block.ff._freevideo_unchunked_forward,
+ values['ff_chunk']), block.ff)
if changed.intersection(('projection_chunk', 'residual_offload')):
from .packing import install_streamed_forward
from .blocks import install_bounded_blocks
diff --git a/freevideo_engine/policy.py b/freevideo_engine/policy.py
index 9016a3c..df2257b 100644
--- a/freevideo_engine/policy.py
+++ b/freevideo_engine/policy.py
@@ -268,6 +268,38 @@ RESIDUAL_ACTIVATION_RESERVE = int(6.4 * GiB)
# rather than an error, and 0.09 GiB of measured margin is not enough to
# assume it. benchmarks/pro6000-verification/results-pro6000.md.
RESIDUAL_ADMISSION_FLOOR = int(6.25 * GiB)
+
+# The int8 staging path -- four heads, the residual stream staged, no resident
+# blocks -- measured with the allocator capped on an RTX PRO 6000 (2026-10-07):
+#
+# 1344x768x243, 72576 tokens outputs on the GPU 5.14 GiB reserved 20.6 s/step
+# outputs in host RAM 3.15 GiB 42.0 s/step
+# 1184x672x243, 55944 tokens outputs on the GPU 4.48 GiB with one resident
+# block, at the 4.76 GiB budget of an RTX 3060
+# Laptop report (4.08 without the block)
+#
+# Keeping the outputs on the card costs about 2 GiB at 72576 tokens, not the
+# 0.3 GiB surcharge the FP8 path's larger estimate absorbed. Linear in the
+# token count between those anchors, plus a margin.
+#
+# Linux only. On an RTX 3090 under Windows -- no expandable segments, and an
+# Ampere attention path -- the same placement needed far more. Capped at that
+# laptop's 4.76 GiB, 1184x672x243 with one resident block ran out of memory in
+# its second pass and peaked at 4.38 GiB allocated, 4.67 reserved, without it.
+# Capped at 6.05 GiB, 1344x768x243 with no block ran out of memory in attention
+# at 5.89 GiB allocated (above the 5.14 peak with a 0.85 GiB margin), and the
+# retry at two heads was no faster than outputs in host memory at four (74-84
+# against 78-85 s/step). Windows keeps the FP8-derived choice 0.3.2 made.
+INT8_GPU_OUTPUT_PEAKS = ((55944, 4.08), (72576, 5.14))
+INT8_GPU_OUTPUT_MARGIN = int(.25 * GiB)
+
+
+def int8_gpu_output_need(tokens):
+ """Bytes the int8 staging path needs with its attention outputs on the GPU (Linux)."""
+ (low, at_low), (high, at_high) = INT8_GPU_OUTPUT_PEAKS
+ tokens = high if tokens is None else tokens
+ peak = at_high + (at_high - at_low) / (high - low) * (tokens - high)
+ return int(max(at_low, peak) * GiB) + INT8_GPU_OUTPUT_MARGIN
MIN_GPU_RESERVE_GIB = .2
@@ -353,6 +385,57 @@ class ResourceBudgetError(ValueError):
+def feasible_alternatives(hardware, canvas, **options):
+ """Smaller requests this machine can plan now, for a refusal to name.
+
+ The longest video at the requested size, and the requested length at the
+ largest of the panel's smaller pixel targets that fits; each one admitted
+ by this same planner, never estimated separately.
+ """
+ from .geometry import geometry
+ keep = {key: canvas[key] for key in ('task', 'steps', 'reference_video_tokens', 'reference_audio_tokens')
+ if key in canvas}
+
+ def fits(width, height, frames):
+ try:
+ choose(hardware, **dict(options, canvas=dict(geometry(width, height, frames=frames), **keep)))
+ return True
+ except (ResourceBudgetError, ValueError):
+ return False
+
+ width, height, frames = canvas['width'], canvas['height'], canvas['frames']
+ result = []
+ lengths = [n for n in range(39, frames, 17)]
+ low, high, best = 0, len(lengths) - 1, None
+ while low <= high:
+ middle = (low + high) // 2
+ if fits(width, height, lengths[middle]):
+ best, low = lengths[middle], middle + 1
+ else:
+ high = middle - 1
+ if best is not None:
+ result.append(dict(kind='shorter', width=width, height=height, frames=best, seconds=round(best / 24, 1)))
+ ratio = width / height
+ for megapixels in (.75, .5):
+ area = megapixels * 1024 * 1024
+ smaller_width = max(256, int(round((area * ratio) ** .5 / 32)) * 32)
+ smaller_height = max(256, int(round((area / ratio) ** .5 / 32)) * 32)
+ if smaller_width * smaller_height >= width * height:
+ continue
+ if fits(smaller_width, smaller_height, frames):
+ result.append(dict(kind='smaller', width=smaller_width, height=smaller_height, frames=frames,
+ seconds=round(frames / 24, 1)))
+ break
+ return result
+
+
+def describe_alternatives(rows):
+ """One parseable line for logs, reports and the error panel."""
+ return 'Fits now: ' + '; '.join('%dx%d %s %.1f s' % (row['width'], row['height'],
+ 'up to' if row['kind'] == 'shorter' else 'at', row['seconds'])
+ for row in rows) + '.'
+
+
def memory_fraction(budget_bytes, total_bytes):
"""Share of the device a budget represents, or None if it covers all of it.
@@ -538,9 +621,18 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# 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)
+ # The staging estimate was measured on per-tensor FP8, whose FF keeps every
+ # SwiGLU row for one scale (1.94 GiB at 72576 tokens). Int8 rows carry their
+ # own scales and stash nothing. At 1344x768x243 on int8, with a 4.70 GiB
+ # allocator cap (a 6 GiB RTX 3060 Laptop's budget), this path -- four heads,
+ # attention outputs in host memory, the residual stream staged -- completed
+ # the second pass at a 3.15 GiB reserved peak and decoded at 3.01, where the
+ # FP8-derived 6.4 GiB estimate refused the laptop outright.
+ stash = effective_tokens * FF_STASH_WIDTH * 2 if int8 and effective_tokens else 0
+ fp8_residual_need = max(fixed_workspace, RESIDUAL_ACTIVATION_RESERVE + small_adjustment)
+ residual_need = max(fixed_workspace, RESIDUAL_ACTIVATION_RESERVE + small_adjustment - stash)
residual_floor = (residual_need if desktop else
- max(fixed_workspace, RESIDUAL_ADMISSION_FLOOR + small_adjustment))
+ max(fixed_workspace, RESIDUAL_ADMISSION_FLOOR + small_adjustment - stash))
# 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))
@@ -828,9 +920,22 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# a good price for a fifth to a third of the sampling time. When the
# budget cannot cover them the host buffer stays, which is what the
# 9 GiB/1344x768x345 corner needs.
- cpu_outputs = not no_weights and gpu_budget < reserve + GPU_ATTENTION_OUTPUT_BYTES
- if not cpu_outputs:
- reserve += GPU_ATTENTION_OUTPUT_BYTES
+ if int8 and residual_offload and not no_weights:
+ # Int8 staging keeps its outputs on the GPU only where the measured
+ # requirement of that placement fits; GPU_ATTENTION_OUTPUT_BYTES
+ # was an FP8 surcharge absorbed by that path's larger estimate.
+ # Windows makes the choice 0.3.2 made, from the FP8-derived
+ # estimate, whose stash int8 never uses: the int8 measurement does
+ # not hold there (INT8_GPU_OUTPUT_PEAKS).
+ need = (fp8_residual_need + GPU_ATTENTION_OUTPUT_BYTES if desktop
+ else int8_gpu_output_need(effective_tokens))
+ cpu_outputs = gpu_budget < need
+ if not cpu_outputs:
+ reserve = max(reserve, need)
+ else:
+ cpu_outputs = not no_weights and gpu_budget < reserve + GPU_ATTENTION_OUTPUT_BYTES
+ if not cpu_outputs:
+ reserve += GPU_ATTENTION_OUTPUT_BYTES
# Outputs in host memory means the budget could not cover them on the
# card, which is exactly the regime the PRO 6000 run measured: there,
# not staging cost 0.95 GiB of peak and died in the first sampling
@@ -849,6 +954,14 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# weights ran no slower than block 5 on pinned weights. It still
# relieves host RAM, so the leftover goes to it rather than staying idle.
resident = max(0, min(RESIDENT_VRAM_CEILING, int((gpu_budget - reserve) / block_bytes)))
+ if desktop and int8 and residual_offload:
+ # Except int8 staging on Windows, where that leftover is what absorbs
+ # fragmentation and a desktop budget that can shrink mid-run. On an
+ # RTX 3090 capped at 4.76 GiB, 1184x672x243 with outputs in host
+ # memory and two blocks peaked at 4.39 GiB allocated, 4.61 reserved,
+ # after two allocator retries; 1344x768x243 without blocks, 3.88 and
+ # 4.52 with none. Every 0.3.2 Windows staging plan held no blocks.
+ resident = 0
if not small:
# One measured requirement for the group in use, so the block count is
# continuous across the band edges rather than restarting at each.
diff --git a/freevideo_engine/portable.py b/freevideo_engine/portable.py
index 45e46e0..24ebd40 100644
--- a/freevideo_engine/portable.py
+++ b/freevideo_engine/portable.py
@@ -42,7 +42,7 @@ def inside(root, name):
def manifest(root):
value = json.loads((Path(root) / 'portable.json').read_text(encoding='utf-8'))
- if value.get('schema_version') != 1 or value.get('variant') not in ('rowwise', 'per_tensor'):
+ if value.get('schema_version') != 1 or value.get('variant') not in ('rowwise', 'per_tensor', 'int8_convrot'):
raise ValueError('Invalid FreeVideo portable bundle')
seen = set()
for row in value['files']:
@@ -118,9 +118,14 @@ def environment(root, value, environ=None):
def configuration(root, value, hardware):
root = Path(root).resolve()
- expected = 'per_tensor' if hardware.capability[0] >= 10 else 'rowwise'
- if hardware.capability < (8, 0) or value['variant'] != expected:
- raise ValueError('This GPU needs the %s bundle; this archive contains %s. No models were downloaded or changed.' % (expected, value['variant']))
+ from .prepared_model import preferred_format
+ # The GPU's own FP8 granularity, and int8 where it is the faster format.
+ allowed = {'per_tensor' if hardware.capability[0] >= 10 else 'rowwise'}
+ if preferred_format(hardware) == 'int8_convrot':
+ allowed.add('int8_convrot')
+ if hardware.capability < (8, 0) or value['variant'] not in allowed:
+ raise ValueError('This GPU needs the %s bundle; this archive contains %s. No models were downloaded or changed.'
+ % (' or '.join(sorted(allowed)), value['variant']))
from . import __version__
spec = json.loads((Path(__file__).with_name('dependencies.json')).read_text(encoding='utf-8'))
models = inside(root, value['model_root'])
@@ -131,6 +136,7 @@ def configuration(root, value, hardware):
model_root=str(models), encoder_model_root=str(inside(root, value['encoder_root'])),
base=str(models/'h3-base'), checkpoint=str(models/'stage-dmd-step-250'),
cache=str(inside(root, value['cache'])), encoder=spec['models']['encoder_file'].split('/')[-1],
+ prepared_format='int8_convrot' if value['variant'] == 'int8_convrot' else 'fp8',
model_paths=str(root/'engine/encoder-paths.yaml'), kernel_capabilities=str(root/'engine/kernel-capabilities.json'),
gpu_uuid=hardware.gpu_uuid, gpu_name=hardware.gpu_name, model_revision=spec['models']['vdn_revision'],
vram_gib=None, ram_gib=None, ready=False, portable=True,
@@ -154,8 +160,13 @@ def initialize(root, progress=lambda **kw: None):
'base_path': machine['encoder_model_root'], 'text_encoders': 'text_encoders/'}})
# Reuse only this device/driver/runtime's local kernel receipt. No
# foreign ready machine.json or precompiled GPU cache ships in a ZIP.
- from .kernel_capabilities import available_backends
+ from .kernel_capabilities import available_backends, readiness, receipt_path
available_backends(hardware)
+ if machine['prepared_format'] == 'int8_convrot':
+ rows = json.loads(receipt_path().read_text(encoding='utf-8')).get('kernel_probes', [])
+ if not readiness(rows).get('int8_ready'):
+ raise ValueError('The int8 model needs int8 GPU kernels, and they did not pass on this GPU. '
+ 'No models were changed. Details: ' + str(receipt_path()))
machine['ready'] = True
save(root/'engine/machine.json', machine)
save(root/'engine/prepared-cache.json', dict(cache=machine['cache'],
diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json
index ac2c012..5f885be 100644
--- a/freevideo_engine/release_notes.json
+++ b/freevideo_engine/release_notes.json
@@ -1,28 +1,18 @@
{
"schema": 1,
- "product_version": "0.3.2",
+ "product_version": "0.3.3",
"en": {
- "summary": "Adds Preview first to two-pass sampling, deleting in Your creations and prompt box improvements (the example prompt as a placeholder, the last prompt restored on reopening), and fixes installing into folders with spaces.",
+ "summary": "Runs the int8 model on 6 GB graphics cards and imports the int8 offline packs.",
"changes": [
- "Two-pass sampling can stop at a quick half-resolution preview: choose Two-pass: Preview first. When a preview looks right, choose Run second pass; the finished video is identical to generating it directly. Make several previews in a batch and pick one in Your creations.",
- "Your creations can delete videos you no longer need, after a confirmation.",
- "The example prompt is shown greyed out as a placeholder. Typing replaces it without clearing the box first, and a box that was never typed in generates the example. A box emptied after typing stays empty.",
- "Prompt enhancement rewrites the prompt that was typed. With an empty box, turning it on asks for a prompt first.",
- "Replacing or clearing all of the enhanced text starts a new prompt, which is enhanced before generating. Small edits still adjust the enhanced version.",
- "FreeVideo reopens with the last prompt, finished, unfinished or emptied, and its enhancement setting.",
- "Installing into a folder whose path contains a space, such as \"Comfy UI\", stopped at the PyTorch step with \"File not found\". It installs normally now."
+ "Graphics cards with 6 GB of memory, such as a laptop RTX 3060, can now generate with the int8 model instead of being refused, and 8 to 12 GB cards can make longer videos. These runs use a low-memory mode, which is slower, and FreeVideo says so while generating. When a request still does not fit, the message names sizes and lengths that fit now.",
+ "The launcher imports the new int8 offline packs: video model, text encoder, video & audio decoder, and sampling caches."
]
},
"zh": {
- "summary": "二次采样新增「先出预览」,作品可以删除,提示词框改进(示例提示词以灰色占位显示,重新打开时恢复上次的提示词),并修复安装路径含空格时无法安装的问题。",
+ "summary": "6 GB 显存的显卡可以用 int8 模型生成,并支持导入 int8 离线包。",
"changes": [
- "二次采样新增「先出预览」:先用半分辨率快速出一版预览,满意后点「继续二采」,成片与直接生成完全一致。可以批量出几版预览,在「作品」里挑一版继续二采。",
- "「作品」里可以删除不需要的视频,删除前会确认。",
- "示例提示词以灰色占位显示,直接输入即可替换,无需先清空;未输入过时按示例生成,输入后再清空则保持为空。",
- "提示词增强改写已输入的提示词。提示词框为空时开启增强,会提示先输入提示词。",
- "在改写版中全选替换或清空后重新输入,会作为新的提示词,生成前自动改写;局部修改仍只调整改写版。",
- "重新打开 FreeVideo 时恢复上次编写的提示词(包括未写完或已清空的内容)及增强设置。",
- "安装位置的路径中有空格(例如「Comfy UI」)时,安装会停在 PyTorch 步骤并报「File not found」。现在可以正常安装。"
+ "6 GB 显存的显卡(例如笔记本 RTX 3060)现在可以用 int8 模型生成,不再被拒绝;8 到 12 GB 的显卡也能生成更长的视频。这时会改用省显存方式,速度会慢一些,生成时会提示。如果仍然放不下,提示里会给出这台电脑现在能生成的尺寸和时长。",
+ "启动器支持导入新的 int8 离线包:视频模型、文本编码器、视频与音频解码器、采样缓存。"
]
}
}
diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.py
index 90a59b5..417ea8c 100644
--- a/freevideo_engine/runtime.py
+++ b/freevideo_engine/runtime.py
@@ -331,16 +331,10 @@ class Engine:
raise ValueError('FP8 FF chunks require the official inference kernels')
self.device_backend.install_chunked_ff(block.ff, ff_chunk, recompute=fp8_ff_recompute)
continue
+ from .blocks import chunked_ff
original = block.ff.forward
block.ff._freevideo_unchunked_forward = original
-
- def chunked(ff, hidden, *args, original=original, **kwargs):
- output = torch.empty_like(hidden)
- for start in range(0, hidden.shape[-2], ff_chunk):
- output[..., start:start + ff_chunk, :] = original(hidden[..., start:start + ff_chunk, :], *args, **kwargs)
- return output
-
- block.ff.forward = types.MethodType(chunked, block.ff)
+ block.ff.forward = types.MethodType(chunked_ff(original, ff_chunk), block.ff)
if projection_chunk:
from .packing import install_streamed_forward
install_streamed_forward(model, projection_chunk, residual_offload=residual_offload)
diff --git a/web/error_panel.js b/web/error_panel.js
index 67fcbc8..ec8dc15 100644
--- a/web/error_panel.js
+++ b/web/error_panel.js
@@ -153,10 +153,22 @@ export function failureAdvice(value, t) {
return row('validation', ['Check the workflow inputs', '请检查工作流输入'],
['ComfyUI rejected the workflow before generation. The affected nodes and reasons are listed below.', 'ComfyUI 在生成开始前拒绝了工作流,相关节点和具体原因列在下方。'],
['Check the named inputs, connections and model choices. Copy the details or export the error report when asking for help.', '检查下方指出的输入、节点连接和模型选项;反馈时可复制详情或导出错误报告。']);
- if (/FreeVideo resource planning could not admit/i.test(text))
+ if (/FreeVideo resource planning could not admit/i.test(text)) {
+ // The planner names smaller requests it admitted on this GPU just now.
+ const fits = [...(/Fits now: ([^\n]+?)\.?(?:\n|$)/.exec(text)?.[1] || '').matchAll(/(\d+)x(\d+) (up to|at) ([\d.]+) s/g)]
+ .map(([, width, height, kind, seconds]) => ({width, height, longest: kind === 'up to', seconds: Number(seconds)}));
+ if (fits.length) {
+ const en = fits.map(f => f.longest ? `${f.width} × ${f.height} up to ${f.seconds.toFixed(1)} s` : `${f.width} × ${f.height} at ${f.seconds.toFixed(1)} s`).join(', or ');
+ const zh = fits.map(f => f.longest ? `${f.width}×${f.height} 最长 ${f.seconds.toFixed(1)} 秒` : `${f.width}×${f.height} 生成 ${f.seconds.toFixed(1)} 秒`).join(',或 ');
+ return row('resources', ['This video is too large for the free GPU memory', '这段视频超出了当前可用显存'],
+ ['Resource planning could not fit this request within the GPU memory available right now.', '资源规划发现这段视频超出了当前可用的显存。'],
+ [`This computer can make ${en} right now. Change the duration or total pixels and generate again; closing other programs that use the GPU also frees memory.`,
+ `这台电脑现在可以生成:${zh}。改一下时长或总像素后再生成即可;关闭其他占用显卡的程序也能腾出显存。`]);
+ }
return row('resources', ['The request exceeds available memory', '当前任务的可用内存不足'],
['Resource planning could not fit this request within the available GPU or system memory.', '资源规划发现当前任务超出了可用显存或系统内存预算。'],
['Close other memory-heavy applications, or select a lower resolution or shorter duration and retry. The details show which memory budget was insufficient.', '关闭其他占用内存的程序,或自行调低分辨率、缩短时长后重试。下方详情会指出不足的内存类型和差额。']);
+ }
if (/commit headroom exhausted|paging file is too small|WinError 1455/i.test(text))
return row('commit', ['Windows memory allocation limit reached', 'Windows 内存提交额度不足'],
['Windows cannot back another memory allocation, even if physical RAM is still available.', 'Windows 已没有足够的提交额度;这与物理 RAM 是否还有空闲是两回事。'],
diff --git a/web/freevideo.js b/web/freevideo.js
index f47b7af..81edff7 100644
--- a/web/freevideo.js
+++ b/web/freevideo.js
@@ -335,6 +335,7 @@ function resultPanel(node) {
}
panel.append(stats, links, progress.report);
for (const row of value.reference_trims || []) panel.append(el("div", referenceTrimText(row, text), "fv-note fv-trim-note"));
+ if (value.low_memory && !value.result_cache_hit) panel.append(el("div", text('This video used the low-memory mode for this GPU, so it took longer than usual. A lower resolution or a shorter video runs faster.', '这段视频使用了省显存方式,所以比平时慢。降低分辨率或缩短时长会更快。'), "fv-note"));
warn();
panel.title = (unified
? text("Unified memory: device capacity. Process RAM is not total GPU memory, ", "统一内存为设备总量;进程内存不代表 GPU 内存总占用,")
diff --git a/web/generation_progress.js b/web/generation_progress.js
index c9d163d..37dd3c7 100644
--- a/web/generation_progress.js
+++ b/web/generation_progress.js
@@ -86,9 +86,11 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
recovery.setAttribute('role', 'status');
const silence = el('div', 'fv-generation-silence'); silence.hidden = true;
const notice = el('p', 'fv-generation-note fv-generation-notice'); notice.hidden = true;
+ const lowMemory = el('p', 'fv-generation-note fv-generation-memory'); lowMemory.hidden = true;
+ lowMemory.setAttribute('role', 'status');
notice.setAttribute('role', 'status');
const trims = new Map();
- element.append(heading, track, detail, times, silence, recovery, notice, note);
+ element.append(heading, track, detail, times, silence, recovery, lowMemory, notice, note);
let state = {}, overall = {}, started = 0, sampledAt = 0, overallAt = 0, timer = null;
let shownFraction = null;
// The visible percentage counts toward its value with the bar instead of
@@ -278,6 +280,13 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
stopCount(); countShown = null;
recovery.hidden = true; recovery.textContent = '';
trims.clear(); notice.hidden = true; notice.textContent = '';
+ lowMemory.hidden = true; lowMemory.textContent = '';
+ }
+ if (message.low_memory && typeof message.low_memory === 'object') {
+ // Stays for the whole request: the slower steps are expected, not a stall.
+ lowMemory.textContent = t('This GPU has little free memory, so this video uses the low-memory mode. It is slower than usual but will finish. A lower resolution or a shorter video runs faster.',
+ '显存较少,本次使用省显存方式生成,会比平时慢,但能完成。降低分辨率或缩短时长会更快。');
+ lowMemory.hidden = false;
}
if (message.reference_trimmed && typeof message.reference_trimmed === 'object') {
const row = message.reference_trimmed;
@@ -369,6 +378,7 @@ export function createGenerationProgress(t, now = () => Date.now(), {compact = f
function hide() {
element.hidden = true; recovery.hidden = true; recovery.textContent = '';
trims.clear(); notice.hidden = true; notice.textContent = '';
+ lowMemory.hidden = true; lowMemory.textContent = '';
if (timer !== null) clearInterval(timer); timer = null; state = {}; overall = {}; shownFraction = null;
stopCount(); countShown = null;
}
diff --git a/web/studio.js b/web/studio.js
index f4a512f..1b9e103 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -487,7 +487,8 @@ export function openStudio(node) {
try { await node.freevideoUpscaleResult(saved); await syncQueue(); }
catch (error) { status.dataset.error = 'true'; status.textContent = error.message; throw error; }
};
- output.append(status, reuseRow, trimNote, links, stats, budget, progress.report, prewarm);
+ const memoryNote = el('div', t('This video used the low-memory mode for this GPU, so it took longer than usual. A lower resolution or a shorter video runs faster.', '这段视频使用了省显存方式,所以比平时慢。降低分辨率或缩短时长会更快。'), 'fv-note'); memoryNote.hidden = true;
+ output.append(status, reuseRow, trimNote, memoryNote, links, stats, budget, progress.report, prewarm);
const failure = createErrorPanel(t); output.append(failure.element);
// With the picture, the result's actions and numbers form one block, centred below the header.
output.append(el('div', null, 'fv-preview-end'));
@@ -506,6 +507,7 @@ export function openStudio(node) {
reuseRow.hidden = !r.result_cache_hit;
const trims = Array.isArray(r.reference_trims) ? r.reference_trims : [];
trimNote.textContent = trims.map(row => referenceTrimText(row, t)).join('\n'); trimNote.hidden = !trims.length;
+ memoryNote.hidden = !r.low_memory || !!r.result_cache_hit;
regenerate.disabled = false; regenerate.textContent = t('Regenerate', '重新生成');
const unified = r.memory_model === 'unified';
metricLabels[2].textContent = unified ? t('Unified memory', '统一内存总量') : t('VRAM peak', '显存峰值');