from __future__ import annotations import re import traceback from datetime import datetime 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 PROJECT_DIR = Path(__file__).resolve().parent.parent OUTPUT_DIR = PROJECT_DIR / "outputs" # 工作流固定常量 ALIGN = 16 # 块尺寸向上对齐到 16 的倍数(= inference.PAD_MULTIPLE) TILE_MIN = 512 # 【分块尺寸】下限 TILE_MAX = 1024 # 【分块尺寸】上限 MIN_LONG_SIDE = 1024 # 【输入下限】最长边不足此值时,等比例预放大后再进入流程 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 _content_for(total: int, cols: int) -> int: """把 total 等分为 cols 列后,单列向上对齐到 ALIGN 的倍数(= 块内容尺寸,不含羽化)。""" return ((_ceil_div(total, cols) + ALIGN - 1) // ALIGN) * ALIGN 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): 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]; 相邻块的重叠量 = `feather`(由 tile_batch 的 overlap 参数保证),不计入块尺寸 —— 这样 feather 只控制接缝羽化宽度、不再撑大块尺寸(旧实现把 feather 加进块 尺寸,导致 f=128 时块越界、有效羽化被整数除法反向截断)。 原图宽高均 ≤ 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) # 真实块数:与 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]: """读图取尺寸(宽, 高),不加载模型、不推理。 只读文件头(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, 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**:对齐会把目标画布的宽高比改掉(源图 800×600 抬到 1080×816,画布比 4:3 窄了 0.735%),再用 resize 填进去就成了内容 拉伸。短边改为按源图宽高比等比换算,画布与源图严格同比例,resize 不再 产生任何形变。分块网格的对齐由 compute_grid → _tile_size_for 独立完成 (块尺寸永远是 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(1, round(height * factor)) return min_long_side, short, factor long_ = max(1, round(width * factor)) 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) # 预放大的实际缩放参数: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) # 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 时块尺寸必 ≥ 图尺寸(按 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, "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 _bicubic_upscale(image_bhwc01: torch.Tensor, v: int) -> torch.Tensor: """整图做一次 bicubic 预放大到 v 倍(float32,无 uint8 往返)。 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( 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}") # cover 路径:等比放大到覆盖目标框再裁掉多余边。目标框与源图同比例时 # 裁剪量为 0;若因取整出现 1~2px 的比例差,也是裁边而不是拉伸。 image = _resize_cover_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)---- # # positions / grid 一并留用:拼装阶段直接复用这份真实切块坐标(×v), # 不再另算一套网格(见第 7 步)。overlap=feather 使相邻块在原图上重叠 feather # 像素(feather 仅作羽化宽度,不再撑大块尺寸)。 check_abort() 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)---- # # 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): 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, 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/8. 坐标统一 + 羽化拼装(TTP_Image_Assy 48,padding=羽化×v,节点 202)---- # # 拼装坐标直接复用第 4 步 tile_batch 的**真实** positions(×v 换算到模型尺度), # 不再在 v 尺度画布上另算一套网格。真实切块位置 ×v 是唯一自洽的坐标, # 羽化混合区取到的必是同一段原图内容(feather 即真实重叠,单调可控)。 check_abort() report(0.92, "VOSR2处理完成,最后拼接…") 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] 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 正常显示) # 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" # 过滤非法字符 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