SunderAli17 commited on
Commit
d976653
1 Parent(s): e615809

Create fluxpipeline.py

Browse files
Files changed (1) hide show
  1. ToonMage/fluxpipeline.py +188 -0
ToonMage/fluxpipeline.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+
3
+ import cv2
4
+ import insightface
5
+ import torch
6
+ import torch.nn as nn
7
+ from basicsr.utils import img2tensor, tensor2img
8
+ from facexlib.parsing import init_parsing_model
9
+ from facexlib.utils.face_restoration_helper import FaceRestoreHelper
10
+ from huggingface_hub import hf_hub_download, snapshot_download
11
+ from insightface.app import FaceAnalysis
12
+ from safetensors.torch import load_file
13
+ from torchvision.transforms import InterpolationMode
14
+ from torchvision.transforms.functional import normalize, resize
15
+
16
+ from eva_clip import create_model_and_transforms
17
+ from eva_clip.constants import OPENAI_DATASET_MEAN, OPENAI_DATASET_STD
18
+ from ToonMage.encoders_flux import IDFormer, PerceiverAttentionCA
19
+
20
+
21
+ class ToonMagePipeline(nn.Module):
22
+ def __init__(self, dit, device, weight_dtype=torch.bfloat16, *args, **kwargs):
23
+ super().__init__()
24
+ self.device = device
25
+ self.weight_dtype = weight_dtype
26
+ double_interval = 2
27
+ single_interval = 4
28
+
29
+ # init encoder
30
+ self.toonmage_encoder = IDFormer().to(self.device, self.weight_dtype)
31
+
32
+ num_ca = 19 // double_interval + 38 // single_interval
33
+ if 19 % double_interval != 0:
34
+ num_ca += 1
35
+ if 38 % single_interval != 0:
36
+ num_ca += 1
37
+ self.toonmage_ca = nn.ModuleList([
38
+ PerceiverAttentionCA().to(self.device, self.weight_dtype) for _ in range(num_ca)
39
+ ])
40
+
41
+ dit.toonmage_ca = self.toonmage_ca
42
+ dit.toonmage_double_interval = double_interval
43
+ dit.toonmage_single_interval = single_interval
44
+
45
+ # preprocessors
46
+ # face align and parsing
47
+ self.face_helper = FaceRestoreHelper(
48
+ upscale_factor=1,
49
+ face_size=512,
50
+ crop_ratio=(1, 1),
51
+ det_model='retinaface_resnet50',
52
+ save_ext='png',
53
+ device=self.device,
54
+ )
55
+ self.face_helper.face_parse = None
56
+ self.face_helper.face_parse = init_parsing_model(model_name='bisenet', device=self.device)
57
+ # clip-vit backbone
58
+ model, _, _ = create_model_and_transforms('EVA02-CLIP-L-14-336', 'eva_clip', force_custom_clip=True)
59
+ model = model.visual
60
+ self.clip_vision_model = model.to(self.device, dtype=self.weight_dtype)
61
+ eva_transform_mean = getattr(self.clip_vision_model, 'image_mean', OPENAI_DATASET_MEAN)
62
+ eva_transform_std = getattr(self.clip_vision_model, 'image_std', OPENAI_DATASET_STD)
63
+ if not isinstance(eva_transform_mean, (list, tuple)):
64
+ eva_transform_mean = (eva_transform_mean,) * 3
65
+ if not isinstance(eva_transform_std, (list, tuple)):
66
+ eva_transform_std = (eva_transform_std,) * 3
67
+ self.eva_transform_mean = eva_transform_mean
68
+ self.eva_transform_std = eva_transform_std
69
+ # antelopev2
70
+ snapshot_download('DIAMONIK7777/antelopev2', local_dir='models/antelopev2')
71
+ self.app = FaceAnalysis(
72
+ name='antelopev2', root='.', providers=['CPUExecutionProvider']
73
+ )
74
+ self.app.prepare(ctx_id=0, det_size=(640, 640))
75
+ self.handler_ante = insightface.model_zoo.get_model('models/antelopev2/glintr100.onnx', providers=['CPUExecutionProvider'])
76
+ self.handler_ante.prepare(ctx_id=0)
77
+
78
+ gc.collect()
79
+ torch.cuda.empty_cache()
80
+
81
+ # self.load_pretrain()
82
+
83
+ # other configs
84
+ self.debug_img_list = []
85
+
86
+ def load_pretrain(self, pretrain_path=None):
87
+ hf_hub_download('SunderAli17/SAK', 'toonmage_flux_v0.9.0.safetensors', local_dir='models')
88
+ ckpt_path = 'models/toonmage_flux_v0.9.0.safetensors'
89
+ if pretrain_path is not None:
90
+ ckpt_path = pretrain_path
91
+ state_dict = load_file(ckpt_path)
92
+ state_dict_dict = {}
93
+ for k, v in state_dict.items():
94
+ module = k.split('.')[0]
95
+ state_dict_dict.setdefault(module, {})
96
+ new_k = k[len(module) + 1:]
97
+ state_dict_dict[module][new_k] = v
98
+
99
+ for module in state_dict_dict:
100
+ print(f'loading from {module}')
101
+ getattr(self, module).load_state_dict(state_dict_dict[module], strict=True)
102
+
103
+ del state_dict
104
+ del state_dict_dict
105
+
106
+ def to_gray(self, img):
107
+ x = 0.299 * img[:, 0:1] + 0.587 * img[:, 1:2] + 0.114 * img[:, 2:3]
108
+ x = x.repeat(1, 3, 1, 1)
109
+ return x
110
+
111
+ def get_id_embedding(self, image, cal_uncond=False):
112
+ """
113
+ Args:
114
+ image: numpy rgb image, range [0, 255]
115
+ """
116
+ self.face_helper.clean_all()
117
+ self.debug_img_list = []
118
+ image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
119
+ # get antelopev2 embedding
120
+ # for k in self.app.models.keys():
121
+ # self.app.models[k].session.set_providers(['CUDAExecutionProvider'])
122
+ face_info = self.app.get(image_bgr)
123
+ if len(face_info) > 0:
124
+ face_info = sorted(face_info, key=lambda x: (x['bbox'][2] - x['bbox'][0]) * (x['bbox'][3] - x['bbox'][1]))[
125
+ -1
126
+ ] # only use the maximum face
127
+ id_ante_embedding = face_info['embedding']
128
+ self.debug_img_list.append(
129
+ image[
130
+ int(face_info['bbox'][1]) : int(face_info['bbox'][3]),
131
+ int(face_info['bbox'][0]) : int(face_info['bbox'][2]),
132
+ ]
133
+ )
134
+ else:
135
+ id_ante_embedding = None
136
+
137
+ # using facexlib to detect and align face
138
+ self.face_helper.read_image(image_bgr)
139
+ self.face_helper.get_face_landmarks_5(only_center_face=True)
140
+ self.face_helper.align_warp_face()
141
+ if len(self.face_helper.cropped_faces) == 0:
142
+ raise RuntimeError('facexlib align face fail')
143
+ align_face = self.face_helper.cropped_faces[0]
144
+ # incase insightface didn't detect face
145
+ if id_ante_embedding is None:
146
+ print('fail to detect face using insightface, extract embedding on align face')
147
+ # self.handler_ante.session.set_providers(['CUDAExecutionProvider'])
148
+ id_ante_embedding = self.handler_ante.get_feat(align_face)
149
+
150
+ id_ante_embedding = torch.from_numpy(id_ante_embedding).to(self.device, self.weight_dtype)
151
+ if id_ante_embedding.ndim == 1:
152
+ id_ante_embedding = id_ante_embedding.unsqueeze(0)
153
+
154
+ # parsing
155
+ input = img2tensor(align_face, bgr2rgb=True).unsqueeze(0) / 255.0
156
+ input = input.to(self.device)
157
+ parsing_out = self.face_helper.face_parse(normalize(input, [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]))[0]
158
+ parsing_out = parsing_out.argmax(dim=1, keepdim=True)
159
+ bg_label = [0, 16, 18, 7, 8, 9, 14, 15]
160
+ bg = sum(parsing_out == i for i in bg_label).bool()
161
+ white_image = torch.ones_like(input)
162
+ # only keep the face features
163
+ face_features_image = torch.where(bg, white_image, self.to_gray(input))
164
+ self.debug_img_list.append(tensor2img(face_features_image, rgb2bgr=False))
165
+
166
+ # transform img before sending to eva-clip-vit
167
+ face_features_image = resize(face_features_image, self.clip_vision_model.image_size, InterpolationMode.BICUBIC)
168
+ face_features_image = normalize(face_features_image, self.eva_transform_mean, self.eva_transform_std)
169
+ id_cond_vit, id_vit_hidden = self.clip_vision_model(
170
+ face_features_image.to(self.weight_dtype), return_all_features=False, return_hidden=True, shuffle=False
171
+ )
172
+ id_cond_vit_norm = torch.norm(id_cond_vit, 2, 1, True)
173
+ id_cond_vit = torch.div(id_cond_vit, id_cond_vit_norm)
174
+
175
+ id_cond = torch.cat([id_ante_embedding, id_cond_vit], dim=-1)
176
+
177
+ id_embedding = self.toonmage_encoder(id_cond, id_vit_hidden)
178
+
179
+ if not cal_uncond:
180
+ return id_embedding, None
181
+
182
+ id_uncond = torch.zeros_like(id_cond)
183
+ id_vit_hidden_uncond = []
184
+ for layer_idx in range(0, len(id_vit_hidden)):
185
+ id_vit_hidden_uncond.append(torch.zeros_like(id_vit_hidden[layer_idx]))
186
+ uncond_id_embedding = self.toonmage_encoder(id_uncond, id_vit_hidden_uncond)
187
+
188
+ return id_embedding, uncond_id_embedding