Files
2026-10-27 14:43:23 +08:00

250 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
inference.py — VOSR2 推理契约:bicubic 预放大 → pad → encode → 一步去噪 →
decode → 色彩对齐 → 裁剪,支持 DiT/VAE 分块。
与 ComfyUI 版的唯一差异:comfy.utils.ProgressBar 换成 progress_cb 回调。
`forward_flexible`(models/lightningdit.py)断言方形输入——所有上游分块调用
裁出的都是 lt_size×lt_size 方块,非分块路径会先 pad 成方形再裁回,行为一致。
"""
import gc
import logging
import torch
import torch.nn.functional as F
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
def _oom_safe(fn):
"""执行 fn();遇 CUDA OOM 时清理缓存后重试一次(碎片导致的假性 OOM 多数可恢复)。"""
try:
return fn()
except torch.OutOfMemoryError:
gc.collect()
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
return fn()
def _pad_to_multiple(x: torch.Tensor, multiple: int):
_, _, h, w = x.shape
pad_h = (multiple - h % multiple) % multiple
pad_w = (multiple - w % multiple) % multiple
if pad_h == 0 and pad_w == 0:
return x
return F.pad(x, (0, pad_w, 0, pad_h), mode="reflect")
def _pad_to_square(x: torch.Tensor):
_, _, h, w = x.shape
side = max(h, w)
pad_h, pad_w = side - h, side - w
if pad_h == 0 and pad_w == 0:
return x
return F.pad(x, (0, pad_w, 0, pad_h), mode="reflect")
def _generate_noise(shape, seed: int, device, dtype) -> torch.Tensor:
"""One item's worth of noise per call; a local CPU Generator keeps global RNG state untouched."""
generator = torch.Generator(device="cpu").manual_seed(seed)
noise = torch.randn(shape, generator=generator, dtype=torch.float32)
return noise.to(device=device, dtype=dtype)
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)
lt_overlap = max(tile_overlap // AE_FACTOR, lt_size // 8)
lt_size = min(lt_size, min(lh, lw))
lt_overlap = min(lt_overlap, lt_size - 1)
return lt_size, lt_overlap
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:
return 1
return _count_dit_tiles(h, w, tile_size, tile_overlap)
def _count_dit_tiles(h: int, w: int, tile_size: int, tile_overlap: int) -> int:
"""Tiles a `run_vosr2` will submit to the DiT for one already-upscaled HxW image, for progress reporting."""
padded_h = h + (-h) % PAD_MULTIPLE
padded_w = w + (-w) % PAD_MULTIPLE
lh, lw = padded_h // AE_FACTOR, padded_w // AE_FACTOR
lt_size, lt_overlap = _tile_params(tile_size, tile_overlap, lh, lw)
if lh <= lt_size and lw <= lt_size:
return 1
return len(_make_tile_grid(lh, lt_size, lt_overlap)) * len(_make_tile_grid(lw, lt_size, lt_overlap))
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
padded01 = _pad_to_multiple(resized01, PAD_MULTIPLE)
padded_pm1 = padded01 * 2.0 - 1.0
lq_latent, latents_mean, latents_std = model.encode_tiled(padded_pm1, vae_tile_size, vae_tile_overlap)
_, lc, lh, lw = lq_latent.shape
lt_size, lt_overlap = _tile_params(tile_size, tile_overlap, lh, lw)
if lh <= lt_size and lw <= lt_size:
lq_sq = _pad_to_square(lq_latent)
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)
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 激活让路
if tick is not None:
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)
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])
# 视觉特征已全部提取,卸载视觉编码器并释放放大的原图张量
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
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:
tick()
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 激活让路
decoded_pm1 = _oom_safe(
lambda: model.decode_tiled(sr_latent, latents_mean, latents_std, vae_tile_size, vae_tile_overlap)
)
return decoded_pm1[:, :, :h, :w]
def run_vosr2(
model,
full_upscaled_bhwc01: torch.Tensor,
positions,
upscale: int,
seed: int,
tile_size: int,
tile_overlap: int,
vae_tile_size: int,
vae_tile_overlap: int,
progress_cb=None,
) -> torch.Tensor:
"""progress_cb(done_tiles, total_tiles):DiT 分块粒度的进度回调。
`full_upscaled_bhwc01`:整图已做 `×upscale` 预放大的结果(BHWC float32,
[0,1]),由调用方(pipeline)一次性完成 —— 见 P4:整图放大一次,再按
`positions × upscale` 切片逐块处理,重叠区只放大一次且用整图上下文。
`positions`:tile_batch 返回的原图尺度位置列表,每块切片 = `full_upscaled
[u*upscale:d*upscale, l*upscale:r*upscale]`。
seed 语义:**整张图、全部块共用同一个 seed,不做块序号偏移**(原始设计意图)。
同 seed + 同 shape ⇒ 噪声逐元素相同,给定相同输入与 seed,输出完全可复现、
跨图可比对。代价是相邻块内容相近时可能呈现相同方向的随机纹理,但这是为可比性
刻意保留的行为(P5 的「逐块派生 seed」方案已被否决,恢复统一 seed)。
P6:色彩对齐已移出本函数,由调用方在 assemble 之后对整图统一做,故此处
不再接受 color_alignment,也不逐块保留 bicubic 参考。
"""
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
n = len(positions)
# 每块放大后的尺寸(用首块位置推导;所有块内容尺寸一致)
l0, u0, r0, d0 = positions[0]
per_h = (d0 - u0) * upscale
per_w = (r0 - l0) * upscale
if tile_size == 0 and (per_w > 512 or per_h > 512):
logging.warning(
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 (per_w > 1024 or per_h > 1024):
logging.warning(
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."
)
# 进度/中断计数:每块按 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():
done[0] += 1
if progress_cb:
progress_cb(done[0], total_tiles)
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()
# 循环外的统一回收:块循环里已用 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)