性能优化

性能优化20261030-submit
This commit is contained in:
2026-10-30 15:38:33 +08:00
parent 064e3d2132
commit 6738bff892
4 changed files with 310 additions and 61 deletions
+21 -2
View File
@@ -16,7 +16,9 @@ bundle 布局(与 ComfyUI 版一致):
- 提供 load_vosr2():模型按 (bundle, dtype) 进程级缓存,只加载一次;
unload_models() 可把模型搬回内存,下次运行自动搬回 GPU(不重新读盘)
"""
import contextlib
import json
import logging
import re
from pathlib import Path
@@ -165,7 +167,12 @@ class VOSR2Model:
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)
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):
@@ -198,7 +205,11 @@ class VOSR2Model:
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)
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)."""
@@ -286,6 +297,14 @@ def load_vosr2(model_name: str, dtype: str) -> VOSR2Model:
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():