ObiWanMaxim commited on
Commit
5c40123
·
verified ·
1 Parent(s): b7f6f4d

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,9 @@ saved_model/**/* 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
 
 
 
 
 
 
 
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/comparative_results.jpg filter=lfs diff=lfs merge=lfs -text
37
+ assets/examples/man_pose.jpg filter=lfs diff=lfs merge=lfs -text
38
+ assets/examples/yangmi.jpg filter=lfs diff=lfs merge=lfs -text
39
+ assets/examples/yann-lecun_resize.jpg filter=lfs diff=lfs merge=lfs -text
40
+ assets/plug_and_play.jpg filter=lfs diff=lfs merge=lfs -text
41
+ assets/teaser.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 CHANGED
@@ -1,12 +1,167 @@
1
  ---
2
- title: Frameme
3
- emoji: 🏆
4
- colorFrom: red
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.23.1
8
  app_file: app.py
9
- pinned: false
 
10
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: frameme
 
 
 
 
 
3
  app_file: app.py
4
+ sdk: gradio
5
+ sdk_version: 5.21.0
6
  ---
7
+ <div align="center">
8
+
9
+ ## InfiniteYou: Flexible Photo Recrafting While Preserving Your Identity
10
+
11
+ [**Liming Jiang**](https://liming-jiang.com/)&nbsp;&nbsp;&nbsp;&nbsp;
12
+ [**Qing Yan**](https://scholar.google.com/citations?user=0TIYjPAAAAAJ)&nbsp;&nbsp;&nbsp;&nbsp;
13
+ [**Yumin Jia**](https://www.linkedin.com/in/yuminjia/)&nbsp;&nbsp;&nbsp;&nbsp;
14
+ [**Zichuan Liu**](https://scholar.google.com/citations?user=-H18WY8AAAAJ)&nbsp;&nbsp;&nbsp;&nbsp;
15
+ [**Hao Kang**](https://scholar.google.com/citations?user=VeTCSyEAAAAJ)&nbsp;&nbsp;&nbsp;&nbsp;
16
+ [**Xin Lu**](https://scholar.google.com/citations?user=mFC0wp8AAAAJ)<br />
17
+ ByteDance Intelligent Creation
18
+
19
+ <a href="https://bytedance.github.io/InfiniteYou"><img src="https://img.shields.io/static/v1?label=Project&message=Page&color=blue&logo=github-pages"></a> &ensp;
20
+ <a href="https://arxiv.org/abs/2503.16418"><img src="https://img.shields.io/static/v1?label=Arxiv&message=InfiniteYou&color=darkred&logo=arxiv"></a> &ensp;
21
+ <a href="https://arxiv.org/pdf/2503.16418"><img src="https://img.shields.io/static/v1?label=%F0%9F%93%96%20Paper&message=PDF&color=green"></a> &ensp;
22
+ <a href="https://huggingface.co/spaces/ByteDance/InfiniteYou-FLUX"><img src="https://img.shields.io/static/v1?label=%F0%9F%A4%97%20Hugging%20Face&message=Demo&color=orange"></a> &ensp;
23
+
24
+ </div>
25
+
26
+ ![teaser](./assets/teaser.jpg)
27
+
28
+ > **Abstract:** *Achieving flexible and high-fidelity identity-preserved image generation remains formidable, particularly with advanced Diffusion Transformers (DiTs) like FLUX. We introduce **InfiniteYou (InfU)**, one of the earliest robust frameworks leveraging DiTs for this task. InfU addresses significant issues of existing methods, such as insufficient identity similarity, poor text-image alignment, and low generation quality and aesthetics. Central to InfU is InfuseNet, a component that injects identity features into the DiT base model via residual connections, enhancing identity similarity while maintaining generation capabilities. A multi-stage training strategy, including pretraining and supervised fine-tuning (SFT) with synthetic single-person-multiple-sample (SPMS) data, further improves text-image alignment, ameliorates image quality, and alleviates face copy-pasting. Extensive experiments demonstrate that InfU achieves state-of-the-art performance, surpassing existing baselines. In addition, the plug-and-play design of InfU ensures compatibility with various existing methods, offering a valuable contribution to the broader community.*
29
+
30
+
31
+ ## 🔥 News
32
+
33
+ - [03/2025] 🔥 The [code](https://github.com/bytedance/InfiniteYou), [model](https://huggingface.co/ByteDance/InfiniteYou), and [demo](https://huggingface.co/spaces/ByteDance/InfiniteYou-FLUX) of InfiniteYou-FLUX v1.0 are released.
34
+
35
+ - [03/2025] 🔥 The [project page](https://bytedance.github.io/InfiniteYou) of InfiniteYou is created.
36
+
37
+ - [03/2025] 🔥 The [paper](https://arxiv.org/abs/2503.16418) of InfiniteYou is released on arXiv.
38
+
39
+
40
+ ## 💡 Important Usage Tips
41
+
42
+ - We released two model variants of InfiniteYou-FLUX v1.0: [aes_stage2](https://huggingface.co/ByteDance/InfiniteYou/tree/main/infu_flux_v1.0/aes_stage2) and [sim_stage1](https://huggingface.co/ByteDance/InfiniteYou/tree/main/infu_flux_v1.0/sim_stage1). The `aes_stage2` is our model after SFT, which is used by default for better text-image alignment and aesthetics. For higher ID similarity, please try `sim_stage1` (using `--model_version` to switch). More details can be found in our [paper](https://arxiv.org/abs/2503.16418).
43
+
44
+ - To better fit specific personal needs, we find that two arguments are highly useful to adjust: <br />`--infusenet_conditioning_scale` (default: `1.0`) and `--infusenet_guidance_start` (default: `0.0`). Usually, you may NOT need to adjust them. If necessary, start by trying a slightly larger <br />`--infusenet_guidance_start` (*e.g.*, `0.1`) only (especially helpful for `sim_stage1`). If still not satisfactory, then try a slightly smaller `--infusenet_conditioning_scale` (*e.g.*, `0.9`).
45
+
46
+ - We also provided two LoRAs ([Realism](https://civitai.com/models/631986?modelVersionId=706528) and [Anti-blur](https://civitai.com/models/675581/anti-blur-flux-lora)) to enable additional usage flexibility. If needed, try `Realism` only first. They are *entirely optional*, which are examples to try but are NOT used in our paper.
47
+
48
+ - If the generated gender does not align with your preferences, try adding specific words in the text prompt, such as 'a man', 'a woman', *etc*. We encourage users to use inclusive and respectful language.
49
+
50
+
51
+ ## :european_castle: Model Zoo
52
+
53
+ | InfiniteYou Version | Model Version | Base Model Trained with | Description |
54
+ | :---: | :---: | :---: | :---: |
55
+ | [InfiniteYou-FLUX v1.0](https://huggingface.co/ByteDance/InfiniteYou) | [aes_stage2](https://huggingface.co/ByteDance/InfiniteYou/tree/main/infu_flux_v1.0/aes_stage2) | [FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) | Stage-2 model after SFT. Better text-image alignment and aesthetics. |
56
+ | [InfiniteYou-FLUX v1.0](https://huggingface.co/ByteDance/InfiniteYou) | [sim_stage1](https://huggingface.co/ByteDance/InfiniteYou/tree/main/infu_flux_v1.0/sim_stage1) | [FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) | Stage-1 model before SFT. Higher identity similarity. |
57
+
58
+
59
+ ## 🔧 Requirements and Installation
60
+
61
+ ### Dependencies
62
+
63
+ Simply run this one-line command to install (feel free to create a `python3` virtual environment before you run):
64
+
65
+ ```bash
66
+ pip install -r requirements.txt
67
+ ```
68
+
69
+ ### Memory Requirements
70
+
71
+ Please note that the current full-performance `bf16` model inference requires a **peak VRAM** of around **43GB**. **We are trying to reduce memory usage and will post an update soon.** Community contributions are welcome.
72
+
73
+ If you want to use our models ASAP but do not have a GPU with sufficient VRAM, please follow [Diffusers memory reduction tips](https://huggingface.co/docs/diffusers/en/optimization/memory) first, where some offloading strategies may be helpful.
74
+
75
+
76
+ ## ⚡️ Quick Inference
77
+
78
+ ### Local Inference Script
79
+
80
+ ```bash
81
+ python test.py --id_image ./assets/examples/yann-lecun_resize.jpg --prompt "A man, portrait, cinematic" --out_results_dir ./results
82
+ ```
83
+
84
+ <details>
85
+ <summary style='font-size:20px'><b><i>Explanation of all the arguments (click to expand!)</i></b></summary>
86
+
87
+ - Input and output:
88
+ - `--id_image (str)`: The path to the input identity (ID) image. Default: `./assets/examples/yann-lecun_resize.jpg`.
89
+ - `--prompt (str)`: The text prompt for image generation. Default: `A man, portrait, cinematic`.
90
+ - `--out_results_dir (str)`: The path to the output directory to save the generated results. Default: `./results`.
91
+ - `--control_image (str or None)`: The path to the control image \[*optional*\] to extract five facical keypoints to control the generation. Default: `None`.
92
+ - `--base_model_path (str)`: The huggingface or local path to the base model. Default: `black-forest-labs/FLUX.1-dev`.
93
+ - `--model_dir (str)`: The path to the InfiniteYou model directory. Default: `ByteDance/InfiniteYou`.
94
+ - Version control:
95
+ - `--infu_flux_version (str)`: InfiniteYou-FLUX version: currently only `v1.0` is supported. Default: `v1.0`.
96
+ - `--model_version (str)`: The model variant to use: `aes_stage2` | `sim_stage1`. Default: `aes_stage2`.
97
+ - General inference arguments:
98
+ - `--cuda_device (int)`: The cuda device ID to use. Default: `0`.
99
+ - `--seed (int)`: The seed for reproducibility (0 for random). Default: `0`.
100
+ - `--guideance_scale (float)`: The guidance scale for the diffusion process. Default: `3.5`.
101
+ - `--num_steps (int)`: The number of inference steps. Default: `30`.
102
+ - InfiniteYou-specific arguments:
103
+ - `--infusenet_conditioning_scale (float)`: The scale for the InfuseNet conditioning. Default: `1.0`.
104
+ - `--infusenet_guidance_start (float)`: The start point for the InfuseNet guidance injection. Default: `0.0`.
105
+ - `--infusenet_guidance_end (float)`: The end point for the InfuseNet guidance injection. Default: `1.0`.
106
+ - Optional LoRAs:
107
+ - `--enable_realism_lora (store_true)`: Whether to enable the Realism LoRA. Default: `False`.
108
+ - `--enable_anti_blur_lora (store_true)`: Whether to enable the Anti-blur LoRA. Default: `False`.
109
+
110
+ </details>
111
+
112
+
113
+ ### Local Gradio Demo
114
+
115
+ ```bash
116
+ python app.py
117
+ ```
118
+
119
+ ### Online Hugging Face Demo
120
+
121
+ We appreciate the GPU grant from the Hugging Face team.
122
+ You can also try our [InfiniteYou-FLUX Hugging Face demo](https://huggingface.co/spaces/ByteDance/InfiniteYou-FLUX) online.
123
+
124
+
125
+ ## 🆚 Comparison with State-of-the-Art Relevant Methods
126
+
127
+ ![comparative_results](./assets/comparative_results.jpg)
128
+
129
+ Qualitative comparison results of InfU with the state-of-the-art baselines, FLUX.1-dev IP-Adapter and PuLID-FLUX. The identity similarity and text-image alignment of the results generated by FLUX.1-dev IP-Adapter (IPA) are inadequate. PuLID-FLUX generates images with decent identity similarity. However, it suffers from poor text-image alignment (Columns 1, 2, 4), and the image quality (e.g., bad hands in Column 5) and aesthetic appeal are degraded. In addition, the face copy-paste issue of PuLID-FLUX is evident (Column 5). In comparison, the proposed InfU outperforms the baselines across all dimensions.
130
+
131
+
132
+ ## ⚙️ Plug-and-Play Property with Off-the-Shelf Popular Approaches
133
+
134
+ ![plug_and_play](./assets/plug_and_play.jpg)
135
+
136
+ InfU features a desirable plug-and-play design, compatible with many existing methods. It naturally supports base model replacement with any variants of FLUX.1-dev, such as FLUX.1-schnell for more efficient generation (e.g., in 4 steps). The compatibility with ControlNets and LoRAs provides more controllability and flexibility for customized tasks. Notably, the compatibility with OminiControl extends our potential for multi-concept personalization, such as interacted identity (ID) and object personalized generation. InfU is also compatible with IP-Adapter (IPA) for stylization of personalized images, producing decent results when injecting style references via IPA. Our plug-and-play feature may extend to even more approaches, providing valuable contributions to the broader community.
137
+
138
+
139
+ ## 📜 Disclaimer and Licenses
140
+
141
+ Most images used in this repository and related demos are sourced from consented subjects, with a few taken from public domains or generated by models. These pictures are intended solely to showcase the capabilities of our research. If you have any concerns, please contact us, and we will promptly remove any inappropriate content.
142
+
143
+ The use of the released code, model, and demo must strictly adhere to the respective licenses. Our code is released under the [Apache 2.0 License](./LICENSE), and our model is released under the [Creative Commons Attribution-NonCommercial 4.0 International Public License](https://huggingface.co/ByteDance/InfiniteYou/blob/main/LICENSE) 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.
144
+
145
+ This research aims to positively impact the field of Generative AI. Users are granted the freedom to create images using this tool, but they must comply with local laws and use it responsibly. The developers do not assume any responsibility for potential misuse by users.
146
+
147
+
148
+ ## 🤗 Acknowledgments
149
+
150
+ We sincerely acknowledge the insightful discussions from Stathi Fotiadis, Min Jin Chong, Xiao Yang, Tiancheng Zhi, Jing Liu, and Xiaohui Shen. We genuinely appreciate the help from Jincheng Liang and Lu Guo with our user study and qualitative evaluation.
151
+
152
+
153
+ ## 📖 Citation
154
+
155
+ If you find InfiniteYou useful for your research or applications, please cite our paper:
156
+
157
+ ```bibtex
158
+ @article{jiang2025infiniteyou,
159
+ title={{InfiniteYou}: Flexible Photo Recrafting While Preserving Your Identity},
160
+ author={Jiang, Liming and Yan, Qing and Jia, Yumin and Liu, Zichuan and Kang, Hao and Lu, Xin},
161
+ journal={arXiv preprint},
162
+ volume={arXiv:2503.16418},
163
+ year={2025}
164
+ }
165
+ ```
166
 
167
+ We also appreciate it if you could give a star :star: to this repository. Thanks a lot!
app.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 gradio as gr
16
+ import pillow_avif
17
+ import torch
18
+ from huggingface_hub import snapshot_download
19
+ from pillow_heif import register_heif_opener
20
+
21
+ from pipelines.pipeline_infu_flux import InfUFluxPipeline
22
+
23
+
24
+ # Register HEIF support for Pillow
25
+ register_heif_opener()
26
+
27
+ class ModelVersion:
28
+ STAGE_1 = "sim_stage1"
29
+ STAGE_2 = "aes_stage2"
30
+
31
+ DEFAULT_VERSION = STAGE_2
32
+
33
+ ENABLE_ANTI_BLUR_DEFAULT = False
34
+ ENABLE_REALISM_DEFAULT = False
35
+
36
+ pipeline = None
37
+ loaded_pipeline_config = {
38
+ "model_version": "aes_stage2",
39
+ "enable_realism": False,
40
+ "enable_anti_blur": False,
41
+ }
42
+
43
+
44
+ def download_models():
45
+ snapshot_download(repo_id='ByteDance/InfiniteYou', local_dir='./models/InfiniteYou', local_dir_use_symlinks=False)
46
+ try:
47
+ snapshot_download(repo_id='black-forest-labs/FLUX.1-dev', local_dir='./models/FLUX.1-dev', local_dir_use_symlinks=False)
48
+ except Exception as e:
49
+ print(e)
50
+ print('\nYou are downloading `black-forest-labs/FLUX.1-dev` to `./models/FLUX.1-dev` but failed. '
51
+ 'Please accept the agreement and obtain access at https://huggingface.co/black-forest-labs/FLUX.1-dev. '
52
+ 'Then, use `huggingface-cli login` and your access tokens at https://huggingface.co/settings/tokens to authenticate. '
53
+ 'After that, run the code again.')
54
+ print('\nYou can also download it manually from HuggingFace and put it in `./models/InfiniteYou`, '
55
+ 'or you can modify `base_model_path` in `app.py` to specify the correct path.')
56
+ exit()
57
+
58
+
59
+ def prepare_pipeline(model_version, enable_realism, enable_anti_blur):
60
+ global pipeline
61
+
62
+ if (
63
+ pipeline
64
+ and loaded_pipeline_config["enable_realism"] == enable_realism
65
+ and loaded_pipeline_config["enable_anti_blur"] == enable_anti_blur
66
+ and model_version == loaded_pipeline_config["model_version"]
67
+ ):
68
+ return
69
+
70
+ loaded_pipeline_config["enable_realism"] = enable_realism
71
+ loaded_pipeline_config["enable_anti_blur"] = enable_anti_blur
72
+ loaded_pipeline_config["model_version"] = model_version
73
+
74
+ if pipeline is None or pipeline.model_version != model_version:
75
+ del pipeline
76
+
77
+ model_path = f'./models/InfiniteYou/infu_flux_v1.0/{model_version}'
78
+ print(f'loading model from {model_path}')
79
+
80
+ pipeline = InfUFluxPipeline(
81
+ base_model_path='./models/FLUX.1-dev',
82
+ infu_model_path=model_path,
83
+ insightface_root_path='./models/InfiniteYou/supports/insightface',
84
+ image_proj_num_tokens=8,
85
+ infu_flux_version='v1.0',
86
+ model_version=model_version,
87
+ )
88
+
89
+ pipeline.pipe.delete_adapters(['realism', 'anti_blur'])
90
+ loras = []
91
+ if enable_realism:
92
+ loras.append(['./models/InfiniteYou/supports/optional_loras/flux_realism_lora.safetensors', 'realism', 1.0])
93
+ if enable_anti_blur:
94
+ loras.append(['./models/InfiniteYou/supports/optional_loras/flux_anti_blur_lora.safetensors', 'anti_blur', 1.0])
95
+ pipeline.load_loras(loras)
96
+
97
+
98
+ def generate_image(
99
+ input_image,
100
+ control_image,
101
+ prompt,
102
+ seed,
103
+ width,
104
+ height,
105
+ guidance_scale,
106
+ num_steps,
107
+ infusenet_conditioning_scale,
108
+ infusenet_guidance_start,
109
+ infusenet_guidance_end,
110
+ enable_realism,
111
+ enable_anti_blur,
112
+ model_version
113
+ ):
114
+ global pipeline
115
+
116
+ prepare_pipeline(model_version=model_version, enable_realism=enable_realism, enable_anti_blur=enable_anti_blur)
117
+
118
+ if seed == 0:
119
+ seed = torch.seed() & 0xFFFFFFFF
120
+
121
+ try:
122
+ image = pipeline(
123
+ id_image=input_image,
124
+ prompt=prompt,
125
+ control_image=control_image,
126
+ seed=seed,
127
+ width=width,
128
+ height=height,
129
+ guidance_scale=guidance_scale,
130
+ num_steps=num_steps,
131
+ infusenet_conditioning_scale=infusenet_conditioning_scale,
132
+ infusenet_guidance_start=infusenet_guidance_start,
133
+ infusenet_guidance_end=infusenet_guidance_end,
134
+ )
135
+ except Exception as e:
136
+ print(e)
137
+ gr.Error(f"An error occurred: {e}")
138
+ return gr.update()
139
+
140
+ return gr.update(value = image, label=f"Generated image, seed = {seed}")
141
+
142
+
143
+ def generate_examples(id_image, control_image, prompt_text, seed, enable_realism, enable_anti_blur, model_version):
144
+ return generate_image(id_image, control_image, prompt_text, seed, 864, 1152, 3.5, 30, 1.0, 0.0, 1.0, enable_realism, enable_anti_blur, model_version)
145
+
146
+
147
+ sample_list = [
148
+ ['./assets/examples/yann-lecun_resize.jpg', None, 'A sophisticated gentleman exuding confidence. He is dressed in a 1990s brown plaid jacket with a high collar, paired with a dark grey turtleneck. His trousers are tailored and charcoal in color, complemented by a sleek leather belt. The background showcases an elegant library with bookshelves, a marble fireplace, and warm lighting, creating a refined and cozy atmosphere. His relaxed posture and casual hand-in-pocket stance add to his composed and stylish demeanor', 666, False, False, 'aes_stage2'],
149
+ ['./assets/examples/yann-lecun_resize.jpg', './assets/examples/man_pose.jpg', 'A man, portrait, cinematic', 42, True, False, 'aes_stage2'],
150
+ ['./assets/examples/yann-lecun_resize.jpg', './assets/examples/yann-lecun_resize.jpg', 'A man, portrait, cinematic', 12345, False, False, 'sim_stage1'],
151
+ ['./assets/examples/yangmi.jpg', None, 'A woman, portrait, cinematic', 1621695706, False, False, 'sim_stage1'],
152
+ ['./assets/examples/yangmi.jpg', None, 'A young woman holding a sign with the text "InfiniteYou", "Infinite" in black and "You" in red, pure background', 3724009366, False, False, 'aes_stage2'],
153
+ ['./assets/examples/yangmi.jpg', None, 'A photo of an elegant Javanese bride in traditional attire, with long hair styled into intricate a braid made of many fresh flowers, wearing a delicate headdress made from sequins and beads. She\'s holding flowers, light smiling at the camera, against a backdrop adorned with orchid blooms. The scene captures her grace as she stands amidst soft pastel colors, adding to its dreamy atmosphere', 42, True, False, 'aes_stage2'],
154
+ ['./assets/examples/yangmi.jpg', None, 'A photo of an elegant Javanese bride in traditional attire, with long hair styled into intricate a braid made of many fresh flowers, wearing a delicate headdress made from sequins and beads. She\'s holding flowers, light smiling at the camera, against a backdrop adorned with orchid blooms. The scene captures her grace as she stands amidst soft pastel colors, adding to its dreamy atmosphere', 42, False, False, 'sim_stage1'],
155
+ ]
156
+
157
+ with gr.Blocks() as demo:
158
+ session_state = gr.State({})
159
+ default_model_version = "v1.0"
160
+
161
+ gr.Markdown("""
162
+ <div style="text-align: center; max-width: 900px; margin: 0 auto;">
163
+ <h1 style="font-size: 1.5rem; font-weight: 700; display: block;">InfiniteYou-FLUX</h1>
164
+ <h2 style="font-size: 1.2rem; font-weight: 300; margin-bottom: 1rem; display: block;">Official Gradio Demo for <a href="https://arxiv.org/abs/2503.xxxxx">InfiniteYou: Flexible Photo Recrafting While Preserving Your Identity</a></h2>
165
+ <a href="https://bytedance.github.io/InfiniteYou">[Project Page]</a>&ensp;
166
+ <a href="https://arxiv.org/abs/2503.xxxxx">[Paper]</a>&ensp;
167
+ <a href="https://github.com/bytedance/InfiniteYou">[Code]</a>&ensp;
168
+ <a href="https://huggingface.co/ByteDance/InfiniteYou">[Model]</a>
169
+ </div>
170
+
171
+ ### 💡 How to Use This Demo:
172
+ 1. **Upload an identity (ID) image containing a human face.** For images with multiple faces, only the largest face will be detected. The face should ideally be clear and large enough, without significant occlusions or blur.
173
+ 2. **Enter the text prompt to describe the generated image and select the model version.** Please refer to **important usage tips** under the Generated Image field.
174
+ 3. *[Optional] Upload a control image containing a human face.* Only five facial keypoints will be extracted to control the generation. If not provided, we use a black control image, indicating no control.
175
+ 4. *[Optional] Adjust advanced hyperparameters or apply optional LoRAs to meet personal needs.* Please refer to **important usage tips** under the Generated Image field.
176
+ 5. **Click the "Generate" button to generate an image.** Enjoy!
177
+ """)
178
+
179
+ with gr.Row():
180
+ with gr.Column(scale=3):
181
+ with gr.Row():
182
+ ui_id_image = gr.Image(label="Identity Image", type="pil", scale=3, height=370, min_width=100)
183
+
184
+ with gr.Column(scale=2, min_width=100):
185
+ ui_control_image = gr.Image(label="Control Image [Optional]", type="pil", height=370, min_width=100)
186
+
187
+ ui_prompt_text = gr.Textbox(label="Prompt", value="Portrait, 4K, high quality, cinematic")
188
+ ui_model_version = gr.Dropdown(
189
+ label="Model Version",
190
+ choices=[ModelVersion.STAGE_1, ModelVersion.STAGE_2],
191
+ value=ModelVersion.DEFAULT_VERSION,
192
+ )
193
+
194
+ ui_btn_generate = gr.Button("Generate")
195
+ with gr.Accordion("Advanced", open=False):
196
+ with gr.Row():
197
+ ui_num_steps = gr.Number(label="num steps", value=30)
198
+ ui_seed = gr.Number(label="seed (0 for random)", value=0)
199
+ with gr.Row():
200
+ ui_width = gr.Number(label="width", value=864)
201
+ ui_height = gr.Number(label="height", value=1152)
202
+ ui_guidance_scale = gr.Number(label="guidance scale", value=3.5, step=0.5)
203
+ ui_infusenet_conditioning_scale = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="infusenet conditioning scale")
204
+ with gr.Row():
205
+ ui_infusenet_guidance_start = gr.Slider(minimum=0.0, maximum=1.0, value=0.0, step=0.05, label="infusenet guidance start")
206
+ ui_infusenet_guidance_end = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="infusenet guidance end")
207
+
208
+ with gr.Accordion("LoRAs [Optional]", open=True):
209
+ with gr.Row():
210
+ ui_enable_realism = gr.Checkbox(label="Enable realism LoRA", value=ENABLE_REALISM_DEFAULT)
211
+ ui_enable_anti_blur = gr.Checkbox(label="Enable anti-blur LoRA", value=ENABLE_ANTI_BLUR_DEFAULT)
212
+
213
+ with gr.Column(scale=2):
214
+ image_output = gr.Image(label="Generated Image", interactive=False, height=550, format='png')
215
+ gr.Markdown(
216
+ """
217
+ ### ❗️ Important Usage Tips:
218
+ - **Model Version**: `aes_stage2` is used by default for better text-image alignment and aesthetics. For higher ID similarity, please try `sim_stage1`.
219
+ - **Useful Hyperparameters**: Usually, there is NO need to adjust too much. If necessary, try a slightly larger `--infusenet_guidance_start` (*e.g.*, `0.1`) only (especially helpful for `sim_stage1`). If still not satisfactory, then try a slightly smaller `--infusenet_conditioning_scale` (*e.g.*, `0.9`).
220
+ - **Optional LoRAs**: `realism` and `anti-blur`. To enable them, please check the corresponding boxes. They are optional and were NOT used in our paper.
221
+ - **Gender Prompt**: If the generated gender is not preferred, add specific words in the text prompt, such as 'a man', 'a woman', *etc*. We encourage using inclusive and respectful language.
222
+ """
223
+ )
224
+
225
+ gr.Examples(
226
+ sample_list,
227
+ inputs=[ui_id_image, ui_control_image, ui_prompt_text, ui_seed, ui_enable_realism, ui_enable_anti_blur, ui_model_version],
228
+ outputs=[image_output],
229
+ fn=generate_examples,
230
+ cache_examples=True,
231
+ )
232
+
233
+ ui_btn_generate.click(
234
+ generate_image,
235
+ inputs=[
236
+ ui_id_image,
237
+ ui_control_image,
238
+ ui_prompt_text,
239
+ ui_seed,
240
+ ui_width,
241
+ ui_height,
242
+ ui_guidance_scale,
243
+ ui_num_steps,
244
+ ui_infusenet_conditioning_scale,
245
+ ui_infusenet_guidance_start,
246
+ ui_infusenet_guidance_end,
247
+ ui_enable_realism,
248
+ ui_enable_anti_blur,
249
+ ui_model_version
250
+ ],
251
+ outputs=[image_output],
252
+ concurrency_id="gpu"
253
+ )
254
+
255
+ with gr.Accordion("Local Gradio Demo for Developers", open=False):
256
+ gr.Markdown(
257
+ 'Please refer to our GitHub repository to [run the InfiniteYou-FLUX gradio demo locally](https://github.com/bytedance/InfiniteYou#local-gradio-demo).'
258
+ )
259
+
260
+ gr.Markdown(
261
+ """
262
+ ---
263
+ ### 📜 Disclaimer and Licenses
264
+ Some images in this demo are from public domains or generated by 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.
265
+
266
+ The use of the released code, model, and demo must strictly adhere to the respective licenses. Our code is released under the Apache 2.0 License, and our model is released under the Creative Commons Attribution-NonCommercial 4.0 International Public License 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, etc., must follow their original licenses and be used only for academic research purposes.
267
+
268
+ This research aims to positively impact the Generative AI field. Users are granted freedom to create images using this tool, but they must comply with local laws and use it responsibly. The developers do not assume any responsibility for potential misuse.
269
+
270
+ ### 📖 Citation
271
+
272
+ If you find InfiniteYou useful for your research or applications, please cite our paper:
273
+
274
+ ```bibtex
275
+ @article{jiang2025infiniteyou,
276
+ title={{InfiniteYou}: Flexible Photo Recrafting While Preserving Your Identity},
277
+ author={Jiang, Liming and Yan, Qing and Jia, Yumin and Liu, Zichuan and Kang, Hao and Lu, Xin},
278
+ journal={arXiv preprint},
279
+ volume={arXiv:2503.xxxxx},
280
+ year={2025}
281
+ }
282
+ ```
283
+
284
+ We also appreciate it if you could give a star ⭐ to our [Github repository](https://github.com/bytedance/InfiniteYou). Thanks a lot!
285
+ """
286
+ )
287
+
288
+ download_models()
289
+
290
+ prepare_pipeline(model_version=ModelVersion.DEFAULT_VERSION, enable_realism=ENABLE_REALISM_DEFAULT, enable_anti_blur=ENABLE_ANTI_BLUR_DEFAULT)
291
+
292
+ demo.queue()
293
+ demo.launch(server_name='0.0.0.0',share=True) # IPv4
294
+ # demo.launch(server_name='[::]') # IPv6
assets/comparative_results.jpg ADDED

Git LFS Details

  • SHA256: c612ecafa42cc46459d1bd910582e88b7d633ce5fc12db31cc9db00b2900672d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.13 MB
assets/examples/man_pose.jpg ADDED

Git LFS Details

  • SHA256: 2a5e2f776e134213441e81fe79c03947b30198a7f36af24be9e5d6d67b72474c
  • Pointer size: 131 Bytes
  • Size of remote file: 119 kB
assets/examples/yangmi.jpg ADDED

Git LFS Details

  • SHA256: 254eb7fcf21c77fb6a6e9670d51b59725ddc58d9034290fecf381cd586fa69ef
  • Pointer size: 131 Bytes
  • Size of remote file: 222 kB
assets/examples/yann-lecun_resize.jpg ADDED

Git LFS Details

  • SHA256: 2a5e2f776e134213441e81fe79c03947b30198a7f36af24be9e5d6d67b72474c
  • Pointer size: 131 Bytes
  • Size of remote file: 119 kB
assets/plug_and_play.jpg ADDED

Git LFS Details

  • SHA256: 7905845747f74229969a55fe15be2a4db1cb88692b898f7c7ac1cffba3fc8148
  • Pointer size: 131 Bytes
  • Size of remote file: 832 kB
assets/teaser.jpg ADDED

Git LFS Details

  • SHA256: 08543db3b4797a616c8b1ba778916ce440e1475e2653cc5b89ae5d72654cd91e
  • Pointer size: 131 Bytes
  • Size of remote file: 606 kB
pipelines/__init__.py ADDED
File without changes
pipelines/pipeline_flux_infusenet.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ dtype = self.transformer.dtype
306
+
307
+ lora_scale = (
308
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
309
+ )
310
+ (
311
+ prompt_embeds,
312
+ pooled_prompt_embeds,
313
+ text_ids,
314
+ ) = self.encode_prompt(
315
+ prompt=prompt,
316
+ prompt_2=prompt_2,
317
+ prompt_embeds=prompt_embeds,
318
+ pooled_prompt_embeds=pooled_prompt_embeds,
319
+ device=device,
320
+ num_images_per_prompt=num_images_per_prompt,
321
+ max_sequence_length=max_sequence_length,
322
+ lora_scale=lora_scale,
323
+ )
324
+ if negative_prompt is not None or (negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None):
325
+ (
326
+ negative_prompt_embeds,
327
+ negative_pooled_prompt_embeds,
328
+ negative_text_ids,
329
+ ) = self.encode_prompt(
330
+ prompt=negative_prompt,
331
+ prompt_2=negative_prompt_2,
332
+ prompt_embeds=negative_prompt_embeds,
333
+ pooled_prompt_embeds=negative_pooled_prompt_embeds,
334
+ device=device,
335
+ num_images_per_prompt=num_images_per_prompt,
336
+ max_sequence_length=max_sequence_length,
337
+ lora_scale=lora_scale,
338
+ )
339
+
340
+ if controlnet_prompt_embeds is None:
341
+ controlnet_prompt_embeds = prompt_embeds
342
+ (
343
+ controlnet_prompt_embeds,
344
+ pooled_prompt_embeds,
345
+ controlnet_text_ids,
346
+ ) = self.encode_prompt(
347
+ prompt=prompt,
348
+ prompt_2=prompt_2,
349
+ prompt_embeds=controlnet_prompt_embeds,
350
+ pooled_prompt_embeds=pooled_prompt_embeds,
351
+ device=device,
352
+ num_images_per_prompt=num_images_per_prompt,
353
+ max_sequence_length=max_sequence_length,
354
+ lora_scale=lora_scale,
355
+ )
356
+
357
+ # 3. Prepare control image
358
+ num_channels_latents = self.transformer.config.in_channels // 4
359
+ if isinstance(self.controlnet, FluxControlNetModel):
360
+ control_image = self.prepare_image(
361
+ image=control_image,
362
+ width=width,
363
+ height=height,
364
+ batch_size=batch_size * num_images_per_prompt,
365
+ num_images_per_prompt=num_images_per_prompt,
366
+ device=device,
367
+ dtype=self.vae.dtype,
368
+ )
369
+ height, width = control_image.shape[-2:]
370
+
371
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
372
+ controlnet_blocks_repeat = False if self.controlnet.input_hint_block is None else True
373
+ if self.controlnet.input_hint_block is None:
374
+ # vae encode
375
+ control_image = self.vae.encode(control_image).latent_dist.sample()
376
+ control_image = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
377
+
378
+ # pack
379
+ height_control_image, width_control_image = control_image.shape[2:]
380
+ control_image = self._pack_latents(
381
+ control_image,
382
+ batch_size * num_images_per_prompt,
383
+ num_channels_latents,
384
+ height_control_image,
385
+ width_control_image,
386
+ )
387
+
388
+ # Here we ensure that `control_mode` has the same length as the control_image.
389
+ if control_mode is not None:
390
+ if not isinstance(control_mode, int):
391
+ raise ValueError(" For `FluxControlNet`, `control_mode` should be an `int` or `None`")
392
+ control_mode = torch.tensor(control_mode).to(device, dtype=torch.long)
393
+ control_mode = control_mode.view(-1, 1).expand(control_image.shape[0], 1)
394
+
395
+ elif isinstance(self.controlnet, FluxMultiControlNetModel):
396
+ control_images = []
397
+ # xlab controlnet has a input_hint_block and instantx controlnet does not
398
+ controlnet_blocks_repeat = False if self.controlnet.nets[0].input_hint_block is None else True
399
+ for i, control_image_ in enumerate(control_image):
400
+ control_image_ = self.prepare_image(
401
+ image=control_image_,
402
+ width=width,
403
+ height=height,
404
+ batch_size=batch_size * num_images_per_prompt,
405
+ num_images_per_prompt=num_images_per_prompt,
406
+ device=device,
407
+ dtype=self.vae.dtype,
408
+ )
409
+ height, width = control_image_.shape[-2:]
410
+
411
+ if self.controlnet.nets[0].input_hint_block is None:
412
+ # vae encode
413
+ control_image_ = self.vae.encode(control_image_).latent_dist.sample()
414
+ control_image_ = (control_image_ - self.vae.config.shift_factor) * self.vae.config.scaling_factor
415
+
416
+ # pack
417
+ height_control_image, width_control_image = control_image_.shape[2:]
418
+ control_image_ = self._pack_latents(
419
+ control_image_,
420
+ batch_size * num_images_per_prompt,
421
+ num_channels_latents,
422
+ height_control_image,
423
+ width_control_image,
424
+ )
425
+ control_images.append(control_image_)
426
+
427
+ control_image = control_images
428
+
429
+ # Here we ensure that `control_mode` has the same length as the control_image.
430
+ if isinstance(control_mode, list) and len(control_mode) != len(control_image):
431
+ raise ValueError(
432
+ "For Multi-ControlNet, `control_mode` must be a list of the same "
433
+ + " length as the number of controlnets (control images) specified"
434
+ )
435
+ if not isinstance(control_mode, list):
436
+ control_mode = [control_mode] * len(control_image)
437
+ # set control mode
438
+ control_modes = []
439
+ for cmode in control_mode:
440
+ if cmode is None:
441
+ cmode = -1
442
+ control_mode = torch.tensor(cmode).expand(control_images[0].shape[0]).to(device, dtype=torch.long)
443
+ control_modes.append(control_mode)
444
+ control_mode = control_modes
445
+
446
+ # 4. Prepare latent variables
447
+ num_channels_latents = self.transformer.config.in_channels // 4
448
+ latents, latent_image_ids = self.prepare_latents(
449
+ batch_size * num_images_per_prompt,
450
+ num_channels_latents,
451
+ height,
452
+ width,
453
+ prompt_embeds.dtype,
454
+ device,
455
+ generator,
456
+ latents,
457
+ )
458
+
459
+ # 5. Prepare timesteps
460
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
461
+ image_seq_len = latents.shape[1]
462
+ mu = calculate_shift(
463
+ image_seq_len,
464
+ self.scheduler.config.base_image_seq_len,
465
+ self.scheduler.config.max_image_seq_len,
466
+ self.scheduler.config.base_shift,
467
+ self.scheduler.config.max_shift,
468
+ )
469
+ timesteps, num_inference_steps = retrieve_timesteps(
470
+ self.scheduler,
471
+ num_inference_steps,
472
+ device,
473
+ timesteps,
474
+ sigmas,
475
+ mu=mu,
476
+ )
477
+
478
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
479
+ self._num_timesteps = len(timesteps)
480
+
481
+ # 6. Create tensor stating which controlnets to keep
482
+ controlnet_keep = []
483
+ for i in range(len(timesteps)):
484
+ keeps = [
485
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
486
+ for s, e in zip(control_guidance_start, control_guidance_end)
487
+ ]
488
+ controlnet_keep.append(keeps[0] if isinstance(self.controlnet, FluxControlNetModel) else keeps)
489
+
490
+ # 7. Denoising loop
491
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
492
+ for i, t in enumerate(timesteps):
493
+ if self.interrupt:
494
+ continue
495
+
496
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
497
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
498
+
499
+ if isinstance(self.controlnet, FluxMultiControlNetModel):
500
+ use_guidance = self.controlnet.nets[0].config.guidance_embeds
501
+ else:
502
+ use_guidance = self.controlnet.config.guidance_embeds
503
+
504
+ guidance = torch.tensor([controlnet_guidance_scale], device=device) if use_guidance else None
505
+ guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
506
+
507
+ if isinstance(controlnet_keep[i], list):
508
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
509
+ else:
510
+ controlnet_cond_scale = controlnet_conditioning_scale
511
+ if isinstance(controlnet_cond_scale, list):
512
+ controlnet_cond_scale = controlnet_cond_scale[0]
513
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
514
+
515
+ # controlnet
516
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
517
+ hidden_states=latents,
518
+ controlnet_cond=control_image,
519
+ controlnet_mode=control_mode,
520
+ conditioning_scale=cond_scale,
521
+ timestep=timestep / 1000,
522
+ guidance=guidance,
523
+ pooled_projections=pooled_prompt_embeds,
524
+ encoder_hidden_states=controlnet_prompt_embeds,
525
+ txt_ids=controlnet_text_ids,
526
+ img_ids=latent_image_ids,
527
+ joint_attention_kwargs=self.joint_attention_kwargs,
528
+ return_dict=False,
529
+ )
530
+
531
+ guidance = (
532
+ torch.tensor([guidance_scale], device=device) if self.transformer.config.guidance_embeds else None
533
+ )
534
+ guidance = guidance.expand(latents.shape[0]) if guidance is not None else None
535
+
536
+ noise_pred = self.transformer(
537
+ hidden_states=latents,
538
+ timestep=timestep / 1000,
539
+ guidance=guidance,
540
+ pooled_projections=pooled_prompt_embeds,
541
+ encoder_hidden_states=prompt_embeds,
542
+ controlnet_block_samples=controlnet_block_samples,
543
+ controlnet_single_block_samples=controlnet_single_block_samples,
544
+ txt_ids=text_ids,
545
+ img_ids=latent_image_ids,
546
+ joint_attention_kwargs=self.joint_attention_kwargs,
547
+ return_dict=False,
548
+ controlnet_blocks_repeat=controlnet_blocks_repeat,
549
+ )[0]
550
+
551
+ # perform true CFG
552
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None and negative_text_ids is not None:
553
+ noise_pred_uncond = self.transformer(
554
+ hidden_states=latents,
555
+ timestep=timestep / 1000,
556
+ guidance=guidance,
557
+ pooled_projections=negative_pooled_prompt_embeds,
558
+ encoder_hidden_states=negative_prompt_embeds,
559
+ controlnet_block_samples=None,
560
+ controlnet_single_block_samples=None,
561
+ txt_ids=negative_text_ids,
562
+ img_ids=latent_image_ids,
563
+ joint_attention_kwargs=self.joint_attention_kwargs,
564
+ return_dict=False,
565
+ controlnet_blocks_repeat=controlnet_blocks_repeat,
566
+ )[0]
567
+
568
+ noise_pred = noise_pred_uncond + true_guidance_scale * (noise_pred - noise_pred_uncond)
569
+
570
+ # compute the previous noisy sample x_t -> x_t-1
571
+ latents_dtype = latents.dtype
572
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
573
+
574
+ if latents.dtype != latents_dtype:
575
+ if torch.backends.mps.is_available():
576
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
577
+ latents = latents.to(latents_dtype)
578
+
579
+ if callback_on_step_end is not None:
580
+ callback_kwargs = {}
581
+ for k in callback_on_step_end_tensor_inputs:
582
+ callback_kwargs[k] = locals()[k]
583
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
584
+
585
+ latents = callback_outputs.pop("latents", latents)
586
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
587
+
588
+ # call the callback, if provided
589
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
590
+ progress_bar.update()
591
+
592
+ if XLA_AVAILABLE:
593
+ xm.mark_step()
594
+
595
+ if output_type == "latent":
596
+ image = latents
597
+
598
+ else:
599
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
600
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
601
+
602
+ image = self.vae.decode(latents, return_dict=False)[0]
603
+ image = self.image_processor.postprocess(image, output_type=output_type)
604
+
605
+ # Offload all models
606
+ self.maybe_free_model_hooks()
607
+
608
+ if not return_dict:
609
+ return (image,)
610
+
611
+ return FluxPipelineOutput(images=image)
pipelines/pipeline_infu_flux.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
16
+ import os
17
+ import random
18
+ from typing import Optional
19
+
20
+ import cv2
21
+ import numpy as np
22
+ import torch
23
+ from diffusers.models import FluxControlNetModel
24
+ from facexlib.recognition import init_recognition_model
25
+ from huggingface_hub import snapshot_download
26
+ from insightface.app import FaceAnalysis
27
+ from insightface.utils import face_align
28
+ from PIL import Image
29
+
30
+ from .pipeline_flux_infusenet import FluxInfuseNetPipeline
31
+ from .resampler import Resampler
32
+
33
+
34
+ def seed_everything(seed, deterministic=False):
35
+ """Set random seed.
36
+
37
+ Args:
38
+ seed (int): Seed to be used.
39
+ deterministic (bool): Whether to set the deterministic option for
40
+ CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
41
+ to True and `torch.backends.cudnn.benchmark` to False.
42
+ Default: False.
43
+ """
44
+ random.seed(seed)
45
+ np.random.seed(seed)
46
+ torch.manual_seed(seed)
47
+ torch.cuda.manual_seed(seed)
48
+ torch.cuda.manual_seed_all(seed)
49
+ os.environ['PYTHONHASHSEED'] = str(seed)
50
+ if deterministic:
51
+ torch.backends.cudnn.deterministic = True
52
+ torch.backends.cudnn.benchmark = False
53
+
54
+
55
+ # modified from https://github.com/instantX-research/InstantID/blob/main/pipeline_stable_diffusion_xl_instantid.py
56
+ def draw_kps(image_pil, kps, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]):
57
+ stickwidth = 4
58
+ limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])
59
+ kps = np.array(kps)
60
+
61
+ w, h = image_pil.size
62
+ out_img = np.zeros([h, w, 3])
63
+
64
+ for i in range(len(limbSeq)):
65
+ index = limbSeq[i]
66
+ color = color_list[index[0]]
67
+
68
+ x = kps[index][:, 0]
69
+ y = kps[index][:, 1]
70
+ length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
71
+ angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))
72
+ polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
73
+ out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)
74
+ out_img = (out_img * 0.6).astype(np.uint8)
75
+
76
+ for idx_kp, kp in enumerate(kps):
77
+ color = color_list[idx_kp]
78
+ x, y = kp
79
+ out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)
80
+
81
+ out_img_pil = Image.fromarray(out_img.astype(np.uint8))
82
+ return out_img_pil
83
+
84
+
85
+ def extract_arcface_bgr_embedding(in_image, landmark, arcface_model=None, in_settings=None):
86
+ kps = landmark
87
+ arc_face_image = face_align.norm_crop(in_image, landmark=np.array(kps), image_size=112)
88
+ arc_face_image = torch.from_numpy(arc_face_image).unsqueeze(0).permute(0,3,1,2) / 255.
89
+ arc_face_image = 2 * arc_face_image - 1
90
+ arc_face_image = arc_face_image.cuda().contiguous()
91
+ if arcface_model is None:
92
+ arcface_model = init_recognition_model('arcface', device='cuda')
93
+ face_emb = arcface_model(arc_face_image)[0] # [512], normalized
94
+ return face_emb
95
+
96
+
97
+ def resize_and_pad_image(source_img, target_img_size):
98
+ # Get original and target sizes
99
+ source_img_size = source_img.size
100
+ target_width, target_height = target_img_size
101
+
102
+ # Determine the new size based on the shorter side of target_img
103
+ if target_width <= target_height:
104
+ new_width = target_width
105
+ new_height = int(target_width * (source_img_size[1] / source_img_size[0]))
106
+ else:
107
+ new_height = target_height
108
+ new_width = int(target_height * (source_img_size[0] / source_img_size[1]))
109
+
110
+ # Resize the source image using LANCZOS interpolation for high quality
111
+ resized_source_img = source_img.resize((new_width, new_height), Image.LANCZOS)
112
+
113
+ # Compute padding to center resized image
114
+ pad_left = (target_width - new_width) // 2
115
+ pad_top = (target_height - new_height) // 2
116
+
117
+ # Create a new image with white background
118
+ padded_img = Image.new("RGB", target_img_size, (255, 255, 255))
119
+ padded_img.paste(resized_source_img, (pad_left, pad_top))
120
+
121
+ return padded_img
122
+
123
+
124
+ class InfUFluxPipeline:
125
+ def __init__(
126
+ self,
127
+ base_model_path,
128
+ infu_model_path,
129
+ insightface_root_path = './',
130
+ image_proj_num_tokens=8,
131
+ infu_flux_version='v1.0',
132
+ model_version='aes_stage2',
133
+ ):
134
+
135
+ self.infu_flux_version = infu_flux_version
136
+ self.model_version = model_version
137
+
138
+ # Load pipeline
139
+ try:
140
+ infusenet_path = os.path.join(infu_model_path, 'InfuseNetModel')
141
+ self.infusenet = FluxControlNetModel.from_pretrained(infusenet_path, torch_dtype=torch.bfloat16)
142
+ except:
143
+ print("No InfiniteYou model found. Downloading from HuggingFace `ByteDance/InfiniteYou` to `./models/InfiniteYou` ...")
144
+ snapshot_download(repo_id='ByteDance/InfiniteYou', local_dir='./models/InfiniteYou', local_dir_use_symlinks=False)
145
+ infu_model_path = os.path.join('./models/InfiniteYou', f'infu_flux_{infu_flux_version}', model_version)
146
+ infusenet_path = os.path.join(infu_model_path, 'InfuseNetModel')
147
+ self.infusenet = FluxControlNetModel.from_pretrained(infusenet_path, torch_dtype=torch.bfloat16)
148
+ insightface_root_path = './models/InfiniteYou/supports/insightface'
149
+ try:
150
+ pipe = FluxInfuseNetPipeline.from_pretrained(
151
+ base_model_path,
152
+ controlnet=self.infusenet,
153
+ torch_dtype=torch.bfloat16,
154
+ )
155
+ except:
156
+ try:
157
+ pipe = FluxInfuseNetPipeline.from_single_file(
158
+ base_model_path,
159
+ controlnet=self.infusenet,
160
+ torch_dtype=torch.bfloat16,
161
+ )
162
+ except Exception as e:
163
+ print(e)
164
+ print('\nIf you are using `black-forest-labs/FLUX.1-dev` and have not downloaded it into a local directory, '
165
+ 'please accept the agreement and obtain access at https://huggingface.co/black-forest-labs/FLUX.1-dev. '
166
+ 'Then, use `huggingface-cli login` and your access tokens at https://huggingface.co/settings/tokens to authenticate. '
167
+ 'After that, run the code again. If you have downloaded it, please use `base_model_path` to specify the correct path.')
168
+ print('\nIf you are using other models, please download them to a local directory and use `base_model_path` to specify the correct path.')
169
+ exit()
170
+ pipe.to('cuda', torch.bfloat16)
171
+ self.pipe = pipe
172
+
173
+ # Load image proj model
174
+ num_tokens = image_proj_num_tokens
175
+ image_emb_dim = 512
176
+ image_proj_model = Resampler(
177
+ dim=1280,
178
+ depth=4,
179
+ dim_head=64,
180
+ heads=20,
181
+ num_queries=num_tokens,
182
+ embedding_dim=image_emb_dim,
183
+ output_dim=4096,
184
+ ff_mult=4,
185
+ )
186
+ image_proj_model_path = os.path.join(infu_model_path, 'image_proj_model.bin')
187
+ ipm_state_dict = torch.load(image_proj_model_path, map_location="cpu")
188
+ image_proj_model.load_state_dict(ipm_state_dict['image_proj'])
189
+ del ipm_state_dict
190
+ image_proj_model.to('cuda', torch.bfloat16)
191
+ image_proj_model.eval()
192
+
193
+ self.image_proj_model = image_proj_model
194
+
195
+ # Load face encoder
196
+ self.app_640 = FaceAnalysis(name='antelopev2',
197
+ root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
198
+ self.app_640.prepare(ctx_id=0, det_size=(640, 640))
199
+
200
+ self.app_320 = FaceAnalysis(name='antelopev2',
201
+ root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
202
+ self.app_320.prepare(ctx_id=0, det_size=(320, 320))
203
+
204
+ self.app_160 = FaceAnalysis(name='antelopev2',
205
+ root=insightface_root_path, providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
206
+ self.app_160.prepare(ctx_id=0, det_size=(160, 160))
207
+
208
+ self.arcface_model = init_recognition_model('arcface', device='cuda')
209
+
210
+ def load_loras(self, loras):
211
+ names, scales = [],[]
212
+ for lora_path, lora_name, lora_scale in loras:
213
+ if lora_path != "":
214
+ print(f"loading lora {lora_path}")
215
+ self.pipe.load_lora_weights(lora_path, adapter_name = lora_name)
216
+ names.append(lora_name)
217
+ scales.append(lora_scale)
218
+
219
+ if len(names) > 0:
220
+ self.pipe.set_adapters(names, adapter_weights=scales)
221
+
222
+ def _detect_face(self, id_image_cv2):
223
+ face_info = self.app_640.get(id_image_cv2)
224
+ if len(face_info) > 0:
225
+ return face_info
226
+
227
+ face_info = self.app_320.get(id_image_cv2)
228
+ if len(face_info) > 0:
229
+ return face_info
230
+
231
+ face_info = self.app_160.get(id_image_cv2)
232
+ return face_info
233
+
234
+ def __call__(
235
+ self,
236
+ id_image: Image.Image, # PIL.Image.Image (RGB)
237
+ prompt: str,
238
+ control_image: Optional[Image.Image] = None, # PIL.Image.Image (RGB) or None
239
+ width = 864,
240
+ height = 1152,
241
+ seed = 42,
242
+ guidance_scale = 3.5,
243
+ num_steps = 30,
244
+ infusenet_conditioning_scale = 1.0,
245
+ infusenet_guidance_start = 0.0,
246
+ infusenet_guidance_end = 1.0,
247
+ ):
248
+ # Extract ID embeddings
249
+ print('Preparing ID embeddings')
250
+ id_image_cv2 = cv2.cvtColor(np.array(id_image), cv2.COLOR_RGB2BGR)
251
+ face_info = self._detect_face(id_image_cv2)
252
+ if len(face_info) == 0:
253
+ raise ValueError('No face detected in the input ID image')
254
+
255
+ 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
256
+ landmark = face_info['kps']
257
+ id_embed = extract_arcface_bgr_embedding(id_image_cv2, landmark, self.arcface_model)
258
+ id_embed = id_embed.clone().unsqueeze(0).float().cuda()
259
+ id_embed = id_embed.reshape([1, -1, 512])
260
+ id_embed = id_embed.to(device='cuda', dtype=torch.bfloat16)
261
+ with torch.no_grad():
262
+ id_embed = self.image_proj_model(id_embed)
263
+ bs_embed, seq_len, _ = id_embed.shape
264
+ id_embed = id_embed.repeat(1, 1, 1)
265
+ id_embed = id_embed.view(bs_embed * 1, seq_len, -1)
266
+ id_embed = id_embed.to(device='cuda', dtype=torch.bfloat16)
267
+
268
+ # Load control image
269
+ print('Preparing the control image')
270
+ if control_image is not None:
271
+ control_image = control_image.convert("RGB")
272
+ control_image = resize_and_pad_image(control_image, (width, height))
273
+ face_info = self._detect_face(cv2.cvtColor(np.array(control_image), cv2.COLOR_RGB2BGR))
274
+ if len(face_info) == 0:
275
+ raise ValueError('No face detected in the control image')
276
+ 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
277
+ control_image = draw_kps(control_image, face_info['kps'])
278
+ else:
279
+ out_img = np.zeros([height, width, 3])
280
+ control_image = Image.fromarray(out_img.astype(np.uint8))
281
+
282
+ # Perform inference
283
+ print('Generating image')
284
+ seed_everything(seed)
285
+ image = self.pipe(
286
+ prompt=prompt,
287
+ controlnet_prompt_embeds=id_embed,
288
+ control_image=control_image,
289
+ guidance_scale=guidance_scale,
290
+ num_inference_steps=num_steps,
291
+ controlnet_guidance_scale=1.0,
292
+ controlnet_conditioning_scale=infusenet_conditioning_scale,
293
+ control_guidance_start=infusenet_guidance_start,
294
+ control_guidance_end=infusenet_guidance_end,
295
+ height=height,
296
+ width=width,
297
+ ).images[0]
298
+
299
+ 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,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==1.0.1
2
+ diffusers==0.31.0
3
+ facexlib==0.3.0
4
+ gradio==5.21.0
5
+ httpcore==1.0.7
6
+ httpx==0.28.1
7
+ huggingface-hub==0.28.1
8
+ insightface==0.7.3
9
+ numpy==1.26.4
10
+ onnxruntime==1.19.2
11
+ opencv-python==4.11.0.86
12
+ pillow==10.4.0
13
+ pillow-avif-plugin==1.5.0
14
+ pillow-heif==0.21.0
15
+ sentencepiece==0.2.0
16
+ torch==2.2.1
17
+ torchvision==0.17.1
18
+ transformers==4.48.0
19
+ peft==0.14.0
test.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 argparse
16
+ import os
17
+
18
+ import torch
19
+ from PIL import Image
20
+
21
+ from pipelines.pipeline_infu_flux import InfUFluxPipeline
22
+
23
+
24
+ def main():
25
+ parser = argparse.ArgumentParser()
26
+ parser.add_argument('--id_image', default='./assets/examples/yann-lecun_resize.jpg', help="""input ID image""")
27
+ parser.add_argument('--control_image', default=None, help="""control image [optional]""")
28
+ parser.add_argument('--out_results_dir', default='./results', help="""output folder""")
29
+ parser.add_argument('--prompt', default='A man, portrait, cinematic')
30
+ parser.add_argument('--base_model_path', default='black-forest-labs/FLUX.1-dev')
31
+ parser.add_argument('--model_dir', default='ByteDance/InfiniteYou')
32
+ parser.add_argument('--infu_flux_version', default='v1.0', help="""InfiniteYou-FLUX version: currently only v1.0""")
33
+ parser.add_argument('--model_version', default='aes_stage2', help="""model version: aes_stage2 | sim_stage1""")
34
+ parser.add_argument('--cuda_device', default=0, type=int)
35
+ parser.add_argument('--seed', default=0, type=int, help="""seed (0 for random)""")
36
+ parser.add_argument('--guidance_scale', default=3.5, type=float)
37
+ parser.add_argument('--num_steps', default=30, type=int)
38
+ parser.add_argument('--infusenet_conditioning_scale', default=1.0, type=float)
39
+ parser.add_argument('--infusenet_guidance_start', default=0.0, type=float)
40
+ parser.add_argument('--infusenet_guidance_end', default=1.0, type=float)
41
+ # The LoRA options below are entirely optional. Here we provide two examples to facilitate users to try, but they are NOT used in our paper.
42
+ parser.add_argument('--enable_realism_lora', action='store_true')
43
+ parser.add_argument('--enable_anti_blur_lora', action='store_true')
44
+ args = parser.parse_args()
45
+
46
+ # Check arguments
47
+ assert args.infu_flux_version == 'v1.0', 'Currently only supports InfiniteYou-FLUX v1.0'
48
+ assert args.model_version in ['aes_stage2', 'sim_stage1'], 'Currently only supports model versions: aes_stage2 | sim_stage1'
49
+
50
+ # Set cuda device
51
+ torch.cuda.set_device(args.cuda_device)
52
+
53
+ # Load pipeline
54
+ infu_model_path = os.path.join(args.model_dir, f'infu_flux_{args.infu_flux_version}', args.model_version)
55
+ insightface_root_path = os.path.join(args.model_dir, 'supports', 'insightface')
56
+ pipe = InfUFluxPipeline(
57
+ base_model_path=args.base_model_path,
58
+ infu_model_path=infu_model_path,
59
+ insightface_root_path=insightface_root_path,
60
+ infu_flux_version=args.infu_flux_version,
61
+ model_version=args.model_version,
62
+ )
63
+ # Load LoRAs (optional)
64
+ lora_dir = os.path.join(args.model_dir, 'supports', 'optional_loras')
65
+ if not os.path.exists(lora_dir): lora_dir = './models/InfiniteYou/supports/optional_loras'
66
+ loras = []
67
+ if args.enable_realism_lora:
68
+ loras.append([os.path.join(lora_dir, 'flux_realism_lora.safetensors'), 'realism', 1.0])
69
+ if args.enable_anti_blur_lora:
70
+ loras.append([os.path.join(lora_dir, 'flux_anti_blur_lora.safetensors'), 'anti_blur', 1.0])
71
+ pipe.load_loras(loras)
72
+
73
+ # Perform inference
74
+ if args.seed == 0:
75
+ args.seed = torch.seed() & 0xFFFFFFFF
76
+ image = pipe(
77
+ id_image=Image.open(args.id_image).convert('RGB'),
78
+ prompt=args.prompt,
79
+ control_image=Image.open(args.control_image).convert('RGB') if args.control_image is not None else None,
80
+ seed=args.seed,
81
+ guidance_scale=args.guidance_scale,
82
+ num_steps=args.num_steps,
83
+ infusenet_conditioning_scale=args.infusenet_conditioning_scale,
84
+ infusenet_guidance_start=args.infusenet_guidance_start,
85
+ infusenet_guidance_end=args.infusenet_guidance_end,
86
+ )
87
+
88
+ # Save results
89
+ os.makedirs(args.out_results_dir, exist_ok=True)
90
+ index = len(os.listdir(args.out_results_dir))
91
+ id_name = os.path.splitext(os.path.basename(args.id_image))[0]
92
+ prompt_name = args.prompt[:150] + '*' if len(args.prompt) > 150 else args.prompt
93
+ prompt_name = prompt_name.replace('/', '|')
94
+ out_name = f'{index:05d}_{id_name}_{prompt_name}_seed{args.seed}.png'
95
+ out_result_path = os.path.join(args.out_results_dir, out_name)
96
+ image.save(out_result_path)
97
+
98
+
99
+ if __name__ == "__main__":
100
+ main()