Skip to content

Commit 193717f

Browse files
committed
feat: integrate general_manage_vram into MemoryManager node (v2.4.0)
1 parent 5a9002a commit 193717f

5 files changed

Lines changed: 67 additions & 6 deletions

File tree

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<img src="https://raw.githubusercontent.com/ussoewwin/ComfyUI-DistorchMemoryManager/main/icon.png" width="128">
55
</p>
66

7-
**ComfyUI-VRAM-Manager** (formerly ComfyUI-DistorchMemoryManager) is an independent memory management custom node for ComfyUI. Provides Distorch memory management functionality for efficient GPU/CPU memory handling. Supports purging of SeedVR2, Qwen3-VL, and Nunchaku models (FLUX/Z-Image/Qwen-Image). Includes Model Patch Memory Cleaner for ModelPatchLoader workflows.
7+
**ComfyUI-VRAM-Manager** (formerly ComfyUI-DistorchMemoryManager) is an independent memory management custom node for ComfyUI. Provides Distorch memory management functionality for efficient GPU/CPU memory handling. Supports purging of SeedVR2, Qwen3-VL, and Nunchaku models (FLUX/Z-Image/Qwen-Image). Includes Model Patch Memory Cleaner for ModelPatchLoader workflows. Auto-detects non-PyTorch VRAM usage via NVML to prevent OOM errors in multi-process environments.
88

99
## Overview
1010

@@ -97,7 +97,7 @@ This is a completely original implementation designed specifically for Distorch
9797
</p>
9898

9999
* **Description**: Comprehensive memory management node (for advanced users)
100-
* **Features**: Detailed memory management with UI corruption protection
100+
* **Features**: Detailed memory management with UI corruption protection and general VRAM management
101101
* **Input**: Any data type (ANY)
102102
* **Output**: Any data type (ANY)
103103
* **Options**:
@@ -106,6 +106,7 @@ This is a completely original implementation designed specifically for Distorch
106106
* `force_gc`: Force garbage collection
107107
* `reset_virtual_memory`: Reset virtual memory
108108
* `restore_original_functions`: Restore original functions
109+
* `general_manage_vram`: General VRAM management (v2.4.0) – Auto-detects non-PyTorch VRAM usage (browsers, Discord, OBS, etc.) via NVML and adjusts ComfyUI memory management accordingly. Prevents OOM errors caused by external GPU processes that PyTorch cannot see. Requires `nvidia-ml-py`.
109110

110111
#### Patch Sage Attention DM (New in v2.3.0)
111112

@@ -295,6 +296,7 @@ pip install -r requirements.txt
295296
* For Qwen3-VL workflows: Use DisTorchPurgeVRAMV2 with `purge_qwen3vl_models: True` after Qwen3-VL model usage to prevent OOM. The node automatically handles device_map="auto" case for models distributed across multiple devices.
296297
* For Nunchaku workflows (FLUX/Z-Image/Qwen-Image/SDXL): Use DisTorchPurgeVRAMV2 with `purge_nunchaku_models: True` after Nunchaku model usage to prevent OOM. The node automatically disables CPU offload and clears models from all detection locations (sys.modules, ComfyUI model management, and gc.get_objects()). For Nunchaku SDXL models (v2.2.0), the node now includes cache clearing functionality that can release approximately 2.5GB of VRAM.
297298
* For SageAttention workflows (v2.3.0): Use Patch Sage Attention DM node to replace ComfyUI's attention mechanism with SageAttention for improved memory efficiency and performance. The node supports multiple SageAttention implementations and automatically patches attention on each model execution. To disable SageAttention, run the node again with `sage_attention` set to `disabled`.
299+
* For multi-process environments (v2.4.0): Enable `general_manage_vram` in the Memory Manager node. This uses NVML to detect VRAM consumed by non-PyTorch processes (browsers, Discord, OBS, etc.) and automatically informs ComfyUI to account for it, preventing OOM errors that occur when ComfyUI overestimates available VRAM.
298300

