Files
vosr2_core/device.py
giteaone 6738bff892 性能优化
性能优化20261030-submit
2026-10-30 15:38:33 +08:00

206 lines
8.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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
# cuDNN benchmark 模式:首次遇到某卷积形状时自动搜索最快算法,后续复用。
# 对本项目意义:DiT / VAE 含大量 Conv2d,tile 尺寸在单次运行内固定,
# benchmark 缓存命中率高,可带来 5~15% 卷积加速。代价是首次推理多几秒预热。
if torch.cuda.is_available():
torch.backends.cudnn.benchmark = True
# 全局注册表:本项目创建的所有 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 vram_pressure(free_ratio: float = 0.15) -> bool:
"""当前显存是否处于紧张状态(空闲显存占比低于 free_ratio)。
供推理循环做**条件式**缓存清理判断:`torch.cuda.empty_cache()` 是同步且
昂贵的操作(要向驱动归还所有未用显存并重置分配器),逐块无条件调用会让
GPU 利用率出现周期性锯齿。只在真的快没显存时才付这个代价。
注意用的是**设备级**空闲显存(`mem_get_info`),而非本进程占用量 ——
同一张卡上可能还有别的进程,它同样会造成 OOM,只看自己的占用会漏判。
Args:
free_ratio: 空闲显存占比阈值,低于此值即判定为有压力。
Returns:
是否有显存压力。无 CUDA 设备时恒为 False。
"""
if not torch.cuda.is_available():
return False
try:
free, total = torch.cuda.mem_get_info()
except Exception: # noqa: BLE001 —— 探测失败一律按"无压力"处理,绝不因此中断业务
return False
if total <= 0:
return False
return (free / total) < free_ratio
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