sanjayxm commited on
Commit
757ccb1
1 Parent(s): 7aec9aa

Upload pulidflux.py

Browse files
Files changed (1) hide show
  1. pulidflux.py +419 -0
pulidflux.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ from torch import nn, Tensor
4
+ from torchvision import transforms
5
+ from torchvision.transforms import functional
6
+ import os
7
+ import logging
8
+ import folder_paths
9
+ import comfy.utils
10
+ from comfy.ldm.flux.layers import timestep_embedding
11
+ from insightface.app import FaceAnalysis
12
+ from facexlib.parsing import init_parsing_model
13
+ from facexlib.utils.face_restoration_helper import FaceRestoreHelper
14
+
15
+ from .eva_clip.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
16
+ from .encoders_flux import IDFormer, PerceiverAttentionCA
17
+
18
+ INSIGHTFACE_DIR = os.path.join(folder_paths.models_dir, "insightface")
19
+
20
+ MODELS_DIR = os.path.join(folder_paths.models_dir, "pulid")
21
+ if "pulid" not in folder_paths.folder_names_and_paths:
22
+ current_paths = [MODELS_DIR]
23
+ else:
24
+ current_paths, _ = folder_paths.folder_names_and_paths["pulid"]
25
+ folder_paths.folder_names_and_paths["pulid"] = (current_paths, folder_paths.supported_pt_extensions)
26
+
27
+ class PulidFluxModel(nn.Module):
28
+ def __init__(self):
29
+ super().__init__()
30
+
31
+ self.double_interval = 2
32
+ self.single_interval = 4
33
+
34
+ # Init encoder
35
+ self.pulid_encoder = IDFormer()
36
+
37
+ # Init attention
38
+ num_ca = 19 // self.double_interval + 38 // self.single_interval
39
+ if 19 % self.double_interval != 0:
40
+ num_ca += 1
41
+ if 38 % self.single_interval != 0:
42
+ num_ca += 1
43
+ self.pulid_ca = nn.ModuleList([
44
+ PerceiverAttentionCA() for _ in range(num_ca)
45
+ ])
46
+
47
+ def from_pretrained(self, path: str):
48
+ state_dict = comfy.utils.load_torch_file(path, safe_load=True)
49
+ state_dict_dict = {}
50
+ for k, v in state_dict.items():
51
+ module = k.split('.')[0]
52
+ state_dict_dict.setdefault(module, {})
53
+ new_k = k[len(module) + 1:]
54
+ state_dict_dict[module][new_k] = v
55
+
56
+ for module in state_dict_dict:
57
+ getattr(self, module).load_state_dict(state_dict_dict[module], strict=True)
58
+
59
+ del state_dict
60
+ del state_dict_dict
61
+
62
+ def get_embeds(self, face_embed, clip_embeds):
63
+ return self.pulid_encoder(face_embed, clip_embeds)
64
+
65
+ def forward_orig(
66
+ self,
67
+ img: Tensor,
68
+ img_ids: Tensor,
69
+ txt: Tensor,
70
+ txt_ids: Tensor,
71
+ timesteps: Tensor,
72
+ y: Tensor,
73
+ guidance: Tensor = None,
74
+ control=None,
75
+ ) -> Tensor:
76
+ if img.ndim != 3 or txt.ndim != 3:
77
+ raise ValueError("Input img and txt tensors must have 3 dimensions.")
78
+
79
+ # running on sequences img
80
+ img = self.img_in(img)
81
+ vec = self.time_in(timestep_embedding(timesteps, 256).to(img.dtype))
82
+ if self.params.guidance_embed:
83
+ if guidance is None:
84
+ raise ValueError("Didn't get guidance strength for guidance distilled model.")
85
+ vec = vec + self.guidance_in(timestep_embedding(guidance, 256).to(img.dtype))
86
+
87
+ vec = vec + self.vector_in(y)
88
+ txt = self.txt_in(txt)
89
+
90
+ ids = torch.cat((txt_ids, img_ids), dim=1)
91
+ pe = self.pe_embedder(ids)
92
+
93
+ ca_idx = 0
94
+ for i, block in enumerate(self.double_blocks):
95
+ img, txt = block(img=img, txt=txt, vec=vec, pe=pe)
96
+
97
+ if control is not None: # Controlnet
98
+ control_i = control.get("input")
99
+ if i < len(control_i):
100
+ add = control_i[i]
101
+ if add is not None:
102
+ img += add
103
+
104
+ # PuLID attention
105
+ if self.pulid_data:
106
+ if i % self.pulid_double_interval == 0:
107
+ # Will calculate influence of all pulid nodes at once
108
+ for _, node_data in self.pulid_data.items():
109
+ if torch.any((node_data['sigma_start'] >= timesteps) & (timesteps >= node_data['sigma_end'])):
110
+ img = img + node_data['weight'] * self.pulid_ca[ca_idx](node_data['embedding'], img)
111
+ ca_idx += 1
112
+
113
+ img = torch.cat((txt, img), 1)
114
+
115
+ for i, block in enumerate(self.single_blocks):
116
+ img = block(img, vec=vec, pe=pe)
117
+
118
+ if control is not None: # Controlnet
119
+ control_o = control.get("output")
120
+ if i < len(control_o):
121
+ add = control_o[i]
122
+ if add is not None:
123
+ img[:, txt.shape[1] :, ...] += add
124
+
125
+ # PuLID attention
126
+ if self.pulid_data:
127
+ real_img, txt = img[:, txt.shape[1]:, ...], img[:, :txt.shape[1], ...]
128
+ if i % self.pulid_single_interval == 0:
129
+ # Will calculate influence of all nodes at once
130
+ for _, node_data in self.pulid_data.items():
131
+ if torch.any((node_data['sigma_start'] >= timesteps) & (timesteps >= node_data['sigma_end'])):
132
+ real_img = real_img + node_data['weight'] * self.pulid_ca[ca_idx](node_data['embedding'], real_img)
133
+ ca_idx += 1
134
+ img = torch.cat((txt, real_img), 1)
135
+
136
+ img = img[:, txt.shape[1] :, ...]
137
+
138
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
139
+ return img
140
+
141
+ def tensor_to_image(tensor):
142
+ image = tensor.mul(255).clamp(0, 255).byte().cpu()
143
+ image = image[..., [2, 1, 0]].numpy()
144
+ return image
145
+
146
+ def image_to_tensor(image):
147
+ tensor = torch.clamp(torch.from_numpy(image).float() / 255., 0, 1)
148
+ tensor = tensor[..., [2, 1, 0]]
149
+ return tensor
150
+
151
+ def to_gray(img):
152
+ x = 0.299 * img[:, 0:1] + 0.587 * img[:, 1:2] + 0.114 * img[:, 2:3]
153
+ x = x.repeat(1, 3, 1, 1)
154
+ return x
155
+
156
+ """
157
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
158
+ Nodes
159
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
160
+ """
161
+
162
+ class PulidFluxModelLoader:
163
+ @classmethod
164
+ def INPUT_TYPES(s):
165
+ return {"required": {"pulid_file": (folder_paths.get_filename_list("pulid"), )}}
166
+
167
+ RETURN_TYPES = ("PULIDFLUX",)
168
+ FUNCTION = "load_model"
169
+ CATEGORY = "pulid"
170
+
171
+ def load_model(self, pulid_file):
172
+ model_path = folder_paths.get_full_path("pulid", pulid_file)
173
+
174
+ # Also initialize the model, takes longer to load but then it doesn't have to be done every time you change parameters in the apply node
175
+ model = PulidFluxModel()
176
+
177
+ logging.info("Loading PuLID-Flux model.")
178
+ model.from_pretrained(path=model_path)
179
+
180
+ return (model,)
181
+
182
+ class PulidFluxInsightFaceLoader:
183
+ @classmethod
184
+ def INPUT_TYPES(s):
185
+ return {
186
+ "required": {
187
+ "provider": (["CPU", "CUDA", "ROCM"], ),
188
+ },
189
+ }
190
+
191
+ RETURN_TYPES = ("FACEANALYSIS",)
192
+ FUNCTION = "load_insightface"
193
+ CATEGORY = "pulid"
194
+
195
+ def load_insightface(self, provider):
196
+ model = FaceAnalysis(name="antelopev2", root=INSIGHTFACE_DIR, providers=[provider + 'ExecutionProvider',]) # alternative to buffalo_l
197
+ model.prepare(ctx_id=0, det_size=(640, 640))
198
+
199
+ return (model,)
200
+
201
+ class PulidFluxEvaClipLoader:
202
+ @classmethod
203
+ def INPUT_TYPES(s):
204
+ return {
205
+ "required": {},
206
+ }
207
+
208
+ RETURN_TYPES = ("EVA_CLIP",)
209
+ FUNCTION = "load_eva_clip"
210
+ CATEGORY = "pulid"
211
+
212
+ def load_eva_clip(self):
213
+ from .eva_clip.factory import create_model_and_transforms
214
+
215
+ model, _, _ = create_model_and_transforms('EVA02-CLIP-L-14-336', 'eva_clip', force_custom_clip=True)
216
+
217
+ model = model.visual
218
+
219
+ eva_transform_mean = getattr(model, 'image_mean', OPENAI_DATASET_MEAN)
220
+ eva_transform_std = getattr(model, 'image_std', OPENAI_DATASET_STD)
221
+ if not isinstance(eva_transform_mean, (list, tuple)):
222
+ model["image_mean"] = (eva_transform_mean,) * 3
223
+ if not isinstance(eva_transform_std, (list, tuple)):
224
+ model["image_std"] = (eva_transform_std,) * 3
225
+
226
+ return (model,)
227
+
228
+ class ApplyPulidFlux:
229
+ @classmethod
230
+ def INPUT_TYPES(s):
231
+ return {
232
+ "required": {
233
+ "model": ("MODEL", ),
234
+ "pulid_flux": ("PULIDFLUX", ),
235
+ "eva_clip": ("EVA_CLIP", ),
236
+ "face_analysis": ("FACEANALYSIS", ),
237
+ "image": ("IMAGE", ),
238
+ "weight": ("FLOAT", {"default": 1.0, "min": -1.0, "max": 5.0, "step": 0.05 }),
239
+ "start_at": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001 }),
240
+ "end_at": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001 }),
241
+ },
242
+ "optional": {
243
+ "attn_mask": ("MASK", ),
244
+ },
245
+ "hidden": {
246
+ "unique_id": "UNIQUE_ID"
247
+ },
248
+ }
249
+
250
+ RETURN_TYPES = ("MODEL",)
251
+ FUNCTION = "apply_pulid_flux"
252
+ CATEGORY = "pulid"
253
+
254
+ def __init__(self):
255
+ self.pulid_data_dict = None
256
+
257
+ def apply_pulid_flux(self, model, pulid_flux, eva_clip, face_analysis, image, weight, start_at, end_at, attn_mask=None, unique_id=None):
258
+ device = comfy.model_management.get_torch_device()
259
+ # Why should I care what args say, when the unet model has a different dtype?!
260
+ # Am I missing something?!
261
+ #dtype = comfy.model_management.unet_dtype()
262
+ dtype = model.model.diffusion_model.dtype
263
+ # Because of 8bit models we must check what cast type does the unet uses
264
+ # ZLUDA (Intel, AMD) & GPUs with compute capability < 8.0 don't support bfloat16 etc.
265
+ # Issue: https://github.com/balazik/ComfyUI-PuLID-Flux/issues/6
266
+ if model.model.manual_cast_dtype is not None:
267
+ dtype = model.model.manual_cast_dtype
268
+
269
+ eva_clip.to(device, dtype=dtype)
270
+ pulid_flux.to(device, dtype=dtype)
271
+
272
+ # TODO: Add masking support!
273
+ if attn_mask is not None:
274
+ if attn_mask.dim() > 3:
275
+ attn_mask = attn_mask.squeeze(-1)
276
+ elif attn_mask.dim() < 3:
277
+ attn_mask = attn_mask.unsqueeze(0)
278
+ attn_mask = attn_mask.to(device, dtype=dtype)
279
+
280
+ image = tensor_to_image(image)
281
+
282
+ face_helper = FaceRestoreHelper(
283
+ upscale_factor=1,
284
+ face_size=512,
285
+ crop_ratio=(1, 1),
286
+ det_model='retinaface_resnet50',
287
+ save_ext='png',
288
+ device=device,
289
+ )
290
+
291
+ face_helper.face_parse = None
292
+ face_helper.face_parse = init_parsing_model(model_name='bisenet', device=device)
293
+
294
+ bg_label = [0, 16, 18, 7, 8, 9, 14, 15]
295
+ cond = []
296
+
297
+ # Analyse multiple images at multiple sizes and combine largest area embeddings
298
+ for i in range(image.shape[0]):
299
+ # get insightface embeddings
300
+ iface_embeds = None
301
+ for size in [(size, size) for size in range(640, 256, -64)]:
302
+ face_analysis.det_model.input_size = size
303
+ face_info = face_analysis.get(image[i])
304
+ if face_info:
305
+ # Only use the maximum face
306
+ # Removed the reverse=True from original code because we need the largest area not the smallest one!
307
+ # Sorts the list in ascending order (smallest to largest),
308
+ # then selects the last element, which is the largest face
309
+ face_info = sorted(face_info, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))[-1]
310
+ iface_embeds = torch.from_numpy(face_info.embedding).unsqueeze(0).to(device, dtype=dtype)
311
+ break
312
+ else:
313
+ # No face detected, skip this image
314
+ logging.warning(f'Warning: No face detected in image {str(i)}')
315
+ continue
316
+
317
+ # get eva_clip embeddings
318
+ face_helper.clean_all()
319
+ face_helper.read_image(image[i])
320
+ face_helper.get_face_landmarks_5(only_center_face=True)
321
+ face_helper.align_warp_face()
322
+
323
+ if len(face_helper.cropped_faces) == 0:
324
+ # No face detected, skip this image
325
+ continue
326
+
327
+ # Get aligned face image
328
+ align_face = face_helper.cropped_faces[0]
329
+ # Convert bgr face image to tensor
330
+ align_face = image_to_tensor(align_face).unsqueeze(0).permute(0, 3, 1, 2).to(device)
331
+ parsing_out = face_helper.face_parse(functional.normalize(align_face, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]))[0]
332
+ parsing_out = parsing_out.argmax(dim=1, keepdim=True)
333
+ bg = sum(parsing_out == i for i in bg_label).bool()
334
+ white_image = torch.ones_like(align_face)
335
+ # Only keep the face features
336
+ face_features_image = torch.where(bg, white_image, to_gray(align_face))
337
+
338
+ # Transform img before sending to eva_clip
339
+ # Apparently MPS only supports NEAREST interpolation?
340
+ face_features_image = functional.resize(face_features_image, eva_clip.image_size, transforms.InterpolationMode.BICUBIC if 'cuda' in device.type else transforms.InterpolationMode.NEAREST).to(device, dtype=dtype)
341
+ face_features_image = functional.normalize(face_features_image, eva_clip.image_mean, eva_clip.image_std)
342
+
343
+ # eva_clip
344
+ id_cond_vit, id_vit_hidden = eva_clip(face_features_image, return_all_features=False, return_hidden=True, shuffle=False)
345
+ id_cond_vit = id_cond_vit.to(device, dtype=dtype)
346
+ for idx in range(len(id_vit_hidden)):
347
+ id_vit_hidden[idx] = id_vit_hidden[idx].to(device, dtype=dtype)
348
+
349
+ id_cond_vit = torch.div(id_cond_vit, torch.norm(id_cond_vit, 2, 1, True))
350
+
351
+ # Combine embeddings
352
+ id_cond = torch.cat([iface_embeds, id_cond_vit], dim=-1)
353
+
354
+ # Pulid_encoder
355
+ cond.append(pulid_flux.get_embeds(id_cond, id_vit_hidden))
356
+
357
+ if not cond:
358
+ # No faces detected, return the original model
359
+ logging.warning("PuLID warning: No faces detected in any of the given images, returning unmodified model.")
360
+ return (model,)
361
+
362
+ # average embeddings
363
+ cond = torch.cat(cond).to(device, dtype=dtype)
364
+ if cond.shape[0] > 1:
365
+ cond = torch.mean(cond, dim=0, keepdim=True)
366
+
367
+ sigma_start = model.get_model_object("model_sampling").percent_to_sigma(start_at)
368
+ sigma_end = model.get_model_object("model_sampling").percent_to_sigma(end_at)
369
+
370
+ # Patch the Flux model (original diffusion_model)
371
+ # Nah, I don't care for the official ModelPatcher because it's undocumented!
372
+ # I want the end result now, and I don’t mind if I break other custom nodes in the process. 😄
373
+ flux_model = model.model.diffusion_model
374
+ # Let's see if we already patched the underlying flux model, if not apply patch
375
+ if not hasattr(flux_model, "pulid_ca"):
376
+ # Add perceiver attention, variables and current node data (weight, embedding, sigma_start, sigma_end)
377
+ # The pulid_data is stored in Dict by unique node index,
378
+ # so we can chain multiple ApplyPulidFlux nodes!
379
+ flux_model.pulid_ca = pulid_flux.pulid_ca
380
+ flux_model.pulid_double_interval = pulid_flux.double_interval
381
+ flux_model.pulid_single_interval = pulid_flux.single_interval
382
+ flux_model.pulid_data = {}
383
+ # Replace model forward_orig with our own
384
+ new_method = forward_orig.__get__(flux_model, flux_model.__class__)
385
+ setattr(flux_model, 'forward_orig', new_method)
386
+
387
+ # Patch is already in place, add data (weight, embedding, sigma_start, sigma_end) under unique node index
388
+ flux_model.pulid_data[unique_id] = {
389
+ 'weight': weight,
390
+ 'embedding': cond,
391
+ 'sigma_start': sigma_start,
392
+ 'sigma_end': sigma_end,
393
+ }
394
+
395
+ # Keep a reference for destructor (if node is deleted the data will be deleted as well)
396
+ self.pulid_data_dict = {'data': flux_model.pulid_data, 'unique_id': unique_id}
397
+
398
+ return (model,)
399
+
400
+ def __del__(self):
401
+ # Destroy the data for this node
402
+ if self.pulid_data_dict:
403
+ del self.pulid_data_dict['data'][self.pulid_data_dict['unique_id']]
404
+ del self.pulid_data_dict
405
+
406
+
407
+ NODE_CLASS_MAPPINGS = {
408
+ "PulidFluxModelLoader": PulidFluxModelLoader,
409
+ "PulidFluxInsightFaceLoader": PulidFluxInsightFaceLoader,
410
+ "PulidFluxEvaClipLoader": PulidFluxEvaClipLoader,
411
+ "ApplyPulidFlux": ApplyPulidFlux,
412
+ }
413
+
414
+ NODE_DISPLAY_NAME_MAPPINGS = {
415
+ "PulidFluxModelLoader": "Load PuLID Flux Model",
416
+ "PulidFluxInsightFaceLoader": "Load InsightFace (PuLID Flux)",
417
+ "PulidFluxEvaClipLoader": "Load Eva Clip (PuLID Flux)",
418
+ "ApplyPulidFlux": "Apply PuLID Flux",
419
+ }