From 6738bff892aad6ce001a59c0a42b13e964205ab6 Mon Sep 17 00:00:00 2001 From: Hardwell99 <3022256519@qq.com> Date: Fri, 30 Oct 2026 15:38:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=80=A7=E8=83=BD=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 性能优化20261030-submit --- device.py | 6 + inference.py | 321 +++++++++++++++++++++++++++++++++++++++++++-------- loader.py | 23 +++- pipeline.py | 21 ++-- 4 files changed, 310 insertions(+), 61 deletions(-) diff --git a/device.py b/device.py index d1b10cd..5500a8f 100644 --- a/device.py +++ b/device.py @@ -30,6 +30,12 @@ import threading import torch +# cuDNN benchmark 模式:首次遇到某卷积形状时自动搜索最快算法,后续复用。 +# 对本项目意义:DiT / VAE 含大量 Conv2d,tile 尺寸在单次运行内固定, +# benchmark 缓存命中率高,可带来 5~15% 卷积加速。代价是首次推理多几秒预热。 +if torch.cuda.is_available(): + torch.backends.cudnn.benchmark = True + # 全局注册表:本项目创建的所有 ModelPatcher _PATCHERS: list["ModelPatcher"] = [] diff --git a/inference.py b/inference.py index a8a775e..9c938d1 100644 --- a/inference.py +++ b/inference.py @@ -1,11 +1,22 @@ # -*- coding: utf-8 -*- """ inference.py — VOSR2 推理契约:bicubic 预放大 → pad → encode → 一步去噪 → -decode → 色彩对齐 → 裁剪,支持 DiT/VAE 分块。 +decode → 色彩对齐 → 裁剪,支持 DiT/VAE 分块与批处理加速。 与 ComfyUI 版的唯一差异:comfy.utils.ProgressBar 换成 progress_cb 回调。 `forward_flexible`(models/lightningdit.py)断言方形输入——所有上游分块调用 裁出的都是 lt_size×lt_size 方块,非分块路径会先 pad 成方形再裁回,行为一致。 + +Phase 2 优化: +- DiT 内部分块批处理:将多个 DiT tile 组成 batch 一次 forward,减少 kernel launch +- TTP 外层分块批处理:将多个 TTP tile 组成 batch 一起处理,提高 GPU 利用率 +- 显存自适应批大小:根据可用 VRAM 自动调整 batch size + +OOM 自动降级策略(三层保护): +- Vision 层:DINOv2 特征提取 OOM 时逐步减半位置数 +- DiT 层:去噪 forward OOM 时逐步减半 tile 位置数,最终回退到逐项处理 +- TTP 层:整块推理 OOM 时逐步减半 TTP batch size +- 所有层级均持久化降级后的 batch size,后续批次直接使用缩小值,避免重复探测 """ import gc import logging @@ -20,18 +31,77 @@ AE_FACTOR = 8 DIT_PATCH_SIZE = 2 PAD_MULTIPLE = AE_FACTOR * DIT_PATCH_SIZE # 16 +# 批处理默认上限 +DIT_BATCH_MAX = 8 +TTP_BATCH_MAX = 4 + def _oom_safe(fn): """执行 fn();遇 CUDA OOM 时清理缓存后重试一次(碎片导致的假性 OOM 多数可恢复)。""" try: return fn() except torch.OutOfMemoryError: - gc.collect() - torch.cuda.empty_cache() - torch.cuda.ipc_collect() + _clear_cuda() return fn() +def _clear_cuda(): + """强制释放 CUDA 缓存(OOM 后的标准清理动作)。""" + gc.collect() + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + + +def _shrink_batch(current: int) -> int | None: + """逐次减半 batch size;已为 1 时返回 None 表示无法再缩。""" + if current <= 1: + return None + return max(1, current // 2) + + +def _auto_dit_batch_size(lt_size: int, lc: int, device) -> int: + """根据可用显存估算 DiT tile 批处理大小。 + + DiT 激活内存与 tile 面积、模型深度成正比。本函数用保守估算确保不 OOM; + 实际运行时若遇 OOM 会自动缩小到逐块处理。 + """ + if not torch.cuda.is_available() or device.type != "cuda": + return 1 + try: + free_mb = torch.cuda.mem_get_info(device)[0] / 1024 / 1024 + except Exception: + return 2 + # 保守估算:lt_size=32 时每个 DiT tile 激活约 300 MB,按面积缩放 + per_tile_mb = min(1024, max(100, int((lt_size / 32) ** 2 * 300))) + budget_mb = free_mb * 0.4 + max_batch = max(1, int(budget_mb / per_tile_mb)) + batch_size = min(max_batch, DIT_BATCH_MAX) + if batch_size > 1: + logging.info(f"DiT 批处理大小:{batch_size}(可用显存 {free_mb:.0f} MB)") + return batch_size + + +def _auto_ttp_batch_size(per_tile_pixels: int, device) -> int: + """根据可用显存估算 TTP tile 批处理大小。 + + TTP 批处理影响 VAE 激活内存(与像素面积成正比)。保守估算,确保不 OOM。 + """ + if not torch.cuda.is_available() or device.type != "cuda": + return 1 + try: + free_mb = torch.cuda.mem_get_info(device)[0] / 1024 / 1024 + except Exception: + return 1 + # VAE 激活内存估算:1024px tile 约 200 MB,按面积缩放 + per_tile_mb = min(2048, max(200, int((per_tile_pixels / 1024) ** 2 * 200))) + budget_mb = free_mb * 0.25 + max_batch = max(1, int(budget_mb / per_tile_mb)) + batch_size = min(max_batch, TTP_BATCH_MAX) + if batch_size > 1: + logging.info(f"TTP 批处理大小:{batch_size}(可用显存 {free_mb:.0f} MB)") + return batch_size + + def _pad_to_multiple(x: torch.Tensor, multiple: int): _, _, h, w = x.shape pad_h = (multiple - h % multiple) % multiple @@ -86,8 +156,14 @@ def _count_dit_tiles(h: int, w: int, tile_size: int, tile_overlap: int) -> int: def _run_tiled_single(model, resized01: torch.Tensor, seed: int, tile_size: int, tile_overlap: int, vae_tile_size: int, vae_tile_overlap: int, tick=None) -> torch.Tensor: - """Latent-space tiled DiT inference for one image (B=1). Ported from VOSR's tiled_latent_inference.""" - _, _, h, w = resized01.shape + """Latent-space tiled DiT inference. Supports B>=1 for TTP batching. + + Phase 2 优化: + - 支持 B>1 输入(TTP 批处理) + - DiT 内部分块批处理(减少 kernel launch 开销) + - Vision features 批处理提取(减少 DINOv2 forward 次数) + """ + B, _, h, w = resized01.shape padded01 = _pad_to_multiple(resized01, PAD_MULTIPLE) padded_pm1 = padded01 * 2.0 - 1.0 @@ -100,48 +176,159 @@ def _run_tiled_single(model, resized01: torch.Tensor, seed: int, tile_size: int, venc_fea = model.vision_features(padded01) model.vision_patcher.offload() del padded01, padded_pm1 - noise = _generate_noise(lq_sq.shape[1:], seed, lq_sq.device, lq_sq.dtype).unsqueeze(0) + noise_single = _generate_noise(lq_sq.shape[1:], seed, lq_sq.device, lq_sq.dtype) + noise = noise_single.unsqueeze(0).expand(B, -1, -1, -1) sr_latent = model.denoise_one_step(lq_sq, noise, venc_fea)[:, :, :lh, :lw] - del venc_fea - model.dit_patcher.offload() # 解码前卸载 DiT(fp16 ~2.6G),给 VAE 激活让路 + del venc_fea, noise_single, noise + model.dit_patcher.offload() if tick is not None: - tick() + for _ in range(B): + tick() else: h_pos = _make_tile_grid(lh, lt_size, lt_overlap) w_pos = _make_tile_grid(lw, lt_size, lt_overlap) g_weight = _gaussian_weights(lt_size, lt_size, lc, lq_latent.device) + all_positions = [(hi, wi) for hi in h_pos for wi in w_pos] + n_dit_tiles = len(all_positions) + + # 批处理提取 vision features(减少 DINOv2 forward 次数,OOM 时逐步减半) tile_venc = {} - for hi in h_pos: - for wi in w_pos: - ph_s, pw_s = hi * AE_FACTOR, wi * AE_FACTOR - ph_e = min((hi + lt_size) * AE_FACTOR, padded01.shape[2]) - pw_e = min((wi + lt_size) * AE_FACTOR, padded01.shape[3]) - tile_venc[(hi, wi)] = model.vision_features(padded01[:, :, ph_s:ph_e, pw_s:pw_e]) + venc_batch_size = min(n_dit_tiles, DIT_BATCH_MAX) + v_offset = 0 + while v_offset < n_dit_tiles: + v_end = min(v_offset + venc_batch_size, n_dit_tiles) + batch_pos = all_positions[v_offset:v_end] + n_vpos = len(batch_pos) + + # OOM 降级:逐步减半 vision batch 位置数,每次重建裁剪 + cur_vpos = n_vpos + while cur_vpos >= 1: + use_pos = batch_pos[:cur_vpos] + crops = [] + for b_idx in range(B): + for hi, wi in use_pos: + ph_s, pw_s = hi * AE_FACTOR, wi * AE_FACTOR + ph_e = min((hi + lt_size) * AE_FACTOR, padded01.shape[2]) + pw_e = min((wi + lt_size) * AE_FACTOR, padded01.shape[3]) + crops.append(padded01[b_idx:b_idx + 1, :, ph_s:ph_e, pw_s:pw_e]) + crop_batch = torch.cat(crops, dim=0) + del crops + try: + venc_result = model.vision_features(crop_batch) + del crop_batch + break + except torch.OutOfMemoryError: + del crop_batch + _clear_cuda() + new_vpos = _shrink_batch(cur_vpos) + if new_vpos is None: + raise + logging.warning(f"Vision OOM: {cur_vpos} → {new_vpos} 个位置") + cur_vpos = new_vpos + + # venc_result[0] shape: (B * cur_vpos, N_vision, D) + venc_flat = venc_result[0] + idx = 0 + for b_idx in range(B): + for p in range(cur_vpos): + hi, wi = batch_pos[p] + if (b_idx, hi, wi) not in tile_venc: + tile_venc[(b_idx, hi, wi)] = [venc_flat[idx:idx + 1]] + idx += 1 + del venc_flat, venc_result + + # 持久化降级 + venc_batch_size = max(1, cur_vpos) + v_offset += cur_vpos - # 视觉特征已全部提取,卸载视觉编码器并释放放大的原图张量 model.vision_patcher.offload() del padded01, padded_pm1 - noise = _generate_noise(lq_latent.shape[1:], seed, lq_latent.device, lq_latent.dtype).unsqueeze(0) - z = noise + noise_single = _generate_noise(lq_latent.shape[1:], seed, lq_latent.device, lq_latent.dtype) + z = noise_single.unsqueeze(0).expand(B, -1, -1, -1) u_acc = torch.zeros_like(lq_latent) w_acc = torch.zeros_like(lq_latent) - for hi in h_pos: - for wi in w_pos: - he, we = hi + lt_size, wi + lt_size - inp = torch.cat([lq_latent[:, :, hi:he, wi:we], z[:, :, hi:he, wi:we]], dim=1) - u_tile = _oom_safe(lambda: model.dit_velocity(inp, 1.0, 0.0, tile_venc[(hi, wi)])) - u_acc[:, :, hi:he, wi:we] += u_tile * g_weight - w_acc[:, :, hi:he, wi:we] += g_weight - del inp, u_tile - if tick is not None: + + # 批处理 DiT tile 推理(OOM 时逐步减半位置数,成功值用于后续批次) + dit_batch_size = _auto_dit_batch_size(lt_size, lc, lq_latent.device) + batch_offset = 0 + while batch_offset < n_dit_tiles: + batch_end = min(batch_offset + dit_batch_size, n_dit_tiles) + batch_pos = all_positions[batch_offset:batch_end] + actual_batch = len(batch_pos) + + # OOM 降级:逐步减半 tile 位置数,每次重建 batch 输入 + cur_pos = actual_batch + u_batch = None + while cur_pos >= 1: + use_pos = batch_pos[:cur_pos] + inp_list, venc_list = [], [] + for b_idx in range(B): + for hi, wi in use_pos: + he, we = hi + lt_size, wi + lt_size + inp_list.append(torch.cat([lq_latent[b_idx:b_idx + 1, :, hi:he, wi:we], + z[b_idx:b_idx + 1, :, hi:he, wi:we]], dim=1)) + venc_list.append(tile_venc[(b_idx, hi, wi)][0]) + inp_b = torch.cat(inp_list, dim=0) + venc_b = [torch.cat(venc_list, dim=0)] + del inp_list, venc_list + try: + u_batch = _oom_safe(lambda: model.dit_velocity(inp_b, 1.0, 0.0, venc_b)) + del inp_b, venc_b + break + except torch.OutOfMemoryError: + del inp_b, venc_b + _clear_cuda() + new_pos = _shrink_batch(cur_pos) + if new_pos is None: + break + logging.warning(f"DiT OOM: {cur_pos} → {new_pos} 个位置") + cur_pos = new_pos + + if u_batch is None: + # cur_pos=1 仍 OOM → 逐项处理 + logging.warning(f"DiT 逐项处理({actual_batch * B} 项)") + u_parts = [] + for b in range(B): + for p in range(actual_batch): + hi, wi = batch_pos[p] + he, we = hi + lt_size, wi + lt_size + inp_i = torch.cat([lq_latent[b:b + 1, :, hi:he, wi:we], + z[b:b + 1, :, hi:he, wi:we]], dim=1) + venc_i = [tile_venc[(b, hi, wi)][0]] + u_parts.append(_oom_safe( + lambda ii=inp_i, vi=venc_i: model.dit_velocity(ii, 1.0, 0.0, vi) + )) + del inp_i, venc_i + u_batch = torch.cat(u_parts, dim=0) + del u_parts + cur_pos = actual_batch + + # 拆分结果并累加 + cur_items = cur_pos * B + idx = 0 + for b_idx in range(B): + for p in range(cur_pos): + hi, wi = batch_pos[p] + he, we = hi + lt_size, wi + lt_size + u_acc[b_idx:b_idx + 1, :, hi:he, wi:we] += u_batch[idx:idx + 1] * g_weight + w_acc[b_idx:b_idx + 1, :, hi:he, wi:we] += g_weight + idx += 1 + + del u_batch + batch_offset += cur_pos + if tick is not None: + for _ in range(cur_items): tick() + # 持久化降级:后续批次使用缩小后的位置数 + dit_batch_size = max(1, cur_pos) + sr_latent = z - u_acc / w_acc - del u_acc, w_acc, tile_venc, z, noise - model.dit_patcher.offload() # 解码前卸载 DiT(fp16 ~2.6G),给 VAE 激活让路 + del u_acc, w_acc, tile_venc, z, noise_single + model.dit_patcher.offload() decoded_pm1 = _oom_safe( lambda: model.decode_tiled(sr_latent, latents_mean, latents_std, vae_tile_size, vae_tile_overlap) @@ -177,6 +364,9 @@ def run_vosr2( P6:色彩对齐已移出本函数,由调用方在 assemble 之后对整图统一做,故此处 不再接受 color_alignment,也不逐块保留 bicubic 参考。 + + Phase 2 优化:TTP 外层分块批处理 —— 多个 TTP tile 组成 batch 一起送入 + _run_tiled_single,减少模型调度开销,提高 GPU 利用率。 """ if full_upscaled_bhwc01.shape[-1] != 3: raise ValueError(f"VOSR2Upscale expects a 3-channel RGB IMAGE, got {full_upscaled_bhwc01.shape[-1]} channels.") @@ -216,31 +406,60 @@ def run_vosr2( if progress_cb: progress_cb(done[0], total_tiles) + # TTP 批处理大小(OOM 时逐步减半并持久化) + ttp_batch_size = _auto_ttp_batch_size(max(per_h, per_w), device) + items = [] - for i, (l, u, r, d) in enumerate(positions): - sl = full_upscaled_bhwc01[:, u * upscale:d * upscale, l * upscale:r * upscale, :] - x = sl.movedim(-1, 1).to(device) # BCHW [0,1] - del sl - # 统一 seed:全部块共用同一个 seed,不做块序号偏移(原始设计意图: - # 同 seed + 同 shape 保证跨图可比对、给定输入与 seed 输出完全可复现)。 - item_pm1 = _run_tiled_single( - model, x, seed, tile_size, tile_overlap, - vae_tile_size, vae_tile_overlap, tick=tick, - ).cpu() - del x # 释放该块的 GPU 放大图 - item01 = (item_pm1.clamp(-1.0, 1.0) + 1.0) / 2.0 - del item_pm1 - items.append(item01) - del item01 - # 块间只做"按需"清理:empty_cache() 是同步且昂贵的驱动操作, - # 逐块无条件调用会让 GPU 利用率出现周期性锯齿。只有真的快没显存 - # 时才付这个代价(vram_pressure 用设备级空闲显存判断, - # 同一张卡上还有别的进程时也能正确识别压力)。 + batch_start = 0 + while batch_start < n: + batch_end = min(batch_start + ttp_batch_size, n) + batch_positions = positions[batch_start:batch_end] + B_batch = len(batch_positions) + + # 收集该 batch 的所有 TTP tile + tile_list = [] + for l, u, r, d in batch_positions: + sl = full_upscaled_bhwc01[:, u * upscale:d * upscale, l * upscale:r * upscale, :] + tile_list.append(sl.movedim(-1, 1)) + del sl + x_batch = torch.cat(tile_list, dim=0).to(device) + del tile_list + + # OOM 降级:逐步减半 TTP batch size + cur_b = B_batch + result_batch = None + while cur_b >= 1: + try: + result_batch = _run_tiled_single( + model, x_batch[:cur_b], seed, tile_size, tile_overlap, + vae_tile_size, vae_tile_overlap, tick=tick, + ).cpu() + break + except torch.OutOfMemoryError: + _clear_cuda() + new_b = _shrink_batch(cur_b) + if new_b is None: + raise + logging.warning(f"TTP OOM: batch={cur_b} → {new_b}") + cur_b = new_b + + # 拆分 batch 结果 + for b_idx in range(cur_b): + item_pm1 = result_batch[b_idx:b_idx + 1] + item01 = (item_pm1.clamp(-1.0, 1.0) + 1.0) / 2.0 + del item_pm1 + items.append(item01) + del item01 + del result_batch, x_batch + + # 持久化降级:后续批次使用缩小后的 batch size + ttp_batch_size = max(1, cur_b) + batch_start += cur_b + if _vram_pressure(): gc.collect() torch.cuda.empty_cache() - # 循环外的统一回收:块循环里已用 del 精确释放了引用,这里只补一次 - # 循环引用(dict/list 环)的回收,并把碎片化的小块内存还给驱动。 + gc.collect() if _vram_pressure(): torch.cuda.empty_cache() diff --git a/loader.py b/loader.py index c26bc93..4f04710 100644 --- a/loader.py +++ b/loader.py @@ -16,7 +16,9 @@ bundle 布局(与 ComfyUI 版一致): - 提供 load_vosr2():模型按 (bundle, dtype) 进程级缓存,只加载一次; unload_models() 可把模型搬回内存,下次运行自动搬回 GPU(不重新读盘) """ +import contextlib import json +import logging import re from pathlib import Path @@ -165,7 +167,12 @@ class VOSR2Model: mean = torch.tensor((0.485, 0.456, 0.406), device=device, dtype=x.dtype).view(1, 3, 1, 1) std = torch.tensor((0.229, 0.224, 0.225), device=device, dtype=x.dtype).view(1, 3, 1, 1) x = (x.to(device) - mean) / std - feats = model.forward_intermediate_layer(x.to(model.pos_embed.dtype), self.vision_layer_index) + compute_dtype = x.dtype + ctx = (torch.amp.autocast(device_type="cuda", dtype=compute_dtype) + if device.type == "cuda" and compute_dtype != torch.float32 + else contextlib.nullcontext()) + with ctx: + feats = model.forward_intermediate_layer(x.to(model.pos_embed.dtype), self.vision_layer_index) return [feats] def encode(self, x_bchw_neg1_1: torch.Tensor): @@ -198,7 +205,11 @@ class VOSR2Model: b = inp.shape[0] t_cur_t = torch.full((b,), t_cur, device=device, dtype=compute_dtype) t_next_t = torch.full((b,), t_next, device=device, dtype=compute_dtype) - return model.forward_flexible(inp, t_cur_t, t_next_t, venc_fea) + ctx = (torch.amp.autocast(device_type="cuda", dtype=compute_dtype) + if device.type == "cuda" and compute_dtype != torch.float32 + else contextlib.nullcontext()) + with ctx: + return model.forward_flexible(inp, t_cur_t, t_next_t, venc_fea) def denoise_one_step(self, lq_latent: torch.Tensor, noise: torch.Tensor, venc_fea: list) -> torch.Tensor: """One Euler flow-matching update from t=1 to t=0 (VOSR2 is a one-step model).""" @@ -286,6 +297,14 @@ def load_vosr2(model_name: str, dtype: str) -> VOSR2Model: for p in dit.parameters(): p.requires_grad_(False) + # torch.compile:算子融合 + 内核自动调优,对 36 层 DiT 预期 15~30% 推理加速。 + # 首次调用有编译开销(约 30~60 秒),后续复用缓存。失败时静默回退到原始模型。 + try: + dit = torch.compile(dit, mode="default", dynamic=False) + logging.info("DiT 模型已通过 torch.compile 编译(mode=default)") + except Exception as exc: + logging.warning(f"torch.compile 失败,回退到原始模型:{exc}") + vae = AutoencoderKLQwenImage2D.from_pretrained(str(vae_dir)) vae = vae.eval().float() # Qwen VAE 固定 fp32 for p in vae.parameters(): diff --git a/pipeline.py b/pipeline.py index 0e3236b..8482d61 100644 --- a/pipeline.py +++ b/pipeline.py @@ -72,21 +72,26 @@ def compute_grid(width: int, height: int, feather: int): """块数与块内容尺寸(在【原图】上切块)。 块内容尺寸(**不含羽化**)反解列/行数,使其尽量落在 [TILE_MIN, TILE_MAX]; - 相邻块的重叠量 = `feather`(由 tile_batch 的 overlap 参数保证),不计入块尺寸 - —— 这样 feather 只控制接缝羽化宽度、不再撑大块尺寸(旧实现把 feather 加进块 - 尺寸,导致 f=128 时块越界、有效羽化被整数除法反向截断)。 + 相邻块的重叠量 = `feather`(由 tile_batch 的 overlap 参数保证)。 - 原图宽高均 ≤ TILE_MAX 时整图直喂(cols=rows=1,块=原图尺寸)。 + _pick_cols 与 _content_for 均以 `width + feather` / `height + feather` 为 + 输入,保证 _layout 的 step = block - feather 恰好让 cols 块覆盖整条边: + (cols-1) * (block - feather) + block >= width + 旧实现只给 _content_for 的 width 加了 feather,但 _pick_cols 仍用裸 width + 选列数,导致列数与块尺寸不匹配(1440px + f=64 → 选 2 列 → block=720 → + step=656 → 实际需要 3 列)。 + + 原图宽高均 <= TILE_MAX 时整图直喂(cols=rows=1,块=原图尺寸)。 返回的 cols/rows 与 tile_batch 经 `_layout(..., overlap=feather)` 算出的真实 块数一致(两者共用同一套几何),规划面板显示的块数不再偏大(旧 P3)。 """ if width <= TILE_MAX and height <= TILE_MAX: return 1, 1, width, height - cols_content = _pick_cols(width, TILE_MIN, TILE_MAX) - rows_content = _pick_cols(height, TILE_MIN, TILE_MAX) - block_w = _content_for(width, cols_content) - block_h = _content_for(height, rows_content) + cols_content = _pick_cols(width + feather, TILE_MIN, TILE_MAX) + rows_content = _pick_cols(height + feather, TILE_MIN, TILE_MAX) + block_w = _content_for(width + feather, cols_content) + block_h = _content_for(height + feather, rows_content) # 真实块数:与 tile_batch 共用 _layout(overlap=feather),面板与推理严格一致 ncols, _ = ttp._layout(width, block_w, feather) nrows, _ = ttp._layout(height, block_h, feather)