b3h-young123 commited on
Commit
a61bd59
·
verified ·
1 Parent(s): 93bb496

Add files using upload-large-folder tool

Browse files
PhotoMaker-V2/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
PhotoMaker-V2/LICENSE ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Tencent is pleased to support the open source community by making PhotoMaker available.
2
+
3
+ Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved.
4
+
5
+ PhotoMaker is licensed under the Apache License Version 2.0 except for the third-party components listed below.
6
+
7
+
8
+ Terms of the Apache License Version 2.0:
9
+ ---------------------------------------------
10
+ Apache License
11
+
12
+ Version 2.0, January 2004
13
+
14
+ http://www.apache.org/licenses/
15
+
16
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
17
+ 1. Definitions.
18
+
19
+ “License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
20
+
21
+ “Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
22
+
23
+ “Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, “control” means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ “You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
26
+
27
+ “Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
28
+
29
+ “Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
30
+
31
+ “Work” shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
32
+
33
+ “Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
34
+
35
+ “Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
36
+
37
+ “Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
38
+
39
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
40
+
41
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
42
+
43
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
44
+
45
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
46
+
47
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
48
+
49
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
50
+
51
+ If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
52
+
53
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
54
+
55
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
56
+
57
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
58
+
59
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
60
+
61
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
62
+
63
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
64
+
65
+ END OF TERMS AND CONDITIONS
PhotoMaker-V2/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: PhotoMaker V2
3
+ emoji: 📷✏️
4
+ colorFrom: pink
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 4.37.2
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
PhotoMaker-V2/app.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+
3
+ import torch
4
+ import torchvision.transforms.functional as TF
5
+ import numpy as np
6
+ import random
7
+ import os
8
+ import sys
9
+
10
+ from diffusers.utils import load_image
11
+ from diffusers import EulerDiscreteScheduler, T2IAdapter
12
+
13
+ from huggingface_hub import hf_hub_download
14
+ import gradio as gr
15
+
16
+ from pipeline_t2i_adapter import PhotoMakerStableDiffusionXLAdapterPipeline
17
+ from face_utils import FaceAnalysis2, analyze_faces
18
+
19
+ from style_template import styles
20
+ from aspect_ratio_template import aspect_ratios
21
+
22
+ # global variable
23
+ base_model_path = 'SG161222/RealVisXL_V4.0'
24
+ face_detector = FaceAnalysis2(providers=['CPUExecutionProvider', 'CUDAExecutionProvider'], allowed_modules=['detection', 'recognition'])
25
+ face_detector.prepare(ctx_id=0, det_size=(640, 640))
26
+
27
+ try:
28
+ if torch.cuda.is_available():
29
+ device = "cuda"
30
+ elif sys.platform == "darwin" and torch.backends.mps.is_available():
31
+ device = "mps"
32
+ else:
33
+ device = "cpu"
34
+ except:
35
+ device = "cpu"
36
+
37
+ MAX_SEED = np.iinfo(np.int32).max
38
+ STYLE_NAMES = list(styles.keys())
39
+ DEFAULT_STYLE_NAME = "Photographic (Default)"
40
+ ASPECT_RATIO_LABELS = list(aspect_ratios)
41
+ DEFAULT_ASPECT_RATIO = ASPECT_RATIO_LABELS[0]
42
+
43
+ enable_doodle_arg = False
44
+ photomaker_ckpt = hf_hub_download(repo_id="TencentARC/PhotoMaker-V2", filename="photomaker-v2.bin", repo_type="model")
45
+
46
+ if torch.cuda.is_available() and torch.cuda.is_bf16_supported():
47
+ torch_dtype = torch.bfloat16
48
+ else:
49
+ torch_dtype = torch.float16
50
+
51
+ if device == "mps":
52
+ torch_dtype = torch.float16
53
+
54
+ # load adapter
55
+ adapter = T2IAdapter.from_pretrained(
56
+ "TencentARC/t2i-adapter-sketch-sdxl-1.0", torch_dtype=torch_dtype, variant="fp16"
57
+ ).to(device)
58
+
59
+ pipe = PhotoMakerStableDiffusionXLAdapterPipeline.from_pretrained(
60
+ base_model_path,
61
+ adapter=adapter,
62
+ torch_dtype=torch_dtype,
63
+ use_safetensors=True,
64
+ variant="fp16",
65
+ ).to(device)
66
+
67
+ pipe.load_photomaker_adapter(
68
+ os.path.dirname(photomaker_ckpt),
69
+ subfolder="",
70
+ weight_name=os.path.basename(photomaker_ckpt),
71
+ trigger_word="img",
72
+ pm_version="v2",
73
+ )
74
+ pipe.id_encoder.to(device)
75
+
76
+ pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
77
+ # pipe.set_adapters(["photomaker"], adapter_weights=[1.0])
78
+ pipe.fuse_lora()
79
+ pipe.to(device)
80
+
81
+
82
+ @spaces.GPU()
83
+ def generate_image(
84
+ upload_images,
85
+ prompt,
86
+ negative_prompt,
87
+ aspect_ratio_name,
88
+ style_name,
89
+ num_steps,
90
+ style_strength_ratio,
91
+ num_outputs,
92
+ guidance_scale,
93
+ seed,
94
+ use_doodle,
95
+ sketch_image,
96
+ adapter_conditioning_scale,
97
+ adapter_conditioning_factor,
98
+ progress=gr.Progress(track_tqdm=True)
99
+ ):
100
+ if use_doodle:
101
+ sketch_image = sketch_image["composite"]
102
+ r, g, b, a = sketch_image.split()
103
+ sketch_image = a.convert("RGB")
104
+ sketch_image = TF.to_tensor(sketch_image) > 0.5 # Inversion
105
+ sketch_image = TF.to_pil_image(sketch_image.to(torch.float32))
106
+ adapter_conditioning_scale = adapter_conditioning_scale
107
+ adapter_conditioning_factor = adapter_conditioning_factor
108
+ else:
109
+ adapter_conditioning_scale = 0.
110
+ adapter_conditioning_factor = 0.
111
+ sketch_image = None
112
+
113
+ # check the trigger word
114
+ image_token_id = pipe.tokenizer.convert_tokens_to_ids(pipe.trigger_word)
115
+ input_ids = pipe.tokenizer.encode(prompt)
116
+ if image_token_id not in input_ids:
117
+ raise gr.Error(f"Cannot find the trigger word '{pipe.trigger_word}' in text prompt! Please refer to step 2️⃣")
118
+
119
+ if input_ids.count(image_token_id) > 1:
120
+ raise gr.Error(f"Cannot use multiple trigger words '{pipe.trigger_word}' in text prompt!")
121
+
122
+ # determine output dimensions by the aspect ratio
123
+ output_w, output_h = aspect_ratios[aspect_ratio_name]
124
+ print(f"[Debug] Generate image using aspect ratio [{aspect_ratio_name}] => {output_w} x {output_h}")
125
+
126
+ # apply the style template
127
+ prompt, negative_prompt = apply_style(style_name, prompt, negative_prompt)
128
+
129
+ if upload_images is None:
130
+ raise gr.Error(f"Cannot find any input face image! Please refer to step 1️⃣")
131
+
132
+ input_id_images = []
133
+ for img in upload_images:
134
+ input_id_images.append(load_image(img))
135
+
136
+ id_embed_list = []
137
+
138
+ for img in input_id_images:
139
+ img = np.array(img)
140
+ img = img[:, :, ::-1]
141
+ faces = analyze_faces(face_detector, img)
142
+ if len(faces) > 0:
143
+ id_embed_list.append(torch.from_numpy((faces[0]['embedding'])))
144
+
145
+ if len(id_embed_list) == 0:
146
+ raise gr.Error(f"No face detected, please update the input face image(s)")
147
+
148
+ id_embeds = torch.stack(id_embed_list)
149
+
150
+ generator = torch.Generator(device=device).manual_seed(seed)
151
+
152
+ print("Start inference...")
153
+ print(f"[Debug] Seed: {seed}")
154
+ print(f"[Debug] Prompt: {prompt}, \n[Debug] Neg Prompt: {negative_prompt}")
155
+ start_merge_step = int(float(style_strength_ratio) / 100 * num_steps)
156
+ if start_merge_step > 30:
157
+ start_merge_step = 30
158
+ print(start_merge_step)
159
+ images = pipe(
160
+ prompt=prompt,
161
+ width=output_w,
162
+ height=output_h,
163
+ input_id_images=input_id_images,
164
+ negative_prompt=negative_prompt,
165
+ num_images_per_prompt=num_outputs,
166
+ num_inference_steps=num_steps,
167
+ start_merge_step=start_merge_step,
168
+ generator=generator,
169
+ guidance_scale=guidance_scale,
170
+ id_embeds=id_embeds,
171
+ image=sketch_image,
172
+ adapter_conditioning_scale=adapter_conditioning_scale,
173
+ adapter_conditioning_factor=adapter_conditioning_factor,
174
+ ).images
175
+ return images, gr.update(visible=True)
176
+
177
+ def swap_to_gallery(images):
178
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
179
+
180
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
181
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
182
+
183
+ def remove_back_to_files():
184
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
185
+
186
+ def change_doodle_space(use_doodle):
187
+ if use_doodle:
188
+ return gr.update(visible=True)
189
+ else:
190
+ return gr.update(visible=False)
191
+
192
+ def remove_tips():
193
+ return gr.update(visible=False)
194
+
195
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
196
+ if randomize_seed:
197
+ seed = random.randint(0, MAX_SEED)
198
+ return seed
199
+
200
+ def apply_style(style_name: str, positive: str, negative: str = "") -> tuple[str, str]:
201
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
202
+ return p.replace("{prompt}", positive), n + ' ' + negative
203
+
204
+ def get_image_path_list(folder_name):
205
+ image_basename_list = os.listdir(folder_name)
206
+ image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list])
207
+ return image_path_list
208
+
209
+ def get_example():
210
+ case = [
211
+ [
212
+ get_image_path_list('./examples/scarletthead_woman'),
213
+ "instagram photo, portrait photo of a woman img, colorful, perfect face, natural skin, hard shadows, film grain",
214
+ "(No style)",
215
+ "(asymmetry, worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), open mouth",
216
+ ],
217
+ [
218
+ get_image_path_list('./examples/newton_man'),
219
+ "sci-fi, closeup portrait photo of a man img wearing the sunglasses in Iron man suit, face, slim body, high quality, film grain",
220
+ "(No style)",
221
+ "(asymmetry, worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), open mouth",
222
+ ],
223
+ ]
224
+ return case
225
+
226
+ ### Description and style
227
+ logo = r"""
228
+ <center><img src='https://photo-maker.github.io/assets/logo.png' alt='PhotoMaker logo' style="width:80px; margin-bottom:10px"></center>
229
+ """
230
+ title = r"""
231
+ <h1 align="center">PhotoMaker V2: Improved ID Fidelity and Better Controllability than PhotoMaker V1</h1>
232
+ """
233
+
234
+ description = r"""
235
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/TencentARC/PhotoMaker' target='_blank'><b>PhotoMaker: Customizing Realistic Human Photos via Stacked ID Embedding</b></a>.<br>
236
+ How to use PhotoMaker V2 can be found in 🎬 <a href='https://photo-maker.github.io/assets/demo_pm_v2_full.mp4' target='_blank'>this video</a> 🎬.
237
+ <br>
238
+ <br>
239
+ For previous version of PhotoMaker, you could use our original gradio demos [PhotoMaker](https://huggingface.co/spaces/TencentARC/PhotoMaker) and [PhotoMaker-Style](https://huggingface.co/spaces/TencentARC/PhotoMaker-Style).
240
+ <br>
241
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
242
+ 1️⃣ Upload images of someone you want to customize. One image is ok, but more is better. Although we do not perform face detection, the face in the uploaded image should <b>occupy the majority of the image</b>.<br>
243
+ 2️⃣ Enter a text prompt, making sure to <b>follow the class word</b> you want to customize with the <b>trigger word</b>: `img`, such as: `man img` or `woman img` or `girl img`.<br>
244
+ 3️⃣ Choose your preferred style template.<br>
245
+ 4️⃣ <b>(Optional: but new feature)</b> Select the ‘Enable Drawing Doodle...’ option and draw on the canvas<br>
246
+ 5️⃣ Click the <b>Submit</b> button to start customizing.
247
+ """
248
+
249
+ article = r"""
250
+
251
+ If PhotoMaker V2 is helpful, please help to ⭐ the <a href='https://github.com/TencentARC/PhotoMaker' target='_blank'>Github Repo</a>. Thanks!
252
+ [![GitHub Stars](https://img.shields.io/github/stars/TencentARC/PhotoMaker?style=social)](https://github.com/TencentARC/PhotoMaker)
253
+ ---
254
+ 📝 **Citation**
255
+ <br>
256
+ If our work is useful for your research, please consider citing:
257
+
258
+ ```bibtex
259
+ @article{li2023photomaker,
260
+ title={PhotoMaker: Customizing Realistic Human Photos via Stacked ID Embedding},
261
+ author={Li, Zhen and Cao, Mingdeng and Wang, Xintao and Qi, Zhongang and Cheng, Ming-Ming and Shan, Ying},
262
+ booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
263
+ year={2024}
264
+ }
265
+ ```
266
+ 📋 **License**
267
+ <br>
268
+ Apache-2.0 LICENSE. Please refer to the [LICENSE file](https://huggingface.co/TencentARC/PhotoMaker/blob/main/LICENSE) for details.
269
+
270
+ 📧 **Contact**
271
+ <br>
272
+ If you have any questions, please feel free to reach me out at <b>zhenli1031@gmail.com</b>.
273
+ """
274
+
275
+ tips = r"""
276
+ ### Usage tips of PhotoMaker
277
+ 1. Upload **more photos**of the person to be customized to **improve ID fidelty**.
278
+ 2. If you find that the image quality is poor when using doodle for control, you can reduce the conditioning scale and factor of the adapter.
279
+ If you have any issues, leave the issue in the discussion page of the space. For a more stable (queue-free) experience, you can duplicate the space.
280
+ """
281
+ # We have provided some generate examples and comparisons at: [this website]().
282
+
283
+ css = '''
284
+ .gradio-container {width: 85% !important}
285
+ '''
286
+ with gr.Blocks(css=css) as demo:
287
+ gr.Markdown(logo)
288
+ gr.Markdown(title)
289
+ gr.Markdown(description)
290
+ # gr.DuplicateButton(
291
+ # value="Duplicate Space for private use ",
292
+ # elem_id="duplicate-button",
293
+ # visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
294
+ # )
295
+ with gr.Row():
296
+ with gr.Column():
297
+ files = gr.Files(
298
+ label="Drag (Select) 1 or more photos of your face",
299
+ file_types=["image"]
300
+ )
301
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200)
302
+ with gr.Column(visible=False) as clear_button:
303
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
304
+ prompt = gr.Textbox(label="Prompt",
305
+ info="Try something like 'a photo of a man/woman img', 'img' is the trigger word.",
306
+ placeholder="A photo of a [man/woman img]...")
307
+ style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)
308
+ aspect_ratio = gr.Dropdown(label="Output aspect ratio", choices=ASPECT_RATIO_LABELS, value=DEFAULT_ASPECT_RATIO)
309
+ submit = gr.Button("Submit")
310
+
311
+ enable_doodle = gr.Checkbox(
312
+ label="Enable Drawing Doodle for Control", value=enable_doodle_arg,
313
+ info="After enabling this option, PhotoMaker will generate content based on your doodle on the canvas, driven by the T2I-Adapter (Quality may be decreased)",
314
+ )
315
+ with gr.Accordion("T2I-Adapter-Doodle (Optional)", visible=False) as doodle_space:
316
+ with gr.Row():
317
+ sketch_image = gr.Sketchpad(
318
+ label="Canvas",
319
+ type="pil",
320
+ crop_size=[1024,1024],
321
+ layers=False,
322
+ canvas_size=(350, 350),
323
+ brush=gr.Brush(default_size=5, colors=["#000000"], color_mode="fixed")
324
+ )
325
+ with gr.Group():
326
+ adapter_conditioning_scale = gr.Slider(
327
+ label="Adapter conditioning scale",
328
+ minimum=0.5,
329
+ maximum=1,
330
+ step=0.1,
331
+ value=0.7,
332
+ )
333
+ adapter_conditioning_factor = gr.Slider(
334
+ label="Adapter conditioning factor",
335
+ info="Fraction of timesteps for which adapter should be applied",
336
+ minimum=0.5,
337
+ maximum=1,
338
+ step=0.1,
339
+ value=0.8,
340
+ )
341
+ with gr.Accordion(open=False, label="Advanced Options"):
342
+ negative_prompt = gr.Textbox(
343
+ label="Negative Prompt",
344
+ placeholder="low quality",
345
+ value="nsfw, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry",
346
+ )
347
+ num_steps = gr.Slider(
348
+ label="Number of sample steps",
349
+ minimum=20,
350
+ maximum=100,
351
+ step=1,
352
+ value=50,
353
+ )
354
+ style_strength_ratio = gr.Slider(
355
+ label="Style strength (%)",
356
+ minimum=15,
357
+ maximum=50,
358
+ step=1,
359
+ value=20,
360
+ )
361
+ num_outputs = gr.Slider(
362
+ label="Number of output images",
363
+ minimum=1,
364
+ maximum=4,
365
+ step=1,
366
+ value=2,
367
+ )
368
+ guidance_scale = gr.Slider(
369
+ label="Guidance scale",
370
+ minimum=0.1,
371
+ maximum=10.0,
372
+ step=0.1,
373
+ value=5,
374
+ )
375
+ seed = gr.Slider(
376
+ label="Seed",
377
+ minimum=0,
378
+ maximum=MAX_SEED,
379
+ step=1,
380
+ value=0,
381
+ )
382
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
383
+ with gr.Column():
384
+ gallery = gr.Gallery(label="Generated Images")
385
+ usage_tips = gr.Markdown(label="Usage tips of PhotoMaker", value=tips ,visible=False)
386
+
387
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
388
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
389
+ enable_doodle.select(fn=change_doodle_space, inputs=enable_doodle, outputs=doodle_space)
390
+
391
+ input_list = [
392
+ files,
393
+ prompt,
394
+ negative_prompt,
395
+ aspect_ratio,
396
+ style,
397
+ num_steps,
398
+ style_strength_ratio,
399
+ num_outputs,
400
+ guidance_scale,
401
+ seed,
402
+ enable_doodle,
403
+ sketch_image,
404
+ adapter_conditioning_scale,
405
+ adapter_conditioning_factor
406
+ ]
407
+
408
+ submit.click(
409
+ fn=remove_tips,
410
+ outputs=usage_tips,
411
+ ).then(
412
+ fn=randomize_seed_fn,
413
+ inputs=[seed, randomize_seed],
414
+ outputs=seed,
415
+ queue=False,
416
+ api_name=False,
417
+ ).then(
418
+ fn=generate_image,
419
+ inputs=input_list,
420
+ outputs=[gallery, usage_tips]
421
+ )
422
+
423
+ gr.Examples(
424
+ examples=get_example(),
425
+ inputs=[files, prompt, style, negative_prompt],
426
+ run_on_click=True,
427
+ fn=upload_example_to_gallery,
428
+ outputs=[uploaded_files, clear_button, files],
429
+ )
430
+
431
+ gr.Markdown(article)
432
+
433
+ demo.launch()
PhotoMaker-V2/aspect_ratio_template.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # From https://github.com/TencentARC/PhotoMaker/pull/120 written by https://github.com/DiscoNova
2
+ # Note: Since output width & height need to be divisible by 8, the w & h -values do
3
+ # not exactly match the stated aspect ratios... but they are "close enough":)
4
+
5
+ aspect_ratio_list = [
6
+ {
7
+ "name": "Instagram (1:1)",
8
+ "w": 1024,
9
+ "h": 1024,
10
+ },
11
+ {
12
+ "name": "35mm film / Landscape (3:2)",
13
+ "w": 1024,
14
+ "h": 680,
15
+ },
16
+ {
17
+ "name": "35mm film / Portrait (2:3)",
18
+ "w": 680,
19
+ "h": 1024,
20
+ },
21
+ {
22
+ "name": "CRT Monitor / Landscape (4:3)",
23
+ "w": 1024,
24
+ "h": 768,
25
+ },
26
+ {
27
+ "name": "CRT Monitor / Portrait (3:4)",
28
+ "w": 768,
29
+ "h": 1024,
30
+ },
31
+ {
32
+ "name": "Widescreen TV / Landscape (16:9)",
33
+ "w": 1024,
34
+ "h": 576,
35
+ },
36
+ {
37
+ "name": "Widescreen TV / Portrait (9:16)",
38
+ "w": 576,
39
+ "h": 1024,
40
+ },
41
+ {
42
+ "name": "Widescreen Monitor / Landscape (16:10)",
43
+ "w": 1024,
44
+ "h": 640,
45
+ },
46
+ {
47
+ "name": "Widescreen Monitor / Portrait (10:16)",
48
+ "w": 640,
49
+ "h": 1024,
50
+ },
51
+ {
52
+ "name": "Cinemascope (2.39:1)",
53
+ "w": 1024,
54
+ "h": 424,
55
+ },
56
+ {
57
+ "name": "Widescreen Movie (1.85:1)",
58
+ "w": 1024,
59
+ "h": 552,
60
+ },
61
+ {
62
+ "name": "Academy Movie (1.37:1)",
63
+ "w": 1024,
64
+ "h": 744,
65
+ },
66
+ {
67
+ "name": "Sheet-print (A-series) / Landscape (297:210)",
68
+ "w": 1024,
69
+ "h": 720,
70
+ },
71
+ {
72
+ "name": "Sheet-print (A-series) / Portrait (210:297)",
73
+ "w": 720,
74
+ "h": 1024,
75
+ },
76
+ ]
77
+
78
+ aspect_ratios = {k["name"]: (k["w"], k["h"]) for k in aspect_ratio_list}
PhotoMaker-V2/examples/newton_man/newton_0.jpg ADDED

