├── .gitignore ├── LICENSE ├── README.md ├── lib_layerdiffusion ├── enums.py ├── models.py └── utils.py └── scripts └── forge_layerdiffusion.py /.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 | # sd-forge-layerdiffusion 2 | 3 | *(update Feb29: the name of this repo will change to "sd-forge-layerdiffuse" at Mar 3)* 4 | 5 | Transparent Image Layer Diffusion using Latent Transparency 6 | 7 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/36598904-ae5f-4578-87d3-4b496e11dcc5) 8 | 9 | This is a WIP extension for SD WebUI [(via Forge)](https://github.com/lllyasviel/stable-diffusion-webui-forge) to generate transparent images and layers. 10 | 11 | The image generating and basic layer functionality is working now, but **the transparent img2img is not finished yet (will finish in about one week)**. 12 | 13 | This code base is highly dynamic and may change a lot in the next month. If you are from professional content creation studio and need all previous results to be strictly reproduced, you may consider backup files during each update. 14 | 15 | # Before You Start 16 | 17 | Because many people may be curious about how the latent preview looks like during a transparent diffusion process, I recorded a video so that you can see it before you download the models and extensions: 18 | 19 | https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/e93b71d1-3560-48e2-a970-0b8efbfebb42 20 | 21 | You can see that the native transparent diffusion can process transparent glass, semi-transparent glowing effects, etc, that are not possible with simple background removal methods. Native transparent diffusion also gives you detailed fur, hair, whiskers, and detailed structure like that skeleton. 22 | 23 | # Model Notes 24 | 25 | Note that all currently released models are for SDXL. Models for SD1.5 may be provided later if demanded. 26 | 27 | **Note that in this extension, all model downloads/selections are fully automatic. In fact most users can just skip this section.** 28 | 29 | Below models are released: 30 | 31 | 1. `layer_xl_transparent_attn.safetensors` This is a rank-256 LoRA to turn a SDXL into a transparent image generator. It will change the latent distribution of the model to a "transparent latent space" that can be decoded by the special VAE pipeline. 32 | 2. `layer_xl_transparent_conv.safetensors` This is an alternative model to turn your SDXL into a transparent image generator. This safetensors file includes an offset of all conv layers (and actually, all layers that are not q,k,v of any attention layers). These offsets can be merged to any XL model to change the latent distribution to transparent images. Because we excluded the offset training of any q,k,v layers, the prompt understanding of SDXL should be perfectly preserved. However, in practice, I find the `layer_xl_transparent_attn.safetensors` will lead to better results. This `layer_xl_transparent_conv.safetensors` is still included for some special use cases that needs special prompt understanding. Also, this model may introduce a strong style influence to the base model. 33 | 3. `layer_xl_fg2ble.safetensors` This is a safetensors file includes offsets to turn a SDXL into a layer generating model, that is conditioned on foregrounds, and generates blended compositions. 34 | 4. `layer_xl_fgble2bg.safetensors` This is a safetensors file includes offsets to turn a SDXL into a layer generating model, that is conditioned on foregrounds and blended compositions, and generates backgrounds. 35 | 5. `layer_xl_bg2ble.safetensors` This is a safetensors file includes offsets to turn a SDXL into a layer generating model, that is conditioned on backgrounds, and generates blended compositions. 36 | 6. `layer_xl_bgble2fg.safetensors` This is a safetensors file includes offsets to turn a SDXL into a layer generating model, that is conditioned on backgrounds and blended compositions, and generates foregrounds. 37 | 7. `vae_transparent_encoder.safetensors` This is an image encoder to extract a latent offset from pixel space. The offset can be added to latent images to help the diffusion of transparency. Note that in the paper we used a relatively heavy model with exactly same amount of parameters as the SD VAE. The released model is more light weighted, requires much less vram, and does not influence result quality in my tests. 38 | 8. `vae_transparent_decoder.safetensors` This is an image decoder that takes SD VAE outputs and latent image as inputs, and outputs a real PNG image. The model architecture is also more lightweight than the paper version to reduce VRAM requirement. I have made sure that the reduced parameters does not influence result quality. 39 | 40 | Below models may be released soon (if necessary): 41 | 42 | 1. A model that can generate foreground and background together (using attention sharing similar to AnimateDiff). I put this model on hold because of these reasons: (1) the other released models can already achieve all functionalities and this model does not bring more functionalities. (2) the inference speed of this model is 3x slower than others and requires 4x more VRAM than other released model, and I am working on reducing the VRAM of this model if necessary. (3) This model will involve more hyperparameters and if demanded, I will investigate the best practice for inference/training before release it. **this model is confirmed to be released soon with joint layer generating and one-step bg/fg-condition, after we finish the final VRAM optimization** 43 | 2. The current background-conditioned foreground model may be a bit too lightweight. I will probably release a heavier one with more parameters and different behaviors (see also the discussions later). 44 | 3. Because the difference between diffusers training and k-diffusion inference, I can observe some mystical problems like sometimes DPM++ will give artifacts but Euler A will fix it. I am looking into it and may provide some revised model that works better with all A1111 samplers. 45 | 46 | 47 | # Sanity Check 48 | 49 | We highly encourage you to go through the sanity check and get exactly same results (so that if any problem occurs, we will know if the problem is on our side). 50 | 51 | The two used models are: 52 | 53 | 1. https://civitai.com/models/133005?modelVersionId=198530 Juggernaut XL V6 (note that the used one is **V6**, not v7 or v8 or V9) 54 | 2. https://civitai.com/models/261336?modelVersionId=295158 anima_pencil-XL 1.0.0 (note that the used one is **1.0.0**, not 1.5.0) 55 | 56 | We will first test transparent image generating. Set your extension to this: 57 | 58 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/5b85b383-89c0-403e-aa07-d6e43ff3b8ae) 59 | 60 | an apple, high quality 61 | 62 | Negative prompt: bad, ugly 63 | 64 | Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 5, Seed: 12345, Size: 1024x1024, Model hash: 1fe6c7ec54, Model: juggernautXL_version6Rundiffusion, layerdiffusion_enabled: True, layerdiffusion_method: Only Generate Transparent Image (Attention Injection), layerdiffusion_weight: 1, layerdiffusion_ending_step: 1, layerdiffusion_fg_image: False, layerdiffusion_bg_image: False, layerdiffusion_blend_image: False, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 65 | 66 | Make sure that you get this apple 67 | 68 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/376fa8bc-547e-4cd7-b658-7d60f2e37f1d) 69 | 70 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/16efc57b-4da8-4227-a257-f45f3dfeaddc) 71 | 72 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/38ace070-6530-43c9-9ca1-c98aa5b7a0ed) 73 | 74 | woman, messy hair, high quality 75 | 76 | Negative prompt: bad, ugly 77 | 78 | Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 5, Seed: 12345, Size: 1024x1024, Model hash: 1fe6c7ec54, Model: juggernautXL_version6Rundiffusion, layerdiffusion_enabled: True, layerdiffusion_method: Only Generate Transparent Image (Attention Injection), layerdiffusion_weight: 1, layerdiffusion_ending_step: 1, layerdiffusion_fg_image: False, layerdiffusion_bg_image: False, layerdiffusion_blend_image: False, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 79 | 80 | Make sure that you get the woman with hair as messy as this 81 | 82 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/17c86ba5-eb29-45d4-b708-caf7e836b509) 83 | 84 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/6f1ef595-255c-4162-bdf9-c8e4eb321f31) 85 | 86 | a cup made of glass, high quality 87 | 88 | Negative prompt: bad, ugly 89 | 90 | Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 5, Seed: 12345, Size: 1024x1024, Model hash: 1fe6c7ec54, Model: juggernautXL_version6Rundiffusion, layerdiffusion_enabled: True, layerdiffusion_method: Only Generate Transparent Image (Attention Injection), layerdiffusion_weight: 1, layerdiffusion_ending_step: 1, layerdiffusion_fg_image: False, layerdiffusion_bg_image: False, layerdiffusion_blend_image: False, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 91 | 92 | Make sure that you get this cup 93 | 94 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/a99177e6-72ed-447b-b2a5-6ca0fe1dc105) 95 | 96 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/3b7df3f3-c6c1-401d-afa8-5a1c404165c9) 97 | 98 | glowing effect, book of magic, high quality 99 | 100 | Negative prompt: bad, ugly 101 | 102 | Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 7, Seed: 12345, Size: 1024x1024, Model hash: 1fe6c7ec54, Model: juggernautXL_version6Rundiffusion, layerdiffusion_enabled: True, layerdiffusion_method: Only Generate Transparent Image (Attention Injection), layerdiffusion_weight: 1, layerdiffusion_ending_step: 1, layerdiffusion_fg_image: True, layerdiffusion_bg_image: False, layerdiffusion_blend_image: True, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 103 | 104 | make sure that you get this glowing book 105 | 106 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/c093c862-17a3-4604-8e23-6c7f3a0eb4b3) 107 | 108 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/fa0b02b0-b530-48ed-a8ec-17bd9cccfc87) 109 | 110 | OK then lets move on to a bit longer prompt: 111 | 112 | (this prompt is from https://civitai.com/images/3160575) 113 | 114 | photograph close up portrait of Female boxer training, serious, stoic cinematic 4k epic detailed 4k epic detailed photograph shot on kodak detailed bokeh cinematic hbo dark moody 115 | 116 | Negative prompt: (worst quality, low quality, normal quality, lowres, low details, oversaturated, undersaturated, overexposed, underexposed, grayscale, bw, bad photo, bad photography, bad art:1.4), (watermark, signature, text font, username, error, logo, words, letters, digits, autograph, trademark, name:1.2), (blur, blurry, grainy), morbid, ugly, asymmetrical, mutated malformed, mutilated, poorly lit, bad shadow, draft, cropped, out of frame, cut off, censored, jpeg artifacts, out of focus, glitch, duplicate, (airbrushed, cartoon, anime, semi-realistic, cgi, render, blender, digital art, manga, amateur:1.3), (3D ,3D Game, 3D Game Scene, 3D Character:1.1), (bad hands, bad anatomy, bad body, bad face, bad teeth, bad arms, bad legs, deformities:1.3) 117 | 118 | Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 7, Seed: 12345, Size: 896x1152, Model hash: 1fe6c7ec54, Model: juggernautXL_version6Rundiffusion, layerdiffusion_enabled: True, layerdiffusion_method: Only Generate Transparent Image (Attention Injection), layerdiffusion_weight: 1, layerdiffusion_ending_step: 1, layerdiffusion_fg_image: False, layerdiffusion_bg_image: False, layerdiffusion_blend_image: False, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 119 | 120 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/845c0e35-0096-484b-be2c-d443b4dc63cd) 121 | 122 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/47ee7ba1-7f64-4e27-857f-c82c9d2bbb14) 123 | 124 | Anime model test: 125 | 126 | girl in dress, high quality 127 | 128 | Negative prompt: nsfw, bad, ugly, text, watermark 129 | 130 | Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 7, Seed: 12345, Size: 896x1152, Model hash: 7ed8da12d9, Model: animaPencilXL_v100, layerdiffusion_enabled: True, layerdiffusion_method: Only Generate Transparent Image (Attention Injection), layerdiffusion_weight: 1, layerdiffusion_ending_step: 1, layerdiffusion_fg_image: False, layerdiffusion_bg_image: False, layerdiffusion_blend_image: False, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 131 | 132 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/fcec8ea5-32de-44af-847a-d66dd62b95d1) 133 | 134 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/53d84e56-4061-4d91-982f-8f1e927f68b7) 135 | 136 | (I am not very good at writing prompts in the AnimagineXL format, and perhaps you can get better results with better prompts) 137 | 138 | ### Background Condition 139 | 140 | First download this image: 141 | 142 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/e7e2d80e-ffbe-4724-812a-5139a88027e3) 143 | 144 | then set the interface with 145 | 146 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/99a7e648-a83f-4ea5-bff6-66a1c624c0bd) 147 | 148 | then set the parameters with 149 | 150 | old man sitting, high quality 151 | 152 | Negative prompt: bad, ugly 153 | 154 | Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 7, Seed: 12345, Size: 896x1152, Model hash: 1fe6c7ec54, Model: juggernautXL_version6Rundiffusion, layerdiffusion_enabled: True, layerdiffusion_method: From Background to Blending, layerdiffusion_weight: 1, layerdiffusion_ending_step: 1, layerdiffusion_fg_image: False, layerdiffusion_bg_image: True, layerdiffusion_blend_image: False, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 155 | 156 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/4dd5022a-d9fd-4436-83b8-775e2456bfc6) 157 | 158 | Then set the interface with (you first change the mode and then drag the image from result to interface) 159 | 160 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/8277399c-fc9b-43fd-a9bb-1c7a8dcebb3f) 161 | 162 | Then change the sampler to Euler A or UniPC or some other sampler that is not dpm (This is probably because of some difference between diffusers training script and webui's k-diffusion. I am still looking into this and may revise my training script and model very soon so that this step will be removed.) 163 | 164 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/2c7124c5-e5d4-40cf-b106-e55c33e40003) 165 | 166 | FAQ: 167 | 168 | *OK. But how can I get a background image like this?* 169 | 170 | You can use the Foreground Condition to get a background like this. We will describe it in the next section. 171 | 172 | Or you can use old inpainting tech to perform foreground removal on any image to get a background like this. 173 | 174 | *Wait. Why you generate it with two steps? Can I generate it with one pass?* 175 | 176 | Two steps allows for more flexible editing. We will release the one-step model soon if necessary, but that model is 2x larger and requires 4x larger VRAM, and we are still working on reducing the computation requirement of that model. (But in my tests, the current solution is better than that model in most cases.) 177 | 178 | Also you can see that the current model is about 680MB and in particular I think it is a bit too lightweight and will soon release a relatively heavier model for potential stronger structure understanding (but that is still under experiments). 179 | 180 | # Foreground Condition 181 | 182 | First we generate a dog 183 | 184 | a dog sitting, high quality 185 | 186 | Negative prompt: bad, ugly 187 | 188 | Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 7, Seed: 12345, Size: 896x1152, Model hash: 1fe6c7ec54, Model: juggernautXL_version6Rundiffusion, layerdiffusion_enabled: True, layerdiffusion_method: Only Generate Transparent Image (Attention Injection), layerdiffusion_weight: 1, layerdiffusion_ending_step: 1, layerdiffusion_fg_image: True, layerdiffusion_bg_image: False, layerdiffusion_blend_image: False, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 189 | 190 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/dd515df4-cc58-47e0-8fe0-89e21e8320c4) 191 | 192 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/e2785fd4-c168-4062-ae2f-010540ff0991) 193 | 194 | then change to `From Foreground to Blending` and drag the transparent image to foreground input. 195 | 196 | Note that you drag the real transparent image, not the visualization with checkboard background. Make sure tou see this 197 | 198 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/b912e1e8-7511-4afc-aa61-4bb31d6949f7) 199 | 200 | then do this 201 | 202 | a dog sitting in room, high quality 203 | 204 | Negative prompt: bad, ugly 205 | 206 | Steps: 20, Sampler: DPM++ 2M SDE Karras, CFG scale: 7, Seed: 12345, Size: 896x1152, Model hash: 1fe6c7ec54, Model: juggernautXL_version6Rundiffusion, layerdiffusion_enabled: True, layerdiffusion_method: From Foreground to Blending, layerdiffusion_weight: 1, layerdiffusion_ending_step: 1, layerdiffusion_fg_image: True, layerdiffusion_bg_image: False, layerdiffusion_blend_image: False, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 207 | 208 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/0b2abb76-56b9-448d-8f2a-8572a18c759b) 209 | 210 | Then change mode, drag your image, so that 211 | 212 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/48667cbf-e460-4037-b059-a30580841bcd) 213 | 214 | (Note that here I set stop at as 0.5 to get better results since I do not need the bg to be exactly same) 215 | 216 | Then change the sampler to Euler A or UniPC or some other sampler that is not dpm (This is probably because of some difference between diffusers training script and webui's k-diffusion. I am still looking into this and may revise my training script and model very soon so that this step will be removed.) 217 | 218 | then do this 219 | 220 | room, high quality 221 | 222 | Negative prompt: bad, ugly 223 | 224 | Steps: 20, Sampler: UniPC, CFG scale: 7, Seed: 12345, Size: 896x1152, Model hash: 1fe6c7ec54, Model: juggernautXL_version6Rundiffusion, layerdiffusion_enabled: True, layerdiffusion_method: From Foreground and Blending to Background, layerdiffusion_weight: 1, layerdiffusion_ending_step: 0.5, layerdiffusion_fg_image: True, layerdiffusion_bg_image: False, layerdiffusion_blend_image: True, layerdiffusion_resize_mode: Crop and Resize, Version: f0.0.17v1.8.0rc-latest-269-gef35383b 225 | 226 | ![image](https://github.com/layerdiffusion/sd-forge-layerdiffusion/assets/161511761/5f5a5b6a-7dd2-4e16-9571-1458a9ef465d) 227 | 228 | -------------------------------------------------------------------------------- /lib_layerdiffusion/enums.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class ResizeMode(Enum): 5 | RESIZE = "Just Resize" 6 | CROP_AND_RESIZE = "Crop and Resize" 7 | RESIZE_AND_FILL = "Resize and Fill" 8 | 9 | def int_value(self): 10 | if self == ResizeMode.RESIZE: 11 | return 0 12 | elif self == ResizeMode.CROP_AND_RESIZE: 13 | return 1 14 | elif self == ResizeMode.RESIZE_AND_FILL: 15 | return 2 16 | return 0 17 | -------------------------------------------------------------------------------- /lib_layerdiffusion/models.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | import torch 3 | import cv2 4 | import numpy as np 5 | 6 | from tqdm import tqdm 7 | from typing import Optional, Tuple 8 | from diffusers.configuration_utils import ConfigMixin, register_to_config 9 | from diffusers.models.modeling_utils import ModelMixin 10 | from diffusers.models.unet_2d_blocks import UNetMidBlock2D, get_down_block, get_up_block 11 | import ldm_patched.modules.model_management as model_management 12 | from ldm_patched.modules.model_patcher import ModelPatcher 13 | 14 | 15 | def zero_module(module): 16 | """ 17 | Zero out the parameters of a module and return it. 18 | """ 19 | for p in module.parameters(): 20 | p.detach().zero_() 21 | return module 22 | 23 | 24 | class LatentTransparencyOffsetEncoder(torch.nn.Module): 25 | def __init__(self, *args, **kwargs): 26 | super().__init__(*args, **kwargs) 27 | self.blocks = torch.nn.Sequential( 28 | torch.nn.Conv2d(4, 32, kernel_size=3, padding=1, stride=1), 29 | nn.SiLU(), 30 | torch.nn.Conv2d(32, 32, kernel_size=3, padding=1, stride=1), 31 | nn.SiLU(), 32 | torch.nn.Conv2d(32, 64, kernel_size=3, padding=1, stride=2), 33 | nn.SiLU(), 34 | torch.nn.Conv2d(64, 64, kernel_size=3, padding=1, stride=1), 35 | nn.SiLU(), 36 | torch.nn.Conv2d(64, 128, kernel_size=3, padding=1, stride=2), 37 | nn.SiLU(), 38 | torch.nn.Conv2d(128, 128, kernel_size=3, padding=1, stride=1), 39 | nn.SiLU(), 40 | torch.nn.Conv2d(128, 256, kernel_size=3, padding=1, stride=2), 41 | nn.SiLU(), 42 | torch.nn.Conv2d(256, 256, kernel_size=3, padding=1, stride=1), 43 | nn.SiLU(), 44 | zero_module(torch.nn.Conv2d(256, 4, kernel_size=3, padding=1, stride=1)), 45 | ) 46 | 47 | def __call__(self, x): 48 | return self.blocks(x) 49 | 50 | 51 | # 1024 * 1024 * 3 -> 16 * 16 * 512 -> 1024 * 1024 * 3 52 | class UNet1024(ModelMixin, ConfigMixin): 53 | @register_to_config 54 | def __init__( 55 | self, 56 | in_channels: int = 3, 57 | out_channels: int = 3, 58 | down_block_types: Tuple[str] = ("DownBlock2D", "DownBlock2D", "DownBlock2D", "DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"), 59 | up_block_types: Tuple[str] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D", "UpBlock2D", "UpBlock2D", "UpBlock2D"), 60 | block_out_channels: Tuple[int] = (32, 32, 64, 128, 256, 512, 512), 61 | layers_per_block: int = 2, 62 | mid_block_scale_factor: float = 1, 63 | downsample_padding: int = 1, 64 | downsample_type: str = "conv", 65 | upsample_type: str = "conv", 66 | dropout: float = 0.0, 67 | act_fn: str = "silu", 68 | attention_head_dim: Optional[int] = 8, 69 | norm_num_groups: int = 4, 70 | norm_eps: float = 1e-5, 71 | ): 72 | super().__init__() 73 | 74 | # input 75 | self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) 76 | self.latent_conv_in = zero_module(nn.Conv2d(4, block_out_channels[2], kernel_size=1)) 77 | 78 | self.down_blocks = nn.ModuleList([]) 79 | self.mid_block = None 80 | self.up_blocks = nn.ModuleList([]) 81 | 82 | # down 83 | output_channel = block_out_channels[0] 84 | for i, down_block_type in enumerate(down_block_types): 85 | input_channel = output_channel 86 | output_channel = block_out_channels[i] 87 | is_final_block = i == len(block_out_channels) - 1 88 | 89 | down_block = get_down_block( 90 | down_block_type, 91 | num_layers=layers_per_block, 92 | in_channels=input_channel, 93 | out_channels=output_channel, 94 | temb_channels=None, 95 | add_downsample=not is_final_block, 96 | resnet_eps=norm_eps, 97 | resnet_act_fn=act_fn, 98 | resnet_groups=norm_num_groups, 99 | attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel, 100 | downsample_padding=downsample_padding, 101 | resnet_time_scale_shift="default", 102 | downsample_type=downsample_type, 103 | dropout=dropout, 104 | ) 105 | self.down_blocks.append(down_block) 106 | 107 | # mid 108 | self.mid_block = UNetMidBlock2D( 109 | in_channels=block_out_channels[-1], 110 | temb_channels=None, 111 | dropout=dropout, 112 | resnet_eps=norm_eps, 113 | resnet_act_fn=act_fn, 114 | output_scale_factor=mid_block_scale_factor, 115 | resnet_time_scale_shift="default", 116 | attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1], 117 | resnet_groups=norm_num_groups, 118 | attn_groups=None, 119 | add_attention=True, 120 | ) 121 | 122 | # up 123 | reversed_block_out_channels = list(reversed(block_out_channels)) 124 | output_channel = reversed_block_out_channels[0] 125 | for i, up_block_type in enumerate(up_block_types): 126 | prev_output_channel = output_channel 127 | output_channel = reversed_block_out_channels[i] 128 | input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] 129 | 130 | is_final_block = i == len(block_out_channels) - 1 131 | 132 | up_block = get_up_block( 133 | up_block_type, 134 | num_layers=layers_per_block + 1, 135 | in_channels=input_channel, 136 | out_channels=output_channel, 137 | prev_output_channel=prev_output_channel, 138 | temb_channels=None, 139 | add_upsample=not is_final_block, 140 | resnet_eps=norm_eps, 141 | resnet_act_fn=act_fn, 142 | resnet_groups=norm_num_groups, 143 | attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel, 144 | resnet_time_scale_shift="default", 145 | upsample_type=upsample_type, 146 | dropout=dropout, 147 | ) 148 | self.up_blocks.append(up_block) 149 | prev_output_channel = output_channel 150 | 151 | # out 152 | self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps) 153 | self.conv_act = nn.SiLU() 154 | self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=3, padding=1) 155 | 156 | def forward(self, x, latent): 157 | sample_latent = self.latent_conv_in(latent) 158 | sample = self.conv_in(x) 159 | emb = None 160 | 161 | down_block_res_samples = (sample,) 162 | for i, downsample_block in enumerate(self.down_blocks): 163 | if i == 3: 164 | sample = sample + sample_latent 165 | 166 | sample, res_samples = downsample_block(hidden_states=sample, temb=emb) 167 | down_block_res_samples += res_samples 168 | 169 | sample = self.mid_block(sample, emb) 170 | 171 | for upsample_block in self.up_blocks: 172 | res_samples = down_block_res_samples[-len(upsample_block.resnets) :] 173 | down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)] 174 | sample = upsample_block(sample, res_samples, emb) 175 | 176 | sample = self.conv_norm_out(sample) 177 | sample = self.conv_act(sample) 178 | sample = self.conv_out(sample) 179 | return sample 180 | 181 | 182 | def checkerboard(shape): 183 | return np.indices(shape).sum(axis=0) % 2 184 | 185 | 186 | class TransparentVAEDecoder: 187 | def __init__(self, sd): 188 | self.load_device = model_management.get_torch_device() 189 | self.offload_device = model_management.unet_offload_device() 190 | self.dtype = torch.float16 if model_management.should_use_fp16(self.load_device) else torch.float32 191 | 192 | model = UNet1024(in_channels=3, out_channels=4) 193 | model.load_state_dict(sd, strict=True) 194 | model.to(device=self.offload_device, dtype=self.dtype) 195 | model.eval() 196 | 197 | self.model = ModelPatcher(model, load_device=self.load_device, offload_device=self.offload_device) 198 | return 199 | 200 | @torch.no_grad() 201 | def estimate_single_pass(self, pixel, latent): 202 | y = self.model.model(pixel, latent) 203 | return y 204 | 205 | @torch.no_grad() 206 | def estimate_augmented(self, pixel, latent): 207 | args = [ 208 | [False, 0], [False, 1], [False, 2], [False, 3], [True, 0], [True, 1], [True, 2], [True, 3], 209 | ] 210 | 211 | result = [] 212 | 213 | for flip, rok in tqdm(args): 214 | feed_pixel = pixel.clone() 215 | feed_latent = latent.clone() 216 | 217 | if flip: 218 | feed_pixel = torch.flip(feed_pixel, dims=(3,)) 219 | feed_latent = torch.flip(feed_latent, dims=(3,)) 220 | 221 | feed_pixel = torch.rot90(feed_pixel, k=rok, dims=(2, 3)) 222 | feed_latent = torch.rot90(feed_latent, k=rok, dims=(2, 3)) 223 | 224 | eps = self.estimate_single_pass(feed_pixel, feed_latent).clip(0, 1) 225 | eps = torch.rot90(eps, k=-rok, dims=(2, 3)) 226 | 227 | if flip: 228 | eps = torch.flip(eps, dims=(3,)) 229 | 230 | result += [eps] 231 | 232 | result = torch.stack(result, dim=0) 233 | median = torch.median(result, dim=0).values 234 | return median 235 | 236 | def patch(self, p, vae_patcher, output_origin): 237 | @torch.no_grad() 238 | def wrapper(func, latent): 239 | pixel = func(latent).movedim(-1, 1).to(device=self.load_device, dtype=self.dtype) 240 | 241 | if output_origin: 242 | origin_outputs = (pixel.movedim(1, -1) * 255.0).detach().cpu().float().numpy().clip(0, 255).astype(np.uint8) 243 | for png in origin_outputs: 244 | p.extra_result_images.append(png) 245 | 246 | latent = latent.to(device=self.load_device, dtype=self.dtype) 247 | 248 | model_management.load_model_gpu(self.model) 249 | y = self.estimate_augmented(pixel, latent) 250 | 251 | y = y.clip(0, 1).movedim(1, -1) 252 | alpha = y[..., :1] 253 | fg = y[..., 1:] 254 | 255 | B, H, W, C = fg.shape 256 | cb = checkerboard(shape=(H // 64, W // 64)) 257 | cb = cv2.resize(cb, (W, H), interpolation=cv2.INTER_NEAREST) 258 | cb = (0.5 + (cb - 0.5) * 0.1)[None, ..., None] 259 | cb = torch.from_numpy(cb).to(fg) 260 | 261 | vis = fg * alpha + cb * (1 - alpha) 262 | 263 | pngs = torch.cat([fg, alpha], dim=3) 264 | pngs = (pngs * 255.0).detach().cpu().float().numpy().clip(0, 255).astype(np.uint8) 265 | for png in pngs: 266 | p.extra_result_images.append(png) 267 | 268 | return vis 269 | 270 | vae_patcher.set_model_vae_decode_wrapper(wrapper) 271 | return 272 | 273 | 274 | class TransparentVAEEncoder: 275 | def __init__(self, sd): 276 | self.load_device = model_management.get_torch_device() 277 | self.offload_device = model_management.unet_offload_device() 278 | self.dtype = torch.float16 if model_management.should_use_fp16(self.load_device) else torch.float32 279 | 280 | model = LatentTransparencyOffsetEncoder() 281 | model.load_state_dict(sd, strict=True) 282 | model.to(device=self.offload_device, dtype=self.dtype) 283 | model.eval() 284 | 285 | self.model = ModelPatcher(model, load_device=self.load_device, offload_device=self.offload_device) 286 | return 287 | 288 | def patch(self, p, vae_patcher): 289 | @torch.no_grad() 290 | def wrapper(func, latent): 291 | print('VAE Encode with Latent Transparency Offset is under construction now.') 292 | print('This should not be important if denoising strength is high.') 293 | print('But this will influence results with low denoising strength.') 294 | print('But results should be better if you come back (and update) several days later when we finish this part.') 295 | return func(latent) 296 | 297 | vae_patcher.set_model_vae_encode_wrapper(wrapper) 298 | return 299 | 300 | -------------------------------------------------------------------------------- /lib_layerdiffusion/utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from lib_layerdiffusion.enums import ResizeMode 3 | import cv2 4 | import torch 5 | 6 | 7 | def rgba2rgbfp32(x): 8 | rgb = x[..., :3].astype(np.float32) / 255.0 9 | a = x[..., 3:4].astype(np.float32) / 255.0 10 | return 0.5 + (rgb - 0.5) * a 11 | 12 | 13 | def to255unit8(x): 14 | return (x * 255.0).clip(0, 255).astype(np.uint8) 15 | 16 | 17 | def safe_numpy(x): 18 | # A very safe method to make sure that Apple/Mac works 19 | y = x 20 | 21 | # below is very boring but do not change these. If you change these Apple or Mac may fail. 22 | y = y.copy() 23 | y = np.ascontiguousarray(y) 24 | y = y.copy() 25 | return y 26 | 27 | 28 | def high_quality_resize(x, size): 29 | if x.shape[0] != size[1] or x.shape[1] != size[0]: 30 | if (size[0] * size[1]) < (x.shape[0] * x.shape[1]): 31 | interpolation = cv2.INTER_AREA 32 | else: 33 | interpolation = cv2.INTER_LANCZOS4 34 | 35 | y = cv2.resize(x, size, interpolation=interpolation) 36 | else: 37 | y = x 38 | return y 39 | 40 | 41 | def crop_and_resize_image(detected_map, resize_mode, h, w): 42 | if resize_mode == ResizeMode.RESIZE: 43 | detected_map = high_quality_resize(detected_map, (w, h)) 44 | detected_map = safe_numpy(detected_map) 45 | return detected_map 46 | 47 | old_h, old_w, _ = detected_map.shape 48 | old_w = float(old_w) 49 | old_h = float(old_h) 50 | k0 = float(h) / old_h 51 | k1 = float(w) / old_w 52 | 53 | safeint = lambda x: int(np.round(x)) 54 | 55 | if resize_mode == ResizeMode.RESIZE_AND_FILL: 56 | k = min(k0, k1) 57 | borders = np.concatenate([detected_map[0, :, :], detected_map[-1, :, :], detected_map[:, 0, :], detected_map[:, -1, :]], axis=0) 58 | high_quality_border_color = np.median(borders, axis=0).astype(detected_map.dtype) 59 | high_quality_background = np.tile(high_quality_border_color[None, None], [h, w, 1]) 60 | detected_map = high_quality_resize(detected_map, (safeint(old_w * k), safeint(old_h * k))) 61 | new_h, new_w, _ = detected_map.shape 62 | pad_h = max(0, (h - new_h) // 2) 63 | pad_w = max(0, (w - new_w) // 2) 64 | high_quality_background[pad_h:pad_h + new_h, pad_w:pad_w + new_w] = detected_map 65 | detected_map = high_quality_background 66 | detected_map = safe_numpy(detected_map) 67 | return detected_map 68 | else: 69 | k = max(k0, k1) 70 | detected_map = high_quality_resize(detected_map, (safeint(old_w * k), safeint(old_h * k))) 71 | new_h, new_w, _ = detected_map.shape 72 | pad_h = max(0, (new_h - h) // 2) 73 | pad_w = max(0, (new_w - w) // 2) 74 | detected_map = detected_map[pad_h:pad_h+h, pad_w:pad_w+w] 75 | detected_map = safe_numpy(detected_map) 76 | return detected_map 77 | 78 | 79 | def pytorch_to_numpy(x): 80 | return [np.clip(255. * y.cpu().numpy(), 0, 255).astype(np.uint8) for y in x] 81 | 82 | 83 | def numpy_to_pytorch(x): 84 | y = x.astype(np.float32) / 255.0 85 | y = y[None] 86 | y = np.ascontiguousarray(y.copy()) 87 | y = torch.from_numpy(y).float() 88 | return y 89 | -------------------------------------------------------------------------------- /scripts/forge_layerdiffusion.py: -------------------------------------------------------------------------------- 1 | import gradio as gr 2 | import os 3 | import functools 4 | import torch 5 | import numpy as np 6 | import copy 7 | 8 | from modules import scripts 9 | from modules.processing import StableDiffusionProcessing 10 | from lib_layerdiffusion.enums import ResizeMode 11 | from lib_layerdiffusion.utils import rgba2rgbfp32, to255unit8, crop_and_resize_image 12 | from enum import Enum 13 | from modules.paths import models_path 14 | from ldm_patched.modules.utils import load_torch_file 15 | from lib_layerdiffusion.models import TransparentVAEDecoder, TransparentVAEEncoder 16 | from ldm_patched.modules.model_management import current_loaded_models 17 | from modules_forge.forge_sampler import sampling_prepare 18 | from modules.modelloader import load_file_from_url 19 | 20 | 21 | def is_model_loaded(model): 22 | return any(model == m.model for m in current_loaded_models) 23 | 24 | 25 | layer_model_root = os.path.join(models_path, 'layer_model') 26 | os.makedirs(layer_model_root, exist_ok=True) 27 | 28 | 29 | vae_transparent_encoder = None 30 | vae_transparent_decoder = None 31 | 32 | 33 | class LayerMethod(Enum): 34 | FG_ONLY_ATTN = "Only Generate Transparent Image (Attention Injection)" 35 | FG_ONLY_CONV = "Only Generate Transparent Image (Conv Injection)" 36 | FG_TO_BLEND = "From Foreground to Blending" 37 | FG_BLEND_TO_BG = "From Foreground and Blending to Background" 38 | BG_TO_BLEND = "From Background to Blending" 39 | BG_BLEND_TO_FG = "From Background and Blending to Foreground" 40 | 41 | 42 | @functools.lru_cache(maxsize=2) 43 | def load_layer_model_state_dict(filename): 44 | return load_torch_file(filename, safe_load=True) 45 | 46 | 47 | class LayerDiffusionForForge(scripts.Script): 48 | def title(self): 49 | return "LayerDiffusion" 50 | 51 | def show(self, is_img2img): 52 | return scripts.AlwaysVisible 53 | 54 | def ui(self, *args, **kwargs): 55 | with gr.Accordion(open=False, label=self.title()): 56 | enabled = gr.Checkbox(label='Enabled', value=False) 57 | method = gr.Dropdown(choices=[e.value for e in LayerMethod], value=LayerMethod.FG_ONLY_ATTN.value, label="Method", type='value') 58 | gr.HTML('
') # some strange gradio problems 59 | 60 | with gr.Row(): 61 | fg_image = gr.Image(label='Foreground', source='upload', image_mode='RGBA', visible=False) 62 | bg_image = gr.Image(label='Background', source='upload', image_mode='RGBA', visible=False) 63 | blend_image = gr.Image(label='Blending', source='upload', image_mode='RGBA', visible=False) 64 | 65 | with gr.Row(): 66 | weight = gr.Slider(label=f"Weight", value=1.0, minimum=0.0, maximum=2.0, step=0.001) 67 | ending_step = gr.Slider(label="Stop At", value=1.0, minimum=0.0, maximum=1.0) 68 | 69 | resize_mode = gr.Radio(choices=[e.value for e in ResizeMode], value=ResizeMode.CROP_AND_RESIZE.value, label="Resize Mode", type='value', visible=False) 70 | output_origin = gr.Checkbox(label='Output original mat for img2img', value=False, visible=False) 71 | 72 | def method_changed(m): 73 | m = LayerMethod(m) 74 | 75 | if m == LayerMethod.FG_TO_BLEND: 76 | return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) 77 | 78 | if m == LayerMethod.BG_TO_BLEND: 79 | return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=True) 80 | 81 | if m == LayerMethod.BG_BLEND_TO_FG: 82 | return gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True) 83 | 84 | if m == LayerMethod.FG_BLEND_TO_BG: 85 | return gr.update(visible=True), gr.update(visible=False), gr.update(visible=True), gr.update(visible=True) 86 | 87 | return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False) 88 | 89 | method.change(method_changed, inputs=method, outputs=[fg_image, bg_image, blend_image, resize_mode], show_progress=False, queue=False) 90 | 91 | return enabled, method, weight, ending_step, fg_image, bg_image, blend_image, resize_mode, output_origin 92 | 93 | def process_before_every_sampling(self, p: StableDiffusionProcessing, *script_args, **kwargs): 94 | global vae_transparent_decoder, vae_transparent_encoder 95 | 96 | # This will be called before every sampling. 97 | # If you use highres fix, this will be called twice. 98 | 99 | enabled, method, weight, ending_step, fg_image, bg_image, blend_image, resize_mode, output_origin = script_args 100 | 101 | if not enabled: 102 | return 103 | 104 | p.extra_generation_params.update(dict( 105 | layerdiffusion_enabled=enabled, 106 | layerdiffusion_method=method, 107 | layerdiffusion_weight=weight, 108 | layerdiffusion_ending_step=ending_step, 109 | layerdiffusion_fg_image=fg_image is not None, 110 | layerdiffusion_bg_image=bg_image is not None, 111 | layerdiffusion_blend_image=blend_image is not None, 112 | layerdiffusion_resize_mode=resize_mode, 113 | )) 114 | 115 | B, C, H, W = kwargs['noise'].shape # latent_shape 116 | height = H * 8 117 | width = W * 8 118 | batch_size = p.batch_size 119 | 120 | method = LayerMethod(method) 121 | print(f'[Layer Diffusion] {method}') 122 | 123 | resize_mode = ResizeMode(resize_mode) 124 | fg_image = crop_and_resize_image(rgba2rgbfp32(fg_image), resize_mode, height, width) if fg_image is not None else None 125 | bg_image = crop_and_resize_image(rgba2rgbfp32(bg_image), resize_mode, height, width) if bg_image is not None else None 126 | blend_image = crop_and_resize_image(rgba2rgbfp32(blend_image), resize_mode, height, width) if blend_image is not None else None 127 | 128 | original_unet = p.sd_model.forge_objects.unet.clone() 129 | unet = p.sd_model.forge_objects.unet.clone() 130 | vae = p.sd_model.forge_objects.vae.clone() 131 | 132 | if method in [LayerMethod.FG_ONLY_ATTN, LayerMethod.FG_ONLY_CONV, LayerMethod.BG_BLEND_TO_FG]: 133 | if vae_transparent_decoder is None: 134 | model_path = load_file_from_url( 135 | url='https://huggingface.co/LayerDiffusion/layerdiffusion-v1/resolve/main/vae_transparent_decoder.safetensors', 136 | model_dir=layer_model_root, 137 | file_name='vae_transparent_decoder.safetensors' 138 | ) 139 | vae_transparent_decoder = TransparentVAEDecoder(load_torch_file(model_path)) 140 | vae_transparent_decoder.patch(p, vae.patcher, output_origin) 141 | 142 | if vae_transparent_encoder is None: 143 | model_path = load_file_from_url( 144 | url='https://huggingface.co/LayerDiffusion/layerdiffusion-v1/resolve/main/vae_transparent_encoder.safetensors', 145 | model_dir=layer_model_root, 146 | file_name='vae_transparent_encoder.safetensors' 147 | ) 148 | vae_transparent_encoder = TransparentVAEEncoder(load_torch_file(model_path)) 149 | vae_transparent_encoder.patch(p, vae.patcher) 150 | 151 | if fg_image is not None: 152 | fg_image = vae.encode(torch.from_numpy(np.ascontiguousarray(fg_image[None].copy()))) 153 | fg_image = unet.model.latent_format.process_in(fg_image) 154 | 155 | if bg_image is not None: 156 | bg_image = vae.encode(torch.from_numpy(np.ascontiguousarray(bg_image[None].copy()))) 157 | bg_image = unet.model.latent_format.process_in(bg_image) 158 | 159 | if blend_image is not None: 160 | blend_image = vae.encode(torch.from_numpy(np.ascontiguousarray(blend_image[None].copy()))) 161 | blend_image = unet.model.latent_format.process_in(blend_image) 162 | 163 | if method == LayerMethod.FG_ONLY_ATTN: 164 | model_path = load_file_from_url( 165 | url='https://huggingface.co/LayerDiffusion/layerdiffusion-v1/resolve/main/layer_xl_transparent_attn.safetensors', 166 | model_dir=layer_model_root, 167 | file_name='layer_xl_transparent_attn.safetensors' 168 | ) 169 | layer_lora_model = load_layer_model_state_dict(model_path) 170 | unet.load_frozen_patcher(layer_lora_model, weight) 171 | 172 | if method == LayerMethod.FG_ONLY_CONV: 173 | model_path = load_file_from_url( 174 | url='https://huggingface.co/LayerDiffusion/layerdiffusion-v1/resolve/main/layer_xl_transparent_conv.safetensors', 175 | model_dir=layer_model_root, 176 | file_name='layer_xl_transparent_conv.safetensors' 177 | ) 178 | layer_lora_model = load_layer_model_state_dict(model_path) 179 | unet.load_frozen_patcher(layer_lora_model, weight) 180 | 181 | if method == LayerMethod.BG_TO_BLEND: 182 | model_path = load_file_from_url( 183 | url='https://huggingface.co/LayerDiffusion/layerdiffusion-v1/resolve/main/layer_xl_bg2ble.safetensors', 184 | model_dir=layer_model_root, 185 | file_name='layer_xl_bg2ble.safetensors' 186 | ) 187 | unet.extra_concat_condition = bg_image 188 | layer_lora_model = load_layer_model_state_dict(model_path) 189 | unet.load_frozen_patcher(layer_lora_model, weight) 190 | 191 | if method == LayerMethod.FG_TO_BLEND: 192 | model_path = load_file_from_url( 193 | url='https://huggingface.co/LayerDiffusion/layerdiffusion-v1/resolve/main/layer_xl_fg2ble.safetensors', 194 | model_dir=layer_model_root, 195 | file_name='layer_xl_fg2ble.safetensors' 196 | ) 197 | unet.extra_concat_condition = fg_image 198 | layer_lora_model = load_layer_model_state_dict(model_path) 199 | unet.load_frozen_patcher(layer_lora_model, weight) 200 | 201 | if method == LayerMethod.BG_BLEND_TO_FG: 202 | model_path = load_file_from_url( 203 | url='https://huggingface.co/LayerDiffusion/layerdiffusion-v1/resolve/main/layer_xl_bgble2fg.safetensors', 204 | model_dir=layer_model_root, 205 | file_name='layer_xl_bgble2fg.safetensors' 206 | ) 207 | unet.extra_concat_condition = torch.cat([bg_image, blend_image], dim=1) 208 | layer_lora_model = load_layer_model_state_dict(model_path) 209 | unet.load_frozen_patcher(layer_lora_model, weight) 210 | 211 | if method == LayerMethod.FG_BLEND_TO_BG: 212 | model_path = load_file_from_url( 213 | url='https://huggingface.co/LayerDiffusion/layerdiffusion-v1/resolve/main/layer_xl_fgble2bg.safetensors', 214 | model_dir=layer_model_root, 215 | file_name='layer_xl_fgble2bg.safetensors' 216 | ) 217 | unet.extra_concat_condition = torch.cat([fg_image, blend_image], dim=1) 218 | layer_lora_model = load_layer_model_state_dict(model_path) 219 | unet.load_frozen_patcher(layer_lora_model, weight) 220 | 221 | sigma_end = unet.model.model_sampling.percent_to_sigma(ending_step) 222 | 223 | def remove_concat(cond): 224 | cond = copy.deepcopy(cond) 225 | for i in range(len(cond)): 226 | try: 227 | del cond[i]['model_conds']['c_concat'] 228 | except: 229 | pass 230 | return cond 231 | 232 | def conditioning_modifier(model, x, timestep, uncond, cond, cond_scale, model_options, seed): 233 | if timestep < sigma_end: 234 | if not is_model_loaded(original_unet): 235 | sampling_prepare(original_unet, x) 236 | target_model = original_unet.model 237 | cond = remove_concat(cond) 238 | uncond = remove_concat(uncond) 239 | else: 240 | target_model = model 241 | 242 | return target_model, x, timestep, uncond, cond, cond_scale, model_options, seed 243 | 244 | unet.add_conditioning_modifier(conditioning_modifier) 245 | 246 | p.sd_model.forge_objects.unet = unet 247 | p.sd_model.forge_objects.vae = vae 248 | return 249 | --------------------------------------------------------------------------------