jacktheporsche commited on
Commit
9cdc61c
1 Parent(s): b59e7d2

Final Files

Browse files
Files changed (5) hide show
  1. .gitattributes +35 -35
  2. LICENSE +201 -0
  3. cog.yaml +23 -0
  4. gradio_app_sdxl_specific_id_low_vram.py +800 -0
  5. predict.py +781 -0
.gitattributes CHANGED
@@ -1,35 +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
 
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
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
cog.yaml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Configuration for Cog ⚙️
2
+ # Reference: https://cog.run/yaml
3
+
4
+ build:
5
+ gpu: true
6
+ system_packages:
7
+ - "libgl1-mesa-glx"
8
+ - "libglib2.0-0"
9
+ python_version: "3.11"
10
+ python_packages:
11
+ - xformers==0.0.20
12
+ - torch==2.0.1
13
+ - torchvision==0.15.2
14
+ - diffusers==0.25.0
15
+ - transformers==4.36.2
16
+ - gradio==3.48.0
17
+ - accelerate
18
+ - safetensors
19
+ - peft
20
+ - Pillow==9.5.0
21
+ run:
22
+ - curl -o /usr/local/bin/pget -L "https://github.com/replicate/pget/releases/download/v0.6.0/pget_linux_x86_64" && chmod +x /usr/local/bin/pget
23
+ predict: "predict.py:Predictor"
gradio_app_sdxl_specific_id_low_vram.py ADDED
@@ -0,0 +1,800 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.policy import default
2
+ from this import d
3
+ import gradio as gr
4
+ import numpy as np
5
+ import torch
6
+ import gc
7
+ from huggingface_hub import hf_hub_download
8
+ import requests
9
+ import random
10
+ import os
11
+ import sys
12
+ import pickle
13
+ from PIL import Image
14
+ from tqdm.auto import tqdm
15
+ from datetime import datetime
16
+ from utils.gradio_utils import is_torch2_available
17
+ if is_torch2_available():
18
+ from utils.gradio_utils import \
19
+ AttnProcessor2_0 as AttnProcessor
20
+ else:
21
+ from utils.gradio_utils import AttnProcessor
22
+
23
+ import diffusers
24
+ from diffusers import StableDiffusionXLPipeline
25
+ from utils import PhotoMakerStableDiffusionXLPipeline
26
+ from diffusers import DDIMScheduler
27
+ import torch.nn.functional as F
28
+ from utils.gradio_utils import cal_attn_mask_xl,cal_attn_indice_xl_effcient_memory
29
+ import copy
30
+ import os
31
+ from diffusers.utils import load_image
32
+ from utils.utils import get_comic
33
+ from utils.style_template import styles
34
+ image_encoder_path = "./data/models/ip_adapter/sdxl_models/image_encoder"
35
+ ip_ckpt = "./data/models/ip_adapter/sdxl_models/ip-adapter_sdxl_vit-h.bin"
36
+ os.environ["no_proxy"] = "localhost,127.0.0.1,::1"
37
+ STYLE_NAMES = list(styles.keys())
38
+ DEFAULT_STYLE_NAME = "Japanese Anime"
39
+ global models_dict
40
+ models_dict = {
41
+ "Juggernaut": "RunDiffusion/Juggernaut-XL-v8",
42
+ "RealVision": "SG161222/RealVisXL_V4.0" ,
43
+ "SDXL": "stabilityai/stable-diffusion-xl-base-1.0" ,
44
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y"
45
+ }
46
+ photomaker_path = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
47
+ MAX_SEED = np.iinfo(np.int32).max
48
+ def setup_seed(seed):
49
+ torch.manual_seed(seed)
50
+ torch.cuda.manual_seed_all(seed)
51
+ np.random.seed(seed)
52
+ random.seed(seed)
53
+ torch.backends.cudnn.deterministic = True
54
+ def set_text_unfinished():
55
+ return gr.update(visible=True, value="<h3>(Not Finished) Generating ··· The intermediate results will be shown.</h3>")
56
+ def set_text_finished():
57
+ return gr.update(visible=True, value="<h3>Generation Finished</h3>")
58
+ #################################################
59
+ def get_image_path_list(folder_name):
60
+ image_basename_list = os.listdir(folder_name)
61
+ image_path_list = sorted([os.path.join(folder_name, basename) for basename in image_basename_list])
62
+ return image_path_list
63
+
64
+ #################################################
65
+ class SpatialAttnProcessor2_0(torch.nn.Module):
66
+ r"""
67
+ Attention processor for IP-Adapater for PyTorch 2.0.
68
+ Args:
69
+ hidden_size (`int`):
70
+ The hidden size of the attention layer.
71
+ cross_attention_dim (`int`):
72
+ The number of channels in the `encoder_hidden_states`.
73
+ text_context_len (`int`, defaults to 77):
74
+ The context length of the text features.
75
+ scale (`float`, defaults to 1.0):
76
+ the weight scale of image prompt.
77
+ """
78
+
79
+ def __init__(self, hidden_size = None, cross_attention_dim=None,id_length = 4,device = "cuda",dtype = torch.float16):
80
+ super().__init__()
81
+ if not hasattr(F, "scaled_dot_product_attention"):
82
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
83
+ self.device = device
84
+ self.dtype = dtype
85
+ self.hidden_size = hidden_size
86
+ self.cross_attention_dim = cross_attention_dim
87
+ self.total_length = id_length + 1
88
+ self.id_length = id_length
89
+ self.id_bank = {}
90
+
91
+ def __call__(
92
+ self,
93
+ attn,
94
+ hidden_states,
95
+ encoder_hidden_states=None,
96
+ attention_mask=None,
97
+ temb=None):
98
+ # un_cond_hidden_states, cond_hidden_states = hidden_states.chunk(2)
99
+ # un_cond_hidden_states = self.__call2__(attn, un_cond_hidden_states,encoder_hidden_states,attention_mask,temb)
100
+ # 生成一个0到1之间的随机数
101
+ global total_count,attn_count,cur_step, indices1024,indices4096
102
+ global sa32, sa64
103
+ global write
104
+ global height,width
105
+ if attn_count == 0 and cur_step == 0:
106
+ indices1024,indices4096 = cal_attn_indice_xl_effcient_memory(self.total_length,self.id_length,sa32,sa64,height,width, device=self.device, dtype= self.dtype)
107
+ if write:
108
+ if hidden_states.shape[1] == (height//32) * (width//32):
109
+ indices = indices1024
110
+ else:
111
+ indices = indices4096
112
+ # print(f"white:{cur_step}")
113
+ total_batch_size,nums_token,channel = hidden_states.shape
114
+ img_nums = total_batch_size // 2
115
+ hidden_states = hidden_states.reshape(-1,img_nums,nums_token,channel)
116
+ self.id_bank[cur_step] = [hidden_states[:,img_ind,indices[img_ind],:].reshape(2,-1,channel).clone() for img_ind in range(img_nums)]
117
+ hidden_states = hidden_states.reshape(-1,nums_token,channel)
118
+ #self.id_bank[cur_step] = [hidden_states[:self.id_length].clone(), hidden_states[self.id_length:].clone()]
119
+ else:
120
+ #encoder_hidden_states = torch.cat((self.id_bank[cur_step][0].to(self.device),self.id_bank[cur_step][1].to(self.device)))
121
+ encoder_arr = [tensor.to(self.device) for tensor in self.id_bank[cur_step]]
122
+ # 判断随机数是否大于0.5
123
+ if cur_step <1:
124
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
125
+ else: # 256 1024 4096
126
+ random_number = random.random()
127
+ if cur_step <20:
128
+ rand_num = 0.3
129
+ else:
130
+ rand_num = 0.1
131
+ # print(f"hidden state shape {hidden_states.shape[1]}")
132
+ if random_number > rand_num:
133
+ if hidden_states.shape[1] == (height//32) * (width//32):
134
+ indices = indices1024
135
+ else:
136
+ indices = indices4096
137
+ # print("before attention",hidden_states.shape,attention_mask.shape,encoder_hidden_states.shape if encoder_hidden_states is not None else "None")
138
+ if write:
139
+ total_batch_size,nums_token,channel = hidden_states.shape
140
+ img_nums = total_batch_size // 2
141
+ hidden_states = hidden_states.reshape(-1,img_nums,nums_token,channel)
142
+ encoder_arr = [hidden_states[:,img_ind,indices[img_ind],:].reshape(2,-1,channel) for img_ind in range(img_nums)]
143
+ for img_ind in range(img_nums):
144
+ encoder_hidden_states_tmp = torch.cat(encoder_arr[0:img_ind] + encoder_arr[img_ind+1:] + [hidden_states[:,img_ind,:,:]],dim=1)
145
+ hidden_states[:,img_ind,:,:] = self.__call2__(attn, hidden_states[:,img_ind,:,:],encoder_hidden_states_tmp,None,temb)
146
+ else:
147
+ _,nums_token,channel = hidden_states.shape
148
+ # img_nums = total_batch_size // 2
149
+ # encoder_hidden_states = encoder_hidden_states.reshape(-1,img_nums,nums_token,channel)
150
+ hidden_states = hidden_states.reshape(2,-1,nums_token,channel)
151
+ # print(len(indices))
152
+ # encoder_arr = [encoder_hidden_states[:,img_ind,indices[img_ind],:].reshape(2,-1,channel) for img_ind in range(img_nums)]
153
+ encoder_hidden_states_tmp = torch.cat(encoder_arr+[hidden_states[:,0,:,:]],dim=1)
154
+ hidden_states[:,0,:,:] = self.__call2__(attn, hidden_states[:,0,:,:],encoder_hidden_states_tmp,None,temb)
155
+ hidden_states = hidden_states.reshape(-1,nums_token,channel)
156
+ else:
157
+ hidden_states = self.__call2__(attn, hidden_states,None,attention_mask,temb)
158
+ attn_count +=1
159
+ if attn_count == total_count:
160
+ attn_count = 0
161
+ cur_step += 1
162
+ indices1024,indices4096 = cal_attn_indice_xl_effcient_memory(self.total_length,self.id_length,sa32,sa64,height,width, device=self.device, dtype= self.dtype)
163
+
164
+ return hidden_states
165
+ def __call1__(
166
+ self,
167
+ attn,
168
+ hidden_states,
169
+ encoder_hidden_states=None,
170
+ attention_mask=None,
171
+ temb=None,
172
+ attn_indices = None,
173
+ ):
174
+ # print("hidden state shape",hidden_states.shape,self.id_length)
175
+ residual = hidden_states
176
+ # if encoder_hidden_states is not None:
177
+ # raise Exception("not implement")
178
+ if attn.spatial_norm is not None:
179
+ hidden_states = attn.spatial_norm(hidden_states, temb)
180
+ input_ndim = hidden_states.ndim
181
+
182
+ if input_ndim == 4:
183
+ total_batch_size, channel, height, width = hidden_states.shape
184
+ hidden_states = hidden_states.view(total_batch_size, channel, height * width).transpose(1, 2)
185
+ total_batch_size,nums_token,channel = hidden_states.shape
186
+ img_nums = total_batch_size//2
187
+ hidden_states = hidden_states.view(-1,img_nums,nums_token,channel).reshape(-1,img_nums * nums_token,channel)
188
+ batch_size, sequence_length, _ = hidden_states.shape
189
+
190
+ if attn.group_norm is not None:
191
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
192
+
193
+ query = attn.to_q(hidden_states)
194
+
195
+ if encoder_hidden_states is None:
196
+ encoder_hidden_states = hidden_states # B, N, C
197
+ else:
198
+ encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,nums_token,channel).reshape(-1,(self.id_length+1) * nums_token,channel)
199
+
200
+ key = attn.to_k(encoder_hidden_states)
201
+ value = attn.to_v(encoder_hidden_states)
202
+
203
+
204
+ inner_dim = key.shape[-1]
205
+ head_dim = inner_dim // attn.heads
206
+
207
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
208
+
209
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
210
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
211
+ # print(key.shape,value.shape,query.shape,attention_mask.shape)
212
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
213
+ # TODO: add support for attn.scale when we move to Torch 2.1
214
+ #print(query.shape,key.shape,value.shape,attention_mask.shape)
215
+ hidden_states = F.scaled_dot_product_attention(
216
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
217
+ )
218
+
219
+ hidden_states = hidden_states.transpose(1, 2).reshape(total_batch_size, -1, attn.heads * head_dim)
220
+ hidden_states = hidden_states.to(query.dtype)
221
+
222
+
223
+
224
+ # linear proj
225
+ hidden_states = attn.to_out[0](hidden_states)
226
+ # dropout
227
+ hidden_states = attn.to_out[1](hidden_states)
228
+
229
+ # if input_ndim == 4:
230
+ # tile_hidden_states = tile_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
231
+
232
+ # if attn.residual_connection:
233
+ # tile_hidden_states = tile_hidden_states + residual
234
+
235
+ if input_ndim == 4:
236
+ hidden_states = hidden_states.transpose(-1, -2).reshape(total_batch_size, channel, height, width)
237
+ if attn.residual_connection:
238
+ hidden_states = hidden_states + residual
239
+ hidden_states = hidden_states / attn.rescale_output_factor
240
+ # print(hidden_states.shape)
241
+ return hidden_states
242
+ def __call2__(
243
+ self,
244
+ attn,
245
+ hidden_states,
246
+ encoder_hidden_states=None,
247
+ attention_mask=None,
248
+ temb=None):
249
+ residual = hidden_states
250
+
251
+ if attn.spatial_norm is not None:
252
+ hidden_states = attn.spatial_norm(hidden_states, temb)
253
+
254
+ input_ndim = hidden_states.ndim
255
+
256
+ if input_ndim == 4:
257
+ batch_size, channel, height, width = hidden_states.shape
258
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
259
+
260
+ batch_size, sequence_length, channel = (
261
+ hidden_states.shape
262
+ )
263
+ # print(hidden_states.shape)
264
+ if attention_mask is not None:
265
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
266
+ # scaled_dot_product_attention expects attention_mask shape to be
267
+ # (batch, heads, source_length, target_length)
268
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
269
+
270
+ if attn.group_norm is not None:
271
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
272
+
273
+ query = attn.to_q(hidden_states)
274
+
275
+ if encoder_hidden_states is None:
276
+ encoder_hidden_states = hidden_states # B, N, C
277
+ # else:
278
+ # encoder_hidden_states = encoder_hidden_states.view(-1,self.id_length+1,sequence_length,channel).reshape(-1,(self.id_length+1) * sequence_length,channel)
279
+
280
+ key = attn.to_k(encoder_hidden_states)
281
+ value = attn.to_v(encoder_hidden_states)
282
+
283
+ inner_dim = key.shape[-1]
284
+ head_dim = inner_dim // attn.heads
285
+
286
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
287
+
288
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
289
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
290
+
291
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
292
+ # TODO: add support for attn.scale when we move to Torch 2.1
293
+ hidden_states = F.scaled_dot_product_attention(
294
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
295
+ )
296
+
297
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
298
+ hidden_states = hidden_states.to(query.dtype)
299
+
300
+ # linear proj
301
+ hidden_states = attn.to_out[0](hidden_states)
302
+ # dropout
303
+ hidden_states = attn.to_out[1](hidden_states)
304
+
305
+ if input_ndim == 4:
306
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
307
+
308
+ if attn.residual_connection:
309
+ hidden_states = hidden_states + residual
310
+
311
+ hidden_states = hidden_states / attn.rescale_output_factor
312
+
313
+ return hidden_states
314
+
315
+ def set_attention_processor(unet,id_length,is_ipadapter = False):
316
+ global attn_procs
317
+ attn_procs = {}
318
+ for name in unet.attn_processors.keys():
319
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
320
+ if name.startswith("mid_block"):
321
+ hidden_size = unet.config.block_out_channels[-1]
322
+ elif name.startswith("up_blocks"):
323
+ block_id = int(name[len("up_blocks.")])
324
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
325
+ elif name.startswith("down_blocks"):
326
+ block_id = int(name[len("down_blocks.")])
327
+ hidden_size = unet.config.block_out_channels[block_id]
328
+ if cross_attention_dim is None:
329
+ if name.startswith("up_blocks") :
330
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
331
+ else:
332
+ attn_procs[name] = AttnProcessor()
333
+ else:
334
+ if is_ipadapter:
335
+ attn_procs[name] = IPAttnProcessor2_0(
336
+ hidden_size=hidden_size,
337
+ cross_attention_dim=cross_attention_dim,
338
+ scale=1,
339
+ num_tokens=4,
340
+ ).to(unet.device, dtype=torch.float16)
341
+ else:
342
+ attn_procs[name] = AttnProcessor()
343
+
344
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
345
+ #################################################
346
+ #################################################
347
+ canvas_html = "<div id='canvas-root' style='max-width:400px; margin: 0 auto'></div>"
348
+ load_js = """
349
+ async () => {
350
+ const url = "https://huggingface.co/datasets/radames/gradio-components/raw/main/sketch-canvas.js"
351
+ fetch(url)
352
+ .then(res => res.text())
353
+ .then(text => {
354
+ const script = document.createElement('script');
355
+ script.type = "module"
356
+ script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
357
+ document.head.appendChild(script);
358
+ });
359
+ }
360
+ """
361
+
362
+ get_js_colors = """
363
+ async (canvasData) => {
364
+ const canvasEl = document.getElementById("canvas-root");
365
+ return [canvasEl._data]
366
+ }
367
+ """
368
+
369
+ css = '''
370
+ #color-bg{display:flex;justify-content: center;align-items: center;}
371
+ .color-bg-item{width: 100%; height: 32px}
372
+ #main_button{width:100%}
373
+ <style>
374
+ '''
375
+
376
+
377
+ #################################################
378
+ title = r"""
379
+ <h1 align="center">StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</h1>
380
+ """
381
+
382
+ description = r"""
383
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'><b>StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation</b></a>.<br>
384
+ ❗️❗️❗️[<b>Important</b>] Personalization steps:<br>
385
+ 1️⃣ Enter a Textual Description for Character, if you add the Ref-Image, 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>
386
+ 2️⃣ Enter the prompt array, each line corrsponds to one generated image.<br>
387
+ 3️⃣ Choose your preferred style template.<br>
388
+ 4️⃣ Click the <b>Submit</b> button to start customizing.
389
+ """
390
+
391
+ article = r"""
392
+
393
+ If StoryDiffusion is helpful, please help to ⭐ the <a href='https://github.com/HVision-NKU/StoryDiffusion' target='_blank'>Github Repo</a>. Thanks!
394
+ [![GitHub Stars](https://img.shields.io/github/stars/HVision-NKU/StoryDiffusion?style=social)](https://github.com/HVision-NKU/StoryDiffusion)
395
+ ---
396
+ 📝 **Citation**
397
+ <br>
398
+ If our work is useful for your research, please consider citing:
399
+
400
+ ```bibtex
401
+ @article{Zhou2024storydiffusion,
402
+ title={StoryDiffusion: Consistent Self-Attention for Long-Range Image and Video Generation},
403
+ author={Zhou, Yupeng and Zhou, Daquan and Cheng, Ming-Ming and Feng, Jiashi and Hou, Qibin},
404
+ year={2024}
405
+ }
406
+ ```
407
+ 📋 **License**
408
+ <br>
409
+ The Contents you create are under Apache-2.0 LICENSE. The Code are under Attribution-NonCommercial 4.0 International.
410
+
411
+ 📧 **Contact**
412
+ <br>
413
+ If you have any questions, please feel free to reach me out at <b>[email protected]</b>.
414
+ """
415
+ version = r"""
416
+ <h3 align="center">StoryDiffusion Version 0.01 (test version)</h3>
417
+
418
+ <h5 >1. Support image ref image. (Cartoon Ref image is not support now)</h5>
419
+ <h5 >2. Support Typesetting Style and Captioning.(By default, the prompt is used as the caption for each image. If you need to change the caption, add a # at the end of each line. Only the part after the # will be added as a caption to the image.)</h5>
420
+ <h5 >3. [NC]symbol (The [NC] symbol is used as a flag to indicate that no characters should be present in the generated scene images. If you want do that, prepend the "[NC]" at the beginning of the line. For example, to generate a scene of falling leaves without any character, write: "[NC] The leaves are falling.")</h5>
421
+ <h5 align="center">Tips: </h4>
422
+ """
423
+ #################################################
424
+ global attn_count, total_count, id_length, total_length,cur_step, cur_model_type
425
+ global write
426
+ global sa32, sa64
427
+ global height,width
428
+ attn_count = 0
429
+ total_count = 0
430
+ cur_step = 0
431
+ id_length = 4
432
+ total_length = 5
433
+ cur_model_type = ""
434
+ device="cuda"
435
+ global attn_procs,unet
436
+ attn_procs = {}
437
+ ###
438
+ write = False
439
+ ###
440
+ sa32 = 0.5
441
+ sa64 = 0.5
442
+ height = 768
443
+ width = 768
444
+ ###
445
+ global pipe
446
+ global sd_model_path
447
+ pipe = None
448
+ sd_model_path = models_dict["Unstable"]#"SG161222/RealVisXL_V4.0"
449
+ ### LOAD Stable Diffusion Pipeline
450
+ pipe = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors = False)
451
+ pipe = pipe.to(device)
452
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
453
+ # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
454
+ pipe.scheduler.set_timesteps(50)
455
+ pipe.enable_vae_slicing()
456
+ pipe.enable_model_cpu_offload()
457
+ unet = pipe.unet
458
+ cur_model_type = "Unstable"+"-"+"original"
459
+ ### Insert PairedAttention
460
+ for name in unet.attn_processors.keys():
461
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
462
+ if name.startswith("mid_block"):
463
+ hidden_size = unet.config.block_out_channels[-1]
464
+ elif name.startswith("up_blocks"):
465
+ block_id = int(name[len("up_blocks.")])
466
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
467
+ elif name.startswith("down_blocks"):
468
+ block_id = int(name[len("down_blocks.")])
469
+ hidden_size = unet.config.block_out_channels[block_id]
470
+ if cross_attention_dim is None and (name.startswith("up_blocks") ) :
471
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length = id_length)
472
+ total_count +=1
473
+ else:
474
+ attn_procs[name] = AttnProcessor()
475
+ print("successsfully load paired self-attention")
476
+ print(f"number of the processor : {total_count}")
477
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
478
+ global mask1024,mask4096
479
+ mask1024, mask4096 = cal_attn_mask_xl(total_length,id_length,sa32,sa64,height,width,device=device,dtype= torch.float16)
480
+
481
+ ######### Gradio Fuction #############
482
+
483
+ def swap_to_gallery(images):
484
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
485
+
486
+ def upload_example_to_gallery(images, prompt, style, negative_prompt):
487
+ return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False)
488
+
489
+ def remove_back_to_files():
490
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
491
+
492
+ def remove_tips():
493
+ return gr.update(visible=False)
494
+
495
+ def apply_style_positive(style_name: str, positive: str):
496
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
497
+ return p.replace("{prompt}", positive)
498
+
499
+ def apply_style(style_name: str, positives: list, negative: str = ""):
500
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
501
+ return [p.replace("{prompt}", positive) for positive in positives], n + ' ' + negative
502
+
503
+ def change_visiale_by_model_type(_model_type):
504
+ if _model_type == "Only Using Textual Description":
505
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
506
+ elif _model_type == "Using Ref Images":
507
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
508
+ else:
509
+ raise ValueError("Invalid model type",_model_type)
510
+
511
+
512
+ ######### Image Generation ##############
513
+ def process_generation(_sd_type,_model_type,_upload_images, _num_steps,style_name, _Ip_Adapter_Strength ,_style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt,prompt_array,G_height,G_width,_comic_type):
514
+ _model_type = "Photomaker" if _model_type == "Using Ref Images" else "original"
515
+ if _model_type == "Photomaker" and "img" not in general_prompt:
516
+ raise gr.Error("Please add the triger word \" img \" behind the class word you want to customize, such as: man img or woman img")
517
+ if _upload_images is None and _model_type != "original":
518
+ raise gr.Error(f"Cannot find any input face image!")
519
+ global sa32, sa64,id_length,total_length,attn_procs,unet,cur_model_type
520
+ global write
521
+ global cur_step,attn_count
522
+ global height,width
523
+ height = G_height
524
+ width = G_width
525
+ global pipe
526
+ global sd_model_path,models_dict
527
+ sd_model_path = models_dict[_sd_type]
528
+ use_safe_tensor = True
529
+ for attn_processor in pipe.unet.attn_processors.values():
530
+ if isinstance(attn_processor, SpatialAttnProcessor2_0):
531
+ for values in attn_processor.id_bank.values():
532
+ del values
533
+ attn_processor.id_bank = {}
534
+ attn_processor.id_length = id_length
535
+ attn_processor.total_length = id_length + 1
536
+ gc.collect()
537
+ if cur_model_type != _sd_type+"-"+_model_type:
538
+ if _sd_type == "Unstable":
539
+ use_safe_tensor = False
540
+ # apply the style template
541
+ ##### load pipe
542
+ del pipe
543
+ gc.collect()
544
+ torch.cuda.empty_cache()
545
+ if _model_type == "original":
546
+ pipe = StableDiffusionXLPipeline.from_pretrained(sd_model_path, torch_dtype=torch.float16, use_safetensors=use_safe_tensor)
547
+ pipe = pipe.to(device)
548
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
549
+ elif _model_type == "Photomaker":
550
+ pipe = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
551
+ sd_model_path, torch_dtype=torch.float16, use_safetensors=use_safe_tensor)
552
+ pipe = pipe.to(device)
553
+ pipe.load_photomaker_adapter(
554
+ os.path.dirname(photomaker_path),
555
+ subfolder="",
556
+ weight_name=os.path.basename(photomaker_path),
557
+ trigger_word="img" # define the trigger word
558
+ )
559
+ pipe.fuse_lora()
560
+ set_attention_processor(pipe.unet,id_length_,is_ipadapter = False)
561
+ else:
562
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
563
+ ##### ########################
564
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
565
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
566
+ cur_model_type = _sd_type+"-"+_model_type
567
+ pipe.enable_vae_slicing()
568
+ pipe.enable_model_cpu_offload()
569
+ else:
570
+ unet = pipe.unet
571
+ # unet.set_attn_processor(copy.deepcopy(attn_procs))
572
+ if _model_type != "original":
573
+ input_id_images = []
574
+ for img in _upload_images:
575
+ print(img)
576
+ input_id_images.append(load_image(img))
577
+ prompts = prompt_array.splitlines()
578
+ start_merge_step = int(float(_style_strength_ratio) / 100 * _num_steps)
579
+ if start_merge_step > 30:
580
+ start_merge_step = 30
581
+ print(f"start_merge_step:{start_merge_step}")
582
+ generator = torch.Generator(device="cuda").manual_seed(seed_)
583
+ sa32, sa64 = sa32_, sa64_
584
+ id_length = id_length_
585
+ clipped_prompts = prompts[:]
586
+ prompts = [general_prompt + "," + prompt if "[NC]" not in prompt else prompt.replace("[NC]","") for prompt in clipped_prompts]
587
+ prompts = [prompt.rpartition('#')[0] if "#" in prompt else prompt for prompt in prompts]
588
+ print(prompts)
589
+ id_prompts = prompts[:id_length]
590
+ real_prompts = prompts[id_length:]
591
+ torch.cuda.empty_cache()
592
+ write = True
593
+ cur_step = 0
594
+
595
+ attn_count = 0
596
+ id_prompts, negative_prompt = apply_style(style_name, id_prompts, negative_prompt)
597
+ setup_seed(seed_)
598
+ total_results = []
599
+ if _model_type == "original":
600
+ id_images = pipe(id_prompts, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
601
+ elif _model_type == "Photomaker":
602
+ id_images = pipe(id_prompts,input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images
603
+ else:
604
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
605
+ total_results = id_images + total_results
606
+ yield total_results
607
+ real_images = []
608
+ write = False
609
+ for real_prompt in real_prompts:
610
+ setup_seed(seed_)
611
+ cur_step = 0
612
+ real_prompt = apply_style_positive(style_name, real_prompt)
613
+ if _model_type == "original":
614
+ real_images.append(pipe(real_prompt, num_inference_steps=_num_steps, guidance_scale=guidance_scale, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
615
+ elif _model_type == "Photomaker":
616
+ real_images.append(pipe(real_prompt, input_id_images=input_id_images, num_inference_steps=_num_steps, guidance_scale=guidance_scale, start_merge_step = start_merge_step, height = height, width = width,negative_prompt = negative_prompt,generator = generator).images[0])
617
+ else:
618
+ raise NotImplementedError("You should choice between original and Photomaker!",f"But you choice {_model_type}")
619
+ total_results = [real_images[-1]] + total_results
620
+ yield total_results
621
+ if _comic_type != "No typesetting (default)":
622
+ captions= prompt_array.splitlines()
623
+ captions = [caption.replace("[NC]","") for caption in captions]
624
+ captions = [caption.split('#')[-1] if "#" in caption else caption for caption in captions]
625
+ from PIL import ImageFont
626
+ total_results = get_comic(id_images + real_images, _comic_type,captions= captions,font=ImageFont.truetype("./fonts/Inkfree.ttf", int(45))) + total_results
627
+ yield total_results
628
+
629
+
630
+
631
+ def array2string(arr):
632
+ stringtmp = ""
633
+ for i,part in enumerate(arr):
634
+ if i != len(arr)-1:
635
+ stringtmp += part +"\n"
636
+ else:
637
+ stringtmp += part
638
+
639
+ return stringtmp
640
+
641
+
642
+ #################################################
643
+ #################################################
644
+ ### define the interface
645
+ with gr.Blocks(css=css) as demo:
646
+ binary_matrixes = gr.State([])
647
+ color_layout = gr.State([])
648
+
649
+ # gr.Markdown(logo)
650
+ gr.Markdown(title)
651
+ gr.Markdown(description)
652
+
653
+ with gr.Row():
654
+ with gr.Group(elem_id="main-image"):
655
+
656
+ prompts = []
657
+ colors = []
658
+
659
+ with gr.Column(visible=True) as gen_prompt_vis:
660
+ sd_type = gr.Dropdown(choices=list(models_dict.keys()), value = "Unstable",label="sd_type", info="Select pretrained model")
661
+ model_type = gr.Radio(["Only Using Textual Description", "Using Ref Images"], label="model_type", value = "Only Using Textual Description", info="Control type of the Character")
662
+ with gr.Group(visible=False) as control_image_input:
663
+ files = gr.Files(
664
+ label="Drag (Select) 1 or more photos of your face",
665
+ file_types=["image"],
666
+ )
667
+ uploaded_files = gr.Gallery(label="Your images", visible=False, columns=5, rows=1, height=200)
668
+ with gr.Column(visible=False) as clear_button:
669
+ remove_and_reupload = gr.ClearButton(value="Remove and upload new ones", components=files, size="sm")
670
+ general_prompt = gr.Textbox(value='', label="(1) Textual Description for Character", interactive=True)
671
+ negative_prompt = gr.Textbox(value='', label="(2) Negative_prompt", interactive=True)
672
+ style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME)
673
+ prompt_array = gr.Textbox(lines = 3,value='', label="(3) Comic Description (each line corresponds to a frame).", interactive=True)
674
+ with gr.Accordion("(4) Tune the hyperparameters", open=True):
675
+ sa32_ = gr.Slider(label=" (The degree of Paired Attention at 32 x 32 self-attention layers) ", minimum=0, maximum=1., value=0.5, step=0.1)
676
+ sa64_ = gr.Slider(label=" (The degree of Paired Attention at 64 x 64 self-attention layers) ", minimum=0, maximum=1., value=0.5, step=0.1)
677
+ id_length_ = gr.Slider(label= "Number of id images in total images" , minimum=2, maximum=4, value=2, step=1)
678
+ seed_ = gr.Slider(label="Seed", minimum=-1, maximum=MAX_SEED, value=0, step=1)
679
+ num_steps = gr.Slider(
680
+ label="Number of sample steps",
681
+ minimum=20,
682
+ maximum=100,
683
+ step=1,
684
+ value=50,
685
+ )
686
+ G_height = gr.Slider(
687
+ label="height",
688
+ minimum=256,
689
+ maximum=1024,
690
+ step=32,
691
+ value=768,
692
+ )
693
+ G_width = gr.Slider(
694
+ label="width",
695
+ minimum=256,
696
+ maximum=1024,
697
+ step=32,
698
+ value=768,
699
+ )
700
+ comic_type = gr.Radio(["No typesetting (default)", "Four Pannel", "Classic Comic Style"], value = "Classic Comic Style", label="Typesetting Style", info="Select the typesetting style ")
701
+ guidance_scale = gr.Slider(
702
+ label="Guidance scale",
703
+ minimum=0.1,
704
+ maximum=10.0,
705
+ step=0.1,
706
+ value=5,
707
+ )
708
+ style_strength_ratio = gr.Slider(
709
+ label="Style strength of Ref Image (%)",
710
+ minimum=15,
711
+ maximum=50,
712
+ step=1,
713
+ value=20,
714
+ visible=False
715
+ )
716
+ Ip_Adapter_Strength = gr.Slider(
717
+ label="Ip_Adapter_Strength",
718
+ minimum=0,
719
+ maximum=1,
720
+ step=0.1,
721
+ value=0.5,
722
+ visible=False
723
+ )
724
+ final_run_btn = gr.Button("Generate ! 😺")
725
+
726
+
727
+ with gr.Column():
728
+ out_image = gr.Gallery(label="Result", columns=2, height='auto')
729
+ generated_information = gr.Markdown(label="Generation Details", value="",visible=False)
730
+ gr.Markdown(version)
731
+ model_type.change(fn = change_visiale_by_model_type , inputs = model_type, outputs=[control_image_input,style_strength_ratio,Ip_Adapter_Strength])
732
+ files.upload(fn=swap_to_gallery, inputs=files, outputs=[uploaded_files, clear_button, files])
733
+ remove_and_reupload.click(fn=remove_back_to_files, outputs=[uploaded_files, clear_button, files])
734
+
735
+ final_run_btn.click(fn=set_text_unfinished, outputs = generated_information
736
+ ).then(process_generation, inputs=[sd_type,model_type,files, num_steps,style, Ip_Adapter_Strength,style_strength_ratio, guidance_scale, seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,G_height,G_width,comic_type], outputs=out_image
737
+ ).then(fn=set_text_finished,outputs = generated_information)
738
+
739
+
740
+ gr.Examples(
741
+ examples=[
742
+ [0,0.5,0.5,2,"a man, wearing black suit",
743
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
744
+ array2string(["at home, read new paper #at home, The newspaper says there is a treasure house in the forest.",
745
+ "on the road, near the forest",
746
+ "[NC] The car on the road, near the forest #He drives to the forest in search of treasure.",
747
+ "[NC]A tiger appeared in the forest, at night ",
748
+ "very frightened, open mouth, in the forest, at night",
749
+ "running very fast, in the forest, at night",
750
+ "[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!",
751
+ "in the house filled with treasure, laughing, at night #He is overjoyed inside the house."
752
+ ]),
753
+ "Comic book","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
754
+ ],
755
+ [1,0.5,0.5,3,"a woman img, wearing a white T-shirt, blue loose hair",
756
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
757
+ array2string(["wake up in the bed",
758
+ "have breakfast",
759
+ "is on the road, go to company",
760
+ "work in the company",
761
+ "Take a walk next to the company at noon",
762
+ "lying in bed at night"]),
763
+ "Japanese Anime", "Using Ref Images",get_image_path_list('./examples/taylor'),768,768
764
+ ],
765
+ [0,0.5,0.5,3,"a man, wearing black jacket",
766
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
767
+ array2string(["wake up in the bed",
768
+ "have breakfast",
769
+ "is on the road, go to the company, close look",
770
+ "work in the company",
771
+ "laughing happily",
772
+ "lying in bed at night"
773
+ ]),
774
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
775
+ ],
776
+ [0,0.3,0.5,3,"a girl, wearing white shirt, black skirt, black tie, yellow hair",
777
+ "bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
778
+ array2string([
779
+ "at home #at home, began to go to drawing",
780
+ "sitting alone on a park bench.",
781
+ "reading a book on a park bench.",
782
+ "[NC]A squirrel approaches, peeking over the bench. ",
783
+ "look around in the park. # She looks around and enjoys the beauty of nature.",
784
+ "[NC]leaf falls from the tree, landing on the sketchbook.",
785
+ "picks up the leaf, examining its details closely.",
786
+ "[NC]The brown squirrel appear.",
787
+ "is very happy # She is very happy to see the squirrel again",
788
+ "[NC]The brown squirrel takes the cracker and scampers up a tree. # She gives the squirrel cracker"]),
789
+ "Japanese Anime","Only Using Textual Description",get_image_path_list('./examples/taylor'),768,768
790
+ ]
791
+ ],
792
+ inputs=[seed_, sa32_, sa64_, id_length_, general_prompt, negative_prompt, prompt_array,style,model_type,files,G_height,G_width],
793
+ # outputs=[post_sketch, binary_matrixes, *color_row, *colors, *prompts, gen_prompt_vis, general_prompt, seed_],
794
+ # run_on_click=True,
795
+ label='😺 Examples 😺',
796
+ )
797
+ gr.Markdown(article)
798
+
799
+
800
+ demo.launch(server_name="0.0.0.0", share = False)
predict.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Prediction interface for Cog ⚙️
2
+ # https://cog.run/python
3
+
4
+ import os
5
+ import copy
6
+ import random
7
+ import subprocess
8
+ import numpy as np
9
+ import time
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from PIL import ImageFont
13
+ from cog import BasePredictor, Input, Path, BaseModel
14
+ from diffusers import StableDiffusionXLPipeline, DDIMScheduler
15
+ from diffusers.utils import load_image
16
+
17
+ from utils import PhotoMakerStableDiffusionXLPipeline
18
+ from utils.style_template import styles
19
+ from utils.gradio_utils import (
20
+ AttnProcessor2_0 as AttnProcessor,
21
+ ) # with torch2 installed
22
+ from utils.gradio_utils import cal_attn_mask_xl
23
+ from utils.utils import get_comic
24
+
25
+ MODEL_URL = "https://weights.replicate.delivery/default/HVision_NKU/StoryDiffusion.tar"
26
+ MODEL_CACHE = "model_weights"
27
+ STYLE_NAMES = list(styles.keys())
28
+ DEFAULT_STYLE_NAME = "Japanese Anime"
29
+
30
+ global total_count, attn_count, cur_step, mask1024, mask4096, attn_procs, unet
31
+ global sa32, sa64
32
+ global write
33
+ global height, width
34
+
35
+
36
+ """
37
+ # load and upload the weights to replicate.delivery for faster booting on Replicate
38
+ models_dict = {
39
+ "RealVision": "SG161222/RealVisXL_V4.0",
40
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y",
41
+ }
42
+ # photomaker_path = hf_hub_download(repo_id="TencentARC/PhotoMaker", filename="photomaker-v1.bin", repo_type="model")
43
+ photomaker_path = f"{MODEL_CACHE}/PhotoMaker/photomaker-v1.bin"
44
+
45
+ pipe_unstable = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
46
+ models_dict["Unstable"],
47
+ torch_dtype=torch.float16,
48
+ use_safetensors=False,
49
+ )
50
+ pipe_unstable.save_pretrained(f"{MODEL_CACHE}/Unstable/stablediffusionapi/sdxl-unstable-diffusers-y")
51
+
52
+ pipe_realvision = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
53
+ models_dict["RealVision"], torch_dtype=torch.float16, use_safetensors=True
54
+ )
55
+ pipe_realvision.save_pretrained(f"{MODEL_CACHE}/RealVision/SG161222/RealVisXL_V4.0")
56
+ """
57
+
58
+
59
+ class ModelOutput(BaseModel):
60
+ comic: Path
61
+ individual_images: list[Path]
62
+
63
+
64
+ def download_weights(url, dest):
65
+ start = time.time()
66
+ print("downloading url: ", url)
67
+ print("downloading to: ", dest)
68
+ subprocess.check_call(["pget", "-x", url, dest], close_fds=False)
69
+ print("downloading took: ", time.time() - start)
70
+
71
+
72
+ def setup_seed(seed):
73
+ torch.manual_seed(seed)
74
+ torch.cuda.manual_seed_all(seed)
75
+ np.random.seed(seed)
76
+ random.seed(seed)
77
+ torch.backends.cudnn.deterministic = True
78
+
79
+
80
+ def apply_style_positive(style_name: str, positive: str):
81
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
82
+ return p.replace("{prompt}", positive)
83
+
84
+
85
+ def apply_style(style_name: str, positives: list, negative: str = ""):
86
+ p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
87
+ return [
88
+ p.replace("{prompt}", positive) for positive in positives
89
+ ], n + " " + negative
90
+
91
+
92
+ def set_attention_processor(unet, id_length, is_ipadapter=False):
93
+ global total_count
94
+ total_count = 0
95
+ attn_procs = {}
96
+ for name in unet.attn_processors.keys():
97
+ cross_attention_dim = (
98
+ None
99
+ if name.endswith("attn1.processor")
100
+ else unet.config.cross_attention_dim
101
+ )
102
+ if name.startswith("mid_block"):
103
+ hidden_size = unet.config.block_out_channels[-1]
104
+ elif name.startswith("up_blocks"):
105
+ block_id = int(name[len("up_blocks.")])
106
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
107
+ elif name.startswith("down_blocks"):
108
+ block_id = int(name[len("down_blocks.")])
109
+ hidden_size = unet.config.block_out_channels[block_id]
110
+ if cross_attention_dim is None:
111
+ if name.startswith("up_blocks"):
112
+ attn_procs[name] = SpatialAttnProcessor2_0(id_length=id_length)
113
+ total_count += 1
114
+ else:
115
+ attn_procs[name] = AttnProcessor()
116
+ else:
117
+ if is_ipadapter:
118
+ attn_procs[name] = IPAttnProcessor2_0(
119
+ hidden_size=hidden_size,
120
+ cross_attention_dim=cross_attention_dim,
121
+ scale=1,
122
+ num_tokens=4,
123
+ ).to(unet.device, dtype=torch.float16)
124
+ else:
125
+ attn_procs[name] = AttnProcessor()
126
+
127
+ unet.set_attn_processor(copy.deepcopy(attn_procs))
128
+ print("Successfully load paired self-attention")
129
+ print(f"Number of the processor : {total_count}")
130
+
131
+
132
+ #################################################
133
+ ########Consistent Self-Attention################
134
+ #################################################
135
+ class SpatialAttnProcessor2_0(torch.nn.Module):
136
+ r"""
137
+ Attention processor for IP-Adapater for PyTorch 2.0.
138
+ Args:
139
+ hidden_size (`int`):
140
+ The hidden size of the attention layer.
141
+ cross_attention_dim (`int`):
142
+ The number of channels in the `encoder_hidden_states`.
143
+ text_context_len (`int`, defaults to 77):
144
+ The context length of the text features.
145
+ scale (`float`, defaults to 1.0):
146
+ the weight scale of image prompt.
147
+ """
148
+
149
+ def __init__(
150
+ self,
151
+ hidden_size=None,
152
+ cross_attention_dim=None,
153
+ id_length=4,
154
+ device="cuda",
155
+ dtype=torch.float16,
156
+ ):
157
+ super().__init__()
158
+ if not hasattr(F, "scaled_dot_product_attention"):
159
+ raise ImportError(
160
+ "AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
161
+ )
162
+ self.device = device
163
+ self.dtype = dtype
164
+ self.hidden_size = hidden_size
165
+ self.cross_attention_dim = cross_attention_dim
166
+ self.total_length = id_length + 1
167
+ self.id_length = id_length
168
+ self.id_bank = {}
169
+
170
+ def __call__(
171
+ self,
172
+ attn,
173
+ hidden_states,
174
+ encoder_hidden_states=None,
175
+ attention_mask=None,
176
+ temb=None,
177
+ ):
178
+ global total_count, attn_count, cur_step, mask1024, mask4096
179
+ global sa32, sa64
180
+ global write
181
+ global height, width
182
+ if write:
183
+ self.id_bank[cur_step] = [
184
+ hidden_states[: self.id_length],
185
+ hidden_states[self.id_length :],
186
+ ]
187
+ else:
188
+ encoder_hidden_states = torch.cat(
189
+ (
190
+ self.id_bank[cur_step][0].to(self.device),
191
+ hidden_states[:1],
192
+ self.id_bank[cur_step][1].to(self.device),
193
+ hidden_states[1:],
194
+ )
195
+ )
196
+ # skip in early step
197
+ if cur_step < 5:
198
+ hidden_states = self.__call2__(
199
+ attn, hidden_states, encoder_hidden_states, attention_mask, temb
200
+ )
201
+ else: # 256 1024 4096
202
+ random_number = random.random()
203
+ if cur_step < 20:
204
+ rand_num = 0.3
205
+ else:
206
+ rand_num = 0.1
207
+ if random_number > rand_num:
208
+ if not write:
209
+ if hidden_states.shape[1] == (height // 32) * (width // 32):
210
+ attention_mask = mask1024[
211
+ mask1024.shape[0] // self.total_length * self.id_length :
212
+ ]
213
+ else:
214
+ attention_mask = mask4096[
215
+ mask4096.shape[0] // self.total_length * self.id_length :
216
+ ]
217
+ else:
218
+ if hidden_states.shape[1] == (height // 32) * (width // 32):
219
+ attention_mask = mask1024[
220
+ : mask1024.shape[0] // self.total_length * self.id_length,
221
+ : mask1024.shape[0] // self.total_length * self.id_length,
222
+ ]
223
+ else:
224
+ attention_mask = mask4096[
225
+ : mask4096.shape[0] // self.total_length * self.id_length,
226
+ : mask4096.shape[0] // self.total_length * self.id_length,
227
+ ]
228
+ hidden_states = self.__call1__(
229
+ attn, hidden_states, encoder_hidden_states, attention_mask, temb
230
+ )
231
+ else:
232
+ hidden_states = self.__call2__(
233
+ attn, hidden_states, None, attention_mask, temb
234
+ )
235
+ attn_count += 1
236
+ if attn_count == total_count:
237
+ attn_count = 0
238
+ cur_step += 1
239
+ mask1024, mask4096 = cal_attn_mask_xl(
240
+ self.total_length,
241
+ self.id_length,
242
+ sa32,
243
+ sa64,
244
+ height,
245
+ width,
246
+ device=self.device,
247
+ dtype=self.dtype,
248
+ )
249
+
250
+ return hidden_states
251
+
252
+ def __call1__(
253
+ self,
254
+ attn,
255
+ hidden_states,
256
+ encoder_hidden_states=None,
257
+ attention_mask=None,
258
+ temb=None,
259
+ ):
260
+ residual = hidden_states
261
+ if attn.spatial_norm is not None:
262
+ hidden_states = attn.spatial_norm(hidden_states, temb)
263
+ input_ndim = hidden_states.ndim
264
+
265
+ if input_ndim == 4:
266
+ total_batch_size, channel, height, width = hidden_states.shape
267
+ hidden_states = hidden_states.view(
268
+ total_batch_size, channel, height * width
269
+ ).transpose(1, 2)
270
+ total_batch_size, nums_token, channel = hidden_states.shape
271
+ img_nums = total_batch_size // 2
272
+ hidden_states = hidden_states.view(-1, img_nums, nums_token, channel).reshape(
273
+ -1, img_nums * nums_token, channel
274
+ )
275
+
276
+ batch_size, sequence_length, _ = hidden_states.shape
277
+
278
+ if attn.group_norm is not None:
279
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
280
+ 1, 2
281
+ )
282
+
283
+ query = attn.to_q(hidden_states)
284
+
285
+ if encoder_hidden_states is None:
286
+ encoder_hidden_states = hidden_states # B, N, C
287
+ else:
288
+ encoder_hidden_states = encoder_hidden_states.view(
289
+ -1, self.id_length + 1, nums_token, channel
290
+ ).reshape(-1, (self.id_length + 1) * nums_token, channel)
291
+
292
+ key = attn.to_k(encoder_hidden_states)
293
+ value = attn.to_v(encoder_hidden_states)
294
+
295
+ inner_dim = key.shape[-1]
296
+ head_dim = inner_dim // attn.heads
297
+
298
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
299
+
300
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
301
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
302
+ hidden_states = F.scaled_dot_product_attention(
303
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
304
+ )
305
+
306
+ hidden_states = hidden_states.transpose(1, 2).reshape(
307
+ total_batch_size, -1, attn.heads * head_dim
308
+ )
309
+ hidden_states = hidden_states.to(query.dtype)
310
+
311
+ # linear proj
312
+ hidden_states = attn.to_out[0](hidden_states)
313
+ # dropout
314
+ hidden_states = attn.to_out[1](hidden_states)
315
+
316
+ if input_ndim == 4:
317
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
318
+ total_batch_size, channel, height, width
319
+ )
320
+ if attn.residual_connection:
321
+ hidden_states = hidden_states + residual
322
+ hidden_states = hidden_states / attn.rescale_output_factor
323
+ # print(hidden_states.shape)
324
+ return hidden_states
325
+
326
+ def __call2__(
327
+ self,
328
+ attn,
329
+ hidden_states,
330
+ encoder_hidden_states=None,
331
+ attention_mask=None,
332
+ temb=None,
333
+ ):
334
+ residual = hidden_states
335
+
336
+ if attn.spatial_norm is not None:
337
+ hidden_states = attn.spatial_norm(hidden_states, temb)
338
+
339
+ input_ndim = hidden_states.ndim
340
+
341
+ if input_ndim == 4:
342
+ batch_size, channel, height, width = hidden_states.shape
343
+ hidden_states = hidden_states.view(
344
+ batch_size, channel, height * width
345
+ ).transpose(1, 2)
346
+
347
+ batch_size, sequence_length, channel = hidden_states.shape
348
+ # print(hidden_states.shape)
349
+ if attention_mask is not None:
350
+ attention_mask = attn.prepare_attention_mask(
351
+ attention_mask, sequence_length, batch_size
352
+ )
353
+ # scaled_dot_product_attention expects attention_mask shape to be
354
+ # (batch, heads, source_length, target_length)
355
+ attention_mask = attention_mask.view(
356
+ batch_size, attn.heads, -1, attention_mask.shape[-1]
357
+ )
358
+
359
+ if attn.group_norm is not None:
360
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
361
+ 1, 2
362
+ )
363
+
364
+ query = attn.to_q(hidden_states)
365
+
366
+ if encoder_hidden_states is None:
367
+ encoder_hidden_states = hidden_states # B, N, C
368
+ else:
369
+ encoder_hidden_states = encoder_hidden_states.view(
370
+ -1, self.id_length + 1, sequence_length, channel
371
+ ).reshape(-1, (self.id_length + 1) * sequence_length, channel)
372
+
373
+ key = attn.to_k(encoder_hidden_states)
374
+ value = attn.to_v(encoder_hidden_states)
375
+
376
+ inner_dim = key.shape[-1]
377
+ head_dim = inner_dim // attn.heads
378
+
379
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
380
+
381
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
382
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
383
+
384
+ hidden_states = F.scaled_dot_product_attention(
385
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
386
+ )
387
+
388
+ hidden_states = hidden_states.transpose(1, 2).reshape(
389
+ batch_size, -1, attn.heads * head_dim
390
+ )
391
+ hidden_states = hidden_states.to(query.dtype)
392
+
393
+ # linear proj
394
+ hidden_states = attn.to_out[0](hidden_states)
395
+ # dropout
396
+ hidden_states = attn.to_out[1](hidden_states)
397
+
398
+ if input_ndim == 4:
399
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
400
+ batch_size, channel, height, width
401
+ )
402
+
403
+ if attn.residual_connection:
404
+ hidden_states = hidden_states + residual
405
+
406
+ hidden_states = hidden_states / attn.rescale_output_factor
407
+
408
+ return hidden_states
409
+
410
+
411
+ class Predictor(BasePredictor):
412
+ def setup(self) -> None:
413
+ """Load the model into memory to make running multiple predictions efficient"""
414
+
415
+ models_dict = {
416
+ "RealVision": "SG161222/RealVisXL_V4.0",
417
+ "Unstable": "stablediffusionapi/sdxl-unstable-diffusers-y",
418
+ }
419
+
420
+ if not os.path.exists(MODEL_CACHE):
421
+ download_weights(MODEL_URL, MODEL_CACHE)
422
+
423
+ photomaker_path = f"{MODEL_CACHE}/PhotoMaker/photomaker-v1.bin"
424
+
425
+ self.sdxl_pipe_unstable = StableDiffusionXLPipeline.from_pretrained(
426
+ f"{MODEL_CACHE}/Unstable/sdxl/stablediffusionapi/sdxl-unstable-diffusers-y",
427
+ torch_dtype=torch.float16,
428
+ )
429
+ self.sdxl_pipe_realvision = StableDiffusionXLPipeline.from_pretrained(
430
+ f"{MODEL_CACHE}/RealVision/sdxl/SG161222/RealVisXL_V4.0",
431
+ torch_dtype=torch.float16,
432
+ )
433
+
434
+ self.pipe_unstable = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
435
+ f"{MODEL_CACHE}/Unstable/stablediffusionapi/sdxl-unstable-diffusers-y",
436
+ torch_dtype=torch.float16,
437
+ use_safetensors=False,
438
+ )
439
+ self.pipe_unstable.load_photomaker_adapter(
440
+ os.path.dirname(photomaker_path),
441
+ subfolder="",
442
+ weight_name=os.path.basename(photomaker_path),
443
+ trigger_word="img", # define the trigger word
444
+ )
445
+
446
+ self.pipe_realvision = PhotoMakerStableDiffusionXLPipeline.from_pretrained(
447
+ f"{MODEL_CACHE}/RealVision/SG161222/RealVisXL_V4.0",
448
+ torch_dtype=torch.float16,
449
+ use_safetensors=True,
450
+ )
451
+ self.pipe_realvision.load_photomaker_adapter(
452
+ os.path.dirname(photomaker_path),
453
+ subfolder="",
454
+ weight_name=os.path.basename(photomaker_path),
455
+ trigger_word="img", # define the trigger word
456
+ )
457
+ self.pipe_realvision.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
458
+ self.pipe_realvision.fuse_lora()
459
+
460
+ @torch.inference_mode()
461
+ def predict(
462
+ self,
463
+ sd_model: str = Input(
464
+ description="Choose a model",
465
+ choices=["Unstable", "RealVision"],
466
+ default="Unstable",
467
+ ),
468
+ ref_image: Path = Input(
469
+ description="Reference image for the character",
470
+ default=None,
471
+ ),
472
+ character_description: str = Input(
473
+ description="General description of the character. If ref_image above is provided, making sure to follow the class word you want to customize with the trigger word 'img', such as: 'man img' or 'woman img' or 'girl img'",
474
+ default="a man, wearing black suit",
475
+ ),
476
+ negative_prompt: str = Input(
477
+ description="Describe things you do not want to see in the output",
478
+ default="bad anatomy, bad hands, missing fingers, extra fingers, three hands, three legs, bad arms, missing legs, missing arms, poorly drawn face, bad face, fused face, cloned face, three crus, fused feet, fused thigh, extra crus, ugly fingers, horn, cartoon, cg, 3d, unreal, animate, amputation, disconnected limbs",
479
+ ),
480
+ comic_description: str = Input(
481
+ description="Comic Description. Each frame is divided by a new line. Only the first 10 prompts are valid for demo speed! For comic_description NOT using ref_image: (1) Support Typesetting Style and Captioning. By default, the prompt is used as the caption for each image. If you need to change the caption, add a '#' at the end of each line. Only the part after the '#' will be added as a caption to the image. (2) The [NC] symbol is used as a flag to indicate that no characters should be present in the generated scene images. If you want do that, prepend the '[NC]' at the beginning of the line.",
482
+ default="at home, read new paper #at home, The newspaper says there is a treasure house in the forest.\non the road, near the forest\n[NC] The car on the road, near the forest #He drives to the forest in search of treasure.\n[NC]A tiger appeared in the forest, at night \nvery frightened, open mouth, in the forest, at night\nrunning very fast, in the forest, at night\n[NC] A house in the forest, at night #Suddenly, he discovers the treasure house!\nin the house filled with treasure, laughing, at night #He is overjoyed inside the house.",
483
+ ),
484
+ style_name: str = Input(
485
+ description="Style template",
486
+ choices=STYLE_NAMES,
487
+ default=DEFAULT_STYLE_NAME,
488
+ ),
489
+ comic_style: str = Input(
490
+ description="Select the comic style for the combined comic",
491
+ choices=["Four Pannel", "Classic Comic Style"],
492
+ default="Classic Comic Style",
493
+ ),
494
+ style_strength_ratio: int = Input(
495
+ description="Style strength of Ref Image (%), only used if ref_image is provided",
496
+ default=20,
497
+ ge=15,
498
+ le=50,
499
+ ),
500
+ image_width: int = Input(
501
+ description="Width of output image",
502
+ choices=[
503
+ 256,
504
+ 288,
505
+ 320,
506
+ 352,
507
+ 384,
508
+ 416,
509
+ 448,
510
+ 480,
511
+ 512,
512
+ 544,
513
+ 576,
514
+ 608,
515
+ 640,
516
+ 672,
517
+ 704,
518
+ 736,
519
+ 768,
520
+ 800,
521
+ 832,
522
+ 864,
523
+ 896,
524
+ 928,
525
+ 960,
526
+ 992,
527
+ 1024,
528
+ ],
529
+ default=768,
530
+ ),
531
+ image_height: int = Input(
532
+ description="Height of output image",
533
+ choices=[
534
+ 256,
535
+ 288,
536
+ 320,
537
+ 352,
538
+ 384,
539
+ 416,
540
+ 448,
541
+ 480,
542
+ 512,
543
+ 544,
544
+ 576,
545
+ 608,
546
+ 640,
547
+ 672,
548
+ 704,
549
+ 736,
550
+ 768,
551
+ 800,
552
+ 832,
553
+ 864,
554
+ 896,
555
+ 928,
556
+ 960,
557
+ 992,
558
+ 1024,
559
+ ],
560
+ default=768,
561
+ ),
562
+ num_steps: int = Input(
563
+ description="Number of sample steps", ge=20, le=50, default=25
564
+ ),
565
+ guidance_scale: float = Input(
566
+ description="Scale for classifier-free guidance", ge=0.1, le=10, default=5
567
+ ),
568
+ seed: int = Input(
569
+ description="Random seed. Leave blank to randomize the seed", default=None
570
+ ),
571
+ sa32_setting: float = Input(
572
+ description="The degree of Paired Attention at 32 x 32 self-attention layers",
573
+ default=0.5,
574
+ ge=0,
575
+ le=1.0,
576
+ ),
577
+ sa64_setting: float = Input(
578
+ description="The degree of Paired Attention at 64 x 64 self-attention layers",
579
+ default=0.5,
580
+ ge=0,
581
+ le=1.0,
582
+ ),
583
+ num_ids: int = Input(
584
+ description="Number of id images in total images. This should not exceed total number of line-separated prompts",
585
+ default=3,
586
+ ),
587
+ output_format: str = Input(
588
+ description="Format of the output images",
589
+ choices=["webp", "jpg", "png"],
590
+ default="webp",
591
+ ),
592
+ output_quality: int = Input(
593
+ description="Quality of the output images, from 0 to 100. 100 is best quality, 0 is lowest quality",
594
+ default=80,
595
+ ge=0,
596
+ le=100,
597
+ ),
598
+ ) -> ModelOutput:
599
+ """Run a single prediction on the model"""
600
+
601
+ global total_count, attn_count, cur_step, mask1024, mask4096, attn_procs, unet
602
+ global sa32, sa64
603
+ global write
604
+ global height, width
605
+
606
+ assert (
607
+ len(character_description.strip()) > 0
608
+ ), "Please provide the description of the character."
609
+
610
+ if ref_image is not None:
611
+ assert (
612
+ "img" in character_description
613
+ ), f"When using ref_image, please add the trigger word 'img' behind the class word you want to customize, such as: man img or woman img"
614
+ assert (
615
+ "[NC]" not in character_description
616
+ ), "You should not use trigger word [NC] when ref_image is provided."
617
+
618
+ height = image_height
619
+ width = image_width
620
+ id_length = num_ids
621
+ sa32 = sa32_setting
622
+ sa64 = sa64_setting
623
+
624
+ clipped_prompts = comic_description.splitlines()[:10]
625
+ print(clipped_prompts)
626
+ prompts = [
627
+ (
628
+ character_description + "," + prompt
629
+ if "[NC]" not in prompt
630
+ else prompt.replace("[NC]", "")
631
+ )
632
+ for prompt in clipped_prompts
633
+ ]
634
+ print(prompts)
635
+ prompts = [
636
+ prompt.rpartition("#")[0].strip() if "#" in prompt else prompt.strip()
637
+ for prompt in prompts
638
+ ]
639
+ print(prompts)
640
+ assert id_length <= len(
641
+ prompts
642
+ ), "id_length should not exceed total number of line-separated prompts"
643
+
644
+ id_prompts = prompts[:id_length]
645
+ real_prompts = prompts[id_length:]
646
+
647
+ if seed is None:
648
+ seed = int.from_bytes(os.urandom(2), "big")
649
+ print(f"Using seed: {seed}")
650
+
651
+ device = "cuda:0"
652
+ setup_seed(seed)
653
+ generator = torch.Generator(device=device).manual_seed(seed)
654
+
655
+ torch.cuda.empty_cache()
656
+
657
+ model_type = "original" if ref_image is None else "Photomaker"
658
+
659
+ if model_type == "original":
660
+ pipe = (
661
+ self.sdxl_pipe_realvision
662
+ if style_name == "(No style)"
663
+ else self.sdxl_pipe_unstable
664
+ )
665
+ pipe = pipe.to(device)
666
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
667
+ else:
668
+ if sd_model != "RealVision" and style_name != "(No style)":
669
+ pipe = self.pipe_unstable.to(device)
670
+ else:
671
+ pipe = self.pipe_realvision.to(device)
672
+ pipe.id_encoder.to(device)
673
+
674
+ write = True
675
+ cur_step = 0
676
+ attn_count = 0
677
+
678
+ set_attention_processor(pipe.unet, id_length, is_ipadapter=False)
679
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
680
+ pipe.enable_freeu(s1=0.6, s2=0.4, b1=1.1, b2=1.2)
681
+ curmodel_type = sd_model + "-" + model_type + "" + str(id_length)
682
+
683
+ id_prompts, negative_prompt = apply_style(
684
+ style_name, id_prompts, negative_prompt
685
+ )
686
+
687
+ total_results = []
688
+ if model_type == "original":
689
+ id_images = pipe(
690
+ id_prompts,
691
+ num_inference_steps=num_steps,
692
+ guidance_scale=guidance_scale,
693
+ height=height,
694
+ width=width,
695
+ negative_prompt=negative_prompt,
696
+ generator=generator,
697
+ ).images
698
+ else:
699
+ input_id_images = [load_image(str(ref_image))]
700
+ start_merge_step = int(float(style_strength_ratio) / 100 * num_steps)
701
+ id_images = pipe(
702
+ id_prompts,
703
+ input_id_images=input_id_images,
704
+ num_inference_steps=num_steps,
705
+ guidance_scale=guidance_scale,
706
+ start_merge_step=start_merge_step,
707
+ height=height,
708
+ width=width,
709
+ negative_prompt=negative_prompt,
710
+ generator=generator,
711
+ ).images
712
+
713
+ total_results = id_images + total_results
714
+
715
+ real_images = []
716
+ write = False
717
+ for real_prompt in real_prompts:
718
+ cur_step = 0
719
+ real_prompt = apply_style_positive(style_name, real_prompt)
720
+ if model_type == "original":
721
+ real_images.append(
722
+ pipe(
723
+ real_prompt,
724
+ num_inference_steps=num_steps,
725
+ guidance_scale=guidance_scale,
726
+ height=height,
727
+ width=width,
728
+ negative_prompt=negative_prompt,
729
+ generator=generator,
730
+ ).images[0]
731
+ )
732
+ else:
733
+ real_images.append(
734
+ pipe(
735
+ real_prompt,
736
+ input_id_images=input_id_images,
737
+ num_inference_steps=num_steps,
738
+ guidance_scale=guidance_scale,
739
+ start_merge_step=start_merge_step,
740
+ height=height,
741
+ width=width,
742
+ negative_prompt=negative_prompt,
743
+ generator=generator,
744
+ ).images[0]
745
+ )
746
+
747
+ total_results = [real_images[-1]] + total_results
748
+
749
+ captions = clipped_prompts
750
+ captions = [caption.replace("[NC]", "") for caption in captions]
751
+ captions = [
752
+ caption.split("#")[-1].strip() if "#" in caption else caption.strip()
753
+ for caption in captions
754
+ ]
755
+
756
+ comic = get_comic(
757
+ id_images + real_images,
758
+ comic_style,
759
+ captions=captions,
760
+ font=ImageFont.truetype("./fonts/Inkfree.ttf", int(45)),
761
+ )
762
+
763
+ extension = output_format.lower()
764
+ extension = "jpeg" if extension == "jpg" else extension
765
+ comic_out = f"/tmp/comic.{extension}"
766
+ comic[0].save(comic_out)
767
+
768
+ save_params = {"format": extension.upper()}
769
+ if not output_format == "png":
770
+ save_params["quality"] = output_quality
771
+ save_params["optimize"] = True
772
+
773
+ output_paths = []
774
+ for index, sample in enumerate(total_results[::-1]):
775
+ output_filename = f"/tmp/out-{index}.{extension}"
776
+ sample.save(output_filename, **save_params)
777
+ output_paths.append(Path(output_filename))
778
+
779
+ del pipe
780
+
781
+ return ModelOutput(comic=Path(comic_out), individual_images=output_paths)