commit 179fd5395b6c7e12d1dc611a9ce9909341d6d642 Author: Victor Hall Date: Sat Dec 17 22:32:48 2022 -0500 hey look ed2 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ff6fc1f --- /dev/null +++ b/LICENSE @@ -0,0 +1,13 @@ +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/LICENSE_AGPL b/LICENSE_AGPL new file mode 100644 index 0000000..8ed2483 --- /dev/null +++ b/LICENSE_AGPL @@ -0,0 +1,663 @@ +(C) 2022 Victor C Hall + + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..94e8230 --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ +# EveryDream Trainer 2.0 + +Welcome to 2.0 of EveryDream trainer! Now with more diffusers and even more features! + +Please join us on Discord! https://discord.gg/uheqxU6sXN + +If you find this tool useful, please consider subscribing to the project on Patreon or buy me a Ko-fi. The tools are open source and free, but it is a lot of work to maintain and develop and donations will allow me to expand capabilties and spend more time on the project. + +## Docs + +[Setup and installation](doc/SETUP.md) + +[Download and setup base models](doc/BASEMODELS.md) + +[Data Preparation](doc/DATA.md) + +[Training](doc/TRAINING.md) + +[Tweaking](doc/TWEAKING.md) diff --git a/activate_venv.bat b/activate_venv.bat new file mode 100644 index 0000000..513cbf2 --- /dev/null +++ b/activate_venv.bat @@ -0,0 +1 @@ +call venv/scripts/activate.bat \ No newline at end of file diff --git a/data/aspects.py b/data/aspects.py new file mode 100644 index 0000000..b6d2ef4 --- /dev/null +++ b/data/aspects.py @@ -0,0 +1,152 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +ASPECTS9 = [[1024,1024], # 1048576 1:1 + [1088,960],[960,1088], # 1044480 1.125:1 + [1152,896],[896,1152], # 1032192 1.286:1 + [1216,832],[832,1216], # 1011712 1.462:1 + [1344,768],[768,1344], # 1032192 1.75:1 + [1472,704],[704,1472], # 1036288 2.09:1 + [1600,640],[640,1600], # 1024000 2.5:1 + [1792,576],[576,1792], # 1032192 3.111:1 + [2048,512],[512,2048], # 1048576 4:1 + [2304,448],[448,2304], # 1032192 5.143:1 + [2688,384],[384,2688], # 1032192 7:1 +] + +ASPECTS8 = [[960,960], # 921600 1:1 + [1024,896],[896,1024], # 917504 1.143:1 + [1088,832],[832,1088], # 905216 1.308:1 + [1152,768],[768,1152], # 884736 1.5:1 + [1280,704],[704,1280], # 901120 1.818:1 + [1408,640],[640,1408], # 901120 2.2:1 + [1680,576],[576,1680], # 921600 2.778:1 + [1728,512],[512,1728], # 884736 3.375:1 + [1792,512],[512,1792], # 917504 3.5:1 + [2048,448],[448,2048], # 917504 4.714:1 + [2240,384],[384,2240], # 860160 5.833:1 + [2368,384],[384,2368], # 909312 6.17:1 +] + +ASPECTS7 = [[896,896], # 802816 1:1 + [960,832],[832,960], # 798720 1.153:1 + [1024,768],[768,1024], # 786432 1.333:1 + [1088,704],[704,1088], # 765952 1.545:1 + [1216,640],[640,1216], # 778240 1.9:1 + [1344,576],[576,1344], # 774144 2.333:1 + [1536,512],[512,1536], # 786432 3:1 + [1792,448],[448,1792], # 802816 4:1 + [2048,384],[384,2048], # 786432 5.333:1 +] + +ASPECTS6 = [[832,832], # 692224 1:1 + [896,768],[768,896], # 688128 1.167:1 + [960,704],[704,960], # 675840 1.364:1 + #[960,640],[640,960], # 614400 1.5:1 + [1024,640],[640,1024], # 655360 1.6:1 + [1152,576],[576,1152], # 663552 2:1 + [1216,512],[512,1216], # 622080 2.375:1 + #[1280,512],[512,1280], # 655360 2.5:1 + [1344,512],[512,1344], # 688128 2.625:1 + [1536,448],[448,1536], # 688128 3.429:1 + [1600,384],[384,1600], # 614400 4.167:1 + #[1664,384],[384,1664], # 638976 4.333:1 + [1728,384],[384,1728], # 663552 4.5:1 + [1792,384],[384,1792], # 688128 4.667:1 +] + +ASPECTS5 = [[768,768], # 589824 1:1 + [832,704],[704,832], # 585728 1.181:1 + [896,640],[640,896], # 573440 1.4:1 + [960,576],[576,960], # 552960 1.6:1 + [1024,576],[576,1024], # 524288 1.778:1 + [1088,512],[512,1088], # 497664 2.125:1 + [1152,512],[512,1152], # 589824 2.25:1 + #[1216,448],[448,1216], # 552960 2.714:1 + [1280,448],[448,1280], # 573440 2.857:1 + #[1344,384],[384,1344], # 518400 3.5:1 + [1408,384],[384,1408], # 540672 3.667:1 + [1472,320],[320,1472], # 470400 4.6:1 + [1536,320],[320,1536], # 491520 4.8:1 +] + +ASPECTS4 = [[704,704], # 501,376 1:1 + [768,640],[640,768], # 491,520 1.2:1 + [832,576],[576,832], # 458,752 1.444:1 + [896,512],[512,896], # 458,752 1.75:1 + [960,512],[512,960], # 491,520 1.875:1 + [1024,448],[448,1024], # 458,752 2.286:1 + [1088,448],[448,1088], # 487,424 2.429:1 + [1152,384],[384,1152], # 442,368 3:1 + #[1216,384],[384,1216], # 466,944 3.125:1 + [1280,384],[384,1280], # 491,520 3.333:1 + [1280,320],[320,1280], # 409,600 4:1 + #[1408,320],[320,1408], # 450,560 4.4:1 + [1536,320],[320,1536], # 491,520 4.8:1 +] + +ASPECTS3 = [[640,640], # 409600 1:1 + [704,576],[576,704], # 405504 1.25:1 + [768,512],[512,768], # 393216 1.5:1 + [832,448],[448,832], # 372736 1.857:1 + [896,448],[448,896], # 401408 2:1 + [1024,384],[384,1024], # 393216 2.667:1 + [1152,320],[320,1152], # 368640 3.6:1 + [1280,320],[320,1280], # 409600 4:1 + [1408,256],[256,1408], # 360448 5.5:1 + #[1472,256],[256,1472], # 376832 5.75:1 + #[1536,256],[256,1536], # 393216 6:1 + #[1600,256],[256,1600], # 409600 6.25:1 +] + +ASPECTS2 = [[576,576], # 331776 1:1 + [640,512],[512,640], # 327680 1.25:1 + #[640,448],[448,640], # 286720 1.4286:1 + [704,448],[448,704], # 314928 1.5625:1 + [832,384],[384,832], # 317440 2.1667:1 + [960,320],[320,960], # 307200 3:1 + #[1024,320],[320,1024], # 327680 3.2:1 + [1280,256],[256,1280], # 327680 5:1 +] + +ASPECTS = [[512,512], # 262144 1:1 + [576,448],[448,576], # 258048 1.29:1 + [640,384],[384,640], # 245760 1.667:1 + [768,320],[320,768], # 245760 2.4:1 + #[832,256],[256,832], # 212992 3.25:1 + [896,256],[256,896], # 229376 3.5:1 + #[960,256],[256,960], # 245760 3.75:1 + [1024,256],[256,1024], # 245760 4:1 + ] + +def get_aspect_buckets(resolution, square_only=False, reduced_buckets=False): + if resolution < 512: + raise ValueError("Resolution must be at least 512") + try: + rounded_resolution = int(resolution / 64) * 64 + if square_only: + return [[rounded_resolution, rounded_resolution]] + all_image_sizes = __get_all_aspects() + aspects = next(filter(lambda sizes: sizes[0][0]==rounded_resolution, all_image_sizes), None) + if reduced_buckets: + return aspects[0:2] + return aspects + except Exception as e: + print(f" *** Unsupported resolution of {resolution}, check your resolution config") + print(f" *** Value must be between 512 and 1024") + raise e + +def __get_all_aspects(): + return [ASPECTS, ASPECTS2, ASPECTS3, ASPECTS4, ASPECTS5, ASPECTS6, ASPECTS7, ASPECTS8, ASPECTS9] \ No newline at end of file diff --git a/data/data_loader.py b/data/data_loader.py new file mode 100644 index 0000000..8803cc2 --- /dev/null +++ b/data/data_loader.py @@ -0,0 +1,144 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import os +from PIL import Image +import random +from data.image_train_item import ImageTrainItem +import data.aspects as aspects + +class DataLoaderMultiAspect(): + """ + Data loader for multi-aspect-ratio training and bucketing + + data_root: root folder of training data + batch_size: number of images per batch + flip_p: probability of flipping image horizontally (i.e. 0-0.5) + """ + def __init__(self, data_root, seed=555, debug_level=0, batch_size=1, flip_p=0.0, resolution=512): + self.image_paths = [] + self.debug_level = debug_level + self.flip_p = flip_p + + self.aspects = aspects.get_aspect_buckets(resolution=resolution, square_only=False) + print(f"* DLMA resolution {resolution}, buckets: {self.aspects}") + print(" Preloading images...") + + self.__recurse_data_root(self=self, recurse_root=data_root) + random.Random(seed).shuffle(self.image_paths) + prepared_train_data = self.__prescan_images(self.image_paths, flip_p) # ImageTrainItem[] + self.image_caption_pairs = self.__bucketize_images(prepared_train_data, batch_size=batch_size, debug_level=debug_level) + + #if debug_level > 0: print(f" * DLMA Example: {self.image_caption_pairs[0]} images") + + def get_all_images(self): + return self.image_caption_pairs + + @staticmethod + def __read_caption_from_file(file_path, fallback_caption): + caption = fallback_caption + try: + with open(file_path, encoding='utf-8', mode='r') as caption_file: + caption = caption_file.read() + except: + print(f" *** Error reading {file_path} to get caption, falling back to filename") + caption = fallback_caption + pass + return caption + + def __prescan_images(self, image_paths: list, flip_p=0.0): + """ + Create ImageTrainItem objects with metadata for hydration later + """ + decorated_image_train_items = [] + + for pathname in image_paths: + caption_from_filename = os.path.splitext(os.path.basename(pathname))[0].split("_")[0] + + txt_file_path = os.path.splitext(pathname)[0] + ".txt" + caption_file_path = os.path.splitext(pathname)[0] + ".caption" + + if os.path.exists(txt_file_path): + caption = self.__read_caption_from_file(txt_file_path, caption_from_filename) + elif os.path.exists(caption_file_path): + caption = self.__read_caption_from_file(caption_file_path, caption_from_filename) + else: + caption = caption_from_filename + + image = Image.open(pathname) + width, height = image.size + image_aspect = width / height + + target_wh = min(self.aspects, key=lambda aspects:abs(aspects[0]/aspects[1] - image_aspect)) + + image_train_item = ImageTrainItem(image=None, caption=caption, target_wh=target_wh, pathname=pathname, flip_p=flip_p) + + decorated_image_train_items.append(image_train_item) + + return decorated_image_train_items + + @staticmethod + def __bucketize_images(prepared_train_data: list, batch_size=1, debug_level=0): + """ + Put images into buckets based on aspect ratio with batch_size*n images per bucket, discards remainder + """ + # TODO: this is not terribly efficient but at least linear time + buckets = {} + + for image_caption_pair in prepared_train_data: + target_wh = image_caption_pair.target_wh + + if (target_wh[0],target_wh[1]) not in buckets: + buckets[(target_wh[0],target_wh[1])] = [] + buckets[(target_wh[0],target_wh[1])].append(image_caption_pair) + + print(f" ** Number of buckets used: {len(buckets)}") + + if len(buckets) > 1: + for bucket in buckets: + truncate_count = len(buckets[bucket]) % batch_size + current_bucket_size = len(buckets[bucket]) + buckets[bucket] = buckets[bucket][:current_bucket_size - truncate_count] + + if debug_level > 0: + print(f" ** Bucket {bucket} with {current_bucket_size} will drop {truncate_count} images due to batch size {batch_size}") + + # flatten the buckets + image_caption_pairs = [] + for bucket in buckets: + image_caption_pairs.extend(buckets[bucket]) + + return image_caption_pairs + + @staticmethod + def __recurse_data_root(self, recurse_root): + for f in os.listdir(recurse_root): + current = os.path.join(recurse_root, f) + + if os.path.isfile(current): + ext = os.path.splitext(f)[1] + if ext in ['.jpg', '.jpeg', '.png', '.bmp', '.webp']: + self.image_paths.append(current) + + sub_dirs = [] + + for d in os.listdir(recurse_root): + current = os.path.join(recurse_root, d) + if os.path.isdir(current): + sub_dirs.append(current) + + for dir in sub_dirs: + self.__recurse_data_root(self=self, recurse_root=dir) diff --git a/data/dl_singleton.py b/data/dl_singleton.py new file mode 100644 index 0000000..d20f792 --- /dev/null +++ b/data/dl_singleton.py @@ -0,0 +1,2 @@ +# stop lightning's repeated instantiation of batch train/val/test classes causing multiple sweeps of the same data off disk +shared_dataloader = None diff --git a/data/ed_dl_wrap.py b/data/ed_dl_wrap.py new file mode 100644 index 0000000..26ef411 --- /dev/null +++ b/data/ed_dl_wrap.py @@ -0,0 +1,57 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import torch +from torch.utils.data import DataLoader +from data.every_dream import EveryDreamBatch + +class EveryDreamDataLoaderWrapper(DataLoader): + """ + Collates image:caption pairs into batches + """ + def __init__(self, batch_size: int, tokenizer, dataset: EveryDreamBatch): + self.dataset = dataset + self.tokenizer = tokenizer + + super().__init__(dataset, batch_size, shuffle=False, pin_memory=True) + #super().__init__(dataset, batch_size, shuffle=False, collate_fn=self.collate_fn, pin_memory=True) + + def collate_fn(self, batch): + """ + Collates batches of data + based on https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/train_dreambooth.py + """ + print("collate_fn") + print(len(batch)) + captions = [example["caption"] for example in batch] + images = [example["image"] for example in batch] + + print("collate_fn2") + images = torch.stack(images) + images = images.to(memory_format=torch.contiguous_format).float() + + print("collate_fn3") + captions = self.tokenizer.pad( + {"captions": captions}, + padding=True, + return_tensors="pt", + ).input_ids + + batch = { + "captions": captions, + "images": images, + } + print(f"{batch['captions']} {batch['images'].shape}") + return batch \ No newline at end of file diff --git a/data/ed_validate.py b/data/ed_validate.py new file mode 100644 index 0000000..f1ec8e3 --- /dev/null +++ b/data/ed_validate.py @@ -0,0 +1,70 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import numpy as np +from torch.utils.data import Dataset +from ldm.data.data_loader import DataLoaderMultiAspect as dlma +import math +import ldm.data.dl_singleton as dls +from ldm.data.image_train_item import ImageTrainItem + +class EDValidateBatch(Dataset): + def __init__(self, + data_root, + flip_p=0.0, + repeats=1, + debug_level=0, + batch_size=1, + set='val', + ): + self.data_root = data_root + self.batch_size = batch_size + + if not dls.shared_dataloader: + print("Creating new dataloader singleton") + dls.shared_dataloader = dlma(data_root=data_root, debug_level=debug_level, batch_size=self.batch_size, flip_p=flip_p) + + self.image_train_items = dls.shared_dataloader.get_all_images() + + self.num_images = len(self.image_train_items) + + self._length = max(math.trunc(self.num_images * repeats), batch_size) - self.num_images % self.batch_size + + print() + print(f" ** Validation Set: {set}, steps: {self._length / batch_size:.0f}, repeats: {repeats} ") + print() + + def __len__(self): + return self._length + + def __getitem__(self, i): + idx = i % self.num_images + image_train_item = self.image_train_items[idx] + + example = self.__get_image_for_trainer(image_train_item) + return example + + @staticmethod + def __get_image_for_trainer(image_train_item: ImageTrainItem): + example = {} + + image_train_tmp = image_train_item.hydrate() + + example["image"] = image_train_tmp.image + example["caption"] = image_train_tmp.caption + + return example + \ No newline at end of file diff --git a/data/every_dream.py b/data/every_dream.py new file mode 100644 index 0000000..2a5614a --- /dev/null +++ b/data/every_dream.py @@ -0,0 +1,158 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import torch +from torch.utils.data import Dataset +from data.data_loader import DataLoaderMultiAspect as dlma +import math +import data.dl_singleton as dls +from data.image_train_item import ImageTrainItem +import random +from torchvision import transforms +from transformers import CLIPTokenizer +import torch.nn.functional as F + +class EveryDreamBatch(Dataset): + """ + data_root: root path of all your training images, will be recursively searched for images + repeats: how many times to repeat each image in the dataset + flip_p: probability of flipping the image horizontally + debug_level: 0=none, 1=print drops due to unfilled batches on aspect ratio buckets, 2=debug info per image, 3=save crops to disk for inspection + batch_size: how many images to return in a batch + conditional_dropout: probability of dropping the caption for a given image + resolution: max resolution (relative to square) + jitter: number of pixels to jitter the crop by, only for non-square images + """ + def __init__(self, + data_root, + flip_p=0.0, + debug_level=0, + batch_size=1, + conditional_dropout=0.02, + resolution=512, + crop_jitter=20, + seed=555, + tokenizer=None, + ): + self.data_root = data_root + self.batch_size = batch_size + self.debug_level = debug_level + self.conditional_dropout = conditional_dropout + self.crop_jitter = crop_jitter + self.unloaded_to_idx = 0 + self.tokenizer = tokenizer + #print(f"tokenizer: {tokenizer}") + self.max_token_length = self.tokenizer.model_max_length + + if seed == -1: + seed = random.randint(0, 99999) + + if not dls.shared_dataloader: + print(" * Creating new dataloader singleton") + dls.shared_dataloader = dlma(data_root=data_root, seed=seed, debug_level=debug_level, batch_size=self.batch_size, flip_p=flip_p, resolution=resolution) + + self.image_train_items = dls.shared_dataloader.get_all_images() + + # for iti in self.image_train_items: + # print(f"iti caption:{iti.caption}") + # exit() + self.num_images = len(self.image_train_items) + + self._length = self.num_images + + self.image_transforms = transforms.Compose( + [ + transforms.ToTensor(), + transforms.Normalize([0.5], [0.5]), + ] + ) + + print() + print(f" ** Trainer Set: {self._length / batch_size:.0f}, num_images: {self.num_images}, batch_size: {self.batch_size}, length w/repeats: {self._length}") + print() + + def __len__(self): + return self._length + + def __getitem__(self, i): + #print(" * Getting item", i) + # batch = dict() + # batch["images"] = list() + # batch["captions"] = list() + # first = True + # for j in range(i, i + self.batch_size - 1): + # if j < self.num_images: + # example = self.__get_image_for_trainer(self.image_train_items[j], self.debug_level) + # if first: + # print(f"first example {j}", example) + # batch["images"] = [torch.from_numpy(example["image"])] + # batch["captions"] = [example["caption"]] + # first = False + # else: + # print(f"subsiquent example {j}", example) + # batch["images"].extend(torch.from_numpy(example["image"])) + # batch["captions"].extend(example["caption"]) + example = {} + + train_item = self.__get_image_for_trainer(self.image_train_items[i], self.debug_level) + #example["image"] = torch.from_numpy(train_item["image"]) + example["image"] = self.image_transforms(train_item["image"]) + # if train_item["caption"] == " ": + # example["tokens"] = [0 for i in range(self.max_token_length-2)] + # else: + if random.random() > self.conditional_dropout: + example["tokens"] = self.tokenizer(train_item["caption"], + #padding="max_length", + truncation=True, + padding=False, + add_special_tokens=False, + max_length=self.max_token_length-2, + ).input_ids + example["tokens"] = torch.tensor(example["tokens"]) + else: + example["tokens"] = torch.zeros(75, dtype=torch.int) + #print(f"bos: {self.tokenizer.bos_token_id}{self.tokenizer.eos_token_id}") + + #print(f"example['tokens']: {example['tokens']}") + pad_amt = self.max_token_length-2 - len(example["tokens"]) + example['tokens']= F.pad(example['tokens'],pad=(0,pad_amt),mode='constant',value=0) + example['tokens']= F.pad(example['tokens'],pad=(1,0),mode='constant',value=int(self.tokenizer.bos_token_id)) + eos_int = int(self.tokenizer.eos_token_id) + #eos_int = int(0) + example['tokens']= F.pad(example['tokens'],pad=(0,1),mode='constant',value=eos_int) + #print(f"__getitem__ train_item['caption']: {train_item['caption']}") + #print(f"__getitem__ train_item['pathname']: {train_item['pathname']}") + #print(f"__getitem__ example['tokens'] pad: {example['tokens']}") + + example["caption"] = train_item["caption"] # for sampling if needed + #print(f"len tokens: {len(example['tokens'])} cap: {example['caption']}") + + return example + + def __get_image_for_trainer(self, image_train_item: ImageTrainItem, debug_level=0): + example = {} + + save = debug_level > 2 + + image_train_tmp = image_train_item.hydrate(crop=False, save=save, crop_jitter=self.crop_jitter) + + example["image"] = image_train_tmp.image + + # if random.random() > self.conditional_dropout: + example["caption"] = image_train_tmp.caption + # else: + # example["caption"] = " " + #print(f" {image_train_tmp.pathname}: {image_train_tmp.caption}") + return example diff --git a/data/image_train_item.py b/data/image_train_item.py new file mode 100644 index 0000000..e9214b6 --- /dev/null +++ b/data/image_train_item.py @@ -0,0 +1,144 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import PIL +import numpy as np +from torchvision import transforms, utils +import random +import math +import os + +_RANDOM_TRIM = 0.04 + +class ImageTrainItem(): + """ + image: PIL.Image + identifier: caption, + target_aspect: (width, height), + pathname: path to image file + flip_p: probability of flipping image (0.0 to 1.0) + """ + def __init__(self, image: PIL.Image, caption: str, target_wh: list, pathname: str, flip_p=0.0): + self.caption = caption + self.target_wh = target_wh + self.pathname = pathname + self.flip = transforms.RandomHorizontalFlip(p=flip_p) + self.cropped_img = None + + if image is None: + self.image = [] + else: + self.image = image + + def hydrate(self, crop=False, save=False, crop_jitter=20): + """ + crop: hard center crop to 512x512 + save: save the cropped image to disk, for manual inspection of resize/crop + crop_jitter: randomly shift cropp by N pixels when using multiple aspect ratios to improve training quality + """ + if not hasattr(self, 'image') or len(self.image) == 0: + self.image = PIL.Image.open(self.pathname).convert('RGB') + + width, height = self.image.size + if crop: + cropped_img = self.__autocrop(self.image) + self.image = cropped_img.resize((512,512), resample=PIL.Image.BICUBIC) + else: + width, height = self.image.size + jitter_amount = random.randint(0,crop_jitter) + + if self.target_wh[0] == self.target_wh[1]: + if width > height: + left = random.randint(0, width - height) + self.image = self.image.crop((left, 0, height+left, height)) + width = height + elif height > width: + top = random.randint(0, height - width) + self.image = self.image.crop((0, top, width, width+top)) + height = width + elif width > self.target_wh[0]: + slice = min(int(self.target_wh[0] * _RANDOM_TRIM), width-self.target_wh[0]) + slicew_ratio = random.random() + left = int(slice*slicew_ratio) + right = width-int(slice*(1-slicew_ratio)) + sliceh_ratio = random.random() + top = int(slice*sliceh_ratio) + bottom = height- int(slice*(1-sliceh_ratio)) + + self.image = self.image.crop((left, top, right, bottom)) + else: + image_aspect = width / height + target_aspect = self.target_wh[0] / self.target_wh[1] + if image_aspect > target_aspect: + new_width = int(height * target_aspect) + jitter_amount = max(min(jitter_amount, int(abs(width-new_width)/2)), 0) + left = jitter_amount + right = left + new_width + self.image = self.image.crop((left, 0, right, height)) + else: + new_height = int(width / target_aspect) + jitter_amount = max(min(jitter_amount, int(abs(height-new_height)/2)), 0) + top = jitter_amount + bottom = top + new_height + self.image = self.image.crop((0, top, width, bottom)) + self.image = self.image.resize(self.target_wh, resample=PIL.Image.BICUBIC) + + self.image = self.flip(self.image) + + if type(self.image) is not np.ndarray: + if save: + base_name = os.path.basename(self.pathname) + if not os.path.exists("test/output"): + os.makedirs("test/output") + self.image.save(f"test/output/{base_name}") + + self.image = np.array(self.image).astype(np.uint8) + + self.image = (self.image / 127.5 - 1.0).astype(np.float32) + + #print(self.image.shape) + + return self + + @staticmethod + def __autocrop(image: PIL.Image, q=.404): + """ + crops image to a random square inside small axis using a truncated gaussian distribution across the long axis + """ + x, y = image.size + + if x != y: + if (x>y): + rand_x = x-y + sigma = max(rand_x*q,1) + else: + rand_y = y-x + sigma = max(rand_y*q,1) + + if (x>y): + x_crop_gauss = abs(random.gauss(0, sigma)) + x_crop = min(x_crop_gauss,(x-y)/2) + x_crop = math.trunc(x_crop) + y_crop = 0 + else: + y_crop_gauss = abs(random.gauss(0, sigma)) + x_crop = 0 + y_crop = min(y_crop_gauss,(y-x)/2) + y_crop = math.trunc(y_crop) + + min_xy = min(x, y) + image = image.crop((x_crop, y_crop, x_crop + min_xy, y_crop + min_xy)) + + return image \ No newline at end of file diff --git a/data/latent_cache.py b/data/latent_cache.py new file mode 100644 index 0000000..6526539 --- /dev/null +++ b/data/latent_cache.py @@ -0,0 +1,121 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import torch +import os +import hashlib +import io +from PIL import Image, ImageOps +import random +from aspects import get_aspect_buckets +from torchvision import transforms + +class LatentCacheItem(): + """ + caches image/caption latent pairs and index value to select appropriate random crop jitter + """ + def __init__(self, imagelatent, captionembedding, cropjitteridx, resolution = tuple): + """ + imagelatent: image tensor + captionembedding: caption embedding tensor + cropjitteridx: index of random crop jitter to use + """ + self.imagelatent = imagelatent + self.captionembedding = captionembedding + self.cropjitteridx = cropjitteridx + self.resolution = resolution + + def __repr__(self): + return f"lat: {self.imagelatent.shape} emb:{self.captionembedding.shape} cj:{self.cropjitteridx}" + +class LatentCacheManager(): + """ + Manages a cache of latent vectors for a dataset. + """ + def __init__(self, latent_cache_path="/.cache/latents", device=torch.device("cuda"), jitter_lim=8, vae=None): + """ + Manages caching of image latents to disk, + latent_cache_path: path to latent cache folder + device: device to use for creating latents (torch.device) + vae: vae to use for creating latents + jitter_lim: number of random crop jitters to use per image (default: 8) + """ + assert vae is not None, "LatentCacheManager requires a vae to be passed in" + + self.cache = dict(str, []) # key: sha256 hash of image path, value: list of LatentCacheItem + self.latentcachepath = latent_cache_path + self.jitter_lim = jitter_lim + self.device = device + self.vae = vae + + # create pt file if it doesn't exist + if not os.path.exists(self.latentcachepath): + torch.save(self.cache, self.latentcachepath) + + self.vae_on_device = False + + def set_vae(self, vae): + self.vae = vae + + def delete_vae(self): + self.vae = None + + def vae_to_device(self, device): + self.vae.to(self.device) + self.vae_on_device = True + + def vae_to_cpu(self): + self.vae.to("cpu") + self.vae_on_device = False + + @staticmethod + def __hash(imagepath): + return hashlib.sha256(imagepath.encode("utf-8")).hexdigest() + + def add(self, imagepath: io, captionembedding: torch.tensor, target_resolution=(512,512)): + """ + adds aan item to the cache + """ + if not self.vae_on_device: self.vae_to_gpu() + hash = self.__hash(imagepath) + + image = Image.open(imagepath) + image_aspects = get_aspect_buckets(resolution=target_resolution) + + for i in range(self.jitter_lim): + bleed = random.uniform(0.0, 0.02) + centering = (random.uniform(0.0, 0.02), random.uniform(0.0, 0.02)) + jittered_image = ImageOps.fit(image, target_resolution, method=Image.BICUBIC, bleed=bleed, centering=centering) + # convert to tensor + latent = self.vae(jittered_image) + # add to cache + self.cache[hash].append(LatentCacheItem(imagelatent=latent, + captionembedding=captionembedding, + i, + resolution=self.vae.resolution)) + + + + # append to pt file + torch.save(self.cache, os.path.join(self.latentcachepath, f"{hash}.pt")) + + def __getitem__(self, imagepath, cropjitteridx=0): + """ + returns a LatentCacheItem by imagepath key + """ + hash = self.__hash(imagepath) + + item = self.cache[hash][cropjitteridx] + return item diff --git a/doc/BASEMODELS.md b/doc/BASEMODELS.md new file mode 100644 index 0000000..f8c3344 --- /dev/null +++ b/doc/BASEMODELS.md @@ -0,0 +1,70 @@ +# Download and setup base models + +In order to train, you need a base model on which to train. This is a one-time setup to configure base models when you want to use a particular base. + +Make sure the trainer is installed properly first. See [SETUP.md](doc/SETUP.md) for more details. + +When you finish you should see something like this, come back to reference this picture as you go through the steps below: + +![models](ckptcache.png) + +## Download models + +You need some sort of base model to start training. I suggest these two: + +Stable Diffusion 1.5 with improved VAE: + +https://huggingface.co/panopstor/EveryDream/blob/main/sd_v1-5_vae.ckpt + +SD2.1 768: + +https://huggingface.co/stabilityai/stable-diffusion-2-1/blob/main/v2-1_768-nonema-pruned.ckpt + +You can use SD2.0 512 as well, but typically SD1.5 is going to be better. + +https://huggingface.co/stabilityai/stable-diffusion-2-base/blob/main/512-base-ema.ckpt + +Place these in the root folder of EveryDream2. + +Run these commands *one time* to prepare them. **It's very important to use the correct YAML!** + +For SD1.x models, use this (note it will spill a lot of warnings to the console, but its fine): + + python utils/convert_original_stable_diffusion_to_diffusers.py --scheduler_type ddim ^ + --original_config_file v1-inference.yaml ^ + --image_size 512 ^ + --checkpoint_path sd_v1-5_vae.ckpt ^ + --prediction_type epsilon ^ + --upcast_attn False ^ + --dump_path "ckpt_cache/sd_v1-5_vae" + +And the SD2.1 768 model (uses v2-v yaml and "v_prediction" prediction type): + + python utils/convert_original_stable_diffusion_to_diffusers.py --scheduler_type ddim ^ + --original_config_file v2-inference-v.yaml ^ + --image_size 768 ^ + --checkpoint_path v2-1_768-ema-pruned.ckpt ^ + --prediction_type v_prediction ^ + --upcast_attn False ^ + --dump_path "ckpt_cache/v2-1_768-ema-pruned" + +And finally the SD2.0 512 base model (generally not recommended base model): + + python utils/convert_original_stable_diffusion_to_diffusers.py --scheduler_type ddim ^ + --original_config_file v2-inference.yaml ^ + --image_size 512 ^ + --checkpoint_path 512-base-ema.ckpt ^ + --prediction_type epsilon ^ + --upcast_attn False ^ + --dump_path "ckpt_cache/512-base-ema" + +If you have other models, you need to know the base model that was used for them, **in particular use the correct yaml (original_config_file) or it will not properly convert.** Make sure to put some sort of name in the dump_path after "ckpt_cache/" so you can reference it later. + +All of the above is one time. After running, you will use --resume_ckpt and just name the file without "ckpt_cache/" + +ex. + + python train.py --resume_ckpt "sd_v1-5_vae" ... + python train.py --resume_ckpt "v2-1_768-ema-pruned" ... + python train.py --resume_ckpt "512-base-ema" ... + diff --git a/doc/DATA.md b/doc/DATA.md new file mode 100644 index 0000000..05933ff --- /dev/null +++ b/doc/DATA.md @@ -0,0 +1,42 @@ +# Data organization + +Since this trainer relies on having captions for your training images you will need to decide how you want deal with this. + +There are two currently supported methods to retrieve captions: + +1. Name the files with the caption. Underscore marks the end of the captoin (ex. "john smith on a boat_999.jpg") +2. Put your captions for each image in a .txt file with the same name as the image. All UTF-8 text is supported with no reserved or special case characters. (ex. 00001.jpg, 00001.txt) + +You will need to place all your images and captions into a folder. Inside that folder, you can use subfolders to organize data as you please. The trainer will recursively search for images and captions. It may be useful, for instance, to split each character into a subfolder, and have other subfolders for cityscapes, etc. + +When you train, you will use "--data_root" to point to the root folder of your data. All images in that folder and its subfolders will be used for training. + +# Data preparation + +## Image size + +The trainer will automatically fit your images to the best possible size. It is best to leave your images larger tham you may think for typical Stable Diffusion training. Even 4K images will be handled fine so just don't sweat it if you have large images. The only downside is they take a bit more disk space. + +Current recommendation is 1 megapixel (ex 1100x100, 1300x900, etc) or larger, but thinking ahead to future technology advancements you may wish to keep them at even larger resolutions. Again, don't worry about the trainer squeezing or cropping, it will handle it! + +Aspect ratios up to 4:1 or 1:4 are supported. Again, just don't worry about this too much. The trainer will handle it. + +## Cropping + +You can crop your images in an image editor *if you need, in order to get good close ups of things like faces, or to split images up that contain multiple characters.* As above, make sure **after** cropping your images are still fairly large. It is ok to use a full shot of two characters in one image and also a cropped version of each character separately, but make sure every image is captioned appropriately for what is actually present in each image. + +## Captions + +For most use cases, use a sane English sentence to describe the image. Try to put your character or main object name close to the start. + +### Styles + +For style, consider adding a suffix on the caption that describes the style. Examples would be "by claude monet" or "in the style of gta box art" at the end of the caption. This will help the model learn recall style at inference time so you can style other subjects you did not train with the style. You may also consider "drawing of" or "painting of" at the start of the caption when appropriate. + +Consider also including a style tag as above if you are training anything besides photos. For instance, if you are training a few characters from a video game you can consider "cloud strife holding a buster sword, screenshot from final fantasy for ps5" if you wish to capture the style of the game along with the characters. + +### Context + +Include the surroundings and context in your captions. Ex. "cloud strife standing on a dirt path in midgar city slums district" Again, this will allow you to recall the "dirt path in midgar city slums district" style at inference time, and will even pick up on pieces of that like "midgar city" (if enough samples are present with similar words) as a style you can apply later! + +Also consider some basic mention of pose. ex. "clouds strife sitting on a blue wooden bench in front of a concrete wall" or "barrett wallace holding his fist in front of his face with an angry look on his face, looking at the camera." Captions can capture value not only for the character's look, but also for the pose, the background scene, and the camera angle. You can be creative here, there is a lot of potential! \ No newline at end of file diff --git a/doc/INSTALL.md b/doc/INSTALL.md new file mode 100644 index 0000000..a4f9a5b --- /dev/null +++ b/doc/INSTALL.md @@ -0,0 +1,24 @@ +# Installation + +## Windows + +* Open a normal windows command prompt and run `windows_setup.bat` from the command line. +*Do **not** double click the file from Windows File Explorer*, you need the command window open. + +* While that is running, download the official xformers windows wheel from this URL: +https://github.com/facebookresearch/xformers/suites/9544395581/artifacts/454051141 + +* Unzip the xformers file to the EveryDream2 folder + +* Check your command line window to make sure no errors occured. If you have errors, please post them in the Discord and ask for assistance. + +* Once the command line is done with no errors, paste this command into the command prompt: + + `pip install xformers-0.0.15.dev0+303e613.d20221128-cp310-cp310-win_amd64.whl` + +* When you want to train in the future after closing the command line, run `activate_venv.bat` from the command line to activate the virtual environment again. (hint: you can type `a` then press tab, then press enter) + +## Next step + +Read the documentation to setup your base models from which you will train. +[Base Model setup](doc/BASEMODELS.md) \ No newline at end of file diff --git a/doc/SETUP.md b/doc/SETUP.md new file mode 100644 index 0000000..e40ce88 --- /dev/null +++ b/doc/SETUP.md @@ -0,0 +1,94 @@ +## Install Python + +Install Python 3.10 from here: + +https://www.python.org/downloads/release/python-3109/ + +https://www.python.org/ftp/python/3.10.9/python-3.10.9-amd64.exe + +Download and install Git from [git-scm.com](https://git-scm.com/). + +or [Git for windows](https://gitforwindows.org/) + +## Clone this repo +Clone the repo from normal command line then change into the directory: + + git clone https://github.com/victorchall/EveryDream-trainer2 + + cd EveryDream-trainer2 + +## Download models + +You need some sort of base model to start training. I suggest these two: + +Stable Diffusion 1.5 with improved VAE: + +https://huggingface.co/panopstor/EveryDream/blob/main/sd_v1-5_vae.ckpt + +SD2.1 768: + +https://huggingface.co/stabilityai/stable-diffusion-2-1/blob/main/v2-1_768-nonema-pruned.ckpt + +You can use SD2.0 512 as well, but typically SD1.5 is going to be better. + +https://huggingface.co/stabilityai/stable-diffusion-2-base/blob/main/512-base-ema.ckpt + +Place these in the root folder of EveryDream2. + +Run these commands *one time* to prepare them: + +For SD1.x models, use this: + + python utils/convert_original_stable_diffusion_to_diffusers.py --scheduler_type ddim ^ + --original_config_file v1-inference.yaml ^ + --image_size 768 ^ + --checkpoint_path sd_v1-5_vae.ckpt ^ + --prediction_type epsilon ^ + --upcast_attn False ^ + --pipeline_type FrozenOpenCLIPEmbedder ^ + --dump_path "ckpt_cache/sd_v1-5_vae" + +And the SD2.1 768 model: + + python utils/convert_original_stable_diffusion_to_diffusers.py --scheduler_type ddim ^ + --original_config_file v2-inference-v.yaml ^ + --image_size 768 ^ + --checkpoint_path v2-1_768-ema-pruned.ckpt ^ + --prediction_type v_prediction ^ + --upcast_attn False ^ + --pipeline_type FrozenOpenCLIPEmbedder ^ + --dump_path "ckpt_cache/v2-1_768-ema-pruned" + +And finally the SD2.0 512 base model (generally not recommended base model): + + python utils/convert_original_stable_diffusion_to_diffusers.py --scheduler_type ddim ^ + --original_config_file v2-inference.yaml ^ + --image_size 768 ^ + --checkpoint_path 512-base-ema.ckpt ^ + --prediction_type epsilon ^ + --upcast_attn False ^ + --pipeline_type FrozenOpenCLIPEmbedder ^ + --dump_path "ckpt_cache/512-base-ema" + +If you have other models, you need to know the base model that was used for them, in particular use the correct yaml (original_config_file) or it will not properly convert. + +All of the above is one time. After running, you will use --resume_ckpt and just name the file without "ckpt_cache" + +ex. + + python train.py --resume_ckpt "sd_v1-5_vae" ... + python train.py --resume_ckpt "v2-1_768-ema-pruned" ... + python train.py --resume_ckpt "512-base-ema" ... + +## Windows + + +Run windows_setup.bat to create your venv and install dependencies. + + windows_setup.bat + + +## Linux, Linux containers, or WSL + +TBD + diff --git a/doc/TRAINING.md b/doc/TRAINING.md new file mode 100644 index 0000000..5340e50 --- /dev/null +++ b/doc/TRAINING.md @@ -0,0 +1,67 @@ + +Here are some example commands to get you started, you can copy paste them into your command line and press enter. +Make sure the last line does not have ^ but all other lines do. + + +Training examples: + +Resuming from a checkpoint, 50 epochs, 6 batch size, 3e-6 learning rate, cosine scheduler, generate samples evern 200 steps, 10 minute checkpoint interval, adam8bit, and using the default "input" folder for training data: + + python train.py --resume_ckpt "sd_v1-5_vae" ^ + --max_epochs 50 ^ + --data_root "R:\everydream-trainer\training_samples\mega\ff7r\man_ff7r\cloud" ^ + --lr_scheduler cosine ^ + --lr_decay_steps 1500 ^ + --project_name myproj ^ + --batch_size 6 ^ + --sample_steps 200 ^ + --lr 3e-6 ^ + --ckpt_every_n_minutes 10 ^ + --useadam8bit + +Training from SD2 512 base model, 18 epochs, 4 batch size, 1.2e-6 learning rate, constant LR, generate samples evern 100 steps, 30 minute checkpoint interval, adam8bit, using imagesin the x:\mydata folder, training at resolution class of 640: + + python train.py --resume_ckpt "512-base-ema" ^ + --data_root "x:\mydata" ^ + --max_epochs 18 ^ + --lr_scheduler constant ^ + --project_name myproj ^ + --batch_size 4 ^ + --sample_steps 100 ^ + --lr 1.2e-6 ^ + --resolution 640 ^ + --clip_grad_norm 1 ^ + --ckpt_every_n_minutes 30 ^ + --useadam8bit + + python train.py --resume_ckpt "SD21" ^ + --data_root "R:\everydream-trainer\training_samples\mega\gt\objects\jets" ^ + --max_epochs 50 ^ + --lr_scheduler cosine ^ + --lr_decay_steps 1500 ^ + --lr_warmup_steps 20 ^ + --project_name myproj ^ + --batch_size 6 ^ + --sample_steps 100 ^ + --lr 1.5e-6 ^ + --ckpt_every_n_minutes 15 ^ + --useadam8bit ^ + --clip_grad_norm 1 ^ + + +Copy paste the above to your command line and press enter. +Make sure the last line does not have ^ but all other lines do + + +Scheduler example, note warmup and decay dont work with constant (default), warmup is set automatically to 5% of decay if not set +--lr_scheduler cosine +--lr_warmup_steps 100 +--lr_decay_steps 2500 + +Warmup and decay only count for some schedulers! Constant is not one of them. + +Currently "constant" and "cosine" are recommended. I'll add support to others upon request. + +How to resume: +Point your resume_ckpt to the path in logs like so: +--resume_ckpt "R:\ed3\logs\myproj20221213-161620\ckpts\myproj-ep22-gs01099" ^ diff --git a/sample_prompts.txt b/sample_prompts.txt new file mode 100644 index 0000000..e69de29 diff --git a/train.py b/train.py new file mode 100644 index 0000000..db22ea6 --- /dev/null +++ b/train.py @@ -0,0 +1,674 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +import os +import sys +import math +import signal +import argparse +import logging +import time + +import torch.nn.functional as torch_functional +from torch.cuda.amp import autocast +import torchvision.transforms as transforms + +from colorama import Fore, Style, Cursor +import numpy as np +import itertools +import torch +import datetime +import json +from PIL import Image, ImageDraw, ImageFont + +from diffusers import StableDiffusionPipeline, AutoencoderKL, UNet2DConditionModel, DDIMScheduler, DiffusionPipeline, DDPMScheduler, PNDMScheduler, EulerAncestralDiscreteScheduler +#from diffusers.models import AttentionBlock +from diffusers.optimization import get_scheduler +from diffusers.utils.import_utils import is_xformers_available +from transformers import CLIPTextModel, CLIPTokenizer +#from accelerate import Accelerator +from accelerate.utils import set_seed + +import wandb +from torch.utils.tensorboard import SummaryWriter +from tqdm.auto import tqdm + +from data.every_dream import EveryDreamBatch +from utils.convert_diffusers_to_stable_diffusion import convert as converter +from utils.gpu import GPU + +_GRAD_ACCUM_STEPS = 1 # future use... +_SIGTERM_EXIT_CODE = 130 + +def convert_to_hf(ckpt_path): + hf_cache = os.path.join("ckpt_cache", os.path.basename(ckpt_path)) + + if os.path.isfile(ckpt_path): + if not os.path.exists(hf_cache): + os.makedirs(hf_cache) + logging.info(f"Converting {ckpt_path} to Diffusers format") + import utils.convert_original_stable_diffusion_to_diffusers as convert + convert.convert(ckpt_path, f"ckpt_cache/{ckpt_path}") + return hf_cache + elif os.path.isdir(hf_cache): + return hf_cache + else: + return ckpt_path + +def setup_local_logger(args): + """ + configures logger with file and console logging, logs args, and returns the datestamp + """ + log_path = "logs" + if not os.path.exists(log_path): + os.makedirs(log_path) + + json_config = json.dumps(vars(args), indent=2) + # write current time and date stamp to string + datetimestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + + logfilename = os.path.join(log_path, f"{args.project_name}-train{datetimestamp}.log") + with open(logfilename, "w") as f: + f.write(f"Training config:\n{json_config}\n") + + logging.basicConfig(filename=logfilename, + level=logging.INFO, + format="%(asctime)s %(message)s", + datefmt="%m/%d/%Y %I:%M:%S %p", + ) + + logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) + return datetimestamp + +def log_optimizer(optimizer: torch.optim.Optimizer, betas, epsilon): + logging.info(f"{Fore.CYAN} * Optimizer: {optimizer.__class__.__name__} *{Style.RESET_ALL}") + logging.info(f" betas: {betas}, epsilon: {epsilon} *{Style.RESET_ALL}") + +def save_optimizer(optimizer: torch.optim.Optimizer, path: str): + """ + Saves the optimizer state + """ + torch.save(optimizer.state_dict(), path) + +def load_optimizer(optimizer, path: str): + """ + Loads the optimizer state + """ + optimizer.load_state_dict(torch.load(path)) + +def get_gpu_memory(nvsmi): + """ + returns the gpu memory usage + """ + gpu_query = nvsmi.DeviceQuery('memory.used, memory.total') + gpu_used_mem = int(gpu_query['gpu'][0]['fb_memory_usage']['used']) + gpu_total_mem = int(gpu_query['gpu'][0]['fb_memory_usage']['total']) + return gpu_used_mem, gpu_total_mem + +def append_epoch_log(global_step: int, epoch_pbar, gpu, log_writer, **logs): + """ + updates the vram usage for the epoch + """ + gpu_used_mem, gpu_total_mem = gpu.get_gpu_memory() + log_writer.add_scalar("performance/vram", gpu_used_mem, global_step) + epoch_mem_color = Style.RESET_ALL + if gpu_used_mem > 0.93 * gpu_total_mem: + epoch_mem_color = Fore.LIGHTRED_EX + elif gpu_used_mem > 0.85 * gpu_total_mem: + epoch_mem_color = Fore.LIGHTYELLOW_EX + elif gpu_used_mem > 0.7 * gpu_total_mem: + epoch_mem_color = Fore.LIGHTGREEN_EX + elif gpu_used_mem < 0.5 * gpu_total_mem: + epoch_mem_color = Fore.LIGHTBLUE_EX + + if logs is not None: + epoch_pbar.set_postfix(**logs, vram=f"{epoch_mem_color}{gpu_used_mem}/{gpu_total_mem} MB{Style.RESET_ALL} gs:{global_step}") + + +def main(args): + """ + Main entry point + """ + log_time = setup_local_logger(args) + + seed = 555 + set_seed(seed) + gpu = GPU() + + @torch.no_grad() + def __save_model(save_path, unet, text_encoder, tokenizer, scheduler, vae): + """ + Save the model to disk + """ + global global_step + if global_step is None or global_step == 0: + logging.warning(" No model to save, something likely blew up on startup, not saving") + return + logging.info(f" * Saving diffusers model to {save_path}") + pipeline = StableDiffusionPipeline( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + scheduler=scheduler, + safety_checker=None, # save vram + requires_safety_checker=None, # avoid nag + feature_extractor=None, # must be none of no safety checker + ) + pipeline.save_pretrained(save_path) + sd_ckpt_path = f"{os.path.basename(save_path)}.ckpt" + sd_ckpt_full = os.path.join(os.curdir, sd_ckpt_path) + + logging.info(f" * Saving SD model to {sd_ckpt_full}") + converter(model_path=save_path, checkpoint_path=sd_ckpt_full, half=True) + # optimizer_path = os.path.join(save_path, "optimizer.pt") + + # if self.save_optimizer_flag: + # logging.info(f" Saving optimizer state to {save_path}") + # self.save_optimizer(self.ctx.optimizer, optimizer_path) + + @torch.no_grad() + def __create_inference_pipe(unet, text_encoder, tokenizer, scheduler, vae): + """ + creates a pipeline for SD inference + """ + pipe = StableDiffusionPipeline( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + scheduler=scheduler, + safety_checker=None, # save vram + requires_safety_checker=None, # avoid nag + feature_extractor=None, # must be none of no safety checker + ) + if is_xformers_available(): + try: + pipe.enable_xformers_memory_efficient_attention() + except Exception as ex: + pass + return pipe + + def __generate_sample(pipe: StableDiffusionPipeline, prompt : str, cfg: float, resolution: int): + """ + generates a single sample at a given cfg scale and saves it to disk + """ + gen = torch.Generator(device="cuda").manual_seed(555) + with torch.no_grad(), autocast(): + image = pipe(prompt, + num_inference_steps=30, + num_images_per_prompt=1, + guidance_scale=cfg, + generator=gen, + height=resolution, + width=resolution, + ).images[0] + + draw = ImageDraw.Draw(image) + font = ImageFont.truetype(font="arial.ttf", size=24) + print_msg = f"cfg:{cfg:.1f}" + + l, t, r, b = draw.textbbox(xy=(0,0), text=print_msg, font=font) + text_width = r - l + text_height = b - t + + x = float(image.width - text_width - 10) + y = float(image.height - text_height - 10) + + draw.rectangle((x, y, image.width, image.height), fill="white") + draw.text((x, y), print_msg, fill="black", font=font) + del draw, font + return image + + #@torch.no_grad() + def __generate_test_samples(pipe, prompts, gs, log_writer, log_folder, random_captions=False, resolution=512): + """ + generates samples at different cfg scales and saves them to disk + """ + logging.info(f"Generating samples gs:{gs}, for {prompts}") + + #with torch.inference_mode(), suppress_stdout(): + #with autocast(): + i = 0 + for prompt in prompts: + if prompt is None or len(prompt) < 2: + logging.warning("empty prompt in sample prompts, check your prompts file") + continue + images = [] + for cfg in [7.0, 4.0, 1.01]: + image = __generate_sample(pipe, prompt, cfg, resolution=resolution) + images.append(image) + + width = 0 + height = 0 + for image in images: + width += image.width + height = max(height, image.height) + + result = Image.new('RGB', (width, height)) + + x_offset = 0 + for image in images: + result.paste(image, (x_offset, 0)) + x_offset += image.width + + result.save(f"{log_folder}/samples/gs{gs:05}-{prompt[:150]}.png") + + tfimage = transforms.ToTensor()(result) + if random_captions: + log_writer.add_image(tag=f"sample_{i}", img_tensor=tfimage, global_step=gs) + i += 1 + else: + log_writer.add_image(tag=f"sample_{prompt[:150]}", img_tensor=tfimage, global_step=gs) + + del result + del tfimage + del images + + try: + hf_ckpt_path = convert_to_hf(args.resume_ckpt) + text_encoder = CLIPTextModel.from_pretrained(hf_ckpt_path, subfolder="text_encoder", torch_dtype=torch.float32) + vae = AutoencoderKL.from_pretrained(hf_ckpt_path, subfolder="vae", torch_dtype=torch.float32) + unet = UNet2DConditionModel.from_pretrained(hf_ckpt_path, subfolder="unet", torch_dtype=torch.float32) + scheduler = DDIMScheduler.from_pretrained(hf_ckpt_path, subfolder="scheduler") + tokenizer = CLIPTokenizer.from_pretrained(hf_ckpt_path, subfolder="tokenizer", use_fast=False) + except: + logging.ERROR(" * Failed to load checkpoint *") + + if is_xformers_available(): + try: + unet.enable_xformers_memory_efficient_attention() + logging.info(" Enabled memory efficient attention (xformers)") + except Exception as e: + logging.warning( + "Could not enable memory efficient attention. Make sure xformers is installed" + f" correctly and a GPU is available: {e}" + ) + + default_lr = 2e-6 if args.useadam8bit else 2e-6 + lr = args.lr if args.lr is not None else default_lr + + vae = vae.to(torch.device("cuda"), dtype=torch.float16 if args.sd1 else torch.float32) + unet = unet.to(torch.device("cuda")) + text_encoder = text_encoder.to(torch.device("cuda")) + + if args.disable_textenc_training: + logging.info(f"{Fore.CYAN} * NOT Training Text Encoder, quality reduced *{Style.RESET_ALL}") + params_to_train = itertools.chain(unet.parameters()) + text_encoder.eval() + else: + logging.info(f"{Fore.CYAN} * Training Text Encoder *{Style.RESET_ALL}") + params_to_train = itertools.chain(unet.parameters(), text_encoder.parameters()) + + betas = (0.9, 0.999) + epsilon = 1e-8 if args.mixed_precision == "NO" else 1e-7 + weight_decay = 0.01 + if args.useadam8bit: + logging.info(f"{Fore.CYAN} * Using AdamW 8-bit Optimizer *{Style.RESET_ALL}") + import bitsandbytes as bnb + optimizer = bnb.optim.AdamW8bit( + itertools.chain(params_to_train), + lr=lr, + betas=betas, + eps=epsilon, + weight_decay=weight_decay, + ) + else: + logging.info(f"{Fore.CYAN} * Using AdamW8 standard Optimizer *{Style.RESET_ALL}") + optimizer = torch.optim.AdamW( + itertools.chain(params_to_train), + lr=lr, + betas=betas, + eps=epsilon, + weight_decay=weight_decay, + amsgrad=False, + ) + + log_optimizer(optimizer, betas, epsilon) + + train_batch = EveryDreamBatch( + data_root=args.data_root, + flip_p=0.0, + debug_level=1, + batch_size=args.batch_size, + conditional_dropout=0.03, + resolution=args.resolution, + tokenizer=tokenizer, + ) + + lr_warmup_steps = int(args.lr_decay_steps / 20) if args.lr_warmup_steps is None else args.lr_warmup_steps + + lr_scheduler = get_scheduler( + args.lr_scheduler, + optimizer=optimizer, + num_warmup_steps=lr_warmup_steps * _GRAD_ACCUM_STEPS, + num_training_steps=args.lr_decay_steps * _GRAD_ACCUM_STEPS, + ) + + # read prompts from prompts_file.txt + sample_prompts = [] + with open(args.sample_prompts, "r") as f: + for line in f: + sample_prompts.append(line.strip()) + + log_folder = os.path.join("logs", f"{args.project_name}{log_time}") + + if False: #args.wandb is not None and args.wandb: # not yet supported + log_writer = wandb.init(project="EveryDream2FineTunes", + name=args.project_name, + dir=log_folder, + ) + else: + log_writer = SummaryWriter(log_dir=log_folder, + flush_secs=5, + comment="EveryDream2FineTunes", + ) + + def log_args(log_writer, args): + arglog = "args:\n" + for arg, value in sorted(vars(args).items()): + arglog += f"{arg}={value}, " + log_writer.add_text("config", arglog) + + log_args(log_writer, args) + + args.clip_skip = max(min(2, args.clip_skip), 0) + + """ + Train the model + + """ + print(f" {Fore.LIGHTGREEN_EX}** Welcome to EveryDream trainer 2.0!**{Style.RESET_ALL}") + print(f" (C) 2022 Victor C Hall This program is licensed under AGPL 3.0 https://www.gnu.org/licenses/agpl-3.0.en.html") + print() + print("** Trainer Starting **") + + global interrupted + interrupted = False + + def sigterm_handler(signum, frame): + """ + handles sigterm + """ + global interrupted + if not interrupted: + interrupted=True + global global_step + #TODO: save model on ctrl-c + interrupted_checkpoint_path = os.path.join(f"logs/{log_folder}/interrupted-gs{global_step}.ckpt") + print() + logging.error(f"{Fore.LIGHTRED_EX} ************************************************************************{Style.RESET_ALL}") + logging.error(f"{Fore.LIGHTRED_EX} CTRL-C received, exiting{Style.RESET_ALL}") + logging.error(f"{Fore.LIGHTRED_EX} ************************************************************************{Style.RESET_ALL}") + save_path = os.path.join(f"logs/interrupted.ckpt") + #__save_model(interrupted_checkpoint_path, unet, text_encoder, tokenizer, scheduler, vae) + exit(_SIGTERM_EXIT_CODE) + + signal.signal(signal.SIGINT, sigterm_handler) + + if not os.path.exists(f"{log_folder}/samples/"): + os.makedirs(f"{log_folder}/samples/") + + gpu_used_mem, gpu_total_mem = gpu.get_gpu_memory() + logging.info(f" Pretraining GPU Memory: {gpu_used_mem} / {gpu_total_mem} MB") + logging.info(f" saving ckpts every {args.ckpt_every_n_minutes} minutes") + + scaler = torch.cuda.amp.GradScaler( + enabled=False, + #enabled=True if args.sd1 else False, + init_scale=2**16, + growth_factor=1.000001, + backoff_factor=0.9999999, + growth_interval=50, + ) + logging.info(f" Grad scaler enabled: {scaler.is_enabled()}") + + def collate_fn(batch): + """ + Collates batches + """ + images = [example["image"] for example in batch] + captions = [example["caption"] for example in batch] + tokens = [example["tokens"] for example in batch] + + images = torch.stack(images) + images = images.to(memory_format=torch.contiguous_format).float() + + batch = { + "tokens": torch.stack(tuple(tokens)), + "image": images, + "captions": captions, + } + return batch + + train_dataloader = torch.utils.data.DataLoader( + train_batch, + batch_size=args.batch_size, + shuffle=False, + num_workers=0, + collate_fn=collate_fn + ) + + total_batch_size = args.batch_size * _GRAD_ACCUM_STEPS + epoch_len = math.ceil(len(train_batch) / args.batch_size) + + unet.train() + text_encoder.requires_grad_(True) + text_encoder.train() + + logging.info(f" unet device: {unet.device}, precision: {unet.dtype}, training: {unet.training}") + logging.info(f" text_encoder device: {text_encoder.device}, precision: {text_encoder.dtype}, training: {text_encoder.training}") + logging.info(f" vae device: {vae.device}, precision: {vae.dtype}, training: {vae.training}") + logging.info(f" scheduler: {scheduler.__class__}") + + logging.info(f" {Fore.GREEN}Project name: {Style.RESET_ALL}{Fore.LIGHTGREEN_EX}{args.project_name}{Style.RESET_ALL}") + logging.info(f" {Fore.GREEN}grad_accum: {Style.RESET_ALL}{Fore.LIGHTGREEN_EX}{_GRAD_ACCUM_STEPS}{Style.RESET_ALL}"), + logging.info(f" {Fore.GREEN}batch_size: {Style.RESET_ALL}{Fore.LIGHTGREEN_EX}{args.batch_size}{Style.RESET_ALL}") + logging.info(f" {Fore.GREEN}total_batch_size: {Style.RESET_ALL}{Fore.LIGHTGREEN_EX}{total_batch_size}") + logging.info(f" {Fore.GREEN}epoch_len: {Fore.LIGHTGREEN_EX}{epoch_len}{Style.RESET_ALL}") + + epoch_pbar = tqdm(range(args.max_epochs), position=0) + epoch_pbar.set_description(f"{Fore.LIGHTCYAN_EX}Epochs{Style.RESET_ALL}") + + steps_pbar = tqdm(range(epoch_len), position=1) + steps_pbar.set_description(f"{Fore.LIGHTCYAN_EX}Steps{Style.RESET_ALL}") + + epoch_times = [] + + global global_step + global_step = 0 + training_start_time = time.time() + last_epoch_saved_time = training_start_time + + # (global_step: int, epoch_pbar, gpu, log_writer, **logs): + append_epoch_log(global_step=global_step, epoch_pbar=epoch_pbar, gpu=gpu, log_writer=log_writer) + + torch.cuda.empty_cache() + + try: + for epoch in range(args.max_epochs): + if epoch > 0 and epoch % args.save_every_n_epochs == 0: + logging.info(f" Saving model") + save_path = os.path.join(f"logs/ckpts/{args.project_name}-ep{epoch:02}-gs{global_step:05}") + __save_model(save_path, unet, text_encoder, tokenizer, scheduler, vae) + + epoch_start_time = time.time() + steps_pbar.reset() + images_per_sec_epoch = [] + + #for step, batch in enumerate(self.ctx.train_dataloader): + for step, batch in enumerate(train_dataloader): + step_start_time = time.time() + + with torch.no_grad(): + with autocast(): + pixel_values = batch["image"].to(memory_format=torch.contiguous_format).to(unet.device) + latents = vae.encode(pixel_values, return_dict=False) + + latent = latents[0] + latents = latent.sample() + latents = latents * 0.18215 + + noise = torch.randn_like(latents) + bsz = latents.shape[0] + + timesteps = torch.randint(0, scheduler.config.num_train_timesteps, (bsz,), device=latents.device) + timesteps = timesteps.long() + + cuda_caption = batch["tokens"].to(text_encoder.device) + + encoder_hidden_states = text_encoder(cuda_caption) + + # if clip_skip > 0: #TODO + # encoder_hidden_states = encoder_hidden_states['last_hidden_state'][-clip_skip] + + noisy_latents = scheduler.add_noise(latents, noise, timesteps) + + if scheduler.config.prediction_type == "epsilon": + target = noise + elif scheduler.config.prediction_type in ["v_prediction", "v-prediction"]: + target = scheduler.get_velocity(latents, noise, timesteps) + else: + raise ValueError(f"Unknown prediction type {scheduler.config.prediction_type}") + #del noise, latents + + #with torch.cuda.amp.autocast(enabled=lowvram): + with autocast(): # xformers requires fp16 + model_pred = unet(noisy_latents, timesteps, encoder_hidden_states.last_hidden_state).sample + + with autocast(enabled=args.sd1): + loss = torch_functional.mse_loss(model_pred.float(), target.float(), reduction="mean") + #del timesteps, encoder_hidden_states, noisy_latents + + if args.clip_grad_norm is not None: + torch.nn.utils.clip_grad_norm_(parameters=unet.parameters(), max_norm=args.clip_grad_norm) + torch.nn.utils.clip_grad_norm_(parameters=text_encoder.parameters(), max_norm=args.clip_grad_norm) + + #with torch.cuda.amp(enabled=False): + #if args.mixed_precision in ['bf16','fp16']: + if args.sd1: + with autocast(): + scaler.scale(loss).backward() + scaler.step(optimizer) + scaler.update() + else: + loss.backward() + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + steps_pbar.update(1) + global_step += 1 + + images_per_sec = args.batch_size / (time.time() - step_start_time) + images_per_sec_epoch.append(images_per_sec) + + #with torch.no_grad(): + if (global_step + 1) % args.log_step == 0: + lr = lr_scheduler.get_last_lr()[0] + logs = {"loss/step": loss.detach().item(), "lr": lr, "img/s": images_per_sec, "scale": scaler.get_scale()} + log_writer.add_scalar(tag="loss/step", scalar_value=loss, global_step=global_step) + log_writer.add_scalar(tag="hyperparamater/lr", scalar_value=lr, global_step=global_step) + sum_img = sum(images_per_sec_epoch) + avg = sum_img / len(images_per_sec_epoch) + images_per_sec_epoch = [] + log_writer.add_scalar(tag="hyperparamater/grad scale", scalar_value=scaler.get_scale(), global_step=global_step) + log_writer.add_scalar(tag="performance/images per second", scalar_value=avg, global_step=global_step) + append_epoch_log(global_step=global_step, epoch_pbar=epoch_pbar, gpu=gpu, log_writer=log_writer, **logs) + + if (global_step + 1) % args.sample_steps == 0: + #(unet, text_encoder, tokenizer, scheduler): + pipe = __create_inference_pipe(unet=unet, text_encoder=text_encoder, tokenizer=tokenizer, scheduler=scheduler, vae=vae) + pipe = pipe.to(torch.device("cuda")) + + with torch.no_grad(): + if sample_prompts is not None and len(sample_prompts) > 0 and len(sample_prompts[0]) > 1: + #(pipe, prompts, gs, log_writer, log_folder, random_captions=False): + __generate_test_samples(pipe=pipe, prompts=sample_prompts, log_writer=log_writer, log_folder=log_folder, gs=global_step, resolution=args.resolution) + else: + max_prompts = min(4,len(batch["captions"])) + prompts=batch["captions"][:max_prompts] + __generate_test_samples(pipe=pipe, prompts=prompts, log_writer=log_writer, log_folder=log_folder, gs=global_step, random_captions=True) + + del pipe + torch.cuda.empty_cache() + + min_since_last_ckpt = (time.time() - last_epoch_saved_time) / 60 + + if args.ckpt_every_n_minutes is not None and (min_since_last_ckpt > args.ckpt_every_n_minutes): + last_epoch_saved_time = time.time() + logging.info(f"Saving model at {args.ckpt_every_n_minutes} mins at step {global_step}") + save_path = os.path.join(f"{log_folder}/ckpts/{args.project_name}-ep{epoch:02}-gs{global_step:05}") + + __save_model(save_path, unet, text_encoder, tokenizer, scheduler, vae) + + # end of step + + # end of epoch + elapsed_epoch_time = (time.time() - epoch_start_time) / 60 + epoch_times.append(dict(epoch=epoch, time=elapsed_epoch_time)) + log_writer.add_scalar("performance/minutes per epoch", elapsed_epoch_time, global_step) + + epoch_pbar.update(1) + + # end of training + + save_path = os.path.join(f"{log_folder}/ckpts/last-{args.project_name}-ep{epoch:02}-gs{global_step:05}") + __save_model(save_path, unet, text_encoder, tokenizer, scheduler, vae) + + total_elapsed_time = time.time() - training_start_time + logging.info(f"{Fore.CYAN}Training complete{Style.RESET_ALL}") + logging.info(f"Total training time took {total_elapsed_time:.2f} seconds, total steps: {global_step}") + logging.info(f"Average epoch time: {np.mean([t['time'] for t in epoch_times]) / 60:.2f} minutes") + + except Exception as ex: + logging.error(f"{Fore.LIGHTYELLOW_EX}Something went wrong, attempting to save model{Style.RESET_ALL}") + save_path = os.path.join(f"{log_folder}/ckpts/errored-{args.project_name}-ep{epoch:02}-gs{global_step:05}") + __save_model(save_path, unet, text_encoder, tokenizer, scheduler, vae) + raise ex + + logging.info(f"{Fore.LIGHTWHITE_EX} *Finished training *{Style.RESET_ALL}") + + +if __name__ == "__main__": + supported_resolutions = [512, 576, 640, 704, 768, 832, 896, 960, 1024] + argparser = argparse.ArgumentParser(description="EveryDream Training options") + argparser.add_argument("--resume_ckpt", type=str, required=True, default="sd_v1-5_vae.ckpt") + argparser.add_argument("--lr_scheduler", type=str, default="constant", help="LR scheduler, (default: constant)", choices=["constant", "linear", "cosine", "polynomial"]) + argparser.add_argument("--lr_warmup_steps", type=int, default=None, help="Steps to reach max LR during warmup (def: 0.10x of lr_decay_steps), nonfunctional for constant scheduler") + argparser.add_argument("--lr_decay_steps", type=int, default=1500, help="Steps to reach minimum LR") + argparser.add_argument("--log_step", type=int, default=25, help="How often to log training stats, def: 25, recommend default") + argparser.add_argument("--max_epochs", type=int, default=300, help="Maximum number of epochs to train for") + argparser.add_argument("--ckpt_every_n_minutes", type=int, default=20, help="Save checkpoint every n minutes, def: 20") + argparser.add_argument("--save_every_n_epochs", type=int, default=9999, help="Save checkpoint every n epochs, def: 9999") + argparser.add_argument("--lr", type=float, default=None, help="Learning rate, if using scheduler is maximum LR at top of curve") + argparser.add_argument("--useadam8bit", action="store_true", default=False, help="Use AdamW 8-Bit optimizer") + argparser.add_argument("--project_name", type=str, default="myproj", help="Project name for logs and checkpoints, ex. 'tedbennett', 'superduperV1'") + argparser.add_argument("--sample_prompts", type=str, default="sample_prompts.txt", help="File with prompts to generate test samples from (def: sample_prompts.txt)") + argparser.add_argument("--sample_steps", type=int, default=250, help="Number of steps between samples (def: 250)") + argparser.add_argument("--disable_textenc_training", action="store_true", default=False, help="disables training of text encoder (def: False)") + argparser.add_argument("--batch_size", type=int, default=2, help="Batch size (def: 2)") + argparser.add_argument("--clip_grad_norm", type=float, default=None, help="Clip gradient norm (def: disabled) (ex: 1.5), useful if loss=nan?") + argparser.add_argument("--grad_accum", type=int, default=1, help="NONFUNCTIONING. Gradient accumulation factor (def: 1), (ex, 2)") + argparser.add_argument("--clip_skip", type=int, default=0, help="NONFUNCTIONING. Train using penultimate layers (def: 0)", choices=[0, 1, 2]) + argparser.add_argument("--data_root", type=str, default="input", help="folder where your training images are") + argparser.add_argument("--mixed_precision", default="no", help="NONFUNCTIONING. precision, (default: NO for fp32)", choices=["NO", "fp16", "bf16"]) + argparser.add_argument("--wandb", action="store_true", default=False, help="enable wandb logging instead of tensorboard, requires env var WANDB_API_KEY") + argparser.add_argument("--save_optimizer", action="store_true", default=False, help="saves optimizer state with ckpt, useful for resuming training later") + argparser.add_argument("--resolution", type=int, default=512, help="resolution to train", choices=supported_resolutions) + argparser.add_argument("--sd1", action="store_true", default=False, help="set if training SD1.x, else SD2 is assumed") + args = argparser.parse_args() + + main(args) diff --git a/utils/get_yamls.py b/utils/get_yamls.py new file mode 100644 index 0000000..26627fb --- /dev/null +++ b/utils/get_yamls.py @@ -0,0 +1,27 @@ +import sys +import requests + +_V2V_URL = ["v2-inference-v.yaml","https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml"] +_V2_URL = ["v2-inference.yaml","https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference.yaml"] +_V1_URL = ["v1-inference.yaml","https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"] + +# download https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml + +def download_all(): + list = [_V2V_URL,_V2_URL,_V1_URL] + for file in list: + get_yaml(file) + + +def get_yaml(file): + res = requests.request(method="GET", url=file[1]) + with open(file[0],"wb") as f: + f.write(res.content) + print(f" downloaded: {file[0]}") + +def isWindows(): + return sys.platform.startswith('win') + +if __name__ == '__main__': + download_all() + print("SD1.x and SD2.x yamls downloaded") diff --git a/utils/gpu.py b/utils/gpu.py new file mode 100644 index 0000000..c37e08c --- /dev/null +++ b/utils/gpu.py @@ -0,0 +1,30 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" +from pynvml.smi import nvidia_smi + +class GPU: + def __init__(self): + self.nvsmi = nvidia_smi.getInstance() + + def get_gpu_memory(self): + """ + returns a tuple of [gpu_used_mem, gpu_total_mem] + """ + gpu_query = self.nvsmi.DeviceQuery('memory.used, memory.total') + #print(gpu_query) + gpu_used_mem = int(gpu_query['gpu'][0]['fb_memory_usage']['used']) + gpu_total_mem = int(gpu_query['gpu'][0]['fb_memory_usage']['total']) + return gpu_used_mem, gpu_total_mem \ No newline at end of file diff --git a/utils/patch_bnb.py b/utils/patch_bnb.py new file mode 100644 index 0000000..81c2470 --- /dev/null +++ b/utils/patch_bnb.py @@ -0,0 +1,133 @@ +""" +Copyright [2022] Victor C Hall + +Licensed under the GNU Affero General Public License; +You may not use this code except in compliance with the License. +You may obtain a copy of the License at + + https://www.gnu.org/licenses/agpl-3.0.en.html + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +# see: https://github.com/TimDettmers/bitsandbytes/issues/30 for explanation +import sys +import os +from subprocess import check_output +import shutil + +_CEXT_PATCH = " self.lib = ct.cdll.LoadLibrary(str(binary_path))" +_MAIN_PATCH = " return 'libbitsandbytes_cuda116.dll'" + +def patch_main(): + bnbpath_main = "venv/Lib/site-packages/bitsandbytes/cuda_setup/main.py" + try: + with open(bnbpath_main, "r") as f: + contents = f.read() + contents = contents.split('\n') + except Exception as ex: + print(f"cannot find bitsandbytes install, aborting, error: {ex}") + return False + + main_patched = False + + for i, line in enumerate(contents): + if i == 112: + if line != _MAIN_PATCH: + contents[i] = _MAIN_PATCH + main_patched = True + else: + print(" *** Already patched!") + main_patched = True + + assert main_patched, "unable to patch bitsandbytes, may be mismatched version, requires 0.35.0" + + with open(bnbpath_main, "w") as f: + for line in contents: + f.write(line + "\n") + #print(contents) + + return main_patched + +def patch_cext(): + bnbpath_cextension = "venv/Lib/site-packages/bitsandbytes/cextension.py" + try: + with open(bnbpath_cextension, "r") as f: + contents = f.read() + contents = contents.split('\n') + except Exception as ex: + print(f"cannot find bitsandbytes install, aborting, error: {ex}") + return False + + cext_patched = False + + for i, line in enumerate(contents): + # update both lines 28 and 31 to be sure correct dll is returned + if (i == 30 or i == 27): + if line != _CEXT_PATCH: + contents[i] = _CEXT_PATCH + cext_patched = True + else: + cext_patched = True + + assert cext_patched, "unable to patch bitsandbytes, died midprocess, something broke and may need to reinstall bitsandbytes==0.35.0" + + with open(bnbpath_cextension, "w") as f: + for line in contents: + f.write(line + "\n") + #print(contents) + + return cext_patched + +def iswindows(): + return sys.platform.startswith('win') + +def error(): + print("Somethnig went wrong trying to patch bitsandbytes, aborting") + print("make sure your venv is activated and try again") + print("or if activated try: ") + print(" pip install bitsandbytes==0.35.0") + raise RuntimeError("** FATAL ERROR: unable to patch bitsandbytes for Windows env") + +def check_dlls(): + dll_exists = os.path.exists("venv/Lib/site-packages/bitsandbytes/libbitsandbytes_cuda116.dll") + if not dll_exists: + if not os.path.exists("tmp/bnb_cache"): + check_output("git clone https://github.com/DeXtmL/bitsandbytes-win-prebuilt tmp/bnb_cache", shell=True) + shutil.copy("tmp/bnb_cache/libbitsandbytes_cuda116.dll", "venv/Lib/site-packages/bitsandbytes/libbitsandbytes_cuda116.dll") + dll_exists = os.path.exists("venv/Lib/site-packages/bitsandbytes/libbitsandbytes_cuda116.dll") + return dll_exists + +def main(): + """ + applies a patch for windows compatibility for bitsandbytes 0.35.0 for using their AdamW8bit optimizer + """ + if iswindows(): + print() + print(" *** Applying bitsandbytes patch for windows ***") + if not check_dlls(): + print("unable to find bitsandbytes dll or clone them from git, aborting") + raise RuntimeError("** FATAL ERROR: unable to patch bitsandbytes for Windows env") + + main_patched = patch_main() + cext_patched = patch_cext() + if main_patched and cext_patched: + try: + print(" *************************************************************") + print(" *** bitsandbytes windows patch applied, attempting import *** ") + import bitsandbytes + print(f" *** bitsandbytes patch succeeded, everything looks good! ***") + except: + error() + else: + error() + else: + print(" *** not using windows environment, skipping bitsandbytes patch ***") + return + +if __name__ == "__main__": + main()