Androidonnxfork
commited on
Commit
•
69c5ed3
1
Parent(s):
3d3a6a9
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +6 -0
- patchedstabledifftoonnx_withou_modelort/LICENSE +674 -0
- patchedstabledifftoonnx_withou_modelort/README.md +293 -0
- patchedstabledifftoonnx_withou_modelort/README4GB.md +136 -0
- patchedstabledifftoonnx_withou_modelort/conv_sd_to_onnx.py +658 -0
- patchedstabledifftoonnx_withou_modelort/dance_pose.png +0 -0
- patchedstabledifftoonnx_withou_modelort/input_image_vermeer.png +0 -0
- patchedstabledifftoonnx_withou_modelort/pipeline_onnx_stable_diffusion_controlnet.py +472 -0
- patchedstabledifftoonnx_withou_modelort/pipeline_onnx_stable_diffusion_instruct_pix2pix.py +553 -0
- patchedstabledifftoonnx_withou_modelort/pix2pixUI.py +53 -0
- patchedstabledifftoonnx_withou_modelort/quant.py +0 -0
- patchedstabledifftoonnx_withou_modelort/quantization.py +1 -0
- patchedstabledifftoonnx_withou_modelort/requirements.txt +14 -0
- patchedstabledifftoonnx_withou_modelort/run-batch.md +50 -0
- patchedstabledifftoonnx_withou_modelort/run-batch.py +330 -0
- patchedstabledifftoonnx_withou_modelort/sd_env/bin/python +3 -0
- patchedstabledifftoonnx_withou_modelort/sd_env/bin/python3 +3 -0
- patchedstabledifftoonnx_withou_modelort/sd_env/bin/python3.10 +3 -0
- patchedstabledifftoonnx_withou_modelort/sd_env/pyvenv.cfg +3 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/.dockerignore +6 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/.github/workflows/build-image.yml +16 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/.gitignore +6 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/LICENSE +254 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/README.md +114 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/README_CN.md +111 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/gif/use1.gif +3 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/gif/use2.gif +3 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/gif/use3.gif +3 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/pic/onnx.png +0 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/pic/onnxquantized.png +0 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/pic/torch.png +0 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/build.sh +15 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/docker-compose.yaml +15 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/dockerfile +21 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/entrypoint.sh +1 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/requirements.txt +7 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/entrypoint.sh +1 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/__init__.py +0 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/copy_pb.py +17 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/download_onnx.py +22 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/inference.py +40 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/prepare.py +10 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/quantization.py +28 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/thread.py +27 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/文字转图片.py +151 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/画廊.py +27 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/requirements.txt +9 -0
- patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/主页.py +9 -0
- patchedstabledifftoonnx_withou_modelort/test-controlnet-canny.py +45 -0
- patchedstabledifftoonnx_withou_modelort/test-controlnet-openpose.py +33 -0
.gitattributes
CHANGED
@@ -61,3 +61,9 @@ patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamli
|
|
61 |
patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.ort filter=lfs diff=lfs merge=lfs -text
|
62 |
patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.with_runtime_opt.ort filter=lfs diff=lfs merge=lfs -text
|
63 |
patchedstabledifftoonnx filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.ort filter=lfs diff=lfs merge=lfs -text
|
62 |
patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.with_runtime_opt.ort filter=lfs diff=lfs merge=lfs -text
|
63 |
patchedstabledifftoonnx filter=lfs diff=lfs merge=lfs -text
|
64 |
+
patchedstabledifftoonnx_withou_modelort/sd_env/bin/python filter=lfs diff=lfs merge=lfs -text
|
65 |
+
patchedstabledifftoonnx_withou_modelort/sd_env/bin/python3 filter=lfs diff=lfs merge=lfs -text
|
66 |
+
patchedstabledifftoonnx_withou_modelort/sd_env/bin/python3.10 filter=lfs diff=lfs merge=lfs -text
|
67 |
+
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/gif/use1.gif filter=lfs diff=lfs merge=lfs -text
|
68 |
+
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/gif/use2.gif filter=lfs diff=lfs merge=lfs -text
|
69 |
+
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/gif/use3.gif filter=lfs diff=lfs merge=lfs -text
|
patchedstabledifftoonnx_withou_modelort/LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
patchedstabledifftoonnx_withou_modelort/README.md
ADDED
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Stable Diffusion using ONNX, FP16 and DirectML
|
2 |
+
|
3 |
+
This repository contains a conversion tool, some examples, and instructions on how to set up Stable Diffusion with ONNX models.
|
4 |
+
This was mainly intended for use with AMD GPUs but should work just as well with other DirectML devices (e.g. Intel Arc).
|
5 |
+
I'd be very interested to hear of any results with Intel Arc.
|
6 |
+
|
7 |
+
**MOST IMPORTANT RECENT UPDATES:**
|
8 |
+
**- ONNX Runtime 1.15 has been released! Updated model tuning code to better align with ORT.**
|
9 |
+
**- Realigned with latest version of diffusers, we were forced to switch to torch 2.1 nightly! (Install instructions updated accordingly)**
|
10 |
+
**- I have enabled GitHub discussions: If you have a generic question rather than an issue, start a discussion!**
|
11 |
+
|
12 |
+
This focuses specifically on making it easy to get FP16 models. When using FP16, the VRAM footprint is significantly reduced and speed goes up.
|
13 |
+
|
14 |
+
It's all fairly straightforward, but It helps to be comfortable with command line.
|
15 |
+
|
16 |
+
You can use these instructions to convert models to FP16 and then use them in any tool that allows you to load ONNX models.
|
17 |
+
We'll demonstrate this by downloading and setting up ONNXDiffusersUI specifically for use with our installation (no need to follow the ONNXDiffusersUI setup).
|
18 |
+
|
19 |
+
## Set up
|
20 |
+
|
21 |
+
First make sure you have Python 3.10 (or 3.11) installed. You can get it here: https://www.python.org/downloads/
|
22 |
+
**NOTE:** 3.10 is still the preferred version. Since the release of ONNX Runtime 1.15 all requirements now have proper Python 3.11 support but conversion is extremely slow on 3.11.
|
23 |
+
|
24 |
+
If you don't have git, get it here: https://gitforwindows.org/
|
25 |
+
|
26 |
+
Pick a directory that can contain your Stable Diffusion installation (make sure you've the diskspace to store the models).
|
27 |
+
Open the commandline (Powershell or Command Prompt) and change into the directory you will use.
|
28 |
+
|
29 |
+
Start by cloning this repository:
|
30 |
+
```
|
31 |
+
git clone https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16
|
32 |
+
cd Stable-Diffusion-ONNX-FP16
|
33 |
+
```
|
34 |
+
|
35 |
+
Do the following:
|
36 |
+
```
|
37 |
+
pip install virtualenv
|
38 |
+
python -m venv sd_env
|
39 |
+
sd_env\scripts\activate
|
40 |
+
python -m pip install --upgrade pip
|
41 |
+
pip install torch --extra-index-url https://download.pytorch.org/whl/nightly/cpu --pre
|
42 |
+
pip install -r requirements.txt
|
43 |
+
```
|
44 |
+
|
45 |
+
Now first make sure you have an account on https://huggingface.co/
|
46 |
+
When you do make sure to create a token on https://huggingface.co/settings/tokens
|
47 |
+
And then on the commandline login using following command
|
48 |
+
```
|
49 |
+
huggingface-cli login
|
50 |
+
```
|
51 |
+
|
52 |
+
Now you're ready to download and convert models. Before we explain this, just a pointer on future use.
|
53 |
+
Whenever you want to make use of this post set up, open a command line, change into the directory and enable the environment.
|
54 |
+
Say that you installed this on your D: drive in the root. You would open command line and then:
|
55 |
+
```
|
56 |
+
d:
|
57 |
+
cd Stable-Diffusion-ONNX-FP16
|
58 |
+
sd_env\scripts\activate
|
59 |
+
```
|
60 |
+
|
61 |
+
Remember this for whenver you want to use your installation. Let's now get to the fun part and convert some models:
|
62 |
+
```
|
63 |
+
mkdir model
|
64 |
+
python conv_sd_to_onnx.py --model_path "stabilityai/stable-diffusion-2-1-base" --output_path "./model/sd2_1base-fp32"
|
65 |
+
python conv_sd_to_onnx.py --model_path "stabilityai/stable-diffusion-2-1-base" --output_path "./model/sd2_1base-fp16" --fp16
|
66 |
+
```
|
67 |
+
|
68 |
+
You now have 2 models. These are geared towards creating 512x512 images.
|
69 |
+
|
70 |
+
Now we'll run our test script twice:
|
71 |
+
```
|
72 |
+
python test-txt2img.py --model "model\sd2_1base-fp32" --size 512 --seed 0
|
73 |
+
python test-txt2img.py --model "model\sd2_1base-fp16" --size 512 --seed 0
|
74 |
+
```
|
75 |
+
|
76 |
+
You should now have 2 similar pictures. Note that there'll be differences between FP32 and FP16. But FP16 should not be specifically worse than FP32.
|
77 |
+
The accuracy just shifts things a bit, but it may just as well shift them for the better.
|
78 |
+
|
79 |
+
Next let's do 768x768. This requires your card to have enough VRAM but we'll make a VRAM friendly version too.
|
80 |
+
Here we aren't bothering with FP32 because it just requires too much VRAM.
|
81 |
+
```
|
82 |
+
python conv_sd_to_onnx.py --model_path "stabilityai/stable-diffusion-2-1" --output_path "./model/sd2_1-fp16" --fp16
|
83 |
+
python test-txt2img.py --model "model\sd2_1-fp16" --size 768 --seed 0
|
84 |
+
```
|
85 |
+
|
86 |
+
You should now have a 768x768 picture.
|
87 |
+
|
88 |
+
This will work fine on 12GB VRAM and above but 8GB may already be a stretch. The more VRAM friendly version is next.
|
89 |
+
|
90 |
+
This method uses less VRAM and will be slightly slower when you're not VRAM limited. But, it'll allow you to use far larger resolutions than standard models.
|
91 |
+
The output will be slightly different but should not be specifically worse. If you got the VRAM, see how well size 1024 works!
|
92 |
+
|
93 |
+
```
|
94 |
+
python conv_sd_to_onnx.py --model_path "stabilityai/stable-diffusion-2-1" --output_path "./model/sd2_1-fp16-autoslicing" --fp16 --attention-slicing auto
|
95 |
+
python test-txt2img.py --model "model\sd2_1-fp16-autoslicing" --size 768 --seed 0
|
96 |
+
```
|
97 |
+
|
98 |
+
Now that we've got everything working and we can create pictures, let's get a GUI. We'll use ONNXDiffusersUI but make it so it doesn't break our workflow.
|
99 |
+
First we clone the repository:
|
100 |
+
```
|
101 |
+
git clone https://github.com/Amblyopius/OnnxDiffusersUI
|
102 |
+
```
|
103 |
+
Now we run the UI
|
104 |
+
```
|
105 |
+
python OnnxDiffusersUI\onnxUI.py
|
106 |
+
```
|
107 |
+
It'll take some time to load and then in your browser you can go to http://127.0.0.1:7860 (only accessible on the host you're running it).
|
108 |
+
If you're done you can go back to the CMD window and press Ctrl+C and it will quit.
|
109 |
+
|
110 |
+
Note that it expects your models to be in the model directory (which is why we put them there in the instructions).
|
111 |
+
You can find your history and all the pictures you created in the directory called output.
|
112 |
+
|
113 |
+
If you want to learn more about the UI be sure to visit https://github.com/azuritecoin/OnnxDiffusersUI
|
114 |
+
NOTE: We are using a fork as it simplifies keeping it aligned with our own updates
|
115 |
+
|
116 |
+
## Advanced features
|
117 |
+
### Support for ControlNet
|
118 |
+
ControlNet was recently introduced. It allows conditional control on Text-to-Image Diffusion Models. If you want more in-depth information,
|
119 |
+
get it here: https://github.com/lllyasviel/ControlNet
|
120 |
+
|
121 |
+
As it has now been added to Diffusers I've added a fairly "elegant" ONNX implementation.
|
122 |
+
|
123 |
+
The idea behind the implementation is:
|
124 |
+
- We use the same single tool to convert models
|
125 |
+
- We can load the Pipeline from disk by referencing a single model
|
126 |
+
|
127 |
+
This has only 1 downside, it is not the most disk friendly solution as you'll get some duplication.
|
128 |
+
We may eventually have to opt for a different disk layout for ONNX models.
|
129 |
+
|
130 |
+
The current implementation consists of a simple demo. More to follow soon!
|
131 |
+
|
132 |
+
First let's get ourselves a working model:
|
133 |
+
```
|
134 |
+
python conv_sd_to_onnx.py --model_path "runwayml/stable-diffusion-v1-5" --output_path "./model/sd1_5-fp16-vae_ft_mse-autoslicing-cn_canny" --controlnet_path "lllyasviel/sd-controlnet-canny" --fp16 --attention-slicing auto --vae_path "stabilityai/sd-vae-ft-mse"
|
135 |
+
```
|
136 |
+
This model is an SD 1.5 model combined with Controlnet Canny. Now let's run the test script:
|
137 |
+
```
|
138 |
+
python test-controlnet-canny.py
|
139 |
+
```
|
140 |
+
Once the test is done you'll have an image called controlnet-canny-test.png.
|
141 |
+
The new image is entirely different but the shape is very similar to the original input image.
|
142 |
+
|
143 |
+
You can look at the test-controlnet-canny.py to see how it works.
|
144 |
+
|
145 |
+
Next we'll use openpose. Note that the example is a demanding pose that you would ordinarily probably not go for.
|
146 |
+
Without tweaking this also suffers a bit from bad hands/feet. For the sake of the test I decided to tolerate it.
|
147 |
+
Let's make a ControlNet OpenPose model:
|
148 |
+
```
|
149 |
+
python conv_sd_to_onnx.py --model_path "Linaqruf/anything-v3.0" --output_path "./model/anyv3-fp16-autoslicing-cn_openpose" --controlnet_path "lllyasviel/sd-controlnet-openpose" --fp16 --attention-slicing auto
|
150 |
+
```
|
151 |
+
And now let's run the test:
|
152 |
+
```
|
153 |
+
python test-controlnet-openpose.py
|
154 |
+
```
|
155 |
+
This gives you controlnet-openpose-test.png
|
156 |
+
|
157 |
+
As some may wonder where I got the openpose startpoint image from. I used https://zhuyu1997.github.io/open-pose-editor/
|
158 |
+
Create the pose.
|
159 |
+
Press the button underneath height, then download the generated map on the left.
|
160 |
+
You can further edit it locally to fit the canvas in the way you want it to.
|
161 |
+
|
162 |
+
### Support for Instruct pix2pix
|
163 |
+
Recently a special Stable Diffusion model was released, allowing you to have AI edit images based on instructions.
|
164 |
+
Make sure you read the original documentation here: https://www.timothybrooks.com/instruct-pix2pix
|
165 |
+
|
166 |
+
A pipeline was added to diffusers, but currently Huggingface does not add ONNX equivalents.
|
167 |
+
In this repository I included the required ONNX pipeline and a basic UI (to simplify testing before it gets added to ONNXDiffusersUI)
|
168 |
+
|
169 |
+
You can convert the model using this command (it'll fetch it from huggingface):
|
170 |
+
```
|
171 |
+
python conv_sd_to_onnx.py --model_path "timbrooks/instruct-pix2pix" --output_path "./model/ip2p-base-fp16-vae_ft_mse-autoslicing" --vae_path "stabilityai/sd-vae-ft-mse" --fp16 --attention-slicing auto
|
172 |
+
```
|
173 |
+
Once converted you can run the included UI like this:
|
174 |
+
```
|
175 |
+
python pix2pixUI.py
|
176 |
+
```
|
177 |
+
You'll need an image to start from (you can always create one with Stable Diffusion) and then you can test the pipeline.
|
178 |
+
This first version is _very_ basic and you'll need to save the results (when you want them) using "save image as" in your browser.
|
179 |
+
|
180 |
+
### Use alternative VAE
|
181 |
+
Some models will suggest using an alternative VAE.
|
182 |
+
It's possible to copy the model.onnx from an existing directory and put it in another one, but you may want to keep the conversion command line you use for reference.
|
183 |
+
To simplify the task of using an alternative VAE you can now pass it as part of the conversion command.
|
184 |
+
|
185 |
+
Say you want to have SD1.5 but with the updated MSE VAE that was released later and is the result of further training. You can do it like this:
|
186 |
+
```
|
187 |
+
python conv_sd_to_onnx.py --model_path "runwayml/stable-diffusion-v1-5" --output_path "./model/sd1_5-fp16-vae_ft_mse" --vae_path "stabilityai/sd-vae-ft-mse" --fp16
|
188 |
+
```
|
189 |
+
|
190 |
+
You can also load a vae from a full model on huggingface. You add /vae to make that clear. Say you need the VAE from Anything v3.0:
|
191 |
+
```
|
192 |
+
python conv_sd_to_onnx.py --model_path "runwayml/stable-diffusion-v1-5" --output_path "./model/sd1_5-fp16-vae_anythingv3" --vae_path "Linaqruf/anything-v3.0/vae" --fp16
|
193 |
+
```
|
194 |
+
|
195 |
+
Or if the model is on your local disk, you can just use the local directory. Say you have stable-diffusion 2.1 base on disk, you could it like this:
|
196 |
+
```
|
197 |
+
python conv_sd_to_onnx.py --model_path "runwayml/stable-diffusion-v1-5" --output_path "./model/sd1_5-fp16-vae_2_1" --vae_path "stable-diffusion-2-1-base/vae" --fp16
|
198 |
+
```
|
199 |
+
|
200 |
+
### Clip Skip
|
201 |
+
For some models people will suggest using "Clip Skip" for better results. As we can't arbitrarily change this with ONNX, we need to decide on it at model creation.
|
202 |
+
Therefore there's --clip-skip which you can set to 2, 3 or 4.
|
203 |
+
|
204 |
+
Example:
|
205 |
+
```
|
206 |
+
python conv_sd_to_onnx.py --model_path "Linaqruf/anything-v3.0" --output_path "./model/anythingv3_fp16_cs2" --fp16 --clip-skip 2
|
207 |
+
```
|
208 |
+
|
209 |
+
Clip Skip results in a change to the Text Encoder.
|
210 |
+
To stay compatible with other implementations we use the same numbering where 1 is the default behaviour and 2 skips 1 layer.
|
211 |
+
This ensures that you see similar behaviour to other implementations when setting the same number for Clip Skip.
|
212 |
+
|
213 |
+
### Reducing VRAM usage
|
214 |
+
While FP16 already uses a lot less VRAM, you may still run into VRAM issues. The easiest solution is to load the Text Encoder on CPU rather than GPU. The Text Encoder is only used as part of prompt parsing and not during the iterations.
|
215 |
+
You can expect some additional latency when the Text Encoder is on CPU, but this will be fairly minor as it is not compute intensive. You also gain more than that back during the iterations if you're near your VRAM limit.
|
216 |
+
You'll bump into VRAM limits when it is limited (8GB or less), or you're trying to use a 768x768 model.
|
217 |
+
|
218 |
+
In test-txt2img.py you can see how this works. You can pass --cpu-textenc and it will load the Text Encoder on CPU. This is how it's done:
|
219 |
+
```
|
220 |
+
cputextenc=OnnxRuntimeModel.from_pretrained(args.model+"/text_encoder")
|
221 |
+
pipe = OnnxStableDiffusionPipeline.from_pretrained(args.model, provider="DmlExecutionProvider", text_encoder=cputextenc)
|
222 |
+
```
|
223 |
+
You can use this in your own code when needed. OnnxDiffusersUI supports --cpu-textenc too.
|
224 |
+
|
225 |
+
In extreme circumstances you can also try to load VAE on CPU. This is likely to be only of use for cards that have limited VRAM. The need to load VAE on CPU can be identified when generation crashes after the steps.
|
226 |
+
So if it goes through all the steps but then crashes when it needs to save the final image, VAE is your issue. If it crashes before steps is finished, changes to where VAE is loaded are unlikely to make much of a difference.
|
227 |
+
**You can pass --cpuvae to test-txt2img.py to load VAE on CPU (this will always also load CLIP on CPU).**
|
228 |
+
Note that having VAE loaded on CPU is CPU intensive (far more than CLIP is) and you'll see RAM use spike.
|
229 |
+
|
230 |
+
### Conversion of .ckpt / .safetensors
|
231 |
+
Did your model come as a single file ending in .safetensors or .ckpt? Don't worry, with the 0.12.0 release of diffusers I can now use diffusers to load these directly. I have updated (and renamed) the conversion tool and it
|
232 |
+
will convert directly from .ckpt to ONNX.
|
233 |
+
|
234 |
+
This is probably the most requested feature as many of you have used https://www.civitai.com/ and have found the conversion process a bit cumbersome.
|
235 |
+
|
236 |
+
To properly convert a file you do need a .yaml config file. Ideally this should be included but if not you're advised to try with the v1-inference.yaml included in this repository.
|
237 |
+
To convert a model you'd then do:
|
238 |
+
```
|
239 |
+
python conv_sd_to_onnx.py --model_path ".\downloaded.ckpt" --output_path "./model/downloaded-fp16" --ckpt-original-config-file downloaded.yaml --fp16
|
240 |
+
```
|
241 |
+
If it did not come with a .yaml config file, try with v1-inference.yaml.
|
242 |
+
|
243 |
+
If you have a choice between .safetensors and .ckpt, go for .safetensors. In theory a .ckpt file can contain malicious code. I have not seen any reports of this happening but it's better to be safe than sorry.
|
244 |
+
|
245 |
+
The conversion tool also has additional parameters you can set when converting from .ckpt/.safetensors. The best way to find all the parameters is by doing:
|
246 |
+
```
|
247 |
+
python conv_sd_to_onnx.py --help
|
248 |
+
```
|
249 |
+
You should generally not need these but some advanced users may want to have them just in case.
|
250 |
+
|
251 |
+
## FAQ
|
252 |
+
### Do the converted models work with other ONNX DirectML based implementations?
|
253 |
+
While not tested extensively: yes they should! They are not full FP16, at the interface level they are the same as FP32.
|
254 |
+
They are completely valid drop in replacements and transparently run in FP16 on ORT DirectML.
|
255 |
+
This makes it possible to run both FP16 and FP32 models with the exact same code.
|
256 |
+
|
257 |
+
### Can I convert non-official models?
|
258 |
+
You should be able to convert any model. Most of the models can be found on https://huggingface.co/, but you may prefer using https://civitai.com/ instead.
|
259 |
+
It's generally better to start from a model in diffusers form but if you only have the .ckpt/.safetensors file you now have instructions on how to convert these directly into ONNX.
|
260 |
+
|
261 |
+
### Does this work for inpainting / img2img?
|
262 |
+
Yes, it has been tested on the inpainting models and it works fine. Just like with txt2img, replacement is transparent as the interface is FP32.
|
263 |
+
Additional example scripts may be added in the future to demonstrate inpainting in code. For now mainly useful for use with OnnxDiffusersUI
|
264 |
+
|
265 |
+
### Why is Euler Ancestral not giving me the same image if I provide a seed?
|
266 |
+
Due to how Euler Ancestral works, it adds noise as part of the scheduler that is apparently non-deterministic when interacting with ONNX diffusers pipeline.
|
267 |
+
A clean ONNX implementation without diffusers, torch ... would likely be faster and bug free but it's a lot of work and it would not match SHARK.
|
268 |
+
Best advice is to live with it and to switch to SHARK as soon as your wished for feature is available there. For more on SHARK see the next answer.
|
269 |
+
|
270 |
+
### This is still too slow / taxing on my VRAM
|
271 |
+
Make sure to close as many applications as possible when running FP32 or 768x768 FP16 models.
|
272 |
+
On my 6700XT I can do 768x768 at 1.2s/it but only if I close all applications.
|
273 |
+
If I don't close enough applications, it very quickly goes beyond 2s/it.
|
274 |
+
|
275 |
+
Also consider following https://github.com/nod-ai/SHARK which provides accelerated ML on AMD via MLIR/IREE.
|
276 |
+
It (currently) lacks features and flexibility but it has a faster and more VRAM efficient Stable Diffusion implementation than we can currently get on ONNX.
|
277 |
+
The current motto also is "Things move fast" which means that in a single day you may get both new features and performance boosts. (On my 6700XT SHARK is close to being twice as fast as ONNX FP16!)
|
278 |
+
There's also an onnxdiffusers channel on the Discord where you can ask for help if you want to stick to ONNX for a bit longer. We'll convert you to a dedicated SHARK user there.
|
279 |
+
|
280 |
+
If you are an advanced AMD user, switch to Linux+ROCm. It'll be faster and you can use any torch based solution directly.
|
281 |
+
|
282 |
+
### Can you share any results?
|
283 |
+
On my 6700XT I can get Stable Diffusion 2.1 768x768 down to 1.15s/it and 2.1 base 512x512 to 2.7it/s
|
284 |
+
Reported working for Vega56 and doing 512x512 at 1.75it/s
|
285 |
+
Reported working for RX 480 8GB and doing 512x512 at 1.75s/it
|
286 |
+
Reported working for 5600XT 6GB and doing 512x512 at 1.43s/it (about 4x times faster than using ONNX FP32)
|
287 |
+
|
288 |
+
### All these model downloads seem to be eating my main drive's disk space?!
|
289 |
+
This is an unfortunate side effect of where the huggingface library stores its cache by default.
|
290 |
+
On your main drive go to your users home directory (C:\users\...) and you'll find a .cache directory and in it a directory called huggingface.
|
291 |
+
Point an environment variable HF_HOME towards where you want to have it store things instead.
|
292 |
+
(You can probably move the existing directory to a different drive and point HF_HOME towards it but I have not tested this ...)
|
293 |
+
Once resolved you can remove the huggingface directory from .cache
|
patchedstabledifftoonnx_withou_modelort/README4GB.md
ADDED
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Stable Diffusion using ONNX, FP16 and DirectML
|
2 |
+
|
3 |
+
This repository contains a conversion tool, some examples, and instructions on how to set up Stable Diffusion with ONNX models.
|
4 |
+
|
5 |
+
**These instructions are specifically for people who have only 4GB VRAM**
|
6 |
+
|
7 |
+
It's all fairly straightforward, but It helps to be comfortable with command line.
|
8 |
+
|
9 |
+
We'll focus on making all of it work within limited VRAM. This will still include a UI.
|
10 |
+
|
11 |
+
## Set up
|
12 |
+
|
13 |
+
First make sure you have Python 3.10 or 3.11 installed. You can get it here: https://www.python.org/downloads/
|
14 |
+
|
15 |
+
If you don't have git, get it here: https://gitforwindows.org/
|
16 |
+
|
17 |
+
Pick a directory that can contain your Stable Diffusion installation (make sure you've the diskspace to store the models).
|
18 |
+
Open the commandline (Powershell or Command Prompt) and change into the directory you will use.
|
19 |
+
|
20 |
+
Start by cloning this repository:
|
21 |
+
```
|
22 |
+
git clone https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16
|
23 |
+
cd Stable-Diffusion-ONNX-FP16
|
24 |
+
```
|
25 |
+
|
26 |
+
Do the following:
|
27 |
+
```
|
28 |
+
pip install virtualenv
|
29 |
+
python -m venv sd_env
|
30 |
+
sd_env\scripts\activate
|
31 |
+
python -m pip install --upgrade pip
|
32 |
+
pip install torch --extra-index-url https://download.pytorch.org/whl/nightly/cpu --pre
|
33 |
+
pip install -r requirements.txt
|
34 |
+
```
|
35 |
+
|
36 |
+
Now first make sure you have an account on https://huggingface.co/
|
37 |
+
When you do make sure to create a token on https://huggingface.co/settings/tokens
|
38 |
+
And then on the commandline login using following command
|
39 |
+
```
|
40 |
+
huggingface-cli login
|
41 |
+
```
|
42 |
+
|
43 |
+
Now you're ready to download and convert models. Before we explain this, just a pointer on future use.
|
44 |
+
Whenever you want to make use of this post set up, open a command line, change into the directory and enable the environment.
|
45 |
+
Say that you installed this on your D: drive in the root. You would open command line and then:
|
46 |
+
```
|
47 |
+
d:
|
48 |
+
cd Stable-Diffusion-ONNX-FP16
|
49 |
+
sd_env\scripts\activate
|
50 |
+
```
|
51 |
+
|
52 |
+
Remember this for whenver you want to use your installation. Let's now get to the fun part and convert a model. This will take some time!
|
53 |
+
The extra time spend on creating the model is saved back by having it run fine on 4GB VRAM.
|
54 |
+
```
|
55 |
+
mkdir model
|
56 |
+
python conv_sd_to_onnx.py --model_path "stabilityai/stable-diffusion-2-1-base" --output_path "./model/sd2_1base-fp16-maxslicing" --fp16 --attention-slicing max
|
57 |
+
```
|
58 |
+
|
59 |
+
That's your first model. Let's do a test:
|
60 |
+
|
61 |
+
```
|
62 |
+
python test-txt2img.py --model "model\sd2_1base-fp16-maxslicing" --size 512 --seed 0 --cpu-textenc --cpuvae
|
63 |
+
```
|
64 |
+
|
65 |
+
You should now have your first picture in the current directory.
|
66 |
+
|
67 |
+
Now that we've got everything working and we can create pictures, let's get a GUI. We'll use ONNXDiffusersUI but make it so it doesn't break our workflow.
|
68 |
+
First we clone the repository:
|
69 |
+
```
|
70 |
+
git clone https://github.com/Amblyopius/OnnxDiffusersUI
|
71 |
+
```
|
72 |
+
Now we run the UI
|
73 |
+
```
|
74 |
+
python OnnxDiffusersUI\onnxUI.py --cpu-textenc --cpu-vaedec
|
75 |
+
```
|
76 |
+
It'll take some time to load and then in your browser you can go to http://127.0.0.1:7860 (only accessible on the host you're running it).
|
77 |
+
If you're done you can go back to the CMD window and press Ctrl+C and it will quit.
|
78 |
+
|
79 |
+
Note that it expects your models to be in the model directory (which is why we put them there in the instructions).
|
80 |
+
You can find your history and all the pictures you created in the directory called output.
|
81 |
+
|
82 |
+
If you want to learn more about the UI be sure to visit https://github.com/azuritecoin/OnnxDiffusersUI
|
83 |
+
|
84 |
+
## Advanced features
|
85 |
+
### Use alternative VAE
|
86 |
+
Some models will suggest using an alternative VAE.
|
87 |
+
It's possible to copy the model.onnx from an existing directory and put it in another one, but you may want to keep the conversion command line you use for reference.
|
88 |
+
To simplify the task of using an alternative VAE you can now pass it as part of the conversion command.
|
89 |
+
|
90 |
+
Say you want to have SD1.5 but with the updated MSE VAE that was released later and is the result of further training. You can do it like this:
|
91 |
+
```
|
92 |
+
python conv_sd_to_onnx.py --model_path "runwayml/stable-diffusion-v1-5" --output_path "./model/sd1_5-fp16-vae_ft_mse" --vae_path "stabilityai/sd-vae-ft-mse" --fp16 --attention-slicing max
|
93 |
+
```
|
94 |
+
|
95 |
+
You can also load a vae from a full model on huggingface. You add /vae to make that clear. Say you need the VAE from Anything v3.0:
|
96 |
+
```
|
97 |
+
python conv_sd_to_onnx.py --model_path "runwayml/stable-diffusion-v1-5" --output_path "./model/sd1_5-fp16-vae_anythingv3" --vae_path "Linaqruf/anything-v3.0/vae" --fp16 --attention-slicing max
|
98 |
+
```
|
99 |
+
|
100 |
+
Or if the model is on your local disk, you can just use the local directory. Say you have stable-diffusion 2.1 base on disk, you could it like this:
|
101 |
+
```
|
102 |
+
python conv_sd_to_onnx.py --model_path "runwayml/stable-diffusion-v1-5" --output_path "./model/sd1_5-fp16-vae_2_1" --vae_path "stable-diffusion-2-1-base/vae" --fp16 --attention-slicing max
|
103 |
+
```
|
104 |
+
|
105 |
+
### Clip Skip
|
106 |
+
For some models people will suggest using "Clip Skip" for better results. As we can't arbitrarily change this with ONNX we need to decide on it at model creation.
|
107 |
+
Therefore there's --clip-skip which you can set to 2, 3 or 4.
|
108 |
+
|
109 |
+
Example:
|
110 |
+
```
|
111 |
+
python conv_sd_to_onnx.py --model_path "Linaqruf/anything-v3.0" --output_path "./model/anythingv3_fp16_cs2" --fp16 --clip-skip 2
|
112 |
+
```
|
113 |
+
|
114 |
+
Clip Skip results in a change to the Text Encoder. To stay compatible with other implementations we use the same numbering where 1 is the default behaviour and 2 skips 1 layer.
|
115 |
+
This ensures that you see similar behaviour to other implementations when setting the same number for Clip Skip.
|
116 |
+
|
117 |
+
### Conversion of .ckpt / .safetensors
|
118 |
+
Did your model come as a single file ending in .safetensors or .ckpt? Don't worry, with the 0.12.0 release of diffusers I can now use diffusers to load these directly. I have updated (and renamed) the conversion tool and it
|
119 |
+
will convert directly from .ckpt to ONNX.
|
120 |
+
|
121 |
+
This is probably the most requested feature as many of you have used https://www.civitai.com/ and have found the conversion process a bit cumbersome.
|
122 |
+
|
123 |
+
To properly convert a file you do need a .yaml config file. Ideally this should be included but if not you're advised to try with the v1-inference.yaml included in this repository.
|
124 |
+
To convert a model you'd then do:
|
125 |
+
```
|
126 |
+
python conv_sd_to_onnx.py --model_path ".\downloaded.ckpt" --output_path "./model/downloaded-fp16" --ckpt-original-config-file downloaded.yaml --fp16
|
127 |
+
```
|
128 |
+
If it did not come with a .yaml config file, try with v1-inference.yaml.
|
129 |
+
|
130 |
+
If you have a choice between .safetensors and .ckpt, go for .safetensors. In theory a .ckpt file can contain malicious code. I have not seen any reports of this happening but it's better to be safe than sorry.
|
131 |
+
|
132 |
+
The conversion tool also has additional parameters you can set when converting from .ckpt/.safetensors. The best way to find all the parameters is by doing:
|
133 |
+
```
|
134 |
+
python conv_sd_to_onnx.py --help
|
135 |
+
```
|
136 |
+
You should generally not need these but some advanced users may want to have them just in case.
|
patchedstabledifftoonnx_withou_modelort/conv_sd_to_onnx.py
ADDED
@@ -0,0 +1,658 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
# Copyright 2022 Dirk Moerenhout. All rights reserved.
|
3 |
+
#
|
4 |
+
# This program is free software: you can redistribute it and/or modify it under the terms
|
5 |
+
# of the GNU General Public License as published by the Free Software Foundation,
|
6 |
+
# either version 3 of the License, or (at your option) any later version.
|
7 |
+
#
|
8 |
+
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
9 |
+
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
10 |
+
# See the GNU General Public License for more details.
|
11 |
+
#
|
12 |
+
# You should have received a copy of the GNU General Public License along with this program. If not,
|
13 |
+
# see <https://www.gnu.org/licenses/>.
|
14 |
+
#
|
15 |
+
# *****
|
16 |
+
# NOTE this was originally derived from:
|
17 |
+
# https://github.com/huggingface/diffusers/blob/main/scripts/convert_stable_diffusion_checkpoint_to_onnx.py
|
18 |
+
#
|
19 |
+
# Original file released under Apache License, Version 2.0
|
20 |
+
# *****
|
21 |
+
#
|
22 |
+
# Version history
|
23 |
+
# v1.2 First fully working version converting unet to fp16
|
24 |
+
# v2.0 Refactored + enabled conversion to fp16 for Text Encoder
|
25 |
+
# v2.1 Support for safetensors
|
26 |
+
# v2.2 Reduce visible warnings
|
27 |
+
# v3.0 You can now provide an alternative VAE
|
28 |
+
# v3.1 Align with diffusers 0.12.0
|
29 |
+
# v4.0 Support ckpt conversion (--> renamed to conv_sd_to_onnx.py)
|
30 |
+
# v5.0 Use ONNX Runtime Transformers for model optimisation
|
31 |
+
# v6.0 Support ControlNet
|
32 |
+
# v6.1 Support for diffusers 0.15.0
|
33 |
+
|
34 |
+
import warnings
|
35 |
+
import argparse
|
36 |
+
import os
|
37 |
+
import shutil
|
38 |
+
from pathlib import Path
|
39 |
+
import json
|
40 |
+
import tempfile
|
41 |
+
from typing import Union, Optional, Tuple
|
42 |
+
|
43 |
+
import torch
|
44 |
+
from torch.onnx import export
|
45 |
+
import safetensors
|
46 |
+
|
47 |
+
import onnx
|
48 |
+
from onnxruntime.transformers.float16 import convert_float_to_float16
|
49 |
+
from diffusers.models import AutoencoderKL
|
50 |
+
from diffusers import (
|
51 |
+
OnnxRuntimeModel,
|
52 |
+
OnnxStableDiffusionPipeline,
|
53 |
+
StableDiffusionPipeline,
|
54 |
+
ControlNetModel,
|
55 |
+
UNet2DConditionModel
|
56 |
+
)
|
57 |
+
from diffusers.models.attention_processor import AttnProcessor
|
58 |
+
from diffusers.models.unet_2d_condition import UNet2DConditionOutput
|
59 |
+
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt
|
60 |
+
|
61 |
+
# To improve future development and testing, warnings should be limited to what is somewhat useful
|
62 |
+
# Truncation warnings are expected as part of FP16 conversion and should not be shown
|
63 |
+
warnings.filterwarnings('ignore','.*will be truncated.*')
|
64 |
+
# We are ignoring prim::Constant type related warnings
|
65 |
+
warnings.filterwarnings('ignore','.*The shape inference of prim::Constant type is missing.*')
|
66 |
+
|
67 |
+
# ONNX Runtime Transformers offers ONNX model optimisation
|
68 |
+
# It does not directly support DirectML but we can use a custom class
|
69 |
+
# Based on onnx_model_unet.py in ONNX Runtime Transformers
|
70 |
+
from onnx import ModelProto
|
71 |
+
from onnxruntime.transformers.onnx_model_unet import UnetOnnxModel
|
72 |
+
|
73 |
+
class UnetOnnxModelDML(UnetOnnxModel):
|
74 |
+
def __init__(self, model: ModelProto, num_heads: int = 0, hidden_size: int = 0):
|
75 |
+
"""Initialize UNet ONNX Model.
|
76 |
+
|
77 |
+
Args:
|
78 |
+
model (ModelProto): the ONNX model
|
79 |
+
num_heads (int, optional): number of attention heads. Defaults to 0 (detect the parameter automatically).
|
80 |
+
hidden_size (int, optional): hidden dimension. Defaults to 0 (detect the parameter automatically).
|
81 |
+
"""
|
82 |
+
assert (num_heads == 0 and hidden_size == 0) or (num_heads > 0 and hidden_size % num_heads == 0)
|
83 |
+
|
84 |
+
super().__init__(model, num_heads=num_heads, hidden_size=hidden_size)
|
85 |
+
|
86 |
+
def optimize(self, enable_shape_inference=False):
|
87 |
+
if not enable_shape_inference:
|
88 |
+
self.disable_shape_inference()
|
89 |
+
self.fuse_layer_norm()
|
90 |
+
self.preprocess()
|
91 |
+
self.postprocess()
|
92 |
+
|
93 |
+
# We need a wrapper for UNet2DConditionModel as we need to pass tuples
|
94 |
+
# We can't properly export tuples of Tensors with ONNX
|
95 |
+
|
96 |
+
class UNet2DConditionModel_Cnet(UNet2DConditionModel):
|
97 |
+
def forward(
|
98 |
+
self,
|
99 |
+
sample: torch.FloatTensor,
|
100 |
+
timestep: Union[torch.Tensor, float, int],
|
101 |
+
encoder_hidden_states: torch.Tensor,
|
102 |
+
down_block_add_res00: Optional[torch.Tensor] = None,
|
103 |
+
down_block_add_res01: Optional[torch.Tensor] = None,
|
104 |
+
down_block_add_res02: Optional[torch.Tensor] = None,
|
105 |
+
down_block_add_res03: Optional[torch.Tensor] = None,
|
106 |
+
down_block_add_res04: Optional[torch.Tensor] = None,
|
107 |
+
down_block_add_res05: Optional[torch.Tensor] = None,
|
108 |
+
down_block_add_res06: Optional[torch.Tensor] = None,
|
109 |
+
down_block_add_res07: Optional[torch.Tensor] = None,
|
110 |
+
down_block_add_res08: Optional[torch.Tensor] = None,
|
111 |
+
down_block_add_res09: Optional[torch.Tensor] = None,
|
112 |
+
down_block_add_res10: Optional[torch.Tensor] = None,
|
113 |
+
down_block_add_res11: Optional[torch.Tensor] = None,
|
114 |
+
mid_block_additional_residual: Optional[torch.Tensor] = None,
|
115 |
+
return_dict: bool = False,
|
116 |
+
) -> Union[UNet2DConditionOutput, Tuple]:
|
117 |
+
down_block_add_res = (
|
118 |
+
down_block_add_res00, down_block_add_res01, down_block_add_res02,
|
119 |
+
down_block_add_res03, down_block_add_res04, down_block_add_res05,
|
120 |
+
down_block_add_res06, down_block_add_res07, down_block_add_res08,
|
121 |
+
down_block_add_res09, down_block_add_res10, down_block_add_res11)
|
122 |
+
return super().forward(
|
123 |
+
sample = sample,
|
124 |
+
timestep = timestep,
|
125 |
+
encoder_hidden_states = encoder_hidden_states,
|
126 |
+
down_block_additional_residuals = down_block_add_res,
|
127 |
+
mid_block_additional_residual = mid_block_additional_residual,
|
128 |
+
return_dict = return_dict
|
129 |
+
)
|
130 |
+
|
131 |
+
def onnx_export(
|
132 |
+
model,
|
133 |
+
model_args: tuple,
|
134 |
+
output_path: Path,
|
135 |
+
ordered_input_names,
|
136 |
+
output_names,
|
137 |
+
dynamic_axes,
|
138 |
+
opset,
|
139 |
+
):
|
140 |
+
'''export a PyTorch model as an ONNX model'''
|
141 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
142 |
+
export(
|
143 |
+
model,
|
144 |
+
model_args,
|
145 |
+
f=output_path.as_posix(),
|
146 |
+
input_names=ordered_input_names,
|
147 |
+
output_names=output_names,
|
148 |
+
dynamic_axes=dynamic_axes,
|
149 |
+
do_constant_folding=True,
|
150 |
+
opset_version=opset,
|
151 |
+
)
|
152 |
+
|
153 |
+
@torch.no_grad()
|
154 |
+
def convert_to_fp16(
|
155 |
+
model_path
|
156 |
+
):
|
157 |
+
'''Converts an ONNX model on disk to FP16'''
|
158 |
+
model_dir=os.path.dirname(model_path)
|
159 |
+
# Breaking down in steps due to Windows bug in convert_float_to_float16_model_path
|
160 |
+
onnx.shape_inference.infer_shapes_path(model_path)
|
161 |
+
fp16_model = onnx.load(model_path)
|
162 |
+
fp16_model = convert_float_to_float16(
|
163 |
+
fp16_model, keep_io_types=True, disable_shape_infer=True
|
164 |
+
)
|
165 |
+
# clean up existing tensor files
|
166 |
+
shutil.rmtree(model_dir)
|
167 |
+
os.mkdir(model_dir)
|
168 |
+
# save FP16 model
|
169 |
+
onnx.save(fp16_model, model_path)
|
170 |
+
|
171 |
+
@torch.no_grad()
|
172 |
+
def convert_models(pipeline: StableDiffusionPipeline,
|
173 |
+
output_path: str,
|
174 |
+
opset: int,
|
175 |
+
fp16: bool,
|
176 |
+
notune: bool,
|
177 |
+
controlnet_path: str,
|
178 |
+
attention_slicing: str):
|
179 |
+
'''Converts the individual models in a path (UNET, VAE ...) to ONNX'''
|
180 |
+
|
181 |
+
output_path = Path(output_path)
|
182 |
+
|
183 |
+
# TEXT ENCODER
|
184 |
+
num_tokens = pipeline.text_encoder.config.max_position_embeddings
|
185 |
+
text_hidden_size = pipeline.text_encoder.config.hidden_size
|
186 |
+
text_input = pipeline.tokenizer(
|
187 |
+
"A sample prompt",
|
188 |
+
padding="max_length",
|
189 |
+
max_length=pipeline.tokenizer.model_max_length,
|
190 |
+
truncation=True,
|
191 |
+
return_tensors="pt",
|
192 |
+
)
|
193 |
+
textenc_path=output_path / "text_encoder" / "model.onnx"
|
194 |
+
onnx_export(
|
195 |
+
pipeline.text_encoder,
|
196 |
+
# casting to torch.int32 https://github.com/huggingface/transformers/pull/18515/files
|
197 |
+
model_args=(text_input.input_ids.to(device=device, dtype=torch.int32)),
|
198 |
+
output_path=textenc_path,
|
199 |
+
ordered_input_names=["input_ids"],
|
200 |
+
output_names=["last_hidden_state", "pooler_output"],
|
201 |
+
dynamic_axes={
|
202 |
+
"input_ids": {0: "batch", 1: "sequence"},
|
203 |
+
},
|
204 |
+
opset=opset,
|
205 |
+
)
|
206 |
+
if fp16:
|
207 |
+
textenc_model_path = str(textenc_path.absolute().as_posix())
|
208 |
+
convert_to_fp16(textenc_model_path)
|
209 |
+
|
210 |
+
# UNET
|
211 |
+
unet_in_channels = pipeline.unet.config.in_channels
|
212 |
+
unet_sample_size = pipeline.unet.config.sample_size
|
213 |
+
unet_path = output_path / "unet" / "model.onnx"
|
214 |
+
if controlnet_path:
|
215 |
+
# reload UNET to get an ONNX exportable version with ControlNet support
|
216 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
217 |
+
pl.unet.save_pretrained(tmpdirname)
|
218 |
+
controlnet_unet=UNet2DConditionModel_Cnet.from_pretrained(tmpdirname,
|
219 |
+
low_cpu_mem_usage=False)
|
220 |
+
|
221 |
+
controlnet_unet.set_attn_processor(AttnProcessor())
|
222 |
+
|
223 |
+
if attention_slicing:
|
224 |
+
pl.enable_attention_slicing(attention_slicing)
|
225 |
+
controlnet_unet.set_attention_slice(attention_slicing)
|
226 |
+
|
227 |
+
onnx_export(
|
228 |
+
controlnet_unet,
|
229 |
+
model_args=(
|
230 |
+
torch.randn(2, unet_in_channels, unet_sample_size,
|
231 |
+
unet_sample_size).to(device=device, dtype=dtype),
|
232 |
+
torch.randn(2).to(device=device, dtype=dtype),
|
233 |
+
torch.randn(2, num_tokens, text_hidden_size).to(device=device, dtype=dtype),
|
234 |
+
torch.randn(2, 320, unet_sample_size, unet_sample_size).to(device=device, dtype=dtype),
|
235 |
+
torch.randn(2, 320, unet_sample_size, unet_sample_size).to(device=device, dtype=dtype),
|
236 |
+
torch.randn(2, 320, unet_sample_size, unet_sample_size).to(device=device, dtype=dtype),
|
237 |
+
torch.randn(2, 320, unet_sample_size//2,unet_sample_size//2).to(device=device, dtype=dtype),
|
238 |
+
torch.randn(2, 640, unet_sample_size//2,unet_sample_size//2).to(device=device, dtype=dtype),
|
239 |
+
torch.randn(2, 640, unet_sample_size//2,unet_sample_size//2).to(device=device, dtype=dtype),
|
240 |
+
torch.randn(2, 640, unet_sample_size//4,unet_sample_size//4).to(device=device, dtype=dtype),
|
241 |
+
torch.randn(2, 1280, unet_sample_size//4,unet_sample_size//4).to(device=device, dtype=dtype),
|
242 |
+
torch.randn(2, 1280, unet_sample_size//4,unet_sample_size//4).to(device=device, dtype=dtype),
|
243 |
+
torch.randn(2, 1280, unet_sample_size//8,unet_sample_size//8).to(device=device, dtype=dtype),
|
244 |
+
torch.randn(2, 1280, unet_sample_size//8,unet_sample_size//8).to(device=device, dtype=dtype),
|
245 |
+
torch.randn(2, 1280, unet_sample_size//8,unet_sample_size//8).to(device=device, dtype=dtype),
|
246 |
+
torch.randn(2, 1280, unet_sample_size//8,unet_sample_size//8).to(device=device, dtype=dtype),
|
247 |
+
False,
|
248 |
+
),
|
249 |
+
output_path=unet_path,
|
250 |
+
ordered_input_names=[
|
251 |
+
"sample",
|
252 |
+
"timestep",
|
253 |
+
"encoder_hidden_states",
|
254 |
+
"down_block_0",
|
255 |
+
"down_block_1",
|
256 |
+
"down_block_2",
|
257 |
+
"down_block_3",
|
258 |
+
"down_block_4",
|
259 |
+
"down_block_5",
|
260 |
+
"down_block_6",
|
261 |
+
"down_block_7",
|
262 |
+
"down_block_8",
|
263 |
+
"down_block_9",
|
264 |
+
"down_block_10",
|
265 |
+
"down_block_11",
|
266 |
+
"mid_block_additional_residual",
|
267 |
+
"return_dict"
|
268 |
+
],
|
269 |
+
output_names=["out_sample"], # has to be different from "sample" for correct tracing
|
270 |
+
dynamic_axes={
|
271 |
+
"sample": {0: "batch", 1: "channels", 2: "height", 3: "width"},
|
272 |
+
"timestep": {0: "batch"},
|
273 |
+
"encoder_hidden_states": {0: "batch", 1: "sequence"},
|
274 |
+
"down_block_0": {0: "batch", 2: "height", 3: "width"},
|
275 |
+
"down_block_1": {0: "batch", 2: "height", 3: "width"},
|
276 |
+
"down_block_2": {0: "batch", 2: "height", 3: "width"},
|
277 |
+
"down_block_3": {0: "batch", 2: "height2", 3: "width2"},
|
278 |
+
"down_block_4": {0: "batch", 2: "height2", 3: "width2"},
|
279 |
+
"down_block_5": {0: "batch", 2: "height2", 3: "width2"},
|
280 |
+
"down_block_6": {0: "batch", 2: "height4", 3: "width4"},
|
281 |
+
"down_block_7": {0: "batch", 2: "height4", 3: "width4"},
|
282 |
+
"down_block_8": {0: "batch", 2: "height4", 3: "width4"},
|
283 |
+
"down_block_9": {0: "batch", 2: "height8", 3: "width8"},
|
284 |
+
"down_block_10": {0: "batch", 2: "height8", 3: "width8"},
|
285 |
+
"down_block_11": {0: "batch", 2: "height8", 3: "width8"},
|
286 |
+
"mid_block_additional_residual": {0: "batch", 2: "height8", 3: "width8"},
|
287 |
+
},
|
288 |
+
opset=opset,
|
289 |
+
)
|
290 |
+
|
291 |
+
controlnet = ControlNetModel.from_pretrained(args.controlnet_path, low_cpu_mem_usage=False)
|
292 |
+
if attention_slicing:
|
293 |
+
controlnet.set_attention_slice(attention_slicing)
|
294 |
+
cnet_path = output_path / "controlnet" / "model.onnx"
|
295 |
+
onnx_export(
|
296 |
+
controlnet,
|
297 |
+
model_args=(
|
298 |
+
torch.randn(2, 4, 64, 64).to(device=device, dtype=dtype),
|
299 |
+
torch.randn(2).to(device=device, dtype=torch.int32),
|
300 |
+
torch.randn(2, 77, 768).to(device=device, dtype=dtype),
|
301 |
+
torch.randn(2, 3, 512,512).to(device=device, dtype=dtype),
|
302 |
+
False,
|
303 |
+
),
|
304 |
+
output_path=cnet_path,
|
305 |
+
ordered_input_names=["sample", "timestep", "encoder_hidden_states", "controlnet_cond","return_dict"],
|
306 |
+
output_names=["down_block_res_samples", "mid_block_res_sample"],
|
307 |
+
dynamic_axes={
|
308 |
+
"sample": {0: "batch", 1: "channels", 2: "height", 3: "width"},
|
309 |
+
"timestep": {0: "batch"},
|
310 |
+
"encoder_hidden_states": {0: "batch", 1: "sequence"},
|
311 |
+
"controlnet_cond": {0: "batch", 2: "height", 3: "width"}
|
312 |
+
},
|
313 |
+
opset=opset,
|
314 |
+
)
|
315 |
+
|
316 |
+
if fp16:
|
317 |
+
cnet_path_model_path = str(cnet_path.absolute().as_posix())
|
318 |
+
convert_to_fp16(cnet_path_model_path)
|
319 |
+
|
320 |
+
else:
|
321 |
+
onnx_export(
|
322 |
+
pipeline.unet,
|
323 |
+
model_args=(
|
324 |
+
torch.randn(2, unet_in_channels, unet_sample_size,
|
325 |
+
unet_sample_size).to(device=device, dtype=dtype),
|
326 |
+
torch.randn(2).to(device=device, dtype=torch.int32),
|
327 |
+
torch.randn(2, num_tokens, text_hidden_size).to(device=device, dtype=dtype),
|
328 |
+
False,
|
329 |
+
),
|
330 |
+
output_path=unet_path,
|
331 |
+
ordered_input_names=["sample", "timestep", "encoder_hidden_states", "return_dict"],
|
332 |
+
output_names=["out_sample"], # has to be different from "sample" for correct tracing
|
333 |
+
dynamic_axes={
|
334 |
+
"sample": {0: "batch", 1: "channels", 2: "height", 3: "width"},
|
335 |
+
"timestep": {0: "batch"},
|
336 |
+
"encoder_hidden_states": {0: "batch", 1: "sequence"},
|
337 |
+
},
|
338 |
+
opset=opset,
|
339 |
+
)
|
340 |
+
del pipeline.unet
|
341 |
+
|
342 |
+
unet_model_path = str(unet_path.absolute().as_posix())
|
343 |
+
unet_dir = os.path.dirname(unet_model_path)
|
344 |
+
unet = onnx.load(unet_model_path)
|
345 |
+
# clean up existing tensor files
|
346 |
+
shutil.rmtree(unet_dir)
|
347 |
+
os.mkdir(unet_dir)
|
348 |
+
|
349 |
+
optimizer = UnetOnnxModelDML(unet, 0, 0)
|
350 |
+
if not notune:
|
351 |
+
optimizer.optimize()
|
352 |
+
optimizer.topological_sort()
|
353 |
+
|
354 |
+
# collate external tensor files into one
|
355 |
+
onnx.save_model(
|
356 |
+
optimizer.model,
|
357 |
+
unet_model_path,
|
358 |
+
save_as_external_data=True,
|
359 |
+
all_tensors_to_one_file=True,
|
360 |
+
location="weights.pb",
|
361 |
+
convert_attribute=False,
|
362 |
+
)
|
363 |
+
if fp16:
|
364 |
+
convert_to_fp16(unet_model_path)
|
365 |
+
del unet, optimizer
|
366 |
+
|
367 |
+
# VAE ENCODER
|
368 |
+
vae_encoder = pipeline.vae
|
369 |
+
vae_in_channels = vae_encoder.config.in_channels
|
370 |
+
vae_sample_size = vae_encoder.config.sample_size
|
371 |
+
# need to get the raw tensor output (sample) from the encoder
|
372 |
+
vae_encoder.forward = lambda sample, return_dict: vae_encoder.encode(sample,
|
373 |
+
return_dict)[0].sample()
|
374 |
+
onnx_export(
|
375 |
+
vae_encoder,
|
376 |
+
model_args=(
|
377 |
+
torch.randn(1, vae_in_channels, vae_sample_size,
|
378 |
+
vae_sample_size).to(device=device, dtype=dtype),
|
379 |
+
False,
|
380 |
+
),
|
381 |
+
output_path=output_path / "vae_encoder" / "model.onnx",
|
382 |
+
ordered_input_names=["sample", "return_dict"],
|
383 |
+
output_names=["latent_sample"],
|
384 |
+
dynamic_axes={
|
385 |
+
"sample": {0: "batch", 1: "channels", 2: "height", 3: "width"},
|
386 |
+
},
|
387 |
+
opset=opset,
|
388 |
+
)
|
389 |
+
|
390 |
+
# VAE DECODER
|
391 |
+
vae_decoder = pipeline.vae
|
392 |
+
vae_latent_channels = vae_decoder.config.latent_channels
|
393 |
+
vae_out_channels = vae_decoder.config.out_channels
|
394 |
+
# forward only through the decoder part
|
395 |
+
vae_decoder.forward = vae_encoder.decode
|
396 |
+
onnx_export(
|
397 |
+
vae_decoder,
|
398 |
+
model_args=(
|
399 |
+
torch.randn(1, vae_latent_channels, unet_sample_size,
|
400 |
+
unet_sample_size).to(device=device, dtype=dtype),
|
401 |
+
False,
|
402 |
+
),
|
403 |
+
output_path=output_path / "vae_decoder" / "model.onnx",
|
404 |
+
ordered_input_names=["latent_sample", "return_dict"],
|
405 |
+
output_names=["sample"],
|
406 |
+
dynamic_axes={
|
407 |
+
"latent_sample": {0: "batch", 1: "channels", 2: "height", 3: "width"},
|
408 |
+
},
|
409 |
+
opset=opset,
|
410 |
+
)
|
411 |
+
del pipeline.vae
|
412 |
+
|
413 |
+
# SAFETY CHECKER
|
414 |
+
# NOTE:
|
415 |
+
# Safety checker is excluded because it is a resource hog and you'd be turning it off anyway
|
416 |
+
# I'm not a legal expert but IMHO you are still bound by the model's license after conversion
|
417 |
+
# Check the license of the model you are converting and abide by it
|
418 |
+
|
419 |
+
safety_checker = None
|
420 |
+
feature_extractor = None
|
421 |
+
|
422 |
+
onnx_pipeline = OnnxStableDiffusionPipeline(
|
423 |
+
vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_encoder",
|
424 |
+
low_cpu_mem_usage=False),
|
425 |
+
vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_decoder",
|
426 |
+
low_cpu_mem_usage=False),
|
427 |
+
text_encoder=OnnxRuntimeModel.from_pretrained(output_path / "text_encoder",
|
428 |
+
low_cpu_mem_usage=False),
|
429 |
+
tokenizer=pipeline.tokenizer,
|
430 |
+
unet=OnnxRuntimeModel.from_pretrained(output_path / "unet",low_cpu_mem_usage=False),
|
431 |
+
scheduler=pipeline.scheduler,
|
432 |
+
safety_checker=safety_checker,
|
433 |
+
feature_extractor=feature_extractor,
|
434 |
+
requires_safety_checker=safety_checker is not None,
|
435 |
+
)
|
436 |
+
|
437 |
+
onnx_pipeline.save_pretrained(output_path)
|
438 |
+
|
439 |
+
if controlnet_path:
|
440 |
+
confname=f"{output_path}/model_index.json"
|
441 |
+
with open(confname, 'r', encoding="utf-8") as f:
|
442 |
+
modelconf = json.load(f)
|
443 |
+
modelconf['controlnet'] = ("diffusers","OnnxRuntimeModel")
|
444 |
+
with open(confname, 'w', encoding="utf-8") as f:
|
445 |
+
json.dump(modelconf, f, indent=1)
|
446 |
+
|
447 |
+
print("ONNX pipeline saved to", output_path)
|
448 |
+
|
449 |
+
del pipeline
|
450 |
+
del onnx_pipeline
|
451 |
+
_ = OnnxStableDiffusionPipeline.from_pretrained(output_path,
|
452 |
+
provider="DmlExecutionProvider",
|
453 |
+
low_cpu_mem_usage=False)
|
454 |
+
print("ONNX pipeline is loadable")
|
455 |
+
|
456 |
+
|
457 |
+
if __name__ == "__main__":
|
458 |
+
parser = argparse.ArgumentParser()
|
459 |
+
|
460 |
+
parser.add_argument(
|
461 |
+
"--model_path",
|
462 |
+
default="D:/cache/chilloutmix_NiPrunedFp32Fix.safetensors",
|
463 |
+
type=str,
|
464 |
+
required=False,
|
465 |
+
help=(
|
466 |
+
"Path to the `diffusers` checkpoint to convert (either local directory or on the Hub). "
|
467 |
+
"Or the path to a local checkpoint saved in .ckpt or .safetensors."
|
468 |
+
)
|
469 |
+
)
|
470 |
+
|
471 |
+
parser.add_argument(
|
472 |
+
"--output_path",
|
473 |
+
default="D:/source-fp32",
|
474 |
+
type=str,
|
475 |
+
required=False,
|
476 |
+
help="Path to the output model."
|
477 |
+
)
|
478 |
+
|
479 |
+
parser.add_argument(
|
480 |
+
"--vae_path",
|
481 |
+
default=None,
|
482 |
+
type=str,
|
483 |
+
help=(
|
484 |
+
"Path to alternate VAE `diffusers` checkpoint (either local or on the Hub). "
|
485 |
+
)
|
486 |
+
)
|
487 |
+
|
488 |
+
parser.add_argument(
|
489 |
+
"--controlnet_path",
|
490 |
+
default=None,
|
491 |
+
type=str,
|
492 |
+
help=(
|
493 |
+
"Path to controlnet model to import and convert (either local or on the Hub). "
|
494 |
+
"Setting this results in an SD model intended to be used with a specific ControlNet"
|
495 |
+
)
|
496 |
+
)
|
497 |
+
|
498 |
+
parser.add_argument(
|
499 |
+
"--opset",
|
500 |
+
default=15,
|
501 |
+
type=int,
|
502 |
+
help="The version of the ONNX operator set to use.",
|
503 |
+
)
|
504 |
+
|
505 |
+
parser.add_argument(
|
506 |
+
"--fp16",
|
507 |
+
action="store_true",
|
508 |
+
help="Export Text Encoder and UNET in mixed `float16` mode"
|
509 |
+
)
|
510 |
+
|
511 |
+
parser.add_argument(
|
512 |
+
"--notune",
|
513 |
+
action="store_true",
|
514 |
+
help="Turn off tuning UNET with ONNX Runtime Transformers"
|
515 |
+
)
|
516 |
+
|
517 |
+
parser.add_argument(
|
518 |
+
"--attention-slicing",
|
519 |
+
choices={"auto","max"},
|
520 |
+
type=str,
|
521 |
+
help=(
|
522 |
+
"Attention slicing reduces VRAM needed, off by default. Set to auto or max. "
|
523 |
+
"WARNING: max implies --notune"
|
524 |
+
)
|
525 |
+
)
|
526 |
+
|
527 |
+
parser.add_argument(
|
528 |
+
"--clip-skip",
|
529 |
+
choices={2,3,4},
|
530 |
+
type=int,
|
531 |
+
help="Add permanent clip skip to ONNX model."
|
532 |
+
)
|
533 |
+
|
534 |
+
parser.add_argument(
|
535 |
+
"--diffusers-output",
|
536 |
+
type=str,
|
537 |
+
help="Directory to dump a pre-conversion copy in diffusers format in."
|
538 |
+
)
|
539 |
+
|
540 |
+
parser.add_argument(
|
541 |
+
"--ckpt-original-config-file",
|
542 |
+
default="D:/python/diffusion-convert-FP/v1-inference.yaml",
|
543 |
+
type=str,
|
544 |
+
help="The YAML config file corresponding to the original architecture."
|
545 |
+
)
|
546 |
+
|
547 |
+
parser.add_argument(
|
548 |
+
"--ckpt-image-size",
|
549 |
+
default=None,
|
550 |
+
type=int,
|
551 |
+
help="The image size that the model was trained on. Typically 512 or 768"
|
552 |
+
)
|
553 |
+
|
554 |
+
parser.add_argument(
|
555 |
+
"--ckpt-prediction_type",
|
556 |
+
default=None,
|
557 |
+
type=str,
|
558 |
+
help=(
|
559 |
+
"Prediction type the model was trained on. "
|
560 |
+
"'epsilon' for SD v1.X and SD v2 Base, 'v-prediction' for SD v2"
|
561 |
+
)
|
562 |
+
)
|
563 |
+
|
564 |
+
parser.add_argument(
|
565 |
+
"--ckpt-pipeline_type",
|
566 |
+
default=None,
|
567 |
+
type=str,
|
568 |
+
help="The pipeline type. If `None` pipeline will be automatically inferred."
|
569 |
+
)
|
570 |
+
|
571 |
+
parser.add_argument(
|
572 |
+
"--ckpt-extract-ema",
|
573 |
+
action="store_true",
|
574 |
+
help=(
|
575 |
+
"Only relevant for checkpoints that have both EMA and non-EMA weights. "
|
576 |
+
"If set enables extraction of EMA weights (Default is non-EMA). "
|
577 |
+
"EMA weights usually yield higher quality images for inference. "
|
578 |
+
"Non-EMA weights are usually better to continue fine-tuning."
|
579 |
+
)
|
580 |
+
)
|
581 |
+
|
582 |
+
parser.add_argument(
|
583 |
+
"--ckpt-num-in-channels",
|
584 |
+
default=None,
|
585 |
+
type=int,
|
586 |
+
help=(
|
587 |
+
"The number of input channels. "
|
588 |
+
"If `None` number of input channels will be automatically inferred."
|
589 |
+
)
|
590 |
+
)
|
591 |
+
|
592 |
+
parser.add_argument(
|
593 |
+
"--ckpt-upcast-attention",
|
594 |
+
action="store_true",
|
595 |
+
help=(
|
596 |
+
"Whether the attention computation should always be upcasted. "
|
597 |
+
"Necessary when running SD 2.1"
|
598 |
+
)
|
599 |
+
)
|
600 |
+
|
601 |
+
args = parser.parse_args()
|
602 |
+
|
603 |
+
dtype=torch.float32
|
604 |
+
device = "cpu"
|
605 |
+
if args.model_path.endswith(".ckpt") or args.model_path.endswith(".safetensors"):
|
606 |
+
pl = download_from_original_stable_diffusion_ckpt(
|
607 |
+
checkpoint_path=args.model_path,
|
608 |
+
original_config_file=args.ckpt_original_config_file,
|
609 |
+
image_size=args.ckpt_image_size,
|
610 |
+
prediction_type=args.ckpt_prediction_type,
|
611 |
+
model_type=args.ckpt_pipeline_type,
|
612 |
+
extract_ema=args.ckpt_extract_ema,
|
613 |
+
scheduler_type="pndm",
|
614 |
+
num_in_channels=args.ckpt_num_in_channels,
|
615 |
+
upcast_attention=args.ckpt_upcast_attention,
|
616 |
+
from_safetensors=args.model_path.endswith(".safetensors")
|
617 |
+
)
|
618 |
+
else:
|
619 |
+
pl = StableDiffusionPipeline.from_pretrained(args.model_path,
|
620 |
+
torch_dtype=dtype,low_cpu_mem_usage=False).to(device)
|
621 |
+
|
622 |
+
if args.vae_path:
|
623 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
624 |
+
pl.save_pretrained(tmpdirname)
|
625 |
+
if args.vae_path.endswith('/vae'):
|
626 |
+
vae = AutoencoderKL.from_pretrained(args.vae_path[:-4],subfolder='vae',
|
627 |
+
low_cpu_mem_usage=False)
|
628 |
+
else:
|
629 |
+
vae = AutoencoderKL.from_pretrained(args.vae_path,low_cpu_mem_usage=False)
|
630 |
+
pl = StableDiffusionPipeline.from_pretrained(tmpdirname,
|
631 |
+
torch_dtype=dtype, vae=vae,low_cpu_mem_usage=False).to(device)
|
632 |
+
|
633 |
+
if args.clip_skip:
|
634 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
635 |
+
pl.save_pretrained(tmpdirname)
|
636 |
+
confname=f"{tmpdirname}/text_encoder/config.json"
|
637 |
+
with open(confname, 'r', encoding="utf-8") as f:
|
638 |
+
clipconf = json.load(f)
|
639 |
+
clipconf['num_hidden_layers'] = clipconf['num_hidden_layers']-args.clip_skip+1
|
640 |
+
with open(confname, 'w', encoding="utf-8") as f:
|
641 |
+
json.dump(clipconf, f, indent=1)
|
642 |
+
pl = StableDiffusionPipeline.from_pretrained(tmpdirname,
|
643 |
+
torch_dtype=dtype,low_cpu_mem_usage=False).to(device)
|
644 |
+
|
645 |
+
pl.unet.set_attn_processor(AttnProcessor())
|
646 |
+
|
647 |
+
blocktune=False
|
648 |
+
if args.attention_slicing:
|
649 |
+
if args.attention_slicing == "max":
|
650 |
+
blocktune=True
|
651 |
+
print ("WARNING: attention_slicing max implies --notune")
|
652 |
+
pl.enable_attention_slicing(args.attention_slicing)
|
653 |
+
|
654 |
+
if args.diffusers_output:
|
655 |
+
pl.save_pretrained(args.diffusers_output)
|
656 |
+
|
657 |
+
#convert_models(pl, args.output_path,args.opset,args.fp16,args.notune or blocktune,args.controlnet_path,args.attention_slicing)
|
658 |
+
convert_models(pl, args.output_path, args.opset, False, args.notune or blocktune, args.controlnet_path,args.attention_slicing)
|
patchedstabledifftoonnx_withou_modelort/dance_pose.png
ADDED
patchedstabledifftoonnx_withou_modelort/input_image_vermeer.png
ADDED
patchedstabledifftoonnx_withou_modelort/pipeline_onnx_stable_diffusion_controlnet.py
ADDED
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 The HuggingFace Team.
|
2 |
+
# Converted for use with ONNX as part of https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16
|
3 |
+
# Special thanks to https://github.com/uchuusen for the initial conversion effort
|
4 |
+
|
5 |
+
import inspect
|
6 |
+
from typing import Callable, List, Optional, Union
|
7 |
+
|
8 |
+
import numpy as np
|
9 |
+
import torch
|
10 |
+
import PIL
|
11 |
+
from transformers import CLIPFeatureExtractor, CLIPTokenizer
|
12 |
+
|
13 |
+
from diffusers.configuration_utils import FrozenDict
|
14 |
+
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
|
15 |
+
from diffusers.utils import deprecate, logging, PIL_INTERPOLATION
|
16 |
+
from diffusers.pipelines.onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
|
17 |
+
from diffusers.pipeline_utils import DiffusionPipeline
|
18 |
+
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
|
19 |
+
|
20 |
+
|
21 |
+
logger = logging.get_logger(__name__)
|
22 |
+
|
23 |
+
|
24 |
+
class OnnxStableDiffusionControlNetPipeline(DiffusionPipeline):
|
25 |
+
vae_encoder: OnnxRuntimeModel
|
26 |
+
vae_decoder: OnnxRuntimeModel
|
27 |
+
text_encoder: OnnxRuntimeModel
|
28 |
+
tokenizer: CLIPTokenizer
|
29 |
+
unet: OnnxRuntimeModel
|
30 |
+
controlnet: OnnxRuntimeModel
|
31 |
+
scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]
|
32 |
+
safety_checker: OnnxRuntimeModel
|
33 |
+
feature_extractor: CLIPFeatureExtractor
|
34 |
+
|
35 |
+
_optional_components = ["safety_checker", "feature_extractor"]
|
36 |
+
|
37 |
+
def __init__(
|
38 |
+
self,
|
39 |
+
vae_encoder: OnnxRuntimeModel,
|
40 |
+
vae_decoder: OnnxRuntimeModel,
|
41 |
+
text_encoder: OnnxRuntimeModel,
|
42 |
+
tokenizer: CLIPTokenizer,
|
43 |
+
unet: OnnxRuntimeModel,
|
44 |
+
controlnet: OnnxRuntimeModel,
|
45 |
+
scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
|
46 |
+
safety_checker: OnnxRuntimeModel,
|
47 |
+
feature_extractor: CLIPFeatureExtractor,
|
48 |
+
requires_safety_checker: bool = True,
|
49 |
+
):
|
50 |
+
super().__init__()
|
51 |
+
|
52 |
+
if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
|
53 |
+
deprecation_message = (
|
54 |
+
f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
|
55 |
+
f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
|
56 |
+
"to update the config accordingly as leaving `steps_offset` might led to incorrect results"
|
57 |
+
" in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
|
58 |
+
" it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
|
59 |
+
" file"
|
60 |
+
)
|
61 |
+
deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
|
62 |
+
new_config = dict(scheduler.config)
|
63 |
+
new_config["steps_offset"] = 1
|
64 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
65 |
+
|
66 |
+
if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
|
67 |
+
deprecation_message = (
|
68 |
+
f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
|
69 |
+
" `clip_sample` should be set to False in the configuration file. Please make sure to update the"
|
70 |
+
" config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
|
71 |
+
" future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
|
72 |
+
" nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
|
73 |
+
)
|
74 |
+
deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
|
75 |
+
new_config = dict(scheduler.config)
|
76 |
+
new_config["clip_sample"] = False
|
77 |
+
scheduler._internal_dict = FrozenDict(new_config)
|
78 |
+
|
79 |
+
if safety_checker is None and requires_safety_checker:
|
80 |
+
logger.warning(
|
81 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
82 |
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
83 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
84 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
85 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
86 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
87 |
+
)
|
88 |
+
|
89 |
+
if safety_checker is not None and feature_extractor is None:
|
90 |
+
raise ValueError(
|
91 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
92 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
93 |
+
)
|
94 |
+
|
95 |
+
self.register_modules(
|
96 |
+
vae_encoder=vae_encoder,
|
97 |
+
vae_decoder=vae_decoder,
|
98 |
+
text_encoder=text_encoder,
|
99 |
+
tokenizer=tokenizer,
|
100 |
+
unet=unet,
|
101 |
+
controlnet=controlnet,
|
102 |
+
scheduler=scheduler,
|
103 |
+
safety_checker=safety_checker,
|
104 |
+
feature_extractor=feature_extractor,
|
105 |
+
)
|
106 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
107 |
+
|
108 |
+
|
109 |
+
def _default_height_width(self, height, width, image):
|
110 |
+
if isinstance(image, list):
|
111 |
+
image = image[0]
|
112 |
+
|
113 |
+
if height is None:
|
114 |
+
if isinstance(image, PIL.Image.Image):
|
115 |
+
height = image.height
|
116 |
+
elif isinstance(image, np.ndarray):
|
117 |
+
height = image.shape[3]
|
118 |
+
|
119 |
+
height = (height // 8) * 8 # round down to nearest multiple of 8
|
120 |
+
|
121 |
+
if width is None:
|
122 |
+
if isinstance(image, PIL.Image.Image):
|
123 |
+
width = image.width
|
124 |
+
elif isinstance(image, np.ndarray):
|
125 |
+
width = image.shape[2]
|
126 |
+
|
127 |
+
width = (width // 8) * 8 # round down to nearest multiple of 8
|
128 |
+
|
129 |
+
return height, width
|
130 |
+
|
131 |
+
def prepare_image(self, image, width, height, batch_size, num_images_per_prompt, dtype):
|
132 |
+
if not isinstance(image, np.ndarray):
|
133 |
+
if isinstance(image, PIL.Image.Image):
|
134 |
+
image = [image]
|
135 |
+
|
136 |
+
if isinstance(image[0], PIL.Image.Image):
|
137 |
+
image = [
|
138 |
+
np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image
|
139 |
+
]
|
140 |
+
image = np.concatenate(image, axis=0)
|
141 |
+
image = np.array(image).astype(np.float32) / 255.0
|
142 |
+
image = image.transpose(0, 3, 1, 2)
|
143 |
+
image = torch.from_numpy(image)
|
144 |
+
elif isinstance(image[0], np.ndarray):
|
145 |
+
image = np.concatenate(image, axis=0)
|
146 |
+
image = torch.from_numpy(image)
|
147 |
+
|
148 |
+
image_batch_size = image.shape[0]
|
149 |
+
|
150 |
+
if image_batch_size == 1:
|
151 |
+
repeat_by = batch_size
|
152 |
+
else:
|
153 |
+
# image batch size is the same as prompt batch size
|
154 |
+
repeat_by = num_images_per_prompt
|
155 |
+
|
156 |
+
image = image.repeat_interleave(repeat_by, dim=0)
|
157 |
+
|
158 |
+
return image
|
159 |
+
|
160 |
+
|
161 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
162 |
+
def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, generator, latents=None):
|
163 |
+
shape = (batch_size, num_channels_latents, height // 8, width // 8)
|
164 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
165 |
+
raise ValueError(
|
166 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
167 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
168 |
+
)
|
169 |
+
|
170 |
+
if latents is None:
|
171 |
+
latents = generator.randn(*shape).astype(dtype)
|
172 |
+
|
173 |
+
|
174 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
175 |
+
latents = latents * self.scheduler.init_noise_sigma
|
176 |
+
return latents
|
177 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
178 |
+
def prepare_extra_step_kwargs(self, generator, eta, torch_gen):
|
179 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
180 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
181 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
182 |
+
# and should be between [0, 1]
|
183 |
+
|
184 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
185 |
+
extra_step_kwargs = {}
|
186 |
+
if accepts_eta:
|
187 |
+
extra_step_kwargs["eta"] = eta
|
188 |
+
|
189 |
+
# check if the scheduler accepts generator
|
190 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
191 |
+
if accepts_generator:
|
192 |
+
extra_step_kwargs["generator"] = torch_gen
|
193 |
+
return extra_step_kwargs
|
194 |
+
|
195 |
+
def _encode_prompt(self, prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
|
196 |
+
r"""
|
197 |
+
Encodes the prompt into text encoder hidden states.
|
198 |
+
|
199 |
+
Args:
|
200 |
+
prompt (`str` or `List[str]`):
|
201 |
+
prompt to be encoded
|
202 |
+
num_images_per_prompt (`int`):
|
203 |
+
number of images that should be generated per prompt
|
204 |
+
do_classifier_free_guidance (`bool`):
|
205 |
+
whether to use classifier free guidance or not
|
206 |
+
negative_prompt (`str` or `List[str]`):
|
207 |
+
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
|
208 |
+
if `guidance_scale` is less than `1`).
|
209 |
+
"""
|
210 |
+
batch_size = len(prompt) if isinstance(prompt, list) else 1
|
211 |
+
|
212 |
+
# get prompt text embeddings
|
213 |
+
text_inputs = self.tokenizer(
|
214 |
+
prompt,
|
215 |
+
padding="max_length",
|
216 |
+
max_length=self.tokenizer.model_max_length,
|
217 |
+
truncation=True,
|
218 |
+
return_tensors="np",
|
219 |
+
)
|
220 |
+
text_input_ids = text_inputs.input_ids
|
221 |
+
untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids
|
222 |
+
|
223 |
+
if not np.array_equal(text_input_ids, untruncated_ids):
|
224 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
|
225 |
+
logger.warning(
|
226 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
227 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
228 |
+
)
|
229 |
+
|
230 |
+
prompt_embeds = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0]
|
231 |
+
prompt_embeds = np.repeat(prompt_embeds, num_images_per_prompt, axis=0)
|
232 |
+
|
233 |
+
# get unconditional embeddings for classifier free guidance
|
234 |
+
if do_classifier_free_guidance:
|
235 |
+
uncond_tokens: List[str]
|
236 |
+
if negative_prompt is None:
|
237 |
+
uncond_tokens = [""] * batch_size
|
238 |
+
elif type(prompt) is not type(negative_prompt):
|
239 |
+
raise TypeError(
|
240 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
241 |
+
f" {type(prompt)}."
|
242 |
+
)
|
243 |
+
elif isinstance(negative_prompt, str):
|
244 |
+
uncond_tokens = [negative_prompt] * batch_size
|
245 |
+
elif batch_size != len(negative_prompt):
|
246 |
+
raise ValueError(
|
247 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
248 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
249 |
+
" the batch size of `prompt`."
|
250 |
+
)
|
251 |
+
else:
|
252 |
+
uncond_tokens = negative_prompt
|
253 |
+
|
254 |
+
max_length = text_input_ids.shape[-1]
|
255 |
+
uncond_input = self.tokenizer(
|
256 |
+
uncond_tokens,
|
257 |
+
padding="max_length",
|
258 |
+
max_length=max_length,
|
259 |
+
truncation=True,
|
260 |
+
return_tensors="np",
|
261 |
+
)
|
262 |
+
negative_prompt_embeds = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0]
|
263 |
+
negative_prompt_embeds = np.repeat(negative_prompt_embeds, num_images_per_prompt, axis=0)
|
264 |
+
|
265 |
+
# For classifier free guidance, we need to do two forward passes.
|
266 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
267 |
+
# to avoid doing two forward passes
|
268 |
+
prompt_embeds = np.concatenate([negative_prompt_embeds, prompt_embeds])
|
269 |
+
|
270 |
+
return prompt_embeds
|
271 |
+
|
272 |
+
def __call__(
|
273 |
+
self,
|
274 |
+
prompt: Union[str, List[str]],
|
275 |
+
image: Union[np.ndarray, PIL.Image.Image] = None,
|
276 |
+
height: Optional[int] = None,
|
277 |
+
width: Optional[int] = None,
|
278 |
+
num_inference_steps: Optional[int] = 50,
|
279 |
+
guidance_scale: Optional[float] = 7.5,
|
280 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
281 |
+
num_images_per_prompt: Optional[int] = 1,
|
282 |
+
eta: Optional[float] = 0.0,
|
283 |
+
generator: Optional[np.random.RandomState] = None,
|
284 |
+
latents: Optional[np.ndarray] = None,
|
285 |
+
output_type: Optional[str] = "pil",
|
286 |
+
return_dict: bool = True,
|
287 |
+
callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
|
288 |
+
callback_steps: int = 1,
|
289 |
+
controlnet_conditioning_scale: float = 1.0,
|
290 |
+
):
|
291 |
+
if isinstance(prompt, str):
|
292 |
+
batch_size = 1
|
293 |
+
elif isinstance(prompt, list):
|
294 |
+
batch_size = len(prompt)
|
295 |
+
else:
|
296 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
297 |
+
|
298 |
+
|
299 |
+
if generator:
|
300 |
+
torch_seed = generator.randint(2147483647)
|
301 |
+
torch_gen = torch.Generator().manual_seed(torch_seed)
|
302 |
+
else:
|
303 |
+
generator = np.random
|
304 |
+
torch_gen = None
|
305 |
+
|
306 |
+
height, width = self._default_height_width(height, width, image)
|
307 |
+
|
308 |
+
if height % 8 != 0 or width % 8 != 0:
|
309 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
310 |
+
|
311 |
+
if (callback_steps is None) or (
|
312 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
313 |
+
):
|
314 |
+
raise ValueError(
|
315 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
316 |
+
f" {type(callback_steps)}."
|
317 |
+
)
|
318 |
+
|
319 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
320 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
321 |
+
# corresponds to doing no classifier free guidance.
|
322 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
323 |
+
|
324 |
+
prompt_embeds = self._encode_prompt(
|
325 |
+
prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
|
326 |
+
)
|
327 |
+
|
328 |
+
# 4. Prepare image
|
329 |
+
image = self.prepare_image(
|
330 |
+
image,
|
331 |
+
width,
|
332 |
+
height,
|
333 |
+
batch_size * num_images_per_prompt,
|
334 |
+
num_images_per_prompt,
|
335 |
+
np.float32,
|
336 |
+
).numpy()
|
337 |
+
|
338 |
+
if do_classifier_free_guidance:
|
339 |
+
image = np.concatenate([image] * 2)
|
340 |
+
|
341 |
+
# get the initial random noise unless the user supplied it
|
342 |
+
latents_dtype = prompt_embeds.dtype
|
343 |
+
latents_shape = (batch_size * num_images_per_prompt, 4, height // 8, width // 8)
|
344 |
+
|
345 |
+
num_channels_latents = 4
|
346 |
+
latents = self.prepare_latents(
|
347 |
+
batch_size * num_images_per_prompt,
|
348 |
+
num_channels_latents,
|
349 |
+
height,
|
350 |
+
width,
|
351 |
+
latents_dtype,
|
352 |
+
generator,
|
353 |
+
latents,
|
354 |
+
)
|
355 |
+
|
356 |
+
# set timesteps
|
357 |
+
self.scheduler.set_timesteps(num_inference_steps)
|
358 |
+
timesteps = self.scheduler.timesteps
|
359 |
+
|
360 |
+
|
361 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
362 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
363 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
364 |
+
# and should be between [0, 1]
|
365 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta, torch_gen)
|
366 |
+
|
367 |
+
timestep_dtype = next(
|
368 |
+
(input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
|
369 |
+
)
|
370 |
+
timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
|
371 |
+
|
372 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
373 |
+
|
374 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
375 |
+
for i, t in enumerate(timesteps):
|
376 |
+
# expand the latents if we are doing classifier free guidance
|
377 |
+
latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents
|
378 |
+
latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t)
|
379 |
+
latent_model_input = latent_model_input.cpu().numpy()
|
380 |
+
|
381 |
+
timestep = np.array([t], dtype=timestep_dtype)
|
382 |
+
|
383 |
+
blocksamples = self.controlnet(
|
384 |
+
sample=latent_model_input,
|
385 |
+
timestep=timestep,
|
386 |
+
encoder_hidden_states=prompt_embeds,
|
387 |
+
controlnet_cond=image,
|
388 |
+
conditioning_scale=1.0
|
389 |
+
)
|
390 |
+
|
391 |
+
mid_block_res_sample=blocksamples[12]
|
392 |
+
down_block_res_samples=blocksamples[0:12]
|
393 |
+
|
394 |
+
down_block_res_samples = [
|
395 |
+
down_block_res_sample * controlnet_conditioning_scale
|
396 |
+
for down_block_res_sample in down_block_res_samples
|
397 |
+
]
|
398 |
+
mid_block_res_sample *= controlnet_conditioning_scale
|
399 |
+
|
400 |
+
# predict the noise residual
|
401 |
+
|
402 |
+
noise_pred = self.unet(
|
403 |
+
sample=latent_model_input,
|
404 |
+
timestep=timestep,
|
405 |
+
encoder_hidden_states=prompt_embeds,
|
406 |
+
down_block_0=down_block_res_samples[0],
|
407 |
+
down_block_1=down_block_res_samples[1],
|
408 |
+
down_block_2=down_block_res_samples[2],
|
409 |
+
down_block_3=down_block_res_samples[3],
|
410 |
+
down_block_4=down_block_res_samples[4],
|
411 |
+
down_block_5=down_block_res_samples[5],
|
412 |
+
down_block_6=down_block_res_samples[6],
|
413 |
+
down_block_7=down_block_res_samples[7],
|
414 |
+
down_block_8=down_block_res_samples[8],
|
415 |
+
down_block_9=down_block_res_samples[9],
|
416 |
+
down_block_10=down_block_res_samples[10],
|
417 |
+
down_block_11=down_block_res_samples[11],
|
418 |
+
mid_block_additional_residual=mid_block_res_sample
|
419 |
+
)
|
420 |
+
noise_pred = noise_pred[0]
|
421 |
+
|
422 |
+
# perform guidance
|
423 |
+
if do_classifier_free_guidance:
|
424 |
+
noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
|
425 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
426 |
+
|
427 |
+
# compute the previous noisy sample x_t -> x_t-1
|
428 |
+
scheduler_output = self.scheduler.step(
|
429 |
+
torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs
|
430 |
+
)
|
431 |
+
latents = scheduler_output.prev_sample.numpy()
|
432 |
+
|
433 |
+
# call the callback, if provided
|
434 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
435 |
+
progress_bar.update()
|
436 |
+
if callback is not None and i % callback_steps == 0:
|
437 |
+
callback(i, t, latents)
|
438 |
+
|
439 |
+
latents = 1 / 0.18215 * latents
|
440 |
+
# image = self.vae_decoder(latent_sample=latents)[0]
|
441 |
+
# it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
|
442 |
+
image = np.concatenate(
|
443 |
+
[self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
|
444 |
+
)
|
445 |
+
|
446 |
+
image = np.clip(image / 2 + 0.5, 0, 1)
|
447 |
+
image = image.transpose((0, 2, 3, 1))
|
448 |
+
|
449 |
+
if self.safety_checker is not None:
|
450 |
+
safety_checker_input = self.feature_extractor(
|
451 |
+
self.numpy_to_pil(image), return_tensors="np"
|
452 |
+
).pixel_values.astype(image.dtype)
|
453 |
+
|
454 |
+
images, has_nsfw_concept = [], []
|
455 |
+
for i in range(image.shape[0]):
|
456 |
+
image_i, has_nsfw_concept_i = self.safety_checker(
|
457 |
+
clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
|
458 |
+
)
|
459 |
+
images.append(image_i)
|
460 |
+
has_nsfw_concept.append(has_nsfw_concept_i[0])
|
461 |
+
image = np.concatenate(images)
|
462 |
+
else:
|
463 |
+
has_nsfw_concept = None
|
464 |
+
|
465 |
+
if output_type == "pil":
|
466 |
+
image = self.numpy_to_pil(image)
|
467 |
+
|
468 |
+
if not return_dict:
|
469 |
+
return (image, has_nsfw_concept)
|
470 |
+
|
471 |
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|
472 |
+
|
patchedstabledifftoonnx_withou_modelort/pipeline_onnx_stable_diffusion_instruct_pix2pix.py
ADDED
@@ -0,0 +1,553 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 The InstructPix2Pix Authors and The HuggingFace Team.
|
2 |
+
# Converted for use with ONNX as part of https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16
|
3 |
+
|
4 |
+
import inspect
|
5 |
+
from typing import Callable, List, Optional, Union
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
import PIL
|
9 |
+
import torch
|
10 |
+
from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
|
11 |
+
|
12 |
+
try:
|
13 |
+
from diffusers.pipelines.onnx_utils import ORT_TO_NP_TYPE
|
14 |
+
except ImportError:
|
15 |
+
ORT_TO_NP_TYPE = {
|
16 |
+
"tensor(bool)": np.bool_,
|
17 |
+
"tensor(int8)": np.int8,
|
18 |
+
"tensor(uint8)": np.uint8,
|
19 |
+
"tensor(int16)": np.int16,
|
20 |
+
"tensor(uint16)": np.uint16,
|
21 |
+
"tensor(int32)": np.int32,
|
22 |
+
"tensor(uint32)": np.uint32,
|
23 |
+
"tensor(int64)": np.int64,
|
24 |
+
"tensor(uint64)": np.uint64,
|
25 |
+
"tensor(float16)": np.float16,
|
26 |
+
"tensor(float)": np.float32,
|
27 |
+
"tensor(double)": np.float64,
|
28 |
+
}
|
29 |
+
|
30 |
+
from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, SchedulerMixin
|
31 |
+
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
32 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
|
33 |
+
from diffusers.utils import (
|
34 |
+
PIL_INTERPOLATION,
|
35 |
+
deprecate,
|
36 |
+
logging,
|
37 |
+
randn_tensor,
|
38 |
+
)
|
39 |
+
from diffusers.pipeline_utils import DiffusionPipeline
|
40 |
+
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
|
41 |
+
|
42 |
+
|
43 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
44 |
+
|
45 |
+
|
46 |
+
# Simplified and ONNX specific version (only allows 1 image, np over torch)
|
47 |
+
def preprocess(image):
|
48 |
+
if isinstance(image, np.ndarray):
|
49 |
+
return image
|
50 |
+
|
51 |
+
w, h = image.size
|
52 |
+
w, h = map(lambda x: x - x % 8, (w, h)) # resize to integer multiple of 8
|
53 |
+
image = np.array(image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]))[None, :]
|
54 |
+
image = np.array(image).astype(np.float32) / 255.0
|
55 |
+
image = image.transpose(0, 3, 1, 2)
|
56 |
+
image = 2.0 * image - 1.0
|
57 |
+
return image
|
58 |
+
|
59 |
+
|
60 |
+
class OnnxStableDiffusionInstructPix2PixPipeline(DiffusionPipeline):
|
61 |
+
r"""
|
62 |
+
Pipeline for pixel-level image editing by following text instructions. Based on Stable Diffusion.
|
63 |
+
|
64 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
65 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
66 |
+
|
67 |
+
Args:
|
68 |
+
vae ([`AutoencoderKL`]):
|
69 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
70 |
+
text_encoder ([`CLIPTextModel`]):
|
71 |
+
Frozen text-encoder. Stable Diffusion uses the text portion of
|
72 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
73 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
74 |
+
tokenizer (`CLIPTokenizer`):
|
75 |
+
Tokenizer of class
|
76 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
77 |
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
78 |
+
scheduler ([`SchedulerMixin`]):
|
79 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
80 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
81 |
+
safety_checker ([`StableDiffusionSafetyChecker`]):
|
82 |
+
Classification module that estimates whether generated images could be considered offensive or harmful.
|
83 |
+
Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
|
84 |
+
feature_extractor ([`CLIPFeatureExtractor`]):
|
85 |
+
Model that extracts features from generated images to be used as inputs for the `safety_checker`.
|
86 |
+
"""
|
87 |
+
vae_encoder: OnnxRuntimeModel
|
88 |
+
vae_decoder: OnnxRuntimeModel
|
89 |
+
text_encoder: OnnxRuntimeModel
|
90 |
+
tokenizer: CLIPTokenizer
|
91 |
+
unet: OnnxRuntimeModel
|
92 |
+
scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]
|
93 |
+
safety_checker: OnnxRuntimeModel
|
94 |
+
feature_extractor: CLIPFeatureExtractor
|
95 |
+
_optional_components = ["safety_checker", "feature_extractor"]
|
96 |
+
|
97 |
+
def __init__(
|
98 |
+
self,
|
99 |
+
vae_encoder: OnnxRuntimeModel,
|
100 |
+
vae_decoder: OnnxRuntimeModel,
|
101 |
+
text_encoder: OnnxRuntimeModel,
|
102 |
+
tokenizer: CLIPTokenizer,
|
103 |
+
unet: OnnxRuntimeModel,
|
104 |
+
scheduler: KarrasDiffusionSchedulers,
|
105 |
+
safety_checker: OnnxRuntimeModel,
|
106 |
+
feature_extractor: CLIPFeatureExtractor,
|
107 |
+
requires_safety_checker: bool = True,
|
108 |
+
):
|
109 |
+
super().__init__()
|
110 |
+
self.unet_in_channels = 8
|
111 |
+
self.vae_scale_factor = 8
|
112 |
+
|
113 |
+
if safety_checker is None and requires_safety_checker:
|
114 |
+
logger.warning(
|
115 |
+
f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
|
116 |
+
" that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
|
117 |
+
" results in services or applications open to the public. Both the diffusers team and Hugging Face"
|
118 |
+
" strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
|
119 |
+
" it only for use-cases that involve analyzing network behavior or auditing its results. For more"
|
120 |
+
" information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
|
121 |
+
)
|
122 |
+
|
123 |
+
if safety_checker is not None and feature_extractor is None:
|
124 |
+
raise ValueError(
|
125 |
+
"Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
|
126 |
+
" checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
|
127 |
+
)
|
128 |
+
|
129 |
+
self.register_modules(
|
130 |
+
vae_encoder=vae_encoder,
|
131 |
+
vae_decoder=vae_decoder,
|
132 |
+
text_encoder=text_encoder,
|
133 |
+
tokenizer=tokenizer,
|
134 |
+
unet=unet,
|
135 |
+
scheduler=scheduler,
|
136 |
+
safety_checker=safety_checker,
|
137 |
+
feature_extractor=feature_extractor,
|
138 |
+
)
|
139 |
+
#self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
140 |
+
self.register_to_config(requires_safety_checker=requires_safety_checker)
|
141 |
+
|
142 |
+
@torch.no_grad()
|
143 |
+
def __call__(
|
144 |
+
self,
|
145 |
+
prompt: Union[str, List[str]] = None,
|
146 |
+
image: Union[np.ndarray, PIL.Image.Image] = None,
|
147 |
+
num_inference_steps: int = 100,
|
148 |
+
guidance_scale: float = 7.5,
|
149 |
+
image_guidance_scale: float = 1.5,
|
150 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
151 |
+
num_images_per_prompt: Optional[int] = 1,
|
152 |
+
eta: float = 0.0,
|
153 |
+
generator: Optional[np.random.RandomState] = None,
|
154 |
+
latents: Optional[np.ndarray] = None,
|
155 |
+
output_type: Optional[str] = "pil",
|
156 |
+
return_dict: bool = True,
|
157 |
+
callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
|
158 |
+
callback_steps: int = 1,
|
159 |
+
):
|
160 |
+
r"""
|
161 |
+
Function invoked when calling the pipeline for generation.
|
162 |
+
|
163 |
+
Args:
|
164 |
+
prompt (`str` or `List[str]`, *optional*):
|
165 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
166 |
+
instead.
|
167 |
+
image (`PIL.Image.Image`):
|
168 |
+
`Image`, or tensor representing an image batch which will be repainted according to `prompt`.
|
169 |
+
num_inference_steps (`int`, *optional*, defaults to 100):
|
170 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
171 |
+
expense of slower inference.
|
172 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
173 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
174 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
175 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
176 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
177 |
+
usually at the expense of lower image quality. This pipeline requires a value of at least `1`.
|
178 |
+
image_guidance_scale (`float`, *optional*, defaults to 1.5):
|
179 |
+
Image guidance scale is to push the generated image towards the inital image `image`. Image guidance
|
180 |
+
scale is enabled by setting `image_guidance_scale > 1`. Higher image guidance scale encourages to
|
181 |
+
generate images that are closely linked to the source image `image`, usually at the expense of lower
|
182 |
+
image quality. This pipeline requires a value of at least `1`.
|
183 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
184 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
185 |
+
`negative_prompt_embeds`. instead. Ignored when not using guidance (i.e., ignored if `guidance_scale`
|
186 |
+
is less than `1`).
|
187 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
188 |
+
The number of images to generate per prompt.
|
189 |
+
eta (`float`, *optional*, defaults to 0.0):
|
190 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
191 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
192 |
+
generator (`torch.Generator`, *optional*):
|
193 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
194 |
+
to make generation deterministic.
|
195 |
+
latents (`torch.FloatTensor`, *optional*):
|
196 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
197 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
198 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
199 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
200 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
201 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
202 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
203 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
204 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
205 |
+
argument.
|
206 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
207 |
+
The output format of the generate image. Choose between
|
208 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
209 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
210 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
211 |
+
plain tuple.
|
212 |
+
callback (`Callable`, *optional*):
|
213 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
214 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
215 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
216 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
217 |
+
called at every step.
|
218 |
+
|
219 |
+
Examples:
|
220 |
+
|
221 |
+
```py
|
222 |
+
>>> import PIL
|
223 |
+
>>> import requests
|
224 |
+
>>> import torch
|
225 |
+
>>> from io import BytesIO
|
226 |
+
|
227 |
+
>>> from diffusers import StableDiffusionInstructPix2PixPipeline
|
228 |
+
|
229 |
+
|
230 |
+
>>> def download_image(url):
|
231 |
+
... response = requests.get(url)
|
232 |
+
... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
|
233 |
+
|
234 |
+
|
235 |
+
>>> img_url = "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png"
|
236 |
+
|
237 |
+
>>> image = download_image(img_url).resize((512, 512))
|
238 |
+
|
239 |
+
>>> pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(
|
240 |
+
... "timbrooks/instruct-pix2pix", torch_dtype=torch.float16
|
241 |
+
... )
|
242 |
+
>>> pipe = pipe.to("cuda")
|
243 |
+
|
244 |
+
>>> prompt = "make the mountains snowy"
|
245 |
+
>>> image = pipe(prompt=prompt, image=image).images[0]
|
246 |
+
```
|
247 |
+
|
248 |
+
Returns:
|
249 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
250 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
|
251 |
+
When returning a tuple, the first element is a list with the generated images, and the second element is a
|
252 |
+
list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
|
253 |
+
(nsfw) content, according to the `safety_checker`.
|
254 |
+
"""
|
255 |
+
|
256 |
+
# We need a deterministic torch generator for schedulers if a (likely seeded) generator was provided
|
257 |
+
|
258 |
+
if generator:
|
259 |
+
torch_seed = generator.randint(2147483647)
|
260 |
+
torch_gen = torch.Generator().manual_seed(torch_seed)
|
261 |
+
else:
|
262 |
+
generator = np.random
|
263 |
+
torch_gen = None
|
264 |
+
|
265 |
+
# 0. Check inputs
|
266 |
+
self.check_inputs(prompt, callback_steps)
|
267 |
+
|
268 |
+
if image is None:
|
269 |
+
raise ValueError("`image` input cannot be undefined.")
|
270 |
+
|
271 |
+
# 1. Define call parameters
|
272 |
+
if isinstance(prompt, str):
|
273 |
+
batch_size = 1
|
274 |
+
elif isinstance(prompt, list):
|
275 |
+
batch_size = len(prompt)
|
276 |
+
else:
|
277 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
278 |
+
|
279 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
280 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
281 |
+
# corresponds to doing no classifier free guidance.
|
282 |
+
do_classifier_free_guidance = guidance_scale > 1.0 and image_guidance_scale >= 1.0
|
283 |
+
# check if scheduler is in sigmas space
|
284 |
+
scheduler_is_in_sigma_space = hasattr(self.scheduler, "sigmas")
|
285 |
+
|
286 |
+
# 2. Encode input prompt
|
287 |
+
prompt_embeds = self._encode_prompt(
|
288 |
+
prompt,
|
289 |
+
num_images_per_prompt,
|
290 |
+
do_classifier_free_guidance,
|
291 |
+
negative_prompt,
|
292 |
+
)
|
293 |
+
|
294 |
+
# 3. Preprocess image
|
295 |
+
image = preprocess(image)
|
296 |
+
height, width = image.shape[-2:]
|
297 |
+
|
298 |
+
# 4. set timesteps
|
299 |
+
self.scheduler.set_timesteps(num_inference_steps)
|
300 |
+
timesteps = self.scheduler.timesteps
|
301 |
+
|
302 |
+
# 5. Prepare Image latents
|
303 |
+
latents_dtype = prompt_embeds.dtype
|
304 |
+
image = image.astype(latents_dtype)
|
305 |
+
# encode the init image into latents and scale the latents
|
306 |
+
image_latents = self.vae_encoder(sample=image)[0]
|
307 |
+
if do_classifier_free_guidance:
|
308 |
+
uncond_image_latents = np.zeros_like(image_latents)
|
309 |
+
image_latents = np.concatenate((image_latents, image_latents, uncond_image_latents), axis=0)
|
310 |
+
|
311 |
+
# 6. Prepare latent variables
|
312 |
+
latents_dtype = prompt_embeds.dtype
|
313 |
+
latents_shape = (batch_size * num_images_per_prompt, 4, height // 8, width // 8)
|
314 |
+
if latents is None:
|
315 |
+
latents = generator.randn(*latents_shape).astype(latents_dtype)
|
316 |
+
elif latents.shape != latents_shape:
|
317 |
+
raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
|
318 |
+
latents = latents * self.scheduler.init_noise_sigma.numpy()
|
319 |
+
|
320 |
+
# 7. Check that shapes of latents and image match the UNet channels
|
321 |
+
num_channels_image = image_latents.shape[1]
|
322 |
+
if 4+ num_channels_image != self.unet_in_channels:
|
323 |
+
raise ValueError(
|
324 |
+
f"Incorrect configuration settings! The config of `pipeline.unet`: expects"
|
325 |
+
f" {self.unet_in_channels} but received `num_channels_latents`: {num_channels_latents} +"
|
326 |
+
f" `num_channels_image`: {num_channels_image} "
|
327 |
+
f" = {num_channels_latents+num_channels_image}. Please verify the config of"
|
328 |
+
" `pipeline.unet` or your `image` input."
|
329 |
+
)
|
330 |
+
|
331 |
+
timestep_dtype = next(
|
332 |
+
(input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
|
333 |
+
)
|
334 |
+
timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
|
335 |
+
|
336 |
+
# 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
337 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta, torch_gen)
|
338 |
+
|
339 |
+
# 9. Denoising loop
|
340 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
341 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
342 |
+
for i, t in enumerate(timesteps):
|
343 |
+
# Expand the latents if we are doing classifier free guidance.
|
344 |
+
# The latents are expanded 3 times because for pix2pix the guidance\
|
345 |
+
# is applied for both the text and the input image.
|
346 |
+
latent_model_input = np.concatenate([latents] * 3) if do_classifier_free_guidance else latents
|
347 |
+
|
348 |
+
scaled_latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t)
|
349 |
+
scaled_latent_model_input = scaled_latent_model_input.cpu().numpy()
|
350 |
+
|
351 |
+
scaled_latent_model_input = np.concatenate([scaled_latent_model_input, image_latents], axis=1)
|
352 |
+
|
353 |
+
# predict the noise residual
|
354 |
+
|
355 |
+
noise_pred = self.unet(
|
356 |
+
sample=scaled_latent_model_input,
|
357 |
+
timestep=np.array([t], dtype=timestep_dtype),
|
358 |
+
encoder_hidden_states=prompt_embeds,
|
359 |
+
)[0]
|
360 |
+
|
361 |
+
# Hack:
|
362 |
+
# For karras style schedulers the model does classifer free guidance using the
|
363 |
+
# predicted_original_sample instead of the noise_pred. So we need to compute the
|
364 |
+
# predicted_original_sample here if we are using a karras style scheduler.
|
365 |
+
if scheduler_is_in_sigma_space:
|
366 |
+
step_index = (self.scheduler.timesteps == t).nonzero().item()
|
367 |
+
sigma = self.scheduler.sigmas[step_index]
|
368 |
+
noise_pred = latent_model_input - sigma.numpy() * noise_pred
|
369 |
+
|
370 |
+
# perform guidance
|
371 |
+
if do_classifier_free_guidance:
|
372 |
+
noise_pred_text, noise_pred_image, noise_pred_uncond = np.split(noise_pred, 3)
|
373 |
+
noise_pred = (
|
374 |
+
noise_pred_uncond
|
375 |
+
+ guidance_scale * (noise_pred_text - noise_pred_image)
|
376 |
+
+ image_guidance_scale * (noise_pred_image - noise_pred_uncond)
|
377 |
+
)
|
378 |
+
|
379 |
+
# Hack:
|
380 |
+
# For karras style schedulers the model does classifer free guidance using the
|
381 |
+
# predicted_original_sample instead of the noise_pred. But the scheduler.step function
|
382 |
+
# expects the noise_pred and computes the predicted_original_sample internally. So we
|
383 |
+
# need to overwrite the noise_pred here such that the value of the computed
|
384 |
+
# predicted_original_sample is correct.
|
385 |
+
if scheduler_is_in_sigma_space:
|
386 |
+
noise_pred = (noise_pred - latents) / (-sigma)
|
387 |
+
|
388 |
+
# compute the previous noisy sample x_t -> x_t-1
|
389 |
+
scheduler_output = self.scheduler.step(
|
390 |
+
noise_pred, t, torch.from_numpy(latents), **extra_step_kwargs
|
391 |
+
)
|
392 |
+
latents = scheduler_output.prev_sample.numpy()
|
393 |
+
|
394 |
+
# call the callback, if provided
|
395 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
396 |
+
progress_bar.update()
|
397 |
+
if callback is not None and i % callback_steps == 0:
|
398 |
+
callback(i, t, latents.numpy())
|
399 |
+
|
400 |
+
# 10. Post-processing
|
401 |
+
image = self.decode_latents(latents)
|
402 |
+
|
403 |
+
# 11. Run safety checker
|
404 |
+
image, has_nsfw_concept = self.run_safety_checker(image)
|
405 |
+
|
406 |
+
# 12. Convert to PIL
|
407 |
+
if output_type == "pil":
|
408 |
+
image = self.numpy_to_pil(image)
|
409 |
+
|
410 |
+
if not return_dict:
|
411 |
+
return (image, has_nsfw_concept)
|
412 |
+
|
413 |
+
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
|
414 |
+
|
415 |
+
def _encode_prompt(self, prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
|
416 |
+
r"""
|
417 |
+
Encodes the prompt into text encoder hidden states.
|
418 |
+
|
419 |
+
Args:
|
420 |
+
prompt (`str` or `List[str]`):
|
421 |
+
prompt to be encoded
|
422 |
+
num_images_per_prompt (`int`):
|
423 |
+
number of images that should be generated per prompt
|
424 |
+
do_classifier_free_guidance (`bool`):
|
425 |
+
whether to use classifier free guidance or not
|
426 |
+
negative_prompt (`str` or `List[str]`):
|
427 |
+
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
|
428 |
+
if `guidance_scale` is less than `1`).
|
429 |
+
"""
|
430 |
+
negative_prompt_embeds = None
|
431 |
+
batch_size = len(prompt) if isinstance(prompt, list) else 1
|
432 |
+
|
433 |
+
# get prompt text embeddings
|
434 |
+
text_inputs = self.tokenizer(
|
435 |
+
prompt,
|
436 |
+
padding="max_length",
|
437 |
+
max_length=self.tokenizer.model_max_length,
|
438 |
+
truncation=True,
|
439 |
+
return_tensors="np",
|
440 |
+
)
|
441 |
+
text_input_ids = text_inputs.input_ids
|
442 |
+
untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids
|
443 |
+
|
444 |
+
if not np.array_equal(text_input_ids, untruncated_ids):
|
445 |
+
removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
|
446 |
+
logger.warning(
|
447 |
+
"The following part of your input was truncated because CLIP can only handle sequences up to"
|
448 |
+
f" {self.tokenizer.model_max_length} tokens: {removed_text}"
|
449 |
+
)
|
450 |
+
|
451 |
+
prompt_embeds = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0]
|
452 |
+
prompt_embeds = np.repeat(prompt_embeds, num_images_per_prompt, axis=0)
|
453 |
+
|
454 |
+
# get unconditional embeddings for classifier free guidance
|
455 |
+
if do_classifier_free_guidance:
|
456 |
+
uncond_tokens: List[str]
|
457 |
+
if negative_prompt is None:
|
458 |
+
uncond_tokens = [""] * batch_size
|
459 |
+
elif type(prompt) is not type(negative_prompt):
|
460 |
+
raise TypeError(
|
461 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
462 |
+
f" {type(prompt)}."
|
463 |
+
)
|
464 |
+
elif isinstance(negative_prompt, str):
|
465 |
+
uncond_tokens = [negative_prompt] * batch_size
|
466 |
+
elif batch_size != len(negative_prompt):
|
467 |
+
raise ValueError(
|
468 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
469 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
470 |
+
" the batch size of `prompt`."
|
471 |
+
)
|
472 |
+
else:
|
473 |
+
uncond_tokens = negative_prompt
|
474 |
+
|
475 |
+
max_length = text_input_ids.shape[-1]
|
476 |
+
uncond_input = self.tokenizer(
|
477 |
+
uncond_tokens,
|
478 |
+
padding="max_length",
|
479 |
+
max_length=max_length,
|
480 |
+
truncation=True,
|
481 |
+
return_tensors="np",
|
482 |
+
)
|
483 |
+
negative_prompt_embeds = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0]
|
484 |
+
negative_prompt_embeds = np.repeat(negative_prompt_embeds, num_images_per_prompt, axis=0)
|
485 |
+
|
486 |
+
# For classifier free guidance, we need to do two forward passes.
|
487 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
488 |
+
# to avoid doing two forward passes
|
489 |
+
# pix2pix has two negative embeddings, and unlike in other pipelines latents are ordered [prompt_embeds, negative_prompt_embeds, negative_prompt_embeds]
|
490 |
+
|
491 |
+
prompt_embeds = np.concatenate((prompt_embeds, negative_prompt_embeds, negative_prompt_embeds))
|
492 |
+
|
493 |
+
return prompt_embeds
|
494 |
+
|
495 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
|
496 |
+
def run_safety_checker(self, image):
|
497 |
+
if self.safety_checker is not None:
|
498 |
+
safety_checker_input = self.feature_extractor(
|
499 |
+
self.numpy_to_pil(image), return_tensors="np"
|
500 |
+
).pixel_values.astype(image.dtype)
|
501 |
+
# safety_checker does not support batched inputs yet
|
502 |
+
images, has_nsfw_concept = [], []
|
503 |
+
for i in range(image.shape[0]):
|
504 |
+
image_i, has_nsfw_concept_i = self.safety_checker(
|
505 |
+
clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
|
506 |
+
)
|
507 |
+
images.append(image_i)
|
508 |
+
has_nsfw_concept.append(has_nsfw_concept_i[0])
|
509 |
+
image = np.concatenate(images)
|
510 |
+
else:
|
511 |
+
has_nsfw_concept = None
|
512 |
+
return image, has_nsfw_concept
|
513 |
+
|
514 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
515 |
+
def prepare_extra_step_kwargs(self, generator, eta, torch_gen):
|
516 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
517 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
518 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
519 |
+
# and should be between [0, 1]
|
520 |
+
|
521 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
522 |
+
extra_step_kwargs = {}
|
523 |
+
if accepts_eta:
|
524 |
+
extra_step_kwargs["eta"] = eta
|
525 |
+
|
526 |
+
# check if the scheduler accepts generator
|
527 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
528 |
+
if accepts_generator:
|
529 |
+
extra_step_kwargs["generator"] = torch_gen
|
530 |
+
return extra_step_kwargs
|
531 |
+
|
532 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
|
533 |
+
def decode_latents(self, latents):
|
534 |
+
latents = 1 / 0.18215 * latents
|
535 |
+
image = np.concatenate(
|
536 |
+
[self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
|
537 |
+
)
|
538 |
+
image = np.clip(image / 2 + 0.5, 0, 1)
|
539 |
+
image = image.transpose((0, 2, 3, 1))
|
540 |
+
return image
|
541 |
+
|
542 |
+
def check_inputs(self, prompt, callback_steps):
|
543 |
+
if not isinstance(prompt, str) and not isinstance(prompt, list):
|
544 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
545 |
+
|
546 |
+
if (callback_steps is None) or (
|
547 |
+
callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
|
548 |
+
):
|
549 |
+
raise ValueError(
|
550 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
551 |
+
f" {type(callback_steps)}."
|
552 |
+
)
|
553 |
+
|
patchedstabledifftoonnx_withou_modelort/pix2pixUI.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import gradio as gr
|
3 |
+
|
4 |
+
from pipeline_onnx_stable_diffusion_instruct_pix2pix import OnnxStableDiffusionInstructPix2PixPipeline
|
5 |
+
from diffusers import DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler
|
6 |
+
|
7 |
+
def pix2pix(input_img, prompt, guide, iguide, steps, seed):
|
8 |
+
if seed == -1:
|
9 |
+
generator=None
|
10 |
+
else:
|
11 |
+
generator=np.random
|
12 |
+
generator.seed(seed)
|
13 |
+
img = pipe(
|
14 |
+
prompt=prompt,
|
15 |
+
image=input_img,
|
16 |
+
num_inference_steps=steps,
|
17 |
+
guidance_scale=guide,
|
18 |
+
image_guidance_scale=iguide,
|
19 |
+
generator=generator).images[0]
|
20 |
+
return img
|
21 |
+
|
22 |
+
if __name__ == "__main__":
|
23 |
+
model="./model/ip2p-base-fp16-vae_ft_mse-autoslicing"
|
24 |
+
pipe = OnnxStableDiffusionInstructPix2PixPipeline.from_pretrained(model, provider="DmlExecutionProvider", safety_checker=None)
|
25 |
+
pipe.scheduler=EulerAncestralDiscreteScheduler.from_pretrained(model, subfolder="scheduler")
|
26 |
+
|
27 |
+
demo=gr.Interface(pix2pix, gr.Image(shape=(512,512)), "image")
|
28 |
+
title="ONNX Instruct Pix 2 Pix"
|
29 |
+
css = "#imgbox img {max-width: 100% !important; }\n#imgbox div {height: auto;}"
|
30 |
+
with gr.Blocks(title=title, css=css) as demo:
|
31 |
+
with gr.Row():
|
32 |
+
with gr.Column(scale=1):
|
33 |
+
seed = gr.Number(value=-1, label="seed", precision=0)
|
34 |
+
with gr.Column(scale=14):
|
35 |
+
prompt = gr.Textbox(value="", lines=2, label="prompt")
|
36 |
+
with gr.Row():
|
37 |
+
with gr.Column(scale=1):
|
38 |
+
guide = gr.Slider(1.1, 10, value=3, step=0.1, label="Text guidance")
|
39 |
+
with gr.Column(scale=1):
|
40 |
+
iguide = gr.Slider(1, 10, value=1.1, step=0.1, label="Image guidance")
|
41 |
+
with gr.Column(scale=1):
|
42 |
+
steps = gr.Slider(10,100, value=30, step=1, label="Steps")
|
43 |
+
with gr.Row():
|
44 |
+
with gr.Column(scale=1):
|
45 |
+
input_img = gr.Image(label="Input Image", type="pil", elem_id="imgbox").style(width=600,height=600)
|
46 |
+
with gr.Column(scale=1):
|
47 |
+
image_out = gr.Image(value=None, label="Output Image", elem_id="imgbox").style(width=600,height=600)
|
48 |
+
gen_btn = gr.Button("Generate", variant="primary", elem_id="gen_button")
|
49 |
+
|
50 |
+
inputs=[input_img, prompt, guide, iguide, steps, seed]
|
51 |
+
gen_btn.click(fn=pix2pix, inputs=inputs, outputs=[image_out])
|
52 |
+
|
53 |
+
demo.launch()
|
patchedstabledifftoonnx_withou_modelort/quant.py
ADDED
File without changes
|
patchedstabledifftoonnx_withou_modelort/quantization.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"payload":{"allShortcutsEnabled":false,"fileTree":{"src/stable-diffusion-streamlit/pages/model":{"items":[{"name":"__init__.py","path":"src/stable-diffusion-streamlit/pages/model/__init__.py","contentType":"file"},{"name":"copy_pb.py","path":"src/stable-diffusion-streamlit/pages/model/copy_pb.py","contentType":"file"},{"name":"download_onnx.py","path":"src/stable-diffusion-streamlit/pages/model/download_onnx.py","contentType":"file"},{"name":"inference.py","path":"src/stable-diffusion-streamlit/pages/model/inference.py","contentType":"file"},{"name":"prepare.py","path":"src/stable-diffusion-streamlit/pages/model/prepare.py","contentType":"file"},{"name":"quantization.py","path":"src/stable-diffusion-streamlit/pages/model/quantization.py","contentType":"file"},{"name":"thread.py","path":"src/stable-diffusion-streamlit/pages/model/thread.py","contentType":"file"}],"totalCount":7},"src/stable-diffusion-streamlit/pages":{"items":[{"name":"model","path":"src/stable-diffusion-streamlit/pages/model","contentType":"directory"},{"name":"文字转图片.py","path":"src/stable-diffusion-streamlit/pages/文字转图片.py","contentType":"file"},{"name":"画廊.py","path":"src/stable-diffusion-streamlit/pages/画廊.py","contentType":"file"}],"totalCount":3},"src/stable-diffusion-streamlit":{"items":[{"name":"pages","path":"src/stable-diffusion-streamlit/pages","contentType":"directory"},{"name":"entrypoint.sh","path":"src/stable-diffusion-streamlit/entrypoint.sh","contentType":"file"},{"name":"requirements.txt","path":"src/stable-diffusion-streamlit/requirements.txt","contentType":"file"},{"name":"主页.py","path":"src/stable-diffusion-streamlit/主页.py","contentType":"file"}],"totalCount":4},"src":{"items":[{"name":"stable-diffusion-streamlit","path":"src/stable-diffusion-streamlit","contentType":"directory"}],"totalCount":1},"":{"items":[{"name":".github","path":".github","contentType":"directory"},{"name":"doc","path":"doc","contentType":"directory"},{"name":"docker","path":"docker","contentType":"directory"},{"name":"src","path":"src","contentType":"directory"},{"name":".dockerignore","path":".dockerignore","contentType":"file"},{"name":".gitignore","path":".gitignore","contentType":"file"},{"name":"LICENSE","path":"LICENSE","contentType":"file"},{"name":"README.md","path":"README.md","contentType":"file"},{"name":"README_CN.md","path":"README_CN.md","contentType":"file"}],"totalCount":9}},"fileTreeProcessingTime":17.999537999999998,"foldersToFetch":[],"reducedMotionEnabled":null,"repo":{"id":546836711,"defaultBranch":"main","name":"stable-diffusion-streamlit","ownerLogin":"LowinLi","currentUserCanPush":false,"isFork":false,"isEmpty":false,"createdAt":"2022-10-06T18:19:36.000Z","ownerAvatar":"https://avatars.githubusercontent.com/u/33021512?v=4","public":true,"private":false,"isOrgOwned":false},"refInfo":{"name":"main","listCacheKey":"v0:1665123374.24305","canEdit":false,"refType":"branch","currentOid":"f0f89f1ca432cfe89a80c774829893661aa1608f"},"path":"src/stable-diffusion-streamlit/pages/model/quantization.py","currentUser":null,"blob":{"rawLines":["import os","from onnxruntime.quantization import quantize_dynamic, QuantType","","","def quant():"," for root, dirs, filenames in os.walk(\"./onnx\"):"," if \"model.onnx\" in filenames:"," if \"weights.pb\" in filenames:"," external_data = True"," else:"," external_data = False"," quantize_dynamic("," model_input=os.path.join(root, \"model.onnx\"),"," model_output=os.path.join(root, \"model.onnx\"), # 量化后直接覆盖原onnx文件"," per_channel=True,"," reduce_range=True,"," weight_type=QuantType.QUInt8,"," optimize_model=True,"," use_external_data_format=external_data,"," )"," print(\"Quantized model saved at: \", os.path.join(root, \"model.onnx\"))"," if \"weights.pb\" in filenames:"," os.remove(os.path.join(root, \"weights.pb\"))"," print(\"Removed weights.pb\")","","","if __name__ == \"__main__\":"," quant()"],"stylingDirectives":[[{"start":0,"end":6,"cssClass":"pl-k"},{"start":7,"end":9,"cssClass":"pl-s1"}],[{"start":0,"end":4,"cssClass":"pl-k"},{"start":5,"end":16,"cssClass":"pl-s1"},{"start":17,"end":29,"cssClass":"pl-s1"},{"start":30,"end":36,"cssClass":"pl-k"},{"start":37,"end":53,"cssClass":"pl-s1"},{"start":55,"end":64,"cssClass":"pl-v"}],[],[],[{"start":0,"end":3,"cssClass":"pl-k"},{"start":4,"end":9,"cssClass":"pl-en"}],[{"start":4,"end":7,"cssClass":"pl-k"},{"start":8,"end":12,"cssClass":"pl-s1"},{"start":14,"end":18,"cssClass":"pl-s1"},{"start":20,"end":29,"cssClass":"pl-s1"},{"start":30,"end":32,"cssClass":"pl-c1"},{"start":33,"end":35,"cssClass":"pl-s1"},{"start":36,"end":40,"cssClass":"pl-en"},{"start":41,"end":49,"cssClass":"pl-s"}],[{"start":8,"end":10,"cssClass":"pl-k"},{"start":11,"end":23,"cssClass":"pl-s"},{"start":24,"end":26,"cssClass":"pl-c1"},{"start":27,"end":36,"cssClass":"pl-s1"}],[{"start":12,"end":14,"cssClass":"pl-k"},{"start":15,"end":27,"cssClass":"pl-s"},{"start":28,"end":30,"cssClass":"pl-c1"},{"start":31,"end":40,"cssClass":"pl-s1"}],[{"start":16,"end":29,"cssClass":"pl-s1"},{"start":30,"end":31,"cssClass":"pl-c1"},{"start":32,"end":36,"cssClass":"pl-c1"}],[{"start":12,"end":16,"cssClass":"pl-k"}],[{"start":16,"end":29,"cssClass":"pl-s1"},{"start":30,"end":31,"cssClass":"pl-c1"},{"start":32,"end":37,"cssClass":"pl-c1"}],[{"start":12,"end":28,"cssClass":"pl-en"}],[{"start":16,"end":27,"cssClass":"pl-s1"},{"start":27,"end":28,"cssClass":"pl-c1"},{"start":28,"end":30,"cssClass":"pl-s1"},{"start":31,"end":35,"cssClass":"pl-s1"},{"start":36,"end":40,"cssClass":"pl-en"},{"start":41,"end":45,"cssClass":"pl-s1"},{"start":47,"end":59,"cssClass":"pl-s"}],[{"start":16,"end":28,"cssClass":"pl-s1"},{"start":28,"end":29,"cssClass":"pl-c1"},{"start":29,"end":31,"cssClass":"pl-s1"},{"start":32,"end":36,"cssClass":"pl-s1"},{"start":37,"end":41,"cssClass":"pl-en"},{"start":42,"end":46,"cssClass":"pl-s1"},{"start":48,"end":60,"cssClass":"pl-s"},{"start":64,"end":80,"cssClass":"pl-c"}],[{"start":16,"end":27,"cssClass":"pl-s1"},{"start":27,"end":28,"cssClass":"pl-c1"},{"start":28,"end":32,"cssClass":"pl-c1"}],[{"start":16,"end":28,"cssClass":"pl-s1"},{"start":28,"end":29,"cssClass":"pl-c1"},{"start":29,"end":33,"cssClass":"pl-c1"}],[{"start":16,"end":27,"cssClass":"pl-s1"},{"start":27,"end":28,"cssClass":"pl-c1"},{"start":28,"end":37,"cssClass":"pl-v"},{"start":38,"end":44,"cssClass":"pl-v"}],[{"start":16,"end":30,"cssClass":"pl-s1"},{"start":30,"end":31,"cssClass":"pl-c1"},{"start":31,"end":35,"cssClass":"pl-c1"}],[{"start":16,"end":40,"cssClass":"pl-s1"},{"start":40,"end":41,"cssClass":"pl-c1"},{"start":41,"end":54,"cssClass":"pl-s1"}],[],[{"start":12,"end":17,"cssClass":"pl-en"},{"start":18,"end":46,"cssClass":"pl-s"},{"start":48,"end":50,"cssClass":"pl-s1"},{"start":51,"end":55,"cssClass":"pl-s1"},{"start":56,"end":60,"cssClass":"pl-en"},{"start":61,"end":65,"cssClass":"pl-s1"},{"start":67,"end":79,"cssClass":"pl-s"}],[{"start":12,"end":14,"cssClass":"pl-k"},{"start":15,"end":27,"cssClass":"pl-s"},{"start":28,"end":30,"cssClass":"pl-c1"},{"start":31,"end":40,"cssClass":"pl-s1"}],[{"start":16,"end":18,"cssClass":"pl-s1"},{"start":19,"end":25,"cssClass":"pl-en"},{"start":26,"end":28,"cssClass":"pl-s1"},{"start":29,"end":33,"cssClass":"pl-s1"},{"start":34,"end":38,"cssClass":"pl-en"},{"start":39,"end":43,"cssClass":"pl-s1"},{"start":45,"end":57,"cssClass":"pl-s"}],[{"start":16,"end":21,"cssClass":"pl-en"},{"start":22,"end":42,"cssClass":"pl-s"}],[],[],[{"start":0,"end":2,"cssClass":"pl-k"},{"start":3,"end":11,"cssClass":"pl-s1"},{"start":12,"end":14,"cssClass":"pl-c1"},{"start":15,"end":25,"cssClass":"pl-s"}],[{"start":4,"end":9,"cssClass":"pl-en"}]],"csv":null,"csvError":null,"dependabotInfo":{"showConfigurationBanner":false,"configFilePath":null,"networkDependabotPath":"/LowinLi/stable-diffusion-streamlit/network/updates","dismissConfigurationNoticePath":"/settings/dismiss-notice/dependabot_configuration_notice","configurationNoticeDismissed":null,"repoAlertsPath":"/LowinLi/stable-diffusion-streamlit/security/dependabot","repoSecurityAndAnalysisPath":"/LowinLi/stable-diffusion-streamlit/settings/security_analysis","repoOwnerIsOrg":false,"currentUserCanAdminRepo":false},"displayName":"quantization.py","displayUrl":"https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/src/stable-diffusion-streamlit/pages/model/quantization.py?raw=true","headerInfo":{"blobSize":"999 Bytes","deleteInfo":{"deletePath":null,"deleteTooltip":"You must be signed in to make or propose changes"},"editInfo":{"editTooltip":"You must be signed in to make or propose changes"},"ghDesktopPath":"https://desktop.github.com","gitLfsPath":null,"onBranch":true,"shortPath":"76a75f9","siteNavLoginPath":"/login?return_to=https%3A%2F%2Fgithub.com%2FLowinLi%2Fstable-diffusion-streamlit%2Fblob%2Fmain%2Fsrc%2Fstable-diffusion-streamlit%2Fpages%2Fmodel%2Fquantization.py","isCSV":false,"isRichtext":false,"toc":null,"lineInfo":{"truncatedLoc":"28","truncatedSloc":"24"},"mode":"file"},"image":false,"isCodeownersFile":null,"isValidLegacyIssueTemplate":false,"issueTemplateHelpUrl":"https://docs.github.com/articles/about-issue-and-pull-request-templates","issueTemplate":null,"discussionTemplate":null,"language":"Python","large":false,"loggedIn":false,"newDiscussionPath":"/LowinLi/stable-diffusion-streamlit/discussions/new","newIssuePath":"/LowinLi/stable-diffusion-streamlit/issues/new","planSupportInfo":{"repoIsFork":null,"repoOwnedByCurrentUser":null,"requestFullPath":"/LowinLi/stable-diffusion-streamlit/blob/main/src/stable-diffusion-streamlit/pages/model/quantization.py","showFreeOrgGatedFeatureMessage":null,"showPlanSupportBanner":null,"upgradeDataAttributes":null,"upgradePath":null},"publishBannersInfo":{"dismissActionNoticePath":"/settings/dismiss-notice/publish_action_from_dockerfile","dismissStackNoticePath":"/settings/dismiss-notice/publish_stack_from_file","releasePath":"/LowinLi/stable-diffusion-streamlit/releases/new?marketplace=true","showPublishActionBanner":false,"showPublishStackBanner":false},"renderImageOrRaw":false,"richText":null,"renderedFileInfo":null,"tabSize":8,"topBannersInfo":{"overridingGlobalFundingFile":false,"globalPreferredFundingPath":null,"repoOwner":"LowinLi","repoName":"stable-diffusion-streamlit","showInvalidCitationWarning":false,"citationHelpUrl":"https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-on-github/about-citation-files","showDependabotConfigurationBanner":false,"actionsOnboardingTip":null},"truncated":false,"viewable":true,"workflowRedirectUrl":null,"symbols":{"timedOut":false,"notAnalyzed":false,"symbols":[{"name":"quant","kind":"function","identStart":81,"identEnd":86,"extentStart":77,"extentEnd":957,"fullyQualifiedName":"quant","identUtf16":{"start":{"lineNumber":4,"utf16Col":4},"end":{"lineNumber":4,"utf16Col":9}},"extentUtf16":{"start":{"lineNumber":4,"utf16Col":0},"end":{"lineNumber":23,"utf16Col":43}}}]}},"copilotUserAccess":null,"csrf_tokens":{"/LowinLi/stable-diffusion-streamlit/branches":{"post":"eJjsNRVp8sZQ7zWnchUTmZXYgQPIgC-7asdU5zc71FiIpXRFsTu3r8XNV1yExX9Q4A-dFz6Hl7iOi0tGdOxL8A"}}},"title":"stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/quantization.py at main · LowinLi/stable-diffusion-streamlit","locale":"en"}
|
patchedstabledifftoonnx_withou_modelort/requirements.txt
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
protobuf < 4.0
|
2 |
+
numpy
|
3 |
+
transformers
|
4 |
+
diffusers
|
5 |
+
ftfy
|
6 |
+
spacy
|
7 |
+
scipy
|
8 |
+
safetensors
|
9 |
+
gradio
|
10 |
+
omegaconf
|
11 |
+
onnx
|
12 |
+
onnxconverter-common
|
13 |
+
onnxruntime-directml
|
14 |
+
opencv-python
|
patchedstabledifftoonnx_withou_modelort/run-batch.md
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Running Stable Diffusion ONNX DirectML batches
|
2 |
+
|
3 |
+
Ever feel like it's a struggle to compare schedulers, guidance scale ... while using a UI?
|
4 |
+
Not really interested in coding in Python to resolve it?
|
5 |
+
|
6 |
+
Hopefully run-batch.py will make your life a bit easier.
|
7 |
+
|
8 |
+
## Set up
|
9 |
+
Drop run-batch.py where you've installed OnnxDiffusersUI (it'll use the same lwp_pipe.py).
|
10 |
+
|
11 |
+
As parameter run-batch.py accepts 1 or more paths where it will then check for the existence of settings.json.
|
12 |
+
It'll read settings.json, create a batch of images and save them in the directory it just got the settings from.
|
13 |
+
|
14 |
+
In settings.json you can define the following things:
|
15 |
+
- The model, set with the key 'model'. It will look for a directory with that name in the model subdirectory (just like OnnxDiffusersUI).
|
16 |
+
- The scheduler, set with the key 'scheduler'. You can also set a list of schedulers to iterate over with the key 'schedulerlist'.
|
17 |
+
It currently accepts following values: ddim, deis, dpms_ms, dpms_ss, euler_anc, euler, heun, kdpm2, lms, pndm,unipc.
|
18 |
+
If the value is not recognised, it'll switch to pndm. Not all schedulers have been extensively tested and may behave unexpectendly.
|
19 |
+
- Guidance scale, set with the key 'scale'. You can also set a list of guidance scales to iterate over with the key 'scalelist'
|
20 |
+
- Iteration steps, set with the key 'steps'. You can also set a list of steps to iterate over with the key 'stepslist'
|
21 |
+
- Width and height, with the keys 'width' and 'height'. You can also set a list of resolutions to iterate over with the key 'reslist' (e.g. 'reslist': ["512x512","512x768"])
|
22 |
+
- The seed, set with the key 'seed'. If you want to iterate over seeds you can define the end with the key 'seedend'.
|
23 |
+
Alternatively, you can provide a list of seeds using the key 'seedlist'.
|
24 |
+
- The task to perform, set with the key 'task', default is 'txt2img'. Only txt2img has been tested enough, but it also supports img2img and controlnet (more on that below).
|
25 |
+
- The prompt, set with the key 'prompt'. If you want to iterate over prompts, you can define them with the key 'promptlist'.
|
26 |
+
- A negative prompt, set with the key 'negative_prompt'. Note that the same negative prompt will apply to all prompts you provided.
|
27 |
+
- How to parse the prompt, set with the key 'textenc'. Supports 2 values, 'standard' and 'lwp'. Use 'lwp' when you want to use weights and long prompts.
|
28 |
+
|
29 |
+
If you are doing img2img or controlnet there's more options:
|
30 |
+
- Strength, set with the key 'strength'. Expected to be between 0 to 1. You can iterate over a list by setting 'strengthlist'.
|
31 |
+
|
32 |
+
For img2img or controlnet the directory will also need to contain an image file called input.png. For img2img this acts as source image, for controlnet it is the input for the Controlnet.
|
33 |
+
|
34 |
+
## Example
|
35 |
+
|
36 |
+
Compare the results for a prompt with deis and euler at 20, 30 and 40 steps. Using SD 2.1.
|
37 |
+
|
38 |
+
```
|
39 |
+
{
|
40 |
+
"model": "sd2_1-fp16",
|
41 |
+
"seed": 0,
|
42 |
+
"seedend": 10,
|
43 |
+
"stepslist": [20,30,40],
|
44 |
+
"scale": 8.5,
|
45 |
+
"schedulerlist": ["deis","euler"],
|
46 |
+
"prompt": "(photo portrait) of a ((beautiful)) (woman) wearing (summer dress) in a park, eyes, detailed, high resolution, prime lens",
|
47 |
+
"negative_prompt": "bad quality, low resolution",
|
48 |
+
"textenc": "lwp"
|
49 |
+
}
|
50 |
+
```
|
patchedstabledifftoonnx_withou_modelort/run-batch.py
ADDED
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2022 Dirk Moerenhout. All rights reserved.
|
2 |
+
#
|
3 |
+
# This program is free software: you can redistribute it and/or modify it under the terms
|
4 |
+
# of the GNU General Public License as published by the Free Software Foundation,
|
5 |
+
# either version 3 of the License, or (at your option) any later version.
|
6 |
+
#
|
7 |
+
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
|
8 |
+
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
9 |
+
# See the GNU General Public License for more details.
|
10 |
+
#
|
11 |
+
# You should have received a copy of the GNU General Public License along with this program. If not,
|
12 |
+
# see <https://www.gnu.org/licenses/>.
|
13 |
+
|
14 |
+
# We need sys for argv
|
15 |
+
import sys
|
16 |
+
# We need os.path for isdir, isfile
|
17 |
+
import os.path
|
18 |
+
# Our settings are in json format
|
19 |
+
import json
|
20 |
+
# To be safe we force gc to lower RAM pressure
|
21 |
+
import gc
|
22 |
+
# We want to replace the text encoder in the pipeline
|
23 |
+
import functools
|
24 |
+
# We want to parse arguments
|
25 |
+
import argparse
|
26 |
+
# Numpy is used to provide a random generator
|
27 |
+
import numpy
|
28 |
+
# We need to load images for img2img
|
29 |
+
# We want to save data to PNG
|
30 |
+
from PIL import Image, PngImagePlugin
|
31 |
+
|
32 |
+
# The pipelines
|
33 |
+
from diffusers import OnnxStableDiffusionPipeline, OnnxStableDiffusionImg2ImgPipeline
|
34 |
+
from pipeline_onnx_stable_diffusion_controlnet import OnnxStableDiffusionControlNetPipeline
|
35 |
+
# Model needed to load Text Encoder on CPU
|
36 |
+
from diffusers import OnnxRuntimeModel
|
37 |
+
# The schedulers
|
38 |
+
from diffusers import (
|
39 |
+
DDIMScheduler,
|
40 |
+
DEISMultistepScheduler,
|
41 |
+
DPMSolverMultistepScheduler,
|
42 |
+
DPMSolverSinglestepScheduler,
|
43 |
+
EulerAncestralDiscreteScheduler,
|
44 |
+
EulerDiscreteScheduler,
|
45 |
+
HeunDiscreteScheduler,
|
46 |
+
KDPM2DiscreteScheduler,
|
47 |
+
LMSDiscreteScheduler,
|
48 |
+
PNDMScheduler,
|
49 |
+
UniPCMultistepScheduler
|
50 |
+
)
|
51 |
+
|
52 |
+
# Support special text encoders
|
53 |
+
import OnnxDiffusersUI.lpw_pipe
|
54 |
+
|
55 |
+
# Default settings
|
56 |
+
defSettings = {
|
57 |
+
"width": 512,
|
58 |
+
"height": 512,
|
59 |
+
"reslist": [],
|
60 |
+
"steps": 30,
|
61 |
+
"stepslist": [],
|
62 |
+
"scale": 7.5,
|
63 |
+
"scalelist":[],
|
64 |
+
"seed":0,
|
65 |
+
"seedend":0,
|
66 |
+
"seedlist":[],
|
67 |
+
"task": "txt2img",
|
68 |
+
"model":"sd2_1-fp16",
|
69 |
+
"prompt": "",
|
70 |
+
"promptlist":[],
|
71 |
+
"negative_prompt": "",
|
72 |
+
"textenc": "standard",
|
73 |
+
"scheduler": "pndm",
|
74 |
+
"schedulerlist": [],
|
75 |
+
"strength": 0.9,
|
76 |
+
"strengthlist": []
|
77 |
+
}
|
78 |
+
|
79 |
+
parser = argparse.ArgumentParser()
|
80 |
+
|
81 |
+
parser.add_argument(
|
82 |
+
"--cpu-textenc",
|
83 |
+
action="store_true",
|
84 |
+
help="Load Text Encoder on CPU to save VRAM"
|
85 |
+
)
|
86 |
+
|
87 |
+
parser.add_argument(
|
88 |
+
"--subdirs",
|
89 |
+
action="store_true",
|
90 |
+
help="Add subdirs with settings.json to projects to run"
|
91 |
+
)
|
92 |
+
|
93 |
+
parser.add_argument(
|
94 |
+
'project',
|
95 |
+
nargs='+',
|
96 |
+
type=str,
|
97 |
+
help="Provide projects as directories that contain settings.json"
|
98 |
+
)
|
99 |
+
|
100 |
+
args = parser.parse_args()
|
101 |
+
|
102 |
+
projects=args.project
|
103 |
+
if args.subdirs:
|
104 |
+
for proj in args.project:
|
105 |
+
obj = os.scandir(proj)
|
106 |
+
for entry in obj:
|
107 |
+
if entry.is_dir():
|
108 |
+
if os.path.isfile(f"{proj}/{entry.name}/settings.json"):
|
109 |
+
projects.append(f"{proj}/{entry.name}")
|
110 |
+
|
111 |
+
for proj in projects:
|
112 |
+
print("Running project "+proj)
|
113 |
+
# Check for directory
|
114 |
+
if os.path.isdir(proj):
|
115 |
+
if os.path.isfile(proj+"/settings.json"):
|
116 |
+
with open(proj+"/settings.json", encoding="utf-8") as confFile:
|
117 |
+
projSettings=json.load(confFile)
|
118 |
+
# Merge dictionaries with project settings taking precedence
|
119 |
+
runSettings = defSettings | projSettings
|
120 |
+
# We need prompts
|
121 |
+
prereqmet=len(runSettings['prompt'])>0 or len(runSettings['promptlist'])>0
|
122 |
+
# We need a model
|
123 |
+
model="model/"+runSettings['model']
|
124 |
+
prereqmet=prereqmet and os.path.isfile(model+"/unet/model.onnx")
|
125 |
+
# We need a start image to do img2img or controlnet
|
126 |
+
if runSettings['task']=="img2img" or runSettings['task']=="controlnet":
|
127 |
+
infile=proj+"/input.png"
|
128 |
+
prereqmet = prereqmet and os.path.isfile(infile)
|
129 |
+
if prereqmet:
|
130 |
+
sched = {
|
131 |
+
"ddim": DDIMScheduler.from_pretrained(model, subfolder="scheduler"),
|
132 |
+
"deis": DEISMultistepScheduler.from_pretrained(model, subfolder="scheduler"),
|
133 |
+
"dpms_ms": DPMSolverMultistepScheduler.from_pretrained(model, subfolder="scheduler"),
|
134 |
+
"dpms_ss": DPMSolverSinglestepScheduler.from_pretrained(model, subfolder="scheduler"),
|
135 |
+
"euler_anc": EulerAncestralDiscreteScheduler.from_pretrained(model, subfolder="scheduler"),
|
136 |
+
"euler": EulerDiscreteScheduler.from_pretrained(model, subfolder="scheduler"),
|
137 |
+
"heun": HeunDiscreteScheduler.from_pretrained(model, subfolder="scheduler"),
|
138 |
+
"kdpm2": KDPM2DiscreteScheduler.from_pretrained(model, subfolder="scheduler"),
|
139 |
+
"lms": LMSDiscreteScheduler.from_pretrained(model, subfolder="scheduler"),
|
140 |
+
"pndm": PNDMScheduler.from_pretrained(model, subfolder="scheduler"),
|
141 |
+
"unipc": UniPCMultistepScheduler.from_pretrained(model, subfolder="scheduler")
|
142 |
+
}
|
143 |
+
if runSettings['task']=="img2img":
|
144 |
+
init_image = Image.open(infile).convert("RGB")
|
145 |
+
if args.cpu_textenc:
|
146 |
+
cputextenc=OnnxRuntimeModel.from_pretrained(model+"/text_encoder")
|
147 |
+
pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(
|
148 |
+
model,
|
149 |
+
provider="DmlExecutionProvider",
|
150 |
+
revision="onnx",
|
151 |
+
scheduler=sched['pndm'],
|
152 |
+
text_encoder=cputextenc,
|
153 |
+
safety_checker=None,
|
154 |
+
feature_extractor=None
|
155 |
+
)
|
156 |
+
else:
|
157 |
+
pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained(
|
158 |
+
model,
|
159 |
+
provider="DmlExecutionProvider",
|
160 |
+
revision="onnx",
|
161 |
+
scheduler=sched['pndm'],
|
162 |
+
safety_checker=None,
|
163 |
+
feature_extractor=None
|
164 |
+
)
|
165 |
+
elif runSettings['task']=="controlnet":
|
166 |
+
init_image = Image.open(infile).convert("RGB")
|
167 |
+
if args.cpu_textenc:
|
168 |
+
cputextenc=OnnxRuntimeModel.from_pretrained(model+"/text_encoder")
|
169 |
+
pipe = OnnxStableDiffusionControlNetPipeline.from_pretrained(
|
170 |
+
model,
|
171 |
+
provider="DmlExecutionProvider",
|
172 |
+
revision="onnx",
|
173 |
+
scheduler=sched['pndm'],
|
174 |
+
text_encoder=cputextenc,
|
175 |
+
safety_checker=None,
|
176 |
+
feature_extractor=None
|
177 |
+
)
|
178 |
+
else:
|
179 |
+
pipe = OnnxStableDiffusionControlNetPipeline.from_pretrained(
|
180 |
+
model,
|
181 |
+
provider="DmlExecutionProvider",
|
182 |
+
revision="onnx",
|
183 |
+
scheduler=sched['pndm'],
|
184 |
+
safety_checker=None,
|
185 |
+
feature_extractor=None
|
186 |
+
)
|
187 |
+
else:
|
188 |
+
if args.cpu_textenc:
|
189 |
+
cputextenc=OnnxRuntimeModel.from_pretrained(model+"/text_encoder")
|
190 |
+
pipe = OnnxStableDiffusionPipeline.from_pretrained(
|
191 |
+
model,
|
192 |
+
provider="DmlExecutionProvider",
|
193 |
+
revision="onnx",
|
194 |
+
scheduler=sched['pndm'],
|
195 |
+
text_encoder=cputextenc,
|
196 |
+
safety_checker=None,
|
197 |
+
feature_extractor=None
|
198 |
+
)
|
199 |
+
else:
|
200 |
+
pipe = OnnxStableDiffusionPipeline.from_pretrained(
|
201 |
+
model,
|
202 |
+
provider="DmlExecutionProvider",
|
203 |
+
revision="onnx",
|
204 |
+
scheduler=sched['pndm'],
|
205 |
+
safety_checker=None,
|
206 |
+
feature_extractor=None
|
207 |
+
)
|
208 |
+
if runSettings['textenc'] == "lpw":
|
209 |
+
pipe._encode_prompt = functools.partial(lpw_pipe._encode_prompt, pipe)
|
210 |
+
generator = numpy.random
|
211 |
+
# Set schedulers for projects
|
212 |
+
if len(runSettings['schedulerlist'])==0:
|
213 |
+
schedulerlist=[runSettings['scheduler']]
|
214 |
+
else:
|
215 |
+
schedulerlist=runSettings['schedulerlist']
|
216 |
+
# Set seeds for project
|
217 |
+
if len(runSettings['seedlist'])==0:
|
218 |
+
if runSettings['seed']>runSettings['seedend']:
|
219 |
+
runSettings['seedend']=runSettings['seed']
|
220 |
+
seedlist=range(runSettings['seed'],runSettings['seedend']+1)
|
221 |
+
else:
|
222 |
+
seedlist=runSettings['seedlist']
|
223 |
+
# Set resolustions for project
|
224 |
+
if len(runSettings['reslist'])==0:
|
225 |
+
restuples=[(runSettings['width'],runSettings['height'])]
|
226 |
+
else:
|
227 |
+
restuples=[]
|
228 |
+
for resstr in runSettings['reslist']:
|
229 |
+
restuples.append(tuple(map(int, resstr.split("x"))))
|
230 |
+
# Set steps for project
|
231 |
+
if len(runSettings['stepslist'])==0:
|
232 |
+
stepslist=[runSettings['steps']]
|
233 |
+
else:
|
234 |
+
stepslist=runSettings['stepslist']
|
235 |
+
# Set guidance scales for project
|
236 |
+
if len(runSettings['scalelist'])==0:
|
237 |
+
scalelist=[runSettings['scale']]
|
238 |
+
else:
|
239 |
+
scalelist=runSettings['scalelist']
|
240 |
+
# Set prompts for project
|
241 |
+
if len(runSettings['promptlist'])==0:
|
242 |
+
promptlist=[runSettings['prompt']]
|
243 |
+
else:
|
244 |
+
promptlist=runSettings['promptlist']
|
245 |
+
# Set strengths for project
|
246 |
+
if len(runSettings['strengthlist'])==0:
|
247 |
+
strengthlist=[runSettings['strength']]
|
248 |
+
else:
|
249 |
+
strengthlist=runSettings['strengthlist']
|
250 |
+
imgnr=len(schedulerlist)*len(promptlist)*len(seedlist)*len(restuples)*len(stepslist)*len(scalelist)*len(strengthlist)
|
251 |
+
imgdone=0
|
252 |
+
for scheduler in schedulerlist:
|
253 |
+
if not sched[scheduler]:
|
254 |
+
scheduler="pndm"
|
255 |
+
pipe.scheduler=sched[scheduler]
|
256 |
+
promptnum=0
|
257 |
+
for prompt in promptlist:
|
258 |
+
for seed in seedlist:
|
259 |
+
for res in restuples:
|
260 |
+
for steps in stepslist:
|
261 |
+
for scale in scalelist:
|
262 |
+
for strength in strengthlist:
|
263 |
+
if runSettings['task']=="img2img":
|
264 |
+
filename=(
|
265 |
+
f"{proj}/result-p{promptnum}-seed{seed}-{res[0]}x{res[1]}-"+
|
266 |
+
f"-steps-{steps}-{scheduler}-scale-"+str(scale).replace(".","_")+
|
267 |
+
"-strength-"+str(strength).replace(".","_")+".png"
|
268 |
+
)
|
269 |
+
elif runSettings['task']=="controlnet":
|
270 |
+
filename=(
|
271 |
+
f"{proj}/result-p{promptnum}-seed{seed}-{res[0]}x{res[1]}-"+
|
272 |
+
f"-steps-{steps}-{scheduler}-scale-"+str(scale).replace(".","_")+
|
273 |
+
"-strength-"+str(strength).replace(".","_")+".png"
|
274 |
+
)
|
275 |
+
else:
|
276 |
+
filename=(
|
277 |
+
f"{proj}/result-p{promptnum}-seed{seed}-{res[0]}x{res[1]}-"+
|
278 |
+
f"-steps-{steps}-{scheduler}-scale-"+str(scale).replace(".","_")+".png"
|
279 |
+
)
|
280 |
+
if not os.path.isfile(filename):
|
281 |
+
generator.seed(seed)
|
282 |
+
if runSettings['task']=="img2img":
|
283 |
+
image = pipe(
|
284 |
+
image=init_image,
|
285 |
+
strength=strength,
|
286 |
+
prompt=prompt,
|
287 |
+
negative_prompt=runSettings['negative_prompt'],
|
288 |
+
num_inference_steps=steps,
|
289 |
+
guidance_scale=scale,
|
290 |
+
generator=generator).images[0]
|
291 |
+
elif runSettings['task']=="controlnet":
|
292 |
+
image = pipe(
|
293 |
+
image=init_image,
|
294 |
+
controlnet_conditioning_scale=strength,
|
295 |
+
prompt=prompt,
|
296 |
+
negative_prompt=runSettings['negative_prompt'],
|
297 |
+
num_inference_steps=steps,
|
298 |
+
guidance_scale=scale,
|
299 |
+
generator=generator).images[0]
|
300 |
+
else:
|
301 |
+
image = pipe(
|
302 |
+
prompt=prompt,
|
303 |
+
negative_prompt=runSettings['negative_prompt'],
|
304 |
+
width=res[0],
|
305 |
+
height=res[1],
|
306 |
+
num_inference_steps=steps,
|
307 |
+
guidance_scale=scale,
|
308 |
+
generator = generator).images[0]
|
309 |
+
metadata = PngImagePlugin.PngInfo()
|
310 |
+
metadata.add_text("Generator","Stable Diffusion ONNX https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16")
|
311 |
+
metadata.add_text("SD Model (local name)",model)
|
312 |
+
metadata.add_text("SD Prompt",prompt)
|
313 |
+
metadata.add_text("SD Negative Prompt",runSettings['negative_prompt'])
|
314 |
+
metadata.add_text("SD Scheduler",scheduler)
|
315 |
+
metadata.add_text("SD Steps",str(steps))
|
316 |
+
metadata.add_text("SD Guidance Scale",str(scale))
|
317 |
+
image.save(filename, pnginfo = metadata)
|
318 |
+
else:
|
319 |
+
print("Skipping existing image!")
|
320 |
+
imgdone+=1
|
321 |
+
print(f"Finished {imgdone}/{imgnr}")
|
322 |
+
promptnum+=1
|
323 |
+
del pipe
|
324 |
+
gc.collect()
|
325 |
+
else:
|
326 |
+
print("Minimum requirements not met! Skipping")
|
327 |
+
else:
|
328 |
+
print("Settings not found! Skipping")
|
329 |
+
else:
|
330 |
+
print("Path not found! Skipping")
|
patchedstabledifftoonnx_withou_modelort/sd_env/bin/python
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:682d5b916b076ae9e1f1399b89e7f4b521599cf04f669cbd65af0a317bc6033e
|
3 |
+
size 5912968
|
patchedstabledifftoonnx_withou_modelort/sd_env/bin/python3
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:682d5b916b076ae9e1f1399b89e7f4b521599cf04f669cbd65af0a317bc6033e
|
3 |
+
size 5912968
|
patchedstabledifftoonnx_withou_modelort/sd_env/bin/python3.10
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:682d5b916b076ae9e1f1399b89e7f4b521599cf04f669cbd65af0a317bc6033e
|
3 |
+
size 5912968
|
patchedstabledifftoonnx_withou_modelort/sd_env/pyvenv.cfg
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
home = /usr/bin
|
2 |
+
include-system-site-packages = false
|
3 |
+
version = 3.10.6
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/.dockerignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
src/stable-diffusion-streamlit/pages/model/result
|
2 |
+
src/stable-diffusion-streamlit/pages/model/onnx
|
3 |
+
__pycache__
|
4 |
+
docker/.env
|
5 |
+
tag.sh
|
6 |
+
docker/volume
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/.github/workflows/build-image.yml
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Build Image
|
2 |
+
|
3 |
+
on: push
|
4 |
+
|
5 |
+
jobs:
|
6 |
+
build:
|
7 |
+
runs-on: ubuntu-20.04
|
8 |
+
steps:
|
9 |
+
- uses: actions/checkout@v2
|
10 |
+
- name: Login to Registry
|
11 |
+
if: startsWith(github.ref, 'refs/tags')
|
12 |
+
run: docker login --username=${{ secrets.DOCKER_USERNAME }} --password ${{ secrets.DOCKER_PASSWORD }}
|
13 |
+
- name: Push Image
|
14 |
+
if: startsWith(github.ref, 'refs/tags')
|
15 |
+
run: |
|
16 |
+
cd docker && bash build.sh ${{ secrets.HUGGINGFACE_TOKEN }}
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/.gitignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
result
|
2 |
+
onnx
|
3 |
+
__pycache__
|
4 |
+
docker/.env
|
5 |
+
tag.sh
|
6 |
+
docker/volume
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/LICENSE
ADDED
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
9 |
+
the potential to transform the way artists, among other individuals,
|
10 |
+
conceive and benefit from AI or ML technologies as a tool for content
|
11 |
+
creation.
|
12 |
+
|
13 |
+
Notwithstanding the current and potential benefits that these artifacts
|
14 |
+
can bring to society at large, there are also concerns about potential
|
15 |
+
misuses of them, either due to their technical limitations or ethical
|
16 |
+
considerations.
|
17 |
+
|
18 |
+
In short, this license strives for both the open and responsible
|
19 |
+
downstream use of the accompanying model. When it comes to the open
|
20 |
+
character, we took inspiration from open source permissive licenses
|
21 |
+
regarding the grant of IP rights. Referring to the downstream responsible
|
22 |
+
use, we added use-based restrictions not permitting the use of the Model
|
23 |
+
in very specific scenarios, in order for the licensor to be able to
|
24 |
+
enforce the license in case potential misuses of the Model may occur. At
|
25 |
+
the same time, we strive to promote open and responsible research on
|
26 |
+
generative models for art and content generation.
|
27 |
+
|
28 |
+
Even though downstream derivative versions of the model could be released
|
29 |
+
under different licensing terms, the latter will always have to include -
|
30 |
+
at minimum - the same use-based restrictions as the ones in the original
|
31 |
+
license (this license). We believe in the intersection between open and
|
32 |
+
responsible AI development; thus, this License aims to strike a balance
|
33 |
+
between both in order to enable responsible open-science in the field of
|
34 |
+
AI.
|
35 |
+
|
36 |
+
This License governs the use of the model (and its derivatives) and is
|
37 |
+
informed by the model card associated with the model.
|
38 |
+
|
39 |
+
NOW THEREFORE, You and Licensor agree as follows:
|
40 |
+
|
41 |
+
1. Definitions
|
42 |
+
|
43 |
+
- "License" means the terms and conditions for use, reproduction, and
|
44 |
+
Distribution as defined in this document.
|
45 |
+
- "Data" means a collection of information and/or content extracted from
|
46 |
+
the dataset used with the Model, including to train, pretrain, or
|
47 |
+
otherwise evaluate the Model. The Data is not licensed under this
|
48 |
+
License.
|
49 |
+
- "Output" means the results of operating a Model as embodied in
|
50 |
+
informational content resulting therefrom.
|
51 |
+
- "Model" means any accompanying machine-learning based assemblies
|
52 |
+
(including checkpoints), consisting of learnt weights, parameters
|
53 |
+
(including optimizer states), corresponding to the model architecture as
|
54 |
+
embodied in the Complementary Material, that have been trained or tuned,
|
55 |
+
in whole or in part on the Data, using the Complementary Material.
|
56 |
+
- "Derivatives of the Model" means all modifications to the Model, works
|
57 |
+
based on the Model, or any other model which is created or initialized by
|
58 |
+
transfer of patterns of the weights, parameters, activations or output of
|
59 |
+
the Model, to the other model, in order to cause the other model to
|
60 |
+
perform similarly to the Model, including - but not limited to -
|
61 |
+
distillation methods entailing the use of intermediate data
|
62 |
+
representations or methods based on the generation of synthetic data by
|
63 |
+
the Model for training the other model.
|
64 |
+
- "Complementary Material" means the accompanying source code and scripts
|
65 |
+
used to define, run, load, benchmark or evaluate the Model, and used to
|
66 |
+
prepare data for training or evaluation, if any. This includes any
|
67 |
+
accompanying documentation, tutorials, examples, etc, if any.
|
68 |
+
- "Distribution" means any transmission, reproduction, publication or
|
69 |
+
other sharing of the Model or Derivatives of the Model to a third party,
|
70 |
+
including providing the Model as a hosted service made available by
|
71 |
+
electronic or other remote means - e.g. API-based or web access.
|
72 |
+
- "Licensor" means the copyright owner or entity authorized by the
|
73 |
+
copyright owner that is granting the License, including the persons or
|
74 |
+
entities that may have rights in the Model and/or distributing the Model.
|
75 |
+
- "You" (or "Your") means an individual or Legal Entity exercising
|
76 |
+
permissions granted by this License and/or making use of the Model for
|
77 |
+
whichever purpose and in any field of use, including usage of the Model
|
78 |
+
in an end-use application - e.g. chatbot, translator, image generator.
|
79 |
+
- "Third Parties" means individuals or legal entities that are not under
|
80 |
+
common control with Licensor or You.
|
81 |
+
- "Contribution" means any work of authorship, including the original
|
82 |
+
version of the Model and any modifications or additions to that Model or
|
83 |
+
Derivatives of the Model thereof, that is intentionally submitted to
|
84 |
+
Licensor for inclusion in the Model by the copyright owner or by an
|
85 |
+
individual or Legal Entity authorized to submit on behalf of the
|
86 |
+
copyright owner. For the purposes of this definition, "submitted" means
|
87 |
+
any form of electronic, verbal, or written communication sent to the
|
88 |
+
Licensor or its representatives, including but not limited to
|
89 |
+
communication on electronic mailing lists, source code control systems,
|
90 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
91 |
+
Licensor for the purpose of discussing and improving the Model, but
|
92 |
+
excluding communication that is conspicuously marked or otherwise
|
93 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
94 |
+
- "Contributor" means Licensor and any individual or Legal Entity on
|
95 |
+
behalf of whom a Contribution has been received by Licensor and
|
96 |
+
subsequently incorporated within the Model.
|
97 |
+
|
98 |
+
Section II: INTELLECTUAL PROPERTY RIGHTS
|
99 |
+
|
100 |
+
Both copyright and patent grants apply to the Model, Derivatives of the
|
101 |
+
Model and Complementary Material. The Model and Derivatives of the Model
|
102 |
+
are subject to additional terms as described in Section III.
|
103 |
+
|
104 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
105 |
+
this License, each Contributor hereby grants to You a perpetual,
|
106 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright
|
107 |
+
license to reproduce, prepare, publicly display, publicly perform,
|
108 |
+
sublicense, and distribute the Complementary Material, the Model, and
|
109 |
+
Derivatives of the Model.
|
110 |
+
3. Grant of Patent License. Subject to the terms and conditions of this
|
111 |
+
License and where and as applicable, each Contributor hereby grants to
|
112 |
+
You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
113 |
+
irrevocable (except as stated in this paragraph) patent license to make,
|
114 |
+
have made, use, offer to sell, sell, import, and otherwise transfer the
|
115 |
+
Model and the Complementary Material, where such license applies only to
|
116 |
+
those patent claims licensable by such Contributor that are necessarily
|
117 |
+
infringed by their Contribution(s) alone or by combination of their
|
118 |
+
Contribution(s) with the Model to which such Contribution(s) was
|
119 |
+
submitted. If You institute patent litigation against any entity
|
120 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that the
|
121 |
+
Model and/or Complementary Material or a Contribution incorporated within
|
122 |
+
the Model and/or Complementary Material constitutes direct or
|
123 |
+
contributory patent infringement, then any patent licenses granted to You
|
124 |
+
under this License for the Model and/or Work shall terminate as of the
|
125 |
+
date such litigation is asserted or filed.
|
126 |
+
|
127 |
+
Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
|
128 |
+
|
129 |
+
4. Distribution and Redistribution. You may host for Third Party remote
|
130 |
+
access purposes (e.g. software-as-a-service), reproduce and distribute
|
131 |
+
copies of the Model or Derivatives of the Model thereof in any medium,
|
132 |
+
with or without modifications, provided that You meet the following
|
133 |
+
conditions:
|
134 |
+
Use-based restrictions as referenced in paragraph 5 MUST be included as
|
135 |
+
an enforceable provision by You in any type of legal agreement (e.g. a
|
136 |
+
license) governing the use and/or distribution of the Model or
|
137 |
+
Derivatives of the Model, and You shall give notice to subsequent users
|
138 |
+
You Distribute to, that the Model or Derivatives of the Model are subject
|
139 |
+
to paragraph 5. This provision does not apply to the use of Complementary
|
140 |
+
Material.
|
141 |
+
You must give any Third Party recipients of the Model or Derivatives of
|
142 |
+
the Model a copy of this License;
|
143 |
+
You must cause any modified files to carry prominent notices stating that
|
144 |
+
You changed the files;
|
145 |
+
You must retain all copyright, patent, trademark, and attribution notices
|
146 |
+
excluding those notices that do not pertain to any part of the Model,
|
147 |
+
Derivatives of the Model.
|
148 |
+
You may add Your own copyright statement to Your modifications and may
|
149 |
+
provide additional or different license terms and conditions - respecting
|
150 |
+
paragraph 4.a. - for use, reproduction, or Distribution of Your
|
151 |
+
modifications, or for any such Derivatives of the Model as a whole,
|
152 |
+
provided Your use, reproduction, and Distribution of the Model otherwise
|
153 |
+
complies with the conditions stated in this License.
|
154 |
+
5. Use-based restrictions. The restrictions set forth in Attachment A are
|
155 |
+
considered Use-based restrictions. Therefore You cannot use the Model and
|
156 |
+
the Derivatives of the Model for the specified restricted uses. You may
|
157 |
+
use the Model subject to this License, including only for lawful purposes
|
158 |
+
and in accordance with the License. Use may include creating any content
|
159 |
+
with, finetuning, updating, running, training, evaluating and/or
|
160 |
+
reparametrizing the Model. You shall require all of Your users who use
|
161 |
+
the Model or a Derivative of the Model to comply with the terms of this
|
162 |
+
paragraph (paragraph 5).
|
163 |
+
6. The Output You Generate. Except as set forth herein, Licensor claims
|
164 |
+
no rights in the Output You generate using the Model. You are accountable
|
165 |
+
for the Output you generate and its subsequent uses. No use of the output
|
166 |
+
can contravene any provision as stated in the License.
|
167 |
+
|
168 |
+
Section IV: OTHER PROVISIONS
|
169 |
+
|
170 |
+
7. Updates and Runtime Restrictions. To the maximum extent permitted by
|
171 |
+
law, Licensor reserves the right to restrict (remotely or otherwise)
|
172 |
+
usage of the Model in violation of this License, update the Model through
|
173 |
+
electronic means, or modify the Output of the Model based on updates. You
|
174 |
+
shall undertake reasonable efforts to use the latest version of the
|
175 |
+
Model.
|
176 |
+
8. Trademarks and related. Nothing in this License permits You to make
|
177 |
+
use of Licensors’ trademarks, trade names, logos or to otherwise suggest
|
178 |
+
endorsement or misrepresent the relationship between the parties; and any
|
179 |
+
rights not expressly granted herein are reserved by the Licensors.
|
180 |
+
9. Disclaimer of Warranty. Unless required by applicable law or agreed to
|
181 |
+
in writing, Licensor provides the Model and the Complementary Material
|
182 |
+
(and each Contributor provides its Contributions) on an "AS IS" BASIS,
|
183 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
184 |
+
including, without limitation, any warranties or conditions of TITLE,
|
185 |
+
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
|
186 |
+
You are solely responsible for determining the appropriateness of using
|
187 |
+
or redistributing the Model, Derivatives of the Model, and the
|
188 |
+
Complementary Material and assume any risks associated with Your exercise
|
189 |
+
of permissions under this License.
|
190 |
+
10. Limitation of Liability. In no event and under no legal theory,
|
191 |
+
whether in tort (including negligence), contract, or otherwise, unless
|
192 |
+
required by applicable law (such as deliberate and grossly negligent
|
193 |
+
acts) or agreed to in writing, shall any Contributor be liable to You for
|
194 |
+
damages, including any direct, indirect, special, incidental, or
|
195 |
+
consequential damages of any character arising as a result of this
|
196 |
+
License or out of the use or inability to use the Model and the
|
197 |
+
Complementary Material (including but not limited to damages for loss of
|
198 |
+
goodwill, work stoppage, computer failure or malfunction, or any and all
|
199 |
+
other commercial damages or losses), even if such Contributor has been
|
200 |
+
advised of the possibility of such damages.
|
201 |
+
11. Accepting Warranty or Additional Liability. While redistributing the
|
202 |
+
Model, Derivatives of the Model and the Complementary Material thereof,
|
203 |
+
You may choose to offer, and charge a fee for, acceptance of support,
|
204 |
+
warranty, indemnity, or other liability obligations and/or rights
|
205 |
+
consistent with this License. However, in accepting such obligations, You
|
206 |
+
may act only on Your own behalf and on Your sole responsibility, not on
|
207 |
+
behalf of any other Contributor, and only if You agree to indemnify,
|
208 |
+
defend, and hold each Contributor harmless for any liability incurred by,
|
209 |
+
or claims asserted against, such Contributor by reason of your accepting
|
210 |
+
any such warranty or additional liability.
|
211 |
+
12. If any provision of this License is held to be invalid, illegal or
|
212 |
+
unenforceable, the remaining provisions shall be unaffected thereby and
|
213 |
+
remain valid as if such provision had not been set forth herein.
|
214 |
+
END OF TERMS AND CONDITIONS
|
215 |
+
|
216 |
+
|
217 |
+
|
218 |
+
|
219 |
+
Attachment A
|
220 |
+
|
221 |
+
Use Restrictions
|
222 |
+
|
223 |
+
You agree not to use the Model or Derivatives of the Model:
|
224 |
+
- In any way that violates any applicable national, federal, state, local
|
225 |
+
or international law or regulation;
|
226 |
+
- For the purpose of exploiting, harming or attempting to exploit or harm
|
227 |
+
minors in any way;
|
228 |
+
- To generate or disseminate verifiably false information and/or content
|
229 |
+
with the purpose of harming others;
|
230 |
+
- To generate or disseminate personal identifiable information that can
|
231 |
+
be used to harm an individual;
|
232 |
+
- To defame, disparage or otherwise harass others;
|
233 |
+
- For fully automated decision making that adversely impacts an
|
234 |
+
individual’s legal rights or otherwise creates or modifies a binding,
|
235 |
+
enforceable obligation;
|
236 |
+
- For any use intended to or which has the effect of discriminating
|
237 |
+
against or harming individuals or groups based on online or offline
|
238 |
+
social behavior or known or predicted personal or personality
|
239 |
+
characteristics;
|
240 |
+
- To exploit any of the vulnerabilities of a specific group of persons
|
241 |
+
based on their age, social, physical or mental characteristics, in order
|
242 |
+
to materially distort the behavior of a person pertaining to that group
|
243 |
+
in a manner that causes or is likely to cause that person or another
|
244 |
+
person physical or psychological harm;
|
245 |
+
- For any use intended to or which has the effect of discriminating
|
246 |
+
against individuals or groups based on legally protected characteristics
|
247 |
+
or categories;
|
248 |
+
- To provide medical advice and medical results interpretation;
|
249 |
+
- To generate or disseminate information for the purpose to be used for
|
250 |
+
administration of justice, law enforcement, immigration or asylum
|
251 |
+
processes, such as predicting an individual will commit fraud/crime
|
252 |
+
commitment (e.g. by text profiling, drawing causal relationships between
|
253 |
+
assertions made in documents, indiscriminate and arbitrarily-targeted
|
254 |
+
use).
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/README.md
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[**中文说明**](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/README_CN.md) | [**English**](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/README.md)
|
2 |
+
|
3 |
+
# stable-diffusion-streamlit
|
4 |
+
|
5 |
+
- [1.Introduction](#1-introduction)
|
6 |
+
- [2.Getting Started](#2-getting-started)
|
7 |
+
- [3.Quantization Performance](#3-quantization-performance)
|
8 |
+
- [4.Streamlit Progress Bar](#4-streamlit-progress-bar)
|
9 |
+
- [5.To Do](#5-to-do)
|
10 |
+
- [6.Get Help](#6-get-help)
|
11 |
+
- [7.Acknowledgements](#7-acknowledgements)
|
12 |
+
|
13 |
+
## 1. Introduction
|
14 |
+
|
15 |
+
+ Create beautiful apps using [Streamlit](https://github.com/streamlit/streamlit) to test [CompVis/stable-diffusion-v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4) model quantized by [OnnxRuntime](https://github.com/microsoft/onnxruntime) **cutting down memory 75%**.
|
16 |
+
+ **Streamlit**:
|
17 |
+
+ an open-source app framework for Machine Learning and Data Science teams. Create beautiful web apps in minutes.
|
18 |
+
+ **CompVis/stable-diffusion-v1-4**:
|
19 |
+
+ a latent text-to-image diffusion model capable of generating photo-realistic images given any text input.
|
20 |
+
+ **OnnxRuntime**:
|
21 |
+
+ a cross-platform, faster inference and lower costs accelerator for machine learning models.
|
22 |
+
|
23 |
+
|
24 |
+
## 2. Getting Started
|
25 |
+
|
26 |
+
### 2.1. Deployment
|
27 |
+
+ docker-compose up -d
|
28 |
+
```yaml
|
29 |
+
version: "2.3"
|
30 |
+
services:
|
31 |
+
stable-diffusion-streamlit-onnxquantized:
|
32 |
+
container_name: stable-diffusion-streamlit-onnxquantized
|
33 |
+
image: lowinli98/stable-diffusion-streamlit-onnxquantized:v0.2
|
34 |
+
expose:
|
35 |
+
- 8501
|
36 |
+
ports:
|
37 |
+
- "8501:8501"
|
38 |
+
environment:
|
39 |
+
- APP_TITLE=Stable Diffusion Streamlit
|
40 |
+
restart: always
|
41 |
+
volumes:
|
42 |
+
- /etc/localtime:/etc/localtime
|
43 |
+
- ./volume:/app/pages/model/result
|
44 |
+
```
|
45 |
+
|
46 |
+
### 2.2. Usage
|
47 |
+
+ 2.2.1. Copy an awesome prompt from Blogs like [best-100-stable-diffusion-prompts](https://mpost.io/best-100-stable-diffusion-prompts-the-most-beautiful-ai-text-to-image-prompts/) or [50-text-to-image-prompts-for-ai](https://decentralizedcreator.com/50-text-to-image-prompts-for-ai-art-generator-stable-diffusion-a-visual-treat-inside/)
|
48 |
+
+ 2.2.2. Open http://localhost:8501 and click "文本转图片" on the left sidebar.
|
49 |
+
+ 2.2.3. Fix the runtime parameters, paste your prompt into the text area and click the "开始生成" button.
|
50 |
+
|
51 |
+
![](./doc/gif/use1.gif)
|
52 |
+
|
53 |
+
+ 2.2.4. Wait for a while until the progress bar goes to the end, then you will get a generated image.
|
54 |
+
|
55 |
+
![](./doc/gif/use2.gif)
|
56 |
+
|
57 |
+
+ 2.2.5. Click "画廊" on the left sidebar to see all the images you had generated.
|
58 |
+
|
59 |
+
![](./doc/gif/use3.gif)
|
60 |
+
|
61 |
+
|
62 |
+
## 3. Quantization Performance
|
63 |
+
+ The model in the docker container has been quantized by OnnxRuntime in the building of the docker image.
|
64 |
+
|
65 |
+
+ [dockerfile](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/docker/dockerfile)
|
66 |
+
+ [building progress in Github Action](https://github.com/LowinLi/stable-diffusion-streamlit/actions/runs/3202674839/jobs/5231895605)
|
67 |
+
|
68 |
+
+ The quantized model will be smaller and cut down the inference time a little(UINT8), while the performance of the image generated is almost the same as the original model.
|
69 |
+
+ This is an amazing feature because [CompVis/stable-diffusion-v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4) can be deployed on most home computers. The following table shows the comparison of the quantized model and the original model.
|
70 |
+
|
71 |
+
---
|
72 |
+
| model | memory used | inference 49 steps waste time |
|
73 |
+
| --- | --- | --- |
|
74 |
+
| pytorch | 5.2GB | 6m56s |
|
75 |
+
| onnx | 5.0GB | 4m34s |
|
76 |
+
| onnx-quantized(UINT8) | 1.3GB | 4m29s |
|
77 |
+
|
78 |
+
+ CPU:
|
79 |
+
+ Intel(R) Xeon(R) CPU E5-2650 v3 @ 2.30GHz
|
80 |
+
+ 10 core
|
81 |
+
|
82 |
+
|
83 |
+
+ image generated by PyTorch model
|
84 |
+
|
85 |
+
![](./doc/pic/torch.png)
|
86 |
+
+ image generated by Onnx model
|
87 |
+
|
88 |
+
![](./doc/pic/onnx.png)
|
89 |
+
+ image generated by Onnx-Quantized(UINT8) model
|
90 |
+
|
91 |
+
![](./doc/pic/onnxquantized.png)
|
92 |
+
|
93 |
+
## 4. Streamlit Progress Bar
|
94 |
+
To generate an awesome image, the model needs to be inferences with many steps. So it will take a long time to finish the whole pipeline. To make the user experience better, a progress bar is added to show the pipeline progress.
|
95 |
+
With another thread in Python, the progress bar can be updated by the pipeline scheduler counter.
|
96 |
+
|
97 |
+
|
98 |
+
|
99 |
+
## 5. To Do
|
100 |
+
|
101 |
+
- [ ] Add the Text-Guided Image-to-Image Pipeline in [Huggingface/Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/img2img)
|
102 |
+
- [ ] Add the Text-Guided Image-Inpainting Pipeline in [Huggingface/Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/inpaint)
|
103 |
+
|
104 |
+
## 6. Get Help
|
105 |
+
|
106 |
+
+ Contact me at [email protected]
|
107 |
+
+ If appropriate, open an issue on GitHub
|
108 |
+
|
109 |
+
## 7. Acknowledgements
|
110 |
+
|
111 |
+
+ [Huggingface/Diffusers](https://github.com/huggingface/diffusers)
|
112 |
+
+ [CompVis/stable-diffusion](https://github.com/CompVis/stable-diffusion)
|
113 |
+
+ [Streamlit](https://github.com/streamlit/streamlit)
|
114 |
+
+ [OnnxRuntime](https://github.com/microsoft/onnxruntime)
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/README_CN.md
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[**中文说明**](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/README_CN.md) | [**English**](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/README.md)
|
2 |
+
|
3 |
+
# stable-diffusion-streamlit
|
4 |
+
|
5 |
+
- [1.简介](#1-简介)
|
6 |
+
- [2.快速开始](#2-快速开始)
|
7 |
+
- [3.模型量化提速表现](#3-模型量化提速表现)
|
8 |
+
- [4.Streamlit进度条](#4-Streamlit进度条)
|
9 |
+
- [5.下一步](#5-下一步)
|
10 |
+
- [6.帮助](#6-帮助)
|
11 |
+
- [7.致谢](#7-致谢)
|
12 |
+
|
13 |
+
## 1. 简介
|
14 |
+
|
15 |
+
+ **使用[Streamlit](https://github.com/streamlit/streamlit)构建一个Web服务,测试使用[OnnxRuntime](https://github.com/microsoft/onnxruntime)量化压缩后的[CompVis/stable-diffusion-v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4)模型做图片生成**.
|
16 |
+
+ **Streamlit**:
|
17 |
+
+ 一个流行的开源框架,可以快速搭建机器学习和数据科学团队的Web应用。
|
18 |
+
+ **CompVis/stable-diffusion-v1-4**:
|
19 |
+
+ 一个流行的扩散模型,可以通过文字提示生成栩栩如生的高质量图片。
|
20 |
+
+ **OnnxRuntime**:
|
21 |
+
+ 微软推出的一款推理框架,用户可以非常便利的量化压缩模型。
|
22 |
+
|
23 |
+
|
24 |
+
## 2. 快速开始
|
25 |
+
|
26 |
+
### 2.1. 部署
|
27 |
+
+ docker-compose up -d
|
28 |
+
```yaml
|
29 |
+
version: "2.3"
|
30 |
+
services:
|
31 |
+
stable-diffusion-streamlit-onnxquantized:
|
32 |
+
container_name: stable-diffusion-streamlit-onnxquantized
|
33 |
+
image: lowinli98/stable-diffusion-streamlit-onnxquantized:v0.2
|
34 |
+
expose:
|
35 |
+
- 8501
|
36 |
+
ports:
|
37 |
+
- "8501:8501"
|
38 |
+
environment:
|
39 |
+
- APP_TITLE=Stable Diffusion Streamlit
|
40 |
+
restart: always
|
41 |
+
volumes:
|
42 |
+
- /etc/localtime:/etc/localtime
|
43 |
+
- ./volume:/app/pages/model/result
|
44 |
+
```
|
45 |
+
|
46 |
+
### 2.2. 使用
|
47 |
+
+ 2.2.1. 从博客[best-100-stable-diffusion-prompts](https://mpost.io/best-100-stable-diffusion-prompts-the-most-beautiful-ai-text-to-image-prompts/)或[50-text-to-image-prompts-for-ai](https://decentralizedcreator.com/50-text-to-image-prompts-for-ai-art-generator-stable-diffusion-a-visual-treat-inside/)复制一个文本提示。
|
48 |
+
+ 2.2.2. 打开http://localhost:8501,在侧边栏点击"文本转图片"。
|
49 |
+
+ 2.2.3. 修改运行参数, 粘贴提示,点击"开始生成"。
|
50 |
+
|
51 |
+
![](./doc/gif/use1.gif)
|
52 |
+
|
53 |
+
+ 2.2.4. 待进度条走完后,页面直接展示生成的图片
|
54 |
+
|
55 |
+
![](./doc/gif/use2.gif)
|
56 |
+
|
57 |
+
+ 2.2.5. 点击侧边栏的"画廊"查看所有历史生成的图片
|
58 |
+
|
59 |
+
![](./doc/gif/use3.gif)
|
60 |
+
|
61 |
+
|
62 |
+
## 3. 模型量化提速表现
|
63 |
+
+ 服务中使用的模型已经在打镜像阶段就做了OnnxRuntime量化压缩处理,详见:
|
64 |
+
|
65 |
+
+ [dockerfile](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/docker/dockerfile)
|
66 |
+
+ [Github Action的镜像构建日志](https://github.com/LowinLi/stable-diffusion-streamlit/actions/runs/3202674839/jobs/5231895605)
|
67 |
+
|
68 |
+
+ 量化后的模型尺寸降低很多、推理速度提高一点点(UINT8), 同时保持和原模型几乎一样的生成图片质量.
|
69 |
+
+ 这一点意味着,[CompVis/stable-diffusion-v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4)模型可以被部署在大多数家用电脑上,并进行调试。以下是几种模型的比较:
|
70 |
+
|
71 |
+
---
|
72 |
+
| 模型 | 内存 | 49步推断用时 |
|
73 |
+
| --- | --- | --- |
|
74 |
+
| pytorch | 5.2GB | 6m56s |
|
75 |
+
| onnx | 5.0GB | 4m34s |
|
76 |
+
| onnx-quantized(UINT8) | 1.3GB | 4m29s |
|
77 |
+
|
78 |
+
+ CPU:
|
79 |
+
+ Intel(R) Xeon(R) CPU E5-2650 v3 @ 2.30GHz
|
80 |
+
+ 10 core
|
81 |
+
|
82 |
+
|
83 |
+
+ PyTorch模型生成的图片
|
84 |
+
|
85 |
+
![](./doc/pic/torch.png)
|
86 |
+
+ Onnx模型生成的图片
|
87 |
+
|
88 |
+
![](./doc/pic/onnx.png)
|
89 |
+
+ Onnx-quantized(UINT8)模型生成的图片
|
90 |
+
|
91 |
+
![](./doc/pic/onnxquantized.png)
|
92 |
+
|
93 |
+
## 4. Streamlit进度条
|
94 |
+
为了生成高质量图片,扩散模型一般要推断很多步,这会比较耗时。为了提升用户体验,在Streamlit页面做了一个进度条,通过另一个线程,监控推断步数,并更新到进度条中。
|
95 |
+
|
96 |
+
## 5. 下一步
|
97 |
+
|
98 |
+
- [ ] 增加[Huggingface/Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/img2img)中的图像生成图像流程
|
99 |
+
- [ ] 增加[Huggingface/Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/inpaint)中的抠图生成图像流程
|
100 |
+
|
101 |
+
## 6. 帮助
|
102 |
+
|
103 |
+
+ 联系我的邮箱[email protected]
|
104 |
+
+ 有任何问题,欢迎在Github上提Issue
|
105 |
+
|
106 |
+
## 7. 致谢
|
107 |
+
|
108 |
+
+ [Huggingface/Diffusers](https://github.com/huggingface/diffusers)
|
109 |
+
+ [CompVis/stable-diffusion](https://github.com/CompVis/stable-diffusion)
|
110 |
+
+ [Streamlit](https://github.com/streamlit/streamlit)
|
111 |
+
+ [OnnxRuntime](https://github.com/microsoft/onnxruntime)
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/gif/use1.gif
ADDED
Git LFS Details
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/gif/use2.gif
ADDED
Git LFS Details
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/gif/use3.gif
ADDED
Git LFS Details
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/pic/onnx.png
ADDED
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/pic/onnxquantized.png
ADDED
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/doc/pic/torch.png
ADDED
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/build.sh
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
3 |
+
BUILDROOT=$DIR/..
|
4 |
+
|
5 |
+
cd $BUILDROOT
|
6 |
+
|
7 |
+
CONTAINER="lowinli98/stable-diffusion-streamlit-onnxquantized" #替换成你的容器名称
|
8 |
+
VERSION=`git describe --abbrev=0 --tags`
|
9 |
+
|
10 |
+
IMAGE_NAME="${CONTAINER}:${VERSION}"
|
11 |
+
cmd="docker build -t $IMAGE_NAME -f $DIR/dockerfile $BUILDROOT --build-arg HUGGINGFACE_TOKEN=$1"
|
12 |
+
echo $cmd
|
13 |
+
eval $cmd
|
14 |
+
|
15 |
+
docker push $IMAGE_NAME
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/docker-compose.yaml
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
version: "2.3"
|
2 |
+
services:
|
3 |
+
stable-diffusion-streamlit-onnxquantized:
|
4 |
+
container_name: stable-diffusion-streamlit-onnxquantized
|
5 |
+
image: lowinli98/stable-diffusion-streamlit-onnxquantized:v0.2
|
6 |
+
expose:
|
7 |
+
- 8501
|
8 |
+
ports:
|
9 |
+
- "8501:8501"
|
10 |
+
environment:
|
11 |
+
- APP_TITLE=Stable Diffusion Streamlit
|
12 |
+
restart: always
|
13 |
+
volumes:
|
14 |
+
- /etc/localtime:/etc/localtime
|
15 |
+
- ./volume:/app/pages/model/result
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/dockerfile
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.8.7-slim as builder
|
2 |
+
ARG HUGGINGFACE_TOKEN
|
3 |
+
ENV HUGGINGFACE_TOKEN=${HUGGINGFACE_TOKEN}
|
4 |
+
COPY docker/requirements.txt /app/
|
5 |
+
|
6 |
+
# install
|
7 |
+
RUN echo "==> Installing ..." && \
|
8 |
+
pip3 install --no-cache-dir --upgrade pip && \
|
9 |
+
pip3 install virtualenv && \
|
10 |
+
virtualenv -p /usr/local/bin/python /app/env && \
|
11 |
+
/app/env/bin/pip install --no-cache-dir --upgrade pip && \
|
12 |
+
/app/env/bin/pip install --no-cache-dir -r /app/requirements.txt --extra-index-url https://download.pytorch.org/whl/cpu
|
13 |
+
|
14 |
+
COPY src/stable-diffusion-streamlit /app/
|
15 |
+
RUN cd /app/pages/model/ && \
|
16 |
+
/app/env/bin/python prepare.py
|
17 |
+
|
18 |
+
FROM python:3.8.7-slim
|
19 |
+
COPY --from=builder /app /app
|
20 |
+
WORKDIR /app
|
21 |
+
CMD ["/app/env/bin/streamlit", "run", "主页.py"]
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/entrypoint.sh
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
streamlit run 主页.py
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/docker/requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
ftfy==6.1.1
|
2 |
+
onnx==1.12.0
|
3 |
+
onnxruntime==1.12.1
|
4 |
+
streamlit==1.13.0
|
5 |
+
transformers==4.22.2
|
6 |
+
diffusers==0.4.0
|
7 |
+
torch==1.10.0+cpu
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/entrypoint.sh
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
streamlit run 主页.py
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/__init__.py
ADDED
File without changes
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/copy_pb.py
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
|
4 |
+
|
5 |
+
def copy_weights():
|
6 |
+
for (root, _, file_list) in os.walk(
|
7 |
+
os.path.join(
|
8 |
+
os.environ["HOME"],
|
9 |
+
".cache/huggingface/diffusers/models--CompVis--stable-diffusion-v1-4",
|
10 |
+
)
|
11 |
+
):
|
12 |
+
if "weights.pb" in file_list:
|
13 |
+
shutil.copyfile(os.path.join(root, "weights.pb"), "./onnx/unet/weights.pb")
|
14 |
+
|
15 |
+
|
16 |
+
if __name__ == "__main__":
|
17 |
+
copy_weights()
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/download_onnx.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from diffusers import StableDiffusionOnnxPipeline
|
3 |
+
|
4 |
+
|
5 |
+
def download_save():
|
6 |
+
token = os.environ.get("HUGGINGFACE_TOKEN")
|
7 |
+
|
8 |
+
pipe = StableDiffusionOnnxPipeline.from_pretrained(
|
9 |
+
"CompVis/stable-diffusion-v1-4",
|
10 |
+
revision="onnx",
|
11 |
+
provider="CPUExecutionProvider",
|
12 |
+
use_auth_token=token,
|
13 |
+
)
|
14 |
+
for tmp_dir in ["safety_checker", "text_encoder", "unet", "vae_decoder"]:
|
15 |
+
os.makedirs(os.path.join("./onnx", tmp_dir), exist_ok=True)
|
16 |
+
with open(os.path.join("./onnx", tmp_dir, "model.onnx"), "wb") as f:
|
17 |
+
f.write(b"")
|
18 |
+
pipe.save_pretrained("./onnx")
|
19 |
+
|
20 |
+
|
21 |
+
if __name__ == "__main__":
|
22 |
+
download_save()
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/inference.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from diffusers import StableDiffusionOnnxPipeline, StableDiffusionPipeline
|
2 |
+
import os
|
3 |
+
import json
|
4 |
+
|
5 |
+
root = os.getcwd()
|
6 |
+
last_dir = os.path.split(root)[-1]
|
7 |
+
if last_dir == "stable-diffusion-streamlit":
|
8 |
+
model_dir = os.path.join(root, "pages/model/onnx")
|
9 |
+
result_dir = os.path.join(root, "pages/model/result")
|
10 |
+
elif last_dir == "pages":
|
11 |
+
model_dir = os.path.join(root, "model/onnx")
|
12 |
+
result_dir = os.path.join(root, "model/result")
|
13 |
+
elif last_dir == "app":
|
14 |
+
model_dir = os.path.join(root, "pages/model/onnx")
|
15 |
+
result_dir = os.path.join(root, "pages/model/result")
|
16 |
+
else:
|
17 |
+
model_dir = os.path.join(root, "onnx")
|
18 |
+
result_dir = os.path.join(root, "result")
|
19 |
+
|
20 |
+
global quant_pipe
|
21 |
+
|
22 |
+
quant_pipe = StableDiffusionOnnxPipeline.from_pretrained(
|
23 |
+
model_dir, provider="CPUExecutionProvider", local_files_only=True
|
24 |
+
)
|
25 |
+
# quant_pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", local_files_only=True)
|
26 |
+
|
27 |
+
|
28 |
+
def inference(uid, **args):
|
29 |
+
image = quant_pipe(**args)["sample"][0]
|
30 |
+
target = os.path.join(result_dir, uid)
|
31 |
+
os.makedirs(target, exist_ok=True)
|
32 |
+
image.save(os.path.join(target, "image.png"))
|
33 |
+
with open(os.path.join(target, "config.json"), "w") as f:
|
34 |
+
json.dump(args, f, indent=4, ensure_ascii=False)
|
35 |
+
|
36 |
+
|
37 |
+
if __name__ == "__main__":
|
38 |
+
from pympler.asizeof import asizeof
|
39 |
+
|
40 |
+
print(asizeof(quant_pipe))
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/prepare.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from copy_pb import copy_weights
|
2 |
+
from download_onnx import download_save
|
3 |
+
from quantization import quant
|
4 |
+
import shutil
|
5 |
+
|
6 |
+
if __name__ == "__main__":
|
7 |
+
shutil.rmtree("./onnx", ignore_errors=True)
|
8 |
+
download_save()
|
9 |
+
copy_weights()
|
10 |
+
quant()
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/quantization.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from onnxruntime.quantization import quantize_dynamic, QuantType
|
3 |
+
|
4 |
+
|
5 |
+
def quant():
|
6 |
+
for root, dirs, filenames in os.walk("./onnx"):
|
7 |
+
if "model.onnx" in filenames:
|
8 |
+
if "weights.pb" in filenames:
|
9 |
+
external_data = True
|
10 |
+
else:
|
11 |
+
external_data = False
|
12 |
+
quantize_dynamic(
|
13 |
+
model_input=os.path.join(root, "model.onnx"),
|
14 |
+
model_output=os.path.join(root, "model.onnx"), # 量化后直接覆盖原onnx文件
|
15 |
+
per_channel=True,
|
16 |
+
reduce_range=True,
|
17 |
+
weight_type=QuantType.QUInt8,
|
18 |
+
optimize_model=True,
|
19 |
+
use_external_data_format=external_data,
|
20 |
+
)
|
21 |
+
print("Quantized model saved at: ", os.path.join(root, "model.onnx"))
|
22 |
+
if "weights.pb" in filenames:
|
23 |
+
os.remove(os.path.join(root, "weights.pb"))
|
24 |
+
print("Removed weights.pb")
|
25 |
+
|
26 |
+
|
27 |
+
if __name__ == "__main__":
|
28 |
+
quant()
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/thread.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import threading
|
2 |
+
import copy
|
3 |
+
from diffusers import StableDiffusionOnnxPipeline, StableDiffusionPipeline
|
4 |
+
|
5 |
+
|
6 |
+
class PipelineThread(threading.Thread):
|
7 |
+
def __init__(self, func, args=()):
|
8 |
+
super(PipelineThread, self).__init__()
|
9 |
+
self.func = StableDiffusionOnnxPipeline(
|
10 |
+
func.vae_decoder,
|
11 |
+
func.text_encoder,
|
12 |
+
func.tokenizer,
|
13 |
+
func.unet,
|
14 |
+
copy.deepcopy(func.scheduler),
|
15 |
+
func.safety_checker,
|
16 |
+
func.feature_extractor,
|
17 |
+
)
|
18 |
+
self.args = args
|
19 |
+
|
20 |
+
def run(self):
|
21 |
+
self.result = self.func(*self.args)
|
22 |
+
|
23 |
+
def get_result(self):
|
24 |
+
try:
|
25 |
+
return self.result
|
26 |
+
except Exception:
|
27 |
+
return None
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/文字转图片.py
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import numpy as np
|
3 |
+
import time
|
4 |
+
import threading
|
5 |
+
from datetime import datetime
|
6 |
+
import json
|
7 |
+
import os
|
8 |
+
import gc
|
9 |
+
from diffusers.training_utils import set_seed
|
10 |
+
|
11 |
+
from pages.model.inference import result_dir, quant_pipe
|
12 |
+
from pages.model.thread import PipelineThread
|
13 |
+
|
14 |
+
st.set_page_config(
|
15 |
+
page_title="文字转图片",
|
16 |
+
page_icon="🧊",
|
17 |
+
layout="wide",
|
18 |
+
initial_sidebar_state="expanded",
|
19 |
+
menu_items={},
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
st.title("扩散模型文字生成图片")
|
24 |
+
with st.form(key="my_form"):
|
25 |
+
ce, c1, ce, c2, c3 = st.columns([0.07, 1, 0.07, 5, 0.07])
|
26 |
+
with c1:
|
27 |
+
st.subheader("参数配置", anchor=None)
|
28 |
+
num_inference_steps = st.slider(
|
29 |
+
"生成轮数(num_inference_steps)",
|
30 |
+
min_value=5,
|
31 |
+
max_value=100,
|
32 |
+
value=50,
|
33 |
+
step=1,
|
34 |
+
label_visibility="visible",
|
35 |
+
help="约大生成图片质量越高,但是速度越慢 \n The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.",
|
36 |
+
)
|
37 |
+
guidance_scale = st.slider(
|
38 |
+
"指导参数(guidance_scale)",
|
39 |
+
min_value=0.0,
|
40 |
+
max_value=30.0,
|
41 |
+
value=7.0,
|
42 |
+
step=0.1,
|
43 |
+
help="值越大,约接近输入文字 \n Defined in https://arxiv.org/abs/2207.12598 \n Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality.",
|
44 |
+
label_visibility="visible",
|
45 |
+
)
|
46 |
+
height = st.slider(
|
47 |
+
"高度像素(height)",
|
48 |
+
min_value=64,
|
49 |
+
max_value=1024,
|
50 |
+
value=512,
|
51 |
+
step=8,
|
52 |
+
label_visibility="visible",
|
53 |
+
)
|
54 |
+
width = st.slider(
|
55 |
+
"宽度像素(width)",
|
56 |
+
min_value=64,
|
57 |
+
max_value=1024,
|
58 |
+
value=512,
|
59 |
+
step=8,
|
60 |
+
label_visibility="visible",
|
61 |
+
)
|
62 |
+
eta = st.slider(
|
63 |
+
"eta (η)",
|
64 |
+
min_value=0.0,
|
65 |
+
max_value=5.0,
|
66 |
+
value=0.0,
|
67 |
+
step=0.1,
|
68 |
+
help="Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502",
|
69 |
+
label_visibility="visible",
|
70 |
+
)
|
71 |
+
seed = st.slider(
|
72 |
+
"种子(seed)",
|
73 |
+
min_value=0,
|
74 |
+
max_value=1024,
|
75 |
+
value=10,
|
76 |
+
step=1,
|
77 |
+
label_visibility="visible",
|
78 |
+
help="配置不同种子可以生成不同的图片",
|
79 |
+
)
|
80 |
+
|
81 |
+
with c2:
|
82 |
+
text_prompt = st.text_area(
|
83 |
+
"输入提示文字",
|
84 |
+
value="",
|
85 |
+
help="The prompt or prompts to guide the image generation",
|
86 |
+
disabled=False,
|
87 |
+
label_visibility="visible",
|
88 |
+
)
|
89 |
+
negative_prompt = st.text_area(
|
90 |
+
"输入不要生成的文字描述,不填为不使用",
|
91 |
+
value="",
|
92 |
+
help="The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).",
|
93 |
+
disabled=False,
|
94 |
+
label_visibility="visible",
|
95 |
+
)
|
96 |
+
negative_prompt = None
|
97 |
+
submit_button = st.form_submit_button("开始生成", help=None, args=None, kwargs=None)
|
98 |
+
my_bar = st.progress(0)
|
99 |
+
if not submit_button:
|
100 |
+
st.stop()
|
101 |
+
set_seed(seed)
|
102 |
+
uid = datetime.now().strftime("%Y%m%d_%H:%M:%S")
|
103 |
+
args = (
|
104 |
+
text_prompt,
|
105 |
+
height,
|
106 |
+
width,
|
107 |
+
num_inference_steps,
|
108 |
+
guidance_scale,
|
109 |
+
negative_prompt,
|
110 |
+
eta,
|
111 |
+
)
|
112 |
+
t = PipelineThread(func=quant_pipe, args=args)
|
113 |
+
t.start()
|
114 |
+
while True:
|
115 |
+
time.sleep(1)
|
116 |
+
if isinstance(t.func.scheduler.counter, int):
|
117 |
+
counter = t.func.scheduler.counter
|
118 |
+
else:
|
119 |
+
counter = 0
|
120 |
+
progress = min(
|
121 |
+
t.func.scheduler.counter / (num_inference_steps + 1),
|
122 |
+
1.0,
|
123 |
+
)
|
124 |
+
my_bar.progress(progress)
|
125 |
+
if progress >= 1:
|
126 |
+
break
|
127 |
+
t.join()
|
128 |
+
|
129 |
+
image_filename = os.path.join(result_dir, "text2image", uid, "image.png")
|
130 |
+
json_filename = os.path.join(result_dir, "text2image", uid, "config.json")
|
131 |
+
os.makedirs(os.path.join(result_dir, "text2image", uid), exist_ok=True)
|
132 |
+
t.get_result().images[0].save(image_filename)
|
133 |
+
del t
|
134 |
+
gc.collect()
|
135 |
+
with open(json_filename, "w") as f:
|
136 |
+
config = {
|
137 |
+
"text_prompt": text_prompt,
|
138 |
+
"height": height,
|
139 |
+
"width": width,
|
140 |
+
"num_inference_steps": num_inference_steps,
|
141 |
+
"guidance_scale": guidance_scale,
|
142 |
+
"eta": eta,
|
143 |
+
"seed": seed,
|
144 |
+
}
|
145 |
+
json.dump(config, f, indent=4, ensure_ascii=False)
|
146 |
+
st.balloons()
|
147 |
+
st.image(
|
148 |
+
image_filename, channels="RGB", output_format="auto", caption=text_prompt
|
149 |
+
)
|
150 |
+
with open(json_filename, "r") as f:
|
151 |
+
st.json(json.load(f), expanded=True)
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/画廊.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
import json
|
4 |
+
|
5 |
+
# tab1 = st.tabs(["文字转图片"])
|
6 |
+
|
7 |
+
# with tab1:
|
8 |
+
result_dir = "pages/model/result/text2image"
|
9 |
+
os.makedirs(result_dir, exist_ok=True)
|
10 |
+
list_uid = os.listdir(result_dir)
|
11 |
+
list_uid = sorted(list_uid, reverse=True)
|
12 |
+
|
13 |
+
for uid in list_uid:
|
14 |
+
try:
|
15 |
+
with open(os.path.join(result_dir, uid, "config.json"), "r") as f:
|
16 |
+
config = json.load(f)
|
17 |
+
|
18 |
+
with st.container():
|
19 |
+
st.caption(uid)
|
20 |
+
st.image(
|
21 |
+
os.path.join(result_dir, uid, "image.png"),
|
22 |
+
caption=str(config["text_prompt"]),
|
23 |
+
)
|
24 |
+
st.json(config, expanded=False)
|
25 |
+
st.markdown("---")
|
26 |
+
except:
|
27 |
+
pass
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
ftfy==6.1.1
|
2 |
+
onnx==1.12.0
|
3 |
+
onnxruntime==1.12.1
|
4 |
+
streamlit==1.13.0
|
5 |
+
streamlit-image-comparison==0.0.2
|
6 |
+
transformers==4.22.2
|
7 |
+
diffusers==0.3.0
|
8 |
+
torch==1.10.0
|
9 |
+
pandas==1.4.1
|
patchedstabledifftoonnx_withou_modelort/stable-diffusion-streamlit/src/stable-diffusion-streamlit/主页.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
|
4 |
+
app_title = os.environ.get("APP_TITLE", "Streamlit,Stable Diffusion在线生图工具")
|
5 |
+
st.title(app_title)
|
6 |
+
body = """+ [文字转图片](./文字转图片)
|
7 |
+
+ [画廊](./画廊)
|
8 |
+
"""
|
9 |
+
st.markdown(body, unsafe_allow_html=False)
|
patchedstabledifftoonnx_withou_modelort/test-controlnet-canny.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from diffusers.utils import load_image
|
2 |
+
import cv2
|
3 |
+
from PIL import Image
|
4 |
+
import numpy as np
|
5 |
+
from diffusers import UniPCMultistepScheduler
|
6 |
+
from pipeline_onnx_stable_diffusion_controlnet import OnnxStableDiffusionControlNetPipeline
|
7 |
+
import onnxruntime as ort
|
8 |
+
|
9 |
+
image = load_image(
|
10 |
+
"input_image_vermeer.png"
|
11 |
+
)
|
12 |
+
|
13 |
+
image = np.array(image)
|
14 |
+
|
15 |
+
low_threshold = 100
|
16 |
+
high_threshold = 200
|
17 |
+
|
18 |
+
image = cv2.Canny(image, low_threshold, high_threshold)
|
19 |
+
image = image[:, :, None]
|
20 |
+
image = np.concatenate([image, image, image], axis=2)
|
21 |
+
canny_image = Image.fromarray(image)
|
22 |
+
|
23 |
+
opts = ort.SessionOptions()
|
24 |
+
opts.enable_cpu_mem_arena = False
|
25 |
+
opts.enable_mem_pattern = False
|
26 |
+
|
27 |
+
pipe = OnnxStableDiffusionControlNetPipeline.from_pretrained(
|
28 |
+
"model/sd1_5-fp16-vae_ft_mse-autoslicing-cn_canny",
|
29 |
+
sess_options=opts,
|
30 |
+
provider="DmlExecutionProvider",
|
31 |
+
)
|
32 |
+
|
33 |
+
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
|
34 |
+
prompt = "jpop singer on stage, best quality, extremely detailed"
|
35 |
+
seed=42
|
36 |
+
generator = np.random.RandomState(seed)
|
37 |
+
|
38 |
+
images = pipe(
|
39 |
+
prompt,
|
40 |
+
canny_image,
|
41 |
+
negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
|
42 |
+
num_inference_steps=20,
|
43 |
+
generator=generator,
|
44 |
+
).images[0]
|
45 |
+
images.save("controlnet-canny-test.png")
|
patchedstabledifftoonnx_withou_modelort/test-controlnet-openpose.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
import numpy as np
|
3 |
+
from diffusers import DEISMultistepScheduler
|
4 |
+
from pipeline_onnx_stable_diffusion_controlnet import OnnxStableDiffusionControlNetPipeline
|
5 |
+
import onnxruntime as ort
|
6 |
+
|
7 |
+
pose_image = Image.open(r"dance_pose.png")
|
8 |
+
|
9 |
+
opts = ort.SessionOptions()
|
10 |
+
opts.enable_cpu_mem_arena = False
|
11 |
+
opts.enable_mem_pattern = False
|
12 |
+
|
13 |
+
pipe = OnnxStableDiffusionControlNetPipeline.from_pretrained(
|
14 |
+
"model/anyv3-fp16-autoslicing-cn_openpose",
|
15 |
+
sess_options=opts,
|
16 |
+
provider="DmlExecutionProvider",
|
17 |
+
)
|
18 |
+
|
19 |
+
pipe.scheduler = DEISMultistepScheduler.from_config(pipe.scheduler.config)
|
20 |
+
prompt = "1girl, blonde, long dress, dancing, best quality"
|
21 |
+
seed=25
|
22 |
+
generator = np.random.RandomState(seed)
|
23 |
+
|
24 |
+
images = pipe(
|
25 |
+
prompt,
|
26 |
+
pose_image,
|
27 |
+
width=512,
|
28 |
+
height=512,
|
29 |
+
negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality",
|
30 |
+
num_inference_steps=30,
|
31 |
+
generator=generator,
|
32 |
+
).images[0]
|
33 |
+
images.save("controlnet-openpose-test.png")
|