Initial commit
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
__pycache__
|
||||
/venv
|
||||
.vscode
|
||||
*.ckpt
|
||||
*.pth
|
||||
types
|
||||
models
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
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 General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<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 General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,199 @@
|
||||
# Node to use APISR upscale models in ComfyUI
|
||||
|
||||
# Original repository:
|
||||
https://github.com/Kiteretsu77/APISR
|
||||
|
||||
<p align="center">
|
||||
<img src="__assets__/logo.png" height="100">
|
||||
</p>
|
||||
|
||||
## APISR: Anime Production Inspired Real-World Anime Super-Resolution (CVPR 2024)
|
||||
APISR aims at restoring and enhancing low-quality low-resolution anime images and video sources with various degradations from real-world scenarios.
|
||||
|
||||
[](https://arxiv.org/abs/2403.01598)   [](https://huggingface.co/spaces/HikariDawn/APISR)
|
||||
|
||||
👀 [**Visualization**](#Visualization) **|** 🔥 [Update](#Update) **|** 🔧 [Installation](#installation) **|** 🏰 [**Model Zoo**](docs/model_zoo.md) **|** ⚡ [Inference](#inference) **|** 🧩 [Dataset Curation](#dataset_curation) **|** 💻 [Train](#train)
|
||||
|
||||
|
||||
<p align="center">
|
||||
<img src="__assets__/workflow.png" style="border-radius: 15px">
|
||||
</p>
|
||||
|
||||
|
||||
:star: If you like APISR, please help star this repo. Thanks! :hugs:
|
||||
|
||||
|
||||
|
||||
<!---------------------------------------- Visualization ---------------------------------------->
|
||||
## <a name="Visualization"></a> Visualization (Click them for the best view!) 👀
|
||||
|
||||
<!-- Kiteret: https://imgsli.com/MjQ1NzE0 -->
|
||||
<!-- EVA: https://imgsli.com/MjQ1NzIx -->
|
||||
<!-- Pokemon: https://imgsli.com/MjQ1NzIy -->
|
||||
<!-- Pokemon2: https://imgsli.com/MjQ1NzM5 -->
|
||||
<!-- Gundam0079: https://imgsli.com/MjQ1NzIz -->
|
||||
<!-- Gundam0079 #2: https://imgsli.com/MjQ1NzMw -->
|
||||
<!-- f91: https://imgsli.com/MjQ1NzMx -->
|
||||
<!-- wataru: https://imgsli.com/MjQ1NzMy -->
|
||||
|
||||
[<img src="__assets__/visual_results/0079_visual.png" height="223px"/>](https://imgsli.com/MjQ1NzIz) [<img src="__assets__/visual_results/0079_2_visual.png" height="223px"/>](https://imgsli.com/MjQ1NzMw)
|
||||
|
||||
[<img src="__assets__/visual_results/pokemon_visual.png" height="223px"/>](https://imgsli.com/MjQ1NzIy) [<img src="__assets__/visual_results/pokemon2_visual.png" height="223px"/>](https://imgsli.com/MjQ1NzM5)
|
||||
|
||||
[<img src="__assets__/visual_results/eva_visual.png" height="223px"/>](https://imgsli.com/MjQ1NzIx) [<img src="__assets__/visual_results/kiteret_visual.png" height="223px"/>](https://imgsli.com/MjQ1NzE0)
|
||||
|
||||
[<img src="__assets__/visual_results/f91_visual.png" height="223px"/>](https://imgsli.com/MjQ1NzMx) [<img src="__assets__/visual_results/wataru_visual.png" height="223px"/>](https://imgsli.com/MjQ1NzMy)
|
||||
|
||||
|
||||
|
||||
<p align="center">
|
||||
<img src="__assets__/AVC_RealLQ_comparison.png">
|
||||
</p>
|
||||
<!-------------------------------------------- --------------------------------------------------->
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## <a name="Update"></a>Update 🔥🔥🔥
|
||||
- [x] Release Paper version implementation of APISR
|
||||
- [x] Release different upscaler factor weight (for 2x, 4x and more)
|
||||
- [x] Gradio demo (maybe online)
|
||||
|
||||
|
||||
|
||||
## <a name="installation"></a> Installation 🔧
|
||||
|
||||
```shell
|
||||
git clone git@github.com:Kiteretsu77/APISR.git
|
||||
cd APISR
|
||||
|
||||
# Create conda env
|
||||
conda create -n APISR python=3.10
|
||||
conda activate APISR
|
||||
|
||||
# Install Pytorch and other packages needed
|
||||
pip install torch==2.1.1 torchvision==0.16.1 torchaudio==2.1.1 --index-url https://download.pytorch.org/whl/cu118
|
||||
pip install -r requirements.txt
|
||||
|
||||
|
||||
# To be absolutely sure that the tensorboard can execute. I recommend the following CMD from "https://github.com/pytorch/pytorch/issues/22676#issuecomment-534882021"
|
||||
pip uninstall tb-nightly tensorboard tensorflow-estimator tensorflow-gpu tf-estimator-nightly
|
||||
pip install tensorflow
|
||||
|
||||
# Install FFMPEG [Only needed for training and dataset curation stage; inference only does not need ffmpeg] (the following is for the linux system, Windows users can download ffmpeg from https://ffmpeg.org/download.html)
|
||||
sudo apt install ffmpeg
|
||||
```
|
||||
|
||||
|
||||
|
||||
## <a name="inference"></a> Gradio Fast Inference ⚡⚡⚡
|
||||
Gradio option doesn't need to prepare the weight from the user side but they can only process one image each time.
|
||||
|
||||
An online demo can be found at https://huggingface.co/spaces/HikariDawn/APISR.
|
||||
|
||||
```shell
|
||||
python gradio_apisr.py
|
||||
```
|
||||
|
||||
|
||||
## <a name="regular_inference"></a> Regular Inference ⚡⚡
|
||||
|
||||
1. Download the model weight from [**model zoo**](docs/model_zoo.md) and **put the weight to "pretrained" folder**.
|
||||
|
||||
2. Then, Execute
|
||||
```shell
|
||||
python test_code/inference.py --input_dir XXX --weight_path XXX --store_dir XXX
|
||||
```
|
||||
If the weight you download is paper weight, the default argument of test_code/inference.py is capable of executing sample images from "__assets__" folder
|
||||
|
||||
|
||||
|
||||
## <a name="dataset_curation"></a> Dataset Curation 🧩
|
||||
Our dataset curation pipeline is under **dataset_curation_pipeline** folder.
|
||||
|
||||
You can collect your own dataset by sending videos into the pipeline and get the least compressed and the most informative images from the video sources.
|
||||
|
||||
1. Download [IC9600](https://github.com/tinglyfeng/IC9600?tab=readme-ov-file) weight (ck.pth) from https://drive.google.com/drive/folders/1N3FSS91e7FkJWUKqT96y_zcsG9CRuIJw and place it at "pretrained/" folder (else, you can define a different **--IC9600_pretrained_weight_path** in the following collect.py execution)
|
||||
|
||||
2. With a folder with video sources, you can execute the following to get a basic dataset (with **ffmpeg** installed):
|
||||
|
||||
```shell
|
||||
python dataset_curation_pipeline/collect.py --video_folder_dir XXX --save_dir XXX
|
||||
```
|
||||
|
||||
3. Once you get an image dataset with various aspect ratios and resolutions, you can run the following scripts
|
||||
|
||||
Be careful to check **full_patch_source** && **degrade_hr_dataset_path** && **train_hr_dataset_path** (we will use these path in **opt.py** setting during training stage)
|
||||
|
||||
In order to decrease memory utilization and increase training efficiency, we pre-process all time-consuming pseudo-GT (**train_hr_dataset_path**) at the dataset preparation stage.
|
||||
|
||||
But in order to create a natural input for prediction-oriented compression, in every epoch, the degradation started from the uncropped GT (**full_patch_source**), and LR synthetic images are concurrently stored. The cropped HR GT dataset (**degrade_hr_dataset_path**) and cropped pseudo-GT (**train_hr_dataset_path**) are fixed in the dataset preparation stage and won't be modified during training.
|
||||
|
||||
```shell
|
||||
bash scripts/prepare_datasets.sh
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
## <a name="train"></a> Train 💻
|
||||
|
||||
**The whole training process can be done in one RTX3090/4090!**
|
||||
|
||||
1. Prepare a dataset (AVC/API) which follows step 2 & 3 in [**Dataset Curation**](#dataset_curation)
|
||||
|
||||
In total, you will have 3 folders prepared before executing the following commands:
|
||||
|
||||
--> **full_patch_source**: uncropped GT
|
||||
|
||||
--> **degrade_hr_dataset_path**: cropped GT
|
||||
|
||||
--> **train_hr_dataset_path**: cropped Pseudo-GT
|
||||
|
||||
|
||||
2. Train: Please check **opt.py** carefully to setup parameters you want (modifying **Frequently Changed Setting** is usually enough)
|
||||
|
||||
**Step1** (Net **L1** loss training): Run
|
||||
```shell
|
||||
python train_code/train.py
|
||||
```
|
||||
The trained model weights will be inside the folder 'saved_models' (same to checkpoints)
|
||||
|
||||
**Step2** (GAN **Adversarial** Training):
|
||||
1. Change opt['architecture'] in **opt.py** to "GRLGAN" and change **batch size** if you need. BTW, I don't think that, for personal training, it is needed to train 300K iter for GAN. I did that in order to follow the same setting as in AnimeSR and VQDSR, but **100K ~ 130K** should have a decent visual result.
|
||||
|
||||
2. Following previous works, GAN should start from L1 loss pre-trained network, so please carry a **pretrained_path** (the default path below should be fine)
|
||||
```shell
|
||||
python train_code/train.py --pretrained_path saved_models/grl_best_generator.pth
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Related Projects
|
||||
1. Fast Anime SR acceleration: https://github.com/Kiteretsu77/FAST_Anime_VSR
|
||||
2. My previous paper (VCISR - WACV2024) as the baseline method: https://github.com/Kiteretsu77/VCISR-official
|
||||
|
||||
|
||||
## Citation
|
||||
Please cite us if our work is useful for your research.
|
||||
```
|
||||
@article{wang2024apisr,
|
||||
title={APISR: Anime Production Inspired Real-World Anime Super-Resolution},
|
||||
author={Wang, Boyang and Yang, Fengyu and Yu, Xihang and Zhang, Chao and Zhao, Hanbin},
|
||||
journal={arXiv preprint arXiv:2403.01598},
|
||||
year={2024}
|
||||
}
|
||||
```
|
||||
|
||||
## Disclaimer
|
||||
This project is released for academic use only. We disclaim responsibility for the distribution of the dataset. Users are solely liable for their actions.
|
||||
The project contributors are not legally affiliated with, nor accountable for, users' behaviors.
|
||||
|
||||
|
||||
## License
|
||||
This project is released under the [GPL 3.0 license](LICENSE).
|
||||
|
||||
## Contact
|
||||
If you have any questions, please feel free to contact me at hikaridawn412316@gmail.com or boyangwa@umich.edu.
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
||||
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
||||
@@ -0,0 +1,189 @@
|
||||
# Github Repository: https://github.com/bilibili/ailab/blob/main/Real-CUGAN/README_EN.md
|
||||
# Code snippet (with certain modificaiton) from: https://github.com/bilibili/ailab/blob/main/Real-CUGAN/VapourSynth/upcunet_v3_vs.py
|
||||
|
||||
import torch
|
||||
from torch import nn as nn
|
||||
from torch.nn import functional as F
|
||||
import os, sys
|
||||
import numpy as np
|
||||
from time import time as ttime, sleep
|
||||
|
||||
|
||||
class UNet_Full(nn.Module):
|
||||
|
||||
def __init__(self):
|
||||
super(UNet_Full, self).__init__()
|
||||
self.unet1 = UNet1(3, 3, deconv=True)
|
||||
self.unet2 = UNet2(3, 3, deconv=False)
|
||||
|
||||
def forward(self, x):
|
||||
n, c, h0, w0 = x.shape
|
||||
|
||||
ph = ((h0 - 1) // 2 + 1) * 2
|
||||
pw = ((w0 - 1) // 2 + 1) * 2
|
||||
x = F.pad(x, (18, 18 + pw - w0, 18, 18 + ph - h0), 'reflect') # In order to ensure that it can be divided by 2
|
||||
|
||||
x1 = self.unet1(x)
|
||||
x2 = self.unet2(x1)
|
||||
|
||||
x1 = F.pad(x1, (-20, -20, -20, -20))
|
||||
output = torch.add(x2, x1)
|
||||
|
||||
if (w0 != pw or h0 != ph):
|
||||
output = output[:, :, :h0 * 2, :w0 * 2]
|
||||
|
||||
return output
|
||||
|
||||
|
||||
class SEBlock(nn.Module):
|
||||
def __init__(self, in_channels, reduction=8, bias=False):
|
||||
super(SEBlock, self).__init__()
|
||||
self.conv1 = nn.Conv2d(in_channels, in_channels // reduction, 1, 1, 0, bias=bias)
|
||||
self.conv2 = nn.Conv2d(in_channels // reduction, in_channels, 1, 1, 0, bias=bias)
|
||||
|
||||
def forward(self, x):
|
||||
if ("Half" in x.type()): # torch.HalfTensor/torch.cuda.HalfTensor
|
||||
x0 = torch.mean(x.float(), dim=(2, 3), keepdim=True).half()
|
||||
else:
|
||||
x0 = torch.mean(x, dim=(2, 3), keepdim=True)
|
||||
x0 = self.conv1(x0)
|
||||
x0 = F.relu(x0, inplace=True)
|
||||
x0 = self.conv2(x0)
|
||||
x0 = torch.sigmoid(x0)
|
||||
x = torch.mul(x, x0)
|
||||
return x
|
||||
|
||||
class UNetConv(nn.Module):
|
||||
def __init__(self, in_channels, mid_channels, out_channels, se):
|
||||
super(UNetConv, self).__init__()
|
||||
self.conv = nn.Sequential(
|
||||
nn.Conv2d(in_channels, mid_channels, 3, 1, 0),
|
||||
nn.LeakyReLU(0.1, inplace=True),
|
||||
nn.Conv2d(mid_channels, out_channels, 3, 1, 0),
|
||||
nn.LeakyReLU(0.1, inplace=True),
|
||||
)
|
||||
if se:
|
||||
self.seblock = SEBlock(out_channels, reduction=8, bias=True)
|
||||
else:
|
||||
self.seblock = None
|
||||
|
||||
def forward(self, x):
|
||||
z = self.conv(x)
|
||||
if self.seblock is not None:
|
||||
z = self.seblock(z)
|
||||
return z
|
||||
|
||||
class UNet1(nn.Module):
|
||||
def __init__(self, in_channels, out_channels, deconv):
|
||||
super(UNet1, self).__init__()
|
||||
self.conv1 = UNetConv(in_channels, 32, 64, se=False)
|
||||
self.conv1_down = nn.Conv2d(64, 64, 2, 2, 0)
|
||||
self.conv2 = UNetConv(64, 128, 64, se=True)
|
||||
self.conv2_up = nn.ConvTranspose2d(64, 64, 2, 2, 0)
|
||||
self.conv3 = nn.Conv2d(64, 64, 3, 1, 0)
|
||||
|
||||
if deconv:
|
||||
self.conv_bottom = nn.ConvTranspose2d(64, out_channels, 4, 2, 3)
|
||||
else:
|
||||
self.conv_bottom = nn.Conv2d(64, out_channels, 3, 1, 0)
|
||||
|
||||
for m in self.modules():
|
||||
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):
|
||||
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
||||
elif isinstance(m, nn.Linear):
|
||||
nn.init.normal_(m.weight, 0, 0.01)
|
||||
if m.bias is not None:
|
||||
nn.init.constant_(m.bias, 0)
|
||||
|
||||
def forward(self, x):
|
||||
x1 = self.conv1(x)
|
||||
x2 = self.conv1_down(x1)
|
||||
x2 = F.leaky_relu(x2, 0.1, inplace=True)
|
||||
x2 = self.conv2(x2)
|
||||
x2 = self.conv2_up(x2)
|
||||
x2 = F.leaky_relu(x2, 0.1, inplace=True)
|
||||
|
||||
x1 = F.pad(x1, (-4, -4, -4, -4))
|
||||
x3 = self.conv3(x1 + x2)
|
||||
x3 = F.leaky_relu(x3, 0.1, inplace=True)
|
||||
z = self.conv_bottom(x3)
|
||||
return z
|
||||
|
||||
|
||||
class UNet2(nn.Module):
|
||||
def __init__(self, in_channels, out_channels, deconv):
|
||||
super(UNet2, self).__init__()
|
||||
|
||||
self.conv1 = UNetConv(in_channels, 32, 64, se=False)
|
||||
self.conv1_down = nn.Conv2d(64, 64, 2, 2, 0)
|
||||
self.conv2 = UNetConv(64, 64, 128, se=True)
|
||||
self.conv2_down = nn.Conv2d(128, 128, 2, 2, 0)
|
||||
self.conv3 = UNetConv(128, 256, 128, se=True)
|
||||
self.conv3_up = nn.ConvTranspose2d(128, 128, 2, 2, 0)
|
||||
self.conv4 = UNetConv(128, 64, 64, se=True)
|
||||
self.conv4_up = nn.ConvTranspose2d(64, 64, 2, 2, 0)
|
||||
self.conv5 = nn.Conv2d(64, 64, 3, 1, 0)
|
||||
|
||||
if deconv:
|
||||
self.conv_bottom = nn.ConvTranspose2d(64, out_channels, 4, 2, 3)
|
||||
else:
|
||||
self.conv_bottom = nn.Conv2d(64, out_channels, 3, 1, 0)
|
||||
|
||||
for m in self.modules():
|
||||
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):
|
||||
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
|
||||
elif isinstance(m, nn.Linear):
|
||||
nn.init.normal_(m.weight, 0, 0.01)
|
||||
if m.bias is not None:
|
||||
nn.init.constant_(m.bias, 0)
|
||||
|
||||
def forward(self, x):
|
||||
x1 = self.conv1(x)
|
||||
x2 = self.conv1_down(x1)
|
||||
x2 = F.leaky_relu(x2, 0.1, inplace=True)
|
||||
x2 = self.conv2(x2)
|
||||
|
||||
x3 = self.conv2_down(x2)
|
||||
x3 = F.leaky_relu(x3, 0.1, inplace=True)
|
||||
x3 = self.conv3(x3)
|
||||
x3 = self.conv3_up(x3)
|
||||
x3 = F.leaky_relu(x3, 0.1, inplace=True)
|
||||
|
||||
x2 = F.pad(x2, (-4, -4, -4, -4))
|
||||
x4 = self.conv4(x2 + x3)
|
||||
x4 = self.conv4_up(x4)
|
||||
x4 = F.leaky_relu(x4, 0.1, inplace=True)
|
||||
|
||||
x1 = F.pad(x1, (-16, -16, -16, -16))
|
||||
x5 = self.conv5(x1 + x4)
|
||||
x5 = F.leaky_relu(x5, 0.1, inplace=True)
|
||||
|
||||
z = self.conv_bottom(x5)
|
||||
return z
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
root_path = os.path.abspath('.')
|
||||
sys.path.append(root_path)
|
||||
|
||||
from opt import opt # Manage GPU to choose
|
||||
import time
|
||||
|
||||
model = UNet_Full().cuda()
|
||||
pytorch_total_params = sum(p.numel() for p in model.parameters())
|
||||
print(f"CuNet has param {pytorch_total_params//1000} K params")
|
||||
|
||||
|
||||
# Count the number of FLOPs to double check
|
||||
x = torch.randn((1, 3, 180, 180)).cuda()
|
||||
start = time.time()
|
||||
x = model(x)
|
||||
print("output size is ", x.shape)
|
||||
total = time.time() - start
|
||||
print(total)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,241 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from torch import nn as nn
|
||||
from torch.nn import functional as F
|
||||
from torch.nn.utils import spectral_norm
|
||||
import torch
|
||||
import functools
|
||||
|
||||
class UNetDiscriminatorSN(nn.Module):
|
||||
"""Defines a U-Net discriminator with spectral normalization (SN)
|
||||
|
||||
It is used in Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data.
|
||||
|
||||
Arg:
|
||||
num_in_ch (int): Channel number of inputs. Default: 3.
|
||||
num_feat (int): Channel number of base intermediate features. Default: 64.
|
||||
skip_connection (bool): Whether to use skip connections between U-Net. Default: True.
|
||||
"""
|
||||
|
||||
def __init__(self, num_in_ch, num_feat=64, skip_connection=True):
|
||||
super(UNetDiscriminatorSN, self).__init__()
|
||||
self.skip_connection = skip_connection
|
||||
norm = spectral_norm
|
||||
# the first convolution
|
||||
self.conv0 = nn.Conv2d(num_in_ch, num_feat, kernel_size=3, stride=1, padding=1)
|
||||
# downsample
|
||||
self.conv1 = norm(nn.Conv2d(num_feat, num_feat * 2, 4, 2, 1, bias=False))
|
||||
self.conv2 = norm(nn.Conv2d(num_feat * 2, num_feat * 4, 4, 2, 1, bias=False))
|
||||
self.conv3 = norm(nn.Conv2d(num_feat * 4, num_feat * 8, 4, 2, 1, bias=False))
|
||||
# upsample
|
||||
self.conv4 = norm(nn.Conv2d(num_feat * 8, num_feat * 4, 3, 1, 1, bias=False))
|
||||
self.conv5 = norm(nn.Conv2d(num_feat * 4, num_feat * 2, 3, 1, 1, bias=False))
|
||||
self.conv6 = norm(nn.Conv2d(num_feat * 2, num_feat, 3, 1, 1, bias=False))
|
||||
# extra convolutions
|
||||
self.conv7 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False))
|
||||
self.conv8 = norm(nn.Conv2d(num_feat, num_feat, 3, 1, 1, bias=False))
|
||||
self.conv9 = nn.Conv2d(num_feat, 1, 3, 1, 1)
|
||||
|
||||
def forward(self, x):
|
||||
|
||||
# downsample
|
||||
x0 = F.leaky_relu(self.conv0(x), negative_slope=0.2, inplace=True)
|
||||
x1 = F.leaky_relu(self.conv1(x0), negative_slope=0.2, inplace=True)
|
||||
x2 = F.leaky_relu(self.conv2(x1), negative_slope=0.2, inplace=True)
|
||||
x3 = F.leaky_relu(self.conv3(x2), negative_slope=0.2, inplace=True)
|
||||
|
||||
# upsample
|
||||
x3 = F.interpolate(x3, scale_factor=2, mode='bilinear', align_corners=False)
|
||||
x4 = F.leaky_relu(self.conv4(x3), negative_slope=0.2, inplace=True)
|
||||
|
||||
if self.skip_connection:
|
||||
x4 = x4 + x2
|
||||
x4 = F.interpolate(x4, scale_factor=2, mode='bilinear', align_corners=False)
|
||||
x5 = F.leaky_relu(self.conv5(x4), negative_slope=0.2, inplace=True)
|
||||
|
||||
if self.skip_connection:
|
||||
x5 = x5 + x1
|
||||
x5 = F.interpolate(x5, scale_factor=2, mode='bilinear', align_corners=False)
|
||||
x6 = F.leaky_relu(self.conv6(x5), negative_slope=0.2, inplace=True)
|
||||
|
||||
if self.skip_connection:
|
||||
x6 = x6 + x0
|
||||
|
||||
# extra convolutions
|
||||
out = F.leaky_relu(self.conv7(x6), negative_slope=0.2, inplace=True)
|
||||
out = F.leaky_relu(self.conv8(out), negative_slope=0.2, inplace=True)
|
||||
out = self.conv9(out)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
|
||||
def get_conv_layer(input_nc, ndf, kernel_size, stride, padding, bias=True, use_sn=False):
|
||||
if not use_sn:
|
||||
return nn.Conv2d(input_nc, ndf, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)
|
||||
return spectral_norm(nn.Conv2d(input_nc, ndf, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias))
|
||||
|
||||
|
||||
class PatchDiscriminator(nn.Module):
|
||||
"""Defines a PatchGAN discriminator, the receptive field of default config is 70x70.
|
||||
|
||||
Args:
|
||||
use_sn (bool): Use spectra_norm or not, if use_sn is True, then norm_type should be none.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
num_in_ch,
|
||||
num_feat=64,
|
||||
num_layers=3,
|
||||
max_nf_mult=8,
|
||||
norm_type='batch',
|
||||
use_sigmoid=False,
|
||||
use_sn=False):
|
||||
super(PatchDiscriminator, self).__init__()
|
||||
|
||||
norm_layer = self._get_norm_layer(norm_type)
|
||||
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
|
||||
use_bias = norm_layer.func != nn.BatchNorm2d
|
||||
else:
|
||||
use_bias = norm_layer != nn.BatchNorm2d
|
||||
|
||||
kw = 4
|
||||
padw = 1
|
||||
sequence = [
|
||||
get_conv_layer(num_in_ch, num_feat, kernel_size=kw, stride=2, padding=padw, use_sn=use_sn),
|
||||
nn.LeakyReLU(0.2, True)
|
||||
]
|
||||
nf_mult = 1
|
||||
nf_mult_prev = 1
|
||||
for n in range(1, num_layers): # gradually increase the number of filters
|
||||
nf_mult_prev = nf_mult
|
||||
nf_mult = min(2**n, max_nf_mult)
|
||||
sequence += [
|
||||
get_conv_layer(
|
||||
num_feat * nf_mult_prev,
|
||||
num_feat * nf_mult,
|
||||
kernel_size=kw,
|
||||
stride=2,
|
||||
padding=padw,
|
||||
bias=use_bias,
|
||||
use_sn=use_sn),
|
||||
norm_layer(num_feat * nf_mult),
|
||||
nn.LeakyReLU(0.2, True)
|
||||
]
|
||||
|
||||
nf_mult_prev = nf_mult
|
||||
nf_mult = min(2**num_layers, max_nf_mult)
|
||||
sequence += [
|
||||
get_conv_layer(
|
||||
num_feat * nf_mult_prev,
|
||||
num_feat * nf_mult,
|
||||
kernel_size=kw,
|
||||
stride=1,
|
||||
padding=padw,
|
||||
bias=use_bias,
|
||||
use_sn=use_sn),
|
||||
norm_layer(num_feat * nf_mult),
|
||||
nn.LeakyReLU(0.2, True)
|
||||
]
|
||||
|
||||
# output 1 channel prediction map 我觉得这个应该就是pixel by pixel的feedback反馈
|
||||
sequence += [get_conv_layer(num_feat * nf_mult, 1, kernel_size=kw, stride=1, padding=padw, use_sn=use_sn)]
|
||||
|
||||
if use_sigmoid:
|
||||
sequence += [nn.Sigmoid()]
|
||||
self.model = nn.Sequential(*sequence)
|
||||
|
||||
def _get_norm_layer(self, norm_type='batch'):
|
||||
if norm_type == 'batch':
|
||||
norm_layer = functools.partial(nn.BatchNorm2d, affine=True)
|
||||
elif norm_type == 'instance':
|
||||
norm_layer = functools.partial(nn.InstanceNorm2d, affine=False)
|
||||
elif norm_type == 'batchnorm2d':
|
||||
norm_layer = nn.BatchNorm2d
|
||||
elif norm_type == 'none':
|
||||
norm_layer = nn.Identity
|
||||
else:
|
||||
raise NotImplementedError(f'normalization layer [{norm_type}] is not found')
|
||||
|
||||
return norm_layer
|
||||
|
||||
def forward(self, x):
|
||||
return self.model(x)
|
||||
|
||||
|
||||
class MultiScaleDiscriminator(nn.Module):
|
||||
"""Define a multi-scale discriminator, each discriminator is a instance of PatchDiscriminator.
|
||||
|
||||
Args:
|
||||
num_layers (int or list): If the type of this variable is int, then degrade to PatchDiscriminator.
|
||||
If the type of this variable is list, then the length of the list is
|
||||
the number of discriminators.
|
||||
use_downscale (bool): Progressive downscale the input to feed into different discriminators.
|
||||
If set to True, then the discriminators are usually the same.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
num_in_ch,
|
||||
num_feat=64,
|
||||
num_layers=[3, 3, 3],
|
||||
max_nf_mult=8,
|
||||
norm_type='none',
|
||||
use_sigmoid=False,
|
||||
use_sn=True,
|
||||
use_downscale=True):
|
||||
super(MultiScaleDiscriminator, self).__init__()
|
||||
|
||||
if isinstance(num_layers, int):
|
||||
num_layers = [num_layers]
|
||||
|
||||
# check whether the discriminators are the same
|
||||
if use_downscale:
|
||||
assert len(set(num_layers)) == 1
|
||||
self.use_downscale = use_downscale
|
||||
|
||||
self.num_dis = len(num_layers)
|
||||
self.dis_list = nn.ModuleList()
|
||||
for nl in num_layers:
|
||||
self.dis_list.append(
|
||||
PatchDiscriminator(
|
||||
num_in_ch,
|
||||
num_feat=num_feat,
|
||||
num_layers=nl,
|
||||
max_nf_mult=max_nf_mult,
|
||||
norm_type=norm_type,
|
||||
use_sigmoid=use_sigmoid,
|
||||
use_sn=use_sn,
|
||||
))
|
||||
|
||||
def forward(self, x):
|
||||
outs = []
|
||||
h, w = x.size()[2:]
|
||||
|
||||
y = x
|
||||
for i in range(self.num_dis):
|
||||
if i != 0 and self.use_downscale:
|
||||
y = F.interpolate(y, size=(h // 2, w // 2), mode='bilinear', align_corners=True)
|
||||
h, w = y.size()[2:]
|
||||
outs.append(self.dis_list[i](y))
|
||||
|
||||
return outs
|
||||
|
||||
|
||||
#def main():
|
||||
#from pthflops import count_ops
|
||||
#from torchsummary import summary
|
||||
|
||||
#model = UNetDiscriminatorSN(3)
|
||||
#pytorch_total_params = sum(p.numel() for p in model.parameters())
|
||||
|
||||
# Create a network and a corresponding input
|
||||
#device = 'cuda'
|
||||
#inp = torch.rand(1, 3, 400, 400)
|
||||
|
||||
# Count the number of FLOPs
|
||||
#count_ops(model, inp)
|
||||
#summary(model.cuda(), (3, 400, 400), batch_size=1)
|
||||
# print(f"pathGAN has param {pytorch_total_params//1000} K params")
|
||||
|
||||
|
||||
#if __name__ == "__main__":
|
||||
# main()
|
||||
@@ -0,0 +1,616 @@
|
||||
"""
|
||||
Efficient and Explicit Modelling of Image Hierarchies for Image Restoration
|
||||
Image restoration transformers with global, regional, and local modelling
|
||||
A clean version of the.
|
||||
Shared buffers are used for relative_coords_table, relative_position_index, and attn_mask.
|
||||
"""
|
||||
#import cv2
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from torchvision.transforms import ToTensor
|
||||
from torchvision.utils import save_image
|
||||
#from fairscale.nn import checkpoint_wrapper
|
||||
from omegaconf import OmegaConf
|
||||
from timm.models.layers import to_2tuple, trunc_normal_
|
||||
|
||||
# Import files from local folder
|
||||
import os, sys
|
||||
root_path = os.path.abspath('.')
|
||||
sys.path.append(root_path)
|
||||
|
||||
from .grl_common import Upsample, UpsampleOneStep
|
||||
from .grl_common.mixed_attn_block_efficient import (
|
||||
_get_stripe_info,
|
||||
EfficientMixAttnTransformerBlock,
|
||||
)
|
||||
from .grl_common.ops import (
|
||||
bchw_to_blc,
|
||||
blc_to_bchw,
|
||||
calculate_mask,
|
||||
calculate_mask_all,
|
||||
get_relative_coords_table_all,
|
||||
get_relative_position_index_simple,
|
||||
)
|
||||
from .grl_common.swin_v1_block import (
|
||||
build_last_conv,
|
||||
)
|
||||
|
||||
|
||||
class TransformerStage(nn.Module):
|
||||
"""Transformer stage.
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
input_resolution (tuple[int]): Input resolution.
|
||||
depth (int): Number of blocks.
|
||||
num_heads_window (list[int]): Number of window attention heads in different layers.
|
||||
num_heads_stripe (list[int]): Number of stripe attention heads in different layers.
|
||||
stripe_size (list[int]): Stripe size. Default: [8, 8]
|
||||
stripe_groups (list[int]): Number of stripe groups. Default: [None, None].
|
||||
stripe_shift (bool): whether to shift the stripes. This is used as an ablation study.
|
||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
qkv_proj_type (str): QKV projection type. Default: linear. Choices: linear, separable_conv.
|
||||
anchor_proj_type (str): Anchor projection type. Default: avgpool. Choices: avgpool, maxpool, conv2d, separable_conv, patchmerging.
|
||||
anchor_one_stage (bool): Whether to use one operator or multiple progressive operators to reduce feature map resolution. Default: True.
|
||||
anchor_window_down_factor (int): The downscale factor used to get the anchors.
|
||||
drop (float, optional): Dropout rate. Default: 0.0
|
||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
||||
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
pretrained_window_size (list[int]): pretrained window size. This is actually not used. Default: [0, 0].
|
||||
pretrained_stripe_size (list[int]): pretrained stripe size. This is actually not used. Default: [0, 0].
|
||||
conv_type: The convolutional block before residual connection.
|
||||
init_method: initialization method of the weight parameters used to train large scale models.
|
||||
Choices: n, normal -- Swin V1 init method.
|
||||
l, layernorm -- Swin V2 init method. Zero the weight and bias in the post layer normalization layer.
|
||||
r, res_rescale -- EDSR rescale method. Rescale the residual blocks with a scaling factor 0.1
|
||||
w, weight_rescale -- MSRResNet rescale method. Rescale the weight parameter in residual blocks with a scaling factor 0.1
|
||||
t, trunc_normal_ -- nn.Linear, trunc_normal; nn.Conv2d, weight_rescale
|
||||
fairscale_checkpoint (bool): Whether to use fairscale checkpoint.
|
||||
offload_to_cpu (bool): used by fairscale_checkpoint
|
||||
args:
|
||||
out_proj_type (str): Type of the output projection in the self-attention modules. Default: linear. Choices: linear, conv2d.
|
||||
local_connection (bool): Whether to enable the local modelling module (two convs followed by Channel attention). For GRL base model, this is used. "local_connection": local_connection,
|
||||
euclidean_dist (bool): use Euclidean distance or inner product as the similarity metric. An ablation study.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim,
|
||||
input_resolution,
|
||||
depth,
|
||||
num_heads_window,
|
||||
num_heads_stripe,
|
||||
window_size,
|
||||
stripe_size,
|
||||
stripe_groups,
|
||||
stripe_shift,
|
||||
mlp_ratio=4.0,
|
||||
qkv_bias=True,
|
||||
qkv_proj_type="linear",
|
||||
anchor_proj_type="avgpool",
|
||||
anchor_one_stage=True,
|
||||
anchor_window_down_factor=1,
|
||||
drop=0.0,
|
||||
attn_drop=0.0,
|
||||
drop_path=0.0,
|
||||
norm_layer=nn.LayerNorm,
|
||||
pretrained_window_size=[0, 0],
|
||||
pretrained_stripe_size=[0, 0],
|
||||
conv_type="1conv",
|
||||
init_method="",
|
||||
fairscale_checkpoint=False,
|
||||
offload_to_cpu=False,
|
||||
args=None,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.dim = dim
|
||||
self.input_resolution = input_resolution
|
||||
self.init_method = init_method
|
||||
|
||||
self.blocks = nn.ModuleList()
|
||||
for i in range(depth):
|
||||
block = EfficientMixAttnTransformerBlock(
|
||||
dim=dim,
|
||||
input_resolution=input_resolution,
|
||||
num_heads_w=num_heads_window,
|
||||
num_heads_s=num_heads_stripe,
|
||||
window_size=window_size,
|
||||
window_shift=i % 2 == 0,
|
||||
stripe_size=stripe_size,
|
||||
stripe_groups=stripe_groups,
|
||||
stripe_type="H" if i % 2 == 0 else "W",
|
||||
stripe_shift=i % 4 in [2, 3] if stripe_shift else False,
|
||||
mlp_ratio=mlp_ratio,
|
||||
qkv_bias=qkv_bias,
|
||||
qkv_proj_type=qkv_proj_type,
|
||||
anchor_proj_type=anchor_proj_type,
|
||||
anchor_one_stage=anchor_one_stage,
|
||||
anchor_window_down_factor=anchor_window_down_factor,
|
||||
drop=drop,
|
||||
attn_drop=attn_drop,
|
||||
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
|
||||
norm_layer=norm_layer,
|
||||
pretrained_window_size=pretrained_window_size,
|
||||
pretrained_stripe_size=pretrained_stripe_size,
|
||||
res_scale=0.1 if init_method == "r" else 1.0,
|
||||
args=args,
|
||||
)
|
||||
# print(fairscale_checkpoint, offload_to_cpu)
|
||||
if fairscale_checkpoint:
|
||||
block = checkpoint_wrapper(block, offload_to_cpu=offload_to_cpu)
|
||||
self.blocks.append(block)
|
||||
|
||||
self.conv = build_last_conv(conv_type, dim)
|
||||
|
||||
def _init_weights(self):
|
||||
for n, m in self.named_modules():
|
||||
if self.init_method == "w":
|
||||
if isinstance(m, (nn.Linear, nn.Conv2d)) and n.find("cpb_mlp") < 0:
|
||||
print("nn.Linear and nn.Conv2d weight initilization")
|
||||
m.weight.data *= 0.1
|
||||
elif self.init_method == "l":
|
||||
if isinstance(m, nn.LayerNorm):
|
||||
print("nn.LayerNorm initialization")
|
||||
nn.init.constant_(m.bias, 0)
|
||||
nn.init.constant_(m.weight, 0)
|
||||
elif self.init_method.find("t") >= 0:
|
||||
scale = 0.1 ** (len(self.init_method) - 1) * int(self.init_method[-1])
|
||||
if isinstance(m, nn.Linear) and n.find("cpb_mlp") < 0:
|
||||
trunc_normal_(m.weight, std=scale)
|
||||
elif isinstance(m, nn.Conv2d):
|
||||
m.weight.data *= 0.1
|
||||
print(
|
||||
"Initialization nn.Linear - trunc_normal; nn.Conv2d - weight rescale."
|
||||
)
|
||||
else:
|
||||
raise NotImplementedError(
|
||||
f"Parameter initialization method {self.init_method} not implemented in TransformerStage."
|
||||
)
|
||||
|
||||
def forward(self, x, x_size, table_index_mask):
|
||||
res = x
|
||||
for blk in self.blocks:
|
||||
res = blk(res, x_size, table_index_mask)
|
||||
res = bchw_to_blc(self.conv(blc_to_bchw(res, x_size)))
|
||||
|
||||
return res + x
|
||||
|
||||
def flops(self):
|
||||
pass
|
||||
|
||||
|
||||
class GRL(nn.Module):
|
||||
r"""Image restoration transformer with global, non-local, and local connections
|
||||
Args:
|
||||
img_size (int | list[int]): Input image size. Default 64
|
||||
in_channels (int): Number of input image channels. Default: 3
|
||||
out_channels (int): Number of output image channels. Default: None
|
||||
embed_dim (int): Patch embedding dimension. Default: 96
|
||||
upscale (int): Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction
|
||||
img_range (float): Image range. 1. or 255.
|
||||
upsampler (str): The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None
|
||||
depths (list[int]): Depth of each Swin Transformer layer.
|
||||
num_heads_window (list[int]): Number of window attention heads in different layers.
|
||||
num_heads_stripe (list[int]): Number of stripe attention heads in different layers.
|
||||
window_size (int): Window size. Default: 8.
|
||||
stripe_size (list[int]): Stripe size. Default: [8, 8]
|
||||
stripe_groups (list[int]): Number of stripe groups. Default: [None, None].
|
||||
stripe_shift (bool): whether to shift the stripes. This is used as an ablation study.
|
||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
|
||||
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
||||
qkv_proj_type (str): QKV projection type. Default: linear. Choices: linear, separable_conv.
|
||||
anchor_proj_type (str): Anchor projection type. Default: avgpool. Choices: avgpool, maxpool, conv2d, separable_conv, patchmerging.
|
||||
anchor_one_stage (bool): Whether to use one operator or multiple progressive operators to reduce feature map resolution. Default: True.
|
||||
anchor_window_down_factor (int): The downscale factor used to get the anchors.
|
||||
out_proj_type (str): Type of the output projection in the self-attention modules. Default: linear. Choices: linear, conv2d.
|
||||
local_connection (bool): Whether to enable the local modelling module (two convs followed by Channel attention). For GRL base model, this is used.
|
||||
drop_rate (float): Dropout rate. Default: 0
|
||||
attn_drop_rate (float): Attention dropout rate. Default: 0
|
||||
drop_path_rate (float): Stochastic depth rate. Default: 0.1
|
||||
pretrained_window_size (list[int]): pretrained window size. This is actually not used. Default: [0, 0].
|
||||
pretrained_stripe_size (list[int]): pretrained stripe size. This is actually not used. Default: [0, 0].
|
||||
norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
|
||||
conv_type (str): The convolutional block before residual connection. Default: 1conv. Choices: 1conv, 3conv, 1conv1x1, linear
|
||||
init_method: initialization method of the weight parameters used to train large scale models.
|
||||
Choices: n, normal -- Swin V1 init method.
|
||||
l, layernorm -- Swin V2 init method. Zero the weight and bias in the post layer normalization layer.
|
||||
r, res_rescale -- EDSR rescale method. Rescale the residual blocks with a scaling factor 0.1
|
||||
w, weight_rescale -- MSRResNet rescale method. Rescale the weight parameter in residual blocks with a scaling factor 0.1
|
||||
t, trunc_normal_ -- nn.Linear, trunc_normal; nn.Conv2d, weight_rescale
|
||||
fairscale_checkpoint (bool): Whether to use fairscale checkpoint.
|
||||
offload_to_cpu (bool): used by fairscale_checkpoint
|
||||
euclidean_dist (bool): use Euclidean distance or inner product as the similarity metric. An ablation study.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
img_size=64,
|
||||
in_channels=3,
|
||||
out_channels=None,
|
||||
embed_dim=96,
|
||||
upscale=2,
|
||||
img_range=1.0,
|
||||
upsampler="",
|
||||
depths=[6, 6, 6, 6, 6, 6],
|
||||
num_heads_window=[3, 3, 3, 3, 3, 3],
|
||||
num_heads_stripe=[3, 3, 3, 3, 3, 3],
|
||||
window_size=8,
|
||||
stripe_size=[8, 8], # used for stripe window attention
|
||||
stripe_groups=[None, None],
|
||||
stripe_shift=False,
|
||||
mlp_ratio=4.0,
|
||||
qkv_bias=True,
|
||||
qkv_proj_type="linear",
|
||||
anchor_proj_type="avgpool",
|
||||
anchor_one_stage=True,
|
||||
anchor_window_down_factor=1,
|
||||
out_proj_type="linear",
|
||||
local_connection=False,
|
||||
drop_rate=0.0,
|
||||
attn_drop_rate=0.0,
|
||||
drop_path_rate=0.1,
|
||||
norm_layer=nn.LayerNorm,
|
||||
pretrained_window_size=[0, 0],
|
||||
pretrained_stripe_size=[0, 0],
|
||||
conv_type="1conv",
|
||||
init_method="n", # initialization method of the weight parameters used to train large scale models.
|
||||
fairscale_checkpoint=False, # fairscale activation checkpointing
|
||||
offload_to_cpu=False,
|
||||
euclidean_dist=False,
|
||||
**kwargs,
|
||||
):
|
||||
super(GRL, self).__init__()
|
||||
# Process the input arguments
|
||||
out_channels = out_channels or in_channels
|
||||
self.in_channels = in_channels
|
||||
self.out_channels = out_channels
|
||||
num_out_feats = 64
|
||||
self.embed_dim = embed_dim
|
||||
self.upscale = upscale
|
||||
self.upsampler = upsampler
|
||||
self.img_range = img_range
|
||||
if in_channels == 3:
|
||||
rgb_mean = (0.4488, 0.4371, 0.4040)
|
||||
self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
|
||||
else:
|
||||
self.mean = torch.zeros(1, 1, 1, 1)
|
||||
|
||||
max_stripe_size = max([0 if s is None else s for s in stripe_size])
|
||||
max_stripe_groups = max([0 if s is None else s for s in stripe_groups])
|
||||
max_stripe_groups *= anchor_window_down_factor
|
||||
self.pad_size = max(window_size, max_stripe_size, max_stripe_groups)
|
||||
# if max_stripe_size >= window_size:
|
||||
# self.pad_size *= anchor_window_down_factor
|
||||
# if stripe_groups[0] is None and stripe_groups[1] is None:
|
||||
# self.pad_size = max(stripe_size)
|
||||
# else:
|
||||
# self.pad_size = window_size
|
||||
self.input_resolution = to_2tuple(img_size)
|
||||
self.window_size = to_2tuple(window_size)
|
||||
self.shift_size = [w // 2 for w in self.window_size]
|
||||
self.stripe_size = stripe_size
|
||||
self.stripe_groups = stripe_groups
|
||||
self.pretrained_window_size = pretrained_window_size
|
||||
self.pretrained_stripe_size = pretrained_stripe_size
|
||||
self.anchor_window_down_factor = anchor_window_down_factor
|
||||
|
||||
# Head of the network. First convolution.
|
||||
self.conv_first = nn.Conv2d(in_channels, embed_dim, 3, 1, 1)
|
||||
|
||||
# Body of the network
|
||||
self.norm_start = norm_layer(embed_dim)
|
||||
self.pos_drop = nn.Dropout(p=drop_rate)
|
||||
|
||||
# stochastic depth
|
||||
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
|
||||
# stochastic depth decay rule
|
||||
args = OmegaConf.create(
|
||||
{
|
||||
"out_proj_type": out_proj_type,
|
||||
"local_connection": local_connection,
|
||||
"euclidean_dist": euclidean_dist,
|
||||
}
|
||||
)
|
||||
for k, v in self.set_table_index_mask(self.input_resolution).items():
|
||||
self.register_buffer(k, v)
|
||||
|
||||
self.layers = nn.ModuleList()
|
||||
for i in range(len(depths)):
|
||||
layer = TransformerStage(
|
||||
dim=embed_dim,
|
||||
input_resolution=self.input_resolution,
|
||||
depth=depths[i],
|
||||
num_heads_window=num_heads_window[i],
|
||||
num_heads_stripe=num_heads_stripe[i],
|
||||
window_size=self.window_size,
|
||||
stripe_size=stripe_size,
|
||||
stripe_groups=stripe_groups,
|
||||
stripe_shift=stripe_shift,
|
||||
mlp_ratio=mlp_ratio,
|
||||
qkv_bias=qkv_bias,
|
||||
qkv_proj_type=qkv_proj_type,
|
||||
anchor_proj_type=anchor_proj_type,
|
||||
anchor_one_stage=anchor_one_stage,
|
||||
anchor_window_down_factor=anchor_window_down_factor,
|
||||
drop=drop_rate,
|
||||
attn_drop=attn_drop_rate,
|
||||
drop_path=dpr[
|
||||
sum(depths[:i]) : sum(depths[: i + 1])
|
||||
], # no impact on SR results
|
||||
norm_layer=norm_layer,
|
||||
pretrained_window_size=pretrained_window_size,
|
||||
pretrained_stripe_size=pretrained_stripe_size,
|
||||
conv_type=conv_type,
|
||||
init_method=init_method,
|
||||
fairscale_checkpoint=fairscale_checkpoint,
|
||||
offload_to_cpu=offload_to_cpu,
|
||||
args=args,
|
||||
)
|
||||
self.layers.append(layer)
|
||||
self.norm_end = norm_layer(embed_dim)
|
||||
|
||||
# Tail of the network
|
||||
self.conv_after_body = build_last_conv(conv_type, embed_dim)
|
||||
|
||||
#####################################################################################################
|
||||
################################ 3, high quality image reconstruction ################################
|
||||
if self.upsampler == "pixelshuffle":
|
||||
# for classical SR
|
||||
self.conv_before_upsample = nn.Sequential(
|
||||
nn.Conv2d(embed_dim, num_out_feats, 3, 1, 1), nn.LeakyReLU(inplace=True)
|
||||
)
|
||||
self.upsample = Upsample(upscale, num_out_feats)
|
||||
self.conv_last = nn.Conv2d(num_out_feats, out_channels, 3, 1, 1)
|
||||
elif self.upsampler == "pixelshuffledirect":
|
||||
# for lightweight SR (to save parameters)
|
||||
self.upsample = UpsampleOneStep(
|
||||
upscale,
|
||||
embed_dim,
|
||||
out_channels,
|
||||
)
|
||||
elif self.upsampler == "nearest+conv":
|
||||
# for real-world SR (less artifacts)
|
||||
assert self.upscale == 4, "only support x4 now."
|
||||
self.conv_before_upsample = nn.Sequential(
|
||||
nn.Conv2d(embed_dim, num_out_feats, 3, 1, 1), nn.LeakyReLU(inplace=True)
|
||||
)
|
||||
self.conv_up1 = nn.Conv2d(num_out_feats, num_out_feats, 3, 1, 1)
|
||||
self.conv_up2 = nn.Conv2d(num_out_feats, num_out_feats, 3, 1, 1)
|
||||
self.conv_hr = nn.Conv2d(num_out_feats, num_out_feats, 3, 1, 1)
|
||||
self.conv_last = nn.Conv2d(num_out_feats, out_channels, 3, 1, 1)
|
||||
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
|
||||
else:
|
||||
# for image denoising and JPEG compression artifact reduction
|
||||
self.conv_last = nn.Conv2d(embed_dim, out_channels, 3, 1, 1)
|
||||
|
||||
self.apply(self._init_weights)
|
||||
if init_method in ["l", "w"] or init_method.find("t") >= 0:
|
||||
for layer in self.layers:
|
||||
layer._init_weights()
|
||||
|
||||
def set_table_index_mask(self, x_size):
|
||||
"""
|
||||
Two used cases:
|
||||
1) At initialization: set the shared buffers.
|
||||
2) During forward pass: get the new buffers if the resolution of the input changes
|
||||
"""
|
||||
# ss - stripe_size, sss - stripe_shift_size
|
||||
ss, sss = _get_stripe_info(self.stripe_size, self.stripe_groups, True, x_size)
|
||||
df = self.anchor_window_down_factor
|
||||
|
||||
table_w = get_relative_coords_table_all(
|
||||
self.window_size, self.pretrained_window_size
|
||||
)
|
||||
table_sh = get_relative_coords_table_all(ss, self.pretrained_stripe_size, df)
|
||||
table_sv = get_relative_coords_table_all(
|
||||
ss[::-1], self.pretrained_stripe_size, df
|
||||
)
|
||||
|
||||
index_w = get_relative_position_index_simple(self.window_size)
|
||||
index_sh_a2w = get_relative_position_index_simple(ss, df, False)
|
||||
index_sh_w2a = get_relative_position_index_simple(ss, df, True)
|
||||
index_sv_a2w = get_relative_position_index_simple(ss[::-1], df, False)
|
||||
index_sv_w2a = get_relative_position_index_simple(ss[::-1], df, True)
|
||||
|
||||
mask_w = calculate_mask(x_size, self.window_size, self.shift_size)
|
||||
mask_sh_a2w = calculate_mask_all(x_size, ss, sss, df, False)
|
||||
mask_sh_w2a = calculate_mask_all(x_size, ss, sss, df, True)
|
||||
mask_sv_a2w = calculate_mask_all(x_size, ss[::-1], sss[::-1], df, False)
|
||||
mask_sv_w2a = calculate_mask_all(x_size, ss[::-1], sss[::-1], df, True)
|
||||
return {
|
||||
"table_w": table_w,
|
||||
"table_sh": table_sh,
|
||||
"table_sv": table_sv,
|
||||
"index_w": index_w,
|
||||
"index_sh_a2w": index_sh_a2w,
|
||||
"index_sh_w2a": index_sh_w2a,
|
||||
"index_sv_a2w": index_sv_a2w,
|
||||
"index_sv_w2a": index_sv_w2a,
|
||||
"mask_w": mask_w,
|
||||
"mask_sh_a2w": mask_sh_a2w,
|
||||
"mask_sh_w2a": mask_sh_w2a,
|
||||
"mask_sv_a2w": mask_sv_a2w,
|
||||
"mask_sv_w2a": mask_sv_w2a,
|
||||
}
|
||||
|
||||
def get_table_index_mask(self, device=None, input_resolution=None):
|
||||
# Used during forward pass
|
||||
if input_resolution == self.input_resolution:
|
||||
return {
|
||||
"table_w": self.table_w,
|
||||
"table_sh": self.table_sh,
|
||||
"table_sv": self.table_sv,
|
||||
"index_w": self.index_w,
|
||||
"index_sh_a2w": self.index_sh_a2w,
|
||||
"index_sh_w2a": self.index_sh_w2a,
|
||||
"index_sv_a2w": self.index_sv_a2w,
|
||||
"index_sv_w2a": self.index_sv_w2a,
|
||||
"mask_w": self.mask_w,
|
||||
"mask_sh_a2w": self.mask_sh_a2w,
|
||||
"mask_sh_w2a": self.mask_sh_w2a,
|
||||
"mask_sv_a2w": self.mask_sv_a2w,
|
||||
"mask_sv_w2a": self.mask_sv_w2a,
|
||||
}
|
||||
else:
|
||||
table_index_mask = self.set_table_index_mask(input_resolution)
|
||||
for k, v in table_index_mask.items():
|
||||
table_index_mask[k] = v.to(device)
|
||||
return table_index_mask
|
||||
|
||||
def _init_weights(self, m):
|
||||
if isinstance(m, nn.Linear):
|
||||
# Only used to initialize linear layers
|
||||
# weight_shape = m.weight.shape
|
||||
# if weight_shape[0] > 256 and weight_shape[1] > 256:
|
||||
# std = 0.004
|
||||
# else:
|
||||
# std = 0.02
|
||||
# print(f"Standard deviation during initialization {std}.")
|
||||
trunc_normal_(m.weight, std=0.02)
|
||||
if isinstance(m, nn.Linear) and m.bias is not None:
|
||||
nn.init.constant_(m.bias, 0)
|
||||
elif isinstance(m, nn.LayerNorm):
|
||||
nn.init.constant_(m.bias, 0)
|
||||
nn.init.constant_(m.weight, 1.0)
|
||||
|
||||
@torch.jit.ignore
|
||||
def no_weight_decay(self):
|
||||
return {"absolute_pos_embed"}
|
||||
|
||||
@torch.jit.ignore
|
||||
def no_weight_decay_keywords(self):
|
||||
return {"relative_position_bias_table"}
|
||||
|
||||
def check_image_size(self, x):
|
||||
_, _, h, w = x.size()
|
||||
mod_pad_h = (self.pad_size - h % self.pad_size) % self.pad_size
|
||||
mod_pad_w = (self.pad_size - w % self.pad_size) % self.pad_size
|
||||
# print("padding size", h, w, self.pad_size, mod_pad_h, mod_pad_w)
|
||||
|
||||
try:
|
||||
x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), "reflect")
|
||||
except BaseException:
|
||||
x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), "constant")
|
||||
return x
|
||||
|
||||
def forward_features(self, x):
|
||||
x_size = (x.shape[2], x.shape[3])
|
||||
x = bchw_to_blc(x)
|
||||
x = self.norm_start(x)
|
||||
x = self.pos_drop(x)
|
||||
|
||||
table_index_mask = self.get_table_index_mask(x.device, x_size)
|
||||
for layer in self.layers:
|
||||
x = layer(x, x_size, table_index_mask)
|
||||
|
||||
x = self.norm_end(x) # B L C
|
||||
x = blc_to_bchw(x, x_size)
|
||||
|
||||
return x
|
||||
|
||||
def forward(self, x):
|
||||
H, W = x.shape[2:]
|
||||
x = self.check_image_size(x)
|
||||
|
||||
self.mean = self.mean.type_as(x)
|
||||
x = (x - self.mean) * self.img_range
|
||||
|
||||
if self.upsampler == "pixelshuffle":
|
||||
# for classical SR
|
||||
x = self.conv_first(x)
|
||||
x = self.conv_after_body(self.forward_features(x)) + x
|
||||
x = self.conv_before_upsample(x)
|
||||
x = self.conv_last(self.upsample(x))
|
||||
elif self.upsampler == "pixelshuffledirect":
|
||||
# for lightweight SR
|
||||
x = self.conv_first(x)
|
||||
x = self.conv_after_body(self.forward_features(x)) + x
|
||||
x = self.upsample(x)
|
||||
elif self.upsampler == "nearest+conv":
|
||||
# for real-world SR (claimed to have less artifacts)
|
||||
x = self.conv_first(x)
|
||||
x = self.conv_after_body(self.forward_features(x)) + x
|
||||
x = self.conv_before_upsample(x)
|
||||
x = self.lrelu(
|
||||
self.conv_up1(
|
||||
torch.nn.functional.interpolate(x, scale_factor=2, mode="nearest")
|
||||
)
|
||||
)
|
||||
x = self.lrelu(
|
||||
self.conv_up2(
|
||||
torch.nn.functional.interpolate(x, scale_factor=2, mode="nearest")
|
||||
)
|
||||
)
|
||||
x = self.conv_last(self.lrelu(self.conv_hr(x)))
|
||||
else:
|
||||
# for image denoising and JPEG compression artifact reduction
|
||||
x_first = self.conv_first(x)
|
||||
res = self.conv_after_body(self.forward_features(x_first)) + x_first
|
||||
if self.in_channels == self.out_channels:
|
||||
x = x + self.conv_last(res)
|
||||
else:
|
||||
x = self.conv_last(res)
|
||||
|
||||
x = x / self.img_range + self.mean
|
||||
|
||||
return x[:, :, : H * self.upscale, : W * self.upscale]
|
||||
|
||||
def flops(self):
|
||||
pass
|
||||
|
||||
def convert_checkpoint(self, state_dict):
|
||||
for k in list(state_dict.keys()):
|
||||
if (
|
||||
k.find("relative_coords_table") >= 0
|
||||
or k.find("relative_position_index") >= 0
|
||||
or k.find("attn_mask") >= 0
|
||||
or k.find("model.table_") >= 0
|
||||
or k.find("model.index_") >= 0
|
||||
or k.find("model.mask_") >= 0
|
||||
# or k.find(".upsample.") >= 0
|
||||
):
|
||||
state_dict.pop(k)
|
||||
print(k)
|
||||
return state_dict
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# The version of GRL we use
|
||||
model = GRL(
|
||||
upscale = 4,
|
||||
img_size = 64,
|
||||
window_size = 8,
|
||||
depths = [4, 4, 4, 4],
|
||||
embed_dim = 64,
|
||||
num_heads_window = [2, 2, 2, 2],
|
||||
num_heads_stripe = [2, 2, 2, 2],
|
||||
mlp_ratio = 2,
|
||||
qkv_proj_type = "linear",
|
||||
anchor_proj_type = "avgpool",
|
||||
anchor_window_down_factor = 2,
|
||||
out_proj_type = "linear",
|
||||
conv_type = "1conv",
|
||||
upsampler = "nearest+conv", # Change
|
||||
).cuda()
|
||||
|
||||
# Parameter analysis
|
||||
num_params = 0
|
||||
for p in model.parameters():
|
||||
if p.requires_grad:
|
||||
num_params += p.numel()
|
||||
print(f"Number of parameters {num_params / 10 ** 6: 0.2f}")
|
||||
|
||||
# Print param
|
||||
for name, param in model.named_parameters():
|
||||
print(name, param.dtype)
|
||||
|
||||
|
||||
# Count the number of FLOPs to double check
|
||||
x = torch.randn((1, 3, 180, 180)).cuda() # Don't use input size that is too big (we don't have @torch.no_grad here)
|
||||
x = model(x)
|
||||
print("output size is ", x.shape)
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
from .resblock import ResBlock
|
||||
from .upsample import (
|
||||
Upsample,
|
||||
UpsampleOneStep,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["Upsample", "UpsampleOneStep", "ResBlock"]
|
||||
@@ -0,0 +1,227 @@
|
||||
"""
|
||||
EDSR common.py
|
||||
Since a lot of models are developed on top of EDSR, here we include some common functions from EDSR.
|
||||
In this repository, the common functions is used by edsr_esa.py and ipt.py
|
||||
"""
|
||||
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
def default_conv(in_channels, out_channels, kernel_size, bias=True):
|
||||
return nn.Conv2d(
|
||||
in_channels, out_channels, kernel_size, padding=(kernel_size // 2), bias=bias
|
||||
)
|
||||
|
||||
|
||||
class MeanShift(nn.Conv2d):
|
||||
def __init__(
|
||||
self,
|
||||
rgb_range,
|
||||
rgb_mean=(0.4488, 0.4371, 0.4040),
|
||||
rgb_std=(1.0, 1.0, 1.0),
|
||||
sign=-1,
|
||||
):
|
||||
|
||||
super(MeanShift, self).__init__(3, 3, kernel_size=1)
|
||||
std = torch.Tensor(rgb_std)
|
||||
self.weight.data = torch.eye(3).view(3, 3, 1, 1) / std.view(3, 1, 1, 1)
|
||||
self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean) / std
|
||||
for p in self.parameters():
|
||||
p.requires_grad = False
|
||||
|
||||
|
||||
class BasicBlock(nn.Sequential):
|
||||
def __init__(
|
||||
self,
|
||||
conv,
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride=1,
|
||||
bias=False,
|
||||
bn=True,
|
||||
act=nn.ReLU(True),
|
||||
):
|
||||
|
||||
m = [conv(in_channels, out_channels, kernel_size, bias=bias)]
|
||||
if bn:
|
||||
m.append(nn.BatchNorm2d(out_channels))
|
||||
if act is not None:
|
||||
m.append(act)
|
||||
|
||||
super(BasicBlock, self).__init__(*m)
|
||||
|
||||
|
||||
class ESA(nn.Module):
|
||||
def __init__(self, esa_channels, n_feats):
|
||||
super(ESA, self).__init__()
|
||||
f = esa_channels
|
||||
self.conv1 = nn.Conv2d(n_feats, f, kernel_size=1)
|
||||
self.conv_f = nn.Conv2d(f, f, kernel_size=1)
|
||||
# self.conv_max = conv(f, f, kernel_size=3, padding=1)
|
||||
self.conv2 = nn.Conv2d(f, f, kernel_size=3, stride=2, padding=0)
|
||||
self.conv3 = nn.Conv2d(f, f, kernel_size=3, padding=1)
|
||||
# self.conv3_ = conv(f, f, kernel_size=3, padding=1)
|
||||
self.conv4 = nn.Conv2d(f, n_feats, kernel_size=1)
|
||||
self.sigmoid = nn.Sigmoid()
|
||||
# self.relu = nn.ReLU(inplace=True)
|
||||
|
||||
def forward(self, x):
|
||||
c1_ = self.conv1(x)
|
||||
c1 = self.conv2(c1_)
|
||||
v_max = F.max_pool2d(c1, kernel_size=7, stride=3)
|
||||
c3 = self.conv3(v_max)
|
||||
# v_range = self.relu(self.conv_max(v_max))
|
||||
# c3 = self.relu(self.conv3(v_range))
|
||||
# c3 = self.conv3_(c3)
|
||||
c3 = F.interpolate(
|
||||
c3, (x.size(2), x.size(3)), mode="bilinear", align_corners=False
|
||||
)
|
||||
cf = self.conv_f(c1_)
|
||||
c4 = self.conv4(c3 + cf)
|
||||
m = self.sigmoid(c4)
|
||||
|
||||
return x * m
|
||||
|
||||
|
||||
# class ESA(nn.Module):
|
||||
# def __init__(self, esa_channels, n_feats, conv=nn.Conv2d):
|
||||
# super(ESA, self).__init__()
|
||||
# f = n_feats // 4
|
||||
# self.conv1 = conv(n_feats, f, kernel_size=1)
|
||||
# self.conv_f = conv(f, f, kernel_size=1)
|
||||
# self.conv_max = conv(f, f, kernel_size=3, padding=1)
|
||||
# self.conv2 = conv(f, f, kernel_size=3, stride=2, padding=0)
|
||||
# self.conv3 = conv(f, f, kernel_size=3, padding=1)
|
||||
# self.conv3_ = conv(f, f, kernel_size=3, padding=1)
|
||||
# self.conv4 = conv(f, n_feats, kernel_size=1)
|
||||
# self.sigmoid = nn.Sigmoid()
|
||||
# self.relu = nn.ReLU(inplace=True)
|
||||
#
|
||||
# def forward(self, x):
|
||||
# c1_ = (self.conv1(x))
|
||||
# c1 = self.conv2(c1_)
|
||||
# v_max = F.max_pool2d(c1, kernel_size=7, stride=3)
|
||||
# v_range = self.relu(self.conv_max(v_max))
|
||||
# c3 = self.relu(self.conv3(v_range))
|
||||
# c3 = self.conv3_(c3)
|
||||
# c3 = F.interpolate(c3, (x.size(2), x.size(3)), mode='bilinear', align_corners=False)
|
||||
# cf = self.conv_f(c1_)
|
||||
# c4 = self.conv4(c3 + cf)
|
||||
# m = self.sigmoid(c4)
|
||||
#
|
||||
# return x * m
|
||||
|
||||
|
||||
class ResBlock(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
conv,
|
||||
n_feats,
|
||||
kernel_size,
|
||||
bias=True,
|
||||
bn=False,
|
||||
act=nn.ReLU(True),
|
||||
res_scale=1,
|
||||
esa_block=True,
|
||||
depth_wise_kernel=7,
|
||||
):
|
||||
|
||||
super(ResBlock, self).__init__()
|
||||
m = []
|
||||
for i in range(2):
|
||||
m.append(conv(n_feats, n_feats, kernel_size, bias=bias))
|
||||
if bn:
|
||||
m.append(nn.BatchNorm2d(n_feats))
|
||||
if i == 0:
|
||||
m.append(act)
|
||||
|
||||
self.body = nn.Sequential(*m)
|
||||
self.esa_block = esa_block
|
||||
if self.esa_block:
|
||||
esa_channels = 16
|
||||
self.c5 = nn.Conv2d(
|
||||
n_feats,
|
||||
n_feats,
|
||||
depth_wise_kernel,
|
||||
padding=depth_wise_kernel // 2,
|
||||
groups=n_feats,
|
||||
bias=True,
|
||||
)
|
||||
self.esa = ESA(esa_channels, n_feats)
|
||||
self.res_scale = res_scale
|
||||
|
||||
def forward(self, x):
|
||||
res = self.body(x).mul(self.res_scale)
|
||||
res += x
|
||||
if self.esa_block:
|
||||
res = self.esa(self.c5(res))
|
||||
|
||||
return res
|
||||
|
||||
|
||||
class Upsampler(nn.Sequential):
|
||||
def __init__(self, conv, scale, n_feats, bn=False, act=False, bias=True):
|
||||
|
||||
m = []
|
||||
if (scale & (scale - 1)) == 0: # Is scale = 2^n?
|
||||
for _ in range(int(math.log(scale, 2))):
|
||||
m.append(conv(n_feats, 4 * n_feats, 3, bias))
|
||||
m.append(nn.PixelShuffle(2))
|
||||
if bn:
|
||||
m.append(nn.BatchNorm2d(n_feats))
|
||||
if act == "relu":
|
||||
m.append(nn.ReLU(True))
|
||||
elif act == "prelu":
|
||||
m.append(nn.PReLU(n_feats))
|
||||
|
||||
elif scale == 3:
|
||||
m.append(conv(n_feats, 9 * n_feats, 3, bias))
|
||||
m.append(nn.PixelShuffle(3))
|
||||
if bn:
|
||||
m.append(nn.BatchNorm2d(n_feats))
|
||||
if act == "relu":
|
||||
m.append(nn.ReLU(True))
|
||||
elif act == "prelu":
|
||||
m.append(nn.PReLU(n_feats))
|
||||
else:
|
||||
raise NotImplementedError
|
||||
|
||||
super(Upsampler, self).__init__(*m)
|
||||
|
||||
|
||||
class LiteUpsampler(nn.Sequential):
|
||||
def __init__(self, conv, scale, n_feats, n_out=3, bn=False, act=False, bias=True):
|
||||
|
||||
m = []
|
||||
m.append(conv(n_feats, n_out * (scale**2), 3, bias))
|
||||
m.append(nn.PixelShuffle(scale))
|
||||
# if (scale & (scale - 1)) == 0: # Is scale = 2^n?
|
||||
# for _ in range(int(math.log(scale, 2))):
|
||||
# m.append(conv(n_feats, 4 * n_out, 3, bias))
|
||||
# m.append(nn.PixelShuffle(2))
|
||||
# if bn:
|
||||
# m.append(nn.BatchNorm2d(n_out))
|
||||
# if act == 'relu':
|
||||
# m.append(nn.ReLU(True))
|
||||
# elif act == 'prelu':
|
||||
# m.append(nn.PReLU(n_out))
|
||||
|
||||
# elif scale == 3:
|
||||
# m.append(conv(n_feats, 9 * n_out, 3, bias))
|
||||
# m.append(nn.PixelShuffle(3))
|
||||
# if bn:
|
||||
# m.append(nn.BatchNorm2d(n_out))
|
||||
# if act == 'relu':
|
||||
# m.append(nn.ReLU(True))
|
||||
# elif act == 'prelu':
|
||||
# m.append(nn.PReLU(n_out))
|
||||
# else:
|
||||
# raise NotImplementedError
|
||||
|
||||
super(LiteUpsampler, self).__init__(*m)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,568 @@
|
||||
import math
|
||||
from abc import ABC
|
||||
from math import prod
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from timm.models.layers import DropPath
|
||||
|
||||
|
||||
from .mixed_attn_block import (
|
||||
AnchorProjection,
|
||||
CAB,
|
||||
CPB_MLP,
|
||||
QKVProjection,
|
||||
)
|
||||
from .ops import (
|
||||
window_partition,
|
||||
window_reverse,
|
||||
)
|
||||
from .swin_v1_block import Mlp
|
||||
|
||||
|
||||
class AffineTransform(nn.Module):
|
||||
r"""Affine transformation of the attention map.
|
||||
The window could be a square window or a stripe window. Supports attention between different window sizes
|
||||
"""
|
||||
|
||||
def __init__(self, num_heads):
|
||||
super(AffineTransform, self).__init__()
|
||||
logit_scale = torch.log(10 * torch.ones((num_heads, 1, 1)))
|
||||
self.logit_scale = nn.Parameter(logit_scale, requires_grad=True)
|
||||
|
||||
# mlp to generate continuous relative position bias
|
||||
self.cpb_mlp = CPB_MLP(2, num_heads)
|
||||
|
||||
def forward(self, attn, relative_coords_table, relative_position_index, mask):
|
||||
B_, H, N1, N2 = attn.shape
|
||||
# logit scale
|
||||
attn = attn * torch.clamp(self.logit_scale, max=math.log(1.0 / 0.01)).exp()
|
||||
|
||||
bias_table = self.cpb_mlp(relative_coords_table) # 2*Wh-1, 2*Ww-1, num_heads
|
||||
bias_table = bias_table.view(-1, H)
|
||||
|
||||
bias = bias_table[relative_position_index.view(-1)]
|
||||
bias = bias.view(N1, N2, -1).permute(2, 0, 1).contiguous()
|
||||
# nH, Wh*Ww, Wh*Ww
|
||||
bias = 16 * torch.sigmoid(bias)
|
||||
attn = attn + bias.unsqueeze(0)
|
||||
|
||||
# W-MSA/SW-MSA
|
||||
# shift attention mask
|
||||
if mask is not None:
|
||||
nW = mask.shape[0]
|
||||
mask = mask.unsqueeze(1).unsqueeze(0)
|
||||
attn = attn.view(B_ // nW, nW, H, N1, N2) + mask
|
||||
attn = attn.view(-1, H, N1, N2)
|
||||
|
||||
return attn
|
||||
|
||||
|
||||
def _get_stripe_info(stripe_size_in, stripe_groups_in, stripe_shift, input_resolution):
|
||||
stripe_size, shift_size = [], []
|
||||
for s, g, d in zip(stripe_size_in, stripe_groups_in, input_resolution):
|
||||
if g is None:
|
||||
stripe_size.append(s)
|
||||
shift_size.append(s // 2 if stripe_shift else 0)
|
||||
else:
|
||||
stripe_size.append(d // g)
|
||||
shift_size.append(0 if g == 1 else d // (g * 2))
|
||||
return stripe_size, shift_size
|
||||
|
||||
|
||||
class Attention(ABC, nn.Module):
|
||||
def __init__(self):
|
||||
super(Attention, self).__init__()
|
||||
|
||||
def attn(self, q, k, v, attn_transform, table, index, mask, reshape=True):
|
||||
# q, k, v: # nW*B, H, wh*ww, dim
|
||||
# cosine attention map
|
||||
B_, _, H, head_dim = q.shape
|
||||
if self.euclidean_dist:
|
||||
# print("use euclidean distance")
|
||||
attn = torch.norm(q.unsqueeze(-2) - k.unsqueeze(-3), dim=-1)
|
||||
else:
|
||||
attn = F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1)
|
||||
attn = attn_transform(attn, table, index, mask)
|
||||
# attention
|
||||
attn = self.softmax(attn)
|
||||
attn = self.attn_drop(attn)
|
||||
x = attn @ v # B_, H, N1, head_dim
|
||||
if reshape:
|
||||
x = x.transpose(1, 2).reshape(B_, -1, H * head_dim)
|
||||
# B_, N, C
|
||||
return x
|
||||
|
||||
|
||||
class WindowAttention(Attention):
|
||||
r"""Window attention. QKV is the input to the forward method.
|
||||
Args:
|
||||
num_heads (int): Number of attention heads.
|
||||
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
||||
pretrained_window_size (tuple[int]): The height and width of the window in pre-training.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_resolution,
|
||||
window_size,
|
||||
num_heads,
|
||||
window_shift=False,
|
||||
attn_drop=0.0,
|
||||
pretrained_window_size=[0, 0],
|
||||
args=None,
|
||||
):
|
||||
|
||||
super(WindowAttention, self).__init__()
|
||||
self.input_resolution = input_resolution
|
||||
self.window_size = window_size
|
||||
self.pretrained_window_size = pretrained_window_size
|
||||
self.num_heads = num_heads
|
||||
self.shift_size = window_size[0] // 2 if window_shift else 0
|
||||
self.euclidean_dist = args.euclidean_dist
|
||||
|
||||
self.attn_transform = AffineTransform(num_heads)
|
||||
self.attn_drop = nn.Dropout(attn_drop)
|
||||
self.softmax = nn.Softmax(dim=-1)
|
||||
|
||||
def forward(self, qkv, x_size, table, index, mask):
|
||||
"""
|
||||
Args:
|
||||
qkv: input QKV features with shape of (B, L, 3C)
|
||||
x_size: use x_size to determine whether the relative positional bias table and index
|
||||
need to be regenerated.
|
||||
"""
|
||||
H, W = x_size
|
||||
B, L, C = qkv.shape
|
||||
qkv = qkv.view(B, H, W, C)
|
||||
|
||||
# cyclic shift
|
||||
if self.shift_size > 0:
|
||||
qkv = torch.roll(
|
||||
qkv, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)
|
||||
)
|
||||
|
||||
# partition windows
|
||||
qkv = window_partition(qkv, self.window_size) # nW*B, wh, ww, C
|
||||
qkv = qkv.view(-1, prod(self.window_size), C) # nW*B, wh*ww, C
|
||||
|
||||
B_, N, _ = qkv.shape
|
||||
qkv = qkv.reshape(B_, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
||||
q, k, v = qkv[0], qkv[1], qkv[2] # nW*B, H, wh*ww, dim
|
||||
|
||||
# attention
|
||||
x = self.attn(q, k, v, self.attn_transform, table, index, mask)
|
||||
|
||||
# merge windows
|
||||
x = x.view(-1, *self.window_size, C // 3)
|
||||
x = window_reverse(x, self.window_size, x_size) # B, H, W, C/3
|
||||
|
||||
# reverse cyclic shift
|
||||
if self.shift_size > 0:
|
||||
x = torch.roll(x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
||||
x = x.view(B, L, C // 3)
|
||||
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return (
|
||||
f"window_size={self.window_size}, shift_size={self.shift_size}, "
|
||||
f"pretrained_window_size={self.pretrained_window_size}, num_heads={self.num_heads}"
|
||||
)
|
||||
|
||||
def flops(self, N):
|
||||
pass
|
||||
|
||||
|
||||
class AnchorStripeAttention(Attention):
|
||||
r"""Stripe attention
|
||||
Args:
|
||||
stripe_size (tuple[int]): The height and width of the stripe.
|
||||
num_heads (int): Number of attention heads.
|
||||
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
||||
pretrained_stripe_size (tuple[int]): The height and width of the stripe in pre-training.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_resolution,
|
||||
stripe_size,
|
||||
stripe_groups,
|
||||
stripe_shift,
|
||||
num_heads,
|
||||
attn_drop=0.0,
|
||||
pretrained_stripe_size=[0, 0],
|
||||
anchor_window_down_factor=1,
|
||||
args=None,
|
||||
):
|
||||
|
||||
super(AnchorStripeAttention, self).__init__()
|
||||
self.input_resolution = input_resolution
|
||||
self.stripe_size = stripe_size # Wh, Ww
|
||||
self.stripe_groups = stripe_groups
|
||||
self.stripe_shift = stripe_shift
|
||||
self.num_heads = num_heads
|
||||
self.pretrained_stripe_size = pretrained_stripe_size
|
||||
self.anchor_window_down_factor = anchor_window_down_factor
|
||||
self.euclidean_dist = args.euclidean_dist
|
||||
|
||||
self.attn_transform1 = AffineTransform(num_heads)
|
||||
self.attn_transform2 = AffineTransform(num_heads)
|
||||
|
||||
self.attn_drop = nn.Dropout(attn_drop)
|
||||
self.softmax = nn.Softmax(dim=-1)
|
||||
|
||||
def forward(
|
||||
self, qkv, anchor, x_size, table, index_a2w, index_w2a, mask_a2w, mask_w2a
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
qkv: input features with shape of (B, L, C)
|
||||
anchor:
|
||||
x_size: use stripe_size to determine whether the relative positional bias table and index
|
||||
need to be regenerated.
|
||||
"""
|
||||
H, W = x_size
|
||||
B, L, C = qkv.shape
|
||||
qkv = qkv.view(B, H, W, C)
|
||||
|
||||
stripe_size, shift_size = _get_stripe_info(
|
||||
self.stripe_size, self.stripe_groups, self.stripe_shift, x_size
|
||||
)
|
||||
anchor_stripe_size = [s // self.anchor_window_down_factor for s in stripe_size]
|
||||
anchor_shift_size = [s // self.anchor_window_down_factor for s in shift_size]
|
||||
# cyclic shift
|
||||
if self.stripe_shift:
|
||||
qkv = torch.roll(qkv, shifts=(-shift_size[0], -shift_size[1]), dims=(1, 2))
|
||||
anchor = torch.roll(
|
||||
anchor,
|
||||
shifts=(-anchor_shift_size[0], -anchor_shift_size[1]),
|
||||
dims=(1, 2),
|
||||
)
|
||||
|
||||
# partition windows
|
||||
qkv = window_partition(qkv, stripe_size) # nW*B, wh, ww, C
|
||||
qkv = qkv.view(-1, prod(stripe_size), C) # nW*B, wh*ww, C
|
||||
anchor = window_partition(anchor, anchor_stripe_size)
|
||||
anchor = anchor.view(-1, prod(anchor_stripe_size), C // 3)
|
||||
|
||||
B_, N1, _ = qkv.shape
|
||||
N2 = anchor.shape[1]
|
||||
qkv = qkv.reshape(B_, N1, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
||||
q, k, v = qkv[0], qkv[1], qkv[2]
|
||||
anchor = anchor.reshape(B_, N2, self.num_heads, -1).permute(0, 2, 1, 3)
|
||||
|
||||
# attention
|
||||
x = self.attn(
|
||||
anchor, k, v, self.attn_transform1, table, index_a2w, mask_a2w, False
|
||||
)
|
||||
x = self.attn(q, anchor, x, self.attn_transform2, table, index_w2a, mask_w2a)
|
||||
|
||||
# merge windows
|
||||
x = x.view(B_, *stripe_size, C // 3)
|
||||
x = window_reverse(x, stripe_size, x_size) # B H' W' C
|
||||
|
||||
# reverse the shift
|
||||
if self.stripe_shift:
|
||||
x = torch.roll(x, shifts=shift_size, dims=(1, 2))
|
||||
|
||||
x = x.view(B, H * W, C // 3)
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return (
|
||||
f"stripe_size={self.stripe_size}, stripe_groups={self.stripe_groups}, stripe_shift={self.stripe_shift}, "
|
||||
f"pretrained_stripe_size={self.pretrained_stripe_size}, num_heads={self.num_heads}, anchor_window_down_factor={self.anchor_window_down_factor}"
|
||||
)
|
||||
|
||||
def flops(self, N):
|
||||
pass
|
||||
|
||||
|
||||
class MixedAttention(nn.Module):
|
||||
r"""Mixed window attention and stripe attention
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
stripe_size (tuple[int]): The height and width of the stripe.
|
||||
num_heads (int): Number of attention heads.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
||||
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
|
||||
pretrained_stripe_size (tuple[int]): The height and width of the stripe in pre-training.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim,
|
||||
input_resolution,
|
||||
num_heads_w,
|
||||
num_heads_s,
|
||||
window_size,
|
||||
window_shift,
|
||||
stripe_size,
|
||||
stripe_groups,
|
||||
stripe_shift,
|
||||
qkv_bias=True,
|
||||
qkv_proj_type="linear",
|
||||
anchor_proj_type="separable_conv",
|
||||
anchor_one_stage=True,
|
||||
anchor_window_down_factor=1,
|
||||
attn_drop=0.0,
|
||||
proj_drop=0.0,
|
||||
pretrained_window_size=[0, 0],
|
||||
pretrained_stripe_size=[0, 0],
|
||||
args=None,
|
||||
):
|
||||
|
||||
super(MixedAttention, self).__init__()
|
||||
self.dim = dim
|
||||
self.input_resolution = input_resolution
|
||||
self.args = args
|
||||
# print(args)
|
||||
self.qkv = QKVProjection(dim, qkv_bias, qkv_proj_type, args)
|
||||
# anchor is only used for stripe attention
|
||||
self.anchor = AnchorProjection(
|
||||
dim, anchor_proj_type, anchor_one_stage, anchor_window_down_factor, args
|
||||
)
|
||||
|
||||
self.window_attn = WindowAttention(
|
||||
input_resolution,
|
||||
window_size,
|
||||
num_heads_w,
|
||||
window_shift,
|
||||
attn_drop,
|
||||
pretrained_window_size,
|
||||
args,
|
||||
)
|
||||
self.stripe_attn = AnchorStripeAttention(
|
||||
input_resolution,
|
||||
stripe_size,
|
||||
stripe_groups,
|
||||
stripe_shift,
|
||||
num_heads_s,
|
||||
attn_drop,
|
||||
pretrained_stripe_size,
|
||||
anchor_window_down_factor,
|
||||
args,
|
||||
)
|
||||
self.proj = nn.Linear(dim, dim)
|
||||
self.proj_drop = nn.Dropout(proj_drop)
|
||||
|
||||
def forward(self, x, x_size, table_index_mask):
|
||||
"""
|
||||
Args:
|
||||
x: input features with shape of (B, L, C)
|
||||
stripe_size: use stripe_size to determine whether the relative positional bias table and index
|
||||
need to be regenerated.
|
||||
"""
|
||||
B, L, C = x.shape
|
||||
|
||||
# qkv projection
|
||||
qkv = self.qkv(x, x_size)
|
||||
qkv_window, qkv_stripe = torch.split(qkv, C * 3 // 2, dim=-1)
|
||||
# anchor projection
|
||||
anchor = self.anchor(x, x_size)
|
||||
|
||||
# attention
|
||||
x_window = self.window_attn(
|
||||
qkv_window, x_size, *self._get_table_index_mask(table_index_mask, True)
|
||||
)
|
||||
x_stripe = self.stripe_attn(
|
||||
qkv_stripe,
|
||||
anchor,
|
||||
x_size,
|
||||
*self._get_table_index_mask(table_index_mask, False),
|
||||
)
|
||||
x = torch.cat([x_window, x_stripe], dim=-1)
|
||||
|
||||
# output projection
|
||||
x = self.proj(x)
|
||||
x = self.proj_drop(x)
|
||||
return x
|
||||
|
||||
def _get_table_index_mask(self, table_index_mask, window_attn=True):
|
||||
if window_attn:
|
||||
return (
|
||||
table_index_mask["table_w"],
|
||||
table_index_mask["index_w"],
|
||||
table_index_mask["mask_w"],
|
||||
)
|
||||
else:
|
||||
return (
|
||||
table_index_mask["table_s"],
|
||||
table_index_mask["index_a2w"],
|
||||
table_index_mask["index_w2a"],
|
||||
table_index_mask["mask_a2w"],
|
||||
table_index_mask["mask_w2a"],
|
||||
)
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return f"dim={self.dim}, input_resolution={self.input_resolution}"
|
||||
|
||||
def flops(self, N):
|
||||
pass
|
||||
|
||||
|
||||
class EfficientMixAttnTransformerBlock(nn.Module):
|
||||
r"""Mix attention transformer block with shared QKV projection and output projection for mixed attention modules.
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
input_resolution (tuple[int]): Input resulotion.
|
||||
num_heads (int): Number of attention heads.
|
||||
window_size (int): Window size.
|
||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
drop (float, optional): Dropout rate. Default: 0.0
|
||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
||||
drop_path (float, optional): Stochastic depth rate. Default: 0.0
|
||||
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
pretrained_stripe_size (int): Window size in pre-training.
|
||||
attn_type (str, optional): Attention type. Default: cwhv.
|
||||
c: residual blocks
|
||||
w: window attention
|
||||
h: horizontal stripe attention
|
||||
v: vertical stripe attention
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim,
|
||||
input_resolution,
|
||||
num_heads_w,
|
||||
num_heads_s,
|
||||
window_size=7,
|
||||
window_shift=False,
|
||||
stripe_size=[8, 8],
|
||||
stripe_groups=[None, None],
|
||||
stripe_shift=False,
|
||||
stripe_type="H",
|
||||
mlp_ratio=4.0,
|
||||
qkv_bias=True,
|
||||
qkv_proj_type="linear",
|
||||
anchor_proj_type="separable_conv",
|
||||
anchor_one_stage=True,
|
||||
anchor_window_down_factor=1,
|
||||
drop=0.0,
|
||||
attn_drop=0.0,
|
||||
drop_path=0.0,
|
||||
act_layer=nn.GELU,
|
||||
norm_layer=nn.LayerNorm,
|
||||
pretrained_window_size=[0, 0],
|
||||
pretrained_stripe_size=[0, 0],
|
||||
res_scale=1.0,
|
||||
args=None,
|
||||
):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.input_resolution = input_resolution
|
||||
self.num_heads_w = num_heads_w
|
||||
self.num_heads_s = num_heads_s
|
||||
self.window_size = window_size
|
||||
self.window_shift = window_shift
|
||||
self.stripe_shift = stripe_shift
|
||||
self.stripe_type = stripe_type
|
||||
self.args = args
|
||||
if self.stripe_type == "W":
|
||||
self.stripe_size = stripe_size[::-1]
|
||||
self.stripe_groups = stripe_groups[::-1]
|
||||
else:
|
||||
self.stripe_size = stripe_size
|
||||
self.stripe_groups = stripe_groups
|
||||
self.mlp_ratio = mlp_ratio
|
||||
self.res_scale = res_scale
|
||||
|
||||
self.attn = MixedAttention(
|
||||
dim,
|
||||
input_resolution,
|
||||
num_heads_w,
|
||||
num_heads_s,
|
||||
window_size,
|
||||
window_shift,
|
||||
self.stripe_size,
|
||||
self.stripe_groups,
|
||||
stripe_shift,
|
||||
qkv_bias,
|
||||
qkv_proj_type,
|
||||
anchor_proj_type,
|
||||
anchor_one_stage,
|
||||
anchor_window_down_factor,
|
||||
attn_drop,
|
||||
drop,
|
||||
pretrained_window_size,
|
||||
pretrained_stripe_size,
|
||||
args,
|
||||
)
|
||||
self.norm1 = norm_layer(dim)
|
||||
if self.args.local_connection:
|
||||
self.conv = CAB(dim)
|
||||
|
||||
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
||||
|
||||
self.mlp = Mlp(
|
||||
in_features=dim,
|
||||
hidden_features=int(dim * mlp_ratio),
|
||||
act_layer=act_layer,
|
||||
drop=drop,
|
||||
)
|
||||
self.norm2 = norm_layer(dim)
|
||||
|
||||
def _get_table_index_mask(self, all_table_index_mask):
|
||||
table_index_mask = {
|
||||
"table_w": all_table_index_mask["table_w"],
|
||||
"index_w": all_table_index_mask["index_w"],
|
||||
}
|
||||
if self.stripe_type == "W":
|
||||
table_index_mask["table_s"] = all_table_index_mask["table_sv"]
|
||||
table_index_mask["index_a2w"] = all_table_index_mask["index_sv_a2w"]
|
||||
table_index_mask["index_w2a"] = all_table_index_mask["index_sv_w2a"]
|
||||
else:
|
||||
table_index_mask["table_s"] = all_table_index_mask["table_sh"]
|
||||
table_index_mask["index_a2w"] = all_table_index_mask["index_sh_a2w"]
|
||||
table_index_mask["index_w2a"] = all_table_index_mask["index_sh_w2a"]
|
||||
if self.window_shift:
|
||||
table_index_mask["mask_w"] = all_table_index_mask["mask_w"]
|
||||
else:
|
||||
table_index_mask["mask_w"] = None
|
||||
if self.stripe_shift:
|
||||
if self.stripe_type == "W":
|
||||
table_index_mask["mask_a2w"] = all_table_index_mask["mask_sv_a2w"]
|
||||
table_index_mask["mask_w2a"] = all_table_index_mask["mask_sv_w2a"]
|
||||
else:
|
||||
table_index_mask["mask_a2w"] = all_table_index_mask["mask_sh_a2w"]
|
||||
table_index_mask["mask_w2a"] = all_table_index_mask["mask_sh_w2a"]
|
||||
else:
|
||||
table_index_mask["mask_a2w"] = None
|
||||
table_index_mask["mask_w2a"] = None
|
||||
return table_index_mask
|
||||
|
||||
def forward(self, x, x_size, all_table_index_mask):
|
||||
# Mixed attention
|
||||
table_index_mask = self._get_table_index_mask(all_table_index_mask)
|
||||
if self.args.local_connection:
|
||||
x = (
|
||||
x
|
||||
+ self.res_scale
|
||||
* self.drop_path(self.norm1(self.attn(x, x_size, table_index_mask)))
|
||||
+ self.conv(x, x_size)
|
||||
)
|
||||
else:
|
||||
x = x + self.res_scale * self.drop_path(
|
||||
self.norm1(self.attn(x, x_size, table_index_mask))
|
||||
)
|
||||
# FFN
|
||||
x = x + self.res_scale * self.drop_path(self.norm2(self.mlp(x)))
|
||||
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return (
|
||||
f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads=({self.num_heads_w}, {self.num_heads_s}), "
|
||||
f"window_size={self.window_size}, window_shift={self.window_shift}, "
|
||||
f"stripe_size={self.stripe_size}, stripe_groups={self.stripe_groups}, stripe_shift={self.stripe_shift}, self.stripe_type={self.stripe_type}, "
|
||||
f"mlp_ratio={self.mlp_ratio}, res_scale={self.res_scale}"
|
||||
)
|
||||
|
||||
def flops(self):
|
||||
pass
|
||||
@@ -0,0 +1,551 @@
|
||||
from math import prod
|
||||
from typing import Tuple
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from timm.models.layers import to_2tuple
|
||||
|
||||
|
||||
def bchw_to_bhwc(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Permutes a tensor from the shape (B, C, H, W) to (B, H, W, C)."""
|
||||
return x.permute(0, 2, 3, 1)
|
||||
|
||||
|
||||
def bhwc_to_bchw(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Permutes a tensor from the shape (B, H, W, C) to (B, C, H, W)."""
|
||||
return x.permute(0, 3, 1, 2)
|
||||
|
||||
|
||||
def bchw_to_blc(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Rearrange a tensor from the shape (B, C, H, W) to (B, L, C)."""
|
||||
return x.flatten(2).transpose(1, 2)
|
||||
|
||||
|
||||
def blc_to_bchw(x: torch.Tensor, x_size: Tuple) -> torch.Tensor:
|
||||
"""Rearrange a tensor from the shape (B, L, C) to (B, C, H, W)."""
|
||||
B, L, C = x.shape
|
||||
return x.transpose(1, 2).view(B, C, *x_size)
|
||||
|
||||
|
||||
def blc_to_bhwc(x: torch.Tensor, x_size: Tuple) -> torch.Tensor:
|
||||
"""Rearrange a tensor from the shape (B, L, C) to (B, H, W, C)."""
|
||||
B, L, C = x.shape
|
||||
return x.view(B, *x_size, C)
|
||||
|
||||
|
||||
def window_partition(x, window_size: Tuple[int, int]):
|
||||
"""
|
||||
Args:
|
||||
x: (B, H, W, C)
|
||||
window_size (int): window size
|
||||
|
||||
Returns:
|
||||
windows: (num_windows*B, window_size, window_size, C)
|
||||
"""
|
||||
B, H, W, C = x.shape
|
||||
x = x.view(
|
||||
B, H // window_size[0], window_size[0], W // window_size[1], window_size[1], C
|
||||
)
|
||||
windows = (
|
||||
x.permute(0, 1, 3, 2, 4, 5)
|
||||
.contiguous()
|
||||
.view(-1, window_size[0], window_size[1], C)
|
||||
)
|
||||
return windows
|
||||
|
||||
|
||||
def window_reverse(windows, window_size: Tuple[int, int], img_size: Tuple[int, int]):
|
||||
"""
|
||||
Args:
|
||||
windows: (num_windows * B, window_size[0], window_size[1], C)
|
||||
window_size (Tuple[int, int]): Window size
|
||||
img_size (Tuple[int, int]): Image size
|
||||
|
||||
Returns:
|
||||
x: (B, H, W, C)
|
||||
"""
|
||||
H, W = img_size
|
||||
B = int(windows.shape[0] / (H * W / window_size[0] / window_size[1]))
|
||||
x = windows.view(
|
||||
B, H // window_size[0], W // window_size[1], window_size[0], window_size[1], -1
|
||||
)
|
||||
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
|
||||
return x
|
||||
|
||||
|
||||
def _fill_window(input_resolution, window_size, shift_size=None):
|
||||
if shift_size is None:
|
||||
shift_size = [s // 2 for s in window_size]
|
||||
|
||||
img_mask = torch.zeros((1, *input_resolution, 1)) # 1 H W 1
|
||||
h_slices = (
|
||||
slice(0, -window_size[0]),
|
||||
slice(-window_size[0], -shift_size[0]),
|
||||
slice(-shift_size[0], None),
|
||||
)
|
||||
w_slices = (
|
||||
slice(0, -window_size[1]),
|
||||
slice(-window_size[1], -shift_size[1]),
|
||||
slice(-shift_size[1], None),
|
||||
)
|
||||
cnt = 0
|
||||
for h in h_slices:
|
||||
for w in w_slices:
|
||||
img_mask[:, h, w, :] = cnt
|
||||
cnt += 1
|
||||
|
||||
mask_windows = window_partition(img_mask, window_size)
|
||||
# nW, window_size, window_size, 1
|
||||
mask_windows = mask_windows.view(-1, prod(window_size))
|
||||
return mask_windows
|
||||
|
||||
|
||||
#####################################
|
||||
# Different versions of the functions
|
||||
# 1) Swin Transformer, SwinIR, Square window attention in GRL;
|
||||
# 2) Early development of the decomposition-based efficient attention mechanism (efficient_win_attn.py);
|
||||
# 3) GRL. Window-anchor attention mechanism.
|
||||
# 1) & 3) are still useful
|
||||
#####################################
|
||||
|
||||
|
||||
def calculate_mask(input_resolution, window_size, shift_size):
|
||||
"""
|
||||
Use case: 1)
|
||||
"""
|
||||
# calculate attention mask for SW-MSA
|
||||
if isinstance(shift_size, int):
|
||||
shift_size = to_2tuple(shift_size)
|
||||
mask_windows = _fill_window(input_resolution, window_size, shift_size)
|
||||
|
||||
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
|
||||
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
|
||||
attn_mask == 0, float(0.0)
|
||||
) # nW, window_size**2, window_size**2
|
||||
|
||||
return attn_mask
|
||||
|
||||
|
||||
def calculate_mask_all(
|
||||
input_resolution,
|
||||
window_size,
|
||||
shift_size,
|
||||
anchor_window_down_factor=1,
|
||||
window_to_anchor=True,
|
||||
):
|
||||
"""
|
||||
Use case: 3)
|
||||
"""
|
||||
# calculate attention mask for SW-MSA
|
||||
anchor_resolution = [s // anchor_window_down_factor for s in input_resolution]
|
||||
aws = [s // anchor_window_down_factor for s in window_size]
|
||||
anchor_shift = [s // anchor_window_down_factor for s in shift_size]
|
||||
|
||||
# mask of window1: nW, Wh**Ww
|
||||
mask_windows = _fill_window(input_resolution, window_size, shift_size)
|
||||
# mask of window2: nW, AWh*AWw
|
||||
mask_anchor = _fill_window(anchor_resolution, aws, anchor_shift)
|
||||
|
||||
if window_to_anchor:
|
||||
attn_mask = mask_windows.unsqueeze(2) - mask_anchor.unsqueeze(1)
|
||||
else:
|
||||
attn_mask = mask_anchor.unsqueeze(2) - mask_windows.unsqueeze(1)
|
||||
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
|
||||
attn_mask == 0, float(0.0)
|
||||
) # nW, Wh**Ww, AWh*AWw
|
||||
|
||||
return attn_mask
|
||||
|
||||
|
||||
def calculate_win_mask(
|
||||
input_resolution1, input_resolution2, window_size1, window_size2
|
||||
):
|
||||
"""
|
||||
Use case: 2)
|
||||
"""
|
||||
# calculate attention mask for SW-MSA
|
||||
|
||||
# mask of window1: nW, Wh**Ww
|
||||
mask_windows1 = _fill_window(input_resolution1, window_size1)
|
||||
# mask of window2: nW, AWh*AWw
|
||||
mask_windows2 = _fill_window(input_resolution2, window_size2)
|
||||
|
||||
attn_mask = mask_windows1.unsqueeze(2) - mask_windows2.unsqueeze(1)
|
||||
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
|
||||
attn_mask == 0, float(0.0)
|
||||
) # nW, Wh**Ww, AWh*AWw
|
||||
|
||||
return attn_mask
|
||||
|
||||
|
||||
def _get_meshgrid_coords(start_coords, end_coords):
|
||||
coord_h = torch.arange(start_coords[0], end_coords[0])
|
||||
coord_w = torch.arange(start_coords[1], end_coords[1])
|
||||
coords = torch.stack(torch.meshgrid([coord_h, coord_w], indexing="ij")) # 2, Wh, Ww
|
||||
coords = torch.flatten(coords, 1) # 2, Wh*Ww
|
||||
return coords
|
||||
|
||||
|
||||
def get_relative_coords_table(
|
||||
window_size, pretrained_window_size=[0, 0], anchor_window_down_factor=1
|
||||
):
|
||||
"""
|
||||
Use case: 1)
|
||||
"""
|
||||
# get relative_coords_table
|
||||
ws = window_size
|
||||
aws = [w // anchor_window_down_factor for w in window_size]
|
||||
pws = pretrained_window_size
|
||||
paws = [w // anchor_window_down_factor for w in pretrained_window_size]
|
||||
|
||||
ts = [(w1 + w2) // 2 for w1, w2 in zip(ws, aws)]
|
||||
pts = [(w1 + w2) // 2 for w1, w2 in zip(pws, paws)]
|
||||
|
||||
# TODO: pretrained window size and pretrained anchor window size is only used here.
|
||||
# TODO: Investigate whether it is really important to use this setting when finetuning large window size
|
||||
# TODO: based on pretrained weights with small window size.
|
||||
|
||||
coord_h = torch.arange(-(ts[0] - 1), ts[0], dtype=torch.float32)
|
||||
coord_w = torch.arange(-(ts[1] - 1), ts[1], dtype=torch.float32)
|
||||
table = torch.stack(torch.meshgrid([coord_h, coord_w], indexing="ij")).permute(
|
||||
1, 2, 0
|
||||
)
|
||||
table = table.contiguous().unsqueeze(0) # 1, Wh+AWh-1, Ww+AWw-1, 2
|
||||
if pts[0] > 0:
|
||||
table[:, :, :, 0] /= pts[0] - 1
|
||||
table[:, :, :, 1] /= pts[1] - 1
|
||||
else:
|
||||
table[:, :, :, 0] /= ts[0] - 1
|
||||
table[:, :, :, 1] /= ts[1] - 1
|
||||
table *= 8 # normalize to -8, 8
|
||||
table = torch.sign(table) * torch.log2(torch.abs(table) + 1.0) / np.log2(8)
|
||||
return table
|
||||
|
||||
|
||||
def get_relative_coords_table_all(
|
||||
window_size, pretrained_window_size=[0, 0], anchor_window_down_factor=1
|
||||
):
|
||||
"""
|
||||
Use case: 3)
|
||||
|
||||
Support all window shapes.
|
||||
Args:
|
||||
window_size:
|
||||
pretrained_window_size:
|
||||
anchor_window_down_factor:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
# get relative_coords_table
|
||||
ws = window_size
|
||||
aws = [w // anchor_window_down_factor for w in window_size]
|
||||
pws = pretrained_window_size
|
||||
paws = [w // anchor_window_down_factor for w in pretrained_window_size]
|
||||
|
||||
# positive table size: (Ww - 1) - (Ww - AWw) // 2
|
||||
ts_p = [w1 - 1 - (w1 - w2) // 2 for w1, w2 in zip(ws, aws)]
|
||||
# negative table size: -(AWw - 1) - (Ww - AWw) // 2
|
||||
ts_n = [-(w2 - 1) - (w1 - w2) // 2 for w1, w2 in zip(ws, aws)]
|
||||
pts = [w1 - 1 - (w1 - w2) // 2 for w1, w2 in zip(pws, paws)]
|
||||
|
||||
# TODO: pretrained window size and pretrained anchor window size is only used here.
|
||||
# TODO: Investigate whether it is really important to use this setting when finetuning large window size
|
||||
# TODO: based on pretrained weights with small window size.
|
||||
|
||||
coord_h = torch.arange(ts_n[0], ts_p[0] + 1, dtype=torch.float32)
|
||||
coord_w = torch.arange(ts_n[1], ts_p[1] + 1, dtype=torch.float32)
|
||||
table = torch.stack(torch.meshgrid([coord_h, coord_w], indexing="ij")).permute(
|
||||
1, 2, 0
|
||||
)
|
||||
table = table.contiguous().unsqueeze(0) # 1, Wh+AWh-1, Ww+AWw-1, 2
|
||||
if pts[0] > 0:
|
||||
table[:, :, :, 0] /= pts[0]
|
||||
table[:, :, :, 1] /= pts[1]
|
||||
else:
|
||||
table[:, :, :, 0] /= ts_p[0]
|
||||
table[:, :, :, 1] /= ts_p[1]
|
||||
table *= 8 # normalize to -8, 8
|
||||
table = torch.sign(table) * torch.log2(torch.abs(table) + 1.0) / np.log2(8)
|
||||
# 1, Wh+AWh-1, Ww+AWw-1, 2
|
||||
return table
|
||||
|
||||
|
||||
def coords_diff(coords1, coords2, max_diff):
|
||||
# The coordinates starts from (-start_coord[0], -start_coord[1])
|
||||
coords = coords1[:, :, None] - coords2[:, None, :] # 2, Wh*Ww, AWh*AWw
|
||||
coords = coords.permute(1, 2, 0).contiguous() # Wh*Ww, AWh*AWw, 2
|
||||
coords[:, :, 0] += max_diff[0] - 1 # shift to start from 0
|
||||
coords[:, :, 1] += max_diff[1] - 1
|
||||
coords[:, :, 0] *= 2 * max_diff[1] - 1
|
||||
idx = coords.sum(-1) # Wh*Ww, AWh*AWw
|
||||
return idx
|
||||
|
||||
|
||||
def get_relative_position_index(
|
||||
window_size, anchor_window_down_factor=1, window_to_anchor=True
|
||||
):
|
||||
"""
|
||||
Use case: 1)
|
||||
"""
|
||||
# get pair-wise relative position index for each token inside the window
|
||||
ws = window_size
|
||||
aws = [w // anchor_window_down_factor for w in window_size]
|
||||
coords_anchor_end = [(w1 + w2) // 2 for w1, w2 in zip(ws, aws)]
|
||||
coords_anchor_start = [(w1 - w2) // 2 for w1, w2 in zip(ws, aws)]
|
||||
|
||||
coords = _get_meshgrid_coords((0, 0), window_size) # 2, Wh*Ww
|
||||
coords_anchor = _get_meshgrid_coords(coords_anchor_start, coords_anchor_end)
|
||||
# 2, AWh*AWw
|
||||
|
||||
if window_to_anchor:
|
||||
idx = coords_diff(coords, coords_anchor, max_diff=coords_anchor_end)
|
||||
else:
|
||||
idx = coords_diff(coords_anchor, coords, max_diff=coords_anchor_end)
|
||||
return idx # Wh*Ww, AWh*AWw or AWh*AWw, Wh*Ww
|
||||
|
||||
|
||||
def coords_diff_odd(coords1, coords2, start_coord, max_diff):
|
||||
# The coordinates starts from (-start_coord[0], -start_coord[1])
|
||||
coords = coords1[:, :, None] - coords2[:, None, :] # 2, Wh*Ww, AWh*AWw
|
||||
coords = coords.permute(1, 2, 0).contiguous() # Wh*Ww, AWh*AWw, 2
|
||||
coords[:, :, 0] += start_coord[0] # shift to start from 0
|
||||
coords[:, :, 1] += start_coord[1]
|
||||
coords[:, :, 0] *= max_diff
|
||||
idx = coords.sum(-1) # Wh*Ww, AWh*AWw
|
||||
return idx
|
||||
|
||||
|
||||
def get_relative_position_index_all(
|
||||
window_size, anchor_window_down_factor=1, window_to_anchor=True
|
||||
):
|
||||
"""
|
||||
Use case: 3)
|
||||
Support all window shapes:
|
||||
square window - square window
|
||||
rectangular window - rectangular window
|
||||
window - anchor
|
||||
anchor - window
|
||||
[8, 8] - [8, 8]
|
||||
[4, 86] - [2, 43]
|
||||
"""
|
||||
# get pair-wise relative position index for each token inside the window
|
||||
ws = window_size
|
||||
aws = [w // anchor_window_down_factor for w in window_size]
|
||||
coords_anchor_start = [(w1 - w2) // 2 for w1, w2 in zip(ws, aws)]
|
||||
coords_anchor_end = [s + w2 for s, w2 in zip(coords_anchor_start, aws)]
|
||||
|
||||
coords = _get_meshgrid_coords((0, 0), window_size) # 2, Wh*Ww
|
||||
coords_anchor = _get_meshgrid_coords(coords_anchor_start, coords_anchor_end)
|
||||
# 2, AWh*AWw
|
||||
|
||||
max_horizontal_diff = aws[1] + ws[1] - 1
|
||||
if window_to_anchor:
|
||||
offset = [w2 + s - 1 for s, w2 in zip(coords_anchor_start, aws)]
|
||||
idx = coords_diff_odd(coords, coords_anchor, offset, max_horizontal_diff)
|
||||
else:
|
||||
offset = [w1 - s - 1 for s, w1 in zip(coords_anchor_start, ws)]
|
||||
idx = coords_diff_odd(coords_anchor, coords, offset, max_horizontal_diff)
|
||||
return idx # Wh*Ww, AWh*AWw or AWh*AWw, Wh*Ww
|
||||
|
||||
|
||||
def get_relative_position_index_simple(
|
||||
window_size, anchor_window_down_factor=1, window_to_anchor=True
|
||||
):
|
||||
"""
|
||||
Use case: 3)
|
||||
This is a simplified version of get_relative_position_index_all
|
||||
The start coordinate of anchor window is also (0, 0)
|
||||
get pair-wise relative position index for each token inside the window
|
||||
"""
|
||||
ws = window_size
|
||||
aws = [w // anchor_window_down_factor for w in window_size]
|
||||
|
||||
coords = _get_meshgrid_coords((0, 0), window_size) # 2, Wh*Ww
|
||||
coords_anchor = _get_meshgrid_coords((0, 0), aws)
|
||||
# 2, AWh*AWw
|
||||
|
||||
max_horizontal_diff = aws[1] + ws[1] - 1
|
||||
if window_to_anchor:
|
||||
offset = [w2 - 1 for w2 in aws]
|
||||
idx = coords_diff_odd(coords, coords_anchor, offset, max_horizontal_diff)
|
||||
else:
|
||||
offset = [w1 - 1 for w1 in ws]
|
||||
idx = coords_diff_odd(coords_anchor, coords, offset, max_horizontal_diff)
|
||||
return idx # Wh*Ww, AWh*AWw or AWh*AWw, Wh*Ww
|
||||
|
||||
|
||||
# def get_relative_position_index(window_size):
|
||||
# # This is a very early version
|
||||
# # get pair-wise relative position index for each token inside the window
|
||||
# coords = _get_meshgrid_coords(start_coords=(0, 0), end_coords=window_size)
|
||||
|
||||
# coords = coords[:, :, None] - coords[:, None, :] # 2, Wh*Ww, Wh*Ww
|
||||
# coords = coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
||||
# coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
|
||||
# coords[:, :, 1] += window_size[1] - 1
|
||||
# coords[:, :, 0] *= 2 * window_size[1] - 1
|
||||
# idx = coords.sum(-1) # Wh*Ww, Wh*Ww
|
||||
# return idx
|
||||
|
||||
|
||||
def get_relative_win_position_index(window_size, anchor_window_size):
|
||||
"""
|
||||
Use case: 2)
|
||||
"""
|
||||
# get pair-wise relative position index for each token inside the window
|
||||
ws = window_size
|
||||
aws = anchor_window_size
|
||||
coords_anchor_end = [(w1 + w2) // 2 for w1, w2 in zip(ws, aws)]
|
||||
coords_anchor_start = [(w1 - w2) // 2 for w1, w2 in zip(ws, aws)]
|
||||
|
||||
coords = _get_meshgrid_coords((0, 0), window_size) # 2, Wh*Ww
|
||||
coords_anchor = _get_meshgrid_coords(coords_anchor_start, coords_anchor_end)
|
||||
# 2, AWh*AWw
|
||||
coords = coords[:, :, None] - coords_anchor[:, None, :] # 2, Wh*Ww, AWh*AWw
|
||||
coords = coords.permute(1, 2, 0).contiguous() # Wh*Ww, AWh*AWw, 2
|
||||
coords[:, :, 0] += coords_anchor_end[0] - 1 # shift to start from 0
|
||||
coords[:, :, 1] += coords_anchor_end[1] - 1
|
||||
coords[:, :, 0] *= 2 * coords_anchor_end[1] - 1
|
||||
idx = coords.sum(-1) # Wh*Ww, AWh*AWw
|
||||
return idx
|
||||
|
||||
|
||||
# def get_relative_coords_table(window_size, pretrained_window_size):
|
||||
# # This is a very early version
|
||||
# # get relative_coords_table
|
||||
# ws = window_size
|
||||
# pws = pretrained_window_size
|
||||
# coord_h = torch.arange(-(ws[0] - 1), ws[0], dtype=torch.float32)
|
||||
# coord_w = torch.arange(-(ws[1] - 1), ws[1], dtype=torch.float32)
|
||||
# table = torch.stack(torch.meshgrid([coord_h, coord_w], indexing='ij')).permute(1, 2, 0)
|
||||
# table = table.contiguous().unsqueeze(0) # 1, 2*Wh-1, 2*Ww-1, 2
|
||||
# if pws[0] > 0:
|
||||
# table[:, :, :, 0] /= pws[0] - 1
|
||||
# table[:, :, :, 1] /= pws[1] - 1
|
||||
# else:
|
||||
# table[:, :, :, 0] /= ws[0] - 1
|
||||
# table[:, :, :, 1] /= ws[1] - 1
|
||||
# table *= 8 # normalize to -8, 8
|
||||
# table = torch.sign(table) * torch.log2(torch.abs(table) + 1.0) / np.log2(8)
|
||||
# return table
|
||||
|
||||
|
||||
def get_relative_win_coords_table(
|
||||
window_size,
|
||||
anchor_window_size,
|
||||
pretrained_window_size=[0, 0],
|
||||
pretrained_anchor_window_size=[0, 0],
|
||||
):
|
||||
"""
|
||||
Use case: 2)
|
||||
"""
|
||||
# get relative_coords_table
|
||||
ws = window_size
|
||||
aws = anchor_window_size
|
||||
pws = pretrained_window_size
|
||||
paws = pretrained_anchor_window_size
|
||||
|
||||
# TODO: pretrained window size and pretrained anchor window size is only used here.
|
||||
# TODO: Investigate whether it is really important to use this setting when finetuning large window size
|
||||
# TODO: based on pretrained weights with small window size.
|
||||
|
||||
table_size = [(wsi + awsi) // 2 for wsi, awsi in zip(ws, aws)]
|
||||
table_size_pretrained = [(pwsi + pawsi) // 2 for pwsi, pawsi in zip(pws, paws)]
|
||||
coord_h = torch.arange(-(table_size[0] - 1), table_size[0], dtype=torch.float32)
|
||||
coord_w = torch.arange(-(table_size[1] - 1), table_size[1], dtype=torch.float32)
|
||||
table = torch.stack(torch.meshgrid([coord_h, coord_w], indexing="ij")).permute(
|
||||
1, 2, 0
|
||||
)
|
||||
table = table.contiguous().unsqueeze(0) # 1, Wh+AWh-1, Ww+AWw-1, 2
|
||||
if table_size_pretrained[0] > 0:
|
||||
table[:, :, :, 0] /= table_size_pretrained[0] - 1
|
||||
table[:, :, :, 1] /= table_size_pretrained[1] - 1
|
||||
else:
|
||||
table[:, :, :, 0] /= table_size[0] - 1
|
||||
table[:, :, :, 1] /= table_size[1] - 1
|
||||
table *= 8 # normalize to -8, 8
|
||||
table = torch.sign(table) * torch.log2(torch.abs(table) + 1.0) / np.log2(8)
|
||||
return table
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
table = get_relative_coords_table_all((4, 86), anchor_window_down_factor=2)
|
||||
table = table.view(-1, 2)
|
||||
index1 = get_relative_position_index_all((4, 86), 2, False)
|
||||
index2 = get_relative_position_index_simple((4, 86), 2, False)
|
||||
print(index2)
|
||||
index3 = get_relative_position_index_all((4, 86), 2)
|
||||
index4 = get_relative_position_index_simple((4, 86), 2)
|
||||
print(index4)
|
||||
print(
|
||||
table.shape,
|
||||
index2.shape,
|
||||
index2.max(),
|
||||
index2.min(),
|
||||
index4.shape,
|
||||
index4.max(),
|
||||
index4.min(),
|
||||
torch.allclose(index1, index2),
|
||||
torch.allclose(index3, index4),
|
||||
)
|
||||
|
||||
table = get_relative_coords_table_all((4, 86), anchor_window_down_factor=1)
|
||||
table = table.view(-1, 2)
|
||||
index1 = get_relative_position_index_all((4, 86), 1, False)
|
||||
index2 = get_relative_position_index_simple((4, 86), 1, False)
|
||||
# print(index1)
|
||||
index3 = get_relative_position_index_all((4, 86), 1)
|
||||
index4 = get_relative_position_index_simple((4, 86), 1)
|
||||
# print(index2)
|
||||
print(
|
||||
table.shape,
|
||||
index2.shape,
|
||||
index2.max(),
|
||||
index2.min(),
|
||||
index4.shape,
|
||||
index4.max(),
|
||||
index4.min(),
|
||||
torch.allclose(index1, index2),
|
||||
torch.allclose(index3, index4),
|
||||
)
|
||||
|
||||
table = get_relative_coords_table_all((8, 8), anchor_window_down_factor=2)
|
||||
table = table.view(-1, 2)
|
||||
index1 = get_relative_position_index_all((8, 8), 2, False)
|
||||
index2 = get_relative_position_index_simple((8, 8), 2, False)
|
||||
# print(index1)
|
||||
index3 = get_relative_position_index_all((8, 8), 2)
|
||||
index4 = get_relative_position_index_simple((8, 8), 2)
|
||||
# print(index2)
|
||||
print(
|
||||
table.shape,
|
||||
index2.shape,
|
||||
index2.max(),
|
||||
index2.min(),
|
||||
index4.shape,
|
||||
index4.max(),
|
||||
index4.min(),
|
||||
torch.allclose(index1, index2),
|
||||
torch.allclose(index3, index4),
|
||||
)
|
||||
|
||||
table = get_relative_coords_table_all((8, 8), anchor_window_down_factor=1)
|
||||
table = table.view(-1, 2)
|
||||
index1 = get_relative_position_index_all((8, 8), 1, False)
|
||||
index2 = get_relative_position_index_simple((8, 8), 1, False)
|
||||
# print(index1)
|
||||
index3 = get_relative_position_index_all((8, 8), 1)
|
||||
index4 = get_relative_position_index_simple((8, 8), 1)
|
||||
# print(index2)
|
||||
print(
|
||||
table.shape,
|
||||
index2.shape,
|
||||
index2.max(),
|
||||
index2.min(),
|
||||
index4.shape,
|
||||
index4.max(),
|
||||
index4.min(),
|
||||
torch.allclose(index1, index2),
|
||||
torch.allclose(index3, index4),
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
class ResBlock(nn.Module):
|
||||
"""Residual block without BN.
|
||||
|
||||
It has a style of:
|
||||
|
||||
::
|
||||
|
||||
---Conv-ReLU-Conv-+-
|
||||
|________________|
|
||||
|
||||
Args:
|
||||
num_feats (int): Channel number of intermediate features.
|
||||
Default: 64.
|
||||
res_scale (float): Used to scale the residual before addition.
|
||||
Default: 1.0.
|
||||
"""
|
||||
|
||||
def __init__(self, num_feats=64, res_scale=1.0, bias=True, shortcut=True):
|
||||
super().__init__()
|
||||
self.res_scale = res_scale
|
||||
self.shortcut = shortcut
|
||||
self.conv1 = nn.Conv2d(num_feats, num_feats, 3, 1, 1, bias=bias)
|
||||
self.conv2 = nn.Conv2d(num_feats, num_feats, 3, 1, 1, bias=bias)
|
||||
self.relu = nn.ReLU(inplace=True)
|
||||
|
||||
def forward(self, x):
|
||||
"""Forward function.
|
||||
|
||||
Args:
|
||||
x (Tensor): Input tensor with shape (n, c, h, w).
|
||||
|
||||
Returns:
|
||||
Tensor: Forward results.
|
||||
"""
|
||||
|
||||
identity = x
|
||||
out = self.conv2(self.relu(self.conv1(x)))
|
||||
if self.shortcut:
|
||||
return identity + out * self.res_scale
|
||||
else:
|
||||
return out * self.res_scale
|
||||
|
||||
|
||||
class ResBlockWrapper(ResBlock):
|
||||
"Used for transformers"
|
||||
|
||||
def __init__(self, num_feats, bias=True, shortcut=True):
|
||||
super(ResBlockWrapper, self).__init__(
|
||||
num_feats=num_feats, bias=bias, shortcut=shortcut
|
||||
)
|
||||
|
||||
def forward(self, x, x_size):
|
||||
H, W = x_size
|
||||
B, L, C = x.shape
|
||||
x = x.view(B, H, W, C).permute(0, 3, 1, 2)
|
||||
x = super(ResBlockWrapper, self).forward(x)
|
||||
x = x.flatten(2).permute(0, 2, 1)
|
||||
return x
|
||||
@@ -0,0 +1,602 @@
|
||||
from math import prod
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from .ops import (
|
||||
bchw_to_blc,
|
||||
blc_to_bchw,
|
||||
calculate_mask,
|
||||
window_partition,
|
||||
window_reverse,
|
||||
)
|
||||
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
|
||||
|
||||
|
||||
class Mlp(nn.Module):
|
||||
"""MLP as used in Vision Transformer, MLP-Mixer and related networks"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_features,
|
||||
hidden_features=None,
|
||||
out_features=None,
|
||||
act_layer=nn.GELU,
|
||||
drop=0.0,
|
||||
):
|
||||
super().__init__()
|
||||
out_features = out_features or in_features
|
||||
hidden_features = hidden_features or in_features
|
||||
drop_probs = to_2tuple(drop)
|
||||
|
||||
self.fc1 = nn.Linear(in_features, hidden_features)
|
||||
self.act = act_layer()
|
||||
self.drop1 = nn.Dropout(drop_probs[0])
|
||||
self.fc2 = nn.Linear(hidden_features, out_features)
|
||||
self.drop2 = nn.Dropout(drop_probs[1])
|
||||
|
||||
def forward(self, x):
|
||||
x = self.fc1(x)
|
||||
x = self.act(x)
|
||||
x = self.drop1(x)
|
||||
x = self.fc2(x)
|
||||
x = self.drop2(x)
|
||||
return x
|
||||
|
||||
|
||||
class WindowAttentionV1(nn.Module):
|
||||
r"""Window based multi-head self attention (W-MSA) module with relative position bias.
|
||||
It supports both of shifted and non-shifted window.
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
window_size (tuple[int]): The height and width of the window.
|
||||
num_heads (int): Number of attention heads.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
|
||||
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
||||
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim,
|
||||
window_size,
|
||||
num_heads,
|
||||
qkv_bias=True,
|
||||
qk_scale=None,
|
||||
attn_drop=0.0,
|
||||
proj_drop=0.0,
|
||||
use_pe=True,
|
||||
):
|
||||
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.window_size = window_size # Wh, Ww
|
||||
self.num_heads = num_heads
|
||||
head_dim = dim // num_heads
|
||||
self.scale = qk_scale or head_dim**-0.5
|
||||
self.use_pe = use_pe
|
||||
|
||||
if self.use_pe:
|
||||
# define a parameter table of relative position bias
|
||||
ws = self.window_size
|
||||
table = torch.zeros((2 * ws[0] - 1) * (2 * ws[1] - 1), num_heads)
|
||||
self.relative_position_bias_table = nn.Parameter(table)
|
||||
# 2*Wh-1 * 2*Ww-1, nH
|
||||
trunc_normal_(self.relative_position_bias_table, std=0.02)
|
||||
|
||||
self.get_relative_position_index(self.window_size)
|
||||
|
||||
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
||||
self.attn_drop = nn.Dropout(attn_drop)
|
||||
self.proj = nn.Linear(dim, dim)
|
||||
|
||||
self.proj_drop = nn.Dropout(proj_drop)
|
||||
|
||||
self.softmax = nn.Softmax(dim=-1)
|
||||
|
||||
def get_relative_position_index(self, window_size):
|
||||
# get pair-wise relative position index for each token inside the window
|
||||
coord_h = torch.arange(window_size[0])
|
||||
coord_w = torch.arange(window_size[1])
|
||||
coords = torch.stack(torch.meshgrid([coord_h, coord_w])) # 2, Wh, Ww
|
||||
coords = torch.flatten(coords, 1) # 2, Wh*Ww
|
||||
coords = coords[:, :, None] - coords[:, None, :] # 2, Wh*Ww, Wh*Ww
|
||||
coords = coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
||||
coords[:, :, 0] += window_size[0] - 1 # shift to start from 0
|
||||
coords[:, :, 1] += window_size[1] - 1
|
||||
coords[:, :, 0] *= 2 * window_size[1] - 1
|
||||
relative_position_index = coords.sum(-1) # Wh*Ww, Wh*Ww
|
||||
self.register_buffer("relative_position_index", relative_position_index)
|
||||
|
||||
def forward(self, x, mask=None):
|
||||
"""
|
||||
Args:
|
||||
x: input features with shape of (num_windows*B, N, C)
|
||||
mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
|
||||
"""
|
||||
B_, N, C = x.shape
|
||||
|
||||
# qkv projection
|
||||
qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
||||
q, k, v = qkv[0], qkv[1], qkv[2]
|
||||
|
||||
# attention map
|
||||
q = q * self.scale
|
||||
attn = q @ k.transpose(-2, -1)
|
||||
|
||||
# positional encoding
|
||||
if self.use_pe:
|
||||
win_dim = prod(self.window_size)
|
||||
bias = self.relative_position_bias_table[
|
||||
self.relative_position_index.view(-1)
|
||||
]
|
||||
bias = bias.view(win_dim, win_dim, -1).permute(2, 0, 1).contiguous()
|
||||
# nH, Wh*Ww, Wh*Ww
|
||||
attn = attn + bias.unsqueeze(0)
|
||||
|
||||
# shift attention mask
|
||||
if mask is not None:
|
||||
nW = mask.shape[0]
|
||||
mask = mask.unsqueeze(1).unsqueeze(0)
|
||||
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask
|
||||
attn = attn.view(-1, self.num_heads, N, N)
|
||||
|
||||
# attention
|
||||
attn = self.softmax(attn)
|
||||
attn = self.attn_drop(attn)
|
||||
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
|
||||
|
||||
# output projection
|
||||
x = self.proj(x)
|
||||
x = self.proj_drop(x)
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return f"dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}"
|
||||
|
||||
def flops(self, N):
|
||||
# calculate flops for 1 window with token length of N
|
||||
flops = 0
|
||||
# qkv = self.qkv(x)
|
||||
flops += N * self.dim * 3 * self.dim
|
||||
# attn = (q @ k.transpose(-2, -1))
|
||||
flops += self.num_heads * N * (self.dim // self.num_heads) * N
|
||||
# x = (attn @ v)
|
||||
flops += self.num_heads * N * N * (self.dim // self.num_heads)
|
||||
# x = self.proj(x)
|
||||
flops += N * self.dim * self.dim
|
||||
return flops
|
||||
|
||||
|
||||
class WindowAttentionWrapperV1(WindowAttentionV1):
|
||||
def __init__(self, shift_size, input_resolution, **kwargs):
|
||||
super(WindowAttentionWrapperV1, self).__init__(**kwargs)
|
||||
self.shift_size = shift_size
|
||||
self.input_resolution = input_resolution
|
||||
|
||||
if self.shift_size > 0:
|
||||
attn_mask = calculate_mask(input_resolution, self.window_size, shift_size)
|
||||
else:
|
||||
attn_mask = None
|
||||
self.register_buffer("attn_mask", attn_mask)
|
||||
|
||||
def forward(self, x, x_size):
|
||||
H, W = x_size
|
||||
B, L, C = x.shape
|
||||
x = x.view(B, H, W, C)
|
||||
|
||||
# cyclic shift
|
||||
if self.shift_size > 0:
|
||||
x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
|
||||
|
||||
# partition windows
|
||||
x = window_partition(x, self.window_size) # nW*B, wh, ww, C
|
||||
x = x.view(-1, prod(self.window_size), C) # nW*B, wh*ww, C
|
||||
|
||||
# W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
|
||||
if self.input_resolution == x_size:
|
||||
attn_mask = self.attn_mask
|
||||
else:
|
||||
attn_mask = calculate_mask(x_size, self.window_size, self.shift_size)
|
||||
attn_mask = attn_mask.to(x.device)
|
||||
|
||||
# attention
|
||||
x = super(WindowAttentionWrapperV1, self).forward(x, mask=attn_mask)
|
||||
# nW*B, wh*ww, C
|
||||
|
||||
# merge windows
|
||||
x = x.view(-1, *self.window_size, C)
|
||||
x = window_reverse(x, self.window_size, x_size) # B, H, W, C
|
||||
|
||||
# reverse cyclic shift
|
||||
if self.shift_size > 0:
|
||||
x = torch.roll(x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
||||
x = x.view(B, H * W, C)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class SwinTransformerBlockV1(nn.Module):
|
||||
r"""Swin Transformer Block.
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
input_resolution (tuple[int]): Input resulotion.
|
||||
num_heads (int): Number of attention heads.
|
||||
window_size (int): Window size.
|
||||
shift_size (int): Shift size for SW-MSA.
|
||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
||||
drop (float, optional): Dropout rate. Default: 0.0
|
||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
||||
drop_path (float, optional): Stochastic depth rate. Default: 0.0
|
||||
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim,
|
||||
input_resolution,
|
||||
num_heads,
|
||||
window_size=7,
|
||||
shift_size=0,
|
||||
mlp_ratio=4.0,
|
||||
qkv_bias=True,
|
||||
qk_scale=None,
|
||||
drop=0.0,
|
||||
attn_drop=0.0,
|
||||
drop_path=0.0,
|
||||
act_layer=nn.GELU,
|
||||
norm_layer=nn.LayerNorm,
|
||||
use_pe=True,
|
||||
res_scale=1.0,
|
||||
):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.input_resolution = input_resolution
|
||||
self.num_heads = num_heads
|
||||
self.window_size = window_size
|
||||
self.shift_size = shift_size
|
||||
self.mlp_ratio = mlp_ratio
|
||||
if min(self.input_resolution) <= self.window_size:
|
||||
# if window size is larger than input resolution, we don't partition windows
|
||||
self.shift_size = 0
|
||||
self.window_size = min(self.input_resolution)
|
||||
assert (
|
||||
0 <= self.shift_size < self.window_size
|
||||
), "shift_size must in 0-window_size"
|
||||
self.res_scale = res_scale
|
||||
|
||||
self.norm1 = norm_layer(dim)
|
||||
self.attn = WindowAttentionWrapperV1(
|
||||
shift_size=self.shift_size,
|
||||
input_resolution=self.input_resolution,
|
||||
dim=dim,
|
||||
window_size=to_2tuple(self.window_size),
|
||||
num_heads=num_heads,
|
||||
qkv_bias=qkv_bias,
|
||||
qk_scale=qk_scale,
|
||||
attn_drop=attn_drop,
|
||||
proj_drop=drop,
|
||||
use_pe=use_pe,
|
||||
)
|
||||
|
||||
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
||||
|
||||
self.norm2 = norm_layer(dim)
|
||||
self.mlp = Mlp(
|
||||
in_features=dim,
|
||||
hidden_features=int(dim * mlp_ratio),
|
||||
act_layer=act_layer,
|
||||
drop=drop,
|
||||
)
|
||||
|
||||
def forward(self, x, x_size):
|
||||
# Window attention
|
||||
x = x + self.res_scale * self.drop_path(self.attn(self.norm1(x), x_size))
|
||||
# FFN
|
||||
x = x + self.res_scale * self.drop_path(self.mlp(self.norm2(x)))
|
||||
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return (
|
||||
f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, "
|
||||
f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}, res_scale={self.res_scale}"
|
||||
)
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
H, W = self.input_resolution
|
||||
# norm1
|
||||
flops += self.dim * H * W
|
||||
# W-MSA/SW-MSA
|
||||
nW = H * W / self.window_size / self.window_size
|
||||
flops += nW * self.attn.flops(self.window_size * self.window_size)
|
||||
# mlp
|
||||
flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
|
||||
# norm2
|
||||
flops += self.dim * H * W
|
||||
return flops
|
||||
|
||||
|
||||
class PatchMerging(nn.Module):
|
||||
r"""Patch Merging Layer.
|
||||
Args:
|
||||
input_resolution (tuple[int]): Resolution of input feature.
|
||||
dim (int): Number of input channels.
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
"""
|
||||
|
||||
def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
|
||||
super().__init__()
|
||||
self.input_resolution = input_resolution
|
||||
self.dim = dim
|
||||
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
||||
self.norm = norm_layer(4 * dim)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
x: B, H*W, C
|
||||
"""
|
||||
H, W = self.input_resolution
|
||||
B, L, C = x.shape
|
||||
assert L == H * W, "input feature has wrong size"
|
||||
assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
|
||||
|
||||
x = x.view(B, H, W, C)
|
||||
|
||||
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
|
||||
x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
|
||||
x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
|
||||
x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
|
||||
x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
|
||||
x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
|
||||
|
||||
x = self.norm(x)
|
||||
x = self.reduction(x)
|
||||
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return f"input_resolution={self.input_resolution}, dim={self.dim}"
|
||||
|
||||
def flops(self):
|
||||
H, W = self.input_resolution
|
||||
flops = H * W * self.dim
|
||||
flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
|
||||
return flops
|
||||
|
||||
|
||||
class PatchEmbed(nn.Module):
|
||||
r"""Image to Patch Embedding
|
||||
Args:
|
||||
img_size (int): Image size. Default: 224.
|
||||
patch_size (int): Patch token size. Default: 4.
|
||||
in_chans (int): Number of input image channels. Default: 3.
|
||||
embed_dim (int): Number of linear projection output channels. Default: 96.
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None
|
||||
):
|
||||
super().__init__()
|
||||
img_size = to_2tuple(img_size)
|
||||
patch_size = to_2tuple(patch_size)
|
||||
patches_resolution = [
|
||||
img_size[0] // patch_size[0],
|
||||
img_size[1] // patch_size[1],
|
||||
]
|
||||
self.img_size = img_size
|
||||
self.patch_size = patch_size
|
||||
self.patches_resolution = patches_resolution
|
||||
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
||||
|
||||
self.in_chans = in_chans
|
||||
self.embed_dim = embed_dim
|
||||
|
||||
if norm_layer is not None:
|
||||
self.norm = norm_layer(embed_dim)
|
||||
else:
|
||||
self.norm = None
|
||||
|
||||
def forward(self, x):
|
||||
x = x.flatten(2).transpose(1, 2) # B Ph*Pw C
|
||||
if self.norm is not None:
|
||||
x = self.norm(x)
|
||||
return x
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
H, W = self.img_size
|
||||
if self.norm is not None:
|
||||
flops += H * W * self.embed_dim
|
||||
return flops
|
||||
|
||||
|
||||
class PatchUnEmbed(nn.Module):
|
||||
r"""Image to Patch Unembedding
|
||||
Args:
|
||||
img_size (int): Image size. Default: 224.
|
||||
patch_size (int): Patch token size. Default: 4.
|
||||
in_chans (int): Number of input image channels. Default: 3.
|
||||
embed_dim (int): Number of linear projection output channels. Default: 96.
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None
|
||||
):
|
||||
super().__init__()
|
||||
img_size = to_2tuple(img_size)
|
||||
patch_size = to_2tuple(patch_size)
|
||||
patches_resolution = [
|
||||
img_size[0] // patch_size[0],
|
||||
img_size[1] // patch_size[1],
|
||||
]
|
||||
self.img_size = img_size
|
||||
self.patch_size = patch_size
|
||||
self.patches_resolution = patches_resolution
|
||||
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
||||
|
||||
self.in_chans = in_chans
|
||||
self.embed_dim = embed_dim
|
||||
|
||||
def forward(self, x, x_size):
|
||||
B, HW, C = x.shape
|
||||
x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C
|
||||
return x
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
return flops
|
||||
|
||||
|
||||
class Linear(nn.Linear):
|
||||
def __init__(self, in_features, out_features, bias=True):
|
||||
super(Linear, self).__init__(in_features, out_features, bias)
|
||||
|
||||
def forward(self, x):
|
||||
B, C, H, W = x.shape
|
||||
x = bchw_to_blc(x)
|
||||
x = super(Linear, self).forward(x)
|
||||
x = blc_to_bchw(x, (H, W))
|
||||
return x
|
||||
|
||||
|
||||
def build_last_conv(conv_type, dim):
|
||||
if conv_type == "1conv":
|
||||
block = nn.Conv2d(dim, dim, 3, 1, 1)
|
||||
elif conv_type == "3conv":
|
||||
# to save parameters and memory
|
||||
block = nn.Sequential(
|
||||
nn.Conv2d(dim, dim // 4, 3, 1, 1),
|
||||
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
||||
nn.Conv2d(dim // 4, dim // 4, 1, 1, 0),
|
||||
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
||||
nn.Conv2d(dim // 4, dim, 3, 1, 1),
|
||||
)
|
||||
elif conv_type == "1conv1x1":
|
||||
block = nn.Conv2d(dim, dim, 1, 1, 0)
|
||||
elif conv_type == "linear":
|
||||
block = Linear(dim, dim)
|
||||
return block
|
||||
|
||||
|
||||
# class BasicLayer(nn.Module):
|
||||
# """A basic Swin Transformer layer for one stage.
|
||||
# Args:
|
||||
# dim (int): Number of input channels.
|
||||
# input_resolution (tuple[int]): Input resolution.
|
||||
# depth (int): Number of blocks.
|
||||
# num_heads (int): Number of attention heads.
|
||||
# window_size (int): Local window size.
|
||||
# mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
||||
# qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
# qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
||||
# drop (float, optional): Dropout rate. Default: 0.0
|
||||
# attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
||||
# drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
||||
# norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
# downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
||||
# args: Additional arguments
|
||||
# """
|
||||
|
||||
# def __init__(
|
||||
# self,
|
||||
# dim,
|
||||
# input_resolution,
|
||||
# depth,
|
||||
# num_heads,
|
||||
# window_size,
|
||||
# mlp_ratio=4.0,
|
||||
# qkv_bias=True,
|
||||
# qk_scale=None,
|
||||
# drop=0.0,
|
||||
# attn_drop=0.0,
|
||||
# drop_path=0.0,
|
||||
# norm_layer=nn.LayerNorm,
|
||||
# downsample=None,
|
||||
# args=None,
|
||||
# ):
|
||||
|
||||
# super().__init__()
|
||||
# self.dim = dim
|
||||
# self.input_resolution = input_resolution
|
||||
# self.depth = depth
|
||||
|
||||
# # build blocks
|
||||
# self.blocks = nn.ModuleList(
|
||||
# [
|
||||
# _parse_block(
|
||||
# dim=dim,
|
||||
# input_resolution=input_resolution,
|
||||
# num_heads=num_heads,
|
||||
# window_size=window_size,
|
||||
# shift_size=0
|
||||
# if args.no_shift
|
||||
# else (0 if (i % 2 == 0) else window_size // 2),
|
||||
# mlp_ratio=mlp_ratio,
|
||||
# qkv_bias=qkv_bias,
|
||||
# qk_scale=qk_scale,
|
||||
# drop=drop,
|
||||
# attn_drop=attn_drop,
|
||||
# drop_path=drop_path[i]
|
||||
# if isinstance(drop_path, list)
|
||||
# else drop_path,
|
||||
# norm_layer=norm_layer,
|
||||
# stripe_type="H" if (i % 2 == 0) else "W",
|
||||
# args=args,
|
||||
# )
|
||||
# for i in range(depth)
|
||||
# ]
|
||||
# )
|
||||
# # self.blocks = nn.ModuleList(
|
||||
# # [
|
||||
# # STV1Block(
|
||||
# # dim=dim,
|
||||
# # input_resolution=input_resolution,
|
||||
# # num_heads=num_heads,
|
||||
# # window_size=window_size,
|
||||
# # shift_size=0 if (i % 2 == 0) else window_size // 2,
|
||||
# # mlp_ratio=mlp_ratio,
|
||||
# # qkv_bias=qkv_bias,
|
||||
# # qk_scale=qk_scale,
|
||||
# # drop=drop,
|
||||
# # attn_drop=attn_drop,
|
||||
# # drop_path=drop_path[i]
|
||||
# # if isinstance(drop_path, list)
|
||||
# # else drop_path,
|
||||
# # norm_layer=norm_layer,
|
||||
# # )
|
||||
# # for i in range(depth)
|
||||
# # ]
|
||||
# # )
|
||||
|
||||
# # patch merging layer
|
||||
# if downsample is not None:
|
||||
# self.downsample = downsample(
|
||||
# input_resolution, dim=dim, norm_layer=norm_layer
|
||||
# )
|
||||
# else:
|
||||
# self.downsample = None
|
||||
|
||||
# def forward(self, x, x_size):
|
||||
# for blk in self.blocks:
|
||||
# x = blk(x, x_size)
|
||||
# if self.downsample is not None:
|
||||
# x = self.downsample(x)
|
||||
# return x
|
||||
|
||||
# def extra_repr(self) -> str:
|
||||
# return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
|
||||
|
||||
# def flops(self):
|
||||
# flops = 0
|
||||
# for blk in self.blocks:
|
||||
# flops += blk.flops()
|
||||
# if self.downsample is not None:
|
||||
# flops += self.downsample.flops()
|
||||
# return flops
|
||||
@@ -0,0 +1,306 @@
|
||||
import math
|
||||
from math import prod
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from .ops import (
|
||||
calculate_mask,
|
||||
get_relative_coords_table,
|
||||
get_relative_position_index,
|
||||
window_partition,
|
||||
window_reverse,
|
||||
)
|
||||
from .swin_v1_block import Mlp
|
||||
from timm.models.layers import DropPath, to_2tuple
|
||||
|
||||
|
||||
class WindowAttentionV2(nn.Module):
|
||||
r"""Window based multi-head self attention (W-MSA) module with relative position bias.
|
||||
It supports both of shifted and non-shifted window.
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
window_size (tuple[int]): The height and width of the window.
|
||||
num_heads (int): Number of attention heads.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
||||
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
|
||||
pretrained_window_size (tuple[int]): The height and width of the window in pre-training.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim,
|
||||
window_size,
|
||||
num_heads,
|
||||
qkv_bias=True,
|
||||
attn_drop=0.0,
|
||||
proj_drop=0.0,
|
||||
pretrained_window_size=[0, 0],
|
||||
use_pe=True,
|
||||
):
|
||||
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.window_size = window_size # Wh, Ww
|
||||
self.pretrained_window_size = pretrained_window_size
|
||||
self.num_heads = num_heads
|
||||
self.use_pe = use_pe
|
||||
|
||||
self.logit_scale = nn.Parameter(
|
||||
torch.log(10 * torch.ones((num_heads, 1, 1))), requires_grad=True
|
||||
)
|
||||
|
||||
if self.use_pe:
|
||||
# mlp to generate continuous relative position bias
|
||||
self.cpb_mlp = nn.Sequential(
|
||||
nn.Linear(2, 512, bias=True),
|
||||
nn.ReLU(inplace=True),
|
||||
nn.Linear(512, num_heads, bias=False),
|
||||
)
|
||||
table = get_relative_coords_table(window_size, pretrained_window_size)
|
||||
index = get_relative_position_index(window_size)
|
||||
self.register_buffer("relative_coords_table", table)
|
||||
self.register_buffer("relative_position_index", index)
|
||||
|
||||
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
||||
# self.qkv = nn.Linear(dim, dim * 3, bias=False)
|
||||
# if qkv_bias:
|
||||
# self.q_bias = nn.Parameter(torch.zeros(dim))
|
||||
# self.v_bias = nn.Parameter(torch.zeros(dim))
|
||||
# else:
|
||||
# self.q_bias = None
|
||||
# self.v_bias = None
|
||||
self.attn_drop = nn.Dropout(attn_drop)
|
||||
self.proj = nn.Linear(dim, dim)
|
||||
self.proj_drop = nn.Dropout(proj_drop)
|
||||
self.softmax = nn.Softmax(dim=-1)
|
||||
|
||||
def forward(self, x, mask=None):
|
||||
"""
|
||||
Args:
|
||||
x: input features with shape of (num_windows*B, N, C)
|
||||
mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
|
||||
"""
|
||||
B_, N, C = x.shape
|
||||
|
||||
# qkv projection
|
||||
# qkv_bias = None
|
||||
# if self.q_bias is not None:
|
||||
# qkv_bias = torch.cat(
|
||||
# (
|
||||
# self.q_bias,
|
||||
# torch.zeros_like(self.v_bias, requires_grad=False),
|
||||
# self.v_bias,
|
||||
# )
|
||||
# )
|
||||
# qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
|
||||
qkv = self.qkv(x)
|
||||
qkv = qkv.reshape(B_, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
||||
q, k, v = qkv[0], qkv[1], qkv[2]
|
||||
|
||||
# cosine attention map
|
||||
attn = F.normalize(q, dim=-1) @ F.normalize(k, dim=-1).transpose(-2, -1)
|
||||
logit_scale = torch.clamp(self.logit_scale, max=math.log(1.0 / 0.01)).exp()
|
||||
attn = attn * logit_scale
|
||||
|
||||
# positional encoding
|
||||
if self.use_pe:
|
||||
bias_table = self.cpb_mlp(self.relative_coords_table)
|
||||
bias_table = bias_table.view(-1, self.num_heads)
|
||||
|
||||
win_dim = prod(self.window_size)
|
||||
bias = bias_table[self.relative_position_index.view(-1)]
|
||||
bias = bias.view(win_dim, win_dim, -1).permute(2, 0, 1).contiguous()
|
||||
# nH, Wh*Ww, Wh*Ww
|
||||
bias = 16 * torch.sigmoid(bias)
|
||||
attn = attn + bias.unsqueeze(0)
|
||||
|
||||
# shift attention mask
|
||||
if mask is not None:
|
||||
nW = mask.shape[0]
|
||||
mask = mask.unsqueeze(1).unsqueeze(0)
|
||||
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask
|
||||
attn = attn.view(-1, self.num_heads, N, N)
|
||||
|
||||
# attention
|
||||
attn = self.softmax(attn)
|
||||
attn = self.attn_drop(attn)
|
||||
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
|
||||
|
||||
# output projection
|
||||
x = self.proj(x)
|
||||
x = self.proj_drop(x)
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return (
|
||||
f"dim={self.dim}, window_size={self.window_size}, "
|
||||
f"pretrained_window_size={self.pretrained_window_size}, num_heads={self.num_heads}"
|
||||
)
|
||||
|
||||
def flops(self, N):
|
||||
# calculate flops for 1 window with token length of N
|
||||
flops = 0
|
||||
# qkv = self.qkv(x)
|
||||
flops += N * self.dim * 3 * self.dim
|
||||
# attn = (q @ k.transpose(-2, -1))
|
||||
flops += self.num_heads * N * (self.dim // self.num_heads) * N
|
||||
# x = (attn @ v)
|
||||
flops += self.num_heads * N * N * (self.dim // self.num_heads)
|
||||
# x = self.proj(x)
|
||||
flops += N * self.dim * self.dim
|
||||
return flops
|
||||
|
||||
|
||||
class WindowAttentionWrapperV2(WindowAttentionV2):
|
||||
def __init__(self, shift_size, input_resolution, **kwargs):
|
||||
super(WindowAttentionWrapperV2, self).__init__(**kwargs)
|
||||
self.shift_size = shift_size
|
||||
self.input_resolution = input_resolution
|
||||
|
||||
if self.shift_size > 0:
|
||||
attn_mask = calculate_mask(input_resolution, self.window_size, shift_size)
|
||||
else:
|
||||
attn_mask = None
|
||||
self.register_buffer("attn_mask", attn_mask)
|
||||
|
||||
def forward(self, x, x_size):
|
||||
H, W = x_size
|
||||
B, L, C = x.shape
|
||||
x = x.view(B, H, W, C)
|
||||
|
||||
# cyclic shift
|
||||
if self.shift_size > 0:
|
||||
x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
|
||||
|
||||
# partition windows
|
||||
x = window_partition(x, self.window_size) # nW*B, wh, ww, C
|
||||
x = x.view(-1, prod(self.window_size), C) # nW*B, wh*ww, C
|
||||
|
||||
# W-MSA/SW-MSA
|
||||
if self.input_resolution == x_size:
|
||||
attn_mask = self.attn_mask
|
||||
else:
|
||||
attn_mask = calculate_mask(x_size, self.window_size, self.shift_size)
|
||||
attn_mask = attn_mask.to(x.device)
|
||||
|
||||
# attention
|
||||
x = super(WindowAttentionWrapperV2, self).forward(x, mask=attn_mask)
|
||||
# nW*B, wh*ww, C
|
||||
|
||||
# merge windows
|
||||
x = x.view(-1, *self.window_size, C)
|
||||
x = window_reverse(x, self.window_size, x_size) # B, H, W, C
|
||||
|
||||
# reverse cyclic shift
|
||||
if self.shift_size > 0:
|
||||
x = torch.roll(x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
||||
x = x.view(B, H * W, C)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
class SwinTransformerBlockV2(nn.Module):
|
||||
r"""Swin Transformer Block.
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
input_resolution (tuple[int]): Input resulotion.
|
||||
num_heads (int): Number of attention heads.
|
||||
window_size (int): Window size.
|
||||
shift_size (int): Shift size for SW-MSA.
|
||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
drop (float, optional): Dropout rate. Default: 0.0
|
||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
||||
drop_path (float, optional): Stochastic depth rate. Default: 0.0
|
||||
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
pretrained_window_size (int): Window size in pre-training.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim,
|
||||
input_resolution,
|
||||
num_heads,
|
||||
window_size=7,
|
||||
shift_size=0,
|
||||
mlp_ratio=4.0,
|
||||
qkv_bias=True,
|
||||
drop=0.0,
|
||||
attn_drop=0.0,
|
||||
drop_path=0.0,
|
||||
act_layer=nn.GELU,
|
||||
norm_layer=nn.LayerNorm,
|
||||
pretrained_window_size=0,
|
||||
use_pe=True,
|
||||
res_scale=1.0,
|
||||
):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.input_resolution = input_resolution
|
||||
self.num_heads = num_heads
|
||||
self.window_size = window_size
|
||||
self.shift_size = shift_size
|
||||
self.mlp_ratio = mlp_ratio
|
||||
if min(self.input_resolution) <= self.window_size:
|
||||
# if window size is larger than input resolution, we don't partition windows
|
||||
self.shift_size = 0
|
||||
self.window_size = min(self.input_resolution)
|
||||
assert (
|
||||
0 <= self.shift_size < self.window_size
|
||||
), "shift_size must in 0-window_size"
|
||||
self.res_scale = res_scale
|
||||
|
||||
self.attn = WindowAttentionWrapperV2(
|
||||
shift_size=self.shift_size,
|
||||
input_resolution=self.input_resolution,
|
||||
dim=dim,
|
||||
window_size=to_2tuple(self.window_size),
|
||||
num_heads=num_heads,
|
||||
qkv_bias=qkv_bias,
|
||||
attn_drop=attn_drop,
|
||||
proj_drop=drop,
|
||||
pretrained_window_size=to_2tuple(pretrained_window_size),
|
||||
use_pe=use_pe,
|
||||
)
|
||||
self.norm1 = norm_layer(dim)
|
||||
|
||||
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
||||
|
||||
self.mlp = Mlp(
|
||||
in_features=dim,
|
||||
hidden_features=int(dim * mlp_ratio),
|
||||
act_layer=act_layer,
|
||||
drop=drop,
|
||||
)
|
||||
self.norm2 = norm_layer(dim)
|
||||
|
||||
def forward(self, x, x_size):
|
||||
# Window attention
|
||||
x = x + self.res_scale * self.drop_path(self.norm1(self.attn(x, x_size)))
|
||||
# FFN
|
||||
x = x + self.res_scale * self.drop_path(self.norm2(self.mlp(x)))
|
||||
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return (
|
||||
f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, "
|
||||
f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}, res_scale={self.res_scale}"
|
||||
)
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
H, W = self.input_resolution
|
||||
# norm1
|
||||
flops += self.dim * H * W
|
||||
# W-MSA/SW-MSA
|
||||
nW = H * W / self.window_size / self.window_size
|
||||
flops += nW * self.attn.flops(self.window_size * self.window_size)
|
||||
# mlp
|
||||
flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
|
||||
# norm2
|
||||
flops += self.dim * H * W
|
||||
return flops
|
||||
@@ -0,0 +1,50 @@
|
||||
import math
|
||||
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
class Upsample(nn.Module):
|
||||
"""Upsample module.
|
||||
Args:
|
||||
scale (int): Scale factor. Supported scales: 2^n and 3.
|
||||
num_feat (int): Channel number of intermediate features.
|
||||
"""
|
||||
|
||||
def __init__(self, scale, num_feat):
|
||||
super(Upsample, self).__init__()
|
||||
m = []
|
||||
if (scale & (scale - 1)) == 0: # scale = 2^n
|
||||
for _ in range(int(math.log(scale, 2))):
|
||||
m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
|
||||
m.append(nn.PixelShuffle(2))
|
||||
elif scale == 3:
|
||||
m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
|
||||
m.append(nn.PixelShuffle(3))
|
||||
else:
|
||||
raise ValueError(
|
||||
f"scale {scale} is not supported. " "Supported scales: 2^n and 3."
|
||||
)
|
||||
self.up = nn.Sequential(*m)
|
||||
|
||||
def forward(self, x):
|
||||
return self.up(x)
|
||||
|
||||
|
||||
class UpsampleOneStep(nn.Module):
|
||||
"""UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
|
||||
Used in lightweight SR to save parameters.
|
||||
Args:
|
||||
scale (int): Scale factor. Supported scales: 2^n and 3.
|
||||
num_feat (int): Channel number of intermediate features.
|
||||
"""
|
||||
|
||||
def __init__(self, scale, num_feat, num_out_ch):
|
||||
super(UpsampleOneStep, self).__init__()
|
||||
self.num_feat = num_feat
|
||||
m = []
|
||||
m.append(nn.Conv2d(num_feat, (scale**2) * num_out_ch, 3, 1, 1))
|
||||
m.append(nn.PixelShuffle(scale))
|
||||
self.up = nn.Sequential(*m)
|
||||
|
||||
def forward(self, x):
|
||||
return self.up(x)
|
||||
@@ -0,0 +1,218 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Paper Github Repository: https://github.com/xinntao/Real-ESRGAN
|
||||
# Code snippet from: https://github.com/XPixelGroup/BasicSR/blob/master/basicsr/archs/rrdbnet_arch.py
|
||||
# Paper: https://arxiv.org/pdf/2107.10833.pdf
|
||||
|
||||
import os, sys
|
||||
import torch
|
||||
from torch import nn as nn
|
||||
from torch.nn import functional as F
|
||||
from itertools import repeat
|
||||
from torch.nn import init as init
|
||||
from torch.nn.modules.batchnorm import _BatchNorm
|
||||
|
||||
|
||||
def pixel_unshuffle(x, scale):
|
||||
""" Pixel unshuffle.
|
||||
|
||||
Args:
|
||||
x (Tensor): Input feature with shape (b, c, hh, hw).
|
||||
scale (int): Downsample ratio.
|
||||
|
||||
Returns:
|
||||
Tensor: the pixel unshuffled feature.
|
||||
"""
|
||||
b, c, hh, hw = x.size()
|
||||
out_channel = c * (scale**2)
|
||||
assert hh % scale == 0 and hw % scale == 0
|
||||
h = hh // scale
|
||||
w = hw // scale
|
||||
x_view = x.view(b, c, h, scale, w, scale)
|
||||
return x_view.permute(0, 1, 3, 5, 2, 4).reshape(b, out_channel, h, w)
|
||||
|
||||
def make_layer(basic_block, num_basic_block, **kwarg):
|
||||
"""Make layers by stacking the same blocks.
|
||||
|
||||
Args:
|
||||
basic_block (nn.module): nn.module class for basic block.
|
||||
num_basic_block (int): number of blocks.
|
||||
|
||||
Returns:
|
||||
nn.Sequential: Stacked blocks in nn.Sequential.
|
||||
"""
|
||||
layers = []
|
||||
for _ in range(num_basic_block):
|
||||
layers.append(basic_block(**kwarg))
|
||||
return nn.Sequential(*layers)
|
||||
|
||||
def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs):
|
||||
"""Initialize network weights.
|
||||
|
||||
Args:
|
||||
module_list (list[nn.Module] | nn.Module): Modules to be initialized.
|
||||
scale (float): Scale initialized weights, especially for residual
|
||||
blocks. Default: 1.
|
||||
bias_fill (float): The value to fill bias. Default: 0
|
||||
kwargs (dict): Other arguments for initialization function.
|
||||
"""
|
||||
if not isinstance(module_list, list):
|
||||
module_list = [module_list]
|
||||
for module in module_list:
|
||||
for m in module.modules():
|
||||
if isinstance(m, nn.Conv2d):
|
||||
init.kaiming_normal_(m.weight, **kwargs)
|
||||
m.weight.data *= scale
|
||||
if m.bias is not None:
|
||||
m.bias.data.fill_(bias_fill)
|
||||
elif isinstance(m, nn.Linear):
|
||||
init.kaiming_normal_(m.weight, **kwargs)
|
||||
m.weight.data *= scale
|
||||
if m.bias is not None:
|
||||
m.bias.data.fill_(bias_fill)
|
||||
elif isinstance(m, _BatchNorm):
|
||||
init.constant_(m.weight, 1)
|
||||
if m.bias is not None:
|
||||
m.bias.data.fill_(bias_fill)
|
||||
|
||||
class ResidualDenseBlock(nn.Module):
|
||||
"""Residual Dense Block.
|
||||
|
||||
Used in RRDB block in ESRGAN.
|
||||
|
||||
Args:
|
||||
num_feat (int): Channel number of intermediate features.
|
||||
num_grow_ch (int): Channels for each growth.
|
||||
"""
|
||||
|
||||
def __init__(self, num_feat=64, num_grow_ch=32):
|
||||
super(ResidualDenseBlock, self).__init__()
|
||||
self.conv1 = nn.Conv2d(num_feat, num_grow_ch, 3, 1, 1)
|
||||
self.conv2 = nn.Conv2d(num_feat + num_grow_ch, num_grow_ch, 3, 1, 1)
|
||||
self.conv3 = nn.Conv2d(num_feat + 2 * num_grow_ch, num_grow_ch, 3, 1, 1)
|
||||
self.conv4 = nn.Conv2d(num_feat + 3 * num_grow_ch, num_grow_ch, 3, 1, 1)
|
||||
self.conv5 = nn.Conv2d(num_feat + 4 * num_grow_ch, num_feat, 3, 1, 1)
|
||||
|
||||
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
|
||||
|
||||
# initialization
|
||||
default_init_weights([self.conv1, self.conv2, self.conv3, self.conv4, self.conv5], 0.1)
|
||||
|
||||
def forward(self, x):
|
||||
x1 = self.lrelu(self.conv1(x))
|
||||
x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1)))
|
||||
x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1)))
|
||||
x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1)))
|
||||
x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1))
|
||||
# Empirically, we use 0.2 to scale the residual for better performance
|
||||
return x5 * 0.2 + x
|
||||
|
||||
|
||||
class RRDB(nn.Module):
|
||||
"""Residual in Residual Dense Block.
|
||||
|
||||
Used in RRDB-Net in ESRGAN.
|
||||
|
||||
Args:
|
||||
num_feat (int): Channel number of intermediate features.
|
||||
num_grow_ch (int): Channels for each growth.
|
||||
"""
|
||||
|
||||
def __init__(self, num_feat, num_grow_ch=32):
|
||||
super(RRDB, self).__init__()
|
||||
self.rdb1 = ResidualDenseBlock(num_feat, num_grow_ch)
|
||||
self.rdb2 = ResidualDenseBlock(num_feat, num_grow_ch)
|
||||
self.rdb3 = ResidualDenseBlock(num_feat, num_grow_ch)
|
||||
|
||||
def forward(self, x):
|
||||
out = self.rdb1(x)
|
||||
out = self.rdb2(out)
|
||||
out = self.rdb3(out)
|
||||
# Empirically, we use 0.2 to scale the residual for better performance
|
||||
return out * 0.2 + x
|
||||
|
||||
|
||||
|
||||
class RRDBNet(nn.Module):
|
||||
"""Networks consisting of Residual in Residual Dense Block, which is used
|
||||
in ESRGAN.
|
||||
|
||||
ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks.
|
||||
|
||||
We extend ESRGAN for scale x2 and scale x1.
|
||||
Note: This is one option for scale 1, scale 2 in RRDBNet.
|
||||
We first employ the pixel-unshuffle (an inverse operation of pixelshuffle to reduce the spatial size
|
||||
and enlarge the channel size before feeding inputs into the main ESRGAN architecture.
|
||||
|
||||
Args:
|
||||
num_in_ch (int): Channel number of inputs.
|
||||
num_out_ch (int): Channel number of outputs.
|
||||
num_feat (int): Channel number of intermediate features.
|
||||
Default: 64
|
||||
num_block (int): Block number in the trunk network. Defaults: 6 for our Anime training cases
|
||||
num_grow_ch (int): Channels for each growth. Default: 32.
|
||||
"""
|
||||
|
||||
def __init__(self, num_in_ch, num_out_ch, scale, num_feat=64, num_block=6, num_grow_ch=32):
|
||||
|
||||
super(RRDBNet, self).__init__()
|
||||
self.scale = scale
|
||||
if scale == 2:
|
||||
num_in_ch = num_in_ch * 4
|
||||
elif scale == 1:
|
||||
num_in_ch = num_in_ch * 16
|
||||
self.conv_first = nn.Conv2d(num_in_ch, num_feat, 3, 1, 1)
|
||||
self.body = make_layer(RRDB, num_block, num_feat=num_feat, num_grow_ch=num_grow_ch)
|
||||
self.conv_body = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||
# upsample
|
||||
self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||
self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||
self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
||||
|
||||
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
|
||||
|
||||
def forward(self, x):
|
||||
if self.scale == 2:
|
||||
feat = pixel_unshuffle(x, scale=2)
|
||||
elif self.scale == 1:
|
||||
feat = pixel_unshuffle(x, scale=4)
|
||||
else:
|
||||
feat = x
|
||||
feat = self.conv_first(feat)
|
||||
body_feat = self.conv_body(self.body(feat))
|
||||
feat = feat + body_feat
|
||||
# upsample
|
||||
feat = self.lrelu(self.conv_up1(F.interpolate(feat, scale_factor=2, mode='nearest')))
|
||||
feat = self.lrelu(self.conv_up2(F.interpolate(feat, scale_factor=2, mode='nearest')))
|
||||
out = self.conv_last(self.lrelu(self.conv_hr(feat)))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
# def main():
|
||||
# root_path = os.path.abspath('.')
|
||||
# sys.path.append(root_path)
|
||||
|
||||
# from opt import opt # Manage GPU to choose
|
||||
# from pthflops import count_ops
|
||||
# #from torchsummary import summary
|
||||
# import time
|
||||
|
||||
# # We use RRDB 6Blocks by default.
|
||||
# model = RRDBNet(3, 3)
|
||||
# pytorch_total_params = sum(p.numel() for p in model.parameters())
|
||||
# print(f"RRDB has param {pytorch_total_params//1000} K params")
|
||||
|
||||
|
||||
# # Count the number of FLOPs to double check
|
||||
# x = torch.randn((1, 3, 180, 180))
|
||||
# start = time.time()
|
||||
# x = model(x)
|
||||
# print("output size is ", x.shape)
|
||||
# total = time.time() - start
|
||||
# print(total)
|
||||
|
||||
|
||||
# if __name__ == "__main__":
|
||||
# main()
|
||||
@@ -0,0 +1,874 @@
|
||||
# -----------------------------------------------------------------------------------
|
||||
# SwinIR: Image Restoration Using Swin Transformer, https://arxiv.org/abs/2108.10257
|
||||
# Originally Written by Ze Liu, Modified by Jingyun Liang.
|
||||
# -----------------------------------------------------------------------------------
|
||||
|
||||
import math
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import torch.utils.checkpoint as checkpoint
|
||||
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
|
||||
|
||||
|
||||
class Mlp(nn.Module):
|
||||
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
|
||||
super().__init__()
|
||||
out_features = out_features or in_features
|
||||
hidden_features = hidden_features or in_features
|
||||
self.fc1 = nn.Linear(in_features, hidden_features)
|
||||
self.act = act_layer()
|
||||
self.fc2 = nn.Linear(hidden_features, out_features)
|
||||
self.drop = nn.Dropout(drop)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.fc1(x)
|
||||
x = self.act(x)
|
||||
x = self.drop(x)
|
||||
x = self.fc2(x)
|
||||
x = self.drop(x)
|
||||
return x
|
||||
|
||||
|
||||
def window_partition(x, window_size):
|
||||
"""
|
||||
Args:
|
||||
x: (B, H, W, C)
|
||||
window_size (int): window size
|
||||
|
||||
Returns:
|
||||
windows: (num_windows*B, window_size, window_size, C)
|
||||
"""
|
||||
B, H, W, C = x.shape
|
||||
x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
|
||||
windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
|
||||
return windows
|
||||
|
||||
|
||||
def window_reverse(windows, window_size, H, W):
|
||||
"""
|
||||
Args:
|
||||
windows: (num_windows*B, window_size, window_size, C)
|
||||
window_size (int): Window size
|
||||
H (int): Height of image
|
||||
W (int): Width of image
|
||||
|
||||
Returns:
|
||||
x: (B, H, W, C)
|
||||
"""
|
||||
B = int(windows.shape[0] / (H * W / window_size / window_size))
|
||||
x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
|
||||
x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
|
||||
return x
|
||||
|
||||
|
||||
class WindowAttention(nn.Module):
|
||||
r""" Window based multi-head self attention (W-MSA) module with relative position bias.
|
||||
It supports both of shifted and non-shifted window.
|
||||
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
window_size (tuple[int]): The height and width of the window.
|
||||
num_heads (int): Number of attention heads.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
|
||||
attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
|
||||
proj_drop (float, optional): Dropout ratio of output. Default: 0.0
|
||||
"""
|
||||
|
||||
def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):
|
||||
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.window_size = window_size # Wh, Ww
|
||||
self.num_heads = num_heads
|
||||
head_dim = dim // num_heads
|
||||
self.scale = qk_scale or head_dim ** -0.5
|
||||
|
||||
# define a parameter table of relative position bias
|
||||
self.relative_position_bias_table = nn.Parameter(
|
||||
torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)) # 2*Wh-1 * 2*Ww-1, nH
|
||||
|
||||
# get pair-wise relative position index for each token inside the window
|
||||
coords_h = torch.arange(self.window_size[0])
|
||||
coords_w = torch.arange(self.window_size[1])
|
||||
coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
|
||||
coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
|
||||
relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
|
||||
relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
|
||||
relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
|
||||
relative_coords[:, :, 1] += self.window_size[1] - 1
|
||||
relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
|
||||
relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
|
||||
self.register_buffer("relative_position_index", relative_position_index)
|
||||
|
||||
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
||||
self.attn_drop = nn.Dropout(attn_drop)
|
||||
self.proj = nn.Linear(dim, dim)
|
||||
|
||||
self.proj_drop = nn.Dropout(proj_drop)
|
||||
|
||||
trunc_normal_(self.relative_position_bias_table, std=.02)
|
||||
self.softmax = nn.Softmax(dim=-1)
|
||||
|
||||
def forward(self, x, mask=None):
|
||||
"""
|
||||
Args:
|
||||
x: input features with shape of (num_windows*B, N, C)
|
||||
mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
|
||||
"""
|
||||
B_, N, C = x.shape
|
||||
qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
||||
q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
|
||||
|
||||
q = q * self.scale
|
||||
attn = (q @ k.transpose(-2, -1))
|
||||
|
||||
relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(
|
||||
self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1) # Wh*Ww,Wh*Ww,nH
|
||||
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
||||
attn = attn + relative_position_bias.unsqueeze(0)
|
||||
|
||||
if mask is not None:
|
||||
nW = mask.shape[0]
|
||||
attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
|
||||
attn = attn.view(-1, self.num_heads, N, N)
|
||||
attn = self.softmax(attn)
|
||||
else:
|
||||
attn = self.softmax(attn)
|
||||
|
||||
attn = self.attn_drop(attn)
|
||||
|
||||
x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
|
||||
x = self.proj(x)
|
||||
x = self.proj_drop(x)
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return f'dim={self.dim}, window_size={self.window_size}, num_heads={self.num_heads}'
|
||||
|
||||
def flops(self, N):
|
||||
# calculate flops for 1 window with token length of N
|
||||
flops = 0
|
||||
# qkv = self.qkv(x)
|
||||
flops += N * self.dim * 3 * self.dim
|
||||
# attn = (q @ k.transpose(-2, -1))
|
||||
flops += self.num_heads * N * (self.dim // self.num_heads) * N
|
||||
# x = (attn @ v)
|
||||
flops += self.num_heads * N * N * (self.dim // self.num_heads)
|
||||
# x = self.proj(x)
|
||||
flops += N * self.dim * self.dim
|
||||
return flops
|
||||
|
||||
|
||||
class SwinTransformerBlock(nn.Module):
|
||||
r""" Swin Transformer Block.
|
||||
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
input_resolution (tuple[int]): Input resulotion.
|
||||
num_heads (int): Number of attention heads.
|
||||
window_size (int): Window size.
|
||||
shift_size (int): Shift size for SW-MSA.
|
||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
||||
drop (float, optional): Dropout rate. Default: 0.0
|
||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
||||
drop_path (float, optional): Stochastic depth rate. Default: 0.0
|
||||
act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
"""
|
||||
|
||||
def __init__(self, dim, input_resolution, num_heads, window_size=7, shift_size=0,
|
||||
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,
|
||||
act_layer=nn.GELU, norm_layer=nn.LayerNorm):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.input_resolution = input_resolution
|
||||
self.num_heads = num_heads
|
||||
self.window_size = window_size
|
||||
self.shift_size = shift_size
|
||||
self.mlp_ratio = mlp_ratio
|
||||
if min(self.input_resolution) <= self.window_size:
|
||||
# if window size is larger than input resolution, we don't partition windows
|
||||
self.shift_size = 0
|
||||
self.window_size = min(self.input_resolution)
|
||||
assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
|
||||
|
||||
self.norm1 = norm_layer(dim)
|
||||
self.attn = WindowAttention(
|
||||
dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,
|
||||
qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
|
||||
|
||||
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
|
||||
self.norm2 = norm_layer(dim)
|
||||
mlp_hidden_dim = int(dim * mlp_ratio)
|
||||
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
|
||||
|
||||
if self.shift_size > 0:
|
||||
attn_mask = self.calculate_mask(self.input_resolution)
|
||||
else:
|
||||
attn_mask = None
|
||||
|
||||
self.register_buffer("attn_mask", attn_mask)
|
||||
|
||||
def calculate_mask(self, x_size):
|
||||
# calculate attention mask for SW-MSA
|
||||
H, W = x_size
|
||||
img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1
|
||||
h_slices = (slice(0, -self.window_size),
|
||||
slice(-self.window_size, -self.shift_size),
|
||||
slice(-self.shift_size, None))
|
||||
w_slices = (slice(0, -self.window_size),
|
||||
slice(-self.window_size, -self.shift_size),
|
||||
slice(-self.shift_size, None))
|
||||
cnt = 0
|
||||
for h in h_slices:
|
||||
for w in w_slices:
|
||||
img_mask[:, h, w, :] = cnt
|
||||
cnt += 1
|
||||
|
||||
mask_windows = window_partition(img_mask, self.window_size) # nW, window_size, window_size, 1
|
||||
mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
|
||||
attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
|
||||
attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
|
||||
|
||||
return attn_mask
|
||||
|
||||
def forward(self, x, x_size):
|
||||
H, W = x_size
|
||||
B, L, C = x.shape
|
||||
# assert L == H * W, "input feature has wrong size"
|
||||
|
||||
shortcut = x
|
||||
x = self.norm1(x)
|
||||
x = x.view(B, H, W, C)
|
||||
|
||||
# cyclic shift
|
||||
if self.shift_size > 0:
|
||||
shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
|
||||
else:
|
||||
shifted_x = x
|
||||
|
||||
# partition windows
|
||||
x_windows = window_partition(shifted_x, self.window_size) # nW*B, window_size, window_size, C
|
||||
x_windows = x_windows.view(-1, self.window_size * self.window_size, C) # nW*B, window_size*window_size, C
|
||||
|
||||
# W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size
|
||||
if self.input_resolution == x_size:
|
||||
attn_windows = self.attn(x_windows, mask=self.attn_mask) # nW*B, window_size*window_size, C
|
||||
else:
|
||||
attn_windows = self.attn(x_windows, mask=self.calculate_mask(x_size).to(x.device))
|
||||
|
||||
# merge windows
|
||||
attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
|
||||
shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C
|
||||
|
||||
# reverse cyclic shift
|
||||
if self.shift_size > 0:
|
||||
x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
|
||||
else:
|
||||
x = shifted_x
|
||||
x = x.view(B, H * W, C)
|
||||
|
||||
# FFN
|
||||
x = shortcut + self.drop_path(x)
|
||||
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
||||
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " \
|
||||
f"window_size={self.window_size}, shift_size={self.shift_size}, mlp_ratio={self.mlp_ratio}"
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
H, W = self.input_resolution
|
||||
# norm1
|
||||
flops += self.dim * H * W
|
||||
# W-MSA/SW-MSA
|
||||
nW = H * W / self.window_size / self.window_size
|
||||
flops += nW * self.attn.flops(self.window_size * self.window_size)
|
||||
# mlp
|
||||
flops += 2 * H * W * self.dim * self.dim * self.mlp_ratio
|
||||
# norm2
|
||||
flops += self.dim * H * W
|
||||
return flops
|
||||
|
||||
|
||||
class PatchMerging(nn.Module):
|
||||
r""" Patch Merging Layer.
|
||||
|
||||
Args:
|
||||
input_resolution (tuple[int]): Resolution of input feature.
|
||||
dim (int): Number of input channels.
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
"""
|
||||
|
||||
def __init__(self, input_resolution, dim, norm_layer=nn.LayerNorm):
|
||||
super().__init__()
|
||||
self.input_resolution = input_resolution
|
||||
self.dim = dim
|
||||
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
||||
self.norm = norm_layer(4 * dim)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
x: B, H*W, C
|
||||
"""
|
||||
H, W = self.input_resolution
|
||||
B, L, C = x.shape
|
||||
assert L == H * W, "input feature has wrong size"
|
||||
assert H % 2 == 0 and W % 2 == 0, f"x size ({H}*{W}) are not even."
|
||||
|
||||
x = x.view(B, H, W, C)
|
||||
|
||||
x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
|
||||
x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
|
||||
x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
|
||||
x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
|
||||
x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
|
||||
x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
|
||||
|
||||
x = self.norm(x)
|
||||
x = self.reduction(x)
|
||||
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return f"input_resolution={self.input_resolution}, dim={self.dim}"
|
||||
|
||||
def flops(self):
|
||||
H, W = self.input_resolution
|
||||
flops = H * W * self.dim
|
||||
flops += (H // 2) * (W // 2) * 4 * self.dim * 2 * self.dim
|
||||
return flops
|
||||
|
||||
|
||||
class BasicLayer(nn.Module):
|
||||
""" A basic Swin Transformer layer for one stage.
|
||||
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
input_resolution (tuple[int]): Input resolution.
|
||||
depth (int): Number of blocks.
|
||||
num_heads (int): Number of attention heads.
|
||||
window_size (int): Local window size.
|
||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
||||
drop (float, optional): Dropout rate. Default: 0.0
|
||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
||||
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
||||
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
||||
"""
|
||||
|
||||
def __init__(self, dim, input_resolution, depth, num_heads, window_size,
|
||||
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
|
||||
drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False):
|
||||
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.input_resolution = input_resolution
|
||||
self.depth = depth
|
||||
self.use_checkpoint = use_checkpoint
|
||||
|
||||
# build blocks
|
||||
self.blocks = nn.ModuleList([
|
||||
SwinTransformerBlock(dim=dim, input_resolution=input_resolution,
|
||||
num_heads=num_heads, window_size=window_size,
|
||||
shift_size=0 if (i % 2 == 0) else window_size // 2,
|
||||
mlp_ratio=mlp_ratio,
|
||||
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
||||
drop=drop, attn_drop=attn_drop,
|
||||
drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
|
||||
norm_layer=norm_layer)
|
||||
for i in range(depth)])
|
||||
|
||||
# patch merging layer
|
||||
if downsample is not None:
|
||||
self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer)
|
||||
else:
|
||||
self.downsample = None
|
||||
|
||||
def forward(self, x, x_size):
|
||||
for blk in self.blocks:
|
||||
if self.use_checkpoint:
|
||||
x = checkpoint.checkpoint(blk, x, x_size)
|
||||
else:
|
||||
x = blk(x, x_size)
|
||||
if self.downsample is not None:
|
||||
x = self.downsample(x)
|
||||
return x
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}"
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
for blk in self.blocks:
|
||||
flops += blk.flops()
|
||||
if self.downsample is not None:
|
||||
flops += self.downsample.flops()
|
||||
return flops
|
||||
|
||||
|
||||
class RSTB(nn.Module):
|
||||
"""Residual Swin Transformer Block (RSTB).
|
||||
|
||||
Args:
|
||||
dim (int): Number of input channels.
|
||||
input_resolution (tuple[int]): Input resolution.
|
||||
depth (int): Number of blocks.
|
||||
num_heads (int): Number of attention heads.
|
||||
window_size (int): Local window size.
|
||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
|
||||
qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
|
||||
qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
|
||||
drop (float, optional): Dropout rate. Default: 0.0
|
||||
attn_drop (float, optional): Attention dropout rate. Default: 0.0
|
||||
drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
|
||||
downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
|
||||
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
|
||||
img_size: Input image size.
|
||||
patch_size: Patch size.
|
||||
resi_connection: The convolutional block before residual connection.
|
||||
"""
|
||||
|
||||
def __init__(self, dim, input_resolution, depth, num_heads, window_size,
|
||||
mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0.,
|
||||
drop_path=0., norm_layer=nn.LayerNorm, downsample=None, use_checkpoint=False,
|
||||
img_size=224, patch_size=4, resi_connection='1conv'):
|
||||
super(RSTB, self).__init__()
|
||||
|
||||
self.dim = dim
|
||||
self.input_resolution = input_resolution
|
||||
|
||||
self.residual_group = BasicLayer(dim=dim,
|
||||
input_resolution=input_resolution,
|
||||
depth=depth,
|
||||
num_heads=num_heads,
|
||||
window_size=window_size,
|
||||
mlp_ratio=mlp_ratio,
|
||||
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
||||
drop=drop, attn_drop=attn_drop,
|
||||
drop_path=drop_path,
|
||||
norm_layer=norm_layer,
|
||||
downsample=downsample,
|
||||
use_checkpoint=use_checkpoint)
|
||||
|
||||
if resi_connection == '1conv':
|
||||
self.conv = nn.Conv2d(dim, dim, 3, 1, 1)
|
||||
elif resi_connection == '3conv':
|
||||
# to save parameters and memory
|
||||
self.conv = nn.Sequential(nn.Conv2d(dim, dim // 4, 3, 1, 1), nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
||||
nn.Conv2d(dim // 4, dim // 4, 1, 1, 0),
|
||||
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
||||
nn.Conv2d(dim // 4, dim, 3, 1, 1))
|
||||
|
||||
self.patch_embed = PatchEmbed(
|
||||
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
|
||||
norm_layer=None)
|
||||
|
||||
self.patch_unembed = PatchUnEmbed(
|
||||
img_size=img_size, patch_size=patch_size, in_chans=0, embed_dim=dim,
|
||||
norm_layer=None)
|
||||
|
||||
def forward(self, x, x_size):
|
||||
return self.patch_embed(self.conv(self.patch_unembed(self.residual_group(x, x_size), x_size))) + x
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
flops += self.residual_group.flops()
|
||||
H, W = self.input_resolution
|
||||
flops += H * W * self.dim * self.dim * 9
|
||||
flops += self.patch_embed.flops()
|
||||
flops += self.patch_unembed.flops()
|
||||
|
||||
return flops
|
||||
|
||||
|
||||
class PatchEmbed(nn.Module):
|
||||
r""" Image to Patch Embedding
|
||||
|
||||
Args:
|
||||
img_size (int): Image size. Default: 224.
|
||||
patch_size (int): Patch token size. Default: 4.
|
||||
in_chans (int): Number of input image channels. Default: 3.
|
||||
embed_dim (int): Number of linear projection output channels. Default: 96.
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
||||
"""
|
||||
|
||||
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
|
||||
super().__init__()
|
||||
img_size = to_2tuple(img_size)
|
||||
patch_size = to_2tuple(patch_size)
|
||||
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
|
||||
self.img_size = img_size
|
||||
self.patch_size = patch_size
|
||||
self.patches_resolution = patches_resolution
|
||||
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
||||
|
||||
self.in_chans = in_chans
|
||||
self.embed_dim = embed_dim
|
||||
|
||||
if norm_layer is not None:
|
||||
self.norm = norm_layer(embed_dim)
|
||||
else:
|
||||
self.norm = None
|
||||
|
||||
def forward(self, x):
|
||||
x = x.flatten(2).transpose(1, 2) # B Ph*Pw C
|
||||
if self.norm is not None:
|
||||
x = self.norm(x)
|
||||
return x
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
H, W = self.img_size
|
||||
if self.norm is not None:
|
||||
flops += H * W * self.embed_dim
|
||||
return flops
|
||||
|
||||
|
||||
class PatchUnEmbed(nn.Module):
|
||||
r""" Image to Patch Unembedding
|
||||
|
||||
Args:
|
||||
img_size (int): Image size. Default: 224.
|
||||
patch_size (int): Patch token size. Default: 4.
|
||||
in_chans (int): Number of input image channels. Default: 3.
|
||||
embed_dim (int): Number of linear projection output channels. Default: 96.
|
||||
norm_layer (nn.Module, optional): Normalization layer. Default: None
|
||||
"""
|
||||
|
||||
def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
|
||||
super().__init__()
|
||||
img_size = to_2tuple(img_size)
|
||||
patch_size = to_2tuple(patch_size)
|
||||
patches_resolution = [img_size[0] // patch_size[0], img_size[1] // patch_size[1]]
|
||||
self.img_size = img_size
|
||||
self.patch_size = patch_size
|
||||
self.patches_resolution = patches_resolution
|
||||
self.num_patches = patches_resolution[0] * patches_resolution[1]
|
||||
|
||||
self.in_chans = in_chans
|
||||
self.embed_dim = embed_dim
|
||||
|
||||
def forward(self, x, x_size):
|
||||
B, HW, C = x.shape
|
||||
x = x.transpose(1, 2).view(B, self.embed_dim, x_size[0], x_size[1]) # B Ph*Pw C
|
||||
return x
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
return flops
|
||||
|
||||
|
||||
class Upsample(nn.Sequential):
|
||||
"""Upsample module.
|
||||
|
||||
Args:
|
||||
scale (int): Scale factor. Supported scales: 2^n and 3.
|
||||
num_feat (int): Channel number of intermediate features.
|
||||
"""
|
||||
|
||||
def __init__(self, scale, num_feat):
|
||||
m = []
|
||||
if (scale & (scale - 1)) == 0: # scale = 2^n
|
||||
for _ in range(int(math.log(scale, 2))):
|
||||
m.append(nn.Conv2d(num_feat, 4 * num_feat, 3, 1, 1))
|
||||
m.append(nn.PixelShuffle(2))
|
||||
elif scale == 3:
|
||||
m.append(nn.Conv2d(num_feat, 9 * num_feat, 3, 1, 1))
|
||||
m.append(nn.PixelShuffle(3))
|
||||
else:
|
||||
raise ValueError(f'scale {scale} is not supported. ' 'Supported scales: 2^n and 3.')
|
||||
super(Upsample, self).__init__(*m)
|
||||
|
||||
|
||||
class UpsampleOneStep(nn.Sequential):
|
||||
"""UpsampleOneStep module (the difference with Upsample is that it always only has 1conv + 1pixelshuffle)
|
||||
Used in lightweight SR to save parameters.
|
||||
|
||||
Args:
|
||||
scale (int): Scale factor. Supported scales: 2^n and 3.
|
||||
num_feat (int): Channel number of intermediate features.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, scale, num_feat, num_out_ch, input_resolution=None):
|
||||
self.num_feat = num_feat
|
||||
self.input_resolution = input_resolution
|
||||
m = []
|
||||
m.append(nn.Conv2d(num_feat, (scale ** 2) * num_out_ch, 3, 1, 1))
|
||||
m.append(nn.PixelShuffle(scale))
|
||||
super(UpsampleOneStep, self).__init__(*m)
|
||||
|
||||
def flops(self):
|
||||
H, W = self.input_resolution
|
||||
flops = H * W * self.num_feat * 3 * 9
|
||||
return flops
|
||||
|
||||
|
||||
class SwinIR(nn.Module):
|
||||
r""" SwinIR
|
||||
A PyTorch impl of : `SwinIR: Image Restoration Using Swin Transformer`, based on Swin Transformer.
|
||||
|
||||
Args:
|
||||
img_size (int | tuple(int)): Input image size. Default 64
|
||||
patch_size (int | tuple(int)): Patch size. Default: 1
|
||||
in_chans (int): Number of input image channels. Default: 3
|
||||
embed_dim (int): Patch embedding dimension. Default: 96
|
||||
depths (tuple(int)): Depth of each Swin Transformer layer.
|
||||
num_heads (tuple(int)): Number of attention heads in different layers.
|
||||
window_size (int): Window size. Default: 7
|
||||
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4
|
||||
qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
|
||||
qk_scale (float): Override default qk scale of head_dim ** -0.5 if set. Default: None
|
||||
drop_rate (float): Dropout rate. Default: 0
|
||||
attn_drop_rate (float): Attention dropout rate. Default: 0
|
||||
drop_path_rate (float): Stochastic depth rate. Default: 0.1
|
||||
norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
|
||||
ape (bool): If True, add absolute position embedding to the patch embedding. Default: False
|
||||
patch_norm (bool): If True, add normalization after patch embedding. Default: True
|
||||
use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False
|
||||
upscale: Upscale factor. 2/3/4/8 for image SR, 1 for denoising and compress artifact reduction
|
||||
img_range: Image range. 1. or 255.
|
||||
upsampler: The reconstruction reconstruction module. 'pixelshuffle'/'pixelshuffledirect'/'nearest+conv'/None
|
||||
resi_connection: The convolutional block before residual connection. '1conv'/'3conv'
|
||||
"""
|
||||
|
||||
def __init__(self, img_size=64, patch_size=1, in_chans=3,
|
||||
embed_dim=96, depths=[6, 6, 6, 6], num_heads=[6, 6, 6, 6],
|
||||
window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None,
|
||||
drop_rate=0., attn_drop_rate=0., drop_path_rate=0.1,
|
||||
norm_layer=nn.LayerNorm, ape=False, patch_norm=True,
|
||||
use_checkpoint=False, upscale=2, img_range=1., upsampler='', resi_connection='1conv',
|
||||
**kwargs):
|
||||
super(SwinIR, self).__init__()
|
||||
num_in_ch = in_chans
|
||||
num_out_ch = in_chans
|
||||
num_feat = 64
|
||||
self.img_range = img_range
|
||||
if in_chans == 3:
|
||||
rgb_mean = (0.4488, 0.4371, 0.4040)
|
||||
self.mean = torch.Tensor(rgb_mean).view(1, 3, 1, 1)
|
||||
else:
|
||||
self.mean = torch.zeros(1, 1, 1, 1)
|
||||
self.upscale = upscale
|
||||
self.upsampler = upsampler
|
||||
self.window_size = window_size
|
||||
|
||||
#####################################################################################################
|
||||
################################### 1, shallow feature extraction ###################################
|
||||
self.conv_first = nn.Conv2d(num_in_ch, embed_dim, 3, 1, 1)
|
||||
|
||||
#####################################################################################################
|
||||
################################### 2, deep feature extraction ######################################
|
||||
self.num_layers = len(depths)
|
||||
self.embed_dim = embed_dim
|
||||
self.ape = ape
|
||||
self.patch_norm = patch_norm
|
||||
self.num_features = embed_dim
|
||||
self.mlp_ratio = mlp_ratio
|
||||
|
||||
# split image into non-overlapping patches
|
||||
self.patch_embed = PatchEmbed(
|
||||
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
|
||||
norm_layer=norm_layer if self.patch_norm else None)
|
||||
num_patches = self.patch_embed.num_patches
|
||||
patches_resolution = self.patch_embed.patches_resolution
|
||||
self.patches_resolution = patches_resolution
|
||||
|
||||
# merge non-overlapping patches into image
|
||||
self.patch_unembed = PatchUnEmbed(
|
||||
img_size=img_size, patch_size=patch_size, in_chans=embed_dim, embed_dim=embed_dim,
|
||||
norm_layer=norm_layer if self.patch_norm else None)
|
||||
|
||||
# absolute position embedding
|
||||
if self.ape:
|
||||
self.absolute_pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim))
|
||||
trunc_normal_(self.absolute_pos_embed, std=.02)
|
||||
|
||||
self.pos_drop = nn.Dropout(p=drop_rate)
|
||||
|
||||
# stochastic depth
|
||||
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule
|
||||
|
||||
# build Residual Swin Transformer blocks (RSTB)
|
||||
self.layers = nn.ModuleList()
|
||||
for i_layer in range(self.num_layers):
|
||||
layer = RSTB(dim=embed_dim,
|
||||
input_resolution=(patches_resolution[0],
|
||||
patches_resolution[1]),
|
||||
depth=depths[i_layer],
|
||||
num_heads=num_heads[i_layer],
|
||||
window_size=window_size,
|
||||
mlp_ratio=self.mlp_ratio,
|
||||
qkv_bias=qkv_bias, qk_scale=qk_scale,
|
||||
drop=drop_rate, attn_drop=attn_drop_rate,
|
||||
drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], # no impact on SR results
|
||||
norm_layer=norm_layer,
|
||||
downsample=None,
|
||||
use_checkpoint=use_checkpoint,
|
||||
img_size=img_size,
|
||||
patch_size=patch_size,
|
||||
resi_connection=resi_connection
|
||||
|
||||
)
|
||||
self.layers.append(layer)
|
||||
self.norm = norm_layer(self.num_features)
|
||||
|
||||
# build the last conv layer in deep feature extraction
|
||||
if resi_connection == '1conv':
|
||||
self.conv_after_body = nn.Conv2d(embed_dim, embed_dim, 3, 1, 1)
|
||||
elif resi_connection == '3conv':
|
||||
# to save parameters and memory
|
||||
self.conv_after_body = nn.Sequential(nn.Conv2d(embed_dim, embed_dim // 4, 3, 1, 1),
|
||||
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
||||
nn.Conv2d(embed_dim // 4, embed_dim // 4, 1, 1, 0),
|
||||
nn.LeakyReLU(negative_slope=0.2, inplace=True),
|
||||
nn.Conv2d(embed_dim // 4, embed_dim, 3, 1, 1))
|
||||
|
||||
#####################################################################################################
|
||||
################################ 3, high quality image reconstruction ################################
|
||||
if self.upsampler == 'pixelshuffle':
|
||||
# for classical SR
|
||||
self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
|
||||
nn.LeakyReLU(inplace=True))
|
||||
self.upsample = Upsample(upscale, num_feat)
|
||||
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
||||
elif self.upsampler == 'pixelshuffledirect':
|
||||
# for lightweight SR (to save parameters)
|
||||
self.upsample = UpsampleOneStep(upscale, embed_dim, num_out_ch,
|
||||
(patches_resolution[0], patches_resolution[1]))
|
||||
elif self.upsampler == 'nearest+conv':
|
||||
# for real-world SR (less artifacts)
|
||||
self.conv_before_upsample = nn.Sequential(nn.Conv2d(embed_dim, num_feat, 3, 1, 1),
|
||||
nn.LeakyReLU(inplace=True))
|
||||
self.conv_up1 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||
if self.upscale == 4:
|
||||
self.conv_up2 = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||
self.conv_hr = nn.Conv2d(num_feat, num_feat, 3, 1, 1)
|
||||
self.conv_last = nn.Conv2d(num_feat, num_out_ch, 3, 1, 1)
|
||||
self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
|
||||
else:
|
||||
# for image denoising and JPEG compression artifact reduction
|
||||
self.conv_last = nn.Conv2d(embed_dim, num_out_ch, 3, 1, 1)
|
||||
|
||||
self.apply(self._init_weights)
|
||||
|
||||
def _init_weights(self, m):
|
||||
if isinstance(m, nn.Linear):
|
||||
trunc_normal_(m.weight, std=.02)
|
||||
if isinstance(m, nn.Linear) and m.bias is not None:
|
||||
nn.init.constant_(m.bias, 0)
|
||||
elif isinstance(m, nn.LayerNorm):
|
||||
nn.init.constant_(m.bias, 0)
|
||||
nn.init.constant_(m.weight, 1.0)
|
||||
|
||||
@torch.jit.ignore
|
||||
def no_weight_decay(self):
|
||||
return {'absolute_pos_embed'}
|
||||
|
||||
@torch.jit.ignore
|
||||
def no_weight_decay_keywords(self):
|
||||
return {'relative_position_bias_table'}
|
||||
|
||||
def check_image_size(self, x):
|
||||
_, _, h, w = x.size()
|
||||
mod_pad_h = (self.window_size - h % self.window_size) % self.window_size
|
||||
mod_pad_w = (self.window_size - w % self.window_size) % self.window_size
|
||||
x = F.pad(x, (0, mod_pad_w, 0, mod_pad_h), 'reflect')
|
||||
return x
|
||||
|
||||
def forward_features(self, x):
|
||||
x_size = (x.shape[2], x.shape[3])
|
||||
x = self.patch_embed(x)
|
||||
if self.ape:
|
||||
x = x + self.absolute_pos_embed
|
||||
x = self.pos_drop(x)
|
||||
|
||||
for layer in self.layers:
|
||||
x = layer(x, x_size)
|
||||
|
||||
x = self.norm(x) # B L C
|
||||
x = self.patch_unembed(x, x_size)
|
||||
|
||||
return x
|
||||
|
||||
def forward(self, x):
|
||||
H, W = x.shape[2:]
|
||||
x = self.check_image_size(x)
|
||||
|
||||
self.mean = self.mean.type_as(x)
|
||||
x = (x - self.mean) * self.img_range
|
||||
|
||||
if self.upsampler == 'pixelshuffle':
|
||||
# for classical SR
|
||||
x = self.conv_first(x)
|
||||
x = self.conv_after_body(self.forward_features(x)) + x
|
||||
x = self.conv_before_upsample(x)
|
||||
x = self.conv_last(self.upsample(x))
|
||||
elif self.upsampler == 'pixelshuffledirect':
|
||||
# for lightweight SR
|
||||
x = self.conv_first(x)
|
||||
x = self.conv_after_body(self.forward_features(x)) + x
|
||||
x = self.upsample(x)
|
||||
elif self.upsampler == 'nearest+conv':
|
||||
# for real-world SR
|
||||
x = self.conv_first(x)
|
||||
x = self.conv_after_body(self.forward_features(x)) + x
|
||||
x = self.conv_before_upsample(x)
|
||||
x = self.lrelu(self.conv_up1(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
||||
if self.upscale == 4:
|
||||
x = self.lrelu(self.conv_up2(torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest')))
|
||||
x = self.conv_last(self.lrelu(self.conv_hr(x)))
|
||||
else:
|
||||
# for image denoising and JPEG compression artifact reduction
|
||||
x_first = self.conv_first(x)
|
||||
res = self.conv_after_body(self.forward_features(x_first)) + x_first
|
||||
x = x + self.conv_last(res)
|
||||
|
||||
x = x / self.img_range + self.mean
|
||||
|
||||
return x[:, :, :H*self.upscale, :W*self.upscale]
|
||||
|
||||
def flops(self):
|
||||
flops = 0
|
||||
H, W = self.patches_resolution
|
||||
flops += H * W * 3 * self.embed_dim * 9
|
||||
flops += self.patch_embed.flops()
|
||||
for i, layer in enumerate(self.layers):
|
||||
flops += layer.flops()
|
||||
flops += H * W * 3 * self.embed_dim * self.embed_dim
|
||||
flops += self.upsample.flops()
|
||||
return flops
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
upscale = 4
|
||||
window_size = 8
|
||||
height = (1024 // upscale // window_size + 1) * window_size
|
||||
width = (720 // upscale // window_size + 1) * window_size
|
||||
model = SwinIR(upscale=2, img_size=(height, width),
|
||||
window_size=window_size, img_range=1., depths=[6, 6, 6, 6],
|
||||
embed_dim=60, num_heads=[6, 6, 6, 6], mlp_ratio=2, upsampler='pixelshuffledirect').cuda()
|
||||
print(model)
|
||||
|
||||
pytorch_total_params = sum(p.numel() for p in model.parameters())
|
||||
print(f"pathGAN has param {pytorch_total_params//1000} K params")
|
||||
|
||||
|
||||
# Count the time
|
||||
import time
|
||||
x = torch.randn((1, 3, 180, 180)).cuda()
|
||||
start = time.time()
|
||||
x = model(x)
|
||||
total = time.time() - start
|
||||
print("total time spent is ", total)
|
||||
@@ -0,0 +1,24 @@
|
||||
# :european_castle: Model Zoo
|
||||
|
||||
- [For Paper weight](#for-paper-weight)
|
||||
- [For Diverse Upscaler](#for-diverse-upscaler)
|
||||
|
||||
|
||||
|
||||
## For Paper Weight
|
||||
|
||||
| Models | Scale | Description |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------- | :---- | :------------------------------------------- |
|
||||
| [4x_APISR_GRL_GAN_generator](https://github.com/Kiteretsu77/APISR/releases/download/v0.1.0/4x_APISR_GRL_GAN_generator.pth) | 4X | 4X GRL model used in the paper |
|
||||
|
||||
|
||||
## For Diverse Upscaler
|
||||
|
||||
Actually, I am not that much like GRL. Though they can have the smallest param size with higher numerical results, they are not very memory efficient and the processing speed is slow for Transformer model. One more concern come from the TensorRT deployment, where Transformer architecture is hard to be adapted (needless to say for a modified version of Transformer like GRL).
|
||||
|
||||
Thus, for other weights, I will not train a GRL network and also real-world SR of GRL only supports 4x.
|
||||
|
||||
|
||||
| Models | Scale | Description |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------- | :---- | :------------------------------------------- |
|
||||
| [2x_APISR_RRDB_GAN_generator](https://github.com/Kiteretsu77/APISR/releases/download/v0.1.0/2x_APISR_RRDB_GAN_generator.pth) | 2X | 2X upscaler by RRDB-6blocks |
|
||||
@@ -0,0 +1,196 @@
|
||||
import folder_paths
|
||||
import os
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from .architecture.rrdb import RRDBNet
|
||||
from .architecture.grl import GRL
|
||||
import comfy.model_management as mm
|
||||
import comfy.utils
|
||||
|
||||
def convert_dtype(dtype_str):
|
||||
if dtype_str == 'fp32':
|
||||
return torch.float32
|
||||
elif dtype_str == 'fp16':
|
||||
return torch.float16
|
||||
elif dtype_str == 'bf16':
|
||||
return torch.bfloat16
|
||||
else:
|
||||
raise NotImplementedError
|
||||
def load_rrdb(generator_weight_PATH, scale, print_options=False):
|
||||
''' A simpler API to load RRDB model from Real-ESRGAN
|
||||
Args:
|
||||
generator_weight_PATH (str): The path to the weight
|
||||
scale (int): the scaling factor
|
||||
print_options (bool): whether to print options to show what kinds of setting is used
|
||||
Returns:
|
||||
generator (torch): the generator instance of the model
|
||||
'''
|
||||
|
||||
# Load the checkpoint
|
||||
checkpoint_g = torch.load(generator_weight_PATH)
|
||||
|
||||
# Find the generator weight
|
||||
if 'params_ema' in checkpoint_g:
|
||||
# For official ESRNET/ESRGAN weight
|
||||
weight = checkpoint_g['params_ema']
|
||||
generator = RRDBNet(3, 3, scale=scale) # Default blocks num is 6
|
||||
|
||||
elif 'params' in checkpoint_g:
|
||||
# For official ESRNET/ESRGAN weight
|
||||
weight = checkpoint_g['params']
|
||||
generator = RRDBNet(3, 3, scale=scale)
|
||||
|
||||
elif 'model_state_dict' in checkpoint_g:
|
||||
# For my personal trained weight
|
||||
weight = checkpoint_g['model_state_dict']
|
||||
generator = RRDBNet(3, 3, scale=scale)
|
||||
|
||||
else:
|
||||
print("This weight is not supported")
|
||||
os._exit(0)
|
||||
|
||||
|
||||
# Handle torch.compile weight key rename
|
||||
old_keys = [key for key in weight]
|
||||
for old_key in old_keys:
|
||||
if old_key[:10] == "_orig_mod.":
|
||||
new_key = old_key[10:]
|
||||
weight[new_key] = weight[old_key]
|
||||
del weight[old_key]
|
||||
|
||||
generator.load_state_dict(weight)
|
||||
generator = generator.eval()
|
||||
|
||||
|
||||
# Print options to show what kinds of setting is used
|
||||
if print_options:
|
||||
if 'opt' in checkpoint_g:
|
||||
for key in checkpoint_g['opt']:
|
||||
value = checkpoint_g['opt'][key]
|
||||
print(f'{key} : {value}')
|
||||
|
||||
return generator
|
||||
|
||||
def load_grl(generator_weight_PATH, scale=4):
|
||||
''' A simpler API to load GRL model
|
||||
Args:
|
||||
generator_weight_PATH (str): The path to the weight
|
||||
scale (int): Scale Factor (Usually Set as 4)
|
||||
Returns:
|
||||
generator (torch): the generator instance of the model
|
||||
'''
|
||||
|
||||
# Load the checkpoint
|
||||
checkpoint_g = torch.load(generator_weight_PATH)
|
||||
|
||||
# Find the generator weight
|
||||
if 'model_state_dict' in checkpoint_g:
|
||||
weight = checkpoint_g['model_state_dict']
|
||||
|
||||
# GRL tiny model (Note: tiny2 version)
|
||||
generator = GRL(
|
||||
upscale = scale,
|
||||
img_size = 64,
|
||||
window_size = 8,
|
||||
depths = [4, 4, 4, 4],
|
||||
embed_dim = 64,
|
||||
num_heads_window = [2, 2, 2, 2],
|
||||
num_heads_stripe = [2, 2, 2, 2],
|
||||
mlp_ratio = 2,
|
||||
qkv_proj_type = "linear",
|
||||
anchor_proj_type = "avgpool",
|
||||
anchor_window_down_factor = 2,
|
||||
out_proj_type = "linear",
|
||||
conv_type = "1conv",
|
||||
upsampler = "nearest+conv", # Change
|
||||
)
|
||||
|
||||
else:
|
||||
print("This weight is not supported")
|
||||
os._exit(0)
|
||||
|
||||
|
||||
generator.load_state_dict(weight)
|
||||
generator = generator.eval()
|
||||
|
||||
|
||||
num_params = 0
|
||||
for p in generator.parameters():
|
||||
if p.requires_grad:
|
||||
num_params += p.numel()
|
||||
print(f"Number of parameters {num_params / 10 ** 6: 0.2f}")
|
||||
|
||||
|
||||
return generator
|
||||
|
||||
class APISR_upscale:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"ckpt_name": (folder_paths.get_filename_list("upscale_models"), ),
|
||||
"images": ("IMAGE",),
|
||||
"per_batch": ("INT", {"default": 16, "min": 1, "max": 4096, "step": 1}),
|
||||
"dtype": (
|
||||
[
|
||||
'fp32',
|
||||
'fp16',
|
||||
], {
|
||||
"default": 'fp32'
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", )
|
||||
RETURN_NAMES = ("images", )
|
||||
FUNCTION = "upscale"
|
||||
CATEGORY = "ASPIR"
|
||||
|
||||
def upscale(self, ckpt_name, dtype, images, per_batch):
|
||||
device = mm.get_torch_device()
|
||||
model_path = folder_paths.get_full_path("upscale_models", ckpt_name)
|
||||
custom_config = {
|
||||
'dtype': dtype,
|
||||
'ckpt_name': ckpt_name,
|
||||
}
|
||||
|
||||
dtype = (convert_dtype(dtype))
|
||||
if not hasattr(self, 'model') or self.model == None or custom_config != self.current_config:
|
||||
self.model = None
|
||||
self.current_config = custom_config
|
||||
if "RRDB" in ckpt_name:
|
||||
self.model = load_rrdb(model_path, scale=2)
|
||||
elif "GRL" in ckpt_name:
|
||||
self.model = load_grl(model_path, scale=4)
|
||||
self.model = self.model.to(dtype).to(device)
|
||||
|
||||
images = images.permute(0, 3, 1, 2)
|
||||
B, C, H, W = images.shape
|
||||
H = (H // 8) * 8
|
||||
W = (W // 8) * 8
|
||||
|
||||
if images.shape[2] != H or images.shape[3] != W:
|
||||
images = F.interpolate(images, size=(H, W), mode="bicubic")
|
||||
images = images.to(device = device, dtype = dtype)
|
||||
self.model.to(device)
|
||||
pbar = comfy.utils.ProgressBar(B)
|
||||
t = []
|
||||
for start_idx in range(0, B, per_batch):
|
||||
sub_images = self.model(images[start_idx:start_idx+per_batch])
|
||||
t.append(sub_images.cpu())
|
||||
# Calculate the number of images processed in this batch
|
||||
batch_count = sub_images.shape[0]
|
||||
# Update the progress bar by the number of images processed in this batch
|
||||
pbar.update(batch_count)
|
||||
self.model.cpu()
|
||||
|
||||
t = torch.cat(t, dim=0).permute(0, 2, 3, 1).cpu().to(torch.float32)
|
||||
|
||||
return (t,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"APISR_upscale": APISR_upscale,
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"APISR_upscale": "APISR Upscale",
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
numpy>=1.26.0
|
||||
scipy>=1.11.3
|
||||
omegaconf>=2.3.0
|
||||
timm>=0.9.7
|
||||
Reference in New Issue
Block a user