|
|
8G 卡批量跑图,跑到第 5、6 张就开始变慢,最后 OOM。
我写了个节点,接在出图后立刻卸载模型 + 清缓存,连续跑 200 张不再掉速。
两种用法:接在 VAEDecode 后面(图片直通,不改变画面),或者放个不连线的触发器,放哪都会执行。
96 行,不用额外装依赖(只用到 torch + comfy.model_management)。
有个坑顺便提醒:torch.cuda.empty_cache() 单独用没用,得先 unload_all_models(),
否则模型还占着显存,缓存清了也白清。
代码贴在下面。欢迎反馈 —— 尤其如果你那边表现不一样的话。
# -*- coding: utf-8 -*-
"""
FreeVRAM - 出图后清理显存节点
用途:批量跑图时,每张图生成完立刻释放显存,避免越跑越慢 / OOM
"""
import gc
import torch
import comfy.model_management as mm
class FreeVRAM:
"""清理显存(图片直通):VAEDecode -> FreeVRAM -> SaveImage"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"unload_models": ("BOOLEAN", {"default": True}),
"empty_cache": ("BOOLEAN", {"default": True}),
}
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "free"
CATEGORY = "utils/显存"
OUTPUT_NODE = True
def free(self, image, unload_models=True, empty_cache=True):
try:
print("[FreeVRAM] 出图完成 -> 清理显存中...", flush=True)
if unload_models:
try:
mm.unload_all_models()
except Exception:
pass
try:
mm.soft_empty_cache()
except Exception:
pass
if empty_cache and torch.cuda.is_available():
try:
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
except Exception:
pass
gc.collect()
except Exception:
pass
return (image,)
class FreeVRAMTrigger:
"""独立清理显存:无需连线,放哪都会执行"""
@classmethod
def INPUT_TYPES(cls):
return {"required": {"unload_models": ("BOOLEAN", {"default": True})}}
RETURN_TYPES = ()
FUNCTION = "free"
CATEGORY = "utils/显存"
OUTPUT_NODE = True
def free(self, unload_models=True):
try:
if unload_models:
try:
mm.unload_all_models()
except Exception:
pass
try:
mm.soft_empty_cache()
except Exception:
pass
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
print("[FreeVRAM] 显存已清理", flush=True)
except Exception:
pass
return ()
NODE_CLASS_MAPPINGS = {
"FreeVRAM": FreeVRAM,
"FreeVRAMTrigger": FreeVRAMTrigger,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"FreeVRAM": "清理显存 ClearVRAM",
"FreeVRAMTrigger": "清理显存(独立) ClearVRAM",
}
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
|