Repository: a2569875/stable-diffusion-webui-composable-lora
Branch: main
Commit: a03d40eb3a3b
Files: 15
Total size: 164.9 KB
Directory structure:
gitextract_xrqbioiw/
├── .github/
│ └── FUNDING.yml
├── .gitignore
├── .vscode/
│ └── settings.json
├── LICENSE
├── README.ja.md
├── README.md
├── README.zh-cn.md
├── README.zh-tw.md
├── composable_lora.py
├── composable_lora_function_handler.py
├── composable_lora_step.py
├── composable_lycoris.py
├── lora_ext.py
├── plot_helper.py
└── scripts/
└── composable_lora_script.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
#github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
#patreon: # Replace with a single Patreon username
#open_collective: # Replace with a single Open Collective username
#ko_fi: # Replace with a single Ko-fi username
#tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
#community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
#liberapay: # Replace with a single Liberapay username
#issuehunt: # Replace with a single IssueHunt username
#otechie: # Replace with a single Otechie username
#lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: ['https://www.buymeacoffee.com/a2569875']
================================================
FILE: .gitignore
================================================
# 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/
pip-wheel-metadata/
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/
# 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
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.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
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__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/
================================================
FILE: .vscode/settings.json
================================================
{
"python.envFile": "${workspaceFolder}/.env",
"python.defaultInterpreterPath": "${workspaceFolder}/../../sd.webui/webui/venv/Scripts/"
}
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (c) 2023 a2569875/Chang Yu-Fan(張宇帆) – a2569875@gmail.com ; and opparco.
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
===================================================================
The Original is MIT License
This program was developed based on the opparco's original version
Copyright (c) 2023 opparco
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.ja.md
================================================
[](https://www.python.org/downloads/)
[](https://github.com/a2569875/stable-diffusion-webui-composable-lora/blob/main/LICENSE)
# Composable LoRA/LyCORIS with steps
この拡張機能は、内部のforward LoRAプロセスを置き換え、同時にLoCon、LyCORISをサポートします。
この拡張機能はComposable LoRAのフォークです。
[](https://www.buymeacoffee.com/a2569875 "buy me a coffee")
[](https://www.youtube.com/watch?v=QS9yjSMySuY "stable-diffusion-webui-composable-lycoris")
### 言語
* [英語](README.md) (グーグル翻訳)
* [台湾中国語](README.zh-tw.md)
* [簡体字中国語](README.zh-cn.md) (ウィキペディア 従来および簡略化された変換システム)
## インストール
注意: このバージョンのComposable LoRAには、元のComposable LoRAのすべての機能が含まれています。1つ選んでインストールするだけです。
この拡張機能は、元のバージョンのComposable LoRA拡張機能と同時に使用できません。インストールする前に、`webui\extensions\`フォルダー内の`stable-diffusion-webui-composable-lora`フォルダーを削除する必要があります。
次に、WebUIの\[Extensions\] -> \[Install from URL\]で以下のURLを入力します。
```
https://github.com/a2569875/stable-diffusion-webui-composable-lora.git
```
インストールして再起動します。
## デモ
ここでは2つのLoRA(1つはLoHA、もう1つはLoCon)を紹介します。
* [`<lora:roukin8_loha:0.8>`](https://civitai.com/models/17336/roukin8-character-lohaloconfullckpt-8) に対応するトリガーワード: `yamanomitsuha`
* `<lora:dia_viekone_locon:0.8>` に対応するトリガーワード: `dia_viekone_\(ansatsu_kizoku\)`
[Latent Couple extension](https://github.com/opparco/stable-diffusion-webui-two-shot)と組み合わせます。
以下はその効果です。

以下のことが分かります。
- `<lora:roukin8_loha:0.8>`を`yamanomitsuha`と組み合わせ、そして`<lora:dia_viekone_locon:0.8>`を`dia_viekone_\(ansatsu_kizoku\)`と組み合わせることで、対応するキャラクターを描画できます。
- モデルのトリガーワードが互いに交換され、一致しなくなった場合、2つのキャラクターは描画できません。これは`<lora:roukin8_loha:0.8>`が画像の左側のブロックにのみ制限されているため、そして`<lora:dia_viekone_locon:0.8>`が画像の右側のブロックにのみ制限されているためです。したがって、このアルゴリズムは有効です。
画像のヒントの文法には[sd-webui-prompt-highlight](https://github.com/a2569875/sd-webui-prompt-highlight)プラグインが使用されています。
このテストは2023年5月14日に行われ、使用されたStable Diffusion WebUIのバージョンは[v1.2 (89f9faa)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/89f9faa63388756314e8a1d96cf86bf5e0663045)です。
(Note: You should enable \[`Lora: use old method that takes longer when you have multiple Loras active and produces same results as kohya-ss/sd-webui-additional-networks extension`\] in setting page.)
2023年7月25日、Stable Diffusion WebUIバージョン[v1.5.0 (a3ddf46)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/a3ddf464a2ed24c999f67ddfef7969f8291567be)を使用して、もう一つのテストが行われました。私自身が訓練したヒヨリのLoConモデルと、私自身が訓練したディア・ヴィコーネのLoConモデルの両方を使用しました。

## 機能
### Composable-Diffusionと互換性がある
LoRAの挿入箇所を`AND`構文と関連付け、LoRAの影響範囲を特定のサブプロンプト内に限定します(特定の`AND...AND`ブロック内)。
### ステップに基づく可組合性
形式`[A:B:N]`のプロンプトにLoRAを配置し、LoRAの影響範囲を特定のグラフィックステップに制限します。

### LoRA重み制御
`[A #xxx]`構文を追加して、LoRAの各グラフィックステップでの重みを制御できます。
現在、サポートされているものは以下のとおりです。
* `decrease`
- LoRAの有効なステップ数で徐々に重みを減少させ、0になります
* `increment`
- LoRAの有効なステップ数で0から重みを徐々に増加させます
* `cmd(...)`
- カスタムの重み制御コマンドで、主にPython構文を使用します。
* 使用可能なパラメータ
+ `weight`
* 現在のLoRA重み
+ `life`
* 0-1の数字で、現在のLoRAのライフサイクルを表します。開始ステップ数にある場合は0であり、このLoRAが最後に適用されるステップ数にある場合は1です。
+ `step`
* 現在のステップ数
+ `steps`
* 全ステップ数
+ `lora`
* 現在のLoRAオブジェクト
+ `lora_module`
* 現在のLoRA作用層オブジェクト
+ `lora_type`
* 現在のLoRAのロードされた種類で、`lora`または`lyco`のいずれかです。
+ `lora_name`
* 現在のLoRAの名前
+ `lora_count`
* すべてのLoRAの数
+ `block_lora_count`
* 作用中の`AND...AND`ブロック内のLoRAの数
+ `is_negative`
* 反転提示語であるかどうか
+ `layer_name`
* 現在の作用層の名前。これを使用して、[LoRA Block Weight](https://github.com/hako-mikan/sd-webui-lora-block-weight)の効果をシミュレートできます。
+ `current_prompt`
* 作用中の`AND...AND`ブロック内のプロンプト
+ `sd_processing`
* sd画像の生成パラメータ
+ `enable_prepare_step`
* (出力用パラメータ) Trueに設定すると、この重みがtransformer text model encoder層に適用されます。 step == -1の場合は、現在transformer text model encoder層にいます。
* 使用可能な関数は以下の通りです
+ `warmup(x)`
* xは0から1までの数値で、総ステップ数に対して、xの比率以下のステップでは関数値が0から1に徐々に上昇し、x以降は1になります。
+ `cooldown(x)`
* xは0から1までの数値で、総ステップ数に対して、xの比率以上のステップでは関数値が1から0に徐々に減少し、0になります。
+ sin, cos, tan, asin, acos, atan
* すべてのステップを周期とする三角関数です。sin、cosの値は0から1に変更されます。
+ sinr, cosr, tanr, asinr, acosr, atanr
* 弧度単位の周期2*piの三角関数です。
+ abs, ceil, floor, trunc, fmod, gcd, lcm, perm, comb, gamma, sqrt, cbrt, exp, pow, log, log2, log10
* Pythonのmath関数ライブラリと同じ関数です。
例 :
* `[<lora:A:1>::10]`
- 名前がAのLoRAを使用して、10ステップで停止します。

* `[<lora:A:1>:<lora:B:1>:10]`
- 名前がAのLoRAを、10ステップまで使用し、10ステップから名前がBのLoRAを使用します。

* `[<lora:A:1>:10]`
- 10ステップから名前がAのLoRAを使用します。
* `[<lora:A:1>:0.5]`
- 50%のステップから名前がAのLoRAを使用します。
* `[[<lora:A:1>::25]:10]`
- 10ステップから名前がAのLoRAを使用し、25ステップで使用を停止します。

* `[<lora:A:1> #increment:10]`
- 名前がAのLoRAを使用する期間中に重みを0から線形に増加させ、設定された重みに到達します。そして、10ステップからこのLoRAを使用します。

* `[<lora:A:1> #decrease:10]`
- 名前がAのLoRAを使用する期間中に重みを1から線形に減少させ、0に到達します。そして、10ステップからこのLoRAを使用します。

* `[<lora:A:1> #cmd\(warmup\(0.5\)\):10]`
- 名前がAのLoRAを使用する期間中、重みはウォームアップ定数であり、0からこのLoRAのライフサイクルの50%に到達するまで線形に増加します。そして、10ステップからこのLoRAを使用します。
- 
* `[<lora:A:1> #cmd\(sin\(life\)\):20]`
- 名前がAのLoRAを使用する期間中、重みは正弦波であり、10ステップからこのLoRAを使用します。

すべての生成された画像:

### 反向トークンに対する影響の消去
内蔵のLoRAを使用する場合、反転トークンは常にLoRAの影響を受けます。これは通常、出力に負の影響を与えます。この拡張機能は、負の影響を排除するオプションを提供します。
## 使用方法
### 有効化 (Enabled)
このオプションをオンにすると、Composable LoRAの機能を使用できるようになります。
### Composable LoRA with step
特定のステップでLoRAを有効または無効にする機能を使用するには、このオプションを選択する必要があります。
### Use Lora in uc text model encoder
言語モデルエンコーダー(text model encoder)の逆提示語部分でLoRAを使用します。
このオプションをオフにすると、より良い出力が期待できます。
### Use Lora in uc diffusion model
拡散モデル(diffusion model)またはデノイザー(denoiser)の逆提示語部分でLoRAを使用します。
このオプションをオフにすると、より良い出力が期待できます。
### plot the LoRA weight in all steps
\[Composable LoRA with step\]が選択されている場合、LoRAの重みが各ステップでどのように変化するかを観察するために、このオプションを選択できます。
## 互換性
`--always-batch-cond-uncond`は`--medvram`または`--lowvram`と一緒に使用する必要があります。
## 更新ログ
### 2023-04-02
* LoCon、LyCORISサポートを追加
* 不具合を修正:IndexError: list index out of range
### 2023-04-08
* 複数の異なるANDブロックで同じLoRAを使用できるようにする

### 2023-04-13
* 2023-04-08のバージョンでpull requestを提出
### 2023-04-19
* pytorch 2.0を使用する場合に拡張がロードされない問題を修正
* 不具合を修正: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda and cpu! (when checking argument for argument mat2 in method wrapper_CUDA_mm)
### 2023-04-20
* 特定のステップでLoRAを有効または無効にする機能を実装
* LoCon、LyCORISの拡張プログラムを参考にし、異なるANDブロックおよびステップでのLoRAの有効化/無効化アルゴリズムを改善
### 2023-04-21
* 異なるステップ数でのLoRAの重みを制御する方法の実装 `[A #xxx]`
* 異なるステップ数でのLoRAの重み変化を示すグラフの作成
### 2023-04-22
* 不具合を修正: AttributeError: 'Options' object has no attribute 'lora_apply_to_outputs'
* 不具合を修正: RuntimeError: "addmm_impl_cpu_" not implemented for 'Half'
## 特別な感謝
* [opparco: Composable LoRAの元の作者である](https://github.com/opparco)、[Composable LoRA](https://github.com/opparco/stable-diffusion-webui-composable-lora)
* [JackEllieのStable-Siffusionコミュニティチーム](https://discord.gg/TM5d89YNwA) 、 [YouTubeチャンネル](https://www.youtube.com/@JackEllie)
* [中文ウィキペディアのコミュニティチーム](https://discord.gg/77n7vnu)
<p align="center"><img src="https://count.getloli.com/get/@a2569875-stable-diffusion-webui-composable-lora.github" alt="a2569875/stable-diffusion-webui-composable-lora"></p>
================================================
FILE: README.md
================================================
[](https://www.python.org/downloads/)
[](https://github.com/a2569875/stable-diffusion-webui-composable-lora/blob/main/LICENSE)
# Composable LoRA/LyCORIS with steps
This extension replaces the built-in LoRA forward procedure and provides support for LoCon and LyCORIS.
This extension is forked from the Composable LoRA extension.
[](https://www.buymeacoffee.com/a2569875 "buy me a coffee")
[](https://www.youtube.com/watch?v=QS9yjSMySuY "stable-diffusion-webui-composable-lycoris")
### Language
* [繁體中文](README.zh-tw.md)
* [简体中文](README.zh-cn.md) (Wikipedia zh converter)
* [日本語](README.ja.md) (ChatGPT)
## Installation
Note: This version of Composable LoRA already includes all the features of the original version of Composable LoRA. You only need to select one to install.
This extension cannot be used simultaneously with the original version of the Composable LoRA extension. Before installation, you must first delete the `stable-diffusion-webui-composable-lora` folder of the original version of the Composable LoRA extension in the `webui\extensions\` directory.
Next, go to \[Extension\] -> \[Install from URL\] in the webui and enter the following URL:
```
https://github.com/a2569875/stable-diffusion-webui-composable-lora.git
```
Install and restart to complete the process.
## Demo
Here we demonstrate two LoRAs (one LoHA and one LoCon), where
* [`<lora:roukin8_loha:0.8>`](https://civitai.com/models/17336/roukin8-character-lohaloconfullckpt-8) corresponds to the trigger word `yamanomitsuha`
* `<lora:dia_viekone_locon:0.8>` corresponds to the trigger word `dia_viekone_\(ansatsu_kizoku\)`
We use the [Latent Couple extension](https://github.com/opparco/stable-diffusion-webui-two-shot) for generating the images.
The results are shown below:

It can be observed that:
- The combination of `<lora:roukin8_loha:0.8>` with `yamanomitsuha`, and `<lora:dia_viekone_locon:0.8>` with `dia_viekone_\(ansatsu_kizoku\)` can successfully generate the corresponding characters.
- When the trigger words are swapped, causing a mismatch, both characters cannot be generated successfully. This demonstrates that `<lora:roukin8_loha:0.8>` is restricted to the left half of the image, while `<lora:dia_viekone_locon:0.8>` is restricted to the right half of the image. Therefore, the algorithm is effective.
The highlighting of the prompt words on the image is done using the [sd-webui-prompt-highlight](https://github.com/a2569875/sd-webui-prompt-highlight) plugin.
This test was conducted on May 14, 2023, using Stable Diffusion WebUI version [v1.2 (89f9faa)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/89f9faa63388756314e8a1d96cf86bf5e0663045).
Another test was conducted on July 25, 2023, using Stable Diffusion WebUI version [v1.5.0 (a3ddf46)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/a3ddf464a2ed24c999f67ddfef7969f8291567be). Using hiyori \(princess_connect!\) and dia viekone locon model that I trained myself.

## Features
### Compatible with Composable-Diffusion
By associating LoRA's insertion position in the prompt with `AND` syntax, LoRA's scope of influence is limited to a specific subprompt.
### Composable with step
By placing LoRA within a prompt in the form of `[A:B:N]`, the scope of LoRA's effect is limited to specific drawing steps.

### LoRA weight controller
Added a syntax `[A #xxx]` to control the weight of LoRA at each drawing step.
You can replace the `#` symbol with `\u0023`, if `#` didn't work.
Currently supported options are:
* `decrease`
- Gradually decrease weight within the effective steps of LoRA until 0.
* `increment`
- Gradually increase weight from 0 within the effective steps of LoRA.
* `cmd(...)`
- A customizable weight control command, mainly using Python syntax.
* Available parameters
+ `weight`
* The current weight of LoRA.
+ `life`
* A number between 0-1, indicating the current life cycle of LoRA. It is 0 when it is at the starting step and 1 when it is at the final step of this LoRA's effect.
+ `step`
* The current step number.
+ `steps`
* The total number of steps.
+ `lora`
* The current LoRA object.
+ `lora_module`
* The current LoRA working layer object.
+ `lora_type`
* The type of LoRA being loaded, which may be `lora` or `lyco`.
+ `lora_name`
* The name of the current LoRA.
+ `lora_count`
* The number of all LoRAs.
+ `block_lora_count`
* The number of LoRAs in the `AND...AND` block currently being used.
+ `is_negative`
* Whether it is a negative prompt.
+ `layer_name`
* The name of the current working layer. You can use this to determine and simulate the effect of [LoRA Block Weight](https://github.com/hako-mikan/sd-webui-lora-block-weight).
+ `current_prompt`
* The prompt currently being used in the `AND...AND` block.
+ `sd_processing`
* Parameters for generating the SD image.
+ `enable_prepare_step`
* (Output parameter) If set to True, it means that this weight will be applied to the transformer text model encoder layer. If step == -1, it means that the current layer is in the transformer text model encoder layer.
* Available functions
+ `warmup(x)`
* x is a number between 0-1, representing a warmup constant. Calculated based on the total number of steps, the function value gradually increases from 0 to 1 until x is reached.
+ `cooldown(x)`
* x is a number between 0-1, representing a cooldown constant. Calculated based on the total number of steps, the function value gradually decreases from 1 to 0 after x.
+ sin, cos, tan, asin, acos, atan
* Trigonometric functions with all steps as the period. The values of sin and cos are expected to be between 0 and 1.
+ sinr, cosr, tanr, asinr, acosr, atanr
* Trigonometric functions in radians, with a period of 2π.
+ abs, ceil, floor, trunc, fmod, gcd, lcm, perm, comb, gamma, sqrt, cbrt, exp, pow, log, log2, log10
* Functions in the math library of Python.
Example :
* `[<lora:A:1>::10]`
- Use LoRA named A until step 10.

* `[<lora:A:1>:<lora:B:1>:10]`
- Use LoRA named A until step 10, then switch to LoRA named B.

* `[<lora:A:1>:10]`
- Start using LoRA named A from step 10.
* `[<lora:A:1>:0.5]`
- Start using LoRA named A from 50% of the steps.
* `[[<lora:A:1>::25]:10]`
- Start using LoRA named A from step 10 until step 25.

* `[<lora:A:1> #increment:10]`
- During the usage of LoRA named A, increment the weight linearly from 0 to the specified weight, starting from step 10.

* `[<lora:A:1> #decrease:10]`
- During the usage of LoRA named A, decrease the weight linearly from 1 to 0, starting from step 10.

* `[<lora:A:1> #cmd\(warmup\(0.5\)\):10]`
- During the usage of LoRA named A, set the weight to the warm-up constant and increase it linearly from 0 to the specified weight until 50% of the LoRA lifecycle is reached, starting from step 10.
- 
* `[<lora:A:1> #cmd\(sin\(life\)\):10]`
- During the usage of LoRA named A, set the weight to a sine wave, starting from step 10.

```python
[<lora:A:1> #cmd\(
def my_func\(\)\:
return sin\(life\)
my_func\(\)
\):10]
```
- same as `[<lora:A:1> #cmd\(sin\(life\)\):10]`, but using function syntax.
All the image:

* Note :
- Try `[<lora:A:1> \u0023cmd\(sin\(life\)\):10]` if `[<lora:A:1> #cmd\(sin\(life\)\):10]` doesn't work.
- Try `[<lora:A:1> \u0023increment:10]` if `[<lora:A:1> #increment:10]` doesn't work.
### Eliminate the impact on negative prompts
With the built-in LoRA, negative prompts are always affected by LoRA. This often has a negative impact on the output.
So this extension offers options to eliminate the negative effects.
## How to use
### Enabled
When checked, Composable LoRA is enabled.
### Composable LoRA with step
Check this option to enable the feature of turning on or off LoRAs at specific steps.
### Use Lora in uc text model encoder
Enable LoRA for uncondition (negative prompt) text model encoder.
With this disabled, you can expect better output.
### Use Lora in uc diffusion model
Enable LoRA for uncondition (negative prompt) diffusion model (denoiser).
With this disabled, you can expect better output.
### plot the LoRA weight in all steps
If "Composable LoRA with step" is enabled, you can select this option to generate a chart that shows the relationship between LoRA weight and the number of steps after the drawing is completed. This allows you to observe the variation of LoRA weight at each step.
### Other
* If the image you generated becomes like this:

try the following steps to solve it:
1. Disable Composable LoRA first
2. Temporarily remove all LoRA from your prompt
3. Randomly generate a image
4. If the image of the habitat is normal, enable Composable LoRA again
5. Add the LoRA you just removed back to the prompt
6. It should be able to generate pictures normally
## Compatibilities
`--always-batch-cond-uncond` must be enabled with `--medvram` or `--lowvram`
## Changelog
### 2023-04-02
* Added support for LoCon and LyCORIS
* Fixed error: IndexError: list index out of range
### 2023-04-08
* Allow using the same LoRA in multiple AND blocks

### 2023-04-13
* Submitted pull request for the 2023-04-08 version
### 2023-04-19
* Fixed loading extension failure issue when using pytorch 2.0
* Fixed error: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda and cpu! (when checking argument for argument mat2 in method wrapper_CUDA_mm)
### 2023-04-20
* Implemented the function of enabling or disabling LoRA at specific steps
* Improved the algorithm for enabling or disabling LoRA in different AND blocks and steps, by referring to the code of LoCon and LyCORIS extensions
### 2023-04-21
* Implemented the method to control different weights of LoRA at different steps (`[A #xxx]`)
* Plotted a chart of LoRA weight changes at different steps
### 2023-04-22
* Fixed error: AttributeError: 'Options' object has no attribute 'lora_apply_to_outputs'
* Fixed error: RuntimeError: "addmm_impl_cpu_" not implemented for 'Half'
### 2023-04-23
* Fixed the problem that sometimes LoRA cannot be removed after being added
### 2023-04-25
* Add support for `<lyco:MODEL>` syntax.
## Acknowledgements
* [opparco, Composable LoRA original author](https://github.com/opparco)、[Composable LoRA](https://github.com/opparco/stable-diffusion-webui-composable-lora)
* [JackEllie's Stable-Siffusion community team](https://discord.gg/TM5d89YNwA) 、 [Youtube channel](https://www.youtube.com/@JackEllie)
* [Chinese Wikipedia community team](https://discord.gg/77n7vnu)
<p align="center"><img src="https://count.getloli.com/get/@a2569875-stable-diffusion-webui-composable-lora.github" alt="a2569875/stable-diffusion-webui-composable-lora"></p>
================================================
FILE: README.zh-cn.md
================================================
[](https://www.python.org/downloads/)
[](https://github.com/a2569875/stable-diffusion-webui-composable-lora/blob/main/LICENSE)
# Composable LoRA/LyCORIS with steps
这个扩展取代了内置的 forward LoRA 过程,同时提供对LoCon、LyCORIS的支持。
本扩展Fork自Composable LoRA扩展
[](https://www.buymeacoffee.com/a2569875 "buy me a coffee")
[](https://www.youtube.com/watch?v=QS9yjSMySuY "stable-diffusion-webui-composable-lycoris")
### 语言
* [繁体中文](README.zh-tw.md)
* [英语](README.md) (google translate)
* [日语](README.ja.md) (ChatGPT)
## 安装
注意 : 这个版本的Composable LoRA已经包含了原版Composable LoRA的所有功能,只要选一个安装就好。
此扩展不能与原始版本的Composable LoRA扩展同时使用,安装前必须先删除原始版本的Composable LoRA扩展。请先到`webui\extensions\`文件夹下删除`stable-diffusion-webui-composable-lora`文件夹
接下来到webui的\[扩展\] -> \[从网址安装\]输入以下网址:
```
https://github.com/a2569875/stable-diffusion-webui-composable-lora.git
```
安装并重启即可
## 演示
这里示范两个LoRA (分别为LoHA和LoCon) ,其中
* [`<lora:roukin8_loha:0.8>`](https://civitai.com/models/17336/roukin8-character-lohaloconfullckpt-8) 对应的触发词: `yamanomitsuha`
* `<lora:dia_viekone_locon:0.8>` 对应的触发词: `dia_viekone_\(ansatsu_kizoku\)`
并搭配[Latent Couple extension](https://github.com/opparco/stable-diffusion-webui-two-shot)
效果如下:

可以看到:
- 当我`<lora:roukin8_loha:0.8>`搭配`yamanomitsuha`,以及`<lora:dia_viekone_locon:0.8>`搭配`dia_viekone_\(ansatsu_kizoku\)`的组合可以顺利画出对应角色;
- 当模型触发词互相交换而导致不匹配时,两个角色都无法顺利画出,可见`<lora:roukin8_loha:0.8>`被限制在只作用于图片的左半边区块、而`<lora:dia_viekone_locon:0.8>`被限制在只作用于图片的右半边区块,因此这个算法是有效的。
图片上的提示词语法使用[sd-webui-prompt-highlight](https://github.com/a2569875/sd-webui-prompt-highlight)插件進行上色。
本次测试于2023年5月14日完成,使用Stable Diffusion WebUI版本为[v1.2 (89f9faa)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/89f9faa63388756314e8a1d96cf86bf5e0663045)
(Note: You should enable \[`Lora: use old method that takes longer when you have multiple Loras active and produces same results as kohya-ss/sd-webui-additional-networks extension`\] in setting page.)
另一次测试于2023年7月25日完成,使用Stable Diffusion WebUI版本为[v1.5.0 (a3ddf46)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/a3ddf464a2ed24c999f67ddfef7969f8291567be)。 测试中使用了自行训练的春咲日和莉和蒂雅·维科尼LoCon模型模型。

## 功能
### 与 Composable-Diffusion 兼容
将 LoRA 在提示词中的插入位置与`AND`语法相关系,让 LoRA 的影响范围限制在特定的子提示词中 (特定 AND...AND区块中)。
### 在步骤数上的 Composable
使 LoRA 支持放置在形如`[A:B:N]`的提示词语法中,让 LoRA 的影响范围限制在特定的绘图步骤上。

### LoRA 权重控制
添加了一个语法`[A #xxx]`可以用来控制LoRA在每个绘图步骤的权重
如果 `#` 不起作用,您可以将 `#` 符号替换为 `\u0023`。
目前支持的有:
* `decrease`
- 在LoRA的有效步骤数内逐渐递减权重直到0
* `increment`
- 在LoRA的有效步骤数内从0开始逐渐递增权重
* `cmd(...)`
- 自定义的权重控制指令,主要以python语法为主
* 可用参数
+ `weight`
* 当前的LoRA权重
+ `life`
* 0-1之间的数字,表示目前LoRA的生命周期。位于起始步骤数时为0,位于此LoRA最终作用的步骤数时为1
+ `step`
* 目前的步骤数
+ `steps`
* 总共的步骤数
+ `lora`
* 目前的LoRA物件
+ `lora_module`
* 目前的LoRA作用层物件
+ `lora_type`
* 目前的LoRA载入的种类,可能是`lora`或`lyco`
+ `lora_name`
* 目前的LoRA名称
+ `lora_count`
* 所有LoRA的数量
+ `block_lora_count`
* 作用中的`AND...AND`区块内LoRA的数量
+ `is_negative`
* 是否为反向提示词
+ `layer_name`
* 目前作用层名称。你可以用这来来判断并模拟[LoRA Block Weight](https://github.com/hako-mikan/sd-webui-lora-block-weight)的效果
+ `current_prompt`
* 作用中的`AND...AND`区块内的提示词
+ `sd_processing`
* sd图片生成的参数
+ `enable_prepare_step`
* (输出用参数) 如果设为True,则代表此权重会做用到transformer text model encoder层。如过step==-1代表目前在transformer text model encoder层。
* 可用函数
+ `warmup(x)`
* x为0-1之间的数字,表示一个预热的常数,以总步数计算,在低于x比例的步数时,函数值从0逐渐递增,直到x之后为1
+ `cooldown(x)`
* x为0-1之间的数字,表示一个冷却的常数,以总步数计算,在高于x比例的步数时,函数值从1逐渐递减,直到0
+ sin, cos, tan, asin, acos, atan
* 以所有步数为周期的三角函数。其中sin, cos的值预被改成0到1之间
+ sinr, cosr, tanr, asinr, acosr, atanr
* 以弧度为单位的三角函数,周期 2*pi。
+ abs, ceil, floor, trunc, fmod, gcd, lcm, perm, comb, gamma, sqrt, cbrt, exp, pow, log, log2, log10
* 同python的math函数库中的函数
示例 :
* `[<lora:A:1>::10]`
- 使用名为A的LoRA到第10步停止

* `[<lora:A:1>:<lora:B:1>:10]`
- 使用名为A的LoRA到第10步为止,从第10步开始换用名为B的LoRA

* `[<lora:A:1>:10]`
- 从第10步才开始使用名为A的LoRA
* `[<lora:A:1>:0.5]`
- 从50%的步数才开始使用名为A的LoRA
* `[[<lora:A:1>::25]:10]`
- 从第10步才开始使用名为A的LoRA,并且到第25步停止使用

* `[<lora:A:1> #increment:10]`
- 在名为A的LoRA使用期间,权重从0开始线性递增直到设置的权重,且从第10步才开始使用此LoRA

* `[<lora:A:1> #decrease:10]`
- 在名为A的LoRA使用期间,权重从1开始线性递减直到0,且从第10步才开始使用此LoRA

* `[<lora:A:1> #cmd\(warmup\(0.5\)\):10]`
- 在名为A的LoRA使用期间,权重为预热的常数,从0开始递增直到50%的此LoRA生命周期达到设置的权重,且从第10步才开始使用此LoRA
- 
* `[<lora:A:1> #cmd\(sin\(life\)\):20]`
- 在名为A的LoRA使用期间,权重为正弦波,且从第10步才开始使用此LoRA

```python
[<lora:A:1> #cmd\(
def my_func\(\)\:
return sin\(life\)
my_func\(\)
\):10]
```
- 与`[<lora:A:1> #cmd\(sin\(life\)\):10]`相同,但用了函数语法
所有生成的图像 :

* 提示 :
- 如果`[<lora:A:1> #cmd\(sin\(life\)\):10]`无效的话,试试`[<lora:A:1> \u0023cmd\(sin\(life\)\):10]`。
- 如果`[<lora:A:1> #increment:10]`无效的话,试试`[<lora:A:1> \u0023increment:10]`
### 消除对反向提示词的影响
使用内置的 LoRA 时,反向提示词总是受到 LoRA 的影响。 这通常会对输出产生负面影响。
而此扩展程序提供了消除负面影响的选项。
## 使用方法
### 激活 (Enabled)
勾选此选项之后才能使用Composable LoRA的功能。
### Composable LoRA with step
勾选此选项之后才能使用在特定步数上激活或不激活LoRA的功能。
### 在反向提示词的语言模型编码器上使用LoRA (Use Lora in uc text model encoder)
在语言模型编码器(text model encoder)的反向提示词部分使用LoRA。
关闭此选项后,您可以期待更好的输出。
### 在反向提示词的扩散模型上上使用LoRA (Use Lora in uc diffusion model)
在扩散模型(diffusion model)或称降噪器(denoiser)的反向提示词部分使用LoRA。
关闭此选项后,您可以期待更好的输出。
### 绘制LoRA权重与步数关系的图表 (plot the LoRA weight in all steps)
如果有勾选\[Composable LoRA with step\],可以勾选此选项来观察LoRA权重在每个步骤数上的变化
### 其他
* 如果你产生的图片崩成这样:

可尝试以下步骤解决:
1. 先关闭Composable LoRA
2. 从你的提示词中暂时移除所有LoRA
3. 随便生成一张图片
4. 如果产生的图片是正常的,再次开启Composable LoRA
5. 再把刚才移除的LoRA加回去提示词中 (注意,要先开启Composable LoRA再加入LoRA语法)
6. 应该就能正常产生图片了
## 兼容性
`--always-batch-cond-uncond`必须与`--medvram`或`--lowvram`一起使用
## 更新日志
### 2023-04-02
* 新增LoCon、LyCORIS支持
* 修正: IndexError: list index out of range
### 2023-04-08
* 允许在多个不同AND区块使用同一个LoRA

### 2023-04-13
* 2023-04-08的版本提交pull request
### 2023-04-19
* 修正使用 pytorch 2.0 时,扩展加载失败的问题
* 修正: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda and cpu! (when checking argument for argument mat2 in method wrapper_CUDA_mm)
### 2023-04-20
* 实现控制LoRA在指定步数激活与不激活的功能
* 参考LoCon、LyCORIS扩展的代码,改善LoRA在不同AND区块与步数激活与不激活的算法
### 2023-04-21
* 实现控制LoRA在不同步骤数能有不同权重的方法`[A #xxx]`
* 绘制LoRA权重在不同步骤数之变化的图表
### 2023-04-22
* 修正: AttributeError: 'Options' object has no attribute 'lora_apply_to_outputs'
* 修正: RuntimeError: "addmm_impl_cpu_" not implemented for 'Half'
### 2023-04-23
* 修正有时候LoRA加上去后会无法移除的问题 (症状 : 崩图。)
### 2023-04-25
* 加入对`<lyco:MODEL>`语法的支持。
## 铭谢
* [Composable LoRA原始作者opparco](https://github.com/opparco)、[Composable LoRA](https://github.com/opparco/stable-diffusion-webui-composable-lora)
* [JackEllie的Stable-Siffusion的社群团队](https://discord.gg/TM5d89YNwA) 、 [Youtube频道](https://www.youtube.com/@JackEllie)
* [中文维基百科的社群团队](https://discord.gg/77n7vnu)
<p align="center"><img src="https://count.getloli.com/get/@a2569875-stable-diffusion-webui-composable-lora.github" alt="a2569875/stable-diffusion-webui-composable-lora"></p>
================================================
FILE: README.zh-tw.md
================================================
[](https://www.python.org/downloads/)
[](https://github.com/a2569875/stable-diffusion-webui-composable-lora/blob/main/LICENSE)
# Composable LoRA/LyCORIS with steps
這個擴展取代了內置的 forward LoRA 過程,同時提供對LoCon、LyCORIS的支援。
本擴展Fork自Composable LoRA擴展
[](https://www.buymeacoffee.com/a2569875 "buy me a coffee")
[](https://www.youtube.com/watch?v=QS9yjSMySuY "stable-diffusion-webui-composable-lycoris")
### 語言
* [英文](README.md) (google翻譯)
* [简体中文](README.zh-cn.md) (維基百科繁簡轉換系統)
* [日文](README.ja.md) (ChatGPT翻譯)
## 安裝
注意 : 這個版本的Composable LoRA已經包含了原版Composable LoRA的所有功能,只要選一個安裝就好。
此擴展不能與原始版本的Composable LoRA擴展同時使用,安裝前必須先刪除原始版本的Composable LoRA擴展。請先到`webui\extensions\`資料夾下刪除`stable-diffusion-webui-composable-lora`資料夾
接下來到webui的\[擴充功能\] -> \[從網址安裝\]輸入以下網址:
```
https://github.com/a2569875/stable-diffusion-webui-composable-lora.git
```
安裝並重新啟動即可
## 演示
這裡示範兩個LoRA (分別為LoHA和LoCon),其中
* [`<lora:roukin8_loha:0.8>`](https://civitai.com/models/17336/roukin8-character-lohaloconfullckpt-8) 對應的觸發詞: `yamanomitsuha`
* `<lora:dia_viekone_locon:0.8>` 對應的觸發詞: `dia_viekone_\(ansatsu_kizoku\)`
並搭配[Latent Couple extension](https://github.com/opparco/stable-diffusion-webui-two-shot)
效果如下:

可以看到:
- 當我`<lora:roukin8_loha:0.8>`搭配`yamanomitsuha`,以及`<lora:dia_viekone_locon:0.8>`搭配`dia_viekone_\(ansatsu_kizoku\)`的組合可以順利畫出對應角色;
- 當模型觸發詞互相交換而導致不匹配時,兩個角色都無法順利畫出,可見`<lora:roukin8_loha:0.8>`被限制在只作用於圖片的左半邊區塊、而`<lora:dia_viekone_locon:0.8>`被限制在只作用於圖片的右半邊區塊,因此這個演算法是有效的。
圖片上的提示詞語法使用[sd-webui-prompt-highlight](https://github.com/a2569875/sd-webui-prompt-highlight)插件進行上色。
本次測試於2023年5月14日完成,使用Stable Diffusion WebUI版本為[v1.2 (89f9faa)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/89f9faa63388756314e8a1d96cf86bf5e0663045)
另一次測試於2023年7月25日完成,使用Stable Diffusion WebUI版本為[v1.5.0 (a3ddf46)](https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/a3ddf464a2ed24c999f67ddfef7969f8291567be)。 測試中使用了自行訓練的《世界頂尖的暗殺者轉生為異世界貴族》蒂雅·維科尼和《公主連結》日和LoCon模型。

## 功能
### 與 Composable-Diffusion 相容
將 LoRA 在提示詞中的插入位置與`AND`語法相關聯,讓 LoRA 的影響範圍限制在特定的子提示詞中 (特定 AND...AND區塊中)。
### 在步驟數上的 Composable
使 LoRA 支援放置在形如`[A:B:N]`的提示詞語法中,讓 LoRA 的影響範圍限制在特定的繪圖步驟上。

### LoRA 權重控制
添加了一個語法`[A #xxx]`可以用來控制LoRA在每個繪圖步驟的權重
如果 `#` 不起作用,您可以將 `#` 符號替換為 `\u0023`。
目前支援的有:
* `decrease`
- 在LoRA的有效步驟數內逐漸遞減權重直到0
* `increment`
- 在LoRA的有效步驟數內從0開始逐漸遞增權重
* `cmd(...)`
- 自定義的權重控制指令,主要以python語法為主
* 可用參數
+ `weight`
* 當前的LoRA權重
+ `life`
* 0-1之間的數字,表示目前LoRA的生命週期。位於起始步驟數時為0,位於此LoRA最終作用的步驟數時為1
+ `step`
* 目前的步驟數
+ `steps`
* 總共的步驟數
+ `lora`
* 目前的LoRA物件
+ `lora_module`
* 目前的LoRA作用層物件
+ `lora_type`
* 目前的LoRA載入的種類,可能是`lora`或`lyco`
+ `lora_name`
* 目前的LoRA名稱
+ `lora_count`
* 所有LoRA的數量
+ `block_lora_count`
* 作用中的`AND...AND`區塊內LoRA的數量
+ `is_negative`
* 是否為反向提示詞
+ `layer_name`
* 目前作用層名稱。你可以用這來來判斷並模擬[LoRA Block Weight](https://github.com/hako-mikan/sd-webui-lora-block-weight)的效果
+ `current_prompt`
* 作用中的`AND...AND`區塊內的提示詞
+ `sd_processing`
* sd圖片生成的參數
+ `enable_prepare_step`
* (輸出用參數) 如果設為True,則代表此權重會做用到transformer text model encoder層。如過step==-1代表目前在transformer text model encoder層。
* 可用函數
+ `warmup(x)`
* x為0-1之間的數字,表示一個預熱的常數,以總步數計算,在低於x比例的步數時,函數值從0逐漸遞增,直到x之後為1
+ `cooldown(x)`
* x為0-1之間的數字,表示一個冷卻的常數,以總步數計算,在高於x比例的步數時,函數值從1逐漸遞減,直到0
+ sin, cos, tan, asin, acos, atan
* 以所有步數為週期的三角函數。其中sin, cos的值預被改成0到1之間
+ sinr, cosr, tanr, asinr, acosr, atanr
* 以弧度為單位的三角函數,週期 2*pi。
+ abs, ceil, floor, trunc, fmod, gcd, lcm, perm, comb, gamma, sqrt, cbrt, exp, pow, log, log2, log10
* 同python的math函數庫中的函數
範例 :
* `[<lora:A:1>::10]`
- 使用名為A的LoRA到第10步停止

* `[<lora:A:1>:<lora:B:1>:10]`
- 使用名為A的LoRA到第10步為止,從第10步開始換用名為B的LoRA

* `[<lora:A:1>:10]`
- 從第10步才開始使用名為A的LoRA
* `[<lora:A:1>:0.5]`
- 從50%的步數才開始使用名為A的LoRA
* `[[<lora:A:1>::25]:10]`
- 從第10步才開始使用名為A的LoRA,並且到第25步停止使用

* `[<lora:A:1> #increment:10]`
- 在名為A的LoRA使用期間,權重從0開始線性遞增直到設定的權重,且從第10步才開始使用此LoRA

* `[<lora:A:1> #decrease:10]`
- 在名為A的LoRA使用期間,權重從1開始線性遞減直到0,且從第10步才開始使用此LoRA

* `[<lora:A:1> #cmd\(warmup\(0.5\)\):10]`
- 在名為A的LoRA使用期間,權重為預熱的常數,從0開始遞增直到50%的此LoRA生命週期達到設定的權重,且從第10步才開始使用此LoRA
- 
* `[<lora:A:1> #cmd\(sin\(life\)\):20]`
- 在名為A的LoRA使用期間,權重為正弦波,且從第10步才開始使用此LoRA

```python
[<lora:A:1> #cmd\(
def my_func\(\)\:
return sin\(life\)
my_func\(\)
\):10]
```
- 與`[<lora:A:1> #cmd\(sin\(life\)\):10]`相同,但用了函數語法
所有生成的圖像 :

* 提示 :
- 如果`[<lora:A:1> #cmd\(sin\(life\)\):10]`沒有作用的話,試試`[<lora:A:1> \u0023cmd\(sin\(life\)\):10]`。
- 如果`[<lora:A:1> #increment:10]`沒有作用的話,試試`[<lora:A:1> \u0023increment:10]` 。
### 消除對反向提示詞的影響
使用內建的 LoRA 時,反向提示詞總是受到 LoRA 的影響。 這通常會對輸出產生負面影響。
而此擴展程序提供了消除負面影響的選項。
## 使用方法
### 啟用 (Enabled)
勾選此選項之後才能使用Composable LoRA的功能。
### Composable LoRA with step
勾選此選項之後才能使用在特定步數上啟用或不啟用LoRA的功能。
### 在反向提示詞的語言模型編碼器上使用LoRA (Use Lora in uc text model encoder)
在語言模型編碼器(text model encoder)的反向提示詞部分使用LoRA。
關閉此選項後,您可以期待更好的輸出。
### 在反向提示詞的擴散模型上上使用LoRA (Use Lora in uc diffusion model)
在擴散模型(diffusion model)或稱降噪器(denoiser)的反向提示詞部分使用LoRA。
關閉此選項後,您可以期待更好的輸出。
### 繪製LoRA權重與步數關聯的圖表 (plot the LoRA weight in all steps)
如果有勾選\[Composable LoRA with step\],可以勾選此選項來觀察LoRA權重在每個步驟數上的變化
### 其他
* 如果你產生的圖片崩成這樣:

可嘗試以下步驟解決:
1. 先關閉Composable LoRA
2. 從你的提示詞中暫時移除所有LoRA
3. 隨便生成一張圖片
4. 如果產生的圖片是正常的,再次開啟Composable LoRA
5. 再把剛才移除的LoRA加回去提示詞中 (注意,要先開啟Composable LoRA再加入LoRA語法)
6. 應該就能正常產生圖片了
## 相容性
`--always-batch-cond-uncond`必須與`--medvram`或`--lowvram`一起使用
## 更新日誌
### 2023-04-02
* 新增LoCon、LyCORIS支援
* 修正: IndexError: list index out of range
### 2023-04-08
* 允許在多個不同AND區塊使用同一個LoRA

### 2023-04-13
* 2023-04-08的版本提交pull request
### 2023-04-19
* 修正使用 pytorch 2.0 時,擴展載入失敗的問題
* 修正: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda and cpu! (when checking argument for argument mat2 in method wrapper_CUDA_mm)
### 2023-04-20
* 實作控制LoRA在指定步數啟用與不啟用的功能
* 參考LoCon、LyCORIS擴展的程式碼,改善LoRA在不同AND區塊與步數啟用與不啟用的演算法
### 2023-04-21
* 實作控制LoRA在不同步驟數能有不同權重的方法`[A #xxx]`
* 繪製LoRA權重在不同步驟數之變化的圖表
### 2023-04-22
* 修正: AttributeError: 'Options' object has no attribute 'lora_apply_to_outputs'
* 修正: RuntimeError: "addmm_impl_cpu_" not implemented for 'Half'
### 2023-04-23
* 修正有時候LoRA加上去後會無法移除的問題 (症狀 : 崩圖。)
### 2023-04-25
* 加入對`<lyco:MODEL>`語法的支援。
## 銘謝
* [Composable LoRA原始作者opparco](https://github.com/opparco)、[Composable LoRA](https://github.com/opparco/stable-diffusion-webui-composable-lora)
* [JackEllie的Stable-Siffusion的社群團隊](https://discord.gg/TM5d89YNwA) 、 [Youtube頻道](https://www.youtube.com/@JackEllie)
* [中文維基百科的社群團隊](https://discord.gg/77n7vnu)
<p align="center"><img src="https://count.getloli.com/get/@a2569875-stable-diffusion-webui-composable-lora.github" alt="a2569875/stable-diffusion-webui-composable-lora"></p>
================================================
FILE: composable_lora.py
================================================
from typing import List, Dict, Optional, Union
import re
import torch
import composable_lora_step
import composable_lycoris
import plot_helper
import lora_ext
from modules import extra_networks, devices
def lora_forward(compvis_module: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention], input, res):
global text_model_encoder_counter
global diffusion_model_counter
global step_counter
global should_print
global first_log_drawing
global drawing_lora_first_index
import lora
if composable_lycoris.has_webui_lycoris:
import lycoris
if len(lycoris.loaded_lycos) > 0 and not first_log_drawing:
print("Found LyCORIS models, Using Composable LyCORIS.")
if not first_log_drawing:
first_log_drawing = True
if enabled:
print("Composable LoRA load successful.")
if opt_plot_lora_weight:
log_lora()
drawing_lora_first_index = drawing_data[0]
if len(lora_ext.get_loaded_lora()) == 0:
return res
if hasattr(devices, "cond_cast_unet"):
input = devices.cond_cast_unet(input)
lora_layer_name_loading : Optional[str] = getattr(compvis_module, 'lora_layer_name', None)
if lora_layer_name_loading is None:
lora_layer_name_loading = getattr(compvis_module, 'network_layer_name', None)
if lora_layer_name_loading is None:
return res
#let it type is actually a string
lora_layer_name : str = str(lora_layer_name_loading)
del lora_layer_name_loading
lora_loaded_loras = lora_ext.get_loaded_lora()
num_loras = len(lora_loaded_loras)
if composable_lycoris.has_webui_lycoris:
num_loras += len(lycoris.loaded_lycos)
if text_model_encoder_counter == -1:
text_model_encoder_counter = len(prompt_loras) * num_loras
tmp_check_loras = [] #store which lora are already apply
tmp_check_loras.clear()
for m_lora in lora_loaded_loras:
module = m_lora.modules.get(lora_layer_name, None)
if module is None:
#fix the lyCORIS issue
composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)
continue
current_lora = composable_lycoris.normalize_lora_name(m_lora.name)
lora_already_used = False
if current_lora in tmp_check_loras:
lora_already_used = True
#store the applied lora into list
tmp_check_loras.append(current_lora)
if lora_already_used:
composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)
continue
#support for lyCORIS
patch = composable_lycoris.get_lora_patch(module, input, res, lora_layer_name)
alpha = composable_lycoris.get_lora_alpha(module, 1.0)
num_prompts = len(prompt_loras)
# print(f"lora.name={m_lora.name} lora.mul={m_lora.multiplier} alpha={alpha} pat.shape={patch.shape}")
res = apply_composable_lora(lora_layer_name, m_lora, module, "lora", patch, alpha, res, num_loras, num_prompts)
return res
re_AND = re.compile(r"\bAND\b")
def load_prompt_loras(prompt: str):
global is_single_block
global full_controllers
global first_log_drawing
global full_prompt
prompt_loras.clear()
prompt_blocks.clear()
lora_controllers.clear()
drawing_data.clear()
full_controllers.clear()
drawing_lora_names.clear()
cache_layer_list.clear()
#load AND...AND block
subprompts = re_AND.split(prompt)
full_prompt = prompt
tmp_prompt_loras = []
tmp_prompt_blocks = []
for i, subprompt in enumerate(subprompts):
loras = {}
_, extra_network_data = extra_networks.parse_prompt(subprompt)
for m_type in ['lora', 'lyco']:
if m_type in extra_network_data.keys():
for params in extra_network_data[m_type]:
name = params.items[0]
multiplier = float(params.items[1]) if len(params.items) > 1 else 1.0
loras[f"{m_type}:{name}"] = multiplier
tmp_prompt_loras.append(loras)
tmp_prompt_blocks.append(subprompt)
is_single_block = (len(tmp_prompt_loras) == 1)
#load [A:B:N] syntax
if opt_composable_with_step:
print("Loading LoRA step controller...")
tmp_lora_controllers = composable_lora_step.parse_step_rendering_syntax(prompt)
#for batches > 1
prompt_loras.extend(tmp_prompt_loras * num_batches)
lora_controllers.extend(tmp_lora_controllers * num_batches)
prompt_blocks.extend(tmp_prompt_blocks * num_batches)
for controller_it in tmp_lora_controllers:
full_controllers += controller_it
first_log_drawing = False
def reset_counters():
global text_model_encoder_counter
global diffusion_model_counter
global step_counter
global should_print
# reset counter to uc head
text_model_encoder_counter = -1
diffusion_model_counter = 0
step_counter += 1
should_print = True
def reset_step_counters():
global step_counter
global should_print
should_print = True
step_counter = 0
def add_step_counters():
global step_counter
global should_print
should_print = True
step_counter += 1
reset_flag = False
if step_counter == num_steps + 1:
if not opt_hires_step_as_global:
step_counter = 0
reset_flag = True
elif step_counter > num_steps + num_hires_steps:
step_counter = 0
reset_flag = True
if not reset_flag:
if opt_plot_lora_weight:
log_lora()
def log_lora():
import lora
loaded_loras = lora_ext.get_loaded_lora()
loaded_lycos = []
if composable_lycoris.has_webui_lycoris:
import lycoris
loaded_lycos = lycoris.loaded_lycos
tmp_data : List[float] = []
if len(loaded_loras) + len(loaded_lycos) <= 0:
tmp_data = [0.0]
if len(drawing_lora_names) <= 0:
drawing_lora_names.append("LoRA Model Not Found.")
for m_type in [("lora", loaded_loras), ("lyco", loaded_lycos)]:
for m_lora in m_type[1]:
m_lora_name = composable_lycoris.normalize_lora_name(m_lora.name)
custom_scope = {}
if opt_composable_with_step:
custom_scope = {
"is_negative": False,
"lora": m_lora,
"lora_module": None,
"lora_type": m_type[0],
"lora_name": m_lora_name,
"lora_count": len(loaded_loras) + len(loaded_lycos),
"block_lora_count": len(loaded_loras) + len(loaded_lycos),
"layer_name": "ploting",
"current_prompt": full_prompt,
"sd_processing": sd_processing
}
current_lora = f"{m_type[0]}:{m_lora_name}"
multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, "lora_layer_name")
if opt_composable_with_step:
multiplier = composable_lora_step.check_lora_weight(full_controllers, current_lora, step_counter, num_steps, custom_scope)
index = -1
if current_lora in drawing_lora_names:
index = drawing_lora_names.index(current_lora)
else:
index = len(drawing_lora_names)
drawing_lora_names.append(current_lora)
if index >= len(tmp_data):
for i in range(len(tmp_data), index):
tmp_data.append(0.0)
tmp_data.append(multiplier)
else:
tmp_data[index] = multiplier
drawing_data.append(tmp_data)
def plot_lora():
"""Plot the LoRA weight chart"""
max_size = -1
if len(drawing_data) < num_steps:
item = drawing_data[len(drawing_data) - 1] if len(drawing_data) > 0 else [0.0]
drawing_data.extend([item]*(num_steps - len(drawing_data)))
drawing_data.insert(0, drawing_lora_first_index)
for datalist in drawing_data:
datalist_len = len(datalist)
if datalist_len > max_size:
max_size = datalist_len
for i, datalist in enumerate(drawing_data):
datalist_len = len(datalist)
if datalist_len < max_size:
drawing_data[i].extend([0.0]*(max_size - datalist_len))
return plot_helper.plot_lora_weight(drawing_data, drawing_lora_names)
def lora_backup_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention]):
lora_layer_name = getattr(self, 'lora_layer_name', None)
if lora_layer_name is None:
return
import lora
weights_backup = getattr(self, "composable_lora_weights_backup", None)
if weights_backup is None:
if isinstance(self, torch.nn.MultiheadAttention):
weights_backup = (self.in_proj_weight.to(devices.cpu, copy=True), self.out_proj.weight.to(devices.cpu, copy=True))
else:
weights_backup = self.weight.to(devices.cpu, copy=True)
self.composable_lora_weights_backup = weights_backup
self.lora_weights_backup = weights_backup
def clear_cache_lora(compvis_module : Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention], force_clear : bool):
lora_layer_name = getattr(compvis_module, 'lora_layer_name', 'unknown layer')
if lora_layer_name in cache_layer_list:
return
cache_layer_list.append(lora_layer_name)
lyco_weights_backup = getattr(compvis_module, "lyco_weights_backup", None)
lora_weights_backup = getattr(compvis_module, "lora_weights_backup", None)
composable_lora_weights_backup = getattr(compvis_module, "composable_lora_weights_backup", None)
if enabled or force_clear:
if composable_lora_weights_backup is not None:
if isinstance(compvis_module, torch.nn.MultiheadAttention):
compvis_module.in_proj_weight.copy_(composable_lora_weights_backup[0])
compvis_module.out_proj.weight.copy_(composable_lora_weights_backup[1])
else:
compvis_module.weight.copy_(composable_lora_weights_backup)
else:
if lyco_weights_backup is not None:
if isinstance(compvis_module, torch.nn.MultiheadAttention):
compvis_module.in_proj_weight.copy_(lyco_weights_backup[0])
compvis_module.out_proj.weight.copy_(lyco_weights_backup[1])
lora_weights_backup = (
lyco_weights_backup[0].to(devices.cpu, copy=True),
lyco_weights_backup[1].to(devices.cpu, copy=True)
)
else:
compvis_module.weight.copy_(lyco_weights_backup)
lora_weights_backup = lyco_weights_backup.to(devices.cpu, copy=True)
setattr(compvis_module, "lora_weights_backup", lora_weights_backup)
elif lora_weights_backup is not None:
if isinstance(compvis_module, torch.nn.MultiheadAttention):
compvis_module.in_proj_weight.copy_(lora_weights_backup[0])
compvis_module.out_proj.weight.copy_(lora_weights_backup[1])
else:
compvis_module.weight.copy_(lora_weights_backup)
setattr(compvis_module, "lora_current_names", ())
setattr(compvis_module, "lyco_current_names", ())
else:
if (composable_lora_weights_backup is not None) and composable_lycoris.has_webui_lycoris:
if isinstance(compvis_module, torch.nn.MultiheadAttention):
compvis_module.in_proj_weight.copy_(composable_lora_weights_backup[0])
compvis_module.out_proj.weight.copy_(composable_lora_weights_backup[1])
else:
compvis_module.weight.copy_(composable_lora_weights_backup)
def apply_composable_lora(lora_layer_name, m_lora, module, m_type: str, patch, alpha, res, num_loras, num_prompts):
global text_model_encoder_counter
global diffusion_model_counter
global step_counter
custom_scope = {}
if opt_composable_with_step:
custom_scope = {
"is_negative": False,
"lora": m_lora,
"lora_module": module,
"lora_type": m_type,
"lora_name": composable_lycoris.normalize_lora_name(m_lora.name),
"lora_count": num_loras,
"block_lora_count": 0,
"layer_name": lora_layer_name,
"current_prompt": "",
"sd_processing": sd_processing
}
m_lora_name = f"{m_type}:{composable_lycoris.normalize_lora_name(m_lora.name)}"
# print(f"lora.name={m_lora.name} lora.mul={m_lora.multiplier} alpha={alpha} pat.shape={patch.shape}")
if enabled:
if lora_layer_name.startswith("transformer_"): # "transformer_text_model_encoder_"
#
if 0 <= text_model_encoder_counter // num_loras < len(prompt_loras):
# c
prompt_block_id = text_model_encoder_counter // num_loras
loras = prompt_loras[prompt_block_id]
multiplier = loras.get(m_lora_name, 0.0)
if opt_composable_with_step:
custom_scope["current_prompt"] = prompt_blocks[prompt_block_id]
custom_scope["block_lora_count"] = len(loras)
lora_controller = lora_controllers[prompt_block_id]
multiplier = composable_lora_step.check_lora_weight(lora_controller, m_lora_name, -1, num_steps, custom_scope)
if multiplier != 0.0:
multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)
# print(f"c #{text_model_encoder_counter // num_loras} lora.name={m_lora_name} mul={multiplier} lora_layer_name={lora_layer_name}")
res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)
else:
# uc
multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)
if (opt_uc_text_model_encoder or (is_single_block and (not opt_single_no_uc))) and multiplier != 0.0:
# print(f"uc #{text_model_encoder_counter // num_loras} lora.name={m_lora_name} lora.mul={multiplier} lora_layer_name={lora_layer_name}")
custom_scope["current_prompt"] = negative_prompt
custom_scope["is_negative"] = True
res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)
composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)
elif lora_layer_name.startswith("diffusion_model_"): # "diffusion_model_"
if res.shape[0] == num_batches * num_prompts + num_batches:
# tensor.shape[1] == uncond.shape[1]
tensor_off = 0
uncond_off = num_batches * num_prompts
for b in range(num_batches):
# c
for p, loras in enumerate(prompt_loras):
multiplier = loras.get(m_lora_name, 0.0)
if opt_composable_with_step:
prompt_block_id = p
custom_scope["current_prompt"] = prompt_blocks[prompt_block_id]
custom_scope["block_lora_count"] = len(loras)
lora_controller = lora_controllers[prompt_block_id]
multiplier = composable_lora_step.check_lora_weight(lora_controller, m_lora_name, step_counter, num_steps, custom_scope)
if multiplier != 0.0:
multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)
# print(f"tensor #{b}.{p} lora.name={m_lora_name} mul={multiplier} lora_layer_name={lora_layer_name}")
res[tensor_off] = composable_lycoris.composable_forward(module, patch[tensor_off], alpha, multiplier, res[tensor_off])
tensor_off += 1
# uc
multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)
if (opt_uc_diffusion_model or (is_single_block and (not opt_single_no_uc))) and multiplier != 0.0:
# print(f"uncond lora.name={m_lora_name} lora.mul={m_lora.multiplier} lora_layer_name={lora_layer_name}")
if is_single_block and opt_composable_with_step:
custom_scope["current_prompt"] = negative_prompt
custom_scope["is_negative"] = True
multiplier = composable_lora_step.check_lora_weight(full_controllers, m_lora_name, step_counter, num_steps, custom_scope)
multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)
res[uncond_off] = composable_lycoris.composable_forward(module, patch[uncond_off], alpha, multiplier, res[uncond_off])
uncond_off += 1
else:
# tensor.shape[1] != uncond.shape[1]
cur_num_prompts = res.shape[0]
base = (diffusion_model_counter // cur_num_prompts) // num_loras * cur_num_prompts
prompt_len = len(prompt_loras)
if 0 <= base < len(prompt_loras):
# c
for off in range(cur_num_prompts):
if base + off < prompt_len:
loras = prompt_loras[base + off]
multiplier = loras.get(m_lora_name, 0.0)
if opt_composable_with_step:
prompt_block_id = base + off
custom_scope["current_prompt"] = prompt_blocks[prompt_block_id]
custom_scope["block_lora_count"] = len(loras)
lora_controller = lora_controllers[prompt_block_id]
multiplier = composable_lora_step.check_lora_weight(lora_controller, m_lora_name, step_counter, num_steps, custom_scope)
if multiplier != 0.0:
multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)
# print(f"c #{base + off} lora.name={m_lora_name} mul={multiplier} lora_layer_name={lora_layer_name}")
res[off] = composable_lycoris.composable_forward(module, patch[off], alpha, multiplier, res[off])
else:
# uc
multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)
if (opt_uc_diffusion_model or (is_single_block and (not opt_single_no_uc))) and multiplier != 0.0:
# print(f"uc {lora_layer_name} lora.name={m_lora_name} lora.mul={m_lora.multiplier}")
if is_single_block and opt_composable_with_step:
custom_scope["current_prompt"] = negative_prompt
custom_scope["is_negative"] = True
multiplier = composable_lora_step.check_lora_weight(full_controllers, m_lora_name, step_counter, num_steps, custom_scope)
multiplier *= composable_lycoris.lycoris_get_multiplier_normalized(m_lora, lora_layer_name)
res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)
composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)
else:
# default
multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)
if multiplier != 0.0:
# print(f"default {lora_layer_name} lora.name={m_lora_name} lora.mul={m_lora.multiplier}")
res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)
composable_lycoris.check_lycoris_end_layer(lora_layer_name, res, num_loras)
else:
# default
multiplier = composable_lycoris.lycoris_get_multiplier(m_lora, lora_layer_name)
if multiplier != 0.0:
# print(f"DEFAULT {lora_layer_name} lora.name={m_lora_name} lora.mul={m_lora.multiplier}")
res = composable_lycoris.composable_forward(module, patch, alpha, multiplier, res)
return res
def lora_Linear_forward(self, input):
if composable_lycoris.has_webui_lycoris:
lora_backup_weights(self)
if not enabled:
import lycoris
import lora
lyco_count = len(lycoris.loaded_lycos)
old_lyco_count = getattr(self, "old_lyco_count", 0)
if old_lyco_count > 0 and lyco_count <= 0:
clear_cache_lora(self, True)
self.old_lyco_count = lyco_count
lora_ext.load_lora_ext()
torch.nn.Linear_forward_before_lyco = lora_ext.lora_Linear_forward
torch.nn.Linear_forward_before_network = Linear_forward_before_clora
#if lyco_count <= 0:
# return lora_ext.lora_Linear_forward(self, input)
if 'lyco_notfound' in locals() or 'lyco_notfound' in globals():
if lyco_notfound:
backup_Linear_forward = torch.nn.Linear_forward_before_lora
torch.nn.Linear_forward_before_lora = Linear_forward_before_clora
result = lycoris.lyco_Linear_forward(self, input)
torch.nn.Linear_forward_before_lora = backup_Linear_forward
return result
return lycoris.lyco_Linear_forward(self, input)
if lora_ext.is_sd_1_5:
import networks
networks.network_restore_weights_from_backup(self)
networks.network_reset_cached_weight(self)
else:
clear_cache_lora(self, False)
if (not self.weight.is_cuda) and input.is_cuda: #if variables not on the same device (between cpu and gpu)
self_weight_cuda = self.weight.to(device=devices.device) #pass to GPU
to_del = self.weight
self.weight = None #delete CPU variable
del to_del
del self.weight #avoid pytorch 2.0 throwing exception
self.weight = self_weight_cuda #load GPU data to self.weight
res = torch.nn.Linear_forward_before_lora(self, input)
res = lora_forward(self, input, res)
if composable_lycoris.has_webui_lycoris:
res = composable_lycoris.lycoris_forward(self, input, res)
return res
def lora_Conv2d_forward(self, input):
if composable_lycoris.has_webui_lycoris:
lora_backup_weights(self)
if not enabled:
import lycoris
import lora
lyco_count = len(lycoris.loaded_lycos)
old_lyco_count = getattr(self, "old_lyco_count", 0)
if old_lyco_count > 0 and lyco_count <= 0:
clear_cache_lora(self, True)
self.old_lyco_count = lyco_count
lora_ext.load_lora_ext()
torch.nn.Conv2d_forward_before_lyco = lora_ext.lora_Conv2d_forward
torch.nn.Conv2d_forward_before_network = Conv2d_forward_before_clora
#if lyco_count <= 0:
# return lora_ext.lora_Conv2d_forward(self, input)
if 'lyco_notfound' in locals() or 'lyco_notfound' in globals():
if lyco_notfound:
backup_Conv2d_forward = torch.nn.Conv2d_forward_before_lora
torch.nn.Conv2d_forward_before_lora = Conv2d_forward_before_clora
result = lycoris.lyco_Conv2d_forward(self, input)
torch.nn.Conv2d_forward_before_lora = backup_Conv2d_forward
return result
return lycoris.lyco_Conv2d_forward(self, input)
if lora_ext.is_sd_1_5:
import networks
networks.network_restore_weights_from_backup(self)
networks.network_reset_cached_weight(self)
else:
clear_cache_lora(self, False)
if (not self.weight.is_cuda) and input.is_cuda:
self_weight_cuda = self.weight.to(device=devices.device)
to_del = self.weight
self.weight = None
del to_del
del self.weight #avoid "cannot assign XXX as parameter YYY (torch.nn.Parameter or None expected)"
self.weight = self_weight_cuda
res = torch.nn.Conv2d_forward_before_lora(self, input)
res = lora_forward(self, input, res)
if composable_lycoris.has_webui_lycoris:
res = composable_lycoris.lycoris_forward(self, input, res)
return res
def lora_MultiheadAttention_forward(self, input):
if composable_lycoris.has_webui_lycoris:
lora_backup_weights(self)
if not enabled:
import lycoris
import lora
lyco_count = len(lycoris.loaded_lycos)
old_lyco_count = getattr(self, "old_lyco_count", 0)
if old_lyco_count > 0 and lyco_count <= 0:
clear_cache_lora(self, True)
self.old_lyco_count = lyco_count
lora_ext.load_lora_ext()
torch.nn.MultiheadAttention_forward_before_lyco = lora_ext.lora_MultiheadAttention_forward
torch.nn.MultiheadAttention_forward_before_network = MultiheadAttention_forward_before_clora
#if lyco_count <= 0:
# return lora_ext.lora_MultiheadAttention_forward(self, input)
if 'lyco_notfound' in locals() or 'lyco_notfound' in globals():
if lyco_notfound:
backup_MultiheadAttention_forward = torch.nn.MultiheadAttention_forward_before_lora
torch.nn.MultiheadAttention_forward_before_lora = MultiheadAttention_forward_before_clora
result = lycoris.lyco_MultiheadAttention_forward(self, input)
torch.nn.MultiheadAttention_forward_before_lora = backup_MultiheadAttention_forward
return result
return lycoris.lyco_MultiheadAttention_forward(self, input)
if lora_ext.is_sd_1_5:
import networks
networks.network_restore_weights_from_backup(self)
networks.network_reset_cached_weight(self)
else:
clear_cache_lora(self, False)
if (not self.weight.is_cuda) and input.is_cuda:
self_weight_cuda = self.weight.to(device=devices.device)
to_del = self.weight
self.weight = None
del to_del
del self.weight #avoid "cannot assign XXX as parameter YYY (torch.nn.Parameter or None expected)"
self.weight = self_weight_cuda
res = torch.nn.MultiheadAttention_forward_before_lora(self, input)
res = lora_forward(self, input, res)
if composable_lycoris.has_webui_lycoris:
res = composable_lycoris.lycoris_forward(self, input, res)
return res
def noop():
pass
def should_reload():
#pytorch 2.0 should reload
match = re.search(r"\d+(\.\d+)?",str(torch.__version__))
if not match:
return True
ver = float(match.group(0))
return ver >= 2.0
enabled : bool = False
opt_composable_with_step : bool = False
opt_uc_text_model_encoder : bool = False
opt_uc_diffusion_model : bool = False
opt_plot_lora_weight : bool = False
opt_single_no_uc : bool = False
opt_hires_step_as_global : bool = False
verbose : bool = True
sd_processing = None
full_prompt: str = ""
negative_prompt: str = ""
drawing_lora_names : List[str] = []
drawing_data : List[List[float]] = []
drawing_lora_first_index : List[float] = []
first_log_drawing : bool = False
is_single_block : bool = False
num_batches: int = 0
num_steps: int = 20
num_hires_steps: int = 20
prompt_loras: List[Dict[str, float]] = []
text_model_encoder_counter: int = -1
diffusion_model_counter: int = 0
step_counter: int = 0
cache_layer_list : List[str] = []
should_print : bool = True
prompt_blocks: List[str] = []
lora_controllers: List[List[composable_lora_step.LoRA_Controller_Base]] = []
full_controllers: List[composable_lora_step.LoRA_Controller_Base] = []
================================================
FILE: composable_lora_function_handler.py
================================================
import torch
import composable_lora
import composable_lycoris
def on_enable():
#backup original forward methods
composable_lora.backup_lora_Linear_forward = torch.nn.Linear.forward
composable_lora.backup_lora_Conv2d_forward = torch.nn.Conv2d.forward
composable_lora.backup_lora_MultiheadAttention_forward = torch.nn.MultiheadAttention.forward
if hasattr(torch.nn, 'Linear_forward_before_lyco'):
#if a1111-sd-webui-lycoris installed, backup it's forward methods
import lycoris
composable_lycoris.has_webui_lycoris = True
if hasattr(torch.nn, 'Linear_forward_before_lyco'):
composable_lycoris.backup_Linear_forward_before_lyco = torch.nn.Linear_forward_before_lyco
if hasattr(torch.nn, 'Linear_load_state_dict_before_lyco'):
composable_lycoris.backup_Linear_load_state_dict_before_lyco = torch.nn.Linear_load_state_dict_before_lyco
if hasattr(torch.nn, 'Conv2d_forward_before_lyco'):
composable_lycoris.backup_Conv2d_forward_before_lyco = torch.nn.Conv2d_forward_before_lyco
if hasattr(torch.nn, 'Conv2d_load_state_dict_before_lyco'):
composable_lycoris.backup_Conv2d_load_state_dict_before_lyco = torch.nn.Conv2d_load_state_dict_before_lyco
if hasattr(torch.nn, 'MultiheadAttention_forward_before_lyco'):
composable_lycoris.backup_MultiheadAttention_forward_before_lyco = torch.nn.MultiheadAttention_forward_before_lyco
if hasattr(torch.nn, 'MultiheadAttention_load_state_dict_before_lyco'):
composable_lycoris.backup_MultiheadAttention_load_state_dict_before_lyco = torch.nn.MultiheadAttention_load_state_dict_before_lyco
if hasattr(composable_lora, 'lyco_notfound'):
if composable_lora.lyco_notfound:
torch.nn.Linear_forward_before_lyco = composable_lora.Linear_forward_before_clora
torch.nn.Conv2d_forward_before_lyco = composable_lora.Conv2d_forward_before_clora
torch.nn.MultiheadAttention_forward_before_lyco = composable_lora.MultiheadAttention_forward_before_clora
torch.nn.Linear.forward = composable_lora.lora_Linear_forward
torch.nn.Conv2d.forward = composable_lora.lora_Conv2d_forward
torch.nn.MultiheadAttention.forward = lycoris.lyco_MultiheadAttention_forward
torch.nn.MultiheadAttention._load_from_state_dict = lycoris.lyco_MultiheadAttention_load_state_dict
else:
composable_lycoris.has_webui_lycoris = False
if (composable_lora.should_reload() or (torch.nn.Linear.forward != composable_lora.lora_Linear_forward)):
if composable_lora.enabled:
torch.nn.Linear.forward = composable_lora.lora_Linear_forward
torch.nn.Conv2d.forward = composable_lora.lora_Conv2d_forward
def on_disable():
torch.nn.Linear.forward = composable_lora.backup_lora_Linear_forward
torch.nn.Conv2d.forward = composable_lora.backup_lora_Conv2d_forward
torch.nn.MultiheadAttention.forward = composable_lora.backup_lora_MultiheadAttention_forward
if hasattr(torch.nn, 'Linear_forward_before_lyco'):
composable_lycoris.has_webui_lycoris = True
if hasattr(composable_lycoris, 'backup_Linear_forward_before_lyco'):
torch.nn.Linear_forward_before_lyco = composable_lycoris.backup_Linear_forward_before_lyco
if hasattr(composable_lycoris, 'backup_Linear_load_state_dict_before_lyco'):
torch.nn.Linear_load_state_dict_before_lyco = composable_lycoris.backup_Linear_load_state_dict_before_lyco
if hasattr(composable_lycoris, 'backup_Conv2d_forward_before_lyco'):
torch.nn.Conv2d_forward_before_lyco = composable_lycoris.backup_Conv2d_forward_before_lyco
if hasattr(composable_lycoris, 'backup_Conv2d_load_state_dict_before_lyco'):
torch.nn.Conv2d_load_state_dict_before_lyco = composable_lycoris.backup_Conv2d_load_state_dict_before_lyco
if hasattr(composable_lycoris, 'backup_MultiheadAttention_forward_before_lyco'):
torch.nn.MultiheadAttention_forward_before_lyco = composable_lycoris.backup_MultiheadAttention_forward_before_lyco
if hasattr(composable_lycoris, 'backup_MultiheadAttention_load_state_dict_before_lyco'):
torch.nn.MultiheadAttention_load_state_dict_before_lyco = composable_lycoris.backup_MultiheadAttention_load_state_dict_before_lyco
else:
composable_lycoris.has_webui_lycoris = False
================================================
FILE: composable_lora_step.py
================================================
from typing import List, Union
import re
import ast
import copy
import json
import math
import sys
import traceback
import random
from modules import extra_networks
re_AND = re.compile(r"\bAND\b")
class Runable:
"""
like exec() but can return values
https://stackoverflow.com/a/52361938/5862977
"""
def __init__(self, code : str, code_name : str = "<prompt>"):
self.code = code
self.code_name = code_name
self.compiled = False
try:
self.compile_self()
except Exception:
pass
def compile_self(self):
self.code_ast = ast.parse(self.code, self.code_name)
self.init_ast = copy.deepcopy(self.code_ast)
self.init_ast.body = self.code_ast.body[:-1]
self.last_ast = copy.deepcopy(self.code_ast)
self.last_ast.body = self.code_ast.body[-1:]
self.full_bin = compile(self.code_ast, self.code_name, "exec")
self.start_bin = compile(self.init_ast, self.code_name, "exec")
if type(self.last_ast.body[0]) == ast.Expr:
self.run_bin = compile(self.convertExpr2Expression(self.last_ast.body[0]), self.code_name, "eval")
else:
self.end_bin = compile(self.last_ast, self.code_name, "exec")
self.compiled = True
def convertExpr2Expression(self, expr : ast.Expr):
expr.lineno = 0
expr.col_offset = 0
result = ast.Expression(expr.value, lineno=0, col_offset = 0)
return result
def run(self, module):
if not self.compiled:
self.compile_self()
if len(self.init_ast.body) > 0:
exec(self.start_bin, module.__dict__)
if type(self.last_ast.body[0]) == ast.Expr:
return eval(self.run_bin, module.__dict__)
else:
exec(self.end_bin, module.__dict__)
class LoRA_data:
def __init__(self, name : str, weight : float):
self.name = name
self.weight = weight
def __repr__(self):
return f"LoRA:{self.name}:{self.weight}"
def __str__(self):
return f"LoRA:{self.name}:{self.weight}"
class LoRA_Weight_CMD:
def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):
return weight
class LoRA_Weight_decrement(LoRA_Weight_CMD):
def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):
return weight * (1 - progress)
class LoRA_Weight_increment(LoRA_Weight_CMD):
def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):
return weight * progress
def raise_(ex):
raise ex
def not_allow(name):
return lambda: raise_(Exception(f'function {name} is not allow in LoRA Controller'))
LoRA_Weight_eval_scope = {
"abs": abs,
"ceil": math.ceil, "floor": math.floor, "trunc": math.trunc,
"fmod": math.fmod,
"gcd": math.gcd, "lcm": math.lcm,
"perm": math.perm, "comb": math.comb, "gamma": math.gamma,
"sqrt": math.sqrt, "cbrt": lambda x: pow(x, 1.0 / 3.0),
"exp": math.exp, "pow": math.pow,
"log": math.log, "ln": math.log, "log2": math.log2, "log10": math.log10,
"clamp": lambda x: 1.0 if x > 1 else (0.0 if x < 0 else x),
"asin": lambda x: (math.acos(1.0 - x * 2.0) + 2.0 * math.pi) / (2.0 * math.pi),
"acos": lambda x: (math.acos(x * 2.0 - 1.0) + 2.0 * math.pi) / (2.0 * math.pi),
"atan": lambda x: (math.atan(x) + math.pi) / (2.0 * math.pi),
"sin": lambda x: (math.sin(x * 2.0 * math.pi - (math.pi / 2.0)) + 1.0) / 2.0,
"cos": lambda x: (math.sin(x * 2.0 * math.pi + (math.pi / 2.0)) + 1.0) / 2.0,
"tan": lambda x: math.tan(x * 2.0 * math.pi),
"sinr": math.sin, "cosr": math.cos, "tanr": math.tan,
"asinr": math.asin, "acosr": math.acos, "atanr": math.atan,
"sinh": math.sinh, "cosh": math.cosh, "tanh": math.tanh,
"asinh": math.asinh, "acosh": math.acosh, "atanh": math.atanh,
"abssin": lambda x: abs(math.sin(x * 2 * math.pi)),
"abscos": lambda x: abs(math.cos(x * 2 * math.pi)),
"random": random.random,
"pi": math.pi, "nan": math.nan, "inf": math.inf,
#not allow functions
"eval": not_allow("eval"),
"exec": not_allow("exec"),
"compile": not_allow("compile"),
"breakpoint": not_allow("breakpoint"),
"__import__": not_allow("__import__")
}
class LoRA_Weight_eval(LoRA_Weight_CMD):
def __init__(self, command : str, code_name : str = "<prompt>"):
self.command = command
self.is_error = False
from types import ModuleType
self.module = ModuleType("module_in_prompt")
self.module.__dict__.update(globals())
self.module.__dict__.update(LoRA_Weight_eval_scope)
self.bin = Runable(self.command, code_name)
def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):
result = None
#setup local variables
LoRA_Weight_eval_scope["enable_prepare_step"] = False
LoRA_Weight_eval_scope["weight"] = weight
LoRA_Weight_eval_scope["life"] = progress if step != -1 else 0
LoRA_Weight_eval_scope["step"] = step
LoRA_Weight_eval_scope["steps"] = all_step
LoRA_Weight_eval_scope["warmup"] = lambda x: progress / x if progress < x else 1.0
LoRA_Weight_eval_scope["cooldown"] = lambda x: (1 - progress) / (1 - x) if progress > x else 1.0
self.module.__dict__.update(globals())
self.module.__dict__.update(LoRA_Weight_eval_scope)
self.module.__dict__.update(custom_scope)
try:
result = self.bin.run(self.module)
try:
result = float(result) * weight
except Exception:
raise Exception(\
f"LoRA Controller command result must be a numble, but got {type(result)}")
if math.isnan(result):
raise Exception(\
f"Can not apply a NaN weight to LoRA.")
if math.isinf(result):
raise Exception(\
f"Can not apply a infinity weight to LoRA.")
except:
if not self.is_error:
print(f"CommandError: {self.command}")
traceback.print_exception(*sys.exc_info())
self.is_error = True
return weight
if step == -1 and not self.module.__dict__["enable_prepare_step"]:
return weight
return result
def __repr__(self):
return f"LoRA_Weight_eval:{self.command}"
def __str__(self):
return f"LoRA_Weight_eval:{self.command}"
class LoRA_Controller_Base:
def __init__(self):
self.base_weight = 1.0
self.Weight_Controller = LoRA_Weight_CMD()
def getWeight(self, weight : float, progress: float, step : int, all_step : int, custom_scope):
result = self.Weight_Controller.getWeight(weight, progress, step, all_step, custom_scope)
if step == -1:
if not isinstance(self.Weight_Controller, LoRA_Weight_eval):
return weight
return result
def test(self, test_lora : str, step : int, all_step : int, custom_scope):
return self.base_weight
#normal lora
class LoRA_Controller(LoRA_Controller_Base):
def __init__(self, name : str, weight : float):
super().__init__()
self.name = name
self.weight = float(weight)
def test(self, test_lora : str, step : int, all_step : int, custom_scope):
if test_lora == self.name:
return self.getWeight(self.weight, float(step) / float(all_step), step, all_step, custom_scope)
return 0.0
def __repr__(self):
return f"LoRA_Controller:{self.name}[weight={self.weight}]"
def __str__(self):
return f"LoRA_Controller:{self.name}[weight={self.weight}]"
#lora with start and end
class LoRA_StartEnd_Controller(LoRA_Controller_Base):
def __init__(self, name : str, weight : float, start : Union[float, int], end : Union[float, int]):
super().__init__()
self.name = name
self.weight = float(weight)
self.start = float(start)
self.end = float(end)
def test(self, test_lora : str, step : int, all_step : int, custom_scope):
if test_lora == self.name:
if step == -1:
return self.getWeight(self.weight, -1, step, all_step, custom_scope)
start = self.start
end = self.end
if start < 1:
start = self.start * all_step
if end < 1:
end = self.end * all_step
if end < 0:
end = all_step
if (step >= start) and (step <= end):
return self.getWeight(self.weight, float(step - start) / float(end - start), step, all_step, custom_scope)
return 0.0
def __repr__(self):
return f"LoRA_StartEnd_Controller:{self.name}[weight={self.weight},start at={self.start},end at={self.end}]"
def __str__(self):
return f"LoRA_StartEnd_Controller:{self.name}[weight={self.weight},start at={self.start},end at={self.end}]"
#switch lora
class LoRA_Switcher_Controller(LoRA_Controller_Base):
def __init__(self, lora_dist : List[LoRA_data], start : Union[float, int], end : Union[float, int]):
super().__init__()
self.lora_dist = lora_dist
the_list : List[str] = []
self.lora_list = the_list
self.start = float(start)
self.end = float(end)
for lora_item in self.lora_dist:
self.lora_list.append(lora_item.name)
def test(self, test_lora : str, step : int, all_step : int, custom_scope):
lora_count = len(self.lora_dist)
if step == -1 and test_lora in self.lora_list:
return self.getWeight(self.lora_dist[self.lora_list.index(test_lora)].weight, -1, step, all_step, custom_scope)
if test_lora == self.lora_list[step % lora_count]:
start = self.start
end = self.end
if start < 1:
start = self.start * all_step
if end < 1:
end = self.end * all_step
if end < 0:
end = all_step
if (step >= start) and (step <= end):
return self.getWeight(self.lora_dist[step % lora_count].weight, float(step - start) / float(end - start), step, all_step, custom_scope)
return 0.0
def __repr__(self):
return f"LoRA_Switcher_Controller:{self.lora_dist}[start at={self.start},end at={self.end}]"
def __str__(self):
return f"LoRA_Switcher_Controller:{self.lora_dist}[start at={self.start},end at={self.end}]"
def parse_step_rendering_syntax(prompt: str):
lora_controllers : List[List[LoRA_Controller_Base]] = []
subprompts = re_AND.split(escape_prompt(prompt))
for i, subprompt in enumerate(subprompts):
tmp_lora_controllers: List[LoRA_Controller_Base] = []
step_rendering_list, pure_loratext = get_all_step_rendering_in_prompt(subprompt)
for item in step_rendering_list:
tmp_lora_controllers += get_LoRA_Controllers(item)
lora_list = get_lora_list(pure_loratext)
for lora_item in lora_list:
tmp_lora_controllers.append(LoRA_Controller(lora_item.name, lora_item.weight))
lora_controllers.append(tmp_lora_controllers)
return lora_controllers
def check_lora_weight(controllers : List[LoRA_Controller_Base], test_lora : str, step : int, all_step : int, custom_scope):
result_weight = 0.0
for controller in controllers:
calc_weight = controller.test(test_lora, step, all_step, custom_scope)
if abs(calc_weight) > abs(result_weight):
result_weight = calc_weight
return result_weight
def get_lora_list(prompt: str):
result : List[LoRA_data] = []
_, extra_network_data = extra_networks.parse_prompt(prompt)
for m_type in ['lora', 'lyco']:
if m_type in extra_network_data.keys():
for params in extra_network_data[m_type]:
name = params.items[0]
multiplier = float(params.items[1]) if len(params.items) > 1 else 1.0
result.append(LoRA_data(f"{m_type}:{name}", multiplier))
if len(result) <= 0:
result.append(LoRA_data("", 0.0))
return result
def get_or_list(prompt: str):
return prompt.split("|")
re_start_end = re.compile(r"\[\s*\[\s*([^\:\]]+)\:\s*\:([^\]]+)\]\s*\:\s*([^\]]+)\]")
re_strat_at = re.compile(r"\[\s*([^\:\]]+)\:\s*([0-9\.]+)\s*\]")
re_bucket_inside = re.compile(r"\[([^\]]+)\]")
re_extra_net = re.compile(r"<([^>]+):([^>]+)>")
re_python_escape = re.compile(r"\$\$PYTHON_OBJ\$\$(\d+)\^")
re_python_escape_x = re.compile(r"\$\$PYTHON_OBJX?\$\$(\d+)\^")
re_sd_step_render = re.compile(r"\[[^\[\]]+\]")
re_super_cmd = re.compile(r"(\\u0023|#)([^:#\[\]]+)")
re_escape_char = re.compile(r"\\([\[\]\:\\])")
def escape_prompt(prompt : str):
def preprossing_escape(match_pt : re.Match):
input_str = str(match_pt.group(1))
if input_str == '[':
return '\\u005B'
elif input_str == ']':
return '\\u005D'
elif input_str == ':':
return '\\u003A'
elif input_str == '\\':
return '\\u005C'
return str(match_pt.group(0))
return re.sub(re_escape_char, preprossing_escape, prompt)
class MySearchResult:
def __init__(self):
group : List[str] = []
self.group = group
def extra_net_split(input_str : str, pattern : str):
result : List[str] = []
extra_net_list : List[str] = []
escape_obj_list : List[str] = []
def preprossing_escape(match_pt : re.Match):
escape_obj_list.append(str(match_pt.group(0)))
return f"$$PYTHON_OBJX$${len(escape_obj_list)-1}^"
def preprossing_extra_net(match_pt : re.Match):
extra_net_list.append(str(match_pt.group(0)))
return f"$$PYTHON_OBJ$${len(extra_net_list)-1}^"
def unstrip_extra_net_pattern(match_pt : re.Match):
input_str = str(match_pt.group(0))
try:
index = int(match_pt.group(1))
return extra_net_list[index]
except Exception:
return input_str
def unstrip_text_pattern_obj(match_pt : re.Match):
input_str = str(match_pt.group(0))
try:
index = int(match_pt.group(1))
return escape_obj_list[index]
except Exception:
return input_str
txt : str = input_str
txt = re.sub(re_python_escape_x, preprossing_escape, txt)
txt = re.sub(re_extra_net, preprossing_extra_net, txt)
pre_result = txt.split(pattern)
for i in range(len(pre_result)):
try:
cur_pattern = str(pre_result[i])
cur_result = re.sub(re_python_escape, unstrip_extra_net_pattern, cur_pattern)
cur_result = re.sub(re_python_escape_x, unstrip_text_pattern_obj, cur_result)
result.append(cur_result)
except Exception as ex:
break
if len(result) <= 0:
return [input_str]
return result
def extra_net_re_search(pattern : Union[str, re.Pattern[str]], input_str : str):
result = MySearchResult()
extra_net_list : List[str] = []
escape_obj_list : List[str] = []
def preprossing_escape(match_pt : re.Match):
escape_obj_list.append(str(match_pt.group(0)))
return f"$$PYTHON_OBJX$${len(escape_obj_list)-1}^"
def preprossing_extra_net(match_pt : re.Match):
extra_net_list.append(str(match_pt.group(0)))
return f"$$PYTHON_OBJ$${len(extra_net_list)-1}^"
def unstrip_extra_net_pattern(match_pt : re.Match):
input_str = str(match_pt.group(0))
try:
index = int(match_pt.group(1))
return extra_net_list[index]
except Exception:
return input_str
def unstrip_text_pattern_obj(match_pt : re.Match):
input_str = str(match_pt.group(0))
try:
index = int(match_pt.group(1))
return escape_obj_list[index]
except Exception:
return input_str
txt : str = input_str
txt = re.sub(re_python_escape_x, preprossing_escape, txt)
txt = re.sub(re_extra_net, preprossing_extra_net, txt)
pre_result = re.search(pattern, txt)
for i in range(1000):
try:
cur_pattern = str(pre_result.group(i))
cur_result = re.sub(re_python_escape, unstrip_extra_net_pattern, cur_pattern)
cur_result = re.sub(re_python_escape_x, unstrip_text_pattern_obj, cur_result)
result.group.append(cur_result)
except Exception as ex:
break
if len(result.group) <= 0:
return None
return result
def unescape_string(input_string : str):
result = ''
unicode_list = ['u','x']
i = 0 #for(var i=0; i<input_string.length; ++i)
while i < len(input_string):
current_char = input_string[i]
if current_char == '\\':
i += 1
if i >= len(input_string):
break
string_body = input_string[i]
if(string_body.lower() in unicode_list):
result += f"{current_char}{string_body}"
else:
char_added = False
try:
unescaped = json.loads(f"\"{current_char}{string_body}\"")
if unescaped:
result += unescaped
char_added = True
except Exception:
pass
if not char_added:
result += string_body
else:
result += current_char
i += 1
return str(json.loads(json.dumps(result, indent=4).replace("\\\\", "\\")))
def get_LoRA_Controllers(prompt: str):
result = extra_net_re_search(re_start_end, prompt)
super_cmd = re.search(re_super_cmd, prompt)
Weight_Controller = LoRA_Weight_CMD()
if super_cmd:
super_cmd_text = unescape_string(super_cmd.group(2)).strip()
if super_cmd_text.startswith("cmd("):
Weight_Controller = LoRA_Weight_eval(super_cmd_text[4:-1], f"<prompt>, at {re.sub(re_super_cmd, '', prompt)}")
elif super_cmd_text.startswith("decrease"):
Weight_Controller = LoRA_Weight_decrement()
elif super_cmd_text.startswith("increment"):
Weight_Controller = LoRA_Weight_increment()
def set_Weight_Controller(controller_list : list[LoRA_Controller_Base], the_controller : LoRA_Weight_CMD):
for i, the_item in enumerate(controller_list):
controller_list[i].Weight_Controller = the_controller
return controller_list
result_list: List[LoRA_Controller_Base] = []
if result:
or_list = get_or_list(result.group[1])
if len(or_list) == 1: #LoRA with start and end
lora_list = get_lora_list(or_list[0])
for lora_item in lora_list:
try:
result_list.append(LoRA_StartEnd_Controller(lora_item.name, lora_item.weight, float(result.group[3]), float(result.group[2])))
except Exception:
continue
return set_Weight_Controller(result_list, Weight_Controller)
lora_lists : List[List[LoRA_data]] = []
max_len = -1
for or_block in or_list: #or
lora_list = get_lora_list(or_block)
lora_list_len = len(lora_list)
if lora_list_len > max_len:
max_len = lora_list_len
lora_lists.append(lora_list)
if max_len > 0:
for i in range(max_len):
tmp_lora_list : List[LoRA_data] = []
for it_lora_list in lora_lists:
tmp_lora = LoRA_data("", 0.0)
if i < len(it_lora_list):
tmp_lora = it_lora_list[i]
tmp_lora_list.append(tmp_lora)
result_list.append(LoRA_Switcher_Controller(tmp_lora_list, float(result.group[3]), float(result.group[2])))
return set_Weight_Controller(result_list, Weight_Controller)
result = extra_net_re_search(re_strat_at, prompt)
if result:
or_list = get_or_list(result.group[1])
if len(or_list) == 1: #LoRA with start and end
lora_list = get_lora_list(or_list[0])
for lora_item in lora_list:
try:
result_list.append(LoRA_StartEnd_Controller(lora_item.name, lora_item.weight, float(result.group[2]), -1.0))
except Exception:
continue
return set_Weight_Controller(result_list, Weight_Controller)
lora_lists : List[List[LoRA_data]] = []
max_len = -1
for or_block in or_list: #or
lora_list = get_lora_list(or_block)
lora_list_len = len(lora_list)
if lora_list_len > max_len:
max_len = lora_list_len
lora_lists.append(lora_list)
if max_len > 0:
for i in range(max_len):
tmp_lora_list : List[LoRA_data] = []
for it_lora_list in lora_lists:
tmp_lora = LoRA_data("", 0.0)
if i < len(it_lora_list):
tmp_lora = it_lora_list[i]
tmp_lora_list.append(tmp_lora)
result_list.append(LoRA_Switcher_Controller(tmp_lora_list, float(result.group[2]), -1.0))
return set_Weight_Controller(result_list, Weight_Controller)
result = extra_net_re_search(re_bucket_inside, prompt)
if result:
bucket_inside = result.group[1]
split_by_colon = extra_net_split(bucket_inside,":")
if len(split_by_colon) == 1 and (("|" in bucket_inside) or ("#" in bucket_inside)):
split_by_colon.append('')
split_by_colon.append('-1')
if len(split_by_colon) > 2:
should_pass = False
or_list = get_or_list(split_by_colon[0])
if len(or_list) == 1: #LoRA with start and end
lora_list = get_lora_list(or_list[0])
for lora_item in lora_list:
try:
result_list.append(LoRA_StartEnd_Controller(lora_item.name, lora_item.weight, 0.0, float(split_by_colon[2])))
except Exception:
continue
should_pass = True
if not should_pass:
lora_lists : List[List[LoRA_data]] = []
max_len = -1
for or_block in or_list: #or
lora_list = get_lora_list(or_block)
lora_list_len = len(lora_list)
if lora_list_len > max_len:
max_len = lora_list_len
lora_lists.append(lora_list)
if max_len > 0:
for i in range(max_len):
tmp_lora_list : List[LoRA_data] = []
for it_lora_list in lora_lists:
tmp_lora = LoRA_data("", 0.0)
if i < len(it_lora_list):
tmp_lora = it_lora_list[i]
tmp_lora_list.append(tmp_lora)
result_list.append(LoRA_Switcher_Controller(tmp_lora_list, 0.0, float(split_by_colon[2])))
should_pass = False
or_list = get_or_list(split_by_colon[1])
if len(or_list) == 1: #LoRA with start and end
lora_list = get_lora_list(or_list[0])
for lora_item in lora_list:
try:
result_list.append(LoRA_StartEnd_Controller(lora_item.name, lora_item.weight, float(split_by_colon[2]), -1.0))
except Exception:
continue
should_pass = True
if not should_pass:
lora_lists : List[List[LoRA_data]] = []
max_len = -1
for or_block in or_list: #or
lora_list = get_lora_list(or_block)
lora_list_len = len(lora_list)
if lora_list_len > max_len:
max_len = lora_list_len
lora_lists.append(lora_list)
if max_len > 0:
for i in range(max_len):
tmp_lora_list : List[LoRA_data] = []
for it_lora_list in lora_lists:
tmp_lora = LoRA_data("", 0.0)
if i < len(it_lora_list):
tmp_lora = it_lora_list[i]
tmp_lora_list.append(tmp_lora)
result_list.append(LoRA_Switcher_Controller(tmp_lora_list, float(split_by_colon[2]), -1.0))
return set_Weight_Controller(result_list, Weight_Controller)
return set_Weight_Controller(result_list, Weight_Controller)
def get_all_step_rendering_in_prompt(input_prompt : str):
read_rendering_item_list : List[str] = []
escape_obj_list : List[str] = []
rendering_item_list : List[str] = []
def preprossing_step_rendering_item(match_pt : re.Match):
read_rendering_item_list.append(str(match_pt.group(0)))
return f"$$PYTHON_OBJ$${len(read_rendering_item_list)-1}^"
def preprossing_step_rendering_text(match_pt : re.Match):
escape_obj_list.append(str(match_pt.group(0)))
return f"$$PYTHON_OBJX$${len(escape_obj_list)-1}^"
def load_step_rendering_item(match_pt : re.Match):
input_str = str(match_pt.group(0))
rendering_item_list.append(input_str)
return input_str
def unstrip_rendering_text_pattern(match_pt : re.Match):
input_str = str(match_pt.group(0))
try:
index = int(match_pt.group(1))
return read_rendering_item_list[index]
except Exception:
return input_str
def unstrip_rendering_text_pattern_obj(match_pt : re.Match):
input_str = str(match_pt.group(0))
try:
index = int(match_pt.group(1))
return escape_obj_list[index]
except Exception:
return input_str
def unstrip_rendering_text(input_str : str):
old_result : str = "None"
result : str = input_str
while old_result != result:
old_result = result
result = re.sub(re_python_escape, unstrip_rendering_text_pattern, result)
old_result = "None"
while old_result != result:
old_result = result
result = re.sub(re_python_escape_x, unstrip_rendering_text_pattern_obj, result)
return result
txt : str = input_prompt
txt = re.sub(re_python_escape_x, preprossing_step_rendering_text, txt)
old_txt : str = "None"
while old_txt != txt:
old_txt = txt
txt = re.sub(re_sd_step_render, preprossing_step_rendering_item, txt)
re.sub(re_python_escape, load_step_rendering_item, txt)
for i, the_item in enumerate(rendering_item_list):
rendering_item_list[i] = unstrip_rendering_text(the_item)
return rendering_item_list, txt
================================================
FILE: composable_lycoris.py
================================================
from typing import Optional, Union
import re
import torch
import lora_ext
from modules import shared, devices
#support for <lyco:MODEL>
def lycoris_forward(compvis_module: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.MultiheadAttention], input, res):
import composable_lora as lora_controller
import lora
import lycoris
if len(lycoris.loaded_lycos) == 0:
return res
if hasattr(devices, "cond_cast_unet"):
input = devices.cond_cast_unet(input)
lycoris_layer_name_loading : Optional[str] = getattr(compvis_module, 'lyco_layer_name', None)
if lycoris_layer_name_loading is None:
return res
#let it type is actually a string
lycoris_layer_name : str = str(lycoris_layer_name_loading)
del lycoris_layer_name_loading
sd_module = shared.sd_model.lora_layer_mapping.get(lycoris_layer_name, None)
num_loras = len(lora_ext.get_loaded_lora()) + len(lycoris.loaded_lycos)
if lora_controller.text_model_encoder_counter == -1:
lora_controller.text_model_encoder_counter = len(lora_controller.prompt_loras) * num_loras
tmp_check_loras = [] #store which lora are already apply
tmp_check_loras.clear()
for m_lycoris in lycoris.loaded_lycos:
module = m_lycoris.modules.get(lycoris_layer_name, None)
if module is None:
#fix the lyCORIS issue
check_lycoris_end_layer(lycoris_layer_name, res, num_loras)
continue
current_lora = normalize_lora_name(m_lycoris.name)
lora_already_used = False
if current_lora in tmp_check_loras:
lora_already_used = True
#store the applied lora into list
tmp_check_loras.append(current_lora)
if lora_already_used:
check_lycoris_end_layer(lycoris_layer_name, res, num_loras)
continue
converted_module = convert_lycoris(module, sd_module)
if converted_module is None:
check_lycoris_end_layer(lycoris_layer_name, res, num_loras)
continue
patch = get_lora_patch(converted_module, input, res, lycoris_layer_name)
alpha = get_lora_alpha(converted_module, 1.0)
num_prompts = len(lora_controller.prompt_loras)
# print(f"lora.name={m_lora.name} lora.mul={m_lora.multiplier} alpha={alpha} pat.shape={patch.shape}")
res = lora_controller.apply_composable_lora(lycoris_layer_name, m_lycoris, converted_module, "lyco", patch, alpha, res, num_loras, num_prompts)
return res
def composable_forward(module, patch, alpha, multiplier, res):
if hasattr(module, 'composable_forward'):
return module.composable_forward(patch, alpha, multiplier, res)
return res + multiplier * alpha * patch
re_lora_block_weight = re.compile(r"[_\s]*added[_\s]*by[_\s]*lora[_\s]*block[_\s]*weight[_\s]*.*$")
def normalize_lora_name(lora_name):
result = re.sub(r"[_\s]*added[_\s]*by[_\s]*lora[_\s]*block[_\s]*weight[_\s]*.*$", "", lora_name)
return result
def get_lora_inference(module, input):
if hasattr(module, 'inference'): #support for lyCORIS
return module.inference(input)
elif hasattr(module, 'up'): #LoRA
if hasattr(module.up, "to"):
module.up.to(device=devices.device)
if hasattr(module.down, "to"):
module.down.to(device=devices.device)
return module.up(module.down(input))
else:
return None
def get_lora_patch(module, input, res, lora_layer_name):
if is_loha(module):
if input.is_cuda: #if is cuda, pass to cuda; otherwise do nothing
pass_loha_to_gpu(module)
if getattr(shared.opts, "lora_apply_to_outputs", False) and res.shape == input.shape:
inference = get_lora_inference(module, res)
if inference is not None:
return inference
else:
converted_module = convert_lycoris(module, shared.sd_model.lora_layer_mapping.get(lora_layer_name, None))
if converted_module is not None:
return get_lora_inference(converted_module, res)
else:
raise NotImplementedError(
"Your settings, extensions or models are not compatible with each other."
)
else:
inference = get_lora_inference(module, input)
if inference is not None:
return inference
else:
if hasattr(shared.sd_model, "network_layer_mapping"):
converted_module = convert_lycoris(module, shared.sd_model.network_layer_mapping.get(lora_layer_name, None))
else:
converted_module = convert_lycoris(module, shared.sd_model.lora_layer_mapping.get(lora_layer_name, None))
if converted_module is not None:
return get_lora_inference(converted_module, input)
else:
raise NotImplementedError(
"Your settings, extensions or models are not compatible with each other."
)
def get_lora_alpha(module, default_val):
if hasattr(module, 'up'):
return (module.alpha / module.up.weight.shape[1] if module.alpha else default_val)
elif hasattr(module, 'dim'): #support for lyCORIS
return (module.alpha / module.dim if module.alpha else default_val)
else:
return default_val
def check_lycoris_end_layer(lora_layer_name: str, res, num_loras):
if lora_layer_name.endswith("_11_mlp_fc2") or lora_layer_name.endswith("_11_1_proj_out"):
import composable_lora as lora_controller
if lora_layer_name.endswith("_11_mlp_fc2"): # lyCORIS maybe doesn't has _11_mlp_fc2 layer
lora_controller.text_model_encoder_counter += 1
if lora_controller.text_model_encoder_counter == (len(lora_controller.prompt_loras) + lora_controller.num_batches) * num_loras:
lora_controller.text_model_encoder_counter = 0
if lora_layer_name.endswith("_11_1_proj_out"): # lyCORIS maybe doesn't has _11_1_proj_out layer
lora_controller.diffusion_model_counter += res.shape[0]
if lora_controller.diffusion_model_counter >= (len(lora_controller.prompt_loras) + lora_controller.num_batches) * num_loras:
lora_controller.diffusion_model_counter = 0
lora_controller.add_step_counters()
def lycoris_get_multiplier(lycoris_model, lora_layer_name):
multiplier = 1.0
if hasattr(lycoris_model, 'te_multiplier'):
multiplier = (
lycoris_model.te_multiplier if 'transformer' in lora_layer_name[:20]
else lycoris_model.unet_multiplier
)
elif hasattr(lycoris_model, 'multiplier'):
multiplier = getattr(lycoris_model, 'multiplier', 1.0)
return multiplier
def lycoris_get_multiplier_normalized(lycoris_model, lora_layer_name):
multiplier = 1.0
if hasattr(lycoris_model, 'te_multiplier'):
te_multiplier = 1.0
unet_multiplier = lycoris_model.unet_multiplier / lycoris_model.te_multiplier
multiplier = (
te_multiplier if 'transformer' in lora_layer_name[:20]
else unet_multiplier
)
return multiplier
class FakeModule(torch.nn.Module):
def __init__(self, weight, func):
super().__init__()
self.weight = weight
self.func = func
def forward(self, x):
return self.func(x)
class FullModule:
def __init__(self):
self.weight = None
self.alpha = None
self.op = None
self.extra_args = {}
self.shape = None
self.up = None
def down(self, x):
return x
def inference(self, x):
return self.op(x, self.weight, **self.extra_args)
class IA3Module:
def __init__(self):
self.w = None
self.alpha = None
self.on_input = None
self.shape = None
self.op = None
self.extra_args = {}
def down(self, x):
return x
def inference(self, x):
return self.op(x, self.w, **self.extra_args)
def composable_forward(self, patch, alpha, multiplier, res):
patch = patch.to(res.dtype)
return res * (1 + patch * alpha * multiplier)
class LoraUpDownModule:
def __init__(self):
self.up_model = None
self.mid_model = None
self.down_model = None
self.alpha = None
self.dim = None
self.op = None
self.extra_args = {}
self.shape = None
self.bias = None
self.up = None
def down(self, x):
return x
def inference(self, x):
if hasattr(self, 'bias') and isinstance(self.bias, torch.Tensor):
out_dim = self.up_model.weight.size(0)
rank = self.down_model.weight.size(0)
rebuild_weight = (
self.up_model.weight.reshape(out_dim, -1) @ self.down_model.weight.reshape(rank, -1)
+ self.bias
).reshape(self.shape)
return self.op(
x, rebuild_weight,
bias=None,
**self.extra_args
)
else:
if self.mid_model is None:
return self.up_model(self.down_model(x))
else:
return self.up_model(self.mid_model(self.down_model(x)))
def make_weight_cp(t, wa, wb):
temp = torch.einsum('i j k l, j r -> i r k l', t, wb)
return torch.einsum('i j k l, i r -> r j k l', temp, wa)
class LoraHadaModule:
def __init__(self):
self.t1 = None
self.w1a = None
self.w1b = None
self.t2 = None
self.w2a = None
self.w2b = None
self.alpha = None
self.dim = None
self.op = None
self.extra_args = {}
self.shape = None
self.bias = None
self.up = None
def down(self, x):
return x
def inference(self, x):
if hasattr(self, 'bias') and isinstance(self.bias, torch.Tensor):
bias = self.bias
else:
bias = 0
if self.t1 is None:
return self.op(
x,
((self.w1a @ self.w1b) * (self.w2a @ self.w2b) + bias).view(self.shape),
bias=None,
**self.extra_args
)
else:
return self.op(
x,
(make_weight_cp(self.t1, self.w1a, self.w1b)
* make_weight_cp(self.t2, self.w2a, self.w2b) + bias).view(self.shape),
bias=None,
**self.extra_args
)
def make_kron(orig_shape, w1, w2):
if len(w2.shape) == 4:
w1 = w1.unsqueeze(2).unsqueeze(2)
w2 = w2.contiguous()
return torch.kron(w1, w2).reshape(orig_shape)
class LoraKronModule:
def __init__(self):
self.w1 = None
self.w1a = None
self.w1b = None
self.w2 = None
self.t2 = None
self.w2a = None
self.w2b = None
self._alpha = None
self.dim = None
self.op = None
self.extra_args = {}
self.shape = None
self.bias = None
self.up = None
@property
def alpha(self):
if self.w1a is None and self.w2a is None:
return None
else:
return self._alpha
@alpha.setter
def alpha(self, x):
self._alpha = x
def down(self, x):
return x
def inference(self, x):
if hasattr(self, 'bias') and isinstance(self.bias, torch.Tensor):
bias = self.bias
else:
bias = 0
if self.t2 is None:
return self.op(
x,
(torch.kron(self.w1, self.w2a@self.w2b) + bias).view(self.shape),
**self.extra_args
)
else:
# will raise NotImplemented Error
return self.op(
x,
(torch.kron(self.w1, make_weight_cp(self.t2, self.w2a, self.w2b)) + bias).view(self.shape),
**self.extra_args
)
def convert_lycoris(lycoris_module, sd_module):
result_module = getattr(lycoris_module, 'lyco_converted_lora_module', None)
if result_module is not None:
return result_module
if lycoris_module.__class__.__name__ == "LycoUpDownModule" or lycoris_module.__class__.__name__ == "LoraUpDownModule"\
or lycoris_module.__class__.__name__ == "NetworkModuleLora":
result_module = LoraUpDownModule()
if (type(sd_module) == torch.nn.Linear
or type(sd_module) == torch.nn.modules.linear.NonDynamicallyQuantizableLinear
or type(sd_module) == torch.nn.MultiheadAttention):
result_module.op = torch.nn.functional.linear
elif type(sd_module) == torch.nn.Conv2d:
result_module.op = torch.nn.functional.conv2d
result_module.extra_args = {
'stride': sd_module.stride,
'padding': sd_module.padding
}
else:
return None
result_module.up_model = lycoris_module.up_model
result_module.mid_model = lycoris_module.mid_model
result_module.down_model = lycoris_module.down_model
result_module.alpha = lycoris_module.alpha
result_module.dim = lycoris_module.dim
result_module.shape = lycoris_module.shape
result_module.bias = lycoris_module.bias
result_module.up = FakeModule(
result_module.up_model.weight,
result_module.inference
)
elif lycoris_module.__class__.__name__ == "FullModule" or lycoris_module.__class__.__name__ == "NetworkModuleFull":
result_module = FullModule()
result_module.weight = lycoris_module.weight.to(device=devices.device, dtype=devices.dtype)
result_module.alpha = lycoris_module.alpha
result_module.shape = lycoris_module.shape
result_module.up = FakeModule(
result_module.weight,
result_module.inference
)
if len(result_module.weight.shape)==2:
result_module.op = torch.nn.functional.linear
result_module.extra_args = {
'bias': None
}
else:
result_module.op = torch.nn.functional.conv2d
result_module.extra_args = {
'stride': sd_module.stride,
'padding': sd_module.padding,
'bias': None
}
setattr(lycoris_module, "lyco_converted_lora_module", result_module)
return result_module
elif lycoris_module.__class__.__name__ == "IA3Module" or lycoris_module.__class__.__name__ == "NetworkModuleIa3":
result_module = IA3Module()
result_module.w = lycoris_module.w
result_module.alpha = lycoris_module.alpha
result_module.on_input = lycoris_module.on_input
if hasattr(sd_module, 'weight'):
result_module.shape = sd_module.weight.shape
if (type(sd_module) == torch.nn.Linear
or type(sd_module) == torch.nn.modules.linear.NonDynamicallyQuantizableLinear
or type(sd_module) == torch.nn.MultiheadAttention):
result_module.op = torch.nn.functional.linear
elif type(sd_module) == torch.nn.Conv2d:
result_module.op = torch.nn.functional.conv2d
elif lycoris_module.__class__.__name__ == "LycoHadaModule" or lycoris_module.__class__.__name__ == "LoraHadaModule"\
or lycoris_module.__class__.__name__ == "NetworkModuleHada":
result_module = LoraHadaModule()
result_module.t1 = lycoris_module.t1
result_module.w1a = lycoris_module.w1a
result_module.w1b = lycoris_module.w1b
result_module.t2 = lycoris_module.t2
result_module.w2a = lycoris_module.w2a
result_module.w2b = lycoris_module.w2b
result_module.alpha = lycoris_module.alpha
result_module.dim = lycoris_module.dim
result_module.shape = lycoris_module.shape
result_module.bias = lycoris_module.bias
result_module.up = FakeModule(
result_module.t1 if result_module.t1 is not None else result_module.w1a,
result_module.inference
)
if (type(sd_module) == torch.nn.Linear
or type(sd_module) == torch.nn.modules.linear.NonDynamicallyQuantizableLinear
or type(sd_module) == torch.nn.MultiheadAttention):
result_module.op = torch.nn.functional.linear
elif type(sd_module) == torch.nn.Conv2d:
result_module.op = torch.nn.functional.conv2d
result_module.extra_args = {
'stride': sd_module.stride,
'padding': sd_module.padding
}
elif lycoris_module.__class__.__name__ == "LycoKronModule" or lycoris_module.__class__.__name__ == "LoraKronModule"\
or lycoris_module.__class__.__name__ == "NetworkModuleLokr" :
result_module = LoraKronModule()
result_module.w1 = lycoris_module.w1
result_module.w1a = lycoris_module.w1a
result_module.w1b = lycoris_module.w1b
result_module.w2 = lycoris_module.w2
result_module.t2 = lycoris_module.t2
result_module.w2a = lycoris_module.w2a
result_module.w2b = lycoris_module.w2b
result_module._alpha = lycoris_module._alpha
result_module.dim = lycoris_module.dim
result_module.shape = lycoris_module.shape
result_module.bias = lycoris_module.bias
result_module.up = FakeModule(
result_module.w1a if result_module.w1a is not None else result_module.w2a,
result_module.inference
)
if (any(isinstance(sd_module, torch_layer) for torch_layer in
[torch.nn.Linear, torch.nn.modules.linear.NonDynamicallyQuantizableLinear, torch.nn.MultiheadAttention])):
result_module.op = torch.nn.functional.linear
elif isinstance(sd_module, torch.nn.Conv2d):
result_module.op = torch.nn.functional.conv2d
result_module.extra_args = {
'stride': sd_module.stride,
'padding': sd_module.padding
}
if result_module is not None:
setattr(lycoris_module, "lyco_converted_lora_module", result_module)
return result_module
return None
def is_loha(m_lora):
return hasattr(m_lora, 'w1a') or hasattr(m_lora, 'w1b') or hasattr(m_lora, 'w2a') or hasattr(m_lora, 'w2b')
def pass_loha_to_gpu(m_loha):
if hasattr(m_loha, 'bias'):
if isinstance(m_loha.bias, torch.Tensor):
if not m_loha.bias.is_cuda:
to_cuda = m_loha.bias.to(device=devices.device)
to_del = m_loha.bias
m_loha.bias = None
del to_del
del m_loha.bias
m_loha.bias = to_cuda
if hasattr(m_loha, 't1'):
if isinstance(m_loha.t1, torch.Tensor):
if not m_loha.t1.is_cuda:
to_cuda = m_loha.t1.to(device=devices.device)
to_del = m_loha.t1
m_loha.t1 = None
del to_del
del m_loha.t1
m_loha.t1 = to_cuda
if hasattr(m_loha, 't2'):
if isinstance(m_loha.t2, torch.Tensor):
if not m_loha.t2.is_cuda:
to_cuda = m_loha.t2.to(device=devices.device)
to_del = m_loha.t2
m_loha.t2 = None
del to_del
del m_loha.t2
m_loha.t2 = to_cuda
if hasattr(m_loha, 'w'):
if isinstance(m_loha.w, torch.Tensor):
if not m_loha.w.is_cuda:
to_cuda = m_loha.w.to(device=devices.device)
to_del = m_loha.w
m_loha.w = None
del to_del
del m_loha.w
m_loha.w = to_cuda
if hasattr(m_loha, 'w1'):
if isinstance(m_loha.w1, torch.Tensor):
if not m_loha.w1.is_cuda:
to_cuda = m_loha.w1.to(device=devices.device)
to_del = m_loha.w1
m_loha.w1 = None
del to_del
del m_loha.w1
m_loha.w1 = to_cuda
if hasattr(m_loha, 'w1a'):
if isinstance(m_loha.w1a, torch.Tensor):
if not m_loha.w1a.is_cuda:
to_cuda = m_loha.w1a.to(device=devices.device)
to_del = m_loha.w1a
m_loha.w1a = None
del to_del
del m_loha.w1a
m_loha.w1a = to_cuda
if hasattr(m_loha, 'w1b'):
if isinstance(m_loha.w1b, torch.Tensor):
if not m_loha.w1b.is_cuda:
to_cuda = m_loha.w1b.to(device=devices.device)
to_del = m_loha.w1b
m_loha.w1b = None
del to_del
del m_loha.w1b
m_loha.w1b = to_cuda
if hasattr(m_loha, 'w2'):
if isinstance(m_loha.w2, torch.Tensor):
if not m_loha.w2.is_cuda:
to_cuda = m_loha.w2.to(device=devices.device)
to_del = m_loha.w2
m_loha.w2 = None
del to_del
del m_loha.w2
m_loha.w2 = to_cuda
if hasattr(m_loha, 'w2a'):
if isinstance(m_loha.w2a, torch.Tensor):
if not m_loha.w2a.is_cuda:
to_cuda = m_loha.w2a.to(device=devices.device)
to_del = m_loha.w2a
m_loha.w2a = None
del to_del
del m_loha.w2a
m_loha.w2a = to_cuda
if hasattr(m_loha, 'w2b'):
if isinstance(m_loha.w2b, torch.Tensor):
if not m_loha.w2b.is_cuda:
to_cuda = m_loha.w2b.to(device=devices.device)
to_del = m_loha.w2b
m_loha.w2b = None
del to_del
del m_loha.w2b
m_loha.w2b = to_cuda
has_webui_lycoris : bool = False
================================================
FILE: lora_ext.py
================================================
lora_Linear_forward = None
lora_Linear_load_state_dict = None
lora_Conv2d_forward = None
lora_Conv2d_load_state_dict = None
lora_MultiheadAttention_forward = None
lora_MultiheadAttention_load_state_dict = None
is_sd_1_5 = False
def get_loaded_lora():
global is_sd_1_5
if lora_Linear_forward is None:
load_lora_ext()
import lora
try:
import networks
is_sd_1_5 = True
except ImportError:
pass
if is_sd_1_5:
return networks.loaded_networks
return lora.loaded_loras
def load_lora_ext():
global is_sd_1_5
global lora_Linear_forward
global lora_Linear_load_state_dict
global lora_Conv2d_forward
global lora_Conv2d_load_state_dict
global lora_MultiheadAttention_forward
global lora_MultiheadAttention_load_state_dict
if lora_Linear_forward is not None:
return
import lora
is_sd_1_5 = False
try:
import networks
is_sd_1_5 = True
except ImportError:
pass
if is_sd_1_5:
if hasattr(networks, "network_Linear_forward"):
lora_Linear_forward = networks.network_Linear_forward
if hasattr(networks, "network_Linear_load_state_dict"):
lora_Linear_load_state_dict = networks.network_Linear_load_state_dict
if hasattr(networks, "network_Conv2d_forward"):
lora_Conv2d_forward = networks.network_Conv2d_forward
if hasattr(networks, "network_Conv2d_load_state_dict"):
lora_Conv2d_load_state_dict = networks.network_Conv2d_load_state_dict
if hasattr(networks, "network_MultiheadAttention_forward"):
lora_MultiheadAttention_forward = networks.network_MultiheadAttention_forward
if hasattr(networks, "network_MultiheadAttention_load_state_dict"):
lora_MultiheadAttention_load_state_dict = networks.network_MultiheadAttention_load_state_dict
else:
if hasattr(lora, "network_Linear_forward"):
lora_Linear_forward = lora.lora_Linear_forward
if hasattr(lora, "network_Linear_load_state_dict"):
lora_Linear_load_state_dict = lora.lora_Linear_load_state_dict
if hasattr(lora, "network_Conv2d_forward"):
lora_Conv2d_forward = lora.lora_Conv2d_forward
if hasattr(lora, "network_Conv2d_load_state_dict"):
lora_Conv2d_load_state_dict = lora.lora_Conv2d_load_state_dict
if hasattr(lora, "network_MultiheadAttention_forward"):
lora_MultiheadAttention_forward = lora.lora_MultiheadAttention_forward
if hasattr(lora, "network_MultiheadAttention_load_state_dict"):
lora_MultiheadAttention_load_state_dict = lora.lora_MultiheadAttention_load_state_dict
================================================
FILE: plot_helper.py
================================================
from dataclasses import dataclass
from typing import List
import io
import matplotlib
matplotlib.use('Agg')
import pandas as pd
from pandas.plotting._matplotlib.style import get_standard_colors
from PIL import Image
@dataclass
class YAxis:
name: str
columns: List[str]
@dataclass
class PlotDefinition:
title: str
x_axis: str
y_axis: List[YAxis]
def plot_lora_weight(lora_weights, lora_names):
data = pd.DataFrame(lora_weights, columns=lora_names)
ax = data.plot()
ax.set_xlabel("Steps")
ax.set_ylabel("LoRA weight")
ax.set_title("LoRA weight in all steps")
ax.legend(loc=0)
result_image = fig2img(ax)
matplotlib.pyplot.close(ax.figure)
del ax # RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`). Consider using `matplotlib.pyplot.close()`.
return result_image
def fig2img(fig):
buf = io.BytesIO()
fig.figure.savefig(buf)
buf.seek(0)
img = Image.open(buf)
return img
def plot_graph(
data: pd.DataFrame,
plot_definition: PlotDefinition,
spacing: float = 0.1,
):
colors = get_standard_colors(num_colors=(len(plot_definition.y_axis) + 7))
loss_color = colors[0]
avg_colors = colors[1:]
for i, yi in enumerate(plot_definition.y_axis):
if i == 0:
ax = data.plot(
x=plot_definition.x_axis,
y=yi.columns,
title=plot_definition.title,
color=[loss_color] * len(yi.columns)
)
ax.set_ylabel(ylabel=yi.name)
else:
# Multiple y-axes
ax_new = ax.twinx()
ax_new.spines["right"].set_position(("axes", 1 + spacing * (i - 1)))
data.plot(
ax=ax_new,
x=plot_definition.x_axis,
y=yi.columns,
color=[avg_colors[yl] for yl in range(len(yi.columns))]
)
ax_new.set_ylabel(ylabel=yi.name)
ax.legend(loc=0)
return ax
================================================
FILE: scripts/composable_lora_script.py
================================================
#
# Composable-Diffusion with Lora
#
import torch
import gradio as gr
import composable_lora
import composable_lora_function_handler
import lora_ext
import modules.scripts as scripts
from modules import script_callbacks
from modules.processing import StableDiffusionProcessing
def unload():
torch.nn.Linear.forward = torch.nn.Linear_forward_before_lora
torch.nn.Conv2d.forward = torch.nn.Conv2d_forward_before_lora
torch.nn.MultiheadAttention.forward = torch.nn.MultiheadAttention_forward_before_lora
if not hasattr(composable_lora, 'Linear_forward_before_clora'):
if hasattr(torch.nn, 'Linear_forward_before_lyco'):
composable_lora.Linear_forward_before_clora = torch.nn.Linear_forward_before_lyco
else:
composable_lora.Linear_forward_before_clora = torch.nn.Linear.forward
if not hasattr(composable_lora, 'Conv2d_forward_before_clora'):
if hasattr(torch.nn, 'Conv2d_forward_before_lyco'):
composable_lora.Conv2d_forward_before_clora = torch.nn.Conv2d_forward_before_lyco
else:
composable_lora.Conv2d_forward_before_clora = torch.nn.Conv2d.forward
if not hasattr(composable_lora, 'MultiheadAttention_forward_before_clora'):
if hasattr(torch.nn, 'MultiheadAttention_forward_before_lyco'):
composable_lora.MultiheadAttention_forward_before_clora = torch.nn.MultiheadAttention_forward_before_lyco
else:
composable_lora.MultiheadAttention_forward_before_clora = torch.nn.MultiheadAttention.forward
if not hasattr(torch.nn, 'Linear_forward_before_lora'):
if hasattr(torch.nn, 'Linear_forward_before_lyco'):
torch.nn.Linear_forward_before_lora = torch.nn.Linear_forward_before_lyco
else:
torch.nn.Linear_forward_before_lora = torch.nn.Linear.forward
if not hasattr(torch.nn, 'Conv2d_forward_before_lora'):
if hasattr(torch.nn, 'Conv2d_forward_before_lyco'):
torch.nn.Conv2d_forward_before_lora = torch.nn.Conv2d_forward_before_lyco
else:
torch.nn.Conv2d_forward_before_lora = torch.nn.Conv2d.forward
if not hasattr(torch.nn, 'MultiheadAttention_forward_before_lora'):
if hasattr(torch.nn, 'MultiheadAttention_forward_before_lyco'):
torch.nn.MultiheadAttention_forward_before_lora = torch.nn.MultiheadAttention_forward_before_lyco
else:
torch.nn.MultiheadAttention_forward_before_lora = torch.nn.MultiheadAttention.forward
if hasattr(torch.nn, 'Linear_forward_before_lyco'):
composable_lora.lyco_notfound = False
else:
composable_lora.lyco_notfound = True
#torch.nn.Linear.forward = composable_lora.lora_Linear_forward
#torch.nn.Conv2d.forward = composable_lora.lora_Conv2d_forward
def check_install_state():
if not hasattr(composable_lora, "noop"):
import warnings
warnings.warn( #NOTICE: You Must Restart the WebUI after Install composable_lora!
"module 'composable_lora' not found! Please reinstall composable_lora and restart the WebUI.")
script_callbacks.on_script_unloaded(unload)
if hasattr(script_callbacks, "on_before_reload"):
script_callbacks.on_before_reload(check_install_state)
script_callbacks.on_before_ui(check_install_state)
class ComposableLoraScript(scripts.Script):
def title(self):
return "Composable Lora"
def show(self, is_img2img):
return scripts.AlwaysVisible
def ui(self, is_img2img):
with gr.Group():
with gr.Accordion("Composable Lora", open=False):
if not hasattr(composable_lora, "noop"):
gr.Markdown('<span style="color:red">Error! Composable Lora install failed! Please reinstall composable_lora and restart the WebUI.</span>')
enabled = gr.Checkbox(value=False, label="Enabled")
opt_composable_with_step = gr.Checkbox(value=False, label="Composable LoRA with step")
opt_uc_text_model_encoder = gr.Checkbox(value=False, label="Use Lora in uc text model encoder")
opt_uc_diffusion_model = gr.Checkbox(value=False, label="Use Lora in uc diffusion model")
opt_plot_lora_weight = gr.Checkbox(value=False, label="Plot the LoRA weight in all steps")
opt_single_no_uc = gr.Checkbox(value=False, label="Don't use LoRA in uc if there're no subprompts")
opt_hires_step_as_global = gr.Checkbox(value=False, label="Treat hires step as global step")
return [enabled, opt_composable_with_step, opt_uc_text_model_encoder, opt_uc_diffusion_model, opt_plot_lora_weight, opt_single_no_uc, opt_hires_step_as_global]
def process(self, p: StableDiffusionProcessing,
enabled: bool,
opt_composable_with_step: bool,
opt_uc_text_model_encoder: bool, opt_uc_diffusion_model:
bool, opt_plot_lora_weight: bool, opt_single_no_uc:
bool, opt_hires_step_as_global: bool):
lora_ext.load_lora_ext()
if lora_ext.is_sd_1_5:
import composable_lycoris
if composable_lycoris.has_webui_lycoris:
print("Error! in sd webui 1.5, composable-lora not support with sd-webui-lycoris extension.")
composable_lora.enabled = enabled
composable_lora.opt_uc_text_model_encoder = opt_uc_text_model_encoder
composable_lora.opt_uc_diffusion_model = opt_uc_diffusion_model
composable_lora.opt_composable_with_step = opt_composable_with_step
composable_lora.opt_plot_lora_weight = opt_plot_lora_weight
composable_lora.opt_single_no_uc = opt_single_no_uc
composable_lora.opt_hires_step_as_global = opt_hires_step_as_global
composable_lora.num_batches = p.batch_size
if hasattr(p, "hr_second_pass_steps"):
hr_second_pass_steps = p.hr_second_pass_steps
else:
hr_second_pass_steps = 0
if opt_hires_step_as_global:
composable_lora.num_steps = p.steps + hr_second_pass_steps
else:
composable_lora.num_steps = p.steps
composable_lora.num_hires_steps = hr_second_pass_steps
if not hasattr(composable_lora, "noop"):
raise ModuleNotFoundError( #NOTICE: You Must Restart the WebUI after Install composable_lora!
"No module named 'composable_lora'! Please reinstall composable_lora and restart the WebUI.")
composable_lora_function_handler.on_enable()
composable_lora.reset_step_counters()
prompt = p.all_prompts[0]
composable_lora.negative_prompt = p.all_negative_prompts[0]
composable_lora.load_prompt_loras(prompt)
composable_lora.sd_processing = p
def process_batch(self, p: StableDiffusionProcessing, *args, **kwargs):
composable_lora.sd_processing = p
composable_lora.reset_counters()
def postprocess(self, p, processed, *args):
if not hasattr(composable_lora, "noop"):
raise ModuleNotFoundError( #NOTICE: You Must Restart the WebUI after Install composable_lora!
"No module named 'composable_lora'! Please reinstall composable_lora and restart the WebUI.")
composable_lora_function_handler.on_disable()
if composable_lora.enabled:
if composable_lora.opt_plot_lora_weight:
processed.images.extend([composable_lora.plot_lora()])
gitextract_xrqbioiw/
├── .github/
│ └── FUNDING.yml
├── .gitignore
├── .vscode/
│ └── settings.json
├── LICENSE
├── README.ja.md
├── README.md
├── README.zh-cn.md
├── README.zh-tw.md
├── composable_lora.py
├── composable_lora_function_handler.py
├── composable_lora_step.py
├── composable_lycoris.py
├── lora_ext.py
├── plot_helper.py
└── scripts/
└── composable_lora_script.py
SYMBOL INDEX (126 symbols across 7 files)
FILE: composable_lora.py
function lora_forward (line 10) | def lora_forward(compvis_module: Union[torch.nn.Conv2d, torch.nn.Linear,...
function load_prompt_loras (line 87) | def load_prompt_loras(prompt: str):
function reset_counters (line 132) | def reset_counters():
function reset_step_counters (line 144) | def reset_step_counters():
function add_step_counters (line 151) | def add_step_counters():
function log_lora (line 170) | def log_lora():
function plot_lora (line 218) | def plot_lora():
function lora_backup_weights (line 235) | def lora_backup_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, to...
function clear_cache_lora (line 251) | def clear_cache_lora(compvis_module : Union[torch.nn.Conv2d, torch.nn.Li...
function apply_composable_lora (line 295) | def apply_composable_lora(lora_layer_name, m_lora, module, m_type: str, ...
function lora_Linear_forward (line 428) | def lora_Linear_forward(self, input):
function lora_Conv2d_forward (line 471) | def lora_Conv2d_forward(self, input):
function lora_MultiheadAttention_forward (line 515) | def lora_MultiheadAttention_forward(self, input):
function noop (line 560) | def noop():
function should_reload (line 563) | def should_reload():
FILE: composable_lora_function_handler.py
function on_enable (line 5) | def on_enable():
function on_disable (line 44) | def on_disable():
FILE: composable_lora_step.py
class Runable (line 15) | class Runable:
method __init__ (line 20) | def __init__(self, code : str, code_name : str = "<prompt>"):
method compile_self (line 29) | def compile_self(self):
method convertExpr2Expression (line 46) | def convertExpr2Expression(self, expr : ast.Expr):
method run (line 53) | def run(self, module):
class LoRA_data (line 63) | class LoRA_data:
method __init__ (line 64) | def __init__(self, name : str, weight : float):
method __repr__ (line 67) | def __repr__(self):
method __str__ (line 69) | def __str__(self):
class LoRA_Weight_CMD (line 72) | class LoRA_Weight_CMD:
method getWeight (line 73) | def getWeight(self, weight : float, progress: float, step : int, all_s...
class LoRA_Weight_decrement (line 76) | class LoRA_Weight_decrement(LoRA_Weight_CMD):
method getWeight (line 77) | def getWeight(self, weight : float, progress: float, step : int, all_s...
class LoRA_Weight_increment (line 80) | class LoRA_Weight_increment(LoRA_Weight_CMD):
method getWeight (line 81) | def getWeight(self, weight : float, progress: float, step : int, all_s...
function raise_ (line 84) | def raise_(ex):
function not_allow (line 86) | def not_allow(name):
class LoRA_Weight_eval (line 121) | class LoRA_Weight_eval(LoRA_Weight_CMD):
method __init__ (line 122) | def __init__(self, command : str, code_name : str = "<prompt>"):
method getWeight (line 131) | def getWeight(self, weight : float, progress: float, step : int, all_s...
method __repr__ (line 168) | def __repr__(self):
method __str__ (line 170) | def __str__(self):
class LoRA_Controller_Base (line 173) | class LoRA_Controller_Base:
method __init__ (line 174) | def __init__(self):
method getWeight (line 177) | def getWeight(self, weight : float, progress: float, step : int, all_s...
method test (line 183) | def test(self, test_lora : str, step : int, all_step : int, custom_sco...
class LoRA_Controller (line 187) | class LoRA_Controller(LoRA_Controller_Base):
method __init__ (line 188) | def __init__(self, name : str, weight : float):
method test (line 192) | def test(self, test_lora : str, step : int, all_step : int, custom_sco...
method __repr__ (line 196) | def __repr__(self):
method __str__ (line 198) | def __str__(self):
class LoRA_StartEnd_Controller (line 202) | class LoRA_StartEnd_Controller(LoRA_Controller_Base):
method __init__ (line 203) | def __init__(self, name : str, weight : float, start : Union[float, in...
method test (line 209) | def test(self, test_lora : str, step : int, all_step : int, custom_sco...
method __repr__ (line 224) | def __repr__(self):
method __str__ (line 226) | def __str__(self):
class LoRA_Switcher_Controller (line 230) | class LoRA_Switcher_Controller(LoRA_Controller_Base):
method __init__ (line 231) | def __init__(self, lora_dist : List[LoRA_data], start : Union[float, i...
method test (line 240) | def test(self, test_lora : str, step : int, all_step : int, custom_sco...
method __repr__ (line 256) | def __repr__(self):
method __str__ (line 258) | def __str__(self):
function parse_step_rendering_syntax (line 262) | def parse_step_rendering_syntax(prompt: str):
function check_lora_weight (line 276) | def check_lora_weight(controllers : List[LoRA_Controller_Base], test_lor...
function get_lora_list (line 284) | def get_lora_list(prompt: str):
function get_or_list (line 299) | def get_or_list(prompt: str):
function escape_prompt (line 312) | def escape_prompt(prompt : str):
class MySearchResult (line 326) | class MySearchResult:
method __init__ (line 327) | def __init__(self):
function extra_net_split (line 331) | def extra_net_split(input_str : str, pattern : str):
function extra_net_re_search (line 371) | def extra_net_re_search(pattern : Union[str, re.Pattern[str]], input_str...
function unescape_string (line 411) | def unescape_string(input_string : str):
function get_LoRA_Controllers (line 442) | def get_LoRA_Controllers(prompt: str):
function get_all_step_rendering_in_prompt (line 583) | def get_all_step_rendering_in_prompt(input_prompt : str):
FILE: composable_lycoris.py
function lycoris_forward (line 8) | def lycoris_forward(compvis_module: Union[torch.nn.Conv2d, torch.nn.Line...
function composable_forward (line 65) | def composable_forward(module, patch, alpha, multiplier, res):
function normalize_lora_name (line 72) | def normalize_lora_name(lora_name):
function get_lora_inference (line 76) | def get_lora_inference(module, input):
function get_lora_patch (line 88) | def get_lora_patch(module, input, res, lora_layer_name):
function get_lora_alpha (line 120) | def get_lora_alpha(module, default_val):
function check_lycoris_end_layer (line 128) | def check_lycoris_end_layer(lora_layer_name: str, res, num_loras):
function lycoris_get_multiplier (line 141) | def lycoris_get_multiplier(lycoris_model, lora_layer_name):
function lycoris_get_multiplier_normalized (line 152) | def lycoris_get_multiplier_normalized(lycoris_model, lora_layer_name):
class FakeModule (line 163) | class FakeModule(torch.nn.Module):
method __init__ (line 164) | def __init__(self, weight, func):
method forward (line 169) | def forward(self, x):
class FullModule (line 172) | class FullModule:
method __init__ (line 173) | def __init__(self):
method down (line 181) | def down(self, x):
method inference (line 184) | def inference(self, x):
class IA3Module (line 187) | class IA3Module:
method __init__ (line 188) | def __init__(self):
method down (line 196) | def down(self, x):
method inference (line 199) | def inference(self, x):
method composable_forward (line 202) | def composable_forward(self, patch, alpha, multiplier, res):
class LoraUpDownModule (line 206) | class LoraUpDownModule:
method __init__ (line 207) | def __init__(self):
method down (line 219) | def down(self, x):
method inference (line 222) | def inference(self, x):
function make_weight_cp (line 241) | def make_weight_cp(t, wa, wb):
class LoraHadaModule (line 245) | class LoraHadaModule:
method __init__ (line 246) | def __init__(self):
method down (line 261) | def down(self, x):
method inference (line 264) | def inference(self, x):
function make_kron (line 286) | def make_kron(orig_shape, w1, w2):
class LoraKronModule (line 292) | class LoraKronModule:
method __init__ (line 293) | def __init__(self):
method alpha (line 310) | def alpha(self):
method alpha (line 317) | def alpha(self, x):
method down (line 320) | def down(self, x):
method inference (line 323) | def inference(self, x):
function convert_lycoris (line 343) | def convert_lycoris(lycoris_module, sd_module):
function is_loha (line 468) | def is_loha(m_lora):
function pass_loha_to_gpu (line 471) | def pass_loha_to_gpu(m_loha):
FILE: lora_ext.py
function get_loaded_lora (line 8) | def get_loaded_lora():
function load_lora_ext (line 22) | def load_lora_ext():
FILE: plot_helper.py
class YAxis (line 11) | class YAxis:
class PlotDefinition (line 16) | class PlotDefinition:
function plot_lora_weight (line 21) | def plot_lora_weight(lora_weights, lora_names):
function fig2img (line 33) | def fig2img(fig):
function plot_graph (line 41) | def plot_graph(
FILE: scripts/composable_lora_script.py
function unload (line 14) | def unload():
function check_install_state (line 63) | def check_install_state():
class ComposableLoraScript (line 74) | class ComposableLoraScript(scripts.Script):
method title (line 75) | def title(self):
method show (line 78) | def show(self, is_img2img):
method ui (line 81) | def ui(self, is_img2img):
method process (line 95) | def process(self, p: StableDiffusionProcessing,
method process_batch (line 136) | def process_batch(self, p: StableDiffusionProcessing, *args, **kwargs):
method postprocess (line 140) | def postprocess(self, p, processed, *args):
Condensed preview — 15 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (186K chars).
[
{
"path": ".github/FUNDING.yml",
"chars": 783,
"preview": "# These are supported funding model platforms\n\n#github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., ["
},
{
"path": ".gitignore",
"chars": 1799,
"preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
},
{
"path": ".vscode/settings.json",
"chars": 145,
"preview": "{\n \"python.envFile\": \"${workspaceFolder}/.env\",\n \"python.defaultInterpreterPath\": \"${workspaceFolder}/../../sd.web"
},
{
"path": "LICENSE",
"chars": 35846,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n "
},
{
"path": "README.ja.md",
"chars": 8191,
"preview": "[](https://www.python.org/downloads/)\n[](https://www.python.org/downloads/)\n[](https://www.python.org/downloads/)\n[](https://www.python.org/downloads/)\n[:\n #backup original forward methods\n "
},
{
"path": "composable_lora_step.py",
"chars": 27102,
"preview": "from typing import List, Union\nimport re\nimport ast\nimport copy\nimport json\nimport math\nimport sys\nimport traceback\nimpo"
},
{
"path": "composable_lycoris.py",
"chars": 21933,
"preview": "from typing import Optional, Union\nimport re\nimport torch\nimport lora_ext\nfrom modules import shared, devices\n\n#support "
},
{
"path": "lora_ext.py",
"chars": 2709,
"preview": "lora_Linear_forward = None\nlora_Linear_load_state_dict = None\nlora_Conv2d_forward = None\nlora_Conv2d_load_state_dict = N"
},
{
"path": "plot_helper.py",
"chars": 2195,
"preview": "from dataclasses import dataclass\nfrom typing import List\nimport io\nimport matplotlib\nmatplotlib.use('Agg')\nimport panda"
},
{
"path": "scripts/composable_lora_script.py",
"chars": 7282,
"preview": "#\n# Composable-Diffusion with Lora\n#\nimport torch\nimport gradio as gr\n\nimport composable_lora\nimport composable_lora_fun"
}
]
About this extraction
This page contains the full source code of the a2569875/stable-diffusion-webui-composable-lora GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 15 files (164.9 KB), approximately 45.9k tokens, and a symbol index with 126 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.