Upload 9 files
Browse files- Dockerfile +19 -0
- LICENSE +201 -0
- LICENSE_MODEL +82 -0
- README.md +104 -13
- demo.py +74 -0
- demo_web.py +124 -0
- docker-compose.yaml +10 -0
- requirements.txt +12 -0
- stable_diffusion_engine.py +212 -0
Dockerfile
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.9.9-bullseye
|
2 |
+
|
3 |
+
WORKDIR /src
|
4 |
+
|
5 |
+
RUN apt-get update && \
|
6 |
+
apt-get install -y \
|
7 |
+
libgl1 libglib2.0-0
|
8 |
+
|
9 |
+
COPY requirements.txt /src/
|
10 |
+
|
11 |
+
RUN pip3 install -r requirements.txt
|
12 |
+
|
13 |
+
COPY stable_diffusion_engine.py demo.py demo_web.py /src/
|
14 |
+
COPY data/ /src/data/
|
15 |
+
|
16 |
+
# download models
|
17 |
+
RUN python3 demo.py --num-inference-steps 1 --prompt "test" --output /tmp/test.jpg
|
18 |
+
|
19 |
+
ENTRYPOINT ["python3", "demo.py"]
|
LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright [yyyy] [name of copyright owner]
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
LICENSE_MODEL
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
CHANGED
@@ -1,13 +1,104 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# stable_diffusion.openvino
|
2 |
+
|
3 |
+
Implementation of Text-To-Image generation using Stable Diffusion on Intel CPU.
|
4 |
+
<p align="center">
|
5 |
+
<img src="data/title.png"/>
|
6 |
+
</p>
|
7 |
+
|
8 |
+
## News
|
9 |
+
|
10 |
+
When we started this project, it was just a tiny proof of concept that you can work with state-of-the-art image generators even without access to expensive hardware.
|
11 |
+
But, due we get a lot of feedback from you, we decided to make this project something more than a tiny script.
|
12 |
+
Currently, we work on the new version of our project, so we can respond to your issues and pool requests with delay.
|
13 |
+
|
14 |
+
|
15 |
+
## Requirements
|
16 |
+
|
17 |
+
* Linux, Windows, MacOS
|
18 |
+
* Python 3.8.+
|
19 |
+
* CPU compatible with OpenVINO.
|
20 |
+
|
21 |
+
## Install requirements
|
22 |
+
|
23 |
+
```bash
|
24 |
+
pip install -r requirements.txt
|
25 |
+
```
|
26 |
+
|
27 |
+
## Generate image from text description
|
28 |
+
|
29 |
+
```bash
|
30 |
+
usage: demo.py [-h] [--model MODEL] [--seed SEED] [--beta-start BETA_START] [--beta-end BETA_END] [--beta-schedule BETA_SCHEDULE] [--num-inference-steps NUM_INFERENCE_STEPS]
|
31 |
+
[--guidance-scale GUIDANCE_SCALE] [--eta ETA] [--tokenizer TOKENIZER] [--prompt PROMPT] [--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 |
+
--seed SEED random seed for generating consistent images per prompt
|
37 |
+
--beta-start BETA_START
|
38 |
+
LMSDiscreteScheduler::beta_start
|
39 |
+
--beta-end BETA_END LMSDiscreteScheduler::beta_end
|
40 |
+
--beta-schedule BETA_SCHEDULE
|
41 |
+
LMSDiscreteScheduler::beta_schedule
|
42 |
+
--num-inference-steps NUM_INFERENCE_STEPS
|
43 |
+
num inference steps
|
44 |
+
--guidance-scale GUIDANCE_SCALE
|
45 |
+
guidance scale
|
46 |
+
--eta ETA eta
|
47 |
+
--tokenizer TOKENIZER
|
48 |
+
tokenizer
|
49 |
+
--prompt PROMPT prompt
|
50 |
+
--init-image INIT_IMAGE
|
51 |
+
path to initial image
|
52 |
+
--strength STRENGTH how strong the initial image should be noised [0.0, 1.0]
|
53 |
+
--mask MASK mask of the region to inpaint on the initial image
|
54 |
+
--output OUTPUT output image name
|
55 |
+
```
|
56 |
+
|
57 |
+
## Examples
|
58 |
+
|
59 |
+
### Example Text-To-Image
|
60 |
+
```bash
|
61 |
+
python demo.py --prompt "Street-art painting of Emilia Clarke in style of Banksy, photorealism"
|
62 |
+
```
|
63 |
+
|
64 |
+
### Example Image-To-Image
|
65 |
+
```bash
|
66 |
+
python demo.py --prompt "Photo of Emilia Clarke with a bright red hair" --init-image ./data/input.png --strength 0.5
|
67 |
+
```
|
68 |
+
|
69 |
+
### Example Inpainting
|
70 |
+
```bash
|
71 |
+
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
|
72 |
+
```
|
73 |
+
|
74 |
+
### Example web demo
|
75 |
+
<p align="center">
|
76 |
+
<img src="data/demo_web.png"/>
|
77 |
+
</p>
|
78 |
+
|
79 |
+
[Example video on YouTube](https://youtu.be/wkbrRr6PPcY)
|
80 |
+
|
81 |
+
```bash
|
82 |
+
streamlit run demo_web.py
|
83 |
+
```
|
84 |
+
|
85 |
+
## Performance
|
86 |
+
|
87 |
+
| CPU | Time per iter | Total time |
|
88 |
+
|-------------------------------------------------------|---------------|------------|
|
89 |
+
| AMD Ryzen Threadripper 1900X | 5.34 s/it | 2.58 min |
|
90 |
+
| Intel(R) Core(TM) i7-4790K @ 4.00GHz | 10.1 s/it | 5.39 min |
|
91 |
+
| Intel(R) Core(TM) i5-8279U | 7.4 s/it | 3.59 min |
|
92 |
+
| Intel(R) Core(TM) i7-1165G7 @ 2.80GHz | 7.4 s/it | 3.59 min |
|
93 |
+
| Intel(R) Core(TM) i7-11800H @ 2.30GHz (16 threads) | 2.9 s/it | 1.54 min |
|
94 |
+
| Intel(R) Xeon(R) Gold 6154 CPU @ 3.00GHz | 1 s/it | 33 s |
|
95 |
+
|
96 |
+
## Acknowledgements
|
97 |
+
|
98 |
+
* Original implementation of Stable Diffusion: https://github.com/CompVis/stable-diffusion
|
99 |
+
* diffusers library: https://github.com/huggingface/diffusers
|
100 |
+
|
101 |
+
## Disclaimer
|
102 |
+
|
103 |
+
The authors are not responsible for the content generated using this project.
|
104 |
+
Please, don't use this project to produce illegal, harmful, offensive etc. content.
|
demo.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -- coding: utf-8 --`
|
2 |
+
import argparse
|
3 |
+
import os
|
4 |
+
# engine
|
5 |
+
from stable_diffusion_engine import StableDiffusionEngine
|
6 |
+
# scheduler
|
7 |
+
from diffusers import LMSDiscreteScheduler, PNDMScheduler
|
8 |
+
# utils
|
9 |
+
import cv2
|
10 |
+
import numpy as np
|
11 |
+
|
12 |
+
|
13 |
+
def main(args):
|
14 |
+
if args.seed is not None:
|
15 |
+
np.random.seed(args.seed)
|
16 |
+
if args.init_image is None:
|
17 |
+
scheduler = LMSDiscreteScheduler(
|
18 |
+
beta_start=args.beta_start,
|
19 |
+
beta_end=args.beta_end,
|
20 |
+
beta_schedule=args.beta_schedule,
|
21 |
+
tensor_format="np"
|
22 |
+
)
|
23 |
+
else:
|
24 |
+
scheduler = PNDMScheduler(
|
25 |
+
beta_start=args.beta_start,
|
26 |
+
beta_end=args.beta_end,
|
27 |
+
beta_schedule=args.beta_schedule,
|
28 |
+
skip_prk_steps = True,
|
29 |
+
tensor_format="np"
|
30 |
+
)
|
31 |
+
engine = StableDiffusionEngine(
|
32 |
+
model = args.model,
|
33 |
+
scheduler = scheduler,
|
34 |
+
tokenizer = args.tokenizer
|
35 |
+
)
|
36 |
+
image = engine(
|
37 |
+
prompt = args.prompt,
|
38 |
+
init_image = None if args.init_image is None else cv2.imread(args.init_image),
|
39 |
+
mask = None if args.mask is None else cv2.imread(args.mask, 0),
|
40 |
+
strength = args.strength,
|
41 |
+
num_inference_steps = args.num_inference_steps,
|
42 |
+
guidance_scale = args.guidance_scale,
|
43 |
+
eta = args.eta
|
44 |
+
)
|
45 |
+
cv2.imwrite(args.output, image)
|
46 |
+
|
47 |
+
|
48 |
+
if __name__ == "__main__":
|
49 |
+
parser = argparse.ArgumentParser()
|
50 |
+
# pipeline configure
|
51 |
+
parser.add_argument("--model", type=str, default="bes-dev/stable-diffusion-v1-4-openvino", help="model name")
|
52 |
+
# randomizer params
|
53 |
+
parser.add_argument("--seed", type=int, default=None, help="random seed for generating consistent images per prompt")
|
54 |
+
# scheduler params
|
55 |
+
parser.add_argument("--beta-start", type=float, default=0.00085, help="LMSDiscreteScheduler::beta_start")
|
56 |
+
parser.add_argument("--beta-end", type=float, default=0.012, help="LMSDiscreteScheduler::beta_end")
|
57 |
+
parser.add_argument("--beta-schedule", type=str, default="scaled_linear", help="LMSDiscreteScheduler::beta_schedule")
|
58 |
+
# diffusion params
|
59 |
+
parser.add_argument("--num-inference-steps", type=int, default=32, help="num inference steps")
|
60 |
+
parser.add_argument("--guidance-scale", type=float, default=7.5, help="guidance scale")
|
61 |
+
parser.add_argument("--eta", type=float, default=0.0, help="eta")
|
62 |
+
# tokenizer
|
63 |
+
parser.add_argument("--tokenizer", type=str, default="openai/clip-vit-large-patch14", help="tokenizer")
|
64 |
+
# prompt
|
65 |
+
parser.add_argument("--prompt", type=str, default="Street-art painting of Emilia Clarke in style of Banksy, photorealism", help="prompt")
|
66 |
+
# img2img params
|
67 |
+
parser.add_argument("--init-image", type=str, default=None, help="path to initial image")
|
68 |
+
parser.add_argument("--strength", type=float, default=0.5, help="how strong the initial image should be noised [0.0, 1.0]")
|
69 |
+
# inpainting
|
70 |
+
parser.add_argument("--mask", type=str, default=None, help="mask of the region to inpaint on the initial image")
|
71 |
+
# output name
|
72 |
+
parser.add_argument("--output", type=str, default="output.png", help="output image name")
|
73 |
+
args = parser.parse_args()
|
74 |
+
main(args)
|
demo_web.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -- coding: utf-8 --`
|
2 |
+
import argparse
|
3 |
+
import os
|
4 |
+
import random
|
5 |
+
import streamlit as st
|
6 |
+
from streamlit_drawable_canvas import st_canvas
|
7 |
+
import numpy as np
|
8 |
+
import cv2
|
9 |
+
from PIL import Image, ImageEnhance
|
10 |
+
import numpy as np
|
11 |
+
# engine
|
12 |
+
from stable_diffusion_engine import StableDiffusionEngine
|
13 |
+
# scheduler
|
14 |
+
from diffusers import PNDMScheduler
|
15 |
+
|
16 |
+
|
17 |
+
def run(engine):
|
18 |
+
with st.form(key="request"):
|
19 |
+
with st.sidebar:
|
20 |
+
prompt = st.text_area(label='Enter prompt')
|
21 |
+
|
22 |
+
with st.expander("Initial image"):
|
23 |
+
init_image = st.file_uploader("init_image", type=['jpg','png','jpeg'])
|
24 |
+
stroke_width = st.slider("stroke_width", 1, 100, 50)
|
25 |
+
stroke_color = st.color_picker("stroke_color", "#00FF00")
|
26 |
+
canvas_result = st_canvas(
|
27 |
+
fill_color="rgb(0, 0, 0)",
|
28 |
+
stroke_width = stroke_width,
|
29 |
+
stroke_color = stroke_color,
|
30 |
+
background_color = "#000000",
|
31 |
+
background_image = Image.open(init_image) if init_image else None,
|
32 |
+
height = 512,
|
33 |
+
width = 512,
|
34 |
+
drawing_mode = "freedraw",
|
35 |
+
key = "canvas"
|
36 |
+
)
|
37 |
+
|
38 |
+
if init_image is not None:
|
39 |
+
init_image = cv2.cvtColor(np.array(Image.open(init_image)), cv2.COLOR_RGB2BGR)
|
40 |
+
|
41 |
+
if canvas_result.image_data is not None:
|
42 |
+
mask = cv2.cvtColor(canvas_result.image_data, cv2.COLOR_BGRA2GRAY)
|
43 |
+
mask[mask > 0] = 255
|
44 |
+
else:
|
45 |
+
mask = None
|
46 |
+
|
47 |
+
num_inference_steps = st.select_slider(
|
48 |
+
label='num_inference_steps',
|
49 |
+
options=range(1, 150),
|
50 |
+
value=32
|
51 |
+
)
|
52 |
+
|
53 |
+
guidance_scale = st.select_slider(
|
54 |
+
label='guidance_scale',
|
55 |
+
options=range(1, 21),
|
56 |
+
value=7
|
57 |
+
)
|
58 |
+
|
59 |
+
strength = st.slider(
|
60 |
+
label='strength',
|
61 |
+
min_value = 0.0,
|
62 |
+
max_value = 1.0,
|
63 |
+
value = 0.5
|
64 |
+
)
|
65 |
+
|
66 |
+
seed = st.number_input(
|
67 |
+
label='seed',
|
68 |
+
min_value = 0,
|
69 |
+
max_value = 2 ** 31,
|
70 |
+
value = random.randint(0, 2 ** 31)
|
71 |
+
)
|
72 |
+
|
73 |
+
generate = st.form_submit_button(label = 'Generate')
|
74 |
+
|
75 |
+
if prompt:
|
76 |
+
np.random.seed(seed)
|
77 |
+
image = engine(
|
78 |
+
prompt = prompt,
|
79 |
+
init_image = init_image,
|
80 |
+
mask = mask,
|
81 |
+
strength = strength,
|
82 |
+
num_inference_steps = num_inference_steps,
|
83 |
+
guidance_scale = guidance_scale
|
84 |
+
)
|
85 |
+
st.image(Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)), width=512)
|
86 |
+
|
87 |
+
@st.cache(allow_output_mutation=True)
|
88 |
+
def load_engine(args):
|
89 |
+
scheduler = PNDMScheduler(
|
90 |
+
beta_start=args.beta_start,
|
91 |
+
beta_end=args.beta_end,
|
92 |
+
beta_schedule=args.beta_schedule,
|
93 |
+
skip_prk_steps = True,
|
94 |
+
tensor_format="np"
|
95 |
+
)
|
96 |
+
engine = StableDiffusionEngine(
|
97 |
+
model = args.model,
|
98 |
+
scheduler = scheduler,
|
99 |
+
tokenizer = args.tokenizer
|
100 |
+
)
|
101 |
+
return engine
|
102 |
+
|
103 |
+
|
104 |
+
if __name__ == "__main__":
|
105 |
+
parser = argparse.ArgumentParser()
|
106 |
+
# pipeline configure
|
107 |
+
parser.add_argument("--model", type=str, default="bes-dev/stable-diffusion-v1-4-openvino", help="model name")
|
108 |
+
# scheduler params
|
109 |
+
parser.add_argument("--beta-start", type=float, default=0.00085, help="LMSDiscreteScheduler::beta_start")
|
110 |
+
parser.add_argument("--beta-end", type=float, default=0.012, help="LMSDiscreteScheduler::beta_end")
|
111 |
+
parser.add_argument("--beta-schedule", type=str, default="scaled_linear", help="LMSDiscreteScheduler::beta_schedule")
|
112 |
+
# tokenizer
|
113 |
+
parser.add_argument("--tokenizer", type=str, default="openai/clip-vit-large-patch14", help="tokenizer")
|
114 |
+
|
115 |
+
try:
|
116 |
+
args = parser.parse_args()
|
117 |
+
except SystemExit as e:
|
118 |
+
# This exception will be raised if --help or invalid command line arguments
|
119 |
+
# are used. Currently streamlit prevents the program from exiting normally
|
120 |
+
# so we have to do a hard exit.
|
121 |
+
os._exit(e.code)
|
122 |
+
|
123 |
+
engine = load_engine(args)
|
124 |
+
run(engine)
|
docker-compose.yaml
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
version: '3.9'
|
2 |
+
services:
|
3 |
+
stable-diffusion:
|
4 |
+
build:
|
5 |
+
context: .
|
6 |
+
dockerfile: Dockerfile
|
7 |
+
volumes:
|
8 |
+
# - /tmp/cache:/root/.cache
|
9 |
+
- /tmp/output:/tmp/output
|
10 |
+
# - /tmp/models:/root/models
|
requirements.txt
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.1.0
|
7 |
+
huggingface_hub==0.9.0
|
8 |
+
scipy==1.9.0
|
9 |
+
streamlit==1.12.0
|
10 |
+
streamlit-drawable-canvas==0.8.0
|
11 |
+
watchdog==2.1.9
|
12 |
+
ftfy==6.1.1
|
stable_diffusion_engine.py
ADDED
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# text features
|
31 |
+
self._text_encoder = self.core.read_model(
|
32 |
+
hf_hub_download(repo_id=model, filename="text_encoder.xml"),
|
33 |
+
hf_hub_download(repo_id=model, filename="text_encoder.bin")
|
34 |
+
)
|
35 |
+
self.text_encoder = self.core.compile_model(self._text_encoder, device)
|
36 |
+
# diffusion
|
37 |
+
self._unet = self.core.read_model(
|
38 |
+
hf_hub_download(repo_id=model, filename="unet.xml"),
|
39 |
+
hf_hub_download(repo_id=model, filename="unet.bin")
|
40 |
+
)
|
41 |
+
self.unet = self.core.compile_model(self._unet, device)
|
42 |
+
self.latent_shape = tuple(self._unet.inputs[0].shape)[1:]
|
43 |
+
# decoder
|
44 |
+
self._vae_decoder = self.core.read_model(
|
45 |
+
hf_hub_download(repo_id=model, filename="vae_decoder.xml"),
|
46 |
+
hf_hub_download(repo_id=model, filename="vae_decoder.bin")
|
47 |
+
)
|
48 |
+
self.vae_decoder = self.core.compile_model(self._vae_decoder, device)
|
49 |
+
# encoder
|
50 |
+
self._vae_encoder = self.core.read_model(
|
51 |
+
hf_hub_download(repo_id=model, filename="vae_encoder.xml"),
|
52 |
+
hf_hub_download(repo_id=model, filename="vae_encoder.bin")
|
53 |
+
)
|
54 |
+
self.vae_encoder = self.core.compile_model(self._vae_encoder, device)
|
55 |
+
self.init_image_shape = tuple(self._vae_encoder.inputs[0].shape)[2:]
|
56 |
+
|
57 |
+
def _preprocess_mask(self, mask):
|
58 |
+
h, w = mask.shape
|
59 |
+
if h != self.init_image_shape[0] and w != self.init_image_shape[1]:
|
60 |
+
mask = cv2.resize(
|
61 |
+
mask,
|
62 |
+
(self.init_image_shape[1], self.init_image_shape[0]),
|
63 |
+
interpolation = cv2.INTER_NEAREST
|
64 |
+
)
|
65 |
+
mask = cv2.resize(
|
66 |
+
mask,
|
67 |
+
(self.init_image_shape[1] // 8, self.init_image_shape[0] // 8),
|
68 |
+
interpolation = cv2.INTER_NEAREST
|
69 |
+
)
|
70 |
+
mask = mask.astype(np.float32) / 255.0
|
71 |
+
mask = np.tile(mask, (4, 1, 1))
|
72 |
+
mask = mask[None].transpose(0, 1, 2, 3)
|
73 |
+
mask = 1 - mask
|
74 |
+
return mask
|
75 |
+
|
76 |
+
def _preprocess_image(self, image):
|
77 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
78 |
+
h, w = image.shape[1:]
|
79 |
+
if h != self.init_image_shape[0] and w != self.init_image_shape[1]:
|
80 |
+
image = cv2.resize(
|
81 |
+
image,
|
82 |
+
(self.init_image_shape[1], self.init_image_shape[0]),
|
83 |
+
interpolation=cv2.INTER_LANCZOS4
|
84 |
+
)
|
85 |
+
# normalize
|
86 |
+
image = image.astype(np.float32) / 255.0
|
87 |
+
image = 2.0 * image - 1.0
|
88 |
+
# to batch
|
89 |
+
image = image[None].transpose(0, 3, 1, 2)
|
90 |
+
return image
|
91 |
+
|
92 |
+
def _encode_image(self, init_image):
|
93 |
+
moments = result(self.vae_encoder.infer_new_request({
|
94 |
+
"init_image": self._preprocess_image(init_image)
|
95 |
+
}))
|
96 |
+
mean, logvar = np.split(moments, 2, axis=1)
|
97 |
+
std = np.exp(logvar * 0.5)
|
98 |
+
latent = (mean + std * np.random.randn(*mean.shape)) * 0.18215
|
99 |
+
return latent
|
100 |
+
|
101 |
+
def __call__(
|
102 |
+
self,
|
103 |
+
prompt,
|
104 |
+
init_image = None,
|
105 |
+
mask = None,
|
106 |
+
strength = 0.5,
|
107 |
+
num_inference_steps = 32,
|
108 |
+
guidance_scale = 7.5,
|
109 |
+
eta = 0.0
|
110 |
+
):
|
111 |
+
# extract condition
|
112 |
+
tokens = self.tokenizer(
|
113 |
+
prompt,
|
114 |
+
padding="max_length",
|
115 |
+
max_length=self.tokenizer.model_max_length,
|
116 |
+
truncation=True
|
117 |
+
).input_ids
|
118 |
+
text_embeddings = result(
|
119 |
+
self.text_encoder.infer_new_request({"tokens": np.array([tokens])})
|
120 |
+
)
|
121 |
+
|
122 |
+
# do classifier free guidance
|
123 |
+
if guidance_scale > 1.0:
|
124 |
+
tokens_uncond = self.tokenizer(
|
125 |
+
"",
|
126 |
+
padding="max_length",
|
127 |
+
max_length=self.tokenizer.model_max_length,
|
128 |
+
truncation=True
|
129 |
+
).input_ids
|
130 |
+
uncond_embeddings = result(
|
131 |
+
self.text_encoder.infer_new_request({"tokens": np.array([tokens_uncond])})
|
132 |
+
)
|
133 |
+
text_embeddings = np.concatenate((uncond_embeddings, text_embeddings), axis=0)
|
134 |
+
|
135 |
+
# set timesteps
|
136 |
+
accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
|
137 |
+
extra_set_kwargs = {}
|
138 |
+
offset = 0
|
139 |
+
if accepts_offset:
|
140 |
+
offset = 1
|
141 |
+
extra_set_kwargs["offset"] = 1
|
142 |
+
|
143 |
+
self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
|
144 |
+
|
145 |
+
# initialize latent latent
|
146 |
+
if init_image is None:
|
147 |
+
latents = np.random.randn(*self.latent_shape)
|
148 |
+
init_timestep = num_inference_steps
|
149 |
+
else:
|
150 |
+
init_latents = self._encode_image(init_image)
|
151 |
+
init_timestep = int(num_inference_steps * strength) + offset
|
152 |
+
init_timestep = min(init_timestep, num_inference_steps)
|
153 |
+
timesteps = np.array([[self.scheduler.timesteps[-init_timestep]]]).astype(np.long)
|
154 |
+
noise = np.random.randn(*self.latent_shape)
|
155 |
+
latents = self.scheduler.add_noise(init_latents, noise, timesteps)[0]
|
156 |
+
|
157 |
+
if init_image is not None and mask is not None:
|
158 |
+
mask = self._preprocess_mask(mask)
|
159 |
+
else:
|
160 |
+
mask = None
|
161 |
+
|
162 |
+
# if we use LMSDiscreteScheduler, let's make sure latents are mulitplied by sigmas
|
163 |
+
if isinstance(self.scheduler, LMSDiscreteScheduler):
|
164 |
+
latents = latents * self.scheduler.sigmas[0]
|
165 |
+
|
166 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
167 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
168 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
169 |
+
# and should be between [0, 1]
|
170 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
171 |
+
extra_step_kwargs = {}
|
172 |
+
if accepts_eta:
|
173 |
+
extra_step_kwargs["eta"] = eta
|
174 |
+
|
175 |
+
t_start = max(num_inference_steps - init_timestep + offset, 0)
|
176 |
+
for i, t in tqdm(enumerate(self.scheduler.timesteps[t_start:])):
|
177 |
+
# expand the latents if we are doing classifier free guidance
|
178 |
+
latent_model_input = np.stack([latents, latents], 0) if guidance_scale > 1.0 else latents[None]
|
179 |
+
if isinstance(self.scheduler, LMSDiscreteScheduler):
|
180 |
+
sigma = self.scheduler.sigmas[i]
|
181 |
+
latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5)
|
182 |
+
|
183 |
+
# predict the noise residual
|
184 |
+
noise_pred = result(self.unet.infer_new_request({
|
185 |
+
"latent_model_input": latent_model_input,
|
186 |
+
"t": t,
|
187 |
+
"encoder_hidden_states": text_embeddings
|
188 |
+
}))
|
189 |
+
|
190 |
+
# perform guidance
|
191 |
+
if guidance_scale > 1.0:
|
192 |
+
noise_pred = noise_pred[0] + guidance_scale * (noise_pred[1] - noise_pred[0])
|
193 |
+
|
194 |
+
# compute the previous noisy sample x_t -> x_t-1
|
195 |
+
if isinstance(self.scheduler, LMSDiscreteScheduler):
|
196 |
+
latents = self.scheduler.step(noise_pred, i, latents, **extra_step_kwargs)["prev_sample"]
|
197 |
+
else:
|
198 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs)["prev_sample"]
|
199 |
+
|
200 |
+
# masking for inapinting
|
201 |
+
if mask is not None:
|
202 |
+
init_latents_proper = self.scheduler.add_noise(init_latents, noise, t)
|
203 |
+
latents = ((init_latents_proper * mask) + (latents * (1 - mask)))[0]
|
204 |
+
|
205 |
+
image = result(self.vae_decoder.infer_new_request({
|
206 |
+
"latents": np.expand_dims(latents, 0)
|
207 |
+
}))
|
208 |
+
|
209 |
+
# convert tensor to opencv's image format
|
210 |
+
image = (image / 2 + 0.5).clip(0, 1)
|
211 |
+
image = (image[0].transpose(1, 2, 0)[:, :, ::-1] * 255).astype(np.uint8)
|
212 |
+
return image
|