ND911 commited on
Commit
bdbb9b0
1 Parent(s): ac81ef9

added the official nodes.py file from city96 as he updated it to work with sd3

Browse files
Files changed (1) hide show
  1. nodes.py +402 -0
nodes.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import torch
3
+ import gguf
4
+ import copy
5
+ import logging
6
+
7
+ import comfy.sd
8
+ import comfy.utils
9
+ import comfy.model_management
10
+ import comfy.model_patcher
11
+ import folder_paths
12
+
13
+ from .ops import GGMLTensor, GGMLOps, move_patch_to_device
14
+ from .dequant import is_quantized, is_torch_compatible
15
+
16
+ # Add a custom keys for files ending in .gguf
17
+ if "unet_gguf" not in folder_paths.folder_names_and_paths:
18
+ orig = folder_paths.folder_names_and_paths.get("diffusion_models", folder_paths.folder_names_and_paths.get("unet", [[], set()]))
19
+ folder_paths.folder_names_and_paths["unet_gguf"] = (orig[0], {".gguf"})
20
+
21
+ if "clip_gguf" not in folder_paths.folder_names_and_paths:
22
+ orig = folder_paths.folder_names_and_paths.get("clip", [[], set()])
23
+ folder_paths.folder_names_and_paths["clip_gguf"] = (orig[0], {".gguf"})
24
+
25
+ def gguf_sd_loader_get_orig_shape(reader, tensor_name):
26
+ field_key = f"comfy.gguf.orig_shape.{tensor_name}"
27
+ field = reader.get_field(field_key)
28
+ if field is None:
29
+ return None
30
+ # Has original shape metadata, so we try to decode it.
31
+ if len(field.types) != 2 or field.types[0] != gguf.GGUFValueType.ARRAY or field.types[1] != gguf.GGUFValueType.INT32:
32
+ raise TypeError(f"Bad original shape metadata for {field_key}: Expected ARRAY of INT32, got {field.types}")
33
+ return torch.Size(tuple(int(field.parts[part_idx][0]) for part_idx in field.data))
34
+
35
+ def gguf_sd_loader(path, handle_prefix="model.diffusion_model."):
36
+ """
37
+ Read state dict as fake tensors
38
+ """
39
+ reader = gguf.GGUFReader(path)
40
+
41
+ # filter and strip prefix
42
+ has_prefix = False
43
+ if handle_prefix is not None:
44
+ prefix_len = len(handle_prefix)
45
+ tensor_names = set(tensor.name for tensor in reader.tensors)
46
+ has_prefix = any(s.startswith(handle_prefix) for s in tensor_names)
47
+
48
+ tensors = []
49
+ for tensor in reader.tensors:
50
+ sd_key = tensor_name = tensor.name
51
+ if has_prefix:
52
+ if not tensor_name.startswith(handle_prefix):
53
+ continue
54
+ sd_key = tensor_name[prefix_len:]
55
+ tensors.append((sd_key, tensor))
56
+
57
+ # detect and verify architecture
58
+ compat = None
59
+ arch_str = None
60
+ arch_field = reader.get_field("general.architecture")
61
+ if arch_field is not None:
62
+ if len(arch_field.types) != 1 or arch_field.types[0] != gguf.GGUFValueType.STRING:
63
+ raise TypeError(f"Bad type for GGUF general.architecture key: expected string, got {arch_field.types!r}")
64
+ arch_str = str(arch_field.parts[arch_field.data[-1]], encoding="utf-8")
65
+ if arch_str not in {"flux", "sd1", "sdxl", "sd3", "t5", "t5encoder"}:
66
+ raise ValueError(f"Unexpected architecture type in GGUF file, expected one of flux, sd1, sdxl, t5encoder but got {arch_str!r}")
67
+ else: # stable-diffusion.cpp
68
+ # import here to avoid changes to convert.py breaking regular models
69
+ from .tools.convert import detect_arch
70
+ arch_str = detect_arch(set(val[0] for val in tensors)).arch
71
+ compat = "sd.cpp"
72
+
73
+ # main loading loop
74
+ state_dict = {}
75
+ qtype_dict = {}
76
+ for sd_key, tensor in tensors:
77
+ tensor_name = tensor.name
78
+ tensor_type_str = str(tensor.tensor_type)
79
+ torch_tensor = torch.from_numpy(tensor.data) # mmap
80
+
81
+ shape = gguf_sd_loader_get_orig_shape(reader, tensor_name)
82
+ if shape is None:
83
+ shape = torch.Size(tuple(int(v) for v in reversed(tensor.shape)))
84
+ # Workaround for stable-diffusion.cpp SDXL detection.
85
+ if compat == "sd.cpp" and arch_str == "sdxl":
86
+ if any([tensor_name.endswith(x) for x in (".proj_in.weight", ".proj_out.weight")]):
87
+ while len(shape) > 2 and shape[-1] == 1:
88
+ shape = shape[:-1]
89
+
90
+ # add to state dict
91
+ if tensor.tensor_type in {gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16}:
92
+ torch_tensor = torch_tensor.view(*shape)
93
+ state_dict[sd_key] = GGMLTensor(torch_tensor, tensor_type=tensor.tensor_type, tensor_shape=shape)
94
+ qtype_dict[tensor_type_str] = qtype_dict.get(tensor_type_str, 0) + 1
95
+
96
+ # sanity check debug print
97
+ print("\nggml_sd_loader:")
98
+ for k,v in qtype_dict.items():
99
+ print(f" {k:30}{v:3}")
100
+
101
+ return state_dict
102
+
103
+ # for remapping llama.cpp -> original key names
104
+ clip_sd_map = {
105
+ "enc.": "encoder.",
106
+ ".blk.": ".block.",
107
+ "token_embd": "shared",
108
+ "output_norm": "final_layer_norm",
109
+ "attn_q": "layer.0.SelfAttention.q",
110
+ "attn_k": "layer.0.SelfAttention.k",
111
+ "attn_v": "layer.0.SelfAttention.v",
112
+ "attn_o": "layer.0.SelfAttention.o",
113
+ "attn_norm": "layer.0.layer_norm",
114
+ "attn_rel_b": "layer.0.SelfAttention.relative_attention_bias",
115
+ "ffn_up": "layer.1.DenseReluDense.wi_1",
116
+ "ffn_down": "layer.1.DenseReluDense.wo",
117
+ "ffn_gate": "layer.1.DenseReluDense.wi_0",
118
+ "ffn_norm": "layer.1.layer_norm",
119
+ }
120
+
121
+ def gguf_clip_loader(path):
122
+ raw_sd = gguf_sd_loader(path)
123
+ assert "enc.blk.23.ffn_up.weight" in raw_sd, "Invalid Text Encoder!"
124
+ sd = {}
125
+ for k,v in raw_sd.items():
126
+ for s,d in clip_sd_map.items():
127
+ k = k.replace(s,d)
128
+ sd[k] = v
129
+ return sd
130
+
131
+ # TODO: Temporary fix for now
132
+ import collections
133
+ class GGUFModelPatcher(comfy.model_patcher.ModelPatcher):
134
+ patch_on_device = False
135
+
136
+ def patch_weight_to_device(self, key, device_to=None, inplace_update=False):
137
+ if key not in self.patches:
138
+ return
139
+ weight = comfy.utils.get_attr(self.model, key)
140
+
141
+ try:
142
+ from comfy.lora import calculate_weight
143
+ except Exception:
144
+ calculate_weight = self.calculate_weight
145
+
146
+ patches = self.patches[key]
147
+ if is_quantized(weight):
148
+ out_weight = weight.to(device_to)
149
+ patches = move_patch_to_device(patches, self.load_device if self.patch_on_device else self.offload_device)
150
+ # TODO: do we ever have legitimate duplicate patches? (i.e. patch on top of patched weight)
151
+ out_weight.patches = [(calculate_weight, patches, key)]
152
+ else:
153
+ inplace_update = self.weight_inplace_update or inplace_update
154
+ if key not in self.backup:
155
+ self.backup[key] = collections.namedtuple('Dimension', ['weight', 'inplace_update'])(
156
+ weight.to(device=self.offload_device, copy=inplace_update), inplace_update
157
+ )
158
+
159
+ if device_to is not None:
160
+ temp_weight = comfy.model_management.cast_to_device(weight, device_to, torch.float32, copy=True)
161
+ else:
162
+ temp_weight = weight.to(torch.float32, copy=True)
163
+
164
+ out_weight = calculate_weight(patches, temp_weight, key)
165
+ out_weight = comfy.float.stochastic_rounding(out_weight, weight.dtype)
166
+
167
+ if inplace_update:
168
+ comfy.utils.copy_to_param(self.model, key, out_weight)
169
+ else:
170
+ comfy.utils.set_attr_param(self.model, key, out_weight)
171
+
172
+ def unpatch_model(self, device_to=None, unpatch_weights=True):
173
+ if unpatch_weights:
174
+ for p in self.model.parameters():
175
+ if is_torch_compatible(p):
176
+ continue
177
+ patches = getattr(p, "patches", [])
178
+ if len(patches) > 0:
179
+ p.patches = []
180
+ # TODO: Find another way to not unload after patches
181
+ return super().unpatch_model(device_to=device_to, unpatch_weights=unpatch_weights)
182
+
183
+ mmap_released = False
184
+ def load(self, *args, force_patch_weights=False, **kwargs):
185
+ # always call `patch_weight_to_device` even for lowvram
186
+ super().load(*args, force_patch_weights=True, **kwargs)
187
+
188
+ # make sure nothing stays linked to mmap after first load
189
+ if not self.mmap_released:
190
+ linked = []
191
+ if kwargs.get("lowvram_model_memory", 0) > 0:
192
+ for n, m in self.model.named_modules():
193
+ if hasattr(m, "weight"):
194
+ device = getattr(m.weight, "device", None)
195
+ if device == self.offload_device:
196
+ linked.append((n, m))
197
+ continue
198
+ if hasattr(m, "bias"):
199
+ device = getattr(m.bias, "device", None)
200
+ if device == self.offload_device:
201
+ linked.append((n, m))
202
+ continue
203
+ if linked:
204
+ print(f"Attempting to release mmap ({len(linked)})")
205
+ for n, m in linked:
206
+ # TODO: possible to OOM, find better way to detach
207
+ m.to(self.load_device).to(self.offload_device)
208
+ self.mmap_released = True
209
+
210
+ def clone(self, *args, **kwargs):
211
+ n = GGUFModelPatcher(self.model, self.load_device, self.offload_device, self.size, weight_inplace_update=self.weight_inplace_update)
212
+ n.patches = {}
213
+ for k in self.patches:
214
+ n.patches[k] = self.patches[k][:]
215
+ n.patches_uuid = self.patches_uuid
216
+
217
+ n.object_patches = self.object_patches.copy()
218
+ n.model_options = copy.deepcopy(self.model_options)
219
+ n.backup = self.backup
220
+ n.object_patches_backup = self.object_patches_backup
221
+ n.patch_on_device = getattr(self, "patch_on_device", False)
222
+ return n
223
+
224
+ class UnetLoaderGGUF:
225
+ @classmethod
226
+ def INPUT_TYPES(s):
227
+ unet_names = [x for x in folder_paths.get_filename_list("unet_gguf")]
228
+ return {
229
+ "required": {
230
+ "unet_name": (unet_names,),
231
+ }
232
+ }
233
+
234
+ RETURN_TYPES = ("MODEL",)
235
+ FUNCTION = "load_unet"
236
+ CATEGORY = "bootleg"
237
+ TITLE = "Unet Loader (GGUF)"
238
+
239
+ def load_unet(self, unet_name, dequant_dtype=None, patch_dtype=None, patch_on_device=None):
240
+ ops = GGMLOps()
241
+
242
+ if dequant_dtype in ("default", None):
243
+ ops.Linear.dequant_dtype = None
244
+ elif dequant_dtype in ["target"]:
245
+ ops.Linear.dequant_dtype = dequant_dtype
246
+ else:
247
+ ops.Linear.dequant_dtype = getattr(torch, dequant_dtype)
248
+
249
+ if patch_dtype in ("default", None):
250
+ ops.Linear.patch_dtype = None
251
+ elif patch_dtype in ["target"]:
252
+ ops.Linear.patch_dtype = patch_dtype
253
+ else:
254
+ ops.Linear.patch_dtype = getattr(torch, patch_dtype)
255
+
256
+ # init model
257
+ unet_path = folder_paths.get_full_path("unet", unet_name)
258
+ sd = gguf_sd_loader(unet_path)
259
+ model = comfy.sd.load_diffusion_model_state_dict(
260
+ sd, model_options={"custom_operations": ops}
261
+ )
262
+ if model is None:
263
+ logging.error("ERROR UNSUPPORTED UNET {}".format(unet_path))
264
+ raise RuntimeError("ERROR: Could not detect model type of: {}".format(unet_path))
265
+ model = GGUFModelPatcher.clone(model)
266
+ model.patch_on_device = patch_on_device
267
+ return (model,)
268
+
269
+ class UnetLoaderGGUFAdvanced(UnetLoaderGGUF):
270
+ @classmethod
271
+ def INPUT_TYPES(s):
272
+ unet_names = [x for x in folder_paths.get_filename_list("unet_gguf")]
273
+ return {
274
+ "required": {
275
+ "unet_name": (unet_names,),
276
+ "dequant_dtype": (["default", "target", "float32", "float16", "bfloat16"], {"default": "default"}),
277
+ "patch_dtype": (["default", "target", "float32", "float16", "bfloat16"], {"default": "default"}),
278
+ "patch_on_device": ("BOOLEAN", {"default": False}),
279
+ }
280
+ }
281
+ TITLE = "Unet Loader (GGUF/Advanced)"
282
+
283
+ clip_name_dict = {
284
+ "stable_diffusion": comfy.sd.CLIPType.STABLE_DIFFUSION,
285
+ "stable_cascade": comfy.sd.CLIPType.STABLE_CASCADE,
286
+ "stable_audio": comfy.sd.CLIPType.STABLE_AUDIO,
287
+ "sdxl": comfy.sd.CLIPType.STABLE_DIFFUSION,
288
+ "sd3": comfy.sd.CLIPType.SD3,
289
+ "flux": comfy.sd.CLIPType.FLUX,
290
+ }
291
+
292
+ class CLIPLoaderGGUF:
293
+ @classmethod
294
+ def INPUT_TYPES(s):
295
+ return {
296
+ "required": {
297
+ "clip_name": (s.get_filename_list(),),
298
+ "type": (["stable_diffusion", "stable_cascade", "sd3", "stable_audio"],),
299
+ }
300
+ }
301
+
302
+ RETURN_TYPES = ("CLIP",)
303
+ FUNCTION = "load_clip"
304
+ CATEGORY = "bootleg"
305
+ TITLE = "CLIPLoader (GGUF)"
306
+
307
+ @classmethod
308
+ def get_filename_list(s):
309
+ files = []
310
+ files += folder_paths.get_filename_list("clip")
311
+ files += folder_paths.get_filename_list("clip_gguf")
312
+ return sorted(files)
313
+
314
+ def load_data(self, ckpt_paths):
315
+ clip_data = []
316
+ for p in ckpt_paths:
317
+ if p.endswith(".gguf"):
318
+ clip_data.append(gguf_clip_loader(p))
319
+ else:
320
+ sd = comfy.utils.load_torch_file(p, safe_load=True)
321
+ clip_data.append(
322
+ {k:GGMLTensor(v, tensor_type=gguf.GGMLQuantizationType.F16, tensor_shape=v.shape) for k,v in sd.items()}
323
+ )
324
+ return clip_data
325
+
326
+ def load_patcher(self, clip_paths, clip_type, clip_data):
327
+ clip = comfy.sd.load_text_encoder_state_dicts(
328
+ clip_type = clip_type,
329
+ state_dicts = clip_data,
330
+ model_options = {
331
+ "custom_operations": GGMLOps,
332
+ "initial_device": comfy.model_management.text_encoder_offload_device()
333
+ },
334
+ embedding_directory = folder_paths.get_folder_paths("embeddings"),
335
+ )
336
+ clip.patcher = GGUFModelPatcher.clone(clip.patcher)
337
+
338
+ # for some reason this is just missing in some SAI checkpoints
339
+ if getattr(clip.cond_stage_model, "clip_l", None) is not None:
340
+ if getattr(clip.cond_stage_model.clip_l.transformer.text_projection.weight, "tensor_shape", None) is None:
341
+ clip.cond_stage_model.clip_l.transformer.text_projection = comfy.ops.manual_cast.Linear(768, 768)
342
+ if getattr(clip.cond_stage_model, "clip_g", None) is not None:
343
+ if getattr(clip.cond_stage_model.clip_g.transformer.text_projection.weight, "tensor_shape", None) is None:
344
+ clip.cond_stage_model.clip_g.transformer.text_projection = comfy.ops.manual_cast.Linear(1280, 1280)
345
+
346
+ return clip
347
+
348
+ def load_clip(self, clip_name, type="stable_diffusion"):
349
+ clip_path = folder_paths.get_full_path("clip", clip_name)
350
+ clip_type = clip_name_dict.get(type, comfy.sd.CLIPType.STABLE_DIFFUSION)
351
+ return (self.load_patcher([clip_path], clip_type, self.load_data([clip_path])),)
352
+
353
+ class DualCLIPLoaderGGUF(CLIPLoaderGGUF):
354
+ @classmethod
355
+ def INPUT_TYPES(s):
356
+ file_options = (s.get_filename_list(), )
357
+ return {
358
+ "required": {
359
+ "clip_name1": file_options,
360
+ "clip_name2": file_options,
361
+ "type": (("sdxl", "sd3", "flux"), ),
362
+ }
363
+ }
364
+
365
+ TITLE = "DualCLIPLoader (GGUF)"
366
+
367
+ def load_clip(self, clip_name1, clip_name2, type):
368
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
369
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
370
+ clip_paths = (clip_path1, clip_path2)
371
+ clip_type = clip_name_dict.get(type, comfy.sd.CLIPType.STABLE_DIFFUSION)
372
+ return (self.load_patcher(clip_paths, clip_type, self.load_data(clip_paths)),)
373
+
374
+ class TripleCLIPLoaderGGUF(CLIPLoaderGGUF):
375
+ @classmethod
376
+ def INPUT_TYPES(s):
377
+ file_options = (s.get_filename_list(), )
378
+ return {
379
+ "required": {
380
+ "clip_name1": file_options,
381
+ "clip_name2": file_options,
382
+ "clip_name3": file_options,
383
+ }
384
+ }
385
+
386
+ TITLE = "TripleCLIPLoader (GGUF)"
387
+
388
+ def load_clip(self, clip_name1, clip_name2, clip_name3, type="sd3"):
389
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
390
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
391
+ clip_path3 = folder_paths.get_full_path("clip", clip_name3)
392
+ clip_paths = (clip_path1, clip_path2, clip_path3)
393
+ clip_type = clip_name_dict.get(type, comfy.sd.CLIPType.STABLE_DIFFUSION)
394
+ return (self.load_patcher(clip_paths, clip_type, self.load_data(clip_paths)),)
395
+
396
+ NODE_CLASS_MAPPINGS = {
397
+ "UnetLoaderGGUF": UnetLoaderGGUF,
398
+ "CLIPLoaderGGUF": CLIPLoaderGGUF,
399
+ "DualCLIPLoaderGGUF": DualCLIPLoaderGGUF,
400
+ "TripleCLIPLoaderGGUF": TripleCLIPLoaderGGUF,
401
+ "UnetLoaderGGUFAdvanced": UnetLoaderGGUFAdvanced,
402
+ }