Git LFS Details

  • SHA256: 312532bd8fa2222662aa6807569c710df63640ff00d8984639c358af1128c2ff
  • Pointer size: 131 Bytes
  • Size of remote file: 318 kB
PhotoMaker-V2/examples/newton_man/newton_1.jpg ADDED

Git LFS Details

  • SHA256: 428fa7302f076736edb1cc676734b3c2bb465456bab59fb6db3b181df5f86d39
  • Pointer size: 130 Bytes
  • Size of remote file: 54.1 kB
PhotoMaker-V2/examples/newton_man/newton_3.jpg ADDED

Git LFS Details

  • SHA256: b085b4b78af6ae872c8209ce04b75b8488b9c12d81438ece57b95332316a7f72
  • Pointer size: 130 Bytes
  • Size of remote file: 26.3 kB
PhotoMaker-V2/examples/scarletthead_woman/scarlett_0.jpg ADDED

Git LFS Details

  • SHA256: 23fa9d104903f1899e9383591c584a2266ba2dc3b9afc5f31857408ae8fd52a0
  • Pointer size: 130 Bytes
  • Size of remote file: 89.6 kB
PhotoMaker-V2/examples/scarletthead_woman/scarlett_1.jpg ADDED

Git LFS Details

  • SHA256: 114e3872fe772b3a3ceb52a0733b741a32c1515ab3553c20ccd768808cb69ac1
  • Pointer size: 130 Bytes
  • Size of remote file: 26.9 kB
