diff --git a/.gitattributes b/.gitattributes index 6baeca5477d79f6495f0c7e3b76003f0a3904fe8..ed079a22f9049d19861bd0ffe61924f08c7aeef6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -51,3 +51,12 @@ fp16onnxquantizedsd_in_ort/cyberrealistic/model.ort filter=lfs diff=lfs merge=lf fp16onnxquantizedsd_in_ort/cyberrealistic/model.with_runtime_opt.ort filter=lfs diff=lfs merge=lfs -text fp16onnxquantizedsd_textencoder_in_ort/cyberrealistic/model.ort filter=lfs diff=lfs merge=lfs -text fp16onnxquantizedsd_textencoder_in_ort/cyberrealistic/model.with_runtime_opt.ort filter=lfs diff=lfs merge=lfs -text +patchedstabledifftoonnx/sd_env/bin/python filter=lfs diff=lfs merge=lfs -text +patchedstabledifftoonnx/sd_env/bin/python3 filter=lfs diff=lfs merge=lfs -text +patchedstabledifftoonnx/sd_env/bin/python3.10 filter=lfs diff=lfs merge=lfs -text +patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use1.gif filter=lfs diff=lfs merge=lfs -text +patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use2.gif filter=lfs diff=lfs merge=lfs -text +patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use3.gif filter=lfs diff=lfs merge=lfs -text +patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.onnx.data filter=lfs diff=lfs merge=lfs -text +patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.ort filter=lfs diff=lfs merge=lfs -text +patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.with_runtime_opt.ort filter=lfs diff=lfs merge=lfs -text diff --git a/patchedstabledifftoonnx/LICENSE b/patchedstabledifftoonnx/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/patchedstabledifftoonnx/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/patchedstabledifftoonnx/README.md b/patchedstabledifftoonnx/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cf248307c667ea3a54e9612887c5824760a14eaa --- /dev/null +++ b/patchedstabledifftoonnx/README.md @@ -0,0 +1,293 @@ +# Stable Diffusion using ONNX, FP16 and DirectML + +This repository contains a conversion tool, some examples, and instructions on how to set up Stable Diffusion with ONNX models. +This was mainly intended for use with AMD GPUs but should work just as well with other DirectML devices (e.g. Intel Arc). +I'd be very interested to hear of any results with Intel Arc. + +**MOST IMPORTANT RECENT UPDATES:** +**- ONNX Runtime 1.15 has been released! Updated model tuning code to better align with ORT.** +**- Realigned with latest version of diffusers, we were forced to switch to torch 2.1 nightly! (Install instructions updated accordingly)** +**- I have enabled GitHub discussions: If you have a generic question rather than an issue, start a discussion!** + +This focuses specifically on making it easy to get FP16 models. When using FP16, the VRAM footprint is significantly reduced and speed goes up. + +It's all fairly straightforward, but It helps to be comfortable with command line. + +You can use these instructions to convert models to FP16 and then use them in any tool that allows you to load ONNX models. +We'll demonstrate this by downloading and setting up ONNXDiffusersUI specifically for use with our installation (no need to follow the ONNXDiffusersUI setup). + +## Set up + +First make sure you have Python 3.10 (or 3.11) installed. You can get it here: https://www.python.org/downloads/ +**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. + +If you don't have git, get it here: https://gitforwindows.org/ + +Pick a directory that can contain your Stable Diffusion installation (make sure you've the diskspace to store the models). +Open the commandline (Powershell or Command Prompt) and change into the directory you will use. + +Start by cloning this repository: +``` +git clone https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16 +cd Stable-Diffusion-ONNX-FP16 +``` + +Do the following: +``` +pip install virtualenv +python -m venv sd_env +sd_env\scripts\activate +python -m pip install --upgrade pip +pip install torch --extra-index-url https://download.pytorch.org/whl/nightly/cpu --pre +pip install -r requirements.txt +``` + +Now first make sure you have an account on https://huggingface.co/ +When you do make sure to create a token on https://huggingface.co/settings/tokens +And then on the commandline login using following command +``` +huggingface-cli login +``` + +Now you're ready to download and convert models. Before we explain this, just a pointer on future use. +Whenever you want to make use of this post set up, open a command line, change into the directory and enable the environment. +Say that you installed this on your D: drive in the root. You would open command line and then: +``` +d: +cd Stable-Diffusion-ONNX-FP16 +sd_env\scripts\activate +``` + +Remember this for whenver you want to use your installation. Let's now get to the fun part and convert some models: +``` +mkdir model +python conv_sd_to_onnx.py --model_path "stabilityai/stable-diffusion-2-1-base" --output_path "./model/sd2_1base-fp32" +python conv_sd_to_onnx.py --model_path "stabilityai/stable-diffusion-2-1-base" --output_path "./model/sd2_1base-fp16" --fp16 +``` + +You now have 2 models. These are geared towards creating 512x512 images. + +Now we'll run our test script twice: +``` +python test-txt2img.py --model "model\sd2_1base-fp32" --size 512 --seed 0 +python test-txt2img.py --model "model\sd2_1base-fp16" --size 512 --seed 0 +``` + +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. +The accuracy just shifts things a bit, but it may just as well shift them for the better. + +Next let's do 768x768. This requires your card to have enough VRAM but we'll make a VRAM friendly version too. +Here we aren't bothering with FP32 because it just requires too much VRAM. +``` +python conv_sd_to_onnx.py --model_path "stabilityai/stable-diffusion-2-1" --output_path "./model/sd2_1-fp16" --fp16 +python test-txt2img.py --model "model\sd2_1-fp16" --size 768 --seed 0 +``` + +You should now have a 768x768 picture. + +This will work fine on 12GB VRAM and above but 8GB may already be a stretch. The more VRAM friendly version is next. + +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. +The output will be slightly different but should not be specifically worse. If you got the VRAM, see how well size 1024 works! + +``` +python conv_sd_to_onnx.py --model_path "stabilityai/stable-diffusion-2-1" --output_path "./model/sd2_1-fp16-autoslicing" --fp16 --attention-slicing auto +python test-txt2img.py --model "model\sd2_1-fp16-autoslicing" --size 768 --seed 0 +``` + +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. +First we clone the repository: +``` +git clone https://github.com/Amblyopius/OnnxDiffusersUI +``` +Now we run the UI +``` +python OnnxDiffusersUI\onnxUI.py +``` +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). +If you're done you can go back to the CMD window and press Ctrl+C and it will quit. + +Note that it expects your models to be in the model directory (which is why we put them there in the instructions). +You can find your history and all the pictures you created in the directory called output. + +If you want to learn more about the UI be sure to visit https://github.com/azuritecoin/OnnxDiffusersUI +NOTE: We are using a fork as it simplifies keeping it aligned with our own updates + +## Advanced features +### Support for ControlNet +ControlNet was recently introduced. It allows conditional control on Text-to-Image Diffusion Models. If you want more in-depth information, +get it here: https://github.com/lllyasviel/ControlNet + +As it has now been added to Diffusers I've added a fairly "elegant" ONNX implementation. + +The idea behind the implementation is: +- We use the same single tool to convert models +- We can load the Pipeline from disk by referencing a single model + +This has only 1 downside, it is not the most disk friendly solution as you'll get some duplication. +We may eventually have to opt for a different disk layout for ONNX models. + +The current implementation consists of a simple demo. More to follow soon! + +First let's get ourselves a working model: +``` +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" +``` +This model is an SD 1.5 model combined with Controlnet Canny. Now let's run the test script: +``` +python test-controlnet-canny.py +``` +Once the test is done you'll have an image called controlnet-canny-test.png. +The new image is entirely different but the shape is very similar to the original input image. + +You can look at the test-controlnet-canny.py to see how it works. + +Next we'll use openpose. Note that the example is a demanding pose that you would ordinarily probably not go for. +Without tweaking this also suffers a bit from bad hands/feet. For the sake of the test I decided to tolerate it. +Let's make a ControlNet OpenPose model: +``` +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 +``` +And now let's run the test: +``` +python test-controlnet-openpose.py +``` +This gives you controlnet-openpose-test.png + +As some may wonder where I got the openpose startpoint image from. I used https://zhuyu1997.github.io/open-pose-editor/ +Create the pose. +Press the button underneath height, then download the generated map on the left. +You can further edit it locally to fit the canvas in the way you want it to. + +### Support for Instruct pix2pix +Recently a special Stable Diffusion model was released, allowing you to have AI edit images based on instructions. +Make sure you read the original documentation here: https://www.timothybrooks.com/instruct-pix2pix + +A pipeline was added to diffusers, but currently Huggingface does not add ONNX equivalents. +In this repository I included the required ONNX pipeline and a basic UI (to simplify testing before it gets added to ONNXDiffusersUI) + +You can convert the model using this command (it'll fetch it from huggingface): +``` +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 +``` +Once converted you can run the included UI like this: +``` +python pix2pixUI.py +``` +You'll need an image to start from (you can always create one with Stable Diffusion) and then you can test the pipeline. +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. + +### Use alternative VAE +Some models will suggest using an alternative VAE. +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. +To simplify the task of using an alternative VAE you can now pass it as part of the conversion command. + +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: +``` +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 +``` + +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: +``` +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 +``` + +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: +``` +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 +``` + +### Clip Skip +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. +Therefore there's --clip-skip which you can set to 2, 3 or 4. + +Example: +``` +python conv_sd_to_onnx.py --model_path "Linaqruf/anything-v3.0" --output_path "./model/anythingv3_fp16_cs2" --fp16 --clip-skip 2 +``` + +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. +This ensures that you see similar behaviour to other implementations when setting the same number for Clip Skip. + +### Reducing VRAM usage +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. +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. +You'll bump into VRAM limits when it is limited (8GB or less), or you're trying to use a 768x768 model. + +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: +``` + cputextenc=OnnxRuntimeModel.from_pretrained(args.model+"/text_encoder") + pipe = OnnxStableDiffusionPipeline.from_pretrained(args.model, provider="DmlExecutionProvider", text_encoder=cputextenc) +``` +You can use this in your own code when needed. OnnxDiffusersUI supports --cpu-textenc too. + +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. +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. +**You can pass --cpuvae to test-txt2img.py to load VAE on CPU (this will always also load CLIP on CPU).** +Note that having VAE loaded on CPU is CPU intensive (far more than CLIP is) and you'll see RAM use spike. + +### Conversion of .ckpt / .safetensors +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 +will convert directly from .ckpt to ONNX. + +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. + +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. +To convert a model you'd then do: +``` +python conv_sd_to_onnx.py --model_path ".\downloaded.ckpt" --output_path "./model/downloaded-fp16" --ckpt-original-config-file downloaded.yaml --fp16 +``` +If it did not come with a .yaml config file, try with v1-inference.yaml. + +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. + +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: +``` +python conv_sd_to_onnx.py --help +``` +You should generally not need these but some advanced users may want to have them just in case. + +## FAQ +### Do the converted models work with other ONNX DirectML based implementations? +While not tested extensively: yes they should! They are not full FP16, at the interface level they are the same as FP32. +They are completely valid drop in replacements and transparently run in FP16 on ORT DirectML. +This makes it possible to run both FP16 and FP32 models with the exact same code. + +### Can I convert non-official models? +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. +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. + +### Does this work for inpainting / img2img? +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. +Additional example scripts may be added in the future to demonstrate inpainting in code. For now mainly useful for use with OnnxDiffusersUI + +### Why is Euler Ancestral not giving me the same image if I provide a seed? +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. +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. +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. + +### This is still too slow / taxing on my VRAM +Make sure to close as many applications as possible when running FP32 or 768x768 FP16 models. +On my 6700XT I can do 768x768 at 1.2s/it but only if I close all applications. +If I don't close enough applications, it very quickly goes beyond 2s/it. + +Also consider following https://github.com/nod-ai/SHARK which provides accelerated ML on AMD via MLIR/IREE. +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. +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!) +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. + +If you are an advanced AMD user, switch to Linux+ROCm. It'll be faster and you can use any torch based solution directly. + +### Can you share any results? +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 +Reported working for Vega56 and doing 512x512 at 1.75it/s +Reported working for RX 480 8GB and doing 512x512 at 1.75s/it +Reported working for 5600XT 6GB and doing 512x512 at 1.43s/it (about 4x times faster than using ONNX FP32) + +### All these model downloads seem to be eating my main drive's disk space?! +This is an unfortunate side effect of where the huggingface library stores its cache by default. +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. +Point an environment variable HF_HOME towards where you want to have it store things instead. +(You can probably move the existing directory to a different drive and point HF_HOME towards it but I have not tested this ...) +Once resolved you can remove the huggingface directory from .cache diff --git a/patchedstabledifftoonnx/README4GB.md b/patchedstabledifftoonnx/README4GB.md new file mode 100644 index 0000000000000000000000000000000000000000..364bdb5d94b1666aba5450be9daedbb4cb99feeb --- /dev/null +++ b/patchedstabledifftoonnx/README4GB.md @@ -0,0 +1,136 @@ +# Stable Diffusion using ONNX, FP16 and DirectML + +This repository contains a conversion tool, some examples, and instructions on how to set up Stable Diffusion with ONNX models. + +**These instructions are specifically for people who have only 4GB VRAM** + +It's all fairly straightforward, but It helps to be comfortable with command line. + +We'll focus on making all of it work within limited VRAM. This will still include a UI. + +## Set up + +First make sure you have Python 3.10 or 3.11 installed. You can get it here: https://www.python.org/downloads/ + +If you don't have git, get it here: https://gitforwindows.org/ + +Pick a directory that can contain your Stable Diffusion installation (make sure you've the diskspace to store the models). +Open the commandline (Powershell or Command Prompt) and change into the directory you will use. + +Start by cloning this repository: +``` +git clone https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16 +cd Stable-Diffusion-ONNX-FP16 +``` + +Do the following: +``` +pip install virtualenv +python -m venv sd_env +sd_env\scripts\activate +python -m pip install --upgrade pip +pip install torch --extra-index-url https://download.pytorch.org/whl/nightly/cpu --pre +pip install -r requirements.txt +``` + +Now first make sure you have an account on https://huggingface.co/ +When you do make sure to create a token on https://huggingface.co/settings/tokens +And then on the commandline login using following command +``` +huggingface-cli login +``` + +Now you're ready to download and convert models. Before we explain this, just a pointer on future use. +Whenever you want to make use of this post set up, open a command line, change into the directory and enable the environment. +Say that you installed this on your D: drive in the root. You would open command line and then: +``` +d: +cd Stable-Diffusion-ONNX-FP16 +sd_env\scripts\activate +``` + +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! +The extra time spend on creating the model is saved back by having it run fine on 4GB VRAM. +``` +mkdir model +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 +``` + +That's your first model. Let's do a test: + +``` +python test-txt2img.py --model "model\sd2_1base-fp16-maxslicing" --size 512 --seed 0 --cpu-textenc --cpuvae +``` + +You should now have your first picture in the current directory. + +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. +First we clone the repository: +``` +git clone https://github.com/Amblyopius/OnnxDiffusersUI +``` +Now we run the UI +``` +python OnnxDiffusersUI\onnxUI.py --cpu-textenc --cpu-vaedec +``` +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). +If you're done you can go back to the CMD window and press Ctrl+C and it will quit. + +Note that it expects your models to be in the model directory (which is why we put them there in the instructions). +You can find your history and all the pictures you created in the directory called output. + +If you want to learn more about the UI be sure to visit https://github.com/azuritecoin/OnnxDiffusersUI + +## Advanced features +### Use alternative VAE +Some models will suggest using an alternative VAE. +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. +To simplify the task of using an alternative VAE you can now pass it as part of the conversion command. + +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: +``` +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 +``` + +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: +``` +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 +``` + +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: +``` +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 +``` + +### Clip Skip +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. +Therefore there's --clip-skip which you can set to 2, 3 or 4. + +Example: +``` +python conv_sd_to_onnx.py --model_path "Linaqruf/anything-v3.0" --output_path "./model/anythingv3_fp16_cs2" --fp16 --clip-skip 2 +``` + +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. +This ensures that you see similar behaviour to other implementations when setting the same number for Clip Skip. + +### Conversion of .ckpt / .safetensors +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 +will convert directly from .ckpt to ONNX. + +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. + +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. +To convert a model you'd then do: +``` +python conv_sd_to_onnx.py --model_path ".\downloaded.ckpt" --output_path "./model/downloaded-fp16" --ckpt-original-config-file downloaded.yaml --fp16 +``` +If it did not come with a .yaml config file, try with v1-inference.yaml. + +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. + +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: +``` +python conv_sd_to_onnx.py --help +``` +You should generally not need these but some advanced users may want to have them just in case. diff --git a/patchedstabledifftoonnx/conv_sd_to_onnx.py b/patchedstabledifftoonnx/conv_sd_to_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..a04732f2714de6eb7f0163eaecaa4d79751f14d8 --- /dev/null +++ b/patchedstabledifftoonnx/conv_sd_to_onnx.py @@ -0,0 +1,658 @@ + +# Copyright 2022 Dirk Moerenhout. All rights reserved. +# +# This program is free software: you can redistribute it and/or modify it under the terms +# of the GNU General Public License as published by the Free Software Foundation, +# either version 3 of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. If not, +# see . +# +# ***** +# NOTE this was originally derived from: +# https://github.com/huggingface/diffusers/blob/main/scripts/convert_stable_diffusion_checkpoint_to_onnx.py +# +# Original file released under Apache License, Version 2.0 +# ***** +# +# Version history +# v1.2 First fully working version converting unet to fp16 +# v2.0 Refactored + enabled conversion to fp16 for Text Encoder +# v2.1 Support for safetensors +# v2.2 Reduce visible warnings +# v3.0 You can now provide an alternative VAE +# v3.1 Align with diffusers 0.12.0 +# v4.0 Support ckpt conversion (--> renamed to conv_sd_to_onnx.py) +# v5.0 Use ONNX Runtime Transformers for model optimisation +# v6.0 Support ControlNet +# v6.1 Support for diffusers 0.15.0 + +import warnings +import argparse +import os +import shutil +from pathlib import Path +import json +import tempfile +from typing import Union, Optional, Tuple + +import torch +from torch.onnx import export +import safetensors + +import onnx +from onnxruntime.transformers.float16 import convert_float_to_float16 +from diffusers.models import AutoencoderKL +from diffusers import ( + OnnxRuntimeModel, + OnnxStableDiffusionPipeline, + StableDiffusionPipeline, + ControlNetModel, + UNet2DConditionModel +) +from diffusers.models.attention_processor import AttnProcessor +from diffusers.models.unet_2d_condition import UNet2DConditionOutput +from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt + +# To improve future development and testing, warnings should be limited to what is somewhat useful +# Truncation warnings are expected as part of FP16 conversion and should not be shown +warnings.filterwarnings('ignore','.*will be truncated.*') +# We are ignoring prim::Constant type related warnings +warnings.filterwarnings('ignore','.*The shape inference of prim::Constant type is missing.*') + +# ONNX Runtime Transformers offers ONNX model optimisation +# It does not directly support DirectML but we can use a custom class +# Based on onnx_model_unet.py in ONNX Runtime Transformers +from onnx import ModelProto +from onnxruntime.transformers.onnx_model_unet import UnetOnnxModel + +class UnetOnnxModelDML(UnetOnnxModel): + def __init__(self, model: ModelProto, num_heads: int = 0, hidden_size: int = 0): + """Initialize UNet ONNX Model. + + Args: + model (ModelProto): the ONNX model + num_heads (int, optional): number of attention heads. Defaults to 0 (detect the parameter automatically). + hidden_size (int, optional): hidden dimension. Defaults to 0 (detect the parameter automatically). + """ + assert (num_heads == 0 and hidden_size == 0) or (num_heads > 0 and hidden_size % num_heads == 0) + + super().__init__(model, num_heads=num_heads, hidden_size=hidden_size) + + def optimize(self, enable_shape_inference=False): + if not enable_shape_inference: + self.disable_shape_inference() + self.fuse_layer_norm() + self.preprocess() + self.postprocess() + +# We need a wrapper for UNet2DConditionModel as we need to pass tuples +# We can't properly export tuples of Tensors with ONNX + +class UNet2DConditionModel_Cnet(UNet2DConditionModel): + def forward( + self, + sample: torch.FloatTensor, + timestep: Union[torch.Tensor, float, int], + encoder_hidden_states: torch.Tensor, + down_block_add_res00: Optional[torch.Tensor] = None, + down_block_add_res01: Optional[torch.Tensor] = None, + down_block_add_res02: Optional[torch.Tensor] = None, + down_block_add_res03: Optional[torch.Tensor] = None, + down_block_add_res04: Optional[torch.Tensor] = None, + down_block_add_res05: Optional[torch.Tensor] = None, + down_block_add_res06: Optional[torch.Tensor] = None, + down_block_add_res07: Optional[torch.Tensor] = None, + down_block_add_res08: Optional[torch.Tensor] = None, + down_block_add_res09: Optional[torch.Tensor] = None, + down_block_add_res10: Optional[torch.Tensor] = None, + down_block_add_res11: Optional[torch.Tensor] = None, + mid_block_additional_residual: Optional[torch.Tensor] = None, + return_dict: bool = False, + ) -> Union[UNet2DConditionOutput, Tuple]: + down_block_add_res = ( + down_block_add_res00, down_block_add_res01, down_block_add_res02, + down_block_add_res03, down_block_add_res04, down_block_add_res05, + down_block_add_res06, down_block_add_res07, down_block_add_res08, + down_block_add_res09, down_block_add_res10, down_block_add_res11) + return super().forward( + sample = sample, + timestep = timestep, + encoder_hidden_states = encoder_hidden_states, + down_block_additional_residuals = down_block_add_res, + mid_block_additional_residual = mid_block_additional_residual, + return_dict = return_dict + ) + +def onnx_export( + model, + model_args: tuple, + output_path: Path, + ordered_input_names, + output_names, + dynamic_axes, + opset, +): + '''export a PyTorch model as an ONNX model''' + output_path.parent.mkdir(parents=True, exist_ok=True) + export( + model, + model_args, + f=output_path.as_posix(), + input_names=ordered_input_names, + output_names=output_names, + dynamic_axes=dynamic_axes, + do_constant_folding=True, + opset_version=opset, + ) + +@torch.no_grad() +def convert_to_fp16( + model_path +): + '''Converts an ONNX model on disk to FP16''' + model_dir=os.path.dirname(model_path) + # Breaking down in steps due to Windows bug in convert_float_to_float16_model_path + onnx.shape_inference.infer_shapes_path(model_path) + fp16_model = onnx.load(model_path) + fp16_model = convert_float_to_float16( + fp16_model, keep_io_types=True, disable_shape_infer=True + ) + # clean up existing tensor files + shutil.rmtree(model_dir) + os.mkdir(model_dir) + # save FP16 model + onnx.save(fp16_model, model_path) + +@torch.no_grad() +def convert_models(pipeline: StableDiffusionPipeline, + output_path: str, + opset: int, + fp16: bool, + notune: bool, + controlnet_path: str, + attention_slicing: str): + '''Converts the individual models in a path (UNET, VAE ...) to ONNX''' + + output_path = Path(output_path) + + # TEXT ENCODER + num_tokens = pipeline.text_encoder.config.max_position_embeddings + text_hidden_size = pipeline.text_encoder.config.hidden_size + text_input = pipeline.tokenizer( + "A sample prompt", + padding="max_length", + max_length=pipeline.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + textenc_path=output_path / "text_encoder" / "model.onnx" + onnx_export( + pipeline.text_encoder, + # casting to torch.int32 https://github.com/huggingface/transformers/pull/18515/files + model_args=(text_input.input_ids.to(device=device, dtype=torch.int32)), + output_path=textenc_path, + ordered_input_names=["input_ids"], + output_names=["last_hidden_state", "pooler_output"], + dynamic_axes={ + "input_ids": {0: "batch", 1: "sequence"}, + }, + opset=opset, + ) + if fp16: + textenc_model_path = str(textenc_path.absolute().as_posix()) + convert_to_fp16(textenc_model_path) + + # UNET + unet_in_channels = pipeline.unet.config.in_channels + unet_sample_size = pipeline.unet.config.sample_size + unet_path = output_path / "unet" / "model.onnx" + if controlnet_path: + # reload UNET to get an ONNX exportable version with ControlNet support + with tempfile.TemporaryDirectory() as tmpdirname: + pl.unet.save_pretrained(tmpdirname) + controlnet_unet=UNet2DConditionModel_Cnet.from_pretrained(tmpdirname, + low_cpu_mem_usage=False) + + controlnet_unet.set_attn_processor(AttnProcessor()) + + if attention_slicing: + pl.enable_attention_slicing(attention_slicing) + controlnet_unet.set_attention_slice(attention_slicing) + + onnx_export( + controlnet_unet, + model_args=( + torch.randn(2, unet_in_channels, unet_sample_size, + unet_sample_size).to(device=device, dtype=dtype), + torch.randn(2).to(device=device, dtype=dtype), + torch.randn(2, num_tokens, text_hidden_size).to(device=device, dtype=dtype), + torch.randn(2, 320, unet_sample_size, unet_sample_size).to(device=device, dtype=dtype), + torch.randn(2, 320, unet_sample_size, unet_sample_size).to(device=device, dtype=dtype), + torch.randn(2, 320, unet_sample_size, unet_sample_size).to(device=device, dtype=dtype), + torch.randn(2, 320, unet_sample_size//2,unet_sample_size//2).to(device=device, dtype=dtype), + torch.randn(2, 640, unet_sample_size//2,unet_sample_size//2).to(device=device, dtype=dtype), + torch.randn(2, 640, unet_sample_size//2,unet_sample_size//2).to(device=device, dtype=dtype), + torch.randn(2, 640, unet_sample_size//4,unet_sample_size//4).to(device=device, dtype=dtype), + torch.randn(2, 1280, unet_sample_size//4,unet_sample_size//4).to(device=device, dtype=dtype), + torch.randn(2, 1280, unet_sample_size//4,unet_sample_size//4).to(device=device, dtype=dtype), + torch.randn(2, 1280, unet_sample_size//8,unet_sample_size//8).to(device=device, dtype=dtype), + torch.randn(2, 1280, unet_sample_size//8,unet_sample_size//8).to(device=device, dtype=dtype), + torch.randn(2, 1280, unet_sample_size//8,unet_sample_size//8).to(device=device, dtype=dtype), + torch.randn(2, 1280, unet_sample_size//8,unet_sample_size//8).to(device=device, dtype=dtype), + False, + ), + output_path=unet_path, + ordered_input_names=[ + "sample", + "timestep", + "encoder_hidden_states", + "down_block_0", + "down_block_1", + "down_block_2", + "down_block_3", + "down_block_4", + "down_block_5", + "down_block_6", + "down_block_7", + "down_block_8", + "down_block_9", + "down_block_10", + "down_block_11", + "mid_block_additional_residual", + "return_dict" + ], + output_names=["out_sample"], # has to be different from "sample" for correct tracing + dynamic_axes={ + "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, + "timestep": {0: "batch"}, + "encoder_hidden_states": {0: "batch", 1: "sequence"}, + "down_block_0": {0: "batch", 2: "height", 3: "width"}, + "down_block_1": {0: "batch", 2: "height", 3: "width"}, + "down_block_2": {0: "batch", 2: "height", 3: "width"}, + "down_block_3": {0: "batch", 2: "height2", 3: "width2"}, + "down_block_4": {0: "batch", 2: "height2", 3: "width2"}, + "down_block_5": {0: "batch", 2: "height2", 3: "width2"}, + "down_block_6": {0: "batch", 2: "height4", 3: "width4"}, + "down_block_7": {0: "batch", 2: "height4", 3: "width4"}, + "down_block_8": {0: "batch", 2: "height4", 3: "width4"}, + "down_block_9": {0: "batch", 2: "height8", 3: "width8"}, + "down_block_10": {0: "batch", 2: "height8", 3: "width8"}, + "down_block_11": {0: "batch", 2: "height8", 3: "width8"}, + "mid_block_additional_residual": {0: "batch", 2: "height8", 3: "width8"}, + }, + opset=opset, + ) + + controlnet = ControlNetModel.from_pretrained(args.controlnet_path, low_cpu_mem_usage=False) + if attention_slicing: + controlnet.set_attention_slice(attention_slicing) + cnet_path = output_path / "controlnet" / "model.onnx" + onnx_export( + controlnet, + model_args=( + torch.randn(2, 4, 64, 64).to(device=device, dtype=dtype), + torch.randn(2).to(device=device, dtype=torch.int32), + torch.randn(2, 77, 768).to(device=device, dtype=dtype), + torch.randn(2, 3, 512,512).to(device=device, dtype=dtype), + False, + ), + output_path=cnet_path, + ordered_input_names=["sample", "timestep", "encoder_hidden_states", "controlnet_cond","return_dict"], + output_names=["down_block_res_samples", "mid_block_res_sample"], + dynamic_axes={ + "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, + "timestep": {0: "batch"}, + "encoder_hidden_states": {0: "batch", 1: "sequence"}, + "controlnet_cond": {0: "batch", 2: "height", 3: "width"} + }, + opset=opset, + ) + + if fp16: + cnet_path_model_path = str(cnet_path.absolute().as_posix()) + convert_to_fp16(cnet_path_model_path) + + else: + onnx_export( + pipeline.unet, + model_args=( + torch.randn(2, unet_in_channels, unet_sample_size, + unet_sample_size).to(device=device, dtype=dtype), + torch.randn(2).to(device=device, dtype=torch.int32), + torch.randn(2, num_tokens, text_hidden_size).to(device=device, dtype=dtype), + False, + ), + output_path=unet_path, + ordered_input_names=["sample", "timestep", "encoder_hidden_states", "return_dict"], + output_names=["out_sample"], # has to be different from "sample" for correct tracing + dynamic_axes={ + "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, + "timestep": {0: "batch"}, + "encoder_hidden_states": {0: "batch", 1: "sequence"}, + }, + opset=opset, + ) + del pipeline.unet + + unet_model_path = str(unet_path.absolute().as_posix()) + unet_dir = os.path.dirname(unet_model_path) + unet = onnx.load(unet_model_path) + # clean up existing tensor files + shutil.rmtree(unet_dir) + os.mkdir(unet_dir) + + optimizer = UnetOnnxModelDML(unet, 0, 0) + if not notune: + optimizer.optimize() + optimizer.topological_sort() + + # collate external tensor files into one + onnx.save_model( + optimizer.model, + unet_model_path, + save_as_external_data=True, + all_tensors_to_one_file=True, + location="weights.pb", + convert_attribute=False, + ) + if fp16: + convert_to_fp16(unet_model_path) + del unet, optimizer + + # VAE ENCODER + vae_encoder = pipeline.vae + vae_in_channels = vae_encoder.config.in_channels + vae_sample_size = vae_encoder.config.sample_size + # need to get the raw tensor output (sample) from the encoder + vae_encoder.forward = lambda sample, return_dict: vae_encoder.encode(sample, + return_dict)[0].sample() + onnx_export( + vae_encoder, + model_args=( + torch.randn(1, vae_in_channels, vae_sample_size, + vae_sample_size).to(device=device, dtype=dtype), + False, + ), + output_path=output_path / "vae_encoder" / "model.onnx", + ordered_input_names=["sample", "return_dict"], + output_names=["latent_sample"], + dynamic_axes={ + "sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, + }, + opset=opset, + ) + + # VAE DECODER + vae_decoder = pipeline.vae + vae_latent_channels = vae_decoder.config.latent_channels + vae_out_channels = vae_decoder.config.out_channels + # forward only through the decoder part + vae_decoder.forward = vae_encoder.decode + onnx_export( + vae_decoder, + model_args=( + torch.randn(1, vae_latent_channels, unet_sample_size, + unet_sample_size).to(device=device, dtype=dtype), + False, + ), + output_path=output_path / "vae_decoder" / "model.onnx", + ordered_input_names=["latent_sample", "return_dict"], + output_names=["sample"], + dynamic_axes={ + "latent_sample": {0: "batch", 1: "channels", 2: "height", 3: "width"}, + }, + opset=opset, + ) + del pipeline.vae + + # SAFETY CHECKER + # NOTE: + # Safety checker is excluded because it is a resource hog and you'd be turning it off anyway + # I'm not a legal expert but IMHO you are still bound by the model's license after conversion + # Check the license of the model you are converting and abide by it + + safety_checker = None + feature_extractor = None + + onnx_pipeline = OnnxStableDiffusionPipeline( + vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_encoder", + low_cpu_mem_usage=False), + vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / "vae_decoder", + low_cpu_mem_usage=False), + text_encoder=OnnxRuntimeModel.from_pretrained(output_path / "text_encoder", + low_cpu_mem_usage=False), + tokenizer=pipeline.tokenizer, + unet=OnnxRuntimeModel.from_pretrained(output_path / "unet",low_cpu_mem_usage=False), + scheduler=pipeline.scheduler, + safety_checker=safety_checker, + feature_extractor=feature_extractor, + requires_safety_checker=safety_checker is not None, + ) + + onnx_pipeline.save_pretrained(output_path) + + if controlnet_path: + confname=f"{output_path}/model_index.json" + with open(confname, 'r', encoding="utf-8") as f: + modelconf = json.load(f) + modelconf['controlnet'] = ("diffusers","OnnxRuntimeModel") + with open(confname, 'w', encoding="utf-8") as f: + json.dump(modelconf, f, indent=1) + + print("ONNX pipeline saved to", output_path) + + del pipeline + del onnx_pipeline + _ = OnnxStableDiffusionPipeline.from_pretrained(output_path, + provider="DmlExecutionProvider", + low_cpu_mem_usage=False) + print("ONNX pipeline is loadable") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + parser.add_argument( + "--model_path", + default="D:/cache/chilloutmix_NiPrunedFp32Fix.safetensors", + type=str, + required=False, + help=( + "Path to the `diffusers` checkpoint to convert (either local directory or on the Hub). " + "Or the path to a local checkpoint saved in .ckpt or .safetensors." + ) + ) + + parser.add_argument( + "--output_path", + default="D:/source-fp32", + type=str, + required=False, + help="Path to the output model." + ) + + parser.add_argument( + "--vae_path", + default=None, + type=str, + help=( + "Path to alternate VAE `diffusers` checkpoint (either local or on the Hub). " + ) + ) + + parser.add_argument( + "--controlnet_path", + default=None, + type=str, + help=( + "Path to controlnet model to import and convert (either local or on the Hub). " + "Setting this results in an SD model intended to be used with a specific ControlNet" + ) + ) + + parser.add_argument( + "--opset", + default=15, + type=int, + help="The version of the ONNX operator set to use.", + ) + + parser.add_argument( + "--fp16", + action="store_true", + help="Export Text Encoder and UNET in mixed `float16` mode" + ) + + parser.add_argument( + "--notune", + action="store_true", + help="Turn off tuning UNET with ONNX Runtime Transformers" + ) + + parser.add_argument( + "--attention-slicing", + choices={"auto","max"}, + type=str, + help=( + "Attention slicing reduces VRAM needed, off by default. Set to auto or max. " + "WARNING: max implies --notune" + ) + ) + + parser.add_argument( + "--clip-skip", + choices={2,3,4}, + type=int, + help="Add permanent clip skip to ONNX model." + ) + + parser.add_argument( + "--diffusers-output", + type=str, + help="Directory to dump a pre-conversion copy in diffusers format in." + ) + + parser.add_argument( + "--ckpt-original-config-file", + default="D:/python/diffusion-convert-FP/v1-inference.yaml", + type=str, + help="The YAML config file corresponding to the original architecture." + ) + + parser.add_argument( + "--ckpt-image-size", + default=None, + type=int, + help="The image size that the model was trained on. Typically 512 or 768" + ) + + parser.add_argument( + "--ckpt-prediction_type", + default=None, + type=str, + help=( + "Prediction type the model was trained on. " + "'epsilon' for SD v1.X and SD v2 Base, 'v-prediction' for SD v2" + ) + ) + + parser.add_argument( + "--ckpt-pipeline_type", + default=None, + type=str, + help="The pipeline type. If `None` pipeline will be automatically inferred." + ) + + parser.add_argument( + "--ckpt-extract-ema", + action="store_true", + help=( + "Only relevant for checkpoints that have both EMA and non-EMA weights. " + "If set enables extraction of EMA weights (Default is non-EMA). " + "EMA weights usually yield higher quality images for inference. " + "Non-EMA weights are usually better to continue fine-tuning." + ) + ) + + parser.add_argument( + "--ckpt-num-in-channels", + default=None, + type=int, + help=( + "The number of input channels. " + "If `None` number of input channels will be automatically inferred." + ) + ) + + parser.add_argument( + "--ckpt-upcast-attention", + action="store_true", + help=( + "Whether the attention computation should always be upcasted. " + "Necessary when running SD 2.1" + ) + ) + + args = parser.parse_args() + + dtype=torch.float32 + device = "cpu" + if args.model_path.endswith(".ckpt") or args.model_path.endswith(".safetensors"): + pl = download_from_original_stable_diffusion_ckpt( + checkpoint_path=args.model_path, + original_config_file=args.ckpt_original_config_file, + image_size=args.ckpt_image_size, + prediction_type=args.ckpt_prediction_type, + model_type=args.ckpt_pipeline_type, + extract_ema=args.ckpt_extract_ema, + scheduler_type="pndm", + num_in_channels=args.ckpt_num_in_channels, + upcast_attention=args.ckpt_upcast_attention, + from_safetensors=args.model_path.endswith(".safetensors") + ) + else: + pl = StableDiffusionPipeline.from_pretrained(args.model_path, + torch_dtype=dtype,low_cpu_mem_usage=False).to(device) + + if args.vae_path: + with tempfile.TemporaryDirectory() as tmpdirname: + pl.save_pretrained(tmpdirname) + if args.vae_path.endswith('/vae'): + vae = AutoencoderKL.from_pretrained(args.vae_path[:-4],subfolder='vae', + low_cpu_mem_usage=False) + else: + vae = AutoencoderKL.from_pretrained(args.vae_path,low_cpu_mem_usage=False) + pl = StableDiffusionPipeline.from_pretrained(tmpdirname, + torch_dtype=dtype, vae=vae,low_cpu_mem_usage=False).to(device) + + if args.clip_skip: + with tempfile.TemporaryDirectory() as tmpdirname: + pl.save_pretrained(tmpdirname) + confname=f"{tmpdirname}/text_encoder/config.json" + with open(confname, 'r', encoding="utf-8") as f: + clipconf = json.load(f) + clipconf['num_hidden_layers'] = clipconf['num_hidden_layers']-args.clip_skip+1 + with open(confname, 'w', encoding="utf-8") as f: + json.dump(clipconf, f, indent=1) + pl = StableDiffusionPipeline.from_pretrained(tmpdirname, + torch_dtype=dtype,low_cpu_mem_usage=False).to(device) + + pl.unet.set_attn_processor(AttnProcessor()) + + blocktune=False + if args.attention_slicing: + if args.attention_slicing == "max": + blocktune=True + print ("WARNING: attention_slicing max implies --notune") + pl.enable_attention_slicing(args.attention_slicing) + + if args.diffusers_output: + pl.save_pretrained(args.diffusers_output) + + #convert_models(pl, args.output_path,args.opset,args.fp16,args.notune or blocktune,args.controlnet_path,args.attention_slicing) + convert_models(pl, args.output_path, args.opset, False, args.notune or blocktune, args.controlnet_path,args.attention_slicing) diff --git a/patchedstabledifftoonnx/dance_pose.png b/patchedstabledifftoonnx/dance_pose.png new file mode 100644 index 0000000000000000000000000000000000000000..9f79b53304ca26af80878a7c178a0db33cedbd72 Binary files /dev/null and b/patchedstabledifftoonnx/dance_pose.png differ diff --git a/patchedstabledifftoonnx/input_image_vermeer.png b/patchedstabledifftoonnx/input_image_vermeer.png new file mode 100644 index 0000000000000000000000000000000000000000..6cf55c251f4df73027e18bab82ef5ed4c554a7c8 Binary files /dev/null and b/patchedstabledifftoonnx/input_image_vermeer.png differ diff --git a/patchedstabledifftoonnx/pipeline_onnx_stable_diffusion_controlnet.py b/patchedstabledifftoonnx/pipeline_onnx_stable_diffusion_controlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..8d67b20e38ef2f90c0b36d8ceac3e53f24cd0833 --- /dev/null +++ b/patchedstabledifftoonnx/pipeline_onnx_stable_diffusion_controlnet.py @@ -0,0 +1,472 @@ +# Copyright 2023 The HuggingFace Team. +# Converted for use with ONNX as part of https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16 +# Special thanks to https://github.com/uchuusen for the initial conversion effort + +import inspect +from typing import Callable, List, Optional, Union + +import numpy as np +import torch +import PIL +from transformers import CLIPFeatureExtractor, CLIPTokenizer + +from diffusers.configuration_utils import FrozenDict +from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler +from diffusers.utils import deprecate, logging, PIL_INTERPOLATION +from diffusers.pipelines.onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel +from diffusers.pipeline_utils import DiffusionPipeline +from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput + + +logger = logging.get_logger(__name__) + + +class OnnxStableDiffusionControlNetPipeline(DiffusionPipeline): + vae_encoder: OnnxRuntimeModel + vae_decoder: OnnxRuntimeModel + text_encoder: OnnxRuntimeModel + tokenizer: CLIPTokenizer + unet: OnnxRuntimeModel + controlnet: OnnxRuntimeModel + scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] + safety_checker: OnnxRuntimeModel + feature_extractor: CLIPFeatureExtractor + + _optional_components = ["safety_checker", "feature_extractor"] + + def __init__( + self, + vae_encoder: OnnxRuntimeModel, + vae_decoder: OnnxRuntimeModel, + text_encoder: OnnxRuntimeModel, + tokenizer: CLIPTokenizer, + unet: OnnxRuntimeModel, + controlnet: OnnxRuntimeModel, + scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler], + safety_checker: OnnxRuntimeModel, + feature_extractor: CLIPFeatureExtractor, + requires_safety_checker: bool = True, + ): + super().__init__() + + if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1: + deprecation_message = ( + f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" + f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " + "to update the config accordingly as leaving `steps_offset` might led to incorrect results" + " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," + " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" + " file" + ) + deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False) + new_config = dict(scheduler.config) + new_config["steps_offset"] = 1 + scheduler._internal_dict = FrozenDict(new_config) + + if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True: + deprecation_message = ( + f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`." + " `clip_sample` should be set to False in the configuration file. Please make sure to update the" + " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in" + " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very" + " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file" + ) + deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False) + new_config = dict(scheduler.config) + new_config["clip_sample"] = False + scheduler._internal_dict = FrozenDict(new_config) + + if safety_checker is None and requires_safety_checker: + logger.warning( + f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" + " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" + " results in services or applications open to the public. Both the diffusers team and Hugging Face" + " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" + " it only for use-cases that involve analyzing network behavior or auditing its results. For more" + " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." + ) + + if safety_checker is not None and feature_extractor is None: + raise ValueError( + "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" + " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." + ) + + self.register_modules( + vae_encoder=vae_encoder, + vae_decoder=vae_decoder, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + controlnet=controlnet, + scheduler=scheduler, + safety_checker=safety_checker, + feature_extractor=feature_extractor, + ) + self.register_to_config(requires_safety_checker=requires_safety_checker) + + + def _default_height_width(self, height, width, image): + if isinstance(image, list): + image = image[0] + + if height is None: + if isinstance(image, PIL.Image.Image): + height = image.height + elif isinstance(image, np.ndarray): + height = image.shape[3] + + height = (height // 8) * 8 # round down to nearest multiple of 8 + + if width is None: + if isinstance(image, PIL.Image.Image): + width = image.width + elif isinstance(image, np.ndarray): + width = image.shape[2] + + width = (width // 8) * 8 # round down to nearest multiple of 8 + + return height, width + + def prepare_image(self, image, width, height, batch_size, num_images_per_prompt, dtype): + if not isinstance(image, np.ndarray): + if isinstance(image, PIL.Image.Image): + image = [image] + + if isinstance(image[0], PIL.Image.Image): + image = [ + np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image + ] + image = np.concatenate(image, axis=0) + image = np.array(image).astype(np.float32) / 255.0 + image = image.transpose(0, 3, 1, 2) + image = torch.from_numpy(image) + elif isinstance(image[0], np.ndarray): + image = np.concatenate(image, axis=0) + image = torch.from_numpy(image) + + image_batch_size = image.shape[0] + + if image_batch_size == 1: + repeat_by = batch_size + else: + # image batch size is the same as prompt batch size + repeat_by = num_images_per_prompt + + image = image.repeat_interleave(repeat_by, dim=0) + + return image + + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents + def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, generator, latents=None): + shape = (batch_size, num_channels_latents, height // 8, width // 8) + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + if latents is None: + latents = generator.randn(*shape).astype(dtype) + + + # scale the initial noise by the standard deviation required by the scheduler + latents = latents * self.scheduler.init_noise_sigma + return latents + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs + def prepare_extra_step_kwargs(self, generator, eta, torch_gen): + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 + # and should be between [0, 1] + + accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) + extra_step_kwargs = {} + if accepts_eta: + extra_step_kwargs["eta"] = eta + + # check if the scheduler accepts generator + accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) + if accepts_generator: + extra_step_kwargs["generator"] = torch_gen + return extra_step_kwargs + + def _encode_prompt(self, prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`): + prompt to be encoded + num_images_per_prompt (`int`): + number of images that should be generated per prompt + do_classifier_free_guidance (`bool`): + whether to use classifier free guidance or not + negative_prompt (`str` or `List[str]`): + 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`). + """ + batch_size = len(prompt) if isinstance(prompt, list) else 1 + + # get prompt text embeddings + text_inputs = self.tokenizer( + prompt, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="np", + ) + text_input_ids = text_inputs.input_ids + untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids + + if not np.array_equal(text_input_ids, untruncated_ids): + removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) + logger.warning( + "The following part of your input was truncated because CLIP can only handle sequences up to" + f" {self.tokenizer.model_max_length} tokens: {removed_text}" + ) + + prompt_embeds = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0] + prompt_embeds = np.repeat(prompt_embeds, num_images_per_prompt, axis=0) + + # get unconditional embeddings for classifier free guidance + if do_classifier_free_guidance: + uncond_tokens: List[str] + if negative_prompt is None: + uncond_tokens = [""] * batch_size + elif type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif isinstance(negative_prompt, str): + uncond_tokens = [negative_prompt] * batch_size + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + else: + uncond_tokens = negative_prompt + + max_length = text_input_ids.shape[-1] + uncond_input = self.tokenizer( + uncond_tokens, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="np", + ) + negative_prompt_embeds = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0] + negative_prompt_embeds = np.repeat(negative_prompt_embeds, num_images_per_prompt, axis=0) + + # For classifier free guidance, we need to do two forward passes. + # Here we concatenate the unconditional and text embeddings into a single batch + # to avoid doing two forward passes + prompt_embeds = np.concatenate([negative_prompt_embeds, prompt_embeds]) + + return prompt_embeds + + def __call__( + self, + prompt: Union[str, List[str]], + image: Union[np.ndarray, PIL.Image.Image] = None, + height: Optional[int] = None, + width: Optional[int] = None, + num_inference_steps: Optional[int] = 50, + guidance_scale: Optional[float] = 7.5, + negative_prompt: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: Optional[float] = 0.0, + generator: Optional[np.random.RandomState] = None, + latents: Optional[np.ndarray] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, np.ndarray], None]] = None, + callback_steps: int = 1, + controlnet_conditioning_scale: float = 1.0, + ): + if isinstance(prompt, str): + batch_size = 1 + elif isinstance(prompt, list): + batch_size = len(prompt) + else: + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + + if generator: + torch_seed = generator.randint(2147483647) + torch_gen = torch.Generator().manual_seed(torch_seed) + else: + generator = np.random + torch_gen = None + + height, width = self._default_height_width(height, width, image) + + if height % 8 != 0 or width % 8 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") + + if (callback_steps is None) or ( + callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) + ): + raise ValueError( + f"`callback_steps` has to be a positive integer but is {callback_steps} of type" + f" {type(callback_steps)}." + ) + + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + prompt_embeds = self._encode_prompt( + prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt + ) + + # 4. Prepare image + image = self.prepare_image( + image, + width, + height, + batch_size * num_images_per_prompt, + num_images_per_prompt, + np.float32, + ).numpy() + + if do_classifier_free_guidance: + image = np.concatenate([image] * 2) + + # get the initial random noise unless the user supplied it + latents_dtype = prompt_embeds.dtype + latents_shape = (batch_size * num_images_per_prompt, 4, height // 8, width // 8) + + num_channels_latents = 4 + latents = self.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + latents_dtype, + generator, + latents, + ) + + # set timesteps + self.scheduler.set_timesteps(num_inference_steps) + timesteps = self.scheduler.timesteps + + + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 + # and should be between [0, 1] + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta, torch_gen) + + timestep_dtype = next( + (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)" + ) + timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype] + + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + + with self.progress_bar(total=num_inference_steps) as progress_bar: + for i, t in enumerate(timesteps): + # expand the latents if we are doing classifier free guidance + latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents + latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t) + latent_model_input = latent_model_input.cpu().numpy() + + timestep = np.array([t], dtype=timestep_dtype) + + blocksamples = self.controlnet( + sample=latent_model_input, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + controlnet_cond=image, + conditioning_scale=1.0 + ) + + mid_block_res_sample=blocksamples[12] + down_block_res_samples=blocksamples[0:12] + + down_block_res_samples = [ + down_block_res_sample * controlnet_conditioning_scale + for down_block_res_sample in down_block_res_samples + ] + mid_block_res_sample *= controlnet_conditioning_scale + + # predict the noise residual + + noise_pred = self.unet( + sample=latent_model_input, + timestep=timestep, + encoder_hidden_states=prompt_embeds, + down_block_0=down_block_res_samples[0], + down_block_1=down_block_res_samples[1], + down_block_2=down_block_res_samples[2], + down_block_3=down_block_res_samples[3], + down_block_4=down_block_res_samples[4], + down_block_5=down_block_res_samples[5], + down_block_6=down_block_res_samples[6], + down_block_7=down_block_res_samples[7], + down_block_8=down_block_res_samples[8], + down_block_9=down_block_res_samples[9], + down_block_10=down_block_res_samples[10], + down_block_11=down_block_res_samples[11], + mid_block_additional_residual=mid_block_res_sample + ) + noise_pred = noise_pred[0] + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2) + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) + + # compute the previous noisy sample x_t -> x_t-1 + scheduler_output = self.scheduler.step( + torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs + ) + latents = scheduler_output.prev_sample.numpy() + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(i, t, latents) + + latents = 1 / 0.18215 * latents + # image = self.vae_decoder(latent_sample=latents)[0] + # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1 + image = np.concatenate( + [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])] + ) + + image = np.clip(image / 2 + 0.5, 0, 1) + image = image.transpose((0, 2, 3, 1)) + + if self.safety_checker is not None: + safety_checker_input = self.feature_extractor( + self.numpy_to_pil(image), return_tensors="np" + ).pixel_values.astype(image.dtype) + + images, has_nsfw_concept = [], [] + for i in range(image.shape[0]): + image_i, has_nsfw_concept_i = self.safety_checker( + clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1] + ) + images.append(image_i) + has_nsfw_concept.append(has_nsfw_concept_i[0]) + image = np.concatenate(images) + else: + has_nsfw_concept = None + + if output_type == "pil": + image = self.numpy_to_pil(image) + + if not return_dict: + return (image, has_nsfw_concept) + + return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) + diff --git a/patchedstabledifftoonnx/pipeline_onnx_stable_diffusion_instruct_pix2pix.py b/patchedstabledifftoonnx/pipeline_onnx_stable_diffusion_instruct_pix2pix.py new file mode 100644 index 0000000000000000000000000000000000000000..b6b4a041841239381d5ff906221f9524b8ce0ff6 --- /dev/null +++ b/patchedstabledifftoonnx/pipeline_onnx_stable_diffusion_instruct_pix2pix.py @@ -0,0 +1,553 @@ +# Copyright 2023 The InstructPix2Pix Authors and The HuggingFace Team. +# Converted for use with ONNX as part of https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16 + +import inspect +from typing import Callable, List, Optional, Union + +import numpy as np +import PIL +import torch +from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer + +try: + from diffusers.pipelines.onnx_utils import ORT_TO_NP_TYPE +except ImportError: + ORT_TO_NP_TYPE = { + "tensor(bool)": np.bool_, + "tensor(int8)": np.int8, + "tensor(uint8)": np.uint8, + "tensor(int16)": np.int16, + "tensor(uint16)": np.uint16, + "tensor(int32)": np.int32, + "tensor(uint32)": np.uint32, + "tensor(int64)": np.int64, + "tensor(uint64)": np.uint64, + "tensor(float16)": np.float16, + "tensor(float)": np.float32, + "tensor(double)": np.float64, + } + +from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, SchedulerMixin +from diffusers.models import AutoencoderKL, UNet2DConditionModel +from diffusers.schedulers import KarrasDiffusionSchedulers, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler +from diffusers.utils import ( + PIL_INTERPOLATION, + deprecate, + logging, + randn_tensor, +) +from diffusers.pipeline_utils import DiffusionPipeline +from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +# Simplified and ONNX specific version (only allows 1 image, np over torch) +def preprocess(image): + if isinstance(image, np.ndarray): + return image + + w, h = image.size + w, h = map(lambda x: x - x % 8, (w, h)) # resize to integer multiple of 8 + image = np.array(image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]))[None, :] + image = np.array(image).astype(np.float32) / 255.0 + image = image.transpose(0, 3, 1, 2) + image = 2.0 * image - 1.0 + return image + + +class OnnxStableDiffusionInstructPix2PixPipeline(DiffusionPipeline): + r""" + Pipeline for pixel-level image editing by following text instructions. Based on Stable Diffusion. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the + library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) + + Args: + vae ([`AutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. + text_encoder ([`CLIPTextModel`]): + Frozen text-encoder. Stable Diffusion uses the text portion of + [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically + the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. + tokenizer (`CLIPTokenizer`): + Tokenizer of class + [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). + unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. + scheduler ([`SchedulerMixin`]): + A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of + [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. + safety_checker ([`StableDiffusionSafetyChecker`]): + Classification module that estimates whether generated images could be considered offensive or harmful. + Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details. + feature_extractor ([`CLIPFeatureExtractor`]): + Model that extracts features from generated images to be used as inputs for the `safety_checker`. + """ + vae_encoder: OnnxRuntimeModel + vae_decoder: OnnxRuntimeModel + text_encoder: OnnxRuntimeModel + tokenizer: CLIPTokenizer + unet: OnnxRuntimeModel + scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] + safety_checker: OnnxRuntimeModel + feature_extractor: CLIPFeatureExtractor + _optional_components = ["safety_checker", "feature_extractor"] + + def __init__( + self, + vae_encoder: OnnxRuntimeModel, + vae_decoder: OnnxRuntimeModel, + text_encoder: OnnxRuntimeModel, + tokenizer: CLIPTokenizer, + unet: OnnxRuntimeModel, + scheduler: KarrasDiffusionSchedulers, + safety_checker: OnnxRuntimeModel, + feature_extractor: CLIPFeatureExtractor, + requires_safety_checker: bool = True, + ): + super().__init__() + self.unet_in_channels = 8 + self.vae_scale_factor = 8 + + if safety_checker is None and requires_safety_checker: + logger.warning( + f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" + " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" + " results in services or applications open to the public. Both the diffusers team and Hugging Face" + " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" + " it only for use-cases that involve analyzing network behavior or auditing its results. For more" + " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." + ) + + if safety_checker is not None and feature_extractor is None: + raise ValueError( + "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" + " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." + ) + + self.register_modules( + vae_encoder=vae_encoder, + vae_decoder=vae_decoder, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + scheduler=scheduler, + safety_checker=safety_checker, + feature_extractor=feature_extractor, + ) + #self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) + self.register_to_config(requires_safety_checker=requires_safety_checker) + + @torch.no_grad() + def __call__( + self, + prompt: Union[str, List[str]] = None, + image: Union[np.ndarray, PIL.Image.Image] = None, + num_inference_steps: int = 100, + guidance_scale: float = 7.5, + image_guidance_scale: float = 1.5, + negative_prompt: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[np.random.RandomState] = None, + latents: Optional[np.ndarray] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, np.ndarray], None]] = None, + callback_steps: int = 1, + ): + r""" + Function invoked when calling the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. + instead. + image (`PIL.Image.Image`): + `Image`, or tensor representing an image batch which will be repainted according to `prompt`. + num_inference_steps (`int`, *optional*, defaults to 100): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*, defaults to 7.5): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://arxiv.org/pdf/2205.11487.pdf). 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. This pipeline requires a value of at least `1`. + image_guidance_scale (`float`, *optional*, defaults to 1.5): + Image guidance scale is to push the generated image towards the inital image `image`. Image guidance + scale is enabled by setting `image_guidance_scale > 1`. Higher image guidance scale encourages to + generate images that are closely linked to the source image `image`, usually at the expense of lower + image quality. This pipeline requires a value of at least `1`. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds`. instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` + is less than `1`). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator`, *optional*): + One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) + to make generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will ge generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. The function will be + called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function will be called. If not specified, the callback will be + called at every step. + + Examples: + + ```py + >>> import PIL + >>> import requests + >>> import torch + >>> from io import BytesIO + + >>> from diffusers import StableDiffusionInstructPix2PixPipeline + + + >>> def download_image(url): + ... response = requests.get(url) + ... return PIL.Image.open(BytesIO(response.content)).convert("RGB") + + + >>> img_url = "https://huggingface.co/datasets/diffusers/diffusers-images-docs/resolve/main/mountain.png" + + >>> image = download_image(img_url).resize((512, 512)) + + >>> pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained( + ... "timbrooks/instruct-pix2pix", torch_dtype=torch.float16 + ... ) + >>> pipe = pipe.to("cuda") + + >>> prompt = "make the mountains snowy" + >>> image = pipe(prompt=prompt, image=image).images[0] + ``` + + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. + When returning a tuple, the first element is a list with the generated images, and the second element is a + list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" + (nsfw) content, according to the `safety_checker`. + """ + + # We need a deterministic torch generator for schedulers if a (likely seeded) generator was provided + + if generator: + torch_seed = generator.randint(2147483647) + torch_gen = torch.Generator().manual_seed(torch_seed) + else: + generator = np.random + torch_gen = None + + # 0. Check inputs + self.check_inputs(prompt, callback_steps) + + if image is None: + raise ValueError("`image` input cannot be undefined.") + + # 1. Define call parameters + if isinstance(prompt, str): + batch_size = 1 + elif isinstance(prompt, list): + batch_size = len(prompt) + else: + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 and image_guidance_scale >= 1.0 + # check if scheduler is in sigmas space + scheduler_is_in_sigma_space = hasattr(self.scheduler, "sigmas") + + # 2. Encode input prompt + prompt_embeds = self._encode_prompt( + prompt, + num_images_per_prompt, + do_classifier_free_guidance, + negative_prompt, + ) + + # 3. Preprocess image + image = preprocess(image) + height, width = image.shape[-2:] + + # 4. set timesteps + self.scheduler.set_timesteps(num_inference_steps) + timesteps = self.scheduler.timesteps + + # 5. Prepare Image latents + latents_dtype = prompt_embeds.dtype + image = image.astype(latents_dtype) + # encode the init image into latents and scale the latents + image_latents = self.vae_encoder(sample=image)[0] + if do_classifier_free_guidance: + uncond_image_latents = np.zeros_like(image_latents) + image_latents = np.concatenate((image_latents, image_latents, uncond_image_latents), axis=0) + + # 6. Prepare latent variables + latents_dtype = prompt_embeds.dtype + latents_shape = (batch_size * num_images_per_prompt, 4, height // 8, width // 8) + if latents is None: + latents = generator.randn(*latents_shape).astype(latents_dtype) + elif latents.shape != latents_shape: + raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}") + latents = latents * self.scheduler.init_noise_sigma.numpy() + + # 7. Check that shapes of latents and image match the UNet channels + num_channels_image = image_latents.shape[1] + if 4+ num_channels_image != self.unet_in_channels: + raise ValueError( + f"Incorrect configuration settings! The config of `pipeline.unet`: expects" + f" {self.unet_in_channels} but received `num_channels_latents`: {num_channels_latents} +" + f" `num_channels_image`: {num_channels_image} " + f" = {num_channels_latents+num_channels_image}. Please verify the config of" + " `pipeline.unet` or your `image` input." + ) + + timestep_dtype = next( + (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)" + ) + timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype] + + # 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta, torch_gen) + + # 9. Denoising loop + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + with self.progress_bar(total=num_inference_steps) as progress_bar: + for i, t in enumerate(timesteps): + # Expand the latents if we are doing classifier free guidance. + # The latents are expanded 3 times because for pix2pix the guidance\ + # is applied for both the text and the input image. + latent_model_input = np.concatenate([latents] * 3) if do_classifier_free_guidance else latents + + scaled_latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t) + scaled_latent_model_input = scaled_latent_model_input.cpu().numpy() + + scaled_latent_model_input = np.concatenate([scaled_latent_model_input, image_latents], axis=1) + + # predict the noise residual + + noise_pred = self.unet( + sample=scaled_latent_model_input, + timestep=np.array([t], dtype=timestep_dtype), + encoder_hidden_states=prompt_embeds, + )[0] + + # Hack: + # For karras style schedulers the model does classifer free guidance using the + # predicted_original_sample instead of the noise_pred. So we need to compute the + # predicted_original_sample here if we are using a karras style scheduler. + if scheduler_is_in_sigma_space: + step_index = (self.scheduler.timesteps == t).nonzero().item() + sigma = self.scheduler.sigmas[step_index] + noise_pred = latent_model_input - sigma.numpy() * noise_pred + + # perform guidance + if do_classifier_free_guidance: + noise_pred_text, noise_pred_image, noise_pred_uncond = np.split(noise_pred, 3) + noise_pred = ( + noise_pred_uncond + + guidance_scale * (noise_pred_text - noise_pred_image) + + image_guidance_scale * (noise_pred_image - noise_pred_uncond) + ) + + # Hack: + # For karras style schedulers the model does classifer free guidance using the + # predicted_original_sample instead of the noise_pred. But the scheduler.step function + # expects the noise_pred and computes the predicted_original_sample internally. So we + # need to overwrite the noise_pred here such that the value of the computed + # predicted_original_sample is correct. + if scheduler_is_in_sigma_space: + noise_pred = (noise_pred - latents) / (-sigma) + + # compute the previous noisy sample x_t -> x_t-1 + scheduler_output = self.scheduler.step( + noise_pred, t, torch.from_numpy(latents), **extra_step_kwargs + ) + latents = scheduler_output.prev_sample.numpy() + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(i, t, latents.numpy()) + + # 10. Post-processing + image = self.decode_latents(latents) + + # 11. Run safety checker + image, has_nsfw_concept = self.run_safety_checker(image) + + # 12. Convert to PIL + if output_type == "pil": + image = self.numpy_to_pil(image) + + if not return_dict: + return (image, has_nsfw_concept) + + return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) + + def _encode_prompt(self, prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`): + prompt to be encoded + num_images_per_prompt (`int`): + number of images that should be generated per prompt + do_classifier_free_guidance (`bool`): + whether to use classifier free guidance or not + negative_prompt (`str` or `List[str]`): + 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`). + """ + negative_prompt_embeds = None + batch_size = len(prompt) if isinstance(prompt, list) else 1 + + # get prompt text embeddings + text_inputs = self.tokenizer( + prompt, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="np", + ) + text_input_ids = text_inputs.input_ids + untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids + + if not np.array_equal(text_input_ids, untruncated_ids): + removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) + logger.warning( + "The following part of your input was truncated because CLIP can only handle sequences up to" + f" {self.tokenizer.model_max_length} tokens: {removed_text}" + ) + + prompt_embeds = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0] + prompt_embeds = np.repeat(prompt_embeds, num_images_per_prompt, axis=0) + + # get unconditional embeddings for classifier free guidance + if do_classifier_free_guidance: + uncond_tokens: List[str] + if negative_prompt is None: + uncond_tokens = [""] * batch_size + elif type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif isinstance(negative_prompt, str): + uncond_tokens = [negative_prompt] * batch_size + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + else: + uncond_tokens = negative_prompt + + max_length = text_input_ids.shape[-1] + uncond_input = self.tokenizer( + uncond_tokens, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="np", + ) + negative_prompt_embeds = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0] + negative_prompt_embeds = np.repeat(negative_prompt_embeds, num_images_per_prompt, axis=0) + + # For classifier free guidance, we need to do two forward passes. + # Here we concatenate the unconditional and text embeddings into a single batch + # to avoid doing two forward passes + # pix2pix has two negative embeddings, and unlike in other pipelines latents are ordered [prompt_embeds, negative_prompt_embeds, negative_prompt_embeds] + + prompt_embeds = np.concatenate((prompt_embeds, negative_prompt_embeds, negative_prompt_embeds)) + + return prompt_embeds + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker + def run_safety_checker(self, image): + if self.safety_checker is not None: + safety_checker_input = self.feature_extractor( + self.numpy_to_pil(image), return_tensors="np" + ).pixel_values.astype(image.dtype) + # safety_checker does not support batched inputs yet + images, has_nsfw_concept = [], [] + for i in range(image.shape[0]): + image_i, has_nsfw_concept_i = self.safety_checker( + clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1] + ) + images.append(image_i) + has_nsfw_concept.append(has_nsfw_concept_i[0]) + image = np.concatenate(images) + else: + has_nsfw_concept = None + return image, has_nsfw_concept + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs + def prepare_extra_step_kwargs(self, generator, eta, torch_gen): + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 + # and should be between [0, 1] + + accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) + extra_step_kwargs = {} + if accepts_eta: + extra_step_kwargs["eta"] = eta + + # check if the scheduler accepts generator + accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) + if accepts_generator: + extra_step_kwargs["generator"] = torch_gen + return extra_step_kwargs + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents + def decode_latents(self, latents): + latents = 1 / 0.18215 * latents + image = np.concatenate( + [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])] + ) + image = np.clip(image / 2 + 0.5, 0, 1) + image = image.transpose((0, 2, 3, 1)) + return image + + def check_inputs(self, prompt, callback_steps): + if not isinstance(prompt, str) and not isinstance(prompt, list): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + if (callback_steps is None) or ( + callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) + ): + raise ValueError( + f"`callback_steps` has to be a positive integer but is {callback_steps} of type" + f" {type(callback_steps)}." + ) + diff --git a/patchedstabledifftoonnx/pix2pixUI.py b/patchedstabledifftoonnx/pix2pixUI.py new file mode 100644 index 0000000000000000000000000000000000000000..00f015080619fc987a41f99074ee61cca0ac5904 --- /dev/null +++ b/patchedstabledifftoonnx/pix2pixUI.py @@ -0,0 +1,53 @@ +import numpy as np +import gradio as gr + +from pipeline_onnx_stable_diffusion_instruct_pix2pix import OnnxStableDiffusionInstructPix2PixPipeline +from diffusers import DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler + +def pix2pix(input_img, prompt, guide, iguide, steps, seed): + if seed == -1: + generator=None + else: + generator=np.random + generator.seed(seed) + img = pipe( + prompt=prompt, + image=input_img, + num_inference_steps=steps, + guidance_scale=guide, + image_guidance_scale=iguide, + generator=generator).images[0] + return img + +if __name__ == "__main__": + model="./model/ip2p-base-fp16-vae_ft_mse-autoslicing" + pipe = OnnxStableDiffusionInstructPix2PixPipeline.from_pretrained(model, provider="DmlExecutionProvider", safety_checker=None) + pipe.scheduler=EulerAncestralDiscreteScheduler.from_pretrained(model, subfolder="scheduler") + + demo=gr.Interface(pix2pix, gr.Image(shape=(512,512)), "image") + title="ONNX Instruct Pix 2 Pix" + css = "#imgbox img {max-width: 100% !important; }\n#imgbox div {height: auto;}" + with gr.Blocks(title=title, css=css) as demo: + with gr.Row(): + with gr.Column(scale=1): + seed = gr.Number(value=-1, label="seed", precision=0) + with gr.Column(scale=14): + prompt = gr.Textbox(value="", lines=2, label="prompt") + with gr.Row(): + with gr.Column(scale=1): + guide = gr.Slider(1.1, 10, value=3, step=0.1, label="Text guidance") + with gr.Column(scale=1): + iguide = gr.Slider(1, 10, value=1.1, step=0.1, label="Image guidance") + with gr.Column(scale=1): + steps = gr.Slider(10,100, value=30, step=1, label="Steps") + with gr.Row(): + with gr.Column(scale=1): + input_img = gr.Image(label="Input Image", type="pil", elem_id="imgbox").style(width=600,height=600) + with gr.Column(scale=1): + image_out = gr.Image(value=None, label="Output Image", elem_id="imgbox").style(width=600,height=600) + gen_btn = gr.Button("Generate", variant="primary", elem_id="gen_button") + + inputs=[input_img, prompt, guide, iguide, steps, seed] + gen_btn.click(fn=pix2pix, inputs=inputs, outputs=[image_out]) + + demo.launch() diff --git a/patchedstabledifftoonnx/quant.py b/patchedstabledifftoonnx/quant.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/patchedstabledifftoonnx/quantization.py b/patchedstabledifftoonnx/quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..44b1032aff1ebaa56abe1b957a8a3381a0e81c8b --- /dev/null +++ b/patchedstabledifftoonnx/quantization.py @@ -0,0 +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"} \ No newline at end of file diff --git a/patchedstabledifftoonnx/requirements.txt b/patchedstabledifftoonnx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..e1d7d2371adca99c247bd283607caac477b268e3 --- /dev/null +++ b/patchedstabledifftoonnx/requirements.txt @@ -0,0 +1,14 @@ +protobuf < 4.0 +numpy +transformers +diffusers +ftfy +spacy +scipy +safetensors +gradio +omegaconf +onnx +onnxconverter-common +onnxruntime-directml +opencv-python \ No newline at end of file diff --git a/patchedstabledifftoonnx/run-batch.md b/patchedstabledifftoonnx/run-batch.md new file mode 100644 index 0000000000000000000000000000000000000000..86b88d6a2f6c5d607533d7b355496197423d2e45 --- /dev/null +++ b/patchedstabledifftoonnx/run-batch.md @@ -0,0 +1,50 @@ +# Running Stable Diffusion ONNX DirectML batches + +Ever feel like it's a struggle to compare schedulers, guidance scale ... while using a UI? +Not really interested in coding in Python to resolve it? + +Hopefully run-batch.py will make your life a bit easier. + +## Set up +Drop run-batch.py where you've installed OnnxDiffusersUI (it'll use the same lwp_pipe.py). + +As parameter run-batch.py accepts 1 or more paths where it will then check for the existence of settings.json. +It'll read settings.json, create a batch of images and save them in the directory it just got the settings from. + +In settings.json you can define the following things: +- The model, set with the key 'model'. It will look for a directory with that name in the model subdirectory (just like OnnxDiffusersUI). +- The scheduler, set with the key 'scheduler'. You can also set a list of schedulers to iterate over with the key 'schedulerlist'. +It currently accepts following values: ddim, deis, dpms_ms, dpms_ss, euler_anc, euler, heun, kdpm2, lms, pndm,unipc. +If the value is not recognised, it'll switch to pndm. Not all schedulers have been extensively tested and may behave unexpectendly. +- Guidance scale, set with the key 'scale'. You can also set a list of guidance scales to iterate over with the key 'scalelist' +- Iteration steps, set with the key 'steps'. You can also set a list of steps to iterate over with the key 'stepslist' +- 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"]) +- The seed, set with the key 'seed'. If you want to iterate over seeds you can define the end with the key 'seedend'. +Alternatively, you can provide a list of seeds using the key 'seedlist'. +- 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). +- The prompt, set with the key 'prompt'. If you want to iterate over prompts, you can define them with the key 'promptlist'. +- A negative prompt, set with the key 'negative_prompt'. Note that the same negative prompt will apply to all prompts you provided. +- 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. + +If you are doing img2img or controlnet there's more options: +- Strength, set with the key 'strength'. Expected to be between 0 to 1. You can iterate over a list by setting 'strengthlist'. + +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. + +## Example + +Compare the results for a prompt with deis and euler at 20, 30 and 40 steps. Using SD 2.1. + +``` +{ + "model": "sd2_1-fp16", + "seed": 0, + "seedend": 10, + "stepslist": [20,30,40], + "scale": 8.5, + "schedulerlist": ["deis","euler"], + "prompt": "(photo portrait) of a ((beautiful)) (woman) wearing (summer dress) in a park, eyes, detailed, high resolution, prime lens", + "negative_prompt": "bad quality, low resolution", + "textenc": "lwp" +} +``` diff --git a/patchedstabledifftoonnx/run-batch.py b/patchedstabledifftoonnx/run-batch.py new file mode 100644 index 0000000000000000000000000000000000000000..4eef86a26e310d965d557753394709b60bd8c8a3 --- /dev/null +++ b/patchedstabledifftoonnx/run-batch.py @@ -0,0 +1,330 @@ +# Copyright 2022 Dirk Moerenhout. All rights reserved. +# +# This program is free software: you can redistribute it and/or modify it under the terms +# of the GNU General Public License as published by the Free Software Foundation, +# either version 3 of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. If not, +# see . + +# We need sys for argv +import sys +# We need os.path for isdir, isfile +import os.path +# Our settings are in json format +import json +# To be safe we force gc to lower RAM pressure +import gc +# We want to replace the text encoder in the pipeline +import functools +# We want to parse arguments +import argparse +# Numpy is used to provide a random generator +import numpy +# We need to load images for img2img +# We want to save data to PNG +from PIL import Image, PngImagePlugin + +# The pipelines +from diffusers import OnnxStableDiffusionPipeline, OnnxStableDiffusionImg2ImgPipeline +from pipeline_onnx_stable_diffusion_controlnet import OnnxStableDiffusionControlNetPipeline +# Model needed to load Text Encoder on CPU +from diffusers import OnnxRuntimeModel +# The schedulers +from diffusers import ( + DDIMScheduler, + DEISMultistepScheduler, + DPMSolverMultistepScheduler, + DPMSolverSinglestepScheduler, + EulerAncestralDiscreteScheduler, + EulerDiscreteScheduler, + HeunDiscreteScheduler, + KDPM2DiscreteScheduler, + LMSDiscreteScheduler, + PNDMScheduler, + UniPCMultistepScheduler +) + +# Support special text encoders +import OnnxDiffusersUI.lpw_pipe + +# Default settings +defSettings = { + "width": 512, + "height": 512, + "reslist": [], + "steps": 30, + "stepslist": [], + "scale": 7.5, + "scalelist":[], + "seed":0, + "seedend":0, + "seedlist":[], + "task": "txt2img", + "model":"sd2_1-fp16", + "prompt": "", + "promptlist":[], + "negative_prompt": "", + "textenc": "standard", + "scheduler": "pndm", + "schedulerlist": [], + "strength": 0.9, + "strengthlist": [] +} + +parser = argparse.ArgumentParser() + +parser.add_argument( + "--cpu-textenc", + action="store_true", + help="Load Text Encoder on CPU to save VRAM" +) + +parser.add_argument( + "--subdirs", + action="store_true", + help="Add subdirs with settings.json to projects to run" +) + +parser.add_argument( + 'project', + nargs='+', + type=str, + help="Provide projects as directories that contain settings.json" +) + +args = parser.parse_args() + +projects=args.project +if args.subdirs: + for proj in args.project: + obj = os.scandir(proj) + for entry in obj: + if entry.is_dir(): + if os.path.isfile(f"{proj}/{entry.name}/settings.json"): + projects.append(f"{proj}/{entry.name}") + +for proj in projects: + print("Running project "+proj) + # Check for directory + if os.path.isdir(proj): + if os.path.isfile(proj+"/settings.json"): + with open(proj+"/settings.json", encoding="utf-8") as confFile: + projSettings=json.load(confFile) + # Merge dictionaries with project settings taking precedence + runSettings = defSettings | projSettings + # We need prompts + prereqmet=len(runSettings['prompt'])>0 or len(runSettings['promptlist'])>0 + # We need a model + model="model/"+runSettings['model'] + prereqmet=prereqmet and os.path.isfile(model+"/unet/model.onnx") + # We need a start image to do img2img or controlnet + if runSettings['task']=="img2img" or runSettings['task']=="controlnet": + infile=proj+"/input.png" + prereqmet = prereqmet and os.path.isfile(infile) + if prereqmet: + sched = { + "ddim": DDIMScheduler.from_pretrained(model, subfolder="scheduler"), + "deis": DEISMultistepScheduler.from_pretrained(model, subfolder="scheduler"), + "dpms_ms": DPMSolverMultistepScheduler.from_pretrained(model, subfolder="scheduler"), + "dpms_ss": DPMSolverSinglestepScheduler.from_pretrained(model, subfolder="scheduler"), + "euler_anc": EulerAncestralDiscreteScheduler.from_pretrained(model, subfolder="scheduler"), + "euler": EulerDiscreteScheduler.from_pretrained(model, subfolder="scheduler"), + "heun": HeunDiscreteScheduler.from_pretrained(model, subfolder="scheduler"), + "kdpm2": KDPM2DiscreteScheduler.from_pretrained(model, subfolder="scheduler"), + "lms": LMSDiscreteScheduler.from_pretrained(model, subfolder="scheduler"), + "pndm": PNDMScheduler.from_pretrained(model, subfolder="scheduler"), + "unipc": UniPCMultistepScheduler.from_pretrained(model, subfolder="scheduler") + } + if runSettings['task']=="img2img": + init_image = Image.open(infile).convert("RGB") + if args.cpu_textenc: + cputextenc=OnnxRuntimeModel.from_pretrained(model+"/text_encoder") + pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained( + model, + provider="DmlExecutionProvider", + revision="onnx", + scheduler=sched['pndm'], + text_encoder=cputextenc, + safety_checker=None, + feature_extractor=None + ) + else: + pipe = OnnxStableDiffusionImg2ImgPipeline.from_pretrained( + model, + provider="DmlExecutionProvider", + revision="onnx", + scheduler=sched['pndm'], + safety_checker=None, + feature_extractor=None + ) + elif runSettings['task']=="controlnet": + init_image = Image.open(infile).convert("RGB") + if args.cpu_textenc: + cputextenc=OnnxRuntimeModel.from_pretrained(model+"/text_encoder") + pipe = OnnxStableDiffusionControlNetPipeline.from_pretrained( + model, + provider="DmlExecutionProvider", + revision="onnx", + scheduler=sched['pndm'], + text_encoder=cputextenc, + safety_checker=None, + feature_extractor=None + ) + else: + pipe = OnnxStableDiffusionControlNetPipeline.from_pretrained( + model, + provider="DmlExecutionProvider", + revision="onnx", + scheduler=sched['pndm'], + safety_checker=None, + feature_extractor=None + ) + else: + if args.cpu_textenc: + cputextenc=OnnxRuntimeModel.from_pretrained(model+"/text_encoder") + pipe = OnnxStableDiffusionPipeline.from_pretrained( + model, + provider="DmlExecutionProvider", + revision="onnx", + scheduler=sched['pndm'], + text_encoder=cputextenc, + safety_checker=None, + feature_extractor=None + ) + else: + pipe = OnnxStableDiffusionPipeline.from_pretrained( + model, + provider="DmlExecutionProvider", + revision="onnx", + scheduler=sched['pndm'], + safety_checker=None, + feature_extractor=None + ) + if runSettings['textenc'] == "lpw": + pipe._encode_prompt = functools.partial(lpw_pipe._encode_prompt, pipe) + generator = numpy.random + # Set schedulers for projects + if len(runSettings['schedulerlist'])==0: + schedulerlist=[runSettings['scheduler']] + else: + schedulerlist=runSettings['schedulerlist'] + # Set seeds for project + if len(runSettings['seedlist'])==0: + if runSettings['seed']>runSettings['seedend']: + runSettings['seedend']=runSettings['seed'] + seedlist=range(runSettings['seed'],runSettings['seedend']+1) + else: + seedlist=runSettings['seedlist'] + # Set resolustions for project + if len(runSettings['reslist'])==0: + restuples=[(runSettings['width'],runSettings['height'])] + else: + restuples=[] + for resstr in runSettings['reslist']: + restuples.append(tuple(map(int, resstr.split("x")))) + # Set steps for project + if len(runSettings['stepslist'])==0: + stepslist=[runSettings['steps']] + else: + stepslist=runSettings['stepslist'] + # Set guidance scales for project + if len(runSettings['scalelist'])==0: + scalelist=[runSettings['scale']] + else: + scalelist=runSettings['scalelist'] + # Set prompts for project + if len(runSettings['promptlist'])==0: + promptlist=[runSettings['prompt']] + else: + promptlist=runSettings['promptlist'] + # Set strengths for project + if len(runSettings['strengthlist'])==0: + strengthlist=[runSettings['strength']] + else: + strengthlist=runSettings['strengthlist'] + imgnr=len(schedulerlist)*len(promptlist)*len(seedlist)*len(restuples)*len(stepslist)*len(scalelist)*len(strengthlist) + imgdone=0 + for scheduler in schedulerlist: + if not sched[scheduler]: + scheduler="pndm" + pipe.scheduler=sched[scheduler] + promptnum=0 + for prompt in promptlist: + for seed in seedlist: + for res in restuples: + for steps in stepslist: + for scale in scalelist: + for strength in strengthlist: + if runSettings['task']=="img2img": + filename=( + f"{proj}/result-p{promptnum}-seed{seed}-{res[0]}x{res[1]}-"+ + f"-steps-{steps}-{scheduler}-scale-"+str(scale).replace(".","_")+ + "-strength-"+str(strength).replace(".","_")+".png" + ) + elif runSettings['task']=="controlnet": + filename=( + f"{proj}/result-p{promptnum}-seed{seed}-{res[0]}x{res[1]}-"+ + f"-steps-{steps}-{scheduler}-scale-"+str(scale).replace(".","_")+ + "-strength-"+str(strength).replace(".","_")+".png" + ) + else: + filename=( + f"{proj}/result-p{promptnum}-seed{seed}-{res[0]}x{res[1]}-"+ + f"-steps-{steps}-{scheduler}-scale-"+str(scale).replace(".","_")+".png" + ) + if not os.path.isfile(filename): + generator.seed(seed) + if runSettings['task']=="img2img": + image = pipe( + image=init_image, + strength=strength, + prompt=prompt, + negative_prompt=runSettings['negative_prompt'], + num_inference_steps=steps, + guidance_scale=scale, + generator=generator).images[0] + elif runSettings['task']=="controlnet": + image = pipe( + image=init_image, + controlnet_conditioning_scale=strength, + prompt=prompt, + negative_prompt=runSettings['negative_prompt'], + num_inference_steps=steps, + guidance_scale=scale, + generator=generator).images[0] + else: + image = pipe( + prompt=prompt, + negative_prompt=runSettings['negative_prompt'], + width=res[0], + height=res[1], + num_inference_steps=steps, + guidance_scale=scale, + generator = generator).images[0] + metadata = PngImagePlugin.PngInfo() + metadata.add_text("Generator","Stable Diffusion ONNX https://github.com/Amblyopius/Stable-Diffusion-ONNX-FP16") + metadata.add_text("SD Model (local name)",model) + metadata.add_text("SD Prompt",prompt) + metadata.add_text("SD Negative Prompt",runSettings['negative_prompt']) + metadata.add_text("SD Scheduler",scheduler) + metadata.add_text("SD Steps",str(steps)) + metadata.add_text("SD Guidance Scale",str(scale)) + image.save(filename, pnginfo = metadata) + else: + print("Skipping existing image!") + imgdone+=1 + print(f"Finished {imgdone}/{imgnr}") + promptnum+=1 + del pipe + gc.collect() + else: + print("Minimum requirements not met! Skipping") + else: + print("Settings not found! Skipping") + else: + print("Path not found! Skipping") diff --git a/patchedstabledifftoonnx/sd_env/bin/python b/patchedstabledifftoonnx/sd_env/bin/python new file mode 100644 index 0000000000000000000000000000000000000000..6c7d87058eee2a2d6b7249e951a56b9be6d55d9a --- /dev/null +++ b/patchedstabledifftoonnx/sd_env/bin/python @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:682d5b916b076ae9e1f1399b89e7f4b521599cf04f669cbd65af0a317bc6033e +size 5912968 diff --git a/patchedstabledifftoonnx/sd_env/bin/python3 b/patchedstabledifftoonnx/sd_env/bin/python3 new file mode 100644 index 0000000000000000000000000000000000000000..6c7d87058eee2a2d6b7249e951a56b9be6d55d9a --- /dev/null +++ b/patchedstabledifftoonnx/sd_env/bin/python3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:682d5b916b076ae9e1f1399b89e7f4b521599cf04f669cbd65af0a317bc6033e +size 5912968 diff --git a/patchedstabledifftoonnx/sd_env/bin/python3.10 b/patchedstabledifftoonnx/sd_env/bin/python3.10 new file mode 100644 index 0000000000000000000000000000000000000000..6c7d87058eee2a2d6b7249e951a56b9be6d55d9a --- /dev/null +++ b/patchedstabledifftoonnx/sd_env/bin/python3.10 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:682d5b916b076ae9e1f1399b89e7f4b521599cf04f669cbd65af0a317bc6033e +size 5912968 diff --git a/patchedstabledifftoonnx/sd_env/pyvenv.cfg b/patchedstabledifftoonnx/sd_env/pyvenv.cfg new file mode 100644 index 0000000000000000000000000000000000000000..266b9070b691797b4e023a61b8c460691082a6e5 --- /dev/null +++ b/patchedstabledifftoonnx/sd_env/pyvenv.cfg @@ -0,0 +1,3 @@ +home = /usr/bin +include-system-site-packages = false +version = 3.10.6 diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/.dockerignore b/patchedstabledifftoonnx/stable-diffusion-streamlit/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..2e1cc68e254e7b666851e10c5b385eb117f63f19 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/.dockerignore @@ -0,0 +1,6 @@ +src/stable-diffusion-streamlit/pages/model/result +src/stable-diffusion-streamlit/pages/model/onnx +__pycache__ +docker/.env +tag.sh +docker/volume \ No newline at end of file diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/.github/workflows/build-image.yml b/patchedstabledifftoonnx/stable-diffusion-streamlit/.github/workflows/build-image.yml new file mode 100644 index 0000000000000000000000000000000000000000..abc3692c36534de72deec88361bbc36f97e279d4 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/.github/workflows/build-image.yml @@ -0,0 +1,16 @@ +name: Build Image + +on: push + +jobs: + build: + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + - name: Login to Registry + if: startsWith(github.ref, 'refs/tags') + run: docker login --username=${{ secrets.DOCKER_USERNAME }} --password ${{ secrets.DOCKER_PASSWORD }} + - name: Push Image + if: startsWith(github.ref, 'refs/tags') + run: | + cd docker && bash build.sh ${{ secrets.HUGGINGFACE_TOKEN }} \ No newline at end of file diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/.gitignore b/patchedstabledifftoonnx/stable-diffusion-streamlit/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..97f986b96cd8d3f02e83005125418603aa75b07b --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/.gitignore @@ -0,0 +1,6 @@ +result +onnx +__pycache__ +docker/.env +tag.sh +docker/volume \ No newline at end of file diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/LICENSE b/patchedstabledifftoonnx/stable-diffusion-streamlit/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f2536f973e48ee6508f5b1063d5914ec92a09e6e --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/LICENSE @@ -0,0 +1,254 @@ +Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors + +CreativeML Open RAIL-M +dated August 22, 2022 + +Section I: PREAMBLE + +Multimodal generative models are being widely adopted and used, and have +the potential to transform the way artists, among other individuals, +conceive and benefit from AI or ML technologies as a tool for content +creation. + +Notwithstanding the current and potential benefits that these artifacts +can bring to society at large, there are also concerns about potential +misuses of them, either due to their technical limitations or ethical +considerations. + +In short, this license strives for both the open and responsible +downstream use of the accompanying model. When it comes to the open +character, we took inspiration from open source permissive licenses +regarding the grant of IP rights. Referring to the downstream responsible +use, we added use-based restrictions not permitting the use of the Model +in very specific scenarios, in order for the licensor to be able to +enforce the license in case potential misuses of the Model may occur. At +the same time, we strive to promote open and responsible research on +generative models for art and content generation. + +Even though downstream derivative versions of the model could be released +under different licensing terms, the latter will always have to include - +at minimum - the same use-based restrictions as the ones in the original +license (this license). We believe in the intersection between open and +responsible AI development; thus, this License aims to strike a balance +between both in order to enable responsible open-science in the field of +AI. + +This License governs the use of the model (and its derivatives) and is +informed by the model card associated with the model. + +NOW THEREFORE, You and Licensor agree as follows: + +1. Definitions + +- "License" means the terms and conditions for use, reproduction, and +Distribution as defined in this document. +- "Data" means a collection of information and/or content extracted from +the dataset used with the Model, including to train, pretrain, or +otherwise evaluate the Model. The Data is not licensed under this +License. +- "Output" means the results of operating a Model as embodied in +informational content resulting therefrom. +- "Model" means any accompanying machine-learning based assemblies +(including checkpoints), consisting of learnt weights, parameters +(including optimizer states), corresponding to the model architecture as +embodied in the Complementary Material, that have been trained or tuned, +in whole or in part on the Data, using the Complementary Material. +- "Derivatives of the Model" means all modifications to the Model, works +based on the Model, or any other model which is created or initialized by +transfer of patterns of the weights, parameters, activations or output of +the Model, to the other model, in order to cause the other model to +perform similarly to the Model, including - but not limited to - +distillation methods entailing the use of intermediate data +representations or methods based on the generation of synthetic data by +the Model for training the other model. +- "Complementary Material" means the accompanying source code and scripts +used to define, run, load, benchmark or evaluate the Model, and used to +prepare data for training or evaluation, if any. This includes any +accompanying documentation, tutorials, examples, etc, if any. +- "Distribution" means any transmission, reproduction, publication or +other sharing of the Model or Derivatives of the Model to a third party, +including providing the Model as a hosted service made available by +electronic or other remote means - e.g. API-based or web access. +- "Licensor" means the copyright owner or entity authorized by the +copyright owner that is granting the License, including the persons or +entities that may have rights in the Model and/or distributing the Model. +- "You" (or "Your") means an individual or Legal Entity exercising +permissions granted by this License and/or making use of the Model for +whichever purpose and in any field of use, including usage of the Model +in an end-use application - e.g. chatbot, translator, image generator. +- "Third Parties" means individuals or legal entities that are not under +common control with Licensor or You. +- "Contribution" means any work of authorship, including the original +version of the Model and any modifications or additions to that Model or +Derivatives of the Model thereof, that is intentionally submitted to +Licensor for inclusion in the Model by the copyright owner or by an +individual or Legal Entity authorized to submit on behalf of the +copyright owner. For the purposes of this definition, "submitted" means +any form of electronic, verbal, or written communication sent to the +Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Model, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." +- "Contributor" means Licensor and any individual or Legal Entity on +behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Model. + +Section II: INTELLECTUAL PROPERTY RIGHTS + +Both copyright and patent grants apply to the Model, Derivatives of the +Model and Complementary Material. The Model and Derivatives of the Model +are subject to additional terms as described in Section III. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright +license to reproduce, prepare, publicly display, publicly perform, +sublicense, and distribute the Complementary Material, the Model, and +Derivatives of the Model. +3. Grant of Patent License. Subject to the terms and conditions of this +License and where and as applicable, each Contributor hereby grants to +You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this paragraph) patent license to make, +have made, use, offer to sell, sell, import, and otherwise transfer the +Model and the Complementary Material, where such license applies only to +those patent claims licensable by such Contributor that are necessarily +infringed by their Contribution(s) alone or by combination of their +Contribution(s) with the Model to which such Contribution(s) was +submitted. If You institute patent litigation against any entity +(including a cross-claim or counterclaim in a lawsuit) alleging that the +Model and/or Complementary Material or a Contribution incorporated within +the Model and/or Complementary Material constitutes direct or +contributory patent infringement, then any patent licenses granted to You +under this License for the Model and/or Work shall terminate as of the +date such litigation is asserted or filed. + +Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION + +4. Distribution and Redistribution. You may host for Third Party remote +access purposes (e.g. software-as-a-service), reproduce and distribute +copies of the Model or Derivatives of the Model thereof in any medium, +with or without modifications, provided that You meet the following +conditions: +Use-based restrictions as referenced in paragraph 5 MUST be included as +an enforceable provision by You in any type of legal agreement (e.g. a +license) governing the use and/or distribution of the Model or +Derivatives of the Model, and You shall give notice to subsequent users +You Distribute to, that the Model or Derivatives of the Model are subject +to paragraph 5. This provision does not apply to the use of Complementary +Material. +You must give any Third Party recipients of the Model or Derivatives of +the Model a copy of this License; +You must cause any modified files to carry prominent notices stating that +You changed the files; +You must retain all copyright, patent, trademark, and attribution notices +excluding those notices that do not pertain to any part of the Model, +Derivatives of the Model. +You may add Your own copyright statement to Your modifications and may +provide additional or different license terms and conditions - respecting +paragraph 4.a. - for use, reproduction, or Distribution of Your +modifications, or for any such Derivatives of the Model as a whole, +provided Your use, reproduction, and Distribution of the Model otherwise +complies with the conditions stated in this License. +5. Use-based restrictions. The restrictions set forth in Attachment A are +considered Use-based restrictions. Therefore You cannot use the Model and +the Derivatives of the Model for the specified restricted uses. You may +use the Model subject to this License, including only for lawful purposes +and in accordance with the License. Use may include creating any content +with, finetuning, updating, running, training, evaluating and/or +reparametrizing the Model. You shall require all of Your users who use +the Model or a Derivative of the Model to comply with the terms of this +paragraph (paragraph 5). +6. The Output You Generate. Except as set forth herein, Licensor claims +no rights in the Output You generate using the Model. You are accountable +for the Output you generate and its subsequent uses. No use of the output +can contravene any provision as stated in the License. + +Section IV: OTHER PROVISIONS + +7. Updates and Runtime Restrictions. To the maximum extent permitted by +law, Licensor reserves the right to restrict (remotely or otherwise) +usage of the Model in violation of this License, update the Model through +electronic means, or modify the Output of the Model based on updates. You +shall undertake reasonable efforts to use the latest version of the +Model. +8. Trademarks and related. Nothing in this License permits You to make +use of Licensors’ trademarks, trade names, logos or to otherwise suggest +endorsement or misrepresent the relationship between the parties; and any +rights not expressly granted herein are reserved by the Licensors. +9. Disclaimer of Warranty. Unless required by applicable law or agreed to +in writing, Licensor provides the Model and the Complementary Material +(and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. +You are solely responsible for determining the appropriateness of using +or redistributing the Model, Derivatives of the Model, and the +Complementary Material and assume any risks associated with Your exercise +of permissions under this License. +10. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, unless +required by applicable law (such as deliberate and grossly negligent +acts) or agreed to in writing, shall any Contributor be liable to You for +damages, including any direct, indirect, special, incidental, or +consequential damages of any character arising as a result of this +License or out of the use or inability to use the Model and the +Complementary Material (including but not limited to damages for loss of +goodwill, work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor has been +advised of the possibility of such damages. +11. Accepting Warranty or Additional Liability. While redistributing the +Model, Derivatives of the Model and the Complementary Material thereof, +You may choose to offer, and charge a fee for, acceptance of support, +warranty, indemnity, or other liability obligations and/or rights +consistent with this License. However, in accepting such obligations, You +may act only on Your own behalf and on Your sole responsibility, not on +behalf of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability incurred by, +or claims asserted against, such Contributor by reason of your accepting +any such warranty or additional liability. +12. If any provision of this License is held to be invalid, illegal or +unenforceable, the remaining provisions shall be unaffected thereby and +remain valid as if such provision had not been set forth herein. +END OF TERMS AND CONDITIONS + + + + +Attachment A + +Use Restrictions + +You agree not to use the Model or Derivatives of the Model: +- In any way that violates any applicable national, federal, state, local +or international law or regulation; +- For the purpose of exploiting, harming or attempting to exploit or harm +minors in any way; +- To generate or disseminate verifiably false information and/or content +with the purpose of harming others; +- To generate or disseminate personal identifiable information that can +be used to harm an individual; +- To defame, disparage or otherwise harass others; +- For fully automated decision making that adversely impacts an +individual’s legal rights or otherwise creates or modifies a binding, +enforceable obligation; +- For any use intended to or which has the effect of discriminating +against or harming individuals or groups based on online or offline +social behavior or known or predicted personal or personality +characteristics; +- To exploit any of the vulnerabilities of a specific group of persons +based on their age, social, physical or mental characteristics, in order +to materially distort the behavior of a person pertaining to that group +in a manner that causes or is likely to cause that person or another +person physical or psychological harm; +- For any use intended to or which has the effect of discriminating +against individuals or groups based on legally protected characteristics +or categories; +- To provide medical advice and medical results interpretation; +- To generate or disseminate information for the purpose to be used for +administration of justice, law enforcement, immigration or asylum +processes, such as predicting an individual will commit fraud/crime +commitment (e.g. by text profiling, drawing causal relationships between +assertions made in documents, indiscriminate and arbitrarily-targeted +use). diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/README.md b/patchedstabledifftoonnx/stable-diffusion-streamlit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..020961a6fe5302389643f790a0cf47ddf0116533 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/README.md @@ -0,0 +1,114 @@ +[**中文说明**](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/README_CN.md) | [**English**](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/README.md) + +# stable-diffusion-streamlit + +- [1.Introduction](#1-introduction) +- [2.Getting Started](#2-getting-started) +- [3.Quantization Performance](#3-quantization-performance) +- [4.Streamlit Progress Bar](#4-streamlit-progress-bar) +- [5.To Do](#5-to-do) +- [6.Get Help](#6-get-help) +- [7.Acknowledgements](#7-acknowledgements) + +## 1. Introduction + ++ 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%**. + + **Streamlit**: + + an open-source app framework for Machine Learning and Data Science teams. Create beautiful web apps in minutes. + + **CompVis/stable-diffusion-v1-4**: + + a latent text-to-image diffusion model capable of generating photo-realistic images given any text input. + + **OnnxRuntime**: + + a cross-platform, faster inference and lower costs accelerator for machine learning models. + + +## 2. Getting Started + +### 2.1. Deployment ++ docker-compose up -d +```yaml +version: "2.3" +services: + stable-diffusion-streamlit-onnxquantized: + container_name: stable-diffusion-streamlit-onnxquantized + image: lowinli98/stable-diffusion-streamlit-onnxquantized:v0.2 + expose: + - 8501 + ports: + - "8501:8501" + environment: + - APP_TITLE=Stable Diffusion Streamlit + restart: always + volumes: + - /etc/localtime:/etc/localtime + - ./volume:/app/pages/model/result +``` + +### 2.2. Usage ++ 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/) ++ 2.2.2. Open http://localhost:8501 and click "文本转图片" on the left sidebar. ++ 2.2.3. Fix the runtime parameters, paste your prompt into the text area and click the "开始生成" button. + + ![](./doc/gif/use1.gif) + ++ 2.2.4. Wait for a while until the progress bar goes to the end, then you will get a generated image. + + ![](./doc/gif/use2.gif) + ++ 2.2.5. Click "画廊" on the left sidebar to see all the images you had generated. + + ![](./doc/gif/use3.gif) + + +## 3. Quantization Performance ++ The model in the docker container has been quantized by OnnxRuntime in the building of the docker image. + + + [dockerfile](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/docker/dockerfile) + + [building progress in Github Action](https://github.com/LowinLi/stable-diffusion-streamlit/actions/runs/3202674839/jobs/5231895605) + ++ 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. ++ 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. + +--- +| model | memory used | inference 49 steps waste time | +| --- | --- | --- | +| pytorch | 5.2GB | 6m56s | +| onnx | 5.0GB | 4m34s | +| onnx-quantized(UINT8) | 1.3GB | 4m29s | + ++ CPU: + + Intel(R) Xeon(R) CPU E5-2650 v3 @ 2.30GHz + + 10 core + + ++ image generated by PyTorch model + + ![](./doc/pic/torch.png) ++ image generated by Onnx model + + ![](./doc/pic/onnx.png) ++ image generated by Onnx-Quantized(UINT8) model + + ![](./doc/pic/onnxquantized.png) + +## 4. Streamlit Progress Bar +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. +With another thread in Python, the progress bar can be updated by the pipeline scheduler counter. + + + +## 5. To Do + +- [ ] Add the Text-Guided Image-to-Image Pipeline in [Huggingface/Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/img2img) +- [ ] Add the Text-Guided Image-Inpainting Pipeline in [Huggingface/Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/inpaint) + +## 6. Get Help + ++ Contact me at lowinli@outlook.com ++ If appropriate, open an issue on GitHub + +## 7. Acknowledgements + ++ [Huggingface/Diffusers](https://github.com/huggingface/diffusers) ++ [CompVis/stable-diffusion](https://github.com/CompVis/stable-diffusion) ++ [Streamlit](https://github.com/streamlit/streamlit) ++ [OnnxRuntime](https://github.com/microsoft/onnxruntime) diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/README_CN.md b/patchedstabledifftoonnx/stable-diffusion-streamlit/README_CN.md new file mode 100644 index 0000000000000000000000000000000000000000..9352fe8924339cb81db4b9e154318b5b086e549e --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/README_CN.md @@ -0,0 +1,111 @@ +[**中文说明**](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/README_CN.md) | [**English**](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/README.md) + +# stable-diffusion-streamlit + +- [1.简介](#1-简介) +- [2.快速开始](#2-快速开始) +- [3.模型量化提速表现](#3-模型量化提速表现) +- [4.Streamlit进度条](#4-Streamlit进度条) +- [5.下一步](#5-下一步) +- [6.帮助](#6-帮助) +- [7.致谢](#7-致谢) + +## 1. 简介 + ++ **使用[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)模型做图片生成**. + + **Streamlit**: + + 一个流行的开源框架,可以快速搭建机器学习和数据科学团队的Web应用。 + + **CompVis/stable-diffusion-v1-4**: + + 一个流行的扩散模型,可以通过文字提示生成栩栩如生的高质量图片。 + + **OnnxRuntime**: + + 微软推出的一款推理框架,用户可以非常便利的量化压缩模型。 + + +## 2. 快速开始 + +### 2.1. 部署 ++ docker-compose up -d +```yaml +version: "2.3" +services: + stable-diffusion-streamlit-onnxquantized: + container_name: stable-diffusion-streamlit-onnxquantized + image: lowinli98/stable-diffusion-streamlit-onnxquantized:v0.2 + expose: + - 8501 + ports: + - "8501:8501" + environment: + - APP_TITLE=Stable Diffusion Streamlit + restart: always + volumes: + - /etc/localtime:/etc/localtime + - ./volume:/app/pages/model/result +``` + +### 2.2. 使用 ++ 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/)复制一个文本提示。 ++ 2.2.2. 打开http://localhost:8501,在侧边栏点击"文本转图片"。 ++ 2.2.3. 修改运行参数, 粘贴提示,点击"开始生成"。 + + ![](./doc/gif/use1.gif) + ++ 2.2.4. 待进度条走完后,页面直接展示生成的图片 + + ![](./doc/gif/use2.gif) + ++ 2.2.5. 点击侧边栏的"画廊"查看所有历史生成的图片 + + ![](./doc/gif/use3.gif) + + +## 3. 模型量化提速表现 ++ 服务中使用的模型已经在打镜像阶段就做了OnnxRuntime量化压缩处理,详见: + + + [dockerfile](https://github.com/LowinLi/stable-diffusion-streamlit/blob/main/docker/dockerfile) + + [Github Action的镜像构建日志](https://github.com/LowinLi/stable-diffusion-streamlit/actions/runs/3202674839/jobs/5231895605) + ++ 量化后的模型尺寸降低很多、推理速度提高一点点(UINT8), 同时保持和原模型几乎一样的生成图片质量. ++ 这一点意味着,[CompVis/stable-diffusion-v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4)模型可以被部署在大多数家用电脑上,并进行调试。以下是几种模型的比较: + +--- +| 模型 | 内存 | 49步推断用时 | +| --- | --- | --- | +| pytorch | 5.2GB | 6m56s | +| onnx | 5.0GB | 4m34s | +| onnx-quantized(UINT8) | 1.3GB | 4m29s | + ++ CPU: + + Intel(R) Xeon(R) CPU E5-2650 v3 @ 2.30GHz + + 10 core + + ++ PyTorch模型生成的图片 + + ![](./doc/pic/torch.png) ++ Onnx模型生成的图片 + + ![](./doc/pic/onnx.png) ++ Onnx-quantized(UINT8)模型生成的图片 + + ![](./doc/pic/onnxquantized.png) + +## 4. Streamlit进度条 +为了生成高质量图片,扩散模型一般要推断很多步,这会比较耗时。为了提升用户体验,在Streamlit页面做了一个进度条,通过另一个线程,监控推断步数,并更新到进度条中。 + +## 5. 下一步 + +- [ ] 增加[Huggingface/Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/img2img)中的图像生成图像流程 +- [ ] 增加[Huggingface/Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/inpaint)中的抠图生成图像流程 + +## 6. 帮助 + ++ 联系我的邮箱lowinli@outlook.com ++ 有任何问题,欢迎在Github上提Issue + +## 7. 致谢 + ++ [Huggingface/Diffusers](https://github.com/huggingface/diffusers) ++ [CompVis/stable-diffusion](https://github.com/CompVis/stable-diffusion) ++ [Streamlit](https://github.com/streamlit/streamlit) ++ [OnnxRuntime](https://github.com/microsoft/onnxruntime) diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use1.gif b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use1.gif new file mode 100644 index 0000000000000000000000000000000000000000..b3828625d091ac8c32305a10bce093cd6898c23c --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use1.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d355f1c49d1e541a4dc0869cb884a288cc8f9f1c1fb003ac6dad13cf94dc2d89 +size 1044481 diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use2.gif b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use2.gif new file mode 100644 index 0000000000000000000000000000000000000000..a277b22addc0b6e486ce83a055e8824cfed49b43 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use2.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cd6952004c7197a41cdd3900c37b22526e69c0bfa642fec9fd4014e7530a36d +size 24389688 diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use3.gif b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use3.gif new file mode 100644 index 0000000000000000000000000000000000000000..868eb73de60ae2f01cb4a80235dc967f9ee8f9bf --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/gif/use3.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f66d3dea4fde8c8f2ffa453f5c4df557601f02a9cbbb10f795d21afc1585e9af +size 30709963 diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/pic/onnx.png b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/pic/onnx.png new file mode 100644 index 0000000000000000000000000000000000000000..31a30d946d13f4ac1d2925bf921852a74c851963 Binary files /dev/null and b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/pic/onnx.png differ diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/pic/onnxquantized.png b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/pic/onnxquantized.png new file mode 100644 index 0000000000000000000000000000000000000000..2484ab475d49c5a9984648eea6d3310c16a23e46 Binary files /dev/null and b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/pic/onnxquantized.png differ diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/pic/torch.png b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/pic/torch.png new file mode 100644 index 0000000000000000000000000000000000000000..a139857c712e72b9d41fa4078eb56f38050a52bc Binary files /dev/null and b/patchedstabledifftoonnx/stable-diffusion-streamlit/doc/pic/torch.png differ diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/build.sh b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..582dfdf31fb0a51db8bc7e9f0123f580d2e8948e --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/build.sh @@ -0,0 +1,15 @@ +#!/bin/bash +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +BUILDROOT=$DIR/.. + +cd $BUILDROOT + +CONTAINER="lowinli98/stable-diffusion-streamlit-onnxquantized" #替换成你的容器名称 +VERSION=`git describe --abbrev=0 --tags` + +IMAGE_NAME="${CONTAINER}:${VERSION}" +cmd="docker build -t $IMAGE_NAME -f $DIR/dockerfile $BUILDROOT --build-arg HUGGINGFACE_TOKEN=$1" +echo $cmd +eval $cmd + +docker push $IMAGE_NAME \ No newline at end of file diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/docker-compose.yaml b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/docker-compose.yaml new file mode 100644 index 0000000000000000000000000000000000000000..051ffdc2e4feebc31ccd7e0f9a7a6854ac09261b --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/docker-compose.yaml @@ -0,0 +1,15 @@ +version: "2.3" +services: + stable-diffusion-streamlit-onnxquantized: + container_name: stable-diffusion-streamlit-onnxquantized + image: lowinli98/stable-diffusion-streamlit-onnxquantized:v0.2 + expose: + - 8501 + ports: + - "8501:8501" + environment: + - APP_TITLE=Stable Diffusion Streamlit + restart: always + volumes: + - /etc/localtime:/etc/localtime + - ./volume:/app/pages/model/result \ No newline at end of file diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/dockerfile b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..046a6cad0e0307c8e6147f8b4adf7da5e2114fba --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/dockerfile @@ -0,0 +1,21 @@ +FROM python:3.8.7-slim as builder +ARG HUGGINGFACE_TOKEN +ENV HUGGINGFACE_TOKEN=${HUGGINGFACE_TOKEN} +COPY docker/requirements.txt /app/ + +# install +RUN echo "==> Installing ..." && \ + pip3 install --no-cache-dir --upgrade pip && \ + pip3 install virtualenv && \ + virtualenv -p /usr/local/bin/python /app/env && \ + /app/env/bin/pip install --no-cache-dir --upgrade pip && \ + /app/env/bin/pip install --no-cache-dir -r /app/requirements.txt --extra-index-url https://download.pytorch.org/whl/cpu + +COPY src/stable-diffusion-streamlit /app/ +RUN cd /app/pages/model/ && \ + /app/env/bin/python prepare.py + +FROM python:3.8.7-slim +COPY --from=builder /app /app +WORKDIR /app +CMD ["/app/env/bin/streamlit", "run", "主页.py"] \ No newline at end of file diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/entrypoint.sh b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..c2c01b3f020e08376eb28c3bd0b84a4e467a3baa --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/entrypoint.sh @@ -0,0 +1 @@ +streamlit run 主页.py \ No newline at end of file diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/requirements.txt b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3a584825c8d786299988be1eab8d0ea021683f1b --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/docker/requirements.txt @@ -0,0 +1,7 @@ +ftfy==6.1.1 +onnx==1.12.0 +onnxruntime==1.12.1 +streamlit==1.13.0 +transformers==4.22.2 +diffusers==0.4.0 +torch==1.10.0+cpu \ No newline at end of file diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/entrypoint.sh b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/entrypoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..c2c01b3f020e08376eb28c3bd0b84a4e467a3baa --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/entrypoint.sh @@ -0,0 +1 @@ +streamlit run 主页.py \ No newline at end of file diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/__init__.py b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/copy_pb.py b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/copy_pb.py new file mode 100644 index 0000000000000000000000000000000000000000..08c292c04c64d6ee2044eb7eb0992b5a1e533905 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/copy_pb.py @@ -0,0 +1,17 @@ +import os +import shutil + + +def copy_weights(): + for (root, _, file_list) in os.walk( + os.path.join( + os.environ["HOME"], + ".cache/huggingface/diffusers/models--CompVis--stable-diffusion-v1-4", + ) + ): + if "weights.pb" in file_list: + shutil.copyfile(os.path.join(root, "weights.pb"), "./onnx/unet/weights.pb") + + +if __name__ == "__main__": + copy_weights() diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/download_onnx.py b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/download_onnx.py new file mode 100644 index 0000000000000000000000000000000000000000..280906efb116bb0509cda9e2fd67453f6d6baaa2 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/download_onnx.py @@ -0,0 +1,22 @@ +import os +from diffusers import StableDiffusionOnnxPipeline + + +def download_save(): + token = os.environ.get("HUGGINGFACE_TOKEN") + + pipe = StableDiffusionOnnxPipeline.from_pretrained( + "CompVis/stable-diffusion-v1-4", + revision="onnx", + provider="CPUExecutionProvider", + use_auth_token=token, + ) + for tmp_dir in ["safety_checker", "text_encoder", "unet", "vae_decoder"]: + os.makedirs(os.path.join("./onnx", tmp_dir), exist_ok=True) + with open(os.path.join("./onnx", tmp_dir, "model.onnx"), "wb") as f: + f.write(b"") + pipe.save_pretrained("./onnx") + + +if __name__ == "__main__": + download_save() diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/inference.py b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..d775663f25a587ab518d31dd1491f862497ea530 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/inference.py @@ -0,0 +1,40 @@ +from diffusers import StableDiffusionOnnxPipeline, StableDiffusionPipeline +import os +import json + +root = os.getcwd() +last_dir = os.path.split(root)[-1] +if last_dir == "stable-diffusion-streamlit": + model_dir = os.path.join(root, "pages/model/onnx") + result_dir = os.path.join(root, "pages/model/result") +elif last_dir == "pages": + model_dir = os.path.join(root, "model/onnx") + result_dir = os.path.join(root, "model/result") +elif last_dir == "app": + model_dir = os.path.join(root, "pages/model/onnx") + result_dir = os.path.join(root, "pages/model/result") +else: + model_dir = os.path.join(root, "onnx") + result_dir = os.path.join(root, "result") + +global quant_pipe + +quant_pipe = StableDiffusionOnnxPipeline.from_pretrained( + model_dir, provider="CPUExecutionProvider", local_files_only=True +) +# quant_pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", local_files_only=True) + + +def inference(uid, **args): + image = quant_pipe(**args)["sample"][0] + target = os.path.join(result_dir, uid) + os.makedirs(target, exist_ok=True) + image.save(os.path.join(target, "image.png")) + with open(os.path.join(target, "config.json"), "w") as f: + json.dump(args, f, indent=4, ensure_ascii=False) + + +if __name__ == "__main__": + from pympler.asizeof import asizeof + + print(asizeof(quant_pipe)) diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.onnx b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.onnx new file mode 100644 index 0000000000000000000000000000000000000000..f853c10e1ec7d0e8921d651044b990eb76704f04 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8613d46ab19c61e528f7f9bb37932d55ca6d73f59ff9349e5aaa3e97fc5e0700 +size 17745692 diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.onnx.data b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.onnx.data new file mode 100644 index 0000000000000000000000000000000000000000..2fabdcbea9c55e441bd67a3afa2baf877a586a33 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.onnx.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d12bc8352e8bb54e7a3225883ca80e3aac9201ad21fe2dcaa142c6337d35269e +size 860852480 diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.ort b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.ort new file mode 100644 index 0000000000000000000000000000000000000000..50c500b9bd48720673317fa2eeeec2bc964251b3 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.ort @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1d9c740b06118205354d251d123597c59c2550bd1870197bd7c393c4aa905505 +size 874459960 diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.with_runtime_opt.ort b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.with_runtime_opt.ort new file mode 100644 index 0000000000000000000000000000000000000000..f3c50950737d16fad5cf3359a84c2331035a0c42 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.with_runtime_opt.ort @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7762dc164ef1b7d50a51b4efff243c650e2a87cfc8fddb00ebc6be1c2056bbe0 +size 874913120 diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/required_operators.config b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/required_operators.config new file mode 100644 index 0000000000000000000000000000000000000000..1dad059775c83443755421e7a545a22bdb725f58 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/required_operators.config @@ -0,0 +1,12 @@ +# Generated from model/s: +# - /content/Stable-Diffusion-ONNX-FP16/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.ort +ai.onnx;1;LayerNormalization +ai.onnx;6;InstanceNormalization +ai.onnx;7;Cos,Sin +ai.onnx;9;ConstantOfShape,Where +ai.onnx;10;ConvInteger +ai.onnx;11;DynamicQuantizeLinear,Range +ai.onnx;13;Cast,Concat,Equal,Expand,Gather,MatMul,Resize,ScatterND,Slice,Softmax,Transpose,Unsqueeze +ai.onnx;14;Add,Div,Mul,Reshape +ai.onnx;15;Shape +com.microsoft;1;DynamicQuantizeMatMul,FusedMatMul,Gelu,MatMulIntegerToFloat,QuickGelu diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/required_operators.with_runtime_opt.config b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/required_operators.with_runtime_opt.config new file mode 100644 index 0000000000000000000000000000000000000000..45b85efcc74d432e1df100eecca1e443b2ffde2c --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/required_operators.with_runtime_opt.config @@ -0,0 +1,11 @@ +# Generated from model/s: +# - /content/Stable-Diffusion-ONNX-FP16/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/model.with_runtime_opt.ort +# - /content/Stable-Diffusion-ONNX-FP16/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/onnx/tmpmaqb65r3.without_runtime_opt/model.ort +ai.onnx;6;InstanceNormalization +ai.onnx;7;Cos,Sin +ai.onnx;9;ConstantOfShape,Where +ai.onnx;10;ConvInteger,MatMulInteger +ai.onnx;11;DynamicQuantizeLinear,Range +ai.onnx;13;Cast,Concat,Equal,Erf,Expand,Gather,MatMul,ReduceMean,Resize,ScatterND,Sigmoid,Slice,Softmax,Sqrt,Transpose,Unsqueeze +ai.onnx;14;Add,Div,Mul,Reshape,Sub +ai.onnx;15;Pow,Shape diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/prepare.py b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..1a641e98bae82774f9f66fab4e1a0399b5939b7e --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/prepare.py @@ -0,0 +1,10 @@ +from copy_pb import copy_weights +from download_onnx import download_save +from quantization import quant +import shutil + +if __name__ == "__main__": + shutil.rmtree("./onnx", ignore_errors=True) + download_save() + copy_weights() + quant() diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/quantization.py b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..76a75f9fc186b68982282d7577cc6a8fddaaca2d --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/quantization.py @@ -0,0 +1,28 @@ +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() diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/thread.py b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/thread.py new file mode 100644 index 0000000000000000000000000000000000000000..b69d8dc61f4959a190db60c26ba764d5bf056dd4 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/model/thread.py @@ -0,0 +1,27 @@ +import threading +import copy +from diffusers import StableDiffusionOnnxPipeline, StableDiffusionPipeline + + +class PipelineThread(threading.Thread): + def __init__(self, func, args=()): + super(PipelineThread, self).__init__() + self.func = StableDiffusionOnnxPipeline( + func.vae_decoder, + func.text_encoder, + func.tokenizer, + func.unet, + copy.deepcopy(func.scheduler), + func.safety_checker, + func.feature_extractor, + ) + self.args = args + + def run(self): + self.result = self.func(*self.args) + + def get_result(self): + try: + return self.result + except Exception: + return None diff --git "a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/\346\226\207\345\255\227\350\275\254\345\233\276\347\211\207.py" "b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/\346\226\207\345\255\227\350\275\254\345\233\276\347\211\207.py" new file mode 100644 index 0000000000000000000000000000000000000000..0320fc10c61e2a57bcecad1aa90de26c14cf623f --- /dev/null +++ "b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/\346\226\207\345\255\227\350\275\254\345\233\276\347\211\207.py" @@ -0,0 +1,151 @@ +import streamlit as st +import numpy as np +import time +import threading +from datetime import datetime +import json +import os +import gc +from diffusers.training_utils import set_seed + +from pages.model.inference import result_dir, quant_pipe +from pages.model.thread import PipelineThread + +st.set_page_config( + page_title="文字转图片", + page_icon="🧊", + layout="wide", + initial_sidebar_state="expanded", + menu_items={}, +) + + +st.title("扩散模型文字生成图片") +with st.form(key="my_form"): + ce, c1, ce, c2, c3 = st.columns([0.07, 1, 0.07, 5, 0.07]) + with c1: + st.subheader("参数配置", anchor=None) + num_inference_steps = st.slider( + "生成轮数(num_inference_steps)", + min_value=5, + max_value=100, + value=50, + step=1, + label_visibility="visible", + help="约大生成图片质量越高,但是速度越慢 \n The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.", + ) + guidance_scale = st.slider( + "指导参数(guidance_scale)", + min_value=0.0, + max_value=30.0, + value=7.0, + step=0.1, + 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.", + label_visibility="visible", + ) + height = st.slider( + "高度像素(height)", + min_value=64, + max_value=1024, + value=512, + step=8, + label_visibility="visible", + ) + width = st.slider( + "宽度像素(width)", + min_value=64, + max_value=1024, + value=512, + step=8, + label_visibility="visible", + ) + eta = st.slider( + "eta (η)", + min_value=0.0, + max_value=5.0, + value=0.0, + step=0.1, + help="Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502", + label_visibility="visible", + ) + seed = st.slider( + "种子(seed)", + min_value=0, + max_value=1024, + value=10, + step=1, + label_visibility="visible", + help="配置不同种子可以生成不同的图片", + ) + + with c2: + text_prompt = st.text_area( + "输入提示文字", + value="", + help="The prompt or prompts to guide the image generation", + disabled=False, + label_visibility="visible", + ) + negative_prompt = st.text_area( + "输入不要生成的文字描述,不填为不使用", + value="", + 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`).", + disabled=False, + label_visibility="visible", + ) + negative_prompt = None + submit_button = st.form_submit_button("开始生成", help=None, args=None, kwargs=None) + my_bar = st.progress(0) + if not submit_button: + st.stop() + set_seed(seed) + uid = datetime.now().strftime("%Y%m%d_%H:%M:%S") + args = ( + text_prompt, + height, + width, + num_inference_steps, + guidance_scale, + negative_prompt, + eta, + ) + t = PipelineThread(func=quant_pipe, args=args) + t.start() + while True: + time.sleep(1) + if isinstance(t.func.scheduler.counter, int): + counter = t.func.scheduler.counter + else: + counter = 0 + progress = min( + t.func.scheduler.counter / (num_inference_steps + 1), + 1.0, + ) + my_bar.progress(progress) + if progress >= 1: + break + t.join() + + image_filename = os.path.join(result_dir, "text2image", uid, "image.png") + json_filename = os.path.join(result_dir, "text2image", uid, "config.json") + os.makedirs(os.path.join(result_dir, "text2image", uid), exist_ok=True) + t.get_result().images[0].save(image_filename) + del t + gc.collect() + with open(json_filename, "w") as f: + config = { + "text_prompt": text_prompt, + "height": height, + "width": width, + "num_inference_steps": num_inference_steps, + "guidance_scale": guidance_scale, + "eta": eta, + "seed": seed, + } + json.dump(config, f, indent=4, ensure_ascii=False) + st.balloons() + st.image( + image_filename, channels="RGB", output_format="auto", caption=text_prompt + ) + with open(json_filename, "r") as f: + st.json(json.load(f), expanded=True) diff --git "a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/\347\224\273\345\273\212.py" "b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/\347\224\273\345\273\212.py" new file mode 100644 index 0000000000000000000000000000000000000000..b1e433cda44f48e81d42a241b4982708ee694b6c --- /dev/null +++ "b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/pages/\347\224\273\345\273\212.py" @@ -0,0 +1,27 @@ +import streamlit as st +import os +import json + +# tab1 = st.tabs(["文字转图片"]) + +# with tab1: +result_dir = "pages/model/result/text2image" +os.makedirs(result_dir, exist_ok=True) +list_uid = os.listdir(result_dir) +list_uid = sorted(list_uid, reverse=True) + +for uid in list_uid: + try: + with open(os.path.join(result_dir, uid, "config.json"), "r") as f: + config = json.load(f) + + with st.container(): + st.caption(uid) + st.image( + os.path.join(result_dir, uid, "image.png"), + caption=str(config["text_prompt"]), + ) + st.json(config, expanded=False) + st.markdown("---") + except: + pass diff --git a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/requirements.txt b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..56737367cf4b3059a7b8acb2fdfe0f3d31b9c1e7 --- /dev/null +++ b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/requirements.txt @@ -0,0 +1,9 @@ +ftfy==6.1.1 +onnx==1.12.0 +onnxruntime==1.12.1 +streamlit==1.13.0 +streamlit-image-comparison==0.0.2 +transformers==4.22.2 +diffusers==0.3.0 +torch==1.10.0 +pandas==1.4.1 \ No newline at end of file diff --git "a/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/\344\270\273\351\241\265.py" "b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/\344\270\273\351\241\265.py" new file mode 100644 index 0000000000000000000000000000000000000000..6867cf0790d967e7e275d7c1fb9b058010643a02 --- /dev/null +++ "b/patchedstabledifftoonnx/stable-diffusion-streamlit/src/stable-diffusion-streamlit/\344\270\273\351\241\265.py" @@ -0,0 +1,9 @@ +import streamlit as st +import os + +app_title = os.environ.get("APP_TITLE", "Streamlit,Stable Diffusion在线生图工具") +st.title(app_title) +body = """+ [文字转图片](./文字转图片) ++ [画廊](./画廊) +""" +st.markdown(body, unsafe_allow_html=False) diff --git a/patchedstabledifftoonnx/test-controlnet-canny.py b/patchedstabledifftoonnx/test-controlnet-canny.py new file mode 100644 index 0000000000000000000000000000000000000000..47ce207a31d8c857e98751e40bb9dcdcbd7f0e56 --- /dev/null +++ b/patchedstabledifftoonnx/test-controlnet-canny.py @@ -0,0 +1,45 @@ +from diffusers.utils import load_image +import cv2 +from PIL import Image +import numpy as np +from diffusers import UniPCMultistepScheduler +from pipeline_onnx_stable_diffusion_controlnet import OnnxStableDiffusionControlNetPipeline +import onnxruntime as ort + +image = load_image( + "input_image_vermeer.png" +) + +image = np.array(image) + +low_threshold = 100 +high_threshold = 200 + +image = cv2.Canny(image, low_threshold, high_threshold) +image = image[:, :, None] +image = np.concatenate([image, image, image], axis=2) +canny_image = Image.fromarray(image) + +opts = ort.SessionOptions() +opts.enable_cpu_mem_arena = False +opts.enable_mem_pattern = False + +pipe = OnnxStableDiffusionControlNetPipeline.from_pretrained( + "model/sd1_5-fp16-vae_ft_mse-autoslicing-cn_canny", + sess_options=opts, + provider="DmlExecutionProvider", +) + +pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config) +prompt = "jpop singer on stage, best quality, extremely detailed" +seed=42 +generator = np.random.RandomState(seed) + +images = pipe( + prompt, + canny_image, + negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality", + num_inference_steps=20, + generator=generator, +).images[0] +images.save("controlnet-canny-test.png") diff --git a/patchedstabledifftoonnx/test-controlnet-openpose.py b/patchedstabledifftoonnx/test-controlnet-openpose.py new file mode 100644 index 0000000000000000000000000000000000000000..7811aa879d0644aeda9aa6de734c2e0d4174562c --- /dev/null +++ b/patchedstabledifftoonnx/test-controlnet-openpose.py @@ -0,0 +1,33 @@ +from PIL import Image +import numpy as np +from diffusers import DEISMultistepScheduler +from pipeline_onnx_stable_diffusion_controlnet import OnnxStableDiffusionControlNetPipeline +import onnxruntime as ort + +pose_image = Image.open(r"dance_pose.png") + +opts = ort.SessionOptions() +opts.enable_cpu_mem_arena = False +opts.enable_mem_pattern = False + +pipe = OnnxStableDiffusionControlNetPipeline.from_pretrained( + "model/anyv3-fp16-autoslicing-cn_openpose", + sess_options=opts, + provider="DmlExecutionProvider", +) + +pipe.scheduler = DEISMultistepScheduler.from_config(pipe.scheduler.config) +prompt = "1girl, blonde, long dress, dancing, best quality" +seed=25 +generator = np.random.RandomState(seed) + +images = pipe( + prompt, + pose_image, + width=512, + height=512, + negative_prompt="monochrome, lowres, bad anatomy, worst quality, low quality", + num_inference_steps=30, + generator=generator, +).images[0] +images.save("controlnet-openpose-test.png") diff --git a/patchedstabledifftoonnx/test-txt2img.py b/patchedstabledifftoonnx/test-txt2img.py new file mode 100644 index 0000000000000000000000000000000000000000..77f7305d9e153ec6c200c06e3178bf331ba73124 --- /dev/null +++ b/patchedstabledifftoonnx/test-txt2img.py @@ -0,0 +1,156 @@ +# Copyright 2022 Dirk Moerenhout. All rights reserved. +# +# This program is free software: you can redistribute it and/or modify it under the terms +# of the GNU General Public License as published by the Free Software Foundation, +# either version 3 of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; +# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with this program. If not, +# see . + +# We need regular expressions support +import re +# We need argparse for handling command line arguments +import argparse +# We need os.path for isdir +import os.path +# Numpy is used to provide a random generator +import numpy +# Needed to set session options +import onnxruntime as ort + + +from diffusers import OnnxStableDiffusionPipeline, OnnxRuntimeModel + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + parser.add_argument( + "--model", + type=str, + required=True, + help="Directory in current location to load model from", + ) + + parser.add_argument( + "--size", + default=512, + type=int, + required=False, + help="Width/Height of the picture, defaults to 512, use 768 when appropriate", + ) + + parser.add_argument( + "--steps", + default=30, + type=int, + required=False, + help="Scheduler steps to use", + ) + + parser.add_argument( + "--scale", + default=7.5, + type=float, + required=False, + help="Guidance scale (how strict it sticks to the prompt)" + ) + + parser.add_argument( + "--prompt", + default="a dog on a lawn with the eifel tower in the background", + type=str, + required=False, + help="Text prompt for generation", + ) + + parser.add_argument( + "--negprompt", + default="blurry, low quality", + type=str, + required=False, + help="Negative text prompt for generation (what to avoid)", + ) + + parser.add_argument( + "--seed", + type=int, + required=False, + help="Seed for generation, allows you to get the exact same image again", + ) + + parser.add_argument( + "--fixeddims", + action="store_true", + help="Pass fixed dimensions to ONNX Runtime. Test purposes only, NOT VRAM FRIENDLY!", + ) + + parser.add_argument( + "--cpu-textenc", "--cpuclip", + action="store_true", + help="Load Text Encoder on CPU to save VRAM" + ) + + parser.add_argument( + "--cpuvae", + action="store_true", + help="Load VAE on CPU, this will always load the Text Encoder on CPU too" + ) + + args = parser.parse_args() + + VAECPU = TECPU = False + if args.cpuvae: + VAECPU = TECPU = True + if args.cpu_textenc: + TECPU=True + + if match := re.search(r"([^/\\]*)[/\\]?$", args.model): + fmodel = match.group(1) + generator=numpy.random + imgname="testpicture-"+fmodel+"_"+str(args.size)+".png" + if args.seed is not None: + generator.seed(args.seed) + imgname="testpicture-"+fmodel+"_"+str(args.size)+"_seed"+str(args.seed)+".png" + + if os.path.isdir(args.model+"/unet"): + height=args.size + width=args.size + + sess_options = ort.SessionOptions() + sess_options.enable_mem_pattern = False + + if args.fixeddims: + sess_options.add_free_dimension_override_by_name("unet_sample_batch", 2) + sess_options.add_free_dimension_override_by_name("unet_sample_channels", 4) + sess_options.add_free_dimension_override_by_name("unet_sample_height", 64) + sess_options.add_free_dimension_override_by_name("unet_sample_width", 64) + sess_options.add_free_dimension_override_by_name("unet_timestep_batch", 1) + sess_options.add_free_dimension_override_by_name("unet_ehs_batch", 2) + sess_options.add_free_dimension_override_by_name("unet_ehs_sequence", 77) + + num_inference_steps=args.steps + guidance_scale=args.scale + prompt = args.prompt + negative_prompt = args.negprompt + if TECPU: + cputextenc=OnnxRuntimeModel.from_pretrained(args.model+"/text_encoder") + if VAECPU: + cpuvae=OnnxRuntimeModel.from_pretrained(args.model+"/vae_decoder") + pipe = OnnxStableDiffusionPipeline.from_pretrained(args.model, + provider="DmlExecutionProvider", text_encoder=cputextenc, vae_decoder=cpuvae, + vae_encoder=None) + else: + pipe = OnnxStableDiffusionPipeline.from_pretrained(args.model, + provider="DmlExecutionProvider", text_encoder=cputextenc) + else: + pipe = OnnxStableDiffusionPipeline.from_pretrained(args.model, + provider="DmlExecutionProvider", sess_options=sess_options) + image = pipe(prompt, width, height, num_inference_steps, guidance_scale, + negative_prompt,generator=generator).images[0] + image.save(imgname) + else: + print("model not found") diff --git a/patchedstabledifftoonnx/v1-inference.yaml b/patchedstabledifftoonnx/v1-inference.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4effe569e897369918625f9d8be5603a0e6a0d6 --- /dev/null +++ b/patchedstabledifftoonnx/v1-inference.yaml @@ -0,0 +1,70 @@ +model: + base_learning_rate: 1.0e-04 + target: ldm.models.diffusion.ddpm.LatentDiffusion + params: + linear_start: 0.00085 + linear_end: 0.0120 + num_timesteps_cond: 1 + log_every_t: 200 + timesteps: 1000 + first_stage_key: "jpg" + cond_stage_key: "txt" + image_size: 64 + channels: 4 + cond_stage_trainable: false # Note: different from the one we trained before + conditioning_key: crossattn + monitor: val/loss_simple_ema + scale_factor: 0.18215 + use_ema: False + + scheduler_config: # 10000 warmup steps + target: ldm.lr_scheduler.LambdaLinearScheduler + params: + warm_up_steps: [ 10000 ] + cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases + f_start: [ 1.e-6 ] + f_max: [ 1. ] + f_min: [ 1. ] + + unet_config: + target: ldm.modules.diffusionmodules.openaimodel.UNetModel + params: + image_size: 32 # unused + in_channels: 4 + out_channels: 4 + model_channels: 320 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_heads: 8 + use_spatial_transformer: True + transformer_depth: 1 + context_dim: 768 + use_checkpoint: True + legacy: False + + first_stage_config: + target: ldm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: + - 1 + - 2 + - 4 + - 4 + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity + + cond_stage_config: + target: ldm.modules.encoders.modules.FrozenCLIPEmbedder diff --git a/patchedstabledifftoonnx/v1-inpainting-inference.yaml b/patchedstabledifftoonnx/v1-inpainting-inference.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f9eec37d24bce33ce92320a782d16ae72308190a --- /dev/null +++ b/patchedstabledifftoonnx/v1-inpainting-inference.yaml @@ -0,0 +1,70 @@ +model: + base_learning_rate: 7.5e-05 + target: ldm.models.diffusion.ddpm.LatentInpaintDiffusion + params: + linear_start: 0.00085 + linear_end: 0.0120 + num_timesteps_cond: 1 + log_every_t: 200 + timesteps: 1000 + first_stage_key: "jpg" + cond_stage_key: "txt" + image_size: 64 + channels: 4 + cond_stage_trainable: false # Note: different from the one we trained before + conditioning_key: hybrid # important + monitor: val/loss_simple_ema + scale_factor: 0.18215 + finetune_keys: null + + scheduler_config: # 10000 warmup steps + target: ldm.lr_scheduler.LambdaLinearScheduler + params: + warm_up_steps: [ 2500 ] # NOTE for resuming. use 10000 if starting from scratch + cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases + f_start: [ 1.e-6 ] + f_max: [ 1. ] + f_min: [ 1. ] + + unet_config: + target: ldm.modules.diffusionmodules.openaimodel.UNetModel + params: + image_size: 32 # unused + in_channels: 9 # 4 data + 4 downscaled image + 1 mask + out_channels: 4 + model_channels: 320 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_heads: 8 + use_spatial_transformer: True + transformer_depth: 1 + context_dim: 768 + use_checkpoint: True + legacy: False + + first_stage_config: + target: ldm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: + - 1 + - 2 + - 4 + - 4 + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity + + cond_stage_config: + target: ldm.modules.encoders.modules.FrozenCLIPEmbedder