349 lines
14 KiB
Python
349 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
loader.py — VOSR2 bundle 的发现与严格加载(完全独立版)。
|
||
|
||
bundle 布局(与 ComfyUI 版一致):
|
||
models/<bundle>/
|
||
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 contextlib
|
||
import json
|
||
import logging
|
||
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
|
||
compute_dtype = x.dtype
|
||
ctx = (torch.amp.autocast(device_type="cuda", dtype=compute_dtype)
|
||
if device.type == "cuda" and compute_dtype != torch.float32
|
||
else contextlib.nullcontext())
|
||
with ctx:
|
||
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)
|
||
ctx = (torch.amp.autocast(device_type="cuda", dtype=compute_dtype)
|
||
if device.type == "cuda" and compute_dtype != torch.float32
|
||
else contextlib.nullcontext())
|
||
with ctx:
|
||
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)
|
||
|
||
# torch.compile:算子融合 + 内核自动调优,对 36 层 DiT 预期 15~30% 推理加速。
|
||
# 首次调用有编译开销(约 30~60 秒),后续复用缓存。失败时静默回退到原始模型。
|
||
try:
|
||
dit = torch.compile(dit, mode="default", dynamic=False)
|
||
logging.info("DiT 模型已通过 torch.compile 编译(mode=default)")
|
||
except Exception as exc:
|
||
logging.warning(f"torch.compile 失败,回退到原始模型:{exc}")
|
||
|
||
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
|