-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnodes.py
More file actions
245 lines (178 loc) · 8.76 KB
/
Copy pathnodes.py
File metadata and controls
245 lines (178 loc) · 8.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import comfy.model_management as model_management
import torch
import logging
# Set up logging
logger = logging.getLogger(__name__)
def get_device_list():
"""Get list of available devices"""
devices = ["cpu"]
if torch.cuda.is_available():
devices.extend([f"cuda:{i}" for i in range(torch.cuda.device_count())])
return devices
class MultiGPUPreprocessorWrapper:
"""
Base wrapper class that temporarily overrides device placement during preprocessor model loading
and ensures input tensors are on the correct device to prevent multi-GPU device conflicts.
"""
def __init__(self, preprocessor_class):
self.preprocessor_class = preprocessor_class
@classmethod
def INPUT_TYPES(cls):
# Get base INPUT_TYPES from wrapped preprocessor
if hasattr(cls, 'preprocessor_class'):
base_inputs = cls.preprocessor_class.INPUT_TYPES()
else:
base_inputs = {"required": {}}
# Add device parameter
devices = get_device_list()
default_device = "cuda:0" if "cuda:0" in devices else (devices[1] if len(devices) > 1 else devices[0])
# Ensure optional section exists
if "optional" not in base_inputs:
base_inputs["optional"] = {}
base_inputs["optional"]["device"] = (devices, {"default": default_device})
return base_inputs
RETURN_TYPES = ("IMAGE",) # Most ControlNet preprocessors return IMAGE
FUNCTION = "execute"
CATEGORY = "preprocessors/gpu_wrapper"
def execute(self, device="cuda:1", **kwargs):
"""
Execute preprocessor with device override and input tensor movement.
"""
target_device = torch.device(device)
# Move input tensors to target device
moved_kwargs = {}
for key, value in kwargs.items():
if isinstance(value, torch.Tensor):
moved_kwargs[key] = value.to(target_device)
logger.debug(f"Moved input tensor '{key}' from {value.device} to {target_device}")
else:
moved_kwargs[key] = value
# Critical: Save original function
original_get_device = model_management.get_torch_device
try:
# Temporarily override with consistent device
model_management.get_torch_device = lambda: target_device
logger.debug(f"Temporarily overriding get_torch_device() to return: {target_device}")
# Create and execute original preprocessor using its specific function name
preprocessor = self.preprocessor_class()
function_name = getattr(self.preprocessor_class, 'FUNCTION', 'execute')
result = getattr(preprocessor, function_name)(**moved_kwargs)
logger.debug(f"Successfully executed {self.preprocessor_class.__name__} on {target_device}")
return result
except Exception as e:
logger.error(f"Error in MultiGPUPreprocessorWrapper execution: {e}")
raise
finally:
# ALWAYS restore original function, even on exception
model_management.get_torch_device = original_get_device
logger.debug("Restored original get_torch_device()")
# Import and create specific wrapper instances with error handling
# DepthAnything V2 Wrapper
try:
from comfyui_controlnet_aux import NODE_CLASS_MAPPINGS as AUX_NODE_MAPPINGS
DepthAnythingV2Preprocessor = AUX_NODE_MAPPINGS["DepthAnythingV2Preprocessor"]
class DepthAnythingV2Wrapper(MultiGPUPreprocessorWrapper):
preprocessor_class = DepthAnythingV2Preprocessor
def __init__(self):
super().__init__(DepthAnythingV2Preprocessor)
@classmethod
def INPUT_TYPES(cls):
return super().INPUT_TYPES()
RETURN_TYPES = DepthAnythingV2Preprocessor.RETURN_TYPES
CATEGORY = "preprocessors/gpu_wrapper"
logger.info("DepthAnythingV2Wrapper loaded successfully")
except (ImportError, KeyError) as e:
logger.warning(f"DepthAnythingV2Preprocessor not available: {e}")
DepthAnythingV2Wrapper = None
# DWPose Wrapper
try:
if 'AUX_NODE_MAPPINGS' not in locals():
from comfyui_controlnet_aux import NODE_CLASS_MAPPINGS as AUX_NODE_MAPPINGS
DWPreprocessor = AUX_NODE_MAPPINGS["DWPreprocessor"]
class DWPreprocessorWrapper(MultiGPUPreprocessorWrapper):
preprocessor_class = DWPreprocessor
def __init__(self):
super().__init__(DWPreprocessor)
@classmethod
def INPUT_TYPES(cls):
return super().INPUT_TYPES()
RETURN_TYPES = DWPreprocessor.RETURN_TYPES
CATEGORY = "preprocessors/gpu_wrapper"
logger.info("DWPreprocessorWrapper loaded successfully")
except (ImportError, KeyError) as e:
logger.warning(f"DWPreprocessor not available: {e}")
DWPreprocessorWrapper = None
# Canny Edge Wrapper
try:
if 'AUX_NODE_MAPPINGS' not in locals():
from comfyui_controlnet_aux import NODE_CLASS_MAPPINGS as AUX_NODE_MAPPINGS
CannyEdgePreprocessor = AUX_NODE_MAPPINGS["CannyEdgePreprocessor"]
class CannyEdgePreprocessorWrapper(MultiGPUPreprocessorWrapper):
preprocessor_class = CannyEdgePreprocessor
def __init__(self):
super().__init__(CannyEdgePreprocessor)
@classmethod
def INPUT_TYPES(cls):
return super().INPUT_TYPES()
RETURN_TYPES = CannyEdgePreprocessor.RETURN_TYPES
CATEGORY = "preprocessors/gpu_wrapper"
logger.info("CannyEdgePreprocessorWrapper loaded successfully")
except (ImportError, KeyError) as e:
logger.warning(f"CannyEdgePreprocessor not available: {e}")
CannyEdgePreprocessorWrapper = None
# OpenPose Wrapper
try:
if 'AUX_NODE_MAPPINGS' not in locals():
from comfyui_controlnet_aux import NODE_CLASS_MAPPINGS as AUX_NODE_MAPPINGS
OpenposePreprocessor = AUX_NODE_MAPPINGS["OpenposePreprocessor"]
class OpenposePreprocessorWrapper(MultiGPUPreprocessorWrapper):
preprocessor_class = OpenposePreprocessor
def __init__(self):
super().__init__(OpenposePreprocessor)
@classmethod
def INPUT_TYPES(cls):
return super().INPUT_TYPES()
RETURN_TYPES = OpenposePreprocessor.RETURN_TYPES
CATEGORY = "preprocessors/gpu_wrapper"
logger.info("OpenposePreprocessorWrapper loaded successfully")
except (ImportError, KeyError) as e:
logger.warning(f"OpenposePreprocessor not available: {e}")
OpenposePreprocessorWrapper = None
# Midas Depth Map Wrapper
try:
if 'AUX_NODE_MAPPINGS' not in locals():
from comfyui_controlnet_aux import NODE_CLASS_MAPPINGS as AUX_NODE_MAPPINGS
MidasDepthMapPreprocessor = AUX_NODE_MAPPINGS["MiDaS-DepthMapPreprocessor"]
class MidasDepthMapWrapper(MultiGPUPreprocessorWrapper):
preprocessor_class = MidasDepthMapPreprocessor
def __init__(self):
super().__init__(MidasDepthMapPreprocessor)
@classmethod
def INPUT_TYPES(cls):
return super().INPUT_TYPES()
RETURN_TYPES = MidasDepthMapPreprocessor.RETURN_TYPES
CATEGORY = "preprocessors/gpu_wrapper"
logger.info("MidasDepthMapWrapper loaded successfully")
except (ImportError, KeyError) as e:
logger.warning(f"MidasDepthMapPreprocessor not available: {e}")
MidasDepthMapWrapper = None
# Registration dictionaries
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
# Only register wrappers for available preprocessors
if DepthAnythingV2Wrapper:
NODE_CLASS_MAPPINGS["DepthAnythingV2Wrapper"] = DepthAnythingV2Wrapper
NODE_DISPLAY_NAME_MAPPINGS["DepthAnythingV2Wrapper"] = "DepthAnything V2 (GPU Wrapper)"
if DWPreprocessorWrapper:
NODE_CLASS_MAPPINGS["DWPreprocessorWrapper"] = DWPreprocessorWrapper
NODE_DISPLAY_NAME_MAPPINGS["DWPreprocessorWrapper"] = "DWPose (GPU Wrapper)"
if CannyEdgePreprocessorWrapper:
NODE_CLASS_MAPPINGS["CannyEdgePreprocessorWrapper"] = CannyEdgePreprocessorWrapper
NODE_DISPLAY_NAME_MAPPINGS["CannyEdgePreprocessorWrapper"] = "Canny Edge (GPU Wrapper)"
if OpenposePreprocessorWrapper:
NODE_CLASS_MAPPINGS["OpenposePreprocessorWrapper"] = OpenposePreprocessorWrapper
NODE_DISPLAY_NAME_MAPPINGS["OpenposePreprocessorWrapper"] = "OpenPose (GPU Wrapper)"
if MidasDepthMapWrapper:
NODE_CLASS_MAPPINGS["MidasDepthMapWrapper"] = MidasDepthMapWrapper
NODE_DISPLAY_NAME_MAPPINGS["MidasDepthMapWrapper"] = "Midas Depth (GPU Wrapper)"
logger.info(f"Registered {len(NODE_CLASS_MAPPINGS)} GPU wrapper nodes: {list(NODE_CLASS_MAPPINGS.keys())}")