优化
优化
This commit is contained in:
@@ -135,6 +135,33 @@ def offload_registered_models() -> int:
|
||||
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 缓存。由管线收尾(成功/失败/中断)调用。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user