优化
This commit is contained in:
2026-10-27 14:43:23 +08:00
parent 4daf1df630
commit 064e3d2132
4 changed files with 461 additions and 290 deletions
+60 -95
View File
@@ -13,7 +13,7 @@ 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
@@ -57,16 +57,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 +66,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:
@@ -194,10 +151,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 +163,52 @@ 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 参考。
"""
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 +216,34 @@ 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 放大图
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
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 用设备级空闲显存判断,
# 同一张卡上还有别的进程时也能正确识别压力)。
if _vram_pressure():
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)
torch.cuda.empty_cache()
# 循环外的统一回收:块循环里已用 del 精确释放了引用,这里只补一次
# 循环引用(dict/list 环)的回收,并把碎片化的小块内存还给驱动。
gc.collect()
if _vram_pressure():
torch.cuda.empty_cache()
aligned01 = torch.cat(items, dim=0)
del items
return aligned01.movedim(1, -1)