PhotoMaker-V2/examples/scarletthead_woman/scarlett_2.jpg ADDED

Git LFS Details

  • SHA256: f8d129e1cc11e5aa26a934bbeca82749e60ee8e25ab04a77a20b0c421d14aae9
  • Pointer size: 130 Bytes
  • Size of remote file: 74.3 kB
PhotoMaker-V2/examples/scarletthead_woman/scarlett_3.jpg ADDED

Git LFS Details

  • SHA256: aa19a71617f5e85129bbf0c020c069ac2e9881a3804eae6246bbfe07684827e4
  • Pointer size: 131 Bytes
  • Size of remote file: 109 kB
PhotoMaker-V2/face_utils.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ # pip install insightface==0.7.3
3
+ from insightface.app import FaceAnalysis
4
+ from insightface.data import get_image as ins_get_image
5
+
6
+ ###
7
+ # https://github.com/cubiq/ComfyUI_IPAdapter_plus/issues/165#issue-2055829543
8
+ ###
9
+ class FaceAnalysis2(FaceAnalysis):
10
+ # NOTE: allows setting det_size for each detection call.
11
+ # the model allows it but the wrapping code from insightface
12
+ # doesn't show it, and people end up loading duplicate models
13
+ # for different sizes where there is absolutely no need to
14
+ def get(self, img, max_num=0, det_size=(640, 640)):
15
+ if det_size is not None:
16
+ self.det_model.input_size = det_size
17
+
18
+ return super().get(img, max_num)
19
+
20
+ def analyze_faces(face_analysis: FaceAnalysis, img_data: np.ndarray, det_size=(640, 640)):
21
+ # NOTE: try detect faces, if no faces detected, lower det_size until it does
22
+ detection_sizes = [None] + [(size, size) for size in range(640, 256, -64)] + [(256, 256)]
23
+
24
+ for size in detection_sizes:
25
+ faces = face_analysis.get(img_data, det_size=size)
26
+ if len(faces) > 0:
27
+ return faces
28
+
29
+ return []
PhotoMaker-V2/module/__init__.py ADDED
File without changes
PhotoMaker-V2/module/model_v2.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Merge image encoder and fuse module to create an ID Encoder
2
+ # send multiple ID images, we can directly obtain the updated text encoder containing a stacked ID embedding
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from transformers.models.clip.modeling_clip import CLIPVisionModelWithProjection
7
+ from transformers.models.clip.configuration_clip import CLIPVisionConfig
8
+
9
+ from .resampler import FacePerceiverResampler
10
+
11
+ VISION_CONFIG_DICT = {
12
+ "hidden_size": 1024,
13
+ "intermediate_size": 4096,
14
+ "num_attention_heads": 16,
15
+ "num_hidden_layers": 24,
16
+ "patch_size": 14,
17
+ "projection_dim": 768
18
+ }
19
+
20
+
21
+ class MLP(nn.Module):
22
+ def __init__(self, in_dim, out_dim, hidden_dim, use_residual=True):
23
+ super().__init__()
24
+ if use_residual:
25
+ assert in_dim == out_dim
26
+ self.layernorm = nn.LayerNorm(in_dim)
27
+ self.fc1 = nn.Linear(in_dim, hidden_dim)
28
+ self.fc2 = nn.Linear(hidden_dim, out_dim)
29
+ self.use_residual = use_residual
30
+ self.act_fn = nn.GELU()
31
+
32
+ def forward(self, x):
33
+ residual = x
34
+ x = self.layernorm(x)
35
+ x = self.fc1(x)
36
+ x = self.act_fn(x)
37
+ x = self.fc2(x)
38
+ if self.use_residual:
39
+ x = x + residual
40
+ return x
41
+
42
+
43
+ class QFormerPerceiver(nn.Module):
44
+ def __init__(self, id_embeddings_dim, cross_attention_dim, num_tokens, embedding_dim=1024, use_residual=True, ratio=4):
45
+ super().__init__()
46
+
47
+ self.num_tokens = num_tokens
48
+ self.cross_attention_dim = cross_attention_dim
49
+ self.use_residual = use_residual
50
+ print(cross_attention_dim*num_tokens)
51
+ self.token_proj = nn.Sequential(
52
+ nn.Linear(id_embeddings_dim, id_embeddings_dim*ratio),
53
+ nn.GELU(),
54
+ nn.Linear(id_embeddings_dim*ratio, cross_attention_dim*num_tokens),
55
+ )
56
+ self.token_norm = nn.LayerNorm(cross_attention_dim)
57
+ self.perceiver_resampler = FacePerceiverResampler(
58
+ dim=cross_attention_dim,
59
+ depth=4,
60
+ dim_head=128,
61
+ heads=cross_attention_dim // 128,
62
+ embedding_dim=embedding_dim,
63
+ output_dim=cross_attention_dim,
64
+ ff_mult=4,
65
+ )
66
+
67
+ def forward(self, x, last_hidden_state):
68
+ x = self.token_proj(x)
69
+ x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
70
+ x = self.token_norm(x) # cls token
71
+ out = self.perceiver_resampler(x, last_hidden_state) # retrieve from patch tokens
72
+ if self.use_residual: # TODO: if use_residual is not true
73
+ out = x + 1.0 * out
74
+ return out
75
+
76
+
77
+ class FuseModule(nn.Module):
78
+ def __init__(self, embed_dim):
79
+ super().__init__()
80
+ self.mlp1 = MLP(embed_dim * 2, embed_dim, embed_dim, use_residual=False)
81
+ self.mlp2 = MLP(embed_dim, embed_dim, embed_dim, use_residual=True)
82
+ self.layer_norm = nn.LayerNorm(embed_dim)
83
+
84
+ def fuse_fn(self, prompt_embeds, id_embeds):
85
+ stacked_id_embeds = torch.cat([prompt_embeds, id_embeds], dim=-1)
86
+ stacked_id_embeds = self.mlp1(stacked_id_embeds) + prompt_embeds
87
+ stacked_id_embeds = self.mlp2(stacked_id_embeds)
88
+ stacked_id_embeds = self.layer_norm(stacked_id_embeds)
89
+ return stacked_id_embeds
90
+
91
+ def forward(
92
+ self,
93
+ prompt_embeds,
94
+ id_embeds,
95
+ class_tokens_mask,
96
+ ) -> torch.Tensor:
97
+ # id_embeds shape: [b, max_num_inputs, 1, 2048]
98
+ id_embeds = id_embeds.to(prompt_embeds.dtype)
99
+ num_inputs = class_tokens_mask.sum().unsqueeze(0) # TODO: check for training case
100
+ batch_size, max_num_inputs = id_embeds.shape[:2]
101
+ # seq_length: 77
102
+ seq_length = prompt_embeds.shape[1]
103
+ # flat_id_embeds shape: [b*max_num_inputs, 1, 2048]
104
+ flat_id_embeds = id_embeds.view(
105
+ -1, id_embeds.shape[-2], id_embeds.shape[-1]
106
+ )
107
+ # valid_id_mask [b*max_num_inputs]
108
+ valid_id_mask = (
109
+ torch.arange(max_num_inputs, device=flat_id_embeds.device)[None, :]
110
+ < num_inputs[:, None]
111
+ )
112
+ valid_id_embeds = flat_id_embeds[valid_id_mask.flatten()]
113
+
114
+ prompt_embeds = prompt_embeds.view(-1, prompt_embeds.shape[-1])
115
+ class_tokens_mask = class_tokens_mask.view(-1)
116
+ valid_id_embeds = valid_id_embeds.view(-1, valid_id_embeds.shape[-1])
117
+ # slice out the image token embeddings
118
+ image_token_embeds = prompt_embeds[class_tokens_mask]
119
+ stacked_id_embeds = self.fuse_fn(image_token_embeds, valid_id_embeds)
120
+ assert class_tokens_mask.sum() == stacked_id_embeds.shape[0], f"{class_tokens_mask.sum()} != {stacked_id_embeds.shape[0]}"
121
+ prompt_embeds.masked_scatter_(class_tokens_mask[:, None], stacked_id_embeds.to(prompt_embeds.dtype))
122
+ updated_prompt_embeds = prompt_embeds.view(batch_size, seq_length, -1)
123
+ return updated_prompt_embeds
124
+
125
+
126
+ class PhotoMakerIDEncoder_CLIPInsightfaceExtendtoken(CLIPVisionModelWithProjection):
127
+ def __init__(self, id_embeddings_dim=512):
128
+ super().__init__(CLIPVisionConfig(**VISION_CONFIG_DICT))
129
+ self.fuse_module = FuseModule(2048)
130
+ self.visual_projection_2 = nn.Linear(1024, 1280, bias=False)
131
+
132
+ cross_attention_dim = 2048
133
+ # projection
134
+ self.num_tokens = 2
135
+ self.cross_attention_dim = cross_attention_dim
136
+ self.qformer_perceiver = QFormerPerceiver(
137
+ id_embeddings_dim,
138
+ cross_attention_dim,
139
+ self.num_tokens,
140
+ )
141
+
142
+ def forward(self, id_pixel_values, prompt_embeds, class_tokens_mask, id_embeds):
143
+ b, num_inputs, c, h, w = id_pixel_values.shape
144
+ id_pixel_values = id_pixel_values.view(b * num_inputs, c, h, w)
145
+
146
+ last_hidden_state = self.vision_model(id_pixel_values)[0]
147
+ id_embeds = id_embeds.view(b * num_inputs, -1)
148
+
149
+ id_embeds = self.qformer_perceiver(id_embeds, last_hidden_state)
150
+ id_embeds = id_embeds.view(b, num_inputs, self.num_tokens, -1)
151
+ updated_prompt_embeds = self.fuse_module(prompt_embeds, id_embeds, class_tokens_mask)
152
+
153
+ return updated_prompt_embeds
154
+
155
+ if __name__ == "__main__":
156
+ PhotoMakerIDEncoder_CLIPInsightfaceExtendtoken()
PhotoMaker-V2/module/resampler.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #### Borrowed from https://github.com/tencent-ailab/IP-Adapter/blob/main/ip_adapter/resampler.py
2
+ # modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
3
+ # and https://github.com/lucidrains/imagen-pytorch/blob/main/imagen_pytorch/imagen_pytorch.py
4
+
5
+ import math
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from einops import rearrange
10
+ from einops.layers.torch import Rearrange
11
+
12
+
13
+ class FacePerceiverResampler(torch.nn.Module):
14
+ def __init__(
15
+ self,
16
+ *,
17
+ dim=768,
18
+ depth=4,
19
+ dim_head=64,
20
+ heads=16,
21
+ embedding_dim=1280,
22
+ output_dim=768,
23
+ ff_mult=4,
24
+ ):
25
+ super().__init__()
26
+
27
+ self.proj_in = torch.nn.Linear(embedding_dim, dim)
28
+ self.proj_out = torch.nn.Linear(dim, output_dim)
29
+ self.norm_out = torch.nn.LayerNorm(output_dim)
30
+ self.layers = torch.nn.ModuleList([])
31
+ for _ in range(depth):
32
+ self.layers.append(
33
+ torch.nn.ModuleList(
34
+ [
35
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
36
+ FeedForward(dim=dim, mult=ff_mult),
37
+ ]
38
+ )
39
+ )
40
+
41
+ def forward(self, latents, x):
42
+ x = self.proj_in(x)
43
+ for attn, ff in self.layers:
44
+ latents = attn(x, latents) + latents
45
+ latents = ff(latents) + latents
46
+ latents = self.proj_out(latents)
47
+ return self.norm_out(latents)
48
+
49
+ # FFN
50
+ def FeedForward(dim, mult=4):
51
+ inner_dim = int(dim * mult)
52
+ return nn.Sequential(
53
+ nn.LayerNorm(dim),
54
+ nn.Linear(dim, inner_dim, bias=False),
55
+ nn.GELU(),
56
+ nn.Linear(inner_dim, dim, bias=False),
57
+ )
58
+
59
+
60
+ def reshape_tensor(x, heads):
61
+ bs, length, width = x.shape
62
+ # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
63
+ x = x.view(bs, length, heads, -1)
64
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
65
+ x = x.transpose(1, 2)
66
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
67
+ x = x.reshape(bs, heads, length, -1)
68
+ return x
69
+
70
+
71
+ class PerceiverAttention(nn.Module):
72
+ def __init__(self, *, dim, dim_head=64, heads=8):
73
+ super().__init__()
74
+ self.scale = dim_head**-0.5
75
+ self.dim_head = dim_head
76
+ self.heads = heads
77
+ inner_dim = dim_head * heads
78
+
79
+ self.norm1 = nn.LayerNorm(dim)
80
+ self.norm2 = nn.LayerNorm(dim)
81
+
82
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
83
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
84
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
85
+
86
+ def forward(self, x, latents):
87
+ """
88
+ Args:
89
+ x (torch.Tensor): image features
90
+ shape (b, n1, D)
91
+ latent (torch.Tensor): latent features
92
+ shape (b, n2, D)
93
+ """
94
+ x = self.norm1(x)
95
+ latents = self.norm2(latents)
96
+
97
+ b, l, _ = latents.shape
98
+
99
+ q = self.to_q(latents)
100
+ kv_input = torch.cat((x, latents), dim=-2)
101
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
102
+
103
+ q = reshape_tensor(q, self.heads)
104
+ k = reshape_tensor(k, self.heads)
105
+ v = reshape_tensor(v, self.heads)
106
+
107
+ # attention
108
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
109
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
110
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
111
+ out = weight @ v
112
+
113
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
114
+
115
+ return self.to_out(out)
116
+
117
+
118
+ class Resampler(nn.Module):
119
+ def __init__(
120
+ self,
121
+ dim=1024,
122
+ depth=8,
123
+ dim_head=64,
124
+ heads=16,
125
+ num_queries=8,
126
+ embedding_dim=768,
127
+ output_dim=1024,
128
+ ff_mult=4,
129
+ max_seq_len: int = 257, # CLIP tokens + CLS token
130
+ apply_pos_emb: bool = False,
131
+ num_latents_mean_pooled: int = 0, # number of latents derived from mean pooled representation of the sequence
132
+ ):
133
+ super().__init__()
134
+ self.pos_emb = nn.Embedding(max_seq_len, embedding_dim) if apply_pos_emb else None
135
+
136
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
137
+
138
+ self.proj_in = nn.Linear(embedding_dim, dim)
139
+
140
+ self.proj_out = nn.Linear(dim, output_dim)
141
+ self.norm_out = nn.LayerNorm(output_dim)
142
+
143
+ self.to_latents_from_mean_pooled_seq = (
144
+ nn.Sequential(
145
+ nn.LayerNorm(dim),
146
+ nn.Linear(dim, dim * num_latents_mean_pooled),
147
+ Rearrange("b (n d) -> b n d", n=num_latents_mean_pooled),
148
+ )
149
+ if num_latents_mean_pooled > 0
150
+ else None
151
+ )
152
+
153
+ self.layers = nn.ModuleList([])
154
+ for _ in range(depth):
155
+ self.layers.append(
156
+ nn.ModuleList(
157
+ [
158
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
159
+ FeedForward(dim=dim, mult=ff_mult),
160
+ ]
161
+ )
162
+ )
163
+
164
+ def forward(self, x):
165
+ if self.pos_emb is not None:
166
+ n, device = x.shape[1], x.device
167
+ pos_emb = self.pos_emb(torch.arange(n, device=device))
168
+ x = x + pos_emb
169
+
170
+ latents = self.latents.repeat(x.size(0), 1, 1)
171
+
172
+ x = self.proj_in(x)
173
+
174
+ if self.to_latents_from_mean_pooled_seq:
175
+ meanpooled_seq = masked_mean(x, dim=1, mask=torch.ones(x.shape[:2], device=x.device, dtype=torch.bool))
176
+ meanpooled_latents = self.to_latents_from_mean_pooled_seq(meanpooled_seq)
177
+ latents = torch.cat((meanpooled_latents, latents), dim=-2)
178
+
179
+ for attn, ff in self.layers:
180
+ latents = attn(x, latents) + latents
181
+ latents = ff(latents) + latents
182
+
183
+ latents = self.proj_out(latents)
184
+ return self.norm_out(latents)
185
+
186
+
187
+ def masked_mean(t, *, dim, mask=None):
188
+ if mask is None:
189
+ return t.mean(dim=dim)
190
+
191
+ denom = mask.sum(dim=dim, keepdim=True)
192
+ mask = rearrange(mask, "b n -> b n 1")
193
+ masked_t = t.masked_fill(~mask, 0.0)
194
+
195
+ return masked_t.sum(dim=dim) / denom.clamp(min=1e-5)
PhotoMaker-V2/pipeline_t2i_adapter.py ADDED
@@ -0,0 +1,915 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #####
2
+ # Modified from https://github.com/huggingface/diffusers/blob/v0.29.1/src/diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py
3
+ # PhotoMaker v2 @ TencentARC and MCG-NKU
4
+ # Author: Zhen Li
5
+ #####
6
+
7
+ # Copyright 2024 TencentARC and The HuggingFace Team. All rights reserved.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+
21
+ import inspect
22
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import PIL.Image
26
+ import torch
27
+ from transformers import (
28
+ CLIPImageProcessor,
29
+ CLIPTextModel,
30
+ CLIPTextModelWithProjection,
31
+ CLIPTokenizer,
32
+ CLIPVisionModelWithProjection,
33
+ )
34
+
35
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
36
+ from diffusers.loaders import (
37
+ FromSingleFileMixin,
38
+ IPAdapterMixin,
39
+ StableDiffusionXLLoraLoaderMixin,
40
+ TextualInversionLoaderMixin,
41
+ )
42
+ from diffusers.models import AutoencoderKL, ImageProjection, MultiAdapter, T2IAdapter, UNet2DConditionModel
43
+ from diffusers.models.attention_processor import (
44
+ AttnProcessor2_0,
45
+ LoRAAttnProcessor2_0,
46
+ LoRAXFormersAttnProcessor,
47
+ XFormersAttnProcessor,
48
+ )
49
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
50
+ from diffusers.schedulers import KarrasDiffusionSchedulers
51
+ from diffusers.utils import (
52
+ PIL_INTERPOLATION,
53
+ USE_PEFT_BACKEND,
54
+ logging,
55
+ replace_example_docstring,
56
+ scale_lora_layers,
57
+ unscale_lora_layers,
58
+ )
59
+ from diffusers.utils.torch_utils import randn_tensor
60
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
61
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
62
+ from diffusers.pipelines import StableDiffusionXLAdapterPipeline
63
+ from diffusers.utils import _get_model_file
64
+ from safetensors import safe_open
65
+ from huggingface_hub.utils import validate_hf_hub_args
66
+
67
+ from module.model_v2 import PhotoMakerIDEncoder_CLIPInsightfaceExtendtoken
68
+
69
+
70
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
71
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
72
+ """
73
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
74
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
75
+ """
76
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
77
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
78
+ # rescale the results from guidance (fixes overexposure)
79
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
80
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
81
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
82
+ return noise_cfg
83
+
84
+
85
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
86
+ def retrieve_timesteps(
87
+ scheduler,
88
+ num_inference_steps: Optional[int] = None,
89
+ device: Optional[Union[str, torch.device]] = None,
90
+ timesteps: Optional[List[int]] = None,
91
+ sigmas: Optional[List[float]] = None,
92
+ **kwargs,
93
+ ):
94
+ """
95
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
96
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
97
+
98
+ Args:
99
+ scheduler (`SchedulerMixin`):
100
+ The scheduler to get timesteps from.
101
+ num_inference_steps (`int`):
102
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
103
+ must be `None`.
104
+ device (`str` or `torch.device`, *optional*):
105
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
106
+ timesteps (`List[int]`, *optional*):
107
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
108
+ `num_inference_steps` and `sigmas` must be `None`.
109
+ sigmas (`List[float]`, *optional*):
110
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
111
+ `num_inference_steps` and `timesteps` must be `None`.
112
+
113
+ Returns:
114
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
115
+ second element is the number of inference steps.
116
+ """
117
+ if timesteps is not None and sigmas is not None:
118
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
119
+ if timesteps is not None:
120
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
121
+ if not accepts_timesteps:
122
+ raise ValueError(
123
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
124
+ f" timestep schedules. Please check whether you are using the correct scheduler."
125
+ )
126
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
127
+ timesteps = scheduler.timesteps
128
+ num_inference_steps = len(timesteps)
129
+ elif sigmas is not None:
130
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
131
+ if not accept_sigmas:
132
+ raise ValueError(
133
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
134
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
135
+ )
136
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
137
+ timesteps = scheduler.timesteps
138
+ num_inference_steps = len(timesteps)
139
+ else:
140
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
141
+ timesteps = scheduler.timesteps
142
+ return timesteps, num_inference_steps
143
+
144
+
145
+ def _preprocess_adapter_image(image, height, width):
146
+ if isinstance(image, torch.Tensor):
147
+ return image
148
+ elif isinstance(image, PIL.Image.Image):
149
+ image = [image]
150
+
151
+ if isinstance(image[0], PIL.Image.Image):
152
+ image = [np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])) for i in image]
153
+ image = [
154
+ i[None, ..., None] if i.ndim == 2 else i[None, ...] for i in image
155
+ ] # expand [h, w] or [h, w, c] to [b, h, w, c]
156
+ image = np.concatenate(image, axis=0)
157
+ image = np.array(image).astype(np.float32) / 255.0
158
+ image = image.transpose(0, 3, 1, 2)
159
+ image = torch.from_numpy(image)
160
+ elif isinstance(image[0], torch.Tensor):
161
+ if image[0].ndim == 3:
162
+ image = torch.stack(image, dim=0)
163
+ elif image[0].ndim == 4:
164
+ image = torch.cat(image, dim=0)
165
+ else:
166
+ raise ValueError(
167
+ f"Invalid image tensor! Expecting image tensor with 3 or 4 dimension, but recive: {image[0].ndim}"
168
+ )
169
+ return image
170
+
171
+
172
+ class PhotoMakerStableDiffusionXLAdapterPipeline(StableDiffusionXLAdapterPipeline):
173
+ @validate_hf_hub_args
174
+ def load_photomaker_adapter(
175
+ self,
176
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
177
+ weight_name: str,
178
+ subfolder: str = '',
179
+ trigger_word: str = 'img',
180
+ pm_version: str = 'v2',
181
+ **kwargs,
182
+ ):
183
+ """
184
+ Parameters:
185
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
186
+ Can be either:
187
+
188
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
189
+ the Hub.
190
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
191
+ with [`ModelMixin.save_pretrained`].
192
+ - A [torch state
193
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
194
+
195
+ weight_name (`str`):
196
+ The weight name NOT the path to the weight.
197
+
198
+ subfolder (`str`, defaults to `""`):
199
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
200
+
201
+ trigger_word (`str`, *optional*, defaults to `"img"`):
202
+ The trigger word is used to identify the position of class word in the text prompt,
203
+ and it is recommended not to set it as a common word.
204
+ This trigger word must be placed after the class word when used, otherwise, it will affect the performance of the personalized generation.
205
+ """
206
+
207
+ # Load the main state dict first.
208
+ cache_dir = kwargs.pop("cache_dir", None)
209
+ force_download = kwargs.pop("force_download", False)
210
+ resume_download = kwargs.pop("resume_download", False)
211
+ proxies = kwargs.pop("proxies", None)
212
+ local_files_only = kwargs.pop("local_files_only", None)
213
+ token = kwargs.pop("token", None)
214
+ revision = kwargs.pop("revision", None)
215
+
216
+ user_agent = {
217
+ "file_type": "attn_procs_weights",
218
+ "framework": "pytorch",
219
+ }
220
+
221
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
222
+ model_file = _get_model_file(
223
+ pretrained_model_name_or_path_or_dict,
224
+ weights_name=weight_name,
225
+ cache_dir=cache_dir,
226
+ force_download=force_download,
227
+ # resume_download=resume_download,
228
+ proxies=proxies,
229
+ local_files_only=local_files_only,
230
+ token=token,
231
+ revision=revision,
232
+ subfolder=subfolder,
233
+ user_agent=user_agent,
234
+ )
235
+ if weight_name.endswith(".safetensors"):
236
+ state_dict = {"id_encoder": {}, "lora_weights": {}}
237
+ with safe_open(model_file, framework="pt", device="cpu") as f:
238
+ for key in f.keys():
239
+ if key.startswith("id_encoder."):
240
+ state_dict["id_encoder"][key.replace("id_encoder.", "")] = f.get_tensor(key)
241
+ elif key.startswith("lora_weights."):
242
+ state_dict["lora_weights"][key.replace("lora_weights.", "")] = f.get_tensor(key)
243
+ else:
244
+ state_dict = torch.load(model_file, map_location="cpu")
245
+ else:
246
+ state_dict = pretrained_model_name_or_path_or_dict
247
+
248
+ keys = list(state_dict.keys())
249
+ if keys != ["id_encoder", "lora_weights"]:
250
+ raise ValueError("Required keys are (`id_encoder` and `lora_weights`) missing from the state dict.")
251
+
252
+ self.num_tokens = 2
253
+ self.trigger_word = trigger_word
254
+ # load finetuned CLIP image encoder and fuse module here if it has not been registered to the pipeline yet
255
+ print(f"Loading PhotoMaker {pm_version} components [1] id_encoder from [{pretrained_model_name_or_path_or_dict}]...")
256
+ self.id_image_processor = CLIPImageProcessor()
257
+ if pm_version == "v1": # PhotoMaker v1
258
+ id_encoder = PhotoMakerIDEncoder()
259
+ elif pm_version == "v2": # PhotoMaker v2
260
+ id_encoder = PhotoMakerIDEncoder_CLIPInsightfaceExtendtoken()
261
+ else:
262
+ raise NotImplementedError(f"The PhotoMaker version [{pm_version}] does not support")
263
+
264
+ id_encoder.load_state_dict(state_dict["id_encoder"], strict=True)
265
+ id_encoder = id_encoder.to(self.device, dtype=self.unet.dtype)
266
+ self.id_encoder = id_encoder
267
+
268
+ # load lora into models
269
+ print(f"Loading PhotoMaker {pm_version} components [2] lora_weights from [{pretrained_model_name_or_path_or_dict}]")
270
+ self.load_lora_weights(state_dict["lora_weights"], adapter_name="photomaker")
271
+
272
+ # Add trigger word token
273
+ if self.tokenizer is not None:
274
+ self.tokenizer.add_tokens([self.trigger_word], special_tokens=True)
275
+
276
+ self.tokenizer_2.add_tokens([self.trigger_word], special_tokens=True)
277
+
278
+
279
+ def encode_prompt_with_trigger_word(
280
+ self,
281
+ prompt: str,
282
+ prompt_2: Optional[str] = None,
283
+ device: Optional[torch.device] = None,
284
+ num_images_per_prompt: int = 1,
285
+ do_classifier_free_guidance: bool = True,
286
+ negative_prompt: Optional[str] = None,
287
+ negative_prompt_2: Optional[str] = None,
288
+ prompt_embeds: Optional[torch.Tensor] = None,
289
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
290
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
291
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
292
+ lora_scale: Optional[float] = None,
293
+ clip_skip: Optional[int] = None,
294
+ ### Added args
295
+ num_id_images: int = 1,
296
+ class_tokens_mask: Optional[torch.LongTensor] = None,
297
+ ):
298
+ device = device or self._execution_device
299
+
300
+ # set lora scale so that monkey patched LoRA
301
+ # function of text encoder can correctly access it
302
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
303
+ self._lora_scale = lora_scale
304
+
305
+ # dynamically adjust the LoRA scale
306
+ if self.text_encoder is not None:
307
+ if not USE_PEFT_BACKEND:
308
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
309
+ else:
310
+ scale_lora_layers(self.text_encoder, lora_scale)
311
+
312
+ if self.text_encoder_2 is not None:
313
+ if not USE_PEFT_BACKEND:
314
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
315
+ else:
316
+ scale_lora_layers(self.text_encoder_2, lora_scale)
317
+
318
+ prompt = [prompt] if isinstance(prompt, str) else prompt
319
+
320
+ if prompt is not None:
321
+ batch_size = len(prompt)
322
+ else:
323
+ batch_size = prompt_embeds.shape[0]
324
+
325
+ # Find the token id of the trigger word
326
+ image_token_id = self.tokenizer_2.convert_tokens_to_ids(self.trigger_word)
327
+
328
+ # Define tokenizers and text encoders
329
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
330
+ text_encoders = (
331
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
332
+ )
333
+
334
+ if prompt_embeds is None:
335
+ prompt_2 = prompt_2 or prompt
336
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
337
+
338
+ # textual inversion: process multi-vector tokens if necessary
339
+ prompt_embeds_list = []
340
+ prompts = [prompt, prompt_2]
341
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
342
+ if isinstance(self, TextualInversionLoaderMixin):
343
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
344
+
345
+ text_inputs = tokenizer(
346
+ prompt,
347
+ padding="max_length",
348
+ max_length=tokenizer.model_max_length,
349
+ truncation=True,
350
+ return_tensors="pt",
351
+ )
352
+
353
+ text_input_ids = text_inputs.input_ids
354
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
355
+
356
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
357
+ text_input_ids, untruncated_ids
358
+ ):
359
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
360
+ print(
361
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
362
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
363
+ )
364
+
365
+ clean_index = 0
366
+ clean_input_ids = []
367
+ class_token_index = []
368
+ # Find out the corresponding class word token based on the newly added trigger word token
369
+ for i, token_id in enumerate(text_input_ids.tolist()[0]):
370
+ if token_id == image_token_id:
371
+ class_token_index.append(clean_index - 1)
372
+ else:
373
+ clean_input_ids.append(token_id)
374
+ clean_index += 1
375
+
376
+ if len(class_token_index) != 1:
377
+ raise ValueError(
378
+ f"PhotoMaker currently does not support multiple trigger words in a single prompt.\
379
+ Trigger word: {self.trigger_word}, Prompt: {prompt}."
380
+ )
381
+ class_token_index = class_token_index[0]
382
+
383
+ # Expand the class word token and corresponding mask
384
+ class_token = clean_input_ids[class_token_index]
385
+ clean_input_ids = clean_input_ids[:class_token_index] + [class_token] * num_id_images * self.num_tokens + \
386
+ clean_input_ids[class_token_index+1:]
387
+
388
+ # Truncation or padding
389
+ max_len = tokenizer.model_max_length
390
+ if len(clean_input_ids) > max_len:
391
+ clean_input_ids = clean_input_ids[:max_len]
392
+ else:
393
+ clean_input_ids = clean_input_ids + [tokenizer.pad_token_id] * (
394
+ max_len - len(clean_input_ids)
395
+ )
396
+
397
+ class_tokens_mask = [True if class_token_index <= i < class_token_index+(num_id_images * self.num_tokens) else False \
398
+ for i in range(len(clean_input_ids))]
399
+
400
+ clean_input_ids = torch.tensor(clean_input_ids, dtype=torch.long).unsqueeze(0)
401
+ class_tokens_mask = torch.tensor(class_tokens_mask, dtype=torch.bool).unsqueeze(0)
402
+
403
+ prompt_embeds = text_encoder(clean_input_ids.to(device), output_hidden_states=True)
404
+
405
+ # We are only ALWAYS interested in the pooled output of the final text encoder
406
+ pooled_prompt_embeds = prompt_embeds[0]
407
+ if clip_skip is None:
408
+ prompt_embeds = prompt_embeds.hidden_states[-2]
409
+ else:
410
+ # "2" because SDXL always indexes from the penultimate layer.
411
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
412
+
413
+ prompt_embeds_list.append(prompt_embeds)
414
+
415
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
416
+
417
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
418
+ class_tokens_mask = class_tokens_mask.to(device=device) # TODO: ignoring two-prompt case
419
+ # get unconditional embeddings for classifier free guidance
420
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
421
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
422
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
423
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
424
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
425
+ negative_prompt = negative_prompt or ""
426
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
427
+
428
+ # normalize str to list
429
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
430
+ negative_prompt_2 = (
431
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
432
+ )
433
+
434
+ uncond_tokens: List[str]
435
+ if prompt is not None and type(prompt) is not type(negative_prompt):
436
+ raise TypeError(
437
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
438
+ f" {type(prompt)}."
439
+ )
440
+ elif batch_size != len(negative_prompt):
441
+ raise ValueError(
442
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
443
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
444
+ " the batch size of `prompt`."
445
+ )
446
+ else:
447
+ uncond_tokens = [negative_prompt, negative_prompt_2]
448
+
449
+ negative_prompt_embeds_list = []
450
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
451
+ if isinstance(self, TextualInversionLoaderMixin):
452
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
453
+
454
+ max_length = prompt_embeds.shape[1]
455
+ uncond_input = tokenizer(
456
+ negative_prompt,
457
+ padding="max_length",
458
+ max_length=max_length,
459
+ truncation=True,
460
+ return_tensors="pt",
461
+ )
462
+
463
+ negative_prompt_embeds = text_encoder(
464
+ uncond_input.input_ids.to(device),
465
+ output_hidden_states=True,
466
+ )
467
+ # We are only ALWAYS interested in the pooled output of the final text encoder
468
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
469
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
470
+
471
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
472
+
473
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
474
+
475
+ if self.text_encoder_2 is not None:
476
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
477
+ else:
478
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
479
+
480
+ bs_embed, seq_len, _ = prompt_embeds.shape
481
+
482
+ if do_classifier_free_guidance:
483
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
484
+ seq_len = negative_prompt_embeds.shape[1]
485
+
486
+ if self.text_encoder_2 is not None:
487
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
488
+ else:
489
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
490
+
491
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
492
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
493
+
494
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
495
+ bs_embed * num_images_per_prompt, -1
496
+ )
497
+ if do_classifier_free_guidance:
498
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
499
+ bs_embed * num_images_per_prompt, -1
500
+ )
501
+
502
+ if self.text_encoder is not None:
503
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
504
+ # Retrieve the original scale by scaling back the LoRA layers
505
+ unscale_lora_layers(self.text_encoder, lora_scale)
506
+
507
+ if self.text_encoder_2 is not None:
508
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
509
+ # Retrieve the original scale by scaling back the LoRA layers
510
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
511
+
512
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, class_tokens_mask
513
+
514
+ @property
515
+ def interrupt(self):
516
+ return self._interrupt
517
+
518
+ @torch.no_grad()
519
+ def __call__(
520
+ self,
521
+ prompt: Union[str, List[str]] = None,
522
+ prompt_2: Optional[Union[str, List[str]]] = None,
523
+ image: PipelineImageInput = None,
524
+ height: Optional[int] = None,
525
+ width: Optional[int] = None,
526
+ num_inference_steps: int = 50,
527
+ timesteps: List[int] = None,
528
+ sigmas: List[float] = None,
529
+ denoising_end: Optional[float] = None,
530
+ guidance_scale: float = 5.0,
531
+ negative_prompt: Optional[Union[str, List[str]]] = None,
532
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
533
+ num_images_per_prompt: Optional[int] = 1,
534
+ eta: float = 0.0,
535
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
536
+ latents: Optional[torch.Tensor] = None,
537
+ prompt_embeds: Optional[torch.Tensor] = None,
538
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
539
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
540
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
541
+ ip_adapter_image: Optional[PipelineImageInput] = None,
542
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
543
+ output_type: Optional[str] = "pil",
544
+ return_dict: bool = True,
545
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
546
+ callback_steps: int = 1,
547
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
548
+ guidance_rescale: float = 0.0,
549
+ original_size: Optional[Tuple[int, int]] = None,
550
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
551
+ target_size: Optional[Tuple[int, int]] = None,
552
+ negative_original_size: Optional[Tuple[int, int]] = None,
553
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
554
+ negative_target_size: Optional[Tuple[int, int]] = None,
555
+ adapter_conditioning_scale: Union[float, List[float]] = 1.0,
556
+ adapter_conditioning_factor: float = 1.0,
557
+ clip_skip: Optional[int] = None,
558
+ # Added parameters (for PhotoMaker)
559
+ input_id_images: PipelineImageInput = None,
560
+ start_merge_step: int = 10, # TODO: change to `style_strength_ratio` in the future
561
+ class_tokens_mask: Optional[torch.LongTensor] = None,
562
+ id_embeds: Optional[torch.FloatTensor] = None,
563
+ prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
564
+ pooled_prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
565
+ **kwargs,
566
+ ):
567
+ r"""
568
+ Function invoked when calling the pipeline for generation.
569
+ Only the parameters introduced by PhotoMaker are discussed here.
570
+ For explanations of the previous parameters in StableDiffusionXLControlNetPipeline, please refer to https://github.com/huggingface/diffusers/blob/v0.25.0/src/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py
571
+
572
+ Args:
573
+ input_id_images (`PipelineImageInput`, *optional*):
574
+ Input ID Image to work with PhotoMaker.
575
+ class_tokens_mask (`torch.LongTensor`, *optional*):
576
+ Pre-generated class token. When the `prompt_embeds` parameter is provided in advance, it is necessary to prepare the `class_tokens_mask` beforehand for marking out the position of class word.
577
+ prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
578
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
579
+ provided, text embeddings will be generated from `prompt` input argument.
580
+ pooled_prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
581
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
582
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
583
+
584
+ Returns:
585
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
586
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
587
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
588
+ """
589
+ height, width = self._default_height_width(height, width, image)
590
+ device = self._execution_device
591
+
592
+ use_adapter = True if image is not None else False
593
+ print(f"Use adapter: {use_adapter} | output size: {(height, width)}")
594
+ if use_adapter:
595
+ if isinstance(self.adapter, MultiAdapter):
596
+ adapter_input = []
597
+
598
+ for one_image in image:
599
+ one_image = _preprocess_adapter_image(one_image, height, width)
600
+ one_image = one_image.to(device=device, dtype=self.adapter.dtype)
601
+ adapter_input.append(one_image)
602
+ else:
603
+ adapter_input = _preprocess_adapter_image(image, height, width)
604
+ adapter_input = adapter_input.to(device=device, dtype=self.adapter.dtype)
605
+
606
+ original_size = original_size or (height, width)
607
+ target_size = target_size or (height, width)
608
+
609
+ # 1. Check inputs. Raise error if not correct
610
+ self.check_inputs(
611
+ prompt,
612
+ prompt_2,
613
+ height,
614
+ width,
615
+ callback_steps,
616
+ negative_prompt,
617
+ negative_prompt_2,
618
+ prompt_embeds,
619
+ negative_prompt_embeds,
620
+ pooled_prompt_embeds,
621
+ negative_pooled_prompt_embeds,
622
+ ip_adapter_image,
623
+ ip_adapter_image_embeds,
624
+ )
625
+ self._guidance_scale = guidance_scale
626
+ self._clip_skip = clip_skip
627
+
628
+ #
629
+ if prompt_embeds is not None and class_tokens_mask is None:
630
+ raise ValueError(
631
+ "If `prompt_embeds` are provided, `class_tokens_mask` also have to be passed. Make sure to generate `class_tokens_mask` from the same tokenizer that was used to generate `prompt_embeds`."
632
+ )
633
+ # check the input id images
634
+ if input_id_images is None:
635
+ raise ValueError(
636
+ "Provide `input_id_images`. Cannot leave `input_id_images` undefined for PhotoMaker pipeline."
637
+ )
638
+ if not isinstance(input_id_images, list):
639
+ input_id_images = [input_id_images]
640
+
641
+ # 2. Define call parameters
642
+ if prompt is not None and isinstance(prompt, str):
643
+ batch_size = 1
644
+ elif prompt is not None and isinstance(prompt, list):
645
+ batch_size = len(prompt)
646
+ else:
647
+ batch_size = prompt_embeds.shape[0]
648
+
649
+ device = self._execution_device
650
+
651
+ # 3. Encode input prompt
652
+ lora_scale = (
653
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
654
+ )
655
+
656
+ num_id_images = len(input_id_images)
657
+
658
+ (
659
+ prompt_embeds,
660
+ _,
661
+ pooled_prompt_embeds,
662
+ _,
663
+ class_tokens_mask,
664
+ ) = self.encode_prompt_with_trigger_word(
665
+ prompt=prompt,
666
+ prompt_2=prompt_2,
667
+ device=device,
668
+ num_id_images=num_id_images,
669
+ class_tokens_mask=class_tokens_mask,
670
+ num_images_per_prompt=num_images_per_prompt,
671
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
672
+ negative_prompt=negative_prompt,
673
+ negative_prompt_2=negative_prompt_2,
674
+ prompt_embeds=prompt_embeds,
675
+ negative_prompt_embeds=negative_prompt_embeds,
676
+ pooled_prompt_embeds=pooled_prompt_embeds,
677
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
678
+ lora_scale=lora_scale,
679
+ clip_skip=self._clip_skip,
680
+ )
681
+
682
+ # 4. Encode input prompt without the trigger word for delayed conditioning
683
+ # encode, remove trigger word token, then decode
684
+ tokens_text_only = self.tokenizer.encode(prompt, add_special_tokens=False)
685
+ trigger_word_token = self.tokenizer.convert_tokens_to_ids(self.trigger_word)
686
+ tokens_text_only.remove(trigger_word_token)
687
+ prompt_text_only = self.tokenizer.decode(tokens_text_only, add_special_tokens=False)
688
+ (
689
+ prompt_embeds_text_only,
690
+ negative_prompt_embeds,
691
+ pooled_prompt_embeds_text_only, # TODO: replace the pooled_prompt_embeds with text only prompt
692
+ negative_pooled_prompt_embeds,
693
+ ) = self.encode_prompt(
694
+ prompt=prompt_text_only,
695
+ prompt_2=prompt_2,
696
+ device=device,
697
+ num_images_per_prompt=num_images_per_prompt,
698
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
699
+ negative_prompt=negative_prompt,
700
+ negative_prompt_2=negative_prompt_2,
701
+ prompt_embeds=prompt_embeds_text_only,
702
+ negative_prompt_embeds=negative_prompt_embeds,
703
+ pooled_prompt_embeds=pooled_prompt_embeds_text_only,
704
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
705
+ lora_scale=lora_scale,
706
+ clip_skip=self._clip_skip,
707
+ )
708
+
709
+ # 5. Prepare the input ID images
710
+ dtype = next(self.id_encoder.parameters()).dtype
711
+ if not isinstance(input_id_images[0], torch.Tensor):
712
+ id_pixel_values = self.id_image_processor(input_id_images, return_tensors="pt").pixel_values
713
+
714
+ id_pixel_values = id_pixel_values.unsqueeze(0).to(device=device, dtype=dtype) # TODO: multiple prompts
715
+
716
+ # 6. Get the update text embedding with the stacked ID embedding
717
+ if id_embeds is not None:
718
+ id_embeds = id_embeds.unsqueeze(0).to(device=device, dtype=dtype)
719
+ prompt_embeds = self.id_encoder(id_pixel_values, prompt_embeds, class_tokens_mask, id_embeds)
720
+ else:
721
+ prompt_embeds = self.id_encoder(id_pixel_values, prompt_embeds, class_tokens_mask)
722
+
723
+ bs_embed, seq_len, _ = prompt_embeds.shape
724
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
725
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
726
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
727
+
728
+ # 6.1 Get the ip adapter embedding
729
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
730
+ image_embeds = self.prepare_ip_adapter_image_embeds(
731
+ ip_adapter_image,
732
+ ip_adapter_image_embeds,
733
+ device,
734
+ batch_size * num_images_per_prompt,
735
+ self.do_classifier_free_guidance,
736
+ )
737
+
738
+ # 7. Prepare timesteps
739
+ timesteps, num_inference_steps = retrieve_timesteps(
740
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
741
+ )
742
+
743
+ # 8. Prepare latent variables
744
+ num_channels_latents = self.unet.config.in_channels
745
+ latents = self.prepare_latents(
746
+ batch_size * num_images_per_prompt,
747
+ num_channels_latents,
748
+ height,
749
+ width,
750
+ prompt_embeds.dtype,
751
+ device,
752
+ generator,
753
+ latents,
754
+ )
755
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
756
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
757
+
758
+ # 8.5 Optionally get Guidance Scale Embedding
759
+ timestep_cond = None
760
+ if self.unet.config.time_cond_proj_dim is not None:
761
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
762
+ timestep_cond = self.get_guidance_scale_embedding(
763
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
764
+ ).to(device=device, dtype=latents.dtype)
765
+
766
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
767
+ if use_adapter:
768
+ if isinstance(self.adapter, MultiAdapter):
769
+ adapter_state = self.adapter(adapter_input, adapter_conditioning_scale)
770
+ for k, v in enumerate(adapter_state):
771
+ adapter_state[k] = v
772
+ else:
773
+ adapter_state = self.adapter(adapter_input)
774
+ for k, v in enumerate(adapter_state):
775
+ adapter_state[k] = v * adapter_conditioning_scale
776
+ if num_images_per_prompt > 1:
777
+ for k, v in enumerate(adapter_state):
778
+ adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
779
+ if self.do_classifier_free_guidance:
780
+ for k, v in enumerate(adapter_state):
781
+ adapter_state[k] = torch.cat([v] * 2, dim=0)
782
+
783
+ add_text_embeds = pooled_prompt_embeds
784
+ if self.text_encoder_2 is None:
785
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
786
+ else:
787
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
788
+
789
+ add_time_ids = self._get_add_time_ids(
790
+ original_size,
791
+ crops_coords_top_left,
792
+ target_size,
793
+ dtype=prompt_embeds.dtype,
794
+ text_encoder_projection_dim=text_encoder_projection_dim,
795
+ )
796
+ if negative_original_size is not None and negative_target_size is not None:
797
+ negative_add_time_ids = self._get_add_time_ids(
798
+ negative_original_size,
799
+ negative_crops_coords_top_left,
800
+ negative_target_size,
801
+ dtype=prompt_embeds.dtype,
802
+ text_encoder_projection_dim=text_encoder_projection_dim,
803
+ )
804
+ else:
805
+ negative_add_time_ids = add_time_ids
806
+
807
+ if self.do_classifier_free_guidance:
808
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
809
+
810
+ prompt_embeds = prompt_embeds.to(device)
811
+ add_text_embeds = add_text_embeds.to(device)
812
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
813
+
814
+ # 11. Denoising loop
815
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
816
+ # Apply denoising_end
817
+ if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
818
+ discrete_timestep_cutoff = int(
819
+ round(
820
+ self.scheduler.config.num_train_timesteps
821
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
822
+ )
823
+ )
824
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
825
+ timesteps = timesteps[:num_inference_steps]
826
+
827
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
828
+ for i, t in enumerate(timesteps):
829
+
830
+ # expand the latents if we are doing classifier free guidance
831
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
832
+
833
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
834
+
835
+ if i <= start_merge_step:
836
+ current_prompt_embeds = torch.cat(
837
+ [negative_prompt_embeds, prompt_embeds_text_only], dim=0
838
+ ) if self.do_classifier_free_guidance else prompt_embeds_text_only
839
+ add_text_embeds = torch.cat(
840
+ [negative_pooled_prompt_embeds, pooled_prompt_embeds_text_only], dim=0
841
+ ) if self.do_classifier_free_guidance else pooled_prompt_embeds_text_only
842
+ else:
843
+ current_prompt_embeds = torch.cat(
844
+ [negative_prompt_embeds, prompt_embeds], dim=0
845
+ ) if self.do_classifier_free_guidance else prompt_embeds
846
+ add_text_embeds = torch.cat(
847
+ [negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0
848
+ ) if self.do_classifier_free_guidance else pooled_prompt_embeds
849
+
850
+ if i < int(num_inference_steps * adapter_conditioning_factor) and (use_adapter):
851
+ down_intrablock_additional_residuals = [state.clone() for state in adapter_state]
852
+ else:
853
+ down_intrablock_additional_residuals = None
854
+
855
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
856
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
857
+ added_cond_kwargs["image_embeds"] = image_embeds
858
+
859
+ # predict the noise residual
860
+ noise_pred = self.unet(
861
+ latent_model_input,
862
+ t,
863
+ encoder_hidden_states=current_prompt_embeds,
864
+ timestep_cond=timestep_cond,
865
+ cross_attention_kwargs=cross_attention_kwargs,
866
+ down_intrablock_additional_residuals=down_intrablock_additional_residuals,
867
+ added_cond_kwargs=added_cond_kwargs,
868
+ return_dict=False,
869
+ )[0]
870
+
871
+ # perform guidance
872
+ if self.do_classifier_free_guidance:
873
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
874
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
875
+
876
+ if self.do_classifier_free_guidance and guidance_rescale > 0.0:
877
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
878
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
879
+
880
+ # compute the previous noisy sample x_t -> x_t-1
881
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
882
+
883
+ # call the callback, if provided
884
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
885
+ progress_bar.update()
886
+ if callback is not None and i % callback_steps == 0:
887
+ step_idx = i // getattr(self.scheduler, "order", 1)
888
+ callback(step_idx, t, latents)
889
+
890
+ if not output_type == "latent":
891
+ # make sure the VAE is in float32 mode, as it overflows in float16
892
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
893
+
894
+ if needs_upcasting:
895
+ self.upcast_vae()
896
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
897
+
898
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
899
+
900
+ # cast back to fp16 if needed
901
+ if needs_upcasting:
902
+ self.vae.to(dtype=torch.float16)
903
+ else:
904
+ image = latents
905
+ return StableDiffusionXLPipelineOutput(images=image)
906
+
907
+ image = self.image_processor.postprocess(image, output_type=output_type)
908
+
909
+ # Offload all models
910
+ self.maybe_free_model_hooks()
911
+
912
+ if not return_dict:
913
+ return (image,)
914
+
915
+ return StableDiffusionXLPipelineOutput(images=image)
PhotoMaker-V2/requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diffusers
2
+ torch
3
+ torchvision
4
+ transformers
5
+ accelerate
6
+ safetensors
7
+ einops
8
+ onnxruntime-gpu
9
+ spaces
10
+ omegaconf
11
+ peft
12
+ huggingface-hub
13
+ insightface==0.7.3
PhotoMaker-V2/style_template.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ style_list = [
2
+ {
3
+ "name": "(No style)",
4
+ "prompt": "{prompt}",
5
+ "negative_prompt": "",
6
+ },
7
+ {
8
+ "name": "Cinematic",
9
+ "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
10
+ "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
11
+ },
12
+ {
13
+ "name": "Disney Charactor",
14
+ "prompt": "A Pixar animation character of {prompt} . pixar-style, studio anime, Disney, high-quality",
15
+ "negative_prompt": "lowres, bad anatomy, bad hands, text, bad eyes, bad arms, bad legs, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, blurry, grayscale, noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo",
16
+ },
17
+ {
18
+ "name": "Digital Art",
19
+ "prompt": "concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed",
20
+ "negative_prompt": "photo, photorealistic, realism, ugly",
21
+ },
22
+ {
23
+ "name": "Photographic (Default)",
24
+ "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed",
25
+ "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
26
+ },
27
+ {
28
+ "name": "Fantasy art",
29
+ "prompt": "ethereal fantasy concept art of {prompt} . magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy",
30
+ "negative_prompt": "photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white",
31
+ },
32
+ {
33
+ "name": "Neonpunk",
34
+ "prompt": "neonpunk style {prompt} . cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional",
35
+ "negative_prompt": "painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured",
36
+ },
37
+ {
38
+ "name": "Enhance",
39
+ "prompt": "breathtaking {prompt} . award-winning, professional, highly detailed",
40
+ "negative_prompt": "ugly, deformed, noisy, blurry, distorted, grainy",
41
+ },
42
+ {
43
+ "name": "Comic book",
44
+ "prompt": "comic {prompt} . graphic illustration, comic art, graphic novel art, vibrant, highly detailed",
45
+ "negative_prompt": "photograph, deformed, glitch, noisy, realistic, stock photo",
46
+ },
47
+ {
48
+ "name": "Lowpoly",
49
+ "prompt": "low-poly style {prompt} . low-poly game art, polygon mesh, jagged, blocky, wireframe edges, centered composition",
50
+ "negative_prompt": "noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo",
51
+ },
52
+ {
53
+ "name": "Line art",
54
+ "prompt": "line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics",
55
+ "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, blurry, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, mutated, realism, realistic, impressionism, expressionism, oil, acrylic",
56
+ }
57
+ ]
58
+
59
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}