diff --git a/sd-forge-extra-samplers/.github/workflows/ruff.yaml b/sd-forge-extra-samplers/.github/workflows/ruff.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1224231ebeb25c67af47ffce06515565ce84aca1 --- /dev/null +++ b/sd-forge-extra-samplers/.github/workflows/ruff.yaml @@ -0,0 +1,8 @@ +name: Ruff +on: [pull_request] +jobs: + ruff: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/ruff-action@v1 diff --git a/sd-forge-extra-samplers/.gitignore b/sd-forge-extra-samplers/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..8ce58e54540d4f142b26e0a7e06c2c0ac87f3401 --- /dev/null +++ b/sd-forge-extra-samplers/.gitignore @@ -0,0 +1,163 @@ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ \ No newline at end of file diff --git a/sd-forge-extra-samplers/LICENSE b/sd-forge-extra-samplers/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7 --- /dev/null +++ b/sd-forge-extra-samplers/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/sd-forge-extra-samplers/README.md b/sd-forge-extra-samplers/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d0c319c99b6be3d91b0df9055031fd334f5daec8 --- /dev/null +++ b/sd-forge-extra-samplers/README.md @@ -0,0 +1,97 @@ +# Overview + +This repository provides additional samplers to the Forge WebUI. + +## Features + +- Additional samplers integrated into the Forge WebUI. + - Adaptive Progressive (Experimental) + - Euler Max + - Euler Negative + - Euler Dy + - Euler Dy Negative + - Euler SMEA + - Euler SMEA Dy + - Euler SMEA Dy Negative + - Euler Multipass + - Euler Multipass CFG++ + - Euler a Multipass + - Euler a Multipass CFG++ + - Extended Reverse Time SDE + - Gradient Estimation + - Heun Ancestral + - Kohaku LoNyu Yog + - Langevin Euler (Experimental) + - Res Multistep + - Res Multistep CFG++ + - Res Multistep Ancestral + - Res Multistep Ancestral CFG++ + +- Additional Schedulers + - Linear Log + +Adds a new extension accordian titled "Extra Samplers" to allow adjusting certain samplers. + +## Installation + +### Clone from Git + +1. Navigate to the extension directory in your WebUI installation +1. Clone the repository: + ```sh + git clone https://github.com/MisterChief95/sd-forge-extra-samplers.git + ``` +1. Start WebUI + +### Install from URL + +1. Open the Extensions tab in the web UI. +2. Go to the "Install from URL" section. +3. Enter: `https://github.com/MisterChief95/sd-forge-extra-samplers.git` in the "URL for extension's git repository" box. +4. Click "Install". +5. Restart WebUI + +## Usage + +1. Open the WebUI. +2. Navigate to the sampler settings. +3. Select one of the newly added Euler samplers from the list. +4. Generate images as usual. + +### Important +- Not all samplers work well in every situation. Some will look poor when used for img2img/hires fix. +- Mix-and-match samplers to find the best combinations. A sampler might look bad with one scheduler but good with another! + +## Contributing + +Contributions are welcome! Please open an issue or submit a pull request for any improvements or bug fixes. + +## Acknowledgements + +If any of these are incorrect please let me know! + +- Thanks to the developers of Automatic1111 and Forge. +- [Koishi-Star](https://github.com/Koishi-Star/Euler-Smea-Dyn-Sampler) for the following sampler contributions: + - Euler Negative + - Euler Dy + - Euler Dy Negative + - Euler SMEA Dy (Euler SMEA Dy Negative based on this) + - Kohaku LoNyu Yog +- [licyk](https://github.com/licyk/advanced_euler_sampler_extension/tree/main) for the following sampler contributions: + - Euler Max + - Euler SMEA +- [Panchovix](https://github.com/Panchovix/stable-diffusion-webui-reForge) for the following sampler contributions: + - Res Multistep + - Res Multistep CFG++ +- [comfyanonymous](https://github.com/comfyanonymous/ComfyUI) for the following sampler contributions: + - Gradient Estimation + - Extended Reverse Time SDE + - Res Multistep + - Res Multistep CFG++ + - Res Multistep Ancestral + - Res Multistep Ancestral CFG++ +- Euler Multipass + - Original Implementation: [aria1th](https://github.com/aria1th) + - CFG++ Implementation: [LaVie024](https://github.com/LaVie024) + - Final ComfyUI implementation: [catboxanon](https://github.com/catboxanon) +- Special thanks to the contributors of this repository. diff --git a/sd-forge-extra-samplers/lib_es/__init__.py b/sd-forge-extra-samplers/lib_es/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sd-forge-extra-samplers/lib_es/__pycache__/__init__.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0408bcdd685914138bc8837ef801802be01f15e5 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/__pycache__/__init__.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/__pycache__/const.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/__pycache__/const.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf97479856b8367007637dff9b55b4d74a785a92 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/__pycache__/const.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/__pycache__/samplers.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/__pycache__/samplers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b1b2e1302bd7002bea9048f1d98adc9b925c506 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/__pycache__/samplers.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/__pycache__/schedulers.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/__pycache__/schedulers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbf633cc54529f7b1494702f97e78ae7f84e6ffa Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/__pycache__/schedulers.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/__pycache__/utils.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccf19a66db9ecf0cac4b30091c4232786a6f8ff2 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/__pycache__/utils.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/__pycache__/xyz.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/__pycache__/xyz.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ddf6e72bc5d0ef0e5802f2ede20e2a61527c034 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/__pycache__/xyz.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/const.py b/sd-forge-extra-samplers/lib_es/const.py new file mode 100644 index 0000000000000000000000000000000000000000..d182ab0d5382a539b20a853c9de6ed410b492946 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/const.py @@ -0,0 +1,25 @@ +# Adaptive Progressive +AP_EULER_A_END = "exs_ap_euler_a_end" +AP_DPM_2M_END = "exs_ap_dpm_2m_end" +AP_ANCESTRAL_ETA = "exs_ap_ancestral_eta" +AP_DETAIL_STRENGTH = "exs_ap_detail_strength" + +# Langevin Euler +LANGEVIN_STRENGTH = "exs_langevin_strength" + +# Extended Reverse-Time +ER_MAX_STAGE = "er_max_stage" + +# Gradient Estimation +GE_GAMMA = "ge_gamma" +GE_GAMMA_OFFSET = "ge_gamma_offset" +GE_USE_ADAPTIVE_STEPS = "ge_use_adaptive_steps" +GE_USE_TIMESTEP_ADAPTIVE_GAMMA = "ge_use_timestep_adaptive_gamma" +GE_VALIDATE_SCHEDULE = "ge_validate_schedule" + +GE_DEFAULT_GAMMA = 2.0 +GE_MIN_GAMMA = 1.0 +GE_MAX_GAMMA = 3.0 +GE_DEFAULT_GAMMA_OFFSET = 0.0 +GE_MIN_GAMMA_OFFSET = -1.0 +GE_MAX_GAMMA_OFFSET = 1.0 diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__init__.py b/sd-forge-extra-samplers/lib_es/extra_samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..488dd1dd01077630f8e093c29ab54ffc712a7f42 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/__init__.py @@ -0,0 +1,49 @@ +#from lib_es.extra_samplers.adaptive_progressive import sample_adaptive_progressive +from lib_es.extra_samplers.euler_dy import sample_euler_dy +from lib_es.extra_samplers.euler_dy_negative import sample_euler_dy_negative +from lib_es.extra_samplers.euler_smea import sample_euler_smea +from lib_es.extra_samplers.euler_smea_dy import sample_euler_smea_dy +from lib_es.extra_samplers.euler_smea_dy_negative import sample_euler_smea_dy_negative +from lib_es.extra_samplers.euler_max import sample_euler_max +from lib_es.extra_samplers.euler_multipass import ( + sample_euler_multipass, + sample_euler_multipass_cfg_pp, + sample_euler_ancestral_multipass, + sample_euler_ancestral_multipass_cfg_pp, +) +from lib_es.extra_samplers.euler_negative import sample_euler_negative +from lib_es.extra_samplers.extended_reverse_time import sample_er_sde +from lib_es.extra_samplers.gradient_estimation import sample_gradient_estimation +from lib_es.extra_samplers.heun_ancestral import sample_heun_ancestral +from lib_es.extra_samplers.kohaku_lonyu_yog import sample_kohaku_lonyu_yog +from lib_es.extra_samplers.langevin_euler import sample_langevin_euler +#from lib_es.extra_samplers.res_multistep import ( + #sample_res_multistep, + #sample_res_multistep_cfg_pp, + #sample_res_multistep_ancestral, + #sample_res_multistep_ancestral_cfg_pp, +#) + +__sampler_funcs__ = [ + #sample_adaptive_progressive, + sample_euler_max, + sample_euler_negative, + sample_euler_dy, + sample_euler_dy_negative, + sample_euler_smea, + sample_euler_smea_dy, + sample_euler_smea_dy_negative, + sample_euler_multipass, + sample_euler_multipass_cfg_pp, + sample_euler_ancestral_multipass, + sample_euler_ancestral_multipass_cfg_pp, + sample_er_sde, + sample_gradient_estimation, + sample_heun_ancestral, + sample_kohaku_lonyu_yog, + sample_langevin_euler, + #sample_res_multistep_ancestral_cfg_pp, + #sample_res_multistep_ancestral, + #sample_res_multistep_cfg_pp, + #sample_res_multistep, +] diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/__init__.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff9a63b98b85ec17879efb4ee5c4040bb31f8cd8 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/__init__.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/adaptive_progressive.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/adaptive_progressive.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e0aa8d367ce6fb87ef4f584281fccadad290252 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/adaptive_progressive.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_dy.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_dy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e07cbacf14b2c0161ea530304e885caff99f302 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_dy.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_dy_negative.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_dy_negative.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7264414b7438a2d284a39b04375d8e155a4966fd Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_dy_negative.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_max.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_max.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79ae8a2f207511407ca96fbe8484931aa4138066 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_max.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_multipass.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_multipass.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b01c550b024a70ac742f372d7c074e704387248 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_multipass.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_negative.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_negative.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79018a16460176778a51de0117f106dd8481eef8 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_negative.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_smea.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_smea.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d325da0a5de5ddb48cb9b6a0f276fdb27251b389 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_smea.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_smea_dy.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_smea_dy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9eae687cf7353e64c17321965d876b6e78070266 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_smea_dy.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_smea_dy_negative.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_smea_dy_negative.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da0e3077a2e6273882b1dec020c28b01f9e3b60d Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/euler_smea_dy_negative.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/extended_reverse_time.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/extended_reverse_time.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82a62ae6bd3858ceedec8bf4c021890f3c7c7f71 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/extended_reverse_time.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/gradient_estimation.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/gradient_estimation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f8c7a23b08b81c2fb44d2ab487e5dd9be71b393 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/gradient_estimation.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/heun_ancestral.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/heun_ancestral.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f355691785f0dcb91647f8534fe780668754195 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/heun_ancestral.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/kohaku_lonyu_yog.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/kohaku_lonyu_yog.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97ef5b20e509ff41b19bc143daf8cfbe3fbdcac9 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/kohaku_lonyu_yog.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/langevin_euler.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/langevin_euler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6cd1e7d81c0b9ada1821e9bf11c9d878bfd6e0e4 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/langevin_euler.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/res_multistep.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/res_multistep.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7125459c581b336c4d25c64bef7c4dd59bf8d156 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_samplers/__pycache__/res_multistep.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/adaptive_progressive.py b/sd-forge-extra-samplers/lib_es/extra_samplers/adaptive_progressive.py new file mode 100644 index 0000000000000000000000000000000000000000..3c0c2311d69b4f8cc8602e676cf99c99b6b6d3e5 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/adaptive_progressive.py @@ -0,0 +1,227 @@ +import math +import torch +from tqdm.auto import trange +from k_diffusion.sampling import to_d, get_ancestral_step +#from backend.modules.k_diffusion_extra import default_noise_sampler + +import lib_es.const as consts +from lib_es.utils import sampler_metadata + + +@sampler_metadata( + "Adaptive Progressive", + {"scheduler": "sgm_uniform", "uses_ensd": True}, +) +@torch.no_grad() +def sample_adaptive_progressive( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, + noise_sampler=None, +): + """ + Adaptive progressive sampler that automatically adjusts to different step counts. + Combines Euler ancestral, DPM++ 2M, and detail enhancement with phase-based transitions. + + This sampler is optimized for both high and very low step counts (4+), + dynamically adjusting phase durations based on total step count. + + Args: + model: The denoising model + x: Input noise tensor + sigmas: Noise schedule + extra_args: Additional arguments for the model + callback: Optional callback function + disable: Whether to disable the progress bar + s_churn: Amount of stochasticity + s_tmin: Minimum sigma for stochasticity + s_tmax: Maximum sigma for stochasticity + eta: Ancestral noise parameter + s_noise: Noise scale + noise_sampler: Custom noise sampler function + detail_strength: Strength of detail enhancement phase + + Returns: + Denoised tensor + """ + extra_args = {} if extra_args is None else extra_args + noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler + s_in = x.new_ones([x.shape[0]]) + steps = len(sigmas) - 1 + + euler_a_end = getattr(model.p, consts.AP_EULER_A_END, 0.35) + dpm_2m_end = getattr(model.p, consts.AP_DPM_2M_END, 0.75) + ancestral_eta = getattr(model.p, consts.AP_ANCESTRAL_ETA, 0.4) + detail_strength = getattr(model.p, consts.AP_DETAIL_STRENGTH, 1.5) + + # Store previous steps' information + prev_d = None + prev_denoised = None + + euler_end, dpm_end = calc_phase_bounds(steps, euler_a_end, dpm_2m_end) + + for i in trange(steps, disable=disable): + progress = i / steps + + # Calculate weights based on phase + if progress < euler_end: + # Euler ancestral phase + w_euler = 1.0 + w_multi = 0.0 + w_detail = 0.0 + elif progress < dpm_end: + # DPM++ phase - smooth transition from Euler + phase_progress = (progress - euler_end) / (dpm_end - euler_end) + w_euler = max(0.0, 1.0 - phase_progress * 2.5) # Faster transition out of Euler + w_multi = 1.0 - w_euler + w_detail = 0.0 + else: + # Detail refinement phase - gradual transition + phase_progress = (progress - dpm_end) / (1.0 - dpm_end) + w_euler = 0.0 + w_multi = max(0.0, 1.0 - phase_progress * 1.5) # Gradual reduction in DPM++ + w_detail = 1.0 - w_multi + + # Apply adaptive stochasticity (only in early steps) + if s_churn > 0 and s_tmin <= sigmas[i] <= s_tmax and progress < 0.4: + # Scale down stochasticity as we progress + gamma = min(s_churn / steps, 2**0.5 - 1) * (1.0 - progress / 0.4) + sigma_hat = sigmas[i] * (gamma + 1) + eps = torch.randn_like(x) * s_noise + x = x + eps * (sigma_hat**2 - sigmas[i] ** 2).sqrt() + else: + sigma_hat = sigmas[i] + + # Get denoised prediction + denoised = model(x, sigma_hat * s_in, **extra_args) + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + + # Calculate sigma for step + # Reduce eta as we progress to lower noise in later steps + step_eta = ancestral_eta if progress < 0.5 else ancestral_eta * (1.0 - min(1.0, (progress - 0.5) * 2.0)) + sigma_down, sigma_up = get_ancestral_step(sigma_hat, sigmas[i + 1], eta=step_eta) + + # Calculate current score + d = to_d(x, sigma_hat, denoised) + dt = sigma_down - sigma_hat + + # Special case for final step + if sigmas[i + 1] == 0: + x = denoised + break + + # Calculate step direction based on phase + if prev_d is None: + # First step is pure Euler ancestral + direction = d + else: + # Initialize direction + direction = torch.zeros_like(d) + + # Add Euler component if needed + if w_euler > 0: + direction += w_euler * d + + # Add DPM++ component if needed + if w_multi > 0: + # Adjust coefficients based on noise level + if sigma_hat > 2.0: + # Higher noise: favor current direction + c1, c2 = 0.7, 0.3 + else: + # Lower noise: more balanced + c1, c2 = 0.6, 0.4 + + multi_direction = c1 * d + c2 * prev_d + direction += w_multi * multi_direction + + # Add detail enhancement if needed + if w_detail > 0 and prev_denoised is not None: + # Only apply significant enhancement at lower noise levels + if sigma_hat < 1.0: + # Calculate detail vector (high frequency components) + detail_vector = denoised - prev_denoised + + # Scale based on noise level - stronger at very low noise + detail_scale = detail_strength * min(1.0, 0.2 / (sigma_hat + 0.2)) + + # Apply detail enhancement with adaptive scaling + detail_direction = d + detail_vector * detail_scale / dt + direction += w_detail * detail_direction + else: + # At higher noise levels, use standard direction + direction += w_detail * d + + # Ensure numerical stability + direction = torch.clamp(direction, -1e2, 1e2) + + # Apply the step + x = x + direction * dt + + # Apply ancestral noise with progressive reduction + if sigma_up > 0: + # Only add significant noise in earlier steps + noise_scale = s_noise + if progress > 0.3: + # Exponential reduction in noise after Euler phase + noise_scale *= math.exp(-4.0 * (progress - 0.3)) + + # Add the scaled noise + x = x + noise_sampler(sigma_hat, sigmas[i + 1]) * sigma_up * noise_scale + + # Store values for next step + prev_d = d + prev_denoised = denoised + + return x + + +def calc_phase_bounds(steps: int, custom_euler_end: float = 0.25, custom_dpm_end: float = 0.7) -> tuple[float, float]: + """ + Calculate phase boundaries for the adaptive progressive sampler. + + Args: + steps: Total number of steps + custom_euler_end: End point for Euler phase (0.0-1.0) + custom_dpm_end: End point for DPM++ phase (0.0-1.0) + + Returns: + Tuple of phase boundaries (Euler end, DPM++ end) + """ + # Ensure values are within valid range + euler_end = max(0.0, min(1.0, custom_euler_end)) + dpm_end = max(0.0, min(1.0, custom_dpm_end)) + + # Ensure euler_end < dpm_end + if euler_end >= dpm_end: + euler_end = max(0.0, dpm_end - 0.2) # Ensure at least 20% for DPM++ phase + + # Adaptive phase boundaries based on step count + if steps < 10: + # For very low step counts, shorten Euler phase and extend detail phase + euler_end = min(euler_end, 0.15 + (steps - 4) * 0.01) + dpm_end = min(dpm_end, 0.5 + (steps - 4) * 0.02) + elif steps < 20: + # For low step counts, slightly adjust phases + euler_end = min(euler_end, 0.2) + dpm_end = min(dpm_end, 0.65) + elif steps > 50: + # For high step counts, extend the Euler phase slightly + euler_end = min(0.3, euler_end + (steps - 50) * 0.0005) + # And allow for a longer DPM++ phase + dpm_end = min(0.8, dpm_end + (steps - 50) * 0.0005) + + # Ensure minimum phase lengths + if dpm_end - euler_end < 0.1: + dpm_end = min(1.0, euler_end + 0.1) + + return euler_end, dpm_end diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/euler_dy.py b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_dy.py new file mode 100644 index 0000000000000000000000000000000000000000..d83dfc3c36935e5998fc35834c33fd214f05cc06 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_dy.py @@ -0,0 +1,50 @@ +import torch + +from k_diffusion.sampling import to_d + +from tqdm.auto import trange + +from lib_es.utils import dy_sampling_step +from lib_es.utils import sampler_metadata + + +@sampler_metadata("Euler Dy") +@torch.no_grad() +def sample_euler_dy( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, +): + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + + for i in trange(len(sigmas) - 1, disable=disable): + gamma = max(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0 + eps = torch.randn_like(x) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + dt = sigmas[i + 1] - sigma_hat + + if gamma > 0: + x = x - eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5 + + denoised = model(x, sigma_hat * s_in, **extra_args) + d = to_d(x, sigma_hat, denoised) + + if sigmas[i + 1] > 0: + if i // 2 == 1: + x = dy_sampling_step(x, model, dt, sigma_hat, **extra_args) + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + + # Euler method + x = x + d * dt + + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/euler_dy_negative.py b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_dy_negative.py new file mode 100644 index 0000000000000000000000000000000000000000..cba3eb4368e7edaeb20b86b6cae6798d42f15943 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_dy_negative.py @@ -0,0 +1,50 @@ +import torch + +from k_diffusion.sampling import to_d + +from tqdm.auto import trange + +from lib_es.utils import dy_sampling_step +from lib_es.utils import sampler_metadata + + +@sampler_metadata("Euler Dy Negative") +@torch.no_grad() +def sample_euler_dy_negative( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, +): + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + + for i in trange(len(sigmas) - 1, disable=disable): + gamma = max(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0 + eps = torch.randn_like(x) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + dt = sigmas[i + 1] - sigma_hat + + if gamma > 0: + x = x - eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5 + + denoised = model(x, sigma_hat * s_in, **extra_args) + d = to_d(x, sigma_hat, denoised) + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + + # Euler method + if sigmas[i + 1] > 0 and i // 2 == 1: + x = dy_sampling_step(x, model, dt, sigma_hat, **extra_args) + x = -x - d * dt + else: + x = x + d * dt + + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/euler_max.py b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_max.py new file mode 100644 index 0000000000000000000000000000000000000000..446c8ec87037300bdb956186b44fb32066b5d799 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_max.py @@ -0,0 +1,45 @@ +import math +import torch + +from k_diffusion.sampling import to_d + +from tqdm.auto import trange + +from lib_es.utils import sampler_metadata + + +@sampler_metadata("Euler Max") +@torch.no_grad() +def sample_euler_max( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, +): + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + for i in trange(len(sigmas) - 1, disable=disable): + gamma = max(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0 + eps = torch.randn_like(x) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + + if gamma > 0: + x = x - eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5 + + denoised = model(x, sigma_hat * s_in, **extra_args) + d = to_d(x, sigma_hat, denoised) + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + + dt = sigmas[i + 1] - sigma_hat + + # Euler method + x = x + (math.cos(i + 1) / (i + 1) + 1) * d * dt + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/euler_multipass.py b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_multipass.py new file mode 100644 index 0000000000000000000000000000000000000000..3431a314127d27b6078bc6cf13d58caef4325816 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_multipass.py @@ -0,0 +1,290 @@ +import torch +from tqdm import trange + +from k_diffusion.sampling import get_ancestral_step, to_d + +from lib_es.utils import default_noise_sampler, extend_sigmas, sampler_metadata + + +# ============================================================================================================== +# - Originally written by aria1th: https://github.com/aria1th +# - CFG++ support written by LaVie024: https://github.com/LaVie024 +# - Standard Euler support written by catboxanon: https://github.com/catboxanon +# ============================================================================================================== + + +def apply_churn(x, sub_sigma, s_churn, s_tmin, s_tmax, s_noise, pass_step): + if s_churn > 0: + gamma = min(s_churn / max(0, pass_step - 1), 2**0.5 - 1) if s_tmin <= sub_sigma < s_tmax else 0 + sigma_hat = sub_sigma * (gamma + 1) + else: + gamma = 0 + sigma_hat = sub_sigma + + if gamma > 0: + eps = torch.randn_like(x) * s_noise + x = x + eps * (sigma_hat**2 - sub_sigma**2) ** 0.5 + + return x, sigma_hat + + +@torch.no_grad() +def euler_ancestral_multipass( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + eta=1.0, + s_noise=1.0, + noise_sampler=None, + pass_steps=2, + pass_sigma_max=float("inf"), + pass_sigma_min=12.0, + cfg_pp=False, +): + """ + A multipass variant of Euler-Ancestral sampling. + - For each i in [0, len(sigmas)-2], we check if sigma_i is in [pass_sigma_min, pass_sigma_max]. + If so, subdivide the step from sigma_i -> sigma_{i+1} into 'pass_steps' sub-steps. + Otherwise, do a single standard step. + - Each sub-step calls 'get_ancestral_step(...)' with the sub-interval's start & end sigmas, + then applies the usual Euler-Ancestral update: + x = x + d*dt + (noise * sigma_up) + """ + extra_args = {} if extra_args is None else extra_args + seed = extra_args.get("seed", None) + noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler + s_in = x.new_ones([x.shape[0]]) + + if cfg_pp: + model.need_last_noise_uncond = True + model.inner_model.inner_model.forge_objects.unet.model_options["disable_cfg1_optimization"] = True + + sub_sigmas = extend_sigmas(sigmas, pass_steps, pass_sigma_max, pass_sigma_min) + + for i in trange(len(sub_sigmas) - 1, disable=disable): + # Current sub-step range: + sub_sigma_curr = sub_sigmas[i] + sub_sigma_next = sub_sigmas[i + 1] + + # Denoise at the current sub-sigma + denoised = model(x, sub_sigma_curr * s_in, **extra_args) + + if callback is not None: + callback({"x": x, "i": i, "sub_step": i, "sigma": sub_sigma_curr, "denoised": denoised}) + + # Compute the ancestral step parameters for this sub-interval + sigma_down, sigma_up = get_ancestral_step(sub_sigma_curr, sub_sigma_next, eta=eta) + + d = model.last_noise_uncond if cfg_pp else to_d(x, sub_sigma_curr, denoised) + + if cfg_pp: + x = denoised + d * sigma_down + elif sigma_down == 0.0: + x = denoised + else: + x = x + d * (sigma_down - sub_sigma_curr) + + if sigma_up != 0.0: + # Add noise for the "ancestral" part + x = x + noise_sampler(sub_sigma_curr, sub_sigma_next) * (s_noise * sigma_up) + + return x + + +@sampler_metadata(name="Euler a Multipass", extra_params={"uses_ensd": True}) +def sample_euler_ancestral_multipass( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + eta=1.0, + s_noise=1.0, + noise_sampler=None, + pass_steps=2, + pass_sigma_max=float("inf"), + pass_sigma_min=12.0, +): + return euler_ancestral_multipass( + model, + x, + sigmas, + extra_args, + callback, + disable, + eta, + s_noise, + noise_sampler, + pass_steps, + pass_sigma_max, + pass_sigma_min, + False, + ) + + +@sampler_metadata(name="Euler a Multipass CFG++", extra_params={"uses_ensd": True}) +def sample_euler_ancestral_multipass_cfg_pp( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + eta=1.0, + s_noise=1.0, + noise_sampler=None, + pass_steps=2, + pass_sigma_max=float("inf"), + pass_sigma_min=12.0, +): + return euler_ancestral_multipass( + model, + x, + sigmas, + extra_args, + callback, + disable, + eta, + s_noise, + noise_sampler, + pass_steps, + pass_sigma_max, + pass_sigma_min, + True, + ) + + +@torch.no_grad() +def euler_multipass( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + noise_sampler=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, + pass_steps=2, + pass_sigma_max=float("inf"), + pass_sigma_min=12.0, + cfg_pp=False, +): + """ + A multipass variant of Euler sampling. + """ + extra_args = {} if extra_args is None else extra_args + seed = extra_args.get("seed", None) + noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler + + if cfg_pp: + model.need_last_noise_uncond = True + model.inner_model.inner_model.forge_objects.unet.model_options["disable_cfg1_optimization"] = True + + s_in = x.new_ones([x.shape[0]]) + sub_sigmas = extend_sigmas(sigmas, pass_steps, pass_sigma_max, pass_sigma_min) + + for i in trange(len(sub_sigmas) - 1, disable=disable): + # Current sub-step range: + sub_sigma_curr = sub_sigmas[i] + sub_sigma_next = sub_sigmas[i + 1] + + x, sigma_hat = apply_churn(x, sub_sigma_curr, s_churn, s_tmin, s_tmax, s_noise, pass_steps) + + # Denoise at the current sub-sigma + denoised = model(x, sub_sigma_curr * s_in, **extra_args) + + if callback is not None: + callback( + { + "x": x, + "i": i, + "sub_step": i, + "sigma": sub_sigma_curr, + "sigma_hat": sigma_hat, + "denoised": denoised, + } + ) + + d = model.last_noise_uncond if cfg_pp else to_d(x, sigma_hat, denoised) + x = denoised + d * sub_sigma_next if cfg_pp else x + d * (sub_sigma_next - sigma_hat) + + return x + + +@sampler_metadata(name="Euler Multipass") +def sample_euler_multipass( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_noise=1.0, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + noise_sampler=None, + pass_steps=2, + pass_sigma_max=float("inf"), + pass_sigma_min=12.0, +): + return euler_multipass( + model, + x, + sigmas, + extra_args, + callback, + disable, + noise_sampler, + s_churn, + s_tmin, + s_tmax, + s_noise, + pass_steps, + pass_sigma_max, + pass_sigma_min, + False, + ) + + +@sampler_metadata(name="Euler Multipass CFG++") +def sample_euler_multipass_cfg_pp( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_noise=1.0, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + noise_sampler=None, + pass_steps=2, + pass_sigma_max=float("inf"), + pass_sigma_min=12.0, +): + return euler_multipass( + model, + x, + sigmas, + extra_args, + callback, + disable, + noise_sampler, + s_churn, + s_tmin, + s_tmax, + s_noise, + pass_steps, + pass_sigma_max, + pass_sigma_min, + True, + ) diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/euler_negative.py b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_negative.py new file mode 100644 index 0000000000000000000000000000000000000000..fb06e85feb5b2ad05dd6a3f435d25bb208886ac1 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_negative.py @@ -0,0 +1,48 @@ +import torch + +from k_diffusion.sampling import to_d + +from tqdm.auto import trange + +from lib_es.utils import sampler_metadata + + +@sampler_metadata("Euler Negative") +@torch.no_grad() +def sample_euler_negative( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, +): + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + + for i in trange(len(sigmas) - 1, disable=disable): + gamma = max(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0 + eps = torch.randn_like(x) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + dt = sigmas[i + 1] - sigma_hat + + if gamma > 0: + x = x - eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5 + + denoised = model(x, sigma_hat * s_in, **extra_args) + d = to_d(x, sigma_hat, denoised) + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + + # Euler method + if sigmas[i + 1] > 0 and i // 2 == 1: + x = -x - d * dt + else: + x = x + d * dt + + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/euler_smea.py b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_smea.py new file mode 100644 index 0000000000000000000000000000000000000000..bbd7d829d2b3f319290a767c9abd663aa1584552 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_smea.py @@ -0,0 +1,49 @@ +import torch + +from k_diffusion.sampling import to_d + +from tqdm.auto import trange + +from lib_es.utils import overall_sampling_step +from lib_es.utils import sampler_metadata + + +@sampler_metadata("Euler SMEA") +@torch.no_grad() +def sample_euler_smea( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, +): + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + + for i in trange(len(sigmas) - 1, disable=disable): + gamma = max(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0 + eps = torch.randn_like(x) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + dt = sigmas[i + 1] - sigma_hat + + if i // 2 == 1: + x = overall_sampling_step(x, model, dt, sigma_hat, **extra_args) + + if gamma > 0: + x = x - eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5 + + denoised = model(x, sigma_hat * s_in, **extra_args) + d = to_d(x, sigma_hat, denoised) + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + + # Euler method + x = x + d * dt + + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/euler_smea_dy.py b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_smea_dy.py new file mode 100644 index 0000000000000000000000000000000000000000..3fd210ba28ef19d1bc37815302fbf86c37f0e726 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_smea_dy.py @@ -0,0 +1,53 @@ +import torch + +from k_diffusion.sampling import to_d + +from tqdm.auto import trange + +from lib_es.utils import dy_sampling_step, smea_sampling_step +from lib_es.utils import sampler_metadata + + +@sampler_metadata("Euler SMEA Dy") +@torch.no_grad() +def sample_euler_smea_dy( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, +): + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + + for i in trange(len(sigmas) - 1, disable=disable): + gamma = max(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0 + eps = torch.randn_like(x) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + dt = sigmas[i + 1] - sigma_hat + + if gamma > 0: + x = x - eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5 + + denoised = model(x, sigma_hat * s_in, **extra_args) + d = to_d(x, sigma_hat, denoised) + + # Euler method + x = x + d * dt + + if sigmas[i + 1] > 0: + if i + 1 // 2 == 1: + x = dy_sampling_step(x, model, dt, sigma_hat, **extra_args) + + if i + 1 // 2 == 0: + x = smea_sampling_step(x, model, dt, sigma_hat, **extra_args) + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/euler_smea_dy_negative.py b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_smea_dy_negative.py new file mode 100644 index 0000000000000000000000000000000000000000..0511a5f9be32a0973ac9c2924c206f7503e04fb3 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/euler_smea_dy_negative.py @@ -0,0 +1,55 @@ +import torch + +from k_diffusion.sampling import to_d + +from tqdm.auto import trange + +from lib_es.utils import dy_sampling_step, smea_sampling_step +from lib_es.utils import sampler_metadata + + +@sampler_metadata("Euler SMEA Dy Negative") +@torch.no_grad() +def sample_euler_smea_dy_negative( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, +): + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + + for i in trange(len(sigmas) - 1, disable=disable): + gamma = max(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0 + eps = torch.randn_like(x) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + dt = sigmas[i + 1] - sigma_hat + + if gamma > 0: + x = x - eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5 + + denoised = model(x, sigma_hat * s_in, **extra_args) + d = to_d(x, sigma_hat, denoised) + + # Euler method + x = x + d * dt + + if sigmas[i + 1] > 0: + if i + 1 // 2 == 1: + x = dy_sampling_step(x, model, dt, sigma_hat, **extra_args) + x = -x - d * dt + + if i + 1 // 2 == 0: + x = smea_sampling_step(x, model, dt, sigma_hat, **extra_args) + x = -x - d * dt + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/extended_reverse_time.py b/sd-forge-extra-samplers/lib_es/extra_samplers/extended_reverse_time.py new file mode 100644 index 0000000000000000000000000000000000000000..537624b2fe0e6512e11641637c84d628e56ee97f --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/extended_reverse_time.py @@ -0,0 +1,83 @@ +import torch +from tqdm import trange + +import lib_es.const as consts +from lib_es.utils import default_noise_sampler, sampler_metadata + + +# From ComfyUI +@sampler_metadata( + "Extended Reverse-Time SDE", + {"uses_ensd": True, "scheduler": "sgm_uniform"}, + ["sample_er_sde, extended_reverse_sde"], +) +@torch.no_grad() +def sample_er_sde( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_noise=1.0, + noise_sampler=None, + noise_scaler=None, +): + """ + Extended Reverse-Time SDE solver (VE ER-SDE-Solver-3). Arxiv: https://arxiv.org/abs/2309.06169. + Code reference: https://github.com/QinpengCui/ER-SDE-Solver/blob/main/er_sde_solver.py. + """ + extra_args = {} if extra_args is None else extra_args + seed = extra_args.get("seed", None) + noise_sampler = default_noise_sampler(x, seed=seed) if noise_sampler is None else noise_sampler + s_in = x.new_ones([x.shape[0]]) + + max_stage: int = getattr(model.p, consts.ER_MAX_STAGE, 3) + + def default_noise_scaler(sigma): + return sigma * ((sigma**0.3).exp() + 10.0) + + noise_scaler = default_noise_scaler if noise_scaler is None else noise_scaler + num_integration_points = 200.0 + point_indice = torch.arange(0, num_integration_points, dtype=torch.float32, device=x.device) + + old_denoised = None + old_denoised_d = None + + for i in trange(len(sigmas) - 1, disable=disable): + denoised = model(x, sigmas[i] * s_in, **extra_args) + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised}) + stage_used = min(max_stage, i + 1) + if sigmas[i + 1] == 0: + x = denoised + elif stage_used == 1: + r = noise_scaler(sigmas[i + 1]) / noise_scaler(sigmas[i]) + x = r * x + (1 - r) * denoised + else: + r = noise_scaler(sigmas[i + 1]) / noise_scaler(sigmas[i]) + x = r * x + (1 - r) * denoised + + dt = sigmas[i + 1] - sigmas[i] + sigma_step_size = -dt / num_integration_points + sigma_pos = sigmas[i + 1] + point_indice * sigma_step_size + scaled_pos = noise_scaler(sigma_pos) + + # Stage 2 + s = torch.sum(1 / scaled_pos) * sigma_step_size + denoised_d = (denoised - old_denoised) / (sigmas[i] - sigmas[i - 1]) + x = x + (dt + s * noise_scaler(sigmas[i + 1])) * denoised_d + + if stage_used >= 3: + # Stage 3 + s_u = torch.sum((sigma_pos - sigmas[i]) / scaled_pos) * sigma_step_size + denoised_u = (denoised_d - old_denoised_d) / ((sigmas[i] - sigmas[i - 2]) / 2) + x = x + ((dt**2) / 2 + s_u * noise_scaler(sigmas[i + 1])) * denoised_u + old_denoised_d = denoised_d + + if s_noise != 0 and sigmas[i + 1] > 0: + x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * ( + sigmas[i + 1] ** 2 - sigmas[i] ** 2 * r**2 + ).sqrt().nan_to_num(nan=0.0) + old_denoised = denoised + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/gradient_estimation.py b/sd-forge-extra-samplers/lib_es/extra_samplers/gradient_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..f30cd94f39f5c7b272489dfa94f51462ddae456c --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/gradient_estimation.py @@ -0,0 +1,180 @@ +from collections.abc import Callable +from typing import Any, Optional +import torch +from tqdm import trange + +from k_diffusion.sampling import to_d +from modules import errors + +import lib_es.const as consts +from lib_es.utils import sampler_metadata + + +def compute_optimal_gamma(steps: int, adaptive: bool = True) -> float: + """ + Compute the optimal gamma parameter for gradient estimation based on step count. + + Args: + steps: Number of sampling steps + adaptive: Whether to use adaptive gamma based on step count + + Returns: + Optimal gamma value + """ + if not adaptive: + return consts.GE_DEFAULT_GAMMA + + # Define min and max values + min_steps, max_steps = 10, 100 + min_gamma, max_gamma = 1.5, 2.6 + + # Handle edge cases + if steps <= min_steps: + return min_gamma + elif steps >= max_steps: + return max_gamma + + # Apply logarithmic scaling + # log(steps/min_steps) / log(max_steps/min_steps) gives a value from 0 to 1 + # that increases logarithmically with steps + log_factor = torch.log(torch.tensor(steps / min_steps)) / torch.log(torch.tensor(max_steps / min_steps)) + + # Convert the logarithmic factor to gamma value + gamma = min_gamma + log_factor * (max_gamma - min_gamma) + + return float(gamma) + + +def validate_schedule(sigmas: torch.Tensor, eta: float = 0.1, nu: float = 2.0) -> bool: + """ + Validate whether a noise schedule satisfies the admissibility criteria from the paper. + + Args: + sigmas: Tensor of noise levels in descending order + eta: Error parameter + nu: Accuracy parameter for distance estimates + + Returns: + True if schedule is admissible, False otherwise + """ + n = len(sigmas) - 1 + is_admissible = True + issues = [] + + # Check if sigmas are strictly decreasing + if not torch.all(sigmas[:-1] > sigmas[1:]): + is_admissible = False + issues.append("Sigmas must be strictly decreasing") + + # Calculate the maximum allowable beta + c = 1 - nu ** (-1 / n) + beta_max = c / (eta + c) + + # Check that step sizes respect the admissibility criteria + for i in range(n - 1): + ratio = sigmas[i + 1] / sigmas[i] + beta = 1 - ratio + if beta > beta_max: + is_admissible = False + issues.append(f"Step {i} has beta {beta:.4f} > beta_max {beta_max:.4f}") + + if not is_admissible: + errors.display(ValueError(f"Noise schedule is not admissible: {', '.join(issues)}")) + errors.print_error_explanation("Noise schedule validation failed.\n\tIssues:" + ",\n\t\t".join(issues)) + + return is_admissible + + +@torch.no_grad() +@sampler_metadata("Gradient Estimation", {"scheduler": "sgm_uniform"}) +def sample_gradient_estimation( + model, + x: torch.Tensor, + sigmas: torch.Tensor, + extra_args: Optional[dict[str, Any]] = None, + callback: Optional[Callable] = None, + disable: Optional[bool] = None, + validate_sigmas: bool = False, + eta: float = 0.1, + nu: float = 2.0, +) -> torch.Tensor: + """ + Gradient-estimation sampler as described in "Interpreting and Improving Diffusion Models from an Optimization Perspective". + + This sampler implements a second-order method that improves upon DDIM by using a combination of current and previous + gradients to reduce gradient estimation error. It is based on the insight that denoising is approximately equivalent to + projection onto the data manifold, and diffusion sampling is gradient descent on the squared Euclidean distance function. + + Args: + model: The diffusion model + x: Input tensor + sigmas: Noise schedule (should be in descending order) + extra_args: Extra arguments to pass to the model + callback: Callback function + disable: Whether to disable the progress bar + validate_sigmas: Whether to validate the noise schedule + eta: Error parameter for schedule validation (default 0.1) + nu: Accuracy parameter for schedule validation (default 2.0) + + Returns: + Denoised tensor + + References: + Paper: https://openreview.net/pdf?id=o2ND9v0CeK + """ + # Parameter validation and initialization + if sigmas.shape[0] < 2: + raise ValueError("Need at least 2 timesteps for gradient estimation") + + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + old_d = None + steps = len(sigmas) - 1 + + # Schedule validation + if validate_sigmas: + validate_schedule(sigmas, eta, nu) + + # Get gamma from model properties or compute optimal value + use_adaptive_steps: bool = getattr(model.p, consts.GE_USE_ADAPTIVE_STEPS, True) + if use_adaptive_steps: + # Compute optimal gamma based on the number of steps + # and add the offset if specified + ge_gamma = compute_optimal_gamma(steps, use_adaptive_steps) + getattr( + model.p, consts.GE_GAMMA_OFFSET, consts.GE_DEFAULT_GAMMA_OFFSET + ) + else: + ge_gamma = getattr(model.p, consts.GE_GAMMA, consts.GE_DEFAULT_GAMMA) + + # Initialize timestep-adaptive gamma values if needed + timestep_adaptive_gamma = getattr(model.p, consts.GE_USE_TIMESTEP_ADAPTIVE_GAMMA, False) + + if timestep_adaptive_gamma: + # Higher gamma at the beginning, lower toward the end + # This is a heuristic based on the observation that early steps benefit more + # from aggressive gradient correction + gammas = torch.linspace(ge_gamma * 1.2, ge_gamma * 0.8, steps) + + # Main sampling loop + for i in trange(len(sigmas) - 1, disable=disable): + denoised = model(x, sigmas[i] * s_in, **extra_args) + d = to_d(x, sigmas[i], denoised) + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised}) + + dt = sigmas[i + 1] - sigmas[i] + + if i == 0: + # Euler method for first step + x = x + d * dt + else: + # Gradient estimation + current_gamma = gammas[i].item() if timestep_adaptive_gamma else ge_gamma + + d_bar = current_gamma * d + (1 - current_gamma) * old_d + x = x + d_bar * dt + + old_d = d + + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/heun_ancestral.py b/sd-forge-extra-samplers/lib_es/extra_samplers/heun_ancestral.py new file mode 100644 index 0000000000000000000000000000000000000000..e45d835888ee9de370fa5b0e87aeb5ef6bf10388 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/heun_ancestral.py @@ -0,0 +1,81 @@ +import torch +from tqdm.auto import trange +from k_diffusion.sampling import default_noise_sampler, get_ancestral_step, to_d + +from lib_es.utils import sampler_metadata + + +@sampler_metadata( + "Heun Ancestral", + {"uses_ensd": True}, +) +@torch.no_grad() +def sample_heun_ancestral( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + eta=1.0, + s_noise=1.0, + noise_sampler=None, +): + """ + Ancestral sampling with Heun's method steps. + + Args: + model: The model to sample from. + x: The initial noise. + sigmas: The noise levels to sample at. + extra_args: Extra arguments to the model. + callback: A function that's called after each step. + disable: Disable tqdm progress bar. + eta: Ancestral sampling strength parameter. + s_noise: Noise scale. + noise_sampler: A function that returns noise. + """ + extra_args = {} if extra_args is None else extra_args + noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler + s_in = x.new_ones([x.shape[0]]) + + for i in trange(len(sigmas) - 1, disable=disable): + # Get current and next sigma + sigma = sigmas[i] + + # Run denoising model + denoised = model(x, sigma * s_in, **extra_args) + + # Calculate ancestral step parameters + sigma_down, sigma_up = get_ancestral_step(sigma, sigmas[i + 1], eta=eta) + + if callback is not None: + callback({"x": x, "i": i, "sigma": sigma, "sigma_hat": sigma, "denoised": denoised}) + + # Calculate the derivative + d = to_d(x, sigma, denoised) + + # Determine step size + dt = sigma_down - sigma + + if sigma_down == 0: + # For the last step, use Euler method for stability + x = x + d * dt + else: + # Heun's method (predictor-corrector) + # 1. Predictor step (Euler) + x_2 = x + d * dt + + # 2. Evaluate at the predicted point + denoised_2 = model(x_2, sigma_down * s_in, **extra_args) + d_2 = to_d(x_2, sigma_down, denoised_2) + + # 3. Corrector step (average of gradients) + d_prime = (d + d_2) / 2 + x = x + d_prime * dt + + # Add noise according to ancestral sampling formula + if sigma_up > 0: + x = x + noise_sampler(sigma, sigmas[i + 1]) * s_noise * sigma_up + + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/kohaku_lonyu_yog.py b/sd-forge-extra-samplers/lib_es/extra_samplers/kohaku_lonyu_yog.py new file mode 100644 index 0000000000000000000000000000000000000000..63e5af6816e63fc3c79842063891c34db49b27c2 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/kohaku_lonyu_yog.py @@ -0,0 +1,58 @@ +import torch + +from k_diffusion.sampling import default_noise_sampler, get_ancestral_step, to_d + +from tqdm.auto import trange + +from lib_es.utils import sampler_metadata + + +@sampler_metadata("Kohaku LoNyu Yog") +@torch.no_grad() +def sample_kohaku_lonyu_yog( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, + noise_sampler=None, + eta=1.0, +): + """Kohaku_LoNyu_Yog""" + extra_args = {} if extra_args is None else extra_args + s_in = x.new_ones([x.shape[0]]) + noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler + for i in trange(len(sigmas) - 1, disable=disable): + gamma = min(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0 + eps = torch.randn_like(x) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + if gamma > 0: + x = x + eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5 + denoised = model(x, sigma_hat * s_in, **extra_args) + d = to_d(x, sigma_hat, denoised) + sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta) + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + dt = sigma_down - sigmas[i] + + if i <= (len(sigmas) - 1) / 2: + x2 = -x + denoised2 = model(x2, sigma_hat * s_in, **extra_args) + d2 = to_d(x2, sigma_hat, denoised2) + + x3 = x + ((d + d2) / 2) * dt + denoised3 = model(x3, sigma_hat * s_in, **extra_args) + d3 = to_d(x3, sigma_hat, denoised3) + + real_d = (d + d3) / 2 + x = x + real_d * dt + + x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up + else: + x = x + d * dt + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/langevin_euler.py b/sd-forge-extra-samplers/lib_es/extra_samplers/langevin_euler.py new file mode 100644 index 0000000000000000000000000000000000000000..89fa9b3fa5258f9784d23a9791684eececa0030b --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/langevin_euler.py @@ -0,0 +1,89 @@ +import torch +from tqdm.auto import trange +from k_diffusion.sampling import default_noise_sampler, to_d + +import lib_es.const as consts +from lib_es.utils import sampler_metadata + + +@sampler_metadata( + "Langevin Euler", + {"scheduler": "sgm_uniform"}, +) +@torch.no_grad() +def sample_langevin_euler( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_churn=0.0, + s_tmin=0.0, + s_tmax=float("inf"), + s_noise=1.0, + noise_sampler=None, +): + """ + Langevin dynamics sampler - the adaptive CFG is now handled by the CFG function. + This is your original implementation but with the adaptive CFG logic removed. + """ + extra_args = {} if extra_args is None else extra_args + noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler + s_in = x.new_ones([x.shape[0]]) + + # Store original shape for aspect ratio calculations + height, width = x.shape[2:4] + aspect_ratio = width / height + sigma_max = sigmas[0] + + langevin_strength = getattr(model.p, consts.LANGEVIN_STRENGTH, 0.1) + + for i in trange(len(sigmas) - 1, disable=disable): + # Apply s_churn noise if requested + gamma = min(s_churn / (len(sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigmas[i] <= s_tmax else 0.0 + eps = torch.randn_like(x) * s_noise + sigma_hat = sigmas[i] * (gamma + 1) + if gamma > 0: + x = x + eps * (sigma_hat**2 - sigmas[i] ** 2) ** 0.5 + + # Perform model prediction - CFG is now handled by our function + denoised = model(x, sigma_hat * s_in, **extra_args) + + # Call the callback + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigma_hat, "denoised": denoised}) + + # Calculate the derivative + d = to_d(x, sigma_hat, denoised) + + # Langevin step: Deterministic part + Noise part + dt = sigmas[i + 1] - sigma_hat + + # Deterministic Euler step + x = x + d * dt + + # Apply Langevin noise if not the final step + if sigmas[i + 1] > 0: + # Simpler Langevin noise logic with less aggressive scaling + # Use a constant base noise level with a gentle decay + base_noise_level = langevin_strength # Base level from parameter + + # Gentle decay curve - more consistent noise across steps + # Sqrt provides a more gradual decrease than linear scaling + decay_factor = torch.sqrt(sigmas[i + 1] / sigma_max) + noise_scale = base_noise_level * (0.1 + 0.9 * decay_factor) + + # Higher safety clamp to allow more noise influence + noise_scale = max(langevin_strength * 0.05, min(noise_scale, 0.8)) + + # Generate balanced noise + noise = torch.randn_like(x) * noise_scale + height_scale = torch.sqrt(torch.tensor(aspect_ratio)) + width_scale = 1.0 / height_scale + scaling = torch.tensor([1.0, 1.0, height_scale, width_scale]).reshape(1, -1, 1, 1).to(x.device) + balanced_noise = noise * scaling + + x = x + balanced_noise + + return x diff --git a/sd-forge-extra-samplers/lib_es/extra_samplers/res_multistep.py b/sd-forge-extra-samplers/lib_es/extra_samplers/res_multistep.py new file mode 100644 index 0000000000000000000000000000000000000000..78b8dfa94cd5d80f41c743745684f107ca848783 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_samplers/res_multistep.py @@ -0,0 +1,235 @@ +import torch +from tqdm.auto import trange + +#from backend.modules.k_diffusion_extra import default_noise_sampler +#from backend.patcher.unet import UnetPatcher +from k_diffusion.sampling import get_ancestral_step, to_d + +from lib_es.utils import sampler_metadata + + +def sigma_fn(t): + """ + Computes the sigma function for a given tensor `t`. + The sigma function is defined as the exponential of the negation of `t`. + Args: + t (torch.Tensor): Input tensor. + Returns: + torch.Tensor: The result of applying the sigma function to `t`. + """ + + return t.neg().exp() + + +def t_fn(sigma): + """ + Computes the negative logarithm of the input tensor. + Args: + sigma (torch.Tensor): A tensor for which the negative logarithm is to be computed. + Returns: + torch.Tensor: A tensor containing the negative logarithm of the input tensor. + """ + + return sigma.log().neg() + + +def phi1_fn(t): + """ + Computes the function phi1(t) = (exp(t) - 1) / t using PyTorch's expm1 function. + Args: + t (torch.Tensor): Input tensor. + Returns: + torch.Tensor: The result of (exp(t) - 1) / t. + """ + + return torch.expm1(t) / t + + +def phi2_fn(t): + """ + Compute the value of the phi2 function. + The phi2 function is defined as (phi1_fn(t) - 1.0) / t, where phi1_fn is + another function that takes a single argument t. + Parameters: + t (float): The input value for the function. + Returns: + float: The computed value of the phi2 function. + """ + + return (phi1_fn(t) - 1.0) / t + + +@torch.no_grad() +def res_multistep( + model, + x, + sigmas, + extra_args=None, + callback=None, + disable=None, + s_noise=1.0, + noise_sampler=None, + eta=1.0, + cfg_pp=False, +): + """ + Perform multi-step denoising using a conditional denoising model. + Args: + model (CFGDenoiserKDiffusion): The denoising model to use. + x (torch.Tensor): The input tensor to be denoised. + sigmas (list or torch.Tensor): A list or tensor of sigma values for each step. + extra_args (dict, optional): Additional arguments to pass to the model. Defaults to None. + callback (callable, optional): A callback function to be called after each step. Defaults to None. + disable (bool, optional): If True, disables the progress bar. Defaults to None. + s_noise (float, optional): Noise scale for stochasticity. Defaults to 1.0. + noise_sampler (callable, optional): Function to sample noise. Defaults to None. + cfg_pp (bool, optional): If True, enables post-processing for classifier-free guidance. Defaults to False. + Returns: + torch.Tensor: The denoised output tensor. + """ + extra_args = {} if extra_args is None else extra_args + noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler + s_in = x.new_ones([x.shape[0]]) + + old_denoised = None + uncond_denoised = None + + # unconditional denoised is used for the second order multistep method + def post_cfg_function(args): + nonlocal uncond_denoised + uncond_denoised = args["uncond_denoised"] + return args["denoised"] + + if cfg_pp: + model.need_last_noise_uncond = True + unet_patcher: UnetPatcher = model.inner_model.inner_model.forge_objects.unet + unet_patcher.model_options["disable_cfg1_optimization"] = True # not sure if this really works + unet_patcher.set_model_sampler_post_cfg_function(post_cfg_function) + + for i in trange(len(sigmas) - 1, disable=disable): + denoised = model(x, sigmas[i] * s_in, **extra_args) + sigma_down, sigma_up = get_ancestral_step(sigmas[i], sigmas[i + 1], eta=eta) + if callback is not None: + callback({"x": x, "i": i, "sigma": sigmas[i], "sigma_hat": sigmas[i], "denoised": denoised}) + if sigma_down == 0 or old_denoised is None: + # Euler method + if cfg_pp: + d = to_d(x, sigmas[i], uncond_denoised) + x = denoised + d * sigma_down + else: + d = to_d(x, sigmas[i], denoised) + dt = sigma_down - sigmas[i] + x = x + d * dt + else: + # Second order multistep method in https://arxiv.org/pdf/2308.02157 + t, t_next, t_prev = t_fn(sigmas[i]), t_fn(sigma_down), t_fn(sigmas[i - 1]) + h = t_next - t + c2 = (t_prev - t) / h + + phi1_val, phi2_val = phi1_fn(-h), phi2_fn(-h) + b1 = torch.nan_to_num(phi1_val - phi2_val / c2, nan=0.0) + b2 = torch.nan_to_num(phi2_val / c2, nan=0.0) + + if cfg_pp: + x = x + (denoised - uncond_denoised) + x = sigma_fn(h) * x + h * (b1 * uncond_denoised + b2 * old_denoised) + else: + x = sigma_fn(h) * x + h * (b1 * denoised + b2 * old_denoised) + + # Noise addition + if sigmas[i + 1] > 0: + x = x + noise_sampler(sigmas[i], sigmas[i + 1]) * s_noise * sigma_up + + if cfg_pp: + old_denoised = uncond_denoised + else: + old_denoised = denoised + return x + + +@sampler_metadata( + "Res Multistep", + {"scheduler": "sgm_uniform"}, +) +@torch.no_grad() +def sample_res_multistep( + model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1.0, noise_sampler=None +): + return res_multistep( + model, + x, + sigmas, + extra_args=extra_args, + callback=callback, + disable=disable, + s_noise=s_noise, + noise_sampler=noise_sampler, + eta=0.0, + cfg_pp=False, + ) + + +@sampler_metadata( + "Res Multistep CFG++", + {"scheduler": "sgm_uniform"}, +) +@torch.no_grad() +def sample_res_multistep_cfg_pp( + model, x, sigmas, extra_args=None, callback=None, disable=None, s_noise=1.0, noise_sampler=None +): + return res_multistep( + model, + x, + sigmas, + extra_args=extra_args, + callback=callback, + disable=disable, + s_noise=s_noise, + noise_sampler=noise_sampler, + eta=0.0, + cfg_pp=True, + ) + + +@sampler_metadata( + "Res Multistep Ancestral", + {"uses_ensd": True, "scheduler": "sgm_uniform"}, +) +@torch.no_grad() +def sample_res_multistep_ancestral( + model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None +): + return res_multistep( + model, + x, + sigmas, + extra_args=extra_args, + callback=callback, + disable=disable, + s_noise=s_noise, + noise_sampler=noise_sampler, + eta=eta, + cfg_pp=False, + ) + + +@sampler_metadata( + "Res Multistep Ancestral CFG++", + {"uses_ensd": True, "scheduler": "sgm_uniform"}, +) +@torch.no_grad() +def sample_res_multistep_ancestral_cfg_pp( + model, x, sigmas, extra_args=None, callback=None, disable=None, eta=1.0, s_noise=1.0, noise_sampler=None +): + return res_multistep( + model, + x, + sigmas, + extra_args=extra_args, + callback=callback, + disable=disable, + s_noise=s_noise, + noise_sampler=noise_sampler, + eta=eta, + cfg_pp=True, + ) diff --git a/sd-forge-extra-samplers/lib_es/extra_schedulers/__init__.py b/sd-forge-extra-samplers/lib_es/extra_schedulers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3406ed1b6bb5a21c639f7fb85eda4c4ec06c88b --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_schedulers/__init__.py @@ -0,0 +1,6 @@ +from lib_es.extra_schedulers.linear_log import linear_log + + +__all_schedulers__ = [ + linear_log, +] diff --git a/sd-forge-extra-samplers/lib_es/extra_schedulers/__pycache__/__init__.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_schedulers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb5089529b5d7ccaca954d1b332eb1245cc0b8c3 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_schedulers/__pycache__/__init__.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_schedulers/__pycache__/linear_log.cpython-310.pyc b/sd-forge-extra-samplers/lib_es/extra_schedulers/__pycache__/linear_log.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba4a128c430a20140c01592454314c52d53bb9d5 Binary files /dev/null and b/sd-forge-extra-samplers/lib_es/extra_schedulers/__pycache__/linear_log.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/lib_es/extra_schedulers/linear_log.py b/sd-forge-extra-samplers/lib_es/extra_schedulers/linear_log.py new file mode 100644 index 0000000000000000000000000000000000000000..6f52f161db9aa8d07ae6e74606ab454192df423f --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/extra_schedulers/linear_log.py @@ -0,0 +1,63 @@ +import torch + +from lib_es.utils import scheduler_metadata + + +@scheduler_metadata(name="linear_log", alias="Linear Log", need_inner_model=True) +def linear_log( + n: int, + sigma_min: float, + sigma_max: float, + inner_model, + device: torch.device, + eta: float = 0.1, + nu: float = 2.0, + sgm: bool = False, + floor=False, + final_step_full: bool = True, +) -> torch.Tensor: + """ + Creates a log-linear (geometric) noise schedule as recommended in the paper. + + Args: + n: Number of sampling steps + sigma_min: Minimum noise level + sigma_max: Maximum noise level + eta: Error parameter (default 0.1, as estimated in the paper for CIFAR-10) + nu: Accuracy parameter for distance estimates (default 2.0) + final_step_full: Whether to take a full step (β=1) for the final iteration + + Returns: + A tensor of sigma values in descending order with a geometric progression. + """ + + # TODO: Add adjustable eta/nu parameters for more flexibility + + # Calculate the maximum allowable beta based on the admissibility criteria + # β*,N = c/(η+c) where c = 1 - ν^(-1/N) + c = 1 - nu ** (-1 / n) + beta_max = c / (eta + c) + + # Calculate the ratio that would give us exactly sigma_min from sigma_max in n steps + exact_ratio = (sigma_min / sigma_max) ** (1 / (n - 1)) + + # Use the smaller of the two to ensure admissibility + ratio = max(1 - beta_max, exact_ratio) + + # Generate the geometric sequence + sigs = [sigma_max] + for i in range(1, n): + next_sigma = sigs[-1] * ratio + + # For the final step, optionally set beta=1 (as recommended in the paper) + if final_step_full and i == n - 1: + next_sigma = sigma_min + + sigs.append(next_sigma) + + if not sgm: + # Add final value of 0.0 + sigs.append(0.0) + + # Convert to tensor + return torch.tensor(sigs) diff --git a/sd-forge-extra-samplers/lib_es/samplers.py b/sd-forge-extra-samplers/lib_es/samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..b2de5d43c24580c5d95f7fce6b3db3afedcd2d1f --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/samplers.py @@ -0,0 +1,57 @@ +from modules.sd_samplers import all_samplers +from modules.sd_samplers_common import SamplerData +from modules.sd_samplers_kdiffusion import KDiffusionSampler + +from lib_es.extra_samplers import __sampler_funcs__ + + +# See modules_forge/alter_samplers.py for the basis of this class and build_constructor function +class ExtraSampler(KDiffusionSampler): + """ + Overloads KDiffusionSampler to add extra parameters to the constructor + Based off lllyasviel's AlterSampler + """ + + def __init__(self, sd_model, sampler_name, sampler_func, options=None): + self.sampler_name = sampler_name + self.unet = sd_model.model.diffusion_model + sampler_function = sampler_func + super().__init__(sampler_function, sd_model, options) + self.extra_params = ["s_churn", "s_tmin", "s_tmax", "s_noise"] + + +def build_constructor(sampler_name, sampler_func): + def constructor(m): + return ExtraSampler(m, sampler_name, sampler_func) + + return constructor + + +extra_sampler_list = [ + ( + fn.sampler_name, + fn, + fn.sampler_k_names, + fn.sampler_extra_params, + ) + for fn in __sampler_funcs__ +] + +samplers_data_k_diffusion: list[SamplerData] = [ + SamplerData(name, build_constructor(sampler_name=name, sampler_func=funcname), aliases, options) + for name, funcname, aliases, options in extra_sampler_list +] + + +def add_extra_samplers(): + import modules.sd_samplers as sd_samplers + + for sampler in samplers_data_k_diffusion: + if sampler.name not in sd_samplers.all_samplers_map: + sd_samplers.all_samplers.append(sampler) + + sd_samplers.all_samplers_map = {x.name: x for x in sd_samplers.all_samplers} + sd_samplers.set_samplers() + + + diff --git a/sd-forge-extra-samplers/lib_es/schedulers.py b/sd-forge-extra-samplers/lib_es/schedulers.py new file mode 100644 index 0000000000000000000000000000000000000000..43380930d5fedc67bdcda049c3c47ee73eb983b8 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/schedulers.py @@ -0,0 +1,18 @@ +from lib_es.extra_schedulers import __all_schedulers__ + +import modules.sd_schedulers as sched + + +extra_scheduler_list = [ + sched.Scheduler(fn.name, fn.alias, fn, need_inner_model=fn.need_inner_model) for fn in __all_schedulers__ +] + + +def add_schedulers(): + """ + Add extra schedulers to the list of schedulers in the webui. + """ + for scheduler in extra_scheduler_list: + if scheduler.name not in sched.schedulers_map: + sched.schedulers.append(scheduler) + sched.schedulers_map = {**{x.name: x for x in sched.schedulers}, **{x.label: x for x in sched.schedulers}} diff --git a/sd-forge-extra-samplers/lib_es/utils.py b/sd-forge-extra-samplers/lib_es/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fbd3bd830e36c5583fff3122654133555fb99048 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/utils.py @@ -0,0 +1,230 @@ +from enum import Enum +import math + +import torch + +from k_diffusion.sampling import to_d + + +def clamp(x: int | float, lower: int | float, upper: int | float) -> int | float: + return max(lower, min(x, upper)) + + +# From ComfyUI +def default_noise_sampler(x, seed=None): + """ + Default noise sampler for the extended reverse SDE solver. + Generates Gaussian noise based on the input tensor's shape and device. + If a seed is provided, it uses that seed for reproducibility. + """ + if seed is not None: + generator = torch.Generator(device=x.device) + generator.manual_seed(seed) + else: + generator = None + + return lambda sigma, sigma_next: torch.randn( + x.size(), dtype=x.dtype, layout=x.layout, device=x.device, generator=generator + ) + + +class _Rescaler: + def __init__(self, model, x, mode, **extra_args): + self.model = model + self.x = x + self.mode = mode + self.extra_args = extra_args + self.init_latent, self.mask, self.nmask = model.init_latent, model.mask, model.nmask + + def __enter__(self): + if self.init_latent is not None: + self.model.init_latent = torch.nn.functional.interpolate( + input=self.init_latent, size=self.x.shape[2:4], mode=self.mode + ) + if self.mask is not None: + self.model.mask = torch.nn.functional.interpolate( + input=self.mask.unsqueeze(0), size=self.x.shape[2:4], mode=self.mode + ).squeeze(0) + if self.nmask is not None: + self.model.nmask = torch.nn.functional.interpolate( + input=self.nmask.unsqueeze(0), size=self.x.shape[2:4], mode=self.mode + ).squeeze(0) + + return self + + def __exit__(self, type, value, traceback): + del self.model.init_latent, self.model.mask, self.model.nmask + self.model.init_latent, self.model.mask, self.model.nmask = self.init_latent, self.mask, self.nmask + + +@torch.no_grad() +def overall_sampling_step(x, model, dt, sigma_hat, **extra_args): + original_shape = x.shape + batch_size, channels, m, n = original_shape[0], original_shape[1], original_shape[2] // 2, original_shape[3] // 2 + extra_row = x.shape[2] % 2 == 1 + extra_col = x.shape[3] % 2 == 1 + + if extra_row: + extra_row_content = x[:, :, -1:, :] + x = x[:, :, :-1, :] + + if extra_col: + extra_col_content = x[:, :, :, -1:] + x = x[:, :, :, :-1] + + a_list = x.unfold(2, 2, 2).unfold(3, 2, 2).contiguous().view(batch_size, channels, m * n, 2, 2) + c = a_list[:, :, :, 1, 1].view(batch_size, channels, m, n) + + denoised = model(c, sigma_hat * c.new_ones([c.shape[0]]), **extra_args) + d = to_d(c, sigma_hat, denoised) + c = c + d * dt + + d_list = denoised.view(batch_size, channels, m * n, 1, 1) + a_list[:, :, :, 1, 1] = d_list[:, :, :, 0, 0] + + x = ( + a_list.view(batch_size, channels, m, n, 2, 2) + .permute(0, 1, 2, 4, 3, 5) + .reshape(batch_size, channels, 2 * m, 2 * n) + ) + + if extra_row or extra_col: + x_expanded = torch.zeros(original_shape, dtype=x.dtype, device=x.device) + x_expanded[:, :, : 2 * m, : 2 * n] = x + + if extra_row: + x_expanded[:, :, -1:, : 2 * n + 1] = extra_row_content + + if extra_col: + x_expanded[:, :, : 2 * m, -1:] = extra_col_content + + if extra_row and extra_col: + x_expanded[:, :, -1:, -1:] = extra_col_content[:, :, -1:, :] + + x = x_expanded + + return x + + +@torch.no_grad() +def smea_sampling_step(x, model, dt, sigma_hat, **extra_args): + m, n = x.shape[2], x.shape[3] + x = torch.nn.functional.interpolate(input=x, scale_factor=(1.25, 1.25), mode="nearest-exact") + + with _Rescaler(model, x, "nearest-exact", **extra_args) as rescaler: + denoised = model(x, sigma_hat * x.new_ones([x.shape[0]]), **rescaler.extra_args) + + d = to_d(x, sigma_hat, denoised) + x = x + d * dt + x = torch.nn.functional.interpolate(input=x, size=(m, n), mode="nearest-exact") + + return x + + +@torch.no_grad() +def dy_sampling_step(x, model, dt, sigma_hat, **extra_args): + original_shape = x.shape + batch_size, channels, m, n = original_shape[0], original_shape[1], original_shape[2] // 2, original_shape[3] // 2 + extra_row = x.shape[2] % 2 == 1 + extra_col = x.shape[3] % 2 == 1 + + if extra_row: + extra_row_content = x[:, :, -1:, :] + x = x[:, :, :-1, :] + if extra_col: + extra_col_content = x[:, :, :, -1:] + x = x[:, :, :, :-1] + + a_list = x.unfold(2, 2, 2).unfold(3, 2, 2).contiguous().view(batch_size, channels, m * n, 2, 2) + c = a_list[:, :, :, 1, 1].view(batch_size, channels, m, n) + + with _Rescaler(model, c, "nearest-exact", **extra_args) as rescaler: + denoised = model(c, sigma_hat * c.new_ones([c.shape[0]]), **rescaler.extra_args) + + d = to_d(c, sigma_hat, denoised) + c = c + d * dt + + d_list = c.view(batch_size, channels, m * n, 1, 1) + a_list[:, :, :, 1, 1] = d_list[:, :, :, 0, 0] + x = ( + a_list.view(batch_size, channels, m, n, 2, 2) + .permute(0, 1, 2, 4, 3, 5) + .reshape(batch_size, channels, 2 * m, 2 * n) + ) + + if extra_row or extra_col: + x_expanded = torch.zeros(original_shape, dtype=x.dtype, device=x.device) + x_expanded[:, :, : 2 * m, : 2 * n] = x + + if extra_row: + x_expanded[:, :, -1:, : 2 * n + 1] = extra_row_content + + if extra_col: + x_expanded[:, :, : 2 * m, -1:] = extra_col_content + + if extra_row and extra_col: + x_expanded[:, :, -1:, -1:] = extra_col_content[:, :, -1:, :] + + x = x_expanded + + return x + + +def sampler_metadata(name: str, extra_params: dict = {}, sampler_aliases: list[str] = []): + def decorator(func): + func.sampler_extra_params = extra_params + func.sampler_name = name + func.sampler_k_names = [name.replace(" ", "_").lower(), *sampler_aliases] + return func + + return decorator + + +def scheduler_metadata(name: str, alias: str, need_inner_model: bool = False): + def decorator(func): + func.name = name + func.alias = alias + func.need_inner_model = need_inner_model + return func + + return decorator + + +class Interpolator(Enum): + LINEAR = (lambda x: x,) # noqa: E731 + COSINE = (lambda x: torch.sin(x * math.pi / 2),) # noqa: E731 + SINE = (lambda x: 1 - torch.cos(x * math.pi / 2),) # noqa: E731 + + +# Original Implementation `ExtendIntermediateSigmas` by catboxanon: https://www.github.com/catboxanon/ +# Original class impl: https://github.com/comfyanonymous/ComfyUI/blob/065d855f14968406051a1340e3f2f26461a00e5d/comfy_extras/nodes_custom_sampler.py#L253 +def extend_sigmas( + sigmas: torch.Tensor, + steps: int, + start_at_sigma: float, + end_at_sigma: float, + interpolator: Interpolator = Interpolator.LINEAR, +) -> torch.FloatTensor: + if start_at_sigma < 0: + start_at_sigma = float("inf") + + # linear space for our interpolation function + x = torch.linspace(0, 1, steps + 1, device=sigmas.device)[1:-1] + computed_spacing: torch.Tensor = interpolator.value[0](x) + + extended_sigmas: list[torch.Tensor] = [] + for i in range(len(sigmas) - 1): + sigma_current = sigmas[i] + sigma_next = sigmas[i + 1] + + extended_sigmas.append(sigma_current) + + if end_at_sigma <= sigma_current <= start_at_sigma: + interpolated_steps: torch.Tensor = computed_spacing * (sigma_next - sigma_current) + sigma_current + extended_sigmas.extend(interpolated_steps.tolist()) + + # Add the last sigma value + if len(sigmas) > 0: + extended_sigmas.append(sigmas[-1]) + + return torch.FloatTensor(extended_sigmas) diff --git a/sd-forge-extra-samplers/lib_es/xyz.py b/sd-forge-extra-samplers/lib_es/xyz.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba3458b6512390b2ac86ada23201f9a74bd6cf3 --- /dev/null +++ b/sd-forge-extra-samplers/lib_es/xyz.py @@ -0,0 +1,49 @@ +from modules import scripts + +import lib_es.const as consts + + +def _grid_reference(): + for data in scripts.scripts_data: + if data.script_class.__module__ in ( + "scripts.xyz_grid", + "xyz_grid.py", + ) and hasattr(data, "module"): + return data.module + + raise SystemError("Could not find X/Y/Z Plot...") + + +def xyz_support(cache: dict): + def apply_field(field, is_bool=False): + def _(p, x, xs): + if is_bool: + x = True if x.lower() == "true" else False + cache.update({field: x}) + + return _ + + xyz_grid = _grid_reference() + + extra_axis_options = [ + xyz_grid.AxisOption("[Adaptive Prog] Ancestral Eta", float, apply_field(consts.AP_ANCESTRAL_ETA)), + xyz_grid.AxisOption("[Adaptive Prog] Detail Strength", float, apply_field(consts.AP_DETAIL_STRENGTH)), + xyz_grid.AxisOption("[Adaptive Prog] DPM++ 2M End", float, apply_field(consts.AP_DPM_2M_END)), + xyz_grid.AxisOption("[Adaptive Prog] Euler A End", float, apply_field(consts.AP_EULER_A_END)), + xyz_grid.AxisOption("[Extended Reverse-Time] Max Stage", int, apply_field(consts.ER_MAX_STAGE)), + xyz_grid.AxisOption("[Gradient Estimation] GE Gamma Offset", float, apply_field(consts.GE_GAMMA_OFFSET)), + xyz_grid.AxisOption("[Gradient Estimation] GE Gamma", float, apply_field(consts.GE_GAMMA)), + xyz_grid.AxisOption( + "[Gradient Estimation] GE Use Adaptive Steps", + str, + apply_field(consts.GE_USE_ADAPTIVE_STEPS, is_bool=True), + ), + xyz_grid.AxisOption( + "[Gradient Estimation] GE Use Timestep Adaptive Gamma", + str, + apply_field(consts.GE_USE_TIMESTEP_ADAPTIVE_GAMMA, is_bool=True), + ), + xyz_grid.AxisOption("[Langevin Euler] Langevin Strength", float, apply_field(consts.LANGEVIN_STRENGTH)), + ] + + xyz_grid.axis_options.extend(extra_axis_options) diff --git a/sd-forge-extra-samplers/pyproject.toml b/sd-forge-extra-samplers/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..ae961154eabfc31d7dc77894b10d5766646b5e23 --- /dev/null +++ b/sd-forge-extra-samplers/pyproject.toml @@ -0,0 +1,78 @@ +[tool.ruff] +# Exclude a variety of commonly ignored directories. +exclude = [ + ".bzr", + ".direnv", + ".eggs", + ".git", + ".git-rewrite", + ".hg", + ".ipynb_checkpoints", + ".mypy_cache", + ".nox", + ".pants.d", + ".pyenv", + ".pytest_cache", + ".pytype", + ".ruff_cache", + ".svn", + ".tox", + ".venv", + ".vscode", + "__pypackages__", + "_build", + "buck-out", + "build", + "dist", + "node_modules", + "site-packages", + "venv", +] + +# Same as Black. +line-length = 120 +indent-width = 4 + +# Assume Python 3.8 +target-version = "py310" + +[tool.ruff.lint] +# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default. +# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or +# McCabe complexity (`C901`) by default. +select = ["E4", "E7", "E9", "F"] +ignore = [] + +# Allow fix for all enabled rules (when `--fix`) is provided. +fixable = ["ALL"] +unfixable = [] + +# Allow unused variables when underscore-prefixed. +dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" + +[tool.ruff.format] +# Like Black, use double quotes for strings. +quote-style = "double" + +# Like Black, indent with spaces, rather than tabs. +indent-style = "space" + +# Like Black, respect magic trailing commas. +skip-magic-trailing-comma = false + +# Like Black, automatically detect the appropriate line ending. +line-ending = "auto" + +# Enable auto-formatting of code examples in docstrings. Markdown, +# reStructuredText code/literal blocks and doctests are all supported. +# +# This is currently disabled by default, but it is planned for this +# to be opt-out in the future. +docstring-code-format = false + +# Set the line length limit used when formatting code snippets in +# docstrings. +# +# This only has an effect when the `docstring-code-format` setting is +# enabled. +docstring-code-line-length = "dynamic" \ No newline at end of file diff --git a/sd-forge-extra-samplers/scripts/__pycache__/extra_samplers.cpython-310.pyc b/sd-forge-extra-samplers/scripts/__pycache__/extra_samplers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb6184dfee0a6d019e9e84663473ab92c49f363a Binary files /dev/null and b/sd-forge-extra-samplers/scripts/__pycache__/extra_samplers.cpython-310.pyc differ diff --git a/sd-forge-extra-samplers/scripts/extra_samplers.py b/sd-forge-extra-samplers/scripts/extra_samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..fa83aa368678f70327aa8e5ae3a22f9e14f941ed --- /dev/null +++ b/sd-forge-extra-samplers/scripts/extra_samplers.py @@ -0,0 +1,359 @@ +from typing import Any + +import gradio as gr + +import modules.scripts as scripts +from modules.processing import StableDiffusionProcessing +from modules.script_callbacks import on_ui_settings, on_app_started +from modules.shared import OptionInfo, opts + +import lib_es.const as consts +from lib_es.xyz import xyz_support +from lib_es.samplers import add_extra_samplers +from lib_es.schedulers import add_schedulers + +from modules.script_callbacks import on_before_ui + +def early_init(): + add_extra_samplers() + add_schedulers() + +on_before_ui(early_init) + + + + + +def from_setting_or_default(key: str, default: None | Any) -> None | Any: + return opts.data.get(key, default) + + +def on_change_update_setting(key: str, value: Any) -> None: + opts.set(key, value) + + +class ExtraSamplerExtension(scripts.Script): + def __init__(self): + super().__init__() + self.xyz_cache = {} + xyz_support(self.xyz_cache) + + def title(self): + return "Extra Samplers" + + def show(self, is_img2img): + return scripts.AlwaysVisible + + def ui(self, is_img2img): + with gr.Accordion(label="Extra Samplers", open=False): + with gr.Accordion(label="Adaptive Progressive", open=False): + gr.Markdown("Adaptive progressive sampler that automatically adjusts to different step counts. ") + gr.Markdown( + "Phase ends are automatically adjusted based on the total number of steps. These are approximations" + ) + with gr.Row(): + euler_a_end = gr.Slider( + minimum=0.0, + maximum=1.0, + step=0.05, + value=from_setting_or_default(consts.AP_EULER_A_END, 0.35), + label="Euler A end", + ) + dpm_2m_end = gr.Slider( + minimum=0.0, + maximum=1.0, + step=0.05, + value=from_setting_or_default(consts.AP_DPM_2M_END, 0.75), + label="DPM++ 2M end", + ) + with gr.Row(): + ancestral_eta = gr.Slider( + minimum=0.0, + maximum=1.0, + step=0.05, + value=from_setting_or_default(consts.AP_ANCESTRAL_ETA, 0.4), + label="Ancestral Eta", + ) + detail_strength = gr.Slider( + minimum=0.0, + maximum=10.0, + step=0.1, + value=from_setting_or_default(consts.AP_DETAIL_STRENGTH, 1.5), + label="Detail Strength", + ) + + euler_a_end.change( + fn=lambda value: on_change_update_setting(consts.AP_EULER_A_END, value), inputs=[euler_a_end] + ) + dpm_2m_end.change( + fn=lambda value: on_change_update_setting(consts.AP_DPM_2M_END, value), inputs=[dpm_2m_end] + ) + ancestral_eta.change( + fn=lambda value: on_change_update_setting(consts.AP_ANCESTRAL_ETA, value), + inputs=[ancestral_eta], + ) + detail_strength.change( + fn=lambda value: on_change_update_setting(consts.AP_DETAIL_STRENGTH, value), + inputs=[detail_strength], + ) + + with gr.Accordion(label="Langevin Euler", open=False): + langevin_strength = gr.Slider( + minimum=0.0, + maximum=0.5, + step=0.01, + value=from_setting_or_default(consts.LANGEVIN_STRENGTH, 0.1), + label="Langevin Strength", + info="Langevin strength for Langevin Euler sampler. Adjust to control the amount of noise.", + ) + langevin_strength.change( + fn=lambda value: on_change_update_setting(consts.LANGEVIN_STRENGTH, value), + inputs=[langevin_strength], + ) + + with gr.Accordion(label="Gradient Estimation", open=False): + use_adaptive_steps = from_setting_or_default(consts.GE_USE_ADAPTIVE_STEPS, False) + + adaptive_steps = gr.Checkbox( + label="Use Adaptive Steps", + value=use_adaptive_steps, + info="Modify the number of steps based on the noise schedule.", + ) + use_timestep_adaptive_gamma = gr.Checkbox( + label="Timestep-Based Adaptive Gamma", + value=from_setting_or_default(consts.GE_USE_TIMESTEP_ADAPTIVE_GAMMA, False), + info="Adjust gamma during generation.", + ) + gamma = gr.Slider( + minimum=consts.GE_MIN_GAMMA, + maximum=consts.GE_MAX_GAMMA, + step=0.05, + value=from_setting_or_default(consts.GE_GAMMA, consts.GE_DEFAULT_GAMMA), + label="Gamma", + info="Gamma value for gradient estimation. Higher values increase the amount of noise.", + interactive=not use_adaptive_steps, + ) + gamma_offset = gr.Slider( + minimum=consts.GE_MIN_GAMMA_OFFSET, + maximum=consts.GE_MAX_GAMMA_OFFSET, + step=0.05, + value=from_setting_or_default(consts.GE_GAMMA_OFFSET, consts.GE_DEFAULT_GAMMA_OFFSET), + label="Gamma Offset", + info="Offset to add to the calculated gamma when using adaptive steps.", + interactive=use_adaptive_steps, + ) + gamma.change(fn=lambda value: on_change_update_setting(consts.GE_GAMMA, value), inputs=[gamma]) + gamma_offset.change( + fn=lambda value: on_change_update_setting(consts.GE_GAMMA_OFFSET, value), inputs=[gamma_offset] + ) + + # Update interactivity when adaptive steps checkbox changes + adaptive_steps.change( + fn=lambda value: (gr.Slider(interactive=not value), gr.Slider(interactive=value)), + inputs=[adaptive_steps], + outputs=[gamma, gamma_offset], + ).then( + fn=lambda value: on_change_update_setting(consts.GE_USE_ADAPTIVE_STEPS, value), + inputs=[adaptive_steps], + ) + + use_timestep_adaptive_gamma.change( + fn=lambda value: on_change_update_setting(consts.GE_USE_TIMESTEP_ADAPTIVE_GAMMA, value), + inputs=[use_timestep_adaptive_gamma], + ) + + validate_schedule = gr.Checkbox( + label="Validate Schedule", + value=from_setting_or_default(consts.GE_VALIDATE_SCHEDULE, False), + info="Validate the noise schedule (For debugging purposes).", + ) + + with gr.Accordion(label="Extended Reverse SDE", open=False): + gr.Markdown("Extended reverse SDE sampler.") + gr.Markdown("Max stage for extended reverse SDE.") + max_stage = gr.Slider( + minimum=1, + maximum=3, + step=1, + value=from_setting_or_default(consts.ER_MAX_STAGE, 3), + label="Max Stage", + ) + max_stage.change(fn=lambda value: on_change_update_setting(consts.MAX_STAGE, value), inputs=[max_stage]) + + return [ + euler_a_end, + dpm_2m_end, + ancestral_eta, + detail_strength, + langevin_strength, + max_stage, + adaptive_steps, + use_timestep_adaptive_gamma, + gamma, + gamma_offset, + validate_schedule, + ] + + def get_values_and_apply(self, p: StableDiffusionProcessing, values: dict): + for key, value in values.items(): + value = self.xyz_cache.pop(key, value) + setattr(p, key, value) + p.extra_generation_params[key] = value + + def process_batch( + self, + p: StableDiffusionProcessing, + euler_a_end: float, + dpm_2m_end: float, + ancestral_eta: float, + detail_strength: float, + langevin_strength: float, + max_stage: int, + use_adaptive_steps: bool, + use_timestep_adaptive_gamma: bool, + gamma: float, + gamma_offset: float, + validate_schedule: bool, + batch_number: int, + prompts: list[str], + seeds: list[int], + subseeds: list[int], + ): + if p.sampler_name == "Adaptive Progressive": + self.get_values_and_apply( + p, + { + consts.AP_EULER_A_END: euler_a_end, + consts.AP_DPM_2M_END: dpm_2m_end, + consts.AP_ANCESTRAL_ETA: ancestral_eta, + consts.AP_DETAIL_STRENGTH: detail_strength, + }, + ) + elif p.sampler_name == "Langevin Euler": + self.get_values_and_apply(p, {consts.LANGEVIN_STRENGTH: langevin_strength}) + elif p.sampler_name == "Gradient Estimation": + self.get_values_and_apply( + p, + { + consts.GE_GAMMA: gamma, + consts.GE_GAMMA_OFFSET: gamma_offset, + consts.GE_USE_ADAPTIVE_STEPS: use_adaptive_steps, + consts.GE_USE_TIMESTEP_ADAPTIVE_GAMMA: use_timestep_adaptive_gamma, + consts.GE_VALIDATE_SCHEDULE: validate_schedule, + }, + ) + elif p.sampler_name == "Extended Reverse SDE": + self.get_values_and_apply(p, {consts.ER_MAX_STAGE: max_stage}) + + +section = ("exs", "Extra Samplers") + + +def on_settings(): + opts.add_option( + consts.AP_EULER_A_END, + OptionInfo( + 0.35, + "Euler A End", + component=gr.Slider, + component_args={"minimum": 0.0, "maximum": 1.0, "step": 0.05}, + section=section, + ), + ) + opts.add_option( + consts.AP_DPM_2M_END, + OptionInfo( + 0.75, + "DPM++ 2M End", + component=gr.Slider, + component_args={"minimum": 0.0, "maximum": 1.0, "step": 0.05}, + section=section, + ), + ) + opts.add_option( + consts.AP_ANCESTRAL_ETA, + OptionInfo( + 0.4, + "Adaptive Progressive Eta", + component=gr.Slider, + component_args={"minimum": 0.0, "maximum": 1.0, "step": 0.01}, + section=section, + ), + ) + opts.add_option( + consts.AP_DETAIL_STRENGTH, + OptionInfo( + 1.5, + "Adaptive Progressive Detail Strength", + component=gr.Slider, + component_args={"minimum": 0.0, "maximum": 3.0, "step": 0.01}, + section=section, + ), + ) + + opts.add_option( + consts.LANGEVIN_STRENGTH, + OptionInfo( + 0.1, + "Langevin Strength", + component=gr.Slider, + component_args={"minimum": 0.0, "maximum": 1.0, "step": 0.01}, + section=section, + ), + ) + + opts.add_option( + consts.ER_MAX_STAGE, + OptionInfo( + 3, + "Extended Reverse Time Max Stage", + component=gr.Slider, + component_args={"minimum": 1, "maximum": 3, "step": 1}, + section=section, + ), + ) + + opts.add_option( + consts.GE_GAMMA, + OptionInfo( + consts.GE_DEFAULT_GAMMA, + "Gradient Estimation Gamma", + component=gr.Slider, + component_args={"minimum": consts.GE_MIN_GAMMA, "maximum": consts.GE_MAX_GAMMA, "step": 0.1}, + section=section, + ), + ) + + opts.add_option( + consts.GE_GAMMA_OFFSET, + OptionInfo( + consts.GE_DEFAULT_GAMMA_OFFSET, + "Gradient Estimation Gamma Offset", + component=gr.Slider, + component_args={"minimum": consts.GE_MIN_GAMMA_OFFSET, "maximum": consts.GE_MAX_GAMMA_OFFSET, "step": 0.1}, + section=section, + ), + ) + + opts.add_option( + consts.GE_USE_ADAPTIVE_STEPS, + OptionInfo( + False, + "Use Adaptive Steps", + component=gr.Checkbox, + section=section, + ), + ) + + opts.add_option( + consts.GE_USE_TIMESTEP_ADAPTIVE_GAMMA, + OptionInfo( + False, + "Use Timestep Adaptive Gamma", + component=gr.Checkbox, + section=section, + ), + ) + + +on_ui_settings(on_settings)