Initial commit

This commit is contained in:
2026-10-20 15:33:43 +08:00
commit 4daf1df630
23 changed files with 2722 additions and 0 deletions
+492
View File
@@ -0,0 +1,492 @@
from __future__ import annotations
import re
import traceback
from datetime import datetime
from pathlib import Path
from typing import Callable
import torch
from PIL import Image
from . import device as _device
from . import ttp
from .inference import estimate_dit_tiles, run_vosr2
from .loader import load_vosr2
from .sharpen import cas_sharpen
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 # 【输入下限】最长边不足此值时,等比例预放大后再进入流程
ProgressCB = Callable[[float, str], None]
class PipelineAborted(RuntimeError):
"""用户请求中断任务(abort_check 返回 True 时在各阶段边界抛出)。"""
def load_image_bhwc(image_path: str | Path) -> torch.Tensor:
img = Image.open(image_path)
if img.mode != "RGB":
img = img.convert("RGB")
import numpy as np
arr = np.asarray(img, dtype=np.float32) / 255.0
return torch.from_numpy(arr).unsqueeze(0)
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 _pick_cols(total: int, feather: int, lo: int, hi: int) -> int:
hi_cols = max(1, _ceil_div(total, max(1, lo - feather)))
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:
dist = 0
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,块=原图尺寸,不加羽化)。
"""
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
def image_size(image_path: str | Path) -> tuple[int, int]:
"""读图取尺寸(宽, 高),不加载模型、不推理。"""
image = load_image_bhwc(image_path)
_, height, width, _ = image.shape # BHWC
return width, height
def fit_min_long_side(width: int, height: int,
min_long_side: int = MIN_LONG_SIDE,
enabled: bool = True) -> tuple[int, int, float]:
"""小图预放大换算:最长边不足 min_long_side 时,等比例放大到该值。
VOSR2 的分块区间是 [720, 960],输入远小于此区间时整图直喂,DiT 在极低
分辨率上做去噪,细节几乎等于插值。抬到 1024 后至少能走完整分块流程。
enabled=False 时跳过预放大(实验性开关关闭),原尺寸直接进入后续环节。
返回 (新宽, 新高, 放大倍数);无需放大时倍数 = 1.0 且尺寸原样返回。
短边向上对齐到 ALIGN,与后续分块网格保持同一基准。
"""
if not enabled:
return width, height, 1.0
if max(width, height) >= min_long_side:
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)
return min_long_side, short, factor
long_ = max(ALIGN, ((round(width * factor) + ALIGN - 1) // ALIGN) * ALIGN)
return long_, min_long_side, factor
def plan_info(
image_path: str | Path,
*,
scale: float = 2.0,
vosr2_scale_index: int = 2,
feather: int = 32,
tile_size: int = 640,
tile_overlap: int = 64,
pre_scale_enabled: bool = True,
min_long_side: int = MIN_LONG_SIDE,
) -> dict:
"""处理前一次性获取的规划信息(处理尺寸/输出尺寸、分块、DiT 内部分块预计块数)。
scale: 目标放大倍数(可为小数,输出尺寸 = 处理尺寸 × scale)。
vosr2_scale_index: VOSR2 模型单块超分倍数(2/3/4),决定 sovr2 内部分块数量。
pre_scale_enabled: 是否启用小图预放大(实验性开关)。
min_long_side: 预放大的目标最长边;面板只读展示,实际以本值为准。
尺寸口径与 _run_pipeline_impl 一致:先按 fit_min_long_side 抬到 min_long_side 再规划,
面板显示的即是模型实际吃进去的尺寸(src_* 保留上传原图尺寸)。
"""
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)
out_w, out_h = round(width * scale), round(height * scale)
# 分块在【处理尺寸】上进行:块尺寸 ∈ [720,960];图足够小时整图直喂
cols, rows, block_w, block_h = compute_grid(width, height, feather)
# VOSR2 内部先 bicubic ×v 放大再潜空间分块,故按 块×v 估算 DiT 内部块数
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 判定,不比对块尺寸。
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,
"scale": scale, "vosr2_scale": vosr2_scale_index,
"out_w": out_w, "out_h": out_h,
"cols": cols, "rows": rows,
"block_w": block_w, "block_h": block_h,
"direct_feed": cols == 1 and rows == 1,
"dit_tiles": dit_per_tile * cols * rows,
"dit_tile_size": tile_size, "dit_tile_overlap": tile_overlap,
}
def _resize_bhwc(image: torch.Tensor, out_h: int, out_w: int) -> torch.Tensor:
"""BHWC 张量重采样到目标尺寸(Lanczos,质量优先)。"""
import numpy as np
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)
def _run_pipeline_impl(
image_path: str | Path,
*,
scale: float = 2.0,
vosr2_scale_index: int = 2,
feather: int = 32,
seed: int | None = None,
model_name: str = "VOSR2",
dtype: str = "default",
color_alignment: str = "none",
tile_size: int = 640,
tile_overlap: int = 64,
vae_tile_size: int = 640,
vae_tile_overlap: int = 64,
sharpen_amount: float = 0.0,
pre_scale_enabled: bool = True,
min_long_side: int = MIN_LONG_SIDE,
output_dir: Path | None = None,
orig_name: str | None = None,
progress_cb: ProgressCB | None = None,
on_tile: Callable[[int, int], None] | None = None,
abort_check: Callable[[], bool] | None = None,
) -> Path:
"""执行完整 A06 流程,返回输出 PNG 路径。
流程:读图 → 小图预放大(最长边 → MIN_LONG_SIDE)→ 在原图上切 [720,960]
分块(原图宽高均 ≤960 时整图直喂)
→ 喂 VOSR2(内部先 bicubic ×vosr2_scale_index 放大,再按 tile_size 等
参数在潜空间分块)→ 羽化拼装(模型倍数域,原图×v)→ 重采样到目标
输出尺寸(原图×scale,scale=模型倍数时跳过)→ 锐化 → 保存。
scale: 目标放大倍数(可为小数,输出尺寸 = 原图 × scale)。注意原图口径
是「预放大后的尺寸」,即上传图最长边不足 min_long_side 时先抬到该值再乘 scale;
pre_scale_enabled=False 时跳过这一步,原图口径即上传尺寸。
vosr2_scale_index: VOSR2 模型单块超分倍数(2/3/4),即模型内部处理尺度。
min_long_side: 小图预放大的目标最长边(实验性,面板只读)。
orig_name: 原始文件名(含扩展名),用于输出文件命名。
abort_check: 协作式中断探测,返回 True 时在阶段边界/DiT 分块粒度抛出 PipelineAborted。
"""
import random
def check_abort():
if abort_check is not None and abort_check():
raise PipelineAborted("任务已被用户中断")
if vosr2_scale_index not in (1, 2, 3, 4):
raise ValueError(f"VOSR2 模型倍数只允许 1/2/3/4,收到:{vosr2_scale_index}")
if not (0 < scale <= 8):
raise ValueError(f"放大倍数须在 (0, 8] 内,收到:{scale}")
if feather not in (32, 64, 128):
raise ValueError(f"羽化值只允许 32/64/128,收到:{feather}")
for name, val in (("tile_size", tile_size), ("vae_tile_size", vae_tile_size)):
if val < 0 or val % 64 != 0:
raise ValueError(f"{name} 必须是 64 的整数倍(0 表示禁用分块/整图解码),收到:{val}")
for name, val, size in (("tile_overlap", tile_overlap, tile_size),
("vae_tile_overlap", vae_tile_overlap, vae_tile_size)):
if val < 0 or val % 8 != 0 or (size and val >= size):
raise ValueError(f"{name} 必须是 8 的整数倍且小于对应 tile_size(0 表示无重叠),收到:{val}")
if seed is None or int(seed) < 0:
seed = random.randint(0, 2**48 - 1)
seed = int(seed)
def report(p: float, msg: str):
if progress_cb:
progress_cb(min(max(p, 0.0), 1.0), msg)
# ---- 1. 读图 + 小图预放大(LoadImage 15)---- #
check_abort()
report(0.02, "读取输入图像…")
image = load_image_bhwc(image_path)
_, height, width, _ = image.shape # BHWC
src_w, src_h = width, height
# 上传图最长边不足 min_long_side 时先等比例抬到该值,再进入后续所有环节:
# 分块规划、VOSR2 输入、输出尺寸口径全部以放大后的尺寸为准。
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)
elif not pre_scale_enabled:
report(0.03, f"按原尺寸 {width}×{height} 进入流程")
# 目标输出尺寸(= 处理尺寸 × scale,不做任何上限封顶)
out_w, out_h = round(width * scale), round(height * scale)
# ---- 2/3. 块数与块尺寸(204/205/118/119,在处理尺寸上切块,尺寸锁定 [720,960])---- #
cols, rows, block_w, block_h = compute_grid(width, height, feather)
if cols == 1 and rows == 1:
report(0.05, f"处理尺寸 {width}×{height} 未超过分块区间,VOSR2直接处理")
else:
report(0.05, f"分块规划:{cols}×{rows} 块,分块尺寸 {block_w}×{block_h} + 羽化{feather}")
# ---- 4. 分块(TTP_Image_Tile_Batch 47)---- #
check_abort()
tiles, _positions, _orig, _grid = ttp.tile_batch(image, block_w, block_h)
n_tiles = tiles.shape[0]
# ---- 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),整批进入与工作流一致 ---- #
model = load_vosr2(model_name, dtype)
def vosr_progress(done: int, total: int):
check_abort() # 每个 DiT 分块边界检查一次中断(最细粒度)
report(0.08 + 0.82 * done / max(total, 1), f"VOSR2 超分中… DiT 分块 {done}/{total}")
if on_tile:
on_tile(done, total)
upscaled = run_vosr2(
model, tiles, vosr2_scale_index, seed, color_alignment,
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)---- #
check_abort()
report(0.92, "VOSR2处理完成,最后拼接…")
assembled = ttp.assemble(upscaled, d_positions, d_original, d_grid, padding=feather * v)
# ---- 8.5 重采样到目标输出尺寸(拼装在模型尺度 v=原图×v 上;scale=v 时已到位,跳过)---- #
cur_h, cur_w = assembled.shape[1], assembled.shape[2]
if (out_w, out_h) != (cur_w, cur_h):
report(0.94, f"重采样到目标尺寸 {out_w} × {out_h}(模型 ×{v} → 目标 ×{scale:g})…")
assembled = _resize_bhwc(assembled, out_h, out_w)
# ---- 9. 最终 CA 锐化(原工作流 98/76 两级合并为一级,amount=0 时跳过)---- #
check_abort()
if sharpen_amount and sharpen_amount > 0:
report(0.96, f"锐化(amount={sharpen_amount})…")
result = cas_sharpen(assembled, sharpen_amount)
else:
result = assembled
# ---- 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")
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" # 过滤非法字符
stem = stem[:20] # 原始文件名超长时截断为 20 字符,避免最终文件名过长
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
out_path = day_dir / f"VOSR2_upscaled_x{scale:g}_{stem}_{stamp}.png"
# 文件名只精确到秒:中断后连着重跑、或同一秒内跑完两张,就可能落到同一个路径。
# 复用的路径会让前端按 URL 命中缓存而一直显示旧图 —— 看起来就是「新任务没生效」。
# 只在真撞名时追加序号,正常命名保持不变。
if out_path.exists():
n = 1
while True:
candidate = day_dir / f"VOSR2_upscaled_x{scale:g}_{stem}_{stamp}_{n}.png"
if not candidate.exists():
out_path = candidate
break
n += 1
out_img = (result.squeeze(0).clamp(0, 1).numpy() * 255.0).round().astype("uint8")
Image.fromarray(out_img, mode="RGB").save(out_path, format="png")
report(1.0, f"完成:{out_path.name}({out_img.shape[1]}×{out_img.shape[0]})")
print('OUTPUT_image')
print(out_path)
print("\033[36m 处理完毕 ----------------------------------------------------------------- END \033[0m")
return out_path
_RELEASE_REASON = {
"success": "任务成功收尾",
"aborted": "中断收尾",
"failed": "任务失败收尾",
}
def _report_release(
info: dict,
outcome: str,
release_cb: Callable[[dict], None] | None = None,
) -> None:
"""把显存释放明细打到 stdout,并可选地回调给调用方(WebUI 用于回执)。
注意:本函数在 `finally` 里被调用,任何异常都会顶掉真正的业务异常,
所以刻意只做字符串拼接、print,以及一次受 try 保护的、吞掉异常的回调。
"""
reason = _RELEASE_REASON.get(outcome, "任务收尾")
if info.get("offload_skipped"):
detail = "⚠️ 检测到其他线程正在使用 GPU,本次跳过模型搬移(仅清理缓存)"
else:
detail = f"已搬移 {info.get('components_offloaded', 0)} 个组件回内存"
if info.get("freed_mb") is not None:
detail += (f";显存 {info['before_mb']} MB → {info['after_mb']} MB"
f"(本次回收 {info['freed_mb']} MB)")
print(f"[vram] {reason}:{detail}", flush=True)
if release_cb is not None:
try:
release_cb(info)
except Exception as e: # noqa: BLE001 —— 回调失败绝不能影响收尾释放
print(f"[vram] ⚠️ 释放回执回调异常({type(e).__name__}: {e})", flush=True)
def run_pipeline(
image_path: str | Path,
*,
scale: float = 2.0,
vosr2_scale_index: int = 2,
feather: int = 32,
seed: int | None = None,
model_name: str = "VOSR2",
dtype: str = "default",
color_alignment: str = "none",
tile_size: int = 640,
tile_overlap: int = 64,
vae_tile_size: int = 640,
vae_tile_overlap: int = 64,
sharpen_amount: float = 0.0,
pre_scale_enabled: bool = True,
min_long_side: int = MIN_LONG_SIDE,
output_dir: Path | None = None,
orig_name: str | None = None,
progress_cb: ProgressCB | None = None,
on_tile: Callable[[int, int], None] | None = None,
abort_check: Callable[[], bool] | None = None,
release_cb: Callable[[dict], None] | None = None,
) -> Path:
"""run_pipeline 包装:**处理成功 / 处理失败 / 中断执行,三条路径无一例外**,
都在这里卸载模型回内存并清空显存缓存。不依赖任何按钮,也不依赖任何计时器。
释放点在 try 之后无条件执行 —— 成功走 return、失败抛异常、中断抛
PipelineAborted,最终都会落到同一个释放分支上;调用方不需要(也不应该)
自己再释放一次。模型实例保留在缓存中(CPU 侧),下次运行只需搬回 GPU
(秒级),不重新读盘。
**为什么释放必须发生在这一层,而不是在「中断执行」按钮里**:
按钮的回调跑在 Gradio 的另一个工作线程上,那一刻本函数的推理线程还在
向 GPU 提交 kernel。若在那里调 model.to("cpu"),参数会被从正在执行的
kernel 底下抽走 —— 本次任务会以 CUDA 错误而非「任务已中断」结束,还会
连带影响队列里等其他用户的请求。所以按钮只置 threading.Event(不碰显存),
由真正持有 GPU 的本线程在退出前完成释放。这也是「最早的安全释放时刻」:
检查点之上已经没有任何 GPU 任务,检查点之下只剩拼装/保存等 CPU 阶段。
中断路径额外做两件事,都是为了把显存更早、更完整地还给驱动:
1. 切断异常回溯对推理帧的引用 —— PipelineAborted 从 DiT 分块循环里抛出时,
traceback 会钉住 _run_tiled_single 等帧,而这些帧的局部变量里有
lq_latent / u_acc / w_acc / tile_venc 等 GPU 张量。不切断的话,
下面这次 gc.collect() 收不走它们,empty_cache() 也就退不回这部分显存,
下一个用户得晚拿到卡。切断后帧在出栈瞬间即被回收。
2. 失败路径(OOM / CUDA 异常)先把完整回溯落日志再切断引用 —— 显存最紧张
的时刻恰恰最需要立刻归还,而云端排查又只能依赖这份日志。
Args:
abort_check: 协作式中断探测,返回 True 时在阶段边界/DiT 分块粒度抛 PipelineAborted。
release_cb: 收尾释放完成后回调,入参为释放明细 dict。仅供调用方回执/展示,
不参与任何决策;回调内抛出的异常不会影响释放本身。
Returns:
输出 PNG 路径。
Raises:
PipelineAborted: 用户请求中断。
"""
from .loader import unload_models
print("\033[31m 开始处理 ----------------------------------------------------------------- START \033[0m")
print('SOURCE_image')
print(image_path)
outcome = "success" # success / aborted / failed,仅用于收尾日志与回执
with _device.gpu_lease():
try:
result = _run_pipeline_impl(
image_path,
scale=scale,
vosr2_scale_index=vosr2_scale_index,
feather=feather,
seed=seed,
model_name=model_name,
dtype=dtype,
color_alignment=color_alignment,
tile_size=tile_size,
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,
min_long_side=min_long_side,
output_dir=output_dir,
orig_name=orig_name,
progress_cb=progress_cb,
on_tile=on_tile,
abort_check=abort_check,
)
except PipelineAborted as exc:
outcome = "aborted"
exc.__traceback__ = None # 见 docstring:让下面的 gc 能真正收回激活张量
raise
except Exception as exc:
outcome = "failed"
print("[vram] 任务失败,完整回溯如下(随后切断引用以尽快回收显存):\n"
f"{traceback.format_exc()}", flush=True)
exc.__traceback__ = None
raise
except BaseException:
# KeyboardInterrupt / SystemExit:同样走下面的收尾释放,但不吞掉回溯
outcome = "failed"
raise
finally:
# 三条路径(成功 / 中断 / 失败)的公共出口 —— 「处理后自动释放显存」就在这一句。
# 此刻仍在 with 内:本线程就是租约持有者,搬移模型不会被第二道防线拦下。
_report_release(unload_models(), outcome, release_cb)
return result