commit 4daf1df630e313ed72001dc663f2e45f3b2b476b Author: Hardwell99 <3022256519@qq.com> Date: Tue Oct 20 15:33:43 2026 +0800 Initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/color.py b/color.py new file mode 100644 index 0000000..a6e60a4 --- /dev/null +++ b/color.py @@ -0,0 +1,76 @@ +"""Torch-native color alignment, ported from VOSR's inference_vosr_onestep.py. + +Upstream implements `adain_color_fix`/`wavelet_color_fix` via PIL round-trips and +OpenCV's GaussianBlur on uint8 arrays. VOSR2's contract requires float precision +throughout with no PIL/uint8 quantization and no OpenCV dependency, so both are +reimplemented here directly on BCHW float tensors in [0, 1], with a small separable +Gaussian blur standing in for `cv2.GaussianBlur`. +""" +import math + +import torch +import torch.nn.functional as F + +ADAIN_EPS = 1e-5 +WAVELET_SIGMA = 5.0 + + +def _gaussian_kernel1d(sigma: float, radius: int, device, dtype) -> torch.Tensor: + x = torch.arange(-radius, radius + 1, device=device, dtype=torch.float32) + kernel = torch.exp(-(x**2) / (2.0 * sigma * sigma)) + kernel = kernel / kernel.sum() + return kernel.to(dtype) + + +def gaussian_blur(x: torch.Tensor, sigma: float) -> torch.Tensor: + """Separable Gaussian blur, reflect-padded, applied per-channel. x: (B, C, H, W). + + Reflect padding requires the pad width to be smaller than the dimension it + pads, so each axis' kernel radius is capped to fit -- this only narrows the + (already Gaussian-tapered) kernel tail on tiles/images smaller than ~8*sigma + pixels, it never errors. + """ + c, h, w = x.shape[1], x.shape[2], x.shape[3] + desired_radius = max(int(math.ceil(sigma * 4.0)), 1) + radius_h = max(min(desired_radius, h - 1), 0) + radius_w = max(min(desired_radius, w - 1), 0) + + if radius_w > 0: + kernel_h = _gaussian_kernel1d(sigma, radius_w, x.device, x.dtype).view(1, 1, 1, -1).expand(c, 1, 1, -1) + x = F.pad(x, (radius_w, radius_w, 0, 0), mode="reflect") + x = F.conv2d(x, kernel_h, groups=c) + if radius_h > 0: + kernel_v = _gaussian_kernel1d(sigma, radius_h, x.device, x.dtype).view(1, 1, -1, 1).expand(c, 1, -1, 1) + x = F.pad(x, (0, 0, radius_h, radius_h), mode="reflect") + x = F.conv2d(x, kernel_v, groups=c) + return x + + +def adain_color_fix(target: torch.Tensor, source: torch.Tensor) -> torch.Tensor: + """Match target's per-channel spatial mean/std to source. Both (B, C, H, W) in [0, 1].""" + target_mean = target.mean(dim=[2, 3], keepdim=True) + target_std = target.std(dim=[2, 3], keepdim=True) + ADAIN_EPS + source_mean = source.mean(dim=[2, 3], keepdim=True) + source_std = source.std(dim=[2, 3], keepdim=True) + ADAIN_EPS + result = (target - target_mean) / target_std * source_std + source_mean + return torch.clamp(result, 0.0, 1.0) + + +def wavelet_color_fix(target: torch.Tensor, source: torch.Tensor) -> torch.Tensor: + """Combine source's low frequencies with target's high frequencies. Both (B, C, H, W) in [0, 1].""" + source_low = gaussian_blur(source, WAVELET_SIGMA) + target_low = gaussian_blur(target, WAVELET_SIGMA) + target_high = target - target_low + result = source_low + target_high + return torch.clamp(result, 0.0, 1.0) + + +def apply_color_alignment(decoded: torch.Tensor, reference: torch.Tensor, mode: str) -> torch.Tensor: + """decoded/reference: (B, C, H, W) float in [0, 1], same spatial size.""" + if mode == "none": + return torch.clamp(decoded, 0.0, 1.0) + if mode == "adain": + return adain_color_fix(decoded, reference) + if mode == "wavelet": + return wavelet_color_fix(decoded, reference) + raise ValueError(f"Unknown color_alignment mode: {mode!r}") diff --git a/device.py b/device.py new file mode 100644 index 0000000..a0c845e --- /dev/null +++ b/device.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +""" +device.py — 独立版设备与显存管理(替代 ComfyUI 的 +model_management / model_patcher / utils.ProgressBar)。 + +提供: +- get_torch_device() / unet_dtype():与 ComfyUI 默认行为等价的设备与精度选择 +- ModelPatcher:极简模型包装(记录 load_device / offload_device,按需搬移) +- load_models_gpu():把模型搬到 GPU(缺啥搬啥,已加载则跳过) +- gpu_lease():进程内 GPU 占用登记(谁在用,谁负责放) +- release_vram(unload_models):清理 CUDA 缓存;有他人持租约时拒绝搬移模型 + +并发模型(为什么需要租约): + 本服务是无状态的(不落任何会话数据),但模型注册表 _PATCHERS 与显存是 + 进程级共享资源。显存释放(model.to("cpu"))的唯一触发点是管线收尾 —— + 处理成功、处理失败、中断执行三条路径都会走到那里,跑在持有 GPU 的那个 + 线程上;只要释放发生在「本线程正是租约持有者」时,就绝不会抽走自己 + 正在执行的 kernel 的参数。租约把这件事收敛成一条规则 —— 只有「无他人持 + 租约」或「调用方本身就是持有者」时才允许搬移模型。它挡的是别人误调: + 比如有人在「中断执行」这类旁路线程里直接释放,那一刻推理线程仍在向 GPU + 提交 kernel,参数会被从正在执行的 kernel 底下抽走,既毁掉中断者自己的任务 + (报 CUDA 错而非「任务已中断」),也会波及队列中等待的其他用户。 + 全部基于 threading.Lock 实现,无计时器、无 sleep、无轮询。 +""" +from __future__ import annotations + +import contextlib +import gc +import threading + +import torch + +# 全局注册表:本项目创建的所有 ModelPatcher +_PATCHERS: list["ModelPatcher"] = [] + +# GPU 占用登记:线程 ident -> 该线程的持有深度。字典为空即表示 GPU 空闲。 +# 用深度而非布尔:同一线程可能嵌套进入(管线收尾时再调一次释放), +# 深度计数保证只有最外层退出时才真正注销持有者身份。 +_LEASE_LOCK = threading.Lock() +_LEASE_HOLDERS: dict[int, int] = {} + + +def get_torch_device() -> torch.device: + if torch.cuda.is_available(): + return torch.device("cuda") + return torch.device("cpu") + + +def unet_dtype(device: torch.device | None = None) -> torch.dtype: + """与 ComfyUI 'default' 行为对齐:CUDA 用 fp16,CPU 用 fp32。""" + device = device or get_torch_device() + if device.type == "cuda": + return torch.float16 + return torch.float32 + + +def gpu_busy() -> bool: + """是否已有线程正在使用 GPU(含模型搬移阶段)。""" + with _LEASE_LOCK: + return bool(_LEASE_HOLDERS) + + +def may_release_models() -> bool: + """当前线程此刻是否被允许执行 model.to(cpu)。 + + 允许条件:GPU 空闲,或调用方本身就是持租约的线程(即正常收尾路径)。 + """ + with _LEASE_LOCK: + return not _LEASE_HOLDERS or threading.get_ident() in _LEASE_HOLDERS + + +@contextlib.contextmanager +def gpu_lease(): + """声明「本线程接下来独占 GPU」,退出时自动归还。 + + 刻意不做成互斥锁:加锁会把排队语义耦合进业务代码,而 Gradio 的事件队列 + 已经提供了跨用户串行化(同一 concurrency_id 的事件共用一个队列,见 app.py)。 + 租约只登记「谁在用」,供 release_vram 判断能否安全搬移模型 —— 这是第二道 + 防线,用来兜住队列配置失效、或有人绕过 WebUI 直接打 API 的情况。 + """ + ident = threading.get_ident() + with _LEASE_LOCK: + _LEASE_HOLDERS[ident] = _LEASE_HOLDERS.get(ident, 0) + 1 + try: + yield + finally: + with _LEASE_LOCK: + depth = _LEASE_HOLDERS.get(ident, 0) - 1 + if depth > 0: + _LEASE_HOLDERS[ident] = depth + else: + _LEASE_HOLDERS.pop(ident, None) + + +class ModelPatcher: + """极简版 ModelPatcher:仅保留 load/offload 语义。""" + + def __init__(self, model: torch.nn.Module, load_device: torch.device, + offload_device: torch.device | None = None): + self.model = model + self.load_device = load_device + self.offload_device = offload_device or torch.device("cpu") + self._is_loaded = False + _PATCHERS.append(self) + + @property + def is_loaded(self) -> bool: + return self._is_loaded + + def load(self) -> None: + if not self._is_loaded: + self.model.to(self.load_device) + self._is_loaded = True + + def offload(self) -> None: + """把模型搬回内存(CPU),释放显存引用。""" + if self._is_loaded: + self.model.to(self.offload_device) + self._is_loaded = False + + +def load_models_gpu(patchers: list[ModelPatcher], force_full_load: bool = True) -> None: + """等价于 comfy.model_management.load_models_gpu:确保模型在 GPU 上。""" + for p in patchers: + p.load() + + +def offload_registered_models() -> int: + """把注册表里所有仍在显存上的组件搬回内存,返回实际被搬移的组件数。""" + moved = 0 + for p in _PATCHERS: + if p.is_loaded: + p.offload() + moved += 1 + return moved + + +def release_vram(unload_models: bool = True) -> dict: + """显存释放:卸载模型到内存 + 清空 CUDA 缓存。由管线收尾(成功/失败/中断)调用。 + + 若此刻有其他线程持 GPU 租约,则只做 gc + 缓存清理,拒绝搬移模型 + (结果里 offload_skipped=True),避免抽走别人正在使用的参数。 + + Returns: + 释放明细 dict:before_mb / after_mb / freed_mb / components_offloaded / + offload_skipped。无 CUDA 设备时三个 MB 字段为 None。 + """ + info: dict = { + "before_mb": None, "after_mb": None, "freed_mb": None, + "components_offloaded": 0, "offload_skipped": False, + } + if not torch.cuda.is_available(): + return info + + free0, total = torch.cuda.mem_get_info() + info["before_mb"] = round((total - free0) / 1024 / 1024) + + if unload_models: + if may_release_models(): + info["components_offloaded"] = offload_registered_models() + else: + info["offload_skipped"] = True + + # 即使跳过搬移也照做:这两步只影响本进程的缓存池,不会动到别人的张量 + gc.collect() + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + + free1, _ = torch.cuda.mem_get_info() + info["after_mb"] = round((total - free1) / 1024 / 1024) + info["freed_mb"] = max(info["before_mb"] - info["after_mb"], 0) + return info diff --git a/inference.py b/inference.py new file mode 100644 index 0000000..a925ad3 --- /dev/null +++ b/inference.py @@ -0,0 +1,284 @@ +# -*- 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 .color import apply_color_alignment +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 _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) + 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 _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: + 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, + images_bhwc01: torch.Tensor, + upscale: int, + seed: int, + color_alignment: str, + 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 分块粒度的进度回调。 + + seed 语义:**整张图、全部块共用同一个 seed,不做块序号偏移**。 + 噪声张量在每次 `_generate_noise` / `_generate_noise_batch` 里按传入的 seed + 重新生成,同 seed + 同 shape ⇒ 噪声逐元素相同,因此: + + - 外层 TTP 切出的 N 块拿到完全相同的噪声起点; + - 块内 DiT 潜空间分块共用整块的那一张噪声(本来就是这样,见 _run_tiled_single); + - 换图 / 换块数不会让 seed 语义漂移,跨图可比对。 + + 代价:相邻块若内容相近,会得到相同方向的随机纹理,块边界更容易看出规则重复。 + 外层接缝仍由 TTP 羽化(feather)负责掩盖,与内层 DiT 的高斯加权是两套机制。 + """ + if images_bhwc01.shape[-1] != 3: + raise ValueError(f"VOSR2Upscale expects a 3-channel RGB IMAGE, got {images_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 # 放大后目标尺寸 + + if tile_size == 0 and (h > 512 or w > 512): + logging.warning( + f"VOSR2Upscale: target size {w}x{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): + 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"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 + done = [0] + + def tick(): + done[0] += 1 + 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 + 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) + + return aligned01.movedim(1, -1) diff --git a/loader.py b/loader.py new file mode 100644 index 0000000..c26bc93 --- /dev/null +++ b/loader.py @@ -0,0 +1,329 @@ +# -*- coding: utf-8 -*- +""" +loader.py — VOSR2 bundle 的发现与严格加载(完全独立版)。 + +bundle 布局(与 ComfyUI 版一致): + models// + args.json + checkpoints/ema_model.safetensors + Qwen-Image-vae-2d/{config.json, diffusion_pytorch_model.safetensors} + dinov2_vitl14.safetensors + +与 ComfyUI 版的差异: +- 模型目录固定为项目内 models(不再依赖 folder_paths) +- 不做 HF 自动下载(文件已就位;缺失时直接报错并说明路径) +- 设备/精度由本包 device.py 提供 +- 提供 load_vosr2():模型按 (bundle, dtype) 进程级缓存,只加载一次; + unload_models() 可把模型搬回内存,下次运行自动搬回 GPU(不重新读盘) +""" +import json +import re +from pathlib import Path + +import torch +from safetensors.torch import load_file + +from . import device as _device +from .models.dinov2 import build_dinov2_vitl14 +from .models.lightningdit import LightningDiT +from .models.qwenimage_vae2d import AutoencoderKLQwenImage2D + +PROJECT_DIR = Path(__file__).resolve().parent.parent +MODELS_ROOT = PROJECT_DIR / "models" + +_VAE_SUBDIR = "Qwen-Image-vae-2d" +_VISION_FILENAME = "dinov2_vitl14.safetensors" + +REQUIRED_ARGS = { + "ae_type": "qwen", + "dim": 1536, + "depth": 36, + "num_heads": 24, + "patch_size": 2, + "enc_type": "dinov2l", + "enc_dim": 1024, + "layer_dinov2b_list": [17], + "auxiliary_time_cond": False, + "distill_type": "onestep", +} +DIT_ARG_KEYS = ("mlp_ratio", "use_qknorm", "use_swiglu", "use_rope", "use_rmsnorm", + "encdim_ratio", "resolution") + +_TRAINING_ONLY_KEY_PATTERNS = ( + re.compile(r"^n_averaged$"), + re.compile(r"^step_count$"), + re.compile(r"^decay$"), +) +_STRIPPABLE_PREFIXES = ("module.", "_orig_mod.", "ema_model.") + + +class VOSR2LoadError(RuntimeError): + """Raised for any missing file, incompatible config, or malformed state dict.""" + + +def list_model_bundles() -> list[str]: + if not MODELS_ROOT.is_dir(): + return [] + return sorted( + p.name for p in MODELS_ROOT.iterdir() + if p.is_dir() and (p / "args.json").is_file() + ) + + +def _load_args_json(bundle_dir: Path) -> dict: + args_path = bundle_dir / "args.json" + if not args_path.is_file(): + raise VOSR2LoadError(f"VOSR2 model bundle at {bundle_dir} is missing args.json.") + with open(args_path, "r") as f: + args = json.load(f) + + for key, expected in REQUIRED_ARGS.items(): + actual = args.get(key) + if actual != expected: + raise VOSR2LoadError( + f"VOSR2 model bundle at {bundle_dir} has an incompatible config: " + f"expected {key}={expected!r}, got {actual!r}." + ) + missing = [k for k in DIT_ARG_KEYS if k not in args] + if missing: + raise VOSR2LoadError( + f"VOSR2 model bundle at {bundle_dir}'s args.json is missing required field(s): {missing}." + ) + return args + + +def _find_dit_weight(bundle_dir: Path): + for candidate in ( + bundle_dir / "clean_weights" / "ema_model.safetensors", + bundle_dir / "checkpoints" / "ema_model.safetensors", + bundle_dir / "ema_model.safetensors", + ): + if candidate.is_file(): + return candidate + return None + + +def _clean_state_dict_keys(state_dict: dict) -> dict: + cleaned = {} + for key, value in state_dict.items(): + stripped = key + for prefix in _STRIPPABLE_PREFIXES: + if stripped.startswith(prefix): + stripped = stripped[len(prefix):] + break + if any(pattern.match(stripped) for pattern in _TRAINING_ONLY_KEY_PATTERNS): + continue + cleaned[stripped] = value + return cleaned + + +def _strict_load(module: torch.nn.Module, state_dict: dict, source: Path): + state_dict = _clean_state_dict_keys(state_dict) + missing, unexpected = module.load_state_dict(state_dict, strict=False) + if missing or unexpected: + raise VOSR2LoadError( + f"VOSR2 checkpoint at {source} does not match the expected {type(module).__name__} " + f"architecture (missing={missing}, unexpected={unexpected})." + ) + + +def _resolve_dtype(dtype: str, device) -> torch.dtype: + if dtype == "fp16": + return torch.float16 + if dtype == "bf16": + return torch.bfloat16 + if dtype == "default": + return _device.unet_dtype(device=device) + raise VOSR2LoadError(f"Unknown dtype option: {dtype!r}") + + +class VOSR2Model: + """运行时 bundle:DiT / VAE / 视觉编码器 + 配置,支持独立卸载。 + + 接口与 ComfyUI 版一致(vision_features / encode / denoise_one_step / decode...), + 供 inference.py 无改动复用。 + """ + + def __init__(self, dit_patcher, vae_patcher, vision_patcher, args: dict): + self.dit_patcher = dit_patcher + self.vae_patcher = vae_patcher + self.vision_patcher = vision_patcher + self.args = args + self.vision_layer_index = args["layer_dinov2b_list"][0] + self.dinov2_size = args.get("dinov2_size", 448) + + def _load(self, patcher): + _device.load_models_gpu([patcher], force_full_load=True) + return patcher.model, patcher.load_device + + def vision_features(self, lq_bchw_01: torch.Tensor) -> list: + """lq_bchw_01: (B, 3, H, W) in [0, 1]. Returns a one-item list (fixed-index layer).""" + model, device = self._load(self.vision_patcher) + x = torch.nn.functional.interpolate( + lq_bchw_01, size=(self.dinov2_size, self.dinov2_size), mode="bicubic" + ).clamp(0.0, 1.0) + 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) + return [feats] + + def encode(self, x_bchw_neg1_1: torch.Tensor): + from . import tiled_vae + model, device = self._load(self.vae_patcher) + return tiled_vae.encode_latent(model, x_bchw_neg1_1.to(device)) + + def encode_tiled(self, x_bchw_neg1_1: torch.Tensor, tile_size: int, tile_overlap: int): + from . import tiled_vae + model, device = self._load(self.vae_patcher) + return tiled_vae.encode_dispatch(model, x_bchw_neg1_1.to(device), tile_size, tile_overlap) + + def decode(self, latent: torch.Tensor, latents_mean, latents_std) -> torch.Tensor: + from . import tiled_vae + model, device = self._load(self.vae_patcher) + return tiled_vae.decode_latent(model, latent.to(device), latents_mean, latents_std) + + def decode_tiled(self, latent, latents_mean, latents_std, tile_size: int, tile_overlap: int) -> torch.Tensor: + from . import tiled_vae + model, device = self._load(self.vae_patcher) + return tiled_vae.decode_dispatch(model, latent.to(device), latents_mean, latents_std, + tile_size, tile_overlap) + + def dit_velocity(self, inp: torch.Tensor, t_cur: float, t_next: float, venc_fea: list) -> torch.Tensor: + """Single DiT forward: predicted flow velocity for `inp = cat([lq_latent, z], dim=1)`.""" + model, device = self._load(self.dit_patcher) + compute_dtype = model.t_embedder.mlp[0].weight.dtype + inp = inp.to(device=device, dtype=compute_dtype) + venc_fea = [f.to(device=device, dtype=compute_dtype) for f in venc_fea] + 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) + + 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).""" + device = self.dit_patcher.load_device + z = noise.to(device) + u = self.dit_velocity(torch.cat([lq_latent.to(device), z], dim=1), 1.0, 0.0, venc_fea) + return z - u + + def offload_all(self) -> None: + """把本 bundle 的三个组件全部搬回内存(低层 API)。 + + 注意:WebUI 侧请走 device.release_vram() / loader.unload_models(), + 它们带 GPU 租约校验,能避免把参数从别人正在执行的 kernel 底下抽走。 + """ + for p in (self.dit_patcher, self.vae_patcher, self.vision_patcher): + p.offload() + + +# --------------------------------------------------------------------------- # +# 加载入口(带缓存) +# --------------------------------------------------------------------------- # +_MODEL_CACHE: dict[tuple[str, str], VOSR2Model] = {} + + +def load_vosr2(model_name: str, dtype: str) -> VOSR2Model: + cache_key = (model_name, dtype) + if cache_key in _MODEL_CACHE: + return _MODEL_CACHE[cache_key] + + if not MODELS_ROOT.is_dir(): + raise VOSR2LoadError(f"模型目录不存在:{MODELS_ROOT}") + bundle_dir = MODELS_ROOT / model_name + if not bundle_dir.is_dir() or not (bundle_dir / "args.json").is_file(): + found = list_model_bundles() + raise VOSR2LoadError( + f"VOSR2 model bundle not found: {model_name!r}(在 {MODELS_ROOT} 下;" + f"当前可用:{found or '无'})" + ) + args = _load_args_json(bundle_dir) + dit_weight_path = _find_dit_weight(bundle_dir) + if dit_weight_path is None: + raise VOSR2LoadError( + f"No ema_model.safetensors found under {bundle_dir} " + f"(looked in clean_weights/, checkpoints/, and the bundle root)." + ) + vae_dir = bundle_dir / _VAE_SUBDIR + if not (vae_dir / "config.json").is_file(): + raise VOSR2LoadError( + f"VOSR2 bundle {bundle_dir} is missing its Qwen-Image 2D VAE " + f"({vae_dir}/config.json). The VAE's latent space is tied to this DiT " + f"and cannot be substituted." + ) + vision_path = bundle_dir / _VISION_FILENAME + if not vision_path.is_file(): + raise VOSR2LoadError( + f"VOSR2 bundle {bundle_dir} is missing its DINOv2-L encoder ({vision_path})." + ) + + load_device = _device.get_torch_device() + offload_device = torch.device("cpu") + compute_dtype = _resolve_dtype(dtype, load_device) + + base_channels = 16 # Qwen 2D VAE latent channels + dit = LightningDiT( + input_size=args["resolution"] // 8, + patch_size=args["patch_size"], + in_channels=2 * base_channels, + out_channels=base_channels, + hidden_size=args["dim"], + depth=args["depth"], + num_heads=args["num_heads"], + mlp_ratio=args["mlp_ratio"], + z_dims=args["enc_dim"], + encdim_ratio=args["encdim_ratio"], + auxiliary_time_cond=args["auxiliary_time_cond"], + use_qknorm=args["use_qknorm"], + use_swiglu=args["use_swiglu"], + use_rope=args["use_rope"], + use_rmsnorm=args["use_rmsnorm"], + num_fused_layers=len(args["layer_dinov2b_list"]), + ) + dit_state_dict = load_file(str(dit_weight_path)) + _strict_load(dit, dit_state_dict, dit_weight_path) + dit = dit.eval().to(compute_dtype) + for p in dit.parameters(): + p.requires_grad_(False) + + vae = AutoencoderKLQwenImage2D.from_pretrained(str(vae_dir)) + vae = vae.eval().float() # Qwen VAE 固定 fp32 + for p in vae.parameters(): + p.requires_grad_(False) + + vision_encoder = build_dinov2_vitl14() + vision_state_dict = load_file(str(vision_path)) + _strict_load(vision_encoder, vision_state_dict, vision_path) + vision_encoder = vision_encoder.eval().to(compute_dtype) + for p in vision_encoder.parameters(): + p.requires_grad_(False) + + dit_patcher = _device.ModelPatcher(dit, load_device=load_device, offload_device=offload_device) + vae_patcher = _device.ModelPatcher(vae, load_device=load_device, offload_device=offload_device) + vision_patcher = _device.ModelPatcher(vision_encoder, load_device=load_device, offload_device=offload_device) + + model = VOSR2Model(dit_patcher, vae_patcher, vision_patcher, args) + _MODEL_CACHE[cache_key] = model + return model + + +def unload_models() -> dict: + """把已加载模型全部卸载到内存 + 清空 CUDA 缓存,返回释放明细。 + + 实际搬移由 device.release_vram 统一执行(它遍历 _PATCHERS 全局注册表, + 并在有其他线程持 GPU 租约时拒绝搬移 —— 见 device.gpu_lease 的说明)。 + + 调用点只有一个:pipeline.run_pipeline 的收尾分支。处理成功、处理失败、 + 中断执行三条路径都会走到那里,因此 WebUI 侧没有任何「释放显存」按钮, + 也不需要调用方自己记得释放。此时调用方本身就是租约持有者,搬移必然被允许; + 万一将来从别处调用,租约校验也能兜住,不会打断别人的推理。 + + 模型实例仍保留在 _MODEL_CACHE 中(设计意图——下次运行搬回 GPU 只需秒级, + 不必重新读盘),所以这里的释放不等于卸载缓存,也不会触发重新加载。 + + Returns: + device.release_vram 的明细 dict,额外多一个 cached_bundles 字段。 + """ + info = _device.release_vram(unload_models=True) + info["cached_bundles"] = len(_MODEL_CACHE) + return info diff --git a/models/__pycache__/dinov2.cpython-310.pyc b/models/__pycache__/dinov2.cpython-310.pyc new file mode 100644 index 0000000..46f476c Binary files /dev/null and b/models/__pycache__/dinov2.cpython-310.pyc differ diff --git a/models/__pycache__/lightningdit.cpython-310.pyc b/models/__pycache__/lightningdit.cpython-310.pyc new file mode 100644 index 0000000..955b842 Binary files /dev/null and b/models/__pycache__/lightningdit.cpython-310.pyc differ diff --git a/models/__pycache__/pos_embed.cpython-310.pyc b/models/__pycache__/pos_embed.cpython-310.pyc new file mode 100644 index 0000000..fbbf7c1 Binary files /dev/null and b/models/__pycache__/pos_embed.cpython-310.pyc differ diff --git a/models/__pycache__/qwenimage_vae2d.cpython-310.pyc b/models/__pycache__/qwenimage_vae2d.cpython-310.pyc new file mode 100644 index 0000000..b7770e5 Binary files /dev/null and b/models/__pycache__/qwenimage_vae2d.cpython-310.pyc differ diff --git a/models/__pycache__/rmsnorm.cpython-310.pyc b/models/__pycache__/rmsnorm.cpython-310.pyc new file mode 100644 index 0000000..2bddd64 Binary files /dev/null and b/models/__pycache__/rmsnorm.cpython-310.pyc differ diff --git a/models/__pycache__/swiglu_ffn.cpython-310.pyc b/models/__pycache__/swiglu_ffn.cpython-310.pyc new file mode 100644 index 0000000..de0bfd4 Binary files /dev/null and b/models/__pycache__/swiglu_ffn.cpython-310.pyc differ diff --git a/models/dinov2.py b/models/dinov2.py new file mode 100644 index 0000000..dd265cd --- /dev/null +++ b/models/dinov2.py @@ -0,0 +1,166 @@ +# Minimal local re-implementation of Meta's DINOv2 ViT-L/14 (facebookresearch/dinov2, +# Apache-2.0), sized to load the official `dinov2_vitl14` checkpoint directly from a +# local safetensors/pth file. +# +# VOSR2's spec forbids `torch.hub.load` at import/validate/execute time (it can +# execute cached repository code or reach the network), so the architecture is +# vendored here instead: patch embed, cls token, interpolated position encoding, +# and a stack of pre-norm transformer blocks with LayerScale. `interpolate_pos_encoding` +# below reproduces the official implementation's bicubic-resize formula verbatim +# (including its `+ 0.1` epsilon), since VOSR2 feeds arbitrary tile/image resolutions +# that rarely match the checkpoint's native 518x518 training grid. +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ..ops_shim import disable_weight_init + +# comfy.ops.disable_weight_init.{Conv2d,Linear,LayerNorm} subclass the plain +# torch.nn equivalents directly (same state_dict keys, same forward() unless +# ComfyUI later patches weights), skipping only their random-init cost -- so +# strict checkpoint loading and numerics are unaffected, while VOSR2's DINOv2 +# encoder becomes visible to ComfyUI's dtype-casting/lowvram machinery like +# any other native model. +ops = disable_weight_init + +DINOV2_VITL14_CONFIG = dict( + img_size=518, + patch_size=14, + embed_dim=1024, + depth=24, + num_heads=16, + mlp_ratio=4.0, +) + + +class PatchEmbed(nn.Module): + def __init__(self, img_size, patch_size, embed_dim): + super().__init__() + self.patch_size = patch_size + self.proj = ops.Conv2d(3, embed_dim, kernel_size=patch_size, stride=patch_size) + + def forward(self, x): + x = self.proj(x) + return x.flatten(2).transpose(1, 2) + + +class LayerScale(nn.Module): + def __init__(self, dim, init_values: float = 1.0): + super().__init__() + self.gamma = nn.Parameter(init_values * torch.ones(dim)) + + def forward(self, x): + return x * self.gamma + + +class Attention(nn.Module): + def __init__(self, dim, num_heads): + super().__init__() + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.qkv = ops.Linear(dim, dim * 3, bias=True) + self.proj = ops.Linear(dim, dim, bias=True) + + def forward(self, x): + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + x = F.scaled_dot_product_attention(q, k, v) + x = x.transpose(1, 2).reshape(B, N, C) + return self.proj(x) + + +class Mlp(nn.Module): + def __init__(self, dim, hidden_dim): + super().__init__() + self.fc1 = ops.Linear(dim, hidden_dim) + self.act = nn.GELU() + self.fc2 = ops.Linear(hidden_dim, dim) + + def forward(self, x): + return self.fc2(self.act(self.fc1(x))) + + +class Block(nn.Module): + def __init__(self, dim, num_heads, mlp_ratio): + super().__init__() + self.norm1 = ops.LayerNorm(dim, eps=1e-6) + self.attn = Attention(dim, num_heads) + self.ls1 = LayerScale(dim) + self.norm2 = ops.LayerNorm(dim, eps=1e-6) + self.mlp = Mlp(dim, int(dim * mlp_ratio)) + self.ls2 = LayerScale(dim) + + def forward(self, x): + x = x + self.ls1(self.attn(self.norm1(x))) + x = x + self.ls2(self.mlp(self.norm2(x))) + return x + + +class DinoVisionTransformer(nn.Module): + def __init__(self, img_size=518, patch_size=14, embed_dim=1024, depth=24, num_heads=16, mlp_ratio=4.0): + super().__init__() + self.patch_size = patch_size + self.embed_dim = embed_dim + self.patch_embed = PatchEmbed(img_size, patch_size, embed_dim) + num_patches = (img_size // patch_size) ** 2 + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim)) + self.mask_token = nn.Parameter(torch.zeros(1, embed_dim)) + + self.blocks = nn.ModuleList([Block(embed_dim, num_heads, mlp_ratio) for _ in range(depth)]) + self.norm = ops.LayerNorm(embed_dim, eps=1e-6) + + def interpolate_pos_encoding(self, x, w, h): + """Vendored verbatim from facebookresearch/dinov2 (Apache-2.0): bicubic-resizes + the patch position embeddings to the current (w, h) grid. The `+ 0.1` offset + before the target size and the `int()` truncation after are load-bearing -- + they sidestep a floating-point rounding edge case in `F.interpolate`'s + `scale_factor` path that the upstream implementation works around this way.""" + previous_dtype = x.dtype + npatch = x.shape[1] - 1 + N = self.pos_embed.shape[1] - 1 + if npatch == N and w == h: + return self.pos_embed + pos_embed = self.pos_embed.float() + class_pos_embed = pos_embed[:, 0] + patch_pos_embed = pos_embed[:, 1:] + dim = x.shape[-1] + w0 = w // self.patch_size + h0 = h // self.patch_size + w0, h0 = w0 + 0.1, h0 + 0.1 + patch_pos_embed = F.interpolate( + patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2), + scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)), + mode="bicubic", + ) + assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1] + patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) + return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype) + + def prepare_tokens(self, x): + B, _, w, h = x.shape + x = self.patch_embed(x) + cls_tokens = self.cls_token.expand(B, -1, -1) + x = torch.cat((cls_tokens, x), dim=1) + x = x + self.interpolate_pos_encoding(x, w, h) + return x + + def forward_intermediate_layer(self, x, layer_idx: int) -> torch.Tensor: + """Run through `layer_idx + 1` blocks and return patch tokens (cls token dropped). + + VOSR2 only ever needs one fixed intermediate layer's patch tokens + (`layer_dinov2b_list == [17]`, validated by the loader), so the remaining + `depth - layer_idx - 1` blocks are skipped rather than computed and discarded. + """ + x = self.prepare_tokens(x) + for block in self.blocks[: layer_idx + 1]: + x = block(x) + return x[:, 1:] + + +def build_dinov2_vitl14() -> DinoVisionTransformer: + return DinoVisionTransformer(**DINOV2_VITL14_CONFIG) diff --git a/models/lightningdit.py b/models/lightningdit.py new file mode 100644 index 0000000..dcd766a --- /dev/null +++ b/models/lightningdit.py @@ -0,0 +1,352 @@ +# Vendored from VOSR's models/lightningdit.py (by Jingfeng Yao, HUST-VL; +# built on facebookresearch/DiT and willisma/SiT). +# +# Trimmed for VOSR2 v1: +# - timm's PatchEmbed/Mlp are replaced by the small local equivalents below +# (VOSR2 targets zero new dependencies and timm is not otherwise required). +# - torch.compile decorators on module methods are dropped; ComfyUI runs on +# accelerators/platforms (e.g. Windows without Triton) where compiling +# arbitrary custom-node code is not a safe default. +# - Only forward_flexible's code path is kept; the fixed-size forward(), +# sin-cos position-embedding helpers, and pos-embed interpolation were +# dead code for this one-step model (LightningDiT is RoPE-conditioned and +# never used its optional absolute pos_embed) and are removed. +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ..ops_shim import disable_weight_init + +from .pos_embed import VisionRotaryEmbeddingFast +from .rmsnorm import RMSNorm +from .swiglu_ffn import SwiGLUFFN + +# See models/dinov2.py for why disable_weight_init is the right variant here: +# identical forward()/state_dict keys to plain torch.nn, just ComfyUI-native. +ops = disable_weight_init + + +class PatchEmbed(nn.Module): + """Conv2d patchify, (N, C, H, W) -> (N, T, D). Accepts any H, W divisible by patch_size.""" + + def __init__(self, img_size, patch_size, in_chans, embed_dim, bias=True): + super().__init__() + self.img_size = (img_size, img_size) + self.patch_size = (patch_size, patch_size) + self.proj = ops.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias) + + @property + def num_patches(self): + return (self.img_size[0] // self.patch_size[0]) * (self.img_size[1] // self.patch_size[1]) + + def forward(self, x): + x = self.proj(x) + return x.flatten(2).transpose(1, 2) + + +class Mlp(nn.Module): + def __init__(self, in_features, hidden_features, out_features=None, act_layer=nn.GELU): + super().__init__() + out_features = out_features or in_features + self.fc1 = ops.Linear(in_features, hidden_features) + self.act = act_layer() + self.fc2 = ops.Linear(hidden_features, out_features) + + def forward(self, x): + return self.fc2(self.act(self.fc1(x))) + + +class MultiHeadCrossAttention(nn.Module): + def __init__(self, d_model, num_heads, qk_norm=False, fused_attn: bool = True): + super().__init__() + assert d_model % num_heads == 0, "d_model must be divisible by num_heads" + + self.d_model = d_model + self.num_heads = num_heads + self.head_dim = d_model // num_heads + self.fused_attn = fused_attn + + self.q_linear = ops.Linear(d_model, d_model) + self.k_linear = ops.Linear(d_model, d_model) + self.v_linear = ops.Linear(d_model, d_model) + self.proj = ops.Linear(d_model, d_model) + + if qk_norm: + self.q_norm = RMSNorm(self.head_dim) + self.k_norm = RMSNorm(self.head_dim) + else: + self.q_norm = nn.Identity() + self.k_norm = nn.Identity() + + def forward(self, x, cond): + B, N, C = x.shape + B_cond, N_cond, _ = cond.shape + + q = self.q_linear(x).view(B, N, self.num_heads, self.head_dim).permute(0, 2, 1, 3) + k = self.k_linear(cond).view(B_cond, N_cond, self.num_heads, self.head_dim).permute(0, 2, 1, 3) + v = self.v_linear(cond).view(B_cond, N_cond, self.num_heads, self.head_dim).permute(0, 2, 1, 3) + + q = self.q_norm(q) + k = self.k_norm(k) + + x = F.scaled_dot_product_attention(q, k, v) + x = x.permute(0, 2, 1, 3).contiguous().view(B, N, C) + return self.proj(x) + + +def modulate_adasin(x, shift, scale): + if shift is None: + return x * (1 + scale.unsqueeze(1)) + return x * (1 + scale) + shift + + +def modulate(x, shift, scale): + if shift is None: + return x * (1 + scale.unsqueeze(1)) + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + +class Attention(nn.Module): + def __init__(self, dim, num_heads=8, qkv_bias=False, qk_norm=False, use_rmsnorm=False): + super().__init__() + assert dim % num_heads == 0, "dim should be divisible by num_heads" + + self.num_heads = num_heads + self.head_dim = dim // num_heads + + norm_layer = RMSNorm if use_rmsnorm else ops.LayerNorm + + self.qkv = ops.Linear(dim, dim * 3, bias=qkv_bias) + self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() + self.proj = ops.Linear(dim, dim) + + def forward(self, x, rope=None): + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) + q, k, v = qkv.unbind(0) + q, k = self.q_norm(q), self.k_norm(k) + + if rope is not None: + q = rope(q) + k = rope(k) + + x = F.scaled_dot_product_attention(q, k, v) + x = x.transpose(1, 2).reshape(B, N, C) + return self.proj(x) + + +class TimestepEmbedder(nn.Module): + def __init__(self, hidden_size: int, frequency_embedding_size: int = 256) -> None: + super().__init__() + self.frequency_embedding_size = frequency_embedding_size + self.mlp = nn.Sequential( + ops.Linear(frequency_embedding_size, hidden_size, bias=True), + nn.SiLU(), + ops.Linear(hidden_size, hidden_size, bias=True), + ) + + @staticmethod + def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000) -> torch.Tensor: + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half + ).to(device=t.device) + args = t[:, None].float() * freqs[None] + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + return embedding + + def forward(self, t: torch.Tensor) -> torch.Tensor: + t_freq = self.timestep_embedding(t, self.frequency_embedding_size) + return self.mlp(t_freq.to(self.mlp[0].weight.dtype)) + + +class LightningDiTBlock(nn.Module): + def __init__( + self, + hidden_size, + num_heads, + mlp_ratio=4.0, + use_qknorm=False, + use_swiglu=False, + use_rmsnorm=False, + z_dims=None, + ): + super().__init__() + if not use_rmsnorm: + self.norm1 = ops.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.norm2 = ops.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + else: + self.norm1 = RMSNorm(hidden_size) + self.norm2 = RMSNorm(hidden_size) + + self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, qk_norm=use_qknorm, use_rmsnorm=use_rmsnorm) + + mlp_hidden_dim = int(hidden_size * mlp_ratio) + if use_swiglu: + self.mlp = SwiGLUFFN(hidden_size, int(2 / 3 * mlp_hidden_dim)) + else: + self.mlp = Mlp(hidden_size, mlp_hidden_dim, act_layer=lambda: nn.GELU(approximate="tanh")) + + self.scale_shift_table = nn.Parameter(torch.randn(6, hidden_size) / hidden_size**0.5) + + self.z_dims = z_dims + if self.z_dims is not None: + self.cross_attn = MultiHeadCrossAttention(d_model=hidden_size, num_heads=num_heads, qk_norm=use_qknorm) + + def forward(self, x, c, z=None, feat_rope=None): + B, N, C = x.shape + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( + self.scale_shift_table[None] + c.reshape(B, 6, -1) + ).chunk(6, dim=1) + + x = x + gate_msa * self.attn(modulate_adasin(self.norm1(x), shift_msa, scale_msa), rope=feat_rope) + if self.z_dims is not None: + x = x + self.cross_attn(x, z) + x = x + gate_mlp * self.mlp(modulate_adasin(self.norm2(x), shift_mlp, scale_mlp)) + return x + + +class FinalLayer(nn.Module): + def __init__(self, hidden_size, patch_size, out_channels, use_rmsnorm=False): + super().__init__() + self.norm_final = RMSNorm(hidden_size) if use_rmsnorm else ops.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.linear = ops.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) + self.adaLN_modulation = nn.Sequential(nn.SiLU(), ops.Linear(hidden_size, 2 * hidden_size, bias=True)) + + def forward(self, x, c): + shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) + x = modulate(self.norm_final(x), shift, scale) + return self.linear(x) + + +class LightningDiT(nn.Module): + """One-step VOSR2 flow-matching backbone. Only forward_flexible is used at inference.""" + + def __init__( + self, + input_size=32, + patch_size=2, + in_channels=32, + out_channels=16, + hidden_size=1536, + depth=36, + num_heads=24, + mlp_ratio=4.0, + use_qknorm=False, + use_swiglu=False, + use_rope=False, + use_rmsnorm=False, + z_dims=None, + encdim_ratio=2, + num_fused_layers=1, + auxiliary_time_cond=False, + ): + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + self.patch_size = patch_size + self.num_heads = num_heads + self.use_rope = use_rope + self.hidden_size = hidden_size + + self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True) + self.t_embedder = TimestepEmbedder(hidden_size) + + if self.use_rope: + half_head_dim = hidden_size // num_heads // 2 + hw_seq_len = input_size // patch_size + self.feat_rope = VisionRotaryEmbeddingFast(dim=half_head_dim, pt_seq_len=hw_seq_len) + else: + self.feat_rope = None + + self.t_block = nn.Sequential(nn.SiLU(), ops.Linear(hidden_size, 6 * hidden_size, bias=True)) + + self.blocks = nn.ModuleList([ + LightningDiTBlock( + hidden_size, num_heads, mlp_ratio=mlp_ratio, use_qknorm=use_qknorm, + use_swiglu=use_swiglu, use_rmsnorm=use_rmsnorm, z_dims=z_dims, + ) for _ in range(depth) + ]) + self.final_layer = FinalLayer(hidden_size, patch_size, out_channels, use_rmsnorm=use_rmsnorm) + + self.z_dims = z_dims + if self.z_dims is not None: + self.num_fused_layers = num_fused_layers + self.layer_norm = ops.LayerNorm(z_dims) + self.mlp_ca = Mlp(z_dims, hidden_size * encdim_ratio, out_features=hidden_size, act_layer=lambda: nn.GELU(approximate="tanh")) + + self.auxiliary_time_cond = auxiliary_time_cond + self.r_embedder = TimestepEmbedder(hidden_size) if auxiliary_time_cond else None + + def unpatchify(self, x): + c = self.out_channels + p = self.x_embedder.patch_size[0] + h = w = int(x.shape[1] ** 0.5) + assert h * w == x.shape[1] + x = x.reshape(shape=(x.shape[0], h, w, p, p, c)) + x = torch.einsum("nhwpqc->nchpwq", x) + return x.reshape(shape=(x.shape[0], c, h * p, h * p)) + + def _get_dynamic_rope(self, hw_seq_len, device, dtype): + if not self.use_rope: + return None + + half_head_dim = self.hidden_size // self.num_heads // 2 + pt_seq_len = self.x_embedder.img_size[0] // self.patch_size + + from einops import repeat + + from .pos_embed import broadcat, rotate_half + + theta = 10000 + freqs = 1.0 / (theta ** (torch.arange(0, half_head_dim, 2, device=device)[: (half_head_dim // 2)].float() / half_head_dim)) + t = torch.arange(hw_seq_len, device=device).float() / hw_seq_len * pt_seq_len + freqs = torch.einsum("..., f -> ... f", t, freqs) + freqs = repeat(freqs, "... n -> ... (n r)", r=2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1) + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]).to(dtype) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]).to(dtype) + + def dynamic_rope_fn(t_input): + return t_input * freqs_cos + rotate_half(t_input) * freqs_sin + + return dynamic_rope_fn + + def forward_flexible(self, x, t, r=None, z=None): + """Forward pass supporting variable (square) input sizes via dynamically-sized RoPE.""" + N, C, H, W = x.shape + assert H == W, "forward_flexible currently only supports square inputs" + + current_hw_seq_len = H // self.patch_size + + x = self.x_embedder(x) + t_raw = t + t = self.t_embedder(t) + r = self.r_embedder(r) * (t_raw - r).unsqueeze(-1) if self.r_embedder is not None else 0 + c = t + r + c0 = self.t_block(c) + + if self.z_dims is not None and z is not None: + z = z[0] + z = self.layer_norm(z) + z = self.mlp_ca(z) + + if self.use_rope: + train_hw_seq_len = self.x_embedder.img_size[0] // self.patch_size + if current_hw_seq_len != train_hw_seq_len: + feat_rope = self._get_dynamic_rope(current_hw_seq_len, x.device, x.dtype) + else: + feat_rope = self.feat_rope + else: + feat_rope = None + + for block in self.blocks: + x = block(x, c0, z, feat_rope) + + x = self.final_layer(x, c) + return self.unpatchify(x) diff --git a/models/pos_embed.py b/models/pos_embed.py new file mode 100644 index 0000000..d8296be --- /dev/null +++ b/models/pos_embed.py @@ -0,0 +1,53 @@ +# Vendored from VOSR's models/pos_embed.py (upstream: EVA-02 rotary +# embeddings, MIT, itself adapted from lucidrains/rotary-embedding-torch), +# trimmed to VisionRotaryEmbeddingFast and its helpers -- the only pieces +# LightningDiT's use_rope path calls. +import torch +from einops import rearrange, repeat +from torch import nn + + +def broadcat(tensors, dim=-1): + num_tensors = len(tensors) + shape_lens = set(len(t.shape) for t in tensors) + assert len(shape_lens) == 1, "tensors must all have the same number of dimensions" + shape_len = list(shape_lens)[0] + dim = (dim + shape_len) if dim < 0 else dim + dims = list(zip(*map(lambda t: list(t.shape), tensors))) + expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim] + assert all(len(set(t[1])) <= 2 for t in expandable_dims), "invalid dimensions for broadcastable concatenation" + max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims)) + expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims)) + expanded_dims.insert(dim, (dim, dims[dim])) + expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims))) + tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes))) + return torch.cat(tensors, dim=dim) + + +def rotate_half(x): + x = rearrange(x, "... (d r) -> ... d r", r=2) + x1, x2 = x.unbind(dim=-1) + x = torch.stack((-x2, x1), dim=-1) + return rearrange(x, "... d r -> ... (d r)") + + +class VisionRotaryEmbeddingFast(nn.Module): + def __init__(self, dim, pt_seq_len=16, theta=10000): + super().__init__() + freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)) + t = torch.arange(pt_seq_len) / pt_seq_len * pt_seq_len + freqs = torch.einsum("..., f -> ... f", t, freqs) + freqs = repeat(freqs, "... n -> ... (n r)", r=2) + freqs = broadcat((freqs[:, None, :], freqs[None, :, :]), dim=-1) + + freqs_cos = freqs.cos().view(-1, freqs.shape[-1]) + freqs_sin = freqs.sin().view(-1, freqs.shape[-1]) + + self.register_buffer("freqs_cos", freqs_cos) + self.register_buffer("freqs_sin", freqs_sin) + + @torch.compiler.disable + def forward(self, t): + cos = self.freqs_cos.clone().to(t.dtype) + sin = self.freqs_sin.clone().to(t.dtype) + return (t * cos + rotate_half(t) * sin).contiguous() diff --git a/models/qwenimage_vae2d.py b/models/qwenimage_vae2d.py new file mode 100644 index 0000000..6ad90dc --- /dev/null +++ b/models/qwenimage_vae2d.py @@ -0,0 +1,282 @@ +# Vendored from VOSR's models/qwenimage_vae2d.py (upstream: Qwen-Image / +# Wan / HuggingFace teams, Apache-2.0). +# +# The upstream module subclasses diffusers' ModelMixin/ConfigMixin and reuses +# diffusers.DiagonalGaussianDistribution / AutoencoderKLOutput / DecoderOutput. +# diffusers is not part of a stock ComfyUI install, and VOSR2 targets zero new +# dependencies, so this version is self-contained: a plain nn.Module with a +# from_pretrained() that reads the same config.json/safetensors layout, and a +# local DiagonalGaussianDistribution with only the two ops this node needs +# (.mode(), .sample()). +import json +from dataclasses import dataclass +from pathlib import Path + +import torch +import torch.nn as nn +import torch.nn.functional as F +from safetensors.torch import load_file + +from ..ops_shim import disable_weight_init + +# See models/dinov2.py for why disable_weight_init is the right variant here: +# identical forward()/state_dict keys to plain torch.nn, just ComfyUI-native. +ops = disable_weight_init + +# Qwen-Image VAE per-channel latent normalization constants (from the +# upstream checkpoint's config.json defaults). +DEFAULT_LATENTS_MEAN = [-0.7571, -0.7089, -0.9113, 0.1075, -0.1745, 0.9653, -0.1517, 1.5508, + 0.4134, -0.0715, 0.5517, -0.3632, -0.1922, -0.9497, 0.2503, -0.2921] +DEFAULT_LATENTS_STD = [2.8184, 1.4541, 2.3275, 2.6558, 1.2196, 1.7708, 2.6052, 2.0743, + 3.2687, 2.1526, 2.8652, 1.5579, 1.6382, 1.1253, 2.8251, 1.9160] + + +class DiagonalGaussianDistribution: + def __init__(self, parameters: torch.Tensor): + self.mean, logvar = parameters.chunk(2, dim=1) + self.logvar = torch.clamp(logvar, -30.0, 20.0) + + def mode(self) -> torch.Tensor: + return self.mean + + def sample(self, generator: torch.Generator = None) -> torch.Tensor: + std = torch.exp(0.5 * self.logvar) + noise = torch.randn(self.mean.shape, generator=generator, device=self.mean.device, dtype=self.mean.dtype) + return self.mean + std * noise + + +@dataclass +class EncoderOutput: + latent_dist: DiagonalGaussianDistribution + + +@dataclass +class DecoderOutput: + sample: torch.Tensor + + +class RMSNorm2D(nn.Module): + def __init__(self, dim: int, bias: bool = False): + super().__init__() + self.scale = dim**0.5 + self.gamma = nn.Parameter(torch.ones(dim, 1, 1)) + self.bias = nn.Parameter(torch.zeros(dim, 1, 1)) if bias else 0.0 + + def forward(self, x): + return F.normalize(x, dim=1) * self.scale * self.gamma + self.bias + + +class ResidualBlock2D(nn.Module): + def __init__(self, in_dim: int, out_dim: int): + super().__init__() + self.norm1 = RMSNorm2D(in_dim) + self.conv1 = ops.Conv2d(in_dim, out_dim, kernel_size=3, padding=1) + self.norm2 = RMSNorm2D(out_dim) + self.conv2 = ops.Conv2d(out_dim, out_dim, kernel_size=3, padding=1) + self.conv_shortcut = ops.Conv2d(in_dim, out_dim, kernel_size=1) if in_dim != out_dim else nn.Identity() + + def forward(self, x): + h = self.conv_shortcut(x) + x = F.silu(self.norm1(x)) + x = self.conv1(x) + x = F.silu(self.norm2(x)) + x = self.conv2(x) + return x + h + + +class AttentionBlock2D(nn.Module): + def __init__(self, dim: int): + super().__init__() + self.norm = RMSNorm2D(dim) + self.to_qkv = ops.Conv2d(dim, dim * 3, kernel_size=1) + self.proj = ops.Conv2d(dim, dim, kernel_size=1) + + def forward(self, x): + identity = x + b, c, h, w = x.shape + x = self.norm(x) + qkv = self.to_qkv(x).reshape(b, 3, c, h * w).permute(0, 1, 3, 2).contiguous() + q, k, v = qkv.unbind(dim=1) + # 4-D (b, 1, N, c) single-head layout selects the O(N)-memory fused + # attention kernel; the 3-D (b, N, c) form falls back to O(N^2) math + # on some accelerators and OOMs on large tiles. + x_attn = F.scaled_dot_product_attention(q[:, None], k[:, None], v[:, None]).squeeze(1) + x_attn = x_attn.permute(0, 2, 1).reshape(b, c, h, w) + return self.proj(x_attn) + identity + + +class Resample2D(nn.Module): + def __init__(self, dim: int, mode: str): + super().__init__() + if mode == "upsample2d": + self.resample = nn.Sequential( + nn.Upsample(scale_factor=2.0, mode="nearest"), + ops.Conv2d(dim, dim // 2, kernel_size=3, padding=1), + ) + elif mode == "downsample2d": + self.resample = nn.Sequential( + nn.ZeroPad2d((0, 1, 0, 1)), + ops.Conv2d(dim, dim, kernel_size=3, stride=2), + ) + else: + self.resample = nn.Identity() + + def forward(self, x): + return self.resample(x) + + +class MidBlock2D(nn.Module): + def __init__(self, dim: int, num_layers: int = 1): + super().__init__() + resnets = [ResidualBlock2D(dim, dim)] + attentions = [] + for _ in range(num_layers): + attentions.append(AttentionBlock2D(dim)) + resnets.append(ResidualBlock2D(dim, dim)) + self.attentions = nn.ModuleList(attentions) + self.resnets = nn.ModuleList(resnets) + + def forward(self, x): + x = self.resnets[0](x) + for attn, resnet in zip(self.attentions, self.resnets[1:]): + x = resnet(attn(x)) + return x + + +class Encoder2D(nn.Module): + def __init__(self, dim=96, z_dim=32, dim_mult=(1, 2, 4, 4), num_res_blocks=2, attn_scales=()): + super().__init__() + dims = [dim * u for u in [1] + list(dim_mult)] + scale = 1.0 + + self.conv_in = ops.Conv2d(3, dims[0], kernel_size=3, padding=1) + + self.down_blocks = nn.ModuleList([]) + for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])): + for _ in range(num_res_blocks): + self.down_blocks.append(ResidualBlock2D(in_dim, out_dim)) + if scale in attn_scales: + self.down_blocks.append(AttentionBlock2D(out_dim)) + in_dim = out_dim + if i != len(dim_mult) - 1: + self.down_blocks.append(Resample2D(out_dim, mode="downsample2d")) + scale /= 2.0 + + self.mid_block = MidBlock2D(out_dim, num_layers=1) + self.norm_out = RMSNorm2D(out_dim) + self.conv_out = ops.Conv2d(out_dim, z_dim, kernel_size=3, padding=1) + + def forward(self, x): + x = self.conv_in(x) + for layer in self.down_blocks: + x = layer(x) + x = self.mid_block(x) + x = F.silu(self.norm_out(x)) + return self.conv_out(x) + + +class UpBlock2D(nn.Module): + def __init__(self, in_dim: int, out_dim: int, num_res_blocks: int, upsample_mode=None): + super().__init__() + resnets = [] + cur = in_dim + for _ in range(num_res_blocks + 1): + resnets.append(ResidualBlock2D(cur, out_dim)) + cur = out_dim + self.resnets = nn.ModuleList(resnets) + self.upsamplers = nn.ModuleList([Resample2D(out_dim, mode=upsample_mode)]) if upsample_mode is not None else None + + def forward(self, x): + for resnet in self.resnets: + x = resnet(x) + if self.upsamplers is not None: + x = self.upsamplers[0](x) + return x + + +class Decoder2D(nn.Module): + def __init__(self, dim=96, z_dim=16, dim_mult=(1, 2, 4, 4), num_res_blocks=2): + super().__init__() + dim_mult = list(dim_mult) + dims = [dim * u for u in [dim_mult[-1]] + dim_mult[::-1]] + + self.conv_in = ops.Conv2d(z_dim, dims[0], kernel_size=3, padding=1) + self.mid_block = MidBlock2D(dims[0], num_layers=1) + + self.up_blocks = nn.ModuleList([]) + for i, (in_dim, out_dim) in enumerate(zip(dims[:-1], dims[1:])): + if i > 0: + in_dim = in_dim // 2 + upsample_mode = "upsample2d" if i != len(dim_mult) - 1 else None + self.up_blocks.append(UpBlock2D(in_dim, out_dim, num_res_blocks, upsample_mode)) + + self.norm_out = RMSNorm2D(out_dim) + self.conv_out = ops.Conv2d(out_dim, 3, kernel_size=3, padding=1) + + def forward(self, x): + x = self.conv_in(x) + x = self.mid_block(x) + for up_block in self.up_blocks: + x = up_block(x) + x = F.silu(self.norm_out(x)) + return self.conv_out(x) + + +class AutoencoderKLQwenImage2D(nn.Module): + """2D-only Qwen-Image VAE. API: encode(x) -> EncoderOutput, decode(z) -> DecoderOutput.""" + + def __init__( + self, + base_dim: int = 96, + z_dim: int = 16, + dim_mult=(1, 2, 4, 4), + num_res_blocks: int = 2, + attn_scales=(), + latents_mean=None, + latents_std=None, + ): + super().__init__() + self.z_dim = z_dim + self.latents_mean = list(latents_mean) if latents_mean is not None else list(DEFAULT_LATENTS_MEAN) + self.latents_std = list(latents_std) if latents_std is not None else list(DEFAULT_LATENTS_STD) + + self.encoder = Encoder2D(dim=base_dim, z_dim=z_dim * 2, dim_mult=dim_mult, num_res_blocks=num_res_blocks, attn_scales=attn_scales) + self.quant_conv = ops.Conv2d(z_dim * 2, z_dim * 2, kernel_size=1) + self.post_quant_conv = ops.Conv2d(z_dim, z_dim, kernel_size=1) + self.decoder = Decoder2D(dim=base_dim, z_dim=z_dim, dim_mult=dim_mult, num_res_blocks=num_res_blocks) + + def encode(self, x: torch.Tensor) -> EncoderOutput: + h = self.quant_conv(self.encoder(x)) + return EncoderOutput(latent_dist=DiagonalGaussianDistribution(h)) + + def decode(self, z: torch.Tensor) -> DecoderOutput: + dec = self.decoder(self.post_quant_conv(z)) + return DecoderOutput(sample=torch.clamp(dec, -1.0, 1.0)) + + @classmethod + def from_config_dict(cls, config: dict) -> "AutoencoderKLQwenImage2D": + return cls( + base_dim=config.get("base_dim", 96), + z_dim=config.get("z_dim", 16), + dim_mult=tuple(config.get("dim_mult", (1, 2, 4, 4))), + num_res_blocks=config.get("num_res_blocks", 2), + attn_scales=tuple(config.get("attn_scales", ())), + latents_mean=config.get("latents_mean"), + latents_std=config.get("latents_std"), + ) + + @classmethod + def from_pretrained(cls, path: str) -> "AutoencoderKLQwenImage2D": + path = Path(path) + with open(path / "config.json", "r") as f: + config = json.load(f) + model = cls.from_config_dict(config) + weight_path = path / "diffusion_pytorch_model.safetensors" + state_dict = load_file(str(weight_path)) + missing, unexpected = model.load_state_dict(state_dict, strict=False) + if missing or unexpected: + raise RuntimeError( + f"VOSR2 VAE checkpoint at {weight_path} does not match the expected " + f"architecture (missing={missing}, unexpected={unexpected})." + ) + return model diff --git a/models/rmsnorm.py b/models/rmsnorm.py new file mode 100644 index 0000000..7e5cb70 --- /dev/null +++ b/models/rmsnorm.py @@ -0,0 +1,20 @@ +# Vendored from VOSR's models/rmsnorm.py (upstream: Meta Llama 2 RMSNorm), +# trimmed to the single class LightningDiT actually uses. The upstream file +# also carries an unrelated fairscale-based Transformer that VOSR2 never +# constructs and that would pull in a model-parallel dependency for nothing. +import torch +import torch.nn as nn + + +class RMSNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1e-6): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def _norm(self, x): + return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) + + def forward(self, x): + output = self._norm(x.float()).type_as(x) + return output * self.weight diff --git a/models/swiglu_ffn.py b/models/swiglu_ffn.py new file mode 100644 index 0000000..b896ea1 --- /dev/null +++ b/models/swiglu_ffn.py @@ -0,0 +1,24 @@ +# Vendored from VOSR's models/swiglu_ffn.py (upstream: DINOv2, Apache-2.0), +# trimmed to the pure-PyTorch SwiGLUFFN. The upstream file also has an +# xFormers-backed SwiGLUFFNFused fallback path; VOSR2 always uses the plain +# implementation so that optional dependency is dropped rather than vendored. +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from ..ops_shim import disable_weight_init + +# See models/dinov2.py for why disable_weight_init is the right variant here: +# identical forward()/state_dict keys to plain torch.nn, just ComfyUI-native. +ops = disable_weight_init + + +class SwiGLUFFN(nn.Module): + def __init__(self, in_features: int, hidden_features: int, bias: bool = True) -> None: + super().__init__() + self.w12 = ops.Linear(in_features, 2 * hidden_features, bias=bias) + self.w3 = ops.Linear(hidden_features, in_features, bias=bias) + + def forward(self, x: Tensor) -> Tensor: + x1, x2 = self.w12(x).chunk(2, dim=-1) + return self.w3(F.silu(x1) * x2) diff --git a/ops_shim.py b/ops_shim.py new file mode 100644 index 0000000..d27b253 --- /dev/null +++ b/ops_shim.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +""" +ops_shim.py — ComfyUI `comfy.ops.disable_weight_init` 的独立替身。 + +VOSR2 模型代码(LightningDiT / DINOv2 / Qwen-VAE)只用到了 +ops.Conv2d / ops.Linear / ops.LayerNorm,语义与 torch.nn 完全一致, +唯一区别是跳过权重初始化(加载 checkpoint 前无需初始化,省时且结果确定)。 +这里提供一个覆盖常用层类型的等价实现,不依赖 ComfyUI。 +""" +import torch.nn as nn + + +class disable_weight_init: + """与 comfy.ops.disable_weight_init 等价:各层类型跳过 reset_parameters。""" + + class Linear(nn.Linear): + def reset_parameters(self): + return None + + class Conv1d(nn.Conv1d): + def reset_parameters(self): + return None + + class Conv2d(nn.Conv2d): + def reset_parameters(self): + return None + + class Conv3d(nn.Conv3d): + def reset_parameters(self): + return None + + class ConvTranspose1d(nn.ConvTranspose1d): + def reset_parameters(self): + return None + + class ConvTranspose2d(nn.ConvTranspose2d): + def reset_parameters(self): + return None + + class ConvTranspose3d(nn.ConvTranspose3d): + def reset_parameters(self): + return None + + class LayerNorm(nn.LayerNorm): + def reset_parameters(self): + return None + + class GroupNorm(nn.GroupNorm): + def reset_parameters(self): + return None + + class BatchNorm2d(nn.BatchNorm2d): + def reset_parameters(self): + return None + + class Embedding(nn.Embedding): + def reset_parameters(self): + return None diff --git a/pipeline.py b/pipeline.py new file mode 100644 index 0000000..9839658 --- /dev/null +++ b/pipeline.py @@ -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 diff --git a/sharpen.py b/sharpen.py new file mode 100644 index 0000000..c240b04 --- /dev/null +++ b/sharpen.py @@ -0,0 +1,65 @@ +# -*- coding: utf-8 -*- +""" +sharpen.py — ComfyUI_essentials ImageCASharpening+ 的独立移植。 + +来源:https://github.com/Jamy-L/Pytorch-Contrast-Adaptive-Sharpening/ +与 essentials 逐行对齐(含 min_/max_ 的 clamp 语义)。 + +tensor 约定:BHWC、float32、[0, 1]、RGB。 +""" +from __future__ import annotations + +import torch +import torch.nn.functional as F + + +def _min_(tensor_list): + x = torch.stack(tensor_list) + mn = x.min(axis=0)[0] + return torch.clamp(mn, min=0) + + +def _max_(tensor_list): + x = torch.stack(tensor_list) + mx = x.max(axis=0)[0] + return torch.clamp(mx, max=1) + + +def cas_sharpen(image_bhwc01: torch.Tensor, amount: float) -> torch.Tensor: + """对比度自适应锐化。amount ∈ [0, 1](工作流用 1.0 与 0.8)。""" + epsilon = 1e-5 + img = F.pad(image_bhwc01.permute([0, 3, 1, 2]), pad=(1, 1, 1, 1)) + + a = img[..., :-2, :-2] + b = img[..., :-2, 1:-1] + c = img[..., :-2, 2:] + d = img[..., 1:-1, :-2] + e = img[..., 1:-1, 1:-1] + f = img[..., 1:-1, 2:] + g = img[..., 2:, :-2] + h = img[..., 2:, 1:-1] + i = img[..., 2:, 2:] + + # Computing contrast + cross = (b, d, e, f, h) + mn = _min_(cross) + mx = _max_(cross) + + diag = (a, c, g, i) + mn2 = _min_(diag) + mx2 = _max_(diag) + mx = mx + mx2 + mn = mn + mn2 + + # Computing local weight + inv_mx = torch.reciprocal(mx + epsilon) + amp = inv_mx * torch.minimum(mn, (2 - mx)) + + # scaling + amp = torch.sqrt(amp) + w = -amp * (amount * (1 / 5 - 1 / 8) + 1 / 8) + div = torch.reciprocal(1 + 4 * w) + + output = ((b + d + f + h) * w + e) * div + output = output.clamp(0, 1) + return output.permute([0, 2, 3, 1]) diff --git a/tiled_vae.py b/tiled_vae.py new file mode 100644 index 0000000..380fb39 --- /dev/null +++ b/tiled_vae.py @@ -0,0 +1,145 @@ +"""Gaussian-blended tiled VAE encode/decode for the Qwen-Image 2D VAE. + +Ported from VOSR's tiled_vae.py. Full-image VAE encode/decode of large inputs can +OOM (the Qwen VAE runs in fp32 internally); this bounds peak memory to one tile's +activations. Encoding uses `latent_dist.mode()` (deterministic) rather than +`.sample()`, since sampling draws uncorrelated noise per tile and would create +seams at tile boundaries. + +Why plain Gaussian blending is sufficient here (unlike SD/LDM's pad+crop `VAEHook` +machinery): the Qwen VAE uses RMSNorm2D, a purely per-pixel/per-channel norm with +no cross-tile statistics to reconcile (no GroupNorm), so each tile's forward pass +is independent and a weighted blend of overlapping outputs is well-founded. +""" +import math + +import torch +import torch.nn.functional as F + +AE_FACTOR = 8 # Qwen VAE spatial compression ratio + + +def _gaussian_weights(tile_h: int, tile_w: int, channels: int, device) -> torch.Tensor: + """2-D Gaussian blend mask (1, C, tile_h, tile_w) peaked at the centre.""" + var = 0.01 + mid_h, mid_w = (tile_h - 1) / 2, (tile_w - 1) / 2 + y = torch.arange(tile_h, dtype=torch.float32) + x = torch.arange(tile_w, dtype=torch.float32) + wy = torch.exp(-((y - mid_h) / tile_h) ** 2 / (2 * var)) + wx = torch.exp(-((x - mid_w) / tile_w) ** 2 / (2 * var)) + w = wy[:, None] * wx[None, :] + return w.to(device).unsqueeze(0).unsqueeze(0).expand(1, channels, -1, -1) + + +def _make_tile_grid(length: int, tile: int, overlap: int) -> list: + """Sorted, deduplicated starting positions that cover `length`.""" + stride = max(tile - overlap, 1) + if length <= tile: + return [0] + positions = list(range(0, length - tile + 1, stride)) + if positions[-1] + tile < length: + positions.append(length - tile) + return sorted(set(positions)) + + +def _pad_to_multiple(x: torch.Tensor, multiple: int = 8): + _, _, 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, h, w + return F.pad(x, (0, pad_w, 0, pad_h), mode="reflect"), h, w + + +def encode_latent(vae, x: torch.Tensor): + """Single-shot deterministic VAE encode -> normalized latent. Returns (latent, mean, std).""" + device = x.device + latents_mean = torch.tensor(vae.latents_mean, device=device).view(1, -1, 1, 1) + latents_std = 1.0 / torch.tensor(vae.latents_std, device=device).view(1, -1, 1, 1) + z = vae.encode(x).latent_dist.mode() + return (z - latents_mean) * latents_std, latents_mean, latents_std + + +def decode_latent(vae, sr_latent: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor) -> torch.Tensor: + """Single-shot VAE decode -> pixels in [-1, 1].""" + sr_latent = sr_latent / latents_std + latents_mean + return vae.decode(sr_latent).sample.clamp(-1, 1) + + +def _tile_params(tile_size: int, tile_overlap: int, lh: int, lw: int): + lt_size = max(tile_size // AE_FACTOR, 1) + 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 tiled_encode_latent(vae, x: torch.Tensor, tile_size: int, tile_overlap: int): + """Output latent shape equals the untiled path: ceil(h/8) x ceil(w/8).""" + pad, orig_h, orig_w = _pad_to_multiple(x, 8) + lh, lw = pad.shape[2] // 8, pad.shape[3] // 8 + lt_size, lt_overlap = _tile_params(tile_size, tile_overlap, lh, lw) + + if lh <= lt_size and lw <= lt_size: + return encode_latent(vae, pad) + + h_pos = _make_tile_grid(lh, lt_size, lt_overlap) + w_pos = _make_tile_grid(lw, lt_size, lt_overlap) + + b = pad.shape[0] + acc = wacc = g = None + mean = std = None + for hi in h_pos: + for wi in w_pos: + crop = pad[:, :, hi * 8:(hi + lt_size) * 8, wi * 8:(wi + lt_size) * 8] + z_tile, mean, std = encode_latent(vae, crop) + if acc is None: + lc = z_tile.shape[1] + g = _gaussian_weights(lt_size, lt_size, lc, x.device) + acc = torch.zeros(b, lc, lh, lw, device=x.device, dtype=z_tile.dtype) + wacc = torch.zeros_like(acc) + acc[:, :, hi:hi + lt_size, wi:wi + lt_size] += z_tile * g + wacc[:, :, hi:hi + lt_size, wi:wi + lt_size] += g + + blended = acc / wacc + out_lh, out_lw = math.ceil(orig_h / 8), math.ceil(orig_w / 8) + return blended[:, :, :out_lh, :out_lw], mean, std + + +def tiled_decode_latent(vae, sr_latent: torch.Tensor, latents_mean, latents_std, tile_size: int, tile_overlap: int) -> torch.Tensor: + """Decodes in pixel space (3ch): each latent tile maps to an exactly-8x pixel tile.""" + b, _, lh, lw = sr_latent.shape + lt_size, lt_overlap = _tile_params(tile_size, tile_overlap, lh, lw) + + if lh <= lt_size and lw <= lt_size: + return decode_latent(vae, sr_latent, latents_mean, latents_std) + + h_pos = _make_tile_grid(lh, lt_size, lt_overlap) + w_pos = _make_tile_grid(lw, lt_size, lt_overlap) + + out_h, out_w = lh * 8, lw * 8 + g = _gaussian_weights(lt_size * 8, lt_size * 8, 3, sr_latent.device) + acc = torch.zeros(b, 3, out_h, out_w, device=sr_latent.device, dtype=sr_latent.dtype) + wacc = torch.zeros_like(acc) + for hi in h_pos: + for wi in w_pos: + he, we = hi + lt_size, wi + lt_size + pix = decode_latent(vae, sr_latent[:, :, hi:he, wi:we], latents_mean, latents_std) + acc[:, :, hi * 8:he * 8, wi * 8:we * 8] += pix * g + wacc[:, :, hi * 8:he * 8, wi * 8:we * 8] += g + + return (acc / wacc).clamp(-1, 1) + + +def encode_dispatch(vae, x: torch.Tensor, vae_tile_size: int, vae_tile_overlap: int): + """encode_latent, tiled when vae_tile_size > 0.""" + if vae_tile_size and vae_tile_size > 0: + return tiled_encode_latent(vae, x, vae_tile_size, vae_tile_overlap) + return encode_latent(vae, x) + + +def decode_dispatch(vae, sr_latent: torch.Tensor, latents_mean, latents_std, vae_tile_size: int, vae_tile_overlap: int) -> torch.Tensor: + """decode_latent, tiled when vae_tile_size > 0.""" + if vae_tile_size and vae_tile_size > 0: + return tiled_decode_latent(vae, sr_latent, latents_mean, latents_std, vae_tile_size, vae_tile_overlap) + return decode_latent(vae, sr_latent, latents_mean, latents_std) diff --git a/ttp.py b/ttp.py new file mode 100644 index 0000000..51ae2eb --- /dev/null +++ b/ttp.py @@ -0,0 +1,202 @@ +# -*- coding: utf-8 -*- +""" +ttp.py — TTP_Image_Tile_Batch / TTP_Image_Assy 的独立移植。 + +逻辑与 Comfyui_TTP_Toolset 1.0.5 逐行对齐(PIL 渐变蒙版混合), +仅将 ComfyUI 的 tensor2pil/pil2tensor 换成本地实现。 + +tensor 约定与 ComfyUI IMAGE 一致: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 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): + """等价 TTP_Image_Tile_Batch.tile_image。 + + 返回 (tiles BHWC, positions [(l,t,r,b)], original_size (w,h), grid_size (cols,rows))。 + """ + 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 + + if img_width <= tile_width and img_height <= tile_height: + return ( + pil2tensor(image).unsqueeze(0), + [(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) + + tiles, positions = [], [] + for y in range(num_rows): + for x in range(num_cols): + left = x * step_x + upper = y * step_y + right = min(left + tile_width, img_width) + lower = min(upper + tile_height, img_height) + + if right - left < tile_width: + left = max(0, img_width - tile_width) + if lower - upper < tile_height: + upper = max(0, img_height - tile_height) + + tiles.append(pil2tensor(image.crop((left, upper, right, lower)))) + 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)。 + + 工作流 A06 中 dummy 分块的对象是纯黑 EmptyImage,其位置信息只取决于 + 尺寸参数,因此无需真实栅格化,直接复用同一套切分数学。 + """ + _, 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 + + +class _Assembler: + """TTP_Image_Assy 的混合逻辑(原样移植)。""" + + @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 + + @classmethod + def blend_tiles(cls, tile1, tile2, overlap_size, direction, padding): + blend_size = padding + if blend_size > overlap_size: + blend_size = overlap_size + + 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 + + offset_total = overlap_size - blend_size + offset_left = offset_total // 2 + offset_right = offset_total - offset_left + + 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 + + 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 + + +def assemble(tiles_bhwc: torch.Tensor, positions, original_size, grid_size, padding: int) -> torch.Tensor: + """等价 TTP_Image_Assy.assemble_image。tiles 尺寸应与 positions 对应块一致。""" + num_cols, num_rows = grid_size + reconstructed = Image.new("RGB", original_size) + + # 逐行水平混合 + 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) + + # 逐行垂直混合 + 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 + + return pil2tensor(final_image).unsqueeze(0)