├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── assets ├── 0.png ├── 1.png ├── applications.png ├── compare-a.png ├── compare-b.png └── compare-c.png ├── checkpoints └── __put_instant_id_checkpoints_here__ ├── download_models.py ├── examples ├── kaifu_resize.png ├── musk_resize.jpeg ├── sam_resize.png ├── schmidhuber_resize.png └── yann-lecun_resize.jpg ├── gradio_demo ├── app.py ├── requirements.txt └── style_template.py ├── infer.py ├── ip_adapter ├── attention_processor.py ├── resampler.py └── utils.py ├── models └── __put_antelopev2_here__ ├── nodes.py ├── pipeline_stable_diffusion_xl_instantid.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ComfyUI InstantID 2 | 3 | This is a thin wrapper custom node for [Instant ID](https://github.com/InstantID/InstantID). It's providing basic testing interface for playing around with Instant ID functions. Forgive me for not implementing stepping progress indicator. 4 | 5 | It's not following ComfyUI module design nicely, but I just want to set it up for quick testing. Hope IPAdapterPlus will do better integrating to ComfyUI ecosystems... 6 | 7 | A little more explanation: Yes, I know it's great to break down nodes; but it's diffuser based implementation and its inputs / outputs are not compatible with existing other nodes. Even if you break down nodes, those nodes are just connecting each others within the group. Let's wait for better IPAdapterPlus implementation instead of introducing yet another bunch of fancy nodes just for one purpose. 8 | 9 | ## Install 10 | 11 | Just as other custom nodes: 12 | ``` 13 | cd ComfyUI/custom_nodes/ 14 | git clone https://github.com/huxiuhan/ComfyUI-InstantID.git 15 | pip install -r requirements.txt 16 | ``` 17 | 18 | ## Download Models 19 | 20 | ## Download 21 | 22 | You can directly download the model from [Huggingface](https://huggingface.co/InstantX/InstantID). 23 | You also can download the model in python script: 24 | 25 | ```python 26 | from huggingface_hub import hf_hub_download 27 | hf_hub_download(repo_id="InstantX/InstantID", filename="ControlNetModel/config.json", local_dir="./checkpoints") 28 | hf_hub_download(repo_id="InstantX/InstantID", filename="ControlNetModel/diffusion_pytorch_model.safetensors", local_dir="./checkpoints") 29 | hf_hub_download(repo_id="InstantX/InstantID", filename="ip-adapter.bin", local_dir="./checkpoints") 30 | ``` 31 | 32 | If you cannot access to Huggingface, you can use [hf-mirror](https://hf-mirror.com/) to download models. 33 | ```python 34 | export HF_ENDPOINT=https://hf-mirror.com 35 | huggingface-cli download --resume-download InstantX/InstantID --local-dir checkpoints 36 | ``` 37 | 38 | For face encoder, you need to manually download via this [URL](https://github.com/deepinsight/insightface/issues/1896#issuecomment-1023867304) to `models/antelopev2` as the default link is invalid. Once you have prepared all models, the folder tree should be like: 39 | 40 | ``` 41 | . 42 | ├── models 43 | ├── checkpoints 44 | ├── ip_adapter 45 | ├── pipeline_stable_diffusion_xl_instantid.py 46 | └── README.md 47 | ``` 48 | 49 | ## Usage 50 | 51 | Choose a SDXL base ckpt. You can also try SDXL Turbo with 4 steps, very efficient for fast testing. 52 | 53 | First time loading usually takes more than 60s, but the node will try its best to cache models. 54 | 55 | 截屏2024-01-23 03 24 35 56 | 57 | 截屏2024-01-23 03 54 10 58 | 59 | ## Original Project 60 | 61 | 62 | 63 | 64 | 65 | **InstantID : Zero-shot Identity-Preserving Generation in Seconds** 66 | 67 | InstantID is a new state-of-the-art tuning-free method to achieve ID-Preserving generation with only single image, supporting various downstream tasks. 68 | 69 | 70 | 71 | ## Release 72 | - [2024/1/22] 🔥 We release the [pre-trained checkpoints](https://huggingface.co/InstantX/InstantID), [inference code](https://github.com/InstantID/InstantID/blob/main/infer.py) and [gradio demo](https://huggingface.co/spaces/InstantX/InstantID)! 73 | - [2024/1/15] 🔥 We release the technical report. 74 | - [2023/12/11] 🔥 We launch the project page. 75 | 76 | ## Demos 77 | 78 | ### Stylized Synthesis 79 | 80 |

81 | 82 |

83 | 84 | ### Comparison with Previous Works 85 | 86 |

87 | 88 |

89 | 90 | Comparison with existing tuning-free state-of-the-art techniques. InstantID achieves better fidelity and retain good text editability (faces and styles blend better). 91 | 92 |

93 | 94 |

95 | 96 | Comparison with pre-trained character LoRAs. We don't need multiple images and still can achieve competitive results as LoRAs without any training. 97 | 98 |

99 | 100 |

101 | 102 | Comparison with InsightFace Swapper (also known as ROOP or Refactor). However, in non-realistic style, our work is more flexible on the integration of face and background. 103 | 104 | ## Usage Tips 105 | - For higher similarity, increase the weight of controlnet_conditioning_scale (IdentityNet) and ip_adapter_scale (Adapter). 106 | - For over-saturation, decrease the ip_adapter_scale. If not work, decrease controlnet_conditioning_scale. 107 | - For higher text control ability, decrease ip_adapter_scale. 108 | - For specific styles, choose corresponding base model makes differences. 109 | 110 | ## Acknowledgements 111 | - Our work is highly inspired by [IP-Adapter](https://github.com/tencent-ailab/IP-Adapter) and [ControlNet](https://github.com/lllyasviel/ControlNet). Thanks for their great works! 112 | - Thanks to the HuggingFace team for their generous GPU support! 113 | 114 | ## Disclaimer 115 | This project is released under [Apache License](https://github.com/InstantID/InstantID?tab=Apache-2.0-1-ov-file#readme) and aims to positively impact the field of AI-driven image generation. Users are granted the freedom to create images using this tool, but they are obligated to comply with local laws and utilize it responsibly. The developers will not assume any responsibility for potential misuse by users. 116 | 117 | ## Cite 118 | If you find InstantID useful for your research and applications, please cite us using this BibTeX: 119 | 120 | ```bibtex 121 | @article{wang2024instantid, 122 | title={InstantID: Zero-shot Identity-Preserving Generation in Seconds}, 123 | author={Wang, Qixun and Bai, Xu and Wang, Haofan and Qin, Zekui and Chen, Anthony}, 124 | journal={arXiv preprint arXiv:2401.07519}, 125 | year={2024} 126 | } 127 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | from .nodes import InstantIDSampler 3 | 4 | NODE_CLASS_MAPPINGS = { 5 | "Instant ID Sampler": InstantIDSampler, 6 | } 7 | NODE_DISPLAY_NAME_MAPPINGS = { 8 | "Instant ID Sampler": "Instant ID Sampler For SDXL", 9 | } 10 | -------------------------------------------------------------------------------- /assets/0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/assets/0.png -------------------------------------------------------------------------------- /assets/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/assets/1.png -------------------------------------------------------------------------------- /assets/applications.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/assets/applications.png -------------------------------------------------------------------------------- /assets/compare-a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/assets/compare-a.png -------------------------------------------------------------------------------- /assets/compare-b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/assets/compare-b.png -------------------------------------------------------------------------------- /assets/compare-c.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/assets/compare-c.png -------------------------------------------------------------------------------- /checkpoints/__put_instant_id_checkpoints_here__: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/checkpoints/__put_instant_id_checkpoints_here__ -------------------------------------------------------------------------------- /download_models.py: -------------------------------------------------------------------------------- 1 | from huggingface_hub import hf_hub_download 2 | hf_hub_download(repo_id="InstantX/InstantID", filename="ControlNetModel/config.json", local_dir="./checkpoints") 3 | hf_hub_download(repo_id="InstantX/InstantID", filename="ControlNetModel/diffusion_pytorch_model.safetensors", local_dir="./checkpoints") 4 | hf_hub_download(repo_id="InstantX/InstantID", filename="ip-adapter.bin", local_dir="./checkpoints") -------------------------------------------------------------------------------- /examples/kaifu_resize.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/examples/kaifu_resize.png -------------------------------------------------------------------------------- /examples/musk_resize.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/examples/musk_resize.jpeg -------------------------------------------------------------------------------- /examples/sam_resize.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/examples/sam_resize.png -------------------------------------------------------------------------------- /examples/schmidhuber_resize.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/examples/schmidhuber_resize.png -------------------------------------------------------------------------------- /examples/yann-lecun_resize.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/examples/yann-lecun_resize.jpg -------------------------------------------------------------------------------- /gradio_demo/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import math 4 | import torch 5 | import random 6 | import numpy as np 7 | 8 | import PIL 9 | from PIL import Image 10 | 11 | import diffusers 12 | from diffusers.utils import load_image 13 | from diffusers.models import ControlNetModel 14 | 15 | import insightface 16 | from insightface.app import FaceAnalysis 17 | 18 | from style_template import styles 19 | from pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline 20 | 21 | import gradio as gr 22 | 23 | # global variable 24 | MAX_SEED = np.iinfo(np.int32).max 25 | device = "cuda" if torch.cuda.is_available() else "cpu" 26 | STYLE_NAMES = list(styles.keys()) 27 | DEFAULT_STYLE_NAME = "Watercolor" 28 | 29 | # Load face encoder 30 | app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) 31 | app.prepare(ctx_id=0, det_size=(640, 640)) 32 | 33 | # Path to InstantID models 34 | face_adapter = f'./checkpoints/ip-adapter.bin' 35 | controlnet_path = f'./checkpoints/ControlNetModel' 36 | 37 | # Load pipeline 38 | controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16) 39 | 40 | base_model_path = 'wangqixun/YamerMIX_v8' 41 | 42 | pipe = StableDiffusionXLInstantIDPipeline.from_pretrained( 43 | base_model_path, 44 | controlnet=controlnet, 45 | torch_dtype=torch.float16, 46 | safety_checker=None, 47 | feature_extractor=None, 48 | ) 49 | pipe.cuda() 50 | pipe.load_ip_adapter_instantid(face_adapter) 51 | 52 | def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: 53 | if randomize_seed: 54 | seed = random.randint(0, MAX_SEED) 55 | return seed 56 | 57 | def swap_to_gallery(images): 58 | return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False) 59 | 60 | def upload_example_to_gallery(images, prompt, style, negative_prompt): 61 | return gr.update(value=images, visible=True), gr.update(visible=True), gr.update(visible=False) 62 | 63 | def remove_back_to_files(): 64 | return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) 65 | 66 | def remove_tips(): 67 | return gr.update(visible=False) 68 | 69 | def get_example(): 70 | case = [ 71 | [ 72 | ['./examples/yann-lecun_resize.jpg'], 73 | "a man", 74 | "Snow", 75 | "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 76 | ], 77 | [ 78 | ['./examples/musk_resize.jpeg'], 79 | "a man", 80 | "Mars", 81 | "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 82 | ], 83 | [ 84 | ['./examples/sam_resize.png'], 85 | "a man", 86 | "Jungle", 87 | "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, gree", 88 | ], 89 | [ 90 | ['./examples/schmidhuber_resize.png'], 91 | "a man", 92 | "Neon", 93 | "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 94 | ], 95 | [ 96 | ['./examples/kaifu_resize.png'], 97 | "a man", 98 | "Vibrant Color", 99 | "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 100 | ], 101 | ] 102 | return case 103 | 104 | def convert_from_cv2_to_image(img: np.ndarray) -> Image: 105 | return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) 106 | 107 | def convert_from_image_to_cv2(img: Image) -> np.ndarray: 108 | return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) 109 | 110 | def draw_kps(image_pil, kps, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]): 111 | stickwidth = 4 112 | limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]]) 113 | kps = np.array(kps) 114 | 115 | w, h = image_pil.size 116 | out_img = np.zeros([h, w, 3]) 117 | 118 | for i in range(len(limbSeq)): 119 | index = limbSeq[i] 120 | color = color_list[index[0]] 121 | 122 | x = kps[index][:, 0] 123 | y = kps[index][:, 1] 124 | length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5 125 | angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1])) 126 | polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1) 127 | out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color) 128 | out_img = (out_img * 0.6).astype(np.uint8) 129 | 130 | for idx_kp, kp in enumerate(kps): 131 | color = color_list[idx_kp] 132 | x, y = kp 133 | out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1) 134 | 135 | out_img_pil = Image.fromarray(out_img.astype(np.uint8)) 136 | return out_img_pil 137 | 138 | def resize_img(input_image, max_side=1280, min_side=1024, size=None, 139 | pad_to_max_side=False, mode=PIL.Image.BILINEAR, base_pixel_number=64): 140 | 141 | w, h = input_image.size 142 | if size is not None: 143 | w_resize_new, h_resize_new = size 144 | else: 145 | ratio = min_side / min(h, w) 146 | w, h = round(ratio*w), round(ratio*h) 147 | ratio = max_side / max(h, w) 148 | input_image = input_image.resize([round(ratio*w), round(ratio*h)], mode) 149 | w_resize_new = (round(ratio * w) // base_pixel_number) * base_pixel_number 150 | h_resize_new = (round(ratio * h) // base_pixel_number) * base_pixel_number 151 | input_image = input_image.resize([w_resize_new, h_resize_new], mode) 152 | 153 | if pad_to_max_side: 154 | res = np.ones([max_side, max_side, 3], dtype=np.uint8) * 255 155 | offset_x = (max_side - w_resize_new) // 2 156 | offset_y = (max_side - h_resize_new) // 2 157 | res[offset_y:offset_y+h_resize_new, offset_x:offset_x+w_resize_new] = np.array(input_image) 158 | input_image = Image.fromarray(res) 159 | return input_image 160 | 161 | def apply_style(style_name: str, positive: str, negative: str = "") -> tuple[str, str]: 162 | p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME]) 163 | return p.replace("{prompt}", positive), n + ' ' + negative 164 | 165 | def generate_image(face_image, pose_image, prompt, negative_prompt, style_name, num_steps, identitynet_strength_ratio, adapter_strength_ratio, guidance_scale, seed, progress=gr.Progress(track_tqdm=True)): 166 | 167 | if face_image is None: 168 | raise gr.Error(f"Cannot find any input face image! Please upload the face image") 169 | 170 | if prompt is None: 171 | prompt = "a person" 172 | 173 | # apply the style template 174 | prompt, negative_prompt = apply_style(style_name, prompt, negative_prompt) 175 | 176 | face_image = load_image(face_image[0]) 177 | face_image = resize_img(face_image) 178 | face_image_cv2 = convert_from_image_to_cv2(face_image) 179 | height, width, _ = face_image_cv2.shape 180 | 181 | # Extract face features 182 | face_info = app.get(face_image_cv2) 183 | 184 | if len(face_info) == 0: 185 | raise gr.Error(f"Cannot find any face in the image! Please upload another person image") 186 | 187 | face_info = face_info[-1] 188 | face_emb = face_info['embedding'] 189 | face_kps = draw_kps(convert_from_cv2_to_image(face_image_cv2), face_info['kps']) 190 | 191 | if pose_image is not None: 192 | pose_image = load_image(pose_image[0]) 193 | pose_image = resize_img(pose_image) 194 | pose_image_cv2 = convert_from_image_to_cv2(pose_image) 195 | 196 | face_info = app.get(pose_image_cv2) 197 | 198 | if len(face_info) == 0: 199 | raise gr.Error(f"Cannot find any face in the reference image! Please upload another person image") 200 | 201 | face_info = face_info[-1] 202 | face_kps = draw_kps(pose_image, face_info['kps']) 203 | 204 | width, height = face_kps.size 205 | 206 | generator = torch.Generator(device=device).manual_seed(seed) 207 | 208 | print("Start inference...") 209 | print(f"[Debug] Prompt: {prompt}, \n[Debug] Neg Prompt: {negative_prompt}") 210 | 211 | pipe.set_ip_adapter_scale(adapter_strength_ratio) 212 | images = pipe( 213 | prompt=prompt, 214 | negative_prompt=negative_prompt, 215 | image_embeds=face_emb, 216 | image=face_kps, 217 | controlnet_conditioning_scale=float(identitynet_strength_ratio), 218 | num_inference_steps=num_steps, 219 | guidance_scale=guidance_scale, 220 | height=height, 221 | width=width, 222 | generator=generator 223 | ).images 224 | 225 | return images, gr.update(visible=True) 226 | 227 | ### Description 228 | title = r""" 229 |

InstantID: Zero-shot Identity-Preserving Generation in Seconds

230 | """ 231 | 232 | description = r""" 233 | Official 🤗 Gradio demo for InstantID: Zero-shot Identity-Preserving Generation in Seconds.
234 | 235 | How to use:
236 | 1. Upload a person image. For multiple person images, we will only detect the biggest face. Make sure face is not too small and not significantly blocked or blurred. 237 | 2. (Optionally) upload another person image as reference pose. If not uploaded, we will use the first person image to extract landmarks. If you use a cropped face at step1, it is recommeneded to upload it to extract a new pose. 238 | 3. Enter a text prompt as done in normal text-to-image models. 239 | 4. Click the Submit button to start customizing. 240 | 5. Share your customizd photo with your friends, enjoy😊! 241 | """ 242 | 243 | article = r""" 244 | --- 245 | 📝 **Citation** 246 |
247 | If our work is helpful for your research or applications, please cite us via: 248 | ```bibtex 249 | @article{wang2024instantid, 250 | title={InstantID: Zero-shot Identity-Preserving Generation in Seconds}, 251 | author={Wang, Qixun and Bai, Xu and Wang, Haofan and Qin, Zekui and Chen, Anthony}, 252 | journal={arXiv preprint arXiv:2401.07519}, 253 | year={2024} 254 | } 255 | ``` 256 | 📧 **Contact** 257 |
258 | If you have any questions, please feel free to open an issue or directly reach us out at haofanwang.ai@gmail.com. 259 | """ 260 | 261 | tips = r""" 262 | ### Usage tips of InstantID 263 | 1. If you're not satisfied with the similarity, try to increase the weight of "IdentityNet Strength" and "Adapter Strength". 264 | 2. If you feel that the saturation is too high, first decrease the Adapter strength. If it is still too high, then decrease the IdentityNet strength. 265 | 3. If you find that text control is not as expected, decrease Adapter strength. 266 | 4. If you find that realistic style is not good enough, go for our Github repo and use a more realistic base model. 267 | """ 268 | 269 | css = ''' 270 | .gradio-container {width: 85% !important} 271 | ''' 272 | with gr.Blocks(css=css) as demo: 273 | 274 | # description 275 | gr.Markdown(title) 276 | gr.Markdown(description) 277 | 278 | with gr.Row(): 279 | with gr.Column(): 280 | 281 | # upload face image 282 | face_files = gr.Files( 283 | label="Upload a photo of your face", 284 | file_types=["image"] 285 | ) 286 | uploaded_faces = gr.Gallery(label="Your images", visible=False, columns=1, rows=1, height=512) 287 | with gr.Column(visible=False) as clear_button_face: 288 | remove_and_reupload_faces = gr.ClearButton(value="Remove and upload new ones", components=face_files, size="sm") 289 | 290 | # optional: upload a reference pose image 291 | pose_files = gr.Files( 292 | label="Upload a reference pose image (optional)", 293 | file_types=["image"] 294 | ) 295 | uploaded_poses = gr.Gallery(label="Your images", visible=False, columns=1, rows=1, height=512) 296 | with gr.Column(visible=False) as clear_button_pose: 297 | remove_and_reupload_poses = gr.ClearButton(value="Remove and upload new ones", components=pose_files, size="sm") 298 | 299 | # prompt 300 | prompt = gr.Textbox(label="Prompt", 301 | info="Give simple prompt is enough to achieve good face fedility", 302 | placeholder="A photo of a person", 303 | value="") 304 | 305 | submit = gr.Button("Submit", variant="primary") 306 | 307 | style = gr.Dropdown(label="Style template", choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME) 308 | 309 | # strength 310 | identitynet_strength_ratio = gr.Slider( 311 | label="IdentityNet strength (for fedility)", 312 | minimum=0, 313 | maximum=1.5, 314 | step=0.05, 315 | value=0.80, 316 | ) 317 | adapter_strength_ratio = gr.Slider( 318 | label="Image adapter strength (for detail)", 319 | minimum=0, 320 | maximum=1.5, 321 | step=0.05, 322 | value=0.80, 323 | ) 324 | 325 | with gr.Accordion(open=False, label="Advanced Options"): 326 | negative_prompt = gr.Textbox( 327 | label="Negative Prompt", 328 | placeholder="low quality", 329 | value="(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 330 | ) 331 | num_steps = gr.Slider( 332 | label="Number of sample steps", 333 | minimum=20, 334 | maximum=100, 335 | step=1, 336 | value=30, 337 | ) 338 | guidance_scale = gr.Slider( 339 | label="Guidance scale", 340 | minimum=0.1, 341 | maximum=10.0, 342 | step=0.1, 343 | value=5, 344 | ) 345 | seed = gr.Slider( 346 | label="Seed", 347 | minimum=0, 348 | maximum=MAX_SEED, 349 | step=1, 350 | value=42, 351 | ) 352 | randomize_seed = gr.Checkbox(label="Randomize seed", value=True) 353 | 354 | with gr.Column(): 355 | gallery = gr.Gallery(label="Generated Images") 356 | usage_tips = gr.Markdown(label="Usage tips of InstantID", value=tips ,visible=False) 357 | 358 | face_files.upload(fn=swap_to_gallery, inputs=face_files, outputs=[uploaded_faces, clear_button_face, face_files]) 359 | pose_files.upload(fn=swap_to_gallery, inputs=pose_files, outputs=[uploaded_poses, clear_button_pose, pose_files]) 360 | 361 | remove_and_reupload_faces.click(fn=remove_back_to_files, outputs=[uploaded_faces, clear_button_face, face_files]) 362 | remove_and_reupload_poses.click(fn=remove_back_to_files, outputs=[uploaded_poses, clear_button_pose, pose_files]) 363 | 364 | submit.click( 365 | fn=remove_tips, 366 | outputs=usage_tips, 367 | ).then( 368 | fn=randomize_seed_fn, 369 | inputs=[seed, randomize_seed], 370 | outputs=seed, 371 | queue=False, 372 | api_name=False, 373 | ).then( 374 | fn=generate_image, 375 | inputs=[face_files, pose_files, prompt, negative_prompt, style, num_steps, identitynet_strength_ratio, adapter_strength_ratio, guidance_scale, seed], 376 | outputs=[gallery, usage_tips] 377 | ) 378 | 379 | gr.Examples( 380 | examples=get_example(), 381 | inputs=[face_files, prompt, style, negative_prompt], 382 | run_on_click=True, 383 | fn=upload_example_to_gallery, 384 | outputs=[uploaded_faces, clear_button_face, face_files], 385 | ) 386 | 387 | gr.Markdown(article) 388 | 389 | demo.launch() -------------------------------------------------------------------------------- /gradio_demo/requirements.txt: -------------------------------------------------------------------------------- 1 | diffusers==0.25.0 2 | torch==2.0.0 3 | torchvision==0.15.1 4 | transformers==4.36.2 5 | accelerate 6 | safetensors 7 | einops 8 | onnxruntime-gpu 9 | spaces==0.19.4 10 | omegaconf 11 | peft 12 | huggingface-hub==0.20.2 13 | opencv-python 14 | insightface -------------------------------------------------------------------------------- /gradio_demo/style_template.py: -------------------------------------------------------------------------------- 1 | style_list = [ 2 | { 3 | "name": "(No style)", 4 | "prompt": "{prompt}", 5 | "negative_prompt": "", 6 | }, 7 | { 8 | "name": "Watercolor", 9 | "prompt": "watercolor painting, {prompt}. vibrant, beautiful, painterly, detailed, textural, artistic", 10 | "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy", 11 | }, 12 | { 13 | "name": "Film Noir", 14 | "prompt": "film noir style, ink sketch|vector, {prompt} highly detailed, sharp focus, ultra sharpness, monochrome, high contrast, dramatic shadows, 1940s style, mysterious, cinematic", 15 | "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 16 | }, 17 | { 18 | "name": "Neon", 19 | "prompt": "masterpiece painting, buildings in the backdrop, kaleidoscope, lilac orange blue cream fuchsia bright vivid gradient colors, the scene is cinematic, {prompt}, emotional realism, double exposure, watercolor ink pencil, graded wash, color layering, magic realism, figurative painting, intricate motifs, organic tracery, polished", 20 | "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 21 | }, 22 | { 23 | "name": "Jungle", 24 | "prompt": 'waist-up "{prompt} in a Jungle" by Syd Mead, tangerine cold color palette, muted colors, detailed, 8k,photo r3al,dripping paint,3d toon style,3d style,Movie Still', 25 | "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 26 | }, 27 | { 28 | "name": "Mars", 29 | "prompt": "{prompt}, Post-apocalyptic. Mars Colony, Scavengers roam the wastelands searching for valuable resources, rovers, bright morning sunlight shining, (detailed) (intricate) (8k) (HDR) (cinematic lighting) (sharp focus)", 30 | "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 31 | }, 32 | { 33 | "name": "Vibrant Color", 34 | "prompt": "vibrant colorful, ink sketch|vector|2d colors, at nightfall, sharp focus, {prompt}, highly detailed, sharp focus, the clouds,colorful,ultra sharpness", 35 | "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 36 | }, 37 | { 38 | "name": "Snow", 39 | "prompt": "cinema 4d render, {prompt}, high contrast, vibrant and saturated, sico style, surrounded by magical glow,floating ice shards, snow crystals, cold, windy background, frozen natural landscape in background cinematic atmosphere,highly detailed, sharp focus, intricate design, 3d, unreal engine, octane render, CG best quality, highres, photorealistic, dramatic lighting, artstation, concept art, cinematic, epic Steven Spielberg movie still, sharp focus, smoke, sparks, art by pascal blanche and greg rutkowski and repin, trending on artstation, hyperrealism painting, matte painting, 4k resolution", 40 | "negative_prompt": "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green", 41 | }, 42 | { 43 | "name": "Line art", 44 | "prompt": "line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics", 45 | "negative_prompt": "anime, photorealistic, 35mm film, deformed, glitch, blurry, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, mutated, realism, realistic, impressionism, expressionism, oil, acrylic", 46 | }, 47 | ] 48 | 49 | styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list} -------------------------------------------------------------------------------- /infer.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import torch 3 | import numpy as np 4 | from PIL import Image 5 | 6 | from diffusers.utils import load_image 7 | from diffusers.models import ControlNetModel 8 | from diffusers import StableDiffusionXLPipeline 9 | 10 | from insightface.app import FaceAnalysis 11 | from .pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline, draw_kps 12 | 13 | def resize_img(input_image, max_side=1280, min_side=1024, size=None, 14 | pad_to_max_side=False, mode=Image.BILINEAR, base_pixel_number=64): 15 | 16 | w, h = input_image.size 17 | if size is not None: 18 | w_resize_new, h_resize_new = size 19 | else: 20 | ratio = min_side / min(h, w) 21 | w, h = round(ratio*w), round(ratio*h) 22 | ratio = max_side / max(h, w) 23 | input_image = input_image.resize([round(ratio*w), round(ratio*h)], mode) 24 | w_resize_new = (round(ratio * w) // base_pixel_number) * base_pixel_number 25 | h_resize_new = (round(ratio * h) // base_pixel_number) * base_pixel_number 26 | input_image = input_image.resize([w_resize_new, h_resize_new], mode) 27 | 28 | if pad_to_max_side: 29 | res = np.ones([max_side, max_side, 3], dtype=np.uint8) * 255 30 | offset_x = (max_side - w_resize_new) // 2 31 | offset_y = (max_side - h_resize_new) // 2 32 | res[offset_y:offset_y+h_resize_new, offset_x:offset_x+w_resize_new] = np.array(input_image) 33 | input_image = Image.fromarray(res) 34 | return input_image 35 | 36 | 37 | if __name__ == "__main__": 38 | 39 | app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) 40 | app.prepare(ctx_id=0, det_size=(640, 640)) 41 | 42 | # Path to InstantID models 43 | face_adapter = f'./checkpoints/ip-adapter.bin' 44 | controlnet_path = f'./checkpoints/ControlNetModel' 45 | 46 | # Load pipeline 47 | controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16, use_safetensors=True) 48 | 49 | base_model_path = '/nieta_fs/ops/models/checkpoint/sd_xl_base_1.0.safetensors' 50 | ckpt_cache_path = './tmp/tmpckpt.safetensors' 51 | StableDiffusionXLPipeline.from_single_file( 52 | pretrained_model_link_or_path=base_model_path, 53 | torch_dtype=torch.float16, 54 | cache_dir='./tmp', 55 | ).save_pretrained(ckpt_cache_path, safe_serialization=True) 56 | 57 | 58 | pipe = StableDiffusionXLInstantIDPipeline.from_pretrained( 59 | ckpt_cache_path, 60 | controlnet=controlnet, 61 | torch_dtype=torch.float16, 62 | ) 63 | pipe.cuda() 64 | pipe.load_ip_adapter_instantid(face_adapter) 65 | 66 | prompt = "anime film screenshot of a man, masterpiece, best quality" 67 | n_prompt = "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured (lowres, low quality, worst quality:1.2), (text:1.2), watermark, painting, drawing, illustration, glitch,deformed, mutated, cross-eyed, ugly, disfigured" 68 | 69 | face_image = load_image("./examples/yann-lecun_resize.jpg") 70 | face_image = resize_img(face_image) 71 | 72 | face_info = app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR)) 73 | 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 74 | face_emb = face_info['embedding'] 75 | face_kps = draw_kps(face_image, face_info['kps']) 76 | 77 | pipe.set_ip_adapter_scale(0.8) 78 | image = pipe( 79 | prompt=prompt, 80 | negative_prompt=n_prompt, 81 | image_embeds=face_emb, 82 | image=face_kps, 83 | controlnet_conditioning_scale=0.8, 84 | num_inference_steps=30, 85 | guidance_scale=5, 86 | ).images[0] 87 | 88 | image.save('result.jpg') -------------------------------------------------------------------------------- /ip_adapter/attention_processor.py: -------------------------------------------------------------------------------- 1 | # modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | 6 | try: 7 | import xformers 8 | import xformers.ops 9 | xformers_available = True 10 | except Exception as e: 11 | xformers_available = False 12 | 13 | 14 | 15 | class RegionControler(object): 16 | def __init__(self) -> None: 17 | self.prompt_image_conditioning = [] 18 | region_control = RegionControler() 19 | 20 | 21 | class AttnProcessor(nn.Module): 22 | r""" 23 | Default processor for performing attention-related computations. 24 | """ 25 | def __init__( 26 | self, 27 | hidden_size=None, 28 | cross_attention_dim=None, 29 | ): 30 | super().__init__() 31 | 32 | def __call__( 33 | self, 34 | attn, 35 | hidden_states, 36 | encoder_hidden_states=None, 37 | attention_mask=None, 38 | temb=None, 39 | ): 40 | residual = hidden_states 41 | 42 | if attn.spatial_norm is not None: 43 | hidden_states = attn.spatial_norm(hidden_states, temb) 44 | 45 | input_ndim = hidden_states.ndim 46 | 47 | if input_ndim == 4: 48 | batch_size, channel, height, width = hidden_states.shape 49 | hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) 50 | 51 | batch_size, sequence_length, _ = ( 52 | hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape 53 | ) 54 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) 55 | 56 | if attn.group_norm is not None: 57 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) 58 | 59 | query = attn.to_q(hidden_states) 60 | 61 | if encoder_hidden_states is None: 62 | encoder_hidden_states = hidden_states 63 | elif attn.norm_cross: 64 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) 65 | 66 | key = attn.to_k(encoder_hidden_states) 67 | value = attn.to_v(encoder_hidden_states) 68 | 69 | query = attn.head_to_batch_dim(query) 70 | key = attn.head_to_batch_dim(key) 71 | value = attn.head_to_batch_dim(value) 72 | 73 | attention_probs = attn.get_attention_scores(query, key, attention_mask) 74 | hidden_states = torch.bmm(attention_probs, value) 75 | hidden_states = attn.batch_to_head_dim(hidden_states) 76 | 77 | # linear proj 78 | hidden_states = attn.to_out[0](hidden_states) 79 | # dropout 80 | hidden_states = attn.to_out[1](hidden_states) 81 | 82 | if input_ndim == 4: 83 | hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width) 84 | 85 | if attn.residual_connection: 86 | hidden_states = hidden_states + residual 87 | 88 | hidden_states = hidden_states / attn.rescale_output_factor 89 | 90 | return hidden_states 91 | 92 | 93 | class IPAttnProcessor(nn.Module): 94 | r""" 95 | Attention processor for IP-Adapater. 96 | Args: 97 | hidden_size (`int`): 98 | The hidden size of the attention layer. 99 | cross_attention_dim (`int`): 100 | The number of channels in the `encoder_hidden_states`. 101 | scale (`float`, defaults to 1.0): 102 | the weight scale of image prompt. 103 | num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16): 104 | The context length of the image features. 105 | """ 106 | 107 | def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4): 108 | super().__init__() 109 | 110 | self.hidden_size = hidden_size 111 | self.cross_attention_dim = cross_attention_dim 112 | self.scale = scale 113 | self.num_tokens = num_tokens 114 | 115 | self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) 116 | self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) 117 | 118 | def __call__( 119 | self, 120 | attn, 121 | hidden_states, 122 | encoder_hidden_states=None, 123 | attention_mask=None, 124 | temb=None, 125 | ): 126 | residual = hidden_states 127 | 128 | if attn.spatial_norm is not None: 129 | hidden_states = attn.spatial_norm(hidden_states, temb) 130 | 131 | input_ndim = hidden_states.ndim 132 | 133 | if input_ndim == 4: 134 | batch_size, channel, height, width = hidden_states.shape 135 | hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) 136 | 137 | batch_size, sequence_length, _ = ( 138 | hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape 139 | ) 140 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) 141 | 142 | if attn.group_norm is not None: 143 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) 144 | 145 | query = attn.to_q(hidden_states) 146 | 147 | if encoder_hidden_states is None: 148 | encoder_hidden_states = hidden_states 149 | else: 150 | # get encoder_hidden_states, ip_hidden_states 151 | end_pos = encoder_hidden_states.shape[1] - self.num_tokens 152 | encoder_hidden_states, ip_hidden_states = encoder_hidden_states[:, :end_pos, :], encoder_hidden_states[:, end_pos:, :] 153 | if attn.norm_cross: 154 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) 155 | 156 | key = attn.to_k(encoder_hidden_states) 157 | value = attn.to_v(encoder_hidden_states) 158 | 159 | query = attn.head_to_batch_dim(query) 160 | key = attn.head_to_batch_dim(key) 161 | value = attn.head_to_batch_dim(value) 162 | 163 | if xformers_available: 164 | hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask) 165 | else: 166 | attention_probs = attn.get_attention_scores(query, key, attention_mask) 167 | hidden_states = torch.bmm(attention_probs, value) 168 | hidden_states = attn.batch_to_head_dim(hidden_states) 169 | 170 | # for ip-adapter 171 | ip_key = self.to_k_ip(ip_hidden_states) 172 | ip_value = self.to_v_ip(ip_hidden_states) 173 | 174 | ip_key = attn.head_to_batch_dim(ip_key) 175 | ip_value = attn.head_to_batch_dim(ip_value) 176 | 177 | if xformers_available: 178 | ip_hidden_states = self._memory_efficient_attention_xformers(query, ip_key, ip_value, None) 179 | else: 180 | ip_attention_probs = attn.get_attention_scores(query, ip_key, None) 181 | ip_hidden_states = torch.bmm(ip_attention_probs, ip_value) 182 | ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states) 183 | 184 | # region control 185 | if len(region_control.prompt_image_conditioning) == 1: 186 | region_mask = region_control.prompt_image_conditioning[0].get('region_mask', None) 187 | if region_mask is not None: 188 | h, w = region_mask.shape[:2] 189 | ratio = (h * w / query.shape[1]) ** 0.5 190 | mask = F.interpolate(region_mask[None, None], scale_factor=1/ratio, mode='nearest').reshape([1, -1, 1]) 191 | else: 192 | mask = torch.ones_like(ip_hidden_states) 193 | ip_hidden_states = ip_hidden_states * mask 194 | 195 | hidden_states = hidden_states + self.scale * ip_hidden_states 196 | 197 | # linear proj 198 | hidden_states = attn.to_out[0](hidden_states) 199 | # dropout 200 | hidden_states = attn.to_out[1](hidden_states) 201 | 202 | if input_ndim == 4: 203 | hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width) 204 | 205 | if attn.residual_connection: 206 | hidden_states = hidden_states + residual 207 | 208 | hidden_states = hidden_states / attn.rescale_output_factor 209 | 210 | return hidden_states 211 | 212 | 213 | def _memory_efficient_attention_xformers(self, query, key, value, attention_mask): 214 | # TODO attention_mask 215 | query = query.contiguous() 216 | key = key.contiguous() 217 | value = value.contiguous() 218 | hidden_states = xformers.ops.memory_efficient_attention(query, key, value, attn_bias=attention_mask) 219 | # hidden_states = self.reshape_batch_dim_to_heads(hidden_states) 220 | return hidden_states 221 | 222 | 223 | class AttnProcessor2_0(torch.nn.Module): 224 | r""" 225 | Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). 226 | """ 227 | def __init__( 228 | self, 229 | hidden_size=None, 230 | cross_attention_dim=None, 231 | ): 232 | super().__init__() 233 | if not hasattr(F, "scaled_dot_product_attention"): 234 | raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.") 235 | 236 | def __call__( 237 | self, 238 | attn, 239 | hidden_states, 240 | encoder_hidden_states=None, 241 | attention_mask=None, 242 | temb=None, 243 | ): 244 | residual = hidden_states 245 | 246 | if attn.spatial_norm is not None: 247 | hidden_states = attn.spatial_norm(hidden_states, temb) 248 | 249 | input_ndim = hidden_states.ndim 250 | 251 | if input_ndim == 4: 252 | batch_size, channel, height, width = hidden_states.shape 253 | hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) 254 | 255 | batch_size, sequence_length, _ = ( 256 | hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape 257 | ) 258 | 259 | if attention_mask is not None: 260 | attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) 261 | # scaled_dot_product_attention expects attention_mask shape to be 262 | # (batch, heads, source_length, target_length) 263 | attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1]) 264 | 265 | if attn.group_norm is not None: 266 | hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) 267 | 268 | query = attn.to_q(hidden_states) 269 | 270 | if encoder_hidden_states is None: 271 | encoder_hidden_states = hidden_states 272 | elif attn.norm_cross: 273 | encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) 274 | 275 | key = attn.to_k(encoder_hidden_states) 276 | value = attn.to_v(encoder_hidden_states) 277 | 278 | inner_dim = key.shape[-1] 279 | head_dim = inner_dim // attn.heads 280 | 281 | query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) 282 | 283 | key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) 284 | value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) 285 | 286 | # the output of sdp = (batch, num_heads, seq_len, head_dim) 287 | # TODO: add support for attn.scale when we move to Torch 2.1 288 | hidden_states = F.scaled_dot_product_attention( 289 | query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False 290 | ) 291 | 292 | hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) 293 | hidden_states = hidden_states.to(query.dtype) 294 | 295 | # linear proj 296 | hidden_states = attn.to_out[0](hidden_states) 297 | # dropout 298 | hidden_states = attn.to_out[1](hidden_states) 299 | 300 | if input_ndim == 4: 301 | hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width) 302 | 303 | if attn.residual_connection: 304 | hidden_states = hidden_states + residual 305 | 306 | hidden_states = hidden_states / attn.rescale_output_factor 307 | 308 | return hidden_states -------------------------------------------------------------------------------- /ip_adapter/resampler.py: -------------------------------------------------------------------------------- 1 | # modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py 2 | import math 3 | 4 | import torch 5 | import torch.nn as nn 6 | 7 | 8 | # FFN 9 | def FeedForward(dim, mult=4): 10 | inner_dim = int(dim * mult) 11 | return nn.Sequential( 12 | nn.LayerNorm(dim), 13 | nn.Linear(dim, inner_dim, bias=False), 14 | nn.GELU(), 15 | nn.Linear(inner_dim, dim, bias=False), 16 | ) 17 | 18 | 19 | def reshape_tensor(x, heads): 20 | bs, length, width = x.shape 21 | #(bs, length, width) --> (bs, length, n_heads, dim_per_head) 22 | x = x.view(bs, length, heads, -1) 23 | # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head) 24 | x = x.transpose(1, 2) 25 | # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head) 26 | x = x.reshape(bs, heads, length, -1) 27 | return x 28 | 29 | 30 | class PerceiverAttention(nn.Module): 31 | def __init__(self, *, dim, dim_head=64, heads=8): 32 | super().__init__() 33 | self.scale = dim_head**-0.5 34 | self.dim_head = dim_head 35 | self.heads = heads 36 | inner_dim = dim_head * heads 37 | 38 | self.norm1 = nn.LayerNorm(dim) 39 | self.norm2 = nn.LayerNorm(dim) 40 | 41 | self.to_q = nn.Linear(dim, inner_dim, bias=False) 42 | self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False) 43 | self.to_out = nn.Linear(inner_dim, dim, bias=False) 44 | 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) -------------------------------------------------------------------------------- /ip_adapter/utils.py: -------------------------------------------------------------------------------- 1 | import torch.nn.functional as F 2 | 3 | 4 | def is_torch2_available(): 5 | return hasattr(F, "scaled_dot_product_attention") 6 | -------------------------------------------------------------------------------- /models/__put_antelopev2_here__: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huxiuhan/ComfyUI-InstantID/c725820fcae81cfb7bddd6e80d5d19df634eb050/models/__put_antelopev2_here__ -------------------------------------------------------------------------------- /nodes.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import os 3 | import torch 4 | from safetensors.torch import load_file 5 | from torchvision.transforms import ToTensor 6 | from comfy.model_management import get_torch_device 7 | from .pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline, draw_kps 8 | from .infer import resize_img 9 | import folder_paths 10 | import cv2 11 | import numpy as np 12 | from PIL import Image 13 | 14 | from diffusers.utils import load_image 15 | from diffusers.models import ControlNetModel 16 | from diffusers import StableDiffusionXLPipeline 17 | 18 | from insightface.app import FaceAnalysis 19 | 20 | CUSTOM_NODE_CWD = os.path.dirname(os.path.realpath(__file__)) 21 | 22 | class InstantIDSampler: 23 | def __init__(self): 24 | self.torch_device = get_torch_device() 25 | self.tmp_dir = folder_paths.get_temp_directory() 26 | self.face_app = None 27 | self.controlnet = None 28 | self.previous_ckpt = None 29 | self.pipe = None 30 | 31 | @classmethod 32 | def INPUT_TYPES(s): 33 | return { 34 | "required": { 35 | "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), 36 | "positive": ("STRING", {"multiline": True}), 37 | "negative": ("STRING", {"multiline": True}), 38 | "steps": ("INT", {"default": 30, "min": 1, "max": 10000}), 39 | "cfg": ("FLOAT", {"default": 5, "min": 0.0, "max": 100.0}), 40 | "strength": ("FLOAT", {"default": 0.8, "min": 0.0, "max": 1.0}), 41 | "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}), 42 | "image" : ("IMAGE", ) 43 | } 44 | } 45 | 46 | RETURN_TYPES = ("IMAGE",) 47 | 48 | FUNCTION = "sample" 49 | 50 | CATEGORY = "Instant ID" 51 | 52 | 53 | def sample(self, ckpt_name, positive, negative, steps, cfg, strength, seed, image): 54 | 55 | print("Instant ID Current Working Dir:", CUSTOM_NODE_CWD) 56 | 57 | if self.face_app is None: 58 | app = FaceAnalysis(name='antelopev2', root=CUSTOM_NODE_CWD, providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) 59 | app.prepare(ctx_id=0, det_size=(640, 640)) 60 | self.face_app = app 61 | print("Instant ID Insightface App Loaded.") 62 | 63 | # Path to InstantID models 64 | face_adapter = os.path.join(CUSTOM_NODE_CWD, f'./checkpoints/ip-adapter.bin') 65 | controlnet_path = os.path.join(CUSTOM_NODE_CWD, f'./checkpoints/ControlNetModel') 66 | 67 | # Load pipeline 68 | if self.controlnet is None: 69 | self.controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16, use_safetensors=True) 70 | print("Instant ID Controlnet Loaded.") 71 | 72 | # prepare ckpt for diffusers 73 | 74 | if self.previous_ckpt != ckpt_name: 75 | ckpt_cache_path = os.path.join(self.tmp_dir, ckpt_name) 76 | StableDiffusionXLPipeline.from_single_file( 77 | pretrained_model_link_or_path=folder_paths.get_full_path("checkpoints", ckpt_name), 78 | torch_dtype=torch.float16, 79 | cache_dir=self.tmp_dir, 80 | ).save_pretrained(ckpt_cache_path, safe_serialization=True) 81 | 82 | self.previous_ckpt = ckpt_name 83 | self.pipe = StableDiffusionXLInstantIDPipeline.from_pretrained( 84 | ckpt_cache_path, 85 | controlnet=self.controlnet, 86 | torch_dtype=torch.float16, 87 | ) 88 | self.pipe.cuda() 89 | self.pipe.load_ip_adapter_instantid(face_adapter) 90 | print("Instant ID Ckpt Reloaded.") 91 | 92 | 93 | prompt = positive 94 | n_prompt = negative 95 | 96 | face_image = Image.fromarray(np.clip(255. * image[0].cpu().numpy(), 0, 255).astype(np.uint8)) 97 | face_image = resize_img(face_image) 98 | 99 | face_info = self.face_app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR)) 100 | if len(face_info) < 1: 101 | raise ValueError("Cannot find any face.") 102 | 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 103 | face_emb = face_info['embedding'] 104 | face_kps = draw_kps(face_image, face_info['kps']) 105 | print("Instant ID Face Info Updated.") 106 | 107 | 108 | self.pipe.set_ip_adapter_scale(strength) 109 | 110 | g_cpu = torch.Generator() 111 | g_cpu.manual_seed(seed) 112 | result = self.pipe( 113 | prompt=prompt, 114 | negative_prompt=n_prompt, 115 | image_embeds=face_emb, 116 | image=face_kps, 117 | controlnet_conditioning_scale=strength, 118 | num_inference_steps=steps, 119 | guidance_scale=cfg, 120 | generator=g_cpu 121 | ).images 122 | 123 | def convert_images_to_tensors(images: list[Image.Image]): 124 | return torch.stack([np.transpose(ToTensor()(image), (1, 2, 0)) for image in images]) 125 | 126 | return (convert_images_to_tensors(result),) 127 | -------------------------------------------------------------------------------- /pipeline_stable_diffusion_xl_instantid.py: -------------------------------------------------------------------------------- 1 | # Copyright 2024 The InstantX Team. 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 | 16 | from typing import Any, Callable, Dict, List, Optional, Tuple, Union 17 | 18 | import cv2 19 | import math 20 | 21 | import numpy as np 22 | import PIL.Image 23 | import torch 24 | import torch.nn.functional as F 25 | 26 | from diffusers.image_processor import PipelineImageInput 27 | 28 | from diffusers.models import ControlNetModel 29 | 30 | from diffusers.utils import ( 31 | deprecate, 32 | logging, 33 | replace_example_docstring, 34 | ) 35 | from diffusers.utils.torch_utils import is_compiled_module, is_torch_version 36 | from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput 37 | 38 | from diffusers import StableDiffusionXLControlNetPipeline 39 | from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel 40 | from diffusers.utils.import_utils import is_xformers_available 41 | 42 | from .ip_adapter.resampler import Resampler 43 | from .ip_adapter.utils import is_torch2_available 44 | 45 | from .ip_adapter.attention_processor import AttnProcessor, IPAttnProcessor 46 | 47 | logger = logging.get_logger(__name__) # pylint: disable=invalid-name 48 | 49 | 50 | EXAMPLE_DOC_STRING = """ 51 | Examples: 52 | ```py 53 | >>> # !pip install opencv-python transformers accelerate insightface 54 | >>> import diffusers 55 | >>> from diffusers.utils import load_image 56 | >>> from diffusers.models import ControlNetModel 57 | 58 | >>> import cv2 59 | >>> import torch 60 | >>> import numpy as np 61 | >>> from PIL import Image 62 | 63 | >>> from insightface.app import FaceAnalysis 64 | >>> from pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline, draw_kps 65 | 66 | >>> # download 'antelopev2' under ./models 67 | >>> app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) 68 | >>> app.prepare(ctx_id=0, det_size=(640, 640)) 69 | 70 | >>> # download models under ./checkpoints 71 | >>> face_adapter = f'./checkpoints/ip-adapter.bin' 72 | >>> controlnet_path = f'./checkpoints/ControlNetModel' 73 | 74 | >>> # load IdentityNet 75 | >>> controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16) 76 | 77 | >>> pipe = StableDiffusionXLInstantIDPipeline.from_pretrained( 78 | ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16 79 | ... ) 80 | >>> pipe.cuda() 81 | 82 | >>> # load adapter 83 | >>> pipe.load_ip_adapter_instantid(face_adapter) 84 | 85 | >>> prompt = "analog film photo of a man. faded film, desaturated, 35mm photo, grainy, vignette, vintage, Kodachrome, Lomography, stained, highly detailed, found footage, masterpiece, best quality" 86 | >>> negative_prompt = "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured (lowres, low quality, worst quality:1.2), (text:1.2), watermark, painting, drawing, illustration, glitch,deformed, mutated, cross-eyed, ugly, disfigured" 87 | 88 | >>> # load an image 89 | >>> image = load_image("your-example.jpg") 90 | 91 | >>> face_info = app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))[-1] 92 | >>> face_emb = face_info['embedding'] 93 | >>> face_kps = draw_kps(face_image, face_info['kps']) 94 | 95 | >>> pipe.set_ip_adapter_scale(0.8) 96 | 97 | >>> # generate image 98 | >>> image = pipe( 99 | ... prompt, image_embeds=face_emb, image=face_kps, controlnet_conditioning_scale=0.8 100 | ... ).images[0] 101 | ``` 102 | """ 103 | 104 | def draw_kps(image_pil, kps, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]): 105 | 106 | stickwidth = 4 107 | limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]]) 108 | kps = np.array(kps) 109 | 110 | w, h = image_pil.size 111 | out_img = np.zeros([h, w, 3]) 112 | 113 | for i in range(len(limbSeq)): 114 | index = limbSeq[i] 115 | color = color_list[index[0]] 116 | 117 | x = kps[index][:, 0] 118 | y = kps[index][:, 1] 119 | length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5 120 | angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1])) 121 | polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1) 122 | out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color) 123 | out_img = (out_img * 0.6).astype(np.uint8) 124 | 125 | for idx_kp, kp in enumerate(kps): 126 | color = color_list[idx_kp] 127 | x, y = kp 128 | out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1) 129 | 130 | out_img_pil = PIL.Image.fromarray(out_img.astype(np.uint8)) 131 | return out_img_pil 132 | 133 | class StableDiffusionXLInstantIDPipeline(StableDiffusionXLControlNetPipeline): 134 | 135 | def cuda(self, dtype=torch.float16, use_xformers=False): 136 | self.to('cuda', dtype) 137 | 138 | if hasattr(self, 'image_proj_model'): 139 | self.image_proj_model.to(self.unet.device).to(self.unet.dtype) 140 | 141 | if use_xformers: 142 | if is_xformers_available(): 143 | import xformers 144 | from packaging import version 145 | 146 | xformers_version = version.parse(xformers.__version__) 147 | if xformers_version == version.parse("0.0.16"): 148 | logger.warn( 149 | "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details." 150 | ) 151 | self.enable_xformers_memory_efficient_attention() 152 | else: 153 | raise ValueError("xformers is not available. Make sure it is installed correctly") 154 | 155 | def load_ip_adapter_instantid(self, model_ckpt, image_emb_dim=512, num_tokens=16, scale=0.5): 156 | self.set_image_proj_model(model_ckpt, image_emb_dim, num_tokens) 157 | self.set_ip_adapter(model_ckpt, num_tokens, scale) 158 | 159 | def set_image_proj_model(self, model_ckpt, image_emb_dim=512, num_tokens=16): 160 | 161 | image_proj_model = Resampler( 162 | dim=1280, 163 | depth=4, 164 | dim_head=64, 165 | heads=20, 166 | num_queries=num_tokens, 167 | embedding_dim=image_emb_dim, 168 | output_dim=self.unet.config.cross_attention_dim, 169 | ff_mult=4, 170 | ) 171 | 172 | image_proj_model.eval() 173 | 174 | self.image_proj_model = image_proj_model.to(self.device, dtype=self.dtype) 175 | state_dict = torch.load(model_ckpt, map_location="cpu") 176 | if 'image_proj' in state_dict: 177 | state_dict = state_dict["image_proj"] 178 | self.image_proj_model.load_state_dict(state_dict) 179 | 180 | self.image_proj_model_in_features = image_emb_dim 181 | 182 | def set_ip_adapter(self, model_ckpt, num_tokens, scale): 183 | 184 | unet = self.unet 185 | attn_procs = {} 186 | for name in unet.attn_processors.keys(): 187 | cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim 188 | if name.startswith("mid_block"): 189 | hidden_size = unet.config.block_out_channels[-1] 190 | elif name.startswith("up_blocks"): 191 | block_id = int(name[len("up_blocks.")]) 192 | hidden_size = list(reversed(unet.config.block_out_channels))[block_id] 193 | elif name.startswith("down_blocks"): 194 | block_id = int(name[len("down_blocks.")]) 195 | hidden_size = unet.config.block_out_channels[block_id] 196 | if cross_attention_dim is None: 197 | attn_procs[name] = AttnProcessor().to(unet.device, dtype=unet.dtype) 198 | else: 199 | attn_procs[name] = IPAttnProcessor(hidden_size=hidden_size, 200 | cross_attention_dim=cross_attention_dim, 201 | scale=scale, 202 | num_tokens=num_tokens).to(unet.device, dtype=unet.dtype) 203 | unet.set_attn_processor(attn_procs) 204 | 205 | state_dict = torch.load(model_ckpt, map_location="cpu") 206 | ip_layers = torch.nn.ModuleList(self.unet.attn_processors.values()) 207 | if 'ip_adapter' in state_dict: 208 | state_dict = state_dict['ip_adapter'] 209 | ip_layers.load_state_dict(state_dict) 210 | 211 | def set_ip_adapter_scale(self, scale): 212 | unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet 213 | for attn_processor in unet.attn_processors.values(): 214 | if isinstance(attn_processor, IPAttnProcessor): 215 | attn_processor.scale = scale 216 | 217 | def _encode_prompt_image_emb(self, prompt_image_emb, device, dtype, do_classifier_free_guidance): 218 | 219 | if isinstance(prompt_image_emb, torch.Tensor): 220 | prompt_image_emb = prompt_image_emb.clone().detach() 221 | else: 222 | prompt_image_emb = torch.tensor(prompt_image_emb) 223 | 224 | prompt_image_emb = prompt_image_emb.to(device=device, dtype=dtype) 225 | prompt_image_emb = prompt_image_emb.reshape([1, -1, self.image_proj_model_in_features]) 226 | 227 | if do_classifier_free_guidance: 228 | prompt_image_emb = torch.cat([torch.zeros_like(prompt_image_emb), prompt_image_emb], dim=0) 229 | else: 230 | prompt_image_emb = torch.cat([prompt_image_emb], dim=0) 231 | 232 | prompt_image_emb = self.image_proj_model(prompt_image_emb) 233 | return prompt_image_emb 234 | 235 | @torch.no_grad() 236 | @replace_example_docstring(EXAMPLE_DOC_STRING) 237 | def __call__( 238 | self, 239 | prompt: Union[str, List[str]] = None, 240 | prompt_2: Optional[Union[str, List[str]]] = None, 241 | image: PipelineImageInput = None, 242 | height: Optional[int] = None, 243 | width: Optional[int] = None, 244 | num_inference_steps: int = 50, 245 | guidance_scale: float = 5.0, 246 | negative_prompt: Optional[Union[str, List[str]]] = None, 247 | negative_prompt_2: Optional[Union[str, List[str]]] = None, 248 | num_images_per_prompt: Optional[int] = 1, 249 | eta: float = 0.0, 250 | generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, 251 | latents: Optional[torch.FloatTensor] = None, 252 | prompt_embeds: Optional[torch.FloatTensor] = None, 253 | negative_prompt_embeds: Optional[torch.FloatTensor] = None, 254 | pooled_prompt_embeds: Optional[torch.FloatTensor] = None, 255 | negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None, 256 | image_embeds: Optional[torch.FloatTensor] = None, 257 | output_type: Optional[str] = "pil", 258 | return_dict: bool = True, 259 | cross_attention_kwargs: Optional[Dict[str, Any]] = None, 260 | controlnet_conditioning_scale: Union[float, List[float]] = 1.0, 261 | guess_mode: bool = False, 262 | control_guidance_start: Union[float, List[float]] = 0.0, 263 | control_guidance_end: Union[float, List[float]] = 1.0, 264 | original_size: Tuple[int, int] = None, 265 | crops_coords_top_left: Tuple[int, int] = (0, 0), 266 | target_size: Tuple[int, int] = None, 267 | negative_original_size: Optional[Tuple[int, int]] = None, 268 | negative_crops_coords_top_left: Tuple[int, int] = (0, 0), 269 | negative_target_size: Optional[Tuple[int, int]] = None, 270 | clip_skip: Optional[int] = None, 271 | callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None, 272 | callback_on_step_end_tensor_inputs: List[str] = ["latents"], 273 | **kwargs, 274 | ): 275 | r""" 276 | The call function to the pipeline for generation. 277 | 278 | Args: 279 | prompt (`str` or `List[str]`, *optional*): 280 | The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. 281 | prompt_2 (`str` or `List[str]`, *optional*): 282 | The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is 283 | used in both text-encoders. 284 | image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,: 285 | `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`): 286 | The ControlNet input condition to provide guidance to the `unet` for generation. If the type is 287 | specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be 288 | accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height 289 | and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in 290 | `init`, images must be passed as a list such that each element of the list can be correctly batched for 291 | input to a single ControlNet. 292 | height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): 293 | The height in pixels of the generated image. Anything below 512 pixels won't work well for 294 | [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 295 | and checkpoints that are not specifically fine-tuned on low resolutions. 296 | width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): 297 | The width in pixels of the generated image. Anything below 512 pixels won't work well for 298 | [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) 299 | and checkpoints that are not specifically fine-tuned on low resolutions. 300 | num_inference_steps (`int`, *optional*, defaults to 50): 301 | The number of denoising steps. More denoising steps usually lead to a higher quality image at the 302 | expense of slower inference. 303 | guidance_scale (`float`, *optional*, defaults to 5.0): 304 | A higher guidance scale value encourages the model to generate images closely linked to the text 305 | `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`. 306 | negative_prompt (`str` or `List[str]`, *optional*): 307 | The prompt or prompts to guide what to not include in image generation. If not defined, you need to 308 | pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). 309 | negative_prompt_2 (`str` or `List[str]`, *optional*): 310 | The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2` 311 | and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders. 312 | num_images_per_prompt (`int`, *optional*, defaults to 1): 313 | The number of images to generate per prompt. 314 | eta (`float`, *optional*, defaults to 0.0): 315 | Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies 316 | to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers. 317 | generator (`torch.Generator` or `List[torch.Generator]`, *optional*): 318 | A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make 319 | generation deterministic. 320 | latents (`torch.FloatTensor`, *optional*): 321 | Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image 322 | generation. Can be used to tweak the same generation with different prompts. If not provided, a latents 323 | tensor is generated by sampling using the supplied random `generator`. 324 | prompt_embeds (`torch.FloatTensor`, *optional*): 325 | Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not 326 | provided, text embeddings are generated from the `prompt` input argument. 327 | negative_prompt_embeds (`torch.FloatTensor`, *optional*): 328 | Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If 329 | not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument. 330 | pooled_prompt_embeds (`torch.FloatTensor`, *optional*): 331 | Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If 332 | not provided, pooled text embeddings are generated from `prompt` input argument. 333 | negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*): 334 | Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt 335 | weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input 336 | argument. 337 | image_embeds (`torch.FloatTensor`, *optional*): 338 | Pre-generated image embeddings. 339 | output_type (`str`, *optional*, defaults to `"pil"`): 340 | The output format of the generated image. Choose between `PIL.Image` or `np.array`. 341 | return_dict (`bool`, *optional*, defaults to `True`): 342 | Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a 343 | plain tuple. 344 | cross_attention_kwargs (`dict`, *optional*): 345 | A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in 346 | [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). 347 | controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0): 348 | The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added 349 | to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set 350 | the corresponding scale as a list. 351 | guess_mode (`bool`, *optional*, defaults to `False`): 352 | The ControlNet encoder tries to recognize the content of the input image even if you remove all 353 | prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended. 354 | control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0): 355 | The percentage of total steps at which the ControlNet starts applying. 356 | control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0): 357 | The percentage of total steps at which the ControlNet stops applying. 358 | original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): 359 | If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled. 360 | `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as 361 | explained in section 2.2 of 362 | [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). 363 | crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)): 364 | `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position 365 | `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting 366 | `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of 367 | [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). 368 | target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): 369 | For most cases, `target_size` should be set to the desired height and width of the generated image. If 370 | not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in 371 | section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). 372 | negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): 373 | To negatively condition the generation process based on a specific image resolution. Part of SDXL's 374 | micro-conditioning as explained in section 2.2 of 375 | [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more 376 | information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. 377 | negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)): 378 | To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's 379 | micro-conditioning as explained in section 2.2 of 380 | [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more 381 | information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. 382 | negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)): 383 | To negatively condition the generation process based on a target image resolution. It should be as same 384 | as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of 385 | [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more 386 | information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208. 387 | clip_skip (`int`, *optional*): 388 | Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that 389 | the output of the pre-final layer will be used for computing the prompt embeddings. 390 | callback_on_step_end (`Callable`, *optional*): 391 | A function that calls at the end of each denoising steps during the inference. The function is called 392 | with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, 393 | callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by 394 | `callback_on_step_end_tensor_inputs`. 395 | callback_on_step_end_tensor_inputs (`List`, *optional*): 396 | The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list 397 | will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the 398 | `._callback_tensor_inputs` attribute of your pipeine class. 399 | 400 | Examples: 401 | 402 | Returns: 403 | [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: 404 | If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, 405 | otherwise a `tuple` is returned containing the output images. 406 | """ 407 | 408 | callback = kwargs.pop("callback", None) 409 | callback_steps = kwargs.pop("callback_steps", None) 410 | 411 | if callback is not None: 412 | deprecate( 413 | "callback", 414 | "1.0.0", 415 | "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`", 416 | ) 417 | if callback_steps is not None: 418 | deprecate( 419 | "callback_steps", 420 | "1.0.0", 421 | "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`", 422 | ) 423 | 424 | controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet 425 | 426 | # align format for control guidance 427 | if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list): 428 | control_guidance_start = len(control_guidance_end) * [control_guidance_start] 429 | elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list): 430 | control_guidance_end = len(control_guidance_start) * [control_guidance_end] 431 | elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list): 432 | mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1 433 | control_guidance_start, control_guidance_end = ( 434 | mult * [control_guidance_start], 435 | mult * [control_guidance_end], 436 | ) 437 | 438 | # 1. Check inputs. Raise error if not correct 439 | self.check_inputs( 440 | prompt, 441 | prompt_2, 442 | image, 443 | callback_steps, 444 | negative_prompt, 445 | negative_prompt_2, 446 | prompt_embeds, 447 | negative_prompt_embeds, 448 | pooled_prompt_embeds, 449 | negative_pooled_prompt_embeds, 450 | controlnet_conditioning_scale, 451 | control_guidance_start, 452 | control_guidance_end, 453 | callback_on_step_end_tensor_inputs, 454 | ) 455 | 456 | self._guidance_scale = guidance_scale 457 | self._clip_skip = clip_skip 458 | self._cross_attention_kwargs = cross_attention_kwargs 459 | 460 | # 2. Define call parameters 461 | if prompt is not None and isinstance(prompt, str): 462 | batch_size = 1 463 | elif prompt is not None and isinstance(prompt, list): 464 | batch_size = len(prompt) 465 | else: 466 | batch_size = prompt_embeds.shape[0] 467 | 468 | device = self._execution_device 469 | 470 | if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float): 471 | controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets) 472 | 473 | global_pool_conditions = ( 474 | controlnet.config.global_pool_conditions 475 | if isinstance(controlnet, ControlNetModel) 476 | else controlnet.nets[0].config.global_pool_conditions 477 | ) 478 | guess_mode = guess_mode or global_pool_conditions 479 | 480 | # 3.1 Encode input prompt 481 | text_encoder_lora_scale = ( 482 | self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None 483 | ) 484 | ( 485 | prompt_embeds, 486 | negative_prompt_embeds, 487 | pooled_prompt_embeds, 488 | negative_pooled_prompt_embeds, 489 | ) = self.encode_prompt( 490 | prompt, 491 | prompt_2, 492 | device, 493 | num_images_per_prompt, 494 | self.do_classifier_free_guidance, 495 | negative_prompt, 496 | negative_prompt_2, 497 | prompt_embeds=prompt_embeds, 498 | negative_prompt_embeds=negative_prompt_embeds, 499 | pooled_prompt_embeds=pooled_prompt_embeds, 500 | negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, 501 | lora_scale=text_encoder_lora_scale, 502 | clip_skip=self.clip_skip, 503 | ) 504 | 505 | # 3.2 Encode image prompt 506 | prompt_image_emb = self._encode_prompt_image_emb(image_embeds, 507 | device, 508 | self.unet.dtype, 509 | self.do_classifier_free_guidance) 510 | 511 | # 4. Prepare image 512 | if isinstance(controlnet, ControlNetModel): 513 | image = self.prepare_image( 514 | image=image, 515 | width=width, 516 | height=height, 517 | batch_size=batch_size * num_images_per_prompt, 518 | num_images_per_prompt=num_images_per_prompt, 519 | device=device, 520 | dtype=controlnet.dtype, 521 | do_classifier_free_guidance=self.do_classifier_free_guidance, 522 | guess_mode=guess_mode, 523 | ) 524 | height, width = image.shape[-2:] 525 | elif isinstance(controlnet, MultiControlNetModel): 526 | images = [] 527 | 528 | for image_ in image: 529 | image_ = self.prepare_image( 530 | image=image_, 531 | width=width, 532 | height=height, 533 | batch_size=batch_size * num_images_per_prompt, 534 | num_images_per_prompt=num_images_per_prompt, 535 | device=device, 536 | dtype=controlnet.dtype, 537 | do_classifier_free_guidance=self.do_classifier_free_guidance, 538 | guess_mode=guess_mode, 539 | ) 540 | 541 | images.append(image_) 542 | 543 | image = images 544 | height, width = image[0].shape[-2:] 545 | else: 546 | assert False 547 | 548 | # 5. Prepare timesteps 549 | self.scheduler.set_timesteps(num_inference_steps, device=device) 550 | timesteps = self.scheduler.timesteps 551 | self._num_timesteps = len(timesteps) 552 | 553 | # 6. Prepare latent variables 554 | num_channels_latents = self.unet.config.in_channels 555 | latents = self.prepare_latents( 556 | batch_size * num_images_per_prompt, 557 | num_channels_latents, 558 | height, 559 | width, 560 | prompt_embeds.dtype, 561 | device, 562 | generator, 563 | latents, 564 | ) 565 | 566 | # 6.5 Optionally get Guidance Scale Embedding 567 | timestep_cond = None 568 | if self.unet.config.time_cond_proj_dim is not None: 569 | guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt) 570 | timestep_cond = self.get_guidance_scale_embedding( 571 | guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim 572 | ).to(device=device, dtype=latents.dtype) 573 | 574 | # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline 575 | extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) 576 | 577 | # 7.1 Create tensor stating which controlnets to keep 578 | controlnet_keep = [] 579 | for i in range(len(timesteps)): 580 | keeps = [ 581 | 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e) 582 | for s, e in zip(control_guidance_start, control_guidance_end) 583 | ] 584 | controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps) 585 | 586 | # 7.2 Prepare added time ids & embeddings 587 | if isinstance(image, list): 588 | original_size = original_size or image[0].shape[-2:] 589 | else: 590 | original_size = original_size or image.shape[-2:] 591 | target_size = target_size or (height, width) 592 | 593 | add_text_embeds = pooled_prompt_embeds 594 | if self.text_encoder_2 is None: 595 | text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1]) 596 | else: 597 | text_encoder_projection_dim = self.text_encoder_2.config.projection_dim 598 | 599 | add_time_ids = self._get_add_time_ids( 600 | original_size, 601 | crops_coords_top_left, 602 | target_size, 603 | dtype=prompt_embeds.dtype, 604 | text_encoder_projection_dim=text_encoder_projection_dim, 605 | ) 606 | 607 | if negative_original_size is not None and negative_target_size is not None: 608 | negative_add_time_ids = self._get_add_time_ids( 609 | negative_original_size, 610 | negative_crops_coords_top_left, 611 | negative_target_size, 612 | dtype=prompt_embeds.dtype, 613 | text_encoder_projection_dim=text_encoder_projection_dim, 614 | ) 615 | else: 616 | negative_add_time_ids = add_time_ids 617 | 618 | if self.do_classifier_free_guidance: 619 | prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0) 620 | add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0) 621 | add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0) 622 | 623 | prompt_embeds = prompt_embeds.to(device) 624 | add_text_embeds = add_text_embeds.to(device) 625 | add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1) 626 | encoder_hidden_states = torch.cat([prompt_embeds, prompt_image_emb], dim=1) 627 | 628 | # 8. Denoising loop 629 | num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order 630 | is_unet_compiled = is_compiled_module(self.unet) 631 | is_controlnet_compiled = is_compiled_module(self.controlnet) 632 | is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1") 633 | 634 | with self.progress_bar(total=num_inference_steps) as progress_bar: 635 | for i, t in enumerate(timesteps): 636 | # Relevant thread: 637 | # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428 638 | if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1: 639 | torch._inductor.cudagraph_mark_step_begin() 640 | # expand the latents if we are doing classifier free guidance 641 | latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents 642 | latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) 643 | 644 | added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids} 645 | 646 | # controlnet(s) inference 647 | if guess_mode and self.do_classifier_free_guidance: 648 | # Infer ControlNet only for the conditional batch. 649 | control_model_input = latents 650 | control_model_input = self.scheduler.scale_model_input(control_model_input, t) 651 | controlnet_prompt_embeds = prompt_embeds.chunk(2)[1] 652 | controlnet_added_cond_kwargs = { 653 | "text_embeds": add_text_embeds.chunk(2)[1], 654 | "time_ids": add_time_ids.chunk(2)[1], 655 | } 656 | else: 657 | control_model_input = latent_model_input 658 | controlnet_prompt_embeds = prompt_embeds 659 | controlnet_added_cond_kwargs = added_cond_kwargs 660 | 661 | if isinstance(controlnet_keep[i], list): 662 | cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])] 663 | else: 664 | controlnet_cond_scale = controlnet_conditioning_scale 665 | if isinstance(controlnet_cond_scale, list): 666 | controlnet_cond_scale = controlnet_cond_scale[0] 667 | cond_scale = controlnet_cond_scale * controlnet_keep[i] 668 | 669 | down_block_res_samples, mid_block_res_sample = self.controlnet( 670 | control_model_input, 671 | t, 672 | encoder_hidden_states=prompt_image_emb, 673 | controlnet_cond=image, 674 | conditioning_scale=cond_scale, 675 | guess_mode=guess_mode, 676 | added_cond_kwargs=controlnet_added_cond_kwargs, 677 | return_dict=False, 678 | ) 679 | 680 | if guess_mode and self.do_classifier_free_guidance: 681 | # Infered ControlNet only for the conditional batch. 682 | # To apply the output of ControlNet to both the unconditional and conditional batches, 683 | # add 0 to the unconditional batch to keep it unchanged. 684 | down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples] 685 | mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample]) 686 | 687 | # predict the noise residual 688 | noise_pred = self.unet( 689 | latent_model_input, 690 | t, 691 | encoder_hidden_states=encoder_hidden_states, 692 | timestep_cond=timestep_cond, 693 | cross_attention_kwargs=self.cross_attention_kwargs, 694 | down_block_additional_residuals=down_block_res_samples, 695 | mid_block_additional_residual=mid_block_res_sample, 696 | added_cond_kwargs=added_cond_kwargs, 697 | return_dict=False, 698 | )[0] 699 | 700 | # perform guidance 701 | if self.do_classifier_free_guidance: 702 | noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) 703 | noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) 704 | 705 | # compute the previous noisy sample x_t -> x_t-1 706 | latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] 707 | 708 | if callback_on_step_end is not None: 709 | callback_kwargs = {} 710 | for k in callback_on_step_end_tensor_inputs: 711 | callback_kwargs[k] = locals()[k] 712 | callback_outputs = callback_on_step_end(self, i, t, callback_kwargs) 713 | 714 | latents = callback_outputs.pop("latents", latents) 715 | prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds) 716 | negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds) 717 | 718 | # call the callback, if provided 719 | if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): 720 | progress_bar.update() 721 | if callback is not None and i % callback_steps == 0: 722 | step_idx = i // getattr(self.scheduler, "order", 1) 723 | callback(step_idx, t, latents) 724 | 725 | if not output_type == "latent": 726 | # make sure the VAE is in float32 mode, as it overflows in float16 727 | needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast 728 | if needs_upcasting: 729 | self.upcast_vae() 730 | latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype) 731 | 732 | image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] 733 | 734 | # cast back to fp16 if needed 735 | if needs_upcasting: 736 | self.vae.to(dtype=torch.float16) 737 | else: 738 | image = latents 739 | 740 | if not output_type == "latent": 741 | # apply watermark if available 742 | if self.watermark is not None: 743 | image = self.watermark.apply_watermark(image) 744 | 745 | image = self.image_processor.postprocess(image, output_type=output_type) 746 | 747 | # Offload all models 748 | self.maybe_free_model_hooks() 749 | 750 | if not return_dict: 751 | return (image,) 752 | 753 | return StableDiffusionXLPipelineOutput(images=image) 754 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python 2 | transformers 3 | accelerate 4 | insightface 5 | safetensors 6 | diffusers[torch] 7 | omegaconf 8 | ip_adapter --------------------------------------------------------------------------------