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.

Support community LoRAs with compact reusable adapters (#4)

Bowen Xue9651972f8d45
diff --git a/.github/workflows/install.yml b/.github/workflows/install.yml
index 61bcd8a..713a31b 100644
--- a/.github/workflows/install.yml
+++ b/.github/workflows/install.yml
@@ -202,6 +202,8 @@ jobs:
Run MiniMax H3 on your own GPU, with FreeVideo inside ComfyUI.
+ Now supports community LoRAs. [See comparisons](https://github.com/FlashML-org/FreeVideo/blob/main/docs/LORA.md).
+
1. [Download FreeVideo.exe](https://github.com/FlashML-org/FreeVideo/releases/download/windows-preview/FreeVideo.exe) and run it.
2. Select an existing ComfyUI folder or install a new one. Add existing model folders to reuse your files; missing models download automatically.
3. Click **Install & launch** to open the FreeVideo workspace in your browser.
@@ -212,6 +214,8 @@ jobs:
FreeVideo 让 MiniMax H3 在消费级显卡上本地运行,打开 ComfyUI 即可创作。
+ 支持社区 LoRA。[查看效果对比](https://github.com/FlashML-org/FreeVideo/blob/main/docs/LORA.zh-CN.md)。
+
1. [下载 FreeVideo.exe](https://github.com/FlashML-org/FreeVideo/releases/download/windows-preview/FreeVideo.exe) 并运行。
2. 选择已有的 ComfyUI 或安装新的 ComfyUI。可添加模型目录以复用文件,缺失的模型会自动下载。
3. 点击 **安装并启动**,浏览器中会打开 FreeVideo 创作面板。
diff --git a/MANIFEST.in b/MANIFEST.in
index e203af5..a83a934 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -14,6 +14,7 @@ include scripts/bootstrap_linux.sh scripts/build_windows.py scripts/windows_app.
include scripts/scan_windows_release.py
include scripts/build_launcher_notices.py
prune docs
+include docs/LORA.md docs/LORA.zh-CN.md
prune tests
prune benchmarks
prune distribution
diff --git a/README.md b/README.md
index bd1cd48..82ec408 100644
--- a/README.md
+++ b/README.md
@@ -22,6 +22,7 @@ FreeVideo is a local inference engine for running MiniMax H3 on consumer GPUs. B
- **Hardware-adaptive execution**: Chooses the FP8 compute path for each GPU architecture, either native FP8 or FP8 storage with BF16 compute, and automatically probes the available attention kernels.
- **Low-memory inference**: Weight streaming, asynchronous prefetching and chunked computation keep peak memory low, enabling inference with as little as 8 GB of VRAM and 16 GB of RAM.
- **Multimodal inputs**: Text prompts, first and last frames, and image, video and audio references.
+- **Community LoRAs**: Use MiniMax H3 LoRAs in your workflow. See [side-by-side examples](docs/LORA.md).
- **ComfyUI integration**: A dedicated creative workspace inside ComfyUI that supports two-pass sampling and batch generation and keeps a history of past creations. For finer control, switch to the node view to add LoRAs or customize the workflow.
- **One-click deployment**: The Windows launcher sets up ComfyUI, the runtime environment and the models, reuses existing models, and supports offline installation.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 3c6f378..402867a 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -22,6 +22,7 @@ FreeVideo 是在消费级显卡上运行 MiniMax H3 的本地推理引擎。它
- **硬件自适应**:针对不同显卡架构选择 FP8 计算路径(原生 FP8,或 FP8 存储配合 BF16 计算),并自动探测可用的注意力内核,无需手动配置。
- **低显存推理**:通过权重流式加载、异步预取与分块计算降低峰值显存,最低只需 8GB 显存和 16GB 内存。
- **多模态输入**:支持文本、首帧、尾帧,以及图像、视频、音频参考输入。
+- **社区 LoRA**:支持在工作流中使用 MiniMax H3 社区 LoRA。[查看效果对比](docs/LORA.zh-CN.md)。
- **ComfyUI 集成**:在 ComfyUI 中提供专门的创作面板,支持二次采样和批量生成,并可浏览历史作品;需要更精细的控制时,可切换到节点视图,接入 LoRA 或自定义工作流。
- **一键部署**:Windows 启动器自动完成 ComfyUI、运行环境与模型的部署,可复用已有模型,并支持离线安装。
diff --git a/docs/LORA.md b/docs/LORA.md
new file mode 100644
index 0000000..206a538
--- /dev/null
+++ b/docs/LORA.md
@@ -0,0 +1,23 @@
+# Community LoRAs
+
+English · [中文](LORA.zh-CN.md)
+
+FreeVideo supports community LoRAs for MiniMax H3. Each comparison uses the same prompt and seed.
+
+## [VHS](https://huggingface.co/KennethFal/vh5tape-vhs-lora-minimax-h3)
+
+| Without LoRA | With LoRA |
+| :---: | :---: |
+| https://github.com/user-attachments/assets/c32440e6-6fba-4685-bd47-3cdac3b5c63e | https://github.com/user-attachments/assets/83989e7a-0f4f-4e58-80f3-705d4fc3e392 |
+
+## [Looping Sketch Anime](https://huggingface.co/Inner-Reflections/MiniMax-H3-Looping-Sketch-Anime)
+
+| Without LoRA | With LoRA |
+| :---: | :---: |
+| https://github.com/user-attachments/assets/60982172-eb0e-4f30-a19d-7ffcbe5ff920 | https://github.com/user-attachments/assets/1bab08eb-8c1f-4ee7-a25c-960ac40a201b |
+
+## [Male POV](https://civitai.com/models/2966380/minimax-h3-male-pov)
+
+| Without LoRA | With LoRA |
+| :---: | :---: |
+| https://github.com/user-attachments/assets/163924ad-dd11-4b08-9b91-62c823b6c0a7 | https://github.com/user-attachments/assets/17d3374b-c3b3-409e-8da5-6a1415bb4acb |
diff --git a/docs/LORA.zh-CN.md b/docs/LORA.zh-CN.md
new file mode 100644
index 0000000..1ba382f
--- /dev/null
+++ b/docs/LORA.zh-CN.md
@@ -0,0 +1,23 @@
+# 社区 LoRA
+
+[English](LORA.md) · 中文
+
+FreeVideo 支持 MiniMax H3 社区 LoRA。每组对照使用相同的提示词和 seed。
+
+## [VHS 录像带](https://huggingface.co/KennethFal/vh5tape-vhs-lora-minimax-h3)
+
+| 无 LoRA | 有 LoRA |
+| :---: | :---: |
+| https://github.com/user-attachments/assets/c32440e6-6fba-4685-bd47-3cdac3b5c63e | https://github.com/user-attachments/assets/83989e7a-0f4f-4e58-80f3-705d4fc3e392 |
+
+## [手绘线稿动画](https://huggingface.co/Inner-Reflections/MiniMax-H3-Looping-Sketch-Anime)
+
+| 无 LoRA | 有 LoRA |
+| :---: | :---: |
+| https://github.com/user-attachments/assets/60982172-eb0e-4f30-a19d-7ffcbe5ff920 | https://github.com/user-attachments/assets/1bab08eb-8c1f-4ee7-a25c-960ac40a201b |
+
+## [Male POV 第一人称](https://civitai.com/models/2966380/minimax-h3-male-pov)
+
+| 无 LoRA | 有 LoRA |
+| :---: | :---: |
+| https://github.com/user-attachments/assets/163924ad-dd11-4b08-9b91-62c823b6c0a7 | https://github.com/user-attachments/assets/17d3374b-c3b3-409e-8da5-6a1415bb4acb |
diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py
index 134bb7e..f456676 100644
--- a/freevideo_engine/comfy_bridge.py
+++ b/freevideo_engine/comfy_bridge.py
@@ -368,7 +368,7 @@ def progress_message(event):
'conditioning_cache_hit': 'Reusing prompt cache', 'encoder_complete': 'Prompt ready',
'video_start': 'Loading video model',
'decode_resume': 'Reusing completed sampling · retrying video and audio decoding',
- 'lora_prepare_start': 'Preparing or reusing the LoRA FP8 variant',
+ 'lora_prepare_start': 'Loading LoRAs',
'resource_retry': 'Adjusting memory placement and retrying'}
if name == 'decode_phase':
return {'label': str(event.get('phase', 'Decoding video and audio')), 'timing_phase': 'decode'}
@@ -392,7 +392,7 @@ def progress_message(event):
label += ' · %s / %s blocks' % (event.get('done', 0), event['total'])
return {'label': label, 'timing_phase': 'load'}
if name == 'lora_prepare':
- return {'label': 'Preparing LoRA variant · %s / %s groups' % (event.get('done', '?'), event.get('total', '?')),
+ return {'label': 'Loading LoRAs · %s / %s' % (event.get('done', '?'), event.get('total', '?')),
'timing_phase': 'load'}
if name in labels:
phase = ('encoding' if name.startswith('encoding') or name.startswith('encoder_')
diff --git a/freevideo_engine/fp8_ops.py b/freevideo_engine/fp8_ops.py
index f14ef6b..af59251 100644
--- a/freevideo_engine/fp8_ops.py
+++ b/freevideo_engine/fp8_ops.py
@@ -6,6 +6,7 @@ import triton
import triton.language as tl
from src.models.ops import fp8_linear as official
+from .lora_online import apply as apply_lora, quantized as lora_quantized
@triton.jit
@@ -54,23 +55,25 @@ def row_scale(scale, rows):
def project_with_scale(module, value, scale=None):
if scale is None or not isinstance(module, official.Fp8Linear):
return module(value)
- return module.forward_quantized(*quantize_fixed_scale(value, scale), out_dtype=value.dtype)
+ return lora_quantized(module, value, *quantize_fixed_scale(value, scale))
def sliced_projection(module, value, channels, quantized=None):
from .weight_only import WeightOnlyLinear
if isinstance(module, WeightOnlyLinear):
- return module.project(value, channels)
+ return apply_lora(module, value, module.project(value, channels), channels)
if not isinstance(module, official.Fp8Linear):
- return torch.nn.functional.linear(value, module.weight[channels],
- None if module.bias is None else module.bias[channels])
+ result = torch.nn.functional.linear(value, module.weight[channels],
+ None if module.bias is None else module.bias[channels])
+ return apply_lora(module, value, result, channels)
quantized = official.quantize_activation(value) if quantized is None else quantized
x_fp8, scale = quantized
weight_scale = module.weight_scale if module.weight_scale.numel() == 1 else module.weight_scale[:, channels].contiguous()
from .fp8_gemm import scaled_mm
result = scaled_mm(x_fp8, module.weight_fp8[channels].t(), scale, weight_scale,
out_dtype=value.dtype, implementation=getattr(module, 'freevideo_fp8_gemm', 'torch'))
- return result if module.bias is None else result + module.bias[channels]
+ result = result if module.bias is None else result + module.bias[channels]
+ return apply_lora(module, value, result, channels)
def install_chunked_ff(module, chunk, recompute=False):
@@ -94,8 +97,17 @@ def install_chunked_ff(module, chunk, recompute=False):
if not official.per_tensor_gemm():
for start in range(0, len(rows), chunk):
section = slice(start, start + chunk)
- h = self.net[0].proj.forward_quantized(x_fp8[section], row_scale(x_scale, section), out_dtype=rows.dtype)
- output[section] = self.net[2].forward_quantized(*official.swiglu_quantize(h), out_dtype=rows.dtype)
+ h = lora_quantized(self.net[0].proj, rows[section], x_fp8[section], row_scale(x_scale, section))
+ quantized = official.swiglu_quantize(h)
+ result = self.net[2].forward_quantized(*quantized, out_dtype=rows.dtype)
+ if hasattr(self.net[2], '_freevideo_lora'):
+ tile = torch.empty((len(h), width), device=rows.device, dtype=rows.dtype)
+ maxima = torch.empty(len(h), device=rows.device, dtype=torch.float32)
+ official._swiglu_rowmax_kernel[(len(h),)](h, tile, maxima, width, BLOCK_K=2048, num_warps=16)
+ apply_lora(self.net[2], tile, result)
+ del tile, maxima
+ output[section] = result
+ del h, quantized, result
return output.reshape(shape)
try:
activation = None if recompute else torch.empty((len(rows), width), device=rows.device, dtype=rows.dtype)
@@ -108,7 +120,7 @@ def install_chunked_ff(module, chunk, recompute=False):
maxima = torch.empty(len(rows), device=rows.device, dtype=torch.float32)
for start in range(0, len(rows), chunk):
section = slice(start, min(start + chunk, len(rows)))
- h = self.net[0].proj.forward_quantized(x_fp8[section], x_scale, out_dtype=rows.dtype)
+ h = lora_quantized(self.net[0].proj, rows[section], x_fp8[section], x_scale)
tile = torch.empty((len(h), width), device=rows.device, dtype=rows.dtype) if recompute else activation[section]
official._swiglu_rowmax_kernel[(len(h),)](h, tile, maxima[section], width, BLOCK_K=2048, num_warps=16)
del h, tile
@@ -119,14 +131,14 @@ def install_chunked_ff(module, chunk, recompute=False):
for start in range(0, len(rows), chunk):
section = slice(start, min(start + chunk, len(rows)))
if recompute:
- h = self.net[0].proj.forward_quantized(x_fp8[section], x_scale, out_dtype=rows.dtype)
+ h = lora_quantized(self.net[0].proj, rows[section], x_fp8[section], x_scale)
tile = torch.empty((len(h), width), device=rows.device, dtype=rows.dtype)
unused_maxima = torch.empty(len(h), device=rows.device, dtype=torch.float32)
official._swiglu_rowmax_kernel[(len(h),)](h, tile, unused_maxima, width, BLOCK_K=2048, num_warps=16)
del h, unused_maxima
else:
tile = activation[section]
- output[section] = self.net[2].forward_quantized(*quantize_fixed_scale(tile, scale), out_dtype=rows.dtype)
+ output[section] = lora_quantized(self.net[2], tile, *quantize_fixed_scale(tile, scale))
del tile
return output.reshape(shape)
diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py
index f524a3c..48d989e 100644
--- a/freevideo_engine/generate.py
+++ b/freevideo_engine/generate.py
@@ -151,6 +151,10 @@ def automatic_profile(args, canvas, *, stage, evidence, descriptor=None, environ
('vram_gib', 'ram_gib', 'attention', 'gpu_reserve_gib', 'ram_reserve_gib')}
options.update(available_backends=available_backends(hardware, probe_missing=False), canvas=canvas,
demonstrated_ram_bytes=demonstrated_local_ram(hardware, args, canvas))
+ if getattr(args, '_lora_max_block_bytes', 0):
+ options['lora_max_block_bytes'] = args._lora_max_block_bytes
+ if getattr(args, '_lora_root_bytes', 0):
+ options['lora_root_bytes'] = args._lora_root_bytes
if encoding_stage:
options['stage'] = 'encoding'
try:
@@ -334,7 +338,8 @@ def _run(args):
if active_loras:
lora_request = artifacts / 'lora-request.json'
lora_result = artifacts / 'lora-result.json'
- save(lora_request, {'cache': str(args.cache.resolve()), 'adapters': active_loras, 'result': str(lora_result)})
+ save(lora_request, {'cache': str(args.cache.resolve()), 'adapters': active_loras, 'result': str(lora_result),
+ 'mode': 'online' if profile['engine'].get('head_chunk') and profile['engine'].get('inference_kernels') else 'fused'})
lora_env = dict(os.environ, PYTHONPATH=str(repo), CUDA_VISIBLE_DEVICES='', PYTHONUNBUFFERED='1')
lora_env[LOCK_ENV] = str(descriptor)
print(json.dumps({'event': 'lora_prepare_start'}), flush=True)
@@ -344,6 +349,11 @@ def _run(args):
prepared = json.loads(lora_result.read_text(encoding='utf-8'))
args.cache = Path(prepared['cache'])
report['lora'] = prepared['report']
+ args._lora_max_block_bytes = prepared['report'].get('max_block_bytes', 0)
+ args._lora_root_bytes = prepared['report'].get('root_bytes', 0)
+ if args._lora_max_block_bytes or args._lora_root_bytes:
+ profile.setdefault('policy', {})['lora_max_block_bytes'] = args._lora_max_block_bytes
+ profile['policy']['lora_root_bytes'] = args._lora_root_bytes
resource_identity = local_identity(hardware, args.cache)
history = ResourceHistory(history_path())
history.recover_pending()
diff --git a/freevideo_engine/lora_cache.py b/freevideo_engine/lora_cache.py
index f5a970c..0485339 100644
--- a/freevideo_engine/lora_cache.py
+++ b/freevideo_engine/lora_cache.py
@@ -31,6 +31,11 @@ def _targets(name):
while any(name.startswith(prefix) for prefix in prefixes):
prefix = next(prefix for prefix in prefixes if name.startswith(prefix))
name = name[len(prefix):]
+ # Community H3 trainers also export Kohya-style flattened module names.
+ # Only the known H3 block grammar is expanded; underscores inside qkv_proj
+ # and out_proj are meaningful and must not become dots.
+ name = re.sub(r'^lora_unet_blocks_(\d+)_(attn|mlp)_(out_proj|qkv_proj|fc1|fc2)(?=\.|$)',
+ r'blocks.\1.\2.\3', name)
name = re.sub(r'^blocks\.', 'transformer_blocks.', name)
name = name.replace('token_refiner.blocks.', 'token_refiner.refiner_blocks.')
name = name.replace('final_layer.adaln_proj.linear', 'norm_out.linear')
@@ -335,7 +340,9 @@ def main():
args = parser.parse_args()
request = json.loads(args.request.read_text(encoding='utf-8'))
torch.set_num_threads(8)
- output, report = prepare(request['cache'], request['adapters'])
+ from .lora_online_cache import prepare as prepare_online
+ output, report = (prepare if request.get('mode') == 'fused' else prepare_online)(
+ request['cache'], request['adapters'])
save(request['result'], {'cache': str(output), 'report': report})
diff --git a/freevideo_engine/lora_kernels.py b/freevideo_engine/lora_kernels.py
new file mode 100644
index 0000000..d9f8337
--- /dev/null
+++ b/freevideo_engine/lora_kernels.py
@@ -0,0 +1,28 @@
+"""LoRA up projection and addition without a second full output matrix."""
+import triton
+import triton.language as tl
+
+
+def _up_add(Z, B, Y, M: tl.constexpr, N: tl.constexpr, R: tl.constexpr,
+ SCALE: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BR: tl.constexpr):
+ m = tl.program_id(0) * BM + tl.arange(0, BM)
+ n = tl.program_id(1) * BN + tl.arange(0, BN)
+ r = tl.arange(0, BR)
+ z = tl.load(Z + m[:, None] * R + r[None, :],
+ (m[:, None] < M) & (r[None, :] < R), other=0.)
+ b = tl.load(B + n[None, :] * R + r[:, None],
+ (n[None, :] < N) & (r[:, None] < R), other=0.)
+ delta = tl.dot(z, b).to(Y.dtype.element_ty).to(tl.float32)
+ old = tl.load(Y + m[:, None] * N + n[None, :],
+ (m[:, None] < M) & (n[None, :] < N), other=0.).to(tl.float32)
+ tl.store(Y + m[:, None] * N + n[None, :], old + SCALE * delta,
+ (m[:, None] < M) & (n[None, :] < N))
+
+
+def up_add(z, b, output, scale):
+ m, n = output.shape
+ _up_add[(triton.cdiv(m, 32), triton.cdiv(n, 128))](
+ z, b, output, m, n, z.shape[1], scale, 32, 128,
+ max(32, triton.next_power_of_2(z.shape[1])), num_warps=4)
+ return output
diff --git a/freevideo_engine/lora_online.py b/freevideo_engine/lora_online.py
new file mode 100644
index 0000000..6a74b16
--- /dev/null
+++ b/freevideo_engine/lora_online.py
@@ -0,0 +1,56 @@
+"""Independent low-rank branches whose buffers follow the layer offloader."""
+import types
+
+import torch
+import torch.nn.functional as F
+
+
+def attach_block(block, index, cache, manifest, load, device='cpu'):
+ spec = manifest.get('online_lora', {}).get('blocks', {}).get(str(index))
+ if not spec:
+ return
+ values = load(cache / spec['file'])
+ prefix = f'transformer_blocks.{index}.' if index != 'root' else ''
+ for name, patches in spec['modules'].items():
+ module = block.get_submodule(name.removeprefix(prefix))
+ branches = torch.nn.ModuleList()
+ for number, patch in enumerate(patches):
+ factor = torch.nn.Module()
+ key = name + '._freevideo_lora.' + str(number)
+ factor.register_buffer('a', values.pop(key + '.a').to(device=device))
+ factor.register_buffer('b', values.pop(key + '.b').to(device=device))
+ factor.scale = patch['scale']
+ branches.append(factor)
+ module.add_module('_freevideo_lora', branches)
+ original = module.forward
+ def forward(self, value, old=original):
+ return apply(self, value, old(value))
+ module.forward = types.MethodType(forward, module)
+ if values:
+ raise ValueError('Unbound LoRA tensors')
+
+
+def apply(module, raw, output, channels=None):
+ branches = getattr(module, '_freevideo_lora', None)
+ if branches is None:
+ return output
+ rows = raw.reshape(-1, raw.shape[-1])
+ target = output.reshape(-1, output.shape[-1])
+ if not target.is_contiguous():
+ raise ValueError('LoRA projection output must be contiguous')
+ for branch in branches:
+ b = branch.b if channels is None else branch.b[channels].contiguous()
+ # Bound workspace independently of the video/reference token count.
+ for start in range(0, len(rows), 512):
+ z = F.linear(rows[start:start + 512], branch.a)
+ result = target[start:start + 512]
+ if z.is_cuda and z.dtype in (torch.bfloat16, torch.float16) and z.shape[1] <= 256:
+ from .lora_kernels import up_add
+ up_add(z, b, result, branch.scale)
+ else:
+ result.add_(F.linear(z, b), alpha=branch.scale)
+ return output
+
+
+def quantized(module, raw, xq, xs):
+ return apply(module, raw, module.forward_quantized(xq, xs, out_dtype=raw.dtype))
diff --git a/freevideo_engine/lora_online_cache.py b/freevideo_engine/lora_online_cache.py
new file mode 100644
index 0000000..296b3b0
--- /dev/null
+++ b/freevideo_engine/lora_online_cache.py
@@ -0,0 +1,143 @@
+"""Prepare small, streamable adapter factors beside unchanged FP8 weights."""
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import time
+
+import torch
+from safetensors.torch import save_file
+
+from .lora_cache import _targets, index_adapter, prepare as prepare_fused
+from .media_request import digest, verify_files
+from .monitoring import save
+from .storage import fingerprint
+from .tensor_io import open_tensors
+
+
+def _supported(adapters, linears):
+ for adapter in adapters:
+ with open_tensors(adapter['path']) as source:
+ for key in source.keys():
+ name = re.sub(r'\.(?:lora_[AB]\.weight|lora_(?:down|up)\.weight|alpha)$',
+ '', key.replace('.default.', '.'))
+ for target, _, _ in _targets(name):
+ if target not in linears and '.attn.' in target:
+ target = target.replace('.attn.', '.attn.orig.', 1)
+ if target not in linears or not target.startswith(('transformer_blocks.', 'token_refiner.refiner_blocks.')):
+ return False
+ return True
+
+
+def prepare(cache, adapters, output_root=None):
+ cache = Path(cache).resolve()
+ adapters = [row for row in adapters if row['strength'] != 0]
+ if not adapters:
+ return cache, dict(enabled=False)
+ verify_files({'loras': adapters})
+ manifest = json.loads((cache / 'manifest.json').read_text(encoding='utf-8'))
+ if manifest.get('online_lora'):
+ raise ValueError('Select the original model when changing the LoRA combination')
+ if manifest.get('precision') != 'fp8' or not _supported(adapters, manifest.get('linears', {})):
+ # Full-difference, bias and modulation patches retain the existing
+ # exact preparation path. Never silently omit an unsupported patch.
+ path, report = prepare_fused(cache, adapters, output_root)
+ return path, dict(report, mode='fused', reason='Adapter includes non-linear or modulation patches')
+ identity = dict(source_manifest_sha256=digest(cache / 'manifest.json'),
+ implementation_sha256=digest(__file__), index_sha256=digest(Path(__file__).with_name('lora_cache.py')),
+ adapters=[{k: v for k, v in row.items() if k != 'path'} for row in adapters],
+ arithmetic='FP8 base plus independent BF16 low-rank branches')
+ key = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()
+ output = Path(output_root or cache.parent) / ('vdn-online-lora-' + key[:24])
+ marker = output / 'manifest.json'
+ if marker.is_file():
+ saved = json.loads(marker.read_text(encoding='utf-8'))
+ if saved.get('lora_identity') != identity:
+ raise ValueError('Adapter cache identity mismatch')
+ refreshed = False
+ for group in saved['groups']:
+ path = output / group['file']
+ stamp = fingerprint(path)
+ if stamp != saved['lora_file_stamps'].get(group['file']):
+ if digest(path) != group['sha256']:
+ raise ValueError('Adapter cache changed: ' + str(path))
+ saved['lora_file_stamps'][group['file']] = stamp
+ refreshed = True
+ if refreshed:
+ # 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)
+ 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 = {}
+ for adapter in adapters:
+ for patch in index_adapter(adapter, targets):
+ block = (patch['target'].split('.')[1] if patch['target'].startswith('transformer_blocks.') else 'root')
+ groups.setdefault(block, []).append(patch)
+ output.mkdir(parents=True, exist_ok=True)
+ started = time.perf_counter()
+ records, specs, block_bytes = [], {}, {}
+ for block, patches in sorted(groups.items()):
+ values, modules = {}, {}
+ for patch in patches:
+ name = patch['target']
+ branches = modules.setdefault(name, [])
+ prefix = name + '._freevideo_lora.' + str(len(branches))
+ dtype = getattr(torch, manifest['linears'][name].get('input_dtype', 'bfloat16'))
+ with open_tensors(patch['file']) as source:
+ a = source.get_tensor(patch['A']).to(dtype=dtype).clone()
+ b = source.get_tensor(patch['B'])
+ if patch['split'] is not None:
+ b = b.chunk(3, dim=0)[patch['split']]
+ if patch['swap']:
+ b = torch.cat(b.chunk(2, dim=0)[::-1], dim=0)
+ b = b.to(dtype=dtype).contiguous().clone()
+ if not bool(torch.isfinite(a).all() and torch.isfinite(b).all()):
+ raise ValueError('LoRA contains nonfinite or overflowing factors')
+ values[prefix + '.a'], values[prefix + '.b'] = a, b
+ branches.append(dict(scale=patch['scale'], rank=a.shape[0]))
+ label = f'{int(block):02d}' if block != 'root' else 'root'
+ relative = f'lora/{label}.safetensors'
+ destination = output / relative
+ destination.parent.mkdir(exist_ok=True)
+ temporary = destination.with_suffix('.partial')
+ save_file(values, temporary)
+ temporary.replace(destination)
+ block_bytes[str(block)] = sum(t.numel() * t.element_size() for t in values.values())
+ records.append(dict(group=f'lora/{label}', file=relative,
+ bytes=destination.stat().st_size, sha256=digest(destination)))
+ specs[str(block)] = dict(file=relative, modules=modules)
+ del values, a, b
+ print(json.dumps(dict(event='lora_prepare', done=len(records), total=len(groups))), flush=True)
+ from .export_slim import share
+ for group in manifest['groups']:
+ source, destination = cache / group['file'], output / group['file']
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ if source.stat().st_size != group['bytes']:
+ raise ValueError('Prepared source group is incomplete')
+ if destination.exists():
+ if not os.path.samefile(source, destination):
+ raise ValueError('Adapter base weights changed: ' + str(destination))
+ else:
+ try:
+ os.link(source, destination)
+ except OSError as error:
+ raise RuntimeError('Store LoRA preparation beside the model on a volume supporting hardlinks') from error
+ for table in manifest.get('adaln_tables', []):
+ for row in table['files']:
+ share(cache / row['file'], output / row['file'], row['sha256'])
+ verify_files({'loras': adapters})
+ root_bytes = block_bytes.get('root', 0)
+ summary = dict(targets=sum(len(spec['modules']) for spec in specs.values()),
+ adapter_count=len(adapters), factor_bytes=sum(block_bytes.values()),
+ root_bytes=root_bytes,
+ max_block_bytes=max((v for k, v in block_bytes.items() if k != 'root'), default=0))
+ online = dict(version=1, blocks=specs, block_bytes=block_bytes, summary=summary)
+ records = list(manifest['groups']) + records
+ 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/'))))
+ return output, dict(enabled=True, mode='online', cache_hit=False,
+ prepare_seconds=time.perf_counter() - started, **summary)
diff --git a/freevideo_engine/policy.py b/freevideo_engine/policy.py
index 18b0af8..f1e7f6c 100644
--- a/freevideo_engine/policy.py
+++ b/freevideo_engine/policy.py
@@ -374,6 +374,8 @@ class Policy:
evidence: str
notes: list[str]
capacity_trial: bool = False
+ lora_max_block_bytes: int = 0
+ lora_root_bytes: int = 0
def to_dict(self):
return asdict(self)
@@ -429,10 +431,22 @@ def decoder_workspace(canvas=None):
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'):
+ demonstrated_ram_bytes=None, allow_capacity_trial=False, stage='generation',
+ lora_max_block_bytes=0, lora_root_bytes=0):
from .geometry import geometry
if stage not in ('encoding', 'generation'):
raise ValueError('Resource planning stage must be encoding or generation')
+ if type(lora_max_block_bytes) is not int or lora_max_block_bytes < 0:
+ raise ValueError('LoRA block bytes must be a nonnegative integer')
+ if type(lora_root_bytes) is not int or lora_root_bytes < 0:
+ raise ValueError('LoRA root bytes must be a nonnegative integer')
+ if stage == 'encoding':
+ lora_max_block_bytes = lora_root_bytes = 0
+ block_bytes = BLOCK_BYTES + lora_max_block_bytes
+ # Two transfer slots plus bounded raw-SwiGLU/LoRA workspace. Resident and
+ # retained-host blocks below use the enlarged per-block storage as well.
+ lora_workspace = (128 * 2**20 + 2 * lora_max_block_bytes + lora_root_bytes
+ if lora_max_block_bytes or lora_root_bytes else 0)
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')):
@@ -454,6 +468,8 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
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'
+ request_gpu_budget = gpu_budget
+ gpu_budget -= lora_workspace
# 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
@@ -513,7 +529,8 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# whose margin was measured.
if not desktop and gpu_reserve_gib is None and free_gpu < 10 * GiB and gpu_budget < residual_need:
reserve_gpu = MIN_GPU_RESERVE_GIB
- gpu_budget = free_gpu - int(reserve_gpu * GiB)
+ request_gpu_budget = free_gpu - int(reserve_gpu * GiB)
+ gpu_budget = request_gpu_budget - lora_workspace
# The encoding phase already has a measured host floor. Do not discard a
# preloaded encoder because the later video stage needs a larger minimum;
# automatic_profile replans generation after conditioning has been saved.
@@ -775,12 +792,12 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# weight traffic is 6.78 s of 878 s sampling, and block 45 on mapped
# 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)))
+ resident = max(0, min(RESIDENT_VRAM_CEILING, int((gpu_budget - reserve) / block_bytes)))
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.
resident = max(0, min(RESIDENT_VRAM_CEILING,
- int((gpu_budget - activation_bytes(head, effective_tokens)) / BLOCK_BYTES)))
+ int((gpu_budget - activation_bytes(head, effective_tokens)) / block_bytes)))
# Placement alone is numerically neutral. Scale the activation allowance
# with the actual token count before spending memory on resident weights.
# The small staging path is anchored to the complete 243-frame Ada run;
@@ -812,13 +829,13 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# Saving a transfer slot must not turn fully retained host weights
# into per-step disk reads. Compare both placements, including the
# full FF workspace, before spending that slot.
- with_slot = min(resident, max(0, int((gpu_budget - windows_workspace) / BLOCK_BYTES)))
- without_slot = min(resident, max(0, int((gpu_budget - windows_workspace + BLOCK_BYTES) / BLOCK_BYTES)))
- host_need = (50 - with_slot) * BLOCK_BYTES + int(2.5 * GiB)
- if host_need > ram_budget >= (50 - without_slot) * BLOCK_BYTES + int(2.5 * GiB):
+ with_slot = min(resident, max(0, int((gpu_budget - windows_workspace) / block_bytes)))
+ without_slot = min(resident, max(0, int((gpu_budget - windows_workspace + BLOCK_BYTES) / block_bytes)))
+ host_need = (50 - with_slot) * block_bytes + int(2.5 * GiB)
+ if host_need > ram_budget >= (50 - without_slot) * block_bytes + int(2.5 * GiB):
prefetch = False
windows_workspace -= BLOCK_BYTES
- resident = min(resident, max(0, int((gpu_budget - windows_workspace) / BLOCK_BYTES)))
+ resident = min(resident, max(0, int((gpu_budget - windows_workspace) / block_bytes)))
# Do not enable FF recomputation merely to retain all host mappings.
# Native 5060 Ti measurements show that doing so makes the same layer
# 18% slower. Reopening an unpinned layer can hit the OS file cache and
@@ -849,7 +866,7 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
head, resident, prefetch = 4, 0, False
cpu_outputs = residual_offload = True
pin = max(0, min(22_000_000_000, retention_budget - HOST_WEIGHT_HEADROOM)) / 1e9
- pin = min(pin, (50 - resident) * BLOCK_BYTES / 1e9)
+ pin = min(pin, (50 - resident) * block_bytes / 1e9)
if small:
# Only locking every offloaded layer removes the offloader's own
# staging buffers, so a partial pin pays full memory for both: a
@@ -892,10 +909,10 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
# A card too small for what RAM asks still streams from disk; the retained
# subset below is what bounds that case.
host_room = retention_budget - host_activation - 2 * GiB
- ram_wants = max(0, 50 - max(0, int(host_room // BLOCK_BYTES)))
+ ram_wants = max(0, 50 - max(0, int(host_room // block_bytes)))
if not small:
resident = min(resident, max(RESIDENT_TARGET, ram_wants))
- streamed_weights = (50 - resident) * BLOCK_BYTES + host_activation + 2 * GiB > retention_budget
+ streamed_weights = (50 - resident) * block_bytes + host_activation + 2 * GiB > retention_budget
if streamed_weights:
# When the remaining weights exceed RAM, a bounded retained subset
# prevents rereading those bytes every step. This addresses disk I/O,
@@ -913,8 +930,8 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
cpu_outputs=cpu_outputs, canvas=canvas)
if ram_budget >= 8 * GiB else HOST_WEIGHT_HEADROOM)
host_headroom += residual_host
- pin = max(0, min((50 - resident) * BLOCK_BYTES, retention_budget - host_headroom)) / 1e9
- if small and not streamed_weights and pin * 1e9 < (50 - resident) * BLOCK_BYTES:
+ pin = max(0, min((50 - resident) * block_bytes, retention_budget - host_headroom)) / 1e9
+ if small and not streamed_weights and pin * 1e9 < (50 - resident) * block_bytes:
# All or nothing only when the weights already sit in RAM. On a
# disk-backed request the partial pin is not a transfer optimisation
# at all -- it is the bounded retained subset that stops those bytes
@@ -1010,6 +1027,10 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
(original_reserve_gpu, reserve_gpu, free_gpu / GiB, residual_need / GiB))
# The transformer is released before decode. Full-GPU VAE decode measured
# below 14 GiB on SM120; keep additional margin for other devices/backends.
+ if lora_workspace:
+ notes.append('Online LoRA reserves %d bytes per block plus %d bytes for transfer slots and bounded workspace.'
+ % (lora_max_block_bytes, lora_workspace))
+ gpu_budget = request_gpu_budget
decoder_offload = gpu_budget < 20 * GiB
if reference_rows:
notes.append('Reference conditioning adds %d packed rows; activation placement scales with total rows. This is a starting estimate, not a verified reference-capacity result.' % reference_rows)
@@ -1059,4 +1080,5 @@ def choose(hardware: Hardware, *, vram_gib=None, ram_gib=None, attention='auto',
resident_blocks=vae_resident,
linear_compute_cache=decoder_linear_cache),
'Architecture-specific candidate; validate this exact policy on the target GPU.', notes,
- capacity_trial=capacity_trial)
+ capacity_trial=capacity_trial, lora_max_block_bytes=lora_max_block_bytes,
+ lora_root_bytes=lora_root_bytes)
diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.py
index 53c3522..a8f568e 100644
--- a/freevideo_engine/runtime.py
+++ b/freevideo_engine/runtime.py
@@ -102,6 +102,13 @@ class Engine:
self.refiner_released = False
started = time.perf_counter()
manifest = json.loads((self.cache / 'manifest.json').read_text(encoding='utf-8'))
+ online_lora = manifest.get('online_lora', {})
+ self.online_lora_root = online_lora.get('blocks', {}).get('root', {}).get('file')
+ if online_lora:
+ if not head_chunk or not inference_kernels:
+ raise ValueError('Online LoRA requires bounded attention; select the automatic generation profile')
+ ff_chunk = ff_chunk or 2048
+ lora_paths = [self.cache / spec['file'] for spec in online_lora.get('blocks', {}).values()]
from .adaln_assets import SLIM_FORMAT, validate_catalog, restore_projections
portable_adaln = manifest.get('format') == SLIM_FORMAT
if portable_adaln:
@@ -153,7 +160,7 @@ class Engine:
streamed_paths += [self.cache / f'adaln/{index:02d}.safetensors'
for index in range(resident_blocks, len(model.transformer_blocks))]
if streamed_prefixes:
- streamed_source = SafetensorLayers(streamed_paths, streamed_prefixes)
+ streamed_source = SafetensorLayers(streamed_paths + lora_paths, streamed_prefixes)
self.stream_weight_source = streamed_source
# Only source-backed placeholders may remain empty between
# refinement requests; pinned groups keep their own storage.
@@ -192,6 +199,10 @@ class Engine:
if result.unexpected_keys or any(not key.startswith('transformer_blocks.') for key in result.missing_keys):
raise ValueError('Unexpected root weight keys')
del root_weights
+ if online_lora:
+ from .lora_online import attach_block
+ attach_block(model, 'root', self.cache, manifest, _load_safetensors,
+ device='cpu' if offload_refiner else 'cuda')
if streamed_source is not None and streamed_refiner_count:
# Refiner weights live in root.safetensors and otherwise remain a
# second large CPU allocation until LayerOffloader is constructed.
@@ -246,6 +257,9 @@ class Engine:
if result.unexpected_keys or any(not key.startswith('adaln_proj.step_') for key in result.missing_keys):
raise ValueError(f'Incomplete block {index}: {result}')
del weights
+ if online_lora:
+ from .lora_online import attach_block
+ attach_block(block, index, self.cache, manifest, _load_safetensors)
if not adaln_cache:
# ``weights.update(adaln)`` leaves the source dictionary alive
# until the next iteration. Drop it before replacing this
@@ -328,7 +342,7 @@ class Engine:
paths += [self.cache / f'blocks/{index:02d}.safetensors' for index in range(resident_blocks, len(model.transformer_blocks))]
if not adaln_cache:
paths += [self.cache / f'adaln/{index:02d}.safetensors' for index in range(resident_blocks, len(model.transformer_blocks))]
- self.stream_weight_source = SafetensorLayers(paths, prefixes)
+ self.stream_weight_source = SafetensorLayers(paths + lora_paths, prefixes)
self.host_preload_seconds = 0.
self.pinned_model_bytes = prepared_pins['logical']
self.pinned_host_allocated_bytes = 0
@@ -387,6 +401,7 @@ class Engine:
if fa4_path is not None else None),
'precision': precision, 'fp8_linears': len(manifest.get('linears', {})),
'linear_compute': linear_compute,
+ 'online_lora': online_lora.get('summary'),
'fp8_gemm': actual_fp8_gemm,
'fp8_scale_granularity': manifest.get('scale_granularity'),
'fp8_ff_recompute': fp8_ff_recompute,
@@ -678,6 +693,9 @@ class Engine:
prefix = 'token_refiner.refiner_blocks.'
values = {name.removeprefix(prefix): tensor for name, tensor in
_load_safetensors(self.cache / 'root.safetensors').items() if name.startswith(prefix)}
+ if self.online_lora_root:
+ values.update({name.removeprefix(prefix): tensor for name, tensor in
+ _load_safetensors(self.cache / self.online_lora_root).items()})
refiner.load_state_dict(values, strict=True, assign=True)
del values
# load_prompt returns [tokens, width]; generate_latents adds the batch
diff --git a/freevideo_engine/two_pass.py b/freevideo_engine/two_pass.py
index 2a32850..779f4bb 100644
--- a/freevideo_engine/two_pass.py
+++ b/freevideo_engine/two_pass.py
@@ -173,5 +173,7 @@ def first_pass_policy(profile, canvas, sampling_plan):
backend = profile['engine']['attention']
selected = choose(hardware, attention=backend, available_backends=set(backend.split('/')),
gpu_reserve_gib=gpu_reserve / GiB, ram_reserve_gib=ram_reserve / GiB,
+ lora_max_block_bytes=policy.get('lora_max_block_bytes', 0),
+ lora_root_bytes=policy.get('lora_root_bytes', 0),
canvas=first, allow_capacity_trial=policy.get('capacity_trial', False)).legacy_profile()
return dict(geometry=first, profile=selected)