Paper99 commited on
Commit
a866b04
1 Parent(s): 9c243c8

Update PhotoMaker V2 gradio demo

Browse files
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
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
  title: PhotoMaker V2
3
- emoji: 🌍
4
  colorFrom: pink
5
- colorTo: gray
6
  sdk: gradio
7
  sdk_version: 4.37.2
8
  app_file: app.py
@@ -10,4 +10,4 @@ pinned: false
10
  license: apache-2.0
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
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
 
10
  license: apache-2.0
11
  ---
12
 
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision.transforms.functional as TF
3
+ import numpy as np
4
+ import random
5
+ import os
6
+ import sys
7
+
8
+ from diffusers.utils import load_image
9
+ from diffusers import EulerDiscreteScheduler, T2IAdapter
10
+
11
+ from huggingface_hub import hf_hub_download
12
+ import spaces
13
+ import gradio as gr
14
+
15
+ from model.pipeline_t2i_adapter import PhotoMakerStableDiffusionXLAdapterPipeline
16
+ from face_utils import FaceAnalysis2, analyze_faces
17
+
18
+ from style_template import styles
19
+ from aspect_ratio_template import aspect_ratios
20
+
21
+ # global variable
22
+ base_model_path = 'SG161222/RealVisXL_V4.0'
23
+ face_detector = FaceAnalysis2(providers=['CUDAExecutionProvider'], allowed_modules=['detection', 'recognition'])
24
+ face_detector.prepare(ctx_id=0, det_size=(640, 640))
25
+
26
+ try:
27
+ if torch.cuda.is_available():
28
+ device = "cuda"
29
+ elif sys.platform == "darwin" and torch.backends.mps.is_available():
30
+ device = "mps"
31
+ else:
32
+ device = "cpu"
33
+ except:
34
+ device = "cpu"
35
+
36
+ MAX_SEED = np.iinfo(np.int32).max
37
+ STYLE_NAMES = list(styles.keys())
38
+ DEFAULT_STYLE_NAME = "Photographic (Default)"
39
+ ASPECT_RATIO_LABELS = list(aspect_ratios)
40
+ DEFAULT_ASPECT_RATIO = ASPECT_RATIO_LABELS[0]
41
+
42
+ enable_doodle_arg = False
43
+ photomaker_ckpt = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v2.bin", repo_type="model")
44
+
45
+ torch_dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
46
+ if device == "mps":
47
+ torch_dtype = torch.float16
48
+
49
+ # load adapter
50
+ adapter = T2IAdapter.from_pretrained(
51
+ "TencentARC/t2i-adapter-sketch-sdxl-1.0", torch_dtype=torch_dtype, variant="fp16"
52
+ ).to(device)
53
+
54
+ pipe = PhotoMakerStableDiffusionXLAdapterPipeline.from_pretrained(
55
+ base_model_path,
56
+ adapter=adapter,
57
+ torch_dtype=torch_dtype,
58
+ use_safetensors=True,
59
+ variant="fp16",
60
+ ).to(device)
61
+
62
+ pipe.load_photomaker_adapter(
63
+ os.path.dirname(photomaker_ckpt),
64
+ subfolder="",
65
+ weight_name=os.path.basename(photomaker_ckpt),
66
+ trigger_word="img",
67
+ pm_version="v2",
68
+ )
69
+ pipe.id_encoder.to(device)
70
+
71
+ pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
72
+ # pipe.set_adapters(["photomaker"], adapter_weights=[1.0])
73
+ pipe.fuse_lora()
74
+ pipe.to(device)
75
+
76
+
77
+ @spaces.GPU
78
+ def generate_image(
79
+ upload_images,
80
+ prompt,
81
+ negative_prompt,
82
+ aspect_ratio_name,
83
+ style_name,
84
+ num_steps,
85
+ style_strength_ratio,
86
+ num_outputs,
87
+ guidance_scale,
88
+ seed,
89
+ use_doodle,
90
+ sketch_image,
91
+ adapter_conditioning_scale,
92
+ adapter_conditioning_factor,
93
+ progress=gr.Progress(track_tqdm=True)
94
+ ):
95
+ if use_doodle:
96
+ sketch_image = sketch_image["composite"]
97
+ r, g, b, a = sketch_image.split()
98
+ sketch_image = a.convert("RGB")
99
+ sketch_image = TF.to_tensor(sketch_image) > 0.5 # Inversion
100
+ sketch_image = TF.to_pil_image(sketch_image.to(torch.float32))
101
+ adapter_conditioning_scale = adapter_conditioning_scale
102
+ adapter_conditioning_factor = adapter_conditioning_factor
103
+ else:
104
+ adapter_conditioning_scale = 0.
105
+ adapter_conditioning_factor = 0.
106
+ sketch_image = None
107
+
108
+ # check the trigger word
109
+ image_token_id = pipe.tokenizer.convert_tokens_to_ids(pipe.trigger_word)
110
+ input_ids = pipe.tokenizer.encode(prompt)
111
+ if image_token_id not in input_ids:
112
+ raise gr.Error(f"Cannot find the trigger word '{pipe.trigger_word}' in text prompt! Please refer to step 2️⃣")
113
+
114
+ if input_ids.count(image_token_id) > 1:
115
+ raise gr.Error(f"Cannot use multiple trigger words '{pipe.trigger_word}' in text prompt!")
116
+
117
+ # determine output dimensions by the aspect ratio
118
+ output_w, output_h = aspect_ratios[aspect_ratio_name]
119
+ print(f"[Debug] Generate image using aspect ratio [{aspect_ratio_name}] => {output_w} x {output_h}")
120
+
121
+ # apply the style template
122
+ prompt, negative_prompt = apply_style(style_name, prompt, negative_prompt)
123
+
124
+ if upload_images is None:
125
+ raise gr.Error(f"Cannot find any input face image! Please refer to step 1️⃣")
126
+
127
+ input_id_images = []
128
+ for img in upload_images:
129
+ input_id_images.append(load_image(img))
130
+
131
+ id_embed_list = []
132
+
133
+ for img in input_id_images:
134
+ img = np.array(img)
135
+ img = img[:, :, ::-1]
136
+ faces = analyze_faces(face_detector, img)
137
+ if len(faces) > 0:
138
+ id_embed_list.append(torch.from_numpy((faces[0]['embedding'])))
139
+
140
+ if len(id_embed_list) == 0:
141
+ raise gr.Error(f"No face detected, please update the input face image(s)")
142
+
143
+ id_embeds = torch.stack(id_embed_list)
144
+
145
+ generator = torch.Generator(device=device).manual_seed(seed)
146
+
147
+ print("Start inference...")
148
+ print(f"[Debug] Seed: {seed}")
149
+ print(f"[Debug] Prompt: {prompt}, \n[Debug] Neg Prompt: {negative_prompt}")
150
+ start_merge_step = int(float(style_strength_ratio) / 100 * num_steps)
151
+ if start_merge_step > 30:
152
+ start_merge_step = 30
153
+ print(start_merge_step)
154
+ images = pipe(
155
+ prompt=prompt,
156
+ width=output_w,
157
+ height=output_h,
158
+ input_id_images=input_id_images,
159
+ negative_prompt=negative_prompt,
160
+ num_images_per_prompt=num_outputs,
161
+ num_inference_steps=num_steps,
162
+ start_merge_step=start_merge_step,
163
+ generator=generator,
164
+ guidance_scale=guidance_scale,
165
+ id_embeds=id_embeds,
166
+ image=sketch_image,
167
+ adapter_conditioning_scale=adapter_conditioning_scale,
168
+ adapter_conditioning_factor=adapter_conditioning_factor,
169
+ ).images
170
+ return images, gr.update(visible=True)
171
+
172
+ def swap_to_gallery(images):
173
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
174
+
175
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
176
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
177
+
178
+ def remove_back_to_files():
179
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
180
+
181
+ def change_doodle_space(use_doodle):
182
+ if use_doodle:
183
+ return gr.update(visible=True)
184
+ else:
185
+ return gr.update(visible=False)
186
+
187
+ def remove_tips():
188
+ return gr.update(visible=False)
189
+
190
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
191
+ if randomize_seed:
192
+ seed = random.randint(0, MAX_SEED)
193
+ return seed
194
+
195
+ def apply_style(style_name: str, positive: str, negative: str = "") -> tuple[str, str]:
196
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
197
+ return p.replace("{prompt}", positive), n + ' ' + negative
198
+
199
+ def get_image_path_list(folder_name):
200
+ image_basename_list = os.listdir(folder_name)
201
+ image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list])
202
+ return image_path_list
203
+
204
+ def get_example():
205
+ case = [
206
+ [
207
+ get_image_path_list('./examples/scarletthead_woman'),
208
+ "instagram photo, portrait photo of a woman img, colorful, perfect face, natural skin, hard shadows, film grain",
209
+ "(No style)",
210
+ "(asymmetry, worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), open mouth",
211
+ ],
212
+ [
213
+ get_image_path_list('./examples/newton_man'),
214
+ "sci-fi, closeup portrait photo of a man img wearing the sunglasses in Iron man suit, face, slim body, high quality, film grain",
215
+ "(No style)",
216
+ "(asymmetry, worst quality, low quality, illustration, 3d, 2d, painting, cartoons, sketch), open mouth",
217
+ ],
218
+ ]
219
+ return case
220
+
221
+ ### Description and style
222
+ logo = r"""
223
+ <center><img src='https://photo-maker.github.io/assets/logo.png' alt='PhotoMaker logo' style="width:80px; margin-bottom:10px"></center>
224
+ """
225
+ title = r"""
226
+ <h1 align="center">PhotoMaker V2: Improved ID Fidelity and Better Controllability than PhotoMaker V1</h1>
227
+ """
228
+
229
+ description = r"""
230
+ <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>
231
+ The details of PhotoMaker V2 can be found in
232
+ <br>
233
+ <br>
234
+ 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).
235
+ <br>
236
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
237
+ 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>
238
+ 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>
239
+ 3️⃣ Choose your preferred style template.<br>
240
+ 4️⃣ <b>(Optional: but new feature)</b> Select the ‘Enable Drawing Doodle...’ option and draw on the canvas<br>
241
+ 5️⃣ Click the <b>Submit</b> button to start customizing.
242
+ """
243
+
244
+ article = r"""
245
+
246
+ If PhotoMaker V2 is helpful, please help to ⭐ the <a href='https://github.com/TencentARC/PhotoMaker' target='_blank'>Github Repo</a>. Thanks!
247
+ [![GitHub Stars](https://img.shields.io/github/stars/TencentARC/PhotoMaker?style=social)](https://github.com/TencentARC/PhotoMaker)
248
+ ---
249
+ 📝 **Citation**
250
+ <br>
251
+ If our work is useful for your research, please consider citing:
252
+
253
+ ```bibtex
254
+ @article{li2023photomaker,
255
+ title={PhotoMaker: Customizing Realistic Human Photos via Stacked ID Embedding},
256
+ author={Li, Zhen and Cao, Mingdeng and Wang, Xintao and Qi, Zhongang and Cheng, Ming-Ming and Shan, Ying},
257
+ booktitle={IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
258
+ year={2024}
259
+ }
260
+ ```
261
+ 📋 **License**
262
+ <br>
263
+ Apache-2.0 LICENSE. Please refer to the [LICENSE file](https://huggingface.co/TencentARC/PhotoMaker/blob/main/LICENSE) for details.
264
+
265
+ 📧 **Contact**
266
+ <br>
267
+ If you have any questions, please feel free to reach me out at <b>zhenli1031@gmail.com</b>.
268
+ """
269
+
270
+ tips = r"""
271
+ ### Usage tips of PhotoMaker
272
+ 1. Upload **more photos**of the person to be customized to **improve ID fidelty**.
273
+ 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.
274
+ 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.
275
+ """
276
+ # We have provided some generate examples and comparisons at: [this website]().
277
+
278
+ css = '''
279
+ .gradio-container {width: 85% !important}
280
+ '''
281
+ with gr.Blocks(css=css) as demo:
282
+ gr.Markdown(logo)
283
+ gr.Markdown(title)
284
+ gr.Markdown(description)
285
+ # gr.DuplicateButton(
286
+ # value="Duplicate Space for private use ",
287
+ # elem_id="duplicate-button",
288
+ # visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
289
+ # )
290
+ with gr.Row():
291
+ with gr.Column():
292
+ files = gr.Files(
293
+ label="Drag (Select) 1 or more photos of your face",
294
+ file_types=["image"]
295
+ )
296
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200)
297
+ with gr.Column(visible=False) as clear_button:
298
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
299
+ prompt = gr.Textbox(label="Prompt",
300
+ info="Try something like 'a photo of a man/woman img', 'img' is the trigger word.",
301
+ placeholder="A photo of a [man/woman img]...")
302
+ style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)
303
+ aspect_ratio = gr.Dropdown(label="Output aspect ratio", choices=ASPECT_RATIO_LABELS, value=DEFAULT_ASPECT_RATIO)
304
+ submit = gr.Button("Submit")
305
+
306
+ enable_doodle = gr.Checkbox(
307
+ label="Enable Drawing Doodle for Control", value=enable_doodle_arg,
308
+ 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)",
309
+ )
310
+ with gr.Accordion("T2I-Adapter-Doodle (Optional)", visible=False) as doodle_space:
311
+ with gr.Row():
312
+ sketch_image = gr.Sketchpad(
313
+ label="Canvas",
314
+ type="pil",
315
+ crop_size=[1024,1024],
316
+ layers=False,
317
+ canvas_size=(350, 350),
318
+ brush=gr.Brush(default_size=5, colors=["#000000"], color_mode="fixed")
319
+ )
320
+ with gr.Group():
321
+ adapter_conditioning_scale = gr.Slider(
322
+ label="Adapter conditioning scale",
323
+ minimum=0.5,
324
+ maximum=1,
325
+ step=0.1,
326
+ value=0.7,
327
+ )
328
+ adapter_conditioning_factor = gr.Slider(
329
+ label="Adapter conditioning factor",
330
+ info="Fraction of timesteps for which adapter should be applied",
331
+ minimum=0.5,
332
+ maximum=1,
333
+ step=0.1,
334
+ value=0.8,
335
+ )
336
+ with gr.Accordion(open=False, label="Advanced Options"):
337
+ negative_prompt = gr.Textbox(
338
+ label="Negative Prompt",
339
+ placeholder="low quality",
340
+ 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",
341
+ )
342
+ num_steps = gr.Slider(
343
+ label="Number of sample steps",
344
+ minimum=20,
345
+ maximum=100,
346
+ step=1,
347
+ value=50,
348
+ )
349
+ style_strength_ratio = gr.Slider(
350
+ label="Style strength (%)",
351
+ minimum=15,
352
+ maximum=50,
353
+ step=1,
354
+ value=20,
355
+ )
356
+ num_outputs = gr.Slider(
357
+ label="Number of output images",
358
+ minimum=1,
359
+ maximum=4,
360
+ step=1,
361
+ value=2,
362
+ )
363
+ guidance_scale = gr.Slider(
364
+ label="Guidance scale",
365
+ minimum=0.1,
366
+ maximum=10.0,
367
+ step=0.1,
368
+ value=5,
369
+ )
370
+ seed = gr.Slider(
371
+ label="Seed",
372
+ minimum=0,
373
+ maximum=MAX_SEED,
374
+ step=1,
375
+ value=0,
376
+ )
377
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
378
+ with gr.Column():
379
+ gallery = gr.Gallery(label="Generated Images")
380
+ usage_tips = gr.Markdown(label="Usage tips of PhotoMaker", value=tips ,visible=False)
381
+
382
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
383
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
384
+ enable_doodle.select(fn=change_doodle_space, inputs=enable_doodle, outputs=doodle_space)
385
+
386
+ input_list = [
387
+ files,
388
+ prompt,
389
+ negative_prompt,
390
+ aspect_ratio,
391
+ style,
392
+ num_steps,
393
+ style_strength_ratio,
394
+ num_outputs,
395
+ guidance_scale,
396
+ seed,
397
+ enable_doodle,
398
+ sketch_image,
399
+ adapter_conditioning_scale,
400
+ adapter_conditioning_factor
401
+ ]
402
+
403
+ submit.click(
404
+ fn=remove_tips,
405
+ outputs=usage_tips,
406
+ ).then(
407
+ fn=randomize_seed_fn,
408
+ inputs=[seed, randomize_seed],
409
+ outputs=seed,
410
+ queue=False,
411
+ api_name=False,
412
+ ).then(
413
+ fn=generate_image,
414
+ inputs=input_list,
415
+ outputs=[gallery, usage_tips]
416
+ )
417
+
418
+ gr.Examples(
419
+ examples=get_example(),
420
+ inputs=[files, prompt, style, negative_prompt],
421
+ run_on_click=True,
422
+ fn=upload_example_to_gallery,
423
+ outputs=[uploaded_files, clear_button, files],
424
+ )
425
+
426
+ gr.Markdown(article)
427
+
428
+ demo.launch()
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}
examples/newton_man/newton_0.jpg ADDED
examples/newton_man/newton_1.jpg ADDED
examples/newton_man/newton_3.jpg ADDED
examples/scarletthead_woman/scarlett_0.jpg ADDED
examples/scarletthead_woman/scarlett_1.jpg ADDED
examples/scarletthead_woman/scarlett_2.jpg ADDED
examples/scarletthead_woman/scarlett_3.jpg ADDED
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 []
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()
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)
pipeline_t2i_adapter.py ADDED
@@ -0,0 +1,914 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #####
2
+ # Modified from https://github.com/huggingface/diffusers/blob/v0.29.1/src/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.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 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.trigger_word = trigger_word
253
+ # load finetuned CLIP image encoder and fuse module here if it has not been registered to the pipeline yet
254
+ print(f"Loading PhotoMaker {pm_version} components [1] id_encoder from [{pretrained_model_name_or_path_or_dict}]...")
255
+ self.id_image_processor = CLIPImageProcessor()
256
+ if pm_version == "v1": # PhotoMaker v1
257
+ id_encoder = PhotoMakerIDEncoder()
258
+ elif pm_version == "v2": # PhotoMaker v2
259
+ id_encoder = PhotoMakerIDEncoder_CLIPInsightfaceExtendtoken()
260
+ else:
261
+ raise NotImplementedError(f"The PhotoMaker version [{pm_version}] does not support")
262
+
263
+ id_encoder.load_state_dict(state_dict["id_encoder"], strict=True)
264
+ id_encoder = id_encoder.to(self.device, dtype=self.unet.dtype)
265
+ self.id_encoder = id_encoder
266
+
267
+ # load lora into models
268
+ print(f"Loading PhotoMaker {pm_version} components [2] lora_weights from [{pretrained_model_name_or_path_or_dict}]")
269
+ self.load_lora_weights(state_dict["lora_weights"], adapter_name="photomaker")
270
+
271
+ # Add trigger word token
272
+ if self.tokenizer is not None:
273
+ self.tokenizer.add_tokens([self.trigger_word], special_tokens=True)
274
+
275
+ self.tokenizer_2.add_tokens([self.trigger_word], special_tokens=True)
276
+
277
+
278
+ def encode_prompt_with_trigger_word(
279
+ self,
280
+ prompt: str,
281
+ prompt_2: Optional[str] = None,
282
+ device: Optional[torch.device] = None,
283
+ num_images_per_prompt: int = 1,
284
+ do_classifier_free_guidance: bool = True,
285
+ negative_prompt: Optional[str] = None,
286
+ negative_prompt_2: Optional[str] = None,
287
+ prompt_embeds: Optional[torch.Tensor] = None,
288
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
289
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
290
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
291
+ lora_scale: Optional[float] = None,
292
+ clip_skip: Optional[int] = None,
293
+ ### Added args
294
+ num_id_images: int = 1,
295
+ class_tokens_mask: Optional[torch.LongTensor] = None,
296
+ ):
297
+ device = device or self._execution_device
298
+
299
+ # set lora scale so that monkey patched LoRA
300
+ # function of text encoder can correctly access it
301
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
302
+ self._lora_scale = lora_scale
303
+
304
+ # dynamically adjust the LoRA scale
305
+ if self.text_encoder is not None:
306
+ if not USE_PEFT_BACKEND:
307
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
308
+ else:
309
+ scale_lora_layers(self.text_encoder, lora_scale)
310
+
311
+ if self.text_encoder_2 is not None:
312
+ if not USE_PEFT_BACKEND:
313
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
314
+ else:
315
+ scale_lora_layers(self.text_encoder_2, lora_scale)
316
+
317
+ prompt = [prompt] if isinstance(prompt, str) else prompt
318
+
319
+ if prompt is not None:
320
+ batch_size = len(prompt)
321
+ else:
322
+ batch_size = prompt_embeds.shape[0]
323
+
324
+ # Find the token id of the trigger word
325
+ image_token_id = self.tokenizer_2.convert_tokens_to_ids(self.trigger_word)
326
+
327
+ # Define tokenizers and text encoders
328
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
329
+ text_encoders = (
330
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
331
+ )
332
+
333
+ if prompt_embeds is None:
334
+ prompt_2 = prompt_2 or prompt
335
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
336
+
337
+ # textual inversion: process multi-vector tokens if necessary
338
+ prompt_embeds_list = []
339
+ prompts = [prompt, prompt_2]
340
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
341
+ if isinstance(self, TextualInversionLoaderMixin):
342
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
343
+
344
+ text_inputs = tokenizer(
345
+ prompt,
346
+ padding="max_length",
347
+ max_length=tokenizer.model_max_length,
348
+ truncation=True,
349
+ return_tensors="pt",
350
+ )
351
+
352
+ text_input_ids = text_inputs.input_ids
353
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
354
+
355
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
356
+ text_input_ids, untruncated_ids
357
+ ):
358
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
359
+ print(
360
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
361
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
362
+ )
363
+
364
+ clean_index = 0
365
+ clean_input_ids = []
366
+ class_token_index = []
367
+ # Find out the corresponding class word token based on the newly added trigger word token
368
+ for i, token_id in enumerate(text_input_ids.tolist()[0]):
369
+ if token_id == image_token_id:
370
+ class_token_index.append(clean_index - 1)
371
+ else:
372
+ clean_input_ids.append(token_id)
373
+ clean_index += 1
374
+
375
+ if len(class_token_index) != 1:
376
+ raise ValueError(
377
+ f"PhotoMaker currently does not support multiple trigger words in a single prompt.\
378
+ Trigger word: {self.trigger_word}, Prompt: {prompt}."
379
+ )
380
+ class_token_index = class_token_index[0]
381
+
382
+ # Expand the class word token and corresponding mask
383
+ class_token = clean_input_ids[class_token_index]
384
+ clean_input_ids = clean_input_ids[:class_token_index] + [class_token] * num_id_images * self.num_tokens + \
385
+ clean_input_ids[class_token_index+1:]
386
+
387
+ # Truncation or padding
388
+ max_len = tokenizer.model_max_length
389
+ if len(clean_input_ids) > max_len:
390
+ clean_input_ids = clean_input_ids[:max_len]
391
+ else:
392
+ clean_input_ids = clean_input_ids + [tokenizer.pad_token_id] * (
393
+ max_len - len(clean_input_ids)
394
+ )
395
+
396
+ class_tokens_mask = [True if class_token_index <= i < class_token_index+(num_id_images * self.num_tokens) else False \
397
+ for i in range(len(clean_input_ids))]
398
+
399
+ clean_input_ids = torch.tensor(clean_input_ids, dtype=torch.long).unsqueeze(0)
400
+ class_tokens_mask = torch.tensor(class_tokens_mask, dtype=torch.bool).unsqueeze(0)
401
+
402
+ prompt_embeds = text_encoder(clean_input_ids.to(device), output_hidden_states=True)
403
+
404
+ # We are only ALWAYS interested in the pooled output of the final text encoder
405
+ pooled_prompt_embeds = prompt_embeds[0]
406
+ if clip_skip is None:
407
+ prompt_embeds = prompt_embeds.hidden_states[-2]
408
+ else:
409
+ # "2" because SDXL always indexes from the penultimate layer.
410
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
411
+
412
+ prompt_embeds_list.append(prompt_embeds)
413
+
414
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
415
+
416
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
417
+ class_tokens_mask = class_tokens_mask.to(device=device) # TODO: ignoring two-prompt case
418
+ # get unconditional embeddings for classifier free guidance
419
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
420
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
421
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
422
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
423
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
424
+ negative_prompt = negative_prompt or ""
425
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
426
+
427
+ # normalize str to list
428
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
429
+ negative_prompt_2 = (
430
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
431
+ )
432
+
433
+ uncond_tokens: List[str]
434
+ if prompt is not None and type(prompt) is not type(negative_prompt):
435
+ raise TypeError(
436
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
437
+ f" {type(prompt)}."
438
+ )
439
+ elif batch_size != len(negative_prompt):
440
+ raise ValueError(
441
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
442
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
443
+ " the batch size of `prompt`."
444
+ )
445
+ else:
446
+ uncond_tokens = [negative_prompt, negative_prompt_2]
447
+
448
+ negative_prompt_embeds_list = []
449
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
450
+ if isinstance(self, TextualInversionLoaderMixin):
451
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
452
+
453
+ max_length = prompt_embeds.shape[1]
454
+ uncond_input = tokenizer(
455
+ negative_prompt,
456
+ padding="max_length",
457
+ max_length=max_length,
458
+ truncation=True,
459
+ return_tensors="pt",
460
+ )
461
+
462
+ negative_prompt_embeds = text_encoder(
463
+ uncond_input.input_ids.to(device),
464
+ output_hidden_states=True,
465
+ )
466
+ # We are only ALWAYS interested in the pooled output of the final text encoder
467
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
468
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
469
+
470
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
471
+
472
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
473
+
474
+ if self.text_encoder_2 is not None:
475
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
476
+ else:
477
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
478
+
479
+ bs_embed, seq_len, _ = prompt_embeds.shape
480
+
481
+ if do_classifier_free_guidance:
482
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
483
+ seq_len = negative_prompt_embeds.shape[1]
484
+
485
+ if self.text_encoder_2 is not None:
486
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
487
+ else:
488
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
489
+
490
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
491
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
492
+
493
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
494
+ bs_embed * num_images_per_prompt, -1
495
+ )
496
+ if do_classifier_free_guidance:
497
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
498
+ bs_embed * num_images_per_prompt, -1
499
+ )
500
+
501
+ if self.text_encoder is not None:
502
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
503
+ # Retrieve the original scale by scaling back the LoRA layers
504
+ unscale_lora_layers(self.text_encoder, lora_scale)
505
+
506
+ if self.text_encoder_2 is not None:
507
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
508
+ # Retrieve the original scale by scaling back the LoRA layers
509
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
510
+
511
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, class_tokens_mask
512
+
513
+ @property
514
+ def interrupt(self):
515
+ return self._interrupt
516
+
517
+ @torch.no_grad()
518
+ def __call__(
519
+ self,
520
+ prompt: Union[str, List[str]] = None,
521
+ prompt_2: Optional[Union[str, List[str]]] = None,
522
+ image: PipelineImageInput = None,
523
+ height: Optional[int] = None,
524
+ width: Optional[int] = None,
525
+ num_inference_steps: int = 50,
526
+ timesteps: List[int] = None,
527
+ sigmas: List[float] = None,
528
+ denoising_end: Optional[float] = None,
529
+ guidance_scale: float = 5.0,
530
+ negative_prompt: Optional[Union[str, List[str]]] = None,
531
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
532
+ num_images_per_prompt: Optional[int] = 1,
533
+ eta: float = 0.0,
534
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
535
+ latents: Optional[torch.Tensor] = None,
536
+ prompt_embeds: Optional[torch.Tensor] = None,
537
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
538
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
539
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
540
+ ip_adapter_image: Optional[PipelineImageInput] = None,
541
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
542
+ output_type: Optional[str] = "pil",
543
+ return_dict: bool = True,
544
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
545
+ callback_steps: int = 1,
546
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
547
+ guidance_rescale: float = 0.0,
548
+ original_size: Optional[Tuple[int, int]] = None,
549
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
550
+ target_size: Optional[Tuple[int, int]] = None,
551
+ negative_original_size: Optional[Tuple[int, int]] = None,
552
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
553
+ negative_target_size: Optional[Tuple[int, int]] = None,
554
+ adapter_conditioning_scale: Union[float, List[float]] = 1.0,
555
+ adapter_conditioning_factor: float = 1.0,
556
+ clip_skip: Optional[int] = None,
557
+ # Added parameters (for PhotoMaker)
558
+ input_id_images: PipelineImageInput = None,
559
+ start_merge_step: int = 10, # TODO: change to `style_strength_ratio` in the future
560
+ class_tokens_mask: Optional[torch.LongTensor] = None,
561
+ id_embeds: Optional[torch.FloatTensor] = None,
562
+ prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
563
+ pooled_prompt_embeds_text_only: Optional[torch.FloatTensor] = None,
564
+ **kwargs,
565
+ ):
566
+ r"""
567
+ Function invoked when calling the pipeline for generation.
568
+ Only the parameters introduced by PhotoMaker are discussed here.
569
+ 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
570
+
571
+ Args:
572
+ input_id_images (`PipelineImageInput`, *optional*):
573
+ Input ID Image to work with PhotoMaker.
574
+ class_tokens_mask (`torch.LongTensor`, *optional*):
575
+ 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.
576
+ prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
577
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
578
+ provided, text embeddings will be generated from `prompt` input argument.
579
+ pooled_prompt_embeds_text_only (`torch.FloatTensor`, *optional*):
580
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
581
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
582
+
583
+ Returns:
584
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
585
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
586
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
587
+ """
588
+ height, width = self._default_height_width(height, width, image)
589
+ device = self._execution_device
590
+
591
+ use_adapter = True if image is not None else False
592
+ print(f"Use adapter: {use_adapter} | output size: {(height, width)}")
593
+ if use_adapter:
594
+ if isinstance(self.adapter, MultiAdapter):
595
+ adapter_input = []
596
+
597
+ for one_image in image:
598
+ one_image = _preprocess_adapter_image(one_image, height, width)
599
+ one_image = one_image.to(device=device, dtype=self.adapter.dtype)
600
+ adapter_input.append(one_image)
601
+ else:
602
+ adapter_input = _preprocess_adapter_image(image, height, width)
603
+ adapter_input = adapter_input.to(device=device, dtype=self.adapter.dtype)
604
+
605
+ original_size = original_size or (height, width)
606
+ target_size = target_size or (height, width)
607
+
608
+ # 1. Check inputs. Raise error if not correct
609
+ self.check_inputs(
610
+ prompt,
611
+ prompt_2,
612
+ height,
613
+ width,
614
+ callback_steps,
615
+ negative_prompt,
616
+ negative_prompt_2,
617
+ prompt_embeds,
618
+ negative_prompt_embeds,
619
+ pooled_prompt_embeds,
620
+ negative_pooled_prompt_embeds,
621
+ ip_adapter_image,
622
+ ip_adapter_image_embeds,
623
+ )
624
+ self._guidance_scale = guidance_scale
625
+ self._clip_skip = clip_skip
626
+
627
+ #
628
+ if prompt_embeds is not None and class_tokens_mask is None:
629
+ raise ValueError(
630
+ "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`."
631
+ )
632
+ # check the input id images
633
+ if input_id_images is None:
634
+ raise ValueError(
635
+ "Provide `input_id_images`. Cannot leave `input_id_images` undefined for PhotoMaker pipeline."
636
+ )
637
+ if not isinstance(input_id_images, list):
638
+ input_id_images = [input_id_images]
639
+
640
+ # 2. Define call parameters
641
+ if prompt is not None and isinstance(prompt, str):
642
+ batch_size = 1
643
+ elif prompt is not None and isinstance(prompt, list):
644
+ batch_size = len(prompt)
645
+ else:
646
+ batch_size = prompt_embeds.shape[0]
647
+
648
+ device = self._execution_device
649
+
650
+ # 3. Encode input prompt
651
+ lora_scale = (
652
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
653
+ )
654
+
655
+ num_id_images = len(input_id_images)
656
+
657
+ (
658
+ prompt_embeds,
659
+ _,
660
+ pooled_prompt_embeds,
661
+ _,
662
+ class_tokens_mask,
663
+ ) = self.encode_prompt_with_trigger_word(
664
+ prompt=prompt,
665
+ prompt_2=prompt_2,
666
+ device=device,
667
+ num_id_images=num_id_images,
668
+ class_tokens_mask=class_tokens_mask,
669
+ num_images_per_prompt=num_images_per_prompt,
670
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
671
+ negative_prompt=negative_prompt,
672
+ negative_prompt_2=negative_prompt_2,
673
+ prompt_embeds=prompt_embeds,
674
+ negative_prompt_embeds=negative_prompt_embeds,
675
+ pooled_prompt_embeds=pooled_prompt_embeds,
676
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
677
+ lora_scale=lora_scale,
678
+ clip_skip=self._clip_skip,
679
+ )
680
+
681
+ # 4. Encode input prompt without the trigger word for delayed conditioning
682
+ # encode, remove trigger word token, then decode
683
+ tokens_text_only = self.tokenizer.encode(prompt, add_special_tokens=False)
684
+ trigger_word_token = self.tokenizer.convert_tokens_to_ids(self.trigger_word)
685
+ tokens_text_only.remove(trigger_word_token)
686
+ prompt_text_only = self.tokenizer.decode(tokens_text_only, add_special_tokens=False)
687
+ (
688
+ prompt_embeds_text_only,
689
+ negative_prompt_embeds,
690
+ pooled_prompt_embeds_text_only, # TODO: replace the pooled_prompt_embeds with text only prompt
691
+ negative_pooled_prompt_embeds,
692
+ ) = self.encode_prompt(
693
+ prompt=prompt_text_only,
694
+ prompt_2=prompt_2,
695
+ device=device,
696
+ num_images_per_prompt=num_images_per_prompt,
697
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
698
+ negative_prompt=negative_prompt,
699
+ negative_prompt_2=negative_prompt_2,
700
+ prompt_embeds=prompt_embeds_text_only,
701
+ negative_prompt_embeds=negative_prompt_embeds,
702
+ pooled_prompt_embeds=pooled_prompt_embeds_text_only,
703
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
704
+ lora_scale=lora_scale,
705
+ clip_skip=self._clip_skip,
706
+ )
707
+
708
+ # 5. Prepare the input ID images
709
+ dtype = next(self.id_encoder.parameters()).dtype
710
+ if not isinstance(input_id_images[0], torch.Tensor):
711
+ id_pixel_values = self.id_image_processor(input_id_images, return_tensors="pt").pixel_values
712
+
713
+ id_pixel_values = id_pixel_values.unsqueeze(0).to(device=device, dtype=dtype) # TODO: multiple prompts
714
+
715
+ # 6. Get the update text embedding with the stacked ID embedding
716
+ if id_embeds is not None:
717
+ id_embeds = id_embeds.unsqueeze(0).to(device=device, dtype=dtype)
718
+ prompt_embeds = self.id_encoder(id_pixel_values, prompt_embeds, class_tokens_mask, id_embeds)
719
+ else:
720
+ prompt_embeds = self.id_encoder(id_pixel_values, prompt_embeds, class_tokens_mask)
721
+
722
+ bs_embed, seq_len, _ = prompt_embeds.shape
723
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
724
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
725
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
726
+
727
+ # 6.1 Get the ip adapter embedding
728
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
729
+ image_embeds = self.prepare_ip_adapter_image_embeds(
730
+ ip_adapter_image,
731
+ ip_adapter_image_embeds,
732
+ device,
733
+ batch_size * num_images_per_prompt,
734
+ self.do_classifier_free_guidance,
735
+ )
736
+
737
+ # 7. Prepare timesteps
738
+ timesteps, num_inference_steps = retrieve_timesteps(
739
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
740
+ )
741
+
742
+ # 8. Prepare latent variables
743
+ num_channels_latents = self.unet.config.in_channels
744
+ latents = self.prepare_latents(
745
+ batch_size * num_images_per_prompt,
746
+ num_channels_latents,
747
+ height,
748
+ width,
749
+ prompt_embeds.dtype,
750
+ device,
751
+ generator,
752
+ latents,
753
+ )
754
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
755
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
756
+
757
+ # 8.5 Optionally get Guidance Scale Embedding
758
+ timestep_cond = None
759
+ if self.unet.config.time_cond_proj_dim is not None:
760
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
761
+ timestep_cond = self.get_guidance_scale_embedding(
762
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
763
+ ).to(device=device, dtype=latents.dtype)
764
+
765
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
766
+ if use_adapter:
767
+ if isinstance(self.adapter, MultiAdapter):
768
+ adapter_state = self.adapter(adapter_input, adapter_conditioning_scale)
769
+ for k, v in enumerate(adapter_state):
770
+ adapter_state[k] = v
771
+ else:
772
+ adapter_state = self.adapter(adapter_input)
773
+ for k, v in enumerate(adapter_state):
774
+ adapter_state[k] = v * adapter_conditioning_scale
775
+ if num_images_per_prompt > 1:
776
+ for k, v in enumerate(adapter_state):
777
+ adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
778
+ if self.do_classifier_free_guidance:
779
+ for k, v in enumerate(adapter_state):
780
+ adapter_state[k] = torch.cat([v] * 2, dim=0)
781
+
782
+ add_text_embeds = pooled_prompt_embeds
783
+ if self.text_encoder_2 is None:
784
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
785
+ else:
786
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
787
+
788
+ add_time_ids = self._get_add_time_ids(
789
+ original_size,
790
+ crops_coords_top_left,
791
+ target_size,
792
+ dtype=prompt_embeds.dtype,
793
+ text_encoder_projection_dim=text_encoder_projection_dim,
794
+ )
795
+ if negative_original_size is not None and negative_target_size is not None:
796
+ negative_add_time_ids = self._get_add_time_ids(
797
+ negative_original_size,
798
+ negative_crops_coords_top_left,
799
+ negative_target_size,
800
+ dtype=prompt_embeds.dtype,
801
+ text_encoder_projection_dim=text_encoder_projection_dim,
802
+ )
803
+ else:
804
+ negative_add_time_ids = add_time_ids
805
+
806
+ if self.do_classifier_free_guidance:
807
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
808
+
809
+ prompt_embeds = prompt_embeds.to(device)
810
+ add_text_embeds = add_text_embeds.to(device)
811
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
812
+
813
+ # 11. Denoising loop
814
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
815
+ # Apply denoising_end
816
+ if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
817
+ discrete_timestep_cutoff = int(
818
+ round(
819
+ self.scheduler.config.num_train_timesteps
820
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
821
+ )
822
+ )
823
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
824
+ timesteps = timesteps[:num_inference_steps]
825
+
826
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
827
+ for i, t in enumerate(timesteps):
828
+
829
+ # expand the latents if we are doing classifier free guidance
830
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
831
+
832
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
833
+
834
+ if i <= start_merge_step:
835
+ current_prompt_embeds = torch.cat(
836
+ [negative_prompt_embeds, prompt_embeds_text_only], dim=0
837
+ ) if self.do_classifier_free_guidance else prompt_embeds_text_only
838
+ add_text_embeds = torch.cat(
839
+ [negative_pooled_prompt_embeds, pooled_prompt_embeds_text_only], dim=0
840
+ ) if self.do_classifier_free_guidance else pooled_prompt_embeds_text_only
841
+ else:
842
+ current_prompt_embeds = torch.cat(
843
+ [negative_prompt_embeds, prompt_embeds], dim=0
844
+ ) if self.do_classifier_free_guidance else prompt_embeds
845
+ add_text_embeds = torch.cat(
846
+ [negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0
847
+ ) if self.do_classifier_free_guidance else pooled_prompt_embeds
848
+
849
+ if i < int(num_inference_steps * adapter_conditioning_factor) and (use_adapter):
850
+ down_intrablock_additional_residuals = [state.clone() for state in adapter_state]
851
+ else:
852
+ down_intrablock_additional_residuals = None
853
+
854
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
855
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
856
+ added_cond_kwargs["image_embeds"] = image_embeds
857
+
858
+ # predict the noise residual
859
+ noise_pred = self.unet(
860
+ latent_model_input,
861
+ t,
862
+ encoder_hidden_states=current_prompt_embeds,
863
+ timestep_cond=timestep_cond,
864
+ cross_attention_kwargs=cross_attention_kwargs,
865
+ down_intrablock_additional_residuals=down_intrablock_additional_residuals,
866
+ added_cond_kwargs=added_cond_kwargs,
867
+ return_dict=False,
868
+ )[0]
869
+
870
+ # perform guidance
871
+ if self.do_classifier_free_guidance:
872
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
873
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
874
+
875
+ if self.do_classifier_free_guidance and guidance_rescale > 0.0:
876
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
877
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
878
+
879
+ # compute the previous noisy sample x_t -> x_t-1
880
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
881
+
882
+ # call the callback, if provided
883
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
884
+ progress_bar.update()
885
+ if callback is not None and i % callback_steps == 0:
886
+ step_idx = i // getattr(self.scheduler, "order", 1)
887
+ callback(step_idx, t, latents)
888
+
889
+ if not output_type == "latent":
890
+ # make sure the VAE is in float32 mode, as it overflows in float16
891
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
892
+
893
+ if needs_upcasting:
894
+ self.upcast_vae()
895
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
896
+
897
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
898
+
899
+ # cast back to fp16 if needed
900
+ if needs_upcasting:
901
+ self.vae.to(dtype=torch.float16)
902
+ else:
903
+ image = latents
904
+ return StableDiffusionXLPipelineOutput(images=image)
905
+
906
+ image = self.image_processor.postprocess(image, output_type=output_type)
907
+
908
+ # Offload all models
909
+ self.maybe_free_model_hooks()
910
+
911
+ if not return_dict:
912
+ return (image,)
913
+
914
+ return StableDiffusionXLPipelineOutput(images=image)
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
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}