Author SHA1 Message Date
giteaone 6738bff892 性能优化
性能优化20261030-submit
2026-10-30 15:38:33 +08:00
giteaone 064e3d2132 优化
优化
2026-10-27 14:43:23 +08:00
5 changed files with 740 additions and 320 deletions
+33
View File
@@ -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"] = []
@@ -135,6 +141,33 @@ def offload_registered_models() -> int:
return moved
def vram_pressure(free_ratio: float = 0.15) -> bool:
"""当前显存是否处于紧张状态(空闲显存占比低于 free_ratio)。
供推理循环做**条件式**缓存清理判断:`torch.cuda.empty_cache()` 是同步且
昂贵的操作(要向驱动归还所有未用显存并重置分配器),逐块无条件调用会让
GPU 利用率出现周期性锯齿。只在真的快没显存时才付这个代价。
注意用的是**设备级**空闲显存(`mem_get_info`),而非本进程占用量 ——
同一张卡上可能还有别的进程,它同样会造成 OOM,只看自己的占用会漏判。
Args:
free_ratio: 空闲显存占比阈值,低于此值即判定为有压力。
Returns:
是否有显存压力。无 CUDA 设备时恒为 False。
"""
if not torch.cuda.is_available():
return False
try:
free, total = torch.cuda.mem_get_info()
except Exception: # noqa: BLE001 —— 探测失败一律按"无压力"处理,绝不因此中断业务
return False
if total <= 0:
return False
return (free / total) < free_ratio
def release_vram(unload_models: bool = True) -> dict:
"""显存释放:卸载模型到内存 + 清空 CUDA 缓存。由管线收尾(成功/失败/中断)调用。
+307 -123
View File
@@ -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
@@ -13,25 +24,84 @@ import logging
import torch
import torch.nn.functional as F
from .color import apply_color_alignment
from .device import vram_pressure as _vram_pressure
from .tiled_vae import _gaussian_weights, _make_tile_grid
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
@@ -57,16 +127,6 @@ def _generate_noise(shape, seed: int, device, dtype) -> torch.Tensor:
return noise.to(device=device, dtype=dtype)
def _generate_noise_batch(shape_per_item, seed: int, batch_size: int, device, dtype) -> torch.Tensor:
"""整批共用同一个 seed —— 每项噪声逐元素相同。
`expand` 返回只读视图而非拷贝;后续它只被 `torch.cat` / 减法读取,从不原地写,
因此各 batch 项共享同一份底层存储是安全的(真要写就会踩到 view 语义,需要 clone)。
"""
noise = _generate_noise(shape_per_item, seed, device, dtype)
return noise.unsqueeze(0).expand(batch_size, *noise.shape)
def _tile_params(tile_size: int, tile_overlap: int, lh: int, lw: int):
"""Pixel tile size/overlap -> latent-space, aligned to the DiT patch size."""
lt_size = max((tile_size // AE_FACTOR // DIT_PATCH_SIZE) * DIT_PATCH_SIZE, DIT_PATCH_SIZE)
@@ -76,39 +136,6 @@ def _tile_params(tile_size: int, tile_overlap: int, lh: int, lw: int):
return lt_size, lt_overlap
def _resize_to_target(images_bhwc01: torch.Tensor, upscale: int, device) -> torch.Tensor:
x = images_bhwc01.movedim(-1, 1).to(device) # BCHW [0, 1]
_, _, h, w = x.shape
target_h, target_w = h * upscale, w * upscale
return F.interpolate(x, size=(target_h, target_w), mode="bicubic").clamp(0.0, 1.0)
def _run_untiled_batch(model, resized01: torch.Tensor, seed: int, vae_tile_size: int, vae_tile_overlap: int,
tick=None) -> torch.Tensor:
b, _, h, w = resized01.shape
padded01 = _pad_to_multiple(resized01, PAD_MULTIPLE)
padded01 = _pad_to_square(padded01)
padded_pm1 = padded01 * 2.0 - 1.0
lq_latent, latents_mean, latents_std = model.encode_tiled(padded_pm1, vae_tile_size, vae_tile_overlap)
venc_fea = model.vision_features(padded01)
model.vision_patcher.offload() # 视觉编码器用完即卸载,为 DiT/VAE 让路
noise = _generate_noise_batch(lq_latent.shape[1:], seed, b, lq_latent.device, lq_latent.dtype)
sr_latent = model.denoise_one_step(lq_latent, noise, venc_fea)
model.dit_patcher.offload() # DiT 用完即卸载(fp16 ~2.6G),VAE 解码是激活峰值大户
# 整图解码前的中断检查:tile_size=0 时 DiT 只有一次前向,这里是全流程唯一的
# 细粒度检查点。放在解码之前,中断可直接省掉最重、最容易 OOM 的全图 VAE 解码,
# 而不是把解码白跑完再退出。
if tick is not None:
tick()
decoded_pm1 = model.decode_tiled(sr_latent, latents_mean, latents_std, vae_tile_size, vae_tile_overlap)
return decoded_pm1[:, :, :h, :w]
def estimate_dit_tiles(h: int, w: int, tile_size: int, tile_overlap: int) -> int:
"""公开接口:预估一张 HxW(已放大像素)图像会被 DiT 内部切成多少块。tile_size=0 时为 1。"""
if not tile_size:
@@ -129,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
@@ -143,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)
@@ -194,10 +338,10 @@ def _run_tiled_single(model, resized01: torch.Tensor, seed: int, tile_size: int,
def run_vosr2(
model,
images_bhwc01: torch.Tensor,
full_upscaled_bhwc01: torch.Tensor,
positions,
upscale: int,
seed: int,
color_alignment: str,
tile_size: int,
tile_overlap: int,
vae_tile_size: int,
@@ -206,46 +350,55 @@ def run_vosr2(
) -> torch.Tensor:
"""progress_cb(done_tiles, total_tiles):DiT 分块粒度的进度回调。
seed 语义:**整张图、全部块共用同一个 seed,不做块序号偏移**。
噪声张量在每次 `_generate_noise` / `_generate_noise_batch` 里按传入的 seed
重新生成,同 seed + 同 shape ⇒ 噪声逐元素相同,因此:
`full_upscaled_bhwc01`:整图已做 `×upscale` 预放大的结果(BHWC float32,
[0,1]),由调用方(pipeline)一次性完成 —— 见 P4:整图放大一次,再按
`positions × upscale` 切片逐块处理,重叠区只放大一次且用整图上下文。
- 外层 TTP 切出的 N 块拿到完全相同的噪声起点;
- 块内 DiT 潜空间分块共用整块的那一张噪声(本来就是这样,见 _run_tiled_single);
- 换图 / 换块数不会让 seed 语义漂移,跨图可比对。
`positions`:tile_batch 返回的原图尺度位置列表,每块切片 = `full_upscaled
[u*upscale:d*upscale, l*upscale:r*upscale]`。
代价:相邻块若内容相近,会得到相同方向的随机纹理,块边界更容易看出规则重复。
外层接缝仍由 TTP 羽化(feather)负责掩盖,与内层 DiT 的高斯加权是两套机制。
seed 语义:**整张图、全部块共用同一个 seed,不做块序号偏移**(原始设计意图)。
同 seed + 同 shape ⇒ 噪声逐元素相同,给定相同输入与 seed,输出完全可复现、
跨图可比对。代价是相邻块内容相近时可能呈现相同方向的随机纹理,但这是为可比性
刻意保留的行为(P5 的「逐块派生 seed」方案已被否决,恢复统一 seed)。
P6:色彩对齐已移出本函数,由调用方在 assemble 之后对整图统一做,故此处
不再接受 color_alignment,也不逐块保留 bicubic 参考。
Phase 2 优化:TTP 外层分块批处理 —— 多个 TTP tile 组成 batch 一起送入
_run_tiled_single,减少模型调度开销,提高 GPU 利用率。
"""
if images_bhwc01.shape[-1] != 3:
raise ValueError(f"VOSR2Upscale expects a 3-channel RGB IMAGE, got {images_bhwc01.shape[-1]} channels.")
if full_upscaled_bhwc01.shape[-1] != 3:
raise ValueError(f"VOSR2Upscale expects a 3-channel RGB IMAGE, got {full_upscaled_bhwc01.shape[-1]} channels.")
if tile_size > 0 and tile_overlap >= tile_size:
raise ValueError(f"VOSR2Upscale: tile_overlap ({tile_overlap}) must be smaller than tile_size ({tile_size}).")
if vae_tile_size > 0 and vae_tile_overlap >= vae_tile_size:
raise ValueError(f"VOSR2Upscale: vae_tile_overlap ({vae_tile_overlap}) must be smaller than vae_tile_size ({vae_tile_size}).")
device = model.dit_patcher.load_device
b = images_bhwc01.shape[0]
h0, w0 = images_bhwc01.shape[1:3]
h, w = h0 * upscale, w0 * upscale # 放大后目标尺寸
n = len(positions)
# 每块放大后的尺寸(用首块位置推导;所有块内容尺寸一致)
l0, u0, r0, d0 = positions[0]
per_h = (d0 - u0) * upscale
per_w = (r0 - l0) * upscale
if tile_size == 0 and (h > 512 or w > 512):
if tile_size == 0 and (per_w > 512 or per_h > 512):
logging.warning(
f"VOSR2Upscale: target size {w}x{h} (after {upscale}x upscale) exceeds VOSR 2.0's "
f"VOSR2Upscale: block target size {per_w}x{per_h} (after {upscale}x upscale) exceeds VOSR 2.0's "
f"native 512px training resolution with tile_size=0 (DiT tiling disabled). Set "
f"tile_size > 0 (e.g. 512) or quality will likely degrade."
)
if vae_tile_size == 0 and (h > 1024 or w > 1024):
if vae_tile_size == 0 and (per_w > 1024 or per_h > 1024):
logging.warning(
f"VOSR2Upscale: target size {w}x{h} (after {upscale}x upscale) with vae_tile_size=0 "
f"(VAE tiling disabled) decodes the full image in one pass regardless of tile_size -- "
f"VOSR2Upscale: block target size {per_w}x{per_h} (after {upscale}x upscale) with vae_tile_size=0 "
f"(VAE tiling disabled) decodes the full block in one pass regardless of tile_size -- "
f"common CUDA OOM source. Set vae_tile_size > 0 (e.g. 1024) to bound peak VRAM."
)
# 进度/中断计数:tile_size>0 时按 DiT 分块逐块推进(tick 在每个分块边界
# 触发,管线借它做中断检查);tile_size=0 时 _run_untiled_batch 一次性吃掉
# 整批,只在整图解码前报一次,故总数记 1。
total_tiles = b * _count_dit_tiles(h, w, tile_size, tile_overlap) if tile_size > 0 else 1
# 进度/中断计数:每块按 DiT 内部分块逐块推进;tick 在每个分块边界触发,
# 管线借它做中断检查。
total_per_block = _count_dit_tiles(per_h, per_w, tile_size, tile_overlap) if tile_size > 0 else 1
total_tiles = n * total_per_block
done = [0]
def tick():
@@ -253,32 +406,63 @@ def run_vosr2(
if progress_cb:
progress_cb(done[0], total_tiles)
if tile_size > 0:
# 逐块放大 + 处理:任意时刻 GPU 上只有一块的放大图,而非整批
aligned_items = []
for i in range(b):
x = images_bhwc01[i:i + 1].movedim(-1, 1).to(device) # BCHW [0,1]
x = F.interpolate(x, size=(h, w), mode="bicubic").clamp(0.0, 1.0)
ref_cpu = x.cpu() # 供色彩对齐使用
item_pm1 = _run_tiled_single(
model, x, seed, tile_size, tile_overlap,
vae_tile_size, vae_tile_overlap, tick=tick,
).cpu()
del x # 释放该块的 GPU 放大图
# TTP 批处理大小(OOM 时逐步减半并持久化)
ttp_batch_size = _auto_ttp_batch_size(max(per_h, per_w), device)
items = []
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
aligned_items.append(apply_color_alignment(item01, ref_cpu, color_alignment))
del item01, ref_cpu
gc.collect()
torch.cuda.empty_cache() # 块间清理缓存碎片,降低长驻峰值
aligned01 = torch.cat(aligned_items, dim=0)
del aligned_items
else:
resized01 = _resize_to_target(images_bhwc01, upscale, device)
outputs_pm1 = _run_untiled_batch(
model, resized01, seed, vae_tile_size, vae_tile_overlap, tick=tick,
)
decoded01 = (outputs_pm1.clamp(-1.0, 1.0) + 1.0) / 2.0
aligned01 = apply_color_alignment(decoded01, resized01, color_alignment)
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()
gc.collect()
if _vram_pressure():
torch.cuda.empty_cache()
aligned01 = torch.cat(items, dim=0)
del items
return aligned01.movedim(1, -1)
+21 -2
View File
@@ -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():
+171 -56
View File
@@ -7,10 +7,12 @@ from pathlib import Path
from typing import Callable
import torch
import torch.nn.functional as F
from PIL import Image
from . import device as _device
from . import ttp
from .color import apply_color_alignment
from .inference import estimate_dit_tiles, run_vosr2
from .loader import load_vosr2
from .sharpen import cas_sharpen
@@ -19,10 +21,10 @@ PROJECT_DIR = Path(__file__).resolve().parent.parent
OUTPUT_DIR = PROJECT_DIR / "outputs"
# 工作流固定常量
ALIGN = 8 # 块尺寸向上对齐到 8 的倍数
TILE_MIN = 720 # 【分块尺寸】下限
TILE_MAX = 960 # 【分块尺寸】上限
MIN_LONG_SIDE = 1080 # 【输入下限】最长边不足此值时,等比例预放大后再进入流程
ALIGN = 16 # 块尺寸向上对齐到 16 的倍数(= inference.PAD_MULTIPLE)
TILE_MIN = 512 # 【分块尺寸】下限
TILE_MAX = 1024 # 【分块尺寸】上限
MIN_LONG_SIDE = 1024 # 【输入下限】最长边不足此值时,等比例预放大后再进入流程
ProgressCB = Callable[[float, str], None]
@@ -44,47 +46,89 @@ def _ceil_div(a: int, b: int) -> int:
return -(-a // b)
def _tile_size_for(total: int, cols: int, feather: int) -> int:
return ((_ceil_div(total, cols) + ALIGN - 1) // ALIGN) * ALIGN + feather
def _content_for(total: int, cols: int) -> int:
"""把 total 等分为 cols 列后,单列向上对齐到 ALIGN 的倍数(= 块内容尺寸,不含羽化)。"""
return ((_ceil_div(total, cols) + ALIGN - 1) // ALIGN) * ALIGN
def _pick_cols(total: int, feather: int, lo: int, hi: int) -> int:
hi_cols = max(1, _ceil_div(total, max(1, lo - feather)))
def _pick_cols(total: int, lo: int, hi: int) -> int:
"""选列数,使块内容尺寸尽量落在 [lo, hi];落不进区间时取离区间最近者。"""
hi_cols = max(1, _ceil_div(total, lo))
best_cols, best_dist = 1, None
for cols in range(1, hi_cols + 1):
tile = _tile_size_for(total, cols, feather)
if tile < lo:
dist = lo - tile
elif tile > hi:
dist = tile - hi
else:
content = _content_for(total, cols)
if lo <= content <= hi:
dist = 0
elif content < lo:
dist = lo - content
else:
dist = content - hi
if best_dist is None or dist < best_dist:
best_cols, best_dist = cols, dist
return best_cols
def compute_grid(width: int, height: int, feather: int):
"""块数与块宽/块高(在【原图】上切块)。
"""块数与块内容尺寸(在【原图】上切块)。
每块尺寸(含羽化)反解块数,使其尽量落在 [TILE_MIN, TILE_MAX],
即【分块尺寸】∈ [720, 960],切好后喂给 VOSR2。
原图宽高均 ≤ TILE_MAX 时整图直喂(cols=rows=1,块=原图尺寸,不加羽化)。
块内容尺寸(**不含羽化**)反解列/行数,使其尽量落在 [TILE_MIN, TILE_MAX];
相邻块的重叠量 = `feather`(由 tile_batch 的 overlap 参数保证)。
_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 = _pick_cols(width, feather, TILE_MIN, TILE_MAX)
rows = _pick_cols(height, feather, TILE_MIN, TILE_MAX)
block_w = _tile_size_for(width, cols, feather)
block_h = _tile_size_for(height, rows, feather)
return cols, rows, block_w, block_h
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)
return ncols, nrows, block_w, block_h
def image_size(image_path: str | Path) -> tuple[int, int]:
"""读图取尺寸(宽, 高),不加载模型、不推理。"""
image = load_image_bhwc(image_path)
_, height, width, _ = image.shape # BHWC
return width, height
"""读图取尺寸(宽, 高),不加载模型、不推理。
只读文件头(PIL 惰性解析 header,不解码像素)—— 本函数在 UI 每次改动
参数时都会被 plan_info 调用,全图像素解码在 4K 图上是几百毫秒的
同步阻塞,纯粹为了拿两个整数不值当。真正的像素解码留给
load_image_bhwc(推理时才调用)。
"""
with Image.open(image_path) as image:
return image.size
def cover_plan(src_w: int, src_h: int, dst_w: int, dst_h: int):
"""计算「等比放大到覆盖目标框 + 中心裁剪」所需的参数。
返回 (scale, scaled_w, scaled_h, crop_box),crop_box 为 PIL crop 的
(left, upper, right, lower)。
纯数学,不碰像素 —— plan_info 要在只读文件头的前提下算出同样的结果。
为什么是 cover 而不是普通 resize:普通 resize 强制把源图映射到目标框,
目标框宽高比与源图不一致时就产生各向异性缩放(内容被拉伸,圆变椭圆)。
cover 先按两轴中较大的比例等比放大(保证内容完全不变形),再裁掉多出来的
边,代价是丢掉少量边缘像素,换来几何比例 100% 保真。
"""
scale = max(dst_w / float(src_w), dst_h / float(src_h))
scaled_w = max(dst_w, int(round(src_w * scale)))
scaled_h = max(dst_h, int(round(src_h * scale)))
left = (scaled_w - dst_w) // 2
upper = (scaled_h - dst_h) // 2
return scale, scaled_w, scaled_h, (left, upper, left + dst_w, upper + dst_h)
def fit_min_long_side(width: int, height: int,
@@ -98,7 +142,12 @@ def fit_min_long_side(width: int, height: int,
enabled=False 时跳过预放大(实验性开关关闭),原尺寸直接进入后续环节。
返回 (新宽, 新高, 放大倍数);无需放大时倍数 = 1.0 且尺寸原样返回。
短边向上对齐到 ALIGN,与后续分块网格保持同一基准。
短边**不再向上对齐到 ALIGN**:对齐会把目标画布的宽高比改掉(源图 800×600
抬到 1080×816,画布比 4:3 窄了 0.735%),再用 resize 填进去就成了内容
拉伸。短边改为按源图宽高比等比换算,画布与源图严格同比例,resize 不再
产生任何形变。分块网格的对齐由 compute_grid → _tile_size_for 独立完成
(块尺寸永远是 ALIGN 的倍数),不依赖图像自身尺寸是否对齐。
"""
if not enabled:
return width, height, 1.0
@@ -106,9 +155,9 @@ def fit_min_long_side(width: int, height: int,
return width, height, 1.0
factor = min_long_side / float(max(width, height))
if width >= height: # 横图:宽为最长边
short = max(ALIGN, ((round(height * factor) + ALIGN - 1) // ALIGN) * ALIGN)
short = max(1, round(height * factor))
return min_long_side, short, factor
long_ = max(ALIGN, ((round(width * factor) + ALIGN - 1) // ALIGN) * ALIGN)
long_ = max(1, round(width * factor))
return long_, min_long_side, factor
@@ -135,6 +184,14 @@ def plan_info(
"""
src_w, src_h = image_size(image_path)
width, height, pre_scale = fit_min_long_side(src_w, src_h, min_long_side, pre_scale_enabled)
# 预放大的实际缩放参数:cover 语义(等比放大到覆盖目标框,再裁掉多余边)。
# 目标框与源图同比例时裁剪量为 0;若有 1~2px 取整差,也是裁边而非拉伸。
if pre_scale > 1.0:
cover_scale, cover_w, cover_h, cover_box = cover_plan(src_w, src_h, width, height)
pre_crop_x = cover_w - width
pre_crop_y = cover_h - height
else:
cover_scale, pre_crop_x, pre_crop_y = pre_scale, 0, 0
out_w, out_h = round(width * scale), round(height * scale)
# 分块在【处理尺寸】上进行:块尺寸 ∈ [720,960];图足够小时整图直喂
cols, rows, block_w, block_h = compute_grid(width, height, feather)
@@ -142,12 +199,13 @@ def plan_info(
dit_per_tile = estimate_dit_tiles(
block_h * vosr2_scale_index, block_w * vosr2_scale_index, tile_size, tile_overlap
)
# cols/rows 均为 1 时块尺寸必 ≥ 图尺寸(align8(边长)+羽化),ttp.tile_batch
# cols/rows 均为 1 时块尺寸必 ≥ 图尺寸(按 ALIGN 对齐 + 羽化),ttp.tile_batch
# 必然走整图直喂分支,故直接以 cols/rows 判定,不比对块尺寸。
return {
"width": width, "height": height,
"src_width": src_w, "src_height": src_h, "pre_scale": pre_scale,
"pre_scale_enabled": pre_scale_enabled, "min_long_side": min_long_side,
"cover_scale": cover_scale, "pre_crop_x": pre_crop_x, "pre_crop_y": pre_crop_y,
"scale": scale, "vosr2_scale": vosr2_scale_index,
"out_w": out_w, "out_h": out_h,
"cols": cols, "rows": rows,
@@ -158,16 +216,49 @@ def plan_info(
}
def _resize_bhwc(image: torch.Tensor, out_h: int, out_w: int) -> torch.Tensor:
"""BHWC 张量重采样到目标尺寸(Lanczos,质量优先)。"""
import numpy as np
def _bicubic_upscale(image_bhwc01: torch.Tensor, v: int) -> torch.Tensor:
"""整图做一次 bicubic 预放大到 v 倍(float32,无 uint8 往返)。
resample = getattr(Image, "Resampling", Image).LANCZOS
arr = image.squeeze(0).clamp(0, 1).numpy()
pil = Image.fromarray((arr * 255.0).round().astype("uint8"), mode="RGB")
pil = pil.resize((out_w, out_h), resample)
arr = np.asarray(pil, dtype=np.float32) / 255.0
return torch.from_numpy(arr).unsqueeze(0)
P4:替代逐块独立放大。整图放大后由 run_vosr2 按 positions×v 切片,
重叠区只被放大一次且使用整图上下文(逐块放大时块边缘因 F.interpolate
的零填充会产生边界伪影)。
"""
x = image_bhwc01.movedim(-1, 1).to(torch.float32) # (1,3,H,W)
h, w = x.shape[-2:]
if v == 1:
return image_bhwc01
out = F.interpolate(x, size=(h * v, w * v), mode="bicubic", align_corners=False).clamp(0.0, 1.0)
return out.movedim(1, -1)
def _resize_bhwc(image: torch.Tensor, out_h: int, out_w: int) -> torch.Tensor:
"""BHWC 张量重采样到目标尺寸(float32 bicubic,质量优先,无 uint8 往返)。"""
x = image.movedim(-1, 1).to(torch.float32) # (1,3,H,W)
if x.shape[-2:] == (out_h, out_w):
return image
out = F.interpolate(x, size=(out_h, out_w), mode="bicubic", align_corners=False).clamp(0.0, 1.0)
return out.movedim(1, -1)
def _resize_cover_bhwc(image: torch.Tensor, out_h: int, out_w: int) -> torch.Tensor:
"""等比放大到覆盖目标框,再中心裁剪(cover),不做任何拉伸。
与 _resize_bhwc 的区别:_resize_bhwc 是把源图硬拉到目标框(各向异性),
目标框宽高比与源图不一致时内容必然变形;本函数先按两轴较大的比例等比
放大(内容零形变),再裁掉多出来的边。
预放大走这条路径:目标框与源图同比例时裁剪量为 0,等价于普通 resize;
万一目标框与源图不同比例,也只会裁边而不会拉变形。
全程 float32(F.interpolate bicubic),替代旧实现的 PIL uint8 往返。
"""
x = image.movedim(-1, 1).to(torch.float32) # (1,3,H,W)
src_h, src_w = x.shape[-2:]
_, scaled_w, scaled_h, box = cover_plan(src_w, src_h, out_w, out_h)
up = F.interpolate(x, size=(scaled_h, scaled_w), mode="bicubic", align_corners=False).clamp(0.0, 1.0)
left, upper, right, lower = box
crop = up[:, :, upper:lower, left:right]
return crop.movedim(1, -1)
def _run_pipeline_impl(
@@ -248,8 +339,10 @@ def _run_pipeline_impl(
width, height, pre_scale = fit_min_long_side(width, height, min_long_side, pre_scale_enabled)
if pre_scale > 1.0:
report(0.03, f"原图 {src_w}×{src_h} 小于 {min_long_side},"
f"已预放大 ×{pre_scale:.3f} → {width}×{height}")
image = _resize_bhwc(image, height, width)
f"已等比放大 ×{pre_scale:.3f} → {width}×{height}")
# cover 路径:等比放大到覆盖目标框再裁掉多余边。目标框与源图同比例时
# 裁剪量为 0;若因取整出现 1~2px 的比例差,也是裁边而不是拉伸。
image = _resize_cover_bhwc(image, height, width)
elif not pre_scale_enabled:
report(0.03, f"按原尺寸 {width}×{height} 进入流程")
@@ -264,16 +357,28 @@ def _run_pipeline_impl(
report(0.05, f"分块规划:{cols}×{rows} 块,分块尺寸 {block_w}×{block_h} + 羽化{feather}")
# ---- 4. 分块(TTP_Image_Tile_Batch 47)---- #
# positions / grid 一并留用:拼装阶段直接复用这份真实切块坐标(×v),
# 不再另算一套网格(见第 7 步)。overlap=feather 使相邻块在原图上重叠 feather
# 像素(feather 仅作羽化宽度,不再撑大块尺寸)。
check_abort()
tiles, _positions, _orig, _grid = ttp.tile_batch(image, block_w, block_h)
tiles, positions, orig_size, grid = ttp.tile_batch(image, block_w, block_h, overlap=feather)
n_tiles = tiles.shape[0]
del tiles # 整图放大后按 positions 切片,原图切块张量不再需要
# ---- 5. 清显存(easy cleanGpuUsed 99)---- #
from .device import release_vram
release_vram(unload_models=False)
report(0.08, f"显存已清理,开始超分 {n_tiles} 个块(模型 ×{vosr2_scale_index},目标 ×{scale:g})…")
# ---- 6. VOSR2 一步超分(171/172),整批进入与工作流一致 ---- #
# ---- 6. VOSR2 一步超分(171/172)---- #
# P4:整图一次性 bicubic 预放大到 v 倍(CPU float32),随后按 positions×v 切片逐块
# 处理;重叠区只被放大一次、且使用整图上下文(逐块放大时块边缘因 F.interpolate
# 的零填充产生边界伪影,已消除)。放大结果另作为 P6 整图色彩对齐的参考。
check_abort()
v = vosr2_scale_index
whole_up = _bicubic_upscale(image, v)
del image # whole_up 已派生,原图可释放
model = load_vosr2(model_name, dtype)
def vosr_progress(done: int, total: int):
@@ -283,21 +388,29 @@ def _run_pipeline_impl(
on_tile(done, total)
upscaled = run_vosr2(
model, tiles, vosr2_scale_index, seed, color_alignment,
model, whole_up, positions, v, seed,
tile_size, tile_overlap, vae_tile_size, vae_tile_overlap,
progress_cb=vosr_progress,
) # BHWC,每块 (block_w×v, block_h×v)
# ---- 7. dummy 网格位置(198/199 + 128/129/200/201,模型尺度 v,画布 = 原图×v)---- #
v = vosr2_scale_index
dummy_w, dummy_h = width * v, height * v
dummy_tw, dummy_th = block_w * v, block_h * v
d_positions, d_original, d_grid = ttp.tile_positions(dummy_w, dummy_h, dummy_tw, dummy_th)
# ---- 8. 羽化拼装(TTP_Image_Assy 48,padding=羽化×v,节点 202)---- #
# ---- 7/8. 坐标统一 + 羽化拼装(TTP_Image_Assy 48,padding=羽化×v,节点 202)---- #
# 拼装坐标直接复用第 4 步 tile_batch 的**真实** positions(×v 换算到模型尺度),
# 不再在 v 尺度画布上另算一套网格。真实切块位置 ×v 是唯一自洽的坐标,
# 羽化混合区取到的必是同一段原图内容(feather 即真实重叠,单调可控)。
check_abort()
report(0.92, "VOSR2处理完成,最后拼接…")
assembled = ttp.assemble(upscaled, d_positions, d_original, d_grid, padding=feather * v)
s_positions = ttp.scale_positions(positions, v)
s_original = (orig_size[0] * v, orig_size[1] * v)
assembled = ttp.assemble(upscaled, s_positions, s_original, grid, padding=feather * v)
# P6:色彩对齐改为对整图做一次(参考整图 bicubic 放大结果 whole_up),跨块
# 色彩/亮度更一致,接缝处不再因各块独立对齐而割裂。逐块对齐已移出 run_vosr2。
if color_alignment != "none":
_a_bchw = assembled.movedim(-1, 1)
_ref_bchw = whole_up.movedim(-1, 1)
assembled = apply_color_alignment(_a_bchw, _ref_bchw, color_alignment).movedim(1, -1)
del _a_bchw, _ref_bchw
del whole_up
# ---- 8.5 重采样到目标输出尺寸(拼装在模型尺度 v=原图×v 上;scale=v 时已到位,跳过)---- #
cur_h, cur_w = assembled.shape[1], assembled.shape[2]
@@ -315,7 +428,9 @@ def _run_pipeline_impl(
# ---- 10. 保存(CR Image Output 112 → 本地 outputs/)---- #
# 命名:VOSR2_upscaled_x倍数_原始文件名_时间.png(倍数用 :g,小数如 1.5 正常显示)
day_dir = (output_dir or OUTPUT_DIR) / datetime.now().strftime("%Y%m%d")
# output_dir 容忍 str:类型标注写的是 Path,但传 str 时报错会发生在跑完整个
# 推理之后(白烧一次 GPU),这里提前归一化。
day_dir = Path(output_dir or OUTPUT_DIR) / datetime.now().strftime("%Y%m%d")
day_dir.mkdir(parents=True, exist_ok=True)
stem = Path(orig_name).stem if orig_name else "image"
stem = re.sub(r'[\\/:*?"<>|]', "_", stem).strip() or "image" # 过滤非法字符
@@ -461,8 +576,8 @@ def run_pipeline(
tile_overlap=tile_overlap,
vae_tile_size=vae_tile_size,
vae_tile_overlap=vae_tile_overlap,
sharpen_amount=sharpen_amount,
pre_scale_enabled=pre_scale_enabled,
sharpen_amount=sharpen_amount,
pre_scale_enabled=pre_scale_enabled,
min_long_side=min_long_side,
output_dir=output_dir,
orig_name=orig_name,
+208 -139
View File
@@ -1,60 +1,102 @@
# -*- coding: utf-8 -*-
"""
ttp.py — TTP_Image_Tile_Batch / TTP_Image_Assy 的独立移植。
ttp.py — TTP_Image_Tile_Batch / TTP_Image_Assy 的 torch 化移植。
逻辑与 Comfyui_TTP_Toolset 1.0.5 逐行对齐(PIL 渐变蒙版混合),
仅将 ComfyUI 的 tensor2pil/pil2tensor 换成本地实现。
与早期 PIL 版的差异(两处根改动):
tensor 约定与 ComfyUI IMAGE 一致:BHWC、float32、[0, 1]、RGB。
1. **全程 float32,不再经过 PIL/uint8**(原 P2-5)。
旧实现把 张量 → PIL(uint8) → crop → 张量、再 张量 → PIL(uint8) → paste → 张量,
8bit 量化发生两次,模型输出的浮点精度在拼装环节被削掉。
现在切块用张量切片、拼装用 numpy 浮点累加,量化一次都不发生。
2. **2D 权重累加拼装,取代"先横向拼行、再纵向拼行"**(原 P2-4)。
旧实现先逐行横向混合、再逐行纵向混合:横竖交点(L 形接缝)处两侧处理
不对称,且必须先凑齐全部行图才能进入纵向阶段,内存上要多留一份整图。
现在与 `tiled_vae.tiled_decode_latent` 同构:每块带一个 2D 权重图,
累加 acc += tile * w、wacc += w,最后 acc / wacc。
权重是可分离的:w = wy ⊗ wx(水平/垂直各一条 ramp)。
每条 ramp 在与邻块的重叠区里做 1→0 / 0→1 的线性过渡,
过渡带宽度 = min(padding, 实际重叠宽度),位置在重叠区居中
—— 与旧 PIL 渐变蒙版的语义逐像素一致。
由于 Σwx = Σwy = 1(在任何像素处),2D 权重之和恒为 1,
acc / wacc 的归一化在数学上是恒等操作(实现里仍保留除法以吸收浮点误差)。
附带的等价性:旧的"先横后竖"两段式在数学上等价于可分离的 2D 权重
(横向权重同时乘进上下两行),因此新实现在一维过渡带上与旧实现
逐像素一致,差别只在 L 形交点处 —— 那里新实现是对称的双线性过渡。
坐标口径(本模块的唯一约定):
- `positions` 必须是**目标尺度**(= 原图尺度 × 模型倍率 v)下的真实切块位置,
即 tile_batch 返回的位置经 scale_positions 缩放后的结果;
- `original_size` 是目标尺度的画布尺寸 (width*v, height*v);
- `grid_size` 是 (列数, 行数),与 tiles 的行主序索引一致。
tensor 约定:BHWC、float32、[0, 1]、RGB。
"""
from __future__ import annotations
import numpy as np
import torch
from PIL import Image
def tensor2pil(image: torch.Tensor) -> Image.Image:
"""(H, W, C) float [0,1] -> PIL RGB。"""
arr = (image.detach().cpu().numpy() * 255.0).round().clip(0, 255).astype(np.uint8)
return Image.fromarray(arr, mode="RGB")
def _layout(size: int, tile_size: int, overlap: int):
"""把长度为 `size` 的轴切成若干 `tile_size` 宽、相邻重叠 `overlap` 的块。
返回 (块数, 步长)。步长 = tile_size - overlap,因此内部接缝的重叠量恰为
`overlap`;最后一块右对齐到轴末端,其接缝重叠可能略有偏差 —— `assemble`
用 `min(padding, 实际重叠)` 吸收,且权重和恒为 1,不会产生接缝。
overlap=0 时退化为无重叠整切(步长 = tile_size)。
与 `compute_grid` 共用此函数,保证「规划面板显示的块数」与「tile_batch 实际
切出的块数」严格一致(旧实现两边各自推导 num/overlap,导致 f=128 时面板块数
偏大)。
"""
if size <= tile_size:
return 1, 0
step = tile_size - overlap
if step <= 0:
step = tile_size
overlap = 0
num = (size - tile_size + step - 1) // step + 1
# 保证最后一块覆盖到轴末端
while (num - 1) * step + tile_size < size:
num += 1
return num, step
def pil2tensor(image: Image.Image) -> torch.Tensor:
"""PIL RGB -> (H, W, C) float [0,1]。"""
arr = np.asarray(image, dtype=np.float32) / 255.0
return torch.from_numpy(arr)
def tile_batch(image_bhwc01: torch.Tensor, tile_width: int, tile_height: int, overlap: int = 0):
"""等价 TTP_Image_Tile_Batch.tile_image(纯张量切片版)。
返回 (tiles BHWC, positions [(l,u,r,b)], original_size (w,h), grid_size (cols,rows))。
def tile_batch(image_bhwc01: torch.Tensor, tile_width: int, tile_height: int):
"""等价 TTP_Image_Tile_Batch.tile_image。
与 PIL 版的唯一区别:切块不再经过 uint8 量化,切出的是原始 float32 像素。
返回 (tiles BHWC, positions [(l,t,r,b)], original_size (w,h), grid_size (cols,rows))。
`overlap` 是相邻块在【原图】上的重叠像素数(= pipeline 的 feather)。块按
`tile_width - overlap` 步长推进,内部接缝重叠量恒为 `overlap`,因此 `assemble`
用 `padding = feather * v` 作羽化宽度时与真实重叠一致,feather 具备单调语义
(越大重叠越宽、接缝越柔)。这取代了旧实现把 feather 加进块尺寸、导致大 feather
时有效羽化被整数除法反向截断的做法。
"""
if image_bhwc01.dim() != 4 or image_bhwc01.shape[0] != 1:
raise ValueError("tile_batch 期望单张图(B=1)")
image = tensor2pil(image_bhwc01.squeeze(0))
img_width, img_height = image.size
_, img_height, img_width, _ = image_bhwc01.shape
if img_width <= tile_width and img_height <= tile_height:
# 整图直喂:直接沿用输入张量(不复制、不量化)
return (
pil2tensor(image).unsqueeze(0),
image_bhwc01,
[(0, 0, img_width, img_height)],
(img_width, img_height),
(1, 1),
)
def calculate_step(size, tile_size):
if size <= tile_size:
return 1, 0
num_tiles = (size + tile_size - 1) // tile_size
overlap = (num_tiles * tile_size - size) // (num_tiles - 1)
step = tile_size - overlap
return num_tiles, step
num_cols, step_x = calculate_step(img_width, tile_width)
num_rows, step_y = calculate_step(img_height, tile_height)
num_cols, step_x = _layout(img_width, tile_width, overlap)
num_rows, step_y = _layout(img_height, tile_height, overlap)
img = image_bhwc01.squeeze(0) # (H, W, C)
tiles, positions = [], []
for y in range(num_rows):
for x in range(num_cols):
@@ -68,135 +110,162 @@ def tile_batch(image_bhwc01: torch.Tensor, tile_width: int, tile_height: int):
if lower - upper < tile_height:
upper = max(0, img_height - tile_height)
tiles.append(pil2tensor(image.crop((left, upper, right, lower))))
tiles.append(img[upper:lower, left:right])
positions.append((left, upper, right, lower))
tiles = torch.stack(tiles, dim=0)
return tiles, positions, (img_width, img_height), (num_cols, num_rows)
def tile_positions(img_width: int, img_height: int, tile_width: int, tile_height: int):
"""只计算分块位置(等价于对一张纯色 EmptyImage 做 tile_batch)。
def scale_positions(positions, factor: int):
"""把【原图尺度】的分块位置整体缩放到【目标尺度】(模型倍率域)。
工作流 A06 中 dummy 分块的对象是纯黑 EmptyImage,其位置信息只取决于
尺寸参数,因此无需真实栅格化,直接复用同一套切分数学。
切块发生在原图尺度上,而每块经 VOSR2 放大 factor 倍后,其在输出画布上
覆盖的区间正是 [left*factor, right*factor)。因此拼装阶段唯一的正确
坐标来源,就是 tile_batch 返回的**真实** positions 乘以 factor。
早期实现在 v× 画布上用 tile_positions 重新推导了一套网格,其步长由
`overlap=(num*tile-size)//(num-1)` 独立算出,与真实切块步长不共除,
导致块边界错位 1~4px —— 羽化混合的其实是不同原图位置的像素(接缝重影)。
本函数是"拼装只认一套坐标"的落点。
Args:
positions: tile_batch 返回的位置列表,每项为 (left, upper, right, lower)。
factor: 放大倍数(整数),即 VOSR2 的模型倍率。
Returns:
缩放后的位置列表,元素为 (left*f, upper*f, right*f, lower*f)。
"""
_, positions, original_size, grid_size = tile_batch(
torch.zeros(1, img_height, img_width, 3), tile_width, tile_height
)
return positions, original_size, grid_size
if factor == 1:
return list(positions)
return [(l * factor, u * factor, r * factor, d * factor)
for (l, u, r, d) in positions]
class _Assembler:
"""TTP_Image_Assy 的混合逻辑(原样移植)。"""
def _axis_profiles(starts, ends, padding: int) -> list[np.ndarray]:
"""构造某个轴上每块的 1D 权重曲线(float32,长度 = 该块在该轴上的跨度)。
@staticmethod
def create_gradient_mask(size, direction):
mask = Image.new("L", size)
for i in range(size[0] if direction == "horizontal" else size[1]):
value = int(255 * (1 - (i / size[0] if direction == "horizontal" else i / size[1])))
if direction == "horizontal":
mask.paste(value, (i, 0, i + 1, size[1]))
else:
mask.paste(value, (0, i, size[0], i + 1))
return mask
权重语义(与旧 PIL 渐变蒙版逐像素一致):
@classmethod
def blend_tiles(cls, tile1, tile2, overlap_size, direction, padding):
blend_size = padding
if blend_size > overlap_size:
blend_size = overlap_size
- 块的"核心区"权重恒为 1;
- 与左邻块的重叠区:权重 0 线性升到 1;
- 与右邻块的重叠区:权重 1 线性降到 0;
- 过渡带宽度 = min(padding, 实际重叠宽度),且在重叠区内居中
(左端留 offset_left 像素、右端留 offset_right 像素)。
if blend_size == 0:
if direction == "horizontal":
result = Image.new("RGB", (tile1.width + tile2.width - overlap_size, tile1.height))
result.paste(tile1.crop((0, 0, tile1.width - overlap_size, tile1.height)), (0, 0))
result.paste(tile2, (tile1.width - overlap_size, 0))
else:
result = Image.new("RGB", (tile1.width, tile1.height + tile2.height - overlap_size))
result.paste(tile1.crop((0, 0, tile1.width, tile1.height - overlap_size)), (0, 0))
result.paste(tile2, (0, tile1.height - overlap_size))
return result
这样在重叠区内两块权重之和恒为 1:
左块 1-(u-off)/blend + 右块 (u-off)/blend = 1。
offset_total = overlap_size - blend_size
offset_left = offset_total // 2
offset_right = offset_total - offset_left
Args:
starts: 每块在该轴上的起点(递增)。
ends: 每块在该轴上的终点。
padding: 羽化宽度(过渡带最大宽度),单位与 starts/ends 相同。
if direction == "horizontal":
size = (blend_size, tile1.height)
mask = cls.create_gradient_mask(size, direction)
crop_tile1 = tile1.crop((tile1.width - overlap_size + offset_left, 0,
tile1.width - offset_right, tile1.height))
crop_tile2 = tile2.crop((offset_left, 0, offset_left + blend_size, tile2.height))
if crop_tile1.size != crop_tile2.size:
raise ValueError(f"Crop sizes do not match: {crop_tile1.size} vs {crop_tile2.size}")
blended = Image.composite(crop_tile1, crop_tile2, mask)
result = Image.new("RGB", (tile1.width + tile2.width - overlap_size, tile1.height))
result.paste(tile1.crop((0, 0, tile1.width - overlap_size + offset_left, tile1.height)), (0, 0))
result.paste(blended, (tile1.width - overlap_size + offset_left, 0))
result.paste(tile2.crop((offset_left + blend_size, 0, tile2.width, tile2.height)),
(tile1.width - offset_right, 0))
else:
offset_total = overlap_size - blend_size
offset_top = offset_total // 2
offset_bottom = offset_total - offset_top
Returns:
每块一条权重曲线(list[np.ndarray])。
"""
n = len(starts)
profiles = []
for i in range(n):
length = ends[i] - starts[i]
left = np.ones(length, dtype=np.float32)
right = np.ones(length, dtype=np.float32)
size = (tile1.width, blend_size)
mask = cls.create_gradient_mask(size, direction)
crop_tile1 = tile1.crop((0, tile1.height - overlap_size + offset_top,
tile1.width, tile1.height - offset_bottom))
crop_tile2 = tile2.crop((0, offset_top, tile2.width, offset_top + blend_size))
if crop_tile1.size != crop_tile2.size:
raise ValueError(f"Crop sizes do not match: {crop_tile1.size} vs {crop_tile2.size}")
blended = Image.composite(crop_tile1, crop_tile2, mask)
result = Image.new("RGB", (tile1.width, tile1.height + tile2.height - overlap_size))
result.paste(tile1.crop((0, 0, tile1.width, tile1.height - overlap_size + offset_top)), (0, 0))
result.paste(blended, (0, tile1.height - overlap_size + offset_top))
result.paste(tile2.crop((0, offset_top + blend_size, tile2.width, tile2.height)),
(0, tile1.height - offset_bottom))
return result
# 与左邻块的重叠:本作右块,权重 0 → 1
if i > 0:
overlap = ends[i - 1] - starts[i]
if overlap > 0:
blend = min(padding, overlap)
offset_left = (overlap - blend) // 2
if blend > 0:
left[:offset_left] = 0.0
left[offset_left:offset_left + blend] = (
np.arange(blend, dtype=np.float32) / blend
)
else:
left[:overlap] = 0.0
# 与右邻块的重叠:本作左块,权重 1 → 0
if i < n - 1:
overlap = ends[i] - starts[i + 1]
if overlap > 0:
blend = min(padding, overlap)
offset_left = (overlap - blend) // 2
band_start = length - overlap + offset_left
if blend > 0:
right[band_start:band_start + blend] = (
1.0 - np.arange(blend, dtype=np.float32) / blend
)
right[band_start + blend:] = 0.0
else:
right[length - overlap:] = 0.0
profiles.append(left * right)
return profiles
def assemble(tiles_bhwc: torch.Tensor, positions, original_size, grid_size, padding: int) -> torch.Tensor:
"""等价 TTP_Image_Assy.assemble_image。tiles 尺寸应与 positions 对应块一致。"""
def assemble(tiles_bhwc: torch.Tensor, positions, original_size, grid_size,
padding: int) -> torch.Tensor:
"""等价 TTP_Image_Assy.assemble_image(2D 权重累加版)。
坐标口径(本移植的唯一约定):
- `positions` 必须是**目标尺度**(= 原图尺度 × 模型倍率 v)下的真实切块位置,
即 tile_batch 返回的位置经 scale_positions 缩放后的结果;
- `original_size` 是目标尺度的画布尺寸 (width*v, height*v);
- `grid_size` 是 (列数, 行数),与 tiles 的行主序索引一致。
拼装只认这一套坐标:混合区取自 `positions` 相邻块的实际重叠宽度,
因此重叠区两侧取到的必然是同一段原图内容。
实现:每块生成 2D 权重 w = wy ⊗ wx(可分离),累加
acc[region] += tile * w
wacc[region] += w
最后 acc / wacc 归一化。横向交点(L 形接缝)因此得到对称的双线性过渡,
而不像旧实现那样受"先横后竖"的顺序影响。
Returns:
(1, H, W, 3) 的 float32 张量,值域 [0, 1]。
"""
num_cols, num_rows = grid_size
reconstructed = Image.new("RGB", original_size)
canvas_w, canvas_h = original_size
n_tiles = tiles_bhwc.shape[0]
# 逐行水平混合
row_images = []
for row in range(num_rows):
row_image = tensor2pil(tiles_bhwc[row * num_cols])
for col in range(1, num_cols):
index = row * num_cols + col
tile_image = tensor2pil(tiles_bhwc[index])
prev_right = positions[index - 1][2]
left = positions[index][0]
overlap_width = prev_right - left
if overlap_width > 0:
row_image = _Assembler.blend_tiles(row_image, tile_image, overlap_width, "horizontal", padding)
else:
new_width = row_image.width + tile_image.width
new_height = max(row_image.height, tile_image.height)
new_row = Image.new("RGB", (new_width, new_height))
new_row.paste(row_image, (0, 0))
new_row.paste(tile_image, (row_image.width, 0))
row_image = new_row
row_images.append(row_image)
# 网格是规则的:各列的 x 区间相同,各行的 y 区间相同。
# 取第 0 行得到列边界,取第 0 列得到行边界。
col_starts = [positions[c][0] for c in range(num_cols)]
col_ends = [positions[c][2] for c in range(num_cols)]
row_starts = [positions[r * num_cols][1] for r in range(num_rows)]
row_ends = [positions[r * num_cols][3] for r in range(num_rows)]
# 逐行垂直混合
final_image = row_images[0]
for row in range(1, num_rows):
prev_lower = positions[(row - 1) * num_cols][3]
upper = positions[row * num_cols][1]
overlap_height = prev_lower - upper
if overlap_height > 0:
final_image = _Assembler.blend_tiles(final_image, row_images[row], overlap_height, "vertical", padding)
else:
new_width = max(final_image.width, row_images[row].width)
new_height = final_image.height + row_images[row].height
new_final = Image.new("RGB", (new_width, new_height))
new_final.paste(final_image, (0, 0))
new_final.paste(row_images[row], (0, final_image.height))
final_image = new_final
wx = _axis_profiles(col_starts, col_ends, padding)
wy = _axis_profiles(row_starts, row_ends, padding)
return pil2tensor(final_image).unsqueeze(0)
acc = np.zeros((canvas_h, canvas_w, 3), dtype=np.float32)
wacc = np.zeros((canvas_h, canvas_w), dtype=np.float32)
for idx in range(n_tiles):
row = idx // num_cols
col = idx % num_cols
left, upper, right, lower = positions[idx]
h = lower - upper
w = right - left
tile = tiles_bhwc[idx]
if tile.shape[0] != h or tile.shape[1] != w:
raise ValueError(
f"assemble: 第 {idx} 块尺寸 {tuple(tile.shape[:2])} 与 positions "
f"({h}, {w}) 不一致"
)
weight2d = wy[row][:, None] * wx[col][None, :] # (h, w)
region_acc = acc[upper:lower, left:right]
region_acc += tile.detach().cpu().numpy() * weight2d[:, :, None]
region_w = wacc[upper:lower, left:right]
region_w += weight2d
# 权重和处处为 1(Σwx = Σwy = 1),除法在数学上是恒等的;
# 仍保留一次归一化以吸收浮点累加误差。wacc 为 0 的像素(理论上不存在,
# 因为块矩形恰好铺满画布)用极小分母兜底,结果仍是 0。
np.maximum(wacc, 1e-12, out=wacc)
np.divide(acc, wacc[:, :, None], out=acc)
return torch.from_numpy(acc).unsqueeze(0)