MrOplus commited on
Commit
d7881fa
Β·
0 Parent(s):
.gitattributes ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
+ assets/examples/man.jpg filter=lfs diff=lfs merge=lfs -text
37
+ assets/examples/woman.jpg filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ .idea
3
+ .ipynb_checkpoints
4
+ .gradio
5
+ *.swp
6
+ *.pyc
7
+ __pycache__
8
+ *.tar*
9
+ *.zip
10
+ *.pkl
11
+ *.pyc
12
+ *.bak
13
+ *.png
14
+ *.deb
15
+
16
+ .isort.cfg
17
+ .pre-commit-config.yaml
18
+
19
+ dataset_stats
20
+ debug*
21
+ locks
22
+ checkpoints
23
+ pretrained_checkpoint
24
+ ./models
25
+ models
26
+ results
27
+ wandb
28
+ tmp*
29
+ env*
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.
README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: InfiniteYou-FLUX
3
+ emoji: πŸ“Έ
4
+ colorFrom: red
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 5.23.1
8
+ app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ short_description: Flexible Photo Recrafting While Preserving Your Identity
12
+ ---
13
+
14
+ The images used in this demo are sourced from consented subjects or generated by the models. These pictures are intended solely to show the capabilities of our research. If you have any concerns, please contact us, and we will promptly remove any inappropriate content.
15
+
16
+ The use of the released code, model, and demo must strictly adhere to the respective licenses. The code in this demo is licensed under the [Apache License 2.0](./LICENSE), and our model is released under the [Creative Commons Attribution-NonCommercial 4.0 International Public License](https://creativecommons.org/licenses/by-nc/4.0/legalcode) for academic research purposes only. Any manual or automatic downloading of the face models from [InsightFace](https://github.com/deepinsight/insightface), the [FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) base model, LoRAs ([Realism](https://civitai.com/models/631986?modelVersionId=706528) and [Anti-blur](https://civitai.com/models/675581/anti-blur-flux-lora)), *etc.*, must follow their original licenses and be used only for academic research purposes.
17
+
18
+ This research aims to positively impact the field of Generative AI. Any usage of this method must be responsible and comply with local laws. The developers do not assume any responsibility for any potential misuse. We added the "AI Generated" watermark for enhanced safety.
app.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 All rights reserved.
2
+
3
+ import os
4
+ import torch
5
+ import gradio as gr
6
+ import huggingface_hub
7
+ from huggingface_hub import snapshot_download
8
+ from PIL import Image, ImageDraw, ImageFont
9
+
10
+ # Import the base pipeline from diffusers
11
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
12
+ from transformers import CLIPTextModel, CLIPTokenizer
13
+
14
+ # Define default parameters
15
+ DEFAULT_SEED = 42
16
+ DEFAULT_STEPS = 30
17
+ DEFAULT_GUIDANCE_SCALE = 7.5
18
+ RED_BG_COLOR = "#ffcccc" # Light red background
19
+
20
+ # Initialize the model
21
+ def download_model():
22
+ # Download the model (using a simple SD model as example)
23
+ snapshot_download(repo_id='runwayml/stable-diffusion-v1-5', local_dir='./models/stable-diffusion', local_dir_use_symlinks=False)
24
+
25
+ def init_pipeline():
26
+ # Initialize a simple text-to-image pipeline
27
+ pipeline = StableDiffusionControlNetPipeline.from_pretrained(
28
+ "./models/stable-diffusion",
29
+ torch_dtype=torch.float16,
30
+ safety_checker=None
31
+ )
32
+ pipeline = pipeline.to("cuda")
33
+ return pipeline
34
+
35
+ # Generate image function
36
+ def generate_image(prompt, seed, num_steps, guidance_scale):
37
+ try:
38
+ # Make sure we have a valid seed
39
+ if seed == 0:
40
+ seed = torch.seed() & 0xFFFFFFFF
41
+
42
+ # Set up generator for reproducibility
43
+ generator = torch.Generator("cuda").manual_seed(seed)
44
+
45
+ # Generate the image
46
+ image = pipeline(
47
+ prompt=prompt,
48
+ num_inference_steps=num_steps,
49
+ guidance_scale=guidance_scale,
50
+ generator=generator
51
+ ).images[0]
52
+
53
+ # Add watermark
54
+ image = add_safety_watermark(image)
55
+
56
+ except Exception as e:
57
+ print(f"Error generating image: {e}")
58
+ return gr.update()
59
+
60
+ return gr.update(value=image, label=f"Generated Image, seed = {seed}")
61
+
62
+ # Add watermark to image
63
+ def add_safety_watermark(image, text='AI Generated'):
64
+ width, height = image.size
65
+ draw = ImageDraw.Draw(image)
66
+
67
+ # Set font size based on image height
68
+ font_size = int(height * 0.028)
69
+ font = ImageFont.load_default()
70
+
71
+ # Calculate text position
72
+ text_width = len(text) * font_size * 0.6 # Approximate width
73
+ x = width - text_width - 10
74
+ y = height - font_size - 20
75
+
76
+ # Add shadow and text
77
+ draw.text((x+2, y+2), text, fill="black")
78
+ draw.text((x, y), text, fill="white")
79
+
80
+ return image
81
+
82
+ # Create example function
83
+ def generate_example(prompt, seed):
84
+ return generate_image(prompt, seed, DEFAULT_STEPS, DEFAULT_GUIDANCE_SCALE)
85
+
86
+ # Sample examples
87
+ sample_list = [
88
+ ['A majestic mountain landscape with snow peaks and pine trees', 123],
89
+ ['A futuristic city with flying cars and tall skyscrapers', 456],
90
+ ['A serene beach scene with clear blue waters', 789],
91
+ ]
92
+
93
+ # Create the Gradio interface
94
+ with gr.Blocks(css=f".gradio-container {{ background-color: {RED_BG_COLOR} !important; }}") as demo:
95
+ gr.HTML("""
96
+ <div style="text-align: center; max-width: 800px; margin: 0 auto;">
97
+ <h1 style="font-size: 2rem; font-weight: 700;">Simple Text to Image Generator</h1>
98
+ <h2 style="font-size: 1.2rem; font-weight: 300; margin-bottom: 1rem;">Convert your text descriptions into images</h2>
99
+ </div>
100
+ """)
101
+
102
+ with gr.Row():
103
+ with gr.Column(scale=2):
104
+ # Input components
105
+ ui_prompt_text = gr.Textbox(label="Text Prompt", value="A beautiful landscape with mountains and trees")
106
+ ui_seed = gr.Number(label="Seed (0 for random)", value=DEFAULT_SEED)
107
+ ui_steps = gr.Slider(minimum=10, maximum=50, value=DEFAULT_STEPS, step=1, label="Number of Steps")
108
+ ui_guidance_scale = gr.Slider(minimum=1.0, maximum=15.0, value=DEFAULT_GUIDANCE_SCALE, step=0.5, label="Guidance Scale")
109
+
110
+ ui_btn_generate = gr.Button("Generate Image")
111
+
112
+ with gr.Column(scale=3):
113
+ # Output components
114
+ image_output = gr.Image(label="Generated Image", interactive=False, height=512)
115
+
116
+ gr.Examples(
117
+ sample_list,
118
+ inputs=[ui_prompt_text, ui_seed],
119
+ outputs=[image_output],
120
+ fn=generate_example,
121
+ cache_examples=True
122
+ )
123
+
124
+ ui_btn_generate.click(
125
+ generate_image,
126
+ inputs=[ui_prompt_text, ui_seed, ui_steps, ui_guidance_scale],
127
+ outputs=[image_output]
128
+ )
129
+
130
+ gr.Markdown(
131
+ """
132
+ ### How to Use:
133
+ 1. Enter a detailed text description of the image you want to create
134
+ 2. Adjust the parameters if needed (or leave as default)
135
+ 3. Click "Generate Image" and wait for the result
136
+
137
+ ### Tips:
138
+ - Detailed prompts work better than short ones
139
+ - Try different seeds for different variations
140
+ - Higher guidance scale values make the image follow the prompt more closely
141
+ """
142
+ )
143
+
144
+ # Initialize and launch
145
+ print("Downloading models...")
146
+ download_model()
147
+
148
+ print("Initializing pipeline...")
149
+ pipeline = init_pipeline()
150
+
151
+ print("Launching Gradio interface...")
152
+ demo.launch()
pipelines/__init__.py ADDED
File without changes
pipelines/pipeline_flux_infusenet.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 Bytedance Ltd. and/or its affiliates.
2
+ # Copyright (c) 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from diffusers import FluxControlNetPipeline
22
+ from diffusers.models.controlnet_flux import FluxControlNetModel, FluxMultiControlNetModel
23
+ from diffusers.image_processor import PipelineImageInput
24
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
25
+ from diffusers.utils import replace_example_docstring, is_torch_xla_available, logging
26
+
27
+
28
+ if is_torch_xla_available():
29
+ import torch_xla.core.xla_model as xm
30
+
31
+ XLA_AVAILABLE = True
32
+ else:
33
+ XLA_AVAILABLE = False
34
+
35
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
36
+
37
+
38
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
39
+ def calculate_shift(
40
+ image_seq_len,
41
+ base_seq_len: int = 256,
42
+ max_seq_len: int = 4096,
43
+ base_shift: float = 0.5,
44
+ max_shift: float = 1.16,
45
+ ):
46
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
47
+ b = base_shift - m * base_seq_len
48
+ mu = image_seq_len * m + b
49
+ return mu
50
+
51
+
52
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
53
+ def retrieve_timesteps(
54
+ scheduler,
55
+ num_inference_steps: Optional[int] = None,
56
+ device: Optional[Union[str, torch.device]] = None,
57
+ timesteps: Optional[List[int]] = None,
58
+ sigmas: Optional[List[float]] = None,
59
+ **kwargs,
60
+ ):
61
+ r"""
62
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
63
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
64
+
65
+ Args:
66
+ scheduler (`SchedulerMixin`):
67
+ The scheduler to get timesteps from.
68
+ num_inference_steps (`int`):
69
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
70
+ must be `None`.
71
+ device (`str` or `torch.device`, *optional*):
72
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
73
+ timesteps (`List[int]`, *optional*):
74
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
75
+ `num_inference_steps` and `sigmas` must be `None`.
76
+ sigmas (`List[float]`, *optional*):
77
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
78
+ `num_inference_steps` and `timesteps` must be `None`.
79
+
80
+ Returns:
81
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
82
+ second element is the number of inference steps.
83
+ """
84
+ if timesteps is not None and sigmas is not None:
85
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
86
+ if timesteps is not None:
87
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
88
+ if not accepts_timesteps:
89
+ raise ValueError(
90
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
91
+ f" timestep schedules. Please check whether you are using the correct scheduler."
92
+ )
93
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
94
+ timesteps = scheduler.timesteps
95
+ num_inference_steps = len(timesteps)
96
+ elif sigmas is not None:
97
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
98
+ if not accept_sigmas:
99
+ raise ValueError(
100
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
101
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
102
+ )
103
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
104
+ timesteps = scheduler.timesteps
105
+ num_inference_steps = len(timesteps)
106
+ else:
107
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
108
+ timesteps = scheduler.timesteps
109
+ return timesteps, num_inference_steps
110
+
111
+
112
+ class FluxInfuseNetPipeline(FluxControlNetPipeline):
113
+ @torch.no_grad()
114
+ def __call__(
115
+ self,
116
+ prompt: Union[str, List[str]] = None,
117
+ prompt_2: Optional[Union[str, List[str]]] = None,
118
+ height: Optional[int] = None,
119
+ width: Optional[int] = None,
120
+ num_inference_steps: int = 28,
121
+ timesteps: List[int] = None,
122
+ guidance_scale: float = 3.5,
123
+ controlnet_guidance_scale: float = 1.0,
124
+ control_guidance_start: Union[float, List[float]] = 0.0,
125
+ control_guidance_end: Union[float, List[float]] = 1.0,
126
+ control_image: PipelineImageInput = None,
127
+ control_mode: Optional[Union[int, List[int]]] = None,
128
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
129
+ num_images_per_prompt: Optional[int] = 1,
130
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
131
+ latents: Optional[torch.FloatTensor] = None,
132
+ prompt_embeds: Optional[torch.FloatTensor] = None,
133
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
134
+ output_type: Optional[str] = "pil",
135
+ return_dict: bool = True,
136
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
137
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
138
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
139
+ max_sequence_length: int = 512,
140
+
141
+ # ID-specific parameters
142
+ controlnet_prompt_embeds: Optional[torch.FloatTensor] = None,
143
+
144
+ # True CFG parameters
145
+ true_guidance_scale: float = 1.0,
146
+ negative_prompt: Optional[Union[str, List[str]]] = None,
147
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
148
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
149
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
150
+ ):
151
+ r"""
152
+ Function invoked when calling the pipeline for generation.
153
+
154
+ Args:
155
+ prompt (`str` or `List[str]`, *optional*):
156
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
157
+ instead.
158
+ prompt_2 (`str` or `List[str]`, *optional*):
159
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
160
+ will be used instead
161
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
162
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
163
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
164
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
165
+ num_inference_steps (`int`, *optional*, defaults to 50):
166
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
167
+ expense of slower inference.
168
+ timesteps (`List[int]`, *optional*):
169
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
170
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
171
+ passed will be used. Must be in descending order.
172
+ guidance_scale (`float`, *optional*, defaults to 7.0):
173
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
174
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
175
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
176
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
177
+ usually at the expense of lower image quality.
178
+ controlnet_guidance_scale (`float`, *optional*, defaults to 7.0):
179
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
180
+ `controlnet_guidance_scale` is defined as `w` of equation 2. of [Imagen
181
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
182
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
183
+ usually at the expense of lower image quality.
184
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
185
+ The percentage of total steps at which the ControlNet starts applying.
186
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
187
+ The percentage of total steps at which the ControlNet stops applying.
188
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
189
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
190
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
191
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
192
+ as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
193
+ width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
194
+ images must be passed as a list such that each element of the list can be correctly batched for input
195
+ to a single ControlNet.
196
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
197
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
198
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
199
+ the corresponding scale as a list.
200
+ control_mode (`int` or `List[int]`,, *optional*, defaults to None):
201
+ The control mode when applying ControlNet-Union.
202
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
203
+ The number of images to generate per prompt.
204
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
205
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
206
+ to make generation deterministic.
207
+ latents (`torch.FloatTensor`, *optional*):
208
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
209
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
210
+ tensor will ge generated by sampling using the supplied random `generator`.
211
+ prompt_embeds (`torch.FloatTensor`, *optional*):
212
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
213
+ provided, text embeddings will be generated from `prompt` input argument.
214
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
215
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
216
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
217
+ output_type (`str`, *optional*, defaults to `"pil"`):
218
+ The output format of the generate image. Choose between
219
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
220
+ return_dict (`bool`, *optional*, defaults to `True`):
221
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
222
+ joint_attention_kwargs (`dict`, *optional*):
223
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
224
+ `self.processor` in
225
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
226
+ callback_on_step_end (`Callable`, *optional*):
227
+ A function that calls at the end of each denoising steps during the inference. The function is called
228
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
229
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
230
+ `callback_on_step_end_tensor_inputs`.
231
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
232
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
233
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
234
+ `._callback_tensor_inputs` attribute of your pipeline class.
235
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
236
+ controlnet_prompt_embeds (`torch.FloatTensor`, *optional*):
237
+ Pre-generated embeddings for the InfuseNet. Can be used to easily tweak inputs, *e.g.* image embeddings.
238
+ If not provided, embeddings will be generated from `prompt` or `prompt_embeds` input arguments.
239
+ true_guidance_scale (`float`, *optional*, defaults to 1.0):
240
+ True CFG scale as defined in [Classifier-Free Diffusion Guidance]((https://arxiv.org/abs/2207.12598).
241
+ negative_prompt (`str` or `List[str]`, *optional*):
242
+ The negative prompt or negative prompts to guide the image generation. If not defined, one has to pass
243
+ `negative_prompt_embeds`. instead.
244
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
245
+ The negative prompt or negative prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined,
246
+ `negative_prompt` is will be used instead.
247
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
248
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
249
+ weighting. If not provided, negative text embeddings will be generated from `negative_prompt` input
250
+ argument.
251
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
252
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
253
+ weighting. If not provided, negative pooled text embeddings will be generated from
254
+ `negative_prompt` input argument.
255
+
256
+ Examples:
257
+
258
+ Returns:
259
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
260
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
261
+ images.
262
+ """
263
+
264
+ height = height or self.default_sample_size * self.vae_scale_factor
265
+ width = width or self.default_sample_size * self.vae_scale_factor
266
+
267
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
268
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
269
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
270
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
271
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
272
+ mult = len(self.controlnet.nets) if isinstance(self.controlnet, FluxMultiControlNetModel) else 1
273
+ control_guidance_start, control_guidance_end = (
274
+ mult * [control_guidance_start],
275
+ mult * [control_guidance_end],
276
+ )
277
+
278
+ # 1. Check inputs. Raise error if not correct
279
+ self.check_inputs(
280
+ prompt,
281
+ prompt_2,
282
+ height,
283
+ width,
284
+ prompt_embeds=prompt_embeds,
285
+ pooled_prompt_embeds=pooled_prompt_embeds,
286
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
287
+ max_sequence_length=max_sequence_length,
288
+ )
289
+
290
+ self._guidance_scale = guidance_scale
291
+ self._controlnet_guidance_scale = controlnet_guidance_scale
292
+ self._true_guidance_scale = true_guidance_scale
293
+ self._joint_attention_kwargs = joint_attention_kwargs
294
+ self._interrupt = False
295
+
296
+ # 2. Define call parameters
297
+ if prompt is not None and isinstance(prompt, str):
298
+ batch_size = 1
299
+ elif prompt is not None and isinstance(prompt, list):
300
+ batch_size = len(prompt)
301
+ else:
302
+ batch_size = prompt_embeds.shape[0]
303
+
304
+ # device = self._execution_device
305
+ device = 'cuda'
306
+ dtype = self.transformer.dtype
307
+
308
+ # CPU offload controlnet, move back T5 to GPU
309
+ self.controlnet.cpu()
310
+ torch.cuda.empty_cache()
311
+ self.text_encoder_2.to(device)
312
+
313
+ lora_scale = (
314
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
315
+ )
316
+ (
317
+ prompt_embeds,
318
+ pooled_prompt_embeds,
319
+ text_ids,
320
+ ) = self.encode_prompt(
321
+ prompt=prompt,
322
+ prompt_2=prompt_2,
323
+ prompt_embeds=prompt_embeds,
324
+ pooled_prompt_embeds=pooled_prompt_embeds,
325
+ device=device,
326
+ num_images_per_prompt=num_images_per_prompt,
327
+ max_sequence_length=max_sequence_length,
328
+ lora_scale=lora_scale,
329
+ )
330
+ if negative_prompt is not None or (negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None):
331
+ (
332
+ negative_prompt_embeds,
333
+ negative_pooled_prompt_embeds,
334
+ negative_text_ids,
335
+ ) = self.encode_prompt(
336
+ prompt=negative_prompt,
337
+ prompt_2=negative_prompt_2,
338
+ prompt_embeds=negative_prompt_embeds,
339
+ pooled_prompt_embeds=negative_pooled_prompt_embeds,
340
+ device=device,
341
+ num_images_per_prompt=num_images_per_prompt,
342
+ max_sequence_length=max_sequence_length,
343
+ lora_scale=lora_scale,
344
+ )
345
+
346
+ if controlnet_prompt_embeds is None:
347
+ controlnet_prompt_embeds = prompt_embeds
348
+ (
349
+ controlnet_prompt_embeds,
350
+ pooled_prompt_embeds,
351
+ controlnet_text_ids,
352
+ ) = self.encode_prompt(
353
+ prompt=prompt,
354
+ prompt_2=prompt_2,
355
+ prompt_embeds=controlnet_prompt_embeds,
356
+ pooled_prompt_embeds=pooled_prompt_embeds,
357
+ device=device,
358
+ num_images_per_prompt=num_images_per_prompt,
359
+ max_sequence_length=max_sequence_length,
360
+ lora_scale=lora_scale,
361
+ )
362
+
363
+ # CPU offload T5, move back controlnet to GPU
364
+ self.text_encoder_2.cpu()
365
+ torch.cuda.empty_cache()
366
+ self.controlnet.to(device)
367
+
368
+ # 3. Prepare control image
369
+ num_channels_latents = self.transformer.config.in_channels // 4
370
+ if isinstance(self.controlnet, FluxControlNetModel):
371
+ control_image = self.prepare_image(
372
+ image=control_image,
373
+ width=width,
374
+ height=height,
375
+ batch_size=batch_size * num_images_per_prompt,
376
+ num_images_per_prompt=num_images_per_prompt,
377
+ device=device,
378
+ dtype=self.vae.dtype,
379
+ )
380
+ height, width = control_image.shape[-2:]
381
+
382
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
383
+ controlnet_blocks_repeat = False if self.controlnet.input_hint_block is None else True
384
+ if self.controlnet.input_hint_block is None:
385
+ # vae encode
386
+ control_image = self.vae.encode(control_image).latent_dist.sample()
387
+ control_image = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
388
+
389
+ # pack
390
+ height_control_image, width_control_image = control_image.shape[2:]
391
+ control_image = self._pack_latents(
392
+ control_image,
393
+ batch_size * num_images_per_prompt,
394
+ num_channels_latents,
395
+ height_control_image,
396
+ width_control_image,
397
+ )
398
+
399
+ # Here we ensure that `control_mode` has the same length as the control_image.
400
+ if control_mode is not None:
401
+ if not isinstance(control_mode, int):
402
+ raise ValueError(" For `FluxControlNet`, `control_mode` should be an `int` or `None`")
403
+ control_mode = torch.tensor(control_mode).to(device, dtype=torch.long)
404
+ control_mode = control_mode.view(-1, 1).expand(control_image.shape[0], 1)
405
+
406
+ elif isinstance(self.controlnet, FluxMultiControlNetModel):
407
+ control_images = []
408
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
409
+ controlnet_blocks_repeat = False if self.controlnet.nets[0].input_hint_block is None else True
410
+ for i, control_image_ in enumerate(control_image):
411
+ control_image_ = self.prepare_image(
412
+ image=control_image_,
413
+ width=width,
414
+ height=height,
415
+ batch_size=batch_size * num_images_per_prompt,
416
+ num_images_per_prompt=num_images_per_prompt,
417
+ device=device,
418
+ dtype=self.vae.dtype,
419
+ )
420
+ height, width = control_image_.shape[-2:]
421
+
422
+ if self.controlnet.nets[0].input_hint_block is None:
423
+ # vae encode
424
+ control_image_ = self.vae.encode(control_image_).latent_dist.sample()
425
+ control_image_ = (control_image_ - self.vae.config.shift_factor) * self.vae.config.scaling_factor
426
+
427
+ # pack
428
+ height_control_image, width_control_image = control_image_.shape[2:]
429
+ control_image_ = self._pack_latents(
430
+ control_image_,
431
+ batch_size * num_images_per_prompt,
432
+ num_channels_latents,
433
+ height_control_image,
434
+ width_control_image,
435
+ )
436
+ control_images.append(control_image_)
437
+
438
+ control_image = control_images
439
+
440
+ # Here we ensure that `control_mode` has the same length as the control_image.
441
+ if isinstance(control_mode, list) and len(control_mode) != len(control_image):
442
+ raise ValueError(
443
+ "For Multi-ControlNet, `control_mode` must be a list of the same "
444
+ + " length as the number of controlnets (control images) specified"
445
+ )
446
+ if not isinstance(control_mode, list):
447
+ control_mode = [control_mode] * len(control_image)
448
+ # set control mode
449
+ control_modes = []
450
+ for cmode in control_mode:
451
+ if cmode is None:
452
+ cmode = -1
453
+ control_mode = torch.tensor(cmode).expand(control_images[0].shape[0]).to(device, dtype=torch.long)
454
+ control_modes.append(control_mode)
455
+ control_mode = control_modes
456
+
457
+ # 4. Prepare latent variables
458
+ num_channels_latents = self.transformer.config.in_channels // 4
459
+ latents, latent_image_ids = self.prepare_latents(
460
+ batch_size * num_images_per_prompt,
461
+ num_channels_latents,
462
+ height,
463
+ width,
464
+ prompt_embeds.dtype,
465
+ device,
466
+ generator,
467
+ latents,
468
+ )
469
+
470
+ # 5. Prepare timesteps
471
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
472
+ image_seq_len = latents.shape[1]
473
+ mu = calculate_shift(
474
+ image_seq_len,
475
+ self.scheduler.config.base_image_seq_len,
476
+ self.scheduler.config.max_image_seq_len,
477
+ self.scheduler.config.base_shift,
478
+ self.scheduler.config.max_shift,
479
+ )
480
+ timesteps, num_inference_steps = retrieve_timesteps(
481
+ self.scheduler,
482
+ num_inference_steps,
483
+ device,
484
+ timesteps,
485
+ sigmas,
486
+ mu=mu,
487
+ )
488
+
489
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
490
+ self._num_timesteps = len(timesteps)
491
+
492
+ # 6. Create tensor stating which controlnets to keep
493
+ controlnet_keep = []
494
+ for i in range(len(timesteps)):
495
+ keeps = [
496
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
497
+ for s, e in zip(control_guidance_start, control_guidance_end)
498
+ ]
499
+ controlnet_keep.append(keeps[0] if isinstance(self.controlnet, FluxControlNetModel) else keeps)
500
+
501
+ # 7. Denoising loop
502
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
503
+ for i, t in enumerate(timesteps):
504
+ if self.interrupt:
505
+ continue
506
+
507
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
508
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
509
+
510
+ if isinstance(self.controlnet, FluxMultiControlNetModel):
511
+ use_guidance = self.controlnet.nets[0].config.guidance_embeds
512
+ else:
513
+ use_guidance = self.controlnet.config.guidance_embeds
514
+
515
+ guidance = torch.tensor([controlnet_guidance_scale], device=device) if use_guidance else None
516
+ guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
517
+
518
+ if isinstance(controlnet_keep[i], list):
519
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
520
+ else:
521
+ controlnet_cond_scale = controlnet_conditioning_scale
522
+ if isinstance(controlnet_cond_scale, list):
523
+ controlnet_cond_scale = controlnet_cond_scale[0]
524
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
525
+
526
+ # controlnet
527
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
528
+ hidden_states=latents,
529
+ controlnet_cond=control_image,
530
+ controlnet_mode=control_mode,
531
+ conditioning_scale=cond_scale,
532
+ timestep=timestep / 1000,
533
+ guidance=guidance,
534
+ pooled_projections=pooled_prompt_embeds,
535
+ encoder_hidden_states=controlnet_prompt_embeds,
536
+ txt_ids=controlnet_text_ids,
537
+ img_ids=latent_image_ids,
538
+ joint_attention_kwargs=self.joint_attention_kwargs,
539
+ return_dict=False,
540
+ )
541
+
542
+ guidance = (
543
+ torch.tensor([guidance_scale], device=device) if self.transformer.config.guidance_embeds else None
544
+ )
545
+ guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
546
+
547
+ noise_pred = self.transformer(
548
+ hidden_states=latents,
549
+ timestep=timestep / 1000,
550
+ guidance=guidance,
551
+ pooled_projections=pooled_prompt_embeds,
552
+ encoder_hidden_states=prompt_embeds,
553
+ controlnet_block_samples=controlnet_block_samples,
554
+ controlnet_single_block_samples=controlnet_single_block_samples,
555
+ txt_ids=text_ids,
556
+ img_ids=latent_image_ids,
557
+ joint_attention_kwargs=self.joint_attention_kwargs,
558
+ return_dict=False,
559
+ controlnet_blocks_repeat=controlnet_blocks_repeat,
560
+ )[0]
561
+
562
+ # perform true CFG
563
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None and negative_text_ids is not None:
564
+ noise_pred_uncond = self.transformer(
565
+ hidden_states=latents,
566
+ timestep=timestep / 1000,
567
+ guidance=guidance,
568
+ pooled_projections=negative_pooled_prompt_embeds,
569
+ encoder_hidden_states=negative_prompt_embeds,
570
+ controlnet_block_samples=None,
571
+ controlnet_single_block_samples=None,
572
+ txt_ids=negative_text_ids,
573
+ img_ids=latent_image_ids,
574
+ joint_attention_kwargs=self.joint_attention_kwargs,
575
+ return_dict=False,
576
+ controlnet_blocks_repeat=controlnet_blocks_repeat,
577
+ )[0]
578
+
579
+ noise_pred = noise_pred_uncond + true_guidance_scale * (noise_pred - noise_pred_uncond)
580
+
581
+ # compute the previous noisy sample x_t -> x_t-1
582
+ latents_dtype = latents.dtype
583
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
584
+
585
+ if latents.dtype != latents_dtype:
586
+ if torch.backends.mps.is_available():
587
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
588
+ latents = latents.to(latents_dtype)
589
+
590
+ if callback_on_step_end is not None:
591
+ callback_kwargs = {}
592
+ for k in callback_on_step_end_tensor_inputs:
593
+ callback_kwargs[k] = locals()[k]
594
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
595
+
596
+ latents = callback_outputs.pop("latents", latents)
597
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
598
+
599
+ # call the callback, if provided
600
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
601
+ progress_bar.update()
602
+
603
+ if XLA_AVAILABLE:
604
+ xm.mark_step()
605
+
606
+ if output_type == "latent":
607
+ image = latents
608
+
609
+ else:
610
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
611
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
612
+
613
+ image = self.vae.decode(latents, return_dict=False)[0]
614
+ image = self.image_processor.postprocess(image, output_type=output_type)
615
+
616
+ # Offload all models
617
+ self.maybe_free_model_hooks()
618
+
619
+ if not return_dict:
620
+ return (image,)
621
+
622
+ return FluxPipelineOutput(images=image)
pipelines/pipeline_infu_flux.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025 Bytedance Ltd. and/or its affiliates. All rights reserved.
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import copy
16
+ import math
17
+ import os
18
+ import random
19
+ from typing import Optional
20
+
21
+ import cv2
22
+ import numpy as np
23
+ import torch
24
+ from diffusers.models import FluxControlNetModel
25
+ from facexlib.recognition import init_recognition_model
26
+ from huggingface_hub import snapshot_download
27
+ from insightface.app import FaceAnalysis
28
+ from insightface.utils import face_align
29
+ from PIL import Image
30
+
31
+ from .pipeline_flux_infusenet import FluxInfuseNetPipeline
32
+ from .resampler import Resampler
33
+
34
+
35
+ def seed_everything(seed, deterministic=False):
36
+ """Set random seed.
37
+
38
+ Args:
39
+ seed (int): Seed to be used.
40
+ deterministic (bool): Whether to set the deterministic option for
41
+ CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
42
+ to True and `torch.backends.cudnn.benchmark` to False.
43
+ Default: False.
44
+ """
45
+ random.seed(seed)
46
+ np.random.seed(seed)
47
+ torch.manual_seed(seed)
48
+ torch.cuda.manual_seed(seed)
49
+ torch.cuda.manual_seed_all(seed)
50
+ os.environ['PYTHONHASHSEED'] = str(seed)
51
+ if deterministic:
52
+ torch.backends.cudnn.deterministic = True
53
+ torch.backends.cudnn.benchmark = False
54
+
55
+
56
+ # modified from https://github.com/instantX-research/InstantID/blob/main/pipeline_stable_diffusion_xl_instantid.py
57
+ def draw_kps(image_pil, kps, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]):
58
+ stickwidth = 4
59
+ limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])
60
+ kps = np.array(kps)
61
+
62
+ w, h = image_pil.size
63
+ out_img = np.zeros([h, w, 3])
64
+
65
+ for i in range(len(limbSeq)):
66
+ index = limbSeq[i]
67
+ color = color_list[index[0]]
68
+
69
+ x = kps[index][:, 0]
70
+ y = kps[index][:, 1]
71
+ length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
72
+ angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))
73
+ polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
74
+ out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)
75
+ out_img = (out_img * 0.6).astype(np.uint8)
76
+
77
+ for idx_kp, kp in enumerate(kps):
78
+ color = color_list[idx_kp]
79
+ x, y = kp
80
+ out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)
81
+
82
+ out_img_pil = Image.fromarray(out_img.astype(np.uint8))
83
+ return out_img_pil
84
+
85
+
86
+ def extract_arcface_bgr_embedding(in_image, landmark, arcface_model=None, in_settings=None):
87
+ kps = landmark
88
+ arc_face_image = face_align.norm_crop(in_image, landmark=np.array(kps), image_size=112)
89
+ arc_face_image = torch.from_numpy(arc_face_image).unsqueeze(0).permute(0,3,1,2) / 255.
90
+ arc_face_image = 2 * arc_face_image - 1
91
+ arc_face_image = arc_face_image.cuda().contiguous()
92
+ if arcface_model is None:
93
+ arcface_model = init_recognition_model('arcface', device='cuda')
94
+ face_emb = arcface_model(arc_face_image)[0] # [512], normalized
95
+ return face_emb
96
+
97
+
98
+ def resize_and_pad_image(source_img, target_img_size):
99
+ # Get original and target sizes
100
+ source_img_size = source_img.size
101
+ target_width, target_height = target_img_size
102
+
103
+ # Determine the new size based on the shorter side of target_img
104
+ if target_width <= target_height:
105
+ new_width = target_width
106
+ new_height = int(target_width * (source_img_size[1] / source_img_size[0]))
107
+ else:
108
+ new_height = target_height
109
+ new_width = int(target_height * (source_img_size[0] / source_img_size[1]))
110
+
111
+ # Resize the source image using LANCZOS interpolation for high quality
112
+ resized_source_img = source_img.resize((new_width, new_height), Image.LANCZOS)
113
+
114
+ # Compute padding to center resized image
115
+ pad_left = (target_width - new_width) // 2
116
+ pad_top = (target_height - new_height) // 2
117
+
118
+ # Create a new image with white background
119
+ padded_img = Image.new("RGB", target_img_size, (255, 255, 255))
120
+ padded_img.paste(resized_source_img, (pad_left, pad_top))
121
+
122
+ return padded_img
123
+
124
+
125
+ class InfUFluxPipeline:
126
+ def __init__(
127
+ self,
128
+ base_model_path,
129
+ infu_model_path,
130
+ insightface_root_path = './',
131
+ image_proj_num_tokens=8,
132
+ infu_flux_version='v1.0',
133
+ model_version='aes_stage2',
134
+ ):
135
+
136
+ self.infu_flux_version = infu_flux_version
137
+ self.model_version = model_version
138
+
139
+ # Load pipeline
140
+ try:
141
+ infusenet_path = os.path.join(os.path.dirname(infu_model_path), 'aes_stage2', 'InfuseNetModel')
142
+ self.infusenet_aes = FluxControlNetModel.from_pretrained(infusenet_path, torch_dtype=torch.bfloat16)
143
+ infusenet_path = os.path.join(os.path.dirname(infu_model_path), 'sim_stage1', 'InfuseNetModel')
144
+ self.infusenet_sim = FluxControlNetModel.from_pretrained(infusenet_path, torch_dtype=torch.bfloat16)
145
+ except:
146
+ print("No InfiniteYou model found. Downloading from HuggingFace `ByteDance/InfiniteYou` to `./models/InfiniteYou` ...")
147
+ snapshot_download(repo_id='ByteDance/InfiniteYou', local_dir='./models/InfiniteYou', local_dir_use_symlinks=False)
148
+ infu_model_path = os.path.join('./models/InfiniteYou', f'infu_flux_{infu_flux_version}', 'aes_stage2')
149
+ infusenet_path = os.path.join(infu_model_path, 'InfuseNetModel')
150
+ self.infusenet_aes = FluxControlNetModel.from_pretrained(infusenet_path, torch_dtype=torch.bfloat16)
151
+ infu_model_path = os.path.join('./models/InfiniteYou', f'infu_flux_{infu_flux_version}', 'sim_stage1')
152
+ infusenet_path = os.path.join(infu_model_path, 'InfuseNetModel')
153
+ self.infusenet_sim = FluxControlNetModel.from_pretrained(infusenet_path, torch_dtype=torch.bfloat16)
154
+ insightface_root_path = './models/InfiniteYou/supports/insightface'
155
+ self.infusenet_sim.cpu()
156
+ torch.cuda.empty_cache()
157
+ try:
158
+ pipe = FluxInfuseNetPipeline.from_pretrained(
159
+ base_model_path,
160
+ controlnet=self.infusenet_aes,
161
+ torch_dtype=torch.bfloat16,
162
+ )
163
+ except:
164
+ try:
165
+ pipe = FluxInfuseNetPipeline.from_single_file(
166
+ base_model_path,
167
+ controlnet=self.infusenet_aes,
168
+ torch_dtype=torch.bfloat16,
169
+ )
170
+ except Exception as e:
171
+ print(e)
172
+ print('\nIf you are using `black-forest-labs/FLUX.1-dev` and have not downloaded it into a local directory, '
173
+ 'please accept the agreement and obtain access at https://huggingface.co/black-forest-labs/FLUX.1-dev. '
174
+ 'Then, use `huggingface-cli login` and your access tokens at https://huggingface.co/settings/tokens to authenticate. '
175
+ 'After that, run the code again. If you have downloaded it, please use `base_model_path` to specify the correct path.')
176
+ print('\nIf you are using other models, please download them to a local directory and use `base_model_path` to specify the correct path.')
177
+ exit()
178
+ pipe.to('cuda', torch.bfloat16)
179
+ # CPU offload controlnet and T5 in advance
180
+ pipe.controlnet.cpu()
181
+ pipe.text_encoder_2.cpu()
182
+ torch.cuda.empty_cache()
183
+ pipe.text_encoder.to('cuda')
184
+ pipe.transformer.to('cuda')
185
+ pipe.vae.to('cuda')
186
+ # pipe.enable_model_cpu_offload()
187
+ self.pipe = pipe
188
+
189
+ # Load image proj model
190
+ num_tokens = image_proj_num_tokens
191
+ image_emb_dim = 512
192
+ image_proj_model = Resampler(
193
+ dim=1280,
194
+ depth=4,
195
+ dim_head=64,
196
+ heads=20,
197
+ num_queries=num_tokens,
198
+ embedding_dim=image_emb_dim,
199
+ output_dim=4096,
200
+ ff_mult=4,
201
+ )
202
+ image_proj_model_path = os.path.join(os.path.dirname(infu_model_path), 'aes_stage2', 'image_proj_model.bin')
203
+ ipm_state_dict = torch.load(image_proj_model_path, map_location="cpu")
204
+ image_proj_model.load_state_dict(ipm_state_dict['image_proj'])
205
+ del ipm_state_dict
206
+ self.image_proj_model_aes = copy.deepcopy(image_proj_model)
207
+ self.image_proj_model_aes.to('cuda', torch.bfloat16)
208
+ self.image_proj_model_aes.eval()
209
+
210
+ image_proj_model = Resampler(
211
+ dim=1280,
212
+ depth=4,
213
+ dim_head=64,
214
+ heads=20,
215
+ num_queries=num_tokens,
216
+ embedding_dim=image_emb_dim,
217
+ output_dim=4096,
218
+ ff_mult=4,
219
+ )
220
+ image_proj_model_path = os.path.join(os.path.dirname(infu_model_path), 'sim_stage1', 'image_proj_model.bin')
221
+ ipm_state_dict = torch.load(image_proj_model_path, map_location="cpu")
222
+ image_proj_model.load_state_dict(ipm_state_dict['image_proj'])
223
+ del ipm_state_dict
224
+ self.image_proj_model_sim = image_proj_model
225
+ self.image_proj_model_sim.to('cpu', dtype=torch.bfloat16)
226
+ self.image_proj_model_sim.eval()
227
+
228
+ self.image_proj_model = self.image_proj_model_aes
229
+
230
+ # Load face encoder
231
+ self.app_640 = FaceAnalysis(name='antelopev2',
232
+ root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
233
+ self.app_640.prepare(ctx_id=0, det_size=(640, 640))
234
+
235
+ self.app_320 = FaceAnalysis(name='antelopev2',
236
+ root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
237
+ self.app_320.prepare(ctx_id=0, det_size=(320, 320))
238
+
239
+ self.app_160 = FaceAnalysis(name='antelopev2',
240
+ root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
241
+ self.app_160.prepare(ctx_id=0, det_size=(160, 160))
242
+
243
+ self.arcface_model = init_recognition_model('arcface', device='cuda')
244
+
245
+ # Load LoRAs in advance
246
+ user_agent = {
247
+ "file_type": "attn_procs_weights",
248
+ "framework": "pytorch",
249
+ }
250
+ self.loras_state_dict = {}
251
+ self.loras_state_dict['realism'] = self.pipe._fetch_state_dict(os.path.join(os.path.dirname(insightface_root_path), 'optional_loras', 'flux_realism_lora.safetensors'),
252
+ weight_name=None, use_safetensors=True, local_files_only=None, cache_dir=None, force_download=False, proxies=None, token=None, revision=None, subfolder=None, user_agent=user_agent, allow_pickle=True)
253
+ self.loras_state_dict['anti_blur'] = self.pipe._fetch_state_dict(os.path.join(os.path.dirname(insightface_root_path), 'optional_loras', 'flux_anti_blur_lora.safetensors'),
254
+ weight_name=None, use_safetensors=True, local_files_only=None, cache_dir=None, force_download=False, proxies=None, token=None, revision=None, subfolder=None, user_agent=user_agent, allow_pickle=True)
255
+
256
+ def load_loras_state_dict(self, loras):
257
+ names, scales = [],[]
258
+ for lora_name, lora_scale in loras:
259
+ print(f"loading lora state dict of {lora_name}")
260
+ self.pipe.load_lora_weights(self.loras_state_dict[lora_name], adapter_name=lora_name)
261
+ names.append(lora_name)
262
+ scales.append(lora_scale)
263
+
264
+ if len(names) > 0:
265
+ self.pipe.set_adapters(names, adapter_weights=scales)
266
+
267
+ def load_loras(self, loras):
268
+ names, scales = [],[]
269
+ for lora_path, lora_name, lora_scale in loras:
270
+ if lora_path != "":
271
+ print(f"loading lora {lora_path}")
272
+ self.pipe.load_lora_weights(lora_path, adapter_name=lora_name)
273
+ names.append(lora_name)
274
+ scales.append(lora_scale)
275
+
276
+ if len(names) > 0:
277
+ self.pipe.set_adapters(names, adapter_weights=scales)
278
+
279
+ def _detect_face(self, id_image_cv2):
280
+ face_info = self.app_640.get(id_image_cv2)
281
+ if len(face_info) > 0:
282
+ return face_info
283
+
284
+ face_info = self.app_320.get(id_image_cv2)
285
+ if len(face_info) > 0:
286
+ return face_info
287
+
288
+ face_info = self.app_160.get(id_image_cv2)
289
+ return face_info
290
+
291
+ def __call__(
292
+ self,
293
+ id_image: Image.Image, # PIL.Image.Image (RGB)
294
+ prompt: str,
295
+ control_image: Optional[Image.Image] = None, # PIL.Image.Image (RGB) or None
296
+ width = 864,
297
+ height = 1152,
298
+ seed = 42,
299
+ guidance_scale = 3.5,
300
+ num_steps = 30,
301
+ infusenet_conditioning_scale = 1.0,
302
+ infusenet_guidance_start = 0.0,
303
+ infusenet_guidance_end = 1.0,
304
+ ):
305
+ # Extract ID embeddings
306
+ print('Preparing ID embeddings')
307
+ id_image_cv2 = cv2.cvtColor(np.array(id_image), cv2.COLOR_RGB2BGR)
308
+ face_info = self._detect_face(id_image_cv2)
309
+ if len(face_info) == 0:
310
+ raise ValueError('No face detected in the input ID image')
311
+
312
+ face_info = sorted(face_info, key=lambda x:(x['bbox'][2]-x['bbox'][0])*(x['bbox'][3]-x['bbox'][1]))[-1] # only use the maximum face
313
+ landmark = face_info['kps']
314
+ id_embed = extract_arcface_bgr_embedding(id_image_cv2, landmark, self.arcface_model)
315
+ id_embed = id_embed.clone().unsqueeze(0).float()
316
+ id_embed = id_embed.reshape([1, -1, 512])
317
+ id_embed = id_embed.to(device='cuda', dtype=torch.bfloat16)
318
+ self.image_proj_model.to('cuda', torch.bfloat16)
319
+ with torch.no_grad():
320
+ id_embed = self.image_proj_model(id_embed)
321
+ bs_embed, seq_len, _ = id_embed.shape
322
+ id_embed = id_embed.repeat(1, 1, 1)
323
+ id_embed = id_embed.view(bs_embed * 1, seq_len, -1)
324
+ id_embed = id_embed.to(device='cuda', dtype=torch.bfloat16)
325
+
326
+ # Load control image
327
+ print('Preparing the control image')
328
+ if control_image is not None:
329
+ control_image = control_image.convert("RGB")
330
+ control_image = resize_and_pad_image(control_image, (width, height))
331
+ face_info = self._detect_face(cv2.cvtColor(np.array(control_image), cv2.COLOR_RGB2BGR))
332
+ if len(face_info) == 0:
333
+ raise ValueError('No face detected in the control image')
334
+ face_info = sorted(face_info, key=lambda x:(x['bbox'][2]-x['bbox'][0])*(x['bbox'][3]-x['bbox'][1]))[-1] # only use the maximum face
335
+ control_image = draw_kps(control_image, face_info['kps'])
336
+ else:
337
+ out_img = np.zeros([height, width, 3])
338
+ control_image = Image.fromarray(out_img.astype(np.uint8))
339
+
340
+ # Perform inference
341
+ print('Generating image')
342
+ seed_everything(seed)
343
+ image = self.pipe(
344
+ prompt=prompt,
345
+ controlnet_prompt_embeds=id_embed,
346
+ control_image=control_image,
347
+ guidance_scale=guidance_scale,
348
+ num_inference_steps=num_steps,
349
+ controlnet_guidance_scale=1.0,
350
+ controlnet_conditioning_scale=infusenet_conditioning_scale,
351
+ control_guidance_start=infusenet_guidance_start,
352
+ control_guidance_end=infusenet_guidance_end,
353
+ height=height,
354
+ width=width,
355
+ ).images[0]
356
+
357
+ return image
pipelines/resampler.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
2
+
3
+ import math
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+
8
+
9
+ # FFN
10
+ def FeedForward(dim, mult=4):
11
+ inner_dim = int(dim * mult)
12
+ return nn.Sequential(
13
+ nn.LayerNorm(dim),
14
+ nn.Linear(dim, inner_dim, bias=False),
15
+ nn.GELU(),
16
+ nn.Linear(inner_dim, dim, bias=False),
17
+ )
18
+
19
+
20
+ def reshape_tensor(x, heads):
21
+ bs, length, width = x.shape
22
+ #(bs, length, width) --> (bs, length, n_heads, dim_per_head)
23
+ x = x.view(bs, length, heads, -1)
24
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
25
+ x = x.transpose(1, 2)
26
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
27
+ x = x.reshape(bs, heads, length, -1)
28
+ return x
29
+
30
+
31
+ class PerceiverAttention(nn.Module):
32
+ def __init__(self, *, dim, dim_head=64, heads=8):
33
+ super().__init__()
34
+ self.scale = dim_head**-0.5
35
+ self.dim_head = dim_head
36
+ self.heads = heads
37
+ inner_dim = dim_head * heads
38
+
39
+ self.norm1 = nn.LayerNorm(dim)
40
+ self.norm2 = nn.LayerNorm(dim)
41
+
42
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
43
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
44
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
45
+
46
+ def forward(self, x, latents):
47
+ """
48
+ Args:
49
+ x (torch.Tensor): image features
50
+ shape (b, n1, D)
51
+ latent (torch.Tensor): latent features
52
+ shape (b, n2, D)
53
+ """
54
+ x = self.norm1(x)
55
+ latents = self.norm2(latents)
56
+
57
+ b, l, _ = latents.shape
58
+
59
+ q = self.to_q(latents)
60
+ kv_input = torch.cat((x, latents), dim=-2)
61
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
62
+
63
+ q = reshape_tensor(q, self.heads)
64
+ k = reshape_tensor(k, self.heads)
65
+ v = reshape_tensor(v, self.heads)
66
+
67
+ # attention
68
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
69
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
70
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
71
+ out = weight @ v
72
+
73
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
74
+
75
+ return self.to_out(out)
76
+
77
+
78
+ class Resampler(nn.Module):
79
+ def __init__(
80
+ self,
81
+ dim=1024,
82
+ depth=8,
83
+ dim_head=64,
84
+ heads=16,
85
+ num_queries=8,
86
+ embedding_dim=768,
87
+ output_dim=1024,
88
+ ff_mult=4,
89
+ ):
90
+ super().__init__()
91
+
92
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
93
+
94
+ self.proj_in = nn.Linear(embedding_dim, dim)
95
+
96
+ self.proj_out = nn.Linear(dim, output_dim)
97
+ self.norm_out = nn.LayerNorm(output_dim)
98
+
99
+ self.layers = nn.ModuleList([])
100
+ for _ in range(depth):
101
+ self.layers.append(
102
+ nn.ModuleList(
103
+ [
104
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
105
+ FeedForward(dim=dim, mult=ff_mult),
106
+ ]
107
+ )
108
+ )
109
+
110
+ def forward(self, x):
111
+
112
+ latents = self.latents.repeat(x.size(0), 1, 1)
113
+
114
+ x = self.proj_in(x)
115
+
116
+ for attn, ff in self.layers:
117
+ latents = attn(x, latents) + latents
118
+ latents = ff(latents) + latents
119
+
120
+ latents = self.proj_out(latents)
121
+ return self.norm_out(latents)
requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==1.0.1
2
+ diffusers==0.31.0
3
+ facexlib==0.3.0
4
+ gradio==5.23.1
5
+ gradio_client==1.8.0
6
+ httpcore==1.0.7
7
+ httpx==0.28.1
8
+ huggingface-hub==0.28.1
9
+ insightface==0.7.3
10
+ numpy==1.26.4
11
+ onnxruntime==1.19.2
12
+ opencv-python==4.11.0.86
13
+ peft==0.14.0
14
+ pillow==10.4.0
15
+ pillow-avif-plugin==1.5.0
16
+ pillow-heif==0.21.0
17
+ sentencepiece==0.2.0
18
+ torch==2.2.2
19
+ torchvision==0.17.2
20
+ transformers==4.48.0