Delete pulidflux.py
Browse files- pulidflux.py +0 -552
pulidflux.py
DELETED
|
@@ -1,552 +0,0 @@
|
|
| 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 |
-
import torch.nn.functional as F
|
| 16 |
-
|
| 17 |
-
from .eva_clip.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
|
| 18 |
-
from .encoders_flux import IDFormer, PerceiverAttentionCA
|
| 19 |
-
|
| 20 |
-
INSIGHTFACE_DIR = os.path.join(folder_paths.models_dir, "insightface")
|
| 21 |
-
|
| 22 |
-
MODELS_DIR = os.path.join(folder_paths.models_dir, "pulid")
|
| 23 |
-
if "pulid" not in folder_paths.folder_names_and_paths:
|
| 24 |
-
current_paths = [MODELS_DIR]
|
| 25 |
-
else:
|
| 26 |
-
current_paths, _ = folder_paths.folder_names_and_paths["pulid"]
|
| 27 |
-
folder_paths.folder_names_and_paths["pulid"] = (current_paths, folder_paths.supported_pt_extensions)
|
| 28 |
-
|
| 29 |
-
from .online_train2 import online_train
|
| 30 |
-
|
| 31 |
-
class PulidFluxModel(nn.Module):
|
| 32 |
-
def __init__(self):
|
| 33 |
-
super().__init__()
|
| 34 |
-
|
| 35 |
-
self.double_interval = 2
|
| 36 |
-
self.single_interval = 4
|
| 37 |
-
|
| 38 |
-
# Init encoder
|
| 39 |
-
self.pulid_encoder = IDFormer()
|
| 40 |
-
|
| 41 |
-
# Init attention
|
| 42 |
-
num_ca = 19 // self.double_interval + 38 // self.single_interval
|
| 43 |
-
if 19 % self.double_interval != 0:
|
| 44 |
-
num_ca += 1
|
| 45 |
-
if 38 % self.single_interval != 0:
|
| 46 |
-
num_ca += 1
|
| 47 |
-
self.pulid_ca = nn.ModuleList([
|
| 48 |
-
PerceiverAttentionCA() for _ in range(num_ca)
|
| 49 |
-
])
|
| 50 |
-
|
| 51 |
-
def from_pretrained(self, path: str):
|
| 52 |
-
state_dict = comfy.utils.load_torch_file(path, safe_load=True)
|
| 53 |
-
state_dict_dict = {}
|
| 54 |
-
for k, v in state_dict.items():
|
| 55 |
-
module = k.split('.')[0]
|
| 56 |
-
state_dict_dict.setdefault(module, {})
|
| 57 |
-
new_k = k[len(module) + 1:]
|
| 58 |
-
state_dict_dict[module][new_k] = v
|
| 59 |
-
|
| 60 |
-
for module in state_dict_dict:
|
| 61 |
-
getattr(self, module).load_state_dict(state_dict_dict[module], strict=True)
|
| 62 |
-
|
| 63 |
-
del state_dict
|
| 64 |
-
del state_dict_dict
|
| 65 |
-
|
| 66 |
-
def get_embeds(self, face_embed, clip_embeds):
|
| 67 |
-
return self.pulid_encoder(face_embed, clip_embeds)
|
| 68 |
-
|
| 69 |
-
def forward_orig(
|
| 70 |
-
self,
|
| 71 |
-
img: Tensor,
|
| 72 |
-
img_ids: Tensor,
|
| 73 |
-
txt: Tensor,
|
| 74 |
-
txt_ids: Tensor,
|
| 75 |
-
timesteps: Tensor,
|
| 76 |
-
y: Tensor,
|
| 77 |
-
guidance: Tensor = None,
|
| 78 |
-
control=None,
|
| 79 |
-
transformer_options={},
|
| 80 |
-
attn_mask: Tensor = None,
|
| 81 |
-
**kwargs # so it won't break if we add more stuff in the future
|
| 82 |
-
) -> Tensor:
|
| 83 |
-
patches_replace = transformer_options.get("patches_replace", {})
|
| 84 |
-
|
| 85 |
-
if img.ndim != 3 or txt.ndim != 3:
|
| 86 |
-
raise ValueError("Input img and txt tensors must have 3 dimensions.")
|
| 87 |
-
|
| 88 |
-
# running on sequences img
|
| 89 |
-
img = self.img_in(img)
|
| 90 |
-
vec = self.time_in(timestep_embedding(timesteps, 256).to(img.dtype))
|
| 91 |
-
if self.params.guidance_embed:
|
| 92 |
-
if guidance is None:
|
| 93 |
-
raise ValueError("Didn't get guidance strength for guidance distilled model.")
|
| 94 |
-
vec = vec + self.guidance_in(timestep_embedding(guidance, 256).to(img.dtype))
|
| 95 |
-
|
| 96 |
-
vec = vec + self.vector_in(y)
|
| 97 |
-
txt = self.txt_in(txt)
|
| 98 |
-
|
| 99 |
-
ids = torch.cat((txt_ids, img_ids), dim=1)
|
| 100 |
-
pe = self.pe_embedder(ids)
|
| 101 |
-
|
| 102 |
-
ca_idx = 0
|
| 103 |
-
blocks_replace = patches_replace.get("dit", {})
|
| 104 |
-
for i, block in enumerate(self.double_blocks):
|
| 105 |
-
if ("double_block", i) in blocks_replace:
|
| 106 |
-
def block_wrap(args):
|
| 107 |
-
out = {}
|
| 108 |
-
out["img"], out["txt"] = block(img=args["img"],
|
| 109 |
-
txt=args["txt"],
|
| 110 |
-
vec=args["vec"],
|
| 111 |
-
pe=args["pe"],
|
| 112 |
-
attn_mask=args.get("attn_mask"))
|
| 113 |
-
return out
|
| 114 |
-
|
| 115 |
-
out = blocks_replace[("double_block", i)]({"img": img,
|
| 116 |
-
"txt": txt,
|
| 117 |
-
"vec": vec,
|
| 118 |
-
"pe": pe,
|
| 119 |
-
"attn_mask": attn_mask},
|
| 120 |
-
{"original_block": block_wrap})
|
| 121 |
-
txt = out["txt"]
|
| 122 |
-
img = out["img"]
|
| 123 |
-
else:
|
| 124 |
-
img, txt = block(img=img,
|
| 125 |
-
txt=txt,
|
| 126 |
-
vec=vec,
|
| 127 |
-
pe=pe,
|
| 128 |
-
attn_mask=attn_mask)
|
| 129 |
-
|
| 130 |
-
if control is not None: # Controlnet
|
| 131 |
-
control_i = control.get("input")
|
| 132 |
-
if i < len(control_i):
|
| 133 |
-
add = control_i[i]
|
| 134 |
-
if add is not None:
|
| 135 |
-
img += add
|
| 136 |
-
|
| 137 |
-
# PuLID attention
|
| 138 |
-
if self.pulid_data:
|
| 139 |
-
if i % self.pulid_double_interval == 0:
|
| 140 |
-
# Will calculate influence of all pulid nodes at once
|
| 141 |
-
for _, node_data in self.pulid_data.items():
|
| 142 |
-
condition_start = node_data['sigma_start'] >= timesteps
|
| 143 |
-
condition_end = timesteps >= node_data['sigma_end']
|
| 144 |
-
condition = torch.logical_and(
|
| 145 |
-
condition_start, condition_end).all()
|
| 146 |
-
|
| 147 |
-
if condition:
|
| 148 |
-
img = img + node_data['weight'] * self.pulid_ca[ca_idx](node_data['embedding'], img)
|
| 149 |
-
ca_idx += 1
|
| 150 |
-
|
| 151 |
-
img = torch.cat((txt, img), 1)
|
| 152 |
-
for i, block in enumerate(self.single_blocks):
|
| 153 |
-
if ("single_block", i) in blocks_replace:
|
| 154 |
-
def block_wrap(args):
|
| 155 |
-
out = {}
|
| 156 |
-
out["img"] = block(args["img"],
|
| 157 |
-
vec=args["vec"],
|
| 158 |
-
pe=args["pe"],
|
| 159 |
-
attn_mask=args.get("attn_mask"))
|
| 160 |
-
return out
|
| 161 |
-
|
| 162 |
-
out = blocks_replace[("single_block", i)]({"img": img,
|
| 163 |
-
"vec": vec,
|
| 164 |
-
"pe": pe,
|
| 165 |
-
"attn_mask": attn_mask},
|
| 166 |
-
{"original_block": block_wrap})
|
| 167 |
-
img = out["img"]
|
| 168 |
-
else:
|
| 169 |
-
img = block(img, vec=vec, pe=pe, attn_mask=attn_mask)
|
| 170 |
-
|
| 171 |
-
if control is not None: # Controlnet
|
| 172 |
-
control_o = control.get("output")
|
| 173 |
-
if i < len(control_o):
|
| 174 |
-
add = control_o[i]
|
| 175 |
-
if add is not None:
|
| 176 |
-
img[:, txt.shape[1] :, ...] += add
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
# PuLID attention
|
| 180 |
-
if self.pulid_data:
|
| 181 |
-
real_img, txt = img[:, txt.shape[1]:, ...], img[:, :txt.shape[1], ...]
|
| 182 |
-
if i % self.pulid_single_interval == 0:
|
| 183 |
-
# Will calculate influence of all nodes at once
|
| 184 |
-
for _, node_data in self.pulid_data.items():
|
| 185 |
-
condition_start = node_data['sigma_start'] >= timesteps
|
| 186 |
-
condition_end = timesteps >= node_data['sigma_end']
|
| 187 |
-
|
| 188 |
-
# Combine conditions and reduce to a single boolean
|
| 189 |
-
condition = torch.logical_and(condition_start, condition_end).all()
|
| 190 |
-
|
| 191 |
-
if condition:
|
| 192 |
-
real_img = real_img + node_data['weight'] * self.pulid_ca[ca_idx](node_data['embedding'], real_img)
|
| 193 |
-
ca_idx += 1
|
| 194 |
-
img = torch.cat((txt, real_img), 1)
|
| 195 |
-
|
| 196 |
-
img = img[:, txt.shape[1] :, ...]
|
| 197 |
-
|
| 198 |
-
img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
|
| 199 |
-
return img
|
| 200 |
-
|
| 201 |
-
def tensor_to_image(tensor):
|
| 202 |
-
image = tensor.mul(255).clamp(0, 255).byte().cpu()
|
| 203 |
-
image = image[..., [2, 1, 0]].numpy()
|
| 204 |
-
return image
|
| 205 |
-
|
| 206 |
-
def image_to_tensor(image):
|
| 207 |
-
tensor = torch.clamp(torch.from_numpy(image).float() / 255., 0, 1)
|
| 208 |
-
tensor = tensor[..., [2, 1, 0]]
|
| 209 |
-
return tensor
|
| 210 |
-
|
| 211 |
-
def resize_with_pad(img, target_size): # image: 1, h, w, 3
|
| 212 |
-
img = img.permute(0, 3, 1, 2)
|
| 213 |
-
H, W = target_size
|
| 214 |
-
|
| 215 |
-
h, w = img.shape[2], img.shape[3]
|
| 216 |
-
scale_h = H / h
|
| 217 |
-
scale_w = W / w
|
| 218 |
-
scale = min(scale_h, scale_w)
|
| 219 |
-
|
| 220 |
-
new_h = int(min(h * scale,H))
|
| 221 |
-
new_w = int(min(w * scale,W))
|
| 222 |
-
new_size = (new_h, new_w)
|
| 223 |
-
|
| 224 |
-
img = F.interpolate(img, size=new_size, mode='bicubic', align_corners=False)
|
| 225 |
-
|
| 226 |
-
pad_top = (H - new_h) // 2
|
| 227 |
-
pad_bottom = (H - new_h) - pad_top
|
| 228 |
-
pad_left = (W - new_w) // 2
|
| 229 |
-
pad_right = (W - new_w) - pad_left
|
| 230 |
-
img = F.pad(img, pad=(pad_left, pad_right, pad_top, pad_bottom), mode='constant', value=0)
|
| 231 |
-
|
| 232 |
-
return img.permute(0, 2, 3, 1)
|
| 233 |
-
|
| 234 |
-
def to_gray(img):
|
| 235 |
-
x = 0.299 * img[:, 0:1] + 0.587 * img[:, 1:2] + 0.114 * img[:, 2:3]
|
| 236 |
-
x = x.repeat(1, 3, 1, 1)
|
| 237 |
-
return x
|
| 238 |
-
|
| 239 |
-
"""
|
| 240 |
-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 241 |
-
Nodes
|
| 242 |
-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 243 |
-
"""
|
| 244 |
-
|
| 245 |
-
class PulidFluxModelLoader:
|
| 246 |
-
@classmethod
|
| 247 |
-
def INPUT_TYPES(s):
|
| 248 |
-
return {"required": {"pulid_file": (folder_paths.get_filename_list("pulid"), )}}
|
| 249 |
-
|
| 250 |
-
RETURN_TYPES = ("PULIDFLUX",)
|
| 251 |
-
FUNCTION = "load_model"
|
| 252 |
-
CATEGORY = "pulid"
|
| 253 |
-
|
| 254 |
-
def load_model(self, pulid_file):
|
| 255 |
-
model_path = folder_paths.get_full_path("pulid", pulid_file)
|
| 256 |
-
|
| 257 |
-
# 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
|
| 258 |
-
model = PulidFluxModel()
|
| 259 |
-
|
| 260 |
-
logging.info("Loading PuLID-Flux model.")
|
| 261 |
-
model.from_pretrained(path=model_path)
|
| 262 |
-
|
| 263 |
-
return (model,)
|
| 264 |
-
|
| 265 |
-
class PulidFluxInsightFaceLoader:
|
| 266 |
-
@classmethod
|
| 267 |
-
def INPUT_TYPES(s):
|
| 268 |
-
return {
|
| 269 |
-
"required": {
|
| 270 |
-
"provider": (["CPU", "CUDA", "ROCM"], ),
|
| 271 |
-
},
|
| 272 |
-
}
|
| 273 |
-
|
| 274 |
-
RETURN_TYPES = ("FACEANALYSIS",)
|
| 275 |
-
FUNCTION = "load_insightface"
|
| 276 |
-
CATEGORY = "pulid"
|
| 277 |
-
|
| 278 |
-
def load_insightface(self, provider):
|
| 279 |
-
model = FaceAnalysis(name="antelopev2", root=INSIGHTFACE_DIR, providers=[provider + 'ExecutionProvider',]) # alternative to buffalo_l
|
| 280 |
-
model.prepare(ctx_id=0, det_size=(640, 640))
|
| 281 |
-
|
| 282 |
-
return (model,)
|
| 283 |
-
|
| 284 |
-
class PulidFluxEvaClipLoader:
|
| 285 |
-
@classmethod
|
| 286 |
-
def INPUT_TYPES(s):
|
| 287 |
-
return {
|
| 288 |
-
"required": {},
|
| 289 |
-
}
|
| 290 |
-
|
| 291 |
-
RETURN_TYPES = ("EVA_CLIP",)
|
| 292 |
-
FUNCTION = "load_eva_clip"
|
| 293 |
-
CATEGORY = "pulid"
|
| 294 |
-
|
| 295 |
-
def load_eva_clip(self):
|
| 296 |
-
from .eva_clip.factory import create_model_and_transforms
|
| 297 |
-
|
| 298 |
-
model, _, _ = create_model_and_transforms('EVA02-CLIP-L-14-336', 'eva_clip', force_custom_clip=True)
|
| 299 |
-
|
| 300 |
-
model = model.visual
|
| 301 |
-
|
| 302 |
-
eva_transform_mean = getattr(model, 'image_mean', OPENAI_DATASET_MEAN)
|
| 303 |
-
eva_transform_std = getattr(model, 'image_std', OPENAI_DATASET_STD)
|
| 304 |
-
if not isinstance(eva_transform_mean, (list, tuple)):
|
| 305 |
-
model["image_mean"] = (eva_transform_mean,) * 3
|
| 306 |
-
if not isinstance(eva_transform_std, (list, tuple)):
|
| 307 |
-
model["image_std"] = (eva_transform_std,) * 3
|
| 308 |
-
|
| 309 |
-
return (model,)
|
| 310 |
-
|
| 311 |
-
class ApplyPulidFlux:
|
| 312 |
-
@classmethod
|
| 313 |
-
def INPUT_TYPES(s):
|
| 314 |
-
return {
|
| 315 |
-
"required": {
|
| 316 |
-
"model": ("MODEL", ),
|
| 317 |
-
"pulid_flux": ("PULIDFLUX", ),
|
| 318 |
-
"eva_clip": ("EVA_CLIP", ),
|
| 319 |
-
"face_analysis": ("FACEANALYSIS", ),
|
| 320 |
-
"image": ("IMAGE", ),
|
| 321 |
-
"weight": ("FLOAT", {"default": 1.0, "min": -1.0, "max": 5.0, "step": 0.05 }),
|
| 322 |
-
"start_at": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001 }),
|
| 323 |
-
"end_at": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001 }),
|
| 324 |
-
"fusion": (["mean","concat","max","norm_id","max_token","auto_weight","train_weight"],),
|
| 325 |
-
"fusion_weight_max": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 20.0, "step": 0.1 }),
|
| 326 |
-
"fusion_weight_min": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 20.0, "step": 0.1 }),
|
| 327 |
-
"train_step": ("INT", {"default": 1000, "min": 0, "max": 20000, "step": 1 }),
|
| 328 |
-
"use_gray": ("BOOLEAN", {"default": True, "label_on": "enabled", "label_off": "disabled"}),
|
| 329 |
-
},
|
| 330 |
-
"optional": {
|
| 331 |
-
"attn_mask": ("MASK", ),
|
| 332 |
-
"prior_image": ("IMAGE",), # for train weight, as the target
|
| 333 |
-
},
|
| 334 |
-
"hidden": {
|
| 335 |
-
"unique_id": "UNIQUE_ID"
|
| 336 |
-
},
|
| 337 |
-
}
|
| 338 |
-
|
| 339 |
-
RETURN_TYPES = ("MODEL",)
|
| 340 |
-
FUNCTION = "apply_pulid_flux"
|
| 341 |
-
CATEGORY = "pulid"
|
| 342 |
-
|
| 343 |
-
def __init__(self):
|
| 344 |
-
self.pulid_data_dict = None
|
| 345 |
-
|
| 346 |
-
def apply_pulid_flux(self, model, pulid_flux, eva_clip, face_analysis, image, weight, start_at, end_at, prior_image=None,fusion="mean", fusion_weight_max=1.0, fusion_weight_min=0.0, train_step=1000, use_gray=True, attn_mask=None, unique_id=None):
|
| 347 |
-
device = comfy.model_management.get_torch_device()
|
| 348 |
-
# Why should I care what args say, when the unet model has a different dtype?!
|
| 349 |
-
# Am I missing something?!
|
| 350 |
-
#dtype = comfy.model_management.unet_dtype()
|
| 351 |
-
dtype = model.model.diffusion_model.dtype
|
| 352 |
-
# For 8bit use bfloat16 (because ufunc_add_CUDA is not implemented)
|
| 353 |
-
if model.model.manual_cast_dtype is not None:
|
| 354 |
-
dtype = model.model.manual_cast_dtype
|
| 355 |
-
|
| 356 |
-
eva_clip.to(device, dtype=dtype)
|
| 357 |
-
pulid_flux.to(device, dtype=dtype)
|
| 358 |
-
|
| 359 |
-
# TODO: Add masking support!
|
| 360 |
-
if attn_mask is not None:
|
| 361 |
-
if attn_mask.dim() > 3:
|
| 362 |
-
attn_mask = attn_mask.squeeze(-1)
|
| 363 |
-
elif attn_mask.dim() < 3:
|
| 364 |
-
attn_mask = attn_mask.unsqueeze(0)
|
| 365 |
-
attn_mask = attn_mask.to(device, dtype=dtype)
|
| 366 |
-
|
| 367 |
-
if prior_image is not None:
|
| 368 |
-
prior_image = resize_with_pad(prior_image.to(image.device, dtype=image.dtype), target_size=(image.shape[1], image.shape[2]))
|
| 369 |
-
image=torch.cat((prior_image,image),dim=0)
|
| 370 |
-
image = tensor_to_image(image)
|
| 371 |
-
|
| 372 |
-
face_helper = FaceRestoreHelper(
|
| 373 |
-
upscale_factor=1,
|
| 374 |
-
face_size=512,
|
| 375 |
-
crop_ratio=(1, 1),
|
| 376 |
-
det_model='retinaface_resnet50',
|
| 377 |
-
save_ext='png',
|
| 378 |
-
device=device,
|
| 379 |
-
)
|
| 380 |
-
|
| 381 |
-
face_helper.face_parse = None
|
| 382 |
-
face_helper.face_parse = init_parsing_model(model_name='bisenet', device=device)
|
| 383 |
-
|
| 384 |
-
bg_label = [0, 16, 18, 7, 8, 9, 14, 15]
|
| 385 |
-
cond = []
|
| 386 |
-
|
| 387 |
-
# Analyse multiple images at multiple sizes and combine largest area embeddings
|
| 388 |
-
for i in range(image.shape[0]):
|
| 389 |
-
# get insightface embeddings
|
| 390 |
-
iface_embeds = None
|
| 391 |
-
for size in [(size, size) for size in range(640, 256, -64)]:
|
| 392 |
-
face_analysis.det_model.input_size = size
|
| 393 |
-
face_info = face_analysis.get(image[i])
|
| 394 |
-
if face_info:
|
| 395 |
-
# Only use the maximum face
|
| 396 |
-
# Removed the reverse=True from original code because we need the largest area not the smallest one!
|
| 397 |
-
# Sorts the list in ascending order (smallest to largest),
|
| 398 |
-
# then selects the last element, which is the largest face
|
| 399 |
-
face_info = sorted(face_info, key=lambda x: (x.bbox[2] - x.bbox[0]) * (x.bbox[3] - x.bbox[1]))[-1]
|
| 400 |
-
iface_embeds = torch.from_numpy(face_info.embedding).unsqueeze(0).to(device, dtype=dtype)
|
| 401 |
-
break
|
| 402 |
-
else:
|
| 403 |
-
# No face detected, skip this image
|
| 404 |
-
logging.warning(f'Warning: No face detected in image {str(i)}')
|
| 405 |
-
continue
|
| 406 |
-
|
| 407 |
-
# get eva_clip embeddings
|
| 408 |
-
face_helper.clean_all()
|
| 409 |
-
face_helper.read_image(image[i])
|
| 410 |
-
face_helper.get_face_landmarks_5(only_center_face=True)
|
| 411 |
-
face_helper.align_warp_face()
|
| 412 |
-
|
| 413 |
-
if len(face_helper.cropped_faces) == 0:
|
| 414 |
-
# No face detected, skip this image
|
| 415 |
-
continue
|
| 416 |
-
|
| 417 |
-
# Get aligned face image
|
| 418 |
-
align_face = face_helper.cropped_faces[0]
|
| 419 |
-
# Convert bgr face image to tensor
|
| 420 |
-
align_face = image_to_tensor(align_face).unsqueeze(0).permute(0, 3, 1, 2).to(device)
|
| 421 |
-
parsing_out = face_helper.face_parse(functional.normalize(align_face, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]))[0]
|
| 422 |
-
parsing_out = parsing_out.argmax(dim=1, keepdim=True)
|
| 423 |
-
bg = sum(parsing_out == i for i in bg_label).bool()
|
| 424 |
-
white_image = torch.ones_like(align_face)
|
| 425 |
-
# Only keep the face features
|
| 426 |
-
if use_gray:
|
| 427 |
-
_align_face = to_gray(align_face)
|
| 428 |
-
else:
|
| 429 |
-
_align_face = align_face
|
| 430 |
-
face_features_image = torch.where(bg, white_image, _align_face)
|
| 431 |
-
|
| 432 |
-
# Transform img before sending to eva_clip
|
| 433 |
-
# Apparently MPS only supports NEAREST interpolation?
|
| 434 |
-
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)
|
| 435 |
-
face_features_image = functional.normalize(face_features_image, eva_clip.image_mean, eva_clip.image_std)
|
| 436 |
-
|
| 437 |
-
# eva_clip
|
| 438 |
-
id_cond_vit, id_vit_hidden = eva_clip(face_features_image, return_all_features=False, return_hidden=True, shuffle=False)
|
| 439 |
-
id_cond_vit = id_cond_vit.to(device, dtype=dtype)
|
| 440 |
-
for idx in range(len(id_vit_hidden)):
|
| 441 |
-
id_vit_hidden[idx] = id_vit_hidden[idx].to(device, dtype=dtype)
|
| 442 |
-
|
| 443 |
-
id_cond_vit = torch.div(id_cond_vit, torch.norm(id_cond_vit, 2, 1, True))
|
| 444 |
-
|
| 445 |
-
# Combine embeddings
|
| 446 |
-
id_cond = torch.cat([iface_embeds, id_cond_vit], dim=-1)
|
| 447 |
-
|
| 448 |
-
# Pulid_encoder
|
| 449 |
-
cond.append(pulid_flux.get_embeds(id_cond, id_vit_hidden))
|
| 450 |
-
|
| 451 |
-
if not cond:
|
| 452 |
-
# No faces detected, return the original model
|
| 453 |
-
logging.warning("PuLID warning: No faces detected in any of the given images, returning unmodified model.")
|
| 454 |
-
return (model,)
|
| 455 |
-
|
| 456 |
-
# fusion embeddings
|
| 457 |
-
if fusion == "mean":
|
| 458 |
-
cond = torch.cat(cond).to(device, dtype=dtype) # N,32,2048
|
| 459 |
-
if cond.shape[0] > 1:
|
| 460 |
-
cond = torch.mean(cond, dim=0, keepdim=True)
|
| 461 |
-
elif fusion == "concat":
|
| 462 |
-
cond = torch.cat(cond, dim=1).to(device, dtype=dtype)
|
| 463 |
-
elif fusion == "max":
|
| 464 |
-
cond = torch.cat(cond).to(device, dtype=dtype)
|
| 465 |
-
if cond.shape[0] > 1:
|
| 466 |
-
cond = torch.max(cond, dim=0, keepdim=True)[0]
|
| 467 |
-
elif fusion == "norm_id":
|
| 468 |
-
cond = torch.cat(cond).to(device, dtype=dtype)
|
| 469 |
-
if cond.shape[0] > 1:
|
| 470 |
-
norm=torch.norm(cond,dim=(1,2))
|
| 471 |
-
norm=norm/torch.sum(norm)
|
| 472 |
-
cond=torch.einsum("wij,w->ij",cond,norm).unsqueeze(0)
|
| 473 |
-
elif fusion == "max_token":
|
| 474 |
-
cond = torch.cat(cond).to(device, dtype=dtype)
|
| 475 |
-
if cond.shape[0] > 1:
|
| 476 |
-
norm=torch.norm(cond,dim=2)
|
| 477 |
-
_,idx=torch.max(norm,dim=0)
|
| 478 |
-
cond=torch.stack([cond[j,i] for i,j in enumerate(idx)]).unsqueeze(0)
|
| 479 |
-
elif fusion == "auto_weight": # 🤔
|
| 480 |
-
cond = torch.cat(cond).to(device, dtype=dtype)
|
| 481 |
-
if cond.shape[0] > 1:
|
| 482 |
-
norm=torch.norm(cond,dim=2)
|
| 483 |
-
order=torch.argsort(norm,descending=False,dim=0)
|
| 484 |
-
regular_weight=torch.linspace(fusion_weight_min,fusion_weight_max,norm.shape[0]).to(device, dtype=dtype)
|
| 485 |
-
|
| 486 |
-
_cond=[]
|
| 487 |
-
for i in range(cond.shape[1]):
|
| 488 |
-
o=order[:,i]
|
| 489 |
-
_cond.append(torch.einsum('ij,i->j',cond[:,i,:],regular_weight[o]))
|
| 490 |
-
cond=torch.stack(_cond,dim=0).unsqueeze(0)
|
| 491 |
-
elif fusion == "train_weight":
|
| 492 |
-
cond = torch.cat(cond).to(device, dtype=dtype)
|
| 493 |
-
if cond.shape[0] > 1:
|
| 494 |
-
if train_step > 0:
|
| 495 |
-
with torch.inference_mode(False):
|
| 496 |
-
cond = online_train(cond, device=cond.device, step=train_step)
|
| 497 |
-
else:
|
| 498 |
-
cond = torch.mean(cond, dim=0, keepdim=True)
|
| 499 |
-
|
| 500 |
-
sigma_start = model.get_model_object("model_sampling").percent_to_sigma(start_at)
|
| 501 |
-
sigma_end = model.get_model_object("model_sampling").percent_to_sigma(end_at)
|
| 502 |
-
|
| 503 |
-
# Patch the Flux model (original diffusion_model)
|
| 504 |
-
# Nah, I don't care for the official ModelPatcher because it's undocumented!
|
| 505 |
-
# I want the end result now, and I don’t mind if I break other custom nodes in the process. 😄
|
| 506 |
-
flux_model = model.model.diffusion_model
|
| 507 |
-
# Let's see if we already patched the underlying flux model, if not apply patch
|
| 508 |
-
if not hasattr(flux_model, "pulid_ca"):
|
| 509 |
-
# Add perceiver attention, variables and current node data (weight, embedding, sigma_start, sigma_end)
|
| 510 |
-
# The pulid_data is stored in Dict by unique node index,
|
| 511 |
-
# so we can chain multiple ApplyPulidFlux nodes!
|
| 512 |
-
flux_model.pulid_ca = pulid_flux.pulid_ca
|
| 513 |
-
flux_model.pulid_double_interval = pulid_flux.double_interval
|
| 514 |
-
flux_model.pulid_single_interval = pulid_flux.single_interval
|
| 515 |
-
flux_model.pulid_data = {}
|
| 516 |
-
# Replace model forward_orig with our own
|
| 517 |
-
new_method = forward_orig.__get__(flux_model, flux_model.__class__)
|
| 518 |
-
setattr(flux_model, 'forward_orig', new_method)
|
| 519 |
-
|
| 520 |
-
# Patch is already in place, add data (weight, embedding, sigma_start, sigma_end) under unique node index
|
| 521 |
-
flux_model.pulid_data[unique_id] = {
|
| 522 |
-
'weight': weight,
|
| 523 |
-
'embedding': cond,
|
| 524 |
-
'sigma_start': sigma_start,
|
| 525 |
-
'sigma_end': sigma_end,
|
| 526 |
-
}
|
| 527 |
-
|
| 528 |
-
# Keep a reference for destructor (if node is deleted the data will be deleted as well)
|
| 529 |
-
self.pulid_data_dict = {'data': flux_model.pulid_data, 'unique_id': unique_id}
|
| 530 |
-
|
| 531 |
-
return (model,)
|
| 532 |
-
|
| 533 |
-
def __del__(self):
|
| 534 |
-
# Destroy the data for this node
|
| 535 |
-
if self.pulid_data_dict:
|
| 536 |
-
del self.pulid_data_dict['data'][self.pulid_data_dict['unique_id']]
|
| 537 |
-
del self.pulid_data_dict
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
NODE_CLASS_MAPPINGS = {
|
| 541 |
-
"PulidFluxModelLoader": PulidFluxModelLoader,
|
| 542 |
-
"PulidFluxInsightFaceLoader": PulidFluxInsightFaceLoader,
|
| 543 |
-
"PulidFluxEvaClipLoader": PulidFluxEvaClipLoader,
|
| 544 |
-
"ApplyPulidFlux": ApplyPulidFlux,
|
| 545 |
-
}
|
| 546 |
-
|
| 547 |
-
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 548 |
-
"PulidFluxModelLoader": "Load PuLID Flux Model",
|
| 549 |
-
"PulidFluxInsightFaceLoader": "Load InsightFace (PuLID Flux)",
|
| 550 |
-
"PulidFluxEvaClipLoader": "Load Eva Clip (PuLID Flux)",
|
| 551 |
-
"ApplyPulidFlux": "Apply PuLID Flux",
|
| 552 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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