ND911 commited on
Commit
455acc7
·
verified ·
1 Parent(s): 8d57e5e

Upload 2 files

Browse files
Files changed (2) hide show
  1. convert_sd3.py +243 -0
  2. nodes.py +465 -0
convert_sd3.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import numpy as np
4
+ import gguf # This needs to be the llama.cpp one specifically!
5
+ import argparse
6
+ from tqdm import tqdm
7
+
8
+ from safetensors.torch import load_file
9
+
10
+ QUANTIZATION_THRESHOLD = 1024
11
+ REARRANGE_THRESHOLD = 512
12
+ MAX_TENSOR_NAME_LENGTH = 127
13
+
14
+
15
+ class QuantError(Exception):
16
+ pass
17
+
18
+ class quants:
19
+ @staticmethod
20
+ def quantize(data, data_qtype):
21
+ # Implement quantization logic here
22
+ if data_qtype == GGMLQuantizationType.F16:
23
+ return data.astype(np.float16)
24
+ elif data_qtype == GGMLQuantizationType.BF16:
25
+ return data.astype(np.float32) # BF16 is not supported by NumPy, so use float32 instead
26
+ else:
27
+ raise QuantError("Unsupported quantization type")
28
+
29
+ class ModelTemplate:
30
+ arch = "invalid" # string describing architecture
31
+ shape_fix = False # whether to reshape tensors
32
+ keys_detect = [] # list of lists to match in state dict
33
+ keys_banned = [] # list of keys that should mark model as invalid for conversion
34
+
35
+ class ModelFlux(ModelTemplate):
36
+ arch = "fluxz"
37
+ keys_detect = [
38
+ ("transformer_blocks.0.attn.norm_added_k.weight",),
39
+ ("double_blocks.0.img_attn.proj.weight",),
40
+ ]
41
+ keys_banned = ["transformer_blocks.0.attn.norm_added_k.weight",]
42
+
43
+ class ModelSD3(ModelTemplate):
44
+ arch = "sd3"
45
+ keys_detect = [
46
+ ("transformer_blocks.0.attn.add_q_proj.weight",),
47
+ ("joint_blocks.0.x_block.attn.qkv.weight",),
48
+ ]
49
+ keys_banned = ["transformer_blocks.0.attn.add_q_proj.weight",]
50
+
51
+ class ModelSDXL(ModelTemplate):
52
+ arch = "sdxl"
53
+ shape_fix = True
54
+ keys_detect = [
55
+ ("down_blocks.0.downsamplers.0.conv.weight", "add_embedding.linear_1.weight",),
56
+ (
57
+ "input_blocks.3.0.op.weight", "input_blocks.6.0.op.weight",
58
+ "output_blocks.2.2.conv.weight", "output_blocks.5.2.conv.weight",
59
+ ), # Non-diffusers
60
+ ("label_emb.0.0.weight",),
61
+ ]
62
+
63
+ class ModelSD1(ModelTemplate):
64
+ arch = "sd1"
65
+ shape_fix = False
66
+ keys_detect = [
67
+ ("down_blocks.0.downsamplers.0.conv.weight",),
68
+ (
69
+ "input_blocks.3.0.op.weight", "input_blocks.6.0.op.weight", "input_blocks.9.0.op.weight",
70
+ "output_blocks.2.1.conv.weight", "output_blocks.5.2.conv.weight", "output_blocks.8.2.conv.weight"
71
+ ), # Non-diffusers
72
+ ]
73
+
74
+ # Prioritize ModelSD3 over ModelFlux
75
+ arch_list = [ModelSD3, ModelFlux, ModelSDXL, ModelSD1]
76
+
77
+ def is_model_arch(model, state_dict):
78
+ # check if model is correct
79
+ matched = False
80
+ invalid = False
81
+ for match_list in model.keys_detect:
82
+ if all(key in state_dict for key in match_list):
83
+ matched = True
84
+ invalid = any(key in state_dict for key in model.keys_banned)
85
+ break
86
+ assert not invalid, "Model architecture not allowed for conversion! (i.e. reference VS diffusers format)"
87
+ return matched
88
+
89
+ def detect_arch(state_dict):
90
+ model_arch = None
91
+ for arch in arch_list:
92
+ if is_model_arch(arch, state_dict):
93
+ model_arch = arch
94
+ break
95
+ assert model_arch is not None, "Unknown model architecture!"
96
+ return model_arch
97
+
98
+ def parse_args():
99
+ parser = argparse.ArgumentParser(description="Generate F16 GGUF files from single UNET")
100
+ parser.add_argument("--src", required=True, help="Source model ckpt file.")
101
+ parser.add_argument("--dst", help="Output unet gguf file.")
102
+ args = parser.parse_args()
103
+
104
+ if not os.path.isfile(args.src):
105
+ parser.error("No input provided!")
106
+
107
+ return args
108
+
109
+ def load_state_dict(path):
110
+ if any(path.endswith(x) for x in [".ckpt", ".pt", ".bin", ".pth"]):
111
+ state_dict = torch.load(path, map_location="cpu", weights_only=True)
112
+ state_dict = state_dict.get("model", state_dict)
113
+ else:
114
+ state_dict = load_file(path)
115
+
116
+ # only keep unet with no prefix!
117
+ sd = {}
118
+ has_prefix = any(["model.diffusion_model." in x for x in state_dict.keys()])
119
+ for k, v in state_dict.items():
120
+ if has_prefix and "model.diffusion_model." not in k:
121
+ continue
122
+ if has_prefix:
123
+ k = k.replace("model.diffusion_model.", "")
124
+ sd[k] = v
125
+
126
+ return sd
127
+
128
+ def load_model(path):
129
+ state_dict = load_state_dict(path)
130
+ model_arch = detect_arch(state_dict)
131
+ print(f"* Architecture detected from input: {model_arch.arch}")
132
+ writer = gguf.GGUFWriter(path=None, arch=model_arch.arch)
133
+ return (writer, state_dict, model_arch)
134
+
135
+ def handle_tensors(args, writer, state_dict, model_arch):
136
+ name_lengths = tuple(sorted(
137
+ ((key, len(key)) for key in state_dict.keys()),
138
+ key=lambda item: item[1],
139
+ reverse=True,
140
+ ))
141
+ if not name_lengths:
142
+ return
143
+ max_name_len = name_lengths[0][1]
144
+ if max_name_len > MAX_TENSOR_NAME_LENGTH:
145
+ bad_list = ", ".join(f"{key!r} ({namelen})" for key, namelen in name_lengths if namelen > MAX_TENSOR_NAME_LENGTH)
146
+ raise ValueError(f"Can only handle tensor names up to {MAX_TENSOR_NAME_LENGTH} characters. Tensors exceeding the limit: {bad_list}")
147
+ for key, data in tqdm(state_dict.items()):
148
+ old_dtype = data.dtype
149
+
150
+ if data.dtype == torch.bfloat16:
151
+ data = data.to(torch.float32).numpy()
152
+ # this is so we don't break torch 2.0.X
153
+ elif data.dtype in [getattr(torch, "float8_e4m3fn", "_invalid"), getattr(torch, "float8_e5m2", "_invalid")]:
154
+ data = data.to(torch.float16).numpy()
155
+ else:
156
+ data = data.numpy()
157
+
158
+ n_dims = len(data.shape)
159
+ data_shape = data.shape
160
+ data_qtype = getattr(
161
+ gguf.GGMLQuantizationType,
162
+ "BF16" if old_dtype == torch.bfloat16 else "F16"
163
+ )
164
+
165
+ # get number of parameters (AKA elements) in this tensor
166
+ n_params = 1
167
+ for dim_size in data_shape:
168
+ n_params *= dim_size
169
+
170
+ # keys to keep as max precision
171
+ blacklist = {
172
+ "time_embedding.",
173
+ "add_embedding.",
174
+ "time_in.",
175
+ "txt_in.",
176
+ "vector_in.",
177
+ "img_in.",
178
+ "guidance_in.",
179
+ "final_layer.",
180
+ }
181
+
182
+ if old_dtype in (torch.float32, torch.bfloat16):
183
+ if n_dims == 1:
184
+ # one-dimensional tensors should be kept in F32
185
+ # also speeds up inference due to not dequantizing
186
+ data_qtype = gguf.GGMLQuantizationType.F32
187
+
188
+ elif n_params <= QUANTIZATION_THRESHOLD:
189
+ # very small tensors
190
+ data_qtype = gguf.GGMLQuantizationType.F32
191
+
192
+ elif ".weight" in key and any(x in key for x in blacklist):
193
+ data_qtype = gguf.GGMLQuantizationType.F32
194
+
195
+ if (model_arch.shape_fix # NEVER reshape for models such as flux
196
+ and n_dims > 1 # Skip one-dimensional tensors
197
+ and n_params >= REARRANGE_THRESHOLD # Only rearrange tensors meeting the size requirement
198
+ and (n_params / 256).is_integer() # Rearranging only makes sense if total elements is divisible by 256
199
+ and not (data.shape[-1] / 256).is_integer() # Only need to rearrange if the last dimension is not divisible by 256
200
+ ):
201
+ orig_shape = data.shape
202
+ data = data.reshape(n_params // 256, 256)
203
+ writer.add_array(f"comfy.gguf.orig_shape.{key}", tuple(int(dim) for dim in orig_shape))
204
+
205
+ new_name = key # do we need to rename?
206
+
207
+ shape_str = f"{{{', '.join(str(n) for n in reversed(data.shape))}}}"
208
+ tqdm.write(f"{f'%-{max_name_len + 4}s' % f'{new_name}'} {old_dtype} --> {data_qtype.name}, shape = {shape_str}")
209
+
210
+ writer.add_tensor(new_name, data, raw_dtype=data_qtype)
211
+
212
+
213
+
214
+ def load_model(path):
215
+ state_dict = load_state_dict(path)
216
+ model_arch = detect_arch(state_dict)
217
+ print(f"* Architecture detected from input: {model_arch.arch}")
218
+ return state_dict, model_arch
219
+
220
+ ...
221
+
222
+ if __name__ == "__main__":
223
+ args = parse_args()
224
+ path = args.src
225
+ state_dict, model_arch = load_model(path)
226
+
227
+ if next(iter(state_dict.values())).dtype == torch.bfloat16:
228
+ out_path = f"{os.path.splitext(path)[0]}-BF16.gguf"
229
+ else:
230
+ out_path = f"{os.path.splitext(path)[0]}-F16.gguf"
231
+
232
+ out_path = args.dst or out_path
233
+ if os.path.isfile(out_path):
234
+ input("Output exists enter to continue or ctrl+c to abort!")
235
+
236
+ writer = gguf.GGUFWriter(path=out_path, arch=model_arch.arch)
237
+ writer.add_quantization_version(1)
238
+
239
+ handle_tensors(args, writer, state_dict, model_arch)
240
+ writer.write_header_to_file()
241
+ writer.write_kv_data_to_file()
242
+ writer.write_tensors_to_file()
243
+ writer.close()
nodes.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", "t5", "t5encoder", "sd3"}:
66
+ raise ValueError(f"Unexpected architecture type in GGUF file, expected one of flux, sd1, sdxl, t5encoder, sd3 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
+ class UnetLoaderSD3GGUF(UnetLoaderGGUF):
397
+ @classmethod
398
+ def INPUT_TYPES(s):
399
+ unet_names = [x for x in folder_paths.get_filename_list("unet_gguf")]
400
+ return {
401
+ "required": {
402
+ "unet_name": (unet_names,),
403
+ }
404
+ }
405
+
406
+ RETURN_TYPES = ("MODEL",)
407
+ FUNCTION = "load_unet"
408
+ CATEGORY = "bootleg"
409
+ TITLE = "Unet Loader SD3 (GGUF)"
410
+
411
+ def load_unet(self, unet_name, dequant_dtype=None, patch_dtype=None, patch_on_device=None):
412
+ ops = GGMLOps()
413
+
414
+ if dequant_dtype in ("default", None):
415
+ ops.Linear.dequant_dtype = None
416
+ elif dequant_dtype in ["target"]:
417
+ ops.Linear.dequant_dtype = dequant_dtype
418
+ else:
419
+ ops.Linear.dequant_dtype = getattr(torch, dequant_dtype)
420
+
421
+ if patch_dtype in ("default", None):
422
+ ops.Linear.patch_dtype = None
423
+ elif patch_dtype in ["target"]:
424
+ ops.Linear.patch_dtype = patch_dtype
425
+ else:
426
+ ops.Linear.patch_dtype = getattr(torch, patch_dtype)
427
+
428
+ # init model
429
+ unet_path = folder_paths.get_full_path("unet", unet_name)
430
+ sd = gguf_sd_loader(unet_path)
431
+ model = comfy.sd.load_diffusion_model_state_dict(
432
+ sd, model_options={"custom_operations": ops, "model_type": "sd3"}
433
+ )
434
+ if model is None:
435
+ logging.error("ERROR UNSUPPORTED UNET {}".format(unet_path))
436
+ raise RuntimeError("ERROR: Could not detect model type of: {}".format(unet_path))
437
+ model = GGUFModelPatcher.clone(model)
438
+ model.patch_on_device = patch_on_device
439
+ return (model,)
440
+
441
+ class UnetLoaderSD3GGUFAdvanced(UnetLoaderSD3GGUF):
442
+ @classmethod
443
+ def INPUT_TYPES(s):
444
+ unet_names = [x for x in folder_paths.get_filename_list("unet_gguf")]
445
+ return {
446
+ "required": {
447
+ "unet_name": (unet_names,),
448
+ "dequant_dtype": (["default", "target", "float32", "float16", "bfloat16"], {"default": "default"}),
449
+ "patch_dtype": (["default", "target", "float32", "float16", "bfloat16"], {"default": "default"}),
450
+ "patch_on_device": ("BOOLEAN", {"default": False}),
451
+ }
452
+ }
453
+ TITLE = "Unet Loader SD3 (GGUF/Advanced)"
454
+
455
+
456
+
457
+ NODE_CLASS_MAPPINGS = {
458
+ "UnetLoaderGGUF": UnetLoaderGGUF,
459
+ "CLIPLoaderGGUF": CLIPLoaderGGUF,
460
+ "DualCLIPLoaderGGUF": DualCLIPLoaderGGUF,
461
+ "TripleCLIPLoaderGGUF": TripleCLIPLoaderGGUF,
462
+ "UnetLoaderGGUFAdvanced": UnetLoaderGGUFAdvanced,
463
+ "UnetLoaderSD3GGUF": UnetLoaderSD3GGUF,
464
+ "UnetLoaderSD3GGUFAdvanced": UnetLoaderSD3GGUFAdvanced,
465
+ }