299301
## License
300302

changelog/changelog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Release History
22

3+
* **v2.4.0** – Added `general_manage_vram` parameter to Memory Manager node. Auto-detects non-PyTorch VRAM usage (browsers, Discord, OBS, etc.) via NVML and adjusts ComfyUI memory management accordingly. This prevents OOM errors caused by external GPU processes that PyTorch cannot detect. Added `nvidia-ml-py` dependency. Based on [ComfyUI-ReservedVRAM](https://github.com/Windecay/ComfyUI-ReservedVRAM) by Windecay (Apache-2.0).
34
* **v2.3.8** – Technical documentation describing Flash Attention-2 issues when using ComfyUI on PyTorch 2.11.0, including failure symptoms and environment-related constraints. See [Release Notes v2.3.8](https://github.com/ussoewwin/ComfyUI-DistorchMemoryManager/releases/tag/v2.3.8) for details.
45
* **v2.3.7** – Added external runtime SageAttention noise guard behavior for the known `Unsupported head_dim: 160` fallback path, reduced repeated error-log spam, and aligned patch documentation to repository-scoped changes only. See [Release Notes v2.3.7](https://github.com/ussoewwin/ComfyUI-DistorchMemoryManager/releases/tag/v2.3.7) for details.
56
* **v2.3.6** – Enhanced SageAttention3 (SA3) integration in Patch Sage Attention DM node. Added SA3-specific version detection function (`get_sage_attention3_info()`) with Blackwell support detection. Improved SA3 implementation with tensor layout conversion (NHD to HND) and constraint handling (headdim >= 256, attention mask support). Added automatic fallback to PyTorch SDPA when SA3 constraints are not met. Fixed SA2 version logging to skip when SA3 modes are selected. Supports both `sageattn3` and `sageattn3_per_block_mean` modes with proper per-block mean processing. See [Release Notes v2.3.6](https://github.com/ussoewwin/ComfyUI-DistorchMemoryManager/releases/tag/v2.3.6) for details.

nodes/memory_manager.py

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,54 @@
11
"""
22
Memory Manager nodes for DistorchMemoryManager
3+
4+
Reserved VRAM auto-detection based on ComfyUI-ReservedVRAM by Windecay
5+
https://github.com/Windecay/ComfyUI-ReservedVRAM
6+
Original code licensed under Apache License 2.0
37
"""
48
import torch
59
import gc
610

11+
# Safe import for pynvml (NVIDIA Management Library)
12+
try:
13+
import pynvml
14+
try:
15+
pynvml.nvmlInit()
16+
_pynvml_available = True
17+
except Exception as e:
18+
_pynvml_available = False
19+
pynvml = None
20+
print(f"[ComfyUI-VRAM-Manager] WARNING: pynvml imported but NVML init failed: {e}")
21+
except ImportError:
22+
_pynvml_available = False
23+
pynvml = None
24+
print("[ComfyUI-VRAM-Manager] INFO: pynvml (nvidia-ml-py) not installed. general_manage_vram will be unavailable.")
25+
26+
27+
def get_non_torch_vram_usage_bytes():
28+
"""
29+
Returns the amount of VRAM (in bytes) consumed by non-PyTorch processes.
30+
This is the difference between system-wide GPU usage (via NVML) and
31+
PyTorch's own reported usage.
32+
Returns None if detection is not possible.
33+
"""
34+
if not _pynvml_available or pynvml is None:
35+
return None
36+
if not torch.cuda.is_available():
37+
return None
38+
try:
39+
handle = pynvml.nvmlDeviceGetHandleByIndex(0)
40+
nvml_info = pynvml.nvmlDeviceGetMemoryInfo(handle)
41+
system_used = nvml_info.used # bytes, all processes
42+
43+
torch_free, torch_total = torch.cuda.mem_get_info()
44+
torch_used = torch_total - torch_free # bytes, PyTorch only
45+
46+
non_torch = system_used - torch_used
47+
return max(0, non_torch)
48+
except Exception as e:
49+
print(f"[ComfyUI-VRAM-Manager] Error detecting non-PyTorch VRAM usage: {e}")
50+
return None
51+
752
# AnyType mirrors the behavior of the original Purge VRAM node
853
class AnyType(str):
954
"""A special class that is always equal in not equal comparisons. Credit to pythongosssss"""
@@ -38,14 +83,15 @@ def INPUT_TYPES(s):
3883
"force_gc": ("BOOLEAN", {"default": True}),
3984
"reset_virtual_memory": ("BOOLEAN", {"default": True}),
4085
"restore_original_functions": ("BOOLEAN", {"default": False, "tooltip": "Restore original model_management functions"}),
86+
"general_manage_vram": ("BOOLEAN", {"default": False, "tooltip": "General VRAM management: auto-detect non-PyTorch VRAM usage (browsers, other apps) via NVML and adjust ComfyUI memory management accordingly. Requires nvidia-ml-py."}),
4187
}}
4288

4389
RETURN_TYPES = (any,)
4490
RETURN_NAMES = ("any",)
4591
FUNCTION = "manage_memory"
4692
CATEGORY = "Memory"
4793

48-
def manage_memory(self, anything, clean_gpu, clean_cpu, force_gc, reset_virtual_memory, restore_original_functions):
94+
def manage_memory(self, anything, clean_gpu, clean_cpu, force_gc, reset_virtual_memory, restore_original_functions, general_manage_vram=False):
4995
try:
5096
if clean_gpu and torch.cuda.is_available():
5197
torch.cuda.empty_cache()
@@ -81,6 +127,17 @@ def manage_memory(self, anything, clean_gpu, clean_cpu, force_gc, reset_virtual_
81127
except Exception as e:
82128
print(f"Function restoration failed: {e}")
83129

130+
# Auto-detect non-PyTorch VRAM usage and adjust ComfyUI memory management
131+
if general_manage_vram:
132+
non_torch = get_non_torch_vram_usage_bytes()
133+
if non_torch is not None:
134+
import comfy.model_management as mm
135+
mm.EXTRA_RESERVED_VRAM = non_torch
136+
non_torch_gb = non_torch / (1024 * 1024 * 1024)
137+
print(f"[ComfyUI-VRAM-Manager] Detected {non_torch_gb:.2f} GB non-PyTorch VRAM usage; adjusted memory management accordingly")
138+
else:
139+
print("[ComfyUI-VRAM-Manager] general_manage_vram: Could not detect non-PyTorch VRAM usage (pynvml unavailable or error)")
140+
84141
print("Comprehensive memory management completed")
85142

86143
except Exception as e:

pyproject.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
[project]
22
name = "ComfyUI-DistorchMemoryManager"
3-
version = "2.3.8"
4-
description = "An independent memory management custom node for ComfyUI. Provides Distorch memory management functionality for efficient GPU/CPU memory handling. Supports purging of SeedVR2, Qwen3-VL, and Nunchaku models (FLUX/Z-Image/Qwen-Image). Includes Model Patch Memory Cleaner for ModelPatchLoader workflows."
3+
version = "2.4.0"
4+
description = "An independent memory management custom node for ComfyUI. Provides Distorch memory management functionality for efficient GPU/CPU memory handling. Supports purging of SeedVR2, Qwen3-VL, and Nunchaku models (FLUX/Z-Image/Qwen-Image). Includes Model Patch Memory Cleaner for ModelPatchLoader workflows. Auto-detects non-PyTorch VRAM usage via NVML to prevent OOM errors in multi-process environments."
55
authors = [{ name = "ussoewwin" }]
66
license = { file = "LICENSE" }
77
requires-python = ">=3.10, <3.13"

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
torch>=1.12.0
2-
psutil>=5.8.0
2+
psutil>=5.8.0
3+
nvidia-ml-py

0 commit comments

Comments
 (0)