├── .github └── workflows │ ├── docker-image.yml │ └── main.yml ├── .gitignore ├── LICENSE ├── LICENSE_MODEL ├── README.md ├── data ├── input.png ├── mask.png └── title.png ├── demo.py ├── requirements.txt └── stable_diffusion_engine.py /.github/workflows/docker-image.yml: -------------------------------------------------------------------------------- 1 | name: Docker Image CI 2 | 3 | on: 4 | push: 5 | branches: [ "*" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | 11 | build: 12 | # runs-on: ubuntu-latest 13 | runs-on: self-hosted 14 | steps: 15 | - uses: actions/checkout@v3 16 | - name: Build the Docker image 17 | run: docker build . --file Dockerfile --tag my-image-name:$(date +%s) 18 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Docker Image CI 2 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | pull_request: 7 | branches: [ "master" ] 8 | 9 | jobs: 10 | docker: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - 14 | name: Set up QEMU 15 | uses: docker/setup-qemu-action@v2 16 | - 17 | name: Set up Docker Buildx 18 | uses: docker/setup-buildx-action@v2 19 | - 20 | name: Build and push 21 | uses: docker/build-push-action@v3 22 | with: 23 | push: false 24 | tags: user/app:latest 25 | outputs: type=docker,dest=/tmp/stable-diffusion-openvino.tar 26 | - 27 | name: Upload artifact 28 | uses: actions/upload-artifact@v3 29 | with: 30 | name: myimage 31 | path: /tmp/stable-diffusion-openvino.tar 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /out/ 2 | output.png 3 | 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | pip-wheel-metadata/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | 57 | # Translations 58 | *.mo 59 | *.pot 60 | 61 | # Django stuff: 62 | *.log 63 | local_settings.py 64 | db.sqlite3 65 | db.sqlite3-journal 66 | 67 | # Flask stuff: 68 | instance/ 69 | .webassets-cache 70 | 71 | # Scrapy stuff: 72 | .scrapy 73 | 74 | # Sphinx documentation 75 | docs/_build/ 76 | 77 | # PyBuilder 78 | target/ 79 | 80 | # Jupyter Notebook 81 | .ipynb_checkpoints 82 | 83 | # IPython 84 | profile_default/ 85 | ipython_config.py 86 | 87 | # pyenv 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 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | tmp/ 135 | .idea 136 | result.png 137 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LICENSE_MODEL: -------------------------------------------------------------------------------- 1 | Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors 2 | 3 | CreativeML Open RAIL-M 4 | dated August 22, 2022 5 | 6 | Section I: PREAMBLE 7 | 8 | Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation. 9 | 10 | Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations. 11 | 12 | In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation. 13 | 14 | Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI. 15 | 16 | This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model. 17 | 18 | NOW THEREFORE, You and Licensor agree as follows: 19 | 20 | 1. Definitions 21 | 22 | - "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document. 23 | - "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License. 24 | - "Output" means the results of operating a Model as embodied in informational content resulting therefrom. 25 | - "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material. 26 | - "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model. 27 | - "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any. 28 | - "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access. 29 | - "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model. 30 | - "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator. 31 | - "Third Parties" means individuals or legal entities that are not under common control with Licensor or You. 32 | - "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 33 | - "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model. 34 | 35 | Section II: INTELLECTUAL PROPERTY RIGHTS 36 | 37 | Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III. 38 | 39 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model. 40 | 3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed. 41 | 42 | Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION 43 | 44 | 4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions: 45 | Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material. 46 | You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License; 47 | You must cause any modified files to carry prominent notices stating that You changed the files; 48 | You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model. 49 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License. 50 | 5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5). 51 | 6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License. 52 | 53 | Section IV: OTHER PROVISIONS 54 | 55 | 7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model. 56 | 8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors. 57 | 9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License. 58 | 10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 59 | 11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 60 | 12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein. 61 | 62 | END OF TERMS AND CONDITIONS 63 | 64 | 65 | 66 | 67 | Attachment A 68 | 69 | Use Restrictions 70 | 71 | You agree not to use the Model or Derivatives of the Model: 72 | - In any way that violates any applicable national, federal, state, local or international law or regulation; 73 | - For the purpose of exploiting, harming or attempting to exploit or harm minors in any way; 74 | - To generate or disseminate verifiably false information and/or content with the purpose of harming others; 75 | - To generate or disseminate personal identifiable information that can be used to harm an individual; 76 | - To defame, disparage or otherwise harass others; 77 | - For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation; 78 | - For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics; 79 | - To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm; 80 | - For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories; 81 | - To provide medical advice and medical results interpretation; 82 | - To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use). -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # stable_diffusion.openvino 2 | 3 | Implementation of Text-To-Image generation using Stable Diffusion on Intel CPU or GPU. 4 |

5 | 6 |

7 | 8 | ## Requirements 9 | 10 | * Linux, Windows, MacOS 11 | * Python <= 3.9.0 12 | * CPU or GPU compatible with OpenVINO. 13 | 14 | ## Install requirements 15 | 16 | * Set up and update PIP to the highest version 17 | * Install OpenVINO™ Development Tools 2022.3.0 release with PyPI 18 | * Download requirements 19 | 20 | ```bash 21 | python -m pip install --upgrade pip 22 | pip install openvino-dev[onnx,pytorch]==2022.3.0 23 | pip install -r requirements.txt 24 | ``` 25 | 26 | ## Generate image from text description 27 | 28 | ```bash 29 | usage: demo.py [-h] [--model MODEL] [--device DEVICE] [--seed SEED] [--beta-start BETA_START] [--beta-end BETA_END] [--beta-schedule BETA_SCHEDULE] 30 | [--num-inference-steps NUM_INFERENCE_STEPS] [--guidance-scale GUIDANCE_SCALE] [--eta ETA] [--tokenizer TOKENIZER] [--prompt PROMPT] [--params-from PARAMS_FROM] 31 | [--init-image INIT_IMAGE] [--strength STRENGTH] [--mask MASK] [--output OUTPUT] 32 | 33 | optional arguments: 34 | -h, --help show this help message and exit 35 | --model MODEL model name 36 | --device DEVICE inference device [CPU, GPU] 37 | --seed SEED random seed for generating consistent images per prompt 38 | --beta-start BETA_START 39 | LMSDiscreteScheduler::beta_start 40 | --beta-end BETA_END LMSDiscreteScheduler::beta_end 41 | --beta-schedule BETA_SCHEDULE 42 | LMSDiscreteScheduler::beta_schedule 43 | --num-inference-steps NUM_INFERENCE_STEPS 44 | num inference steps 45 | --guidance-scale GUIDANCE_SCALE 46 | guidance scale 47 | --eta ETA eta 48 | --tokenizer TOKENIZER 49 | tokenizer 50 | --prompt PROMPT prompt 51 | --params-from PARAMS_FROM 52 | Extract parameters from a previously generated image. 53 | --init-image INIT_IMAGE 54 | path to initial image 55 | --strength STRENGTH how strong the initial image should be noised [0.0, 1.0] 56 | --mask MASK mask of the region to inpaint on the initial image 57 | --output OUTPUT output image name 58 | ``` 59 | 60 | ## Examples 61 | 62 | ### Example Text-To-Image 63 | ```bash 64 | python demo.py --prompt "Street-art painting of Emilia Clarke in style of Banksy, photorealism" 65 | ``` 66 | 67 | ### Example Image-To-Image 68 | ```bash 69 | python demo.py --prompt "Photo of Emilia Clarke with a bright red hair" --init-image ./data/input.png --strength 0.5 70 | ``` 71 | 72 | ### Example Inpainting 73 | ```bash 74 | python demo.py --prompt "Photo of Emilia Clarke with a bright red hair" --init-image ./data/input.png --mask ./data/mask.png --strength 0.5 75 | ``` 76 | 77 | ## Performance 78 | 79 | | CPU | Time per iter | Total time | 80 | |----------------------------------------------------|---------------|------------| 81 | | AMD Ryzen 7 4800H | 4.8 s/it | 2.58 min | 82 | | AMD Ryzen Threadripper 1900X | 5.34 s/it | 2.58 min | 83 | | Intel(R) Core(TM) i7-4790K @ 4.00GHz | 10.1 s/it | 5.39 min | 84 | | Intel(R) Core(TM) i5-8279U | 7.4 s/it | 3.59 min | 85 | | Intel(R) Core(TM) i5-8569U @ 2.8GHz (MBP13-2019) | 6.17 s/it | 3.23 min | 86 | | Intel(R) Core(TM) i7-1165G7 @ 2.80GHz | 7.4 s/it | 3.59 min | 87 | | Intel(R) Core(TM) i7-11800H @ 2.30GHz (16 threads) | 2.9 s/it | 1.54 min | 88 | | Intel(R) Core(TM) i7-1280P @ 1.80GHz (6P/8E) | 5.45 s/it | 2.55 min | 89 | | Intel(R) Xeon(R) Gold 6154 CPU @ 3.00GHz | 1 s/it | 33 s | 90 | | Intel Arc A770M | 6.64 it/s | 7.53 s | 91 | 92 | 93 | ## Acknowledgements 94 | 95 | * Original implementation of Stable Diffusion: https://github.com/CompVis/stable-diffusion 96 | * diffusers library: https://github.com/huggingface/diffusers 97 | 98 | ## Disclaimer 99 | 100 | The authors are not responsible for the content generated using this project. 101 | Please, don't use this project to produce illegal, harmful, offensive etc. content. 102 | -------------------------------------------------------------------------------- /data/input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bes-dev/stable_diffusion.openvino/3b8ceae3d51236a4a16434deafbf9644f83c42ee/data/input.png -------------------------------------------------------------------------------- /data/mask.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bes-dev/stable_diffusion.openvino/3b8ceae3d51236a4a16434deafbf9644f83c42ee/data/mask.png -------------------------------------------------------------------------------- /data/title.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bes-dev/stable_diffusion.openvino/3b8ceae3d51236a4a16434deafbf9644f83c42ee/data/title.png -------------------------------------------------------------------------------- /demo.py: -------------------------------------------------------------------------------- 1 | # -- coding: utf-8 --` 2 | import argparse 3 | import os 4 | import json 5 | import random 6 | # engine 7 | from stable_diffusion_engine import StableDiffusionEngine 8 | # scheduler 9 | from diffusers import LMSDiscreteScheduler, PNDMScheduler 10 | # utils 11 | import cv2 12 | import numpy as np 13 | from openvino.runtime import Core 14 | 15 | 16 | def main(args): 17 | if args.seed is None: 18 | args.seed = random.randint(0, 2**30) 19 | np.random.seed(args.seed) 20 | if args.init_image is None: 21 | scheduler = LMSDiscreteScheduler( 22 | beta_start=args.beta_start, 23 | beta_end=args.beta_end, 24 | beta_schedule=args.beta_schedule, 25 | tensor_format="np" 26 | ) 27 | else: 28 | scheduler = PNDMScheduler( 29 | beta_start=args.beta_start, 30 | beta_end=args.beta_end, 31 | beta_schedule=args.beta_schedule, 32 | skip_prk_steps = True, 33 | tensor_format="np" 34 | ) 35 | engine = StableDiffusionEngine( 36 | model=args.model, 37 | scheduler=scheduler, 38 | tokenizer=args.tokenizer, 39 | device=args.device 40 | ) 41 | image = engine( 42 | prompt=args.prompt, 43 | init_image=None if args.init_image is None else cv2.imread(args.init_image), 44 | mask=None if args.mask is None else cv2.imread(args.mask, 0), 45 | strength=args.strength, 46 | num_inference_steps=args.num_inference_steps, 47 | guidance_scale=args.guidance_scale, 48 | eta=args.eta 49 | ) 50 | cv2.imwrite(args.output, image) 51 | 52 | 53 | if __name__ == "__main__": 54 | parser = argparse.ArgumentParser() 55 | # pipeline configure 56 | parser.add_argument("--model", type=str, default="bes-dev/stable-diffusion-v1-4-openvino", help="model name") 57 | # inference device 58 | parser.add_argument("--device", type=str, default="CPU", help=f"inference device [{', '.join(Core().available_devices)}]") 59 | # randomizer params 60 | parser.add_argument("--seed", type=int, default=None, help="random seed for generating consistent images per prompt") 61 | # scheduler params 62 | parser.add_argument("--beta-start", type=float, default=0.00085, help="LMSDiscreteScheduler::beta_start") 63 | parser.add_argument("--beta-end", type=float, default=0.012, help="LMSDiscreteScheduler::beta_end") 64 | parser.add_argument("--beta-schedule", type=str, default="scaled_linear", help="LMSDiscreteScheduler::beta_schedule") 65 | # diffusion params 66 | parser.add_argument("--num-inference-steps", type=int, default=32, help="num inference steps") 67 | parser.add_argument("--guidance-scale", type=float, default=7.5, help="guidance scale") 68 | parser.add_argument("--eta", type=float, default=0.0, help="eta") 69 | # tokenizer 70 | parser.add_argument("--tokenizer", type=str, default="openai/clip-vit-large-patch14", help="tokenizer") 71 | # prompt 72 | parser.add_argument("--prompt", type=str, default="Street-art painting of Emilia Clarke in style of Banksy, photorealism", help="prompt") 73 | # Parameter re-use: 74 | parser.add_argument("--params-from", type=str, required=False, help="Extract parameters from a previously generated image.") 75 | # img2img params 76 | parser.add_argument("--init-image", type=str, default=None, help="path to initial image") 77 | parser.add_argument("--strength", type=float, default=0.5, help="how strong the initial image should be noised [0.0, 1.0]") 78 | # inpainting 79 | parser.add_argument("--mask", type=str, default=None, help="mask of the region to inpaint on the initial image") 80 | # output name 81 | parser.add_argument("--output", type=str, default="output.png", help="output image name") 82 | args = parser.parse_args() 83 | main(args) 84 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==1.19.5 2 | opencv-python==4.5.5.64 3 | transformers==4.16.2 4 | diffusers==0.2.4 5 | tqdm==4.64.0 6 | openvino==2022.3.0 7 | huggingface_hub==0.9.0 8 | scipy==1.9.0 9 | streamlit==1.12.0 10 | watchdog==2.1.9 11 | ftfy==6.1.1 12 | streamlit_drawable_canvas==0.9.1 13 | pillow==9.0.1 14 | piexif==1.1.3 15 | -------------------------------------------------------------------------------- /stable_diffusion_engine.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import numpy as np 3 | # openvino 4 | from openvino.runtime import Core 5 | # tokenizer 6 | from transformers import CLIPTokenizer 7 | # utils 8 | from tqdm import tqdm 9 | from huggingface_hub import hf_hub_download 10 | from diffusers import LMSDiscreteScheduler, PNDMScheduler 11 | import cv2 12 | 13 | 14 | def result(var): 15 | return next(iter(var.values())) 16 | 17 | 18 | class StableDiffusionEngine: 19 | def __init__( 20 | self, 21 | scheduler, 22 | model="bes-dev/stable-diffusion-v1-4-openvino", 23 | tokenizer="openai/clip-vit-large-patch14", 24 | device="CPU" 25 | ): 26 | self.tokenizer = CLIPTokenizer.from_pretrained(tokenizer) 27 | self.scheduler = scheduler 28 | # models 29 | self.core = Core() 30 | self.core.set_property({'CACHE_DIR': './cache'}) 31 | 32 | # text features 33 | self._text_encoder = self.core.read_model( 34 | hf_hub_download(repo_id=model, filename="text_encoder.xml"), 35 | hf_hub_download(repo_id=model, filename="text_encoder.bin") 36 | ) 37 | self.text_encoder = self.core.compile_model(self._text_encoder, device) 38 | # diffusion 39 | self._unet = self.core.read_model( 40 | hf_hub_download(repo_id=model, filename="unet.xml"), 41 | hf_hub_download(repo_id=model, filename="unet.bin") 42 | ) 43 | self.unet = self.core.compile_model(self._unet, device) 44 | self.latent_shape = tuple(self._unet.inputs[0].shape)[1:] 45 | # decoder 46 | self._vae_decoder = self.core.read_model( 47 | hf_hub_download(repo_id=model, filename="vae_decoder.xml"), 48 | hf_hub_download(repo_id=model, filename="vae_decoder.bin") 49 | ) 50 | self.vae_decoder = self.core.compile_model(self._vae_decoder, device) 51 | # encoder 52 | self._vae_encoder = self.core.read_model( 53 | hf_hub_download(repo_id=model, filename="vae_encoder.xml"), 54 | hf_hub_download(repo_id=model, filename="vae_encoder.bin") 55 | ) 56 | self.vae_encoder = self.core.compile_model(self._vae_encoder, device) 57 | self.init_image_shape = tuple(self._vae_encoder.inputs[0].shape)[2:] 58 | 59 | def _preprocess_mask(self, mask): 60 | h, w = mask.shape 61 | if h != self.init_image_shape[0] and w != self.init_image_shape[1]: 62 | mask = cv2.resize( 63 | mask, 64 | (self.init_image_shape[1], self.init_image_shape[0]), 65 | interpolation = cv2.INTER_NEAREST 66 | ) 67 | mask = cv2.resize( 68 | mask, 69 | (self.init_image_shape[1] // 8, self.init_image_shape[0] // 8), 70 | interpolation = cv2.INTER_NEAREST 71 | ) 72 | mask = mask.astype(np.float32) / 255.0 73 | mask = np.tile(mask, (4, 1, 1)) 74 | mask = mask[None].transpose(0, 1, 2, 3) 75 | mask = 1 - mask 76 | return mask 77 | 78 | def _preprocess_image(self, image): 79 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 80 | h, w = image.shape[1:] 81 | if h != self.init_image_shape[0] and w != self.init_image_shape[1]: 82 | image = cv2.resize( 83 | image, 84 | (self.init_image_shape[1], self.init_image_shape[0]), 85 | interpolation=cv2.INTER_LANCZOS4 86 | ) 87 | # normalize 88 | image = image.astype(np.float32) / 255.0 89 | image = 2.0 * image - 1.0 90 | # to batch 91 | image = image[None].transpose(0, 3, 1, 2) 92 | return image 93 | 94 | def _encode_image(self, init_image): 95 | moments = result(self.vae_encoder.infer_new_request({ 96 | "init_image": self._preprocess_image(init_image) 97 | })) 98 | mean, logvar = np.split(moments, 2, axis=1) 99 | std = np.exp(logvar * 0.5) 100 | latent = (mean + std * np.random.randn(*mean.shape)) * 0.18215 101 | return latent 102 | 103 | def __call__( 104 | self, 105 | prompt, 106 | init_image = None, 107 | mask = None, 108 | strength = 0.5, 109 | num_inference_steps = 32, 110 | guidance_scale = 7.5, 111 | eta = 0.0 112 | ): 113 | # extract condition 114 | tokens = self.tokenizer( 115 | prompt, 116 | padding="max_length", 117 | max_length=self.tokenizer.model_max_length, 118 | truncation=True 119 | ).input_ids 120 | text_embeddings = result( 121 | self.text_encoder.infer_new_request({"tokens": np.array([tokens])}) 122 | ) 123 | 124 | # do classifier free guidance 125 | if guidance_scale > 1.0: 126 | tokens_uncond = self.tokenizer( 127 | "", 128 | padding="max_length", 129 | max_length=self.tokenizer.model_max_length, 130 | truncation=True 131 | ).input_ids 132 | uncond_embeddings = result( 133 | self.text_encoder.infer_new_request({"tokens": np.array([tokens_uncond])}) 134 | ) 135 | text_embeddings = np.concatenate((uncond_embeddings, text_embeddings), axis=0) 136 | 137 | # set timesteps 138 | accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys()) 139 | extra_set_kwargs = {} 140 | offset = 0 141 | if accepts_offset: 142 | offset = 1 143 | extra_set_kwargs["offset"] = 1 144 | 145 | self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs) 146 | 147 | # initialize latent latent 148 | if init_image is None: 149 | latents = np.random.randn(*self.latent_shape) 150 | init_timestep = num_inference_steps 151 | else: 152 | init_latents = self._encode_image(init_image) 153 | init_timestep = int(num_inference_steps * strength) + offset 154 | init_timestep = min(init_timestep, num_inference_steps) 155 | timesteps = np.array([[self.scheduler.timesteps[-init_timestep]]]).astype(np.long) 156 | noise = np.random.randn(*self.latent_shape) 157 | latents = self.scheduler.add_noise(init_latents, noise, timesteps)[0] 158 | 159 | if init_image is not None and mask is not None: 160 | mask = self._preprocess_mask(mask) 161 | else: 162 | mask = None 163 | 164 | # if we use LMSDiscreteScheduler, let's make sure latents are mulitplied by sigmas 165 | if isinstance(self.scheduler, LMSDiscreteScheduler): 166 | latents = latents * self.scheduler.sigmas[0] 167 | 168 | # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature 169 | # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. 170 | # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 171 | # and should be between [0, 1] 172 | accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) 173 | extra_step_kwargs = {} 174 | if accepts_eta: 175 | extra_step_kwargs["eta"] = eta 176 | 177 | t_start = max(num_inference_steps - init_timestep + offset, 0) 178 | for i, t in tqdm(enumerate(self.scheduler.timesteps[t_start:])): 179 | # expand the latents if we are doing classifier free guidance 180 | latent_model_input = np.stack([latents, latents], 0) if guidance_scale > 1.0 else latents[None] 181 | if isinstance(self.scheduler, LMSDiscreteScheduler): 182 | sigma = self.scheduler.sigmas[i] 183 | latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5) 184 | 185 | # predict the noise residual 186 | noise_pred = result(self.unet.infer_new_request({ 187 | "latent_model_input": latent_model_input, 188 | "t": np.float64(t), 189 | "encoder_hidden_states": text_embeddings 190 | })) 191 | 192 | # perform guidance 193 | if guidance_scale > 1.0: 194 | noise_pred = noise_pred[0] + guidance_scale * (noise_pred[1] - noise_pred[0]) 195 | 196 | # compute the previous noisy sample x_t -> x_t-1 197 | if isinstance(self.scheduler, LMSDiscreteScheduler): 198 | latents = self.scheduler.step(noise_pred, i, latents, **extra_step_kwargs)["prev_sample"] 199 | else: 200 | latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs)["prev_sample"] 201 | 202 | # masking for inapinting 203 | if mask is not None: 204 | init_latents_proper = self.scheduler.add_noise(init_latents, noise, t) 205 | latents = ((init_latents_proper * mask) + (latents * (1 - mask)))[0] 206 | 207 | image = result(self.vae_decoder.infer_new_request({ 208 | "latents": np.expand_dims(latents, 0) 209 | })) 210 | 211 | # convert tensor to opencv's image format 212 | image = (image / 2 + 0.5).clip(0, 1) 213 | image = (image[0].transpose(1, 2, 0)[:, :, ::-1] * 255).astype(np.uint8) 214 | return image 215 | --------------------------------------------------------------------------------